diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..fc95616078fc60759945b16c48f4aa6f9bc63996 --- /dev/null +++ b/.gitignore @@ -0,0 +1,62 @@ +# Prerequisites +*.d + +# Object files +*.o +*.ko +*.obj +*.elf + +# Linker output +*.ilk +*.map +*.exp + +# Precompiled Headers +*.gch +*.pch + +# Libraries +*.lib +*.a +*.la +*.lo + +# Shared objects (inc. Windows DLLs) +*.dll +*.so +*.so.* +*.dylib + +# Executables +*.exe +*.out +*.app +*.i*86 +*.x86_64 +*.hex + +# Debug files +*.dSYM/ +*.su +*.idb +*.pdb + +# Kernel Module Compile Results +*.mod* +*.cmd +.tmp_versions/ +modules.order +Module.symvers +Mkfile.old +dkms.conf + +.idea +.vscode + +/sdk_liteos/output/ +/sdk_liteos/tools/nvtool/out_nv_bin/ +/sdk_liteos/tools/nvtool/__pycache__/ +/sdk_liteos/third_party/u-boot-v2019.07/u-boot-v2019.07/ +/sdk_liteos/build/build_tmp/ +/sdk_liteos/build/scripts/__pycache__/ \ No newline at end of file diff --git a/BUILD.gn b/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..ba1473166df4e48a70b637cd8c6df2863ce7a3f7 --- /dev/null +++ b/BUILD.gn @@ -0,0 +1,15 @@ +# Copyright (c) 2021 Itcast Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +group("genkipi") { +} diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.en.md b/README.en.md old mode 100644 new mode 100755 index 23f3e82185b6c452b8bae1d3db135348391c7d11..b4777e1695e8fbcd652b1cca74ab497b37b7995c --- a/README.en.md +++ b/README.en.md @@ -1,36 +1,111 @@ -# devboard_device_itcast_genkipi +# Itcast GenkiPi -#### Description -{**When you're done, you can delete the content in this README and update the file with details for others getting started with your repository**} +- [Introduction](#section1) +- [Directory Structure](#section2) +- [Compilation](#section3) -#### Software Architecture -Software architecture description -#### Installation -1. xxxx -2. xxxx -3. xxxx +## Introduction -#### Instructions +GenkiPi development board is produced by Itcast Co., Ltd. It is equipped with OpenHarmony2.0 operating system; based on Hisilicon HI3861 module, 160MHz main frequency, SRAM 352KB, ROM 288KB, 2M Flash. 。It supports development protocols such as SPI, IIC, UART, ADC, and PWM, and is widely used in smart wear, smart security and industrial IoT scenarios. -1. xxxx -2. xxxx -3. xxxx +![](./asserts/board.png) + +| 引脚 | Uart | SPI | ADC | PWM | I2S | SDIO | I2C | +| :-----: | :-------------: | :---: | :---: | :---: | :---: | :--: | :---: | +| GPIO_07 | CTS_1 | RXD_0 | ADC_3 | PWM_0 | CLK_0 | | | +| GPIO_08 | RTS_1 | TXD_0 | | PWM_1 | WS_0 | | | +| GPIO_10 | CTS_2 | CLK_0 | | PWM_1 | TX_0 | D3 | SDA_0 | +| GPIO_09 | RTS_2 | TXD_0 | ADC_4 | PWM_0 | MCK_0 | D2 | SCL_0 | +| GPIO_03 | LOG_TXD_0 | | | | | | | +| GPIO_04 | LOG_RXD_0 | | ADC_1 | | | | | +| GPIO_02 | | | | PWM_2 | MCK_0 | | | +| GPIO_05 | RXD_1 | CSI_0 | ADC_2 | PWM_2 | TX_0 | | | +| GPIO_06 | TXD_1 | CLK_0 | | PWM_3 | | | | +| GPIO_14 | LOG_RXD_0/CTS_2 | | | PWM_5 | RX_0 | D1 | SCL_0 | +| GPIO_11 | TXD_2 | RXD_0 | ADC_5 | PWM_2 | CLK_0 | CMD | | +| GPIO_12 | RXD_2 | CSI_0 | ADC_0 | PWM_3 | WS_0 | CLK | | +| GPIO_13 | LOG_TXD_0/RTS_2 | | ADC_6 | PWM_4 | | D0 | SDA_0 | + + + + + +## Direction Structure + +The root directory of GenkiPi SDK package is `device/itcast/genkipi/`: + +```bash +device/itcast/genkipi +├── BUILD.gn # GN build script +├── interfaces # custom interface +└── sdk_liteos # Liteos kernel directory + ├── app # Application layer code (including demo program as a reference example). + ├── boot # Flash bootloader code. + ├── build # The library files, link files, and configuration files needed for SDK building. + ├── BUILD.gn # GN build script + ├── build_patch.sh # Used to decompress uboot open source source package and patch. + ├── build.sh # Start the compilation script and support "sh build.sh. menuconfig" for customized configuration. + ├── components # SDK platform related components. + ├── config # SDK system configuration file. + ├── config.gni # Support OpenHarmony configuration file. + ├── factory.mk # The factory test version compilation script. + ├── hm_build.sh # Adapt to OpenHarmony build script. + ├── include # API header file storage directory. + ├── license # SDK open source license statement. + ├── Makefile # Support make compilation, use "make" or "make all" to start compilation. + ├── non_factory.mk # Non-factory test version compilation script. + ├── platform # SDK platform related files (including: kernel image, driver module, etc.). + ├── SConstruct # SCons compile script. + ├── third_party # Open source third-party software directory. + └── tools # Tools provided by the SDK on Linux and Windows systems (including: NV creation tools, signature tools, Menuconfig, etc.). +``` + + + +## Compilation + +### Source Download + +1. repo tool install。if had install it , omit this step. + + ```bash + curl https://gitee.com/oschina/repo/raw/fork_flow/repo-py3 > repo + sudo mv repo /usr/local/bin/repo + sudo chmod a+x /usr/local/bin/repo + python3 -m pip install -i https://repo.huaweicloud.com/repository/pypi/simple requests + ``` + +2. download source + + ```bash + repo init -u https://gitee.com/openharmony-sig/manifest.git -b master --no-repo-verify -m devboard_itcast_genkipi.xml + repo sync -c + repo forall -c 'git lfs pull' + ``` + +### Compile Code + +1. choose devboard + + ```bash + hb set + ``` + + choose itcast genkipi + +2. compile + + ```bash + hb build + ``` + +### Burn Bin + +burn bin with Hiburn tool. -#### Contribution -1. Fork the repository -2. Create Feat_xxx branch -3. Commit your code -4. Create Pull Request -#### Gitee Feature -1. You can use Readme\_XXX.md to support different languages, such as Readme\_en.md, Readme\_zh.md -2. Gitee blog [blog.gitee.com](https://blog.gitee.com) -3. Explore open source project [https://gitee.com/explore](https://gitee.com/explore) -4. The most valuable open source project [GVP](https://gitee.com/gvp) -5. The manual of Gitee [https://gitee.com/help](https://gitee.com/help) -6. The most popular members [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/) diff --git a/README.md b/README.md old mode 100644 new mode 100755 index 2b2d963c313095c86c750832d8e72fd2f9bf3711..aba962085d5a390a8ac2a3dc6ca4937de4d3bb82 --- a/README.md +++ b/README.md @@ -1,39 +1,109 @@ -# devboard_device_itcast_genkipi +# 传智教育元气派GenkiPi -#### 介绍 -{**以下是 Gitee 平台说明,您可以替换此简介** -Gitee 是 OSCHINA 推出的基于 Git 的代码托管平台(同时支持 SVN)。专为开发者提供稳定、高效、安全的云端软件开发协作平台 -无论是个人、团队、或是企业,都能够用 Gitee 实现代码托管、项目管理、协作开发。企业项目请看 [https://gitee.com/enterprises](https://gitee.com/enterprises)} +- [简介](#section1) +- [目录](#section2) +- [编译指导](#section3) -#### 软件架构 -软件架构说明 -#### 安装教程 +## 简介 -1. xxxx -2. xxxx -3. xxxx +元气派GenKiPi开发板由传智播客教育科技股份有限公司出品,搭载OpenHarmony2.0操作系统;基于海思HI3861模组, 160MHz主频、SRAM 352KB、ROM 288KB、2M Flash。支持SPI、IIC、UART、ADC、PWM等开发协议, 广泛适用于智能穿戴、智能安防和工业物联网场景。 -#### 使用说明 +![](./asserts/board.png) -1. xxxx -2. xxxx -3. xxxx +| 引脚 | Uart | SPI | ADC | PWM | I2S | SDIO | I2C | +| :-----: | :-------------: | :---: | :---: | :---: | :---: | :--: | :---: | +| GPIO_07 | CTS_1 | RXD_0 | ADC_3 | PWM_0 | CLK_0 | | | +| GPIO_08 | RTS_1 | TXD_0 | | PWM_1 | WS_0 | | | +| GPIO_10 | CTS_2 | CLK_0 | | PWM_1 | TX_0 | D3 | SDA_0 | +| GPIO_09 | RTS_2 | TXD_0 | ADC_4 | PWM_0 | MCK_0 | D2 | SCL_0 | +| GPIO_03 | LOG_TXD_0 | | | | | | | +| GPIO_04 | LOG_RXD_0 | | ADC_1 | | | | | +| GPIO_02 | | | | PWM_2 | MCK_0 | | | +| GPIO_05 | RXD_1 | CSI_0 | ADC_2 | PWM_2 | TX_0 | | | +| GPIO_06 | TXD_1 | CLK_0 | | PWM_3 | | | | +| GPIO_14 | LOG_RXD_0/CTS_2 | | | PWM_5 | RX_0 | D1 | SCL_0 | +| GPIO_11 | TXD_2 | RXD_0 | ADC_5 | PWM_2 | CLK_0 | CMD | | +| GPIO_12 | RXD_2 | CSI_0 | ADC_0 | PWM_3 | WS_0 | CLK | | +| GPIO_13 | LOG_TXD_0/RTS_2 | | ADC_6 | PWM_4 | | D0 | SDA_0 | -#### 参与贡献 -1. Fork 本仓库 -2. 新建 Feat_xxx 分支 -3. 提交代码 -4. 新建 Pull Request -#### 特技 -1. 使用 Readme\_XXX.md 来支持不同的语言,例如 Readme\_en.md, Readme\_zh.md -2. Gitee 官方博客 [blog.gitee.com](https://blog.gitee.com) -3. 你可以 [https://gitee.com/explore](https://gitee.com/explore) 这个地址来了解 Gitee 上的优秀开源项目 -4. [GVP](https://gitee.com/gvp) 全称是 Gitee 最有价值开源项目,是综合评定出的优秀开源项目 -5. Gitee 官方提供的使用手册 [https://gitee.com/help](https://gitee.com/help) -6. Gitee 封面人物是一档用来展示 Gitee 会员风采的栏目 [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/) +## 目录 + +GenkiPi 的SDK软件包根目录所在位姿为`device/itcast/genkipi/`, 如下所示: + +```bash +device/itcast/genkipi +├── BUILD.gn # GN构建脚本 +├── interfaces # 自定义接口 +└── sdk_liteos # Liteos内核目录 + ├── app # 应用层代码(其中包含demo程序为参考示例)。 + ├── boot # Flash bootloader代码。 + ├── build # SDK构建所需的库文件、链接文件、配置文件。 + ├── BUILD.gn # GN构建脚本 + ├── build_patch.sh # 用于解压uboot开源源码包和打patch。 + ├── build.sh # 启动编译脚本,同时支持“sh build.sh。 menuconfig”进行客制化配置。 + ├── components # SDK平台相关的组件。 + ├── config # SDK系统配置文件。 + ├── config.gni # 支持OpenHarmony配置文件。 + ├── factory.mk # 厂测版本编译脚本。 + ├── hm_build.sh # 适配OpenHarmony构建脚本。 + ├── include # API头文件存放目录。 + ├── license # SDK开源license声明。 + ├── Makefile # 支持make编译,使用“make”或“make all”启动编译。 + ├── non_factory.mk # 非厂测版本编译脚本。 + ├── platform # SDK平台相关的文件(包括:内核镜像、驱动模块等)。 + ├── SConstruct # SCons编译脚本。 + ├── third_party # 开源第三方软件目录。 + └── tools # SDK提供的Linux系统和Windows系统上使用的工具(包括:NV制作工具、签名工具、Menuconfig等)。 +``` + + + +## 编译指导 + +### 源码下载 + +1. repo工具准备。如果已经安装过repo工具,此步骤省略 + + ```bash + curl https://gitee.com/oschina/repo/raw/fork_flow/repo-py3 > repo + sudo mv repo /usr/local/bin/repo + sudo chmod a+x /usr/local/bin/repo + python3 -m pip install -i https://repo.huaweicloud.com/repository/pypi/simple requests + ``` + +2. 源码下载 + + ```bash + repo init -u https://gitee.com/openharmony-sig/manifest.git -b master --no-repo-verify -m devboard_itcast_genkipi.xml + repo sync -c + repo forall -c 'git lfs pull' + ``` + +### 编译代码 + +1. 选择开发板 + + ```bash + hb set + ``` + + 选中 itcast 下的genkipi 即可 + +2. 编译 + + ```bash + hb build + ``` + +### 烧录 + +通过 hiburn 工具将 out 目录下 allinOne.bin文件进行烧录 + + + diff --git a/asserts/back.png b/asserts/back.png new file mode 100755 index 0000000000000000000000000000000000000000..0f75c175e71929237de8b7ec2d8da308aac2df0d Binary files /dev/null and b/asserts/back.png differ diff --git a/asserts/board.png b/asserts/board.png new file mode 100755 index 0000000000000000000000000000000000000000..a4beee33ee5ef6d8d294dc6edf7c9339e3c548e8 Binary files /dev/null and b/asserts/board.png differ diff --git a/asserts/front.png b/asserts/front.png new file mode 100755 index 0000000000000000000000000000000000000000..a51e9025d63614b295454e5d2ee9db0b424aaf34 Binary files /dev/null and b/asserts/front.png differ diff --git a/hi3861_adapter/LICENSE b/hi3861_adapter/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..2bb9ad240fa04c8cf706a4901c4807878e90c2dc --- /dev/null +++ b/hi3861_adapter/LICENSE @@ -0,0 +1,176 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS \ No newline at end of file diff --git a/hi3861_adapter/hals/communication/wifi_lite/wifiaware/BUILD.gn b/hi3861_adapter/hals/communication/wifi_lite/wifiaware/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..12becb1246e3195af5da5369223c19cffaff85a8 --- /dev/null +++ b/hi3861_adapter/hals/communication/wifi_lite/wifiaware/BUILD.gn @@ -0,0 +1,23 @@ +# Copyright (c) 2021 Itcast Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/lite/config/component/lite_component.gni") + +static_library("hal_wifiaware") { + sources = [ "source/hal_wifiaware.c" ] + include_dirs = [ + "//device/itcast/genkipi/sdk_liteos/include", + "//device/itcast/genkipi/sdk_liteos/third_party/mbedtls-2.16.2/include", + "//foundation/communication/wifi_aware/interfaces/kits", + ] +} diff --git a/hi3861_adapter/hals/communication/wifi_lite/wifiaware/source/hal_wifiaware.c b/hi3861_adapter/hals/communication/wifi_lite/wifiaware/source/hal_wifiaware.c new file mode 100644 index 0000000000000000000000000000000000000000..3df657184e779c60fe523618f68a20c3f6c20396 --- /dev/null +++ b/hi3861_adapter/hals/communication/wifi_lite/wifiaware/source/hal_wifiaware.c @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2021 Itcast Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "hi_cipher.h" +#include "hi_wifi_api.h" +#include "hi_wifi_sdp_api.h" +#include "wifiaware.h" + +int HalWifiSdpInit(const char* ifname) +{ + if (hi_wifi_sdp_init(ifname) != HISI_OK) { + return -1; + } + return 0; +} + +unsigned int HalCipherHashSha256(const char* input, unsigned int inputLen, unsigned char* hash, unsigned hashLen) +{ + if (hi_cipher_hash_sha256((uintptr_t)input, inputLen, hash, hashLen) != HISI_OK) { + return -1; + } + return 0; +} + +int HalWifiSdpStartService(const char* svcName, unsigned char localHandle, RecvCallback recvCB, unsigned char role) +{ + if (hi_wifi_sdp_start_service(svcName, localHandle, (hi_wifi_sdp_recv_cb)recvCB, role) != HISI_OK) { + return -1; + } + return 0; +} + +int HalWifiSdpSend(unsigned char* macAddr, unsigned char peerHandle, unsigned char localHandle, + unsigned char* msg, int len) +{ + if (hi_wifi_sdp_send(macAddr, peerHandle, localHandle, msg, len) != HISI_OK) { + return -1; + } + return 0; +} + +int HalWifiSdpStopService(unsigned char localHandle, unsigned char role) +{ + if (hi_wifi_sdp_stop_service(localHandle, role) != HISI_OK) { + return -1; + } + return 0; +} + +int HalWifiSdpDeinit(void) +{ + if (hi_wifi_sdp_deinit() != HISI_OK) { + return -1; + } + return 0; +} + +int HalWifiSdpAdjustTxPower(const char *ifname, signed char power) +{ + if (hi_wifi_sdp_adjust_tx_power(ifname, power) != HISI_OK) { + return -1; + } + return 0; +} + +int HalWifiSdpRestoreTxPower(const char *ifname) +{ + if (hi_wifi_sdp_restore_tx_power(ifname) != HISI_OK) { + return -1; + } + return 0; +} + +int HalWifiSdpBeaconSwitch(const char *ifname, unsigned char enable) +{ + if (hi_wifi_sdp_beacon_switch(ifname, enable) != HISI_OK) { + return -1; + } + return 0; +} + +int HalWifiSdpSetRetryTimes(unsigned int retries) +{ + if (hi_wifi_sdp_set_retry_times(retries) != HISI_OK) { + return -1; + } + return 0; +} + +int HalWifiSdpGetSyncMode(void) +{ + return hi_wifi_sdp_get_sync_mode(); +} diff --git a/hi3861_adapter/hals/communication/wifi_lite/wifiservice/BUILD.gn b/hi3861_adapter/hals/communication/wifi_lite/wifiservice/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..ac6122aa312f28e0f3183436867a8170d1f9e4ff --- /dev/null +++ b/hi3861_adapter/hals/communication/wifi_lite/wifiservice/BUILD.gn @@ -0,0 +1,35 @@ +# Copyright (c) 2021 Itcast Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/lite/ndk/ndk.gni") +static_library("wifiservice") { + sources = [ + "source/wifi_device.c", + "source/wifi_device_util.c", + "source/wifi_hotspot.c", + ] + include_dirs = [ + "//device/itcast/genkipi/sdk_liteos/include", + "//foundation/communication/wifi_lite/interfaces/wifiservice", + "//kernel/liteos_m/kal", + "//foundation/distributedschedule/samgr_lite/interfaces/kits/samgr", + ] +} +if (ohos_kernel_type == "liteos_m") { + ndk_lib("wifiservice_ndk") { + deps = [ ":wifiservice" ] + + head_files = + [ "//foundation/communication/wifi_lite/interfaces/wifiservice" ] + } +} diff --git a/hi3861_adapter/hals/communication/wifi_lite/wifiservice/source/wifi_device.c b/hi3861_adapter/hals/communication/wifi_lite/wifiservice/source/wifi_device.c new file mode 100755 index 0000000000000000000000000000000000000000..a4d53fd4dd41df8c6edcc7a7878784d8830fb283 --- /dev/null +++ b/hi3861_adapter/hals/communication/wifi_lite/wifiservice/source/wifi_device.c @@ -0,0 +1,990 @@ +/* + * Copyright (c) 2020 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "wifi_device.h" + +#include +#include +#include + +#include "lwip/if_api.h" +#include "lwip/netifapi.h" +#include "wifi_device_util.h" +#include "wifi_hotspot_config.h" +#include "utils_file.h" + +#define WIFI_RECONN_POLICY_ENABLE 1 +#define WIFI_RECONN_POLICY_TIMEOUT 0xFFFF +#define WIFI_RECONN_POLICY_PERIOD 100 +#define WIFI_RECONN_POLICY_MAX_TRY_COUNT 100 +#define WIFI_DISCONNECT_REASON_NO_AP 1 +#define WIFI_DEFAULT_KEY_FOR_PSK "wifipskmode" +#define WLAN_STA_NAME "wlan0" +#define WIFI_FILE "/usrdata/hilink/wifi.cfg" +#define WIFI_FILE_EXIST 1 +#define WIFI_FILE_UNEXIST 0 + +static int g_wifiStaStatus = WIFI_STA_NOT_ACTIVE; +static WifiDeviceConfig g_wifiConfigs[WIFI_MAX_CONFIG_SIZE] = { + {0}, {0}, {0}, 0, WIFI_CONFIG_INVALID, 0, 0, UNKNOWN, {0, 0, {0, 0}, 0} +}; +static WifiEvent* g_wifiEvents[WIFI_MAX_EVENT_SIZE] = {0}; +static int g_connectState = WIFI_STATE_NOT_AVALIABLE; +static int g_networkId = -1; +static bool g_networkConfigReadFlag = false; +static int g_isNetworkConfigExist = WIFI_FILE_UNEXIST; + +static bool IsFileExist(const char* path) +{ + if (path == NULL) { + return false; + } + int32_t fd = UtilsFileOpen(path, O_RDONLY_FS, 0); + if (fd < 0) { + return false; + } + (void)UtilsFileClose(fd); + return true; +} + +static int WriteNetworkConfig(const unsigned char *buf, unsigned int len) +{ + int fd; + + if (buf == 0) { + return ERROR_WIFI_UNKNOWN; + } + + fd = UtilsFileOpen(WIFI_FILE, O_RDWR_FS | O_CREAT_FS | O_TRUNC_FS, 0); + if (fd < 0) { + return ERROR_WIFI_UNKNOWN; + } + + if (UtilsFileWrite(fd, (const char *)buf, len) < 0) { + UtilsFileClose(fd); + return ERROR_WIFI_UNKNOWN; + } + UtilsFileClose(fd); + + return WIFI_SUCCESS; +} + +static int ReadNetworkConfig(unsigned char *buf, unsigned int len) +{ + int fd; + unsigned int fileLen = 0; + int ret; + bool isFileExist = false; + + if (buf == NULL) { + return ERROR_WIFI_UNKNOWN; + } + + if (IsFileExist(WIFI_FILE) == true) { + isFileExist = true; + g_isNetworkConfigExist = WIFI_FILE_EXIST; + } else { + g_isNetworkConfigExist = WIFI_FILE_UNEXIST; + } + + fd = UtilsFileOpen(WIFI_FILE, O_RDWR_FS | O_CREAT_FS, 0); + if (fd < 0) { + return ERROR_WIFI_UNKNOWN; + } + ret = UtilsFileStat(WIFI_FILE, &fileLen); + if (ret != WIFI_SUCCESS) { + UtilsFileClose(fd); + return ERROR_WIFI_UNKNOWN; + } + + ret = UtilsFileSeek(fd, 0, SEEK_SET_FS); + if (ret != WIFI_SUCCESS) { + UtilsFileClose(fd); + return ERROR_WIFI_UNKNOWN; + } + if (fileLen > len) { + UtilsFileClose(fd); + return ERROR_WIFI_UNKNOWN; + } + if (isFileExist == true) { + ret = UtilsFileRead(fd, (char *)buf, len); + if (ret < 0) { + UtilsFileClose(fd); + return ERROR_WIFI_UNKNOWN; + } + } + UtilsFileClose(fd); + return WIFI_SUCCESS; +} + +static void DispatchScanStateChangeEvent(const hi_wifi_event* hisiEvent, + const WifiEvent* hosEvent, WifiEventState event) +{ + if (hosEvent->OnWifiScanStateChanged == NULL) { + return; + } + + int size = 0; + if (event == WIFI_STATE_NOT_AVALIABLE) { + hosEvent->OnWifiScanStateChanged(event, size); + return; + } + + if (hisiEvent->event == HI_WIFI_EVT_SCAN_DONE) { + size = hisiEvent->info.wifi_scan_done.bss_num; + hosEvent->OnWifiScanStateChanged(event, size); + } +} + +static void StaSetLocaladdr(const struct netif *netif, int gw, int ipaddr, int netmask) +{ + ip4_addr_t st_gw; + ip4_addr_t st_ipaddr; + ip4_addr_t st_netmask; + + if (netif == NULL) { + printf("hisi_reset_addr::Null param of netdev\r\n"); + return; + } + + ip4_addr_set_u32(&st_gw, gw); + ip4_addr_set_u32(&st_ipaddr, ipaddr); + ip4_addr_set_u32(&st_netmask, netmask); + netifapi_netif_set_addr(netif, &st_ipaddr, &st_netmask, &st_gw); + return; +} + +static void StaSetDNSServer(int switcher) +{ + ip4_addr_t tmp_dns_ser[WIFI_MAX_DNS_NUM]; + for (int i = 0; i < WIFI_MAX_DNS_NUM; i++) { + if (switcher == HI_WIFI_EVT_CONNECTED) { + ip4_addr_set_u32(&tmp_dns_ser[i], g_wifiConfigs[g_networkId].staticIp.dnsServers[i]); + } else { + ip4_addr_set_u32(&tmp_dns_ser[i], 0); + } + lwip_dns_setserver(i, &tmp_dns_ser[i]); + } + return; +} + +static void StaSetWifiNetConfig(int switcher) +{ + struct netif *netif_node = netif_find(WLAN_STA_NAME); + if (netif_node == NULL) { + printf("[wifi_service]:DispatchConnectEvent netif get fail\r\n"); + return; + } + if (switcher == HI_WIFI_EVT_CONNECTED) { + if (g_wifiConfigs[g_networkId].ipType == DHCP) { + netifapi_dhcp_start(netif_node); + } else if (g_wifiConfigs[g_networkId].ipType == STATIC) { + (void)netifapi_netif_set_link_up(netif_node); + StaSetLocaladdr(netif_node, g_wifiConfigs[g_networkId].staticIp.gateway, + g_wifiConfigs[g_networkId].staticIp.ipAddress, g_wifiConfigs[g_networkId].staticIp.netmask); + (void)netifapi_netif_set_up(netif_node); + StaSetDNSServer(HI_WIFI_EVT_CONNECTED); + } + } else if (switcher == HI_WIFI_EVT_DISCONNECTED) { + if (g_wifiConfigs[g_networkId].ipType == DHCP) { + netifapi_dhcp_stop(netif_node); + StaSetLocaladdr(netif_node, 0, 0, 0); + } else if (g_wifiConfigs[g_networkId].ipType == STATIC) { + (void)netifapi_netif_set_link_down(netif_node); + (void)netifapi_netif_set_down(netif_node); + StaSetLocaladdr(netif_node, 0, 0, 0); + StaSetDNSServer(HI_WIFI_EVT_DISCONNECTED); + } + } + return; +} + +static void DispatchConnectEvent(const hi_wifi_event* hisiEvent, const WifiEvent* hosEvent) +{ + if (hosEvent->OnWifiConnectionChanged == NULL) { + return; + } + + int cpyErr; + WifiLinkedInfo info = {0}; + + if (hisiEvent->event == HI_WIFI_EVT_CONNECTED) { + g_connectState = WIFI_STATE_AVALIABLE; + cpyErr = memcpy_s(&info.ssid, WIFI_MAX_SSID_LEN, + hisiEvent->info.wifi_connected.ssid, HI_WIFI_MAX_SSID_LEN + 1); + if (cpyErr != EOK) { + printf("[wifi_service]:DispatchConnectEvent memcpy failed, err = %d\n", cpyErr); + return; + } + + cpyErr = memcpy_s(&info.bssid, WIFI_MAC_LEN, + hisiEvent->info.wifi_connected.bssid, HI_WIFI_MAC_LEN); + if (cpyErr != EOK) { + printf("[wifi_service]:DispatchConnectEvent memcpy failed, err = %d\n", cpyErr); + return; + } + + StaSetWifiNetConfig(HI_WIFI_EVT_CONNECTED); + hosEvent->OnWifiConnectionChanged(WIFI_STATE_AVALIABLE, &info); + return; + } + + if (hisiEvent->event == HI_WIFI_EVT_STA_FCON_NO_NETWORK && g_connectState == WIFI_STATE_AVALIABLE) { + return; + } + + info.disconnectedReason = WIFI_DISCONNECT_REASON_NO_AP; + + if (hisiEvent->event == HI_WIFI_EVT_DISCONNECTED) { + cpyErr = memcpy_s(&info.bssid, WIFI_MAC_LEN, + hisiEvent->info.wifi_disconnected.bssid, HI_WIFI_MAC_LEN); + if (cpyErr != EOK) { + printf("[wifi_service]:DispatchConnectEvent memcpy failed, err = %d\n", cpyErr); + return; + } + info.disconnectedReason = hisiEvent->info.wifi_disconnected.reason_code; + } + + StaSetWifiNetConfig(HI_WIFI_EVT_DISCONNECTED); + hosEvent->OnWifiConnectionChanged(WIFI_STATE_NOT_AVALIABLE, &info); +} + +static void DispatchStaConnectEvent(const hi_wifi_event* hisiEvent, const WifiEvent* hosEvent) +{ + int cpyErr; + StationInfo info = {0}; + if (hisiEvent->event == HI_WIFI_EVT_STA_CONNECTED) { + if (hosEvent->OnHotspotStaJoin == NULL) { + return; + } + + cpyErr = memcpy_s(&info.macAddress, WIFI_MAC_LEN, + hisiEvent->info.ap_sta_connected.addr, HI_WIFI_MAC_LEN); + if (cpyErr != EOK) { + printf("[wifi_service]:DispatchStaConnectEvent memcpy failed, err = %d\n", cpyErr); + return; + } + + hosEvent->OnHotspotStaJoin(&info); + return; + } + + if (hosEvent->OnHotspotStaLeave == NULL) { + return; + } + + cpyErr = memcpy_s(&info.macAddress, WIFI_MAC_LEN, + hisiEvent->info.ap_sta_disconnected.addr, HI_WIFI_MAC_LEN); + if (cpyErr != EOK) { + printf("[wifi_service]:DispatchStaConnectEvent memcpy failed, err = %d\n", cpyErr); + return; + } + info.disconnectedReason = hisiEvent->info.ap_sta_disconnected.reason_code; + hosEvent->OnHotspotStaLeave(&info); +} + +static void DispatchApStartEvent(const WifiEvent* hosEvent) +{ + if (hosEvent->OnHotspotStateChanged == NULL) { + return; + } + + hosEvent->OnHotspotStateChanged(WIFI_STATE_AVALIABLE); +} + +static void DispatchEvent(const hi_wifi_event* hisiEvent, const WifiEvent* hosEvent) +{ + switch (hisiEvent->event) { + case HI_WIFI_EVT_SCAN_DONE: + DispatchScanStateChangeEvent(hisiEvent, hosEvent, WIFI_STATE_AVALIABLE); + break; + case HI_WIFI_EVT_CONNECTED: + case HI_WIFI_EVT_DISCONNECTED: + case HI_WIFI_EVT_STA_FCON_NO_NETWORK: + DispatchConnectEvent(hisiEvent, hosEvent); + break; + case HI_WIFI_EVT_STA_CONNECTED: + case HI_WIFI_EVT_STA_DISCONNECTED: + DispatchStaConnectEvent(hisiEvent, hosEvent); + break; + case HI_WIFI_EVT_AP_START: + DispatchApStartEvent(hosEvent); + break; + default: + // event not supported in current version, do nothing + break; + } +} + +static void HiWifiWpaEventCb(const hi_wifi_event *hisiEvent) +{ + if (hisiEvent == NULL) { + return; + } + if (LockWifiEventLock() != WIFI_SUCCESS) { + return; + } + for (int i = 0; i < WIFI_MAX_EVENT_SIZE; i++) { + if (g_wifiEvents[i] == NULL) { + continue; + } + DispatchEvent(hisiEvent, g_wifiEvents[i]); + } + if (UnlockWifiEventLock() != WIFI_SUCCESS) { + return; + } +} + +static void RegisterHisiCallback(void) +{ + int hiRet = hi_wifi_register_event_callback(HiWifiWpaEventCb); + if (hiRet != HISI_OK) { + printf("[wifi_service]:RegisterHisiCallback register callback failed\n"); + } + hiRet = hi_wifi_config_callback(1, 0, 0); + if (hiRet != HISI_OK) { + printf("[wifi_service]:ConfigHisiCallback failed\n"); + } +} + +WifiErrorCode EnableWifi(void) +{ + if (LockWifiGlobalLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + if (g_wifiStaStatus == WIFI_STA_ACTIVE) { + if (UnlockWifiGlobalLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + return ERROR_WIFI_BUSY; + } + + char ifName[WIFI_IFNAME_MAX_SIZE + 1] = {0}; + int len = sizeof(ifName); + int hiRet; + + hiRet = hi_wifi_sta_start(ifName, &len); + if (hiRet != HISI_OK) { + printf("[wifi_service]:EnableWifi sta start fail\n"); + if (UnlockWifiGlobalLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + return ERROR_WIFI_NOT_STARTED; + } + + hiRet = hi_wifi_sta_set_reconnect_policy(WIFI_RECONN_POLICY_ENABLE, WIFI_RECONN_POLICY_TIMEOUT, + WIFI_RECONN_POLICY_PERIOD, WIFI_RECONN_POLICY_MAX_TRY_COUNT); + if (hiRet != HISI_OK) { + printf("[wifi_service]:EnableWifi set reconn policy fail\n"); + if (UnlockWifiGlobalLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + return ERROR_WIFI_UNKNOWN; + } + + g_wifiStaStatus = WIFI_STA_ACTIVE; + if (UnlockWifiGlobalLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + + return WIFI_SUCCESS; +} + +WifiErrorCode DisableWifi(void) +{ + if (LockWifiGlobalLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + + if (g_wifiStaStatus == WIFI_STA_NOT_ACTIVE) { + if (UnlockWifiGlobalLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + return ERROR_WIFI_NOT_STARTED; + } + + int hiRet; + + hiRet = hi_wifi_sta_stop(); + if (hiRet != HISI_OK) { + printf("[wifi_service]:DisableWifi failed to stop sta\n"); + if (UnlockWifiGlobalLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + return ERROR_WIFI_NOT_STARTED; + } + + g_wifiStaStatus = WIFI_STA_NOT_ACTIVE; + if (UnlockWifiGlobalLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + + return WIFI_SUCCESS; +} + +int IsWifiActive(void) +{ + if (LockWifiGlobalLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + + int ret = g_wifiStaStatus; + + if (UnlockWifiGlobalLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + return ret; +} + +WifiErrorCode Scan(void) +{ + if (LockWifiGlobalLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + if (g_wifiStaStatus == WIFI_STA_NOT_ACTIVE) { + if (UnlockWifiGlobalLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + return ERROR_WIFI_NOT_STARTED; + } + if (UnlockWifiGlobalLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + + if (LockWifiEventLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + for (int i = 0; i < WIFI_MAX_EVENT_SIZE; i++) { + if (g_wifiEvents[i] == NULL) { + continue; + } + DispatchScanStateChangeEvent(NULL, g_wifiEvents[i], WIFI_STATE_NOT_AVALIABLE); + } + if (UnlockWifiEventLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + + int hiRet; + + hiRet = hi_wifi_sta_scan(); + if (hiRet != HISI_OK) { + printf("[wifi_service]:Scan failed to start sta scan\n"); + return ERROR_WIFI_UNKNOWN; + } + + return WIFI_SUCCESS; +} + +static hi_wifi_scan_type ScanTypeSwitch(WifiScanType type) +{ + hi_wifi_scan_type ret = HI_WIFI_BASIC_SCAN; + + switch (type) { + case WIFI_FREQ_SCAN: + ret = HI_WIFI_CHANNEL_SCAN; + break; + case WIFI_SSID_SCAN: + ret = HI_WIFI_SSID_SCAN; + break; + case WIFI_BSSID_SCAN: + ret = HI_WIFI_BSSID_SCAN; + break; + default: + break; + } + + return ret; +} + +WifiErrorCode AdvanceScan(WifiScanParams *params) +{ + if (params == NULL) { + return ERROR_WIFI_UNKNOWN; + } + + if (LockWifiGlobalLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + if (g_wifiStaStatus == WIFI_STA_NOT_ACTIVE) { + if (UnlockWifiGlobalLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + return ERROR_WIFI_NOT_STARTED; + } + + if (UnlockWifiGlobalLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + + if (LockWifiEventLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + for (int i = 0; i < WIFI_MAX_EVENT_SIZE; i++) { + if (g_wifiEvents[i] == NULL) { + continue; + } + DispatchScanStateChangeEvent(NULL, g_wifiEvents[i], WIFI_STATE_NOT_AVALIABLE); + } + if (UnlockWifiEventLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + + int hiRet; + int cpyErr; + hi_wifi_scan_params sp = {0}; + + cpyErr = memcpy_s(sp.ssid, sizeof(sp.ssid), params->ssid, params->ssidLen); + if (cpyErr != EOK) { + return ERROR_WIFI_UNKNOWN; + } + cpyErr = memcpy_s(sp.bssid, sizeof(sp.bssid), params->bssid, sizeof(params->bssid)); + if (cpyErr != EOK) { + return ERROR_WIFI_UNKNOWN; + } + sp.ssid_len = params->ssidLen; + sp.scan_type = ScanTypeSwitch(params->scanType); + sp.channel = FrequencyToChannel(params->freqs); + + hiRet = hi_wifi_sta_advance_scan(&sp); + if (hiRet != HISI_OK) { + printf("[wifi_service]:Advance Scan failed\n"); + return ERROR_WIFI_UNKNOWN; + } + + return WIFI_SUCCESS; +} + +WifiErrorCode GetScanInfoList(WifiScanInfo* result, unsigned int* size) +{ + if (result == NULL || size == NULL || *size == 0) { + return ERROR_WIFI_INVALID_ARGS; + } + + unsigned int num = WIFI_SCAN_HOTSPOT_LIMIT; + + hi_wifi_ap_info *pstResults = malloc(sizeof(hi_wifi_ap_info) * WIFI_SCAN_HOTSPOT_LIMIT); + if (pstResults == NULL) { + return ERROR_WIFI_UNKNOWN; + } + + int hiRet = hi_wifi_sta_scan_results(pstResults, &num); + if (hiRet != HISI_OK) { + printf("[wifi_service]:GetScanInfoList hi_wifi_sta_scan_results fail\n"); + free(pstResults); + return ERROR_WIFI_UNKNOWN; + } + + if (*size < num) { + free(pstResults); + return ERROR_WIFI_INVALID_ARGS; + } + + int cpyErr; + for (unsigned int i = 0; i < num; i++) { + cpyErr = memcpy_s(result[i].ssid, WIFI_MAX_SSID_LEN, pstResults[i].ssid, HI_WIFI_MAX_SSID_LEN + 1); + if (cpyErr != EOK) { + free(pstResults); + printf("[wifi_service]:GetScanInfoList memcpy failed, err = %d\n", cpyErr); + return ERROR_WIFI_UNKNOWN; + } + + cpyErr = memcpy_s(result[i].bssid, WIFI_MAC_LEN, pstResults[i].bssid, HI_WIFI_MAC_LEN); + if (cpyErr != EOK) { + free(pstResults); + printf("[wifi_service]:GetScanInfoList memcpy failed, err = %d\n", cpyErr); + return ERROR_WIFI_UNKNOWN; + } + + result[i].securityType = HiSecToHoSec(pstResults[i].auth); + result[i].rssi = pstResults[i].rssi; + result[i].frequency = ChannelToFrequency(pstResults[i].channel); + } + + free(pstResults); + *size = num; + + return WIFI_SUCCESS; +} + +WifiErrorCode AddDeviceConfig(const WifiDeviceConfig* config, int* result) +{ + if (config == NULL || result == NULL) { + return ERROR_WIFI_INVALID_ARGS; + } + + int netId = WIFI_CONFIG_INVALID; + if (LockWifiGlobalLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + for (int i = 0; i < WIFI_MAX_CONFIG_SIZE; i++) { + if (g_wifiConfigs[i].netId != i) { + netId = i; + break; + } + } + + if (netId == WIFI_CONFIG_INVALID) { + printf("[wifi_service]:AddDeviceConfig wifi config is full, delete one first\n"); + if (UnlockWifiGlobalLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + return ERROR_WIFI_BUSY; + } + + int cpyErr = memcpy_s(&g_wifiConfigs[netId], sizeof(WifiDeviceConfig), config, sizeof(WifiDeviceConfig)); + if (cpyErr != EOK) { + if (UnlockWifiGlobalLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + printf("[wifi_service]:AddDeviceConfig memcpy failed, err = %d\n", cpyErr); + return ERROR_WIFI_UNKNOWN; + } + + g_wifiConfigs[netId].netId = netId; + if (WriteNetworkConfig((unsigned char *)&g_wifiConfigs[netId], sizeof(WifiDeviceConfig)) != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + + if (UnlockWifiGlobalLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + *result = netId; + return WIFI_SUCCESS; +} + +WifiErrorCode GetDeviceConfigs(WifiDeviceConfig* result, unsigned int* size) +{ + if (result == NULL || size == NULL) { + return ERROR_WIFI_INVALID_ARGS; + } + + unsigned int retIndex = 0; + + if (LockWifiGlobalLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + + if (g_networkConfigReadFlag == false) { + g_networkConfigReadFlag = true; + if (ReadNetworkConfig((unsigned char *)&g_wifiConfigs[0], sizeof(WifiDeviceConfig)) != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + if (g_isNetworkConfigExist == WIFI_FILE_UNEXIST) { + g_wifiConfigs[0].netId = WIFI_CONFIG_INVALID; + } + } + + for (int i = 0; i < WIFI_MAX_CONFIG_SIZE; i++) { + if (g_wifiConfigs[i].netId != i) { + continue; + } + + int cpyErr = memcpy_s(&result[retIndex], sizeof(WifiDeviceConfig), &g_wifiConfigs[i], sizeof(WifiDeviceConfig)); + if (cpyErr != EOK) { + if (UnlockWifiGlobalLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + printf("[wifi_service]:GetDeviceConfig memcpy failed, err = %d\n", cpyErr); + return ERROR_WIFI_UNKNOWN; + } + + retIndex++; + if (*size < retIndex) { + if (UnlockWifiGlobalLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + return ERROR_WIFI_INVALID_ARGS; + } + } + + if (UnlockWifiGlobalLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + + if (retIndex == 0) { + return ERROR_WIFI_NOT_AVAILABLE; + } + + *size = retIndex; + return WIFI_SUCCESS; +} + +static WifiErrorCode StaConnect(unsigned int chan, hi_wifi_assoc_request *assocReq, int pskType) +{ + int hiRet = 0; + int lastState = g_connectState; + + g_connectState = WIFI_STATE_NOT_AVALIABLE; + if (chan == 0) { + hiRet = hi_wifi_sta_connect(assocReq); + } else { + hi_wifi_fast_assoc_request fastReq = {0}; + fastReq.channel = chan; + hiRet += memcpy_s(&fastReq.req, sizeof(hi_wifi_assoc_request), assocReq, sizeof(hi_wifi_assoc_request)); + if (pskType == WIFI_PSK_TYPE_HEX) { + hiRet += memcpy_s(fastReq.req.key, sizeof(fastReq.req.key), + WIFI_DEFAULT_KEY_FOR_PSK, sizeof(WIFI_DEFAULT_KEY_FOR_PSK)); + hiRet += memcpy_s(fastReq.psk, sizeof(fastReq.psk), assocReq->key, HI_WIFI_STA_PSK_LEN); + fastReq.psk_flag = HI_WIFI_WPA_PSK_USE_OUTER; + } + if (hiRet != EOK) { + printf("[wifi_service]:StaConnect memcpy failed, err = %d\n", hiRet); + g_connectState = lastState; + return ERROR_WIFI_UNKNOWN; + } + hiRet = hi_wifi_sta_fast_connect(&fastReq); + if (memset_s(&fastReq, sizeof(hi_wifi_fast_assoc_request), 0, sizeof(hi_wifi_fast_assoc_request)) != EOK) { + printf("[wifi_service]:StaConnect memset failed\n"); + } + } + if (memset_s(assocReq, sizeof(hi_wifi_assoc_request), 0, sizeof(hi_wifi_assoc_request)) != EOK) { + printf("[wifi_service]:StaConnect memset failed\n"); + } + if (hiRet != HISI_OK) { + g_connectState = lastState; + return ERROR_WIFI_UNKNOWN; + } + + return WIFI_SUCCESS; +} + +WifiErrorCode ConnectTo(int networkId) +{ + if (networkId >= WIFI_MAX_CONFIG_SIZE || networkId < 0) { + return ERROR_WIFI_INVALID_ARGS; + } + + if (LockWifiGlobalLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + + if (g_wifiConfigs[networkId].netId != networkId) { + if (UnlockWifiGlobalLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + return ERROR_WIFI_NOT_AVAILABLE; + } + + g_networkId = networkId; + hi_wifi_assoc_request assocReq = {0}; + assocReq.auth = HoSecToHiSec(g_wifiConfigs[networkId].securityType); + + int cpyErr = memcpy_s(assocReq.ssid, sizeof(assocReq.ssid), + g_wifiConfigs[networkId].ssid, sizeof(g_wifiConfigs[networkId].ssid)); + cpyErr += memcpy_s(assocReq.key, sizeof(assocReq.key), + g_wifiConfigs[networkId].preSharedKey, sizeof(g_wifiConfigs[networkId].preSharedKey)); + cpyErr += memcpy_s(assocReq.bssid, sizeof(assocReq.bssid), + g_wifiConfigs[networkId].bssid, sizeof(g_wifiConfigs[networkId].bssid)); + if (UnlockWifiGlobalLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + if (cpyErr != EOK) { + printf("[wifi_service]:ConnectTo memcpy failed, err = %d\n", cpyErr); + return ERROR_WIFI_UNKNOWN; + } + + unsigned int chan = FrequencyToChannel(g_wifiConfigs[networkId].freq); + if (LockWifiEventLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + if (StaConnect(chan, &assocReq, g_wifiConfigs[networkId].wapiPskType) != WIFI_SUCCESS) { + if (UnlockWifiEventLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + return ERROR_WIFI_UNKNOWN; + } + if (UnlockWifiEventLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + return WIFI_SUCCESS; +} + +WifiErrorCode Disconnect(void) +{ + int hiRet = hi_wifi_sta_disconnect(); + if (hiRet != HISI_OK) { + return ERROR_WIFI_UNKNOWN; + } + return WIFI_SUCCESS; +} + +WifiErrorCode RemoveDevice(int networkId) +{ + if (networkId >= WIFI_MAX_CONFIG_SIZE || networkId < 0) { + return ERROR_WIFI_INVALID_ARGS; + } + if (LockWifiGlobalLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + if (memset_s(&g_wifiConfigs[networkId], sizeof(WifiDeviceConfig), + 0, sizeof(WifiDeviceConfig)) != EOK) { + printf("[wifi_service]:removeDevice memset failed\n"); + } + g_wifiConfigs[networkId].netId = WIFI_CONFIG_INVALID; + + if (WriteNetworkConfig((unsigned char *)&g_wifiConfigs[networkId], sizeof(WifiDeviceConfig)) != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + + if (UnlockWifiGlobalLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + return WIFI_SUCCESS; +} + +static int GetLocalWifiIp(int * const ip) +{ + int ret; + struct netif *netif_node = netif_find(WLAN_STA_NAME); + if (netif_node == NULL) { + printf("GetLocalWifiIp netif get fail\r\n"); + return HISI_FAIL; + } + + ip4_addr_t ipAddr; + ip4_addr_t netMask; + ip4_addr_t gateWay; + + ret = netifapi_netif_get_addr(netif_node, &ipAddr, &netMask, &gateWay); + if (ret == 0) { + *ip = ip4_addr_get_u32(&ipAddr); + return HISI_OK; + } + return HISI_FAIL; +} + +WifiErrorCode GetLinkedInfo(WifiLinkedInfo* result) +{ + if (result == NULL) { + return ERROR_WIFI_INVALID_ARGS; + } + + hi_wifi_status connectStatus = {0}; + int hiRet = hi_wifi_sta_get_connect_info(&connectStatus); + if (hiRet != HISI_OK) { + return ERROR_WIFI_UNKNOWN; + } + + int cpyErr = memcpy_s(result->ssid, WIFI_MAX_SSID_LEN, connectStatus.ssid, HI_WIFI_MAX_SSID_LEN + 1); + if (cpyErr != EOK) { + printf("[wifi_service]:GetLinkedInfo memcpy failed, err = %d\n", cpyErr); + return ERROR_WIFI_UNKNOWN; + } + + cpyErr = memcpy_s(result->bssid, WIFI_MAC_LEN, connectStatus.bssid, HI_WIFI_MAC_LEN); + if (cpyErr != EOK) { + printf("[wifi_service]:GetLinkedInfo memcpy failed, err = %d\n", cpyErr); + return ERROR_WIFI_UNKNOWN; + } + + if (connectStatus.status == HI_WIFI_CONNECTED) { + result->connState = WIFI_CONNECTED; + result->rssi = hi_wifi_sta_get_ap_rssi(); + } else { + result->connState = WIFI_DISCONNECTED; + } + + if (GetLocalWifiIp(&(result->ipAddress)) != EOK) { + return ERROR_WIFI_UNKNOWN; + } + + return WIFI_SUCCESS; +} + + +WifiErrorCode RegisterWifiEvent(WifiEvent* event) +{ + if (event == NULL) { + return ERROR_WIFI_INVALID_ARGS; + } + + int emptySlot = WIFI_CONFIG_INVALID; + + if (LockWifiEventLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + for (int i = 0; i < WIFI_MAX_EVENT_SIZE; i++) { + if (g_wifiEvents[i] == event) { + if (UnlockWifiEventLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + return ERROR_WIFI_INVALID_ARGS; + } + + if (g_wifiEvents[i] != NULL) { + continue; + } + + emptySlot = i; + break; + } + + if (emptySlot == WIFI_CONFIG_INVALID) { + if (UnlockWifiEventLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + return ERROR_WIFI_BUSY; + } + + g_wifiEvents[emptySlot] = event; + if (UnlockWifiEventLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + RegisterHisiCallback(); + + return WIFI_SUCCESS; +} + +WifiErrorCode UnRegisterWifiEvent(const WifiEvent* event) +{ + if (event == NULL) { + return ERROR_WIFI_INVALID_ARGS; + } + + if (LockWifiEventLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + + for (int i = 0; i < WIFI_MAX_EVENT_SIZE; i++) { + if (g_wifiEvents[i] != event) { + continue; + } + + g_wifiEvents[i] = 0; + + if (UnlockWifiEventLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + return WIFI_SUCCESS; + } + + if (UnlockWifiEventLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + return ERROR_WIFI_UNKNOWN; +} + +WifiErrorCode GetDeviceMacAddress(unsigned char* result) +{ + if (result == NULL) { + return ERROR_WIFI_INVALID_ARGS; + } + + int hiRet = hi_wifi_get_macaddr((char*)result, WIFI_MAC_LEN); + if (hiRet != HISI_OK) { + return ERROR_WIFI_UNKNOWN; + } + return WIFI_SUCCESS; +} \ No newline at end of file diff --git a/hi3861_adapter/hals/communication/wifi_lite/wifiservice/source/wifi_device_util.c b/hi3861_adapter/hals/communication/wifi_lite/wifiservice/source/wifi_device_util.c new file mode 100755 index 0000000000000000000000000000000000000000..f0e6ca47cb0a95d3e118d8b7fb5f4e28e6f059e8 --- /dev/null +++ b/hi3861_adapter/hals/communication/wifi_lite/wifiservice/source/wifi_device_util.c @@ -0,0 +1,174 @@ +/* + * Copyright (c) 2020 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "wifi_device_util.h" + +#include + +#include "cmsis_os.h" +#include "common.h" +#include "ohos_init.h" + +#include "wifi_hotspot_config.h" + +#define WIFI_WAIT_FOREVER 0xFFFFFFFF +#define CHANNEL_80211B_ONLY 14 +#define FREQ_OF_CHANNEL_1 2412 +#define FREQ_OF_CHANNEL_80211B_ONLY 2484 +#define WIFI_MIN_CHANNEL 1 +#define WIFI_FREQ_INTERVAL 5 + +static MutexId g_wifiGlobalLock = NULL; +static MutexId g_wifiEventLock = NULL; + +WifiSecurityType HiSecToHoSec(hi_wifi_auth_mode mode) +{ + switch (mode) { + case HI_WIFI_SECURITY_OPEN: + return WIFI_SEC_TYPE_OPEN; + case HI_WIFI_SECURITY_WEP: + return WIFI_SEC_TYPE_WEP; + case HI_WIFI_SECURITY_WPAPSK_WPA2PSK_MIX: + return WIFI_SEC_TYPE_PSK; + case HI_WIFI_SECURITY_WPA3_WPA2_PSK_MIX: + return WIFI_SEC_TYPE_SAE; + default: + return WIFI_SEC_TYPE_INVALID; + } +} + +hi_wifi_auth_mode HoSecToHiSec(WifiSecurityType type) +{ + switch (type) { + case WIFI_SEC_TYPE_OPEN: + return HI_WIFI_SECURITY_OPEN; + case WIFI_SEC_TYPE_WEP: + return HI_WIFI_SECURITY_WEP; + case WIFI_SEC_TYPE_PSK: + return HI_WIFI_SECURITY_WPAPSK_WPA2PSK_MIX; + case WIFI_SEC_TYPE_SAE: + return HI_WIFI_SECURITY_WPA3_WPA2_PSK_MIX; + default: + return HI_WIFI_SECURITY_UNKNOWN; + } +} + +static void InitWifiGlobalLock(void) +{ + if (g_wifiGlobalLock == NULL) { + osMutexAttr_t globalMutexAttr = { + "WifiGloablLock", + osMutexRecursive | osMutexPrioInherit, + NULL, + 0U + }; + g_wifiGlobalLock = osMutexNew(&globalMutexAttr); + } + if (g_wifiEventLock == NULL) { + osMutexAttr_t eventMutexAttr = { + "WifiEventLock", + osMutexRecursive | osMutexPrioInherit, + NULL, + 0U + }; + g_wifiEventLock = osMutexNew(&eventMutexAttr); + } +} + +WifiErrorCode LockWifiGlobalLock(void) +{ + if (g_wifiGlobalLock == NULL) { + return ERROR_WIFI_UNKNOWN; + } + + osStatus_t ret = osMutexAcquire(g_wifiGlobalLock, WIFI_WAIT_FOREVER); + if (ret != osOK) { + printf("[wifi_service] osMutexAcquire failed \n"); + return ERROR_WIFI_UNKNOWN; + } + + return WIFI_SUCCESS; +} + +WifiErrorCode UnlockWifiGlobalLock(void) +{ + if (g_wifiGlobalLock == NULL) { + return ERROR_WIFI_UNKNOWN; + } + + osStatus_t ret = osMutexRelease(g_wifiGlobalLock); + if (ret != osOK) { + printf("[wifi_service] osMutexUnlock failed \n"); + return ERROR_WIFI_UNKNOWN; + } + + return WIFI_SUCCESS; +} + +WifiErrorCode LockWifiEventLock(void) +{ + if (g_wifiEventLock == NULL) { + return ERROR_WIFI_UNKNOWN; + } + + osStatus_t ret = osMutexAcquire(g_wifiEventLock, WIFI_WAIT_FOREVER); + if (ret != osOK) { + printf("[wifi_service] osMutexAcquire event failed \n"); + return ERROR_WIFI_UNKNOWN; + } + + return WIFI_SUCCESS; +} + +WifiErrorCode UnlockWifiEventLock(void) +{ + if (g_wifiEventLock == NULL) { + return ERROR_WIFI_UNKNOWN; + } + + osStatus_t ret = osMutexRelease(g_wifiEventLock); + if (ret != osOK) { + printf("[wifi_service] osMutexUnlock event failed \n"); + return ERROR_WIFI_UNKNOWN; + } + + return WIFI_SUCCESS; +} + +unsigned int ChannelToFrequency(unsigned int channel) +{ + if (channel <= 0) { + return 0; + } + if (channel == CHANNEL_80211B_ONLY) { + return FREQ_OF_CHANNEL_80211B_ONLY; + } + return (((channel - WIFI_MIN_CHANNEL) * WIFI_FREQ_INTERVAL) + FREQ_OF_CHANNEL_1); +} + +unsigned int FrequencyToChannel(unsigned int frequency) +{ + if (frequency == FREQ_OF_CHANNEL_80211B_ONLY) { + return CHANNEL_80211B_ONLY; + } + + if (frequency < FREQ_OF_CHANNEL_1) { + return 0; + } + + return (frequency - FREQ_OF_CHANNEL_1) / WIFI_FREQ_INTERVAL + WIFI_MIN_CHANNEL; +} + +CORE_INIT(InitWifiGlobalLock); diff --git a/hi3861_adapter/hals/communication/wifi_lite/wifiservice/source/wifi_device_util.h b/hi3861_adapter/hals/communication/wifi_lite/wifiservice/source/wifi_device_util.h new file mode 100755 index 0000000000000000000000000000000000000000..af7cec44e5525d13cb9a266df9ccef8e7d00e22f --- /dev/null +++ b/hi3861_adapter/hals/communication/wifi_lite/wifiservice/source/wifi_device_util.h @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2020 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _WIFI_DEVICE_UTIL_H +#define _WIFI_DEVICE_UTIL_H + +#include "hi_wifi_api.h" + +#include "wifi_device.h" +#include "wifi_device_config.h" +#include "wifi_error_code.h" + +/** + * @brief convert os security type to hisi security type + * + * @param type [in] os security type. + * + * @return hisi security type. + */ +hi_wifi_auth_mode HoSecToHiSec(WifiSecurityType type); + +/** + * @brief convert hisi security type to os security type + * + * @param type [in] hisi security type. + * + * @return os security type. + */ +WifiSecurityType HiSecToHoSec(hi_wifi_auth_mode mode); + +/** + * @brief get hotspot channel + * + * @return current channel. + */ +int GetHotspotChannel(void); + +/** + * @brief get hotspot interface name + * + * @param result [out] hotspot interface name. + * @param size [in] result buffer size, must bigger than WIFI_IFNAME_MAX_SIZE + 1. + * + * @return WifiErrorCode. + */ +WifiErrorCode GetHotspotInterfaceName(char* result, int size); + +/** + * @brief lock wifi global lock + * + * @return WifiErrorCode. + */ +WifiErrorCode LockWifiGlobalLock(void); + +/** + * @brief unlock wifi global lock + * + * @return WifiErrorCode. + */ +WifiErrorCode UnlockWifiGlobalLock(void); + +/** + * @brief lock wifi event lock + * + * @return WifiErrorCode. + */ +WifiErrorCode LockWifiEventLock(void); + +/** + * @brief unlock wifi event lock + * + * @return WifiErrorCode. + */ +WifiErrorCode UnlockWifiEventLock(void); + +/** + * @brief convert channel to frequency in 2G + * + * @return frequency. + */ +unsigned int ChannelToFrequency(unsigned int channel); + +unsigned int FrequencyToChannel(unsigned int frequency); +#endif // _WIFI_DEVICE_UTIL_H diff --git a/hi3861_adapter/hals/communication/wifi_lite/wifiservice/source/wifi_hotspot.c b/hi3861_adapter/hals/communication/wifi_lite/wifiservice/source/wifi_hotspot.c new file mode 100755 index 0000000000000000000000000000000000000000..07883f16ccd56eba44e322334736b61ffcbf0529 --- /dev/null +++ b/hi3861_adapter/hals/communication/wifi_lite/wifiservice/source/wifi_hotspot.c @@ -0,0 +1,438 @@ +/* + * Copyright (c) 2020 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "wifi_hotspot.h" +#include +#include "hi_wifi_api.h" +#include "lwip/netifapi.h" +#include "wifi_device_util.h" + +#define RSSI_LEVEL_4_2_G (-65) +#define RSSI_LEVEL_3_2_G (-75) +#define RSSI_LEVEL_2_2_G (-82) +#define RSSI_LEVEL_1_2_G (-88) + +#define RSSI_LEVEL_4_5_G (-65) +#define RSSI_LEVEL_3_5_G (-72) +#define RSSI_LEVEL_2_5_G (-79) +#define RSSI_LEVEL_1_5_G (-85) + +#define IP_AP_ADDR0 192 +#define IP_AP_ADDR1 168 +#define IP_AP_ADDR2 5 +#define IP_AP_ADDR3 1 +#define GW_AP_ADDR0 192 +#define GW_AP_ADDR1 168 +#define GW_AP_ADDR2 5 +#define GW_AP_ADDR3 1 +#define NETMSK_ADDR0 255 +#define NETMSK_ADDR1 255 +#define NETMSK_ADDR2 255 +#define NETMSK_ADDR3 0 + +#define WIFI_TPC_MAX_POWER 20 +#define WIFI_TPC_ID 35 +#define WIFI_TPC_LEN 2 +#define WLAN_AP_NAME "ap0" + +static int g_wifiApStatus = WIFI_HOTSPOT_NOT_ACTIVE; +static HotspotConfig g_wifiApConfig = {0}; +static char g_wifiIfName[WIFI_IFNAME_MAX_SIZE + 1] = {0}; +typedef struct { + unsigned char id; + unsigned char len; + signed char power; + unsigned char margin; +} TpcElement; + +static WifiErrorCode SetHotspotIpConfig(void) +{ + struct netif *netif = NULL; + netif = netif_find(WLAN_AP_NAME); + if (netif == NULL) { + printf("get netif failed\r\n"); + return ERROR_WIFI_UNKNOWN; + } + ip4_addr_t ipAddr; + ip4_addr_t netMask; + ip4_addr_t gw; + + IP4_ADDR(&ipAddr, IP_AP_ADDR0, IP_AP_ADDR1, IP_AP_ADDR2, IP_AP_ADDR3); + IP4_ADDR(&netMask, NETMSK_ADDR0, NETMSK_ADDR1, NETMSK_ADDR2, NETMSK_ADDR3); + IP4_ADDR(&gw, GW_AP_ADDR0, GW_AP_ADDR1, GW_AP_ADDR2, GW_AP_ADDR3); + + netifapi_netif_set_addr(netif, &ipAddr, &netMask, &gw); + + if (netifapi_dhcps_start(netif, 0, 0) != 0) { + printf("dhcps shell cmd excute fail!\r\n"); + (void)hi_wifi_softap_stop(); + return ERROR_WIFI_UNKNOWN; + } + return WIFI_SUCCESS; +} + +WifiErrorCode EnableHotspot(void) +{ + if (LockWifiGlobalLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + if (g_wifiApStatus == WIFI_HOTSPOT_ACTIVE) { + if (UnlockWifiGlobalLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + return ERROR_WIFI_BUSY; + } + + hi_wifi_softap_config hapdConf = {0}; + + hapdConf.channel_num = HOTSPOT_DEFAULT_CHANNEL; + if (g_wifiApConfig.channelNum) { + hapdConf.channel_num = g_wifiApConfig.channelNum; + } + hapdConf.authmode = HoSecToHiSec(g_wifiApConfig.securityType); + + int cpyErr = memcpy_s(hapdConf.ssid, WIFI_MAX_SSID_LEN, g_wifiApConfig.ssid, HI_WIFI_MAX_SSID_LEN + 1); + cpyErr += memcpy_s(hapdConf.key, WIFI_MAX_KEY_LEN, g_wifiApConfig.preSharedKey, HI_WIFI_MAX_KEY_LEN + 1); + if (cpyErr != EOK) { + printf("[wifi_service]:EnableHotspot memcpy fail, err = %d\n", cpyErr); + if (UnlockWifiGlobalLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + return ERROR_WIFI_UNKNOWN; + } + + int len = sizeof(g_wifiIfName); + int hiRet = hi_wifi_softap_start(&hapdConf, g_wifiIfName, &len); + if (hiRet != HISI_OK) { + printf("[wifi_service]:EnableHotspot softap start fail, err = %d\n", hiRet); + if (UnlockWifiGlobalLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + return ERROR_WIFI_NOT_STARTED; + } + cpyErr = memset_s(&hapdConf, sizeof(hi_wifi_softap_config), 0, sizeof(hi_wifi_softap_config)); + if (cpyErr != EOK) { + printf("[wifi_service]:EnableHotspot memset fail, err = %d\n", cpyErr); + if (UnlockWifiGlobalLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + return ERROR_WIFI_UNKNOWN; + } + + g_wifiApStatus = WIFI_HOTSPOT_ACTIVE; + if (UnlockWifiGlobalLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + + if (SetHotspotIpConfig() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + return WIFI_SUCCESS; +} + +WifiErrorCode DisableHotspot(void) +{ + if (LockWifiGlobalLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + if (g_wifiApStatus == WIFI_HOTSPOT_NOT_ACTIVE) { + if (UnlockWifiGlobalLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + return ERROR_WIFI_NOT_STARTED; + } + + int hiRet = hi_wifi_softap_stop(); + if (hiRet != HISI_OK) { + printf("[wifi_service]:DisableHotspot failed to stop softap, err = %d\n", hiRet); + if (UnlockWifiGlobalLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + return ERROR_WIFI_NOT_STARTED; + } + + g_wifiApStatus = WIFI_HOTSPOT_NOT_ACTIVE; + if (UnlockWifiGlobalLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + return WIFI_SUCCESS; +} + +WifiErrorCode SetHotspotConfig(const HotspotConfig* config) +{ + if (config == NULL) { + return ERROR_WIFI_INVALID_ARGS; + } + + if (LockWifiGlobalLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + int cpyErr = memcpy_s(&g_wifiApConfig, sizeof(HotspotConfig), config, sizeof(HotspotConfig)); + if (UnlockWifiGlobalLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + if (cpyErr != EOK) { + printf("[wifi_service]:SetHotspotConfig memcpy fail, err = %d\n", cpyErr); + return ERROR_WIFI_UNKNOWN; + } + return WIFI_SUCCESS; +} + +WifiErrorCode GetHotspotConfig(HotspotConfig* result) +{ + if (result == NULL) { + return ERROR_WIFI_INVALID_ARGS; + } + + if (LockWifiGlobalLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + int cpyErr = memcpy_s(result, sizeof(HotspotConfig), &g_wifiApConfig, sizeof(HotspotConfig)); + if (UnlockWifiGlobalLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + if (cpyErr != EOK) { + printf("[wifi_service]:SetHotspotConfig memcpy fail, err = %d\n", cpyErr); + return ERROR_WIFI_UNKNOWN; + } + return WIFI_SUCCESS; +} + +int IsHotspotActive(void) +{ + if (LockWifiGlobalLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + int ret = g_wifiApStatus; + if (UnlockWifiGlobalLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + + return ret; +} + +static int GetPeerSTAWifiIp(const unsigned char *macAddress, int macLen, unsigned int * const ip) +{ + int ret; + ip4_addr_t clientIP; + struct netif *netif_node = netif_find(WLAN_AP_NAME); + if (netif_node == NULL) { + printf("GetPeerSTAWifiIp netif get fail\r\n"); + return HISI_FAIL; + } + + ret = netifapi_dhcps_get_client_ip(netif_node, macAddress, macLen, &clientIP); + if (ret == 0) { + *ip = ntohl(ip4_addr_get_u32(&clientIP)); + return HISI_OK; + } + + return HISI_FAIL; +} + +WifiErrorCode GetStationList(StationInfo* result, unsigned int* size) +{ + if (result == NULL || size == NULL || *size == 0) { + return ERROR_WIFI_INVALID_ARGS; + } + + hi_wifi_ap_sta_info staList[WIFI_MAX_STA_NUM] = {0}; + unsigned int staNum = WIFI_MAX_STA_NUM; + + int hiRet = hi_wifi_softap_get_connected_sta(staList, &staNum); + if (hiRet != HISI_OK) { + printf("[wifi_service]:GetStationList get connected sta failed, err = %d\r\n", hiRet); + return ERROR_WIFI_NOT_AVAILABLE; + } + + if (*size < staNum) { + return ERROR_WIFI_INVALID_ARGS; + } + + int cpyErr; + for (unsigned int i = 0; i < staNum; i++) { + cpyErr = memcpy_s(result[i].macAddress, WIFI_MAC_LEN, staList[i].mac, HI_WIFI_MAC_LEN); + if (cpyErr != EOK) { + printf("[wifi_service]:GetStationList memcpy fail, err = %d\r\n", cpyErr); + return ERROR_WIFI_UNKNOWN; + } + result[i].name = NULL; + +#if LWIP_NETIFAPI_DHCPS_IP + int ret = GetPeerSTAWifiIp(staList[i].mac, WIFI_MAC_LEN, &(result[i].ipAddress)); + if (ret != HISI_OK) { + printf("[wifi_service]:GetPeerSTAWifiIp fail, err = %d\r\n", ret); + return ERROR_WIFI_UNKNOWN; + } +#endif + } + *size = staNum; + return WIFI_SUCCESS; +} + +WifiErrorCode SetBand(int band) +{ + if (band != HOTSPOT_BAND_TYPE_2G) { + return ERROR_WIFI_NOT_SUPPORTED; + } + if (LockWifiGlobalLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + g_wifiApConfig.band = band; + if (UnlockWifiGlobalLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + return WIFI_SUCCESS; +} + +WifiErrorCode GetBand(int* result) +{ + if (result == NULL) { + return ERROR_WIFI_INVALID_ARGS; + } + + if (LockWifiGlobalLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + if (g_wifiApConfig.band == 0) { + if (UnlockWifiGlobalLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + return ERROR_WIFI_NOT_AVAILABLE; + } + if (UnlockWifiGlobalLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + *result = HOTSPOT_BAND_TYPE_2G; + return WIFI_SUCCESS; +} + +int GetSignalLevel(int rssi, int band) +{ + if (band == HOTSPOT_BAND_TYPE_2G) { + if (rssi >= RSSI_LEVEL_4_2_G) { + return RSSI_LEVEL_4; + } + if (rssi >= RSSI_LEVEL_3_2_G) { + return RSSI_LEVEL_3; + } + if (rssi >= RSSI_LEVEL_2_2_G) { + return RSSI_LEVEL_2; + } + if (rssi >= RSSI_LEVEL_1_2_G) { + return RSSI_LEVEL_1; + } + } + + if (band == HOTSPOT_BAND_TYPE_5G) { + if (rssi >= RSSI_LEVEL_4_5_G) { + return RSSI_LEVEL_4; + } + if (rssi >= RSSI_LEVEL_3_5_G) { + return RSSI_LEVEL_3; + } + if (rssi >= RSSI_LEVEL_2_5_G) { + return RSSI_LEVEL_2; + } + if (rssi >= RSSI_LEVEL_1_5_G) { + return RSSI_LEVEL_1; + } + } + + return ERROR_WIFI_INVALID_ARGS; +} + +int GetHotspotChannel(void) +{ + if (LockWifiGlobalLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + if (g_wifiApStatus == WIFI_HOTSPOT_NOT_ACTIVE) { + if (UnlockWifiGlobalLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + return ERROR_WIFI_NOT_STARTED; + } + + int channel = hi_wifi_get_channel(g_wifiIfName, WIFI_IFNAME_MAX_SIZE + 1); + if (UnlockWifiGlobalLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + if (channel == HI_WIFI_INVALID_CHANNEL) { + return ERROR_WIFI_INVALID_ARGS; + } + + return channel; +} + +WifiErrorCode GetHotspotInterfaceName(char* result, int size) +{ + if (LockWifiGlobalLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + if (g_wifiApStatus == WIFI_HOTSPOT_NOT_ACTIVE) { + if (UnlockWifiGlobalLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + return ERROR_WIFI_NOT_STARTED; + } + + int cpyErr = memcpy_s(result, size, g_wifiIfName, WIFI_IFNAME_MAX_SIZE + 1); + if (UnlockWifiGlobalLock() != WIFI_SUCCESS) { + return ERROR_WIFI_UNKNOWN; + } + if (cpyErr != EOK) { + printf("[wifi_service]:getifname memcpy fail, err = %d\n", cpyErr); + return ERROR_WIFI_UNKNOWN; + } + return WIFI_SUCCESS; +} + +WifiErrorCode DisassociateSta(unsigned char* mac, int macLen) +{ + int ret = hi_wifi_softap_deauth_sta(mac, macLen); + if (ret != HISI_OK) { + return ERROR_WIFI_UNKNOWN; + } + return WIFI_SUCCESS; +} + +WifiErrorCode AddTxPowerInfo(int power) +{ + TpcElement tpc = { WIFI_TPC_ID, WIFI_TPC_LEN, 0, 0 }; + if (power > WIFI_TPC_MAX_POWER) { + printf("[wifi_service]:Invalid TPC Power (%d)\n", power); + return ERROR_WIFI_INVALID_ARGS; + } else { + tpc.power = power; + } + + int ret = hi_wifi_add_usr_app_ie(HI_WIFI_IFTYPE_AP, HI_WIFI_FRAME_TYPE_BEACON, HI_WIFI_USR_IE_TYPE_DEFAULT, + (const unsigned char *)&tpc, sizeof(tpc)); + if (ret != HISI_OK) { + printf("[wifi_service]:Wifi Add Beacon IE Fail (%d)\n", ret); + (void)hi_wifi_delete_usr_app_ie(HI_WIFI_IFTYPE_AP, HI_WIFI_FRAME_TYPE_BEACON, HI_WIFI_USR_IE_TYPE_DEFAULT); + return ret; + } + + ret = hi_wifi_add_usr_app_ie(HI_WIFI_IFTYPE_AP, HI_WIFI_FRAME_TYPE_PROBE_RSP, HI_WIFI_USR_IE_TYPE_DEFAULT, + (const unsigned char *)&tpc, sizeof(tpc)); + if (ret != HISI_OK) { + printf("Wifi Add ProbResp IE Fail (%d)\n", ret); + (void)hi_wifi_delete_usr_app_ie(HI_WIFI_IFTYPE_AP, HI_WIFI_FRAME_TYPE_PROBE_RSP, HI_WIFI_USR_IE_TYPE_DEFAULT); + return ret; + } + return WIFI_SUCCESS; +} diff --git a/hi3861_adapter/hals/interfaces/BUILD.gn b/hi3861_adapter/hals/interfaces/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..ccdba37e157ecc3ed6ca83cbd615e1b75a4b7bf5 --- /dev/null +++ b/hi3861_adapter/hals/interfaces/BUILD.gn @@ -0,0 +1,45 @@ +# Copyright (c) 2021 Itcast Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/lite/ndk/ndk.gni") + +group("genkipi_interfaces") { + deps = [ + "$ohos_board_adapter_dir/hals/interfaces:hal_genkipi_interfaces", + ] +} + +if (ohos_kernel_type == "liteos_m") { + ndk_lib("genkipi_interfaces_ndk") { + deps = [ + "$ohos_board_adapter_dir/hals/interfaces:hal_genkipi_interfaces", + ] + head_files = [ "//device/itcast/genkipi/interfaces/kits" ] + } +} + +static_library("hal_genkipi_interfaces") { + if (board_name == "genkipi") { + sources = [ + "hal_genki_led.c", + "hal_genki_wifi_sta.c" + ] + include_dirs = [ + "//utils/native/lite/include", + "//base/iot_hardware/peripheral/interfaces/kits", + "//foundation/communication/wifi_lite/interfaces/wifiservice", + "//device/itcast/genkipi/sdk_liteos/include", + "//device/itcast/genkipi/interfaces/kits" + ] + } +} diff --git a/hi3861_adapter/hals/interfaces/hal_genki_led.c b/hi3861_adapter/hals/interfaces/hal_genki_led.c new file mode 100644 index 0000000000000000000000000000000000000000..42747c4eea735cf9eb46bfe934dc11426f23d14e --- /dev/null +++ b/hi3861_adapter/hals/interfaces/hal_genki_led.c @@ -0,0 +1,113 @@ +/* + * Copyright (c) 2021 Itcast., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include +#include +#include + +#include "ohos_init.h" +#include "iot_gpio.h" +#include "iot_io.h" +#include "iot_pwm.h" + +#include "genki_pin.h" +#include "genki_led.h" + + +static unsigned char led_init = 0; +static unsigned char led_state = 0; +static unsigned char led_pwm_init = 0; + + +static void GenkiLedInit(void) { + // 初始化GPIO端口 + IoTGpioInit(IOT_IO_NAME_2); + + // 设置IO口功能为GPIO + IoTIoSetFunc(IOT_IO_NAME_2, IOT_IO_FUNC_2_GPIO); + + // 设置IO口输出方式:输出 + IoTGpioSetDir(IOT_IO_NAME_2, IOT_GPIO_DIR_OUT); + + IoTGpioSetOutputVal(IOT_IO_NAME_2, IOT_GPIO_VALUE0); + IoTGpioGetOutputVal(IOT_IO_NAME_2, &led_state); +} + +void GenkiLedToggle(void) { + if (led_init == 0) { + GenkiLedInit(); + led_init = 1; + if(led_pwm_init != 0) { + GenkiLedPwmStop(); + } + led_pwm_init = 0; + } + + if (led_state == IOT_GPIO_VALUE0) { + // to high + IoTGpioSetOutputVal(IOT_IO_NAME_2, IOT_GPIO_VALUE1); + IoTGpioGetOutputVal(IOT_IO_NAME_2, &led_state); + } else { + // to low + IoTGpioSetOutputVal(IOT_IO_NAME_2, IOT_GPIO_VALUE0); + IoTGpioGetOutputVal(IOT_IO_NAME_2, &led_state); + } +} + +void GenkiLedState(unsigned char *state) { + IoTGpioGetOutputVal(IOT_IO_NAME_2, &led_state); + *state = led_state; +} + +void GenkiLedOpen(void) { + if (led_state == IOT_GPIO_VALUE0) { + GenkiLedToggle(); + } +} + +void GenkiLedClose(void) { + if (led_state == IOT_GPIO_VALUE1) { + GenkiLedToggle(); + } +} + +static void GenkiLedPwmInit(void) { + // 初始化GPIO端口 + IoTGpioInit(IOT_IO_NAME_2); + + // 设置IO口功能为GPIO + IoTIoSetFunc(IOT_IO_NAME_2, IOT_IO_FUNC_2_PWM2_OUT); + + // 设置IO口输出方式:输出 + IoTGpioSetDir(IOT_IO_NAME_2, IOT_GPIO_DIR_OUT); + + // 初始化PWM + IoTPwmInit(IOT_IO_NAME_2); +} + +void GenkiLedPwmStart(unsigned short duty, unsigned int freq) { + if(led_pwm_init == 0) { + GenkiLedPwmInit(); + led_pwm_init = 1; + led_init = 0; + } + + IoTPwmStart(IOT_IO_NAME_2, duty, freq); +} + +void GenkiLedPwmStop(void) { + IoTPwmStop(IOT_IO_NAME_2); +} diff --git a/hi3861_adapter/hals/interfaces/hal_genki_wifi_sta.c b/hi3861_adapter/hals/interfaces/hal_genki_wifi_sta.c new file mode 100644 index 0000000000000000000000000000000000000000..30b07c6d36951251288fb894456f1adc7d58ee1f --- /dev/null +++ b/hi3861_adapter/hals/interfaces/hal_genki_wifi_sta.c @@ -0,0 +1,299 @@ +/* + * Copyright (c) 2021 Itcast., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ohos_init.h" +#include "ohos_types.h" +#include +#include +#include +#include "cmsis_os2.h" + +#include "wifi_device.h" +#include "wifi_event.h" +#include "wifi_error_code.h" + +#include "lwip/netif.h" +#include "lwip/netifapi.h" +#include "lwip/ip4_addr.h" +#include "lwip/api_shell.h" + +#include "genki_wifi_sta.h" + +#define DEF_TIMEOUT 15 +#define ONE_SECOND 1 + +#define SELECT_WLAN_PORT "wlan0" + +WifiEvent wifi_event_handler = {0}; +static int g_staScanSuccess = 0; +static int g_ConnectSuccess = 0; +static int ssid_count = 0; + +static struct netif *g_lwip_netif = NULL; + + +static void OnWifiConnectionChanged(int state, WifiLinkedInfo *info) { + (void) info; + + if (state > 0) { + g_ConnectSuccess = 1; + printf("[wifi_sta]cb for wifi connect, success\r\n"); + } else { + printf("[wifi_sta]cb for wifi connect, failed, please check password\r\n"); + } + return; +} + +static void OnWifiScanStateChanged(int state, int size) { + (void) state; + if (size > 0) { + ssid_count = size; + g_staScanSuccess = 1; + } + return; +} + +static void OnHotspotStateChanged(int state) { + printf("[wifi_sta]cb for HotspotStateChanged:state is %d.\n", state); + return; +} + +static void OnHotspotStaJoin(StationInfo *info) { + (void) info; + printf("[wifi_sta]STA join AP\r\n"); + return; +} + +static void OnHotspotStaLeave(StationInfo *info) { + (void) info; + printf("[wifi_sta]cb for HotspotStaLeave:mac is %s.\r\n", info->macAddress); + return; +} + +static WifiErrorCode wifi_init(void) { + WifiErrorCode error; + wifi_event_handler.OnWifiConnectionChanged = OnWifiConnectionChanged; + wifi_event_handler.OnWifiScanStateChanged = OnWifiScanStateChanged; + wifi_event_handler.OnHotspotStateChanged = OnHotspotStateChanged; + wifi_event_handler.OnHotspotStaJoin = OnHotspotStaJoin; + wifi_event_handler.OnHotspotStaLeave = OnHotspotStaLeave; + error = RegisterWifiEvent(&wifi_event_handler); + return error; +} + +static void wait_scan_result(void) { + int scanTimeout = DEF_TIMEOUT; + while (scanTimeout > 0) { + sleep(ONE_SECOND); + scanTimeout--; + if (g_staScanSuccess == 1) { + printf("[wifi_sta]wait scan result: wait success[%d]s\n", (DEF_TIMEOUT - scanTimeout)); + break; + } + } + if (scanTimeout <= 0) { + printf("[wifi_sta]wait scan result:timeout!\n"); + } +} + +static int wait_connect_result(void) +{ + int ConnectTimeout = DEF_TIMEOUT; + while (ConnectTimeout > 0) + { + sleep(1); + ConnectTimeout--; + if (g_ConnectSuccess == 1) + { + printf("[wifi_sta]wait connect result:wait success[%d]s\n", (DEF_TIMEOUT - ConnectTimeout)); + break; + } + } + if (ConnectTimeout <= 0) + { + printf("[wifi_sta]wait connect result:timeout!\n"); + return 0; + } + return 1; +} + +int connect_wifi(const char* ssid, const char* password, const char* hostname) { + + // wifi init + WifiErrorCode error = wifi_init(); + if (WIFI_SUCCESS != error) { + printf("[wifi_sta]register wifi event failed, error=%d\r\n", error); + return error; + } + printf("[wifi_sta]register wifi event success\r\n"); + + // wifi enable + error = EnableWifi(); + if (WIFI_SUCCESS != error) { + printf("[wifi_sta]enable wifi failed, error=%d\r\n", error); + return error; + } + printf("[wifi_sta]enable wifi success\r\n"); + + // check wifi active + if (IsWifiActive() == 0) { + printf("[wifi_sta] wifi station is not active\r\n"); + return error; + } + + unsigned int size = WIFI_SCAN_HOTSPOT_LIMIT; + WifiScanInfo *info = NULL; + info = malloc(sizeof(WifiScanInfo) * size); + if (NULL == info) { + printf("[wifi_sta] wifi scan info init failed\r\n"); + return error; + } + + // scan wifi list + do { + // reset + ssid_count = 0; + g_staScanSuccess = 0; + + // start scan + Scan(); + + // wait scan result + wait_scan_result(); + + // get scan result + error = GetScanInfoList(info, &size); + + } while (g_staScanSuccess != 1); + + // print wifi list + for (int i = 0; i < ssid_count; ++i) { + printf("[wifi_sta]scan wifi: %s\r\n", info[i].ssid); + + if (strcmp(ssid, info[i].ssid) == 0) { + WifiDeviceConfig ap_config = {0}; + strcpy(ap_config.ssid, info[i].ssid); + strcpy(ap_config.preSharedKey, password); + ap_config.securityType = WIFI_SEC_TYPE_PSK; + + int result; + if (AddDeviceConfig(&ap_config, &result) == WIFI_SUCCESS) { + + // connect to wifi + if (ConnectTo(result) == WIFI_SUCCESS && wait_connect_result() == 1) { + printf("[wifi_sta]wifi connect success!\r\n"); + g_lwip_netif = netifapi_netif_find(SELECT_WLAN_PORT); + break; + } + } + } + + if (i == ssid_count - 1) { + printf("[wifi_sta]ERROR No wifi expected \r\n"); + } + } + + if (!g_lwip_netif) { + printf("[wifi_sta]netif error \r\n"); + return error; + } + + // start dhcp + netifapi_set_hostname(g_lwip_netif, hostname, strlen(hostname)); + netifapi_dhcp_start(g_lwip_netif); + + // wait dhcp + while (1) { + if (dhcp_is_bound(g_lwip_netif) == ERR_OK) { + printf("[wifi_sta]dhcp bound success\r\n"); + + netifapi_netif_common(g_lwip_netif, dhcp_clients_info_show, NULL); + break; + } + + osDelay(100); + } + + return WIFI_SUCCESS; +} + +int disconnect_wifi(void) { + if (!g_lwip_netif) { + printf("[wifi_sta]netif error \r\n"); + return -1; + } + + WifiErrorCode error = Disconnect(); + if (WIFI_SUCCESS != error) { + printf("[wifi_sta]disconnect wifi failed, error=%d\r\n", error); + return error; + } + + error = DisableWifi(); + if (WIFI_SUCCESS != error) { + printf("[wifi_sta]disable wifi failed, error=%d\r\n", error); + return error; + } + + error = UnRegisterWifiEvent(&wifi_event_handler); + if (WIFI_SUCCESS != error) { + printf("[wifi_sta]unregister wifi event failed, error=%d\r\n", error); + return error; + } + printf("[wifi_sta]disconnect wifi success\r\n"); + return WIFI_SUCCESS; +} + +static int get_wifi_local_ip() { + if (!g_lwip_netif) { + printf("[wifi_sta]netif error \r\n"); + return -1; + } + + ip4_addr_t ip_addr; + ip4_addr_t netmask_addr; + ip4_addr_t gw_addr; + if(netifapi_netif_get_addr(g_lwip_netif, &ip_addr, &netmask_addr, &gw_addr) == ERR_OK) { + u32_t ip = ip_addr.addr; + u32_t netmask = netmask_addr.addr; + u32_t gw = gw_addr.addr; + + printf("ip %d.%d.%d.%d\n\r",(ip & 0xff), ((ip >> 8) & 0xff), ((ip >> 16) & 0xff), (ip >> 24)); + printf("netmask %d.%d.%d.%d\n\r",(netmask & 0xff), ((netmask >> 8) & 0xff), ((netmask >> 16) & 0xff), (netmask >> 24)); + printf("gw %d.%d.%d.%d\n\r",(gw & 0xff), ((gw >> 8) & 0xff), ((gw >> 16) & 0xff), (gw >> 24)); + } else { + printf("netif get addr failed\r\n"); + } + + return 1; +} + +int get_wifi_addr(unsigned int *ip, unsigned int *netmask, unsigned int *gateway) { + if (!g_lwip_netif) { + printf("[wifi_sta]netif error \r\n"); + return 0; + } + + ip4_addr_t ip_addr; + ip4_addr_t netmask_addr; + ip4_addr_t gw_addr; + if(netifapi_netif_get_addr(g_lwip_netif, &ip_addr, &netmask_addr, &gw_addr) == ERR_OK) { + *ip = ip_addr.addr; + *netmask = netmask_addr.addr; + *gateway = gw_addr.addr; + return 1; + } + return 0; +} diff --git a/hi3861_adapter/hals/iot_hardware/wifiiot_lite/BUILD.gn b/hi3861_adapter/hals/iot_hardware/wifiiot_lite/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..e8b3127940d78756cbb93eae107ab116150e3be6 --- /dev/null +++ b/hi3861_adapter/hals/iot_hardware/wifiiot_lite/BUILD.gn @@ -0,0 +1,37 @@ +# Copyright (c) 2021 Itcast Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +static_library("hal_iothardware") { + if (board_name == "genkipi") { + sources = [ + "hal_iot_adc.c", + "hal_iot_flash.c", + "hal_iot_gpio.c", + "hal_iot_i2c.c", + "hal_iot_io.c", + "hal_iot_pwm.c", + "hal_iot_spi.c", + "hal_iot_uart.c", + "hal_iot_watchdog.c", + "hal_lowpower.c", + "hal_reset.c", + "hal_time.c" + ] + include_dirs = [ + "//utils/native/lite/include", + "//base/iot_hardware/peripheral/interfaces/kits", + "//device/itcast/genkipi/sdk_liteos/include", + "//device/itcast/genkipi/interfaces/kits", + ] + } +} diff --git a/hi3861_adapter/hals/iot_hardware/wifiiot_lite/hal_iot_adc.c b/hi3861_adapter/hals/iot_hardware/wifiiot_lite/hal_iot_adc.c new file mode 100644 index 0000000000000000000000000000000000000000..51c05ad2e4a4367e22e2eeb6e981478d709cc7ae --- /dev/null +++ b/hi3861_adapter/hals/iot_hardware/wifiiot_lite/hal_iot_adc.c @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2021 Itcast Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "hi_adc.h" +#include "iot_adc.h" + +unsigned int IoTAdcRead(IoTAdcChannelIndex channel, unsigned short *data, IoTAdcEquModelSel equModel, + IoTAdcCurBais curBais, unsigned short rstCnt) { + return hi_adc_read((hi_adc_channel_index) channel, (hi_u16 *) data, (hi_adc_equ_model_sel) equModel, + (hi_adc_cur_bais) curBais, (hi_u16) rstCnt); +} diff --git a/hi3861_adapter/hals/iot_hardware/wifiiot_lite/hal_iot_flash.c b/hi3861_adapter/hals/iot_hardware/wifiiot_lite/hal_iot_flash.c new file mode 100755 index 0000000000000000000000000000000000000000..8b73313f6b79aea5fdc8c5fe17e0ae9228cdc666 --- /dev/null +++ b/hi3861_adapter/hals/iot_hardware/wifiiot_lite/hal_iot_flash.c @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2021 Itcast Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "iot_errno.h" +#include "iot_flash.h" +#include "hi_flash.h" + +unsigned int IoTFlashRead(unsigned int flashOffset, unsigned int size, unsigned char *ramData) +{ + return hi_flash_read(flashOffset, size, ramData); +} + +unsigned int IoTFlashWrite(unsigned int flashOffset, unsigned int size, + const unsigned char *ramData, unsigned char doErase) +{ + return hi_flash_write(flashOffset, size, ramData, doErase); +} + +unsigned int IoTFlashErase(unsigned int flashOffset, unsigned int size) +{ + return hi_flash_erase(flashOffset, size); +} + +unsigned int IoTFlashInit(void) +{ + return hi_flash_init(); +} + +unsigned int IoTFlashDeinit(void) +{ + return hi_flash_deinit(); +} diff --git a/hi3861_adapter/hals/iot_hardware/wifiiot_lite/hal_iot_gpio.c b/hi3861_adapter/hals/iot_hardware/wifiiot_lite/hal_iot_gpio.c new file mode 100755 index 0000000000000000000000000000000000000000..7475113d8e1d88de17844b98496986525a9e3d1b --- /dev/null +++ b/hi3861_adapter/hals/iot_hardware/wifiiot_lite/hal_iot_gpio.c @@ -0,0 +1,113 @@ +/* + * Copyright (c) 2021 Itcast Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "iot_errno.h" +#include "iot_gpio.h" +#include "hi_gpio.h" + + +#define GPIO_PIN_INIT 1 +#define GPIO_PIN_UNINIT 0 + +static unsigned char g_gpioMap[HI_GPIO_IDX_MAX] = {0}; +static unsigned char g_gpioInitNum = 0; + +unsigned int IoTGpioInit(unsigned int id) +{ + if (id >= HI_GPIO_IDX_MAX) { + return IOT_FAILURE; + } + + if (g_gpioInitNum == 0) { + (void)hi_gpio_init(); + } + + if (g_gpioMap[id] == GPIO_PIN_INIT) { + return IOT_FAILURE; + } else { + g_gpioMap[id] = GPIO_PIN_INIT; + g_gpioInitNum++; + } + + return IOT_SUCCESS; +} + +unsigned int IoTGpioSetDir(unsigned int id, IotGpioDir dir) +{ + return hi_gpio_set_dir((hi_gpio_idx)id, (hi_gpio_dir)dir); +} + +unsigned int IoTGpioGetDir(unsigned int id, IotGpioDir *dir) +{ + return hi_gpio_get_dir((hi_gpio_idx)id, (hi_gpio_dir *)dir); +} + +unsigned int IoTGpioSetOutputVal(unsigned int id, IotGpioValue val) +{ + return hi_gpio_set_ouput_val((hi_gpio_idx)id, (hi_gpio_value)val); +} + +unsigned int IoTGpioGetOutputVal(unsigned int id, IotGpioValue *val) +{ + return hi_gpio_get_output_val((hi_gpio_idx)id, (hi_gpio_value *)val); +} + +unsigned int IoTGpioGetInputVal(unsigned int id, IotGpioValue *val) +{ + return hi_gpio_get_input_val((hi_gpio_idx)id, (hi_gpio_value *)val); +} + +unsigned int IoTGpioRegisterIsrFunc(unsigned int id, IotGpioIntType intType, IotGpioIntPolarity intPolarity, + GpioIsrCallbackFunc func, char *arg) +{ + return hi_gpio_register_isr_function((hi_gpio_idx)id, (hi_gpio_int_type)intType, + (hi_gpio_int_polarity)intPolarity, (gpio_isr_callback)func, arg); +} + +unsigned int IoTGpioUnregisterIsrFunc(unsigned int id) +{ + return hi_gpio_unregister_isr_function((hi_gpio_idx)id); +} + +unsigned int IoTGpioSetIsrMask(unsigned int id, unsigned char mask) +{ + return hi_gpio_set_isr_mask((hi_gpio_idx)id, (hi_bool)mask); +} + +unsigned int IoTGpioSetIsrMode(unsigned int id, IotGpioIntType intType, IotGpioIntPolarity intPolarity) +{ + return hi_gpio_set_isr_mode((hi_gpio_idx)id, (hi_gpio_int_type)intType, (hi_gpio_int_polarity)intPolarity); +} + +unsigned int IoTGpioDeinit(unsigned int id) +{ + if (id >= HI_GPIO_IDX_MAX) { + return IOT_FAILURE; + } + + if (g_gpioMap[id] == GPIO_PIN_INIT) { + g_gpioInitNum--; + g_gpioMap[id] = GPIO_PIN_UNINIT; + } else { + return IOT_FAILURE; + } + + if (g_gpioInitNum == 0) { + return hi_gpio_deinit(); + } else { + return IOT_SUCCESS; + } +} + diff --git a/hi3861_adapter/hals/iot_hardware/wifiiot_lite/hal_iot_i2c.c b/hi3861_adapter/hals/iot_hardware/wifiiot_lite/hal_iot_i2c.c new file mode 100755 index 0000000000000000000000000000000000000000..6b075e734f6f83ed773388b870d9c34442cdafbd --- /dev/null +++ b/hi3861_adapter/hals/iot_hardware/wifiiot_lite/hal_iot_i2c.c @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2021 Itcast Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "iot_errno.h" +#include "iot_i2c.h" +#include "hi_i2c.h" + +unsigned int IoTI2cWrite(unsigned int id, unsigned short deviceAddr, const unsigned char *data, unsigned int dataLen) { + hi_i2c_data i2cData; + i2cData.receive_buf = NULL; + i2cData.receive_len = 0; + i2cData.send_buf = data; + i2cData.send_len = dataLen; + + return hi_i2c_write((hi_i2c_idx) id, deviceAddr, &i2cData); +} + +unsigned int IoTI2cRead(unsigned int id, unsigned short deviceAddr, unsigned char *data, unsigned int dataLen) { + hi_i2c_data i2cData; + i2cData.receive_buf = data; + i2cData.receive_len = dataLen; + i2cData.send_buf = NULL; + i2cData.send_len = 0; + + return hi_i2c_read((hi_i2c_idx) id, deviceAddr, &i2cData); +} + +unsigned int IoTI2cWriteRead(unsigned int id, unsigned short deviceAddr, + const unsigned char *writeData, unsigned int writeDataLen, + unsigned char *readData, unsigned int readDataLen) { + hi_i2c_data i2cData; + i2cData.receive_buf = readData; + i2cData.receive_len = readDataLen; + i2cData.send_buf = writeData; + i2cData.send_len = writeDataLen; + + return hi_i2c_writeread((hi_i2c_idx) id, deviceAddr, &i2cData); +} + +unsigned int IoTI2cInit(unsigned int id, unsigned int baudrate) { + return hi_i2c_init((hi_i2c_idx) id, baudrate); +} + +unsigned int IoTI2cDeinit(unsigned int id) { + return hi_i2c_deinit((hi_i2c_idx) id); +} + +unsigned int IoTI2cSetBaudrate(unsigned int id, unsigned int baudrate) { + return hi_i2c_set_baudrate((hi_i2c_idx) id, baudrate); +} diff --git a/hi3861_adapter/hals/iot_hardware/wifiiot_lite/hal_iot_io.c b/hi3861_adapter/hals/iot_hardware/wifiiot_lite/hal_iot_io.c new file mode 100644 index 0000000000000000000000000000000000000000..633eda75126922ec737e7e4115141d64d659cc10 --- /dev/null +++ b/hi3861_adapter/hals/iot_hardware/wifiiot_lite/hal_iot_io.c @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2021 Itcast Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "iot_errno.h" +#include "iot_io.h" + +#include "hi_io.h" +#include "hi_gpio.h" +#include "genki_pin.h" + +unsigned int IoTIoSetPull(unsigned int id, IoTIoPull val) { + if (id >= HI_GPIO_IDX_MAX) { + return IOT_FAILURE; + } + return hi_io_set_pull((hi_io_name) id, (hi_io_pull) val); +} + +unsigned int IoTIoSetFunc(unsigned int id, unsigned char val) { + if (id >= HI_GPIO_IDX_MAX) { + return IOT_FAILURE; + } + return hi_io_set_func((hi_io_name) id, val); +} + +unsigned int IoTIoGetPull(unsigned int id, IoTIoPull *val) { + if (id >= HI_GPIO_IDX_MAX) { + return IOT_FAILURE; + } + return hi_io_get_pull((hi_io_name) id, (hi_io_pull *) val); +} + +unsigned int IoTIoGetFunc(unsigned int id, unsigned char *val) { + if (id >= HI_GPIO_IDX_MAX) { + return IOT_FAILURE; + } + return hi_io_get_func((hi_io_name) id, val); +} + +unsigned int IoTIoGetDriverStrength(unsigned int id, IoTIoDriverStrength *val) { + if (id >= HI_GPIO_IDX_MAX) { + return IOT_FAILURE; + } + return hi_io_get_driver_strength((hi_io_name) id, (hi_io_driver_strength *) val); +} + +unsigned int IoTIoSetDriverStrength(unsigned int id, IoTIoDriverStrength val) { + if (id >= HI_GPIO_IDX_MAX) { + return IOT_FAILURE; + } + return hi_io_set_driver_strength((hi_io_name) id, (hi_io_driver_strength) val); +} diff --git a/hi3861_adapter/hals/iot_hardware/wifiiot_lite/hal_iot_pwm.c b/hi3861_adapter/hals/iot_hardware/wifiiot_lite/hal_iot_pwm.c new file mode 100755 index 0000000000000000000000000000000000000000..fc42f5cc761cd4456c07bbb49e129e1daf59140a --- /dev/null +++ b/hi3861_adapter/hals/iot_hardware/wifiiot_lite/hal_iot_pwm.c @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2021 Itcast Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include "iot_errno.h" +#include "iot_pwm.h" +#include "hi_pwm.h" +#include "hi_errno.h" + +#define CLK_160M 160000000 +#define DUTY_MIN 0 +#define DUTY_MAX 100 +#define SHORT_MAX 0xFFFF + +unsigned int IoTPwmInit(unsigned int port) +{ + if (hi_pwm_set_clock(PWM_CLK_160M) != HI_ERR_SUCCESS) { + return IOT_FAILURE; + } + return hi_pwm_init((hi_pwm_port)port); +} + +unsigned int IoTPwmDeinit(unsigned int port) +{ + return hi_pwm_deinit((hi_pwm_port)port); +} + +unsigned int IoTPwmStart(unsigned int port, unsigned short duty, unsigned int freq) +{ + unsigned short hiDuty; + unsigned short hiFreq; + + if ((freq == 0) || (duty >= DUTY_MAX) || (duty == DUTY_MIN)) { + return IOT_FAILURE; + } + + if ((CLK_160M / freq) > SHORT_MAX) { + return IOT_FAILURE; + } + + hiFreq = (unsigned short)(CLK_160M / freq); + hiDuty = (duty * hiFreq) / DUTY_MAX; + + return hi_pwm_start((hi_pwm_port)port, hiDuty, hiFreq); +} + +unsigned int IoTPwmStop(unsigned int port) +{ + return hi_pwm_stop((hi_pwm_port)port); +} + diff --git a/hi3861_adapter/hals/iot_hardware/wifiiot_lite/hal_iot_spi.c b/hi3861_adapter/hals/iot_hardware/wifiiot_lite/hal_iot_spi.c new file mode 100644 index 0000000000000000000000000000000000000000..a4e1932e96873bce95e310cb87187a13c6b2b761 --- /dev/null +++ b/hi3861_adapter/hals/iot_hardware/wifiiot_lite/hal_iot_spi.c @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2021 Itcast Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "iot_spi.h" + +#include + +#include "hi_spi.h" + +unsigned int IoTSpiSlaveWrite(IoTSpiIdx spiId, char *writeData, unsigned int byteLen, unsigned int timeOutMs) { + return hi_spi_slave_write((hi_spi_idx) spiId, writeData, byteLen, timeOutMs); +} + +unsigned int IoTSpiSlaveRead(IoTSpiIdx spiId, char *readData, unsigned int byteLen, unsigned int timeOutMs) { + return hi_spi_slave_read((hi_spi_idx) spiId, readData, byteLen, timeOutMs); +} + +unsigned int IoTSpiHostWrite(IoTSpiIdx spiId, char *writeData, unsigned int byteLen) { + return hi_spi_host_write((hi_spi_idx) spiId, writeData, byteLen); +} + +unsigned int IoTSpiHostRead(IoTSpiIdx spiId, char *readData, unsigned int byteLen) { + return hi_spi_host_read((hi_spi_idx) spiId, readData, byteLen); +} + +unsigned int IoTSpiHostWriteread(IoTSpiIdx spiId, char *writeData, char *readData, unsigned int byteLen) { + return hi_spi_host_writeread((hi_spi_idx) spiId, writeData, readData, byteLen); +} + +unsigned int IoTSpiSetBasicInfo(IoTSpiIdx spiId, const IoTSpiCfgBasicInfo *param) { + return hi_spi_set_basic_info((hi_spi_idx) spiId, (const hi_spi_cfg_basic_info *) param); +} + +unsigned int IoTSpiInit(IoTSpiIdx spiId, IoTSpiCfgInitParam initParam, + const IoTSpiCfgBasicInfo *param) { + hi_spi_cfg_init_param hiInitParam; + hiInitParam.is_slave = initParam.isSlave; + hiInitParam.pad = initParam.pad; + return hi_spi_init((hi_spi_idx) spiId, hiInitParam, (const hi_spi_cfg_basic_info *) param); +} + +unsigned int IoTSpiDeinit(IoTSpiIdx spiId) { + return hi_spi_deinit((hi_spi_idx) spiId); +} + +unsigned int IoTSpiSetIrqMode(IoTSpiIdx spiId, unsigned char irqEn) { + return hi_spi_set_irq_mode((hi_spi_idx) spiId, irqEn); +} + +unsigned int IoTSpiSetDmaMode(IoTSpiIdx spiId, unsigned char dmaEn) { + return hi_spi_set_dma_mode((hi_spi_idx) spiId, dmaEn); +} + +unsigned int IoTSpiRegisterUsrFunc(IoTSpiIdx spiId, SpiIsrFunc prepareF, SpiIsrFunc restoreF) { + return hi_spi_register_usr_func((hi_spi_idx) spiId, prepareF, restoreF); +} + +unsigned int IoTSpiSetLoopBackMode(IoTSpiIdx spiId, unsigned char lbEn) { + return hi_spi_set_loop_back_mode((hi_spi_idx) spiId, lbEn); +} diff --git a/hi3861_adapter/hals/iot_hardware/wifiiot_lite/hal_iot_uart.c b/hi3861_adapter/hals/iot_hardware/wifiiot_lite/hal_iot_uart.c new file mode 100755 index 0000000000000000000000000000000000000000..dd0fb5ec2f73f6589271658605597ffddf7b45e7 --- /dev/null +++ b/hi3861_adapter/hals/iot_hardware/wifiiot_lite/hal_iot_uart.c @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2021 Itcast Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "iot_errno.h" +#include "iot_uart.h" +#include "hi_uart.h" + +unsigned int IoTUartInit(unsigned int id, const IotUartAttribute *param) +{ + hi_uart_attribute attr = {0}; + hi_uart_extra_attr extraAttr = {0}; + + if (NULL == param) { + return IOT_FAILURE; + } + + attr.baud_rate = param->baudRate; + attr.data_bits = param->dataBits; + attr.pad = param->pad; + attr.parity = param->parity; + attr.stop_bits = param->stopBits; + + if (IOT_UART_BLOCK_STATE_NONE_BLOCK == param->rxBlock) { + extraAttr.rx_block = HI_UART_BLOCK_STATE_NONE_BLOCK; + } else { + extraAttr.rx_block = HI_UART_BLOCK_STATE_BLOCK; + } + + if (IOT_UART_BLOCK_STATE_NONE_BLOCK == param->txBlock) { + extraAttr.tx_block = HI_UART_BLOCK_STATE_NONE_BLOCK; + } else { + extraAttr.tx_block = HI_UART_BLOCK_STATE_BLOCK; + } + + return hi_uart_init((hi_uart_idx)id, &attr, &extraAttr); +} + +int IoTUartRead(unsigned int id, unsigned char *data, unsigned int dataLen) +{ + return hi_uart_read((hi_uart_idx)id, data, dataLen); +} + +int IoTUartWrite(unsigned int id, const unsigned char *data, unsigned int dataLen) +{ + return hi_uart_write((hi_uart_idx)id, data, dataLen); +} + +unsigned int IoTUartDeinit(unsigned int id) +{ + return hi_uart_deinit((hi_uart_idx)id); +} + +unsigned int IoTUartSetFlowCtrl(unsigned int id, IotFlowCtrl flowCtrl) +{ + return hi_uart_set_flow_ctrl((hi_uart_idx)id, (hi_flow_ctrl)flowCtrl); +} diff --git a/hi3861_adapter/hals/iot_hardware/wifiiot_lite/hal_iot_watchdog.c b/hi3861_adapter/hals/iot_hardware/wifiiot_lite/hal_iot_watchdog.c new file mode 100755 index 0000000000000000000000000000000000000000..be023052e8d1fb584c19ad5d26d6e8c1744acb08 --- /dev/null +++ b/hi3861_adapter/hals/iot_hardware/wifiiot_lite/hal_iot_watchdog.c @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2021 Itcast Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "iot_errno.h" +#include "iot_watchdog.h" +#include "hi_watchdog.h" + +void IoTWatchDogEnable(void) +{ + return hi_watchdog_enable(); +} + +void IoTWatchDogKick(void) +{ + return hi_watchdog_feed(); +} + +void IoTWatchDogDisable(void) +{ + return hi_watchdog_disable(); +} + diff --git a/hi3861_adapter/hals/iot_hardware/wifiiot_lite/hal_lowpower.c b/hi3861_adapter/hals/iot_hardware/wifiiot_lite/hal_lowpower.c new file mode 100755 index 0000000000000000000000000000000000000000..453d5ed7b22feade309af88dd3f6d395f0f44829 --- /dev/null +++ b/hi3861_adapter/hals/iot_hardware/wifiiot_lite/hal_lowpower.c @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2021 Itcast Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "lowpower.h" +#include "hi_lowpower.h" + +unsigned int LpcInit(void) +{ + return hi_lpc_init(); +} + +unsigned int LpcSetType(LpcType type) +{ + return hi_lpc_set_type(type); +} + diff --git a/hi3861_adapter/hals/iot_hardware/wifiiot_lite/hal_reset.c b/hi3861_adapter/hals/iot_hardware/wifiiot_lite/hal_reset.c new file mode 100755 index 0000000000000000000000000000000000000000..8d3a9e26d696314e86a4445a06f5d6383711d872 --- /dev/null +++ b/hi3861_adapter/hals/iot_hardware/wifiiot_lite/hal_reset.c @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2021 Itcast Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "reset.h" +#include "hi_reset.h" + +void RebootDevice(unsigned int cause) +{ + hi_hard_reboot(cause); +} diff --git a/hi3861_adapter/hals/iot_hardware/wifiiot_lite/hal_time.c b/hi3861_adapter/hals/iot_hardware/wifiiot_lite/hal_time.c new file mode 100644 index 0000000000000000000000000000000000000000..8c89b5b76a8d70ab5a5df5f2470f222ce81e8b38 --- /dev/null +++ b/hi3861_adapter/hals/iot_hardware/wifiiot_lite/hal_time.c @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2021 Itcast Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include "time.h" +#include "hi_time.h" + +void IoTUdelay(unsigned int us) { + return hi_udelay((hi_u32) us); +} + +unsigned int IoTGetTick(void) { + return hi_get_tick(); +} + +unsigned long long IoTGetTick64(void) { + return hi_get_tick64(); +} + +unsigned int IoTGetMilliSeconds(void) { + return hi_get_milli_seconds(); +} + +unsigned int IoTGetSeconds(void) { + return hi_get_seconds(); +} + +unsigned long IoTGetUs(void) { + return hi_get_us(); +} diff --git a/hi3861_adapter/hals/update/BUILD.gn b/hi3861_adapter/hals/update/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..4ae92971d0fd6e87f7fe748abdd94ef17727e4a8 --- /dev/null +++ b/hi3861_adapter/hals/update/BUILD.gn @@ -0,0 +1,23 @@ +# Copyright (c) 2021 Itcast Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/lite/config/component/lite_component.gni") + +static_library("hal_update_static") { + sources = [ "hal_hota_board.c" ] + include_dirs = [ + "//base/update/ota_lite/hals", + "//base/update/ota_lite/interfaces/kits", + "//device/itcast/genkipi/sdk_liteos/include", + ] +} diff --git a/hi3861_adapter/hals/update/hal_hota_board.c b/hi3861_adapter/hals/update/hal_hota_board.c new file mode 100644 index 0000000000000000000000000000000000000000..37116bafaec7d6e2b872302245db4fe3e5c93f57 --- /dev/null +++ b/hi3861_adapter/hals/update/hal_hota_board.c @@ -0,0 +1,202 @@ +/* + * Copyright (c) 2020 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "hal_hota_board.h" +#include "hi_upg_api.h" +#include "stdio.h" + +#define PUBKEY_LENGTH 270 + + +static const unsigned char g_pubKeyBuf[PUBKEY_LENGTH] = { + 0x30, 0x82, 0x01, 0x0A, 0x02, 0x82, 0x01, 0x01, 0x00, 0xBF, 0xAA, 0xA5, 0xB3, 0xC2, 0x78, 0x5E, + 0x63, 0x07, 0x84, 0xCF, 0x37, 0xF0, 0x45, 0xE8, 0xB9, 0x6E, 0xEF, 0x04, 0x88, 0xD3, 0x43, 0x06, + 0x2C, 0xFC, 0x09, 0x8C, 0x84, 0x3B, 0x43, 0x07, 0x89, 0x6B, 0x23, 0x8F, 0xA2, 0xF0, 0x9D, 0x91, + 0xCB, 0xA8, 0x02, 0x60, 0xD8, 0x5C, 0x18, 0xD9, 0x34, 0xF0, 0x3C, 0x49, 0x10, 0x0E, 0xE3, 0xC7, + 0x19, 0xA5, 0x51, 0x93, 0x38, 0xFD, 0xE0, 0x62, 0x64, 0xBA, 0x6D, 0x11, 0x2E, 0xE1, 0x6E, 0x60, + 0x12, 0x16, 0x1B, 0x35, 0xA6, 0x54, 0x3F, 0x0B, 0x5D, 0x54, 0x08, 0xC9, 0x23, 0x51, 0x15, 0xA9, + 0xE2, 0x07, 0xCC, 0xF9, 0xFD, 0x19, 0x8A, 0xB3, 0x7E, 0xCE, 0x69, 0xED, 0x26, 0x34, 0xD2, 0x02, + 0xF3, 0xEB, 0x07, 0x13, 0x69, 0xE3, 0x03, 0x87, 0xB3, 0x6A, 0x3E, 0x91, 0x94, 0xAC, 0x2C, 0xBA, + 0xF6, 0xEE, 0x4C, 0x41, 0x0C, 0x2E, 0xD0, 0xE7, 0x58, 0xA7, 0xE6, 0x7F, 0x1A, 0xC0, 0xB8, 0xE3, + 0x12, 0x18, 0x97, 0x8D, 0x99, 0xAB, 0x35, 0x7B, 0xAD, 0x41, 0xA0, 0xFB, 0xCB, 0x23, 0xF6, 0x51, + 0xE6, 0x94, 0x1F, 0xF7, 0xD8, 0x16, 0xCD, 0x15, 0x67, 0x59, 0x10, 0xA2, 0x40, 0x55, 0xD1, 0x67, + 0xDA, 0x18, 0xCD, 0x63, 0x5B, 0x10, 0xAF, 0x22, 0x99, 0xD8, 0x9D, 0x56, 0x66, 0xCD, 0x80, 0x64, + 0x32, 0xB5, 0xD7, 0xF5, 0xBA, 0x91, 0x4A, 0x8D, 0x97, 0x14, 0x8A, 0xB2, 0xB0, 0x42, 0x4A, 0xE6, + 0x43, 0x22, 0x3B, 0x6E, 0xD6, 0x1E, 0x1F, 0xDA, 0xEC, 0x83, 0xCF, 0x20, 0xFA, 0x02, 0xF3, 0xFB, + 0x6E, 0x09, 0x2A, 0x0D, 0xB7, 0x81, 0x1E, 0xD5, 0x71, 0xDF, 0x80, 0xC5, 0x33, 0x78, 0xE5, 0x41, + 0x33, 0xDF, 0x9A, 0xBD, 0x36, 0x51, 0xAC, 0x96, 0xF4, 0xC6, 0x11, 0xC3, 0x93, 0x78, 0x26, 0x96, + 0x9F, 0x67, 0x05, 0x1D, 0xDF, 0xB3, 0xAA, 0x26, 0x25, 0x02, 0x03, 0x01, 0x00, 0x01 +}; +typedef enum { + PARTITION_PASS_THROUGH = 0, + PARTITION_BOOTLOADER = 2, + PARTITION_KERNEL_A = 3, + PARTITION_KERNEL_B = 4, + PARTITION_ROOTFS = 5, + PARTITION_APP = 6, + PARTITION_DATA = 7, + PARTITION_OTA_TAG = 8, + PARTITION_OTA_CONFIG = 9, + PARTITION_ROOTFS_EXT4 = 10, + PARTITION_MAX +} HotaPartition; + +static const ComponentTableInfo g_componentTable[] = { + { PARTITION_PASS_THROUGH, "", "/sdcard/update/ota_pkg_pass_through.bin", 0}, + { PARTITION_INFO_COMP, "", "/sdcard/update/infocomp.bin", 0}, + { PARTITION_BOOTLOADER, "bootloader", "/sdcard/update/u-boot.bin", 0}, + { PARTITION_KERNEL_A, "kernel_A", "/sdcard/update/kernel.bin", 0}, + { PARTITION_KERNEL_B, "kernel_B", "", 0}, + { PARTITION_ROOTFS, "rootfs", "/sdcard/update/rootfs.img", 0}, + { PARTITION_APP, "app", "", 0}, + { PARTITION_DATA, "data", "", 0}, + { PARTITION_OTA_TAG, "ota_tag", "/sdcard/update/OTA.tag", 0}, + { PARTITION_OTA_CONFIG, "config", "/sdcard/update/config", 0}, + { PARTITION_ROOTFS_EXT4, "rootfs_ext4", "/sdcard/update/rootfs_ext4.img", 0}, + { PARTITION_MAX, NULL, NULL, 0} +}; +int HotaHalInit(void) +{ + hi_u32 result = hi_upg_init(); + if (result != HI_ERR_SUCCESS && result != HI_ERR_UPG_INITILIZATION_ALREADY) { + printf("hi_upg_init Failed.Result = %x.\r\n", result); + return OHOS_FAILURE; + } + return OHOS_SUCCESS; +} + +int HotaHalGetUpdateIndex(unsigned int *index) +{ + if (hi_upg_get_file_index((hi_u8 *)index) != HI_ERR_SUCCESS) { + printf("get upgrade index error\r\n"); + return OHOS_FAILURE; + } + return OHOS_SUCCESS; +} + +int HotaHalDeInit(void) +{ + hi_u32 result = hi_upg_stop(); + if (result != HI_ERR_SUCCESS) { + printf("hi_upg_stop Failed.Result = %x.\r\n", result); + return OHOS_FAILURE; + } + return OHOS_SUCCESS; +} + +int HotaHalRead(int partition, unsigned int offset, unsigned int bufLen, unsigned char *buffer) +{ + if ((buffer == NULL) || (bufLen == 0)) { + return OHOS_FAILURE; + } + + if (hi_upg_get_content(offset, buffer, bufLen) != HI_ERR_SUCCESS) { + printf("get ota content error! Partition: %d\r\n", partition); + return OHOS_FAILURE; + } + + return OHOS_SUCCESS; +} + +int HotaHalWrite(int partition, unsigned char *buffer, unsigned int offset, unsigned int buffLen) +{ + if (partition == PARTITION_INFO_COMP) { + printf("partition == PARTITION_INFO_COMP, skip it."); + return OHOS_SUCCESS; + } + hi_u32 result = hi_upg_transmit(offset, buffer, buffLen); + if (result != HI_ERR_SUCCESS) { + printf("hi_upg_transmit failed. retCode = %x.\r\n", result); + return OHOS_FAILURE; + } + return OHOS_SUCCESS; +} + +int HotaHalRestart(void) +{ + hi_upg_finish_with_cache(); + return OHOS_SUCCESS; +} + +int HotaHalSetBootSettings(void) +{ + hi_u32 result = hi_upg_transmit_finish_save_cache(); + if (result != HI_ERR_SUCCESS) { + printf("hi_upg_transmit_finish failed. retCode = %x.\r\n", result); + return OHOS_FAILURE; + } + return OHOS_SUCCESS; +} + +int HotaHalRollback(void) +{ + return OHOS_SUCCESS; +} + +const ComponentTableInfo *HotaHalGetPartitionInfo() +{ + return g_componentTable; +} + +unsigned char *HotaHalGetPubKey(unsigned int *length) +{ + if (length == NULL) { + printf("OTA pub key is NULL.\r\n"); + return NULL; + } + + *length = sizeof(g_pubKeyBuf); + return (unsigned char *)g_pubKeyBuf; +} + + +int HotaHalGetUpdateAbility(void) +{ + return ABILITY_PKG_SEARCH | ABILITY_PKG_DLOAD; +} + +int HotaHalGetOtaPkgPath(char *path, int len) +{ + int ret = strcpy_s(path, len ,"/sdcard"); + if (ret != 0) { + return OHOS_FAILURE; + } + return OHOS_SUCCESS; +} + +int HotaHalIsDeviceCanReboot(void) +{ + return 1; +} + +int HotaHalGetMetaData(UpdateMetaData *metaData) +{ + return OHOS_SUCCESS; +} + +int HotaHalSetMetaData(UpdateMetaData *metaData) +{ + return OHOS_SUCCESS; +} + +int HotaHalRebootAndCleanUserData(void) +{ + return OHOS_SUCCESS; +} + +int HotaHalRebootAndCleanCache(void) +{ + return OHOS_SUCCESS; +} diff --git a/hi3861_adapter/hals/utils/file/BUILD.gn b/hi3861_adapter/hals/utils/file/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..1e5743e6757e20cb03a7cfedc5670e70c72d909d --- /dev/null +++ b/hi3861_adapter/hals/utils/file/BUILD.gn @@ -0,0 +1,22 @@ +# Copyright (c) 2021 Itcast Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/lite/config/component/lite_component.gni") + +static_library("hal_file_static") { + sources = [ "src/hal_file.c" ] + include_dirs = [ + "//utils/native/lite/hals/file", + "//device/itcast/genkipi/sdk_liteos/include", + ] +} diff --git a/hi3861_adapter/hals/utils/file/src/hal_file.c b/hi3861_adapter/hals/utils/file/src/hal_file.c new file mode 100755 index 0000000000000000000000000000000000000000..eb23282f5d6921107bba747033c3137b9b77a43f --- /dev/null +++ b/hi3861_adapter/hals/utils/file/src/hal_file.c @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2020 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "hal_file.h" +#include "hi_fs.h" + +int HalFileOpen(const char* path, int oflag, int mode) +{ + (void)mode; + return hi_open(path, oflag); +} + +int HalFileClose(int fd) +{ + return hi_close(fd); +} + +int HalFileRead(int fd, char *buf, unsigned int len) +{ + return hi_read(fd, buf, len); +} + +int HalFileWrite(int fd, const char *buf, unsigned int len) +{ + return hi_write(fd, buf, len); +} + +int HalFileDelete(const char *path) +{ + return hi_unlink(path); +} + +int HalFileStat(const char *path, unsigned int *fileSize) +{ + return hi_stat(path, fileSize); +} + +int HalFileSeek(int fd, int offset, unsigned int whence) +{ + return hi_lseek(fd, offset, whence); +} diff --git a/hi3861_adapter/kal/BUILD.gn b/hi3861_adapter/kal/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..883dbd528c11ce8febcfc8982adc5c417059ee4c --- /dev/null +++ b/hi3861_adapter/kal/BUILD.gn @@ -0,0 +1,37 @@ +# Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved. +# Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, +# are permitted provided that the following conditions are met: +# +# 1. Redistributions of source code must retain the above copyright notice, this list of +# conditions and the following disclaimer. +# +# 2. Redistributions in binary form must reproduce the above copyright notice, this list +# of conditions and the following disclaimer in the documentation and/or other materials +# provided with the distribution. +# +# 3. Neither the name of the copyright holder nor the names of its contributors may be used +# to endorse or promote products derived from this software without specific prior written +# permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, +# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; +# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR +# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF +# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +import("//build/lite/config/component/lite_component.gni") + +lite_component("kal") { + features = [ + "posix", + "cmsis", + ] +} diff --git a/hi3861_adapter/kal/cmsis/BUILD.gn b/hi3861_adapter/kal/cmsis/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..d71e564fea328fa8d38abc966c81cb2b52e50671 --- /dev/null +++ b/hi3861_adapter/kal/cmsis/BUILD.gn @@ -0,0 +1,43 @@ +# Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved. +# Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, +# are permitted provided that the following conditions are met: +# +# 1. Redistributions of source code must retain the above copyright notice, this list of +# conditions and the following disclaimer. +# +# 2. Redistributions in binary form must reproduce the above copyright notice, this list +# of conditions and the following disclaimer in the documentation and/or other materials +# provided with the distribution. +# +# 3. Neither the name of the copyright holder nor the names of its contributors may be used +# to endorse or promote products derived from this software without specific prior written +# permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, +# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; +# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR +# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF +# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +import("//build/lite/config/component/lite_component.gni") + +static_library("cmsis") { + sources = [ "cmsis_liteos.c" ] + + include_dirs = [ + "//device/itcast/genkipi/hi3861_adapter/kal/cmsis", + "//third_party/bounds_checking_function/include", + ] + + defines = [ "LITEOS_WIFI_IOT_VERSION" ] + + cflags = [ "-Wno-error" ] +} diff --git a/hi3861_adapter/kal/cmsis/LICENSE.txt b/hi3861_adapter/kal/cmsis/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..8dada3edaf50dbc082c9a125058f25def75e625a --- /dev/null +++ b/hi3861_adapter/kal/cmsis/LICENSE.txt @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/hi3861_adapter/kal/cmsis/README.OpenSource b/hi3861_adapter/kal/cmsis/README.OpenSource new file mode 100644 index 0000000000000000000000000000000000000000..cc522613d1c88775821e7297975e4221cf4f5f21 --- /dev/null +++ b/hi3861_adapter/kal/cmsis/README.OpenSource @@ -0,0 +1,10 @@ +[ + { + "Name" : "CMSIS", + "License" : "Apache License V2.0", + "License File" : "LICENSE.txt", + "Version Number" : "5.7.0", + "Upstream URL" : "http://www.arm.com/zh/products/processors/cortex-m/cortex-microcontroller-software-interface-standard.php", + "Description" : "The Cortex Microcontroller Software Interface Standard (CMSIS) is a vendor-independent hardware abstraction layer for microcontrollers that are based on Arm® Cortex® processors" + } +] diff --git a/hi3861_adapter/kal/cmsis/cmsis_liteos.c b/hi3861_adapter/kal/cmsis/cmsis_liteos.c new file mode 100755 index 0000000000000000000000000000000000000000..641cd694655298412fd23171471a1d69ebd5b490 --- /dev/null +++ b/hi3861_adapter/kal/cmsis/cmsis_liteos.c @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "los_config.h" + +#if (CMSIS_OS_VER == 1) +#error "cmsis version 1.0 is not supported now!" +#elif (CMSIS_OS_VER == 2) +#include "cmsis_liteos2.c" +#endif diff --git a/hi3861_adapter/kal/cmsis/cmsis_liteos2.c b/hi3861_adapter/kal/cmsis/cmsis_liteos2.c new file mode 100755 index 0000000000000000000000000000000000000000..c9b7e17c7e733a66e0666fe4de6b11b89e8c130b --- /dev/null +++ b/hi3861_adapter/kal/cmsis/cmsis_liteos2.c @@ -0,0 +1,1386 @@ +/* + * Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "cmsis_os.h" +#include "los_typedef.h" +#include "los_printf.h" + +#include "los_event.h" +#include "los_membox.h" +#include "los_memory.h" +#include "los_hwi.h" + +#include "los_mux_pri.h" +#include "los_queue_pri.h" +#include "los_sem_pri.h" +#include "los_swtmr_pri.h" +#include "los_sys_pri.h" +#include "los_task_pri.h" +#include "los_tick_pri.h" +#include "string.h" +#include "securec.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif /* __cplusplus */ +#endif /* __cplusplus */ +#if (CMSIS_OS_VER == 2) + +/* Kernel initialization state */ +static osKernelState_t g_kernelState; + +extern BOOL g_taskScheduled; + +#define LOS_PRIORITY_WIN 8 + +const osVersion_t g_stLosVersion = { 001, 001 }; + +#define LITEOS_VERSION_MAJOR 1 +#define LITEOS_VERSION_MINOR 0 +#define LITEOS_VERSION_BUILD 0 + +/* Kernel version and identification string definition */ +#define KERNEL_VERSION (((UINT32)LITEOS_VERSION_MAJOR * 10000000UL) | \ + ((UINT32)LITEOS_VERSION_MINOR * 10000UL) | \ + ((UINT32)LITEOS_VERSION_BUILD * 1UL)) + +#define KERNEL_ID "HUAWEI-LiteOS" +#define UNUSED(var) do { (void)var; } while (0) + +// ==== Kernel Management Functions ==== +uint32_t osTaskStackWaterMarkGet(UINT32 taskID); + + +osStatus_t osKernelInitialize(void) +{ + if (OS_INT_ACTIVE) { + return osErrorISR; + } + + if (g_kernelState != osKernelInactive) { + return osError; + } + + if (LOS_OK == LOS_KernelInit()) { + g_kernelState = osKernelReady; + return osOK; + } else { + return osError; + } +} + + +osStatus_t osKernelGetInfo(osVersion_t *version, char *id_buf, uint32_t id_size) +{ + uint32_t uwRet; + + if (OS_INT_ACTIVE) { + return osErrorISR; + } + + if (version != NULL) { + version->api = g_stLosVersion.api; + version->kernel = g_stLosVersion.kernel; + } + + if ((id_buf != NULL) && (id_size != 0U)) { + if (id_size > sizeof(KERNEL_ID)) { + id_size = sizeof(KERNEL_ID); + } + uwRet = memcpy_s(id_buf, id_size, KERNEL_ID, id_size); + if (uwRet != EOK) { + PRINT_ERR("%s[%d] memcpy failed, error type = %u\n", __FUNCTION__, __LINE__, uwRet); + return osError; + } + } + + return osOK; +} + + +osKernelState_t osKernelGetState(void) +{ + if (OS_INT_ACTIVE) { + return osKernelError; + } + + if (!g_taskScheduled) { + if (g_kernelState == osKernelReady) { + return osKernelReady; + } else { + return osKernelInactive; + } + } else if (g_losTaskLock > 0) { + return osKernelLocked; + } else { + return osKernelRunning; + } +} + + +osStatus_t osKernelStart(void) +{ + if (OS_INT_ACTIVE) { + return osErrorISR; + } + + if (g_kernelState == osKernelReady) { + if (LOS_OK == LOS_Start()) { + g_kernelState = osKernelRunning; + return osOK; + } else { + return osError; + } + } else { + return osError; + } +} + + +int32_t osKernelLock(void) +{ + int32_t lock; + + if (OS_INT_ACTIVE) { + return (int32_t)osErrorISR; + } + + if (!g_taskScheduled) { + return (int32_t)osError; + } + + if (g_losTaskLock > 0) { + lock = 1; + } else { + LOS_TaskLock(); + lock = 0; + } + + return lock; +} + + +int32_t osKernelUnlock(void) +{ + int32_t lock; + + if (OS_INT_ACTIVE) { + return (int32_t)osErrorISR; + } + + if (!g_taskScheduled) { + return (int32_t)osError; + } + + if (g_losTaskLock > 0) { + LOS_TaskUnlock(); + if (g_losTaskLock != 0) { + return (int32_t)osError; + } + lock = 1; + } else { + lock = 0; + } + + return lock; +} + + +int32_t osKernelRestoreLock(int32_t lock) +{ + if (OS_INT_ACTIVE) { + return (int32_t)osErrorISR; + } + + if (!g_taskScheduled) { + return (int32_t)osError; + } + + switch (lock) { + case 0: + LOS_TaskUnlock(); + if (g_losTaskLock != 0) { + break; + } + return 0; + case 1: + LOS_TaskLock(); + return 1; + default: + break; + } + + return (int32_t)osError; +} + + +uint32_t osKernelGetTickCount(void) +{ + uint64_t ticks; + UINTPTR uvIntSave; + + if (OS_INT_ACTIVE) { +#ifndef LITEOS_WIFI_IOT_VERSION + ticks = g_ullTickCount; +#else + ticks = g_tickCount; +#endif + } else { + uvIntSave = LOS_IntLock(); +#ifndef LITEOS_WIFI_IOT_VERSION + ticks = g_ullTickCount; +#else + ticks = g_tickCount; +#endif + LOS_IntRestore(uvIntSave); + } + + return (uint32_t)ticks; +} + +uint32_t osKernelGetTickFreq(void) +{ + uint32_t freq; + + if (OS_INT_ACTIVE) { + freq = 0U; + } else { + freq = LOSCFG_BASE_CORE_TICK_PER_SECOND; + } + + return (freq); +} + +extern VOID LOS_GetCpuCycle(UINT32 *puwCntHi, UINT32 *puwCntLo); +uint32_t osKernelGetSysTimerCount(void) +{ + uint32_t countHigh = 0; + uint32_t countLow = 0; + if (OS_INT_ACTIVE) { + countLow = 0U; + } else { + LOS_GetCpuCycle((UINT32 *)&countHigh, (UINT32 *)&countLow); + } + return countLow; +} + + +uint32_t osKernelGetSysTimerFreq(void) +{ + return OS_SYS_CLOCK; +} + + +// ==== Thread Management Functions ==== + +osThreadId_t osThreadNew(osThreadFunc_t func, void *argument, const osThreadAttr_t *attr) +{ + UINT32 uwTid; + UINT32 uwRet; + LosTaskCB *pstTaskCB = NULL; + TSK_INIT_PARAM_S stTskInitParam; + + if (OS_INT_ACTIVE) { + return NULL; + } + + if ((attr == NULL) || (func == NULL) || (attr->priority < osPriorityLow1) || + (attr->priority > osPriorityAboveNormal6)) { + return (osThreadId_t)NULL; + } + + (void)memset_s(&stTskInitParam, sizeof(TSK_INIT_PARAM_S), 0, sizeof(TSK_INIT_PARAM_S)); + stTskInitParam.pfnTaskEntry = (TSK_ENTRY_FUNC)func; +#ifndef LITEOS_WIFI_IOT_VERSION + stTskInitParam.uwArg = (UINT32)argument; +#else + stTskInitParam.auwArgs[0] = (UINT32)argument; +#endif + stTskInitParam.uwStackSize = attr->stack_size; + stTskInitParam.pcName = (CHAR *)attr->name; + stTskInitParam.usTaskPrio = OS_TASK_PRIORITY_LOWEST - ((UINT16)(attr->priority) - LOS_PRIORITY_WIN); /* 0~31 */ + + uwRet = LOS_TaskCreate(&uwTid, &stTskInitParam); + + if (LOS_OK != uwRet) { + return (osThreadId_t)NULL; + } + + pstTaskCB = OS_TCB_FROM_TID(uwTid); + + return (osThreadId_t)pstTaskCB; +} + + +const char *osThreadGetName(osThreadId_t thread_id) +{ + LosTaskCB *pstTaskCB = NULL; + + if (OS_INT_ACTIVE || thread_id == NULL) { + return NULL; + } + + pstTaskCB = (LosTaskCB *)thread_id; + + return pstTaskCB->taskName; +} + + +osThreadId_t osThreadGetId(void) +{ + if (OS_INT_ACTIVE) { + return NULL; + } + + return (osThreadId_t)(g_losTask.runTask); +} + +void *osThreadGetArgument(void) +{ + if (OS_INT_ACTIVE) { + return 0; + } + + LosTaskCB *taskCb = (LosTaskCB *)osThreadGetId(); + if (taskCb == NULL) { + return NULL; + } +#ifndef LITEOS_WIFI_IOT_VERSION + return (void *)(taskCb->arg); +#else + return (void *)(taskCb->args[0]); +#endif +} + +osThreadState_t osThreadGetState(osThreadId_t thread_id) +{ + UINT16 taskStatus; + osThreadState_t stState; + LosTaskCB *pstTaskCB = NULL; + + if (OS_INT_ACTIVE || thread_id == NULL) { + return osThreadError; + } + + pstTaskCB = (LosTaskCB *)thread_id; + taskStatus = pstTaskCB->taskStatus; + + if (taskStatus & OS_TASK_STATUS_RUNNING) { + stState = osThreadRunning; + } else if (taskStatus & OS_TASK_STATUS_READY) { + stState = osThreadReady; + } else if (taskStatus & + (OS_TASK_STATUS_DELAY | OS_TASK_STATUS_PEND | OS_TASK_STATUS_SUSPEND | OS_TASK_STATUS_PEND_QUEUE)) { + stState = osThreadBlocked; + } else if (taskStatus & OS_TASK_STATUS_UNUSED) { + stState = osThreadInactive; + } else { + stState = osThreadError; + } + + return stState; +} + + +uint32_t osThreadGetStackSize(osThreadId_t thread_id) +{ + LosTaskCB *pstTaskCB = NULL; + + if (OS_INT_ACTIVE || thread_id == NULL) { + return 0U; + } + + pstTaskCB = (LosTaskCB *)thread_id; + + return pstTaskCB->stackSize; +} + + +uint32_t osTaskStackWaterMarkGet(UINT32 taskID) +{ + UINT32 uwCount = 0; + UINT32 *ptopOfStack; + UINTPTR uvIntSave; + LosTaskCB *pstTaskCB = NULL; + + if (taskID > LOSCFG_BASE_CORE_TSK_LIMIT) { + return 0; + } + + uvIntSave = LOS_IntLock(); + + pstTaskCB = OS_TCB_FROM_TID(taskID); + if (OS_TASK_STATUS_UNUSED & (pstTaskCB->taskStatus)) { + LOS_IntRestore(uvIntSave); + return 0; + } + + // first 4 bytes is OS_TASK_MAGIC_WORD, skip + ptopOfStack = (UINT32 *)(UINTPTR)pstTaskCB->topOfStack + 1; + + while (*ptopOfStack == (UINT32)OS_TASK_STACK_INIT) { + ++ptopOfStack; + ++uwCount; + } + + uwCount *= sizeof(UINT32); + + LOS_IntRestore(uvIntSave); + return uwCount; +} + + +uint32_t osThreadGetStackSpace(osThreadId_t thread_id) +{ + LosTaskCB *pstTaskCB = NULL; + + if (OS_INT_ACTIVE || thread_id == NULL) { + return 0U; + } + + pstTaskCB = (LosTaskCB *)thread_id; + + return osTaskStackWaterMarkGet(pstTaskCB->taskID); +} + + +osStatus_t osThreadSetPriority(osThreadId_t thread_id, osPriority_t priority) +{ + UINT32 uwRet; + UINT16 usPriority; + LosTaskCB *pstTaskCB = NULL; + + if (OS_INT_ACTIVE) { + return osErrorISR; + } + + if (thread_id == NULL) { + return osErrorParameter; + } + + if (priority < osPriorityLow1 || priority > osPriorityAboveNormal6) { + return osErrorParameter; + } + + pstTaskCB = (LosTaskCB *)thread_id; + usPriority = OS_TASK_PRIORITY_LOWEST - ((UINT16)priority - LOS_PRIORITY_WIN); + uwRet = LOS_TaskPriSet(pstTaskCB->taskID, usPriority); + switch (uwRet) { + case LOS_ERRNO_TSK_PRIOR_ERROR: + case LOS_ERRNO_TSK_OPERATE_IDLE: + case LOS_ERRNO_TSK_ID_INVALID: + return osErrorParameter; + + case LOS_ERRNO_TSK_NOT_CREATED: + return osErrorResource; + + default: + return osOK; + } +} + + +osPriority_t osThreadGetPriority(osThreadId_t thread_id) +{ + UINT16 usRet; + LosTaskCB *pstTaskCB = NULL; + + if (OS_INT_ACTIVE || thread_id == NULL) { + return osPriorityError; + } + + pstTaskCB = (LosTaskCB *)thread_id; + usRet = LOS_TaskPriGet(pstTaskCB->taskID); + + if (usRet == (UINT16)OS_INVALID) { + return osPriorityError; + } + + return (osPriority_t)(OS_TASK_PRIORITY_LOWEST - (usRet - LOS_PRIORITY_WIN)); +} + + +osStatus_t osThreadYield(void) +{ + UINT32 uwRet; + + if (OS_INT_ACTIVE) { + return osErrorISR; + } + + uwRet = LOS_TaskYield(); + + if (uwRet == LOS_OK) { + return osOK; + } + + return osError; +} + + +osStatus_t osThreadSuspend(osThreadId_t thread_id) +{ + UINT32 uwRet; + LosTaskCB *pstTaskCB = NULL; + + if (OS_INT_ACTIVE) { + return osErrorISR; + } + + if (thread_id == NULL) { + return osErrorParameter; + } + + pstTaskCB = (LosTaskCB *)thread_id; + uwRet = LOS_TaskSuspend(pstTaskCB->taskID); + switch (uwRet) { + case LOS_ERRNO_TSK_OPERATE_IDLE: + case LOS_ERRNO_TSK_SUSPEND_SWTMR_NOT_ALLOWED: + case LOS_ERRNO_TSK_ID_INVALID: + return osErrorParameter; + + case LOS_ERRNO_TSK_NOT_CREATED: + case LOS_ERRNO_TSK_ALREADY_SUSPENDED: + case LOS_ERRNO_TSK_SUSPEND_LOCKED: + return osErrorResource; + + default: + return osOK; + } +} + + +osStatus_t osThreadResume(osThreadId_t thread_id) +{ + UINT32 uwRet; + LosTaskCB *pstTaskCB = NULL; + + if (OS_INT_ACTIVE) { + return osErrorISR; + } + + if (thread_id == NULL) { + return osErrorParameter; + } + + pstTaskCB = (LosTaskCB *)thread_id; + uwRet = LOS_TaskResume(pstTaskCB->taskID); + + switch (uwRet) { + case LOS_ERRNO_TSK_ID_INVALID: + return osErrorParameter; + + case LOS_ERRNO_TSK_NOT_CREATED: + case LOS_ERRNO_TSK_NOT_SUSPENDED: + return osErrorResource; + + default: + return osOK; + } +} + + +osStatus_t osThreadTerminate(osThreadId_t thread_id) +{ + UINT32 uwRet; + LosTaskCB *pstTaskCB = NULL; + + if (OS_INT_ACTIVE) { + return osErrorISR; + } + + if (thread_id == NULL) { + return osErrorParameter; + } + + pstTaskCB = (LosTaskCB *)thread_id; + uwRet = LOS_TaskDelete(pstTaskCB->taskID); + + switch (uwRet) { + case LOS_ERRNO_TSK_OPERATE_IDLE: + case LOS_ERRNO_TSK_SUSPEND_SWTMR_NOT_ALLOWED: + case LOS_ERRNO_TSK_ID_INVALID: + return osErrorParameter; + + case LOS_ERRNO_TSK_NOT_CREATED: + return osErrorResource; + + default: + return osOK; + } +} + + +uint32_t osThreadGetCount(void) +{ + uint32_t uwCount = 0; + + if (OS_INT_ACTIVE) { + return 0U; + } + + for (uint32_t index = 0; index <= LOSCFG_BASE_CORE_TSK_LIMIT; index++) { + if (!((g_taskCBArray + index)->taskStatus & OS_TASK_STATUS_UNUSED)) { + uwCount++; + } + } + + return uwCount; +} + + +// ==== Generic Wait Functions ==== +WEAK UINT32 LOS_HalDelay(UINT32 ticks) +{ + UNUSED(ticks); + return LOS_ERRNO_TSK_DELAY_IN_INT; +} + + +osStatus_t osDelay(uint32_t ticks) +{ + UINT32 uwRet; + if (ticks == 0) { + return osOK; + } + if (osKernelGetState() != osKernelRunning) { + uwRet = LOS_HalDelay(ticks); + } else { + uwRet = LOS_TaskDelay(ticks); + } + if (uwRet == LOS_OK) { + return osOK; + } else { + return osError; + } +} + + +osStatus_t osDelayUntil(uint32_t ticks) +{ + UINT32 uwRet; + UINT32 uwTicks; + UINT32 tickCount = osKernelGetTickCount(); + + if (ticks < tickCount) { + return osError; + } + + uwTicks = (UINT32)(ticks - tickCount); + + uwRet = LOS_TaskDelay(uwTicks); + if (uwRet == LOS_OK) { + return osOK; + } else { + return osError; + } +} + +// ==== Timer Management Functions ==== +#if (LOSCFG_BASE_CORE_SWTMR == 1) +osTimerId_t osTimerNew(osTimerFunc_t func, osTimerType_t type, void *argument, const osTimerAttr_t *attr) +{ + UNUSED(attr); + UINT16 usSwTmrID; + UINT8 mode; + + if ((OS_INT_ACTIVE) || (NULL == func) || ((osTimerOnce != type) && (osTimerPeriodic != type))) { + return (osTimerId_t)NULL; + } + + if (osTimerOnce == type) { + mode = LOS_SWTMR_MODE_NO_SELFDELETE; + } else { + mode = LOS_SWTMR_MODE_PERIOD; + } +#if (LOSCFG_BASE_CORE_SWTMR_ALIGN == 1) + if (LOS_OK != LOS_SwtmrCreate(1, mode, (SWTMR_PROC_FUNC)func, &usSwTmrID, (UINT32)(UINTPTR)argument, + osTimerRousesAllow, osTimerAlignIgnore)) { + return (osTimerId_t)NULL; + } +#else + if (LOS_OK != LOS_SwtmrCreate(1, mode, (SWTMR_PROC_FUNC)func, &usSwTmrID, (UINT32)(UINTPTR)argument)) { + return (osTimerId_t)NULL; + } +#endif + + return (osTimerId_t)OS_SWT_FROM_SID(usSwTmrID); +} + +osStatus_t osTimerStart(osTimerId_t timer_id, uint32_t ticks) +{ + UINT32 uwRet; + SWTMR_CTRL_S *pstSwtmr; + + if ((0 == ticks) || (NULL == timer_id)) { + return osErrorParameter; + } + + pstSwtmr = (SWTMR_CTRL_S *)timer_id; + pstSwtmr->uwInterval = ticks; + uwRet = LOS_SwtmrStart(pstSwtmr->usTimerID); + if (LOS_OK == uwRet) { + return osOK; + } else if (LOS_ERRNO_SWTMR_ID_INVALID == uwRet) { + return osErrorParameter; + } else { + return osErrorResource; + } +} + + +const char *osTimerGetName(osTimerId_t timer_id) +{ + UNUSED(timer_id); + return (const char *)NULL; +} + + +osStatus_t osTimerStop(osTimerId_t timer_id) +{ + UINT32 uwRet; + SWTMR_CTRL_S *pstSwtmr = (SWTMR_CTRL_S *)timer_id; + + if (OS_INT_ACTIVE) { + return osErrorISR; + } + + if (NULL == pstSwtmr) { + return osErrorParameter; + } + + uwRet = LOS_SwtmrStop(pstSwtmr->usTimerID); + if (LOS_OK == uwRet) { + return osOK; + } else if (LOS_ERRNO_SWTMR_ID_INVALID == uwRet) { + return osErrorParameter; + } else { + return osErrorResource; + } +} + + +uint32_t osTimerIsRunning(osTimerId_t timer_id) +{ + if ((OS_INT_ACTIVE) || (NULL == timer_id)) { + return 0; + } + + return (OS_SWTMR_STATUS_TICKING == ((SWTMR_CTRL_S *)timer_id)->ucState); +} + + +osStatus_t osTimerDelete(osTimerId_t timer_id) +{ + UINT32 uwRet; + SWTMR_CTRL_S *pstSwtmr = (SWTMR_CTRL_S *)timer_id; + + if (OS_INT_ACTIVE) { + return osErrorISR; + } + + if (NULL == pstSwtmr) { + return osErrorParameter; + } + + uwRet = LOS_SwtmrDelete(pstSwtmr->usTimerID); + if (LOS_OK == uwRet) { + return osOK; + } else if (LOS_ERRNO_SWTMR_ID_INVALID == uwRet) { + return osErrorParameter; + } else { + return osErrorResource; + } +} +#endif + +osEventFlagsId_t osEventFlagsNew(const osEventFlagsAttr_t *attr) +{ + PEVENT_CB_S pstEventCB; + UINT32 uwRet; + + UNUSED(attr); + + if (OS_INT_ACTIVE) { + return (osEventFlagsId_t)NULL; + } + + pstEventCB = (PEVENT_CB_S)LOS_MemAlloc(m_aucSysMem0, sizeof(EVENT_CB_S)); + if (pstEventCB == NULL) { + return (osEventFlagsId_t)NULL; + } + + uwRet = LOS_EventInit(pstEventCB); + if (uwRet == LOS_ERRNO_EVENT_PTR_NULL) { + return (osEventFlagsId_t)NULL; + } else { + return (osEventFlagsId_t)pstEventCB; + } +} + + +const char *osEventFlagsGetName(osEventFlagsId_t ef_id) +{ + UNUSED(ef_id); + + if (OS_INT_ACTIVE) { + return (const char *)NULL; + } + + return (const char *)NULL; +} + + +uint32_t osEventFlagsSet(osEventFlagsId_t ef_id, uint32_t flags) +{ + PEVENT_CB_S pstEventCB = (PEVENT_CB_S)ef_id; + UINT32 uwRet; + uint32_t rflags; + if (pstEventCB == NULL) { + return osFlagsErrorParameter; + } + uwRet = LOS_EventWrite(pstEventCB, (UINT32)flags); + if (uwRet != LOS_OK) { + return (uint32_t)osFlagsErrorParameter; + } else { + rflags = pstEventCB->uwEventID; + return rflags; + } +} + + +uint32_t osEventFlagsClear(osEventFlagsId_t ef_id, uint32_t flags) +{ + PEVENT_CB_S pstEventCB = (PEVENT_CB_S)ef_id; + UINTPTR uwIntSave; + uint32_t rflags; + UINT32 uwRet; + + if (pstEventCB == NULL) { + return (uint32_t)osFlagsErrorParameter; + } + + uwIntSave = LOS_IntLock(); + rflags = pstEventCB->uwEventID; + + uwRet = LOS_EventClear(pstEventCB, ~flags); + LOS_IntRestore(uwIntSave); + if (uwRet != LOS_OK) { + return (uint32_t)osFlagsErrorParameter; + } else { + return rflags; + } +} + + +uint32_t osEventFlagsGet(osEventFlagsId_t ef_id) +{ + PEVENT_CB_S pstEventCB = (PEVENT_CB_S)ef_id; + UINTPTR uwIntSave; + uint32_t rflags; + + if (pstEventCB == NULL) { + return (uint32_t)osFlagsErrorParameter; + } + + uwIntSave = LOS_IntLock(); + rflags = pstEventCB->uwEventID; + LOS_IntRestore(uwIntSave); + + return rflags; +} + +uint32_t osEventFlagsWait(osEventFlagsId_t ef_id, uint32_t flags, uint32_t options, uint32_t timeout) +{ + PEVENT_CB_S pstEventCB = (PEVENT_CB_S)ef_id; + UINT32 uwMode = 0; + UINT32 uwRet; + uint32_t rflags; + + if (options > (osFlagsWaitAny | osFlagsWaitAll | osFlagsNoClear)) { + return (uint32_t)osFlagsErrorParameter; + } + + if ((options & osFlagsWaitAll) == osFlagsWaitAll) { + uwMode |= LOS_WAITMODE_AND; + } else { + uwMode |= LOS_WAITMODE_OR; + } + + if ((options & osFlagsNoClear) == osFlagsNoClear) { + uwMode &= ~LOS_WAITMODE_CLR; + } else { + uwMode |= LOS_WAITMODE_CLR; + } + + uwRet = LOS_EventRead(pstEventCB, (UINT32)flags, uwMode, (UINT32)timeout); + switch (uwRet) { + case LOS_ERRNO_EVENT_PTR_NULL: + case LOS_ERRNO_EVENT_EVENTMASK_INVALID: + case LOS_ERRNO_EVENT_SETBIT_INVALID: + return (uint32_t)osFlagsErrorParameter; + + case LOS_ERRNO_EVENT_READ_IN_INTERRUPT: + case LOS_ERRNO_EVENT_FLAGS_INVALID: + case LOS_ERRNO_EVENT_READ_IN_LOCK: + return (uint32_t)osFlagsErrorResource; + + case LOS_ERRNO_EVENT_READ_TIMEOUT: + return (uint32_t)osFlagsErrorTimeout; + + default: + rflags = (uint32_t)uwRet; + return rflags; + } +} + +osStatus_t osEventFlagsDelete(osEventFlagsId_t ef_id) +{ + PEVENT_CB_S pstEventCB = (PEVENT_CB_S)ef_id; + UINTPTR uwIntSave; + osStatus_t uwRet; + + uwIntSave = LOS_IntLock(); + if (LOS_EventDestroy(pstEventCB) == LOS_OK) { + uwRet = osOK; + } else { + uwRet = osErrorParameter; + } + LOS_IntRestore(uwIntSave); + + if (LOS_MemFree(m_aucSysMem0, (void *)pstEventCB) == LOS_OK) { + uwRet = osOK; + } else { + uwRet = osErrorParameter; + } + + return uwRet; +} + +// ==== Mutex Management Functions ==== +#if (LOSCFG_BASE_IPC_MUX == 1) +osMutexId_t osMutexNew(const osMutexAttr_t *attr) +{ + UINT32 uwRet; + UINT32 uwMuxId; + + UNUSED(attr); + + if (OS_INT_ACTIVE) { + return NULL; + } + + uwRet = LOS_MuxCreate(&uwMuxId); + if (uwRet == LOS_OK) { + return (osMutexId_t)(GET_MUX(uwMuxId)); + } else { + return (osMutexId_t)NULL; + } +} + + +osStatus_t osMutexAcquire(osMutexId_t mutex_id, uint32_t timeout) +{ + UINT32 uwRet; + + if (mutex_id == NULL) { + return osErrorParameter; + } + + if (OS_INT_ACTIVE && (timeout != LOS_NO_WAIT)) { + timeout = 0; + } + + uwRet = LOS_MuxPend(((LosMuxCB *)mutex_id)->muxID, timeout); + if (uwRet == LOS_OK) { + return osOK; + } else if (uwRet == LOS_ERRNO_MUX_TIMEOUT) { + return osErrorTimeout; + } else if (uwRet == LOS_ERRNO_MUX_INVALID) { + return osErrorParameter; + } else { + return osErrorResource; + } +} + + +osStatus_t osMutexRelease(osMutexId_t mutex_id) +{ + UINT32 uwRet; + + if (mutex_id == NULL) { + return osErrorParameter; + } + + uwRet = LOS_MuxPost(((LosMuxCB *)mutex_id)->muxID); + if (uwRet == LOS_OK) { + return osOK; + } else { + return osErrorResource; + } +} + + +osThreadId_t osMutexGetOwner(osMutexId_t mutex_id) +{ + UINT32 uwIntSave; + LosTaskCB *pstTaskCB; + + if (OS_INT_ACTIVE) { + return NULL; + } + + if (mutex_id == NULL) { + return NULL; + } + + uwIntSave = LOS_IntLock(); + pstTaskCB = ((LosMuxCB *)mutex_id)->owner; + LOS_IntRestore(uwIntSave); + + return (osThreadId_t)pstTaskCB; +} + + +osStatus_t osMutexDelete(osMutexId_t mutex_id) +{ + UINT32 uwRet; + + if (OS_INT_ACTIVE) { + return osErrorISR; + } + + if (mutex_id == NULL) { + return osErrorParameter; + } + + uwRet = LOS_MuxDelete(((LosMuxCB *)mutex_id)->muxID); + if (uwRet == LOS_OK) { + return osOK; + } else if (uwRet == LOS_ERRNO_MUX_INVALID) { + return osErrorParameter; + } else { + return osErrorResource; + } +} +#endif + +// ==== Semaphore Management Functions ==== +#if (LOSCFG_BASE_IPC_SEM == 1) + +osSemaphoreId_t osSemaphoreNew(uint32_t max_count, uint32_t initial_count, const osSemaphoreAttr_t *attr) +{ + UINT32 uwRet; + UINT32 uwSemId; + + UNUSED(attr); + + if (OS_INT_ACTIVE) { + return (osSemaphoreId_t)NULL; + } + + if (1 == max_count) { + uwRet = LOS_BinarySemCreate((UINT16)initial_count, &uwSemId); + } else { + uwRet = LOS_SemCreate((UINT16)initial_count, &uwSemId); + } + + if (uwRet == LOS_OK) { + return (osSemaphoreId_t)(GET_SEM(uwSemId)); + } else { + return (osSemaphoreId_t)NULL; + } +} + + +osStatus_t osSemaphoreAcquire(osSemaphoreId_t semaphore_id, uint32_t timeout) +{ + UINT32 uwRet; + + if (semaphore_id == NULL) { + return osErrorParameter; + } + + if (OS_INT_ACTIVE && (timeout != LOS_NO_WAIT)) { + return osErrorISR; + } + + uwRet = LOS_SemPend(((LosSemCB *)semaphore_id)->semID, timeout); + if (uwRet == LOS_OK) { + return osOK; + } else if (uwRet == LOS_ERRNO_SEM_TIMEOUT) { + return osErrorTimeout; + } else if (uwRet == LOS_ERRNO_SEM_INVALID) { + return osErrorParameter; + } else if (uwRet == LOS_ERRNO_SEM_PEND_INTERR) { + return osErrorISR; + } else { + return osErrorResource; + } +} + + +osStatus_t osSemaphoreRelease(osSemaphoreId_t semaphore_id) +{ + UINT32 uwRet; + + if (semaphore_id == NULL) { + return osErrorParameter; + } + + uwRet = LOS_SemPost(((LosSemCB *)semaphore_id)->semID); + if (uwRet == LOS_OK) { + return osOK; + } else if (uwRet == LOS_ERRNO_SEM_INVALID) { + return osErrorParameter; + } else { + return osErrorResource; + } +} + + +uint32_t osSemaphoreGetCount(osSemaphoreId_t semaphore_id) +{ + UINT32 uwIntSave; + UINT32 uwCount; + + if (OS_INT_ACTIVE) { + return 0; + } + + if (semaphore_id == NULL) { + return 0; + } + + uwIntSave = LOS_IntLock(); + uwCount = ((LosSemCB *)semaphore_id)->semCount; + LOS_IntRestore(uwIntSave); + + return uwCount; +} + + +osStatus_t osSemaphoreDelete(osSemaphoreId_t semaphore_id) +{ + UINT32 uwRet; + + if (OS_INT_ACTIVE) { + return osErrorISR; + } + + if (semaphore_id == NULL) { + return osErrorParameter; + } + + uwRet = LOS_SemDelete(((LosSemCB *)semaphore_id)->semID); + if (uwRet == LOS_OK) { + return osOK; + } else if (uwRet == LOS_ERRNO_SEM_INVALID) { + return osErrorParameter; + } else { + return osErrorResource; + } +} +#endif + + +// ==== Message Queue Management Functions ==== +#if (LOSCFG_BASE_IPC_QUEUE == 1) +osMessageQueueId_t osMessageQueueNew(uint32_t msg_count, uint32_t msg_size, const osMessageQueueAttr_t *attr) +{ + UINT32 uwQueueID; + UINT32 uwRet; + UNUSED(attr); + osMessageQueueId_t handle; + + if (0 == msg_count || 0 == msg_size || OS_INT_ACTIVE) { + return (osMessageQueueId_t)NULL; + } + + uwRet = LOS_QueueCreate((char *)NULL, (UINT16)msg_count, &uwQueueID, 0, (UINT16)msg_size); + if (uwRet == LOS_OK) { + handle = (osMessageQueueId_t)(GET_QUEUE_HANDLE(uwQueueID)); + } else { + handle = (osMessageQueueId_t)NULL; + } + + return handle; +} + + +osStatus_t osMessageQueuePut(osMessageQueueId_t mq_id, const void *msg_ptr, uint8_t msg_prio, uint32_t timeout) +{ + UNUSED(msg_prio); + UINT32 uwRet; + UINT32 uwBufferSize; + LosQueueCB *pstQueue = (LosQueueCB *)mq_id; + + if (pstQueue == NULL || msg_ptr == NULL || ((OS_INT_ACTIVE) && (0 != timeout))) { + return osErrorParameter; + } + if (pstQueue->queueSize < sizeof(UINT32)) { + return osErrorParameter; + } + uwBufferSize = (UINT32)(pstQueue->queueSize - sizeof(UINT32)); + uwRet = LOS_QueueWriteCopy((UINT32)pstQueue->queueID, (void *)msg_ptr, uwBufferSize, timeout); + if (uwRet == LOS_OK) { + return osOK; + } else if (uwRet == LOS_ERRNO_QUEUE_INVALID || uwRet == LOS_ERRNO_QUEUE_NOT_CREATE) { + return osErrorParameter; + } else if (uwRet == LOS_ERRNO_QUEUE_TIMEOUT) { + return osErrorTimeout; + } else { + return osErrorResource; + } +} + + +osStatus_t osMessageQueueGet(osMessageQueueId_t mq_id, void *msg_ptr, uint8_t *msg_prio, uint32_t timeout) +{ + UNUSED(msg_prio); + UINT32 uwRet; + UINT32 uwBufferSize; + LosQueueCB *pstQueue = (LosQueueCB *)mq_id; + + if (pstQueue == NULL || msg_ptr == NULL || ((OS_INT_ACTIVE) && (0 != timeout))) { + return osErrorParameter; + } + + uwBufferSize = (UINT32)(pstQueue->queueSize - sizeof(UINT32)); + uwRet = LOS_QueueReadCopy((UINT32)pstQueue->queueID, msg_ptr, &uwBufferSize, timeout); + if (uwRet == LOS_OK) { + return osOK; + } else if (uwRet == LOS_ERRNO_QUEUE_INVALID || uwRet == LOS_ERRNO_QUEUE_NOT_CREATE) { + return osErrorParameter; + } else if (uwRet == LOS_ERRNO_QUEUE_TIMEOUT) { + return osErrorTimeout; + } else { + return osErrorResource; + } +} + +uint32_t osMessageQueueGetCapacity(osMessageQueueId_t mq_id) +{ + uint32_t capacity; + LosQueueCB *pstQueue = (LosQueueCB *)mq_id; + + if (pstQueue == NULL) { + capacity = 0U; + } else { + capacity = pstQueue->queueLen; + } + + return (capacity); +} + +uint32_t osMessageQueueGetMsgSize(osMessageQueueId_t mq_id) +{ + uint32_t size; + LosQueueCB *pstQueue = (LosQueueCB *)mq_id; + + if (pstQueue == NULL) { + size = 0U; + } else { + size = pstQueue->queueSize - sizeof(UINT32); + } + + return (size); +} + + +uint32_t osMessageQueueGetCount(osMessageQueueId_t mq_id) +{ + uint32_t count; + UINTPTR uwIntSave; + LosQueueCB *pstQueue = (LosQueueCB *)mq_id; + + if (pstQueue == NULL) { + count = 0U; + } else { + uwIntSave = LOS_IntLock(); + count = (uint32_t)(pstQueue->readWriteableCnt[OS_QUEUE_READ]); + LOS_IntRestore(uwIntSave); + } + return count; +} + + +uint32_t osMessageQueueGetSpace(osMessageQueueId_t mq_id) +{ + uint32_t space; + UINTPTR uwIntSave; + LosQueueCB *pstQueue = (LosQueueCB *)mq_id; + + if (pstQueue == NULL) { + space = 0U; + } else { + uwIntSave = LOS_IntLock(); + space = (uint32_t)pstQueue->readWriteableCnt[OS_QUEUE_WRITE]; + LOS_IntRestore(uwIntSave); + } + return space; +} + +osStatus_t osMessageQueueDelete(osMessageQueueId_t mq_id) +{ + LosQueueCB *pstQueue = (LosQueueCB *)mq_id; + UINT32 uwRet; + + if (pstQueue == NULL) { + return osErrorParameter; + } + + if (OS_INT_ACTIVE) { + return osErrorISR; + } + + uwRet = LOS_QueueDelete((UINT32)pstQueue->queueID); + if (uwRet == LOS_OK) { + return osOK; + } else if (uwRet == LOS_ERRNO_QUEUE_NOT_FOUND || uwRet == LOS_ERRNO_QUEUE_NOT_CREATE) { + return osErrorParameter; + } else { + return osErrorResource; + } +} +void osThreadExit(void) +{ + return; +} +#endif + +#endif // (CMSIS_OS_VER == 2) +#ifdef __cplusplus +#if __cplusplus +} +#endif /* __cplusplus */ +#endif /* __cplusplus */ diff --git a/hi3861_adapter/kal/cmsis/cmsis_os.h b/hi3861_adapter/kal/cmsis/cmsis_os.h new file mode 100755 index 0000000000000000000000000000000000000000..bc288b2a34e4c7f9a4fbebcf4684c0d8026efd6d --- /dev/null +++ b/hi3861_adapter/kal/cmsis/cmsis_os.h @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef CMSIS_OS_H_ +#define CMSIS_OS_H_ + +#include "los_config.h" + +#if (CMSIS_OS_VER == 1) +#error "cmsis version 1.0 is not supported now!" +#elif (CMSIS_OS_VER == 2) +#include "cmsis_os2.h" +#endif + +#endif /* CMSIS_OS_H_ */ diff --git a/hi3861_adapter/kal/cmsis/cmsis_os2.h b/hi3861_adapter/kal/cmsis/cmsis_os2.h new file mode 100755 index 0000000000000000000000000000000000000000..394bbd28c590152aa8adfae8290892ec2902a506 --- /dev/null +++ b/hi3861_adapter/kal/cmsis/cmsis_os2.h @@ -0,0 +1,1215 @@ +/* + * Copyright (c) 2013-2018 Arm Limited. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the License); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ---------------------------------------------------------------------- + * + * $Date: 18. June 2018 + * $Revision: V2.1.3 + * + * Project: CMSIS-RTOS2 API + * Title: cmsis_os2.h header file + * + * Version 2.1.3 + * Additional functions allowed to be called from Interrupt Service Routines: + * - osThreadGetId + * Version 2.1.2 + * Additional functions allowed to be called from Interrupt Service Routines: + * - osKernelGetInfo, osKernelGetState + * Version 2.1.1 + * Additional functions allowed to be called from Interrupt Service Routines: + * - osKernelGetTickCount, osKernelGetTickFreq + * Changed Kernel Tick type to uint32_t: + * - updated: osKernelGetTickCount, osDelayUntil + * Version 2.1.0 + * Support for critical and uncritical sections (nesting safe): + * - updated: osKernelLock, osKernelUnlock + * - added: osKernelRestoreLock + * Updated Thread and Event Flags: + * - changed flags parameter and return type from int32_t to uint32_t + * Version 2.0.0 + * Initial Release + *---------------------------------------------------------------------------*/ + +/** + * @addtogroup CMSIS + * @{ + * + * @brief Provides standard, universal real-time operating system (RTOS) APIs. + * + * CMSIS Module may contain portions from ARM Cortex Microcontroller Software Interface Standard (CMSIS) licensed under Apache License v2.0. + * + * @since 1.0 + * @version 1.0 + */ + +#ifndef CMSIS_OS2_H_ +#define CMSIS_OS2_H_ + +#ifndef __NO_RETURN +#if defined(__CC_ARM) +#define __NO_RETURN __declspec(noreturn) +#elif defined(__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050) +#define __NO_RETURN __attribute__((__noreturn__)) +#elif defined(__GNUC__) +#define __NO_RETURN __attribute__((__noreturn__)) +#elif defined(__ICCARM__) +#define __NO_RETURN __noreturn +#else +#define __NO_RETURN +#endif +#endif + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + + +// ==== Enumerations, structures, defines ==== + +/** +* @brief Describes the system version. +* +* @since 1.0 +* @version 1.0 +*/ +typedef struct { + /** API version */ + uint32_t api; + /** Kernel version */ + uint32_t kernel; +} osVersion_t; + +/** +* @brief Enumerates kernel states. +* +*/ +typedef enum { + /** The kernel is inactive. */ + osKernelInactive = 0, + /** The kernel is ready. */ + osKernelReady = 1, + /** The kernel is running. */ + osKernelRunning = 2, + /** The kernel is locked. */ + osKernelLocked = 3, + /** The kernel is suspended. */ + osKernelSuspended = 4, + /** The kernel is abnormal. */ + osKernelError = -1, + /** Reserved */ + osKernelReserved = 0x7FFFFFFFU +} osKernelState_t; + +/** +* @brief Enumerates thread states. +* +*/ +typedef enum { + /** The thread is inactive. */ + osThreadInactive = 0, + /** The thread is ready. */ + osThreadReady = 1, + /** The thread is running. */ + osThreadRunning = 2, + /** The thread is blocked. */ + osThreadBlocked = 3, + /** The thread is terminated. */ + osThreadTerminated = 4, + /** The thread is abnormal. */ + osThreadError = -1, + /** Reserved */ + osThreadReserved = 0x7FFFFFFF +} osThreadState_t; + +/** +* @brief Enumerates thread priorities. +* +*/ +typedef enum { + /** Undefined */ + osPriorityNone = 0, + /** Reserved for idle threads */ + osPriorityIdle = 1, + /** Low (unsupported) */ + osPriorityLow = 8, + /** Low + 1 */ + osPriorityLow1 = 8+1, + /** Low + 2 */ + osPriorityLow2 = 8+2, + /** Low + 3 */ + osPriorityLow3 = 8+3, + /** Low + 4 */ + osPriorityLow4 = 8+4, + /** Low + 5 */ + osPriorityLow5 = 8+5, + /** Low + 6 */ + osPriorityLow6 = 8+6, + /** Low + 7 */ + osPriorityLow7 = 8+7, + /** Below normal */ + osPriorityBelowNormal = 16, + /** Below normal + 1 */ + osPriorityBelowNormal1 = 16+1, + /** Below normal + 2 */ + osPriorityBelowNormal2 = 16+2, + /** Below normal + 3 */ + osPriorityBelowNormal3 = 16+3, + /** Below normal + 4 */ + osPriorityBelowNormal4 = 16+4, + /** Below normal + 5 */ + osPriorityBelowNormal5 = 16+5, + /** Below normal + 6 */ + osPriorityBelowNormal6 = 16+6, + /** Below normal + 7 */ + osPriorityBelowNormal7 = 16+7, + /** Normal */ + osPriorityNormal = 24, + /** Normal + 1 */ + osPriorityNormal1 = 24+1, + /** Normal + 2 */ + osPriorityNormal2 = 24+2, + /** Normal + 3 */ + osPriorityNormal3 = 24+3, + /** Normal + 4 */ + osPriorityNormal4 = 24+4, + /** Normal + 5 */ + osPriorityNormal5 = 24+5, + /** Normal + 6 */ + osPriorityNormal6 = 24+6, + /** Normal + 7 */ + osPriorityNormal7 = 24+7, + /** Above normal */ + osPriorityAboveNormal = 32, + /** Above normal + 1 */ + osPriorityAboveNormal1 = 32+1, + /** Above normal + 2 */ + osPriorityAboveNormal2 = 32+2, + /** Above normal + 3 */ + osPriorityAboveNormal3 = 32+3, + /** Above normal + 4 */ + osPriorityAboveNormal4 = 32+4, + /** Above normal + 5 */ + osPriorityAboveNormal5 = 32+5, + /** Above normal + 6 */ + osPriorityAboveNormal6 = 32+6, + /** Above normal + 7 (unsupported) */ + osPriorityAboveNormal7 = 32+7, + /** High (unsupported) */ + osPriorityHigh = 40, + /** High + 1 (unsupported) */ + osPriorityHigh1 = 40+1, + /** High + 2 (unsupported) */ + osPriorityHigh2 = 40+2, + /** High + 3 (unsupported) */ + osPriorityHigh3 = 40+3, + /** High + 4 (unsupported) */ + osPriorityHigh4 = 40+4, + /** High + 5 (unsupported) */ + osPriorityHigh5 = 40+5, + /** High + 6 (unsupported) */ + osPriorityHigh6 = 40+6, + /** High + 7 (unsupported) */ + osPriorityHigh7 = 40+7, + /** Real-time (unsupported) */ + osPriorityRealtime = 48, + /** Real-time + 1 (unsupported) */ + osPriorityRealtime1 = 48+1, + /** Real-time + 2 (unsupported) */ + osPriorityRealtime2 = 48+2, + /** Real-time + 3 (unsupported) */ + osPriorityRealtime3 = 48+3, + /** Real-time + 4 (unsupported) */ + osPriorityRealtime4 = 48+4, + /** Real-time + 5 (unsupported) */ + osPriorityRealtime5 = 48+5, + /** Real-time + 6 (unsupported) */ + osPriorityRealtime6 = 48+6, + /** Real-time + 7 (unsupported) */ + osPriorityRealtime7 = 48+7, + /** Reserved for ISR deferred threads (unsupported) */ + osPriorityISR = 56, + /** Invalid */ + osPriorityError = -1, + /** Reserved. It enables the compiler to identify enumeration variables as 32-bit numbers and prevents the enumeration variables from being optimized. */ + osPriorityReserved = 0x7FFFFFFF +} osPriority_t; + +/** +* @brief Callback for thread scheduling +* +*/ +typedef void (*osThreadFunc_t) (void *argument); + +/** +* @brief Callback for timer triggering +* +*/ +typedef void (*osTimerFunc_t) (void *argument); + +/** +* @brief Enumerates timer types. +* +*/ +typedef enum { + /** One-shot timer */ + osTimerOnce = 0, + /** Repeating timer */ + osTimerPeriodic = 1 +} osTimerType_t; + +/** +* @brief Indicates that the RTOS waits forever unless an event flag is received. +* +*/ +#define osWaitForever 0xFFFFFFFFU + +/** +* @brief Indicates that the RTOS does not wait. +* +*/ +#define osNoWait 0x0U + +/** +* @brief Indicates that the RTOS waits until any event flag is triggered. +* +*/ +#define osFlagsWaitAny 0x00000000U + +/** +* @brief Indicates that the system waits until all event flags are triggered. +* +*/ +#define osFlagsWaitAll 0x00000001U + +/** +* @brief Indicates that defined flags are not cleared. +* +*/ +#define osFlagsNoClear 0x00000002U + +/** +* @brief Indicates a flag error. +* +*/ +#define osFlagsError 0x80000000U + +/** +* @brief Indicates an unknown error. +* +*/ +#define osFlagsErrorUnknown 0xFFFFFFFFU + +/** +* @brief Indicates a timeout. +* +*/ +#define osFlagsErrorTimeout 0xFFFFFFFEU + +/** +* @brief Indicates a resource error. +* +*/ +#define osFlagsErrorResource 0xFFFFFFFDU + +/** +* @brief Indicates an incorrect parameter. +* +*/ +#define osFlagsErrorParameter 0xFFFFFFFCU +#define osFlagsErrorISR 0xFFFFFFFAU + +// Thread attributes (attr_bits in \ref osThreadAttr_t). +#define osThreadDetached 0x00000000U +#define osThreadJoinable 0x00000001U + +// Mutex attributes (attr_bits in \ref osMutexAttr_t). +#define osMutexRecursive 0x00000001U +#define osMutexPrioInherit 0x00000002U +#define osMutexRobust 0x00000008U + +/** +* @brief Enumerates return values of CMSIS-RTOS. +* +*/ +typedef enum { + /** Operation completed successfully */ + osOK = 0, + /** Unspecified error */ + osError = -1, + /** Timeout */ + osErrorTimeout = -2, + /** Resource error */ + osErrorResource = -3, + /** Incorrect parameter */ + osErrorParameter = -4, + /** Insufficient memory */ + osErrorNoMemory = -5, + /** Service interruption */ + osErrorISR = -6, + /** Reserved. It is used to prevent the compiler from optimizing enumerations. */ + osStatusReserved = 0x7FFFFFFF +} osStatus_t; + +/** +* @brief Identifies a thread. +* +*/ +typedef void *osThreadId_t; + +/** +* @brief Identifies a timer. +* +*/ +typedef void *osTimerId_t; + +/** +* @brief Identifies an event flag. +* +*/ +typedef void *osEventFlagsId_t; + +/** +* @brief Identifies a mutex. +* +*/ +typedef void *osMutexId_t; + +/** +* @brief Identifies a semaphore object. +* +*/ +typedef void *osSemaphoreId_t; + + +typedef void *osMemoryPoolId_t; + +/** +* @brief Identifies a message queue. +* +*/ +typedef void *osMessageQueueId_t; + + +#ifndef TZ_MODULEID_T +#define TZ_MODULEID_T + +/** +* @brief Identifies a TrustZone module call process. +* +*/ +typedef uint32_t TZ_ModuleId_t; +#endif + +/** +* @brief Describes thread attributes. +* +* @since 1.0 +* @version 1.0 +*/ +typedef struct { + /** Thread name */ + const char *name; + /** Thread attribute bits */ + uint32_t attr_bits; + /** Memory for the thread control block */ + void *cb_mem; + /** Size of the memory for the thread control block */ + uint32_t cb_size; + /** Memory for the thread stack */ + void *stack_mem; + /** Size of the thread stack */ + uint32_t stack_size; + /** Thread priority */ + osPriority_t priority; + /** TrustZone module of the thread */ + TZ_ModuleId_t tz_module; + /** Reserved */ + uint32_t reserved; +} osThreadAttr_t; + +/** +* @brief Describes timer attributes. +* +* @since 1.0 +* @version 1.0 +*/ +typedef struct { + /** Timer name */ + const char *name; + /** Reserved attribute bits */ + uint32_t attr_bits; + /** Memory for the timer control block */ + void *cb_mem; + /** Size of the memory for the timer control block */ + uint32_t cb_size; +} osTimerAttr_t; + +/** +* @brief Describes event attributes. +* +* @since 1.0 +* @version 1.0 +*/ +typedef struct { + /** Event name */ + const char *name; + /** Reserved attribute bits */ + uint32_t attr_bits; + /** Memory for the event control block */ + void *cb_mem; + /** Size of the memory for the event control block */ + uint32_t cb_size; +} osEventFlagsAttr_t; + +/** +* @brief Describes mutex attributes. +* +* @since 1.0 +* @version 1.0 +*/ +typedef struct { + /** Mutex name */ + const char *name; + /** Reserved attribute bits */ + uint32_t attr_bits; + /** Memory for the mutex control block */ + void *cb_mem; + /** Size of the memory for the mutex control block */ + uint32_t cb_size; +} osMutexAttr_t; + +/** +* @brief Describes semaphore attributes. +* +* @since 1.0 +* @version 1.0 +*/ +typedef struct { + /** Semaphore name */ + const char *name; + /** Reserved attribute bits */ + uint32_t attr_bits; + /** Memory for the semaphore control block */ + void *cb_mem; + /** Size of the memory for the semaphore control block */ + uint32_t cb_size; +} osSemaphoreAttr_t; + + +typedef struct { + const char *name; + uint32_t attr_bits; + void *cb_mem; + uint32_t cb_size; + void *mp_mem; + uint32_t mp_size; +} osMemoryPoolAttr_t; + +/** +* @brief Describes message queue attributes. +* +* @since 1.0 +* @version 1.0 +*/ +typedef struct { + /** Message queue name */ + const char *name; + /** Reserved attribute bits */ + uint32_t attr_bits; + /** Memory for the message queue control block */ + void *cb_mem; + /** Size of the memory for the message queue control block */ + uint32_t cb_size; + /** Memory for storing data in the message queue */ + void *mq_mem; + /** Size of the memory for storing data in the message queue */ + uint32_t mq_size; +} osMessageQueueAttr_t; + + +// ==== Kernel Management Functions ==== + +/** +* @brief Initializes the RTOS kernel. +* +* @return Returns the CMSIS-RTOS running result. +* @since 1.0 +* @version 1.0 +*/ +osStatus_t osKernelInitialize (void); + +/** +* @brief Obtains the system version and name. +* +* @param version Indicates the pointer to the buffer for storing the version. +* @param id_buf Indicates the pointer to the buffer for storing the kernel ID. +* @param id_size Indicates the size of the buffer for storing the kernel ID. +* @return Returns the CMSIS-RTOS running result. +* @since 1.0 +* @version 1.0 +*/ +osStatus_t osKernelGetInfo (osVersion_t *version, char *id_buf, uint32_t id_size); + +/** +* @brief Obtains the kernel state. +* +* @return Returns the kernel state. +* @since 1.0 +* @version 1.0 +*/ +osKernelState_t osKernelGetState (void); + +/** +* @brief Starts the kernel. +* +* @return Returns the CMSIS-RTOS running result. +* @since 1.0 +* @version 1.0 +*/ +osStatus_t osKernelStart (void); + +/** +* @brief Locks the kernel. +* +* @return Returns 1 if the kernel is locked successfully; returns 0 if the lock starts; returns a negative value in the case of an error. +* @since 1.0 +* @version 1.0 +*/ +int32_t osKernelLock (void); + +/** +* @brief Unlocks the kernel. +* +* @return Returns 1 if the kernel is unlocked successfully; returns 0 if the kernel is not locked; returns a negative value in the case of an error. +* @since 1.0 +* @version 1.0 +*/ +int32_t osKernelUnlock (void); + +/** +* @brief Restores the previous lock state of the kernel. +* +* @param lock Indicates the lock state to restore to. The value 1 indicates the locked state, and 0 indicates the unlocked state. +* @return Returns 1 if the kernel is locked; returns 0 if the kernel is not locked; returns a negative value in the case of an error. +* @since 1.0 +* @version 1.0 +*/ +int32_t osKernelRestoreLock (int32_t lock); + +uint32_t osKernelSuspend (void); + +void osKernelResume (uint32_t sleep_ticks); + +/// Get the RTOS kernel tick count. +/// \return RTOS kernel current tick count. +uint32_t osKernelGetTickCount (void); + + + +/** +* @brief Obtains the number of kernel ticks per second. +* +* @return Returns the number of kernel ticks. +* @since 1.0 +* @version 1.0 +*/ +uint32_t osKernelGetTickFreq (void); + +/** +* @brief Obtains the kernel system timer. +* +* @return Returns the kernel system timer. +* @since 1.0 +* @version 1.0 +*/ +uint32_t osKernelGetSysTimerCount (void); + +/** +* @brief Obtains the frequency of the system timer. +* +* @return Returns the system timer frequency. +* @since 1.0 +* @version 1.0 +*/ +uint32_t osKernelGetSysTimerFreq (void); + + +// ==== Thread Management Functions ==== + +/** +* @brief Creates an active thread. +* +* The priority ranges from 9 to 38. Select a proper priority as required. +* The maximum of tasks is LOSCFG_BASE_CORE_TSK_LIMIT(LOSCFG_BASE_CORE_TSK_LIMIT is defined in the traget_config.h). +* @param func Indicates the entry of the thread callback function. +* @param argument Indicates the pointer to the argument passed to the thread. +* @param attr Indicates the thread attributes. +* @return Returns the thread ID; returns NULL in the case of an error. +* @since 1.0 +* @version 1.0 +*/ +osThreadId_t osThreadNew (osThreadFunc_t func, void *argument, const osThreadAttr_t *attr); + +/** +* @brief Obtains the name of a thread. +* +* @param thread_id Indicates the thread ID, which is obtained using osThreadNew or osThreadGetId. +* @return Returns the thread name; returns NULL in the case of an error. +* @since 1.0 +* @version 1.0 +*/ +const char *osThreadGetName (osThreadId_t thread_id); + +/** +* @brief Obtains the ID of the currently running thread. +* +* @return Returns the thread ID; returns NULL in the case of an error. +* @since 1.0 +* @version 1.0 +*/ +osThreadId_t osThreadGetId (void); + + +/** +* @brief Obtains the state of a thread. +* +* @param thread_id Indicates the thread ID, which is obtained using osThreadNew or osThreadGetId. +* @return Returns the thread state. +* @since 1.0 +* @version 1.0 +*/ +osThreadState_t osThreadGetState (osThreadId_t thread_id); + +/** +* @brief Obtains the stack size of a thread. +* +* @param thread_id Indicates the thread ID, which is obtained using osThreadNew or osThreadGetId. +* @return Returns the stack size, in bytes; returns 0 in the case of an error. +* @since 1.0 +* @version 1.0 +*/ +uint32_t osThreadGetStackSize (osThreadId_t thread_id); + +/** +* @brief Obtains the size of the available stack space for a thread based on the stack watermark. +* +* @param thread_id Indicates the thread ID, which is obtained using osThreadNew or osThreadGetId. +* @return Returns the available stack size, in bytes; returns 0 in the case of an error. +* @since 1.0 +* @version 1.0 +*/ +uint32_t osThreadGetStackSpace (osThreadId_t thread_id); + +/** +* @brief Changes the priority of a thread. +* +* @param thread_id Indicates the thread ID, which is obtained using osThreadNew or osThreadGetId. +* @param priority Indicates the new priority. +* @return Returns the CMSIS-RTOS running result. +* @since 1.0 +* @version 1.0 +*/ +osStatus_t osThreadSetPriority (osThreadId_t thread_id, osPriority_t priority); + +/** +* @brief Gets the prority of an active thread. +* +* @param thread_id Indicates the thread ID, which is obtained using osThreadNew or osThreadGetId. +* @return Returns the prority of the thread. +* @since 1.0 +* @version 1.0 +*/ +osPriority_t osThreadGetPriority (osThreadId_t thread_id); + +/** +* @brief Sets the currently running thread to the ready state. +* +* @return Returns the CMSIS-RTOS running result. +* @since 1.0 +* @version 1.0 +*/ +osStatus_t osThreadYield (void); + +/** +* @brief Suspends a thread. +* +* @param thread_id Indicates the thread ID, which is obtained using osThreadNew or osThreadGetId. +* @return Returns the CMSIS-RTOS running result. +* @since 1.0 +* @version 1.0 +*/ +osStatus_t osThreadSuspend (osThreadId_t thread_id); + +/** +* @brief Resumes a thread from the suspended state. +* +* @param thread_id Indicates the thread ID, which is obtained using osThreadNew or osThreadGetId. +* @return Returns the CMSIS-RTOS running result. +* @since 1.0 +* @version 1.0 +*/ +osStatus_t osThreadResume (osThreadId_t thread_id); + +osStatus_t osThreadDetach (osThreadId_t thread_id); + +osStatus_t osThreadJoin (osThreadId_t thread_id); + +void osThreadExit (void); + +/** +* @brief Terminates a thread. +* +* @param thread_id Indicates the thread ID, which is obtained using osThreadNew or osThreadGetId. +* @return Returns the CMSIS-RTOS running result. +* @since 1.0 +* @version 1.0 +*/ +osStatus_t osThreadTerminate (osThreadId_t thread_id); + +/** +* @brief Obtains the number of active threads. +* +* @return Returns the number; returns 0 in the case of an error. +* @since 1.0 +* @version 1.0 +*/ +uint32_t osThreadGetCount (void); + +uint32_t osThreadEnumerate (osThreadId_t *thread_array, uint32_t array_items); + + +// ==== Thread Flags Functions ==== + +uint32_t osThreadFlagsSet (osThreadId_t thread_id, uint32_t flags); + +uint32_t osThreadFlagsClear (uint32_t flags); + +uint32_t osThreadFlagsGet (void); + +uint32_t osThreadFlagsWait (uint32_t flags, uint32_t options, uint32_t timeout); + + +// ==== Generic Wait Functions ==== + +/** +* @brief Waits for a period of time. +* +* @param ticks Indicates the number of ticks to wait for. +* @return Returns the CMSIS-RTOS running result. +* @since 1.0 +* @version 1.0 +*/ +osStatus_t osDelay (uint32_t ticks); + +/** +* @brief Waits until a specified time arrives. +* +* This function handles the overflow of the system timer. Note that the maximum value of this parameter is (2^31 - 1) ticks. +* @param ticks Indicates the number of ticks converted from the absolute time. +* @return Returns the CMSIS-RTOS running result. +* @since 1.0 +* @version 1.0 +*/ +osStatus_t osDelayUntil (uint32_t ticks); + + +// ==== Timer Management Functions ==== + +/** +* @brief Creates and initializes a timer. +* +* This function creates a timer associated with the arguments callback function. The timer stays in the stopped state until OSTimerStart is used to start the timer. +* The timer precision is 1000 / LOSCFG_BASE_CORE_TICK_PER_SECOND ms(LOSCFG_BASE_CORE_TICK_PER_SECOND is defined in the traget_config.h). +* @param func Indicates the entry of the timer callback function. +* @param type Indicates the timer type. +* @param argument Indicates the pointer to the argument used in timer callback. +* @param attr Indicates the pointer to the timer attributes. This parameter is not used. +* @return Returns the timer ID; returns NULL in the case of an error. +* @since 1.0 +* @version 1.0 +*/ +osTimerId_t osTimerNew (osTimerFunc_t func, osTimerType_t type, void *argument, const osTimerAttr_t *attr); + +/** +* @brief Obtains the timer name. +* +* @param timer_id Indicates the timer ID, which is obtained using osTimerNew. +* @return Returns the timer name; returns NULL in the case of an error. +* @since 1.0 +* @version 1.0 +*/ +const char *osTimerGetName (osTimerId_t timer_id); + +/** +* @brief Starts or restarts a timer. +* +* @param timer_id Indicates the timer ID, which is obtained using osTimerNew. +* @param ticks Indicates the number of ticks since the timer starts running. +* @return Returns the CMSIS-RTOS running result. +* @since 1.0 +* @version 1.0 +*/ +osStatus_t osTimerStart (osTimerId_t timer_id, uint32_t ticks); + +/** +* @brief Stops a timer. +* +* @param timer_id Indicates the timer ID, which is obtained using osTimerNew. +* @return Returns the CMSIS-RTOS running result. +* @since 1.0 +* @version 1.0 +*/ +osStatus_t osTimerStop (osTimerId_t timer_id); + +/** +* @brief Checks whether a timer is running. +* +* @param timer_id Indicates the timer ID, which is obtained using osTimerNew. +* @return Returns 1 if the timer is running; returns 0 otherwise. +* @since 1.0 +* @version 1.0 +*/ +uint32_t osTimerIsRunning (osTimerId_t timer_id); + +/** +* @brief Deletes a timer. +* +* @param timer_id Indicates the timer ID, which is obtained using osTimerNew. +* @return Returns the CMSIS-RTOS running result. +* @since 1.0 +* @version 1.0 +*/ +osStatus_t osTimerDelete (osTimerId_t timer_id); + + +// ==== Event Flags Management Functions ==== + +/** +* @brief Creates and initializes an event flags object. +* +* @param attr Indicates the pointer to the event flags attributes. This parameter is not used. +* @return Returns the event flags ID; returns NULL in the case of an error. +* @since 1.0 +* @version 1.0 +*/ +osEventFlagsId_t osEventFlagsNew (const osEventFlagsAttr_t *attr); + +/** +* @brief Obtains the name of an event flags object. +* +* @param ef_id Indicates the event flags ID, which is obtained using osEventFlagsNew. +* @return Returns the event flags name; returns NULL in the case of an error. +* @since 1.0 +* @version 1.0 +*/ +const char *osEventFlagsGetName (osEventFlagsId_t ef_id); + +/** +* @brief Sets event flags. +* +* @param ef_id Indicates the event flags ID, which is obtained using osEventFlagsNew. +* @param flags Indicates the event flags to set. +* @return Returns the event flags; returns osFlagsErrorParameter in the case of an error. +* @since 1.0 +* @version 1.0 +*/ +uint32_t osEventFlagsSet (osEventFlagsId_t ef_id, uint32_t flags); + +/** +* @brief Clears event flags. +* +* @param ef_id Indicates the event flags ID, which is obtained using osEventFlagsNew. +* @param flags Indicates the event flags to clear. +* @return Returns the event flags; returns osFlagsErrorParameter in the case of an error. +* @since 1.0 +* @version 1.0 +*/ +uint32_t osEventFlagsClear (osEventFlagsId_t ef_id, uint32_t flags); + +/** +* @brief Obtains event flags. +* +* @param ef_id Indicates the event flags ID, which is obtained using osEventFlagsNew. +* @return Returns the event flags triggered. +* @since 1.0 +* @version 1.0 +*/ +uint32_t osEventFlagsGet (osEventFlagsId_t ef_id); + +/** +* @brief Waits for event flags to trigger. +* +* When the specified flag of the event is set, the function returns immediately. Otherwise, the thread is blocked. +* @param ef_id Indicates the event flags ID, which is obtained using osEventFlagsNew. +* @param flags Indicates the event flags to trigger. +* @param options Indicates the configuration of the event flags to trigger. +* @param timeout Indicates the timeout duration. +* @return Returns the triggered event flags; returns an error value in the case of an error. +* @since 1.0 +* @version 1.0 +*/ +uint32_t osEventFlagsWait (osEventFlagsId_t ef_id, uint32_t flags, uint32_t options, uint32_t timeout); + +/** +* @brief Deletes an event flags object. +* +* @param ef_id Indicates the event flags ID, which is obtained using osEventFlagsNew. +* @return Returns the CMSIS-RTOS running result. +* @since 1.0 +* @version 1.0 +*/ +osStatus_t osEventFlagsDelete (osEventFlagsId_t ef_id); + + +// ==== Mutex Management Functions ==== + +/** +* @brief Creates and initializes a mutex. +* +* @param attr Indicates the pointer to the mutex attributes. This parameter is not used. +* @return Returns the mutex ID; returns NULL in the case of an error. +* @since 1.0 +* @version 1.0 +*/ +osMutexId_t osMutexNew (const osMutexAttr_t *attr); + +const char *osMutexGetName (osMutexId_t mutex_id); + +/** +* @brief Obtains a mutex. +* +* @param mutex_id Indicates the mutex ID, which is obtained using osMutexNew. +* @param timeout Indicates the timeout duration. +* @return Returns the CMSIS-RTOS running result. +* @since 1.0 +* @version 1.0 +*/ +osStatus_t osMutexAcquire (osMutexId_t mutex_id, uint32_t timeout); + +/** +* @brief Releases a mutex. +* +* @param mutex_id Indicates the mutex ID, which is obtained using osMutexNew. +* @return Returns the CMSIS-RTOS running result. +* @since 1.0 +* @version 1.0 +*/ +osStatus_t osMutexRelease (osMutexId_t mutex_id); + +/** +* @brief Obtains the thread ID of the currently acquired mutex. +* +* @param mutex_id Indicates the mutex ID, which is obtained using osMutexNew. +* @return Returns the thread ID. +* @since 1.0 +* @version 1.0 +*/ +osThreadId_t osMutexGetOwner (osMutexId_t mutex_id); + +/** +* @brief Deletes a mutex. +* +* @param mutex_id Indicates the mutex ID, which is obtained using osMutexNew. +* @return Returns the CMSIS-RTOS running result. +* @since 1.0 +* @version 1.0 +*/ +osStatus_t osMutexDelete (osMutexId_t mutex_id); + + +// ==== Semaphore Management Functions ==== + +/** +* @brief Creates and initializes a semaphore object. +* +* @param max_count Indicates the maximum number of available tokens that can be applied for. +* @param initial_count Indicates the initial number of available tokens. +* @param attr Indicates the pointer to the semaphore attributes. This parameter is not used. +* @return Returns the semaphore ID; returns NULL in the case of an error. +* @since 1.0 +* @version 1.0 +*/ +osSemaphoreId_t osSemaphoreNew (uint32_t max_count, uint32_t initial_count, const osSemaphoreAttr_t *attr); + +const char *osSemaphoreGetName (osSemaphoreId_t semaphore_id); + +/** +* @brief Acquires a token of a semaphore object. +* +* @param semaphore_id Indicates the semaphore ID, which is obtained using osSemaphoreNew. +* @param timeout Indicates the timeout duration. This parameter is the number of ticks. +* @return Returns the CMSIS-RTOS running result. +* @since 1.0 +* @version 1.0 +*/ +osStatus_t osSemaphoreAcquire (osSemaphoreId_t semaphore_id, uint32_t timeout); + +/** +* @brief Releases a token of a semaphore object. +* +* @param semaphore_id Indicates the semaphore ID, which is obtained using osSemaphoreNew. +* @return Returns the CMSIS-RTOS running result. +* @since 1.0 +* @version 1.0 +*/ +osStatus_t osSemaphoreRelease (osSemaphoreId_t semaphore_id); + +/** +* @brief Obtains the number of available tokens of a semaphore object. +* +* @param semaphore_id Indicates the semaphore ID, which is obtained using osSemaphoreNew. +* @return Returns the number of available tokens. +* @since 1.0 +* @version 1.0 +*/ +uint32_t osSemaphoreGetCount (osSemaphoreId_t semaphore_id); + +/** +* @brief Deletes a semaphore object. +* +* @param semaphore_id Indicates the semaphore ID, which is obtained using osSemaphoreNew. +* @return Returns the CMSIS-RTOS running result. +* @since 1.0 +* @version 1.0 +*/ +osStatus_t osSemaphoreDelete (osSemaphoreId_t semaphore_id); + + +// ==== Memory Pool Management Functions ==== + +osMemoryPoolId_t osMemoryPoolNew (uint32_t block_count, uint32_t block_size, const osMemoryPoolAttr_t *attr); + +const char *osMemoryPoolGetName (osMemoryPoolId_t mp_id); + +void *osMemoryPoolAlloc (osMemoryPoolId_t mp_id, uint32_t timeout); + +osStatus_t osMemoryPoolFree (osMemoryPoolId_t mp_id, void *block); + +uint32_t osMemoryPoolGetCapacity (osMemoryPoolId_t mp_id); + +uint32_t osMemoryPoolGetBlockSize (osMemoryPoolId_t mp_id); + +uint32_t osMemoryPoolGetCount (osMemoryPoolId_t mp_id); + +uint32_t osMemoryPoolGetSpace (osMemoryPoolId_t mp_id); + +osStatus_t osMemoryPoolDelete (osMemoryPoolId_t mp_id); + + +// ==== Message Queue Management Functions ==== + +/** +* @brief Creates and initializes a message queue. +* +* @param msg_count Indicates the number of messages in the message queue. +* @param msg_size Indicates the size of messages in the message queue. +* @param attr Indicates the pointer to the message queue attributes. This parameter is not used. +* @return Returns the message queue ID; returns NULL in the case of an error. +* @since 1.0 +* @version 1.0 +*/ +osMessageQueueId_t osMessageQueueNew (uint32_t msg_count, uint32_t msg_size, const osMessageQueueAttr_t *attr); + +const char *osMessageQueueGetName (osMessageQueueId_t mq_id); + +/** +* @brief Places a message in a message queue. +* +* @param mq_id Indicates the message queue ID, which is obtained using osMessageQueueNew. +* @param msg_ptr Indicates the pointer to the buffer for storing the message to be placed in the message queue. +* @param msg_prio Indicates the priority of the message to be placed in the message queue. This parameter is not used. +* @param timeout Indicates the timeout duration. +* @return Returns the CMSIS-RTOS running result. +* @since 1.0 +* @version 1.0 +*/ +osStatus_t osMessageQueuePut (osMessageQueueId_t mq_id, const void *msg_ptr, uint8_t msg_prio, uint32_t timeout); + +/** +* @brief Obtains a message in a message queue. +* +* @param mq_id Indicates the message queue ID, which is obtained using osMessageQueueNew. +* @param msg_ptr Indicates the pointer to the buffer for storing the message to be retrieved from the message queue. +* @param msg_prio Indicates the pointer to the buffer for storing the priority of the message to be retrieved from the message queue. This parameter is not used. +* @param timeout Indicates the timeout duration. +* @return Returns the CMSIS-RTOS running result. +* @since 1.0 +* @version 1.0 +*/ +osStatus_t osMessageQueueGet (osMessageQueueId_t mq_id, void *msg_ptr, uint8_t *msg_prio, uint32_t timeout); + +/** +* @brief Obtains the maximum number of messages that can be placed in a message queue. +* +* @param mq_id Indicates the message queue ID, which is obtained using osMessageQueueNew. +* @return Returns the maximum number. +* @since 1.0 +* @version 1.0 +*/ +uint32_t osMessageQueueGetCapacity (osMessageQueueId_t mq_id); + +/** +* @brief Obtains the maximum size of messages that can be placed in a message queue. +* +* @param mq_id Indicates the message queue ID, which is obtained using osMessageQueueNew. +* @return Returns the maximum message size. +* @since 1.0 +* @version 1.0 +*/ +uint32_t osMessageQueueGetMsgSize (osMessageQueueId_t mq_id); + +/** +* @brief Obtains the number of queued messages in a message queue. +* +* @param mq_id Indicates the message queue ID, which is obtained using osMessageQueueNew. +* @return Returns the number of queued messages. +* @since 1.0 +* @version 1.0 +*/ +uint32_t osMessageQueueGetCount (osMessageQueueId_t mq_id); + +/** +* @brief Obtains the number of available slots for messages in a message queue. +* +* @param mq_id Indicates the message queue ID, which is obtained using osMessageQueueNew. +* @return Returns the number of available slots for messages. +* @since 1.0 +* @version 1.0 +*/ +uint32_t osMessageQueueGetSpace (osMessageQueueId_t mq_id); + +osStatus_t osMessageQueueReset (osMessageQueueId_t mq_id); + +/** +* @brief Deletes a message queue. +* +* @param mq_id Indicates the message queue ID, which is obtained using osMessageQueueNew. +* @return Returns the CMSIS-RTOS running result. +* @since 1.0 +* @version 1.0 +*/ +osStatus_t osMessageQueueDelete (osMessageQueueId_t mq_id); + + +#ifdef __cplusplus +} +#endif + +#endif // CMSIS_OS2_H_ diff --git a/hi3861_adapter/kal/cmsis/hos_cmsis_adp.h b/hi3861_adapter/kal/cmsis/hos_cmsis_adp.h new file mode 100755 index 0000000000000000000000000000000000000000..78e3c90687b64519a1744faf7da34d4111d073d0 --- /dev/null +++ b/hi3861_adapter/kal/cmsis/hos_cmsis_adp.h @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef HOS_CMSIS_ADP_H +#define HOS_CMSIS_ADP_H + +#include "cmsis_os.h" +#include "ohos_types.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ + +typedef struct { + osSemaphoreAttr_t attr; + uint32 maxCount; + uint32 initialCount; +} SemaphoreEx; + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif diff --git a/hi3861_adapter/kal/posix/BUILD.gn b/hi3861_adapter/kal/posix/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..9a22fda42a9ec7899f0b656ef31c7586c96f9e60 --- /dev/null +++ b/hi3861_adapter/kal/posix/BUILD.gn @@ -0,0 +1,48 @@ +# Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved. +# Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, +# are permitted provided that the following conditions are met: +# +# 1. Redistributions of source code must retain the above copyright notice, this list of +# conditions and the following disclaimer. +# +# 2. Redistributions in binary form must reproduce the above copyright notice, this list +# of conditions and the following disclaimer in the documentation and/or other materials +# provided with the distribution. +# +# 3. Neither the name of the copyright holder nor the names of its contributors may be used +# to endorse or promote products derived from this software without specific prior written +# permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, +# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; +# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR +# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF +# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +import("//build/lite/config/component/lite_component.gni") + +static_library("posix") { + sources = [ + "src/file.c", + "src/libc.c", + "src/pthread.c", + "src/pthread_attr.c", + "src/time.c", + ] + + include_dirs = [ "include" ] + defines = [ + "LIBC_VERSION_NUM=0x00010000", + "LIBC_VERSION_STR=\"1.0.0-liteos_m\"", + ] + + cflags = [ "-Werror" ] +} diff --git a/hi3861_adapter/kal/posix/include/libc.h b/hi3861_adapter/kal/posix/include/libc.h new file mode 100644 index 0000000000000000000000000000000000000000..7ee6cc587c78356723fa5c86434de28bc38da6bb --- /dev/null +++ b/hi3861_adapter/kal/posix/include/libc.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef LIBC_H_ +#define LIBC_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +const char *libc_get_version_string(void); +int libc_get_version(void); + +#ifdef __cplusplus +} +#endif + +#endif // LIBC_H_ diff --git a/hi3861_adapter/kal/posix/include/limits.h b/hi3861_adapter/kal/posix/include/limits.h new file mode 100644 index 0000000000000000000000000000000000000000..417ec2a1afc4b6ed5edb7acb87ab4c449a97c59a --- /dev/null +++ b/hi3861_adapter/kal/posix/include/limits.h @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef _KAL_LIMITS_H +#define _KAL_LIMITS_H + +#include_next + +#ifndef PTHREAD_STACK_MIN +#ifdef __LITEOS__ +#define PTHREAD_STACK_MIN LOSCFG_BASE_CORE_TSK_MIN_STACK_SIZE +#endif +#endif + +#endif diff --git a/hi3861_adapter/kal/posix/include/pthread.h b/hi3861_adapter/kal/posix/include/pthread.h new file mode 100644 index 0000000000000000000000000000000000000000..ecff4d2f23ca90165422d006bda25f9f5d9c2611 --- /dev/null +++ b/hi3861_adapter/kal/posix/include/pthread.h @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef _KAL_PTHREAD_H +#define _KAL_PTHREAD_H + +#include_next + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef _GNU_SOURCE +int pthread_getname_np(pthread_t, char *, size_t); +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/hi3861_adapter/kal/posix/src/file.c b/hi3861_adapter/kal/posix/src/file.c new file mode 100644 index 0000000000000000000000000000000000000000..7eb1d0d0a6d4e850b967d2eef8e58a3ddaa6ff2f --- /dev/null +++ b/hi3861_adapter/kal/posix/src/file.c @@ -0,0 +1,223 @@ +/* + * Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include +#include +#include +#include + +#include "lwip/sockets.h" +#include "hks_client.h" + +#define RANDOM_DEV_FD LWIP_CONFIG_NUM_SOCKETS +#define RANDOM_DEV_PATH "/dev/random" + +#define FREE_AND_SET_NULL(ptr) do { \ + free(ptr); \ + ptr = NULL; \ +} while (0) + +/** + * @brief Get canonical form of a given path based on cwd(Current working directory). + * + * @param cwd Indicates the current working directory. + * @param path Indicates the path to be canonicalization. + * @param buf Indicates the pointer to the buffer where the result will be return. + * @param bufSize Indicates the size of the buffer. + * @return Returns the length of the canonical path. + * + * @attention if path is an absolute path, cwd is ignored. if cwd if not specified, it is assumed to be root('/'). + * if the buffer is not big enough the result will be truncated, but the return value will always be the + * length of the canonical path. + */ +static size_t GetCanonicalPath(const char *cwd, const char *path, char *buf, size_t bufSize) +{ + if (!path) { + path = ""; + } + + if (!cwd || path[0] == '/') { + cwd = ""; + } + + size_t tmpLen = strlen(cwd) + strlen(path) + 4; // three '/' and one '\0' + if (tmpLen <= 0) { + return 0; + } + char *tmpBuf = (char *)malloc(tmpLen); + if (tmpBuf == NULL) { + return 0; + } + + if (-1 == sprintf_s(tmpBuf, tmpLen, "/%s/%s/", cwd, path)) { + free(tmpBuf); + return 0; + } + + char *p; + /* replace /./ to / */ + while ((p = strstr(tmpBuf, "/./")) != NULL) { + if (EOK != memmove_s(p, tmpLen - (p - tmpBuf), p + 2, tmpLen - (p - tmpBuf) - 2)) { + free(tmpBuf); + return 0; + } + } + + /* replace // to / */ + while ((p = strstr(tmpBuf, "//")) != NULL) { + if (EOK != memmove_s(p, tmpLen - (p - tmpBuf), p + 1, tmpLen - (p - tmpBuf) - 1)) { + free(tmpBuf); + return 0; + } + } + + /* handle /../ (e.g., replace /aa/bb/../ to /aa/) */ + while ((p = strstr(tmpBuf, "/../")) != NULL) { + char *start = p; + while (start > tmpBuf && *--start != '/') { + } + if (EOK != memmove_s(start, tmpLen - (start - tmpBuf), p + 3, tmpLen - (p - tmpBuf) - 3)) { + free(tmpBuf); + return 0; + } + } + + size_t totalLen = strlen(tmpBuf); + + /* strip the last / */ + if (totalLen > 1 && tmpBuf[totalLen - 1] == '/') { + tmpBuf[--totalLen] = 0; + } + + if (!buf || bufSize == 0) { + free(tmpBuf); + return totalLen; + } + + if (EOK != memcpy_s(buf, bufSize, tmpBuf, (totalLen + 1 > bufSize) ? bufSize : totalLen + 1)) { + free(tmpBuf); + return 0; + } + + buf[bufSize - 1] = 0; + free(tmpBuf); + return totalLen; +} + +int open(const char *file, int oflag, ...) +{ + unsigned flags = O_RDONLY | O_WRONLY | O_RDWR | O_APPEND | O_CREAT | O_LARGEFILE | O_TRUNC | O_EXCL | O_DIRECTORY; + if (((unsigned)oflag & ~flags) || (file == NULL)) { + errno = EINVAL; + return -1; + } + size_t pathLen = strlen(file) + 1; + if (pathLen <= 0) { + errno = EINVAL; + return -1; + } + char *canonicalPath = (char *)malloc(pathLen); + if (!canonicalPath) { + errno = ENOMEM; + return -1; + } + if (GetCanonicalPath(NULL, file, canonicalPath, pathLen) == 0) { + FREE_AND_SET_NULL(canonicalPath); + errno = ENOMEM; + return -1; + } + if (strcmp(canonicalPath, RANDOM_DEV_PATH) == 0) { + FREE_AND_SET_NULL(canonicalPath); + if ((O_ACCMODE & (unsigned)oflag) != O_RDONLY) { + errno = EPERM; + return -1; + } + if ((unsigned)oflag & O_DIRECTORY) { + errno = ENOTDIR; + return -1; + } + return RANDOM_DEV_FD; + } + if (strcmp(canonicalPath, "/") == 0 || strcmp(canonicalPath, "/dev") == 0) { + FREE_AND_SET_NULL(canonicalPath); + if ((unsigned)oflag & O_DIRECTORY) { + errno = EPERM; + return -1; + } + errno = EISDIR; + return -1; + } + FREE_AND_SET_NULL(canonicalPath); + errno = ENOENT; + return -1; +} + +int close(int fd) +{ + if (fd == RANDOM_DEV_FD) { + return 0; + } + return closesocket(fd); +} + +ssize_t read(int fd, void *buf, size_t nbytes) +{ + if (fd == RANDOM_DEV_FD) { + if (nbytes == 0) { + return 0; + } + if (buf == NULL) { + errno = EINVAL; + return -1; + } + if (nbytes > 1024) { + nbytes = 1024; /* hks_generate_random: random_size must <= 1024 */ + } + struct hks_blob key = {HKS_BLOB_TYPE_RAW, (uint8_t *)buf, nbytes}; + if (hks_generate_random(&key) != 0) { + errno = EIO; + return -1; + } + return (ssize_t)nbytes; + } + return recv(fd, buf, nbytes, 0); +} + +ssize_t write(int fd, const void *buf, size_t nbytes) +{ + if (fd == RANDOM_DEV_FD) { + errno = EBADF; /* "/dev/random" is readonly */ + return -1; + } + return send(fd, buf, nbytes, 0); +} diff --git a/hi3861_adapter/kal/posix/src/libc.c b/hi3861_adapter/kal/posix/src/libc.c new file mode 100644 index 0000000000000000000000000000000000000000..9bc3ada298c569e910b4bbf9441bf87c48073bff --- /dev/null +++ b/hi3861_adapter/kal/posix/src/libc.c @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include + +/** + * get libc version string. + * @return libc version string. the format is ..[-[-]] + */ +const char *libc_get_version_string(void) +{ + return LIBC_VERSION_STR; +} + +/** + * get libc version code. + * @return libc version code. the format is 0x00XXYYZZ, XX is major version, YY is minor version and ZZ is patch version + */ +int libc_get_version(void) +{ + return LIBC_VERSION_NUM; +} diff --git a/hi3861_adapter/kal/posix/src/pthread.c b/hi3861_adapter/kal/posix/src/pthread.c new file mode 100644 index 0000000000000000000000000000000000000000..c74e986a2a26db705220c0dd641cf4de64fdaf76 --- /dev/null +++ b/hi3861_adapter/kal/posix/src/pthread.c @@ -0,0 +1,262 @@ +/* + * Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include +#include +#include "los_task.h" +#include "los_task_pri.h" + +#define PTHREAD_NAMELEN 16 + +/* this is just an assertion: LOS_TASK_ARG_NUM >= 4 */ +typedef char NULNAM[-!((LOS_TASK_ARG_NUM * 4) >= PTHREAD_NAMELEN)]; + +static void *PthreadEntry(UINT32 param1, UINT32 param2, UINT32 param3, UINT32 param4) +{ + void *(*startRoutine)(void *) = (void *)(UINTPTR)param1; + void *param = (void *)(UINTPTR)param2; + (void)param3; + (void)param4; + int ret; + + LosTaskCB *tcb = OS_TCB_FROM_TID(LOS_CurTaskIDGet()); + char *tmp = tcb->taskName; + tcb->taskName = (char *)tcb->args; /* args are reused as task name */ + ret = strcpy_s(tcb->taskName, PTHREAD_NAMELEN, tmp); + if (ret != 0) { + free(tmp); + return NULL; + } + free(tmp); + + return startRoutine(param); +} + +static inline int IsPthread(pthread_t thread) +{ + return ((UINT32)thread <= LOSCFG_BASE_CORE_TSK_LIMIT) && + (OS_TCB_FROM_TID((UINT32)thread)->taskEntry == PthreadEntry); +} + +int pthread_create(pthread_t *thread, const pthread_attr_t *attr, + void *(*startRoutine)(void *), void *arg) +{ + TSK_INIT_PARAM_S taskInitParam = {0}; + UINT32 taskID; + + if ((thread == NULL) || (startRoutine == NULL)) { + return EINVAL; + } + + taskInitParam.usTaskPrio = LOSCFG_BASE_CORE_TSK_DEFAULT_PRIO; + taskInitParam.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; + if (attr) { + if (attr->detachstate == PTHREAD_CREATE_DETACHED) { + return ENOTSUP; + } + if (attr->stackaddr_set) { + return ENOTSUP; + } + if (attr->stacksize_set) { + taskInitParam.uwStackSize = attr->stacksize; + } + taskInitParam.usTaskPrio = (UINT16)attr->schedparam.sched_priority; + } + + taskInitParam.pcName = malloc(PTHREAD_NAMELEN); + if (taskInitParam.pcName == NULL) { + return ENOMEM; + } + + taskInitParam.pfnTaskEntry = PthreadEntry; + taskInitParam.auwArgs[0] = (UINT32)(UINTPTR)startRoutine; + taskInitParam.auwArgs[1] = (UINT32)(UINTPTR)arg; + + if (LOS_TaskCreateOnly(&taskID, &taskInitParam) != LOS_OK) { + free(taskInitParam.pcName); + return EINVAL; + } + + /* set pthread default name */ + (void)sprintf_s(taskInitParam.pcName, PTHREAD_NAMELEN, "pthread%u", taskID); + + (void)LOS_TaskResume(taskID); + + *thread = (pthread_t)taskID; + return 0; +} + +int pthread_setschedparam(pthread_t thread, int policy, const struct sched_param *param) +{ + if ((param == NULL) || (param->sched_priority < OS_TASK_PRIORITY_HIGHEST) || + (param->sched_priority >= OS_TASK_PRIORITY_LOWEST) || !IsPthread(thread)) { + return EINVAL; + } + + /* Only support SCHED_RR policy now */ + if (policy != SCHED_RR) { + return ENOTSUP; + } + + if (LOS_TaskPriSet((UINT32)thread, (UINT16)param->sched_priority) != LOS_OK) { + return EINVAL; + } + + return 0; +} + +int pthread_getschedparam(pthread_t thread, int *policy, struct sched_param *param) +{ + UINT32 prio; + + if ((policy == NULL) || (param == NULL) || !IsPthread(thread)) { + return EINVAL; + } + + prio = LOS_TaskPriGet((UINT32)thread); + if (prio == OS_INVALID) { + return EINVAL; + } + + *policy = SCHED_RR; + param->sched_priority = prio; + return 0; +} + +pthread_t pthread_self(void) +{ + return (pthread_t)LOS_CurTaskIDGet(); +} + +int pthread_cancel(pthread_t thread) +{ + if (!IsPthread(thread)) { + return EINVAL; + } + + return ENOSYS; +} + +static void *VoidTask(UINT32 param1, UINT32 param2, UINT32 param3, UINT32 param4) +{ + (void)param1; + (void)param2; + (void)param3; + (void)param4; + return 0; +} + +static void CleanupTaskResource(void) +{ + TSK_INIT_PARAM_S taskInitParam = {0}; + UINT32 taskID; + + taskInitParam.pcName = "void"; + taskInitParam.pfnTaskEntry = VoidTask; + taskInitParam.usTaskPrio = LOSCFG_BASE_CORE_TSK_DEFAULT_PRIO; + taskInitParam.uwStackSize = LOSCFG_BASE_CORE_TSK_MIN_STACK_SIZE; + + (void)LOS_TaskCreate(&taskID, &taskInitParam); +} + +int pthread_join(pthread_t thread, void **retval) +{ + UINT32 taskStatus; + + if (!IsPthread(thread)) { + return EINVAL; + } + + if (retval) { + /* retrieve thread exit code is not supported currently */ + return ENOTSUP; + } + + if (thread == pthread_self()) { + return EDEADLK; + } + + while (LOS_TaskStatusGet((UINT32)thread, &taskStatus) == LOS_OK) { + usleep(10000); + } + + CleanupTaskResource(); + return 0; +} + +int pthread_detach(pthread_t thread) +{ + if (!IsPthread(thread)) { + return EINVAL; + } + + return ENOSYS; +} + +void pthread_exit(void *retVal) +{ + (void)retVal; + (void)LOS_TaskDelete(LOS_CurTaskIDGet()); +} + +int pthread_setname_np(pthread_t thread, const char *name) +{ + char *taskName = LOS_TaskNameGet((UINT32)thread); + if (taskName == NULL || !IsPthread(thread)) { + return EINVAL; + } + if (strnlen(name, PTHREAD_NAMELEN) >= PTHREAD_NAMELEN) { + return ERANGE; + } + if (strcpy_s(taskName, PTHREAD_NAMELEN, name) != 0) { + return ERANGE; + } + return 0; +} + +int pthread_getname_np(pthread_t thread, char *buf, size_t buflen) +{ + int ret; + + const char *name = LOS_TaskNameGet((UINT32)thread); + if (name == NULL || !IsPthread(thread)) { + return EINVAL; + } + if (buflen > strlen(name)) { + ret = strcpy_s(buf, buflen, name); + if (ret == 0) { + return 0; + } + } + return ERANGE; +} diff --git a/hi3861_adapter/kal/posix/src/pthread_attr.c b/hi3861_adapter/kal/posix/src/pthread_attr.c new file mode 100644 index 0000000000000000000000000000000000000000..9fdbcebe2cd4211d775b7f539452b22361698bba --- /dev/null +++ b/hi3861_adapter/kal/posix/src/pthread_attr.c @@ -0,0 +1,232 @@ +/* + * Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include + +int pthread_attr_init(pthread_attr_t *attr) +{ + if (attr == NULL) { + return EINVAL; + } + + attr->detachstate = PTHREAD_CREATE_JOINABLE; + attr->schedpolicy = SCHED_RR; + attr->schedparam.sched_priority = LOSCFG_BASE_CORE_TSK_DEFAULT_PRIO; + attr->inheritsched = PTHREAD_INHERIT_SCHED; + attr->scope = PTHREAD_SCOPE_PROCESS; + attr->stackaddr_set = 0; + attr->stackaddr = NULL; + attr->stacksize_set = 1; + attr->stacksize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; + + return 0; +} + +int pthread_attr_destroy(pthread_attr_t *attr) +{ + if (attr == NULL) { + return EINVAL; + } + + /* Nothing to do here... */ + return 0; +} + +int pthread_attr_setdetachstate(pthread_attr_t *attr, int detachState) +{ + if ((attr != NULL) && ((detachState == PTHREAD_CREATE_JOINABLE) || (detachState == PTHREAD_CREATE_DETACHED))) { + attr->detachstate = (UINT32)detachState; + return 0; + } + + return EINVAL; +} + +int pthread_attr_getdetachstate(const pthread_attr_t *attr, int *detachState) +{ + if ((attr == NULL) || (detachState == NULL)) { + return EINVAL; + } + + *detachState = (int)attr->detachstate; + + return 0; +} + +int pthread_attr_setscope(pthread_attr_t *attr, int scope) +{ + if (attr == NULL) { + return EINVAL; + } + + if (scope == PTHREAD_SCOPE_PROCESS) { + attr->scope = (unsigned int)scope; + return 0; + } + + if (scope == PTHREAD_SCOPE_SYSTEM) { + return ENOTSUP; + } + + return EINVAL; +} + +int pthread_attr_getscope(const pthread_attr_t *attr, int *scope) +{ + if ((attr == NULL) || (scope == NULL)) { + return EINVAL; + } + + *scope = (int)attr->scope; + + return 0; +} + +int pthread_attr_setinheritsched(pthread_attr_t *attr, int inherit) +{ + if ((attr != NULL) && ((inherit == PTHREAD_INHERIT_SCHED) || (inherit == PTHREAD_EXPLICIT_SCHED))) { + attr->inheritsched = (UINT32)inherit; + return 0; + } + + return EINVAL; +} + +int pthread_attr_getinheritsched(const pthread_attr_t *attr, int *inherit) +{ + if ((attr == NULL) || (inherit == NULL)) { + return EINVAL; + } + + *inherit = (int)attr->inheritsched; + + return 0; +} + +int pthread_attr_setschedpolicy(pthread_attr_t *attr, int policy) +{ + if ((attr != NULL) && (policy == SCHED_RR)) { + attr->schedpolicy = SCHED_RR; + return 0; + } + + return EINVAL; +} + +int pthread_attr_getschedpolicy(const pthread_attr_t *attr, int *policy) +{ + if ((attr == NULL) || (policy == NULL)) { + return EINVAL; + } + + *policy = (int)attr->schedpolicy; + + return 0; +} + +int pthread_attr_setschedparam(pthread_attr_t *attr, const struct sched_param *param) +{ + if ((attr == NULL) || (param == NULL)) { + return EINVAL; + } else if ((param->sched_priority < OS_TASK_PRIORITY_HIGHEST) || + (param->sched_priority >= OS_TASK_PRIORITY_LOWEST)) { + return ENOTSUP; + } + + attr->schedparam = *param; + + return 0; +} + +int pthread_attr_getschedparam(const pthread_attr_t *attr, struct sched_param *param) +{ + if ((attr == NULL) || (param == NULL)) { + return EINVAL; + } + + *param = attr->schedparam; + + return 0; +} + +/* + * Set starting address of stack. Whether this is at the start or end of + * the memory block allocated for the stack depends on whether the stack + * grows up or down. + */ +int pthread_attr_setstackaddr(pthread_attr_t *attr, void *stackAddr) +{ + if (attr == NULL) { + return EINVAL; + } + + attr->stackaddr_set = 1; + attr->stackaddr = stackAddr; + + return 0; +} + +int pthread_attr_getstackaddr(const pthread_attr_t *attr, void **stackAddr) +{ + if (((attr != NULL) && (stackAddr != NULL)) && attr->stackaddr_set) { + *stackAddr = attr->stackaddr; + return 0; + } + + return EINVAL; /* Stack address not set, return EINVAL. */ +} + +int pthread_attr_setstacksize(pthread_attr_t *attr, size_t stackSize) +{ + /* Reject inadequate stack sizes */ + if ((attr == NULL) || (stackSize < PTHREAD_STACK_MIN)) { + return EINVAL; + } + + attr->stacksize_set = 1; + attr->stacksize = stackSize; + + return 0; +} + +int pthread_attr_getstacksize(const pthread_attr_t *attr, size_t *stackSize) +{ + /* Reject attempts to get a stack size when one has not been set. */ + if ((attr == NULL) || (stackSize == NULL) || (!attr->stacksize_set)) { + return EINVAL; + } + + *stackSize = attr->stacksize; + + return 0; +} diff --git a/hi3861_adapter/kal/posix/src/time.c b/hi3861_adapter/kal/posix/src/time.c new file mode 100644 index 0000000000000000000000000000000000000000..4b5a43d8cec88d4292f9a41d29411026452f9186 --- /dev/null +++ b/hi3861_adapter/kal/posix/src/time.c @@ -0,0 +1,274 @@ +/* + * Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include +#include +#include +#include +#include + +#ifndef STATIC +#define STATIC static +#endif + +#define OS_SYS_NS_PER_US 1000 +#define OS_SYS_NS_PER_SECOND 1000000000 +#define OS_SYS_US_PER_SECOND 1000000 +#define OS_SYS_MS_PER_SECOND 1000 + +STATIC INLINE BOOL ValidTimerID(UINT16 swtmrID) +{ + /* check timer id */ + return (swtmrID < LOSCFG_BASE_CORE_SWTMR_LIMIT); +} + +/* internal functions */ +STATIC INLINE BOOL ValidTimeSpec(const struct timespec *tp) +{ + /* Fail a NULL pointer */ + if (tp == NULL) { + return FALSE; + } + + /* Fail illegal nanosecond values */ + if ((tp->tv_nsec < 0) || (tp->tv_nsec >= OS_SYS_NS_PER_SECOND) || (tp->tv_sec < 0)) { + return FALSE; + } + + return TRUE; +} + +STATIC INLINE UINT32 OsTimeSpec2Tick(const struct timespec *tp) +{ + UINT64 tick, ns; + + ns = (UINT64)tp->tv_sec * OS_SYS_NS_PER_SECOND + tp->tv_nsec; + /* Round up for ticks */ + tick = (ns * LOSCFG_BASE_CORE_TICK_PER_SECOND + (OS_SYS_NS_PER_SECOND - 1)) / OS_SYS_NS_PER_SECOND; + if (tick > LOS_WAIT_FOREVER) { + tick = LOS_WAIT_FOREVER; + } + return (UINT32)tick; +} + +STATIC INLINE VOID OsTick2TimeSpec(struct timespec *tp, UINT32 tick) +{ + UINT64 ns = ((UINT64)tick * OS_SYS_NS_PER_SECOND) / LOSCFG_BASE_CORE_TICK_PER_SECOND; + tp->tv_sec = (time_t)(ns / OS_SYS_NS_PER_SECOND); + tp->tv_nsec = (long)(ns % OS_SYS_NS_PER_SECOND); +} + +int nanosleep(const struct timespec *rqtp, struct timespec *rmtp) +{ + UINT64 nseconds; + UINT64 tick; + UINT32 ret; + const UINT32 nsPerTick = OS_SYS_NS_PER_SECOND / LOSCFG_BASE_CORE_TICK_PER_SECOND; + + if (!ValidTimeSpec(rqtp)) { + errno = EINVAL; + return -1; + } + + nseconds = (UINT64)rqtp->tv_sec * OS_SYS_NS_PER_SECOND + rqtp->tv_nsec; + + tick = (nseconds + nsPerTick - 1) / nsPerTick; // Round up for ticks + + if (tick >= UINT32_MAX) { + errno = EINVAL; + return -1; + } + + /* PS: skip the first tick because it is NOT a full tick. */ + ret = LOS_TaskDelay(tick ? (UINT32)(tick + 1) : 0); + if (ret == LOS_OK || ret == LOS_ERRNO_TSK_YIELD_NOT_ENOUGH_TASK) { + if (rmtp) { + rmtp->tv_sec = rmtp->tv_nsec = 0; + } + return 0; + } + + /* sleep in interrupt context or in task sched lock state */ + errno = EPERM; + return -1; +} + +int timer_create(clockid_t clockID, struct sigevent *restrict evp, timer_t *restrict timerID) +{ + UINT32 ret; + UINT16 swtmrID; + + if (!timerID || (clockID != CLOCK_REALTIME)) { + errno = EINVAL; + return -1; + } + + if (!evp || evp->sigev_notify != SIGEV_THREAD || evp->sigev_notify_attributes) { + errno = ENOTSUP; + return -1; + } + + ret = LOS_SwtmrCreate(1, LOS_SWTMR_MODE_ONCE, (SWTMR_PROC_FUNC)evp->sigev_notify_function, + &swtmrID, (UINT32)(UINTPTR)evp->sigev_value.sival_ptr); + if (ret != LOS_OK) { + errno = (ret == LOS_ERRNO_SWTMR_MAXSIZE) ? EAGAIN : EINVAL; + return -1; + } + + *timerID = (timer_t)(UINTPTR)swtmrID; + return 0; +} + +int timer_delete(timer_t timerID) +{ + UINT16 swtmrID = (UINT16)(UINTPTR)timerID; + + if (!ValidTimerID(swtmrID)) { + errno = EINVAL; + return -1; + } + + if (LOS_SwtmrDelete(swtmrID) != LOS_OK) { + errno = EINVAL; + return -1; + } + + return 0; +} + +int timer_settime(timer_t timerID, int flags, + const struct itimerspec *restrict value, + struct itimerspec *restrict oldValue) +{ + UINT16 swtmrID = (UINT16)(UINTPTR)timerID; + SWTMR_CTRL_S *swtmr = NULL; + UINT32 interval, expiry, ret; + + if (flags != 0) { + /* flags not supported currently */ + errno = ENOSYS; + return -1; + } + + if (value == NULL || !ValidTimerID(swtmrID)) { + errno = EINVAL; + return -1; + } + + if (!ValidTimeSpec(&value->it_value) || !ValidTimeSpec(&value->it_interval)) { + errno = EINVAL; + return -1; + } + + expiry = OsTimeSpec2Tick(&value->it_value); + interval = OsTimeSpec2Tick(&value->it_interval); + + /* if specified interval, it must be same with expiry due to the limitation of liteos-m */ + if (interval && interval != expiry) { + errno = ENOTSUP; + return -1; + } + + if (oldValue) { + (VOID)timer_gettime(timerID, oldValue); + } + + ret = LOS_SwtmrStop(swtmrID); + if ((ret != LOS_OK) && (ret != LOS_ERRNO_SWTMR_NOT_STARTED)) { + errno = EINVAL; + return -1; + } + + swtmr = OS_SWT_FROM_SID(swtmrID); + ret = LOS_SwtmrModify(swtmrID, expiry, (interval ? LOS_SWTMR_MODE_PERIOD : LOS_SWTMR_MODE_NO_SELFDELETE), + swtmr->pfnHandler, swtmr->uwArg); + if (ret != LOS_OK) { + errno = EINVAL; + return -1; + } + + if ((value->it_value.tv_sec == 0) && (value->it_value.tv_nsec == 0)) { + /* + * 1) when expiry is 0, means timer should be stopped. + * 2) If timer is ticking, stopping timer is already done before. + * 3) If timer is created but not ticking, return 0 as well. + */ + return 0; + } + + if (LOS_SwtmrStart(swtmr->usTimerID) != LOS_OK) { + errno = EINVAL; + return -1; + } + + return 0; +} + +int timer_gettime(timer_t timerID, struct itimerspec *value) +{ + UINT32 tick = 0; + SWTMR_CTRL_S *swtmr = NULL; + UINT16 swtmrID = (UINT16)(UINTPTR)timerID; + UINT32 ret; + + if ((value == NULL) || !ValidTimerID(swtmrID)) { + errno = EINVAL; + return -1; + } + + swtmr = OS_SWT_FROM_SID(swtmrID); + + /* get expire time */ + ret = LOS_SwtmrTimeGet(swtmr->usTimerID, &tick); + if ((ret != LOS_OK) && (ret != LOS_ERRNO_SWTMR_NOT_STARTED)) { + errno = EINVAL; + return -1; + } + + OsTick2TimeSpec(&value->it_value, tick); + OsTick2TimeSpec(&value->it_interval, (swtmr->ucMode == LOS_SWTMR_MODE_ONCE) ? 0 : swtmr->uwInterval); + return 0; +} + +int timer_getoverrun(timer_t timerID) +{ + UINT16 swtmrID = (UINT16)(UINTPTR)timerID; + + if (!ValidTimerID(swtmrID)) { + errno = EINVAL; + return -1; + } + + errno = ENOSYS; + return -1; +} diff --git a/interfaces/BUILD.gn b/interfaces/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..177ab783118ea0d1deecc07e45134ba1c637c056 --- /dev/null +++ b/interfaces/BUILD.gn @@ -0,0 +1,29 @@ +# Copyright (c) 2021 Itcast Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/lite/ndk/ndk.gni") + +group("genkipi_interfaces") { + deps = [ + "$ohos_board_adapter_dir/hals/interfaces:hal_genkipi_interfaces", + ] +} + +if (ohos_kernel_type == "liteos_m") { + ndk_lib("genkipi_interfaces_ndk") { + deps = [ + "$ohos_board_adapter_dir/hals/interfaces:hal_genkipi_interfaces", + ] + head_files = [ "//device/itcast/genkipi/interfaces/kits" ] + } +} diff --git a/interfaces/kits/genki_led.h b/interfaces/kits/genki_led.h new file mode 100644 index 0000000000000000000000000000000000000000..bab4596cfc7f7ef61458451764a69afbe5d58cbf --- /dev/null +++ b/interfaces/kits/genki_led.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2021 Itcast., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef GENKI_LED_H +#define GENKI_LED_H + +#include + +void GenkiLedToggle(void); + +void GenkiLedState(unsigned char *state); + +void GenkiLedOpen(void); + +void GenkiLedClose(void); + +void GenkiLedPwmStart(unsigned short duty, unsigned int freq); + +void GenkiLedPwmStop(void); + +#endif //GENKI_LED_H diff --git a/interfaces/kits/genki_pin.h b/interfaces/kits/genki_pin.h new file mode 100644 index 0000000000000000000000000000000000000000..1adbe73b66cc8885834f83cfb2fd4340f97e594f --- /dev/null +++ b/interfaces/kits/genki_pin.h @@ -0,0 +1,390 @@ +/* + * Copyright (c) 2021 Itcast., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef GENKI_PIN_H +#define GENKI_PIN_H + +/** + * @brief Enumerates GPIO hardware pin IDs. + */ +typedef enum +{ + /** GPIO hardware pin 0 */ + IOT_IO_NAME_0, + /** GPIO hardware pin 1 */ + IOT_IO_NAME_1, + /** GPIO hardware pin 2 */ + IOT_IO_NAME_2, + /** GPIO hardware pin 3 */ + IOT_IO_NAME_3, + /** GPIO hardware pin 4 */ + IOT_IO_NAME_4, + /** GPIO hardware pin 5 */ + IOT_IO_NAME_5, + /** GPIO hardware pin 6 */ + IOT_IO_NAME_6, + /** GPIO hardware pin 7 */ + IOT_IO_NAME_7, + /** GPIO hardware pin 8 */ + IOT_IO_NAME_8, + /** GPIO hardware pin 9 */ + IOT_IO_NAME_9, + /** GPIO hardware pin 10 */ + IOT_IO_NAME_10, + /** GPIO hardware pin 11 */ + IOT_IO_NAME_11, + /** GPIO hardware pin 12 */ + IOT_IO_NAME_12, + /** GPIO hardware pin 13 */ + IOT_IO_NAME_13, + /** GPIO hardware pin 14 */ + IOT_IO_NAME_14, + /**< SFC_CSN */ + IOT_IO_NAME_SFC_CSN, + /**< SFC_IO1 */ + IOT_IO_NAME_SFC_IO1, + /**< SFC_IO2 */ + IOT_IO_NAME_SFC_IO2, + /**< SFC_IO0 */ + IOT_IO_NAME_SFC_IO0, + /**< SFC_CLK */ + IOT_IO_NAME_SFC_CLK, + /**< SFC_IO3 */ + IOT_IO_NAME_SFC_IO3, + /** Maximum value */ + IOT_IO_NAME_MAX, +} IoTIoName; + +/** + * @brief Enumerates the functions of GPIO hardware pin 0. + */ +typedef enum +{ + /** GPIO0 function */ + IOT_IO_FUNC_0_GPIO, + /** Functions of UART1 TXD */ + IOT_IO_FUNC_0_UART1_TXD = 2, + /** SPI1 CK function */ + IOT_IO_FUNC_0_SPI1_CK, + /** Functions of JTAG TD0 */ + IOT_IO_FUNC_0_JTAG_TDO, + /** PWM3 OUT function */ + IOT_IO_FUNC_0_PWM3_OUT, + /** I2C1 SDA function */ + IOT_IO_FUNC_0_I2C1_SDA, +} IoTIoFunc0; + +/** + * @brief Enumerates the functions of GPIO hardware pin 1. + */ +typedef enum +{ + /** GPIO1 function */ + IOT_IO_FUNC_1_GPIO, + IOT_IO_FUNC_1_UART1_RXD = 2, + IOT_IO_FUNC_1_SPI1_RXD, + IOT_IO_FUNC_1_JTAG_TCK, + IOT_IO_FUNC_1_PWM4_OUT, + IOT_IO_FUNC_1_I2C1_SCL, + IOT_IO_FUNC_1_BT_FREQ, +} IoTIoFunc1; + +/** + * @brief Enumerates the functions of GPIO hardware pin 2. + */ +typedef enum +{ + /** GPIO2 function */ + IOT_IO_FUNC_2_GPIO, + /** UART1 RTS function */ + IOT_IO_FUNC_2_UART1_RTS_N = 2, + /** SPI1 TXD function */ + IOT_IO_FUNC_2_SPI1_TXD, + /** JTAG TRSTN function */ + IOT_IO_FUNC_2_JTAG_TRSTN, + /** PWM2 OUT function */ + IOT_IO_FUNC_2_PWM2_OUT, + /** SSI CLK function */ + IOT_IO_FUNC_2_SSI_CLK = 7, +} IoTIoFunc2; + +/** + * @brief Enumerates the functions of GPIO hardware pin 3. + */ +typedef enum +{ + /** GPIO3 function */ + IOT_IO_FUNC_3_GPIO, + /** UART0 TXD function */ + IOT_IO_FUNC_3_UART0_TXD, + /** UART1 CTS function */ + IOT_IO_FUNC_3_UART1_CTS_N, + /** SPI CSN function */ + IOT_IO_FUNC_3_SPI1_CSN, + /** JTAG TDI function */ + IOT_IO_FUNC_3_JTAG_TDI, + /** PWM5 OUT function */ + IOT_IO_FUNC_3_PWM5_OUT, + /** I2C1 SDA function */ + IOT_IO_FUNC_3_I2C1_SDA, + /** SSI DATA function */ + IOT_IO_FUNC_3_SSI_DATA, +} IoTIoFunc3; + +/** + * @brief Enumerates the functions of GPIO hardware pin 4. + */ +typedef enum +{ + /** GPIO4 function */ + IOT_IO_FUNC_4_GPIO, + /** UART0 RXD function */ + IOT_IO_FUNC_4_UART0_RXD = 2, + /** JTAG TMS function */ + IOT_IO_FUNC_4_JTAG_TMS = 4, + /** PWM1 OUT function */ + IOT_IO_FUNC_4_PWM1_OUT, + /** I2C1 SCL function */ + IOT_IO_FUNC_4_I2C1_SCL, +} IoTIoFunc4; + +/** + * @brief Enumerates the functions of GPIO hardware pin 5. + */ +typedef enum +{ + /** GPIO5 function */ + IOT_IO_FUNC_5_GPIO, + /** UART1 RXD function */ + IOT_IO_FUNC_5_UART1_RXD = 2, + /** SPI0 CSN function */ + IOT_IO_FUNC_5_SPI0_CSN, + /** PWM2 OUT function */ + IOT_IO_FUNC_5_PWM2_OUT = 5, + /** I2C0 MCLK function */ + IOT_IO_FUNC_5_I2S0_MCLK, + /** BT STATUS function */ + IOT_IO_FUNC_5_BT_STATUS, +} IoTIoFunc5; + +/** + * @brief Enumerates the functions of GPIO hardware pin 6. + */ +typedef enum +{ + /** GPIO6 function */ + IOT_IO_FUNC_6_GPIO, + /** UART1 TXD function */ + IOT_IO_FUNC_6_UART1_TXD = 2, + /** SPI0 CK function */ + IOT_IO_FUNC_6_SPI0_CK, + /** PWM3 OUT function */ + IOT_IO_FUNC_6_PWM3_OUT = 5, + /** I2S0 TX function */ + IOT_IO_FUNC_6_I2S0_TX, + /** COEX switch function */ + IOT_IO_FUNC_6_COEX_SWITCH, +} IoTIoFunc6; + +/** + * @brief Enumerates the functions of GPIO hardware pin 7. + */ +typedef enum +{ + /** GPIO7 function */ + IOT_IO_FUNC_7_GPIO, + /** UART1 CTS function */ + IOT_IO_FUNC_7_UART1_CTS_N = 2, + /** SPI0 RXD function */ + IOT_IO_FUNC_7_SPI0_RXD, + /** PWM0 OUT function */ + IOT_IO_FUNC_7_PWM0_OUT = 5, + /** I2S0 BCLK function */ + IOT_IO_FUNC_7_I2S0_BCLK, + /** BT ACTIVE function */ + IOT_IO_FUNC_7_BT_ACTIVE, +} IoTIoFunc7; + +/** + * @brief Enumerates the functions of GPIO hardware pin 8. + */ +typedef enum +{ + /** GPIO8 function */ + IOT_IO_FUNC_8_GPIO, + /** UART1 RTS function */ + IOT_IO_FUNC_8_UART1_RTS_N = 2, + /** SPI0 TXD function */ + IOT_IO_FUNC_8_SPI0_TXD, + /** PWM1 OUT function */ + IOT_IO_FUNC_8_PWM1_OUT = 5, + /** I2S0 WS function */ + IOT_IO_FUNC_8_I2S0_WS, + /** WLAN ACTIVE function */ + IOT_IO_FUNC_8_WLAN_ACTIVE, +} IoTIoFunc8; + +/** + * @brief Enumerates the functions of GPIO hardware pin 10. + */ +typedef enum +{ + /** GPIO10 function */ + IOT_IO_FUNC_9_GPIO, + /** I2C0 SCL function */ + IOT_IO_FUNC_9_I2C0_SCL, + /** UART2 RTS function */ + IOT_IO_FUNC_9_UART2_RTS_N, + /** SDIO D2 function */ + IOT_IO_FUNC_9_SDIO_D2, + /** SPI0 TXD function */ + IOT_IO_FUNC_9_SPI0_TXD, + /** PWM0 OUT function */ + IOT_IO_FUNC_9_PWM0_OUT, + /** I2S0 MCLK function */ + IOT_IO_FUNC_9_I2S0_MCLK = 7, +} IoTIoFunc9; + +/** + * @brief Enumerates the functions of GPIO hardware pin 9. + */ +typedef enum +{ + /** GPIO9 function */ + IOT_IO_FUNC_10_GPIO, + /** I2C0 SDA function */ + IOT_IO_FUNC_10_I2C0_SDA, + /** UART2 CTS function */ + IOT_IO_FUNC_10_UART2_CTS_N, + /** SDIO D3 function */ + IOT_IO_FUNC_10_SDIO_D3, + /** SPI0 CK function */ + IOT_IO_FUNC_10_SPI0_CK, + /** PWM1 OUT function */ + IOT_IO_FUNC_10_PWM1_OUT, + /** I2S0 TX function */ + IOT_IO_FUNC_10_I2S0_TX = 7, +} IoTIoFunc10; + +/** + * @brief Enumerates the functions of GPIO hardware pin 11. + */ +typedef enum +{ + /** GPIO11 function */ + IOT_IO_FUNC_11_GPIO, + /** UART2 TXD function */ + IOT_IO_FUNC_11_UART2_TXD = 2, + /** SDIO CMD function */ + IOT_IO_FUNC_11_SDIO_CMD, + /** SDIO RXD function */ + IOT_IO_FUNC_11_SPI0_RXD, + /** PWM2 OUT function */ + IOT_IO_FUNC_11_PWM2_OUT, + /** RF TX_EN_EXT function */ + IOT_IO_FUNC_11_RF_TX_EN_EXT, + /** I2S0 RX function */ + IOT_IO_FUNC_11_I2S0_RX, +} IoTIoFunc11; + +/** + * @brief Enumerates the functions of GPIO hardware pin 12. + */ +typedef enum +{ + /** GPIO12 function */ + IOT_IO_FUNC_12_GPIO, + /** SUART2 RXD function */ + IOT_IO_FUNC_12_UART2_RXD = 2, + /** SDIO CLK function */ + IOT_IO_FUNC_12_SDIO_CLK, + /** SDIO CSN function */ + IOT_IO_FUNC_12_SPI0_CSN, + /** PWM3 OUT function */ + IOT_IO_FUNC_12_PWM3_OUT, + /** RF RX_EN_EXT function */ + IOT_IO_FUNC_12_RF_RX_EN_EXT, + /** I2S0 BCLK function */ + IOT_IO_FUNC_12_I2S0_BCLK, +} IoTIoFunc12; + +/** + * @brief Enumerates the functions of GPIO hardware pin 13. + */ +typedef enum +{ + /** SSI DATA function */ + IOT_IO_FUNC_13_SSI_DATA, + /** UART0 TXD function */ + IOT_IO_FUNC_13_UART0_TXD, + /** UART2 RTS function */ + IOT_IO_FUNC_13_UART2_RTS_N, + /** SDIO D0 function */ + IOT_IO_FUNC_13_SDIO_D0, + /** GPIO13 function */ + IOT_IO_FUNC_13_GPIO, + /** PWM4 OUT function */ + IOT_IO_FUNC_13_PWM4_OUT, + /** I2C0 SDA function */ + IOT_IO_FUNC_13_I2C0_SDA, + /** I2S0 WS function */ + IOT_IO_FUNC_13_I2S0_WS, +} IoTIoFunc13; + +/** + * @brief Enumerates the functions of GPIO hardware pin 14. + */ +typedef enum +{ + /** SSI CLK function */ + IOT_IO_FUNC_14_SSI_CLK, + /** UART0 RXD function */ + IOT_IO_FUNC_14_UART0_RXD, + /** UART2 CTS function */ + IOT_IO_FUNC_14_UART2_CTS_N, + /** SDIO D1 function */ + IOT_IO_FUNC_14_SDIO_D1, + /** GPIO14 function */ + IOT_IO_FUNC_14_GPIO, + /** PWM5 OUT function */ + IOT_IO_FUNC_14_PWM5_OUT, + /** I2C0 SCL function */ + IOT_IO_FUNC_14_I2C0_SCL, +} IoTIoFunc14; + + +/** +* @brief Enumerotes PWM Hardware port IDS +*/ +typedef enum +{ + /** PWM hardware port 0 */ + IOT_PWM_NAME_0, + /** PWM hardware port 1 */ + IOT_PWM_NAME_1, + /** PWM hardware port 2 */ + IOT_PWM_NAME_2, + /** PWM hardware port 3 */ + IOT_PWM_NAME_3, + /** PWM hardware port 4 */ + IOT_PWM_NAME_4, + /** PWM hardware port 5 */ + IOT_PWM_NAME_5, + /** Maximum value */ + IOT_PWM_NAME_MAX, +} IoTPwmName; + + +#endif //GENKI_PIN_H diff --git a/interfaces/kits/genki_wifi_sta.h b/interfaces/kits/genki_wifi_sta.h new file mode 100644 index 0000000000000000000000000000000000000000..bc15e809b35f398d5b1ed3d1aca554a4faac33e6 --- /dev/null +++ b/interfaces/kits/genki_wifi_sta.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2021 Itcast., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef GENKIPI_GENKI_WIFI_STA_H +#define GENKIPI_GENKI_WIFI_STA_H + +/** + * link wifi + * @param ssid + * @param password + * @param hostname + * @return 0 failed 1 success + */ +int connect_wifi(const char* ssid, const char* password, const char* hostname); +/** + * disconnect wifi + * @return 0 failed 1 success + */ +int disconnect_wifi(void); + +/** + * get wifi addr + * @param ip + * @param netmask + * @param gateway + * @return + */ +int get_wifi_addr(unsigned int *ip, unsigned int *netmask, unsigned int *gateway); + +#endif //GENKIPI_GENKI_WIFI_STA_H diff --git a/sdk_liteos/.sconsign.dblite b/sdk_liteos/.sconsign.dblite new file mode 100644 index 0000000000000000000000000000000000000000..2f76e6e581d39b95239d1618c6d3134f4f6f2c84 Binary files /dev/null and b/sdk_liteos/.sconsign.dblite differ diff --git a/sdk_liteos/3rd_sdk/demolink/libs/.gitignore b/sdk_liteos/3rd_sdk/demolink/libs/.gitignore new file mode 100755 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/sdk_liteos/BUILD.gn b/sdk_liteos/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..cb60b8a5d2b2f02ae32313b92291d0dccdd055c8 --- /dev/null +++ b/sdk_liteos/BUILD.gn @@ -0,0 +1,46 @@ +# Copyright (c) 2021 Itcast Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/lite/config/component/lite_component.gni") +import("//build/lite/config/subsystem/lite_subsystem.gni") + +declare_args() { + enable_hos_vendor_wifiiot_xts = false +} + +lite_subsystem("wifiiot_sdk") { + subsystem_components = [ ":sdk" ] +} + +build_ext_component("run_wifiiot_scons") { + exec_path = rebase_path(".", root_build_dir) + outdir = rebase_path(root_out_dir) + command = "sh hm_build.sh $outdir" + deps = [ + ":sdk", + "//base/security/deviceauth/frameworks/deviceauth_lite:hichainsdk", + "//build/lite:ohos", + ] + if (enable_hos_vendor_wifiiot_xts) { + deps += [ "//build/lite/config/subsystem/xts:xts" ] + } +} + +lite_component("sdk") { + features = [] + + deps = [ + "//build/lite/config/component/cJSON:cjson_static", + "//device/itcast/genkipi/hi3861_adapter/kal", + ] +} diff --git a/sdk_liteos/Makefile b/sdk_liteos/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..a1c2fd2a7ffe6f0ad86fbc8c63b107d1af2243b0 --- /dev/null +++ b/sdk_liteos/Makefile @@ -0,0 +1,31 @@ +# Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +MAIN_TOPDIR = $(shell pwd) +export MAIN_TOPDIR + +all: + $(MAKE) -f non_factory.mk all + +clean: + $(MAKE) -f non_factory.mk clean + +all_clean: + $(MAKE) -f non_factory.mk all_clean + +factory: + $(MAKE) -f factory.mk all + +clean_factory: + $(MAKE) -f factory.mk clean + diff --git a/sdk_liteos/README.md b/sdk_liteos/README.md new file mode 100755 index 0000000000000000000000000000000000000000..c1d842a1aabf0b74eb9c64049e694996af6c58ca --- /dev/null +++ b/sdk_liteos/README.md @@ -0,0 +1,179 @@ +# Hi3861V100介绍 + +## 简介 + +Hi3861V100是一款高度集成的2.4GHz WiFi SoC芯片,集成IEEE 802.11b/g/n基带和RF电路,RF电路包括功率放大器PA、低 噪声放大器LNA、RF balun、天线开关以及电源管理等模块;支持20MHz标准带宽和5MHz/10MHz窄带宽,提供最大72.2Mbit/s 物理层速率。 Hi3861V100 WiFi基带支持正交频分复用(OFDM)技术,并向下兼容直接序列扩频(DSSS)和补码键控(CCK)技术,支 持IEEE 802.11 b/g/n协议的各种数据速率。 Hi3861V100芯片集成高性能32bit微处理器、硬件安全引擎以及丰富的外设接口,外设接口包括SPI、UART、I2C、PWM、 GPIO和多路ADC,同时支持高速SDIO2.0 Slave接口,最高时钟可达50MHz;芯片内置SRAM和Flash,可独立运行,并支持 在Flash上运行程序。 Hi3861V100芯片适应于智能家电等物联网智能终端领域。 + +## 架构 + +上海海思Hi3861系列的平台软件对应用层实现了底层屏蔽,并对应用软件直接提供API\(Application Programming Interface\)接口完成相应功能。典型的系统应用架构如下: + +**图 1** 系统应用框架图 + + +![](figures/zh-cn_image_0000001054797626.png) + +该框架可以分为以下几个层次: + +- APP层:即应用层。SDK提供的代码示例在SDK的代码目录:app\\demo\\src。 +- API层:提供基于SDK开发的通用接口。 +- Platform平台层:提供SOC系统板级支持包,包括如下功能: + - 芯片和外围器件驱动 + - 操作系统 + - 系统管理 + +- Service服务层:提供包含WiFi等应用协议栈。用于上层应用软件进行数据收发等操作。 +- 第三方库:提供给Service服务层或提供给应用层使用的第三方软件库。 + +## 特点 + +**稳定、可靠的通信能力** + +- 支持复杂环境下 TPC、自动速率、弱干扰免疫等可靠性通信算法 + +**灵活的组网能力** + +- 支持 256 节点 Mesh 组网 +- 支持标准 20M 带宽组网和 5M/10M 窄带组网 + +**完善的网络支持** + +- 支持 IPv4/IPv6 网络功能 +- 支持 DHCPv4/DHCPv6 Client/Server +- 支持 DNS Client 功能 +- 支持 mDNS 功能 +- 支持 CoAP/MQTT/HTTP/JSON 基础组件 + +**强大的安全引擎** + +- 硬件实现 AES128/256 加解密算法 +- 硬件实现 HASH-SHA256、HMAC\_SHA256 算法 +- 硬件实现 RSA、ECC 签名校验算法 +- 硬件实现真随机数生成,满足 FIPS140-2 随机测试标准 +- 硬件支持 TLS/DTLS 加速 +- 内部集成 EFUSE,支持安全存储、安全启动、硬件 ID +- 内部集成 MPU 特性,支持内存隔离特性 + +**开放的操作系统** + +- 丰富的低功耗、小内存、高稳定性、高实时性机制 +- 灵活的协议支撑和扩展能力 +- 二次开发接口 +- 多层级开发接口:操作系统适配接口和系统诊断接口、 链路层接口、网络层接口 + +## 目录 + +SDK根目录结构如下图所示: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

目录

+

说明

+

app

+

应用层代码(其中包含demo程序为参考示例)。

+

boot

+

Flash bootloader代码。

+

build

+

SDK构建所需的库文件、链接文件、配置文件。

+

config

+

SDK系统配置文件。

+

documents

+

文档目录(包括:SDK说明文档)。

+

include

+

API头文件存放目录。

+

license

+

SDK开源license声明

+

output

+

编译时生成的目标文件与中间文件(包括:库文件、打印log、生成的二进制文件等)。

+

platform

+

SDK平台相关的文件(包括:镜像、内核驱动模块等)。

+

third_party

+

开源第三方软件目录。

+

tools

+

SDK提供的Linux系统和Windows系统上使用的工具(包括:NV制作工具、签名工具、Menuconfig等)。

+

SConstruct

+

SCons编译脚本。

+

build.sh

+

启动编译脚本,同时支持“sh build.sh menuconfig”进行客制化配置。

+

build_patch.sh

+

解压开源源码包和patch文件编译脚本。

+

Makefile

+

支持makefile编译,使用“make”或“make all”启动编译。

+

non_factory.mk

+

非厂测版本编译脚本。

+

factory.mk

+

厂测版本编译脚本。

+

NOTICE

+

第三方软件开源声明

+
+ +## 许可协议 + +- Hi3861V100自研代码使用基于Apache License Version 2.0许可的hisi版权声明。许可信息和版权信息通常可以在代码开头看到: + +``` + / *Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED.Licensed under the Apache License,* ... * / +``` + +- Hi3861V100使用的第三方代码遵循软件版本自带的开源许可声明。 +- 将生成的库文件统一存放于根目录下的build/libs下。 +- 本软件中可能会使用一些开源软件组件。如果这些开源软件组件所适用的许可与本协议内容冲突,则以该开源软件组件的许可为准。 + diff --git a/sdk_liteos/SConstruct b/sdk_liteos/SConstruct new file mode 100644 index 0000000000000000000000000000000000000000..11216a5c4d461b28fd6d5390f39b878f6ec63001 --- /dev/null +++ b/sdk_liteos/SConstruct @@ -0,0 +1,556 @@ +#!/usr/bin/env python3 +# coding=utf-8 + +''' +* Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +* Description: SCons build system entry. +''' + +EnsureSConsVersion(3, 0, 1) +EnsurePythonVersion(3, 7) + +import os +import sys +import datetime +import atexit +from distutils import dir_util +sys.path.append(os.path.join(os.getcwd(), 'build')) +from scripts import common_env +from scripts import scons_utils +from scripts import scons_app +from scripts import scons_env_cfg +from scripts import pkt_builder +from scripts.packet_create import packet_bin +from tools.nvtool.build_nv import make_nv_bin +import shutil + +#Init compile parameters +env_cfg = scons_env_cfg.SconsEnvCfg() + +#Accept APP parameter +app_name = ARGUMENTS.get('app', 'demo') +factory_mode = ARGUMENTS.get('factory_mode', 'no') +app_builder = scons_app.AppTarget(app_name, factory_mode) +env_cfg.set_app_builder(app_builder) + +#Compile message output control +if common_env.log_output_flag == False: + current = datetime.datetime.now() + if not os.path.exists(os.path.dirname(env_cfg.log_path)) or not os.path.exists(env_cfg.log_path): + os.makedirs(env_cfg.log_path) + log_file = os.path.join(env_cfg.log_path,'scons_trace.log') + old_stdout = sys.stdout + file = open(log_file, 'w+') + file.write("Building at %s %s\n" % (current.strftime('%Y/%m/%d'), current.strftime('%H:%M:%S'))) + sys.stdout = file + +#Init environment +env = Environment(ENV={'PATH':os.environ['PATH']}, + TARGET_PREFIX=env_cfg.target_name,) + +env_cfg.set_tools(env) +env_cfg.set_environs(env) + +print('----------------------------top-----------------') +#libraries to be built +libs = [env.SConscript(os.path.join(env_cfg.get_module_dir(module), 'SConscript'), {'env':env, 'env_cfg':env_cfg, 'module':module}, + variant_dir=os.path.join(env_cfg.lib_path, env_cfg.get_module_dir(module)), duplicate=0) for module in env_cfg.get_build_modules()] +#Get settings +env['LIBPATH'] = env_cfg.get_lib_path() + +if scons_utils.scons_usr_bool_option('CONFIG_TARGET_CHIP_HI3861') == 'y': + if scons_utils.scons_usr_bool_option('CONFIG_DIAG_SUPPORT') == 'y': + if factory_mode == 'yes': + env.Append(LIBPATH=os.path.join('-Lbuild', 'libs', 'hi3861', 'debug', 'factory')) + elif scons_utils.scons_usr_bool_option('CONFIG_QUICK_SEND_MODE') == 'y': + env.Append(LIBPATH=os.path.join('-Lbuild', 'libs', 'hi3861', 'debug', 'no_mesh_quick_start')) + elif scons_utils.scons_usr_bool_option('CONFIG_MESH_SUPPORT') == 'y': + env.Append(LIBPATH=os.path.join('-Lbuild', 'libs', 'hi3861', 'debug', 'mesh')) + else: + env.Append(LIBPATH=os.path.join('-Lbuild', 'libs', 'hi3861', 'debug', 'no_mesh')) + else: + if factory_mode == 'yes': + env.Append(LIBPATH=os.path.join('-Lbuild', 'libs', 'hi3861', 'release', 'factory')) + elif scons_utils.scons_usr_bool_option('CONFIG_QUICK_SEND_MODE') == 'y': + env.Append(LIBPATH=os.path.join('-Lbuild', 'libs', 'hi3861', 'release', 'no_mesh_quick_start')) + elif scons_utils.scons_usr_bool_option('CONFIG_MESH_SUPPORT') == 'y': + env.Append(LIBPATH=os.path.join('-Lbuild', 'libs', 'hi3861', 'release', 'mesh')) + else: + env.Append(LIBPATH=os.path.join('-Lbuild', 'libs', 'hi3861', 'release', 'no_mesh')) +else: + if scons_utils.scons_usr_bool_option('CONFIG_DIAG_SUPPORT') == 'y': + if factory_mode == 'yes': + env.Append(LIBPATH=os.path.join('-Lbuild', 'libs', 'hi3861l', 'debug', 'factory')) + elif scons_utils.scons_get_cfg_val('CONFIG_CHIP_PKT_48K') == 'y': + env.Append(LIBPATH=os.path.join('-Lbuild', 'libs', 'hi3861l', 'debug', 'no_mesh_pkt_48k')) + elif scons_utils.scons_usr_bool_option('CONFIG_MESH_SUPPORT') == 'y': + env.Append(LIBPATH=os.path.join('-Lbuild', 'libs', 'hi3861l', 'debug', 'mesh')) + else: + env.Append(LIBPATH=os.path.join('-Lbuild', 'libs', 'hi3861l', 'debug', 'no_mesh')) + else: + if factory_mode == 'yes': + env.Append(LIBPATH=os.path.join('-Lbuild', 'libs', 'hi3861l', 'release', 'factory')) + elif scons_utils.scons_get_cfg_val('CONFIG_CHIP_PKT_48K') == 'y': + env.Append(LIBPATH=os.path.join('-Lbuild', 'libs', 'hi3861l', 'release', 'no_mesh_pkt_48k')) + elif scons_utils.scons_usr_bool_option('CONFIG_MESH_SUPPORT') == 'y': + env.Append(LIBPATH=os.path.join('-Lbuild', 'libs', 'hi3861l', 'release', 'mesh')) + else: + env.Append(LIBPATH=os.path.join('-Lbuild', 'libs', 'hi3861l', 'release', 'no_mesh')) + +env.Append(LIBPATH=app_builder.get_app_lib_path()) +## wifiiot_app is the only one app for ohos +if app_name != "wifiiot_app": + env['LIBS'] = list(map(lambda x:'-l%s'%x, env_cfg.get_libs())) +else: + env['LIBS'] = list(map(lambda x:'-l%s'%x, env_cfg.get_libs())) + ['--whole-archive'] + list(map(lambda x:'-l%s'%x, env_cfg.get_ohos_libs())) + ['--no-whole-archive'] +env.Append(LIBS = app_builder.get_app_libs()) +env.Append(LIBS = '-lwifi_flash') +env.Append(LIBS = '-lwifi') +env.Append(LIBS = '-llitekernel_flash') +env.Append(LIBS = '-lsystem') +if scons_utils.scons_usr_bool_option('CONFIG_MESH_SUPPORT') == 'y': + if factory_mode != 'yes': + env.Append(LIBS = '-lmeshautolink') +env['LIBS'] = sorted(env["LIBS"]) +env['LIBPATH'] = sorted(env["LIBPATH"]) +env['LINKFILE'] = env_cfg.link_file +env['MAPFILE'] = env_cfg.map_file +print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~libpath:',env['LIBPATH']) +print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~libs:',env['LIBS']) + +####################################################### LINK by Command ####################################################### + +# config by menuconfig +signature = { + 'RSA':{ + 0:0x0054d3c0, # factory startup addr:0x1E3000(HILINK_ADDR - 600K) = 0x14D000 + 'A':0x0040d3c0, + 'B':0x004f13c0, + }, + 'ECC':{ + 0:0x0054d3c0, # factory startup addr:0x1E3000(HILINK_ADDR - 600K) = 0x14D000 + 'A':0x0040d3c0, + 'B':0x004f13c0, + } +} + +link_env = env.Clone() + +"""Build link script +""" +linker_builder = Builder( + action='$CC $LINK_SCRIPTS_FLAG -E $SOURCE -o $TARGET -P', + src_suffix='.ld.S' +) + +"""Build elf file +""" +elf_builder = Builder( + action='$LINK $LINKFLAGS $LIBPATH -T$LINKFILE -Map=$MAPFILE -o $TARGET --start-group $LIBS --end-group',#--verbose + suffix='.out' +) + +"""Build binary from .out file +""" +binary_builder = Builder( + action='$OBJCOPY -O binary $SOURCE $TARGET', + suffix='.bin', + src_suffix='.out' +) + +"""Build asm file from binary +""" +asm_builder = Builder( + action='$OBJDUMP -d $SOURCE >$TARGET', + suffix='.asm', + src_suffix='.out' +) + +"""Base image builder +""" +def baseimg_builder(target, source, env): + base_bin_target = str(target[0]) + scons_utils.scons_bin_dd(str(source[0]), base_bin_target, seek=0, count=278) + env_cfg.base_bin_check(base_bin_target) + no_base_bin_target = str(target[1]) + scons_utils.scons_bin_dd(str(source[0]), no_base_bin_target, skip=278) + +"""NV image builder +""" +def nvimg_builder(target, source, env): + if os.path.exists(env_cfg.nv_path) is False: + os.makedirs(env_cfg.nv_path) + make_nv_bin(env_cfg.nv_path, env_cfg.target_name, env_cfg.nv_cfg_name) #genrate nv first + +"""Combine NV image and kernel +""" +def nvkernel_builder(target, source, env): + factory_nv = str(source[0]) + normal_nv = str(source[1]) + no_base_bin_target = str(source[2]) + nv_kernel_bin = str(target[0]) + scons_utils.scons_bin_dd(factory_nv, nv_kernel_bin, seek=0, bs=4096, count=1) + scons_utils.scons_bin_dd(normal_nv, nv_kernel_bin, seek=2, bs=4096, count=1) + scons_utils.scons_bin_dd(no_base_bin_target, nv_kernel_bin, seek=4, bs=4096) + +factory_nv = os.path.join(env_cfg.nv_path, env_cfg.nv_factory_name) +normal_nv = os.path.join(env_cfg.nv_path, env_cfg.nv_normal_name) +#Build flashboot +flash_boot_bin = env.SConscript(os.path.join('boot', 'flashboot', 'SConscript'), {'env':env, 'env_cfg':env_cfg, 'module':'boot'}, duplicate=0) +#Build loaderboot +loader_boot_bin = env.SConscript(os.path.join('boot', 'loaderboot', 'SConscript'), {'env':env, 'env_cfg':env_cfg, 'module':'loaderboot'}, duplicate=0) +#ota object +ota_flag = 1 if scons_utils.scons_usr_bool_option('CONFIG_COMPRESSION_OTA_SUPPORT') != 'y' else 0 +ota_build_object = pkt_builder.ImageBuild(env_cfg.target_name, ota_mode=ota_flag) +def init_ota_build_object(ota_build_object): + ota_build_object.set_pkt_path(env_cfg.bin_path) + ota_build_object.set_src_path(boot_bin_path=str(flash_boot_bin[0]), normal_nv_path=normal_nv, factory_nv_path=factory_nv) + ota_build_object.set_chip_product_name(env.get("CHIP_TYPE")) + +def get_ota_object(): + return ota_build_object + +def get_secure_boot(): + if (scons_utils.scons_usr_bool_option('CONFIG_TARGET_SIG_SHA256') == 'y'): + return False + else: + return True; + +def get_hilink_enable(): + if (scons_utils.scons_usr_bool_option('CONFIG_HILINK') == 'y'): + return True + else: + return False; + +def get_sign_dict(): + sig = '' + if scons_utils.scons_usr_bool_option('CONFIG_TARGET_SIG_RSA_V15') == 'y': + sig = 'RSA' + get_ota_object().set_sign_alg(0x0) + elif scons_utils.scons_usr_bool_option('CONFIG_TARGET_SIG_RSA_PSS') == 'y': + sig = 'RSA' + get_ota_object().set_sign_alg(0x1) + elif scons_utils.scons_usr_bool_option('CONFIG_TARGET_SIG_ECC') == 'y': + sig = 'ECC' + get_ota_object().set_sign_alg(0x10) + elif scons_utils.scons_usr_bool_option('CONFIG_TARGET_SIG_SHA256') == 'y': + sig = 'ECC' + get_ota_object().set_sign_alg(0x3F) + if sig not in signature: + raise scons_utils.SconsBuildError("%s============== <%s> SIGNATURE SETTING NULL =============%s"%(scons_utils.colors['red'], sig, scons_utils.colors['end'])) + return signature[sig] + +init_ota_build_object(ota_build_object) +sign_dict = get_sign_dict() #signature mode configuration + +def ota_builder(target, source, env): + """Build upg binary + """ + get_ota_object().set_encrypt_flag(0x42) + if scons_utils.scons_usr_bool_option('CONFIG_FLASH_ENCRYPT_SUPPORT') == 'y': + get_ota_object().set_file_attr_encrypt(0x2) + else: + get_ota_object().set_file_attr_encrypt(0x1) + if scons_utils.scons_usr_bool_option('CONFIG_COMPRESSION_OTA_SUPPORT') == 'y': + get_ota_object().set_kernel_file_attr_ota(0x4) + get_ota_object().set_kernel_max_size(0) #(912+972)KB + else: + get_ota_object().set_kernel_file_attr_ota(env['SIGN']) + get_ota_object().set_kernel_max_size(env['SIGN']) #912 or 972KB + if scons_utils.scons_usr_bool_option('CONFIG_FLASH_ENCRYPT_SUPPORT') == 'y': + get_ota_object().set_encrypt_flag(0xFF) + get_ota_object().set_src_path(kernel_bin_path=str(source[1])) + get_ota_object().BuildUpgBin(str(target[0])) + + return 0 + +def factory_builder(target, source, env): + """Build factory binary + """ + get_ota_object().set_encrypt_flag(0x42) + if scons_utils.scons_usr_bool_option('CONFIG_FLASH_ENCRYPT_SUPPORT') == 'y': + get_ota_object().set_file_attr_encrypt(0x2) + else: + get_ota_object().set_file_attr_encrypt(0x1) + get_ota_object().set_kernel_file_attr_ota('A') # same as kernel A. + get_ota_object().set_kernel_max_size(0x4) #0x4 means __factory_bin_max_size:600K + get_ota_object().set_src_path(kernel_bin_path=str(source[1])) + get_ota_object().BuildUpgBurnBin(str(target[0])) + + factory_bin_path = os.path.join('build', 'libs', 'factory_bin') + if not os.path.exists(factory_bin_path): + os.makedirs(factory_bin_path) + shutil.rmtree(factory_bin_path) + shutil.copytree(env_cfg.bin_path, factory_bin_path, False) #copy factory bin output to build/libs temply. + + return 0 + +def burn_bin_builder(target, source, env): + """Build binary + """ + get_ota_object().set_build_temp_path(build_temp_path = env_cfg.cache_path) + burn_bin = get_ota_object().BuildHiburnBin(str(target[0]), str(source[0])) + loader_bin = str(source[1]) + efuse_bin = str(source[2]) if len(source) == 3 else None + boot_b = os.path.join('output', 'bin', '%s_boot_signed_B.bin'%(env.get('CHIP_TYPE'))) + boot_b_size = os.path.getsize(boot_b) + factory_bin_path = os.path.join('build', 'libs', 'factory_bin') + factory_bin = os.path.join(factory_bin_path, '%s_factory.bin'%env_cfg.target_name) + burn_for_erase_bin = os.path.join('build', 'basebin', 'burn_for_erase_4k.bin') + #证书安全存储示例 + tee_cert1_file = os.path.join('build', 'basebin', 'tee_cert1.bin'); + tee_cert2_file = os.path.join('build', 'basebin', 'tee_cert2.bin'); + tee_key_file = os.path.join('build', 'basebin', 'tee_key.bin'); + tee_cert_key_bin_max = 12*1024; #必须为4KB证书倍,需匹配分区表确定烧写地址和大小 + tee_total_file_cnt = 3; #3个文件:2个证书,1个key。 + burn_tee_cert = False + if ((os.path.exists(tee_cert1_file)) and (os.path.exists(tee_cert2_file)) and (os.path.exists(tee_key_file))): + burn_tee_cert = True + + version_bin = bytearray(8) + boot_ver = get_ota_object().get_flashboot_file_ver() + kernel_ver = get_ota_object().get_kernel_file_ver() + boot_ver_bytes = boot_ver.to_bytes(4, byteorder = 'little', signed = True) + kernel_ver_bytes = kernel_ver.to_bytes(4, byteorder = 'little', signed = True) + version_bin[0:4] = boot_ver_bytes + version_bin[4:8] = kernel_ver_bytes + version_file = os.path.join("output", "bin", '%s_vercfg.bin'%env_cfg.target_name) + with open(version_file, 'wb+') as fp: + fp.write(version_bin) + + burn_bin_ease_size = 0x200000; + #根据分区表适配烧写地址和大小 + if (get_hilink_enable() == True): + burn_bin_ease_size = 0x200000 - 0x8000 - 0x1000 - 0x2000 + if (burn_tee_cert == True): + burn_bin_ease_size = 0x200000 - 0x8000 - 0x1000 - 0x2000 - 0x5000 + + if os.path.exists(factory_bin): + cmd_list = ['%s|0|0|0'%loader_bin, '%s|0|0|3'%efuse_bin, '%s|0|%d|1'%(burn_bin, burn_bin_ease_size), '%s|%d|%d|6'%(factory_bin, 0x14D000, 0x96000)] if efuse_bin!=None else ['%s|0|0|0'%loader_bin, '%s|0|%d|1'%(burn_bin, burn_bin_ease_size), '%s|%d|%d|6'%(factory_bin, 0x14D000, 0x96000),] + shutil.copytree(factory_bin_path, os.path.join(env_cfg.bin_path, 'factory_bin')) + else: + cmd_list = ['%s|0|0|0'%loader_bin, '%s|0|0|3'%efuse_bin, '%s|0|%d|1'%(burn_bin, burn_bin_ease_size)] if efuse_bin!=None else ['%s|0|0|0'%loader_bin, '%s|0|%d|1'%(burn_bin, burn_bin_ease_size)] + + if ((get_hilink_enable() == True) or (burn_tee_cert == True)): + cmd_list.append('%s|%d|%d|1'%(burn_for_erase_bin, 0x200000 - 0x8000 - 0x1000, 0x1000)) + + cmd_list.append('%s|%d|%d|1'%(boot_b, 0x200000 - boot_b_size, boot_b_size)); + + if (burn_tee_cert == True): + cert_key_bin = bytearray(tee_cert_key_bin_max) + tee_cert1_size = os.path.getsize(tee_cert1_file) + tee_cert2_size = os.path.getsize(tee_cert2_file) + tee_key_size = os.path.getsize(tee_key_file) + total_cert_key_size = tee_cert1_size + tee_cert2_size + tee_key_size + if (total_cert_key_size > tee_cert_key_bin_max - 4 - 4 - 4*tee_total_file_cnt): + print ("%s============== cert total len bigger than %d=============%s"%(scons_utils.colors['red'], total_cert_key_size,scons_utils.colors['end'])) + return -1 + else: + with open(tee_cert1_file, 'rb') as fp: + tee_cert1_bin = fp.read() + with open(tee_cert2_file, 'rb') as fp: + tee_cert2_bin = fp.read() + with open(tee_key_file, 'rb') as fp: + tee_key_bin = fp.read() + + #填充头部结构 + start_flag = 0xDEADBEEF + start_flag_bytes = start_flag.to_bytes(4, byteorder = 'little', signed = False) + cert_key_bin[0:4] = start_flag_bytes #填充魔术字 + tee_total_file_cnt_bytes = tee_total_file_cnt.to_bytes(4, byteorder = 'little', signed = True) + cert_key_bin[4:8] = tee_total_file_cnt_bytes #填充总的文件数 + #填充各文件的大小 + cert_key_bin[8:12] = tee_cert1_size.to_bytes(4, byteorder = 'little', signed = True) + cert_key_bin[12:16] = tee_cert2_size.to_bytes(4, byteorder = 'little', signed = True) + cert_key_bin[16:20] = tee_key_size.to_bytes(4, byteorder = 'little', signed = True) + #填充各文件 + cert_key_bin[20:20 + tee_cert1_size] = tee_cert1_bin + cert_key_bin[20 + tee_cert1_size:20 + tee_cert1_size + tee_cert2_size] = tee_cert2_bin + cert_key_bin[20 + tee_cert1_size + tee_cert2_size:20 + tee_cert1_size + tee_cert2_size + tee_key_size] = tee_key_bin + #写文件 + cert_bin_file = os.path.join("output", "bin", '%s_tee_cert_key.bin'%env_cfg.target_name) + with open(cert_bin_file, 'wb+') as fp: + fp.write(cert_key_bin) + cmd_list.append('%s|%d|%d|1'%(cert_bin_file, 0x200000 - 0x8000 - 0x1000 - 0x2000 - 0x5000, tee_cert_key_bin_max)) + + if (get_secure_boot() == True): #only need write ver file in secure boot mode. + cmd_list.append('%s|0|0|7'%version_file) + + packet_bin(str(target[1]), cmd_list) + if os.path.exists(factory_bin_path): + shutil.rmtree(factory_bin_path) + return 0 + +def compress_ota_builder(target, source, env): + """Build compressed upgrade file + """ + get_ota_object().set_encrypt_flag(0x42) + if scons_utils.scons_usr_bool_option('CONFIG_FLASH_ENCRYPT_SUPPORT') == 'y': + get_ota_object().set_file_attr_encrypt(0x2) + get_ota_object().set_encrypt_flag(0xFF) + else: + get_ota_object().set_file_attr_encrypt(0x1) + get_ota_object().set_kernel_file_attr_ota(0x4) + get_ota_object().set_build_temp_path(build_temp_path = env_cfg.cache_path) + compress_ota = get_ota_object().BuildCompressUpgBin(str(target[0]), str(source[0])) + return 0 + +def boot_ota_builder(target, source, env): + """Build boot ota + """ + if scons_utils.scons_usr_bool_option('CONFIG_FLASH_ENCRYPT_SUPPORT') == 'y': + get_ota_object().set_file_attr_encrypt(0x2) + else: + get_ota_object().set_file_attr_encrypt(0x1) + if scons_utils.scons_usr_bool_option('CONFIG_COMPRESSION_OTA_SUPPORT') == 'y': + get_ota_object().set_flashboot_file_attr_ota(0x4) + else: + get_ota_object().set_flashboot_file_attr_ota(0x3) + get_ota_object().set_encrypt_flag(0x42) + boot_ota = get_ota_object().BuildUpgBoot(str(target[0])) + return 0 + +#Builders +link_env.Append(BUILDERS={'LinkFile':linker_builder, + 'Elf':elf_builder, + 'Binary':binary_builder, + 'Asm':asm_builder, + 'BaseImg':Builder(action=baseimg_builder), + 'NVKernel':Builder(action=nvkernel_builder), + 'BootOta':Builder(action=boot_ota_builder), + 'OtaImg':Builder(action=ota_builder), + 'FactoryImg':Builder(action=factory_builder), + 'BurnImg':Builder(action=burn_bin_builder), + 'CompressOtaImg':Builder(action = compress_ota_builder), +}) + +def build_all(build_env, link_sys, flash_boot_bin, loader_boot_bin): + """Processing build + """ + + #kernel_ver + kernel_ver = scons_utils.scons_usr_int_option('CONFIG_TARGET_KERNEL_VER') + if (kernel_ver < 0 or kernel_ver > 48): + raise scons_utils.SconsBuildError("%s============== kernel_ver invalied, should be 0-48 =============%s"%(scons_utils.colors['red'], scons_utils.colors['end'])) + else: + get_ota_object().set_kernel_file_ver(kernel_ver) + + #boot_ver + boot_ver = scons_utils.scons_usr_int_option('CONFIG_TARGET_BOOT_VER') + if (boot_ver < 0 or boot_ver > 16): + raise scons_utils.SconsBuildError("%s============== boot_ver invalied, should be 0-16 =============%s"%(scons_utils.colors['red'], scons_utils.colors['end'])) + else: + get_ota_object().set_flashboot_file_ver(boot_ver) + + #images container, insert boot ota at first + imgs = [build_env.BootOta(target=os.path.join(env_cfg.bin_path, '%s_flash_boot_ota.bin'%env_cfg.target_name), source=flash_boot_bin)] + for sig_key in sign_dict: + if sig_key == 0 and factory_mode != 'yes': + continue + sign_build = build_env.Clone() + sign_build['SIGN'] = sig_key + name_suffix = '_%s'%sig_key + if sig_key == 0: + name_suffix = '_factory' + ota_file = os.path.join(env_cfg.bin_path, '%s%s.bin'%(env_cfg.target_name, name_suffix)) + elif scons_utils.scons_usr_bool_option('CONFIG_COMPRESSION_OTA_SUPPORT') == 'y': + name_suffix = '' + ota_file = os.path.join(env_cfg.cache_path, '%s_ota_%s.bin'%(env_cfg.target_name, 'temp')) #tmp file + else: + ota_file = os.path.join(env_cfg.bin_path, '%s_ota%s.bin'%(env_cfg.target_name, name_suffix)) + + sign_build['LINKFILE'] = os.path.join(env_cfg.link_path, 'link%s.lds'%name_suffix) + sign_build['MAPFILE'] = '%s%s.map'%(sign_build['MAPFILE'][:-len('.map')], name_suffix) + sign_build.Append(LINK_SCRIPTS_FLAG = '-DFLASH_FIRM_START=%s'%sign_dict[sig_key]) + + link_risc = sign_build.LinkFile(source=os.path.join('build', 'link', 'link'), + target='$LINKFILE') + sign_build.Depends(link_risc, link_sys) + #start + target_out = sign_build.Elf(source = libs, target = os.path.join(env_cfg.bin_path, '%s%s.out'%(env_cfg.target_name, name_suffix))) + sign_build.Depends(target_out, [link_risc, libs]) + target_out_bin = sign_build.Binary(source = target_out, target = os.path.join(env_cfg.cache_path, '%s%s'%(env_cfg.target_name, name_suffix))) + target_asm = sign_build.Asm(source = target_out, target=os.path.join(env_cfg.bin_path, '%s%s.asm'%(env_cfg.target_name, name_suffix))) + + base_bin_target = os.path.join(env_cfg.cache_path, '%s_base%s.bin'%(env_cfg.target_name, name_suffix)) + kernel_bin_target = os.path.join(env_cfg.cache_path, '%s_kernel%s.bin'%(env_cfg.target_name, name_suffix)) + + #Build kernel and ota + kernel = sign_build.BaseImg(source=target_out_bin, target=[base_bin_target, kernel_bin_target]) + if factory_mode == 'yes': + ota_bin = sign_build.FactoryImg(source=kernel, target=ota_file) + else: + ota_bin = sign_build.OtaImg(source=kernel, target=ota_file) + imgs.append(ota_bin) + sign_build.AddPostAction(kernel, scons_utils.cleanup) #hook clean + if sig_key == 'A': #need signature + loader_bin = os.path.join('#', env_cfg.bin_path, '%s_loader_signed.bin'%(env.get('CHIP_TYPE'))) + efuse_bin = os.path.join('build', 'basebin', 'efuse_cfg.bin') + burn_bin = os.path.join(env_cfg.bin_path, '%s_burn.bin'%env_cfg.target_name) + allinone_bin = os.path.join(env_cfg.bin_path, '%s_allinone.bin'%env_cfg.target_name) + burn_bins = sign_build.BurnImg(source=[ota_bin, loader_bin, efuse_bin] if os.path.exists(efuse_bin) else [ota_bin, loader_bin], + target=[burn_bin, allinone_bin]) + imgs.append(burn_bins) + #mark binaries to be built everytime + if sig_key in ['A', 'B']: + sign_build.AlwaysBuild([link_risc, target_out, target_out_bin, target_asm, kernel, ota_bin, burn_bins]) + if scons_utils.scons_usr_bool_option('CONFIG_COMPRESSION_OTA_SUPPORT') == 'y' and sig_key == 'A': + compress_ota_bin = os.path.join(env_cfg.bin_path, '%s_ota.bin'%env_cfg.target_name) + compress_ota_file = sign_build.CompressOtaImg(source = ota_bin, target = compress_ota_bin) + break + if sig_key == 0: + break + return imgs + +link_env.AddMethod(build_all, 'BUILD') +#prepare link script +link_sys = link_env.LinkFile(source=os.path.join('build', 'link', 'system_config'), + target=os.path.join(env_cfg.link_path, 'system_config.ld')) +link_env.Depends(link_sys, [flash_boot_bin, loader_boot_bin]) +link_env.AddPostAction(link_sys, nvimg_builder) #prepare nv image + +# START LINK +target_img = link_env.BUILD(link_sys, flash_boot_bin, loader_boot_bin) +link_env.AlwaysBuild([target_img, link_sys]) +Clean(target_img, env_cfg.clean_list) +####################################################### LINK ####################################################### + +####################################################### BUILD CHECK ####################################################### + +def build_status(): + bf = GetBuildFailures() + status = 0 + failures_message = '' + if bf: + status = -1 + failures_message = "\n".join(["Failed building %s" % scons_utils.bf_to_str(x) for x in bf if x is not None]) + return (status, failures_message) + +def display_build_status(): + if env.GetOption("clean"): + return + status, failures_message = build_status() + if status == 0: + scons_utils.show_burn_tips() + else: + scons_utils.show_alert("BUILD FAILED!!!!") + scons_utils.show_alert(failures_message) + +atexit.register(display_build_status) + +if common_env.log_output_flag == False: + file.close() #close log file handler + sys.stdout = old_stdout + diff --git a/sdk_liteos/app/demo/Makefile b/sdk_liteos/app/demo/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..ecf1e27b669c642bb74fd41d7c7e0a9ab2f7f490 --- /dev/null +++ b/sdk_liteos/app/demo/Makefile @@ -0,0 +1,49 @@ +# Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +include $(MAIN_TOPDIR)/build/make_scripts/config.mk +-include $(MAIN_TOPDIR)/$(MODULE_DIR)/srcs.mk +include $(MAIN_TOPDIR)/$(MODULE_DIR)/module_config.mk + +OBJDIR = $(MAIN_TOPDIR)/$(OBJ_PATH)/$(MODULE_DIR) + +ID_CFG_FILE = $(MAIN_TOPDIR)/$(MODULE_DIR)/file_id.cfg + +LIB_NAME = lib$(LIB).a +SRCS = $($(LIB)_srcs) +LIBOUT = $(MAIN_TOPDIR)/$(LIB_PATH)/$(MODULE_DIR)/$(LIB_NAME) + +ifdef SRC_FILES +OBJ_SRCS := $(filter %.c, $(SRC_FILES)) +ASM_SRCS := $(filter %.S, $(SRC_FILES)) +else +OBJ_SRCS := $(foreach dir, $(SRCS), $(wildcard $(dir)/*.c)) +ASM_SRCS := $(foreach dir, $(SRCS), $(wildcard $(dir)/*.S )) +endif + +OBJ_SRCS := $(filter-out %/ethernetif.c, $(OBJ_SRCS)) +OBJS = $(patsubst %.c, $(OBJDIR)/%.o, $(OBJ_SRCS)) +ASM_OBJS = $(patsubst %.S, $(OBJDIR)/%.o, $(ASM_SRCS)) + +all: $(LIBOUT) +include $(MAIN_TOPDIR)/build/make_scripts/lib.mk + +clean: + $(Q)$(foreach x, $(OBJS) $(ASM_OBJS) $(LIBOUT), \ + if [ -d $(dir $x) ]; \ + then $(RM) $(dir $x); \ + echo clean dir $(dir $x) success; \ + fi;) + +.PHONY: all clean + diff --git a/sdk_liteos/app/demo/SConscript b/sdk_liteos/app/demo/SConscript new file mode 100644 index 0000000000000000000000000000000000000000..9eee5386a645f984e1091bd614f370487d02e5fb --- /dev/null +++ b/sdk_liteos/app/demo/SConscript @@ -0,0 +1,39 @@ +#!/usr/bin/env python3 +# coding=utf-8 +# +# Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +from scripts import common_env +Import('env') +Import('env_cfg') +Import('module') + +module_path = env_cfg.get_module_dir(module) +obj_path = env_cfg.obj_path +module_libs = env_cfg.get_module_libs(module) +libs = [] + +env = env.Clone() +env_cfg.append_environs(env, module) +common_env.print_log_env(env, env_cfg.get_module_dir(module)) + +for lib in module_libs: + print('lib_name:',lib) + src_path = module_libs[lib] + objs = [] + for src in src_path: + objs += env.SConscript(os.path.join(src, 'SConscript'), {'env':env}, variant_dir = os.path.join('#', obj_path, module_path, src), duplicate = 0) + libs += env.Library(lib,objs) +Return('libs') diff --git a/sdk_liteos/app/demo/app.json b/sdk_liteos/app/demo/app.json new file mode 100755 index 0000000000000000000000000000000000000000..4a6d96e9a91773401281ceaefaf58018dffe88f1 --- /dev/null +++ b/sdk_liteos/app/demo/app.json @@ -0,0 +1,31 @@ +{ + "TARGET_LIB": "demo", + "APP_SRCS": [ + "init", + "src" + ], + "INCLUDE": [ + "components/iperf2/include", + "app/demo/include", + "app/demo/init", + "app/demo/src", + "config/app", + "config/diag", + "platform/os/Huawei_LiteOS/net/ripple/exports", + "components/ripple/exports", + "components/hilink/include", + "third_party/mbedtls/include/mbedtls/" + ], + "CC_FLAGS": [ + ], + "DEFINES": [ + "_PRE_WLAN_FEATURE_CSI", + "_PRE_WLAN_FEATURE_P2P", + "LWIP_ENABLE_DIAG_CMD=0" + ], + "AR_FLAGS": [], + "LD_FLAGS": [], + "AS_FLAGS": [], + "LD_DIRS": [], + "CLEAN": [] +} diff --git a/sdk_liteos/app/demo/include/app_demo_adc.h b/sdk_liteos/app/demo/include/app_demo_adc.h new file mode 100755 index 0000000000000000000000000000000000000000..acb3288a353428b33a7906b476b51ee4ac36f3b1 --- /dev/null +++ b/sdk_liteos/app/demo/include/app_demo_adc.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __APP_DEMO_ADC_H__ +#define __APP_DEMO_ADC_H__ + +#include + +#define APP_DEMO_ADC +#ifdef APP_DEMO_ADC + +#include +#include +#include + +#define ADC_TEST_LENGTH 128 +#define VLT_MIN 100 + +hi_void app_demo_adc_test(hi_void); +#endif +#endif \ No newline at end of file diff --git a/sdk_liteos/app/demo/include/app_demo_efuse.h b/sdk_liteos/app/demo/include/app_demo_efuse.h new file mode 100755 index 0000000000000000000000000000000000000000..6ec580726ba0d65a9fa9fef959a009315af4fcb6 --- /dev/null +++ b/sdk_liteos/app/demo/include/app_demo_efuse.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __APP_DEMO_EFUSE_H__ +#define __APP_DEMO_EFUSE_H__ + +#include + +#include +#include + +#define EFUSE_USR_RW_SAMPLE_BUFF_MAX_LEN 2 /* The efuse customer_rsvd0 length is 64 bits. + Two 32-bit space is required for storing read and write data. */ + +hi_u32 get_efuse_id_size_test(hi_void); +hi_void efuse_get_lock_stat(hi_void); +hi_u32 efuse_usr_read(hi_void); +hi_u32 efuse_usr_write(hi_void); +hi_u32 efuse_usr_lock(hi_void); +hi_u32 sample_usr_efuse(hi_void); +hi_u32 efuse_id_read(hi_void); +hi_u32 efuse_id_write(hi_void); +hi_u32 efuse_id_lock(hi_void); +hi_u32 sample_id_efuse(hi_void); +hi_void efuse_demo(hi_void); +#endif diff --git a/sdk_liteos/app/demo/include/app_demo_flash.h b/sdk_liteos/app/demo/include/app_demo_flash.h new file mode 100755 index 0000000000000000000000000000000000000000..16a94c4b57f17fa5af17e89729aeccf289a8195a --- /dev/null +++ b/sdk_liteos/app/demo/include/app_demo_flash.h @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __APP_DEMO_FLASH_H__ +#define __APP_DEMO_FLASH_H__ + +#include + +#ifdef TEST_KERNEL_FLASH + +#include +#include +#include +#include +#include +#include + +#define TEST_SIZE 0x1000 +#define TEST_FLASH_OFFSET 0x1FF000 + +hi_void cmd_test_flash(hi_u32 test_time, hi_u32 test_mode); +#endif +#endif \ No newline at end of file diff --git a/sdk_liteos/app/demo/include/app_demo_i2c.h b/sdk_liteos/app/demo/include/app_demo_i2c.h new file mode 100755 index 0000000000000000000000000000000000000000..7749b86b48f717fb18f9ca83d94ffa2793494377 --- /dev/null +++ b/sdk_liteos/app/demo/include/app_demo_i2c.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __APP_DEMO_I2C_H__ +#define __APP_DEMO_I2C_H__ + +#include +#include +#include +#include + +#define I2C_REG_ARRAY_LEN 64 +#define ES8311_DEV_ADDR 0x30 /* 11000 0 */ +#define ES8311_REG_ADDR 0x10 +#define I2C_SEND_LEN_2 2 +#define I2C_RECV_LEN_1 1 + +hi_void i2c_demo_send_data_init(hi_void); +hi_u32 i2c_demo_write(hi_i2c_idx id, hi_u16 device_addr, hi_u32 send_len); +hi_u32 i2c_demo_writeread(hi_i2c_idx id, hi_u16 device_addr, hi_u32 recv_len); +hi_void i2c_demo(hi_i2c_idx id); +hi_void app_demo_custom_i2c(hi_void); + +#endif diff --git a/sdk_liteos/app/demo/include/app_demo_i2s.h b/sdk_liteos/app/demo/include/app_demo_i2s.h new file mode 100644 index 0000000000000000000000000000000000000000..66bf65c2fcdcd6df3c6a92404b7c19ff02b2c337 --- /dev/null +++ b/sdk_liteos/app/demo/include/app_demo_i2s.h @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __APP_DEMO_I2S_H__ +#define __APP_DEMO_I2S_H__ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#define I2S_TEST_TASK_STAK_SIZE 2048 +#define I2S_TEST_TASK_PRIORITY 28 +#define AUDIO_PLAY_BUF_SIZE 4096 +#define AUDIO_RECORD_BUF_SIZE 3072 +#define AUDIO_RECORD_FINISH_BIT (1 << 0) +#define ALL_AUDIO_RECORD_FINISH_BIT (1 << 1) + +#define AUDIO_PLAY_FIEL_MODE 0 +#define AUDIO_RECORD_AND_PLAY_MODE 1 + +typedef struct { + hi_u32 flash_start_addr; + hi_u32 data_len; +} audio_map; + +typedef struct { + hi_u8 *play_buf; + hi_u8 *record_buf; +} test_audio_attr; + +hi_void i2s_demo(hi_void); +#endif diff --git a/sdk_liteos/app/demo/include/app_demo_io_gpio.h b/sdk_liteos/app/demo/include/app_demo_io_gpio.h new file mode 100755 index 0000000000000000000000000000000000000000..98b4dc7186d167cb85dcd9de01c257474008b8c9 --- /dev/null +++ b/sdk_liteos/app/demo/include/app_demo_io_gpio.h @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __APP_DEMO_IO_GPIO_H__ +#define __APP_DEMO_IO_GPIO_H__ + +#include +#include +#include +#include +#include + +/* gpio callback func */ +hi_void gpio_isr_func(hi_void *arg); +hi_void io_gpio_demo(hi_void); +/* gpio callback demo */ +hi_void gpio_isr_demo(hi_void); +hi_void app_demo_custom_io_gpio(hi_void); +#endif \ No newline at end of file diff --git a/sdk_liteos/app/demo/include/app_demo_nv.h b/sdk_liteos/app/demo/include/app_demo_nv.h new file mode 100755 index 0000000000000000000000000000000000000000..afcac8c5c01d0d93b3d82e2d60aa66d0921c606e --- /dev/null +++ b/sdk_liteos/app/demo/include/app_demo_nv.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __APP_DEMO_NV_H__ +#define __APP_DEMO_NV_H__ + +#include +#include +#include +#include +#include +#include + +#define HI_NV_DEMO_RST_CFG_ID 0x22 +#define HI_FACTORY_NV_DEMO_ID 0x1 + +typedef struct { + hi_u32 nv_demo_test_num0; + hi_u32 nv_demo_test_num1; + hi_u32 nv_demo_test_num2; + hi_u32 nv_demo_test_num3; +} hi_nv_demo_tset_cfg; + +typedef struct { + hi_s32 nv_factory_demo_test_num0; + hi_s32 nv_factory_demo_test_num1; + hi_s32 nv_factory_demo_test_num2; +} hi_factory_nv_demo_tset_cfg; + +hi_void nv_demo(hi_void); +hi_void factory_nv_demo(hi_void); + +#endif \ No newline at end of file diff --git a/sdk_liteos/app/demo/include/app_demo_pwm.h b/sdk_liteos/app/demo/include/app_demo_pwm.h new file mode 100755 index 0000000000000000000000000000000000000000..50a57e95f59ec43f61dbde64678611532fed0ad3 --- /dev/null +++ b/sdk_liteos/app/demo/include/app_demo_pwm.h @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __APP_DEMO_PWM_H__ +#define __APP_DEMO_PWM_H__ + +#include +#include +#include +#include + +hi_void app_demo_pwm(hi_void); +#endif \ No newline at end of file diff --git a/sdk_liteos/app/demo/include/app_demo_spi.h b/sdk_liteos/app/demo/include/app_demo_spi.h new file mode 100755 index 0000000000000000000000000000000000000000..afff37c380599beba84f04ed400f1c64473fe07e --- /dev/null +++ b/sdk_liteos/app/demo/include/app_demo_spi.h @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __APP_DEMO_SPI_H__ +#define __APP_DEMO_SPI_H__ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define BUF_LENGTH 512 +#define BUF_LENGTH_HALF (BUF_LENGTH >> 1) +#define TEST_LOOP_LENGTH 256 +#define test_spi_printf(fmt...) \ + do { \ + printf("[SPI TEST]" fmt); \ + printf("\n"); \ + } while (0) + +#ifndef min +#define min(a, b) ((a) < (b) ? (a) : (b)) +#endif + +typedef struct { + hi_spi_cfg_basic_info cfg_info; + hi_spi_idx spi_id; + hi_u32 loop; + hi_u32 length; + hi_bool irq; + hi_bool slave; + hi_bool lb; + hi_bool dma_en; +} test_spi_para; + +typedef enum { + TEST_CASE_ALL, + TEST_CASE_POL0_PHA0 = 1, + TEST_CASE_POL0_PHA1, + TEST_CASE_POL1_PHA0, + TEST_CASE_POL1_PHA1, + TEST_CASE_MOTOROLA, + TEST_CASE_TI, + TEST_CASE_BIT4, + TEST_CASE_BIT7, + TEST_CASE_BIT8, + TEST_CASE_BIT9 = 10, + TEST_CASE_BIT15, + TEST_CASE_BIT16, + TEST_CASE_CLK_MIN, + TEST_CASE_CLK_16, + TEST_CASE_CLK_50, + TEST_CASE_CLK_100, + TEST_CASE_CLK_200, + TEST_CASE_CLK_MAX, + TEST_CASE_PARAMETER_WRONG, + TEST_CASE_SLAVE = 20, + TEST_CASE_MASTER, + TEST_CASE_MAX, +} hi_spi_test_case; + +hi_u32 app_demo_spi_para_test(hi_spi_cfg_basic_info *spi_para); +hi_u32 app_demo_spi_test_case(hi_u8 test_case); +hi_void app_demo_spi_test(hi_spi_idx spi_id, hi_u32 irq_en, hi_u32 test_case, hi_u32 loop); +hi_void app_demo_spi_cmd_host_read(hi_spi_idx spi_id, hi_u32 length, hi_u32 loop); +hi_void app_demo_spi_cmd_slave_write(hi_spi_idx spi_id, hi_u32 length, hi_u32 loop); +hi_void app_demo_spi_cmd_host_write(hi_spi_idx spi_id, hi_u32 length, hi_u32 loop); +hi_void app_demo_spi_cmd_slave_read(hi_spi_idx spi_id, hi_u32 length, hi_u32 loop); +#endif diff --git a/sdk_liteos/app/demo/include/app_demo_timer_systick.h b/sdk_liteos/app/demo/include/app_demo_timer_systick.h new file mode 100755 index 0000000000000000000000000000000000000000..752be4840a7bf00969618cb3ce3874dedfa42528 --- /dev/null +++ b/sdk_liteos/app/demo/include/app_demo_timer_systick.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __APP_DEMO_TIMER_SYSTICK_H__ +#define __APP_DEMO_TIMER_SYSTICK_H__ + +#include +#include +#include +#include +#include +#include +#include + +#define NO_CALLBACK 0xffff +#define HRTIMER_EXPIRE 2000 /* expire timer is 2000us */ +#define WORK_TICK_DELAY_US 31 /* 1/32K */ +#define APP_DEMO_TIMER_WAIT 10000 /* wait 10s */ + +hi_void hr_timer_callback(hi_u32 data); +hi_void app_demo_hrtimer(hi_void); +hi_void app_demo_systick(hi_void); +static hi_void app_demo_timer_handle(hi_u32 data); +hi_void app_demo_timer(hi_void); +#endif \ No newline at end of file diff --git a/sdk_liteos/app/demo/include/app_demo_tsensor.h b/sdk_liteos/app/demo/include/app_demo_tsensor.h new file mode 100755 index 0000000000000000000000000000000000000000..9eaf80f26b11597e932e4cf9ac099e2f21a8dc27 --- /dev/null +++ b/sdk_liteos/app/demo/include/app_demo_tsensor.h @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __APP_DEMO_I2S_H__ +#define __APP_DEMO_I2S_H__ + +#include +#include +#include +#include +#include +#include +#include + +#define TEMPERRATURE_OUT_THRESHOLD_LOW (-30) +#define TEMPERRATURE_OUT_THRESHOLD_HIGH 100 +#define TEMPERRATURE_OVER_THRESHOLD 115 +#define TEMPERRATURE_POWER_DOWN_THRESHOLD 125 +#define TSENSOR_CALIBRATE_CODE 0x07 +#define TSENSOR_CALIBRATE_CODE_LOAD_EFUSE 0 +#define TSENSOR_CALIBRATE_CODE_LOAD_REG 1 +#define TSENSOR_PERIOD_VALUE 500 +#define TSENSOR_TEST_INTERVAL 1000 +#define TSENSOR_TEST_LOOP 10 +#define TSENSOR_GET_TEMPERRATURE_INTERVAL (TSENSOR_PERIOD_VALUE * 31.25 + 192 * 16) + +static hi_void tensor_collect_finish_irq(hi_s16 irq_temperature); +static hi_void tensor_outtemp_irq(hi_s16 irq_temperature); +static hi_void tensor_overtemp_irq(hi_s16 irq_temperature); +static hi_void read_temprature_none_irq_single(hi_void); +hi_void tsensor_demo(hi_void); +#endif diff --git a/sdk_liteos/app/demo/include/app_demo_uart.h b/sdk_liteos/app/demo/include/app_demo_uart.h new file mode 100755 index 0000000000000000000000000000000000000000..d8733452996dbd16e4bceab0dce42b6bc2532b34 --- /dev/null +++ b/sdk_liteos/app/demo/include/app_demo_uart.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __APP_DEMO_UART_H__ +#define __APP_DEMO_UART_H__ + +#include +#include +#include +#include +#include + +#define WRITE_BY_INT +#define UART_DEMO_TASK_STAK_SIZE 2048 +#define UART_DEMO_TASK_PRIORITY 25 +#define DEMO_UART_NUM HI_UART_IDX_2 +#define UART_BUFF_SIZE 32 + +static hi_void *uart_demo_task(hi_void *param); +hi_void uart_demo(hi_void); +#endif \ No newline at end of file diff --git a/sdk_liteos/app/demo/include/app_http_client.h b/sdk_liteos/app/demo/include/app_http_client.h new file mode 100755 index 0000000000000000000000000000000000000000..9095fc42b4a60a8ea68bc703658b793ae67f4328 --- /dev/null +++ b/sdk_liteos/app/demo/include/app_http_client.h @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __APP_HTTP_CLOENT_H__ +#define __APP_HTTP_CLOENT_H__ + +#include + +unsigned int http_clienti_get(int argc, const char *argv[]); +#endif \ No newline at end of file diff --git a/sdk_liteos/app/demo/include/app_io_init.h b/sdk_liteos/app/demo/include/app_io_init.h new file mode 100644 index 0000000000000000000000000000000000000000..7ff7cc36b5f09ff3c83eafa3fddbd8da6c802b36 --- /dev/null +++ b/sdk_liteos/app/demo/include/app_io_init.h @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __APP_IO_INIT_H__ +#define __APP_IO_INIT_H__ + +#include + +HI_CPP_START + +hi_void app_io_init(hi_void); +hi_void app_io_set_gpio2_clkout_enable(hi_bool enable); + +HI_CPP_END +#endif /* __APP_IO_INIT_H__ */ + diff --git a/sdk_liteos/app/demo/include/app_main.h b/sdk_liteos/app/demo/include/app_main.h new file mode 100644 index 0000000000000000000000000000000000000000..a21fe23a1581f8be7668e0f9c4a4ad6a59c27493 --- /dev/null +++ b/sdk_liteos/app/demo/include/app_main.h @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __APP_MAIN_H__ +#define __APP_MAIN_H__ + +#include + +typedef struct { + hi_u16 gpio6_cfg; + hi_u16 gpio8_cfg; + hi_u16 gpio10_cfg; + hi_u16 gpio11_cfg; + hi_u16 gpio12_cfg; + hi_u16 gpio13_cfg; + hi_u16 sfc_csn_cfg; +} app_iocfg_backup; + +#endif // __APP_MAIN_H__ diff --git a/sdk_liteos/app/demo/include/wifi_softap.h b/sdk_liteos/app/demo/include/wifi_softap.h new file mode 100644 index 0000000000000000000000000000000000000000..5a66c2fec21c32dc2084e4e1fda6df581c62e9a8 --- /dev/null +++ b/sdk_liteos/app/demo/include/wifi_softap.h @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __WIFI_SOFTAP_H__ +#define __WIFI_SOFTAP_H__ + +int hi_wifi_start_softap(void); + +void hi_wifi_stop_softap(void); + +#endif /* __WIFI_STA_H__ */ + diff --git a/sdk_liteos/app/demo/include/wifi_sta.h b/sdk_liteos/app/demo/include/wifi_sta.h new file mode 100644 index 0000000000000000000000000000000000000000..54a6bb4b03409bbb9b090a7a0f97c0332277dcac --- /dev/null +++ b/sdk_liteos/app/demo/include/wifi_sta.h @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __WIFI_STA_H__ +#define __WIFI_STA_H__ + +int hi_wifi_start_sta(void); + +void hi_wifi_stop_sta(void); + +#endif /* __WIFI_STA_H__ */ + diff --git a/sdk_liteos/app/demo/init/SConscript b/sdk_liteos/app/demo/init/SConscript new file mode 100644 index 0000000000000000000000000000000000000000..e5cfdb03a24885d7c4ea6f74bf397147d1ce7b33 --- /dev/null +++ b/sdk_liteos/app/demo/init/SConscript @@ -0,0 +1,19 @@ +# Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +Import('env') + +env = env.Clone() + +objs = env.Object(Glob('*.c')) +Return('objs') diff --git a/sdk_liteos/app/demo/init/app_io_init.c b/sdk_liteos/app/demo/init/app_io_init.c new file mode 100644 index 0000000000000000000000000000000000000000..411a77ac2b89b941f52a8da440cce81707a93edc --- /dev/null +++ b/sdk_liteos/app/demo/init/app_io_init.c @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +hi_void app_io_set_gpio2_clkout_enable(hi_bool enable) +{ + if (enable == HI_TRUE) { + hi_io_set_input_enable(HI_IO_NAME_GPIO_2, HI_TRUE); + hi_reg_write16(DIAG_CTL_DIAG_MUX, 0x2); + hi_reg_write16(DIAG_CTL_CLOCK_TEST_DIV, 0x0); + hi_reg_write16(DIAG_CTL_CLOCK_TEST_EN, 0x3FFF); + hi_reg_write16(DIAG_CTL_CLOCK_TEST_SEL, 0x1); + hi_io_set_func(HI_IO_NAME_GPIO_2, 0x6); /* let gpio2 output clk. */ + hi_io_set_driver_strength(HI_IO_NAME_GPIO_2, HI_IO_DRIVER_STRENGTH_3); + } else { + hi_io_set_func(HI_IO_NAME_GPIO_2, HI_IO_FUNC_GPIO_2_GPIO); + hi_io_set_input_enable(HI_IO_NAME_GPIO_2, HI_FALSE); /* set io enable false, for low power. */ + hi_io_set_pull(HI_IO_NAME_GPIO_2, HI_IO_PULL_NONE); + } +} + +hi_void app_io_init(hi_void) +{ + /* + * You need to select the I/O multiplexing configuration of each peripheral + * based on the application scenario. The following is an example. + */ +#ifdef CONFIG_UART0_SUPPORT + /* Configure UART0 as the debugging serial port. */ + hi_io_set_func(HI_IO_NAME_GPIO_3, HI_IO_FUNC_GPIO_3_UART0_TXD); /* uart0 tx */ + hi_io_set_func(HI_IO_NAME_GPIO_4, HI_IO_FUNC_GPIO_4_UART0_RXD); /* uart0 rx */ +#endif + +#ifdef CONFIG_UART1_SUPPORT + /* Configure UART1 as the AT command serial port. */ + hi_io_set_func(HI_IO_NAME_GPIO_5, HI_IO_FUNC_GPIO_5_UART1_RXD); /* uart1 rx */ + hi_io_set_func(HI_IO_NAME_GPIO_6, HI_IO_FUNC_GPIO_6_UART1_TXD); /* uart1 tx */ +#endif + +#ifdef CONFIG_UART2_SUPPORT + /* Configure UART1 as the SIGMA authentication serial port. */ + hi_io_set_func(HI_IO_NAME_GPIO_11, HI_IO_FUNC_GPIO_11_UART2_TXD); /* uart2 tx */ + hi_io_set_func(HI_IO_NAME_GPIO_12, HI_IO_FUNC_GPIO_12_UART2_RXD); /* uart2 rx */ +#endif + + /* SPI MUX: */ +#ifdef CONFIG_SPI_SUPPORT + /* The SPI I/O multiplexing mode can also be 5/6/7/8 or 0/1/2/3 based on the product design. */ + hi_io_set_func(HI_IO_NAME_GPIO_9, HI_IO_FUNC_GPIO_9_SPI0_TXD); + hi_io_set_func(HI_IO_NAME_GPIO_10, HI_IO_FUNC_GPIO_10_SPI0_CK); + hi_io_set_func(HI_IO_NAME_GPIO_11, HI_IO_FUNC_GPIO_11_SPI0_RXD); + hi_io_set_func(HI_IO_NAME_GPIO_12, HI_IO_FUNC_GPIO_12_SPI0_CSN); + hi_io_set_driver_strength(HI_IO_NAME_GPIO_9, HI_IO_DRIVER_STRENGTH_0); +#endif + + /* I2C MUX: */ +#ifdef CONFIG_I2C_SUPPORT + /* The I2C I/O multiplexing mode can also be 3/4 or 9/10 based on the product design. */ + hi_io_set_func(HI_IO_NAME_GPIO_0, HI_IO_FUNC_GPIO_0_I2C1_SDA); + hi_io_set_func(HI_IO_NAME_GPIO_1, HI_IO_FUNC_GPIO_1_I2C1_SCL); +#endif + + /* PWM MUX: */ +#ifdef CONFIG_PWM_SUPPORT + /* The configurations for multiplexing 0/2/3/4/5 into PWM are similar. */ + hi_io_set_func(HI_IO_NAME_GPIO_8, HI_IO_FUNC_GPIO_8_PWM1_OUT); +#endif + + /* I2S MUX: */ +#ifdef CONFIG_I2S_SUPPORT + hi_io_set_func(HI_IO_NAME_GPIO_9, HI_IO_FUNC_GPIO_9_I2S0_MCLK); + hi_io_set_func(HI_IO_NAME_GPIO_10, HI_IO_FUNC_GPIO_10_I2S0_TX); + hi_io_set_func(HI_IO_NAME_GPIO_11, HI_IO_FUNC_GPIO_11_I2S0_RX); + hi_io_set_func(HI_IO_NAME_GPIO_12, HI_IO_FUNC_GPIO_12_I2S0_BCLK); + hi_io_set_func(HI_IO_NAME_GPIO_13, HI_IO_FUNC_GPIO_13_I2S0_WS); +#endif + + /* SDIO MUX: */ +#ifdef CONFIG_SDIO_SUPPORT + (hi_void)hi_io_set_func(HI_IO_NAME_GPIO_9, HI_IO_FUNC_GPIO_9_SDIO_D2); + (hi_void)hi_io_set_func(HI_IO_NAME_GPIO_10, HI_IO_FUNC_GPIO_10_SDIO_D3); + (hi_void)hi_io_set_func(HI_IO_NAME_GPIO_11, HI_IO_FUNC_GPIO_11_SDIO_CMD); + (hi_void)hi_io_set_func(HI_IO_NAME_GPIO_12, HI_IO_FUNC_GPIO_12_SDIO_CLK); + (hi_void)hi_io_set_func(HI_IO_NAME_GPIO_13, HI_IO_FUNC_GPIO_13_SDIO_D0); + (hi_void)hi_io_set_func(HI_IO_NAME_GPIO_14, HI_IO_FUNC_GPIO_14_SDIO_D1); + + (hi_void)hi_io_set_pull(HI_IO_NAME_GPIO_9, HI_IO_PULL_UP); + (hi_void)hi_io_set_pull(HI_IO_NAME_GPIO_10, HI_IO_PULL_UP); + (hi_void)hi_io_set_pull(HI_IO_NAME_GPIO_11, HI_IO_PULL_UP); + (hi_void)hi_io_set_pull(HI_IO_NAME_GPIO_13, HI_IO_PULL_UP); + (hi_void)hi_io_set_pull(HI_IO_NAME_GPIO_14, HI_IO_PULL_UP); +#endif +} + diff --git a/sdk_liteos/app/demo/module_config.mk b/sdk_liteos/app/demo/module_config.mk new file mode 100644 index 0000000000000000000000000000000000000000..ad65c5d33267eab4e9b4c059b1d1e08266a2994f --- /dev/null +++ b/sdk_liteos/app/demo/module_config.mk @@ -0,0 +1,19 @@ +# Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +ALL_LIBS := demo +demo_srcs := init src +CCFLAGS += +CCFLAGS += -D_PRE_WLAN_FEATURE_CSI -D_PRE_WLAN_FEATURE_P2P -DLWIP_ENABLE_DIAG_CMD=0 +CCFLAGS += -I$(MAIN_TOPDIR)/components/iperf2/include -I$(MAIN_TOPDIR)/app/demo/include -I$(MAIN_TOPDIR)/app/demo/init -I$(MAIN_TOPDIR)/app/demo/src -I$(MAIN_TOPDIR)/config/app -I$(MAIN_TOPDIR)/config/diag -I$(MAIN_TOPDIR)/platform/os/Huawei_LiteOS/net/ripple/exports -I$(MAIN_TOPDIR)/components/ripple/exports -I$(MAIN_TOPDIR)/components/hilink/include +CCFLAGS += -I$(MAIN_TOPDIR)/third_party/mbedtls/include/mbedtls diff --git a/sdk_liteos/app/demo/src/SConscript b/sdk_liteos/app/demo/src/SConscript new file mode 100644 index 0000000000000000000000000000000000000000..2c01223e744ab148fce4e5168587bc3fdc6427dc --- /dev/null +++ b/sdk_liteos/app/demo/src/SConscript @@ -0,0 +1,19 @@ +# Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +Import('env') + +env = env.Clone() + +objs = env.Object(Glob('*.c')) +Return('objs') diff --git a/sdk_liteos/app/demo/src/app_demo_adc.c b/sdk_liteos/app/demo/src/app_demo_adc.c new file mode 100644 index 0000000000000000000000000000000000000000..2f9ed3fa8b09fbc2f676aec041050c0900d082a4 --- /dev/null +++ b/sdk_liteos/app/demo/src/app_demo_adc.c @@ -0,0 +1,118 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#define APP_DEMO_ADC +#ifdef APP_DEMO_ADC +#include + +hi_u16 g_adc_buf[ADC_TEST_LENGTH] = { 0 }; + +hi_void test_para(hi_void) +{ + hi_u32 ret; + hi_u16 data = 0; + printf("********ADC Test Para Set Start********\n"); + ret = hi_adc_read(HI_ADC_CHANNEL_BUTT, &data, HI_ADC_EQU_MODEL_1, HI_ADC_CUR_BAIS_DEFAULT, 0); + if (ret == HI_ERR_ADC_PARAMETER_WRONG) { + printf("ADC TEST WRONG Channel SUCCESS!\n"); + } + ret = hi_adc_read(HI_ADC_CHANNEL_7, HI_NULL, HI_ADC_EQU_MODEL_1, HI_ADC_CUR_BAIS_DEFAULT, 0); + if (ret == HI_ERR_ADC_PARAMETER_WRONG) { + printf("ADC TEST WRONG Data point SUCCESS!\n"); + } + ret = hi_adc_read(HI_ADC_CHANNEL_7, &data, HI_ADC_EQU_MODEL_BUTT, HI_ADC_CUR_BAIS_DEFAULT, 0); + if (ret == HI_ERR_ADC_PARAMETER_WRONG) { + printf("ADC TEST WRONG Average Algorithm SUCCESS!\n"); + } + ret = hi_adc_read(HI_ADC_CHANNEL_7, &data, HI_ADC_EQU_MODEL_1, HI_ADC_CUR_BAIS_BUTT, 0); + if (ret == HI_ERR_ADC_PARAMETER_WRONG) { + printf("ADC TEST WRONG Analog Power Control SUCCESS!\n"); + } + ret = hi_adc_read(HI_ADC_CHANNEL_7, &data, HI_ADC_EQU_MODEL_1, HI_ADC_CUR_BAIS_DEFAULT, 0xFFF); + if (ret == HI_ERR_ADC_PARAMETER_WRONG) { + printf("ADC TEST WRONG Reset Count SUCCESS!\n"); + } +} + +/* asic adc test */ +hi_void convert_to_voltage(hi_u32 data_len) +{ + hi_u32 i; + float vlt_max = 0; + float vlt_min = VLT_MIN; + hi_u16 vlt; + for (i = 0; i < data_len; i++) { + vlt = g_adc_buf[i]; + float voltage = (float)vlt * 1.8 * 4 / 4096.0; /* vlt * 1.8 * 4 / 4096.0: Convert code into voltage */ + vlt_max = (voltage > vlt_max) ? voltage : vlt_max; + vlt_min = (voltage < vlt_min) ? voltage : vlt_min; + } + printf("vlt_min:%.3f, vlt_max:%.3f \n", vlt_min, vlt_max); +} + +hi_void app_demo_adc_test(hi_void) +{ + hi_u32 ret, i; + hi_u16 data; /* 10 */ + printf("ADC Test Start\n"); + + memset_s(g_adc_buf, sizeof(g_adc_buf), 0x0, sizeof(g_adc_buf)); + for (hi_u8 ch = 0; ch < HI_ADC_CHANNEL_BUTT; ch++) { + for (i = 0; i < ADC_TEST_LENGTH; i++) { + ret = hi_adc_read((hi_adc_channel_index)ch, &data, HI_ADC_EQU_MODEL_1, HI_ADC_CUR_BAIS_DEFAULT, 0); + if (ret != HI_ERR_SUCCESS) { + printf("ADC Read Fail\n"); + return; + } + g_adc_buf[i] = data; + } + convert_to_voltage(ADC_TEST_LENGTH); + } + printf("ADC Test Channels End\n"); + + memset_s(g_adc_buf, sizeof(g_adc_buf), 0x0, sizeof(g_adc_buf)); + for (hi_u8 em = 0; em < HI_ADC_EQU_MODEL_BUTT; em++) { + for (i = 0; i < ADC_TEST_LENGTH; i++) { + ret = hi_adc_read(HI_ADC_CHANNEL_7, &data, (hi_adc_equ_model_sel)em, HI_ADC_CUR_BAIS_DEFAULT, 0); + if (ret != HI_ERR_SUCCESS) { + printf("ADC Read Fail\n"); + return; + } + g_adc_buf[i] = data; + } + convert_to_voltage(ADC_TEST_LENGTH); + } + printf("ADC Test Average Mode End\n"); + + memset_s(g_adc_buf, sizeof(g_adc_buf), 0x0, sizeof(g_adc_buf)); + for (hi_u16 rc = 0; rc <= 0xFF0; rc += 0xF) { + for (i = 0; i < ADC_TEST_LENGTH; i++) { + ret = hi_adc_read(HI_ADC_CHANNEL_7, &data, HI_ADC_EQU_MODEL_8, HI_ADC_CUR_BAIS_DEFAULT, rc); + if (ret != HI_ERR_SUCCESS) { + printf("ADC Read Fail\n"); + return; + } + g_adc_buf[i] = data; + } + convert_to_voltage(ADC_TEST_LENGTH); + } + printf("ADC Test Reset Count End\n"); + + test_para(); + + printf("ADC Test End!\n"); +} + +#endif diff --git a/sdk_liteos/app/demo/src/app_demo_efuse.c b/sdk_liteos/app/demo/src/app_demo_efuse.c new file mode 100644 index 0000000000000000000000000000000000000000..ffdc5ff73ce29523ec9523e96d26f44b35f87cfa --- /dev/null +++ b/sdk_liteos/app/demo/src/app_demo_efuse.c @@ -0,0 +1,257 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +hi_u32 get_efuse_id_size_test(hi_void) +{ + hi_s32 i; + hi_u32 efuse_size; + + for (i = 0; i < HI_EFUSE_IDX_MAX; i++) { + efuse_size = hi_efuse_get_id_size((hi_efuse_idx)i); + if (efuse_size == HI_ERR_EFUSE_INVALIDATE_ID) { + printf("***exception***! failed to get size of efuse ID%d(0x%02X)\n", i, i); + return efuse_size; + } + + printf("size of efuse ID%d(0x%02X) = %d\n", i, i, efuse_size); + } + + return HI_ERR_SUCCESS; +} + +hi_void efuse_get_lock_stat(hi_void) +{ + hi_u64 lock_data; + + hi_efuse_get_lockstat(&lock_data); + printf("lock_stat = 0x%08X ", (hi_u32)((lock_data >> 32) & 0xFFFFFFFF)); /* right shift 32bits */ + printf("%08X\n", (hi_u32)(lock_data & 0xFFFFFFFF)); +} + +hi_u32 efuse_usr_read(hi_void) +{ + hi_u32 ret; + hi_u32 read_data[EFUSE_USR_RW_SAMPLE_BUFF_MAX_LEN] = {0}; + hi_u16 start_bit = 0x75C; /* The offset address of customer_rsvd0 is 0x75C */ + hi_u16 rw_bits = 64; /* The lenth of customer_rsvd0 is 64bits */ + hi_u16 align_size; + hi_u8 tmp_data[9] = {0}; /* 9 bytes(72 bits) for customer_rsvd0 field, length 8-bit aligned. */ + hi_u64 first_u64; + hi_u8 second_u8; + + hi_u8 diff_head_read = start_bit % 8; /* The start address is read in 8-bit alignment mode. */ + start_bit = start_bit - diff_head_read; + align_size = (((rw_bits + diff_head_read) >> 3) + 1) << 3; /* 3-bit offset */ + + ret = hi_efuse_usr_read(start_bit, align_size, (hi_u8 *)tmp_data); + if (ret != HI_ERR_SUCCESS) { + printf("Failed to read EFUSE at line%d! Err code = %X\n", __LINE__, ret); + return ret; + } + + first_u64 = *(hi_u64 *)&tmp_data[0]; + second_u8 = *(hi_u8 *)&tmp_data[8]; /* the last u8 bit */ + /* The lower bits of the first u64 multi-read are discarded.(The diff_head_read) */ + first_u64 = first_u64 >> diff_head_read; + /* + * The least significant eight bits of tmp_data are shifted leftward by 64-diff_head_read bits + * as the most significant 64 bits of tmp_data.diff_head_read) + */ + first_u64 = first_u64 | ((hi_u64)second_u8 << (64 - diff_head_read)); /* (64 - diff_head_read)bits */ + *(hi_u64 *)read_data = first_u64; + + printf("usr_data = 0x%08X %08X\n", read_data[0], read_data[1]); + + return HI_ERR_SUCCESS; +} + +hi_u32 efuse_usr_write(hi_void) +{ + hi_u32 ret; + hi_u32 write_data[EFUSE_USR_RW_SAMPLE_BUFF_MAX_LEN] = { + 0x0, + 0x1, + }; + hi_u16 start_bit = 0x75C; /* Offset address:0x75C */ + hi_u16 rw_bits = 64; /* length:64bits */ + + ret = efuse_usr_read(); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + ret = hi_efuse_usr_write(start_bit, rw_bits, (hi_u8 *)write_data); + if (ret != HI_ERR_SUCCESS) { + printf("Failed to write EFUSE!\n"); + return ret; + } + + return HI_ERR_SUCCESS; +} + +hi_u32 efuse_usr_lock(hi_void) +{ + hi_u32 ret; + hi_u8 lock_data = 0x1; + hi_u16 lock_start_bit = 0x7FD; /* Offset address:0x7FD */ + hi_u16 lock_bits = 1; /* length:1bit */ + + efuse_get_lock_stat(); + + ret = hi_efuse_usr_write(lock_start_bit, lock_bits, &lock_data); + if (ret != HI_ERR_SUCCESS) { + printf("Failed to lock EFUSE!\n"); + return ret; + } + + efuse_get_lock_stat(); + + return HI_ERR_SUCCESS; +} + +hi_u32 sample_usr_efuse(hi_void) +{ + hi_u32 ret; + +#ifdef EFUSE_WRITE_ENABLE + ret = efuse_usr_write(); + if (ret != HI_ERR_SUCCESS) { + return ret; + } +#endif + + ret = efuse_usr_read(); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + +#ifdef EFUSE_LOCK_ENABLE + ret = efuse_usr_lock(); + if (ret != HI_ERR_SUCCESS) { + return ret; + } +#endif + + return HI_ERR_SUCCESS; +} + +hi_u32 efuse_id_read(hi_void) +{ + hi_u32 ret; + hi_u32 read_data[EFUSE_USR_RW_SAMPLE_BUFF_MAX_LEN] = {0}; + hi_efuse_idx efuse_id = HI_EFUSE_CUSTOMER_RSVD0_RW_ID; + + ret = hi_efuse_read(efuse_id, (hi_u8 *)read_data, (hi_u8)sizeof(read_data)); + if (ret != HI_ERR_SUCCESS) { + printf("Failed to read EFUSE at line%d! Err code = %X\n", __LINE__, ret); + return ret; + } + printf("id_data = 0x%08X %08X\n", read_data[0], read_data[1]); + + return HI_ERR_SUCCESS; +} + +hi_u32 efuse_id_write(hi_void) +{ + hi_u32 ret; + hi_u32 write_data[EFUSE_USR_RW_SAMPLE_BUFF_MAX_LEN] = { + 0x1, + 0x0, + }; + hi_efuse_idx efuse_id = HI_EFUSE_CUSTOMER_RSVD0_RW_ID; + + ret = efuse_id_read(); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + ret = hi_efuse_write(efuse_id, (hi_u8 *)write_data); + if (ret != HI_ERR_SUCCESS) { + printf("Failed to write EFUSE!\n"); + return ret; + } + + return HI_ERR_SUCCESS; +} + +hi_u32 efuse_id_lock(hi_void) +{ + hi_u32 ret; + hi_efuse_lock_id lock_id = HI_EFUSE_LOCK_CUSTOMER_RSVD0_ID; + efuse_get_lock_stat(); + + ret = hi_efuse_lock(lock_id); + if (ret != HI_ERR_SUCCESS) { + printf("Failed to lock EFUSE!\n"); + return ret; + } + + efuse_get_lock_stat(); + + return HI_ERR_SUCCESS; +} + +hi_u32 sample_id_efuse(hi_void) +{ + hi_u32 ret; + +#ifdef EFUSE_WRITE_ENABLE + ret = efuse_id_write(); + if (ret != HI_ERR_SUCCESS) { + return ret; + } +#endif + + ret = efuse_id_read(); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + +#ifdef EFUSE_LOCK_ENABLE + ret = efuse_id_lock(); + if (ret != HI_ERR_SUCCESS) { + return ret; + } +#endif + + return HI_ERR_SUCCESS; +} + +/* + * This demo simply shows how to use efuse interface to write, read and lock customer_rsvd0 field. + * -note: Efuse is a one-time programmable logic. Once set, it cannot be modified. + * Be careful when using write and lock interfaces. + */ +hi_void efuse_demo(hi_void) +{ + hi_u32 ret; + + ret = get_efuse_id_size_test(); + if (ret != HI_ERR_SUCCESS) { + return; + } + + ret = sample_id_efuse(); + if (ret != HI_ERR_SUCCESS) { + return; + } + + ret = sample_usr_efuse(); + if (ret != HI_ERR_SUCCESS) { + return; + } +} diff --git a/sdk_liteos/app/demo/src/app_demo_flash.c b/sdk_liteos/app/demo/src/app_demo_flash.c new file mode 100644 index 0000000000000000000000000000000000000000..92137c18e8640ff486f3f73d90a6f2cbb3a4c8b5 --- /dev/null +++ b/sdk_liteos/app/demo/src/app_demo_flash.c @@ -0,0 +1,110 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#define TEST_KERNEL_FLASH +#ifdef TEST_KERNEL_FLASH +#include + +hi_u32 g_test_flash_tb = 0; +hi_u32 g_tf_test_time = 60; +hi_u32 g_tf_test_mode = 0; + +hi_u8 g_tf_pdata[TEST_SIZE]; +hi_u8 g_tf_pdata_back[TEST_SIZE]; + +#define CODE_IN_FLASH +#ifdef CODE_IN_FLASH +hi_void *test_flash_body2(hi_void* param) +#else +BSP_RAM_TEXT_SECTION hi_void *test_flash_body2(hi_void* param) +#endif +{ + hi_u32 ret; + hi_u32 tick[2]; /* 2 */ + hi_unref_param(param); + hi_watchdog_disable(); + tick[0] = hi_get_tick(); + for (;;) { + if (g_tf_test_mode == 2) { /* 2 */ + for (int i = 0; i < TEST_SIZE; i++) { + g_tf_pdata_back[i] = (hi_u8)(*(hi_u16*)(0x401000 + i * 2)); /* flash addr:0x401000 2 */ + } + } else { + ret = hi_flash_erase(TEST_FLASH_OFFSET, TEST_SIZE); + if (ret != HI_ERR_SUCCESS) { + printf("erase fail:%x\n", ret); + } + ret = hi_flash_write(TEST_FLASH_OFFSET, TEST_SIZE, g_tf_pdata, HI_TRUE); + if (ret != HI_ERR_SUCCESS) { + printf("write fail:%x\n", ret); + } + memset_s(g_tf_pdata_back, TEST_SIZE, 0x0, TEST_SIZE); + ret = hi_flash_read(TEST_FLASH_OFFSET, TEST_SIZE, g_tf_pdata_back); + if (ret != HI_ERR_SUCCESS) { + printf("read fail:%x\n", ret); + } + } + if (memcmp(g_tf_pdata, g_tf_pdata_back, TEST_SIZE)) { + printf("hi_flash_read fail !\r\n"); + break; + } + tick[1] = hi_get_tick(); + if ((tick[1] - tick[0]) >= (g_tf_test_time * 100)) { /* 100 */ + printf("test over\r\n"); + break; + } + } + return HI_NULL; +} + +hi_void cmd_test_flash(hi_u32 test_time, hi_u32 test_mode) +{ + hi_task_attr attr; + hi_u32 ret; + hi_u32 i; + g_tf_test_time = test_time; + g_tf_test_mode = test_mode; + printf("test mode %d ,test %d s,wait ..\r\n", g_tf_test_mode, g_tf_test_time); + if (g_tf_test_mode == 0) { + for (i = 0; i < TEST_SIZE; i++) { + g_tf_pdata[i] = (hi_u8)i; + } + } else if (g_tf_test_mode == 1) { + memset_s(g_tf_pdata, TEST_SIZE, 0xF0, TEST_SIZE); + printf("test F0\r\n"); + } else if (g_tf_test_mode == 2) { /* 2 */ + printf("test task in flash\r\n"); + } + ret = hi_flash_write(TEST_FLASH_OFFSET, TEST_SIZE, g_tf_pdata, HI_TRUE); + if (ret != HI_ERR_SUCCESS) { + return; + } + ret = hi_flash_read(TEST_FLASH_OFFSET, TEST_SIZE, g_tf_pdata_back); + if (ret != HI_ERR_SUCCESS) { + return; + } + if (memcmp(g_tf_pdata, g_tf_pdata_back, TEST_SIZE)) { + printf("write or read fail !\r\n"); + printf("testdata addr:0x%x\r\n", (hi_u32)g_tf_pdata_back); + return; + } + printf("testdata addr:0x%x\r\n", (hi_u32)g_tf_pdata_back); + attr.stack_size = 0x800; /* 800 */ + attr.task_name = (hi_char*) "test_flash"; + attr.task_prio = 28; /* 28 */ + hi_task_create(&g_test_flash_tb, &attr, test_flash_body2, 0); +} + +#endif diff --git a/sdk_liteos/app/demo/src/app_demo_i2c.c b/sdk_liteos/app/demo/src/app_demo_i2c.c new file mode 100644 index 0000000000000000000000000000000000000000..0fcba6c48f1895dbc6a4a7ed12116535a0029d71 --- /dev/null +++ b/sdk_liteos/app/demo/src/app_demo_i2c.c @@ -0,0 +1,125 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +/* Es8311 initialization array */ +hi_u8 g_es8311_reg_array[I2C_REG_ARRAY_LEN] = { + 0x1F, 0x00, 0x00, 0x10, 0x10, 0x00, 0x03, 0x00, /* 0x00 ~ 0x0f */ + 0xff, 0x00, 0x00, 0x00, 0x20, 0xfc, 0x6a, 0x00, + 0x13, 0x7c, 0x02, 0x40, 0x10, 0x00, 0x04, 0x00, /* 0x10 ~ 0x1f */ + 0x00, 0x00, 0x00, 0x0b, 0x4b, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x20 ~ 0x2f */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, /* 0x30 ~ 0x3f */ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +}; + +hi_u8 g_send_data[I2C_REG_ARRAY_LEN] = { 0 }; + +hi_void i2c_demo_send_data_init(hi_void) +{ + hi_u8 i; + + hi_u8 reg_addr = ES8311_REG_ADDR; + + g_send_data[0] = reg_addr; + g_send_data[1] = g_es8311_reg_array[reg_addr]; + + reg_addr++; + g_send_data[2] = reg_addr; /* size 2 */ + g_send_data[3] = g_es8311_reg_array[reg_addr]; /* size 3 */ + + for (i = 0; i < I2C_SEND_LEN_2; i++) { + printf("----- data init: send_buf[%d] = 0x%x! -----*\r\n", i, g_send_data[i]); + } + + printf("\n"); +} + +hi_u32 i2c_demo_write(hi_i2c_idx id, hi_u16 device_addr, hi_u32 send_len) +{ + hi_u32 status; + hi_i2c_data es8311_i2c_data = { 0 }; + + es8311_i2c_data.send_buf = g_send_data; + es8311_i2c_data.send_len = send_len; + status = hi_i2c_write(id, device_addr, &es8311_i2c_data); + if (status != HI_ERR_SUCCESS) { + printf("===== Error: I2C write status = 0x%x! =====\r\n", status); + return status; + } + + return HI_ERR_SUCCESS; +} + +hi_u32 i2c_demo_writeread(hi_i2c_idx id, hi_u16 device_addr, hi_u32 recv_len) +{ + hi_u8 i; + hi_u32 status; + hi_u8 recv_data[I2C_REG_ARRAY_LEN] = { 0 }; + hi_i2c_data es8311_i2c_data = { 0 }; + + printf("----- reg addr[0] = 0x%x! -----\r\n", g_send_data[0]); + + /* Request memory space */ + memset_s(recv_data, I2C_REG_ARRAY_LEN, 0x0, sizeof(recv_data)); + memset_s(&es8311_i2c_data, sizeof(hi_i2c_data), 0x0, sizeof(hi_i2c_data)); + + es8311_i2c_data.send_buf = g_send_data; + es8311_i2c_data.send_len = 1; + es8311_i2c_data.receive_buf = recv_data; + es8311_i2c_data.receive_len = recv_len; + status = hi_i2c_writeread(id, device_addr, &es8311_i2c_data); + if (status != HI_ERR_SUCCESS) { + printf("===== Error: I2C read status = 0x%x! =====\r\n", status); + return status; + } + + for (i = 0; i < recv_len; i++) { + printf("----- revData[%d] = 0x%x! -----\r\n", i, recv_data[i]); + } + + return HI_ERR_SUCCESS; +} + +hi_void i2c_demo(hi_i2c_idx id) +{ + hi_u32 ret; + + printf("----- I2C Start -----\r\n"); + + i2c_demo_send_data_init(); + hi_i2c_init(id, 100000); /* baudrate: 100000 */ + + ret = i2c_demo_write(id, ES8311_DEV_ADDR, I2C_SEND_LEN_2); + printf("----- (ES8311)i2c_demo_write %d : %s! -----\r\n\n", __LINE__, + ret == HI_ERR_SUCCESS ? "SUCCESS!" : "FAILURE!"); + + ret = i2c_demo_writeread(id, ES8311_DEV_ADDR, I2C_RECV_LEN_1); + printf("----- (ES8311)i2c_demo_writeread %d : %s! -----\r\n\n", __LINE__, + ret == HI_ERR_SUCCESS ? "SUCCESS!" : "FAILURE!"); + + hi_i2c_deinit(id); + + printf("I2C Test End!\r\n"); +} + +hi_void app_demo_custom_i2c(hi_void) +{ + /* Default use I2C 0 */ + i2c_demo(HI_I2C_IDX_0); +} + diff --git a/sdk_liteos/app/demo/src/app_demo_i2s.c b/sdk_liteos/app/demo/src/app_demo_i2s.c new file mode 100644 index 0000000000000000000000000000000000000000..0ec1176560cb52d0398c90fe9dc08a5267e0cee1 --- /dev/null +++ b/sdk_liteos/app/demo/src/app_demo_i2s.c @@ -0,0 +1,237 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "app_demo_i2s.h" + +#ifndef I2S_TEST_DEBUG +#define i2s_print(ftm...) do {printf(ftm);} while (0); +#else +#define i2s_print(ftm...) +#endif + +audio_map g_audio_map[2] = { /* 2 flash fields */ + {0x001A1000, 100 * 1024}, /* audio file size: 100 * 1024(100K) */ + {0x001CE000, 204800}, /* recod size: 200K */ +}; + +hi_u32 g_audio_event; +hi_u32 g_audio_task_id; +test_audio_attr g_audio_test; +hi_u8 g_record_data[AUDIO_RECORD_BUF_SIZE] = {0}; + +hi_void es8311_codec_init(const hi_codec_attribute *codec_attr) +{ + if (codec_attr == HI_NULL) { + return; + } + hi_u32 ret; + + ret = hi_i2c_init(HI_I2C_IDX_1, 100000); /* 100000: i2s bit rate */ + if (ret != HI_ERR_SUCCESS) { + i2s_print("==ERROR== hi_i2c_init, err = %X\n", ret); + return; + } + + ret = hi_codec_init(codec_attr); + if (ret != HI_ERR_SUCCESS) { + i2s_print("==ERROR== Failed to init codec!! err = %X\n", ret); + } else { + i2s_print("init codec success!\n"); + } +} + +hi_void audio_play(hi_u32 map_index) +{ + hi_u32 ret; + hi_u32 play_addr = g_audio_map[map_index].flash_start_addr; + hi_u32 total_play_len = g_audio_map[map_index].data_len; + hi_u32 time_out = HI_SYS_WAIT_FOREVER; + + /* apply memory */ + g_audio_test.play_buf = (hi_u8 *) hi_malloc(HI_MOD_ID_DRV, AUDIO_PLAY_BUF_SIZE); + if (g_audio_test.play_buf == HI_NULL) { + hi_i2s_deinit(); + i2s_print("==ERROR== play buf malloc fail!!!\n"); + return; + } + memset_s(g_audio_test.play_buf, AUDIO_PLAY_BUF_SIZE, 0, AUDIO_PLAY_BUF_SIZE); + + while (total_play_len > 0) { + hi_u32 send_len = hi_min(total_play_len, AUDIO_PLAY_BUF_SIZE); + ret = hi_flash_read(play_addr, send_len, g_audio_test.play_buf); + if (ret != HI_ERR_SUCCESS) { + i2s_print("==ERROR== hi_flash_read fail, err = %X\n", ret); + } + + ret = hi_i2s_write(g_audio_test.play_buf, send_len, time_out); + if (ret != HI_ERR_SUCCESS) { + i2s_print("hi_i2s_write fail, err = %X\n", ret); + } + + play_addr += send_len; + total_play_len -= send_len; + } + + i2s_print("Play over....\n"); + + hi_free(HI_MOD_ID_DRV, g_audio_test.play_buf); +} + +hi_void audio_record_func(hi_u32 map_index) +{ + hi_u32 ret; + hi_u32 record_addr = g_audio_map[map_index].flash_start_addr; + hi_u32 total_record_len = g_audio_map[map_index].data_len; + hi_u32 time_out = HI_SYS_WAIT_FOREVER; + + ret = hi_flash_erase(record_addr, total_record_len); + if (ret != HI_ERR_SUCCESS) { + i2s_print("Failed to erase flash, err = %X\n", ret); + return; + } + + while (total_record_len > 0) { + hi_u32 len = hi_min(AUDIO_RECORD_BUF_SIZE, total_record_len); + ret = hi_i2s_read(g_audio_test.record_buf, len, time_out); + if (ret != HI_ERR_SUCCESS) { + i2s_print("Failed to hi_i2s_read, err = %X\n", ret); + return; + } + + if (memcpy_s(g_record_data, sizeof(g_record_data), g_audio_test.record_buf, len) != EOK) { + return; + } + hi_event_send(g_audio_event, AUDIO_RECORD_FINISH_BIT); + + record_addr += len; + total_record_len -= len; + } + + hi_event_send(g_audio_event, ALL_AUDIO_RECORD_FINISH_BIT); +} + +hi_void *record_n_play_task(hi_void *param) +{ + hi_u32 ret; + hi_u32 event_bit = 0; + hi_u32 record_addr = g_audio_map[AUDIO_RECORD_AND_PLAY_MODE].flash_start_addr; + hi_u32 total_record_len = g_audio_map[AUDIO_RECORD_AND_PLAY_MODE].data_len; + hi_u32 len; + hi_unref_param(param); + + while (1) { + hi_event_wait(g_audio_event, AUDIO_RECORD_FINISH_BIT | ALL_AUDIO_RECORD_FINISH_BIT, &event_bit, + HI_SYS_WAIT_FOREVER, HI_EVENT_WAITMODE_OR | HI_EVENT_WAITMODE_CLR); + if (event_bit & ALL_AUDIO_RECORD_FINISH_BIT) { + break; + } + len = hi_min(AUDIO_RECORD_BUF_SIZE, total_record_len); + + ret = hi_flash_write(record_addr, len, g_record_data, HI_FALSE); + if (ret != HI_ERR_SUCCESS) { + i2s_print("==ERROR== hi_flash_write, err = %X\n", ret); + } + record_addr += len; + total_record_len -= len; + } + + i2s_print("Record success!...\n"); + hi_udelay(1000000); /* 1000000: delay 1s */ + + audio_play(AUDIO_RECORD_AND_PLAY_MODE); + i2s_print("Play record audio success!...\n"); + + return HI_NULL; +} + + +hi_void audio_record_play(hi_u32 map_index) +{ + hi_u32 ret; + + hi_task_attr attr = {0}; + attr.stack_size = I2S_TEST_TASK_STAK_SIZE; + attr.task_prio = I2S_TEST_TASK_PRIORITY; + attr.task_name = (hi_char*)"audio_record"; + ret = hi_task_create(&g_audio_task_id, &attr, record_n_play_task, 0); + if (ret != HI_ERR_SUCCESS) { + i2s_print("Falied to create record task, err = %X\n", ret); + } + + /* apply memory */ + g_audio_test.record_buf = (hi_u8 *) hi_malloc(HI_MOD_ID_DRV, AUDIO_RECORD_BUF_SIZE); + if (g_audio_test.record_buf == HI_NULL) { + hi_i2s_deinit(); + i2s_print("==ERROR== record buf malloc fail!!!\n"); + return; + } + memset_s(g_audio_test.record_buf, AUDIO_RECORD_BUF_SIZE, 0, AUDIO_RECORD_BUF_SIZE); + + i2s_print("==start record== please say somerthing~~\n"); + audio_record_func(map_index); +} + +/* + * i2s_demo: a simple demo implement paly audio file and record audio then play them back function. + * -note: If it is in play mode, user need to burn the audio file to the specified location of flash in advance. + * max size of audio file: 100K bytes + * burn command: burn 1A1000 19000 + */ +hi_void i2s_demo(hi_void) +{ + hi_u32 ret; + + ret = hi_flash_init(); + if (ret == HI_ERR_FLASH_RE_INIT) { + i2s_print("Flash has already been initialized!\n"); + } else if (ret != HI_ERR_SUCCESS) { + i2s_print("Falied to init flash, err = %X\n", ret); + } + + /* create I2S record event */ + ret = hi_event_create(&g_audio_event); + if (ret != HI_ERR_SUCCESS) { + i2s_print("Failed to init g_audio_event! err = %X\n", ret); + return; + } + + hi_codec_attribute codec_cfg = { + .sample_rate = HI_CODEC_SAMPLE_RATE_8K, + .resolution = HI_CODEC_RESOLUTION_16BIT, + }; + hi_i2s_attribute i2s_cfg = { + .sample_rate = HI_I2S_SAMPLE_RATE_8K, + .resolution = HI_I2S_RESOLUTION_16BIT, + }; + + es8311_codec_init(&codec_cfg); + + ret = hi_i2s_init(&i2s_cfg); + if (ret != HI_ERR_SUCCESS) { + i2s_print("Failed to init i2s!\n"); + return; + } + + i2s_print("I2s init success!\n"); + + /* paly audio file */ + audio_play(AUDIO_PLAY_FIEL_MODE); + + hi_udelay(5000000); /* 5000000: delay 5s */ + + /* record audio then play them back */ + audio_record_play(AUDIO_RECORD_AND_PLAY_MODE); +} + diff --git a/sdk_liteos/app/demo/src/app_demo_io_gpio.c b/sdk_liteos/app/demo/src/app_demo_io_gpio.c new file mode 100644 index 0000000000000000000000000000000000000000..dafca421c1df5460197ee44b435caaf5c899799d --- /dev/null +++ b/sdk_liteos/app/demo/src/app_demo_io_gpio.c @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +/* gpio callback func */ +hi_void gpio_isr_func(hi_void *arg) +{ + hi_unref_param(arg); + printf("----- gpio isr success -----\r\n"); +} + +hi_void io_gpio_demo(hi_void) +{ + /* Take gpio 0 as an example */ + hi_u32 ret; + hi_gpio_value gpio_val = HI_GPIO_VALUE1; + + ret = hi_gpio_init(); + if (ret != HI_ERR_SUCCESS) { + printf("===== ERROR ===== gpio -> hi_gpio_init ret:%d\r\n", ret); + return; + } + printf("----- gpio init success-----\r\n"); + + ret = hi_io_set_func(HI_IO_NAME_GPIO_0, HI_IO_FUNC_GPIO_0_GPIO); + if (ret != HI_ERR_SUCCESS) { + printf("===== ERROR ===== gpio -> hi_io_set_func ret:%d\r\n", ret); + return; + } + printf("----- io set func success-----\r\n"); + + ret = hi_gpio_set_dir(HI_GPIO_IDX_0, HI_GPIO_DIR_IN); + if (ret != HI_ERR_SUCCESS) { + printf("===== ERROR ===== gpio -> hi_gpio_set_dir1 ret:%d\r\n", ret); + return; + } + printf("----- gpio set dir success! -----\r\n"); + + ret = hi_gpio_get_input_val(HI_GPIO_IDX_0, &gpio_val); + if (ret != HI_ERR_SUCCESS) { + printf("===== ERROR ===== gpio -> hi_gpio_get_input_val ret:%d\r\n", ret); + return; + } + printf("----- gpio input val is:%d. -----\r\n", gpio_val); + + ret = hi_gpio_deinit(); + if (ret != HI_ERR_SUCCESS) { + printf("===== ERROR ===== gpio -> hi_gpio_deinit ret:%d\r\n", ret); + return; + } + printf("----- gpio deinit success-----\r\n"); +} + +/* gpio callback demo */ +hi_void gpio_isr_demo(hi_void) +{ + hi_u32 ret; + + printf("----- gpio isr demo -----\r\n"); + + (hi_void)hi_gpio_init(); + + ret = hi_gpio_set_dir(HI_GPIO_IDX_0, HI_GPIO_DIR_IN); + if (ret != HI_ERR_SUCCESS) { + printf("===== ERROR ======gpio -> hi_gpio_set_dir1 ret:%d\r\n", ret); + return; + } + + ret = hi_gpio_register_isr_function(HI_GPIO_IDX_0, HI_INT_TYPE_LEVEL, + HI_GPIO_EDGE_RISE_LEVEL_HIGH, gpio_isr_func, HI_NULL); + if (ret != HI_ERR_SUCCESS) { + printf("===== ERROR ======gpio -> hi_gpio_register_isr_function ret:%d\r\n", ret); + } +} + +hi_void app_demo_custom_io_gpio(hi_void) +{ + io_gpio_demo(); + hi_sleep(1000); /* sleep 1000ms */ + gpio_isr_demo(); +} + diff --git a/sdk_liteos/app/demo/src/app_demo_nv.c b/sdk_liteos/app/demo/src/app_demo_nv.c new file mode 100644 index 0000000000000000000000000000000000000000..5e3a354d613f38726a8e1fc6bd98e4f647a7097c --- /dev/null +++ b/sdk_liteos/app/demo/src/app_demo_nv.c @@ -0,0 +1,122 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +/* + * This demo simply shows how to read and write nv item. + * nv demo must excute after hi_nv_init in app_main. + * nv default value was defined in tools\scripts\generate_nv\xml_file\mss_nvi_db.xml + */ +hi_void nv_demo(hi_void) +{ + hi_u32 ret; + hi_u32 err_info = 0; + hi_nv_demo_tset_cfg cfg, cfg1; + hi_flash_partition_table *ptable = hi_get_partition_table(); + (hi_void)memset_s(&cfg, sizeof(cfg), 0, sizeof(cfg)); + (hi_void)memset_s(&cfg1, sizeof(cfg1), 0, sizeof(cfg1)); + + cfg.nv_demo_test_num0 = 0x1; + + hi_flash_deinit(); + ret = hi_flash_init(); + if (ret != HI_ERR_SUCCESS) { + err_info |= 1 << 0x6; + printf("flash init status:0x%x\n", err_info); + return; + } + + ret = hi_nv_init(ptable->table[HI_FLASH_PARTITON_NORMAL_NV].addr, HI_NV_DEFAULT_TOTAL_SIZE, + HI_NV_DEFAULT_BLOCK_SIZE); + if (ret != HI_ERR_SUCCESS) { + printf("nv init fail\r\n"); + return; + } + + /* read nv data(which nv id is 0x22) from board */ + ret = hi_nv_read(HI_NV_DEMO_RST_CFG_ID, &cfg, sizeof(cfg), 0); + if (ret != HI_ERR_SUCCESS) { + printf("nv read fail\r\n"); + return; + } + printf("nv read success, cfg.nv_demo_test_num0:%d\r\n", cfg.nv_demo_test_num0); + + cfg1.nv_demo_test_num0 = 0x3; + + /* write nv data(which nv id is 0x22) to board */ + ret = hi_nv_write(HI_NV_DEMO_RST_CFG_ID, &cfg1, sizeof(cfg1), 0); + if (ret != HI_ERR_SUCCESS) { + printf("nv write fail\r\n"); + return; + } + printf("nv write success\r\n"); + ret = hi_nv_read(HI_NV_DEMO_RST_CFG_ID, &cfg, sizeof(cfg), 0); + if (ret != HI_ERR_SUCCESS) { + printf("nv read fail\r\n"); + return; + } + printf("nv read success, cfg.nv_demo_test_num0:%d\r\n", cfg.nv_demo_test_num0); +} + +hi_void factory_nv_demo(hi_void) +{ + hi_u32 ret; + hi_u32 err_info = 0; + hi_factory_nv_demo_tset_cfg cfg, cfg1; + (hi_void)memset_s(&cfg, sizeof(cfg), 0, sizeof(cfg)); + (hi_void)memset_s(&cfg1, sizeof(cfg1), 0, sizeof(cfg1)); + + cfg.nv_factory_demo_test_num0 = 0x1; + + hi_flash_deinit(); + ret = hi_flash_init(); + if (ret != HI_ERR_SUCCESS) { + err_info |= 1 << 0x6; + printf("flash init status:0x%x\n", err_info); + return; + } + + ret = hi_factory_nv_init(HI_FNV_DEFAULT_ADDR, HI_NV_DEFAULT_TOTAL_SIZE, HI_NV_DEFAULT_BLOCK_SIZE); + if (ret != HI_ERR_SUCCESS) { + printf("factory nv init fail\r\n"); + return; + } + + /* read factory nv data(which nv id is 0x1) from board */ + ret = hi_factory_nv_read(HI_FACTORY_NV_DEMO_ID, &cfg, sizeof(cfg), 0); + if (ret != HI_ERR_SUCCESS) { + printf("factory nv read fail\r\n"); + return; + } + printf("factory nv read success, cfg.nv_demo_test_num0:%d\r\n", cfg.nv_factory_demo_test_num0); + + cfg1.nv_factory_demo_test_num0 = 0x3; + + /* write factory nv data(which nv id is 0x1) to board */ + ret = hi_factory_nv_write(HI_FACTORY_NV_DEMO_ID, &cfg1, sizeof(cfg1), 0); + if (ret != HI_ERR_SUCCESS) { + printf("factory nv write fail\r\n"); + return; + } + printf("factory nv write success\r\n"); + ret = hi_factory_nv_read(HI_FACTORY_NV_DEMO_ID, &cfg, sizeof(cfg), 0); + if (ret != HI_ERR_SUCCESS) { + printf("factory nv read fail\r\n"); + return; + } + printf("factory nv read success, cfg.nv_demo_test_num0:%d\r\n", cfg.nv_factory_demo_test_num0); +} + diff --git a/sdk_liteos/app/demo/src/app_demo_pwm.c b/sdk_liteos/app/demo/src/app_demo_pwm.c new file mode 100644 index 0000000000000000000000000000000000000000..38b8aea6ceb768aa521259b1735ab9a385da984d --- /dev/null +++ b/sdk_liteos/app/demo/src/app_demo_pwm.c @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +hi_void pwm_0_demo(hi_void) +{ + hi_pwm_init(HI_PWM_PORT_PWM0); + hi_pwm_set_clock(PWM_CLK_160M); + hi_pwm_start(HI_PWM_PORT_PWM0, 750, 1500); /* duty: 750 freq:1500 */ +} + +hi_void pwm_1_demo(hi_void) +{ + hi_pwm_init(HI_PWM_PORT_PWM1); + hi_pwm_set_clock(PWM_CLK_160M); + hi_pwm_start(HI_PWM_PORT_PWM1, 750, 1500); /* duty: 750 freq:1500 */ +} + +hi_void pwm_2_demo(hi_void) +{ + hi_pwm_init(HI_PWM_PORT_PWM2); + hi_pwm_set_clock(PWM_CLK_160M); + hi_pwm_start(HI_PWM_PORT_PWM2, 750, 1500); /* duty: 750 freq:1500 */ +} + +hi_void pwm_3_demo(hi_void) +{ + hi_pwm_init(HI_PWM_PORT_PWM3); + hi_pwm_set_clock(PWM_CLK_160M); + hi_pwm_start(HI_PWM_PORT_PWM3, 750, 1500); /* duty: 750 freq:1500 */ +} + +hi_void pwm_4_demo(hi_void) +{ + hi_pwm_init(HI_PWM_PORT_PWM4); + hi_pwm_set_clock(PWM_CLK_160M); + hi_pwm_start(HI_PWM_PORT_PWM4, 750, 1500); /* duty: 750 freq:1500 */ +} + +hi_void pwm_5_demo(hi_void) +{ + hi_pwm_init(HI_PWM_PORT_PWM5); + hi_pwm_set_clock(PWM_CLK_160M); + hi_pwm_start(HI_PWM_PORT_PWM5, 750, 1500); /* duty: 750 freq:1500 */ +} + +hi_void app_demo_pwm(hi_void) +{ + printf("start test pwm"); + + pwm_0_demo(); + pwm_1_demo(); + pwm_2_demo(); + pwm_3_demo(); + pwm_4_demo(); + pwm_5_demo(); + + printf("please use an oscilloscope to check the output waveform!"); +} + diff --git a/sdk_liteos/app/demo/src/app_demo_sdio_device.c b/sdk_liteos/app/demo/src/app_demo_sdio_device.c new file mode 100644 index 0000000000000000000000000000000000000000..54aeffea16092f01d95d2b5fa8509c2e9faf9a74 --- /dev/null +++ b/sdk_liteos/app/demo/src/app_demo_sdio_device.c @@ -0,0 +1,197 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Description: app sdio slave demo: shows send and receive data with sdio. + */ + +#include +#include +#include +#include +#include + +#define DATA_BLOCK 32768 /* sdio data block size:32768 */ +#define SEND_RCV_DATA_SIZE 1024 /* send/recv 1024 byte per cycle */ +hi_u32 g_sdio_send_data[SEND_RCV_DATA_SIZE] = {0}; /* data array of data to be send */ +hi_u32* g_sdio_send_data_addr = NULL; + +hi_s32 app_demo_sdio_read_over_callback(hi_void) +{ + printf("app_demo_sdio_read_over_callback\r\n"); + return HI_ERR_SUCCESS; +} + +hi_s32 app_demo_sdio_read_start_callback(hi_u32 len, hi_u8* admatable) +{ + hi_watchdog_feed(); + + hi_u32 i; + hi_u32 remain; + hi_u32 index = 0; + hi_u32* addr = NULL; + g_sdio_send_data_addr = &g_sdio_send_data[0]; + + for (i = 0; i < (len / DATA_BLOCK); i++) { + addr = g_sdio_send_data_addr + ((DATA_BLOCK >> 2) * i); /* 2 bits for g_download_addr is hi_u32 */ + if (hi_sdio_set_admatable(admatable, index++, addr, DATA_BLOCK) != 0) { + return HI_ERR_FAILURE; + } + } + + remain = len % DATA_BLOCK; + if (remain != 0) { + addr = g_sdio_send_data_addr + ((DATA_BLOCK >> 2) * i); /* 2 bits for g_download_addr is hi_u32 */ + if (hi_sdio_set_admatable(admatable, index++, addr, remain) != 0) { + return HI_ERR_FAILURE; + } + } + + if (hi_sdio_complete_send(admatable, index) != 0) { + return HI_ERR_FAILURE; + } + + hi_cache_flush(); + return (hi_s32) index; +} + +hi_u32 g_receive_data[SEND_RCV_DATA_SIZE] = {0}; /* data array to receive data */ +hi_u32* g_receive_data_addr = NULL; +hi_u32 g_recevei_data_len = 0; +hi_s32 app_demo_sdio_write_start_callback(hi_u32 len, hi_u8* admatable) +{ + printf("app_demo_sdio_write_start_callback,len: %d\n", len); + hi_watchdog_feed(); + g_receive_data_addr = &g_receive_data[0]; + g_recevei_data_len = len; + + hi_u32 i; + hi_u32 remain; + hi_u32 index = 0; + hi_u32* addr = NULL; + + for (i = 0; i < (len / DATA_BLOCK); i++) { + addr = g_receive_data_addr + ((DATA_BLOCK >> 2) * i); /* shift 2bits is for hi_u32* reason. */ + if (hi_sdio_set_admatable(admatable, index++, addr, DATA_BLOCK) != 0) { + return HI_ERR_FAILURE; + } + } + + remain = len % DATA_BLOCK; + + if (remain != 0) { + addr = g_receive_data_addr + ((DATA_BLOCK >> 2) * i); /* shift 2bits is for hi_u32* reason. */ + if (hi_sdio_set_admatable(admatable, index++, addr, remain) != 0) { + return HI_ERR_FAILURE; + } + } + + if (hi_sdio_complete_send(admatable, index) != 0) { + return HI_ERR_FAILURE; + } + + hi_cache_flush(); + return (hi_s32) index; +} + +hi_s32 app_demo_sdio_write_over_callback(hi_void) +{ + printf("app_demo_sdio_write_over_callback, len:%d\n", g_recevei_data_len); + + hi_u8* received_data = (hi_u8*)(&g_receive_data[0]); + for (hi_u32 i = 0; i < g_recevei_data_len; i++) { + if (i % 8 == 0) { /* 8:Newline */ + printf ("\r\n"); + } + printf("0x%x ", received_data[i]); + } + return HI_ERR_SUCCESS; +} + +hi_void app_demo_sdio_receive_msg_callback(hi_u32 msg) +{ + printf("app_demo_sdio_receive_msg_callback:0x%x\n", msg); +} + +hi_void app_demo_sdio_read_err_callback(hi_void) +{ + printf("app_demo_sdio_read_err_callback\n"); +} + +hi_void app_demo_sdio_soft_rst_callback(hi_void) +{ + printf("app_demo_sdio_soft_rst_callback\r\n"); +} + +hi_void app_demo_sdio_send_data(hi_void) +{ + printf("app demo sdio start send data\r\n"); + + hi_u8* send_data = (hi_u8*)&g_sdio_send_data[0]; + hi_cipher_trng_get_random_bytes(send_data, SEND_RCV_DATA_SIZE); + hi_sdio_send_data(SEND_RCV_DATA_SIZE); + + return; +} + +hi_void app_demo_sdio_send_msg(hi_void) +{ + hi_sdio_send_sync_msg(0); + return; +} + +hi_void app_demo_sdio_callback_init(hi_void) +{ + hi_sdio_intcallback callback; + + callback.rdover_callback = app_demo_sdio_read_over_callback; + callback.rdstart_callback = app_demo_sdio_read_start_callback; + callback.wrstart_callback = app_demo_sdio_write_start_callback; + callback.wrover_callback = app_demo_sdio_write_over_callback; + callback.processmsg_callback = app_demo_sdio_receive_msg_callback; + callback.rderr_callback = app_demo_sdio_read_err_callback; + callback.soft_rst_callback = app_demo_sdio_soft_rst_callback; + (hi_void)hi_sdio_register_callback(&callback); + + printf("app_demo_sdio_callback_init success\r\n"); +} + +hi_void app_demo_sdio(hi_void) +{ + hi_u32 ret; + /* init sdio */ + /* should config io in app_io_init first. */ + ret = hi_sdio_init(); + if (ret != HI_ERR_SUCCESS) { + printf("app demo sdio init fail\r\n"); + return; + } + + /* register sdio interrupt callbak. */ + app_demo_sdio_callback_init(); + + /* sdio send and receive msg */ + /* when host send msg to device, device will receive msg in + * app_demo_sdio_receive_msg_callback + */ + app_demo_sdio_send_msg(); + + /* sdio send data */ + app_demo_sdio_send_data(); + + /* sdio receive data */ + /* + * when host send data to device, device will receive data in + * app_demo_sdio_write_start_callback, app_demo_sdio_write_over_callback + */ +} diff --git a/sdk_liteos/app/demo/src/app_demo_sdio_device.h b/sdk_liteos/app/demo/src/app_demo_sdio_device.h new file mode 100644 index 0000000000000000000000000000000000000000..8aced7c3f02ea118a3cc065381d93e3dc8ffbfdc --- /dev/null +++ b/sdk_liteos/app/demo/src/app_demo_sdio_device.h @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Description: app sdio slave demo headerfile. + */ + +#ifndef __APP_DEMO_SDIO_DEVICE_H__ +#define __APP_DEMO_SDIO_DEVICE_H__ + +#include +#include +#include +#include +#include +#include + +hi_void app_demo_sdio_callback_init(hi_void); + +#endif diff --git a/sdk_liteos/app/demo/src/app_demo_spi.c b/sdk_liteos/app/demo/src/app_demo_spi.c new file mode 100644 index 0000000000000000000000000000000000000000..7973b92f3f513d2127c6a40e4af19651c42715b0 --- /dev/null +++ b/sdk_liteos/app/demo/src/app_demo_spi.c @@ -0,0 +1,937 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +hi_u8 g_spi_send_buf[BUF_LENGTH]; +hi_u8 g_spi_rcv_buf[BUF_LENGTH]; +hi_spi_idx g_spi_id = HI_SPI_ID_0; +hi_u32 g_transfer_lenth = 0; +hi_u32 g_test_loop = 0; +hi_u32 g_lb_loop = 0; +hi_u32 g_delay_us_spi = 0; +hi_spi_cfg_data_width g_data_width = HI_SPI_CFG_DATA_WIDTH_E_7BIT; + +hi_void prepare_func(hi_void) +{ + test_spi_printf("prepare"); +} + +hi_void restore_func(hi_void) +{ + test_spi_printf("restore"); +} + +hi_void app_demo_spi_print_reg(hi_spi_idx spi_id) +{ + hi_u16 reg_val; + hi_u32 reg_base; + if (spi_id == HI_SPI_ID_0) { + reg_base = HI_SSP0_REG_BASE; + } else { + reg_base = HI_SSP1_REG_BASE; + } + test_spi_printf("BASE_ADDR=%x", reg_base); + reg_val = hi_reg_read_val16(reg_base + 0x00); + test_spi_printf("REG_SPI_CR0=%x", reg_val); + reg_val = hi_reg_read_val16(reg_base + 0x04); + test_spi_printf("REG_SPI_CR1=%x", reg_val); + reg_val = hi_reg_read_val16(reg_base + 0x0c); + test_spi_printf("REG_SPI_SR=%x", reg_val); + reg_val = hi_reg_read_val16(reg_base + 0x10); + test_spi_printf("REG_SPI_CPSR=%x", reg_val); + reg_val = hi_reg_read_val16(reg_base + 0x14); + test_spi_printf("REG_SPI_IMSC=%x", reg_val); + reg_val = hi_reg_read_val16(reg_base + 0x18); + test_spi_printf("REG_SPI_RIS=%x", reg_val); + reg_val = hi_reg_read_val16(reg_base + 0x1c); + test_spi_printf("REG_SPI_MIS=%x", reg_val); + reg_val = hi_reg_read_val16(reg_base + 0x24); + test_spi_printf("REG_SPI_DMACR=%x", reg_val); + reg_val = hi_reg_read_val16(reg_base + 0x28); + test_spi_printf("REG_SPI_TXFIFOCR=%x", reg_val); + reg_val = hi_reg_read_val16(reg_base + 0x2c); + test_spi_printf("REG_SPI_RXFIFOCR=%x", reg_val); +} + +hi_void app_demo_spi_print_test_para(const test_spi_para *spi_para) +{ + if (spi_para == HI_NULL) { + test_spi_printf("spi para is null\n"); + return; + } + test_spi_printf("cpol:%d", spi_para->cfg_info.cpol); + test_spi_printf("cpha:%d", spi_para->cfg_info.cpha); + test_spi_printf("fram_mode:%d", spi_para->cfg_info.fram_mode); + test_spi_printf("data_width:%d", spi_para->cfg_info.data_width); + test_spi_printf("freq:%d", spi_para->cfg_info.freq); + test_spi_printf("spi id:%d", spi_para->spi_id); + test_spi_printf("loop:%d", spi_para->loop); + test_spi_printf("length:%d", spi_para->length); + test_spi_printf("irq:%d", spi_para->irq); + test_spi_printf("slave:%d", spi_para->slave); + test_spi_printf("lb:%d", spi_para->lb); + test_spi_printf("dma en:%d", spi_para->dma_en); + test_spi_printf("delay:%d", g_delay_us_spi); +} + +hi_void print_err_send_buf_u8(const hi_u8 *buf, hi_u32 len) +{ + hi_u32 i; + for (i = 0; i < len; i++) { + test_spi_printf("%d", buf[i]); + } +} + +hi_void print_err_send_buf_u16(const hi_u16 *buf, hi_u32 len) +{ + hi_u32 i; + for (i = 0; i < len; i++) { + test_spi_printf("%d", buf[i]); + } +} + +hi_void print_err_rev_buf_u16(const hi_u16 *buf, const hi_u16 *cmp, hi_u32 len) +{ + hi_u32 i; + for (i = 0; i < len; i++) { + test_spi_printf("%d, %d", cmp[i], buf[i]); + } +} +hi_void print_err_rev_buf_u8(const hi_u8 *buf, const hi_u8 *cmp, hi_u32 len) +{ + hi_u32 i; + for (i = 0; i < len; i++) { + test_spi_printf("%d, %d", cmp[i], buf[i]); + } +} + + +hi_u32 app_demo_spi_init(hi_spi_idx id, const hi_spi_cfg_basic_info *spi_cfg_basic_info, hi_bool slave) +{ + hi_u32 ret; + hi_spi_cfg_init_param init_param; + init_param.is_slave = slave; + ret = hi_spi_init(id, init_param, spi_cfg_basic_info); + + test_spi_printf("app_demo_spi_init ret=%x", ret); + return ret; +} + +hi_void app_demo_spi_config_gpio(hi_spi_idx id) +{ + if (id == HI_SPI_ID_0) { + hi_io_set_func(HI_IO_NAME_GPIO_5, HI_IO_FUNC_GPIO_5_SPI0_CSN); + hi_io_set_func(HI_IO_NAME_GPIO_6, HI_IO_FUNC_GPIO_6_SPI0_CK); + hi_io_set_func(HI_IO_NAME_GPIO_7, HI_IO_FUNC_GPIO_7_SPI0_RXD); + hi_io_set_func(HI_IO_NAME_GPIO_8, HI_IO_FUNC_GPIO_8_SPI0_TXD); + hi_io_set_driver_strength(HI_IO_NAME_GPIO_6, HI_IO_DRIVER_STRENGTH_2); + } else { + hi_io_set_func(HI_IO_NAME_GPIO_0, HI_IO_FUNC_GPIO_0_SPI1_CK); + hi_io_set_func(HI_IO_NAME_GPIO_1, HI_IO_FUNC_GPIO_1_SPI1_RXD); + hi_io_set_func(HI_IO_NAME_GPIO_2, HI_IO_FUNC_GPIO_2_SPI1_TXD); + hi_io_set_func(HI_IO_NAME_GPIO_3, HI_IO_FUNC_GPIO_3_SPI1_CSN); + hi_io_set_driver_strength(HI_IO_NAME_GPIO_0, HI_IO_DRIVER_STRENGTH_2); + } +} + +hi_u32 app_demo_spi_slave_send_8bits(hi_spi_idx spi_id) +{ + hi_u32 i; + hi_u32 j; + hi_u32 while_times = 0; + hi_u32 ret; + hi_u32 err_times = 0; + if (g_transfer_lenth > BUF_LENGTH) { + return HI_ERR_FAILURE; + } + i = 0; + for (j = 0; j < g_transfer_lenth; j++) { + g_spi_send_buf[j] = (hi_u8)i; + i++; + } + do { + ret = hi_spi_slave_write(spi_id, g_spi_send_buf, g_transfer_lenth, 10000); /* time out 10000 ms */ + if (ret != HI_ERR_SUCCESS) { + err_times += 1; + break; + } + hi_watchdog_feed(); + while_times++; + } while (while_times < g_test_loop || g_test_loop == 0); + test_spi_printf("demo_spi_slave_send err_send: %d,while_times:%d, ret:%x", err_times, while_times, ret); + return ret; +} + +hi_u32 app_demo_spi_slave_send_16bits(hi_spi_idx spi_id) +{ + hi_u32 i; + hi_u32 j; + hi_u32 while_times = 0; + hi_u32 ret = HI_ERR_SUCCESS; + hi_u32 index; + hi_u32 err_times = 0; + hi_u32 send_len; + do { + i = 0; + index = 0; + while (index < g_transfer_lenth) { + send_len = min(g_transfer_lenth - index, BUF_LENGTH_HALF); + for (j = 0; j < send_len; j++) { /* loops 256 */ + *((hi_u16 *)g_spi_send_buf + j) = (hi_u16)i; + i++; + } + ret = hi_spi_slave_write(spi_id, g_spi_send_buf, send_len * 2, 10000); /* 2:doubule the length 10000:ms */ + if (ret != HI_ERR_SUCCESS) { + err_times++; + print_err_send_buf_u16((hi_u16 *)g_spi_send_buf, send_len); + break; + } + hi_watchdog_feed(); + index += send_len; /* add 256 */ + } + while_times++; + } while (while_times < g_test_loop || g_test_loop == 0); + test_spi_printf("demo_spi_slave_send err_send: %d,while_times:%d, ret:%x", err_times, while_times, ret); + return ret; +} + +hi_void *app_demo_spi_slave_send_task(hi_void *param) +{ + hi_spi_idx spi_id = *(hi_spi_idx*)param; + hi_u32 ret; + hi_u32 time_old; + hi_u32 time_new; + time_old = hi_get_milli_seconds(); + if (g_data_width < HI_SPI_CFG_DATA_WIDTH_E_9BIT) { + ret = app_demo_spi_slave_send_8bits(spi_id); + } else { + ret = app_demo_spi_slave_send_16bits(spi_id); + } + if (ret != HI_ERR_SUCCESS) { + printf("app_demo_spi_slave_send fail: %x\n", ret); + } + + time_new = hi_get_milli_seconds(); + app_demo_spi_print_reg(spi_id); + test_spi_printf("demo_spi_slave_send time_old: %d,time_new %d, delt:%d", time_old, time_new, time_new - time_old); + ret = hi_spi_deinit(spi_id); + if (ret != HI_ERR_SUCCESS) { + printf("hi_spi_deinit fail: %x\n", ret); + } + return HI_NULL; +} + +hi_u32 app_demo_spi_slave_receive_8bits(hi_spi_idx spi_id) +{ + hi_u8 cmp_buf[BUF_LENGTH]; + hi_u32 while_times = 0; + hi_u32 i; + hi_u32 j; + hi_u32 ret; + hi_u32 err_times = 0; + i = 0; + if (g_transfer_lenth > BUF_LENGTH) { + return HI_ERR_FAILURE; + } + for (j = 0; j < g_transfer_lenth; j++) { + cmp_buf[j] = (hi_u8)i; + i++; + } + do { + while_times++; + memset_s(g_spi_rcv_buf, sizeof(g_spi_rcv_buf), 0x0, sizeof(g_spi_rcv_buf)); + ret = hi_spi_slave_read(spi_id, g_spi_rcv_buf, g_transfer_lenth, 10000); /* time out 10000 ms */ + if ((memcmp(g_spi_rcv_buf, cmp_buf, g_transfer_lenth) != 0) || (ret != HI_ERR_SUCCESS)) { + err_times++; + print_err_rev_buf_u8(g_spi_rcv_buf, cmp_buf, g_transfer_lenth); + break; + } + } while (while_times < g_test_loop || g_test_loop == 0); + test_spi_printf("demo_spi_rev err_rev: %d,while_times:%d, ret:%x", err_times, while_times, ret); + return ret; +} + +hi_u32 app_demo_spi_slave_receive_16bits(hi_spi_idx spi_id) +{ + hi_u8 cmp_buf[BUF_LENGTH]; + hi_u32 while_times = 0; + hi_u32 i; + hi_u32 j; + hi_u32 k; + hi_u32 ret = HI_ERR_SUCCESS; + hi_u32 err_times = 0; + hi_u32 rcv_len; + do { + k = 0; + while_times++; + i = 0; + while (k < g_transfer_lenth) { + rcv_len = min(g_transfer_lenth - k, BUF_LENGTH_HALF); + for (j = 0; j < rcv_len; j++) { + *((hi_u16 *)cmp_buf + j) = (hi_u16)i; + i++; + } + memset_s(g_spi_rcv_buf, sizeof(g_spi_rcv_buf), 0x0, sizeof(g_spi_rcv_buf)); + ret = hi_spi_slave_read(spi_id, g_spi_rcv_buf, rcv_len * 2, 10000); /* 2:doubule the length 10000:ms */ + if ((memcmp(g_spi_rcv_buf, cmp_buf, rcv_len) != 0) || (ret != HI_ERR_SUCCESS)) { + err_times++; + print_err_rev_buf_u16((hi_u16 *)g_spi_rcv_buf, (hi_u16 *)cmp_buf, rcv_len); + break; + } + hi_watchdog_feed(); + k += rcv_len; + } + } while (while_times < g_test_loop || g_test_loop == 0); + test_spi_printf("demo_spi_slave_rev err_rev: %d,while_times:%d, ret:%x", err_times, while_times, ret); + return ret; +} + +hi_void *app_demo_spi_slave_receive_task(hi_void *param) +{ + hi_spi_idx spi_id = *(hi_spi_idx*)param; + hi_u32 ret; + hi_u32 time_old; + hi_u32 time_new; + time_old = hi_get_milli_seconds(); + if (g_data_width < HI_SPI_CFG_DATA_WIDTH_E_9BIT) { + ret = app_demo_spi_slave_receive_8bits(spi_id); + } else { + ret = app_demo_spi_slave_receive_16bits(spi_id); + } + if (ret != HI_ERR_SUCCESS) { + printf("app_demo_spi_slave_receive fail: %x\n", ret); + } + + time_new = hi_get_milli_seconds(); + test_spi_printf("time_old: %d,time_new %d, delt:%d", time_old, time_new, time_new - time_old); + app_demo_spi_print_reg(spi_id); + ret = hi_spi_deinit(spi_id); + if (ret != HI_ERR_SUCCESS) { + printf("hi_spi_deinit fail: %x\n", ret); + } + return HI_NULL; +} + +hi_void *app_demo_spi_host_write_read_task(hi_void *param) +{ + hi_spi_idx spi_id = *(hi_spi_idx*)param; + hi_u32 ret; + hi_u32 i; + hi_u8 send_buf[g_transfer_lenth]; + hi_u8 recv_buf[g_transfer_lenth + 1]; + hi_u32 while_times = 0; + hi_u32 err_times = 0; + hi_u32 time_old; + hi_u32 time_new; + for (i = 0; i < g_transfer_lenth; i++) { + send_buf[i] = (hi_u8)i; + } + time_old = hi_get_milli_seconds(); + do { + memset_s(recv_buf, sizeof(recv_buf), 0x0, sizeof(recv_buf)); + ret = hi_spi_host_writeread(spi_id, send_buf, recv_buf, g_transfer_lenth); + if (memcmp(recv_buf, send_buf, g_transfer_lenth) != 0 || ret != HI_ERR_SUCCESS) { + err_times++; + } + while_times++; + } while (while_times < g_test_loop || g_test_loop == 0); + time_new = hi_get_milli_seconds(); + test_spi_printf("while_times:%d ,err_times:%d", while_times, err_times); + test_spi_printf("time_old: %d,time_new %d, delt:%d", time_old, time_new, time_new - time_old); + app_demo_spi_print_reg(spi_id); + return HI_NULL; +} + +hi_u32 app_demo_spi_host_send_8bits(hi_spi_idx spi_id) +{ + hi_u32 i; + hi_u32 j; + hi_u32 while_times = 0; + hi_u32 err_times = 0; + hi_u32 ret; + if (g_transfer_lenth > BUF_LENGTH) { + return HI_ERR_FAILURE; + } + i = 0; + for (j = 0; j < g_transfer_lenth; j++) { + g_spi_send_buf[j] = (hi_u8)i; + i++; + } + do { + ret = hi_spi_host_write(spi_id, g_spi_send_buf, g_transfer_lenth); + hi_udelay(g_delay_us_spi); + if (ret != HI_ERR_SUCCESS) { + err_times++; + break; + } + while_times++; + } while (while_times < g_test_loop || g_test_loop == 0); + test_spi_printf("demo_spi_host_send err_send: %d,while_times:%d, ret:%x", err_times, while_times, ret); + return ret; +} + +hi_u32 app_demo_spi_host_send_16bits(hi_spi_idx spi_id) +{ + hi_u32 i; + hi_u32 j; + hi_u32 while_times = 0; + hi_u32 ret = HI_ERR_SUCCESS; + hi_u32 index; + hi_u32 err_times = 0; + hi_u32 send_len; + do { + i = 0; + index = 0; + while (index < g_transfer_lenth) { + send_len = min(g_transfer_lenth - index, BUF_LENGTH_HALF); + for (j = 0; j < send_len; j++) { + *((hi_u16 *)g_spi_send_buf + j) = (hi_u16)i; + i++; + } + ret = hi_spi_host_write(spi_id, g_spi_send_buf, send_len * 2); /* 2:doubule the length */ + hi_udelay(g_delay_us_spi); + if (ret != HI_ERR_SUCCESS) { + err_times++; + print_err_send_buf_u16((hi_u16 *)g_spi_send_buf, send_len); + } + hi_watchdog_feed(); + index += send_len; + } + while_times++; + } while (while_times < g_test_loop || g_test_loop == 0); + test_spi_printf("demo_spi_slave_send err_send: %d,while_times:%d, ret:%x", err_times, while_times, ret); + return ret; +} +/* + * spi host device write data task + */ +hi_void *app_demo_spi_host_write_task(hi_void *param) +{ + hi_spi_idx spi_id = *(hi_spi_idx*)param; + hi_u32 ret; + hi_u32 time_old; + hi_u32 time_new; + time_old = hi_get_milli_seconds(); + if (g_data_width < HI_SPI_CFG_DATA_WIDTH_E_9BIT) { + ret = app_demo_spi_host_send_8bits(spi_id); + } else { + ret = app_demo_spi_host_send_16bits(spi_id); + } + if (ret != HI_ERR_SUCCESS) { + printf("app_demo_spi_host_send fail: %x\n", ret); + } + time_new = hi_get_milli_seconds(); + test_spi_printf("time_old: %d,time_new %d, delt:%d", time_old, time_new, time_new - time_old); + app_demo_spi_print_reg(spi_id); + ret = hi_spi_deinit(spi_id); + if (ret != HI_ERR_SUCCESS) { + printf("hi_spi_deinit fail: %x\n", ret); + return HI_NULL; + } + return HI_NULL; +} + +hi_u32 app_demo_spi_host_receive_8bits(hi_spi_idx spi_id) +{ + hi_u8 cmp_buf[BUF_LENGTH]; + hi_u32 while_times = 0; + hi_u32 i; + hi_u32 j; + hi_u32 err_times = 0; + hi_u32 ret; + i = 0; + if (g_transfer_lenth > BUF_LENGTH) { + return HI_ERR_FAILURE; + } + for (j = 0; j < g_transfer_lenth; j++) { + cmp_buf[j] = (hi_u8)i; + i++; + } + do { + while_times++; + if (memset_s(g_spi_rcv_buf, sizeof(g_spi_rcv_buf), 0x0, sizeof(g_spi_rcv_buf)) != EOK) { + ret = HI_ERR_MEMSET_S; + break; + } + ret = hi_spi_host_read(spi_id, g_spi_rcv_buf, g_transfer_lenth); + hi_udelay(g_delay_us_spi); + if (memcmp(g_spi_rcv_buf, cmp_buf, g_transfer_lenth) != 0) { + err_times++; + print_err_rev_buf_u8(g_spi_rcv_buf, cmp_buf, g_transfer_lenth); + break; + } + } while (while_times < g_test_loop || g_test_loop == 0); + test_spi_printf("demo_spi_host_rev err_rev: %d,while_times:%d, ret:%x", err_times, while_times, ret); + return ret; +} + +hi_u32 app_demo_spi_host_receive_16bits(hi_spi_idx spi_id) +{ + hi_u8 cmp_buf[BUF_LENGTH]; + hi_u32 while_times = 0; + hi_u32 err_times = 0; + hi_u32 i; + hi_u32 j; + hi_u32 k; + hi_u32 ret = HI_ERR_SUCCESS; + hi_u32 recv_len; + do { + k = 0; + while_times++; + i = 0; + while (k < g_transfer_lenth) { + recv_len = min(g_transfer_lenth - k, BUF_LENGTH_HALF); + for (j = 0; j < recv_len; j++) { + *((hi_u16 *)cmp_buf + j) = (hi_u16)i; + i++; + } + memset_s(g_spi_rcv_buf, sizeof(g_spi_rcv_buf), 0x0, sizeof(g_spi_rcv_buf)); + ret = hi_spi_host_read(spi_id, g_spi_rcv_buf, recv_len * 2); /* 2:doubule the length */ + hi_udelay(g_delay_us_spi); + if (memcmp(g_spi_rcv_buf, cmp_buf, recv_len * 2) != 0) { /* 2:doubule the length */ + err_times++; + print_err_rev_buf_u16((hi_u16 *)g_spi_rcv_buf, (hi_u16 *)cmp_buf, recv_len); + break; + } + hi_watchdog_feed(); + k += recv_len; + } + } while (while_times < g_test_loop || g_test_loop == 0); + test_spi_printf("demo_spi_host_rev err_rev: %d,while_times:%d, ret:%x", err_times, while_times, ret); + return ret; +} + +/* + * spi host device read data task + */ +hi_void *app_demo_spi_host_read_task(hi_void *param) +{ + hi_spi_idx spi_id = *(hi_spi_idx*)param; + printf("spi_id:%d\n", spi_id); + hi_u32 ret; + hi_u32 time_old; + hi_u32 time_new; + time_old = hi_get_milli_seconds(); + if (g_data_width < HI_SPI_CFG_DATA_WIDTH_E_9BIT) { + ret = app_demo_spi_host_receive_8bits(spi_id); + } else { + ret = app_demo_spi_host_receive_16bits(spi_id); + } + if (ret != HI_ERR_SUCCESS) { + printf("app_demo_spi_host_receive fail: %x\n", ret); + } + time_new = hi_get_milli_seconds(); + test_spi_printf("time_old: %d,time_new %d, delt:%d", time_old, time_new, time_new - time_old); + app_demo_spi_print_reg(spi_id); + ret = hi_spi_deinit(spi_id); + if (ret != HI_ERR_SUCCESS) { + printf("hi_spi_deinit fail: %x\n", ret); + } + return HI_NULL; +} + +/* + * host device write data and slave device read data + */ +hi_void app_demo_spi_test_cmd_mw_sr(const test_spi_para *spi_para) +{ + hi_u32 ret; + hi_u32 taskid1; + hi_task_attr attr; + + test_spi_printf("app_demo_spi_test_cmd_mw_sr Start"); + ret = app_demo_spi_init(spi_para->spi_id, &(spi_para->cfg_info), spi_para->slave); + + g_transfer_lenth = spi_para->length; + g_spi_id = spi_para->spi_id; + if (ret == HI_ERR_SUCCESS) { + test_spi_printf("SPI init succ!"); + } else { + test_spi_printf("SPI init fail! %x ", ret); + return; + } + hi_spi_set_loop_back_mode(spi_para->spi_id, spi_para->lb); + app_demo_spi_config_gpio(spi_para->spi_id); + g_test_loop = spi_para->loop; + g_data_width = (hi_spi_cfg_data_width)spi_para->cfg_info.data_width; + hi_sleep(1000); /* 1000 */ + hi_spi_set_irq_mode(spi_para->spi_id, spi_para->irq); + hi_spi_set_dma_mode(spi_para->spi_id, spi_para->dma_en); + if (spi_para->slave == 0) { + attr.task_prio = 5; /* priority 5 */ + attr.stack_size = 0x2000; + attr.task_name = (hi_char *)"spi_host"; + ret = hi_task_create(&taskid1, &attr, app_demo_spi_host_write_task, (hi_void *)&spi_para->spi_id); + } else { + attr.task_prio = 5; /* priority 5 */ + attr.stack_size = 0x2000; + attr.task_name = (hi_char *)"r_spi_slave"; + ret = hi_task_create(&taskid1, &attr, app_demo_spi_slave_receive_task, (hi_void *)&spi_para->spi_id); + } + test_spi_printf("SPI Test End!"); +} + +/* + * host device read data and slave device write data + */ +hi_void app_demo_spi_test_cmd_mr_sw(const test_spi_para *spi_para) +{ + hi_u32 ret; + hi_u32 taskid1; + hi_task_attr attr; + + test_spi_printf("app_demo_spi_test_cmd_mr_sw Start"); + ret = app_demo_spi_init(spi_para->spi_id, &(spi_para->cfg_info), spi_para->slave); + app_demo_spi_config_gpio(spi_para->spi_id); + g_transfer_lenth = spi_para->length; + g_spi_id = spi_para->spi_id; + g_data_width = (hi_spi_cfg_data_width)spi_para->cfg_info.data_width; + if (ret == HI_ERR_SUCCESS) { + test_spi_printf("SPI init succ!"); + } else { + test_spi_printf("SPI init fail! %x ", ret); + return; + } + hi_spi_set_loop_back_mode(spi_para->spi_id, spi_para->lb); + g_test_loop = spi_para->loop; + hi_sleep(1000); /* 1000 */ + hi_spi_set_irq_mode(spi_para->spi_id, spi_para->irq); + ret = hi_spi_set_dma_mode(spi_para->spi_id, spi_para->dma_en); + printf("hi_spi_set_dma_mode :%x\n", ret); + if (spi_para->slave == 0) { + attr.task_prio = 25; /* priority 25 */ + attr.stack_size = 0x2000; + attr.task_name = (hi_char *)"spi_host"; + ret = hi_task_create(&taskid1, &attr, app_demo_spi_host_read_task, (hi_void *)&spi_para->spi_id); + } else { + attr.task_prio = 25; /* priority 25 */ + attr.stack_size = 0x2000; + attr.task_name = (hi_char *)"w_spi_slave"; + ret = hi_task_create(&taskid1, &attr, app_demo_spi_slave_send_task, (hi_void *)&spi_para->spi_id); + } + test_spi_printf("SPI Test End!"); +} + +hi_u32 app_demo_spi_single_loopback(hi_spi_idx spi_id, hi_u8 data_width) +{ + hi_u32 ret; + hi_u32 i; + hi_u8 send_buf[512] = { 0 }; /* 512 */ + hi_u8 recv_buf[512] = { 0 }; /* 512 */ + hi_u32 test_length = 243; /* 243: test length */ + hi_u32 while_times = 0; + do { + if (data_width < HI_SPI_CFG_DATA_WIDTH_E_8BIT) { + test_length = (0x1 << data_width) - 1; + } + while_times++; + printf("while_times:%d \n", while_times); + memset_s(recv_buf, sizeof(recv_buf), 0x0, sizeof(recv_buf)); + if (data_width >= HI_SPI_CFG_DATA_WIDTH_E_9BIT) { + for (i = 0; i < 256; i++) { /* loop 256 times */ + *((hi_u16 *)send_buf + i) = (hi_u16)i; + } + ret = hi_spi_host_writeread(spi_id, (hi_pvoid)send_buf, (hi_pvoid)recv_buf, test_length * 2); /* 2 */ + if (ret != HI_ERR_SUCCESS) { + return ret; + } + if (memcmp(recv_buf, send_buf, test_length * 2) != 0) { /* 2 double buf length */ + print_err_rev_buf_u16((hi_u16 *)send_buf, (hi_u16 *)recv_buf, test_length); + return HI_ERR_FAILURE; + } + continue; + } + for (i = 0; i < 512; i++) { /* 512 */ + send_buf[i] = (hi_u8)i; + } + ret = hi_spi_host_writeread(spi_id, (hi_pvoid)send_buf, (hi_pvoid)recv_buf, test_length); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + if (memcmp(recv_buf, send_buf, test_length) != 0) { + for (i = 0; i < test_length; i++) { + test_spi_printf("b[%d]i[%d]s[%d]r[%d]", data_width + 1, i, send_buf[i], recv_buf[i]); + } + return HI_ERR_FAILURE; + } + } while (while_times <= g_lb_loop); + return ret; +} + +hi_u32 app_demo_spi_para_test(hi_spi_cfg_basic_info *spi_para) +{ + hi_u32 ret; + spi_para->data_width = 2; /* data width 2 */ + ret = hi_spi_set_basic_info(g_spi_id, spi_para); + if (ret != HI_ERR_SPI_PARAMETER_WRONG) { + return HI_ERR_FAILURE; + } + spi_para->data_width = HI_SPI_CFG_DATA_WIDTH_E_8BIT; + spi_para->fram_mode = 3; /* data protocol 3 */ + ret = hi_spi_set_basic_info(g_spi_id, spi_para); + if (ret != HI_ERR_SPI_PARAMETER_WRONG) { + return HI_ERR_FAILURE; + } + spi_para->fram_mode = HI_SPI_CFG_FRAM_MODE_MOTOROLA; + spi_para->freq = 80000000; /* Clock rate 13 80000000 */ + ret = hi_spi_set_basic_info(g_spi_id, spi_para); + if (ret != HI_ERR_SPI_PARAMETER_WRONG) { + return HI_ERR_FAILURE; + } + spi_para->freq = 1000; /* Clock rate 256 1000 */ + ret = hi_spi_set_basic_info(g_spi_id, spi_para); + if (ret != HI_ERR_SPI_PARAMETER_WRONG) { + return HI_ERR_FAILURE; + } + spi_para->freq = 2000000; /* Clock rate 24 2000000 */ + return HI_ERR_SUCCESS; +} + +hi_void app_demo_spi_test_case_part1(hi_spi_cfg_basic_info *spi_para, hi_u8 test_case) +{ + switch (test_case) { + case TEST_CASE_POL0_PHA0: + spi_para->cpol = HI_SPI_CFG_CLOCK_CPOL_0; + spi_para->cpha = HI_SPI_CFG_CLOCK_CPHA_0; + break; + case TEST_CASE_POL0_PHA1: + spi_para->cpol = HI_SPI_CFG_CLOCK_CPOL_0; + spi_para->cpha = HI_SPI_CFG_CLOCK_CPHA_1; + break; + case TEST_CASE_POL1_PHA0: + spi_para->cpol = HI_SPI_CFG_CLOCK_CPOL_1; + spi_para->cpha = HI_SPI_CFG_CLOCK_CPHA_0; + break; + case TEST_CASE_POL1_PHA1: + spi_para->cpol = HI_SPI_CFG_CLOCK_CPOL_1; + spi_para->cpha = HI_SPI_CFG_CLOCK_CPHA_1; + break; + case TEST_CASE_MOTOROLA: + spi_para->fram_mode = HI_SPI_CFG_FRAM_MODE_MOTOROLA; + break; + case TEST_CASE_TI: + spi_para->fram_mode = HI_SPI_CFG_FRAM_MODE_TI; + break; + /* Microware does not support self-loopback tests. Two devices must be connected for tests. */ + case TEST_CASE_BIT4: + spi_para->data_width = HI_SPI_CFG_DATA_WIDTH_E_4BIT; + break; + case TEST_CASE_BIT7: + spi_para->data_width = HI_SPI_CFG_DATA_WIDTH_E_7BIT; + break; + case TEST_CASE_BIT8: + spi_para->data_width = HI_SPI_CFG_DATA_WIDTH_E_8BIT; + break; + case TEST_CASE_BIT9: + spi_para->data_width = HI_SPI_CFG_DATA_WIDTH_E_9BIT; + break; + case TEST_CASE_BIT15: + spi_para->data_width = HI_SPI_CFG_DATA_WIDTH_E_15BIT; + break; + case TEST_CASE_BIT16: + spi_para->data_width = HI_SPI_CFG_DATA_WIDTH_E_16BIT; + break; + default: + break; + } +} + +hi_u32 app_demo_spi_test_case_part2(hi_spi_cfg_basic_info *spi_para, hi_u8 test_case, hi_u8 *flag) +{ + switch (test_case) { + case TEST_CASE_CLK_MIN: + spi_para->freq = 20000000; /* Clock rate 4 20000000 */ + break; + case TEST_CASE_CLK_16: + spi_para->freq = 5000000; /* Clock rate 16 5000000 */ + break; + case TEST_CASE_CLK_50: + spi_para->freq = 1600000; /* Clock rate 50 1600000 */ + break; + case TEST_CASE_CLK_100: + spi_para->freq = 800000; /* Clock rate 100 800000 */ + break; + case TEST_CASE_CLK_200: + spi_para->freq = 400000; /* Clock rate 200 400000 */ + break; + case TEST_CASE_PARAMETER_WRONG: + *flag = 1; + return app_demo_spi_para_test(spi_para); + default: + break; + } + return HI_ERR_SUCCESS; +} + +hi_u32 app_demo_spi_test_case(hi_u8 test_case) +{ + hi_u32 ret; + hi_u8 flag = 0; + hi_spi_cfg_basic_info spi_para = { + .data_width = HI_SPI_CFG_DATA_WIDTH_E_8BIT, + .fram_mode = HI_SPI_CFG_FRAM_MODE_MOTOROLA, + .cpol = HI_SPI_CFG_CLOCK_CPOL_0, + .cpha = HI_SPI_CFG_CLOCK_CPHA_0, + .endian = HI_SPI_CFG_ENDIAN_LITTLE, + .pad = 0, + .freq = 2000000, /* Clock rate 24 2000000 */ + }; + app_demo_spi_test_case_part1(&spi_para, test_case); + ret = app_demo_spi_test_case_part2(&spi_para, test_case, &flag); + if (flag) { + return ret; + } + ret = hi_spi_set_basic_info(g_spi_id, &spi_para); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + return app_demo_spi_single_loopback(g_spi_id, spi_para.data_width); +} + +/* + * Test SPI unit parameters and loop back mode + */ +hi_void app_demo_spi_test(hi_spi_idx spi_id, hi_u32 irq_en, hi_u32 test_case, hi_u32 loop) +{ + test_spi_printf("SPI%d TEST START", spi_id); + hi_spi_cfg_basic_info spi_cfg_basic_info; + spi_cfg_basic_info.cpha = 1; + spi_cfg_basic_info.cpol = 1; + spi_cfg_basic_info.data_width = HI_SPI_CFG_DATA_WIDTH_E_7BIT; + spi_cfg_basic_info.endian = 0; + spi_cfg_basic_info.fram_mode = 0; + spi_cfg_basic_info.freq = 2000000; /* set frequency 2000000 */ + app_demo_spi_init(spi_id, &spi_cfg_basic_info, HI_FALSE); + hi_spi_set_loop_back_mode(spi_id, HI_TRUE); + hi_spi_set_irq_mode(spi_id, (hi_bool)irq_en); + g_spi_id = spi_id; + g_lb_loop = loop; + if (test_case == TEST_CASE_ALL) { + /* The last three test case need connect Peripherals */ + for (int i = TEST_CASE_POL0_PHA0; i < TEST_CASE_SLAVE; i++) { + hi_u32 ret = app_demo_spi_test_case((hi_u8)i); + test_spi_printf("===spi[%d]====TEST_CASE %d %s!=====", spi_id, i, + ret == HI_ERR_SUCCESS ? "SUCCESS!" : "FAILURE!"); + } + } else { + if (test_case >= TEST_CASE_MAX) { + test_spi_printf("INVALID TEST CASE!"); + return; + } + hi_u32 ret = app_demo_spi_test_case((hi_u8)test_case); + test_spi_printf("===spi[%d]====TEST_CASE %d %s!=====", spi_id, test_case, + ret == HI_ERR_SUCCESS ? "SUCCESS!" : "FAILURE!"); + } + app_demo_spi_print_reg(g_spi_id); + test_spi_printf("SPI%d TEST END", spi_id); +} + +/* + * The host device sets the SPI unit and read data + */ +hi_void app_demo_spi_cmd_host_read(hi_spi_idx spi_id, hi_u32 length, hi_u32 loop) +{ + test_spi_para spi_para; + spi_para.spi_id = spi_id; + spi_para.irq = HI_FALSE; + spi_para.length = length; + spi_para.loop = loop; + spi_para.cfg_info.data_width = HI_SPI_CFG_DATA_WIDTH_E_8BIT; + spi_para.cfg_info.cpha = HI_SPI_CFG_CLOCK_CPHA_0; + spi_para.cfg_info.cpol = HI_SPI_CFG_CLOCK_CPOL_0; + spi_para.cfg_info.fram_mode = HI_SPI_CFG_FRAM_MODE_MOTOROLA; + spi_para.cfg_info.endian = HI_SPI_CFG_ENDIAN_LITTLE; + spi_para.slave = HI_FALSE; + spi_para.lb = HI_FALSE; + spi_para.dma_en = HI_FALSE; + g_delay_us_spi = 200; /* 200us */ + spi_para.cfg_info.freq = 8000000; /* defaul freq 8000000 Hz */ + app_demo_spi_print_test_para(&spi_para); + app_demo_spi_test_cmd_mr_sw(&spi_para); +} + +/* + * The slave device sets the SPI unit and write data + */ +hi_void app_demo_spi_cmd_slave_write(hi_spi_idx spi_id, hi_u32 length, hi_u32 loop) +{ + test_spi_para spi_para; + spi_para.spi_id = spi_id; + spi_para.irq = HI_FALSE; + spi_para.length = length; + spi_para.loop = loop; + spi_para.cfg_info.data_width = HI_SPI_CFG_DATA_WIDTH_E_8BIT; + spi_para.cfg_info.cpha = HI_SPI_CFG_CLOCK_CPHA_0; + spi_para.cfg_info.cpol = HI_SPI_CFG_CLOCK_CPOL_0; + spi_para.cfg_info.fram_mode = HI_SPI_CFG_FRAM_MODE_MOTOROLA; + spi_para.cfg_info.endian = HI_SPI_CFG_ENDIAN_LITTLE; + spi_para.slave = HI_TRUE; + spi_para.lb = HI_FALSE; + spi_para.dma_en = HI_TRUE; + g_delay_us_spi = 0; + spi_para.cfg_info.freq = 8000000; /* defaul freq 8000000 Hz */ + app_demo_spi_print_test_para(&spi_para); + app_demo_spi_test_cmd_mr_sw(&spi_para); +} + +/* + * The host device sets the SPI unit and write data + */ +hi_void app_demo_spi_cmd_host_write(hi_spi_idx spi_id, hi_u32 length, hi_u32 loop) +{ + test_spi_para spi_para; + spi_para.spi_id = spi_id; + spi_para.irq = HI_FALSE; + spi_para.length = length; + spi_para.loop = loop; + spi_para.cfg_info.data_width = HI_SPI_CFG_DATA_WIDTH_E_8BIT; + spi_para.cfg_info.cpha = HI_SPI_CFG_CLOCK_CPHA_0; + spi_para.cfg_info.cpol = HI_SPI_CFG_CLOCK_CPOL_0; + spi_para.cfg_info.fram_mode = HI_SPI_CFG_FRAM_MODE_MOTOROLA; + spi_para.cfg_info.endian = HI_SPI_CFG_ENDIAN_LITTLE; + spi_para.slave = HI_FALSE; + spi_para.lb = HI_FALSE; + spi_para.dma_en = HI_FALSE; + g_delay_us_spi = 100; /* 100 us */ + spi_para.cfg_info.freq = 8000000; /* defaul freq 8000000 Hz */ + app_demo_spi_print_test_para(&spi_para); + app_demo_spi_test_cmd_mw_sr(&spi_para); +} + +/* + * The slave device sets the SPI unit and read data + */ +hi_void app_demo_spi_cmd_slave_read(hi_spi_idx spi_id, hi_u32 length, hi_u32 loop) +{ + test_spi_para spi_para; + spi_para.spi_id = spi_id; + spi_para.irq = HI_FALSE; + spi_para.length = length; + spi_para.loop = loop; + spi_para.cfg_info.data_width = HI_SPI_CFG_DATA_WIDTH_E_8BIT; + spi_para.cfg_info.cpha = HI_SPI_CFG_CLOCK_CPHA_0; + spi_para.cfg_info.cpol = HI_SPI_CFG_CLOCK_CPOL_0; + spi_para.cfg_info.fram_mode = HI_SPI_CFG_FRAM_MODE_MOTOROLA; + spi_para.cfg_info.endian = HI_SPI_CFG_ENDIAN_LITTLE; + spi_para.slave = HI_TRUE; + spi_para.lb = HI_FALSE; + spi_para.dma_en = HI_TRUE; + g_delay_us_spi = 0; + spi_para.cfg_info.freq = 8000000; /* defaul freq 8000000 Hz */ + app_demo_spi_print_test_para(&spi_para); + app_demo_spi_test_cmd_mw_sr(&spi_para); +} + diff --git a/sdk_liteos/app/demo/src/app_demo_timer_systick.c b/sdk_liteos/app/demo/src/app_demo_timer_systick.c new file mode 100644 index 0000000000000000000000000000000000000000..0090e3750b2a37035826cd340a0dee3c227fada2 --- /dev/null +++ b/sdk_liteos/app/demo/src/app_demo_timer_systick.c @@ -0,0 +1,133 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +hi_u64 g_time1; +hi_u64 g_time2; +hi_u32 g_hrtimer_handle; /* hr timer handle */ +hi_u32 g_timer_handle; /* timer handle */ + +/* hrtimer callback func */ +hi_void hr_timer_callback(hi_u32 data) +{ + g_time2 = hi_systick_get_cur_tick(); + + printf("----- hrtimer_callback data:%d\r\n", data); + + printf("----- hrtimer_callback, g_time1:%lld\r\n", g_time1); + printf("----- hrtimer_callback, g_time2:%lld\r\n", g_time2); + printf("----- hrtimer_callback, cha:%lld\r\n", g_time2 - g_time1); + + printf("***** sleep 50000us ******\r\n"); +} + +/* + * This demo simply shows how to create and start hrtimer. + */ +hi_void app_demo_hrtimer(hi_void) +{ + hi_u32 ret; + + /* create timer handle */ + ret = hi_hrtimer_create(&g_hrtimer_handle); + if (ret != HI_ERR_SUCCESS) { + printf("=====ERROR===== hrtimer handle create ret is: %d !!\r\n", ret); + return; + } + printf("----- hrtimer handle create success -----\n"); + + g_time1 = hi_systick_get_cur_tick(); + + ret = hi_hrtimer_start(g_hrtimer_handle, HRTIMER_EXPIRE, hr_timer_callback, 0); + if (ret != HI_ERR_SUCCESS) { + printf("=====ERROR=====hrtimer start error, ret is: %d !!\n", ret); + return; + } + printf("----- hrtimer start success -----\n"); + + hi_sleep(1000); /* sleep 1000 to prevent the timer from being destroyed before the callback function is completed */ + ret = hi_hrtimer_stop(g_hrtimer_handle); + if (ret != HI_ERR_SUCCESS) { + printf("=====ERROR===== hrtimer stop error, ret is: %d !!\r\n", ret); + } + printf("----- hrtimer stop success -----\n"); + + /* delete timer */ + ret = hi_hrtimer_delete(g_hrtimer_handle); + if (ret != HI_ERR_SUCCESS) { + printf("=====ERROR===== hrtimer delete error, ret is: %d !!\r\n", ret); + } + printf("----- hrtimer handle delete success -----\n"); +} + +/* + * This demo simply shows how to use systick. + */ +hi_void app_demo_systick(hi_void) +{ + hi_u64 cnt1; + hi_u64 cnt2; + + /* Get the current tick value, then clear the tick and get the tick value again */ + cnt1 = hi_systick_get_cur_tick(); + printf("----- get current tick cnt1 is %llu -----\r\n", cnt1); + hi_systick_clear(); + hi_udelay(WORK_TICK_DELAY_US * 3); /* systick waits for 3 tick before clearing */ + cnt2 = hi_systick_get_cur_tick(); + printf("----- get current tick cnt2 is %llu -----\r\n", cnt2); + + /* Because of the error, the number read immediately after clearing cannot be guaranteed to be 0, + so cnt2 which less than 20us is qualified */ + if (cnt2 < 20) { /* 20us */ + printf("----- systick clear success -----\r\n"); + } else { + printf("======ERROR===== systick clear error, cnt2 = %llu\r\n", cnt2); + } +} + +static hi_void app_demo_timer_handle(hi_u32 data) +{ + hi_unref_param(data); + printf("app demo timer timeout\r\n"); +} + +/* + * This demo simply shows how to create and start os timer. + */ +hi_void app_demo_timer(hi_void) +{ + hi_u32 ret; + ret = hi_timer_create(&g_timer_handle); + if (ret != HI_ERR_SUCCESS) { + printf("timer create fail\r\n"); + } + printf("timer create success\r\n"); + + ret = hi_timer_start(g_timer_handle, HI_TIMER_TYPE_ONCE, APP_DEMO_TIMER_WAIT, app_demo_timer_handle, 0); + if (ret != HI_ERR_SUCCESS) { + printf("timer start fail\r\n"); + } + printf("timer start success\r\n"); + + hi_sleep(20000); /* 20000: sleep 20s */ + + ret = hi_timer_stop(g_timer_handle); + if (ret != HI_ERR_SUCCESS) { + printf("timer stop fail\r\n"); + } + printf("timer stop success\r\n"); +} + diff --git a/sdk_liteos/app/demo/src/app_demo_tsensor.c b/sdk_liteos/app/demo/src/app_demo_tsensor.c new file mode 100644 index 0000000000000000000000000000000000000000..184c899c550755305d9759334c5b8730003bfabe --- /dev/null +++ b/sdk_liteos/app/demo/src/app_demo_tsensor.c @@ -0,0 +1,123 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +hi_u32 g_tsensor_loop_count = 0; + +static hi_void tensor_collect_finish_irq(hi_s16 irq_temperature) +{ + hi_u64 cnt; + + cnt = hi_systick_get_cur_tick(); + printf("cnt = %lld\n", cnt); + printf("read temperature: %d\n", irq_temperature); + if (g_tsensor_loop_count > TSENSOR_TEST_LOOP) { + g_tsensor_loop_count = 0; + + hi_tsensor_stop(); + printf("*********stop tsensor***********\n"); + printf("**** End of reading temperature by interrupt mode****\r\n"); + } + + g_tsensor_loop_count++; +} + +static hi_void tensor_outtemp_irq(hi_s16 irq_temperature) +{ + hi_s16 temperature; + temperature = irq_temperature; + + printf("temperature: %d is outtemp!!\n", temperature); + hi_tsensor_stop(); + printf("*********stop tsensor***********\n"); +} + +static hi_void tensor_overtemp_irq(hi_s16 irq_temperature) +{ + hi_s16 temperature; + temperature = irq_temperature; + + printf("temperature: %d is overtemp!!\n", temperature); + hi_tsensor_destroy(); + printf("*********destroy tsensor***********\n"); +} + +static hi_void read_temprature_none_irq_single(hi_void) +{ + hi_s32 i; + + for (i = 0; i < TSENSOR_TEST_LOOP; i++) { + hi_udelay((hi_u32)TSENSOR_GET_TEMPERRATURE_INTERVAL); + hi_s16 temperature = 0; + if (hi_tsensor_read_temperature(&temperature) == HI_ERR_SUCCESS) { + printf("Read success: temperature = %d\n", temperature); + } else { + printf("Read fail, continue!\n"); + } + } + + hi_sleep(TSENSOR_TEST_INTERVAL); +} + +/* + * This demo simply shows how to set temperature protect threshold and read temperature by polling or interrupt mode. + */ +hi_void tsensor_demo(hi_void) +{ + hi_u32 ret; + + hi_sleep(TSENSOR_TEST_INTERVAL); + printf("\n**** set temperature threshold ****\n"); + /* Set power down temperature threshold. */ + ret = hi_tsensor_set_pdtemp_threshold(TEMPERRATURE_POWER_DOWN_THRESHOLD); + if (ret != HI_ERR_SUCCESS) { + printf("Failed to set power down temperature threshold! Err code = %X\n", ret); + return; + } + + /* Set over temperature threshold and register callback function. */ + hi_tsensor_set_overtemp_threshold(TEMPERRATURE_OVER_THRESHOLD, tensor_overtemp_irq); + if (ret != HI_ERR_SUCCESS) { + printf("Failed to set overtemp temperature threshold! Err code = %X\n", ret); + return; + } + + /* Set out temperature threshold and register callback function. */ + hi_tsensor_set_outtemp_threshold(TEMPERRATURE_OUT_THRESHOLD_LOW, + TEMPERRATURE_OUT_THRESHOLD_HIGH, tensor_outtemp_irq); + if (ret != HI_ERR_SUCCESS) { + printf("Failed to set outtemp temperature threshold! Err code = %X\n", ret); + return; + } + hi_tsensor_start(HI_TSENSOR_MODE_16_POINTS_SINGLE, TSENSOR_PERIOD_VALUE); + hi_sleep(TSENSOR_TEST_INTERVAL); + printf("**** End of setting temperature threshold ****\n"); + + printf("\n**** read temperature by polling mode****\n"); + hi_tsensor_start(HI_TSENSOR_MODE_16_POINTS_SINGLE, TSENSOR_PERIOD_VALUE); + /* Read temperature by polling mode. */ + read_temprature_none_irq_single(); + hi_tsensor_stop(); + printf("**** End of reading temperature by polling mode****\n"); + + printf("\n**** read temperature by interrupt mode****\n"); + /* Read temperature by interrupt mode. */ + hi_tsensor_register_temp_collect_finish_int_callback(tensor_collect_finish_irq); + if (ret != HI_ERR_SUCCESS) { + return; + } + hi_tsensor_start(HI_TSENSOR_MODE_16_POINTS_SINGLE, TSENSOR_PERIOD_VALUE); +} diff --git a/sdk_liteos/app/demo/src/app_demo_uart.c b/sdk_liteos/app/demo/src/app_demo_uart.c new file mode 100644 index 0000000000000000000000000000000000000000..f9f32607c5fdd027d45e62a1cf9a382657a19bb6 --- /dev/null +++ b/sdk_liteos/app/demo/src/app_demo_uart.c @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +hi_u32 g_uart_demo_task_id = 0; + +static hi_void *uart_demo_task(hi_void *param) +{ + hi_u8 uart_buff[UART_BUFF_SIZE] = {0}; + hi_u8 *uart_buff_ptr = uart_buff; + hi_unref_param(param); + printf("Initialize uart demo successfully, please enter some datas via DEMO_UART_NUM port...\n"); + + for (;;) { + hi_s32 len = hi_uart_read(DEMO_UART_NUM, uart_buff_ptr, UART_BUFF_SIZE); + if (len > 0) { +#ifdef WRITE_BY_INT + hi_uart_write(DEMO_UART_NUM, uart_buff_ptr, len); +#else + hi_uart_write_immediately(DEMO_UART_NUM, uart_buff_ptr, len); +#endif + } else { + printf("Read nothing!\n"); + hi_sleep(1000); /* sleep 1000ms */ + } + } + + hi_task_delete(g_uart_demo_task_id); + g_uart_demo_task_id = 0; + + return HI_NULL; +} + +/* + * This demo simply shows how to read datas from UART2 port and then echo back. + */ +hi_void uart_demo(hi_void) +{ + hi_u32 ret; + hi_uart_attribute uart_attr = { + .baud_rate = 115200, /* baud_rate: 115200 */ + .data_bits = 8, /* data_bits: 8bits */ + .stop_bits = 1, + .parity = 0, + }; + + /* Initialize uart driver */ + ret = hi_uart_init(DEMO_UART_NUM, &uart_attr, HI_NULL); + if (ret != HI_ERR_SUCCESS) { + printf("Failed to init uart! Err code = %d\n", ret); + return; + } + + /* Create a task to handle uart communication */ + hi_task_attr attr = {0}; + attr.stack_size = UART_DEMO_TASK_STAK_SIZE; + attr.task_prio = UART_DEMO_TASK_PRIORITY; + attr.task_name = (hi_char*)"uart_demo"; + ret = hi_task_create(&g_uart_demo_task_id, &attr, uart_demo_task, HI_NULL); + if (ret != HI_ERR_SUCCESS) { + printf("Falied to create uart demo task!\n"); + } +} diff --git a/sdk_liteos/app/demo/src/app_demo_upg_verify.c b/sdk_liteos/app/demo/src/app_demo_upg_verify.c new file mode 100644 index 0000000000000000000000000000000000000000..585ba07190e541907ad96983937cb5e333d9eb84 --- /dev/null +++ b/sdk_liteos/app/demo/src/app_demo_upg_verify.c @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "app_demo_upg_verify.h" +#include +#include + +hi_u32 app_demo_upg_check_chip_product(const hi_upg_user_info *info, hi_void *param) +{ + hi_char file_chip[HI_APP_CHIP_PRODUCT_LEN] = { 0 }; + app_upg_user_info *user_info = HI_NULL; + + hi_unref_param(param); + if (info == HI_NULL) { + printf("[app upg demo verify]null."); + return HI_ERR_FAILURE; + } + user_info = (app_upg_user_info *)info; + if (sprintf_s(file_chip, HI_APP_CHIP_PRODUCT_LEN, "%s", CONFIG_CHIP_PRODUCT_NAME) < 0) { + printf("[app upg demo verify]sprintf_s error \r\n"); + return HI_ERR_FAILURE; + } + printf("[app upg demo verify]kernel chip product:%s \r\n", file_chip); + + if (memcmp(user_info->chip_product, file_chip, HI_APP_CHIP_PRODUCT_LEN) == EOK) { + return HI_ERR_SUCCESS; + } + + return HI_ERR_FAILURE; +} + +hi_u32 app_demo_upg_init(hi_void) +{ + return hi_upg_register_file_verify_fn(app_demo_upg_check_chip_product, HI_NULL); +} diff --git a/sdk_liteos/app/demo/src/app_demo_upg_verify.h b/sdk_liteos/app/demo/src/app_demo_upg_verify.h new file mode 100644 index 0000000000000000000000000000000000000000..831664c0b752f1a65faa8ee6f6833e2a9208e3f0 --- /dev/null +++ b/sdk_liteos/app/demo/src/app_demo_upg_verify.h @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _APP_DEMO_UPG_VERIFY_H_ +#define _APP_DEMO_UPG_VERIFY_H_ + +#include + +#define HI_APP_CHIP_PRODUCT_LEN 8 /* 8: chip product length */ + +typedef struct { + hi_char chip_product[HI_APP_CHIP_PRODUCT_LEN]; + hi_u8 reserved[24]; /* 24 bytes reserved */ +}app_upg_user_info; + +hi_u32 app_demo_upg_init(hi_void); + +#endif /* _APP_DEMO_UPG_VERIFY_H_ */ + diff --git a/sdk_liteos/app/demo/src/app_http_client.c b/sdk_liteos/app/demo/src/app_http_client.c new file mode 100644 index 0000000000000000000000000000000000000000..a2f3a6b4d25586959619711f128f1b72dd5bcd12 --- /dev/null +++ b/sdk_liteos/app/demo/src/app_http_client.c @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "hi_stdlib.h" +#include "lwip/sockets.h" +#include "lwip/netdb.h" +#include "app_http_client.h" +#define HTTPC_DEMO_RECV_BUFSIZE 64 +#define SOCK_TARGET_PORT 80 + +static const char *g_request = "GET / HTTP/1.1\r\n\ +Content-Type: application/x-www-form-urlencoded;charset=UTF-8\r\n\ +Host: baidu.com\r\n\ +Connection: close\r\n\ +\r\n"; + +/***************************************************************************** +* Func description: demo for http get action +*****************************************************************************/ +unsigned int http_clienti_get(int argc, const char *argv[]) +{ + if ((argc != 1) || (argv == NULL)) { + return 1; + } + struct sockaddr_in addr = {0}; + int s, r; + char recv_buf[HTTPC_DEMO_RECV_BUFSIZE]; + addr.sin_family = AF_INET; + addr.sin_port = PP_HTONS(SOCK_TARGET_PORT); + addr.sin_addr.s_addr = inet_addr(argv[0]); + s = socket(AF_INET, SOCK_STREAM, 0); + if (s < 0) { + return 1; + } + printf("... allocated socket"); + if (connect(s, (struct sockaddr*)&addr, sizeof(addr)) != 0) { + printf("... socket connect failed errno=%d", errno); + lwip_close(s); + return 1; + } + printf("... connected"); + if (lwip_write(s, g_request, strlen(g_request)) < 0) { + lwip_close(s); + return 1; + } + printf("... socket send success"); + struct timeval receiving_timeout; + /* 5S Timeout */ + receiving_timeout.tv_sec = 5; + receiving_timeout.tv_usec = 0; + if (setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &receiving_timeout, sizeof(receiving_timeout)) < 0) { + printf("... failed to set socket receiving timeout"); + lwip_close(s); + return 1; + } + printf("... set socket receiving timeout success"); + /* Read HTTP response */ + do { + (void)memset_s(recv_buf, sizeof(recv_buf), 0, sizeof(recv_buf)); + r = lwip_read(s, recv_buf, sizeof(recv_buf) - 1); + for (int i = 0; i < r; i++) { + putchar(recv_buf[i]); + } + } while (r > 0); + printf("... done reading from socket. Last read return=%d errno=%d\r\n", r, errno); + lwip_close(s); + return 0; +} + diff --git a/sdk_liteos/app/demo/src/app_main.c b/sdk_liteos/app/demo/src/app_main.c new file mode 100755 index 0000000000000000000000000000000000000000..6196d9c94eca31ebb1734090c9b88cb745ae3c38 --- /dev/null +++ b/sdk_liteos/app/demo/src/app_main.c @@ -0,0 +1,545 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "app_main.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#if defined(CONFIG_AT_COMMAND) || defined(CONFIG_FACTORY_TEST_MODE) +#include +#endif +#include +#include +#include +#include +#include +#ifdef CONFIG_DMA_SUPPORT +#include +#endif +#ifdef CONFIG_I2C_SUPPORT +#include +#endif +#ifdef CONFIG_I2S_SUPPORT +#include +#endif +#ifdef CONFIG_SPI_SUPPORT +#include +#endif +#ifdef CONFIG_PWM_SUPPORT +#include +#endif +#ifdef CONFIG_SDIO_SUPPORT +#include +#include +#include +#endif +#include +#include + +#ifndef CONFIG_FACTORY_TEST_MODE +#include "lwip/opt.h" +#include "lwip/ip_addr.h" +#include "lwip/netifapi.h" +#endif + +#include "app_demo_upg_verify.h" +#include "hi_wifi_api.h" +#ifdef CONFIG_HILINK +#include "hilink.h" +#endif + +#include +#include + +#define APP_DEMO_RELEASE_MEM_TASK_SIZE 0x200 +/* + * Should be a high priority(but priority can't lower than 3), + * because the memory of app_main task needs to free as soon as possible. + */ +#define APP_DEMO_RELEASE_MEM_TASK_PRIO 0x3 + +#ifndef CONFIG_QUICK_SEND_MODE + +#define APP_INIT_VAP_NUM 2 +#ifdef CONFIG_MESH_SUPPORT +#define APP_INIT_USR_NUM 6 +#else +#define APP_INIT_USR_NUM 2 +#endif + +#else +#define APP_INIT_VAP_NUM 1 +#define APP_INIT_USR_NUM 1 +#endif + +#define APP_INIT_EVENT_NUM 7 + +#define PERIPHERAL_INIT_ERR_FLASH (1 << 0) +#define PERIPHERAL_INIT_ERR_UART0 (1 << 1) +#define PERIPHERAL_INIT_ERR_UART1 (1 << 2) +#define PERIPHERAL_INIT_ERR_UART2 (1 << 3) +#define PERIPHERAL_INIT_ERR_IO (1 << 4) +#define PERIPHERAL_INIT_ERR_CIPHER (1 << 5) +#define PERIPHERAL_INIT_ERR_DMA (1 << 6) +#define PERIPHERAL_INIT_ERR_I2C (1 << 7) +#define PERIPHERAL_INIT_ERR_I2S (1 << 8) +#define PERIPHERAL_INIT_ERR_SPI (1 << 9) +#define PERIPHERAL_INIT_ERR_PWM (1 << 10) +#define PERIPHERAL_INIT_ERR_SDIO (1 << 11) + +#ifndef IO_CTRL_REG_BASE_ADDR +#define IO_CTRL_REG_BASE_ADDR 0x904 +#endif +#define iocfg_reg_addr(_x) (HI_IOCFG_REG_BASE + IO_CTRL_REG_BASE_ADDR + (_x) * 4) +#define IOCFG_LOWPOWER_CFG_VAL 0xF8 + +#ifdef CONFIG_SDIO_SUPPORT +#define APP_SDIO_INIT_TASK_SIZE 0x1000 +#define APP_SDIO_INIT_TASK_PRIO 25 + +static hi_void *sdio_init_task_body(hi_void *param) +{ + printf("start sdio init\r\n"); + hi_unref_param(param); + /* To prevent watchdog exceptions caused by SDIO host, disable the watchdog first. */ + hi_watchdog_disable(); + hi_u32 ret = hi_sdio_init(); + if (ret != HI_ERR_SUCCESS) { + printf("sdio driver init fail\r\n"); + } + hi_watchdog_enable(); + app_demo_sdio_callback_init(); + printf("finish sdio init\r\n"); + return HI_NULL; +} + +hi_u32 app_sdio_init(hi_void) +{ + /* Create a task to init sdio */ + hi_u32 sdio_init_task_id = 0; + hi_task_attr attr = {0}; + attr.stack_size = APP_SDIO_INIT_TASK_SIZE; + attr.task_prio = APP_SDIO_INIT_TASK_PRIO; + attr.task_name = (hi_char*)"sdio_init"; + hi_u32 ret = hi_task_create(&sdio_init_task_id, &attr, sdio_init_task_body, HI_NULL); + if (ret != HI_ERR_SUCCESS) { + printf("Falied to create sdio init task!\n"); + } + return ret; +} +#endif + +#define CLKEN_I2C0 14 +#define CLKEN_I2C1 15 +#define CLKEN_SPI0 5 +#define CLKEN_SPI1 0 +#define CLKEN_MONITOR 6 +#define CLKEN_DMA_WBUS 1 +#define CLKEN1_PWM5 10 +#define CLKEN1_PWM_BUS 6 +#define CLKEN1_PWM 5 +#define CLKEN1_PWM4 4 +#define CLKEN1_PWM3 3 +#define CLKEN1_PWM2 2 +#define CLKEN1_PWM1 1 +#define CLKEN1_PWM0 0 +#define CLKEN1_PWM_ALL ((1 << (CLKEN1_PWM0)) | (1 << (CLKEN1_PWM1)) | (1 << (CLKEN1_PWM2)) | (1 << (CLKEN1_PWM3)) | \ + (1 << (CLKEN1_PWM4)) | (1 << (CLKEN1_PWM5))) +#define CLKEN2_I2S_BUS 11 +#define CLKEN2_I2S 10 +#define CLKEN_UART2 6 +#define CLKEN_UART2_BUS 9 +#define CLKEN_TIMER1 7 +#define CLKEN_TIMER2 8 +#define CLKEN_SDIO_WBUS 4 + +hi_void peripheral_close_clken(hi_void) +{ + hi_u16 reg_val; + hi_reg_read16(CLDO_CTL_CLKEN_REG, reg_val); + reg_val &= ~((1 << CLKEN_I2C0) | (1 << CLKEN_I2C1)); + reg_val &= ~((1 << CLKEN_SPI0) | (1 << CLKEN_SPI1)); + reg_val &= ~((1 << CLKEN_DMA_WBUS) | (1 << CLKEN_MONITOR)); + reg_val &= ~((1 << CLKEN_TIMER1) | (1 << CLKEN_TIMER2)); + hi_reg_write16(CLDO_CTL_CLKEN_REG, reg_val); /* disable clken0 clk gate */ + +#ifndef CONFIG_PWM_HOLD_AFTER_REBOOT + hi_reg_read16(CLDO_CTL_CLKEN1_REG, reg_val); + reg_val &= ~CLKEN1_PWM_ALL; + reg_val &= ~((1 << CLKEN1_PWM_BUS) | (1 << CLKEN1_PWM)); + hi_reg_write16(CLDO_CTL_CLKEN1_REG, reg_val); /* disable clken1 clk gate */ +#endif + + hi_reg_read16(CLDO_CTL_CLKEN2_REG, reg_val); + reg_val &= ~((1 << CLKEN2_I2S) | (1 << CLKEN2_I2S_BUS)); + hi_reg_write16(CLDO_CTL_CLKEN2_REG, reg_val); /* disable clken2 clk gate */ + hi_reg_read16(W_CTL_UART_MAC80M_CLKEN_REG, reg_val); +#ifdef CONFIG_SDIO_SUPPORT + reg_val &= ~((1 << CLKEN_UART2) | (1 << CLKEN_UART2_BUS)); +#else + reg_val &= ~((1 << CLKEN_UART2) | (1 << CLKEN_UART2_BUS) | (1 << CLKEN_SDIO_WBUS)); +#endif + hi_reg_write16(W_CTL_UART_MAC80M_CLKEN_REG, reg_val); /* disable uart_mac80m clk gate */ + hi_reg_write16(PMU_CMU_CTL_CLK_960M_GT_REG, 0x1); /* disable 960m clk gate */ +} + +static hi_uart_attribute g_at_uart_cfg = {115200, 8, 1, 0, 0}; + +hi_bool g_have_inited = HI_FALSE; +static app_iocfg_backup g_iocfg_backup = {0}; + +hi_void peripheral_init(hi_void) +{ + hi_u32 ret; + hi_u32 err_info = 0; + hi_cipher_set_clk_switch(HI_TRUE); + peripheral_close_clken(); + hi_flash_deinit(); + ret = hi_flash_init(); + if (ret != HI_ERR_SUCCESS) { + err_info |= PERIPHERAL_INIT_ERR_FLASH; + } + + if (g_have_inited == HI_FALSE) { + /* app_io_set_gpio2_clkout_enable(HI_TRUE); set gpio2 clock out */ + ret = hi_uart_init(HI_UART_IDX_1, &g_at_uart_cfg, HI_NULL); + if (ret != HI_ERR_SUCCESS) { + err_info |= PERIPHERAL_INIT_ERR_UART1; + } + } else { + /* app_io_set_gpio2_clkout_enable(HI_TRUE); output clock after wakeup, + user also can output clock whenever needed */ + ret = hi_uart_lp_restore(HI_UART_IDX_1); + if (ret != HI_ERR_SUCCESS) { + err_info |= PERIPHERAL_INIT_ERR_UART0; + } + ret = hi_uart_lp_restore(HI_UART_IDX_0); + if (ret != HI_ERR_SUCCESS) { + err_info |= PERIPHERAL_INIT_ERR_UART1; + } + ret = hi_uart_lp_restore(HI_UART_IDX_2); + if (ret != HI_ERR_SUCCESS) { + err_info |= PERIPHERAL_INIT_ERR_UART2; + } + hi_tsensor_lp_restore(); + } + g_have_inited = HI_TRUE; + + app_io_init(); + + ret = hi_cipher_init(); + if (ret != HI_ERR_SUCCESS) { + err_info |= PERIPHERAL_INIT_ERR_CIPHER; + } + +#ifdef CONFIG_DMA_SUPPORT + /* 如果需要使用UART/SPI的DMA功能,或者使用I2S驱动等,需要初始化DMA */ + /* if product use dma in uart or spi, or use I2S driver, or DMA memory transfer, + should init DMA Driver here. */ + ret = hi_dma_init(); + if (ret != HI_ERR_SUCCESS) { + err_info |= PERIPHERAL_INIT_ERR_DMA; + } +#endif + +#ifdef CONFIG_I2C_SUPPORT + ret = hi_i2c_deinit(HI_I2C_IDX_0); /* if wake_up from deep sleep, should deinit first */ + ret |= hi_i2c_init(HI_I2C_IDX_0, 100000); /* baudrate: 100000 */ + if (ret != HI_ERR_SUCCESS) { + err_info |= PERIPHERAL_INIT_ERR_I2C; + } +#endif + +#ifdef CONFIG_I2S_SUPPORT + ret = hi_i2s_deinit(); /* if wake_up from deep sleep, should deinit first */ + hi_i2s_attribute i2s_cfg = { + .sample_rate = HI_I2S_SAMPLE_RATE_8K, + .resolution = HI_I2S_RESOLUTION_16BIT, + }; + ret |= hi_i2s_init(&i2s_cfg); + if (ret != HI_ERR_SUCCESS) { + err_info |= PERIPHERAL_INIT_ERR_I2S; + } +#endif + +#ifdef CONFIG_SPI_SUPPORT + ret = hi_spi_deinit(HI_SPI_ID_0); /* if wake_up from deep sleep, should deinit first */ + hi_spi_cfg_basic_info spi_cfg_basic_info; + spi_cfg_basic_info.cpha = 1; + spi_cfg_basic_info.cpol = 1; + spi_cfg_basic_info.data_width = HI_SPI_CFG_DATA_WIDTH_E_7BIT; + spi_cfg_basic_info.endian = 0; + spi_cfg_basic_info.fram_mode = 0; + spi_cfg_basic_info.freq = 2000000; /* set frequency 2000000 */ + hi_spi_cfg_init_param spi_init_param = {0}; + spi_init_param.is_slave = HI_FALSE; + ret |= hi_spi_init(HI_SPI_ID_0, spi_init_param, &spi_cfg_basic_info); + if (ret != HI_ERR_SUCCESS) { + err_info |= PERIPHERAL_INIT_ERR_SPI; + } +#endif + +#ifdef CONFIG_PWM_SUPPORT + ret = hi_pwm_init(HI_PWM_PORT_PWM1); + if (ret != HI_ERR_SUCCESS) { + err_info |= PERIPHERAL_INIT_ERR_PWM; + } +#endif + +#ifdef AT_DEBUG_CMD_SUPPORT + if (err_info != 0) { + hi_at_printf("peri_init:%x\r\n", err_info); + } +#endif +} + +hi_void peripheral_init_no_sleep(hi_void) +{ + /* + * Example: To initialize a peripheral that does not need to be reinitialized + * during deep sleep wakeup, call this API. + */ +#ifdef CONFIG_SDIO_SUPPORT + hi_sdio_set_powerdown_when_deep_sleep(HI_FALSE); + hi_u32 ret = app_sdio_init(); + if (ret != HI_ERR_SUCCESS) { + printf("sdio init failed\r\n"); + } +#endif +} + +hi_u32 config_before_sleep(hi_void) +{ + /* Configured based on the actual I/O design to prevent current leakage during deep sleep */ + if (hi_lpc_get_type() == HI_DEEP_SLEEP) { +#ifdef AT_DEBUG_CMD_SUPPORT + hi_at_printf("!"); +#endif + /* + * You can set the parameters based on the actual I/O usage, + * such as no pull-up resistor, no pull-down resistor, + * and disabled input signal enable, to prevent current leakage. For details, see the chip manual. + */ + hi_reg_read16(iocfg_reg_addr(HI_IO_NAME_GPIO_6), g_iocfg_backup.gpio6_cfg); + hi_reg_read16(iocfg_reg_addr(HI_IO_NAME_GPIO_8), g_iocfg_backup.gpio8_cfg); + hi_reg_read16(iocfg_reg_addr(HI_IO_NAME_GPIO_10), g_iocfg_backup.gpio10_cfg); + hi_reg_read16(iocfg_reg_addr(HI_IO_NAME_GPIO_11), g_iocfg_backup.gpio11_cfg); + hi_reg_read16(iocfg_reg_addr(HI_IO_NAME_GPIO_12), g_iocfg_backup.gpio12_cfg); + hi_reg_read16(iocfg_reg_addr(HI_IO_NAME_GPIO_13), g_iocfg_backup.gpio13_cfg); + hi_reg_read16(iocfg_reg_addr(HI_IO_NAME_SFC_CSN), g_iocfg_backup.sfc_csn_cfg); + + hi_reg_write16(iocfg_reg_addr(HI_IO_NAME_GPIO_6), IOCFG_LOWPOWER_CFG_VAL); + hi_reg_write16(iocfg_reg_addr(HI_IO_NAME_GPIO_8), IOCFG_LOWPOWER_CFG_VAL); + hi_reg_write16(iocfg_reg_addr(HI_IO_NAME_GPIO_10), IOCFG_LOWPOWER_CFG_VAL); + hi_reg_write16(iocfg_reg_addr(HI_IO_NAME_GPIO_11), IOCFG_LOWPOWER_CFG_VAL); + hi_reg_write16(iocfg_reg_addr(HI_IO_NAME_GPIO_12), IOCFG_LOWPOWER_CFG_VAL); + hi_reg_write16(iocfg_reg_addr(HI_IO_NAME_GPIO_13), IOCFG_LOWPOWER_CFG_VAL); + hi_reg_write16(iocfg_reg_addr(HI_IO_NAME_SFC_CSN), IOCFG_LOWPOWER_CFG_VAL); + hi_uart_lp_save(HI_UART_IDX_0); + hi_uart_lp_save(HI_UART_IDX_1); + hi_uart_lp_save(HI_UART_IDX_2); + hi_tsensor_lp_save(); + + /* app_io_set_gpio2_clkout_enable(HI_FALSE); set gpio2 input disable for lowpower */ + } + return HI_ERR_SUCCESS; +} + +hi_u32 config_after_sleep(hi_void) +{ + /* Restore the I/O status based on the actual I/O design to prevent current leakage during deep sleep. */ + if (hi_lpc_get_type() == HI_DEEP_SLEEP) { + /* Restore the configuration based on the actual I/O usage. */ + hi_reg_write16(iocfg_reg_addr(HI_IO_NAME_GPIO_6), g_iocfg_backup.gpio6_cfg); + hi_reg_write16(iocfg_reg_addr(HI_IO_NAME_GPIO_8), g_iocfg_backup.gpio8_cfg); + hi_reg_write16(iocfg_reg_addr(HI_IO_NAME_GPIO_10), g_iocfg_backup.gpio10_cfg); + hi_reg_write16(iocfg_reg_addr(HI_IO_NAME_GPIO_11), g_iocfg_backup.gpio11_cfg); + hi_reg_write16(iocfg_reg_addr(HI_IO_NAME_GPIO_12), g_iocfg_backup.gpio12_cfg); + hi_reg_write16(iocfg_reg_addr(HI_IO_NAME_GPIO_13), g_iocfg_backup.gpio13_cfg); + hi_reg_write16(iocfg_reg_addr(HI_IO_NAME_SFC_CSN), g_iocfg_backup.sfc_csn_cfg); +#ifdef AT_DEBUG_CMD_SUPPORT + hi_at_printf("@\r\n"); +#endif + } + return HI_ERR_SUCCESS; +} + +static hi_void *app_demo_task_second_body(hi_void *param) +{ + /* Releases the app_main stack memory. */ + hi_unref_param(param); + return HI_NULL; +} + +static hi_void *app_demo_task_body(hi_void *param) +{ + /* Releases the app_main stack memory. */ + hi_unref_param(param); + + hi_u32 task_id = 0; + hi_task_attr attr = {0}; + attr.stack_size = APP_DEMO_RELEASE_MEM_TASK_SIZE; + attr.task_prio = APP_DEMO_RELEASE_MEM_TASK_PRIO; + attr.task_name = (hi_char*)"app_demo_second"; + hi_u32 ret = hi_task_create(&task_id, &attr, app_demo_task_second_body, HI_NULL); + if (ret != HI_ERR_SUCCESS) { + printf("Falied to create app_demo_second task:0x%x\n", ret); + } + return HI_NULL; +} + +hi_void app_demo_task_release_mem(hi_void) +{ + /* Releases the app_main stack memory. */ + hi_u32 task_id = 0; + hi_task_attr attr = {0}; + attr.stack_size = APP_DEMO_RELEASE_MEM_TASK_SIZE; + attr.task_prio = APP_DEMO_RELEASE_MEM_TASK_PRIO; + attr.task_name = (hi_char*)"app_demo"; + hi_u32 ret = hi_task_create(&task_id, &attr, app_demo_task_body, HI_NULL); + if (ret != HI_ERR_SUCCESS) { + printf("Falied to create app_demo task:0x%x\n", ret); + } + return; +} + +#ifndef CONFIG_QUICK_SEND_MODE +hi_void app_main(hi_void) +{ + (hi_void)hi_event_init(APP_INIT_EVENT_NUM, HI_NULL); +#ifdef CONFIG_FACTORY_TEST_MODE + printf("factory test mode!\r\n"); +#endif + + const hi_char* sdk_ver = hi_get_sdk_version(); + printf("sdk ver:%s\r\n", sdk_ver); + + hi_flash_partition_table *ptable = HI_NULL; + + peripheral_init(); + peripheral_init_no_sleep(); + +#ifndef CONFIG_FACTORY_TEST_MODE + hi_lpc_register_wakeup_entry(peripheral_init); +#endif + + hi_u32 ret = hi_factory_nv_init(HI_FNV_DEFAULT_ADDR, HI_NV_DEFAULT_TOTAL_SIZE, HI_NV_DEFAULT_BLOCK_SIZE); + if (ret != HI_ERR_SUCCESS) { + printf("factory nv init fail\r\n"); + } + + /* partion table should init after factory nv init. */ + ret = hi_flash_partition_init(); + if (ret != HI_ERR_SUCCESS) { + printf("flash partition table init fail:0x%x \r\n", ret); + } + ptable = hi_get_partition_table(); + + ret = hi_nv_init(ptable->table[HI_FLASH_PARTITON_NORMAL_NV].addr, ptable->table[HI_FLASH_PARTITON_NORMAL_NV].size, + HI_NV_DEFAULT_BLOCK_SIZE); + if (ret != HI_ERR_SUCCESS) { + printf("nv init fail\r\n"); + } + +#ifndef CONFIG_FACTORY_TEST_MODE + hi_upg_init(); +#endif + + /* if not use file system, there is no need init it */ + hi_fs_init(); + + hi_sal_init(); + /* + * If this parameter is set to TRUE, the PC value during reset is displayed when the watchdog is reset. + * However,the reset may be incomplete. + * Therefore, you must set this parameter to FALSE for the mass production version. + */ + hi_syserr_watchdog_debug(HI_FALSE); + /* 默认记录宕机信息到FLASH,根据应用场景,可不记录,避免频繁异常宕机情况损耗FLASH寿命 */ + /* By default, breakdown information is recorded in the flash memory. You can choose not to record breakdown + * information based on the application scenario to prevent flash servicelife loss caused by frequent breakdown. */ + hi_syserr_record_crash_info(HI_TRUE); + + hi_lpc_init(); + hi_lpc_register_hw_handler(config_before_sleep, config_after_sleep); + +#if defined(CONFIG_AT_COMMAND) || defined(CONFIG_FACTORY_TEST_MODE) + ret = hi_at_init(); + if (ret == HI_ERR_SUCCESS) { + hi_at_sys_cmd_register(); + } +#endif + + /* 如果不需要使用Histudio查看WIFI驱动运行日志等,无需初始化diag */ + /* if not use histudio for diagnostic, diag initialization is unnecessary */ + /* Shell and Diag use the same uart port, only one of them can be selected */ +#ifndef CONFIG_FACTORY_TEST_MODE + +#ifndef ENABLE_SHELL_DEBUG +#ifdef CONFIG_DIAG_SUPPORT + (hi_void)hi_diag_init(); +#endif +#else + (hi_void)hi_shell_init(); +#endif + + /* + * If the diag and shell are not started, this interface is invoked to reallocate the serial port number + * for outputting debug logs based on the NV configuration. + * hi_printf_alloc_uart_by_nv(); + * You can also invoke the change_uart interface in serial_dw.h to forcibly change the serial port number + * for outputting debug logs. + * change_uart((hi_uart)uart_id, default_uart_param); + */ + tcpip_init(NULL, NULL); +#endif + + ret = hi_wifi_init(APP_INIT_VAP_NUM, APP_INIT_USR_NUM); + if (ret != HISI_OK) { + printf("wifi init failed!\n"); + } else { + printf("wifi init success!\n"); + } + app_demo_task_release_mem(); /* Task used to release the system stack memory. */ + InitWifiGlobalLock(); + +#ifndef CONFIG_FACTORY_TEST_MODE + app_demo_upg_init(); +#ifdef CONFIG_HILINK + ret = hilink_main(); + if (ret != HISI_OK) { + printf("hilink init failed!\n"); + } else { + printf("hilink init success!\n"); + } +#endif +#endif + printf("\n app_main test\n"); + MODULE_INIT(bsp); + MODULE_INIT(device); + MODULE_INIT(core); + SYS_INIT(service); + SYS_INIT(feature); + MODULE_INIT(run); + printf("\n app_main INIT_TEST_CALL\n"); +} diff --git a/sdk_liteos/app/demo/src/app_promis.c b/sdk_liteos/app/demo/src/app_promis.c new file mode 100644 index 0000000000000000000000000000000000000000..7f5a3d8067590dff983b02eb5760e961babaf0f4 --- /dev/null +++ b/sdk_liteos/app/demo/src/app_promis.c @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "app_promis.h" + +#include +#include + +#include +#include +#include + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif + +/* Description: Packet receiving and reporting in promiscuous mode */ +int hi_promis_recv(void* recv_buf, int frame_len, signed char rssi) +{ + hi_at_printf("resv buf: %u , len: %d , rssi: %c\r\n", *(unsigned int*)recv_buf, frame_len, rssi); + + return HI_ERR_SUCCESS; +} + +/* Description: Enable the promiscuous mode */ +unsigned int hi_promis_start(const char *ifname) +{ + int ret; + hi_wifi_ptype_filter filter = {0}; + + filter.mdata_en = 1; + filter.udata_en = 1; + filter.mmngt_en = 1; + filter.umngt_en = 1; + + hi_wifi_promis_set_rx_callback(hi_promis_recv); + + ret = hi_wifi_promis_enable(ifname, 1, &filter); + if (ret != HI_ERR_SUCCESS) { + hi_at_printf("hi_wifi_promis_enable:: set error!\r\n"); + return ret; + } + + hi_at_printf("start promis SUCCESS!\r\n"); + + return HI_ERR_SUCCESS; +} + +/* Description: Disable the promiscuous mode */ +unsigned int hi_promis_stop(const char *ifname) +{ + int ret; + hi_wifi_ptype_filter filter = {0}; + + ret = hi_wifi_promis_enable(ifname, 0, &filter); + if (ret != HI_ERR_SUCCESS) { + hi_at_printf("hi_wifi_promis_enable:: set error!\r\n"); + return ret; + } + + hi_at_printf("stop promis SUCCESS!\r\n"); + + return HI_ERR_SUCCESS; +} + +#ifdef __cplusplus +#if __cplusplus + } +#endif +#endif diff --git a/sdk_liteos/app/demo/src/app_promis.h b/sdk_liteos/app/demo/src/app_promis.h new file mode 100644 index 0000000000000000000000000000000000000000..d90f360fd9cd9f37dbfbbbd7fd441466f1100a3a --- /dev/null +++ b/sdk_liteos/app/demo/src/app_promis.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __APP_PROMIS_H__ +#define __APP_PROMIS_H__ + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif + +unsigned int hi_promis_start(const char *ifname); +unsigned int hi_promis_stop(const char *ifname); +#ifdef __cplusplus +#if __cplusplus + } +#endif +#endif + +#endif diff --git a/sdk_liteos/app/demo/src/es8311_codec.c b/sdk_liteos/app/demo/src/es8311_codec.c new file mode 100644 index 0000000000000000000000000000000000000000..dbba08d5078e9c3a728714511793d264dc8f427f --- /dev/null +++ b/sdk_liteos/app/demo/src/es8311_codec.c @@ -0,0 +1,155 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include "es8311_codec.h" + +#define CODEC_DEBUG +#ifdef CODEC_DEBUG +#define codec_print(ftm...) do {printf(ftm);printf("\r\n");} while (0); +#else +#define codec_print(ftm...) +#endif + +hi_u32 codec_write_reg(hi_u8 reg, hi_u8 val) +{ + hi_i2c_data i2c_data; + hi_u8 send_data[2] = { reg, val }; /* size 2 */ + + i2c_data.send_buf = send_data; + i2c_data.send_len = 2; /* send_len is 2 */ + + return hi_i2c_write(HI_I2C_IDX_1, CODEC_DEVICE_ADDR, &i2c_data); +} + +hi_u32 codec_read_reg(hi_u8 reg, hi_u8 *val) +{ + hi_i2c_data i2c_data; + + i2c_data.send_buf = (hi_u8*)® + i2c_data.send_len = 1; + i2c_data.receive_len = 1; + i2c_data.receive_buf = val; + return hi_i2c_writeread(HI_I2C_IDX_1, CODEC_DEVICE_ADDR, &i2c_data); +} + +static hi_u32 codec_set_gain(hi_void) +{ + hi_u32 ret = HI_ERR_SUCCESS; + /* set low or normal power mode */ + ret |= codec_write_reg(ES8311_SYSTEM_REG0E, 0x02); /* enable analog pga/adc modulator */ + /* normal power mode */ + ret |= codec_write_reg(ES8311_SYSTEM_REG0F, 0x44); + /* set adc */ + ret |= codec_write_reg(ES8311_ADC_REG15, 0x40); /* set softramp->00 */ + ret |= codec_write_reg(ES8311_ADC_REG1B, 0x0A); /* set adc hpf */ + ret |= codec_write_reg(ES8311_ADC_REG1C, 0x6A); /* set adc hpf,ADC_EQ bypass */ + ret |= codec_write_reg(ES8311_ADC_REG17, 0xBF); /* set adc digtal vol */ + /* set dac */ + ret |= codec_write_reg(ES8311_DAC_REG37, 0x48); /* set dac softramp,disable DAC_EQ */ + ret |= codec_write_reg(ES8311_DAC_REG32, 0xBF); + + /* only set adc alc funtion for amic record */ + ret |= codec_write_reg(ES8311_ADC_REG16, 0x22); /* set adc gain scale up */ + ret |= codec_write_reg(ES8311_ADC_REG17, 0xDF); /* set adc alc maxgain */ + ret |= codec_write_reg(ES8311_ADC_REG18, 0x87); /* adc alc enable,alc_winsize ->00 */ + ret |= codec_write_reg(ES8311_ADC_REG19, 0xFB); /* set alc target level */ + ret |= codec_write_reg(ES8311_ADC_REG1A, 0x03); /* set adc_automute noise gate */ + ret |= codec_write_reg(ES8311_ADC_REG1B, 0xEA); /* set adc_automute vol */ + + return ret; +} + +hi_u32 hi_codec_init(const hi_codec_attribute *codec_attr) +{ + if (codec_attr == HI_NULL) { + return HI_ERR_FAILURE; + } + + hi_u32 ret; + + /* set adc/dac data form */ + codec_write_reg(ES8311_GPIO_REG44, 0x08); /* adc to dac disable,ADCDATA=ADC(L)+ADC(R) */ + hi_udelay(5000); /* 5000us */ + + ret = codec_write_reg(ES8311_DAC_REG31, 0x40); /* mute DAC state machine */ + ret |= codec_write_reg(ES8311_RESET_REG00, 0x1F); /* Reset the clock and slave mode. */ + + ret |= codec_write_reg(ES8311_GP_REG45, 0x00); /* Pull up the BCLK/LRCK. */ + + ret |= codec_write_reg(ES8311_CLK_MANAGER_REG01, 0x30); /* MCLK and BCLK are enabled. */ + + ret |= codec_write_reg(ES8311_CLK_MANAGER_REG02, 0x10); /* Time required for completing AD/DA conversion: 0x10 + dig_mclk = mclk_prediv*4 */ + + if (codec_attr->sample_rate == HI_CODEC_SAMPLE_RATE_8K) { + ret |= codec_write_reg(ES8311_CLK_MANAGER_REG02, 0xA0); /* 0 - dig_mclk=mclk_prediv*1 (default) */ + } else if (codec_attr->sample_rate == HI_CODEC_SAMPLE_RATE_16K) { + ret |= codec_write_reg(ES8311_CLK_MANAGER_REG02, 0x40); /* 0 - dig_mclk=mclk_prediv*1 (default) */ + } else if (codec_attr->sample_rate == HI_CODEC_SAMPLE_RATE_32K) { + ret |= codec_write_reg(ES8311_CLK_MANAGER_REG02, 0x48); /* 0 - dig_mclk=mclk_prediv*1 (default) */ + } else if (codec_attr->sample_rate == HI_CODEC_SAMPLE_RATE_48K) { + ret |= codec_write_reg(ES8311_CLK_MANAGER_REG02, 0x00); /* 0 - dig_mclk=mclk_prediv*1 (default) */ + } + + ret |= codec_write_reg(ES8311_CLK_MANAGER_REG03, 0x10); /* 16 - 64 * fs(ss) / 32 * fs(ds) (default) */ + + ret |= codec_write_reg(ES8311_ADC_REG16, 0x24); /* ADC gain 4 - 24dB (default) */ + ret |= codec_write_reg(ES8311_CLK_MANAGER_REG04, 0x10); /* DAC over sample rate : 16 - 64 * fs (default) */ + ret |= codec_write_reg(ES8311_CLK_MANAGER_REG05, 0x00); /* Frequency division coefficient of the ADC and + DAC clocks, which determines the working frequencies of the ADC and DAC */ + + ret |= codec_write_reg(ES8311_SYSTEM_REG0B, 0x00); /* Determines the power-up duration. */ + ret |= codec_write_reg(ES8311_SYSTEM_REG0C, 0x00); /* Determines the power-up duration. */ + ret |= codec_write_reg(ES8311_SYSTEM_REG10, 0x1F); /* Bias setting */ + ret |= codec_write_reg(ES8311_SYSTEM_REG11, 0x7F); /* internal use */ + + /* + * Set Codec in Slave mode + */ + ret |= codec_write_reg(ES8311_RESET_REG00, 0x80); /* csm power on */ + + hi_udelay(50000); /* 50000us */ + + ret |= codec_write_reg(ES8311_SYSTEM_REG0D, 0x01); /* 1 - start up vmid normal speed charge */ + /* + * select clock source for internal mclk + */ + ret |= codec_write_reg(ES8311_CLK_MANAGER_REG01, 0x3F); /* Starts the sampling working clock. */ + + /* Selects mic channel 1, select Mic1p-Mic1n ; ADC PGA gain:4 - 12dB */ + ret |= codec_write_reg(ES8311_SYSTEM_REG14, 0x18); + /* set dac */ + ret |= codec_write_reg(ES8311_SYSTEM_REG12, 0x00); /* 0 - enable DAC */ + /* enable HP drive */ + ret |= codec_write_reg(ES8311_SYSTEM_REG13, 0x10); /* 1 - enable output to HP drive */ + + if ((codec_attr->resolution == HI_CODEC_RESOLUTION_16BIT)) { + /* set adc/dac data format */ + ret |= codec_write_reg(ES8311_SDPIN_REG09, 0x0C); /* set dac format=16bit i2s */ + ret |= codec_write_reg(ES8311_SDPOUT_REG0A, 0x0C); /* set adc format=16bit i2s */ + } else { + /* set adc/dac data format */ + ret |= codec_write_reg(ES8311_SDPIN_REG09, 0x00); /* set dac format=24bit i2s */ + ret |= codec_write_reg(ES8311_SDPOUT_REG0A, 0x00); /* set adc format=24bit i2s */ + } + + ret |= codec_set_gain(); + ret |= codec_write_reg(ES8311_DAC_REG31, 0x00); /* unmute DAC state machine */ + + return ret; +} diff --git a/sdk_liteos/app/demo/src/es8311_codec.h b/sdk_liteos/app/demo/src/es8311_codec.h new file mode 100644 index 0000000000000000000000000000000000000000..a17e1e00c6e3a07f59d502151cca02e61aa6e48b --- /dev/null +++ b/sdk_liteos/app/demo/src/es8311_codec.h @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __ES8311_CODEC_H__ +#define __ES8311_CODEC_H__ + +/* +* ES8311_REGISTER NAME_REG_REGISTER ADDRESS +*/ +#define ES8311_RESET_REG00 0x00 /* reset digital,csm,clock manager etc. */ + +/* +* Clock Scheme Register definition +*/ +#define ES8311_CLK_MANAGER_REG01 0x01 /* select clk src for mclk, enable clock for codec */ +#define ES8311_CLK_MANAGER_REG02 0x02 /* clk divider and clk multiplier */ +#define ES8311_CLK_MANAGER_REG03 0x03 /* adc fsmode and osr */ +#define ES8311_CLK_MANAGER_REG04 0x04 /* dac osr */ +#define ES8311_CLK_MANAGER_REG05 0x05 /* clk divier for adc and dac */ +#define ES8311_CLK_MANAGER_REG06 0x06 /* bclk inverter and divider */ +#define ES8311_CLK_MANAGER_REG07 0x07 /* tri-state, lrck divider */ +#define ES8311_CLK_MANAGER_REG08 0x08 /* lrck divider */ +#define ES8311_SDPIN_REG09 0x09 /* dac serial digital port */ +#define ES8311_SDPOUT_REG0A 0x0A /* adc serial digital port */ +#define ES8311_SYSTEM_REG0B 0x0B /* system */ +#define ES8311_SYSTEM_REG0C 0x0C /* system */ +#define ES8311_SYSTEM_REG0D 0x0D /* system, power up/down */ +#define ES8311_SYSTEM_REG0E 0x0E /* system, power up/down */ +#define ES8311_SYSTEM_REG0F 0x0F /* system, low power */ +#define ES8311_SYSTEM_REG10 0x10 /* system */ +#define ES8311_SYSTEM_REG11 0x11 /* system */ +#define ES8311_SYSTEM_REG12 0x12 /* system, Enable DAC */ +#define ES8311_SYSTEM_REG13 0x13 /* system */ +#define ES8311_SYSTEM_REG14 0x14 /* system, select DMIC, select analog pga gain */ +#define ES8311_ADC_REG15 0x15 /* ADC, adc ramp rate, dmic sense */ +#define ES8311_ADC_REG16 0x16 /* ADC */ +#define ES8311_ADC_REG17 0x17 /* ADC, volume */ +#define ES8311_ADC_REG18 0x18 /* ADC, alc enable and winsize */ +#define ES8311_ADC_REG19 0x19 /* ADC, alc maxlevel */ +#define ES8311_ADC_REG1A 0x1A /* ADC, alc automute */ +#define ES8311_ADC_REG1B 0x1B /* ADC, alc automute, adc hpf s1 */ +#define ES8311_ADC_REG1C 0x1C /* ADC, equalizer, hpf s2 */ +#define ES8311_DAC_REG31 0x31 /* DAC, mute */ +#define ES8311_DAC_REG32 0x32 /* DAC, volume */ +#define ES8311_DAC_REG33 0x33 /* DAC, offset */ +#define ES8311_DAC_REG34 0x34 /* DAC, drc enable, drc winsize */ +#define ES8311_DAC_REG35 0x35 /* DAC, drc maxlevel, minilevel */ +#define ES8311_DAC_REG37 0x37 /* DAC, ramprate */ +#define ES8311_GPIO_REG44 0x44 /* GPIO, dac2adc for test */ +#define ES8311_GP_REG45 0x45 /* GP CONTROL */ +#define ES8311_CHD1_REGFD 0xFD /* CHIP ID1 */ +#define ES8311_CHD2_REGFE 0xFE /* CHIP ID2 */ +#define ES8311_CHVER_REGFF 0xFF /* VERSION */ + +#define ES8311_MAX_REGISTER 0xFF + +#define ES8311_PDN_DAC_BIT (1 << 1) + +#define CODEC_DEVICE_ADDR 0x30 /* 0011 00x */ + +typedef enum { + HI_CODEC_SAMPLE_RATE_8K = 8, + HI_CODEC_SAMPLE_RATE_16K = 16, + HI_CODEC_SAMPLE_RATE_32K = 32, + HI_CODEC_SAMPLE_RATE_48K = 48, +} hi_codec_sample_rate; + +typedef enum { + HI_CODEC_RESOLUTION_16BIT = 16, + HI_CODEC_RESOLUTION_24BIT = 24, +} hi_codec_resolution; + +typedef struct { + hi_codec_sample_rate sample_rate; + hi_codec_resolution resolution; +} hi_codec_attribute; + +hi_u32 hi_codec_init(const hi_codec_attribute *codec_attr); + +#endif diff --git a/sdk_liteos/app/demo/src/netcfg_sample.c b/sdk_liteos/app/demo/src/netcfg_sample.c new file mode 100755 index 0000000000000000000000000000000000000000..ae5f5b8adebe5eb9e510f0cdd44294db9b10d67e --- /dev/null +++ b/sdk_liteos/app/demo/src/netcfg_sample.c @@ -0,0 +1,376 @@ +/* + * Copyright (c) 2020 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include "lwip/ip4_addr.h" +#include "lwip/netif.h" +#include "lwip/netifapi.h" + +#include "cmsis_os2.h" +#include "ohos_init.h" +#include "ohos_types.h" +#include "netcfg_service.h" +#include "wifi_device_config.h" +#include "wifiiot_gpio.h" +#include "wifiiot_gpio_ex.h" + +enum LedState { + LED_OFF = 0, + LED_ON, + LED_SPARK, +}; + +WifiDeviceConfig g_netCfg = {0}; +WifiEvent g_staEventHandler = {0}; +struct netif *g_staNetif = NULL; +int g_ledState = LED_OFF; +int g_connectRetryCount = 0; + +#define SAMPLE_SEND_BUF_SIZE 400 +int g_recvFlag = 0; +char g_buf[SAMPLE_SEND_BUF_SIZE] = {0}; +int g_bufLen = 0; + +#define SAMPLE_LED_INTERVAL_TIME_US 300000 +#define SAMPLE_BIZ_SLEEP_TIME_US 1000000 + +static void *LedTask(const char *arg) +{ + (void)arg; + while (1) { + switch (g_ledState) { + case LED_OFF: + GpioSetOutputVal(WIFI_IOT_IO_NAME_GPIO_9, 1); + usleep(SAMPLE_LED_INTERVAL_TIME_US); + break; + case LED_ON: + GpioSetOutputVal(WIFI_IOT_IO_NAME_GPIO_9, 0); + usleep(SAMPLE_LED_INTERVAL_TIME_US); + break; + case LED_SPARK: + GpioSetOutputVal(WIFI_IOT_IO_NAME_GPIO_9, 0); + usleep(SAMPLE_LED_INTERVAL_TIME_US); + GpioSetOutputVal(WIFI_IOT_IO_NAME_GPIO_9, 1); + usleep(SAMPLE_LED_INTERVAL_TIME_US); + break; + default: + usleep(SAMPLE_LED_INTERVAL_TIME_US); + break; + } + } + + return NULL; +} + +#define SAMPLE_TASK_STACK_SIZE 4048 +#define SAMPLE_TASK_PRIO 25 +static void LedInit(void) +{ + osThreadAttr_t attr; + + GpioInit(); + IoSetFunc(WIFI_IOT_IO_NAME_GPIO_9, WIFI_IOT_IO_FUNC_GPIO_9_GPIO); + GpioSetDir(WIFI_IOT_IO_NAME_GPIO_9, WIFI_IOT_GPIO_DIR_OUT); + + attr.name = "LedTask"; + attr.attr_bits = 0U; + attr.cb_mem = NULL; + attr.cb_size = 0U; + attr.stack_mem = NULL; + attr.stack_size = SAMPLE_TASK_STACK_SIZE; + attr.priority = SAMPLE_TASK_PRIO; + + if (osThreadNew((osThreadFunc_t)LedTask, NULL, &attr) == NULL) { + printf("[sample] Falied to create LedTask!\n"); + } +} + +static void LedOn(void) +{ + printf("[sample] led spark.\n"); + g_ledState = LED_ON; +} + +static void PreTransferProc(void) +{ + printf("[sample] oncall pretransfer event.\n"); + g_ledState = LED_SPARK; +} + +static void DisconnectEventProc(void) +{ + printf("[sample] oncall disconnect event.\n"); +} + +static void RecvMessageEventProc(char *msg, int len) +{ + printf("[sample] oncall recv message %s(%d).\n", msg, len); + if (memcpy_s(g_buf, sizeof(g_buf), msg, len) != 0) { + printf("[sample] memcpy ctrl msg fail.\n"); + } + g_recvFlag = 1; + g_bufLen = len; +} + +static void TimeoutProc(void) +{ + printf("[sample] oncall network config service timeout with phone.\n"); +} + +static void NetCfgResult(signed char result) +{ + printf("[sample] network configure done.(result=%d)\n", result); + DisableWifi(); + UnRegisterWifiEvent(&g_staEventHandler); + NotifyConfigWifiResult(result); + if (result == NETCFG_RST_SUCC) { + LedOn(); + } else if (result == NETCFG_RST_FAIL) { + printf("[sample] conn ap fail.\n"); + } + // -1: fail 0: succ +} + +static void StaResetAddr(struct netif *ptrLwipNetif) +{ + ip4_addr_t staGW; + ip4_addr_t staIpaddr; + ip4_addr_t staNetmask; + + if (ptrLwipNetif == NULL) { + printf("[sample] Null param of netdev\r\n"); + return; + } + + IP4_ADDR(&staGW, 0, 0, 0, 0); + IP4_ADDR(&staIpaddr, 0, 0, 0, 0); + IP4_ADDR(&staNetmask, 0, 0, 0, 0); + + netifapi_netif_set_addr(ptrLwipNetif, &staIpaddr, &staNetmask, &staGW); +} + +#define TEST_NUM_2 2 +#define TEST_NUM_3 3 +#define TEST_NUM_4 4 +#define TEST_NUM_5 5 +#define TEST_CONNECT_RETRY_COUNT 5 +static void WifiConnectionChangedHandler(int state, WifiLinkedInfo *info) +{ + if (state == WIFI_STATE_AVALIABLE) { + NetCfgResult(NETCFG_RST_SUCC); + NetCfgResult(TEST_NUM_2); + NetCfgResult(TEST_NUM_3); + NetCfgResult(TEST_NUM_4); + NetCfgResult(TEST_NUM_5); + printf("[sample] WiFi: Connected.\n"); + netifapi_dhcp_start(g_staNetif); + } else if (state == WIFI_STATE_NOT_AVALIABLE) { + printf("[sample] WiFi: Disconnected retry = %d, reason = %d\n", g_connectRetryCount, info->disconnectedReason); + if (g_connectRetryCount < TEST_CONNECT_RETRY_COUNT) { + g_connectRetryCount++; + return; + } + NetCfgResult(NETCFG_RST_FAIL); + netifapi_dhcp_stop(g_staNetif); + StaResetAddr(g_staNetif); + } +} + +static int StaStart(void) +{ + WifiErrorCode error; + error = EnableWifi(); + if (error == ERROR_WIFI_BUSY) { + printf("[sample] Sta had already connnected.\n"); + NetCfgResult(NETCFG_RST_SUCC); + return -1; + } + if (error != WIFI_SUCCESS) { + printf("[sample] EnableWifi fail, error = %d\n", error); + return -1; + } + + g_staNetif = netif_find("wlan0"); + if (g_staNetif == NULL) { + printf("[sample] Get netif failed\n"); + return -1; + } + + g_staEventHandler.OnWifiConnectionChanged = WifiConnectionChangedHandler; + error = RegisterWifiEvent(&g_staEventHandler); + if (error != WIFI_SUCCESS) { + printf("[sample] RegisterWifiEvent fail, error = %d\n", error); + return -1; + } + + if (IsWifiActive() == 0) { + printf("[sample] Wifi station is not actived.\n"); + return -1; + } + + return 0; +} + +static int WapStaConnect(const WifiDeviceConfig *config) +{ + int netId = 0; + WifiErrorCode error; + + error = AddDeviceConfig(config, &netId); + if (error != WIFI_SUCCESS) { + printf("[sample] AddDeviceConfig add config failed %d\n", error); + return -1; + } + + error = ConnectTo(netId); + if (error != WIFI_SUCCESS) { + printf("[sample] ConnectTo conn failed %d\n", error); + return -1; + } + + printf("[sample] WapSta connecting...\n"); + return 0; +} + +static void *CfgNetTask(const char *arg) +{ + (void)arg; + + if (StaStart() != 0) { + return NULL; + } + + if (WapStaConnect(&g_netCfg) != 0) { + return NULL; + } + + return NULL; +} + +static int CreateCfgNetTask(void) +{ + osThreadAttr_t attr; + attr.name = "CfgNetTask"; + attr.attr_bits = 0U; + attr.cb_mem = NULL; + attr.cb_size = 0U; + attr.stack_mem = NULL; + attr.stack_size = SAMPLE_TASK_STACK_SIZE; + attr.priority = SAMPLE_TASK_PRIO; + + if (osThreadNew((osThreadFunc_t)CfgNetTask, NULL, &attr) == NULL) { + printf("[NAN] Falied to create NanCfgNetTask!\n"); + return -1; + } + + return 0; +} + +static void DealSsidPwd(struct NetCfgConfig *config) +{ + if (config == NULL) { + printf("[sample] input config is illegal.\n"); + return; + } + + if (memcpy_s(&g_netCfg, sizeof(WifiDeviceConfig), &(config->config), sizeof(WifiDeviceConfig)) != 0) { + printf("[sample] memcpy netCfg fail.\n"); + return; + } + g_netCfg.securityType = ((config->config.preSharedKey[0] == '\0') ? WIFI_SEC_TYPE_OPEN : WIFI_SEC_TYPE_PSK); + g_connectRetryCount = 0; + if (CreateCfgNetTask() != 0) { + printf("[sample] create cfgnet task fail.\n"); + } +} +#define SAMPLE_NETCFG_DEFAULT_DB (-61) +#define SAMPLE_NETCFG_DEFAULT_ACK_TIMEOUT 3 +#define SAMPLE_NETCFG_DEFAULT_HEARTBEAT_TIMEOUT 60; +#define SAMPLE_TIME_COUNT 5 +struct DevPara g_devPara = {0}; +struct NetCfgPara g_netCfgPara = {0}; + +static void *SampleBizTask(const char *arg) +{ + (void)arg; + int ret; + LedInit(); + struct WifiConfigureEvent event = {0}; + event.OnPreTransferConfig = PreTransferProc; + event.OnTransferConfig = DealSsidPwd; + event.OnDisconnected = DisconnectEventProc; + event.OnMessageReceived = RecvMessageEventProc; + event.OnTimeout = TimeoutProc; + ret = RegConfigWifiCallback(&event); + if (ret != 0) { + printf("[sample] register event fail.\n"); + return NULL; + } + + HotspotConfig config = {0}; + if (strcpy_s(config.ssid, sizeof(config.ssid), "netcfg_softap") != 0) { + printf("[sample] strcpy ssid fail.\n"); + return NULL; + } + config.securityType = WIFI_SEC_TYPE_OPEN; + + char *pin = "0123456789012345"; + char *productId = "1"; + char *sn = "01234567890123450123456789012345"; + + memset_s(&g_devPara, sizeof(g_devPara), 0, sizeof(g_devPara)); + memcpy_s(g_devPara.pin, sizeof(g_devPara.pin), pin, sizeof(g_devPara.pin)); + memcpy_s(g_devPara.productId, sizeof(g_devPara.productId), productId, sizeof(g_devPara.productId)); + memcpy_s(g_devPara.sn, sizeof(g_devPara.sn), sn, sizeof(g_devPara.sn)); + + g_netCfgPara.db = SAMPLE_NETCFG_DEFAULT_DB; + g_netCfgPara.nanAckTimout = SAMPLE_NETCFG_DEFAULT_ACK_TIMEOUT; + g_netCfgPara.hbTimout = SAMPLE_NETCFG_DEFAULT_HEARTBEAT_TIMEOUT; + ret += StartConfigWifi(&config, &g_devPara, &g_netCfgPara); + if (ret != 0) { + printf("[sample] start config wifi fail.\n"); + return NULL; + } + + while (1) { + printf("[sample] main biz.\n"); + if (g_recvFlag) { + g_recvFlag = 0; + printf("[sample] send usr msg.\n"); + SendMessage(g_buf, g_bufLen); + } + usleep(SAMPLE_BIZ_SLEEP_TIME_US); + } + + return NULL; +} + +void SampleBiz(void) +{ + osThreadAttr_t attr; + + attr.name = "samplebiztask"; + attr.attr_bits = 0U; + attr.cb_mem = NULL; + attr.cb_size = 0U; + attr.stack_mem = NULL; + attr.stack_size = SAMPLE_TASK_STACK_SIZE; + attr.priority = SAMPLE_TASK_PRIO; + + if (osThreadNew((osThreadFunc_t)SampleBizTask, NULL, &attr) == NULL) { + printf("[sample] Falied to create SampleBizTask!\n"); + } +} diff --git a/sdk_liteos/app/demo/src/network_config_sample.c b/sdk_liteos/app/demo/src/network_config_sample.c new file mode 100755 index 0000000000000000000000000000000000000000..4ac64a37b291f637ca18d72299af12a362975c91 --- /dev/null +++ b/sdk_liteos/app/demo/src/network_config_sample.c @@ -0,0 +1,547 @@ +/* + * Copyright (c) 2020 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Description: Sample file of the power distribution service + */ + +#include + +#include "lwip/netif.h" +#include "lwip/netifapi.h" +#include "lwip/ip4_addr.h" + +#include "base64.h" +#include "cmsis_os2.h" +#include "ohos_types.h" +#include "network_config_service.h" +#include "wifi_device_config.h" +#include "wifiiot_gpio.h" +#include "wifiiot_gpio_ex.h" + +enum LedState { + LED_OFF = 0, + LED_ON, + LED_SPARK, +}; + +WifiDeviceConfig g_netCfg = {0}; +WifiEvent g_staEventHandler = {0}; +struct netif *g_staNetif = NULL; +int g_ledState = LED_OFF; +int g_connectRetryCount = 0; + +const char *g_ssid = "Hi-xxx-Switchs-XXXXX "; +const char *g_pinCode = "11111111"; +const char *g_productId = "1"; +const char *g_sn = "01234567890123450123456789012345"; + +#define SAMPLE_LED_INTERVAL_TIME_US 300000 +#define SAMPLE_BIZ_SLEEP_TIME_US 1000000 +#define SAMPLE_TIME_COUNT 5 +#define DEVICE_INFO_NUM 2 +#define POWER_NUM (-52) +#define MAX_DATA_LEN 4096 + +#define CHANNEL_80211B_ONLY 14 +#define FREQ_OF_CHANNEL_1 2412 +#define FREQ_OF_CHANNEL_80211B_ONLY 2484 +#define WIFI_MIN_CHANNEL 1 +#define WIFI_FREQ_INTERVAL 5 + +static unsigned int ChannelToFrequency(unsigned int channel) +{ + if (channel <= 0) { + return 0; + } + + if (channel == CHANNEL_80211B_ONLY) { + return FREQ_OF_CHANNEL_80211B_ONLY; + } + + return (((channel - WIFI_MIN_CHANNEL) * WIFI_FREQ_INTERVAL) + FREQ_OF_CHANNEL_1); +} + +static void *LedTask(const char *arg) +{ + (void)arg; + while (1) { + switch (g_ledState) { + case LED_OFF: + GpioSetOutputVal(WIFI_IOT_IO_NAME_GPIO_9, 1); + usleep(SAMPLE_LED_INTERVAL_TIME_US); + break; + case LED_ON: + GpioSetOutputVal(WIFI_IOT_IO_NAME_GPIO_9, 0); + usleep(SAMPLE_LED_INTERVAL_TIME_US); + break; + case LED_SPARK: + GpioSetOutputVal(WIFI_IOT_IO_NAME_GPIO_9, 0); + usleep(SAMPLE_LED_INTERVAL_TIME_US); + GpioSetOutputVal(WIFI_IOT_IO_NAME_GPIO_9, 1); + usleep(SAMPLE_LED_INTERVAL_TIME_US); + break; + default: + usleep(SAMPLE_LED_INTERVAL_TIME_US); + break; + } + } + + return NULL; +} + +#define SAMPLE_TASK_STACK_SIZE 4048 +#define SAMPLE_TASK_PRIO 25 + +static void LedInit(void) +{ + osThreadAttr_t attr; + + GpioInit(); + IoSetFunc(WIFI_IOT_IO_NAME_GPIO_9, WIFI_IOT_IO_FUNC_GPIO_9_GPIO); + GpioSetDir(WIFI_IOT_IO_NAME_GPIO_9, WIFI_IOT_GPIO_DIR_OUT); + + attr.name = "LedTask"; + attr.attr_bits = 0U; + attr.cb_mem = NULL; + attr.cb_size = 0U; + attr.stack_mem = NULL; + attr.stack_size = SAMPLE_TASK_STACK_SIZE; + attr.priority = SAMPLE_TASK_PRIO; + + if (osThreadNew((osThreadFunc_t)LedTask, NULL, &attr) == NULL) { + printf("[sample] Falied to create LedTask!\n"); + } +} + +static void LedOn(void) +{ + printf("[sample] led spark.\n"); + g_ledState = LED_ON; +} + +static void LedOff(void) +{ + printf("[sample] led off.\n"); + g_ledState = LED_OFF; +} + +static void NetCfgResult(signed char result) +{ + printf("[sample] Network configure done.(result=%d)\n", result); + UnRegisterWifiEvent(&g_staEventHandler); + NotifyNetCfgResult(result); + if (result == 0) { + LedOff(); + printf("[sample] Led off.\n"); + } else if (result == 1) { + LedOn(); + printf("[sample] Led on.\n"); + } else if (result == -1) { + printf("[sample] Connect ap fail.\n"); + } +} + +static void StaResetAddr(struct netif *ptrLwipNetif) +{ + ip4_addr_t staGW; + ip4_addr_t staIpaddr; + ip4_addr_t staNetmask; + + if (ptrLwipNetif == NULL) { + printf("[sample] Null param of netdev\r\n"); + return; + } + + IP4_ADDR(&staGW, 0, 0, 0, 0); + IP4_ADDR(&staIpaddr, 0, 0, 0, 0); + IP4_ADDR(&staNetmask, 0, 0, 0, 0); + + netifapi_netif_set_addr(ptrLwipNetif, &staIpaddr, &staNetmask, &staGW); +} + +#define TEST_NUM_2 2 +#define TEST_NUM_3 3 +#define TEST_NUM_4 4 +#define TEST_NUM_5 5 +#define TEST_CONNECT_RETRY_COUNT 5 + +static int g_state; + +static void *WifiConnectTask(const char *arg) +{ + (void)arg; + if (g_state == WIFI_STATE_AVALIABLE) { + NetCfgResult(0); + printf("[sample] WiFi: Connected.\n"); + netifapi_dhcp_start(g_staNetif); + } else if (g_state == WIFI_STATE_NOT_AVALIABLE) { + printf("[sample] WiFi: Disconnected retry = %d\n", g_connectRetryCount); + if (g_connectRetryCount < TEST_CONNECT_RETRY_COUNT) { + g_connectRetryCount++; + return NULL; + } + NetCfgResult(-1); + netifapi_dhcp_stop(g_staNetif); + StaResetAddr(g_staNetif); + } + return NULL; +} + +static void WifiConnectionChangedHandler(int state, WifiLinkedInfo *info) +{ + (void)info; + osThreadAttr_t attr; + attr.name = "WifiConnectTask"; + attr.attr_bits = 0U; + attr.cb_mem = NULL; + attr.cb_size = 0U; + attr.stack_mem = NULL; + attr.stack_size = SAMPLE_TASK_STACK_SIZE; + attr.priority = SAMPLE_TASK_PRIO; + g_state = state; + if (osThreadNew((osThreadFunc_t)WifiConnectTask, NULL, &attr) == NULL) { + printf("[sample] Falied to create WifiConnectTask!\n"); + } +} + +static int StaStart(void) +{ + WifiErrorCode error; + error = EnableWifi(); + if (error == ERROR_WIFI_BUSY) { + printf("[sample] Sta had already connnected.\n"); + NetCfgResult(0); + } + if ((error != ERROR_WIFI_BUSY) && (error != WIFI_SUCCESS)) { + printf("[sample] EnableWifi failed, error = %d\n", error); + return -1; + } + + g_staEventHandler.OnWifiConnectionChanged = WifiConnectionChangedHandler; + error = RegisterWifiEvent(&g_staEventHandler); + if (error != WIFI_SUCCESS) { + printf("[sample] RegisterWifiEvent failed, error = %d\n", error); + return -1; + } + + if (IsWifiActive() == 0) { + printf("[sample] Wifi station is not actived.\n"); + return -1; + } + + g_staNetif = netif_find("wlan0"); + if (g_staNetif == NULL) { + printf("[sample] Get netif failed\n"); + return -1; + } + + return 0; +} + +static int WapStaConnect(WifiDeviceConfig *config) +{ + int netId = 0; + WifiErrorCode error; + config->securityType = (config->preSharedKey[0] == '\0') ? WIFI_SEC_TYPE_OPEN : WIFI_SEC_TYPE_PSK; + error = AddDeviceConfig(config, &netId); + if (error != WIFI_SUCCESS) { + printf("[sample] AddDeviceConfig add config failed, error=%d\n", error); + return -1; + } + + error = ConnectTo(netId); + if (error != WIFI_SUCCESS) { + printf("[sample] ConnectTo conn failed %d\n", error); + return -1; + } + + printf("[sample] WapSta connecting...\n"); + return 0; +} + +static void *CfgNetTask(const char *arg) +{ + (void)arg; + + if (StaStart() != 0) { + return NULL; + } + + if (WapStaConnect(&g_netCfg) != 0) { + return NULL; + } + + return NULL; +} + +static int CreateCfgNetTask(void) +{ + osThreadAttr_t attr; + attr.name = "CfgNetTask"; + attr.attr_bits = 0U; + attr.cb_mem = NULL; + attr.cb_size = 0U; + attr.stack_mem = NULL; + attr.stack_size = SAMPLE_TASK_STACK_SIZE; + attr.priority = SAMPLE_TASK_PRIO; + + if (osThreadNew((osThreadFunc_t)CfgNetTask, NULL, &attr) == NULL) { + printf("[sample] Falied to create NanCfgNetTask!\n"); + return -1; + } + + return 0; +} + +static void DealSsidPwd(const WifiDeviceConfig *config) +{ + if (config == NULL) { + printf("[sample] Input config is illegal.\n"); + return; + } + + if (memcpy_s(&g_netCfg, sizeof(WifiDeviceConfig), config, sizeof(WifiDeviceConfig)) != 0) { + printf("[sample] memcpy netCfg failed.\n"); + return; + } + printf("[sample] DealSsidPwd\n"); + g_connectRetryCount = 0; + if (CreateCfgNetTask() != 0) { + printf("[sample] Create cfgnet task failed.\n"); + } +} + +int GetPinCode(unsigned char *pinCode, unsigned int size, unsigned int *len) +{ + if (pinCode == NULL) { + } + memset_s(pinCode, size, 0, size); + if (strncpy_s((char *)pinCode, size, g_pinCode, strlen(g_pinCode)) != 0) { + printf("[sample] GetPinCode copy pinCode failed\n"); + return -1; + } + *len = strlen((char *)pinCode); + return 0; +} + +int FastConnect(const struct WifiInfo *wifiInfo, WifiDeviceConfig *destCfg) +{ + if (memcpy_s(destCfg->ssid, sizeof(destCfg->ssid), wifiInfo->ssid, wifiInfo->ssidLen) != EOK) { + printf("[sample] FastConnect copy ssid failed\n"); + return -1; + } + if (memcpy_s(destCfg->preSharedKey, sizeof(destCfg->preSharedKey), wifiInfo->psk, wifiInfo->pskLen) != EOK) { + printf("[sample] FastConnect copy pwd failed\n"); + return -1; + } + if (memcpy_s(destCfg->bssid, sizeof(destCfg->bssid), wifiInfo->bssid, wifiInfo->bssidLen) != EOK) { + printf("[sample] FastConnect copy bssid failed\n"); + return -1; + } + destCfg->securityType = wifiInfo->authMode; + destCfg->freq = ChannelToFrequency(wifiInfo->channelNumber); + destCfg->wapiPskType = WIFI_PSK_TYPE_HEX; + return 0; +} + +int NormalConnect(const struct WifiInfo *wifiInfo, WifiDeviceConfig *destCfg) +{ + if (memcpy_s(destCfg->ssid, sizeof(destCfg->ssid), wifiInfo->ssid, wifiInfo->ssidLen) != EOK) { + printf("[sample] NormalConnect copy ssid failed\n"); + return -1; + } + if (memcpy_s(destCfg->preSharedKey, sizeof(destCfg->preSharedKey), wifiInfo->pwd, wifiInfo->pwdLen) != EOK) { + printf("[sample] NormalConnect copy pwd failed\n"); + return -1; + } + return 0; +} + +int ParseNetCfgData(const struct WifiInfo *wifiInfo, const unsigned char *vendorData, unsigned int len) +{ + printf("[sample] ParseWifiData vendorData len:%d\n", len); + if (wifiInfo == NULL) { + printf("[sample] wifiInfo is NULL\n"); + return -1; + } + + WifiDeviceConfig netConfig; + memset_s(&netConfig, sizeof(netConfig), 0, sizeof(netConfig)); + FastConnect(wifiInfo, &netConfig); + + if (vendorData != NULL) { + /* process vendorData */ + } + + DealSsidPwd(&netConfig); + return 0; +} + +int SendRawEncodeData(const unsigned char *data, size_t len) +{ + size_t writeLen = 0; + int ret = mbedtls_base64_encode(NULL, 0, &writeLen, (const unsigned char *)data, len); + if (ret != 0) { + printf("[sample] SendRawEncodeData base64 encode fial\n"); + return -1; + } + size_t encodeBufLen = writeLen; + if (writeLen > MAX_DATA_LEN) { + printf("[sample] SendRawEncodeData dataLen overSize\n"); + return -1; + } + char *buf = malloc(writeLen + 1); + if (buf == NULL) { + printf("[sample] malloc failed\r\n"); + return -1; + } + (void)memset_s(buf, writeLen + 1, 0, writeLen + 1); + if (mbedtls_base64_encode((unsigned char *)buf, encodeBufLen, &writeLen, (const unsigned char *)data, len) != 0) { + printf("[sample] SendRawEncodeData base64 encode failed\r\n"); + free(buf); + buf = NULL; + return -1; + } + + printf("[sample] SendRawEncodeData encode buf = %s\n", buf); + SendRawData((const char*)buf); + if (buf != NULL) { + free(buf); + } + + return 0; +} + +int RecvRawData(const char *svcId, unsigned int mode, const char *data) +{ + (void)svcId; + (void)mode; + if (data == NULL) { + return -1; + } + printf("[sample] RecvRawData data : %s \n", data); + + size_t decodeLen = 0; + int ret = mbedtls_base64_decode(NULL, 0, &decodeLen, (const unsigned char *)data, strlen(data)); + if ((ret != MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL) || (decodeLen == 0)) { + printf("[sample] RecvRawData calc decodeLen fail(%d)\n", ret); + return -1; + } + + if (decodeLen > MAX_DATA_LEN) { + printf("[sample] RecvRawData decodeLen overSize\n"); + return -1; + } + unsigned char *decodeData = (unsigned char *)malloc(decodeLen); + if (decodeData == NULL) { + return -1; + } + (void)memset_s(decodeData, decodeLen, 0, decodeLen); + size_t outLen = 0; + if (mbedtls_base64_decode(decodeData, decodeLen, &outLen, (const unsigned char *)data, strlen(data)) != 0) { + printf("[sample] RecvRawData encode data fail\r\n"); + free(decodeData); + return -1; + } + for (int i = 0; i < (int)outLen; i++) { + printf("%02x ", decodeData[i]); + } + printf("\n"); + SendRawEncodeData(decodeData, outLen); + if (decodeData != NULL) { + free(decodeData); + } + return 0; +} + +void NotifyNetCfgStatus(enum NetCfgStatus status) +{ + (void)status; + return; +} + +static void *SampleBizTask(const char *arg) +{ + (void)arg; + int ret; + LedInit(); + + /* Parameter Settings */ + ret = SetSafeDistancePower(POWER_NUM); + if (ret != 0) { + printf("[sample] Set saft distance power failed\n"); + return NULL; + } + + struct SoftAPParam config = {0}; + memset_s(&config, sizeof(struct SoftAPParam), 0, sizeof(struct SoftAPParam)); + strncpy_s(config.ssid, sizeof(config.ssid), g_ssid, strlen(g_ssid)); + config.authType = WIFI_SECURITY_OPEN; + ret = SetSoftAPParameter(&config); + if (ret != 0) { + printf("[sample] Set softAP parameters failed\n"); + return NULL; + } + + /* Register callback */ + NetCfgCallback hook; + memset_s(&hook, sizeof(NetCfgCallback), 0, sizeof(NetCfgCallback)); + hook.GetPinCode = GetPinCode; + hook.ParseNetCfgData = ParseNetCfgData; + hook.RecvRawData = RecvRawData; + hook.NotifyNetCfgStatus = NotifyNetCfgStatus; + ret = RegNetCfgCallback(&hook); + if (ret != 0) { + printf("[sample] Regist config callback failed\n"); + return NULL; + } + + /* Starting the SoftAP Network Configuration Service */ + struct DevInfo devInfo[DEVICE_INFO_NUM]; + memset_s(&devInfo, sizeof(devInfo), 0, sizeof(devInfo)); + devInfo[0].key = "productId"; + devInfo[1].key = "sn"; + devInfo[0].value = g_productId; + devInfo[1].value = g_sn; + ret = StartNetCfg(devInfo, DEVICE_INFO_NUM, NETCFG_SOFTAP_NAN); + if (ret != 0) { + printf("[sample] Start config wifi fail.\n"); + return NULL; + } + + while (1) { + printf("[sample] main biz.\n"); + usleep(SAMPLE_BIZ_SLEEP_TIME_US * SAMPLE_TIME_COUNT); + } + + return NULL; +} + +void NetCfgSampleBiz(void) +{ + printf("[sample] new demo, NetCfgSampleBiz enter.\n"); + osThreadAttr_t attr; + + attr.name = "samplebiztask"; + attr.attr_bits = 0U; + attr.cb_mem = NULL; + attr.cb_size = 0U; + attr.stack_mem = NULL; + attr.stack_size = SAMPLE_TASK_STACK_SIZE; + attr.priority = SAMPLE_TASK_PRIO; + + if (osThreadNew((osThreadFunc_t)SampleBizTask, NULL, &attr) == NULL) { + printf("[sample] Falied to create SampleBizTask!\n"); + } +} diff --git a/sdk_liteos/app/demo/src/wifi_softap.c b/sdk_liteos/app/demo/src/wifi_softap.c new file mode 100644 index 0000000000000000000000000000000000000000..4645af49c50740192da14b425289263a8a5eee08 --- /dev/null +++ b/sdk_liteos/app/demo/src/wifi_softap.c @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "hi_wifi_api.h" +#include "wifi_softap.h" +#include "lwip/ip_addr.h" +#include "lwip/netifapi.h" + +#define APP_INIT_VAP_NUM 2 +#define APP_INIT_USR_NUM 2 + +static struct netif *g_lwip_netif = NULL; + +/* clear netif's ip, gateway and netmask */ +void hi_softap_reset_addr(struct netif *pst_lwip_netif) +{ + ip4_addr_t st_gw; + ip4_addr_t st_ipaddr; + ip4_addr_t st_netmask; + + if (pst_lwip_netif == NULL) { + printf("hisi_reset_addr::Null param of netdev\r\n"); + return; + } + + IP4_ADDR(&st_ipaddr, 0, 0, 0, 0); + IP4_ADDR(&st_gw, 0, 0, 0, 0); + IP4_ADDR(&st_netmask, 0, 0, 0, 0); + + netifapi_netif_set_addr(pst_lwip_netif, &st_ipaddr, &st_netmask, &st_gw); +} + +int hi_wifi_start_softap(void) +{ + int ret; + errno_t rc; + char ifname[WIFI_IFNAME_MAX_SIZE + 1] = {0}; + int len = sizeof(ifname); + hi_wifi_softap_config hapd_conf = {0}; + const unsigned char wifi_vap_res_num = APP_INIT_VAP_NUM; + const unsigned char wifi_user_res_num = APP_INIT_USR_NUM; + ip4_addr_t st_gw; + ip4_addr_t st_ipaddr; + ip4_addr_t st_netmask; + + ret = hi_wifi_init(wifi_vap_res_num, wifi_user_res_num); + if (ret != HISI_OK) { + printf("hi_wifi_init\n"); + return -1; + } + + rc = memcpy_s(hapd_conf.ssid, HI_WIFI_MAX_SSID_LEN + 1, "Hisilicon", 9); /* 9:ssid length */ + if (rc != EOK) { + return -1; + } + + hapd_conf.authmode = HI_WIFI_SECURITY_OPEN; + hapd_conf.channel_num = 1; + + ret = hi_wifi_softap_start(&hapd_conf, ifname, &len); + if (ret != HISI_OK) { + printf("hi_wifi_softap_start\n"); + return -1; + } + + /* acquire netif for IP operation */ + g_lwip_netif = netifapi_netif_find(ifname); + if (g_lwip_netif == NULL) { + printf("%s: get netif failed\n", __FUNCTION__); + return -1; + } + + IP4_ADDR(&st_gw, 0, 0, 0, 0); /* input your IP for example: 192.168.1.1 */ + IP4_ADDR(&st_ipaddr, 0, 0, 0, 0); /* input your netmask for example: 192.168.1.1 */ + IP4_ADDR(&st_netmask, 0, 0, 0, 0); /* input your gateway for example: 255.255.255.0 */ + netifapi_netif_set_addr(g_lwip_netif, &st_ipaddr, &st_netmask, &st_gw); + + netifapi_dhcps_start(g_lwip_netif, 0, 0); + + return 0; +} + +void hi_wifi_stop_softap(void) +{ + int ret; + + netifapi_dhcps_stop(g_lwip_netif); + hi_softap_reset_addr(g_lwip_netif); + + ret = hi_wifi_softap_stop(); + if (ret != HISI_OK) { + printf("failed to stop softap\n"); + } + + ret = hi_wifi_deinit(); + if (ret != HISI_OK) { + printf("failed to deinit wifi\n"); + } + + g_lwip_netif = NULL; +} + diff --git a/sdk_liteos/app/demo/src/wifi_sta.c b/sdk_liteos/app/demo/src/wifi_sta.c new file mode 100644 index 0000000000000000000000000000000000000000..02ebb59ffedaa4143b038ab98541f077fb323ef4 --- /dev/null +++ b/sdk_liteos/app/demo/src/wifi_sta.c @@ -0,0 +1,182 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include "hi_wifi_api.h" +#include "wifi_sta.h" +#include "lwip/ip_addr.h" +#include "lwip/netifapi.h" + +#define APP_INIT_VAP_NUM 2 +#define APP_INIT_USR_NUM 2 + +static struct netif *g_lwip_netif = NULL; + +/* clear netif's ip, gateway and netmask */ +void hi_sta_reset_addr(struct netif *pst_lwip_netif) +{ + ip4_addr_t st_gw; + ip4_addr_t st_ipaddr; + ip4_addr_t st_netmask; + + if (pst_lwip_netif == NULL) { + printf("hisi_reset_addr::Null param of netdev\r\n"); + return; + } + + IP4_ADDR(&st_gw, 0, 0, 0, 0); + IP4_ADDR(&st_ipaddr, 0, 0, 0, 0); + IP4_ADDR(&st_netmask, 0, 0, 0, 0); + + netifapi_netif_set_addr(pst_lwip_netif, &st_ipaddr, &st_netmask, &st_gw); +} + +void wifi_wpa_event_cb(const hi_wifi_event *hisi_event) +{ + if (hisi_event == NULL) + return; + + switch (hisi_event->event) { + case HI_WIFI_EVT_SCAN_DONE: + printf("WiFi: Scan results available\n"); + break; + case HI_WIFI_EVT_CONNECTED: + printf("WiFi: Connected\n"); + netifapi_dhcp_start(g_lwip_netif); + break; + case HI_WIFI_EVT_DISCONNECTED: + printf("WiFi: Disconnected\n"); + netifapi_dhcp_stop(g_lwip_netif); + hi_sta_reset_addr(g_lwip_netif); + break; + case HI_WIFI_EVT_WPS_TIMEOUT: + printf("WiFi: wps is timeout\n"); + break; + default: + break; + } +} + +int hi_wifi_start_connect(void) +{ + int ret; + errno_t rc; + hi_wifi_assoc_request assoc_req = {0}; + + /* copy SSID to assoc_req */ + rc = memcpy_s(assoc_req.ssid, HI_WIFI_MAX_SSID_LEN + 1, "Hisilicon", 9); /* 9:ssid length */ + if (rc != EOK) { + return -1; + } + + /* + * OPEN mode + * for WPA2-PSK mode: + * set assoc_req.auth as HI_WIFI_SECURITY_WPA2PSK, + * then memcpy(assoc_req.key, "12345678", 8). + */ + assoc_req.auth = HI_WIFI_SECURITY_OPEN; + + ret = hi_wifi_sta_connect(&assoc_req); + if (ret != HISI_OK) { + return -1; + } + + return 0; +} + +int hi_wifi_start_sta(void) +{ + int ret; + char ifname[WIFI_IFNAME_MAX_SIZE + 1] = {0}; + int len = sizeof(ifname); + const unsigned char wifi_vap_res_num = APP_INIT_VAP_NUM; + const unsigned char wifi_user_res_num = APP_INIT_USR_NUM; + unsigned int num = WIFI_SCAN_AP_LIMIT; + + ret = hi_wifi_init(wifi_vap_res_num, wifi_user_res_num); + if (ret != HISI_OK) { + return -1; + } + + ret = hi_wifi_sta_start(ifname, &len); + if (ret != HISI_OK) { + return -1; + } + + /* register call back function to receive wifi event, etc scan results event, + * connected event, disconnected event. + */ + ret = hi_wifi_register_event_callback(wifi_wpa_event_cb); + if (ret != HISI_OK) { + printf("register wifi event callback failed\n"); + } + + /* acquire netif for IP operation */ + g_lwip_netif = netifapi_netif_find(ifname); + if (g_lwip_netif == NULL) { + printf("%s: get netif failed\n", __FUNCTION__); + return -1; + } + + /* start scan, scan results event will be received soon */ + ret = hi_wifi_sta_scan(); + if (ret != HISI_OK) { + return -1; + } + + sleep(5); /* sleep 5s, waiting for scan result. */ + + hi_wifi_ap_info *pst_results = malloc(sizeof(hi_wifi_ap_info) * WIFI_SCAN_AP_LIMIT); + if (pst_results == NULL) { + return -1; + } + + ret = hi_wifi_sta_scan_results(pst_results, &num); + if (ret != HISI_OK) { + free(pst_results); + return -1; + } + + for (unsigned int loop = 0; (loop < num) && (loop < WIFI_SCAN_AP_LIMIT); loop++) { + printf("SSID: %s\n", pst_results[loop].ssid); + } + free(pst_results); + + /* if received scan results, select one SSID to connect */ + ret = hi_wifi_start_connect(); + if (ret != 0) { + return -1; + } + + return 0; +} + +void hi_wifi_stop_sta(void) +{ + int ret; + + ret = hi_wifi_sta_stop(); + if (ret != HISI_OK) { + printf("failed to stop sta\n"); + } + + ret = hi_wifi_deinit(); + if (ret != HISI_OK) { + printf("failed to deinit wifi\n"); + } + + g_lwip_netif = NULL; +} diff --git a/sdk_liteos/app/wifiiot_app/Makefile b/sdk_liteos/app/wifiiot_app/Makefile new file mode 100755 index 0000000000000000000000000000000000000000..d7c647bbce2e6267d38e8cc159f890a80701dd10 --- /dev/null +++ b/sdk_liteos/app/wifiiot_app/Makefile @@ -0,0 +1,36 @@ +include $(MAIN_TOPDIR)/build/make_scripts/config.mk +-include $(MAIN_TOPDIR)/$(MODULE_DIR)/srcs.mk +include $(MAIN_TOPDIR)/$(MODULE_DIR)/module_config.mk + +OBJDIR = $(MAIN_TOPDIR)/$(OBJ_PATH)/$(MODULE_DIR) + +ID_CFG_FILE = $(MAIN_TOPDIR)/$(MODULE_DIR)/file_id.cfg + +LIB_NAME = lib$(LIB).a +SRCS = $($(LIB)_srcs) +LIBOUT = $(MAIN_TOPDIR)/$(LIB_PATH)/$(MODULE_DIR)/$(LIB_NAME) + +ifdef SRC_FILES +OBJ_SRCS := $(filter %.c, $(SRC_FILES)) +ASM_SRCS := $(filter %.S, $(SRC_FILES)) +else +OBJ_SRCS := $(foreach dir, $(SRCS), $(wildcard $(dir)/*.c)) +ASM_SRCS := $(foreach dir, $(SRCS), $(wildcard $(dir)/*.S )) +endif + +OBJ_SRCS := $(filter-out %/ethernetif.c, $(OBJ_SRCS)) +OBJS = $(patsubst %.c, $(OBJDIR)/%.o, $(OBJ_SRCS)) +ASM_OBJS = $(patsubst %.S, $(OBJDIR)/%.o, $(ASM_SRCS)) + +all: $(LIBOUT) +include $(MAIN_TOPDIR)/build/make_scripts/lib.mk + +clean: + $(Q)$(foreach x, $(OBJS) $(ASM_OBJS) $(LIBOUT), \ + if [ -d $(dir $x) ]; \ + then $(RM) $(dir $x); \ + echo clean dir $(dir $x) success; \ + fi;) + +.PHONY: all clean + diff --git a/sdk_liteos/app/wifiiot_app/SConscript b/sdk_liteos/app/wifiiot_app/SConscript new file mode 100755 index 0000000000000000000000000000000000000000..0e8bbca948cd4392d26dd5a72dd9bff5d58c6974 --- /dev/null +++ b/sdk_liteos/app/wifiiot_app/SConscript @@ -0,0 +1,26 @@ +#!/usr/bin/env python3 +# coding=utf-8 + +import os +from scripts import common_env +Import('env') +Import('env_cfg') +Import('module') + +module_path = env_cfg.get_module_dir(module) +obj_path = env_cfg.obj_path +module_libs = env_cfg.get_module_libs(module) +libs = [] + +env = env.Clone() +env_cfg.append_environs(env, module) +common_env.print_log_env(env, env_cfg.get_module_dir(module)) + +for lib in module_libs: + print('lib_name:',lib) + src_path = module_libs[lib] + objs = [] + for src in src_path: + objs += env.SConscript(os.path.join(src, 'SConscript'), {'env':env}, variant_dir = os.path.join('#', obj_path, module_path, src), duplicate = 0) + libs += env.Library(lib,objs) +Return('libs') diff --git a/sdk_liteos/app/wifiiot_app/app.json b/sdk_liteos/app/wifiiot_app/app.json new file mode 100755 index 0000000000000000000000000000000000000000..81440eb8e0e87ef1996bc2388a3dcefaa67df34c --- /dev/null +++ b/sdk_liteos/app/wifiiot_app/app.json @@ -0,0 +1,30 @@ +{ + "TARGET_LIB": "wifiiot_app", + "APP_SRCS": [ + "init", + "src" + ], + "INCLUDE": [ + "components/iperf2/include", + "app/wifiiot_app/include", + "app/wifiiot_app/init", + "app/wifiiot_app/src", + "config/app", + "config/diag", + "platform/os/Huawei_LiteOS/net/ripple/exports", + "components/ripple/exports", + "components/hilink/include" + ], + "CC_FLAGS": [ + ], + "DEFINES": [ + "_PRE_WLAN_FEATURE_CSI", + "_PRE_WLAN_FEATURE_P2P", + "LWIP_ENABLE_DIAG_CMD=0" + ], + "AR_FLAGS": [], + "LD_FLAGS": [], + "AS_FLAGS": [], + "LD_DIRS": [], + "CLEAN": [] +} diff --git a/sdk_liteos/app/wifiiot_app/include/app_io_init.h b/sdk_liteos/app/wifiiot_app/include/app_io_init.h new file mode 100755 index 0000000000000000000000000000000000000000..7e3174876be5fbd6ccba329e1ceb05e6111df080 --- /dev/null +++ b/sdk_liteos/app/wifiiot_app/include/app_io_init.h @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2020 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __APP_IO_INIT_H__ +#define __APP_IO_INIT_H__ + +#include + +HI_CPP_START + +hi_void app_io_init(hi_void); + +HI_CPP_END +#endif // __APP_IO_INIT_H__ + diff --git a/sdk_liteos/app/wifiiot_app/include/app_main.h b/sdk_liteos/app/wifiiot_app/include/app_main.h new file mode 100755 index 0000000000000000000000000000000000000000..c1f3f4a3a53f5af2c6b4b975e2b12dbf06783117 --- /dev/null +++ b/sdk_liteos/app/wifiiot_app/include/app_main.h @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2020 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __APP_MAIN_H__ +#define __APP_MAIN_H__ + +#include + +typedef struct { + hi_u16 gpio6_cfg; + hi_u16 gpio8_cfg; + hi_u16 gpio10_cfg; + hi_u16 gpio11_cfg; + hi_u16 gpio12_cfg; + hi_u16 gpio13_cfg; + hi_u16 sfc_csn_cfg; +} app_iocfg_backup; + +#endif // __APP_MAIN_H__ diff --git a/sdk_liteos/app/wifiiot_app/init/SConscript b/sdk_liteos/app/wifiiot_app/init/SConscript new file mode 100755 index 0000000000000000000000000000000000000000..aceb2b6a9464ce64030c1f9c5374ec933dcab384 --- /dev/null +++ b/sdk_liteos/app/wifiiot_app/init/SConscript @@ -0,0 +1,6 @@ +Import('env') + +env = env.Clone() + +objs = env.Object(Glob('*.c')) +Return('objs') diff --git a/sdk_liteos/app/wifiiot_app/init/app_io_init.c b/sdk_liteos/app/wifiiot_app/init/app_io_init.c new file mode 100755 index 0000000000000000000000000000000000000000..00b9e37df305d793a2a65d234feff43a57c43623 --- /dev/null +++ b/sdk_liteos/app/wifiiot_app/init/app_io_init.c @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2020 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +hi_void app_io_init(hi_void) +{ + /* 用户需根据应用场景,合理选择各外设的IO复用配置,此处仅列出示例 */ +#ifdef CONFIG_UART0_SUPPORT + /* uart0 调试串口 */ + hi_io_set_func(HI_IO_NAME_GPIO_3, HI_IO_FUNC_GPIO_3_UART0_TXD); /* uart0 tx */ + hi_io_set_func(HI_IO_NAME_GPIO_4, HI_IO_FUNC_GPIO_4_UART0_RXD); /* uart0 rx */ +#endif + +#ifdef CONFIG_UART1_SUPPORT + /* uart1 AT命令串口 */ + hi_io_set_func(HI_IO_NAME_GPIO_5, HI_IO_FUNC_GPIO_5_UART1_RXD); /* uart1 rx */ + hi_io_set_func(HI_IO_NAME_GPIO_6, HI_IO_FUNC_GPIO_6_UART1_TXD); /* uart1 tx */ +#endif + +#ifdef CONFIG_UART2_SUPPORT + /* uart2 sigma认证使用串口 */ + hi_io_set_func(HI_IO_NAME_GPIO_11, HI_IO_FUNC_GPIO_11_UART2_TXD); /* uart2 tx */ + hi_io_set_func(HI_IO_NAME_GPIO_12, HI_IO_FUNC_GPIO_12_UART2_RXD); /* uart2 rx */ +#endif + + /* SPI MUX: */ +#ifdef CONFIG_SPI_SUPPORT + /* SPI IO复用也可以选择5/6/7/8;0/1/2/3, 根据产品设计选择 */ + hi_io_set_func(HI_IO_NAME_GPIO_9, HI_IO_FUNC_GPIO_9_SPI0_TXD); + hi_io_set_func(HI_IO_NAME_GPIO_10, HI_IO_FUNC_GPIO_10_SPI0_CK); + hi_io_set_func(HI_IO_NAME_GPIO_11, HI_IO_FUNC_GPIO_11_SPI0_RXD); + hi_io_set_func(HI_IO_NAME_GPIO_12, HI_IO_FUNC_GPIO_12_SPI0_CSN); + hi_io_set_driver_strength(HI_IO_NAME_GPIO_9, HI_IO_DRIVER_STRENGTH_0); +#endif + + /* I2C MUX: */ +#ifdef CONFIG_I2C_SUPPORT + /* I2C IO复用也可以选择3/4; 9/10,根据产品设计选择 */ + hi_io_set_func(HI_IO_NAME_GPIO_0, HI_IO_FUNC_GPIO_0_I2C1_SDA); + hi_io_set_func(HI_IO_NAME_GPIO_1, HI_IO_FUNC_GPIO_1_I2C1_SCL); +#endif + + /* PWM MUX: */ +#ifdef CONFIG_PWM_SUPPORT + /* PWM 0/2/3/4/5 配置同理 */ + hi_io_set_func(HI_IO_NAME_GPIO_8, HI_IO_FUNC_GPIO_8_PWM1_OUT); +#endif + + /* I2S MUX: */ +#ifdef CONFIG_I2S_SUPPORT + hi_io_set_func(HI_IO_NAME_GPIO_9, HI_IO_FUNC_GPIO_9_I2S0_MCLK); + hi_io_set_func(HI_IO_NAME_GPIO_10, HI_IO_FUNC_GPIO_10_I2S0_TX); + hi_io_set_func(HI_IO_NAME_GPIO_11, HI_IO_FUNC_GPIO_11_I2S0_RX); + hi_io_set_func(HI_IO_NAME_GPIO_12, HI_IO_FUNC_GPIO_12_I2S0_BCLK); + hi_io_set_func(HI_IO_NAME_GPIO_13, HI_IO_FUNC_GPIO_13_I2S0_WS); +#endif + + /* SDIO MUX: */ +#ifdef CONFIG_SDIO_SUPPORT + (hi_void)hi_io_set_func(HI_IO_NAME_GPIO_9, HI_IO_FUNC_GPIO_9_SDIO_D2); + (hi_void)hi_io_set_func(HI_IO_NAME_GPIO_10, HI_IO_FUNC_GPIO_10_SDIO_D3); + (hi_void)hi_io_set_func(HI_IO_NAME_GPIO_11, HI_IO_FUNC_GPIO_11_SDIO_CMD); + (hi_void)hi_io_set_func(HI_IO_NAME_GPIO_12, HI_IO_FUNC_GPIO_12_SDIO_CLK); + (hi_void)hi_io_set_func(HI_IO_NAME_GPIO_13, HI_IO_FUNC_GPIO_13_SDIO_D0); + (hi_void)hi_io_set_func(HI_IO_NAME_GPIO_14, HI_IO_FUNC_GPIO_14_SDIO_D1); + + (hi_void)hi_io_set_pull(HI_IO_NAME_GPIO_9, HI_IO_PULL_UP); + (hi_void)hi_io_set_pull(HI_IO_NAME_GPIO_10, HI_IO_PULL_UP); + (hi_void)hi_io_set_pull(HI_IO_NAME_GPIO_11, HI_IO_PULL_UP); + (hi_void)hi_io_set_pull(HI_IO_NAME_GPIO_13, HI_IO_PULL_UP); + (hi_void)hi_io_set_pull(HI_IO_NAME_GPIO_14, HI_IO_PULL_UP); +#endif +} + diff --git a/sdk_liteos/app/wifiiot_app/module_config.mk b/sdk_liteos/app/wifiiot_app/module_config.mk new file mode 100755 index 0000000000000000000000000000000000000000..5c9baf2ae932a1de94983eb1a7a8193ff246a76d --- /dev/null +++ b/sdk_liteos/app/wifiiot_app/module_config.mk @@ -0,0 +1,5 @@ +ALL_LIBS := demo +demo_srcs := init src +CCFLAGS += +CCFLAGS += -D_PRE_WLAN_FEATURE_CSI -D_PRE_WLAN_FEATURE_P2P -DLWIP_ENABLE_DIAG_CMD=0 +CCFLAGS += -I$(MAIN_TOPDIR)/components/iperf2/include -I$(MAIN_TOPDIR)/app/demo/include -I$(MAIN_TOPDIR)/app/demo/init -I$(MAIN_TOPDIR)/app/demo/src -I$(MAIN_TOPDIR)/config/app -I$(MAIN_TOPDIR)/config/diag -I$(MAIN_TOPDIR)/platform/os/Huawei_LiteOS/net/ripple/exports -I$(MAIN_TOPDIR)/components/ripple/exports diff --git a/sdk_liteos/app/wifiiot_app/src/SConscript b/sdk_liteos/app/wifiiot_app/src/SConscript new file mode 100755 index 0000000000000000000000000000000000000000..aceb2b6a9464ce64030c1f9c5374ec933dcab384 --- /dev/null +++ b/sdk_liteos/app/wifiiot_app/src/SConscript @@ -0,0 +1,6 @@ +Import('env') + +env = env.Clone() + +objs = env.Object(Glob('*.c')) +Return('objs') diff --git a/sdk_liteos/app/wifiiot_app/src/app_demo_upg_verify.c b/sdk_liteos/app/wifiiot_app/src/app_demo_upg_verify.c new file mode 100755 index 0000000000000000000000000000000000000000..79a0ee8fab4b2a91698804e17ef99437e0f9353a --- /dev/null +++ b/sdk_liteos/app/wifiiot_app/src/app_demo_upg_verify.c @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2020 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "app_demo_upg_verify.h" +#include +#include + +hi_u32 app_demo_upg_check_chip_product(const hi_upg_user_info *info, hi_void *param) +{ + hi_char file_chip[HI_APP_CHIP_PRODUCT_LEN] = { 0 }; + app_upg_user_info *user_info = HI_NULL; + + hi_unref_param(param); + if (info == HI_NULL) { + printf("[app upg demo verify]null."); + return HI_ERR_FAILURE; + } + user_info = (app_upg_user_info *)info; + if (sprintf_s(file_chip, HI_APP_CHIP_PRODUCT_LEN, "%s", CONFIG_CHIP_PRODUCT_NAME) < 0) { + printf("[app upg demo verify]sprintf_s error \r\n"); + return HI_ERR_FAILURE; + } + printf("[app upg demo verify]kernel chip product:%s \r\n", file_chip); + + if (memcmp(user_info->chip_product, file_chip, HI_APP_CHIP_PRODUCT_LEN) == EOK) { + return HI_ERR_SUCCESS; + } + + return HI_ERR_FAILURE; +} + +hi_u32 app_demo_upg_init(hi_void) +{ + return hi_upg_register_file_verify_fn(app_demo_upg_check_chip_product, HI_NULL); +} diff --git a/sdk_liteos/app/wifiiot_app/src/app_demo_upg_verify.h b/sdk_liteos/app/wifiiot_app/src/app_demo_upg_verify.h new file mode 100755 index 0000000000000000000000000000000000000000..cb1ff3432636ac221cb6a2c9a72febb3f2c9f427 --- /dev/null +++ b/sdk_liteos/app/wifiiot_app/src/app_demo_upg_verify.h @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2020 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _APP_DEMO_UPG_VERIFY_H_ +#define _APP_DEMO_UPG_VERIFY_H_ + +#include + +#define HI_APP_CHIP_PRODUCT_LEN 8 /* 8: chip product length */ + +typedef struct { + hi_char chip_product[HI_APP_CHIP_PRODUCT_LEN]; + hi_u8 reserved[24]; /* 24 bytes reserved */ +}app_upg_user_info; + +hi_u32 app_demo_upg_init(hi_void); + +#endif /* _APP_DEMO_UPG_VERIFY_H_ */ + diff --git a/sdk_liteos/app/wifiiot_app/src/app_main.c b/sdk_liteos/app/wifiiot_app/src/app_main.c new file mode 100755 index 0000000000000000000000000000000000000000..a8f2a0aaaf956ca20c7eb9a15eab9a2385371487 --- /dev/null +++ b/sdk_liteos/app/wifiiot_app/src/app_main.c @@ -0,0 +1,495 @@ +/* + * Copyright (c) 2020 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "app_main.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#if defined(CONFIG_AT_COMMAND) || defined(CONFIG_FACTORY_TEST_MODE) +#include +#endif +#include +#include +#include +#include +#include +#ifdef CONFIG_DMA_SUPPORT +#include +#endif +#ifdef CONFIG_I2C_SUPPORT +#include +#endif +#ifdef CONFIG_I2S_SUPPORT +#include +#endif +#ifdef CONFIG_SPI_SUPPORT +#include +#endif +#ifdef CONFIG_PWM_SUPPORT +#include +#endif +#ifdef CONFIG_SDIO_SUPPORT +#include +#include +#include +#endif + +#ifndef CONFIG_FACTORY_TEST_MODE +#include "lwip/opt.h" +#include "lwip/ip_addr.h" +#include "lwip/netifapi.h" +#endif + +#include "app_demo_upg_verify.h" +#include "hi_wifi_api.h" +#ifdef CONFIG_HILINK +#include "hilink.h" +#endif + +#include "ohos_main.h" + +#define APP_DEMO_RELEASE_MEM_TASK_SIZE 0x200 +/* 高优先级(不得小于3),尽快释放系统app_main栈内存 */ +#define APP_DEMO_RELEASE_MEM_TASK_PRIO 0x3 + +#define APP_INIT_EVENT_NUM 4 +#define APP_INIT_VAP_NUM 2 +#ifdef CONFIG_MESH_SUPPORT +#define APP_INIT_USR_NUM 6 +#else +#define APP_INIT_USR_NUM 2 +#endif + +#define PERIPHERAL_INIT_ERR_FLASH (1 << 0) +#define PERIPHERAL_INIT_ERR_UART0 (1 << 1) +#define PERIPHERAL_INIT_ERR_UART1 (1 << 2) +#define PERIPHERAL_INIT_ERR_UART2 (1 << 3) +#define PERIPHERAL_INIT_ERR_IO (1 << 4) +#define PERIPHERAL_INIT_ERR_CIPHER (1 << 5) +#define PERIPHERAL_INIT_ERR_DMA (1 << 6) +#define PERIPHERAL_INIT_ERR_I2C (1 << 7) +#define PERIPHERAL_INIT_ERR_I2S (1 << 8) +#define PERIPHERAL_INIT_ERR_SPI (1 << 9) +#define PERIPHERAL_INIT_ERR_PWM (1 << 10) +#define PERIPHERAL_INIT_ERR_SDIO (1 << 11) + +#ifndef IO_CTRL_REG_BASE_ADDR +#define IO_CTRL_REG_BASE_ADDR 0x904 +#endif +#define iocfg_reg_addr(_x) (HI_IOCFG_REG_BASE + IO_CTRL_REG_BASE_ADDR + (_x) * 4) +#define IOCFG_LOWPOWER_CFG_VAL 0xF8 + +#ifdef CONFIG_SDIO_SUPPORT +#define APP_SDIO_INIT_TASK_SIZE 0x1000 +#define APP_SDIO_INIT_TASK_PRIO 25 + +static hi_void *sdio_init_task_body(hi_void *param) +{ + printf("start sdio init\r\n"); + hi_unref_param(param); + /* 避免由于SDIO HOST长时间未配置触发看门狗异常,此处先关狗 */ + hi_watchdog_disable(); + hi_u32 ret = hi_sdio_init(); + if (ret != HI_ERR_SUCCESS) { + printf("sdio driver init fail\r\n"); + } + hi_watchdog_enable(); + app_demo_sdio_callback_init(); + printf("finish sdio init\r\n"); + return HI_NULL; +} + +hi_u32 app_sdio_init(hi_void) +{ + /* Create a task to init sdio */ + hi_u32 sdio_init_task_id = 0; + hi_task_attr attr = {0}; + attr.stack_size = APP_SDIO_INIT_TASK_SIZE; + attr.task_prio = APP_SDIO_INIT_TASK_PRIO; + attr.task_name = (hi_char*)"sdio_init"; + hi_u32 ret = hi_task_create(&sdio_init_task_id, &attr, sdio_init_task_body, HI_NULL); + if (ret != HI_ERR_SUCCESS) { + printf("Falied to create sdio init task!\n"); + } + return ret; +} +#endif + +#define CLKEN_I2C0 14 +#define CLKEN_I2C1 15 +#define CLKEN_SPI0 5 +#define CLKEN_SPI1 0 +#define CLKEN_MONITOR 6 +#define CLKEN_DMA_WBUS 1 +#define CLKEN1_PWM5 10 +#define CLKEN1_PWM_BUS 6 +#define CLKEN1_PWM 5 +#define CLKEN1_PWM4 4 +#define CLKEN1_PWM3 3 +#define CLKEN1_PWM2 2 +#define CLKEN1_PWM1 1 +#define CLKEN1_PWM0 0 +#define CLKEN1_PWM_ALL ((1 << (CLKEN1_PWM0)) | (1 << (CLKEN1_PWM1)) | (1 << (CLKEN1_PWM2)) | (1 << (CLKEN1_PWM3)) | \ + (1 << (CLKEN1_PWM4)) | (1 << (CLKEN1_PWM5))) +#define CLKEN2_I2S_BUS 11 +#define CLKEN2_I2S 10 +#define CLKEN_UART2 6 +#define CLKEN_UART2_BUS 9 +#define CLKEN_TIMER1 7 +#define CLKEN_TIMER2 8 +#define CLKEN_SDIO_WBUS 4 + +hi_void peripheral_close_clken(hi_void) +{ + hi_u16 reg_val; + hi_reg_read16(CLDO_CTL_CLKEN_REG, reg_val); + reg_val &= ~((1 << CLKEN_I2C0) | (1 << CLKEN_I2C1)); + reg_val &= ~((1 << CLKEN_SPI0) | (1 << CLKEN_SPI1)); + reg_val &= ~((1 << CLKEN_DMA_WBUS) | (1 << CLKEN_MONITOR)); + reg_val &= ~((1 << CLKEN_TIMER1) | (1 << CLKEN_TIMER2)); + hi_reg_write16(CLDO_CTL_CLKEN_REG, reg_val); /* disable clken0 clk gate */ + +#ifndef CONFIG_PWM_HOLD_AFTER_REBOOT + hi_reg_read16(CLDO_CTL_CLKEN1_REG, reg_val); + reg_val &= ~CLKEN1_PWM_ALL; + reg_val &= ~((1 << CLKEN1_PWM_BUS) | (1 << CLKEN1_PWM)); + hi_reg_write16(CLDO_CTL_CLKEN1_REG, reg_val); /* disable clken1 clk gate */ +#endif + + hi_reg_read16(CLDO_CTL_CLKEN2_REG, reg_val); + reg_val &= ~((1 << CLKEN2_I2S) | (1 << CLKEN2_I2S_BUS)); + hi_reg_write16(CLDO_CTL_CLKEN2_REG, reg_val); /* disable clken2 clk gate */ + hi_reg_read16(W_CTL_UART_MAC80M_CLKEN_REG, reg_val); +#ifdef CONFIG_SDIO_SUPPORT + reg_val &= ~((1 << CLKEN_UART2) | (1 << CLKEN_UART2_BUS)); +#else + reg_val &= ~((1 << CLKEN_UART2) | (1 << CLKEN_UART2_BUS) | (1 << CLKEN_SDIO_WBUS)); +#endif + hi_reg_write16(W_CTL_UART_MAC80M_CLKEN_REG, reg_val); /* disable uart_mac80m clk gate */ + hi_reg_write16(PMU_CMU_CTL_CLK_960M_GT_REG, 0x1); /* disable 960m clk gate */ +} + +static hi_uart_attribute g_at_uart_cfg = {115200, 8, 1, 0, 0}; + +hi_bool g_have_inited = HI_FALSE; +static app_iocfg_backup g_iocfg_backup = {0}; + +hi_void peripheral_init(hi_void) +{ + hi_u32 ret; + hi_u32 err_info = 0; + hi_cipher_set_clk_switch(HI_TRUE); + peripheral_close_clken(); + hi_flash_deinit(); + ret = hi_flash_init(); + if (ret != HI_ERR_SUCCESS) { + err_info |= PERIPHERAL_INIT_ERR_FLASH; + } + + if (g_have_inited == HI_FALSE) { + ret = hi_uart_init(HI_UART_IDX_1, &g_at_uart_cfg, HI_NULL); + if (ret != HI_ERR_SUCCESS) { + err_info |= PERIPHERAL_INIT_ERR_UART1; + } + } else { + ret = hi_uart_lp_restore(HI_UART_IDX_1); + if (ret != HI_ERR_SUCCESS) { + err_info |= PERIPHERAL_INIT_ERR_UART0; + } + ret = hi_uart_lp_restore(HI_UART_IDX_0); + if (ret != HI_ERR_SUCCESS) { + err_info |= PERIPHERAL_INIT_ERR_UART1; + } + ret = hi_uart_lp_restore(HI_UART_IDX_2); + if (ret != HI_ERR_SUCCESS) { + err_info |= PERIPHERAL_INIT_ERR_UART2; + } + } + g_have_inited = HI_TRUE; + + app_io_init(); + + ret = hi_cipher_init(); + if (ret != HI_ERR_SUCCESS) { + err_info |= PERIPHERAL_INIT_ERR_CIPHER; + } + +#ifdef CONFIG_DMA_SUPPORT + /* 如果需要使用UART/SPI的DMA功能,或者使用I2S驱动等,需要初始化DMA */ + /* if product use dma in uart or spi, or use I2S driver, or DMA memory transfer, + should init DMA Driver here. */ + ret = hi_dma_init(); + if (ret != HI_ERR_SUCCESS) { + err_info |= PERIPHERAL_INIT_ERR_DMA; + } +#endif + +#ifdef CONFIG_I2C_SUPPORT + ret = hi_i2c_deinit(HI_I2C_IDX_0); /* if wake_up from deep sleep, should deinit first */ + ret |= hi_i2c_init(HI_I2C_IDX_0, 100000); /* baudrate: 100000 */ + if (ret != HI_ERR_SUCCESS) { + err_info |= PERIPHERAL_INIT_ERR_I2C; + } +#endif + +#ifdef CONFIG_I2S_SUPPORT + ret = hi_i2s_deinit(); /* if wake_up from deep sleep, should deinit first */ + hi_i2s_attribute i2s_cfg = { + .sample_rate = HI_I2S_SAMPLE_RATE_8K, + .resolution = HI_I2S_RESOLUTION_16BIT, + }; + ret |= hi_i2s_init(&i2s_cfg); + if (ret != HI_ERR_SUCCESS) { + err_info |= PERIPHERAL_INIT_ERR_I2S; + } +#endif + +#ifdef CONFIG_SPI_SUPPORT + ret = hi_spi_deinit(HI_SPI_ID_0); /* if wake_up from deep sleep, should deinit first */ + hi_spi_cfg_basic_info spi_cfg_basic_info; + spi_cfg_basic_info.cpha = 1; + spi_cfg_basic_info.cpol = 1; + spi_cfg_basic_info.data_width = HI_SPI_CFG_DATA_WIDTH_E_7BIT; + spi_cfg_basic_info.endian = 0; + spi_cfg_basic_info.fram_mode = 0; + spi_cfg_basic_info.freq = 2000000; /* set frequency 2000000 */ + hi_spi_cfg_init_param spi_init_param = {0}; + spi_init_param.is_slave = HI_FALSE; + ret |= hi_spi_init(HI_SPI_ID_0, spi_init_param, &spi_cfg_basic_info); + if (ret != HI_ERR_SUCCESS) { + err_info |= PERIPHERAL_INIT_ERR_SPI; + } +#endif + +#ifdef CONFIG_PWM_SUPPORT + ret = hi_pwm_init(HI_PWM_PORT_PWM1); + if (ret != HI_ERR_SUCCESS) { + err_info |= PERIPHERAL_INIT_ERR_PWM; + } +#endif + +#ifdef AT_DEBUG_CMD_SUPPORT + if (err_info != 0) { + hi_at_printf("peri_init:%x\r\n", err_info); + } +#endif +} + +hi_void peripheral_init_no_sleep(hi_void) +{ + /* 示例:深睡唤醒不需要重新初始化的外设,可放置在此函数初始化 */ +#ifdef CONFIG_SDIO_SUPPORT + hi_sdio_set_powerdown_when_deep_sleep(HI_FALSE); + hi_u32 ret = app_sdio_init(); + if (ret != HI_ERR_SUCCESS) { + printf("sdio init failed\r\n"); + } +#endif +} + +hi_u32 config_before_sleep(hi_void) +{ + /* 用户根据实际io设计配置,防止深睡阶段漏电流 */ + if (hi_lpc_get_type() == HI_DEEP_SLEEP) { +#ifdef AT_DEBUG_CMD_SUPPORT + hi_at_printf("!"); +#endif + /* 用户根据实际io使用情况设置:无上拉电阻、无下拉电阻、禁止输入信号使能等,防止漏电流,具体参考芯片手册 */ + hi_reg_read16(iocfg_reg_addr(HI_IO_NAME_GPIO_6), g_iocfg_backup.gpio6_cfg); + hi_reg_read16(iocfg_reg_addr(HI_IO_NAME_GPIO_8), g_iocfg_backup.gpio8_cfg); + hi_reg_read16(iocfg_reg_addr(HI_IO_NAME_GPIO_10), g_iocfg_backup.gpio10_cfg); + hi_reg_read16(iocfg_reg_addr(HI_IO_NAME_GPIO_11), g_iocfg_backup.gpio11_cfg); + hi_reg_read16(iocfg_reg_addr(HI_IO_NAME_GPIO_12), g_iocfg_backup.gpio12_cfg); + hi_reg_read16(iocfg_reg_addr(HI_IO_NAME_GPIO_13), g_iocfg_backup.gpio13_cfg); + hi_reg_read16(iocfg_reg_addr(HI_IO_NAME_SFC_CSN), g_iocfg_backup.sfc_csn_cfg); + + hi_reg_write16(iocfg_reg_addr(HI_IO_NAME_GPIO_6), IOCFG_LOWPOWER_CFG_VAL); + hi_reg_write16(iocfg_reg_addr(HI_IO_NAME_GPIO_8), IOCFG_LOWPOWER_CFG_VAL); + hi_reg_write16(iocfg_reg_addr(HI_IO_NAME_GPIO_10), IOCFG_LOWPOWER_CFG_VAL); + hi_reg_write16(iocfg_reg_addr(HI_IO_NAME_GPIO_11), IOCFG_LOWPOWER_CFG_VAL); + hi_reg_write16(iocfg_reg_addr(HI_IO_NAME_GPIO_12), IOCFG_LOWPOWER_CFG_VAL); + hi_reg_write16(iocfg_reg_addr(HI_IO_NAME_GPIO_13), IOCFG_LOWPOWER_CFG_VAL); + hi_reg_write16(iocfg_reg_addr(HI_IO_NAME_SFC_CSN), IOCFG_LOWPOWER_CFG_VAL); + hi_uart_lp_save(HI_UART_IDX_0); + hi_uart_lp_save(HI_UART_IDX_1); + hi_uart_lp_save(HI_UART_IDX_2); + } + return HI_ERR_SUCCESS; +} + +hi_u32 config_after_sleep(hi_void) +{ + /* 用户根据实际io设计恢复,防止深睡阶段漏电流 */ + if (hi_lpc_get_type() == HI_DEEP_SLEEP) { + /* 用户根据实际io使用情况配置恢复 */ + hi_reg_write16(iocfg_reg_addr(HI_IO_NAME_GPIO_6), g_iocfg_backup.gpio6_cfg); + hi_reg_write16(iocfg_reg_addr(HI_IO_NAME_GPIO_8), g_iocfg_backup.gpio8_cfg); + hi_reg_write16(iocfg_reg_addr(HI_IO_NAME_GPIO_10), g_iocfg_backup.gpio10_cfg); + hi_reg_write16(iocfg_reg_addr(HI_IO_NAME_GPIO_11), g_iocfg_backup.gpio11_cfg); + hi_reg_write16(iocfg_reg_addr(HI_IO_NAME_GPIO_12), g_iocfg_backup.gpio12_cfg); + hi_reg_write16(iocfg_reg_addr(HI_IO_NAME_GPIO_13), g_iocfg_backup.gpio13_cfg); + hi_reg_write16(iocfg_reg_addr(HI_IO_NAME_SFC_CSN), g_iocfg_backup.sfc_csn_cfg); +#ifdef AT_DEBUG_CMD_SUPPORT + hi_at_printf("@\r\n"); +#endif + } + return HI_ERR_SUCCESS; +} + +static hi_void *app_demo_task_second_body(hi_void *param) +{ + /* 释放app_main栈内存使用 */ + hi_unref_param(param); + return HI_NULL; +} + +static hi_void *app_demo_task_body(hi_void *param) +{ + /* 释放app_main栈内存使用 */ + hi_unref_param(param); + + hi_u32 task_id = 0; + hi_task_attr attr = {0}; + attr.stack_size = APP_DEMO_RELEASE_MEM_TASK_SIZE; + attr.task_prio = APP_DEMO_RELEASE_MEM_TASK_PRIO; + attr.task_name = (hi_char*)"app_demo_second"; + hi_u32 ret = hi_task_create(&task_id, &attr, app_demo_task_second_body, HI_NULL); + if (ret != HI_ERR_SUCCESS) { + printf("Falied to create app_demo_second task:0x%x\n", ret); + } + return HI_NULL; +} + +hi_void app_demo_task_release_mem(hi_void) +{ + /* 释放app_main栈内存使用 */ + hi_u32 task_id = 0; + hi_task_attr attr = {0}; + attr.stack_size = APP_DEMO_RELEASE_MEM_TASK_SIZE; + attr.task_prio = APP_DEMO_RELEASE_MEM_TASK_PRIO; + attr.task_name = (hi_char*)"app_demo"; + hi_u32 ret = hi_task_create(&task_id, &attr, app_demo_task_body, HI_NULL); + if (ret != HI_ERR_SUCCESS) { + printf("Falied to create app_demo task:0x%x\n", ret); + } + return; +} + + +hi_void app_main(hi_void) +{ +#ifdef CONFIG_FACTORY_TEST_MODE + printf("factory test mode!\r\n"); +#endif + + const hi_char* sdk_ver = hi_get_sdk_version(); + printf("sdk ver:%s\r\n", sdk_ver); + + hi_flash_partition_table *ptable = HI_NULL; + + peripheral_init(); + peripheral_init_no_sleep(); + +#ifndef CONFIG_FACTORY_TEST_MODE + hi_lpc_register_wakeup_entry(peripheral_init); +#endif + + hi_u32 ret = hi_factory_nv_init(HI_FNV_DEFAULT_ADDR, HI_NV_DEFAULT_TOTAL_SIZE, HI_NV_DEFAULT_BLOCK_SIZE); + if (ret != HI_ERR_SUCCESS) { + printf("factory nv init fail\r\n"); + } + + /* partion table should init after factory nv init. */ + ret = hi_flash_partition_init(); + if (ret != HI_ERR_SUCCESS) { + printf("flash partition table init fail:0x%x \r\n", ret); + } + ptable = hi_get_partition_table(); + + ret = hi_nv_init(ptable->table[HI_FLASH_PARTITON_NORMAL_NV].addr, ptable->table[HI_FLASH_PARTITON_NORMAL_NV].size, + HI_NV_DEFAULT_BLOCK_SIZE); + if (ret != HI_ERR_SUCCESS) { + printf("nv init fail\r\n"); + } + +#ifndef CONFIG_FACTORY_TEST_MODE + hi_upg_init(); +#endif + + /* if not use file system, there is no need init it */ + hi_fs_init(); + + (hi_void)hi_event_init(APP_INIT_EVENT_NUM, HI_NULL); + hi_sal_init(); + /* 此处设为TRUE后中断中看门狗复位会显示复位时PC值,但有复位不完全风险,量产版本请务必设为FALSE */ + hi_syserr_watchdog_debug(HI_FALSE); + /* 默认记录宕机信息到FLASH,根据应用场景,可不记录,避免频繁异常宕机情况损耗FLASH寿命 */ + hi_syserr_record_crash_info(HI_TRUE); + + hi_lpc_init(); + hi_lpc_register_hw_handler(config_before_sleep, config_after_sleep); + +#if defined(CONFIG_AT_COMMAND) || defined(CONFIG_FACTORY_TEST_MODE) + ret = hi_at_init(); + if (ret == HI_ERR_SUCCESS) { + hi_at_sys_cmd_register(); + } +#endif + + /* 如果不需要使用Histudio查看WIFI驱动运行日志等,无需初始化diag */ + /* if not use histudio for diagnostic, diag initialization is unnecessary */ + /* Shell and Diag use the same uart port, only one of them can be selected */ +#ifndef CONFIG_FACTORY_TEST_MODE + +#ifndef ENABLE_SHELL_DEBUG +#ifdef CONFIG_DIAG_SUPPORT + (hi_void)hi_diag_init(); +#endif +#else + (hi_void)hi_shell_init(); +#endif + + tcpip_init(NULL, NULL); +#endif + + ret = hi_wifi_init(APP_INIT_VAP_NUM, APP_INIT_USR_NUM); + if (ret != HISI_OK) { + printf("wifi init failed!\n"); + } else { + printf("wifi init success!\n"); + } + app_demo_task_release_mem(); /* 释放系统栈内存所使用任务 */ + +#ifndef CONFIG_FACTORY_TEST_MODE + app_demo_upg_init(); +#ifdef CONFIG_HILINK + ret = hilink_main(); + if (ret != HISI_OK) { + printf("hilink init failed!\n"); + } else { + printf("hilink init success!\n"); + } +#endif +#endif + OHOS_Main(); +} + diff --git a/sdk_liteos/app/wifiiot_app/src/ohos_main.c b/sdk_liteos/app/wifiiot_app/src/ohos_main.c new file mode 100644 index 0000000000000000000000000000000000000000..4915d3a79918c1813d286b4f5e9726e5d1a78b27 --- /dev/null +++ b/sdk_liteos/app/wifiiot_app/src/ohos_main.c @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2020 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ohos_main.h" +#include +#include + +#if defined(CONFIG_AT_COMMAND) || defined(CONFIG_FACTORY_TEST_MODE) +int __attribute__((weak)) QuerySysparaCmd() +{ + return; +} + +static const at_cmd_func G_OHOS_AT_FUNC_TBL[] = { + {"+SYSPARA", 8, 0, 0, 0, (at_call_back_func)QuerySysparaCmd}, +}; +#define OHOS_AT_FUNC_NUM (sizeof(G_OHOS_AT_FUNC_TBL) / sizeof(G_OHOS_AT_FUNC_TBL[0])) +#endif + +void __attribute__((weak)) OHOS_SystemInit(void) +{ + return; +} + +void OHOS_Main() +{ +#if defined(CONFIG_AT_COMMAND) || defined(CONFIG_FACTORY_TEST_MODE) + hi_u32 ret; + ret = hi_at_init(); + if (ret == HI_ERR_SUCCESS) { + hi_u32 ret2 = hi_at_register_cmd(G_OHOS_AT_FUNC_TBL, OHOS_AT_FUNC_NUM); + if (ret2 != HI_ERR_SUCCESS) { + printf("Register ohos failed!\n"); + } + } +#endif + OHOS_SystemInit(); +} diff --git a/sdk_liteos/app/wifiiot_app/src/ohos_main.h b/sdk_liteos/app/wifiiot_app/src/ohos_main.h new file mode 100644 index 0000000000000000000000000000000000000000..d4d64bcac27ff24d68a97a2a3bf4460e802dc785 --- /dev/null +++ b/sdk_liteos/app/wifiiot_app/src/ohos_main.h @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2020 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_MAIN_H +#define OHOS_MAIN_H + +void OHOS_Main(); +#endif // OHOS_MAIN_H diff --git a/sdk_liteos/boot/commonboot/adc_drv.h b/sdk_liteos/boot/commonboot/adc_drv.h new file mode 100644 index 0000000000000000000000000000000000000000..c7f1e761cff406762e4a7f01c0b6df6bd944b0d0 --- /dev/null +++ b/sdk_liteos/boot/commonboot/adc_drv.h @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __ADC_DRV_H__ +#define __ADC_DRV_H__ +#include +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ + + +#define LS_ADC_CLK_DIV1_REG CLDO_CTL_CLK_DIV1_REG +#define LS_ADC_CLK_DIV1_OFFSET 9 + +#define HI_LS_ADC_REG_BASE 0x40070000 /* LD ADC base address */ +#define REG_ADC_CFG (HI_LS_ADC_REG_BASE + 0x00) +#define REG_ADC_FIFO_CFG (HI_LS_ADC_REG_BASE + 0x04) +#define REG_ADC_IMSC (HI_LS_ADC_REG_BASE + 0x08) +#define REG_ADC_CR (HI_LS_ADC_REG_BASE + 0x0C) +#define REG_ADC_SR (HI_LS_ADC_REG_BASE + 0x10) +#define REG_ADC_RIS (HI_LS_ADC_REG_BASE + 0x14) +#define REG_ADC_MIS (HI_LS_ADC_REG_BASE + 0x18) +#define REG_ADC_START (HI_LS_ADC_REG_BASE + 0x1C) +#define REG_ADC_STOP (HI_LS_ADC_REG_BASE + 0x20) +#define REG_ADC_DR (HI_LS_ADC_REG_BASE + 0x24) +#define REG_ADC_CTRL (HI_LS_ADC_REG_BASE + 0x28) +#define REG_ADC_EN (HI_LS_ADC_REG_BASE + 0x2C) + +#define ADC_INT_FIFO_WATER_LINE (1 << 1) +#define ADC_INT_FIFO_OVER_FLOW (1 << 0) + +#define ADC_SR_RNE (1 << 0) /* FIFO not empty flag: 0:empty 1:not empty */ +#define ADC_SR_RFF (1 << 1) /* FIFO full flag 0:not full 1:full */ +#define ADC_SR_BSY (1 << 2) /* ADC busy flag 0:idle 1:busy */ + +#define ADC_SCAN_START 1 +#define ADC_SCAN_STOP 1 +#define ADC_POWER_ON 0 +#define ADC_POWER_OFF 1 +#define ADC_ISR_DISABLE 0 + +/* + * The longest time to get 1 data is ((0xfff+(18*8)+3)*334)ns + * The unit of this cnt is about 5us + */ +#define ADC_PER_DATA_TIMEOUT_CNT 500 +#define ADC_LOOP_DELAY_US 5 +hi_u32 get_average_ref_vlt(hi_u16 *voltage); +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif diff --git a/sdk_liteos/boot/commonboot/boot_rom.h b/sdk_liteos/boot/commonboot/boot_rom.h new file mode 100644 index 0000000000000000000000000000000000000000..d2d3c365fbe6446c69367bb859ce3e3aefe3bf91 --- /dev/null +++ b/sdk_liteos/boot/commonboot/boot_rom.h @@ -0,0 +1,308 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _BOOT_ROM_H_ +#define _BOOT_ROM_H_ +#include +#include + +#define BOOTLOADER_FLASH_HEAD_ADDR 0x00400000 + +/* This register is used internally and cannot be used externally. */ +#define GLB_CTL_GP_REG0_REG (GLB_CTL_BASE + 0x10) +#define GLB_CTL_GP_REG1_REG (GLB_CTL_BASE + 0x14) +#define GLB_CTL_GP_REG2_REG (GLB_CTL_BASE + 0x18) +#define GLB_CTL_GP_REG3_REG (GLB_CTL_BASE + 0x1C) +#define PMU_CMU_CTL_GP_REG0_REG (PMU_CMU_CTL_BASE + 0x010) +#define PMU_CMU_CTL_GP_REG1_REG (PMU_CMU_CTL_BASE + 0x014) +#define PMU_CMU_CTL_GP_REG2_REG (PMU_CMU_CTL_BASE + 0x018) +#define PMU_CMU_CTL_GP_REG3_REG (PMU_CMU_CTL_BASE + 0x01C) +#define CLDO_CTL_GEN_REG0 (CLDO_CTL_RB_BASE + 0x10) +#define CLDO_CTL_GEN_REG1 (CLDO_CTL_RB_BASE + 0x14) +#define CLDO_CTL_GEN_REG2 (CLDO_CTL_RB_BASE + 0x18) +#define CLDO_CTL_GEN_REG3 (CLDO_CTL_RB_BASE + 0x1C) + +/* heap module */ +hi_void rom_boot_malloc_init(hi_u32 heap_start_addr, hi_u32 heap_end_addr, hi_u32 check_sum); +hi_void *rom_boot_malloc(hi_u32 size); +hi_u32 rom_boot_free(hi_void *addr); + +/* reset module */ +#define RESET_DELAY_MS 3 +hi_void reset(hi_void); +hi_void global_reset(hi_void); + +/* secure module */ +HI_EXTERN hi_cipher_ecc_param g_brain_pool_p256r1_verify; + +/* flash driver module */ +#define FEATURE_SUPPORT_FLASH_PROTECT + +#define flash_info_print(fmt, ...) +#define SPI_QE_EN 0x02 /* QE Bit Enable */ +#define SPI_QE_EN_MX 0x40 /* QE Bit Enable(temp for FPGA MX) */ + +#define SPI_CMD_WREN 0x06 /* Write Enable */ +/* ----------------------------------------------------------------------------- */ +#define SPI_CMD_SE_4K 0x20 /* 4KB sector Erase */ +#define SPI_CMD_SE_32K 0x52 /* 32KB sector Erase */ +#define SPI_CMD_SE 0xD8 /* 64KB Sector Erase */ +#define SPI_CMD_CE1 0xC7 /* chip erase */ +#define SPI_CMD_CE2 0x60 /* chip erase */ + +/* ----------------------------------------------------------------------------- */ +#define SPI_CMD_WRSR1 0x01 /* Write Status Register */ + +#define SPI_CMD_WRSR2 0x31 /* Write Status Register-2 */ +#define SPI_CMD_RDSR2 0x35 /* Read Status Register-2 */ + +#define SPI_CMD_WRSR3 0x11 /* Write Status Register-3 */ +#define SPI_CMD_RDSR3 0x15 /* Read Status Register-3 */ + +#define SPI_CMD_RDID 0x9F /* Read Identification */ + +/* read status register. */ +#define SPI_CMD_RDSR 0x05 +#define SPI_CMD_VSR_WREN 0x50 /* write volatile SR reg enable */ + +/* write status/configuration register. */ +#define SPI_CMD_WRSRCR 0x01 + +/* ----------------------------------------------------------------------------- */ +#define SPI_CMD_SR_WIPN 0 /* Write in Progress */ +#define SPI_CMD_SR_WIP 1 /* Write in Progress */ +#define SPI_CMD_SR_WEL 2 /* Write Enable Latch */ + +#define SPI_SR_BIT_WIP (1 << 0) /* Write in Progress */ +#define SPI_SR_BIT_WEL (1 << 1) /* Write Enable Latch */ + +#define FLASH_DMA_BUF_LEN 256 +#define FLASH_DMA_RAM_SIZE 1024 +#define HI_FLASH_DEFAULT_TYPE_NUM 8 +#define HI_FLASH_CHIP_ID_NUM 3 +#define HI_FLASH_CAPACITY_ID 2 +typedef struct { + hi_u32 cmd : 8; + hi_u32 iftype : 3; + hi_u32 dummy : 3; + hi_u32 size : 18; +} spi_flash_operation; + +typedef enum { + HI_FLASH_SUPPORT_4K_ERASE = 0x1, /* Flash 4K erasing */ + HI_FLASH_SUPPORT_32K_ERASE = 0x2, /* Flash 32K erasing */ + HI_FLASH_SUPPORT_64K_ERASE = 0x4, /* Flash 64K erasing */ + HI_FLASH_SUPPORT_CHIP_ERASE = 0x8, /* Flash full-chip erasing */ + HI_FLASH_SUPPORT_AREA_LOCK_NV = 0x10, /* Non-volatile flash area protection */ + HI_FLASH_SUPPORT_AREA_LOCK_VOLATILE = 0x20, /* Flash volatile area protection */ + HI_FLASH_SUPPORT_INDIVIDUAL_LOCK = 0x40, /* Independent flash block protection */ + HI_FLASH_VLT_INFLUENCE_FREQ = 0x100, + HI_FLASH_SUPPORT_MASK = 0xFFFF, /* Mask */ +} hi_spi_flash_chip_attribute; + +typedef struct { + hi_char *chip_name; + hi_u8 chip_id[HI_FLASH_CHIP_ID_NUM]; + hi_u8 freq_read; + hi_u8 freq_lowpower; + hi_u8 freq_hpm; + hi_u16 chip_attribute; +} hi_spi_flash_basic_info; + +#define HI_FLASH_SUPPORT_CHIPS (HI_FLASH_SUPPORT_4K_ERASE | \ + HI_FLASH_SUPPORT_64K_ERASE | \ + HI_FLASH_SUPPORT_CHIP_ERASE | \ + HI_FLASH_SUPPORT_AREA_LOCK_NV | \ + HI_FLASH_SUPPORT_AREA_LOCK_VOLATILE) +#define HI_FLASH_SUPPORT_DEFAULT (HI_FLASH_SUPPORT_4K_ERASE | \ + HI_FLASH_SUPPORT_64K_ERASE | \ + HI_FLASH_SUPPORT_CHIP_ERASE) + +#define PRODUCT_CFG_FLASH_BLOCK_SIZE 0x1000 +/*****************************************************************************/ +#define HISFC300_DMA_MAX_SIZE 2048 +#define HISFC300_DMA_MAX_MASK 0x7FF + +/*****************************************************************************/ +#define HISFC300_REG_BUF_SIZE 64 +#define HISFC300_REG_BUF_MASK 0x3F + +#define HISFC300_BUS_CONFIG2 0x0204 +#define HISFC300_BUS_BASE_ADDR_CS1 0x0218 +#define HISFC300_BUS_ALIAS_ADDR 0x021C +#define HISFC300_BUS_ALIAS_CS 0x0220 +#define HISFC300_CMD_DATABUF64 0x04FC + +#define SFC_REG_BASE_ADDRESS HI_SFC_REG_BASE +#define SFC_BUFFER_BASE_ADDRESS 0x400000 + +#define SFC_REG_GLOBAL_CONFIG 0x0100 +#define SFC_REG_GLOBAL_CONFIG_ADDR_MODE_4B (1 << 2) +#define SFC_REG_TIMING 0x0110 +#define SFC_REG_GLOBAL_CONFIG_WP_ENABLE (1 << 1) +#define sfc_timing_tshsl(_n) ((_n) & 0xF) +#define sfc_timing_tshwl(_n) (((_n) & 0xF) << 4) +#define sfc_timing_tcss(_n) (((_n) & 0x7) << 8) +#define sfc_timing_tcsh(_n) (((_n) & 0x7) << 12) +#define sfc_timing_trpd(_n) (((_n) & 0xFFF) << 16) +#define SFC_REG_INT_RAW_STATUS 0x0120 /* Raw interrupt status register */ +#define SFC_REG_INT_RAW_STATUS_DMA_DONE (1 << 1) +#define SFC_REG_INT_STATUS 0x0124 +#define SFC_REG_INT_MASK 0x0128 +#define SFC_REG_INT_CLEAR 0x012C +#define SFC_REG_INT_CLEAR_DMA_DONE (1 << 1) +#define SFC_REG_VERSION 0x01F8 +#define SFC_REG_VERSION_SEL 0x01FC +#define SFC_REG_BUS_CONFIG1 0x0200 +#define SFC_REG_BUS_CONFIG1_MASK_RD 0x8000ffff +#define SFC_REG_BUS_CONFIG1_MASK_WT 0x7fff0000 +#define sfc_bus_config1_wr_ins(_n) (((_n) & 0xFF) << 22) +#define sfc_bus_config1_rd_ins(_n) (((_n) & 0xFF) << 8) +#define sfc_bus_config1_rd_prefetch_cnt(_n) (((_n) & 0x3) << 6) +#define sfc_bus_config1_rd_dummy_bytes(_n) (((_n) & 0x7) << 3) +#define sfc_bus_config1_rd_mem_if_type(_n) ((_n) & 0x7) +#define SFC_BUS_CONFIG1_RD_ENABLE ((hi_u32)1 << 31) + +#define SFC_REG_BUS_FLASH_SIZE 0x0210 +#define SFC_REG_BUS_BASE_ADDR_CS0 0x0214 +#define SFC_REG_BUS_BASE_ADDR_CS1 0x0218 + +#define SFC_REG_BUS_DMA_CTRL 0X0240 +#define SFC_BUS_DMA_CTRL_START (1 << 0) +#define sfc_bus_dma_ctrl_read(_dir) ((_dir) << 1) +#define sfc_bus_dma_ctrl_cs(_cs) (((_cs) & 0x01) << 4) +#define SFC_REG_BUS_DMA_MEM_SADDR 0X0244 /* DMA DDR start address R */ +#define SFC_REG_BUS_DMA_FLASH_SADDR 0X0248 +#define SFC_REG_BUS_DMA_LEN 0x024C +#define SFC_REG_BUS_DMA_AHB_CTRL 0X0250 +#define SFC_BUS_DMA_AHB_CTRL_INCR4_EN (1 << 0) +#define SFC_BUS_DMA_AHB_CTRL_INCR8_EN (1 << 1) +#define SFC_BUS_DMA_AHB_CTRL_INCR16_EN (1 << 2) + +#define SFC_REG_CMD_CONFIG 0x0300 +#define sfc_cmd_config_mem_if_type(_n) (((_n) & 0x07) << 17) +#define sfc_cmd_config_data_cnt(_n) ((((_n) - 1) & HISFC300_REG_BUF_MASK) << 9) +#define SFC_CMD_CONFIG_RW (1 << 8) +#define SFC_CMD_CONFIG_DATA_EN (1 << 7) +#define sfc_cmd_config_dummy_byte_cnt(_n) (((_n) & 0x07) << 4) +#define SFC_CMD_CONFIG_ADDR_EN (1 << 3) +#define SFC_CMD_CONFIG_SEL_CS (0x01 << 1) +#define SFC_CMD_CONFIG_START (1 << 0) +#define SFC_REG_CMD_INS 0x0308 + +#define SFC_REG_CMD_ADDR 0x030C +#define SFC_CMD_ADDR_MASK 0x3FFFFFFF +#define SFC_REG_CMD_DATABUF1 0x0400 + +#define SPI_SR3_DRV_MASK 0x3 + +#define SFC_ERASE_OPT_MAX_NUM 4 + +typedef enum { + SPI_SR3_DRV_100PCT = 0, + SPI_SR3_DRV_75PCT, + SPI_SR3_DRV_50PCT, + SPI_SR3_DRV_25PCT, + SPI_SR3_DRV_MAX, +} hi_flash_drv_strength; + +#define SFC_CMD_WRITE (0 << 8) +#define SFC_CMD_READ (1 << 8) + +typedef enum { + HI_FLASH_CHECK_PARAM_OPT_READ, + HI_FLASH_CHECK_PARAM_OPT_WRITE, + HI_FLASH_CHECK_PARAM_OPT_ERASE, +} hi_flash_check_param_opt; + +typedef struct spi_flash_ctrl { + hi_u32 is_inited; + hi_spi_flash_basic_info basic_info; + spi_flash_operation opt_read; + spi_flash_operation opt_write; + spi_flash_operation array_opt_erase[SFC_ERASE_OPT_MAX_NUM]; + hi_u32 chip_size; + hi_u32 erase_size; + hi_u32 dma_ram_size; + hi_u8 *dma_ram_buffer; + hi_u8 *back_up_buf; + hi_u32(*read)(struct spi_flash_ctrl *spif_ctrl, hi_u32 flash_addr, + hi_u32 read_size, hi_void *ram_addr, hi_bool is_crash); + hi_u32(*write)(struct spi_flash_ctrl *spif_ctrl, hi_u32 flash_addr, + hi_u32 write_size, hi_void *ram_addr, hi_bool is_crash); + hi_u32(*erase)(struct spi_flash_ctrl *spif_ctrl, hi_u32 flash_addr, + hi_u32 erase_size, hi_bool is_crash); + hi_u32 mutex_handle; + hi_pvoid usr_data; +} hi_spi_flash_ctrl; + +/*****************************************************************************/ +#define hisfc_read(_reg) \ + hi_reg_read_val32(SFC_REG_BASE_ADDRESS + (_reg)) + +#define hisfc_write(_reg, _value) \ + hi_reg_write(SFC_REG_BASE_ADDRESS + (_reg), (_value)) + + +HI_EXTERN HI_CONST spi_flash_operation g_spi_opt_fast_quad_out_read; +HI_EXTERN HI_CONST spi_flash_operation g_spi_opt_fast_quad_eb_out_read; + +HI_EXTERN HI_CONST hi_spi_flash_basic_info g_flash_default_info_tbl[]; + +hi_u32 spi_flash_read_chip_id(hi_u8 *chip_id, hi_u8 chip_id_len); +hi_u32 spi_flash_configure_driver_strength(hi_flash_drv_strength drv_strength); + +hi_u32 spif_map_chipsize(hi_u32 chip_size); +hi_u32 spif_dma_read(hi_spi_flash_ctrl *spif_ctrl, hi_u32 flash_addr, hi_u32 read_size, hi_void *ram_addr, + hi_bool is_crash); +hi_u32 spif_reg_erase(hi_spi_flash_ctrl *spif_ctrl, hi_u32 flash_addr, hi_u32 erase_size, hi_bool is_crash); +hi_u32 spif_dma_write(hi_spi_flash_ctrl *spif_ctrl, hi_u32 flash_addr, hi_u32 write_size, hi_void *ram_addr, + hi_bool is_crash); +hi_u32 spi_flash_read_reg(hi_u8 cmd, hi_u8 *data, hi_u8 data_len); +hi_u32 spi_flash_write_reg(hi_u8 cmd, const hi_u8 *data, hi_u8 data_len); +hi_void spif_config(const spi_flash_operation *spi_operation, hi_u8 cmd, hi_bool read); +hi_u32 spi_flash_enable_quad_mode_mx(hi_void); +hi_u32 spi_flash_enable_quad_mode(hi_void); +hi_void spif_wait_config_start(hi_void); +hi_u32 spif_write_enable(hi_bool is_crash); +hi_u32 spif_wait_ready(hi_bool is_crash, hi_u8 val, hi_u8 bit_mask); + +hi_u32 spi_flash_basic_info_probe(hi_spi_flash_ctrl *spif_ctrl, hi_u8 *chip_id, + hi_u8 id_len, hi_spi_flash_basic_info *spi_info_tbl, hi_u32 tbl_size); +hi_u32 flash_write_prv(hi_spi_flash_ctrl *spif_ctrl, hi_u32 flash_addr, const hi_u8 *ram_addr, hi_u32 size, + hi_bool do_erase); +hi_u32 flash_erase_prv(hi_spi_flash_ctrl *spif_ctrl, hi_u32 flash_addr, hi_u32 size); +hi_u32 flash_read_prv(hi_spi_flash_ctrl *spif_ctrl, hi_u32 flash_addr, hi_u8 *data, hi_u32 size); +hi_u32 spi_flash_get_size(const hi_u8 *chip_id); +hi_u32 sfc_check_para(const hi_spi_flash_ctrl *spif_ctrl, hi_u32 addr, hi_u32 size, hi_flash_check_param_opt opt); +hi_u32 flash_protect_set_protect(hi_u8 cmp_bp, hi_bool is_volatile); + +typedef hi_u32 (*flash_init_func)(hi_void); +typedef hi_u32 (*flash_read_func)(hi_u32 flash_addr, hi_u32 flash_read_size, hi_u8 *p_flash_read_data); +typedef hi_u32 (*flash_write_func)(hi_u32 flash_addr, hi_u32 flash_write_size, + const hi_u8 *p_flash_write_data, hi_bool do_erase); +typedef hi_u32 (*flash_erase_func)(hi_u32 flash_addr, hi_u32 flash_erase_size); + +typedef struct { + flash_init_func init; + flash_read_func read; + flash_write_func write; + flash_erase_func erase; +} hi_flash_cmd_func; +HI_EXTERN hi_flash_cmd_func g_flash_cmd_funcs; + +hi_u32 hi_cmd_regist_flash_cmd(const hi_flash_cmd_func *funcs); + +#endif diff --git a/sdk_liteos/boot/commonboot/efuse/SConscript b/sdk_liteos/boot/commonboot/efuse/SConscript new file mode 100755 index 0000000000000000000000000000000000000000..aceb2b6a9464ce64030c1f9c5374ec933dcab384 --- /dev/null +++ b/sdk_liteos/boot/commonboot/efuse/SConscript @@ -0,0 +1,6 @@ +Import('env') + +env = env.Clone() + +objs = env.Object(Glob('*.c')) +Return('objs') diff --git a/sdk_liteos/boot/commonboot/efuse/efuse_drv.c b/sdk_liteos/boot/commonboot/efuse/efuse_drv.c new file mode 100644 index 0000000000000000000000000000000000000000..7510cd26ea23ad21f08a52bbd81ac00030d6c200 --- /dev/null +++ b/sdk_liteos/boot/commonboot/efuse/efuse_drv.c @@ -0,0 +1,245 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "efuse_drv.h" +#define THREE_BITS_OFFSET 3 + +hi_efuse_stru g_efuse_cfg[HI_EFUSE_IDX_MAX] = { + { 0, 8, EFUSE_IDX_RW }, + { 8, 192, EFUSE_IDX_RW }, + { 200, 10, EFUSE_IDX_RW }, + { 210, 10, EFUSE_IDX_RW }, + { 220, 2, EFUSE_IDX_RW }, + { 222, 2, EFUSE_IDX_RW }, + { 224, 2, EFUSE_IDX_RW }, + { 234, 1, EFUSE_IDX_RW }, + { 240, 256, EFUSE_IDX_RW }, + { 496, 256, EFUSE_IDX_WO }, + { 752, 256, EFUSE_IDX_RW }, + { 1008, 32, EFUSE_IDX_RW }, + { 1040, 8, EFUSE_IDX_RW }, + { 1048, 24, EFUSE_IDX_RW }, + { 1072, 1, EFUSE_IDX_RW }, + { 1073, 1, EFUSE_IDX_RW }, + { 1074, 1, EFUSE_IDX_RW }, + { 1075, 1, EFUSE_IDX_RW }, + { 1076, 1, EFUSE_IDX_RW }, + { 1077, 1, EFUSE_IDX_RW }, + { 1078, 1, EFUSE_IDX_RW }, + { 1079, 1, EFUSE_IDX_RW }, + { 1080, 2, EFUSE_IDX_RW }, + { 1082, 2, EFUSE_IDX_RW }, + { 1084, 4, EFUSE_IDX_RW }, + { 1088, 8, EFUSE_IDX_RW }, + { 1096, 48, EFUSE_IDX_RW }, + { 1144, 128, EFUSE_IDX_RW }, + { 1272, 32, EFUSE_IDX_RW }, + { 1304, 32, EFUSE_IDX_RW }, + { 1336, 32, EFUSE_IDX_RW }, + { 1368, 32, EFUSE_IDX_RW }, + { 1400, 32, EFUSE_IDX_RW }, + { 1432, 32, EFUSE_IDX_RW }, + { 1464, 32, EFUSE_IDX_RW }, + { 1496, 32, EFUSE_IDX_RW }, + { 1528, 32, EFUSE_IDX_RW }, + { 1560, 32, EFUSE_IDX_RW }, + { 1592, 32, EFUSE_IDX_RW }, + { 1624, 32, EFUSE_IDX_RW }, + { 1656, 16, EFUSE_IDX_RW }, + { 1672, 48, EFUSE_IDX_RW }, + { 1720, 128, EFUSE_IDX_RW }, + { 1848, 2, EFUSE_IDX_RW }, + { 1850, 2, EFUSE_IDX_RW }, + { 1852, 2, EFUSE_IDX_RW }, + { 1854, 1, EFUSE_IDX_RW }, + { 1855, 1, EFUSE_IDX_RW }, + { 1856, 10, EFUSE_IDX_RW }, + { 1866, 18, EFUSE_IDX_RW }, + { 1884, 64, EFUSE_IDX_RW }, + { 1948, 64, EFUSE_IDX_RW }, + { 226, 8, EFUSE_IDX_RW }, +}; + + +hi_efuse_stru *get_efuse_cfg(hi_void) +{ + return &g_efuse_cfg[0]; +} + +hi_void get_efuse_cfg_by_id(hi_efuse_idx idx, hi_u16 *start_bit, hi_u16 *size, hi_u8 *attr) +{ + hi_efuse_stru *efuse_cfg = get_efuse_cfg(); + + /* Internal interface, which does not check input parameters. */ + if (start_bit != HI_NULL) { + *start_bit = efuse_cfg[idx].id_start_bit; + } + + if (size != HI_NULL) { + *size = efuse_cfg[idx].id_size; + } + + if (attr != HI_NULL) { + *attr = efuse_cfg[idx].attr; + } +} + +hi_bool check_efuse_isbusy(hi_void) +{ + hi_u32 val = 0; + hi_u32 cnt = 0; + + while (cnt < EFUSE_TIMEOUT_DEFAULT) { + hi_reg_read(EFUSE_STATUS, val); + if ((!(val & EFUSE_STATUS_READY)) && (val & EFUSE_PO_STATUS_READY)) { + return HI_FALSE; + } + udelay(EFUSE_TIMECNT_TICK); + cnt += EFUSE_TIMECNT_TICK; + } + return HI_TRUE; +} + +hi_u32 efuse_write_bit(hi_u16 addr) +{ + hi_u32 val; + hi_u32 cnt = 0; + + if (addr >= EFUSE_PGM_ADDR_SIZE) { + return HI_ERR_EFUSE_INVALIDATE_PARA; + } + + if (check_efuse_isbusy() == HI_TRUE) { + boot_msg0("efuse is busy !"); + return HI_ERR_EFUSE_BUSY; + } + + hi_reg_write(EFUSE_PGM_ADDR, addr); + hi_reg_write(EFUSE_PGM_EN, HI_TRUE); + + /* Query the current status. */ + while (cnt < EFUSE_TIMEOUT_DEFAULT) { + hi_reg_read(EFUSE_PGM_EN, val); + if ((val & EFUSE_EN_SWITCH) == EFUSE_EN_OK) { + break; + } + + udelay(EFUSE_TIMECNT_TICK); + cnt += EFUSE_TIMECNT_TICK; + } + + if (cnt >= EFUSE_TIMEOUT_DEFAULT) { + boot_msg0("timeout"); + return HI_ERR_EFUSE_TIMEOUT; + } + + return HI_ERR_SUCCESS; +} + +hi_u32 efuse_read_bits(hi_u16 start_bit, hi_u16 size, hi_u8 *key_data) +{ + hi_u32 i; + hi_u32 val; + hi_u16 free_area_addr_start = start_bit; + hi_u32 free_area_addr_end = start_bit + size; + hi_u32 cnt; + + /* The start position and length must be 8-pixel aligned. */ + if (((start_bit & 0x7) != 0x0) || ((size & 0x7) != 0x0)) { + boot_msg0("start_bits and lenth should be ALIGN_8!"); + return HI_ERR_EFUSE_INVALIDATE_PARA; + } + + if (check_efuse_isbusy() == HI_TRUE) { + boot_msg0("EFUSE is busy!"); + return HI_ERR_EFUSE_BUSY; + } + + free_area_addr_start = free_area_addr_start >> 3; /* right shift 3bit */ + free_area_addr_end = free_area_addr_end >> 3; /* right shift 3bit */ + + for (i = free_area_addr_start; i < free_area_addr_end; i++) { + hi_reg_write(EFUSE_RD_ADDR, i); + hi_reg_write(EFUSE_RD_EN, HI_TRUE); + /* Query the current status. */ + cnt = 0; + while (cnt < EFUSE_TIMEOUT_DEFAULT) { + hi_reg_read(EFUSE_RD_EN, val); + if (((val & EFUSE_EN_SWITCH) == EFUSE_EN_OK) && + ((hi_reg_read_val32(EFUSE_STATUS) & EFUSE_READ_READY_STATUS) != EFUSE_EN_OK)) { + cnt = 0; + break; + } + udelay(1); + cnt++; + } + + if (cnt >= (EFUSE_TIMEOUT_DEFAULT)) { + boot_msg0("timeout\r\n"); + return HI_ERR_EFUSE_TIMEOUT; + } + + hi_reg_read(EFUSE_RDATA, val); + key_data[i - free_area_addr_start] = (hi_u8)val; + } + + return HI_ERR_SUCCESS; +} + +hi_void efuse_get_errstate(hi_u16 byte_id, hi_u16 bit_id, hi_u8 *err_state) +{ + hi_u32 val = 0; + + hi_reg_read(EFUSE_STATUS, val); + + if (val & EFUSE_CTRL_ST) { + err_state[byte_id] |= (hi_u8)(1 << bit_id); + } else { + err_state[byte_id] &= (~(hi_u8)(1 << bit_id)); + } +} + +hi_u32 efuse_write_bits(hi_u16 start_bit, hi_u16 size, const hi_u8 *key_data, hi_u8 *err_state) +{ + hi_u16 i; + hi_u16 j; + hi_u16 a; + hi_u16 b; + hi_u32 ret; + hi_u16 zero_count = 0; + + /* j: the current bit offset of key_data. */ + for (i = start_bit, j = 0; i < (start_bit + size); i++, j++) { + a = j >> THREE_BITS_OFFSET; /* subscript of receive array. */ + b = j & 0x7; /* bit offset in one byte. */ + + if (key_data[a] & (hi_u8)(1 << b)) { + ret = efuse_write_bit(i); + if (ret != HI_ERR_SUCCESS) { + return ret; + } else if (err_state != HI_NULL) { + efuse_get_errstate(a, b, err_state); + } + } else { + zero_count++; + } + } + + if (zero_count == size) { + return HI_ERR_FAILURE; + } + return HI_ERR_SUCCESS; +} + diff --git a/sdk_liteos/boot/commonboot/flash/SConscript b/sdk_liteos/boot/commonboot/flash/SConscript new file mode 100755 index 0000000000000000000000000000000000000000..aceb2b6a9464ce64030c1f9c5374ec933dcab384 --- /dev/null +++ b/sdk_liteos/boot/commonboot/flash/SConscript @@ -0,0 +1,6 @@ +Import('env') + +env = env.Clone() + +objs = env.Object(Glob('*.c')) +Return('objs') diff --git a/sdk_liteos/boot/commonboot/flash/flash_hw_process_flashboot.c b/sdk_liteos/boot/commonboot/flash/flash_hw_process_flashboot.c new file mode 100644 index 0000000000000000000000000000000000000000..3784a7baf6a9fa57640d742947b1cbcfee80ed2b --- /dev/null +++ b/sdk_liteos/boot/commonboot/flash/flash_hw_process_flashboot.c @@ -0,0 +1,117 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +/* QE for MX */ +hi_u32 spi_flash_enable_quad_mode_mx(hi_void) +{ + hi_u32 ret; + hi_u8 data = 0; + + ret = spi_flash_read_reg(SPI_CMD_RDSR, &data, 1); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + /* QE bit is enable already, do nothing. */ + if (data & SPI_QE_EN_MX) { + return HI_ERR_SUCCESS; + } + + data |= SPI_QE_EN_MX; + ret = spi_flash_write_reg(SPI_CMD_WRSRCR, &data, 1); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + ret = spi_flash_read_reg(SPI_CMD_RDSR, &data, 1); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + /* QE bit is enable already, do nothing */ + if (data & SPI_QE_EN_MX) { + return HI_ERR_SUCCESS; + } + + return HI_ERR_FLASH_QUAD_MODE_COMPARE_REG; +} + + +/* QE for W25Q */ +hi_u32 spi_flash_enable_quad_mode(hi_void) +{ + hi_u32 ret; + hi_u8 data[2] = { 0 }; /* flash has 2 RDSR reg */ + + ret = spi_flash_read_reg(SPI_CMD_RDSR2, &data[1], 1); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + /* QE bit is enable already, do nothing */ + if (data[1] & SPI_QE_EN) { + return HI_ERR_SUCCESS; + } + + ret = spi_flash_read_reg(SPI_CMD_RDSR, &data[0], 1); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + /* SPI_CMD_WRSR1 is compatible with the old flash. */ + data[1] |= SPI_QE_EN; + ret = spi_flash_write_reg(SPI_CMD_WRSR1, data, 2); /* flash has 2 RDSR reg */ + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + ret = spi_flash_read_reg(SPI_CMD_RDSR2, &data[1], 1); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + if (data[1] & SPI_QE_EN) { + return HI_ERR_SUCCESS; + } + + return HI_ERR_FLASH_QUAD_MODE_COMPARE_REG; +} + +hi_u32 spi_flash_configure_driver_strength(hi_flash_drv_strength drv_strength) +{ + hi_u8 data = 0; + hi_u32 ret; + + if (drv_strength >= SPI_SR3_DRV_MAX) { + return HI_ERR_FLASH_INVALID_PARAMETER; + } + + ret = spi_flash_read_reg(SPI_CMD_RDSR3, &data, 1); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + if (((hi_u32)drv_strength << 5) == (data & (SPI_SR3_DRV_MASK << 5))) { /* left shift 5bit */ + return HI_ERR_SUCCESS; + } + + data &= ~(SPI_SR3_DRV_MASK << 5); /* left shift 5bit */ + data |= (hi_u32)drv_strength << 5; /* left shift 5bit */ + ret = spi_flash_write_reg(SPI_CMD_WRSR3, &data, 1); + + return ret; +} diff --git a/sdk_liteos/boot/commonboot/hi3861_platform.h b/sdk_liteos/boot/commonboot/hi3861_platform.h new file mode 100644 index 0000000000000000000000000000000000000000..a1eca9fac4ba60761f2e8c9e2daa91cfc78e93c0 --- /dev/null +++ b/sdk_liteos/boot/commonboot/hi3861_platform.h @@ -0,0 +1,160 @@ +/* + * @file hi_3861_platform.h + * + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __HI3861_PLATFORM_H__ +#define __HI3861_PLATFORM_H__ + +/* The CPU configuration memory size is 120KB, which cannot be modified. */ +#define SRAM_LENGTH 0x0001E000 /* CPU SRAM 0x100000-0x11DFFF 120KB */ + +/* Configure the memory start address. This value cannot be modified. */ +#define SRAM_START_ADDR 0x00100000 + +#define CONFIG_CPU_CLOCK 160000000 +#define CONFIG_UART_CLOCK 80000000 + +#define HI_CHIP_ID_1131SV200 0xFF /* Refresh after Asic */ + +#define CALI_PMU_32K_CLK_VAL 10 +#define TCXO_CLK_40MHZ 40000000 +#define TCXO_CLK_24MHZ 24000000 +#define CONFIG_WDT_CLOCK 80000000 + +/* GLOBAL CONTROL REG */ +#define GLB_CTL_BASE 0x50000000 +#define GLB_CTL_SYS_CTL_ID_REG (GLB_CTL_BASE + 0x0) +#define GLB_CTL_AON_SOFT_RST_W_REG (GLB_CTL_BASE + 0x20) +#define GLB_CTL_SOFT_RST_WCPU_REG (GLB_CTL_BASE + 0x24) +#define GLB_CTL_SOFT_GLB_RESET_CFG (GLB_CTL_BASE + 0x28) +#define GLB_CTL_GLB_WDT_RST_SEL_REG (GLB_CTL_BASE + 0x30) +#define GLB_CTL_WDT_RST_SEL_REG (GLB_CTL_BASE + 0x34) +#define GLB_CTL_AON_CKEN_REG (GLB_CTL_BASE + 0x40) +#define GLB_CTL_GLB_AON_32K_CLKEN_REG (GLB_CTL_BASE + 0x50) +#define GLB_CTL_A32K_DIV_REG (GLB_CTL_BASE + 0x70) +#define GLB_CTL_TCXO_DIV_REG (GLB_CTL_BASE + 0x74) +#define GLB_CTL_AON_PERP_CLKSEL_W_REG (GLB_CTL_BASE + 0x90) +#define GLB_CTL_RC_32K_TCXO_SEL_REG (GLB_CTL_BASE + 0x94) +#define GLB_CTL_AON_32K_SEL_REG (GLB_CTL_BASE + 0x98) +#define GLB_CTL_SYS_TICK_CFG_REG (GLB_CTL_BASE + 0xC0) +#define GLB_CTL_SYS_TICK_VALUE_0_REG (GLB_CTL_BASE + 0xD0) +#define GLB_CTL_SYS_TICK_VALUE_1_REG (GLB_CTL_BASE + 0xD4) +#define GLB_CTL_SYS_TICK_VALUE_2_REG (GLB_CTL_BASE + 0xD8) +#define GLB_CTL_SYS_TICK_VALUE_3_REG (GLB_CTL_BASE + 0xDC) +#define GLB_CTL_CLKMUX_STS_REG (GLB_CTL_BASE + 0x110) +#define GLB_CTL_DEBUG_CLKEN_REG (GLB_CTL_BASE + 0x170) +#define GLB_CTL_SOFT_INT_EN_REG (GLB_CTL_BASE + 0x280) +#define GLB_CTL_SOFT_INT_SET_REG (GLB_CTL_BASE + 0x284) +#define GLB_CTL_SOFT_INT_CLR_REG (GLB_CTL_BASE + 0x288) +#define GLB_CTL_SOFT_INT_STS_REG (GLB_CTL_BASE + 0x28C) +#define GLB_CTL_INT_SEL_REG (GLB_CTL_BASE + 0x290) +#define GLB_CTL_REFCLK_FEQ_STATUS_REG (GLB_CTL_BASE + 0x358) +#define GLB_CTL_EXT_TSF_CTRL_REG (GLB_CTL_BASE + 0x400) +#define GLB_CTL_CALI_32K_TCXO_CTL_REG (GLB_CTL_BASE + 0x800) +#define GLB_CTL_CALI_32K_TCXO_CNT_L_REG (GLB_CTL_BASE + 0x810) +#define GLB_CTL_CALI_32K_TCXO_CNT_H_REG (GLB_CTL_BASE + 0x814) +#define GLB_CTL_CALI_32K_TCXO_RESULT_L_REG (GLB_CTL_BASE + 0x818) +#define GLB_CTL_CALI_32K_TCXO_RESULT_H_REG (GLB_CTL_BASE + 0x81C) +#define GLB_CTL_AON_ICM_PRIORITY_REG (GLB_CTL_BASE + 0xF30) +#define GLB_CTL_MEM_CLK_FORCE_ON_REG (GLB_CTL_BASE + 0xF50) +#define GLB_CTL_MARGIN_ADJ_REG (GLB_CTL_BASE + 0xF54) +#define GLB_CTL_MARGIN_ADJ_AB (GLB_CTL_BASE + 0xF58) +#define GLB_CTL_DEFAULT_SLV_EN_REG (GLB_CTL_BASE + 0xF84) +#define GLB_CTL_DEFAULT_SLV_HIT_STATUS_REG (GLB_CTL_BASE + 0xF88) +#define GLB_CTL_DEFAULT_SLV_HIT_CLR_REG (GLB_CTL_BASE + 0xF8C) + +/* CLDO CONTROL REG */ +#define CLDO_CTL_RB_BASE 0x40010000 +#define CLDO_CTL_SOFT_RESET_REG (CLDO_CTL_RB_BASE + 0x20) +#define CLDO_CTL_WDG_RST_SEL_REG (CLDO_CTL_RB_BASE + 0x28) +#define CLDO_CTL_RB_CLKEN_REG (CLDO_CTL_RB_BASE + 0x30) +#define CLDO_CTL_CLK_SEL_REG (CLDO_CTL_RB_BASE + 0x38) +#define CLDO_CTL_SOFT_RESET2_REG (CLDO_CTL_RB_BASE + 0x3C) +#define CLDO_CTL_WDG_RST_SEL1_REG (CLDO_CTL_RB_BASE + 0x4C) +#define CLDO_CTL_CLKMUX_STS_REG (CLDO_CTL_RB_BASE + 0x64) +#define CLDO_CTL_CLK_DIV1_REG (CLDO_CTL_RB_BASE + 0x78) +#define CLDO_CTL_PKT_CPU_MEM_SEL (CLDO_CTL_RB_BASE + 0x100) +#define CLDO_CTL_UART_JTAG_CFG_REG (CLDO_CTL_RB_BASE + 0x250) + +#define EFUSE_RST_BIT 9 +#define JTAG_SWE_ENABLE (1<<3) /* [3] jtag ctrl */ +#define UART0_SWE_ENABLE (1<<0) /* [0] uart0 ctrl */ +#define UART1_SWE_ENABLE (1<<1) /* [1] uart1 ctrl */ +#define UART2_SWE_ENABLE (1<<2) /* [2] uart2 ctrl */ + +/* PMU CMU CONTROL REG */ +#define PMU_CMU_CTL_BASE 0x50002000 +#define PMU_CMU_CTL_UDSLEEP_BUTTON_CTRL_REG (PMU_CMU_CTL_BASE + 0x020) +#define PMU_CMU_CTL_UDSLEEP_BUTTON_RPT_REG (PMU_CMU_CTL_BASE + 0x024) +#define PMU_CMU_CTL_OSC_TRIM_REG (PMU_CMU_CTL_BASE + 0x028) +#define PMU_CMU_CTL_PMU_MAN_CLR_0_REG (PMU_CMU_CTL_BASE + 0x104) +#define PMU_CMU_CTL_FLASHLDO_CFG_1_REG (PMU_CMU_CTL_BASE + 0x260) +#define PMU_CMU_CTL_GATE_TSENSOR_VDDIO_REG (PMU_CMU_CTL_BASE + 0x350) +#define PMU_CMU_CTL_CMU_DBG_SEL_REG (PMU_CMU_CTL_BASE + 0x414) +#define PMU_CMU_CTL_CLK_480M_GT_REG (PMU_CMU_CTL_BASE + 0x420) +#define PMU_CMU_CTL_CLK_192M_GT_REG (PMU_CMU_CTL_BASE + 0x42C) +#define PMU_CMU_CTL_CLK_960M_GT_REG (PMU_CMU_CTL_BASE + 0x430) +#define PMU_CMU_CTL_REFDIV_REG (PMU_CMU_CTL_BASE + 0x500) +#define PMU_CMU_CTL_FBDIV_REG (PMU_CMU_CTL_BASE + 0x504) +#define PMU_CMU_CTL_FRAC_L_REG (PMU_CMU_CTL_BASE + 0x508) +#define PMU_CMU_CTL_FRAC_H_REG (PMU_CMU_CTL_BASE + 0x50C) +#define PMU_CMU_CTL_CMU_MISC_PD_REG (PMU_CMU_CTL_BASE + 0x514) +#define PMU_CMU_CTL_CMU_CLK_SEL_REG (PMU_CMU_CTL_BASE + 0x518) +#define PMU_CMU_CTL_CMU_STATUS_RAW_REG (PMU_CMU_CTL_BASE + 0x600) +#define PMU_CMU_CTL_SYS_STATUS_REG (PMU_CMU_CTL_BASE + 0x804) +#define PMU_CMU_CTL_WLAN_STA0_ALLOW_TO_SLEEP_REG (PMU_CMU_CTL_BASE + 0x900) +#define PMU_CMU_CTL_WLAN_STA1_ALLOW_TO_SLEEP_REG (PMU_CMU_CTL_BASE + 0x904) +#define PMU_CMU_CTL_WLAN_AP0_ALLOW_TO_SLEEP_REG (PMU_CMU_CTL_BASE + 0x908) +#define PMU_CMU_CTL_WLAN_PF_ALLOW_TO_SLEEP_REG (PMU_CMU_CTL_BASE + 0x90C) +#define PMU_CMU_CTL_WLAN_HOST_ALLOW_TO_SLEEP_REG (PMU_CMU_CTL_BASE + 0x910) +#define PMU_CMU_CTL_WLAN_SLP_EVT_EN_REG (PMU_CMU_CTL_BASE + 0x920) +#define PMU_CMU_CTL_WLAN_SLP_EVT_CLR_REG (PMU_CMU_CTL_BASE + 0x924) +#define PMU_CMU_CTL_WLAN_SLP_INT_CLR_REG (PMU_CMU_CTL_BASE + 0x934) +#define PMU_CMU_CTL_WLAN_WKUP_EVT_EN_REG (PMU_CMU_CTL_BASE + 0x940) +#define PMU_CMU_CTL_WLAN_WKUP_EVT_CLR_REG (PMU_CMU_CTL_BASE + 0x944) +#define PMU_CMU_CTL_WLAN_WKUP_INT_EN_REG (PMU_CMU_CTL_BASE + 0x950) +#define PMU_CMU_CTL_WLAN_WKUP_INT_CLR_REG (PMU_CMU_CTL_BASE + 0x954) + +/* WLAN CONTROL REG */ +#define W_CTL_BASE_ADDR 0x40028000 +#define W_CTL_MAC_WDT_RST_SEL_REG (W_CTL_BASE_ADDR + 0x0034) +#define W_CTL_PHY_WDT_RST_SEL_REG (W_CTL_BASE_ADDR + 0x0038) +#define W_CTL_WDT_RST_SEL_REG (W_CTL_BASE_ADDR + 0x003C) +#define W_CTL_CPU_MAC_CLK_DIV_REG (W_CTL_BASE_ADDR + 0x0070) +#define W_CTL_UART01_CKDIV_OFFSET (W_CTL_BASE_ADDR + 0x0074) +#define W_CTL_UART2_CKDIV_OFFSET (W_CTL_BASE_ADDR + 0x0090) +#define W_CTL_W_TCXO_SEL_REG (W_CTL_BASE_ADDR + 0x0118) +#define W_CTL_CLKMUX_STS_DIV_STS_REG (W_CTL_BASE_ADDR + 0x0130) + +/* DIAG CTL REG */ +#define DIAG_CTL_BASE 0x40060000 +#define DIAG_CTL_GP_REG0_REG (DIAG_CTL_BASE + 0x010) /* used to save rsa key */ +#define DIAG_CTL_GP_REG1_REG (DIAG_CTL_BASE + 0x014) /* used to save rsa key */ +#define DIAG_CTL_GP_REG2_REG (DIAG_CTL_BASE + 0x018) /* used to save ecc key */ +#define DIAG_CTL_GP_REG3_REG (DIAG_CTL_BASE + 0x01C) /* used to save ecc key */ + +/* DEVICE REG */ +#define HI_WDG_REG_BASE 0x40000000 +#define HI_GPIO_REG_BASE 0x50006000 +#define HI_IOCFG_REG_BASE 0x5000A000 +#define HI_EFUSE_REG_BASE 0x40078000 +#define HI_SFC_REG_BASE 0x40800000 + +#define HI_UART0_REG_BASE 0x40008000 +#define HI_UART1_REG_BASE 0x40009000 +#define HI_UART2_REG_BASE 0x4000a000 + +#endif diff --git a/sdk_liteos/boot/commonboot/hi_boot_err.h b/sdk_liteos/boot/commonboot/hi_boot_err.h new file mode 100644 index 0000000000000000000000000000000000000000..77aae7f055cd59deae28e5e47636205ad95819b5 --- /dev/null +++ b/sdk_liteos/boot/commonboot/hi_boot_err.h @@ -0,0 +1,182 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __HI_BOOT_ERR_H__ +#define __HI_BOOT_ERR_H__ + +/* Generic errno */ +#define HI_ERR_SUCCESS 0x3CA5965A +#define HI_ERR_FAILURE 0xC35A69A5 +#define HI_ERR_MALLOC_FAILUE 0x80000000 +#define HI_ERR_TIMEOUT 0x80000001 + +/* gpio errno */ +#define HI_ERR_GPIO_INVALID_PARAMETER 0x80001040 +#define HI_ERR_GPIO_REPEAT_INIT 0x80001041 +#define HI_ERR_GPIO_NOT_INIT 0x80001042 +#define HI_ERR_GPIO_NOT_SUPPORT 0x80001043 + +/* Flash errno */ +#define HI_ERR_FLASH_NOT_INIT 0x800010C0 +#define HI_ERR_FLASH_INVALID_PARAMETER 0x800010C1 +#define HI_ERR_FLASH_INVALID_PARAM_BEYOND_ADDR 0x800010C2 +#define HI_ERR_FLASH_INVALID_PARAM_SIZE_ZERO 0x800010C3 +#define HI_ERR_FLASH_INVALID_PARAM_ERASE_NOT_ALIGN 0x800010C4 +#define HI_ERR_FLASH_INVALID_PARAM_IOCTRL_DATA_NULL 0x800010C5 +#define HI_ERR_FLASH_INVALID_PARAM_DATA_NULL 0x800010C6 +#define HI_ERR_FLASH_INVALID_PARAM_PAD1 0x800010C7 +#define HI_ERR_FLASH_INVALID_PARAM_PAD2 0x800010C8 +#define HI_ERR_FLASH_INVALID_PARAM_PAD3 0x800010C9 +#define HI_ERR_FLASH_INVALID_PARAM_PAD4 0x800010CA +#define HI_ERR_FLASH_TIME_OUT_WAIT_READY 0x800010CB +#define HI_ERR_FLASH_QUAD_MODE_READ_REG1 0x800010CC +#define HI_ERR_FLASH_QUAD_MODE_READ_REG2 0x800010CD +#define HI_ERR_FLASH_QUAD_MODE_COMPARE_REG 0x800010CE +#define HI_ERR_FLASH_NO_MATCH_FLASH 0x800010CF +#define HI_ERR_FLASH_WRITE_ENABLE 0x800010D0 +#define HI_ERR_FLASH_NO_MATCH_ERASE_SIZE 0x800010D1 +#define HI_ERR_FLASH_MAX_SPI_OP 0x800010D2 +#define HI_ERR_FLASH_NOT_SUPPORT_IOCTRL_ID 0x800010D3 +#define HI_ERR_FLASH_INVALID_CHIP_ID 0x800010D4 +#define HI_ERR_FLASH_RE_INIT 0x800010D5 +#define HI_ERR_FLASH_WRITE_NOT_SUPPORT_ERASE 0x800010D6 +#define HI_ERR_FLASH_WRITE_COMPARE_WRONG 0x800010D7 +#define HI_ERR_FLASH_WAIT_CFG_START_TIME_OUT 0x800010D8 +#define HI_ERR_FLASH_PATITION_INIT_FAIL 0x800010D9 +#define HI_ERR_FLASH_INITILIZATION 0x800010DA +#define HI_ERR_FLASH_ERASE_NOT_4K_ALIGN 0x800010DB + +/* efuse errno */ +#define HI_ERR_EFUSE_INVALIDATE_ID 0x80001200 +#define HI_ERR_EFUSE_INVALIDATE_PARA 0x80001201 +#define HI_ERR_EFUSE_WRITE_ERR 0x80001202 +#define HI_ERR_EFUSE_INVALIDATE_AUTH 0x80001203 +#define HI_ERR_EFUSE_BUSY 0x80001204 +#define HI_ERR_EFUSE_TIMEOUT 0x80001205 + +/* cipher errno */ +#define HI_ERR_CIPHER_NOT_INIT 0x80001240 +#define HI_ERR_CIPHER_INVALID_POINT 0x80001241 +#define HI_ERR_CIPHER_INVALID_PARAMETER 0x80001242 +#define HI_ERR_CIPHER_NO_AVAILABLE_RNG 0x80001243 +#define HI_ERR_CIPHER_FAILED_MEM 0x80001244 +#define HI_ERR_CIPHER_OVERFLOW 0x80001245 +#define HI_ERR_CIPHER_TIMEOUT 0x80001246 +#define HI_ERR_CIPHER_UNSUPPORTED 0x80001247 +#define HI_ERR_CIPHER_REGISTER_IRQ 0x80001248 +#define HI_ERR_CIPHER_ILLEGAL_KEY 0x80001249 +#define HI_ERR_CIPHER_INVALID_ADDR 0x8000124A +#define HI_ERR_CIPHER_INVALID_LENGTH 0x8000124B +#define HI_ERR_CIPHER_ILLEGAL_DATA 0x8000124C +#define HI_ERR_CIPHER_RSA_SIGN 0x8000124D +#define HI_ERR_CIPHER_RSA_VERIFY 0x8000124E +#define HI_ERR_CIPHER_RESULT_WARNING 0x8000124F +#define HI_ERR_CIPHER_FLUSH_DCACHE_FAILED 0x80001250 + +#define HI_ERR_YMODEM_ERR_TIMEOUT 0xC35A69A6 +#define HI_ERR_YMODEM_ERR_CANCEL 0xC35A69A7 +#define HI_ERR_YMODEM_ERR_FRAME 0xC35A69A8 +#define HI_ERR_YMODEM_ERR_CS 0xC35A69A9 +#define HI_ERR_YMODEM_ERR_EOT 0xC35A69AA +#define HI_ERR_YMODEM_ERR_SEQ 0xC35A69AB +#define HI_ERR_YMODEM_ERR_LENTH 0xC35A69AC + +/* upgrade common error */ +#define HI_ERR_UPG_NULL_POINTER 0x80001300 +#define HI_ERR_UPG_PARAMETER 0x80001301 +#define HI_ERR_UPG_BACKUP_ADDR 0x80001302 +#define HI_ERR_UPG_BUSY 0x80001303 +#define HI_ERR_UPG_FLASH_BAD 0x80001304 +#define HI_ERR_UPG_START_ADDR 0x80001305 +#define HI_ERR_UPG_INITILIZATION_ALREADY 0x80001306 +#define HI_ERR_UPG_FILE_LEN 0x80001307 +#define HI_ERR_UPG_NOT_START 0x80001308 +#define HI_ERR_UPG_MALLOC_FAIL 0x80001309 +#define HI_ERR_UPG_BOOT_MAGIC 0x8000130A +#define HI_ERR_UPG_BOOT_LEN 0x8000130B +#define HI_ERR_UPG_FILE_LEN_OVER 0x8000130C +#define HI_ERR_UPG_FILE_LEN_ZERO 0x8000130D + +/* upgrade file check error */ +#define HI_ERR_UPG_IMAGE_ID 0x80001340 +#define HI_ERR_UPG_FILE_TYPE 0x80001341 +#define HI_ERR_UPG_HEAD_LEN 0x80001342 +#define HI_ERR_UPG_SIGN_ALG 0x80001343 +#define HI_ERR_UPG_RSA_KEY_LEN 0x80001344 +#define HI_ERR_UPG_RSA_HEAD_SIGN 0x80001345 +#define HI_ERR_UPG_ECC_KEY_LEN 0x80001346 +#define HI_ERR_UPG_ECC_HEAD_SIGN 0x80001347 +#define HI_ERR_UPG_COMMON_SHA256 0x80001348 +#define HI_ERR_UPG_SECTION_SHA256 0x80001349 +#define HI_ERR_UPG_KERNEL_VER 0x8000134A +#define HI_ERR_UPG_BOOT_VER 0x8000134B +#define HI_ERR_UPG_DECOMPRESS_FILE_CRC 0x8000134C +#define HI_ERR_UPG_CRC 0x8000134D + +/* lzma-decode */ +#define HI_ERR_LZMA_DECODE 0x80001360 + +/* lzma-common */ +#define HI_ERR_LZMA_PARAM 0x80001380 +#define HI_ERR_LZMA_LEN 0x80001381 + +/* NV */ +#define HI_ERR_NV_FILE_ERR 0x80003000 +#define HI_ERR_NV_MEMCPY_FAIL 0x80003001 +#define HI_ERR_NV_WRITE_FILE_FAIL 0x80003002 +#define HI_ERR_NV_UPDATA_DATA_FAIL 0x80003003 +#define HI_ERR_NV_UPDATA_FILE_FAIL 0x80003004 +#define HI_ERR_NV_NOT_SUPPORT_WRITE 0x80003005 +#define HI_ERR_NV_FSEC_TOTAL_NUM_INVALID 0x80003006 +#define HI_ERR_NV_FAIL_N_TIMES 0x80003007 +#define HI_ERR_NV_SEM_FAIL 0x80003008 +#define HI_ERR_NV_LEN_ERR 0x80003009 +#define HI_ERR_NV_NOT_FOUND 0x8000300A +#define HI_ERR_NV_FULL 0x8000300B +#define HI_ERR_NV_NOT_ENOUGH_MEMORY 0x8000300C +#define HI_ERR_NV_NOT_SUPPORT 0x8000300D +#define HI_ERR_NV_NOT_SUPPORT_ID 0x8000300E +#define HI_ERR_NV_BAD_DATA 0x8000300F +#define HI_ERR_NV_INVALID_TYPE 0x80003010 +/* Read NVIM Failure */ +#define HI_ERR_NV_ERROR_READ 0x80003011 +/* Write Error for Length Overflow */ +#define HI_ERR_NV_NOT_SUPPORT_LENTH 0x80003012 +/* Write Error for Flash Bad Block */ +#define HI_ERR_NV_BAD_BLOCK 0x80003013 +/* Write Error for Unknown Reason */ +#define HI_ERR_NV_ERROR_WRITE 0x80003014 +#define HI_ERR_NV_INITILIZATION 0x80003015 +#define HI_ERR_NV_INVALID_PARAMETER 0x80003016 + +/* CRC */ +#define HI_ERR_CRC_INVALID_PARAMETER 0x800031C0 + +/* upgrade common error */ +#define HI_ERR_UPG_COMMON 0x80003060 +#define HI_ERR_UPG_LOW_KERNEL_VER (HI_ERR_UPG_COMMON + 0x13) +#define HI_ERR_UPG_FULL_KERNEL_VER (HI_ERR_UPG_COMMON + 0x14) +#define HI_ERR_UPG_LOW_BOOT_VER (HI_ERR_UPG_COMMON + 0x15) +#define HI_ERR_UPG_FULL_BOOT_VER (HI_ERR_UPG_COMMON + 0x16) +#define HI_ERR_UPG_FIRST_PACKET_OFFSET (HI_ERR_UPG_COMMON + 0x17) +#define HI_ERR_UPG_UPDATE_VER_TIMEOUT (HI_ERR_UPG_COMMON + 0x18) +#define HI_ERR_UPG_UPDATE_VER_FAIL (HI_ERR_UPG_COMMON + 0x19) +#define HI_ERR_UPG_UPDATE_VER_INVALID_PARAM (HI_ERR_UPG_COMMON + 0x1A) +#define HI_ERR_UPG_KERNEL_VER_OVER (HI_ERR_UPG_COMMON + 0x1B) +#define HI_ERR_UPG_BOOT_VER_OVER (HI_ERR_UPG_COMMON + 0x1C) + +#define EOK HI_ERR_SUCCESS + +#endif diff --git a/sdk_liteos/boot/commonboot/hi_cipher.h b/sdk_liteos/boot/commonboot/hi_cipher.h new file mode 100644 index 0000000000000000000000000000000000000000..7e102517e6c450ee528dc32ccbed773902c40309 --- /dev/null +++ b/sdk_liteos/boot/commonboot/hi_cipher.h @@ -0,0 +1,514 @@ +/* + * @file hi_cipher.h + * + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** @defgroup iot_cipher Cipher APIs + * @ingroup iot_romboot + */ +#ifndef __HI_CIPHER_H__ +#define __HI_CIPHER_H__ + +#include +#include + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ + +#define PKE_LEN_32_BYTES 32 +#define PKE_LEN_256_BYTES 256 +#define PKE_LEN_384_BYTES 384 +#define PKE_LEN_512_BYTES 512 +#define RSA_KEY_LEN_2048 256 +#define AES_MAX_KEY_IN_WORD 16 +#define AES_IV_LEN_IN_WORD 4 +#define KDF_KEY_LEN_IN_BYTES 32 + +/** +* @ingroup iot_cipher +* Rsa sign and veriry scheme +*/ +typedef enum { + HI_CIPHER_RSA_SIGN_SCHEME_RSASSA_PKCS1_V15_SHA256 = 0x00, /* PKCS#1 RSASSA_PKCS1_V15_SHA256 signature */ + HI_CIPHER_RSA_SIGN_SCHEME_RSASSA_PKCS1_PSS_SHA256, /* PKCS#1 RSASSA_PKCS1_PSS_SHA256 signature */ + HI_CIPHER_RSA_SIGN_SCHEME_MAX, + HI_CIPHER_RSA_SIGN_SCHEME_INVALID = 0xffffffff, +}hi_cipher_rsa_sign_scheme; + +/** +* @ingroup iot_cipher +* Aes key from +*/ +typedef enum { + HI_CIPHER_AES_KEY_FROM_CPU = 0x00, + HI_CIPHER_AES_KEY_FROM_KDF, + HI_CIPHER_AES_KEY_FROM_MAX, + HI_CIPHER_AES_KEY_FROM_INVALID = 0xffffffff, +}hi_cipher_aes_key_from; + +/** +* @ingroup iot_cipher +* Aes work mode +*/ +typedef enum { + HI_CIPHER_AES_WORK_MODE_ECB = 0x00, /* Electronic codebook (ECB) mode, ECB has been considered insecure and + it is recommended not to use it. */ + HI_CIPHER_AES_WORK_MODE_CBC, /* Cipher block chaining (CBC) mode. */ + HI_CIPHER_AES_WORK_MODE_CTR, /* Counter (CTR) mode. */ + HI_CIPHER_AES_WORK_MODE_XTS, /* XTS-AES (XTS) mode. */ + HI_CIPHER_AES_WORK_MODE_MAX, + HI_CIPHER_AES_WORK_MODE_INVALID = 0xffffffff, +}hi_cipher_aes_work_mode; + +/** +* @ingroup iot_cipher +* Aes key length +*/ +typedef enum { + HI_CIPHER_AES_KEY_LENGTH_128BIT = 0x00, + HI_CIPHER_AES_KEY_LENGTH_192BIT, + HI_CIPHER_AES_KEY_LENGTH_256BIT, + HI_CIPHER_AES_KEY_LENGTH_512BIT, /* 512bit, just used for xts. */ + HI_CIPHER_AES_KEY_LENGTH_MAX, + HI_CIPHER_AES_KEY_LENGTH_INVALID = 0xffffffff, +}hi_cipher_aes_key_length; + +/** +* @ingroup iot_cipher +* Rsa public key verify +*/ +typedef struct { + hi_cipher_rsa_sign_scheme scheme; /* The rsa sign type */ + hi_u8 *e; /* The public exponent */ + hi_u8 *n; /* The modulus */ + hi_u32 klen; /* The key length */ +} hi_cipher_rsa_verify; + +/** +* @ingroup iot_cipher +* Struct of ecc curves parameters +*/ +typedef struct { + const hi_u8 *p; /* Finite field: equal to p in case of prime field curves or equal to 2^n in case of binary + field curves. */ + const hi_u8 *a; /* Curve parameter a (q-3 in Suite B). */ + const hi_u8 *b; /* Curve parameter b. */ + const hi_u8 *gx; /* X coordinates of G which is a base point on the curve. */ + const hi_u8 *gy; /* Y coordinates of G which is a base point on the curve. */ + const hi_u8 *n; /* Prime which is the order of G point. */ + hi_u32 h; /* Cofactor, which is the order of the elliptic curve divided by the order of the point G. For + the Suite B curves, h = 1. */ + hi_u32 ksize; /* Ecc key size in bytes. It corresponds to the size in bytes of the prime, should be 32bytes. */ +}hi_cipher_ecc_param; + +/** +* @ingroup iot_cipher +* Struct of ecc verify +*/ +typedef struct { + const hi_u8 *px; /* Ecdh X coordinates of the generated public key, the caller ensures it is padded with leading + zeros if the effective size of this key is smaller than ecc key size. */ + const hi_u8 *py; /* Ecdh Y coordinates of the generated public key, the caller ensures it is padded with leading + zeros if the effective size of this key is smaller than ecc key size. */ + const hi_u8 *hash; /* Input hash data for ecc verify. */ + hi_u32 hash_len; /* The length of hash data, just 32 bytes is valid data. */ + const hi_u8 *r; /* Output ecc sign result R, its length is ecc key size. */ + const hi_u8 *s; /* Output ecc sign result S, its length is ecc key size. */ + hi_u8 *out_r; /* Output verify r data for security. */ +}hi_cipher_ecc_verify; + +/** +* @ingroup iot_cipher +* Struct of rsa verify +*/ +typedef struct { + hi_u8 *hash; /* The input hash value will be changed after hi_cipher_rsa_verify_hash execution, + the correct value should be input before each verification */ + hi_u8 *out_hash; + hi_u32 hash_len; + const hi_u8 *sign; + hi_u32 sign_len; +} hi_cipher_rsa_data; + +/** +* @ingroup iot_cipher +* Aes ctrl struct +*/ +typedef struct { + hi_u32 key[AES_MAX_KEY_IN_WORD]; /* Key input. */ + hi_u32 iv[AES_IV_LEN_IN_WORD]; /* Initialization vector (IV). */ + hi_bool random_en; /* Enable random delay or not. */ + hi_cipher_aes_key_from key_from; /* Key from, When using kdf key, no nead to configure the input key. */ + hi_cipher_aes_work_mode work_mode; /* Work mode. */ + hi_cipher_aes_key_length key_len; /* Key length. aes-ecb/cbc/ctr support 128/192/256 bits key, ccm just support + 128 bits key, xts just support 256/512 bits key. */ +}hi_cipher_aes_ctrl; + +/** +* @ingroup iot_cipher +* Kdf key type +*/ +typedef enum { + HI_CIPHER_SSS_KDF_KEY_DEVICE = 0x0, /* kdf device key derivation. */ + HI_CIPHER_SSS_KDF_KEY_STORAGE, /* kdf storage key derivation. */ + HI_CIPHER_SSS_KDF_KEY_MAX, + HI_CIPHER_SSS_KDF_KEY_INVALID = 0xFFFFFFFF, +}hi_cipher_kdf_mode; + +/** +* @ingroup iot_cipher +* Kdf ctrl struct +*/ +typedef struct { + const hi_u8 *salt; /* salt for kdf key derivation. */ + hi_u32 salt_len; /* salt_len should be 16 bytes for kdf device key derivation, + 32 bytes for kdf storage key derivation. */ + hi_u8 key[KDF_KEY_LEN_IN_BYTES]; /* just used for kdf device key. */ + hi_cipher_kdf_mode kdf_mode; /* kdf mode for key derivation. */ + hi_u32 kdf_cnt; /**< kdf cnt for iteration.It is recommended that the number of iterations be + not less than 10000 times, if performance requirement, no less than 1000 + times, and not more than 0xffff times. */ + hi_u8 result[KDF_KEY_LEN_IN_BYTES]; /* output for kdf device key derivation. */ +}hi_cipher_kdf_ctrl; + +/** +* @ingroup iot_cipher +* @brief Initializes the Cipher module. CNcomment:Cipher 模块初始化。CNend +* +* @par 描述: +* Initializes the Cipher module. +CNcomment:Cipher模块初始化。CNend +* +* @attention This function must be called before using cipher module. +CNcomment:使用Cipher模块算法前调用本接口初始化。CNend +* @param None +* +* @retval #HI_ERR_SUCCESS Success +* @retval #Other Failure. For details, see hi_boot_err.h. +* @par 依赖: +* @li hi_cipher.h:Describes Cipher module APIs. +CNcomment:文件用于描述Cipher模块相关接口。CNend +* @see hi_cipher_init。 +*/ +hi_u32 hi_cipher_init(hi_void); + +/** +* @ingroup iot_cipher +* @brief Deinitializes the Cipher module. CNcomment:Cipher 模块去初始化。CNend +* +* @par 描述: +* Deinitializes the Cipher module, does NOT support multi-tasks. +CNcomment:Cipher模块去初始化,不支持多任务。CNend +* +* @attention This function could be called after using Cipher module finished. +CNcomment:结束使用Cipher模块算法后调用本接口去初始化。CNend +* @param None +* +* @retval #HI_ERR_SUCCESS Success +* @retval #Other Failure. For details, see hi_boot_err.h. +* @par 依赖: +* @li hi_cipher.h:Describes Cipher module APIs. +CNcomment:文件用于描述Cipher模块相关接口。CNend +* @see hi_cipher_deinit。 +*/ +hi_u32 hi_cipher_deinit(hi_void); + +/** +* @ingroup iot_cipher +* @brief Settings of AES. CNcomment:AES算法参数配置。CNend +* +* @par 描述: +* Configure of AES. CNcomment:AES算法参数配置。CNend +* +* @attention None +* @param ctrl [IN] type #hi_cipher_aes_ctrl *,AES parameters. CNcomment:AES算法参数配置。CNend +* +* @retval #HI_ERR_SUCCESS Success +* @retval #Other Failure. For details, see hi_boot_err.h. +* @par 依赖: +* @li hi_cipher.h:Describes Cipher module APIs. +CNcomment:文件用于描述Cipher模块相关接口。CNend +* @see hi_cipher_aes_config。 +*/ +hi_u32 hi_cipher_aes_config(hi_cipher_aes_ctrl *ctrl); + +/** +* @ingroup iot_cipher +* @brief Encryption/Decryption of AES, if execution fails, hi_cipher_aes_destroy_config must be called to +release resources. +CNcomment:AES算法加解密,如果执行失败,必须调用hi_cipher_aes_destroy_config接口释放资源。CNend +* +* @par 描述: +* Encryption/Decryption of AES. CNcomment:AES算法加解密。CNend +* +* @attention 无。 +* @param src_addr [IN] type #uintptr_t,Input data source address. +CNcomment:待加密或解密的源数据物理地址,地址要求4对齐。CNend +* @param dest_addr [OUT] type #uintptr_t,output data physical address, the address must be +aligned in 4 bytes. +CNcomment:加密或解密结果数据物理地址,地址要求4对齐。CNend +* @param length [IN] type #hi_u32,data length, ECB/CBC/CTR/XTS must be aligned in 16 bytes. +CNcomment:数据长度, ECB/CBC/CTR/XTS要求16bytes对齐。CNend +* @param encrypt [IN] type #hi_bool,options of encryption/decryption, HI_TRUE is for encryption, +HI_FALSE is for decryption.CNcomment:加解密配置选项,配置HI_TRUE为加密,配置HI_FALSE为解密。CNend +* +* @retval #HI_ERR_SUCCESS Success +* @retval #Other Failure. For details, see hi_boot_err.h. +* @par 依赖: +* @li hi_cipher.h:Describes Cipher module APIs. +CNcomment:文件用于描述Cipher模块相关接口。CNend +* @see hi_cipher_aes_crypto。 +*/ +hi_u32 hi_cipher_aes_crypto(uintptr_t src_addr, uintptr_t dest_addr, hi_u32 length, hi_bool encrypt); + +/** +* @ingroup iot_cipher +* @brief Destory AES configures. CNcomment:AES算法销毁配置的参数CNend +* +* @par 描述: +* Destory AES configures. CNcomment:AES算法销毁配置的参数CNend +* +* @attention In pair with hi_cipher_aes_config.CNcomment:与参数配置成对使用CNend +* @param None + +* @retval #HI_ERR_SUCCESS Success +* @retval #Other Failure. For details, see hi_boot_err.h. +* @par 依赖: +* @li hi_cipher.h:Describes Cipher module APIs. +CNcomment:文件用于描述Cipher模块相关接口。CNend +* @see hi_cipher_aes_destroy_config。 +*/ +hi_u32 hi_cipher_aes_destroy_config(hi_void); + +/** +* @ingroup iot_cipher +* @brief Settings of HASH.CNcomment:HASH算法参数配置CNend +* +* @par 描述: +* Settings of HASH, this function should be called before calculating. +CNcomment:HASH算法参数配置,HASH计算前调用 +* +* @attention None +* @param atts [IN] type #const hi_cipher_hash_atts *,HASH attribute.CNcomment:HASH算法类型配置。CNend + +* @retval #HI_ERR_SUCCESS Success +* @retval #Other Failure. For details, see hi_boot_err.h. +* @par 依赖: +* @li hi_cipher.h:Describes Cipher module APIs. +CNcomment:文件用于描述Cipher模块相关接口。CNend +* @see hi_cipher_hash_start。 +*/ +hi_u32 hi_cipher_hash_start(hi_void); + +/** +* @ingroup iot_cipher +* @brief Calculating by HASH.CNcomment:HASH计算CNend +* +* @par 描述: +* Hash calculation. Multiple segments can be calculated,Maximum 10KB per segment. +CNcomment:HASH计算,支持多段计算,每段最长10KB。CNend +* +* @attention None +* @param src_addr [IN] type #uintptr_t,Data address to be calculated by HASH. +CNcomment:待HASH计算的数据地址。CNend +* @param length [IN] type #hi_u32,Data length to be calculated by HASH,maximum is 10KB. +CNcomment:待HASH计算的数据长度,最长10KB。CNend +* +* @retval #HI_ERR_SUCCESS Success +* @retval #Other Failure. For details, see hi_boot_err.h. +* @par 依赖: +* @li hi_cipher.h:Describes Cipher module APIs. +CNcomment:文件用于描述Cipher模块相关接口。CNend +* @see hi_cipher_hash_update。 +*/ +hi_u32 hi_cipher_hash_update(uintptr_t src_addr, hi_u32 length); + +/** +* @ingroup iot_cipher +* @brief HASH calculation finished.CNcomment:HASH计算结束CNend +* +* @par 描述: +* Ouput results after HASH finished calculating.CNcomment:HASH计算结束, +输出计算结果。CNend +* +* @attention None +* +* @param out [OUT] type #hi_u8 *,Pointer to the output of the HASH calculation result. +CNcomment:HASH计算结果输出指针。CNend +* @param out_len [IN] type #hi_u32,HASH The output pointer of the calculation result points to +* the space length. The output length must be greater than or equal to 32 bytes. +CNcomment:HASH计算结果输出指针指向空间长度,要求输出长度满足不小于32bytes。CNend +* +* @retval #HI_ERR_SUCCESS Success +* @retval #Other Failure. For details, see hi_boot_err.h. +* @par 依赖: +* @li hi_cipher.h:Describes Cipher module APIs. +CNcomment:文件用于描述Cipher模块相关接口。CNend +* @see hi_cipher_hash_final。 +*/ +hi_u32 hi_cipher_hash_final(hi_u8 *out, hi_u32 out_len); + +/** +* @ingroup iot_cipher +* @brief HASH calculation.CNcomment:HASH计算CNend +* +* @par 描述: +* Performs hash calculation on a segment of data and outputs the hash result. +CNcomment:对一段数据做HASH计算,并输出HASH结果。CNend +* +* @attention None +* +* @param input [IN] type #uintptr_t,Enter the data address. The address must be 4-bytes-aligned. +CNcomment:输入数据地址,地址要求4对齐。CNend +* @param input_len [IN] type #hi_u32, Input data length.CNcomment:输入数据长度。CNend +* @param hash [OUT] type #hi_u8 *,Output the hash result. The length is 32 bytes. +CNcomment:输出HASH结果, 长度为 32 bytes。CNend +* @param hash_len [IN] type #hi_u32, BUF length of the hash result. The value must be greater than or +* equal to 32 bytes.CNcomment:输出HASH结果的BUF长度,需要满足不小于32bytes。CNend +* +* @retval #HI_ERR_SUCCESS Success +* @retval #Other Failure. For details, see hi_boot_err.h. +* @par 依赖: +* @li hi_cipher.h:Describes Cipher module APIs. +CNcomment:文件用于描述Cipher模块相关接口。CNend +* @see hi_cipher_hash_sha256。 +*/ +hi_u32 hi_cipher_hash_sha256(uintptr_t input, hi_u32 input_len, hi_u8 *hash, hi_u32 hash_len); + +/** +* @ingroup iot_cipher +* @brief KDF calculation.CNcomment:KDF算法计算。CNend +* +* @par 描述: +* KDF calculation.CNcomment:KDF算法计算。CNend +* +* @attention None +* @param ctrl [IN] type #hi_cipher_kdf_ctrl*,Poninter to KDF algorithm parameter configuration + control structure.CNcomment:KDF算法参数配置控制结构体。CNend +* +* @retval #HI_ERR_SUCCESS Success +* @retval #Other Failure. For details, see hi_boot_err.h. +* @par 依赖: +* @li hi_cipher.h:Describes Cipher module APIs. +CNcomment:文件用于描述Cipher模块相关接口。CNend +* @see hi_cipher_kdf_key_derive。 +*/ +hi_u32 hi_cipher_kdf_key_derive(hi_cipher_kdf_ctrl *ctrl); + +/** +* @ingroup iot_cipher +* @brief Rsa Signature Verification.CNcomment:Rsa 签名结果校验CNend +* +* @par 描述: +* Rsa Signature Verification.CNcomment:Rsa 签名结果校验。CNend +* +* @attention None +* @param rsa_verify [IN] type #hi_cipher_rsa_verify *,Structure of the Rsa signature result +* verification algorithm.CNcomment:Rsa签名结果校验算法结构体。CNend +* @param hash [IN] type #const hi_u8 *,Hash data to be checked. +CNcomment:待校验的HASH数据。CNend +* @param hash_len [IN] type #hi_u32, Indicates the length of the hash data to be verified. +* The value is 32 bytes valid data. +CNcomment:待校验的HASH数据的长度,为32bytes有效数据。CNend +* @param sign [IN] type #const hi_u8 *,Signature input pointer.CNcomment:签名输入指针。CNend +* @param sign_len [IN] type #hi_u32,Length of the signature result. The length is the same as the +* length of the key.CNcomment:签名结果长度, 长度与key的长度相同。CNend +* +* @retval #HI_ERR_SUCCESS Success +* @retval #Other Failure. For details, see hi_boot_err.h. +* @par 依赖: +* @li hi_cipher.h:Describes Cipher module APIs. +CNcomment:文件用于描述Cipher模块相关接口。CNend +* @see hi_cipher_rsa_verify_hash。 +*/ +hi_u32 hi_cipher_rsa_verify_hash(const hi_cipher_rsa_verify *rsa_verify, hi_cipher_rsa_data *pack); + +/** +* @ingroup iot_cipher +* @brief Ecdsa Signature Verification.CNcomment:Ecdsa 签名结果校验CNend +* +* @par 描述: +* Ecdsa Signature Verification.CNcomment:Ecdsa 签名结果校验。CNend +* +* @attention None +* @param ecc [IN] type #const hi_cipher_ecc_param *,ECC elliptic curve parameter. If the length +* is less than the size of the key, add 0 before the key. +CNcomment:ECC椭圆曲线参数,长度不足Key的大小,前面补0。CNend +* @param verify [IN] type #const hi_cipher_ecc_verify *,Pointer to structure of the ECC public key +* verification parameter.CNcomment:ECC公钥验证参数结构体。CNend +* +* @retval #HI_ERR_SUCCESS Success +* @retval #Other Failure. For details, see hi_boot_err.h. +* @par 依赖: +* @li hi_cipher.h:Describes Cipher module APIs. +CNcomment:文件用于描述Cipher模块相关接口。CNend +* @see hi_cipher_ecc_sign_hash。 +*/ +hi_u32 hi_cipher_ecc_verify_hash(hi_cipher_ecc_param *ecc, hi_cipher_ecc_verify *verify); + +/** +* @ingroup iot_cipher +* @brief TRNG Obtain a random number.CNcomment:TRNG获取随机数CNend +* +* @par 描述: +* TRNG Obtain a random number. Only one word size can be obtained at a time. +CNcomment:TRNG获取随机数,每次只能获取一个WORD大小的随机数。CNend +* +* @attention None +* @param randnum [OUT] type #hi_u32 *,Random number output pointer. +CNcomment:随机数输出指针。CNend +* +* @retval #HI_ERR_SUCCESS Success +* @retval #Other Failure. For details, see hi_boot_err.h. +* @par 依赖: +* @li hi_cipher.h:Describes Cipher module APIs. +CNcomment:文件用于描述Cipher模块相关接口。CNend +* @see hi_cipher_trng_get_random。 +*/ +hi_u32 hi_cipher_trng_get_random(hi_u32 *randnum); + +/** +* @ingroup iot_cipher +* @brief TRNG Obtain a random number.CNcomment:TRNG获取随机数CNend +* +* @par 描述: +* The TRNG obtains the random number and obtains the random number of multiple bytes at a time. +CNcomment:TRNG获取随机数,每次获取多个byte的随机数。CNend +* +* @attention None +* @param randbyte [OUT] type #hi_u8 *,Random number output pointer. +CNcomment:随机数输出指针。CNend +* @param size [IN] type #hi_u32,Length of the obtained random number. +CNcomment:获取的随机数长度。CNend +* +* @retval #HI_ERR_SUCCESS Success +* @retval #Other Failure. For details, see hi_boot_err.h. +* @par 依赖: +* @li hi_cipher.h:Describes Cipher module APIs. +CNcomment:文件用于描述Cipher模块相关接口。CNend +* @see hi_cipher_trng_get_random。 +*/ +hi_u32 hi_cipher_trng_get_random_bytes(hi_u8 *randbyte, hi_u32 size); + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif /* __HI_CIPHER_H__ */ diff --git a/sdk_liteos/boot/commonboot/hi_types.h b/sdk_liteos/boot/commonboot/hi_types.h new file mode 100644 index 0000000000000000000000000000000000000000..bf7aee0c521e21c0b142d5d2bf6c59d5caf15784 --- /dev/null +++ b/sdk_liteos/boot/commonboot/hi_types.h @@ -0,0 +1,146 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _HI_BOOT_TYPES_H_ +#define _HI_BOOT_TYPES_H_ + +/* Basic data type definition */ +typedef unsigned char hi_uchar; +typedef unsigned char hi_u8; +typedef unsigned short hi_u16; +typedef unsigned int hi_u32; +typedef unsigned long long hi_u64; +typedef unsigned long hi_ulong; +typedef char hi_char; +typedef signed char hi_s8; +typedef short hi_s16; +typedef int hi_s32; +typedef long long hi_s64; +typedef long hi_slong; +typedef float hi_float; +typedef double hi_double; +typedef unsigned long hi_size_t; +typedef unsigned long hi_length_t; +typedef hi_u32 hi_handle; +typedef hi_u8 hi_bool; +typedef unsigned int uintptr_t; +typedef void hi_void; +typedef void* hi_pvoid; + +typedef hi_u8 hi_byte; +typedef hi_byte* hi_pbyte; +typedef hi_u32 size_t; +typedef unsigned long long uint64_t; + +typedef hi_void (*hi_void_callback_f)(hi_void); + +#define HI_PRV static +#define HI_PRVL static inline +#define HI_INLINE inline +#define HI_EXTERN extern +#define HI_CONST const +#define HI_ALWAYS_INLINE __attribute__((always_inline)) inline + +#define HI_OUT +#define HI_IN +#define HI_INOUT + +#define HI_FALSE 0 +#define HI_TRUE 1 + + +#ifdef __cplusplus +#define HI_NULL 0 +#else +#define HI_NULL ((void*)0) +#endif + +#ifndef NULL +#define NULL (void*)0 +#endif + +#define SZ_1KB 1024 +#define SZ_1MB (SZ_1KB * SZ_1KB) +#define SZ_4KB 4096 + +#define hi_array_count(x) (sizeof(x) / sizeof((x)[0])) + +#define hi_align_4(x) ((unsigned int)((x) + 0x3) & (~0x3)) +#define hi_is_align_u32(x) (!((x) & 3)) +#define hi_is_unalign_u32(x) ((x) & 3) +#if defined(HAVE_PCLINT_CHECK) +#define hi_fieldoffset(s, m) (0) +#else +#define hi_fieldoffset(s, m) ((hi_u32) & (((s*)0)->m)) +#endif +#define HI_CHAR_CR '\r' /* 0x0D */ +#define HI_CHAR_LF '\n' /* 0x0A */ + +#define hi_makeu16(a, b) ((hi_u16)(((hi_u8)(a)) | ((hi_u16)((hi_u8)(b))) << 8)) +#define hi_makeu32(a, b) ((hi_u32)(((hi_u16)(a)) | ((hi_u32)((hi_u16)(b))) << 16)) +#define hi_hiu16(l) ((hi_u16)(((hi_u32)(l) >> 16) & 0xFFFF)) +#define hi_lou16(l) ((hi_u16)(l)) +#define hi_hiu8(l) ((hi_u8)(((hi_u16)(l) >> 8) & 0xFF)) +#define hi_lou8(l) ((hi_u8)(l)) + +#define hi_max(a, b) (((a) > (b)) ? (a) : (b)) +#define hi_min(a, b) (((a) < (b)) ? (a) : (b)) + +#define hi_set_bit_i(val, n) ((val) |= (1 << (n))) +#define hi_clr_bit_i(val, n) ((val) &= ~(1 << (n))) +#define hi_is_bit_set_i(val, n) ((val) & (1 << (n))) +#define hi_is_bit_clr_i(val, n) (~((val) & (1 << (n)))) +#define hi_switch_bit_i(val, n) ((val) ^= (1 << (n))) +#define hi_get_bit_i(val, n) (((val) >> (n)) & 1) +#define hi_u8_bit_val(b7, b6, b5, b4, b3, b2, b1, b0) \ + (((b7) << 7) | ((b6) << 6) | ((b5) << 5) | ((b4) << 4) | ((b3) << 3) | ((b2) << 2) | ((b1) << 1) | ((b0) << 0)) + +#define hi_u16_bit_val(b12, b11, b10, b9, b8, b7, b6, b5, b4, b3, b2, b1, b0) \ + (hi_u16)(((b12) << 12) | ((b11) << 11) | ((b10) << 10) | ((b9) << 9) | ((b8) << 8) | ((b7) << 7) | \ + ((b6) << 6) | ((b5) << 5) | ((b4) << 4) | ((b3) << 3) | ((b2) << 2) | ((b1) << 1) | ((b0) << 0)) + +#define ALIGNTYPE_1BYTE 1 +#define ALIGNTYPE_2BYTE 2 +#define ALIGNTYPE_4BYTE 4 +#define ALIGNTYPE_8BYTE 8 +#define ALIGNTYPE_64BYTE 64 +#define ALIGNTYPE_32BYTE 32 +#define ALIGNTYPE_4K 4096 +#define align_next(val, a) ((((val) + ((a)-1)) & (~((a)-1)))) +#define align_length(val, a) align_next(val, a) +#define HI_ALL_F_32 0xFFFFFFFF +#define HI_ALL_F_16 0xFFFF + +#define BYTE_WIDTH 1 +#define HALF_WIDTH 2 +#define WORD_WIDTH 4 + +#define BITS_PER_BYTE 8 +#define HEXADECIMAL 16 +#define DECIMAL 10 + +#define HALFWORD_BIT_WIDTH 16 + +#if !defined(hi_unref_param) && !defined(HI_HAVE_CROSS_COMPILER_DIAB) +#define hi_unref_param(P) P = P +#else +#define hi_unref_param(P) +#endif + +#ifndef __ROM_ADDITION +#define __ROM_ADDITION __attribute__((section(".rom_addition.text"))) +#endif + +#endif diff --git a/sdk_liteos/boot/commonboot/transfer.h b/sdk_liteos/boot/commonboot/transfer.h new file mode 100644 index 0000000000000000000000000000000000000000..18a60f68c26328460ad3520d3be0391a904fb2ad --- /dev/null +++ b/sdk_liteos/boot/commonboot/transfer.h @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __TRANSFER_H__ +#define __TRANSFER_H__ + +#include +#include +#include +#include + +#define MODEM_SOH 0x01 /* Start character of data block */ +#define MODEM_STX 0x02 /* The start byte of 1024 bytes */ +#define MODEM_EOT 0x04 /* File transfer finish */ +#define MODEM_ACK 0x06 /* ACK message */ +#define MODEM_NAK 0x15 /* Error occurred */ +#define MODEM_CAN 0x18 /* Cancel transmission */ +#define MODEM_EOF 0x1A /* Data blank filler */ +#define MODEM_C 0x43 /* Capital letter C */ + +#define FLASH_ADDR_OFFSET 0x400000 + +#define UPLOAD_WAIT_START_C_TIME 10000000 /* 10s */ +#define UPLOAD_WAIT_DEFAULT_TIME 2000000 /* 2s */ + +#define UPLOAD_DATA_SIZE 1024 +#define UPLOAD_BUFF_LEN 1029 + +#define RETRY_COUNT 0 +#define CAN_COUNT 3 +#define MSG_START_LEN 3 +#define SOH_MSG_LEN 128 +#define SOH_MSG_TOTAL_LEN 133 +#define WAIT_ZERO_ACK_DELAY 100 +#define UPLOAD_FILE_NAME "upload.bin" +#define UPLOAD_FILE_NAME_LEN 11 + +enum { + UPLOAD_NONE, + UPLOAD_WAIT_START_C, + UPLOAD_WAIT_INIT_ACK, + UPLOAD_WAIT_TRANS_C, + UPLOAD_WAIT_INTER_ACK, + UPLOAD_WAIT_FINAL_ACK, + UPLOAD_WAIT_EOT_C, + UPLOAD_WAIT_ZERO_ACK, +}; + +typedef struct { + uintptr_t file_addr; + hi_u32 file_length; + hi_char *file_name; + hi_u32 offset; + hi_u8 status; + hi_u8 seq; + hi_u8 retry : 4; + hi_u8 can_cnt : 4; + hi_u8 buffer[UPLOAD_BUFF_LEN]; +} upload_context; + +hi_u32 download_image(hi_u32 addr, hi_u32 erase_size, hi_u32 flash_size, hi_u8 burn_efuse); +hi_u32 download_factory_image(hi_u32 addr, hi_u32 erase_size, hi_u32 flash_size, hi_u8 burn_efuse); +hi_u32 loady_file(uintptr_t ram_addr); +hi_u32 loady_version_file(uintptr_t ram_addr); +hi_u32 upload_data(hi_u32 addr, hi_u32 length); + +#endif diff --git a/sdk_liteos/boot/flashboot/Makefile b/sdk_liteos/boot/flashboot/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..bdd993a0d45e40b345bf845ea9d7341c24e64ac4 --- /dev/null +++ b/sdk_liteos/boot/flashboot/Makefile @@ -0,0 +1,103 @@ +include $(MAIN_TOPDIR)/build/make_scripts/config.mk +-include $(MAIN_TOPDIR)/$(MODULE_DIR)/srcs.mk +include $(MAIN_TOPDIR)/$(MODULE_DIR)/module_config.mk + +override CCFLAGS = $(BOOT_CCFLAGS) $(BOOT_DEFINE) $(BOOT_INC) +override ASFLAGS = $(BOOT_ASFLAGS) $(BOOT_DEFINE) $(BOOT_INC) + +LIBDIR = $(MAIN_TOPDIR)/$(LIB_PATH)/$(MODULE_DIR) +OBJDIR = $(MAIN_TOPDIR)/$(OBJ_PATH)/flashboot +ID_CFG_FILE = $(MAIN_TOPDIR)/$(MODULE_DIR)/file_id.cfg + +LIB_NAME = lib$(LIB).a +SRCS = $($(LIB)_srcs) +LIBOUT = $(LIBDIR)/$(MODULE_DIR)/$(LIB_NAME) + +ifdef SRC_FILES +OBJ_SRCS = $(filter %.c, $(SRC_FILES)) +ASM_SRCS = $(filter %.S, $(SRC_FILES)) +else +OBJ_SRCS = $(foreach dir, $(SRCS), $(wildcard $(dir)/*.c)) +ASM_SRCS = $(foreach dir, $(SRCS), $(wildcard $(dir)/*.S )) +OBJ_COMMON_SRCS = $(foreach dir, $($(LIB)_common_srcs), $(wildcard $(dir)/*.c)) +ASM_COMMON_SRCS = $(foreach dir, $($(LIB)_common_srcs), $(wildcard $(dir)/*.S )) +endif +OBJ_SRCS += $(MAIN_TOPDIR)/third_party/u-boot-v2019.07/u-boot-v2019.07/lib/crc32.c \ + $(MAIN_TOPDIR)/third_party/u-boot-v2019.07/u-boot-v2019.07/lib/lzma/LzmaDec.c \ + $(MAIN_TOPDIR)/third_party/u-boot-v2019.07/u-boot-v2019.07/lib/lzma/LzmaTools.c +OBJS = $(patsubst %.c, $(OBJDIR)/%.o, $(OBJ_SRCS)) +ASM_OBJS = $(patsubst %.S, $(OBJDIR)/%.o, $(ASM_SRCS)) +COMMON_OBJS = $(patsubst ../%.c, $(OBJDIR)/%.o, $(OBJ_COMMON_SRCS)) +COMMON_ASM_OBJS = $(patsubst ../%.S, $(OBJDIR)/%.o, $(ASM_COMMON_SRCS)) + +SIGN_TOOL = $(MAIN_TOPDIR)/tools/sign_tool/sign_tool +ENCRYPT_KEY_PATH = $(MAIN_TOPDIR)/tools/sign_tool/aes_key.txt +ifeq ($(CONFIG_TARGET_SIG_SHA256), y) + LINK_FILE = $(MAIN_TOPDIR)/build/link/flashboot_sha256.lds + INPUT_LOADER = $(MAIN_TOPDIR)/build/basebin/Hi3861_loader_sha256.bin +else ifeq ($(CONFIG_TARGET_SIG_ECC), y) + LINK_FILE = $(MAIN_TOPDIR)/build/link/flashboot_ecc.lds + INPUT_LOADER = $(MAIN_TOPDIR)/build/basebin/Hi3861_loader_ecc.bin + ROOT_KEY_PATH = $(MAIN_TOPDIR)/tools/sign_tool/root_ecc.pem + SUB_KEY_PATH = $(MAIN_TOPDIR)/tools/sign_tool/sub_ecc.pem + SIGN_TYPE = 2 +else + LINK_FILE = $(MAIN_TOPDIR)/build/link/flashboot_rsa.lds + INPUT_LOADER = $(MAIN_TOPDIR)/build/basebin/Hi3861_loader_rsa.bin + ROOT_KEY_PATH = $(MAIN_TOPDIR)/tools/sign_tool/root_rsa.pem + SUB_KEY_PATH = $(MAIN_TOPDIR)/tools/sign_tool/sub_rsa.pem + ifeq ($(CONFIG_TARGET_SIG_RSA_V15), y) + SIGN_TYPE = 0 + else ifeq ($(CONFIG_TARGET_SIG_RSA_PSS), y) + SIGN_TYPE = 1 + endif +endif + +LIBS := $(patsubst lib%.a, -l%, $(notdir $(wildcard $(MAIN_TOPDIR)/build/libs/boot_libs/*.a))) +LIBPATH := -L$(MAIN_TOPDIR)/build/libs +LIBPATH += -L$(MAIN_TOPDIR)/build/libs/boot_libs +BOOT_ELF = $(MAIN_TOPDIR)/$(CACHE_PATH)/flash_boot.elf +BOOT_BIN = $(MAIN_TOPDIR)/$(CACHE_PATH)/hi_flash_boot.bin +BOOT_BIN_B = $(MAIN_TOPDIR)/$(BIN_PATH)/$(TARGET_CHIP)_boot_signed_B.bin +BOOT_SIGNED_BIN = $(MAIN_TOPDIR)/$(BIN_PATH)/$(TARGET_CHIP)_boot_signed.bin + +all: $(OBJS) $(ASM_OBJS) $(COMMON_OBJS) $(COMMON_ASM_OBJS) + $(LINK) $(BOOT_LINK_FLAGS) -T $(LINK_FILE) $(LIBPATH) $(sort $^) -o $(BOOT_ELF) --start-group $(LIBS) --end-group + $(OBJCOPY) -Obinary -R .rom.text -R .rom.code.text -R .u_boot_cmd -R .rom.data -R .rom.code.data -R .rom.bss -R .rom.code.bss -S $(BOOT_ELF) $(BOOT_BIN) +ifeq ($(CONFIG_TARGET_SIG_SHA256), y) + $(SIGN_TOOL) -i $(BOOT_BIN) -o $(BOOT_SIGNED_BIN) -n -t$(BOOT_BIN_B) +else ifeq ($(CONFIG_BOOT_ENCRYPT), y) + $(SIGN_TOOL) -i $(BOOT_BIN) -o $(BOOT_SIGNED_BIN) -r$(ROOT_KEY_PATH) -s$(SUB_KEY_PATH) -v $(CONFIG_TARGET_BOOT_VER) -a $(SIGN_TYPE) -e$(ENCRYPT_KEY_PATH) -t$(BOOT_BIN_B) +else + $(SIGN_TOOL) -i $(BOOT_BIN) -o $(BOOT_SIGNED_BIN) -r$(ROOT_KEY_PATH) -s$(SUB_KEY_PATH) -v $(CONFIG_TARGET_BOOT_VER) -a $(SIGN_TYPE) -t$(BOOT_BIN_B) +endif + $(Q)echo [BOOT] SUCCESS + $(RM) $(BOOT_ELF) $(BOOT_BIN) + + +include $(MAIN_TOPDIR)/build/make_scripts/lib.mk +$(COMMON_OBJS): $(OBJDIR)/%.o : ../%.c + $(Q)if [ ! -d $(dir $@) ]; then \ + mkdir -p $(dir $@); \ + fi; + $(Q) echo Compile $<; + $(Q)if [ -e $< ]; \ + then $(CC) $(CCFLAGS) -c $< -o $@; \ + if [ "$$?" != "0" ]; then \ + exit 1;\ + fi; \ + fi; + +$(COMMON_ASM_OBJS): $(OBJDIR)/%.o : ../%.S + $(Q)echo Compile $<; + $(Q)if [ ! -d $(dir $@) ]; \ + then \ + mkdir -p $(dir $@);\ + fi; + $(Q)if [ -f $< ]; \ + then \ + $(CC) $(ASFLAGS) -c $< -o $@ ; \ + if [ "$$?" != "0" ]; then \ + exit 1;\ + fi;\ + fi; diff --git a/sdk_liteos/boot/flashboot/SConscript b/sdk_liteos/boot/flashboot/SConscript new file mode 100644 index 0000000000000000000000000000000000000000..3ff9f8de5070d777bc1357e87201044bdb719ff8 --- /dev/null +++ b/sdk_liteos/boot/flashboot/SConscript @@ -0,0 +1,126 @@ +#!/usr/bin/env python3 +# coding=utf-8 + +import os +from scripts.scons_utils import scons_usr_bool_option +from scripts.scons_utils import scons_get_cfg_val +from scripts.scons_utils import scons_usr_int_option +from scripts.scons_utils import cleanup +from scripts import scons_env_cfg + +Import('env') +Import('env_cfg') +Import('module') + +if scons_usr_bool_option('CONFIG_TARGET_CHIP_HI3861') == 'y': + CONFIG_TARGET_BIN_NAME="Hi3861" +else: + CONFIG_TARGET_BIN_NAME="Hi3861L" + +obj_path = env_cfg.obj_path +bin_path = env_cfg.bin_path +lib_path = env_cfg.lib_path +cache_path = env_cfg.cache_path + +sign_tool = os.path.join("tools", "sign_tool", "sign_tool") +link_path = os.path.join(env_cfg.root, "build", "link", "flashboot_sha256.lds") +encrypt_key_path = os.path.join('tools', 'sign_tool', 'aes_key.txt') +if scons_usr_bool_option('CONFIG_TARGET_SIG_SHA256') == 'y': + link_path = os.path.join(env_cfg.root, "build", "link", "flashboot_sha256.lds") +if scons_usr_bool_option('CONFIG_TARGET_SIG_RSA_V15') == 'y': + link_path = os.path.join(env_cfg.root, "build", "link", "flashboot_rsa.lds") + root_key_path = os.path.join('tools', 'sign_tool', 'root_rsa.pem') + sub_key_path = os.path.join('tools', 'sign_tool', 'sub_rsa.pem') + sign_type = 0 +if scons_usr_bool_option('CONFIG_TARGET_SIG_RSA_PSS') == 'y': + link_path = os.path.join(env_cfg.root, "build", "link", "flashboot_rsa.lds") + root_key_path = os.path.join('tools', 'sign_tool', 'root_rsa.pem') + sub_key_path = os.path.join('tools', 'sign_tool', 'sub_rsa.pem') + sign_type = 1 +if scons_usr_bool_option('CONFIG_TARGET_SIG_ECC') == 'y': + link_path = os.path.join(env_cfg.root, "build", "link", "flashboot_ecc.lds") + root_key_path = os.path.join('tools', 'sign_tool', 'root_ecc.pem') + sub_key_path = os.path.join('tools', 'sign_tool', 'sub_ecc.pem') + sign_type = 2 + +#boot_ver +boot_ver = scons_usr_int_option('CONFIG_TARGET_BOOT_VER') +if (boot_ver < 0 or boot_ver > 16): + raise scons_utils.SconsBuildError("%s============== boot_ver invalied, should be 0-16 =============%s"%(scons_utils.colors['red'], scons_utils.colors['end'])) + +module_path = env_cfg.get_module_dir(module) +module_libs = env_cfg.get_module_libs(module) + +env['LIBS'] = list(map(lambda x:'-l%s'%x, env_cfg.get_boot_libs())) +env['LIBPATH'] = env_cfg.get_bootlib_path() +env.Append(LIBPATH=os.path.join('-Lbuild', 'libs', 'boot_libs')) +env = env.Clone() +ld_flags = ["-nostdlib", "-nostartfiles", "-static", "--gc-sections"] +boot_cflags = ["-mabi=ilp32", "-march=rv32imc", "-freorder-blocks-algorithm=simple", "-fno-schedule-insns", + "-nostdinc", "-fno-aggressive-loop-optimizations", "-fno-builtin", "-fstack-protector-strong", + "-fno-exceptions", "-fno-short-enums", "-mtune=size", "-msmall-data-limit=0", "-Wall", "-Werror", "-Os", + "-std=c99", "-falign-functions=2", "-fdata-sections", "-ffunction-sections", "-fno-common"] +boot_asflags = ["-mabi=ilp32", "-march=rv32imc", "-x", "assembler-with-cpp", "-Os", "-Wall", "-Werror", + "-nostdinc", "-fno-common"] +defines = ["-DARCH_RISCV", "-DLOS_COMPILE_LDM", "-DHI_BOARD_ASIC"] +incs = [os.path.join('#', 'boot', 'flashboot', 'fixed', 'include'), os.path.join('#', 'boot', 'flashboot', 'upg'), + os.path.join('#', 'boot', 'flashboot', 'include'), os.path.join('#', 'boot', 'flashboot', 'drivers', 'lsadc'), os.path.join('#', 'boot', 'flashboot', 'drivers', 'efuse'), + os.path.join('#', 'boot', 'flashboot', 'include', 'lzma'), os.path.join('#', 'boot', 'flashboot', 'drivers', 'gpio'), os.path.join('#', 'boot', 'flashboot', 'drivers', 'io'), + os.path.join('#', 'third_party', 'u-boot-v2019.07', 'u-boot-v2019.07', 'lib', 'lzma'), os.path.join('#', 'boot', 'flashboot', 'secure'), os.path.join('#', 'boot', 'commonboot')] + +if scons_usr_bool_option('CONFIG_COMPRESSION_OTA_SUPPORT') == 'y': + defines.append("-DCONFIG_COMPRESSION_OTA_SUPPORT") +if scons_usr_bool_option('CONFIG_DUAL_PARTITION_OTA_SUPPORT') == 'y': + defines.append("-DCONFIG_DUAL_PARTITION_OTA_SUPPORT") +if scons_usr_bool_option('CONFIG_TARGET_SIG_ECC') == 'y': + defines.append("-DCONFIG_TARGET_SIG_ECC") +if scons_usr_bool_option('CONFIG_TARGET_SIG_RSA_V15') == 'y': + defines.append("-DCONFIG_TARGET_SIG_RSA_V15") +if scons_usr_bool_option('CONFIG_TARGET_SIG_RSA_PSS') == 'y': + defines.append("-DCONFIG_TARGET_SIG_RSA_PSS") +if scons_usr_bool_option('CONFIG_FLASH_ENCRYPT_SUPPORT') == 'y': + defines.append("-DCONFIG_FLASH_ENCRYPT_SUPPORT") +if scons_usr_bool_option('CONFIG_FACTORY_TEST_SUPPORT') == 'y': + defines.append("-DCONFIG_FACTORY_TEST_SUPPORT") +if scons_usr_bool_option('CONFIG_QUICK_SEND_MODE') == 'y': + defines.append("-DCONFIG_QUICK_SEND_MODE") + +if scons_get_cfg_val('CONFIG_CHIP_PKT_48K') == 'y': + defines.append("-DCONFIG_CHIP_PKT_48K") +else: + defines.append("-DCONFIG_CHIP_PKT_32K") + +env.Replace(CPPDEFINES=defines) +env.Replace(CCFLAGS=boot_cflags) +env.Replace(ASFLAGS=boot_asflags) +env.Replace(CPPPATH=incs) +env.Replace(LINKFLAGS=ld_flags) + +src_path = module_libs['boot'] + +objs = [] +for src in src_path: + path = src if '..' not in src else os.path.relpath(os.path.realpath(os.path.abspath(src)), os.path.join(env_cfg.root)) + objs += env.SConscript(os.path.join(src, 'SConscript'), {'env':env,}, variant_dir = os.path.join('#', obj_path, "flashboot", path), duplicate=0) + +boot_elf = env.Command(target=os.path.join("#", cache_path, "flash_boot.elf"), source=sorted(objs), action="$LINK $LINKFLAGS -T%s $LIBPATH $SOURCES -o $TARGET --start-group $LIBS --end-group"%(link_path)) +boot_bin = env.Command(target=os.path.join("#", cache_path, "hi_flash_boot.bin"), source=boot_elf, + action="$OBJCOPY -Obinary -R .rom.text -R .rom.code.text -R .u_boot_cmd -R .rom.data -R .rom.code.data -R .rom.bss \ + -R .rom.code.bss -S $SOURCE $TARGET") +boot_bin_B = os.path.join(bin_path, "%s_boot_signed_B.bin"%(CONFIG_TARGET_BIN_NAME)) +if scons_usr_bool_option('CONFIG_TARGET_SIG_SHA256') == 'y': + boot_signed_bin = env.Command(target=os.path.join("#", bin_path, "%s_boot_signed.bin"%(CONFIG_TARGET_BIN_NAME)), source=boot_bin, + action="%s -i $SOURCE -o $TARGET -n -t%s"%(sign_tool, boot_bin_B)) +else: + if scons_usr_bool_option('CONFIG_BOOT_ENCRYPT') == 'y': + boot_signed_bin = env.Command(target=os.path.join("#", bin_path, "%s_boot_signed.bin"%(CONFIG_TARGET_BIN_NAME)), source=boot_bin, + action="%s -i $SOURCE -o $TARGET -r%s -s%s -v %d -a %d -e%s -t%s"%(sign_tool, root_key_path, sub_key_path, boot_ver, sign_type, encrypt_key_path, boot_bin_B)) + else: + boot_signed_bin = env.Command(target=os.path.join("#", bin_path, "%s_boot_signed.bin"%(CONFIG_TARGET_BIN_NAME)), source=boot_bin, + action="%s -i $SOURCE -o $TARGET -r%s -s%s -v %d -a %d -t%s"%(sign_tool, root_key_path, sub_key_path, boot_ver, sign_type, boot_bin_B)) + +env.AddPostAction(boot_bin, cleanup) +env.AddPostAction(boot_signed_bin, cleanup) + +Return('boot_signed_bin') + diff --git a/sdk_liteos/boot/flashboot/common/nvm/SConscript b/sdk_liteos/boot/flashboot/common/nvm/SConscript new file mode 100755 index 0000000000000000000000000000000000000000..aceb2b6a9464ce64030c1f9c5374ec933dcab384 --- /dev/null +++ b/sdk_liteos/boot/flashboot/common/nvm/SConscript @@ -0,0 +1,6 @@ +Import('env') + +env = env.Clone() + +objs = env.Object(Glob('*.c')) +Return('objs') diff --git a/sdk_liteos/boot/flashboot/common/nvm/hi_nvm.c b/sdk_liteos/boot/flashboot/common/nvm/hi_nvm.c new file mode 100644 index 0000000000000000000000000000000000000000..1f91605587009c1b7cb1b9e8b0635011cf393fb3 --- /dev/null +++ b/sdk_liteos/boot/flashboot/common/nvm/hi_nvm.c @@ -0,0 +1,442 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "hi_nvm.h" +#include +#include + +typedef hi_u32(*hi_nvm_changed_notify_f) (hi_u8 id); + +typedef struct { + hi_u8 min_id; + hi_u8 max_id; + hi_u16 count; +} nvm_changed_proc_stru; +typedef struct { + hi_u32 base_addr; + hi_u32 total_size; + hi_u32 block_size; +} nvm_basic_info; + + +HI_CONST hi_u32 g_ver_magic = 0x12345678; + +static hi_nv_ctrl g_s_nv_ctrl[HI_TYPE_NV_MAX]; +hi_u16 g_s_nv_change_notify_list_cnt = 0; + +hi_u32 hi_crc32_nv(hi_u32 crc_start, HI_CONST hi_u8* buf, hi_u32 len, hi_u32 *crc_result) +{ + if (!buf || !len || !crc_result) { + return HI_ERR_CRC_INVALID_PARAMETER; + } + *crc_result = hi_crc32(crc_start, buf, len); + return HI_ERR_SUCCESS; +} + +hi_u32 nv_read_flash(hi_u32 addr, hi_u32 size, hi_u8* data) +{ + hi_u32 ret; + + for (hi_u32 i = 0; i < HNV_FAULT_TOLERANT_TIMES; i++) { + ret = hi_flash_read(addr, size, data); + if (ret == HI_ERR_SUCCESS) { + return HI_ERR_SUCCESS; + } + } + + return HI_ERR_NV_FAIL_N_TIMES; +} + +hi_u32 nv_write_flash(hi_u32 addr, hi_u32 size, const hi_u8* data) +{ + hi_u32 ret; + + for (hi_u32 i = 0; i < HNV_FAULT_TOLERANT_TIMES; i++) { + ret = hi_flash_write(addr, size, data, HI_TRUE); + if (ret == HI_ERR_SUCCESS) { + return HI_ERR_SUCCESS; + } + } + + return HI_ERR_NV_FAIL_N_TIMES; +} + +/* Check the validity of the NV file. */ +hi_u32 nv_check_file(hi_u8* pdata, hi_u32 len, hi_nv_type nv_type) +{ + hi_nv_manage* nv_head; + hi_u32 magic = HNV_FILE_SIGNATURE; + hi_u32 crc_val = 0; + + nv_head = (hi_nv_manage*)pdata; + if (nv_type == HI_TYPE_FACTORY_NV) { + magic = FNV_FILE_SIGNATURE; + } + if (magic != nv_head->magic) { + return HI_ERR_NV_INVALID_TYPE; + } + if (nv_head->total_num >= NV_TOTAL_MAX_NUM) { + return HI_ERR_NV_FULL; + } + hi_crc32_nv(0, pdata + HNV_NCRC_SIZE, len - HNV_NCRC_SIZE, &crc_val); + + if (nv_head->crc != crc_val) { + return HI_ERR_NV_BAD_DATA; + } + return HI_ERR_SUCCESS; +} + +/* Returns the corresponding NV index. */ +hi_nv_item_index* nv_find_item(hi_u8* data, hi_u8 id, hi_nv_type nv_type) +{ + hi_nv_item_index* index = HI_NULL; + hi_u16 total_num; + + if (data == HI_NULL) { + total_num = g_s_nv_ctrl[nv_type].total_num; + index = g_s_nv_ctrl[nv_type].index; + } else { + hi_nv_manage* nv_head = (hi_nv_manage*)data; + total_num = nv_head->total_num; + index = (hi_nv_item_index*)&nv_head->nv_item_data[0]; + } + + for (hi_u32 i = 0; i < total_num; i++) { + if (id == index[i].nv_id) { + return &index[i]; + } + } + return (hi_nv_item_index*)HI_NULL; +} + +hi_u32 nv_init_start(hi_u32 block_size, hi_u8** data, hi_u8** back, hi_nv_ctrl** nv_ctrl, hi_nv_type nv_type) +{ + if (nv_type >= HI_TYPE_NV_MAX) { + return HI_ERR_NV_INVALID_PARAMETER; + } + *nv_ctrl = &g_s_nv_ctrl[nv_type]; + *data = (hi_u8 *)rom_boot_malloc(block_size); + if (*data == HI_NULL) { + return HI_ERR_MALLOC_FAILUE; + } + *back = (hi_u8 *)rom_boot_malloc(block_size); + if (*back == HI_NULL) { + rom_boot_free(*data); + return HI_ERR_MALLOC_FAILUE; + } + return HI_ERR_SUCCESS; +} + +hi_u32 nv_init_index(hi_nv_ctrl* nv_ctrl, const nvm_basic_info* nv_info, hi_u8* p_index, const hi_u8** data, + const hi_u8** back) +{ + hi_u32 ret, cs; + hi_u32 index_size = sizeof(hi_nv_item_index) * nv_ctrl->total_num; + hi_u16 block_count = (hi_u16)nv_info->total_size / (hi_u16)nv_info->block_size; + nv_ctrl->index = (hi_nv_item_index*)rom_boot_malloc(index_size); + if (nv_ctrl->index == HI_NULL) { + ret = HI_ERR_MALLOC_FAILUE; + rom_boot_free((hi_void *)*back); + rom_boot_free((hi_void *)*data); + return ret; + } + cs = (uintptr_t)(nv_ctrl->index) ^ index_size ^ (uintptr_t)p_index ^ index_size; + ret = (hi_u32)memcpy_s(nv_ctrl->index, index_size, p_index, index_size, cs); + if (ret != HI_ERR_SUCCESS) { + ret = HI_ERR_NV_FILE_ERR; + rom_boot_free(p_index); + rom_boot_free((hi_void *)*back); + rom_boot_free((hi_void *)*data); + return ret; + } + nv_ctrl->base_addr = nv_info->base_addr; + nv_ctrl->block_size = nv_info->block_size; + nv_ctrl->total_block_size = nv_info->block_size * block_count; + nv_ctrl->init_flag = HI_TRUE; + + rom_boot_free((hi_void *)*back); + rom_boot_free((hi_void *)*data); + return HI_ERR_SUCCESS; +} + +hi_u32 nv_init_common(hi_u32 base_addr, hi_u32 total_size, hi_u32 block_size, hi_nv_type nv_type) +{ + hi_nv_ctrl* nv_ctrl = HI_NULL; + nvm_basic_info nv_info; + hi_u8* data = HI_NULL; + hi_u8* back = HI_NULL; + hi_u32 seq_max = 0; + hi_u8* p_index = HI_NULL; + if (block_size == (hi_u32)0) { + return HI_ERR_FAILURE; + } + hi_bool flag_read_success = HI_FALSE; + + hi_u32 ret = nv_init_start(block_size, &data, &back, &nv_ctrl, nv_type); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + for (hi_u16 i = 0; i < (hi_u16)total_size / (hi_u16)block_size; i++) { + hi_u32 flash_addr = base_addr + i * block_size; + if (nv_read_flash(flash_addr, block_size, data) != HI_ERR_SUCCESS) { /* 读取 hi_nv_manage nv_head */ + /* If the read value is incorrect, continue the processing. */ + continue; + } + if (nv_check_file(data, block_size, nv_type) != HI_ERR_SUCCESS) { /* 检查nv文件合法性 */ + continue; + } + hi_nv_manage* nv_head = (hi_nv_manage*)data; + if (nv_head->seq >= seq_max) { + seq_max = nv_head->seq; + nv_ctrl->seq = nv_head->seq; + nv_ctrl->current_addr = flash_addr; + nv_ctrl->total_num = nv_head->total_num; + nv_ctrl->ver_magic = nv_head->ver_magic; + hi_u32 cs = (uintptr_t)back ^ block_size ^ (uintptr_t)data ^ block_size; + if (memcpy_s(back, block_size, data, block_size, cs) != EOK) { + continue; + } + p_index = &(((hi_nv_manage*)back)->nv_item_data[0]); + flag_read_success = HI_TRUE; + } + } + if (flag_read_success != HI_TRUE) { + rom_boot_free(data); + rom_boot_free(back); + return HI_ERR_NV_INITILIZATION; + } + nv_info.base_addr = base_addr; + nv_info.block_size = block_size; + nv_info.total_size = total_size; + /* Index space application */ + ret = nv_init_index(nv_ctrl, (const nvm_basic_info*)&nv_info, p_index, (const hi_u8**)&data, (const hi_u8**)&back); + return ret; +} + +hi_u8 nv_get_item_len(hi_u32 id, hi_nv_type nv_type) +{ + hi_nv_item_index* nv_index; + + nv_index = nv_find_item(HI_NULL, (hi_u8)id, nv_type); + if (nv_index == HI_NULL) { + return 0; + } + return nv_index->nv_len; +} + +hi_u32 nv_read_common(hi_u8 id, hi_pvoid pdata, hi_u8 len, hi_nv_type nv_type) +{ + hi_u32 ret; + hi_nv_ctrl* nv_ctrl = HI_NULL; + hi_nv_item_index* nv_index = HI_NULL; + hi_u32 crc = 0; + hi_u32 flash_addr; + hi_u8 item_len; + hi_bool to_check_crc; + hi_u32 crc_val = 0; + + if (nv_type >= HI_TYPE_NV_MAX) { + return HI_ERR_NV_INVALID_PARAMETER; + } + nv_ctrl = &g_s_nv_ctrl[nv_type]; + nv_index = nv_find_item(HI_NULL, id, nv_type); + if (nv_index == HI_NULL) { + return HI_ERR_NV_ERROR_READ; + } + if (nv_index->nv_len == len) { + item_len = len; + to_check_crc = HI_TRUE; + } else { + item_len = hi_min(nv_index->nv_len, len); + to_check_crc = HI_FALSE; + } + + flash_addr = nv_ctrl->current_addr + nv_index->nv_offset; + ret = nv_read_flash(flash_addr, item_len, pdata); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + /* CRC is verified only when the lengths are the same. */ + if (to_check_crc == HI_TRUE) { + ret = nv_read_flash(flash_addr + item_len, sizeof(crc), (hi_u8*)&crc); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + hi_crc32_nv(0, pdata, item_len, &crc_val); + if (crc != crc_val) { + return HI_ERR_NV_BAD_DATA; + } + } else { + ret = HI_ERR_NV_LEN_ERR; + } + + return ret; +} + + +hi_u32 nv_next_addr(HI_CONST hi_nv_ctrl *nv_ctrl) +{ + hi_u32 new_addr = ((nv_ctrl->current_addr + nv_ctrl->block_size) < (nv_ctrl->base_addr + nv_ctrl->total_block_size)) + ? (nv_ctrl->current_addr + nv_ctrl->block_size) : (nv_ctrl->base_addr); + + return new_addr; +} + +hi_u32 nv_block_write(hi_u8* p_nv_file, hi_nv_type nv_type) +{ + hi_u32 ret; + hi_nv_ctrl* nv_ctrl = &g_s_nv_ctrl[nv_type]; + hi_nv_manage* nv_head = (hi_nv_manage*)p_nv_file; + hi_u32 flash_addr = nv_next_addr((HI_CONST hi_nv_ctrl *)nv_ctrl); + + nv_head->ver_magic = g_ver_magic; + nv_head->seq = nv_ctrl->seq + 1; + + hi_crc32_nv(0, p_nv_file + 8, nv_ctrl->block_size - 8, &(nv_head->crc)); // 8 + ret = nv_write_flash(flash_addr, nv_ctrl->block_size, p_nv_file); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + nv_ctrl->seq = nv_head->seq; + nv_ctrl->current_addr = flash_addr; + + return ret; +} + +hi_u32 nv_common_write(hi_u8 id, hi_nv_type nv_type, hi_u8 len, const hi_pvoid data) +{ + hi_u8 backup_num = 1; + hi_u8 item_len = len; + hi_u32 ret, crc, cs; + hi_nv_ctrl* nv_ctrl = &g_s_nv_ctrl[nv_type]; + + /* Normal write process */ + hi_nv_item_index* nv_index = nv_find_item(HI_NULL, id, nv_type); + if (nv_index == HI_NULL) { + return HI_ERR_NV_ERROR_READ; + } + + if (nv_index->nv_len != len) { + item_len = hi_min(nv_index->nv_len, len); + } + + hi_u8* nv_file = (hi_u8 *)rom_boot_malloc(nv_ctrl->block_size); + if (nv_file == HI_NULL) { + return HI_ERR_MALLOC_FAILUE; + } + if (nv_type == HI_TYPE_FACTORY_NV) { + backup_num = 2; /* The operations in the factory area are mutually backed up. 2 copies are written. */ + } + for (; backup_num > 0; backup_num--) { + ret = nv_read_flash(nv_ctrl->current_addr, nv_ctrl->block_size, nv_file); + if (ret != HI_ERR_SUCCESS) { + continue; + } + + hi_crc32_nv(0, data, item_len, &crc); + cs = (uintptr_t)(nv_file + nv_index->nv_offset) ^ item_len ^ (uintptr_t)data ^ item_len; + if (memcpy_s(nv_file + nv_index->nv_offset, item_len, data, item_len, cs) != EOK) { + continue; + } + cs = (uintptr_t)(nv_file + nv_index->nv_offset + item_len) ^ sizeof(crc) ^ ((uintptr_t)&crc) ^ sizeof(crc); + if (memcpy_s(nv_file + nv_index->nv_offset + item_len, sizeof(crc), &crc, sizeof(crc), cs) != EOK) { + continue; + } + ret = nv_block_write(nv_file, nv_type); + if (ret != HI_ERR_SUCCESS) { + continue; + } + } + rom_boot_free(nv_file); + return ret; +} + +hi_u32 nv_write_common(hi_u8 id, const hi_pvoid data, hi_u8 len, hi_nv_type nv_type) +{ + if (nv_type >= HI_TYPE_NV_MAX) { + return HI_ERR_NV_INVALID_PARAMETER; + } + /* If the readback is equal, no write operation is performed. */ + hi_u8* item_readback = (hi_u8 *)rom_boot_malloc(HNV_ITEM_MAXLEN); + if (item_readback == HI_NULL) { + return HI_ERR_MALLOC_FAILUE; + } + + hi_u32 ret = nv_read_common(id, item_readback, len, nv_type); + if (ret != HI_ERR_SUCCESS) { + rom_boot_free(item_readback); + return ret; + } + if (memcmp(data, item_readback, len) == HI_ERR_SUCCESS) { + rom_boot_free(item_readback); + return HI_ERR_SUCCESS; + } + rom_boot_free(item_readback); + + /* Normal write process */ + ret = nv_common_write(id, nv_type, len, data); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + return HI_ERR_SUCCESS; +} + +hi_u32 hi_factory_nv_init(hi_u32 addr, hi_u32 total_size, hi_u32 block_size) +{ + return nv_init_common(addr, total_size, block_size, HI_TYPE_FACTORY_NV); +} + +hi_u32 hi_factory_nv_write(hi_u8 id, hi_pvoid pdata, hi_u8 len, hi_u32 flag) +{ + hi_unref_param(flag); + hi_u32 ret; + hi_nv_ctrl* nv_ctrl = HI_NULL; + + if (id >= HI_NV_FACTORY_USR_ID_END) { + return HI_ERR_NV_NOT_SUPPORT; + } + if ((pdata == HI_NULL) || (len == 0) || (len > HNV_ITEM_MAXLEN)) { + return HI_ERR_NV_INVALID_PARAMETER; + } + nv_ctrl = &g_s_nv_ctrl[HI_TYPE_FACTORY_NV]; + if (nv_ctrl->init_flag != HI_TRUE) { + return HI_ERR_NV_INITILIZATION; + } + ret = nv_write_common(id, (HI_CONST hi_pvoid)pdata, len, HI_TYPE_FACTORY_NV); + + return ret; +} + +hi_u32 hi_factory_nv_read(hi_u8 id, hi_pvoid data, hi_u8 len, hi_u32 flag) +{ + hi_unref_param(flag); + hi_u32 ret; + hi_nv_ctrl* nv_ctrl = HI_NULL; + + if (id >= HI_NV_FACTORY_USR_ID_END) { + return HI_ERR_NV_NOT_SUPPORT; + } + if ((data == HI_NULL) || (len == 0) || (len > HNV_ITEM_MAXLEN)) { + return HI_ERR_NV_INVALID_PARAMETER; + } + nv_ctrl = &g_s_nv_ctrl[HI_TYPE_FACTORY_NV]; + if (nv_ctrl->init_flag != HI_TRUE) { + return HI_ERR_NV_INITILIZATION; + } + ret = nv_read_common(id, data, len, HI_TYPE_FACTORY_NV); + + return ret; +} + diff --git a/sdk_liteos/boot/flashboot/common/nvm/hi_nvm.h b/sdk_liteos/boot/flashboot/common/nvm/hi_nvm.h new file mode 100644 index 0000000000000000000000000000000000000000..3f391e5bc5bf363482c7fc796e30271c69f8295e --- /dev/null +++ b/sdk_liteos/boot/flashboot/common/nvm/hi_nvm.h @@ -0,0 +1,85 @@ +/** + * @file hi_nvm.h + * + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __HI_NVM_H__ +#define __HI_NVM_H__ + +#include + +#define hi_make_identifier(a, b, c, d) hi_makeu32(hi_makeu16(a, b), hi_makeu16(c, d)) +#define HNV_FILE_SIGNATURE hi_make_identifier('H', 'N', 'V', '$') +#define FNV_FILE_SIGNATURE hi_make_identifier('F', 'N', 'V', '#') + +#define FACTORY_NV_SIZE 0x2000 +#define FLASH_BLOCK_SIZE 0x1000 +#define HNV_NCRC_SIZE 8 /* no crc length */ +#define NV_TOTAL_MAX_NUM 255 /* Maximum number of NVs that can be set */ +#define HNV_FAULT_TOLERANT_TIMES 3 /* Error tolerance times */ + +#define HNV_MANAGE_FIXED_LEN 24 + +/* + * The NV structure in the factory area must be the same as that in the kernel and + * cannot be modified after being fixed. + */ +typedef struct _hi_nvm_manage_s_ { + hi_u32 magic; + hi_u32 crc; + hi_u8 ver; + hi_u8 head_len; + hi_u16 total_num; + hi_u32 seq; + hi_u32 ver_magic; + hi_u32 flash_size; + hi_u8 keep_id_range[2]; /* Reserved upg id, size:2 bytes, byte0:upper boundary, byte1:lower boundary */ + hi_u8 reserve[2]; /* Reserved 2 bytes */ + hi_u8 nv_item_data[0]; +} hi_nv_manage; + +typedef struct hi_nv_item_index_s_ { + hi_u8 nv_id; + hi_u8 nv_len; + hi_u16 nv_offset; +} hi_nv_item_index; + +typedef struct _hi_nv_ctrl_s_ { + hi_u32 base_addr; + hi_u32 block_size; + hi_u32 total_block_size; + hi_u32 current_addr; + hi_u32 seq; + hi_u32 sem_handle; + + hi_u8 init_flag; + hi_u8 reserve; + hi_u16 total_num; + hi_u32 ver_magic; + hi_nv_item_index* index; +} hi_nv_ctrl; + +typedef enum _hi_nv_type_e_ { + HI_TYPE_NV = 0, + HI_TYPE_FACTORY_NV, + HI_TYPE_TEMP, + HI_TYPE_NV_MAX, +} hi_nv_type; + +hi_u32 hi_nv_flush_keep_ids(hi_u8* addr, hi_u32 len); +hi_u32 hi_nv_block_write(hi_u8* nv_file, hi_u32 len, hi_u32 flag); + +#endif /* __HI_NVM_H__ */ + diff --git a/sdk_liteos/boot/flashboot/common/partition_table/SConscript b/sdk_liteos/boot/flashboot/common/partition_table/SConscript new file mode 100755 index 0000000000000000000000000000000000000000..aceb2b6a9464ce64030c1f9c5374ec933dcab384 --- /dev/null +++ b/sdk_liteos/boot/flashboot/common/partition_table/SConscript @@ -0,0 +1,6 @@ +Import('env') + +env = env.Clone() + +objs = env.Object(Glob('*.c')) +Return('objs') diff --git a/sdk_liteos/boot/flashboot/common/partition_table/boot_partition_table.c b/sdk_liteos/boot/flashboot/common/partition_table/boot_partition_table.c new file mode 100755 index 0000000000000000000000000000000000000000..90ee4f2a58f2f3481eb71cb0f42677b618602393 --- /dev/null +++ b/sdk_liteos/boot/flashboot/common/partition_table/boot_partition_table.c @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#define PRODUCT_CFG_DEFAULT_BOOT_ADDR 0x0 +#define PRODUCT_CFG_DEFAULT_FNV_ADDR 0x8000 +#define PRODUCT_CFG_DEFAULT_NORMAL_NV_ADDR 0xA000 +#define PRODUCT_CFG_DEFAULT_NORMAL_NV_BACKUP_ADDR 0xC000 +#define PRODUCT_CFG_DEFAULT_KERNEL_A_ADDR 0xD000 +#define PRODUCT_CFG_DEFAULT_KERNEL_B_ADDR 0xF1000 +#define PRODUCT_CFG_DEFAULT_HILINK_ADDR 0x1E3000 +#define PRODUCT_CFG_DEFAULT_FILE_SYSTEM_ADDR 0x1E5000 +#define PRODUCT_CFG_DEFAULT_USER_RESERVE_ADDR 0x1F0000 +#define PRODUCT_CFG_DEFAULT_HILINK_PKI_ADDR 0x1F5000 +#define PRODUCT_CFG_DEFAULT_CRASH_INFO_ADDR 0x1F7000 +#define PRODUCT_CFG_DEFAULT_BOOT_BACK_ADDR 0x1F8000 + +#define PRODUCT_CFG_DEFAULT_BOOT_SIZE 0x8000 /* 32K */ +#define PRODUCT_CFG_DEFAULT_FNV_SIZE 0x2000 /* 8K */ +#define PRODUCT_CFG_DEFAULT_NORMAL_NV_SIZE 0x2000 /* 8K */ +#define PRODUCT_CFG_DEFAULT_NORMAL_NV_BACKUP_SIZE 0x1000 /* 4K */ +#define PRODUCT_CFG_DEFAULT_KERNEL_A_SIZE 0xE4000 /* 912K */ +#define PRODUCT_CFG_DEFAULT_KERNEL_B_SIZE 0xF2000 /* 968K */ +#define PRODUCT_CFG_DEFAULT_HILINK_SIZE 0x2000 /* 8K */ +#define PRODUCT_CFG_DEFAULT_FILE_SYSTEM_SIZE 0xB000 /* 44K */ +#define PRODUCT_CFG_DEFAULT_USER_RESERVE_SIZE 0x5000 /* 20K */ +#define PRODUCT_CFG_DEFAULT_HILINK_PKI_SIZE 0x2000 /* 8K */ +#define PRODUCT_CFG_DEFAULT_CRASH_INFO_SIZE 0x1000 /* 4K */ +#define PRODUCT_CFG_DEFAULT_BOOT_BACK_SIZE 0x8000 /* 32K */ + +static hi_flash_partition_table g_partition_table; + +hi_flash_partition_table* hi_get_partition_table(hi_void) +{ + return &g_partition_table; +} + + +/* Initializes the flash partition table. */ +hi_u32 hi_flash_partition_init(hi_void) +{ + hi_flash_partition_table* table = hi_get_partition_table(); + +#ifndef CONFIG_QUICK_SEND_MODE + hi_u32 ret = hi_factory_nv_read(HI_NV_FTM_FLASH_PARTIRION_TABLE_ID, table, sizeof(hi_flash_partition_table), 0); +#else + hi_u32 ret = HI_ERR_FAILURE; +#endif + if (ret != HI_ERR_SUCCESS) { /* read nv fail, set flash partition table default value */ + table->table[HI_FLASH_PARTITON_BOOT].addr = PRODUCT_CFG_DEFAULT_BOOT_ADDR; + table->table[HI_FLASH_PARTITON_BOOT].size = PRODUCT_CFG_DEFAULT_BOOT_SIZE; + table->table[HI_FLASH_PARTITON_FACTORY_NV].addr = PRODUCT_CFG_DEFAULT_FNV_ADDR; + table->table[HI_FLASH_PARTITON_FACTORY_NV].size = PRODUCT_CFG_DEFAULT_FNV_SIZE; + table->table[HI_FLASH_PARTITON_NORMAL_NV].addr = PRODUCT_CFG_DEFAULT_NORMAL_NV_ADDR; + table->table[HI_FLASH_PARTITON_NORMAL_NV].size = PRODUCT_CFG_DEFAULT_NORMAL_NV_SIZE; + table->table[HI_FLASH_PARTITON_NORMAL_NV_BACKUP].addr = PRODUCT_CFG_DEFAULT_NORMAL_NV_BACKUP_ADDR; + table->table[HI_FLASH_PARTITON_NORMAL_NV_BACKUP].size = PRODUCT_CFG_DEFAULT_NORMAL_NV_BACKUP_SIZE; + table->table[HI_FLASH_PARTITON_KERNEL_A].addr = PRODUCT_CFG_DEFAULT_KERNEL_A_ADDR; + table->table[HI_FLASH_PARTITON_KERNEL_A].size = PRODUCT_CFG_DEFAULT_KERNEL_A_SIZE; + table->table[HI_FLASH_PARTITON_KERNEL_B].addr = PRODUCT_CFG_DEFAULT_KERNEL_B_ADDR; + table->table[HI_FLASH_PARTITON_KERNEL_B].size = PRODUCT_CFG_DEFAULT_KERNEL_B_SIZE; + table->table[HI_FLASH_PARTITON_HILINK].addr = PRODUCT_CFG_DEFAULT_HILINK_ADDR; + table->table[HI_FLASH_PARTITON_HILINK].size = PRODUCT_CFG_DEFAULT_HILINK_SIZE; + table->table[HI_FLASH_PARTITON_FILE_SYSTEM].addr = PRODUCT_CFG_DEFAULT_FILE_SYSTEM_ADDR; + table->table[HI_FLASH_PARTITON_FILE_SYSTEM].size = PRODUCT_CFG_DEFAULT_FILE_SYSTEM_SIZE; + table->table[HI_FLASH_PARTITON_USR_RESERVE].addr = PRODUCT_CFG_DEFAULT_USER_RESERVE_ADDR; + table->table[HI_FLASH_PARTITON_USR_RESERVE].size = PRODUCT_CFG_DEFAULT_USER_RESERVE_SIZE; + table->table[HI_FLASH_PARTITON_HILINK_PKI].addr = PRODUCT_CFG_DEFAULT_HILINK_PKI_ADDR; + table->table[HI_FLASH_PARTITON_HILINK_PKI].size = PRODUCT_CFG_DEFAULT_HILINK_PKI_SIZE; + table->table[HI_FLASH_PARTITON_CRASH_INFO].addr = PRODUCT_CFG_DEFAULT_CRASH_INFO_ADDR; + table->table[HI_FLASH_PARTITON_CRASH_INFO].size = PRODUCT_CFG_DEFAULT_CRASH_INFO_SIZE; + table->table[HI_FLASH_PARTITON_BOOT_BACK].addr = PRODUCT_CFG_DEFAULT_BOOT_BACK_ADDR; + table->table[HI_FLASH_PARTITON_BOOT_BACK].size = PRODUCT_CFG_DEFAULT_BOOT_BACK_SIZE; + } +#ifdef CONFIG_QUICK_SEND_MODE + ret = HI_ERR_SUCCESS; +#endif + + return ret; +} + diff --git a/sdk_liteos/boot/flashboot/drivers/efuse/SConscript b/sdk_liteos/boot/flashboot/drivers/efuse/SConscript new file mode 100755 index 0000000000000000000000000000000000000000..aceb2b6a9464ce64030c1f9c5374ec933dcab384 --- /dev/null +++ b/sdk_liteos/boot/flashboot/drivers/efuse/SConscript @@ -0,0 +1,6 @@ +Import('env') + +env = env.Clone() + +objs = env.Object(Glob('*.c')) +Return('objs') diff --git a/sdk_liteos/boot/flashboot/drivers/efuse/efuse.c b/sdk_liteos/boot/flashboot/drivers/efuse/efuse.c new file mode 100644 index 0000000000000000000000000000000000000000..ddd918560cf8b92309d7c815754e756668eb80b4 --- /dev/null +++ b/sdk_liteos/boot/flashboot/drivers/efuse/efuse.c @@ -0,0 +1,296 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "efuse.h" +#include "efuse_drv.h" + +hi_u32 efuse_start_addr_unaligned_read(hi_u16 start_bit, hi_u16 size, hi_u8 diff_head_read, hi_u8 *data) +{ + hi_u32 ret = HI_ERR_FAILURE; + hi_u32 check_sum; + + if (size == SIZE_8_BITS) { + ret = efuse_read_bits(start_bit, size, data); + if (ret == HI_ERR_SUCCESS) { + data[0] = data[0] >> diff_head_read; + } + } else if (size == SIZE_16_BITS) { + hi_u16 tmp_data = 0; + ret = efuse_read_bits(start_bit, size, (hi_u8 *)&tmp_data); + if (ret == HI_ERR_SUCCESS) { + tmp_data = tmp_data >> diff_head_read; + if (start_bit == 0xE0) { + *data = (hi_u8)(tmp_data & 0xFF); + } else { + *(hi_u16 *)data = tmp_data; + } + } + } else if (size == SIZE_24_BITS) { + hi_u32 tmp_data = 0; + ret = efuse_read_bits(start_bit, SIZE_24_BITS, (hi_u8 *)&tmp_data); + if (ret == HI_ERR_SUCCESS) { + tmp_data = tmp_data >> diff_head_read; + check_sum = (uintptr_t)data ^ DATA_LENGTH ^ (uintptr_t)(hi_u8 *)&tmp_data ^ DATA_LENGTH; + if (memcpy_s(data, DATA_LENGTH, (hi_u8 *)&tmp_data, DATA_LENGTH, check_sum) != EOK) { + return HI_ERR_FAILURE; + } + } + } else if (size == SIZE_72_BITS) { + hi_u8 tmp_data[SIZE_72_BITS / SIZE_8_BITS] = { 0 }; + hi_u32 data_u32[2]; /* U64 is divided into 2 U32 */ + hi_u8 end_u8; + ret = efuse_read_bits(start_bit, SIZE_72_BITS, &tmp_data[0]); + if (ret == HI_ERR_SUCCESS) { + data_u32[0] = *(hi_u32 *)&tmp_data[0]; /* first U32 offset is 0 */ + data_u32[1] = *(hi_u32 *)&tmp_data[4]; /* sencond U32 offset is 4 */ + end_u8 = *(hi_u8 *)&tmp_data[8]; /* the last u8 bit */ + data_u32[0] = data_u32[0] >> diff_head_read; + data_u32[0] = data_u32[0] | (data_u32[1] << (SIZE_32_BITS - diff_head_read)); + data_u32[1] = data_u32[1] >> diff_head_read; + data_u32[1] = data_u32[1] | ((hi_u32)end_u8 << (SIZE_32_BITS - diff_head_read)); + *(hi_u64 *)data = (((hi_u64)data_u32[1] << SIZE_32_BITS) | data_u32[0]); + } + } + return ret; +} + +hi_u32 efuse_bits_read(hi_u16 start_bit, hi_u16 size, hi_u8 *data, hi_u32 data_len) +{ + hi_u8 diff_head_read = 0; + hi_u32 origine_size; + hi_u32 ret; + if (data_len > EFUSE_MAX_INDEX_SIZE) { + return HI_ERR_FAILURE; + } + + origine_size = size; + if ((start_bit & 0x7) != 0x0) { + diff_head_read = start_bit % SIZE_8_BITS; + /* The start address of the chip must be 8-bit aligned. */ + start_bit = start_bit - diff_head_read; + size = size + diff_head_read; + } + + if ((size & 0x7) != 0x0) { + size = ((size >> THREE_BITS_OFFSET) + 1) << THREE_BITS_OFFSET; + } + + if (diff_head_read == 0) { + /* The start address is 8-bit aligned. */ + ret = efuse_read_bits(start_bit, size, data); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + } else { + /* The start address is 8-bit aligned. */ + ret = efuse_start_addr_unaligned_read(start_bit, size, diff_head_read, data); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + } + + if (origine_size <= SIZE_8_BITS) { + *data &= ((1 << origine_size) - 1); + } else if (origine_size <= SIZE_16_BITS) { + *(hi_u16 *)data &= ((1 << origine_size) - 1); + } else if (origine_size < SIZE_32_BITS) { + *(hi_u32 *)data &= (((hi_u32)1 << origine_size) - 1); + } + + return HI_ERR_SUCCESS; +} + +hi_u32 hi_efuse_read(hi_efuse_idx efuse_id, hi_u8 *data, hi_u8 data_len) +{ + hi_u16 start_bit = 0; + hi_u16 size = 0; + hi_u16 align_size; + hi_u8 flag = EFUSE_IDX_NRW; + + if (efuse_id >= HI_EFUSE_IDX_MAX || data == HI_NULL) { + return HI_ERR_EFUSE_INVALIDATE_PARA; + } + + get_efuse_cfg_by_id(efuse_id, &start_bit, &size, &flag); + + if (flag == EFUSE_IDX_WO) { + return HI_ERR_EFUSE_INVALIDATE_AUTH; + } + + align_size = ((size & 0x7) != 0x0) ? (((size >> THREE_BITS_OFFSET) + 1) << THREE_BITS_OFFSET) : size; + + if (align_size > ((hi_u16)data_len * EIGHT_BITS)) { + return HI_ERR_EFUSE_INVALIDATE_PARA; + } + + return efuse_bits_read(start_bit, size, data, data_len); +} + +hi_u32 hi_efuse_write(hi_efuse_idx efuse_id, const hi_u8 *data) +{ + hi_u16 start_bit = 0; + hi_u16 size = 0; + hi_u8 flag = EFUSE_IDX_NRW; + hi_char err_state[EFUSE_MAX_INDEX_SIZE] = { + 0, + }; + hi_u32 i; + hi_u32 ret; + + if (efuse_id >= HI_EFUSE_IDX_MAX || data == HI_NULL) { + boot_msg1("parameter err !", efuse_id); + return HI_ERR_EFUSE_INVALIDATE_PARA; + } + + get_efuse_cfg_by_id(efuse_id, &start_bit, &size, &flag); + if (flag == EFUSE_IDX_RO) { + boot_msg1("This section can not be write !flag = ", flag); + return HI_ERR_EFUSE_INVALIDATE_AUTH; + } + + ret = efuse_write_bits(start_bit, size, data, (hi_u8 *)&err_state[0]); + if (ret != HI_ERR_SUCCESS) { + boot_msg0("efuse write err"); + return ret; + } + + for (i = 0; i < EFUSE_MAX_INDEX_SIZE; i++) { + if (err_state[i]) { + boot_msg1("errstate num is", i); + return HI_ERR_EFUSE_WRITE_ERR; + } + } + + return HI_ERR_SUCCESS; +} + +hi_u32 hi_efuse_lock(hi_efuse_lock_id lock_id) +{ + hi_u16 err_stat = 0; + hi_u32 ret; + hi_u16 start_bit; + hi_u8 lock_val = 1; + + if (lock_id >= HI_EFUSE_LOCK_MAX) { + return HI_ERR_EFUSE_INVALIDATE_ID; + } + + if (lock_id < HI_EFUSE_LOCK_FLASH_ENCPY_CNT3_ID) { + start_bit = EFUSE_LOCK_START_BITS + lock_id; + } else { + start_bit = EFUSE_LOCK_FIELD2_START_BITS + lock_id - HI_EFUSE_LOCK_FLASH_ENCPY_CNT3_ID; + } + + ret = efuse_write_bits(start_bit, 1, &lock_val, (hi_u8 *)&err_stat); + if ((ret == HI_ERR_SUCCESS) && (err_stat == 0)) { + return HI_ERR_SUCCESS; + } else if (err_stat != 0) { + return HI_ERR_EFUSE_WRITE_ERR; + } + + return ret; +} + +hi_u32 hi_efuse_get_lockstat(hi_u64 *lock_stat) +{ + hi_u16 start_bit = EFUSE_LOCK_START_BITS; + hi_u16 size = EFUSE_LOCK_SIZE; + hi_u8 diff_head_read; + hi_u64 tmp_data = 0; + hi_u64 tmp_data_filed_two = 0; + hi_u32 ret; + + if (lock_stat == HI_NULL) { + return HI_ERR_FAILURE; + } + + /* start address and size 8 bits align. */ + diff_head_read = start_bit % EIGHT_BITS; + start_bit = start_bit - diff_head_read; + size = size + diff_head_read; + + ret = efuse_read_bits(start_bit, size, (hi_u8 *)&tmp_data); + if (ret == HI_ERR_SUCCESS) { + tmp_data = tmp_data >> diff_head_read; + } else { + return HI_ERR_FAILURE; + } + + start_bit = EFUSE_LOCK_FIELD2_START_BITS; + size = EFUSE_LOCK_FIELD2_SIZE; + + /* start address and size 8 bits align. */ + diff_head_read = start_bit % EIGHT_BITS; + start_bit = start_bit - diff_head_read; + size = size + diff_head_read; + + ret = efuse_read_bits(start_bit, size, (hi_u8 *)&tmp_data_filed_two); + if (ret == HI_ERR_SUCCESS) { + tmp_data_filed_two = tmp_data_filed_two >> diff_head_read; + } else { + return HI_ERR_FAILURE; + } + + *lock_stat = (((tmp_data_filed_two << EFUSE_LOCK_SIZE) & 0x1F000000000) | (tmp_data & 0xFFFFFFFFF)); + + return HI_ERR_SUCCESS; +} + +hi_u32 hi_efuse_usr_read(hi_u16 start_bit, hi_u16 size, hi_u8 *key_data) +{ + hi_u16 real_size = size; + + if ((start_bit >= EFUSE_PGM_ADDR_SIZE) || ((start_bit & 0x7) != 0) || (key_data == HI_NULL) || (size == 0)) { + return HI_ERR_FAILURE; + } + + /* The start address of the chip must be 8-bit aligned. */ + if ((size & 0x7) != 0x0) { + real_size = ((size >> 3) + 1) << 3; /* right shift 3bit;add;then left shift 3bit */ + } + + if ((start_bit + real_size) > EFUSE_PGM_ADDR_SIZE) { + return HI_ERR_FAILURE; + } + + return efuse_read_bits(start_bit, real_size, key_data); +} + +hi_u32 hi_efuse_usr_write(hi_u16 start_bit, hi_u16 size, const hi_u8 *key_data) +{ + hi_u8 usr_err_stat[EFUSE_MAX_INDEX_SIZE]; + hi_u32 i; + hi_u32 ret; + + if (size > (EFUSE_MAX_INDEX_SIZE * SIZE_8_BITS) || key_data == HI_NULL || size == 0) { + return HI_ERR_FAILURE; + } + hi_u32 check_sum = (uintptr_t)usr_err_stat ^ EFUSE_MAX_INDEX_SIZE ^ 0 ^ EFUSE_MAX_INDEX_SIZE; + memset_s(usr_err_stat, EFUSE_MAX_INDEX_SIZE, 0, EFUSE_MAX_INDEX_SIZE, check_sum); + + ret = efuse_write_bits(start_bit, size, key_data, (hi_u8 *)&usr_err_stat[0]); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + for (i = 0; i < EFUSE_MAX_INDEX_SIZE; i++) { + if (usr_err_stat[i]) { + return HI_ERR_FAILURE; + } + } + + return HI_ERR_SUCCESS; +} + diff --git a/sdk_liteos/boot/flashboot/drivers/efuse/efuse.h b/sdk_liteos/boot/flashboot/drivers/efuse/efuse.h new file mode 100644 index 0000000000000000000000000000000000000000..29e3e3247621b572fde8ebb2307f0c7de4b01333 --- /dev/null +++ b/sdk_liteos/boot/flashboot/drivers/efuse/efuse.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __EFUSE_H__ +#define __EFUSE_H__ +#include + +#define EIGHT_BITS 8 +#define THREE_BITS_OFFSET 3 +#define SIZE_8_BITS 8 +#define SIZE_16_BITS 16 +#define SIZE_24_BITS 24 +#define SIZE_32_BITS 32 +#define SIZE_64_BITS 64 +#define SIZE_72_BITS 72 +#define DATA_LENGTH 4 + +hi_u32 efuse_bits_read(hi_u16 start_bit, hi_u16 size, hi_u8 *data, hi_u32 data_len); + +#endif /* __EFUSE_H__ */ + diff --git a/sdk_liteos/boot/flashboot/drivers/efuse/efuse_drv.h b/sdk_liteos/boot/flashboot/drivers/efuse/efuse_drv.h new file mode 100644 index 0000000000000000000000000000000000000000..4c730877cba26e95306b57c77535b09c5f75a8c8 --- /dev/null +++ b/sdk_liteos/boot/flashboot/drivers/efuse/efuse_drv.h @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __EFUSE_DRV_H__ +#define __EFUSE_DRV_H__ +#include + +typedef struct { + hi_u16 id_start_bit; /* Start bit */ + hi_u16 id_size; /* Unit: bit */ + hi_u8 attr; /* 0x0:None,0x1:RO,0x2:WO,0x3:R/W */ +} hi_efuse_stru; + +#define EFUSE_PGM_EN (HI_EFUSE_REG_BASE + 0x0) +#define EFUSE_PGM_ADDR (HI_EFUSE_REG_BASE + 0x4) +#define EFUSE_RD_EN (HI_EFUSE_REG_BASE + 0x8) +#define EFUSE_RD_ADDR (HI_EFUSE_REG_BASE + 0xc) +#define EFUSE_STATUS (HI_EFUSE_REG_BASE + 0x10) +#define EFUSE_RDATA (HI_EFUSE_REG_BASE + 0x14) + +#define EFUSE_WRITE_READY_STATUS (1 << 0) /* Write completion status. + The value 1 indicates that the write is complete. */ +#define EFUSE_READ_READY_STATUS (1 << 1) /* Read completion status. + The value 1 indicates that the read is complete. */ +#define EFUSE_STATUS_MASK (0x7 << 2) +#define EFUSE_PO_STATUS_READY (0x1 << 2) /* Whether the read operation is complete after power-on. + The value 1 indicates that the read operation is complete. */ +#define EFUSE_STATUS_READY (0x1 << 4) /* Busy/idle status. The value 0 indicates idle. */ + +#define EFUSE_CTRL_ST (0x1 << 5) +#define EFUSE_EN_SWITCH (1 << 0) +#define EFUSE_EN_OK 0 + +#define EFUSE_STATUS_RD (1 << 1) +#define EFUSE_8_BIT 8 +#define EFUSE_KEY_LOCK_BIT 2 + +#define EFUSE_TIMEOUT_DEFAULT 1000000 /* 1000000us */ +#define EFUSE_TIMECNT_TICK 10 + +#define EFUSE_PGM_ADDR_SIZE 2048 +#define EFUSE_USER_RESEVED_START_BIT 1884 +#define EFUSE_USER_RESEVED_END_BIT 2011 +#define EFUSE_LOCK_START_BITS 2012 +#define EFUSE_LOCK_FIELD2_START_BITS 235 +#define EFUSE_LOCK_SIZE 36 +#define EFUSE_LOCK_FIELD2_SIZE 5 +#define EFUSE_MAX_INDEX_SIZE 32 + +#define EFUSE_IDX_NRW 0x0 +#define EFUSE_IDX_RO 0x1 +#define EFUSE_IDX_WO 0x2 +#define EFUSE_IDX_RW 0x3 + +hi_efuse_stru *get_efuse_cfg(hi_void); +hi_void get_efuse_cfg_by_id(hi_efuse_idx idx, hi_u16 *start_bit, hi_u16 *size, hi_u8 *attr); +hi_u32 efuse_read_bits(hi_u16 start_bit, hi_u16 size, hi_u8 *key_data); +hi_u32 efuse_write_bits(hi_u16 start_bit, hi_u16 size, const hi_u8 *key_data, hi_u8 *err_state); + +#endif /* __EFUSE_H__ */ + diff --git a/sdk_liteos/boot/flashboot/drivers/flash/SConscript b/sdk_liteos/boot/flashboot/drivers/flash/SConscript new file mode 100755 index 0000000000000000000000000000000000000000..aceb2b6a9464ce64030c1f9c5374ec933dcab384 --- /dev/null +++ b/sdk_liteos/boot/flashboot/drivers/flash/SConscript @@ -0,0 +1,6 @@ +Import('env') + +env = env.Clone() + +objs = env.Object(Glob('*.c')) +Return('objs') diff --git a/sdk_liteos/boot/flashboot/drivers/flash/hi_flashboot_flash.c b/sdk_liteos/boot/flashboot/drivers/flash/hi_flashboot_flash.c new file mode 100644 index 0000000000000000000000000000000000000000..f92778c26ef36cb51bbee936dc214379f69d248d --- /dev/null +++ b/sdk_liteos/boot/flashboot/drivers/flash/hi_flashboot_flash.c @@ -0,0 +1,488 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include "hi_flashboot.h" + +hi_spi_flash_ctrl g_flash_drv_ctrl = { + 0, +}; + +hi_u32 g_dma_buffer[FLASH_DMA_BUF_LEN] = {0}; +hi_u8 g_back_buffer[SZ_4KB] = { 0 }; + +#define HI_FLASH_SUPPORT_REF_VBAT +#define HI_FLASH_VOLTAGE_TH0 280 +#define HI_FLASH_VOLTAGE_TH1 310 +#define PLL2DBB_192M_MASK 0x3 +#define CMU_CLK_SEL_96M 96 +#define CMU_CLK_SEL_80M 80 +#define CMU_CLK_SEL_48M 48 + +#ifdef HI_FLASH_SUPPORT_REF_VBAT +typedef struct { + hi_u8 chip_id[HI_FLASH_CHIP_ID_NUM]; + hi_u8 freq_high : 2; + hi_u8 freq_midle : 2; + hi_u8 freq_low : 2; + hi_u8 voltage : 2; +} flash_vlt_sfc_info; + +flash_vlt_sfc_info g_flash_vlt_sfc_info_tbl[HI_FLASH_DEFAULT_TYPE_NUM] = { + /* 0-->96Mhz 1-->80Mhz 2-->60Mhz 3-->48Mhz */ + {{0, }, 0x1, 0x1, 0x3, 0x1}, + {{0xef, 0x60, 0x15}, 0x1, 0x1, 0x1, 0x0}, /* w25q16jw 1.8v */ + /* {{0xef, 0x40, 0x15}, 0x1d}, 00,01,11,01}, w25q16jl 3.3v */ + {{0xef, 0x40, 0x15}, 0x0, 0x1, 0x1, 0x1}, /* w25q16jl 3.3v */ + {{0xc8, 0x60, 0x15}, 0x1, 0x1, 0x1, 0x0}, /* gd25le16 1.8v */ + {{0xc8, 0x65, 0x15}, 0x0, 0x1, 0x1, 0x1}, /* gd25wq16 1.65~3.6v use 2.3~3.6v */ + {{0x1c, 0x38, 0x15}, 0x1, 0x1, 0x1, 0x0}, /* en25s16 1.8v */ + {{0x1C, 0x70, 0x15}, 0x0, 0x1, 0x1, 0x1}, /* en25qh16 3.3v */ + {{0x85, 0x60, 0x15}, 0x0, 0x1, 0x1, 0x1}, /* p25q16 1.65~3.6v use 2.3~3.6V */ +}; + +flash_vlt_sfc_info g_flash_vlt_sfc_info = { + 0, +}; +hi_u16 g_voltage = 0; + +hi_void sfc_config_set_experience(const hi_u8 *chip_id, flash_vlt_sfc_info *flash_info, + flash_vlt_sfc_info *flash_info_tbl, hi_u8 tbl_size) +{ + flash_vlt_sfc_info *info = HI_NULL; + hi_u8 i; + hi_u8 cur_chip_idx = 0xFF; /* 0xFF : invalid */ + for (i = 1; i < tbl_size; i++) { + info = &flash_info_tbl[i]; + if (memcmp(info->chip_id, chip_id, HI_FLASH_CHIP_ID_NUM) == HI_ERR_SUCCESS) { + cur_chip_idx = i; + } + } + info = (cur_chip_idx == 0xFF) ? &flash_info_tbl[0] : &flash_info_tbl[cur_chip_idx]; + hi_u32 cs = (uintptr_t)flash_info ^ sizeof(flash_vlt_sfc_info) ^ (uintptr_t)info ^ sizeof(flash_vlt_sfc_info); + if (memcpy_s(flash_info, sizeof(flash_vlt_sfc_info), info, sizeof(flash_vlt_sfc_info), cs) != EOK) { + return; + } +} + +hi_void sfc_config_update_freq(hi_u32 addr) +{ + hi_u32 ret; + hi_u16 val; + hi_u16 reg_val; + flash_vlt_sfc_info *flash_info = (flash_vlt_sfc_info *)(uintptr_t)addr; + if (flash_info == HI_NULL) { + return; + } + hi_reg_read16(PMU_CMU_CTL_CMU_CLK_SEL_REG, reg_val); + reg_val &= ~(PLL2DBB_192M_MASK << 8); /* 8 */ + if (flash_info->voltage == 0) { /* 1.8V flash */ + val = flash_info->freq_high; + reg_val |= val << 8; /* 8 */ + hi_reg_write16(PMU_CMU_CTL_CMU_CLK_SEL_REG, reg_val); /* Configuring Driver Capabilities */ + return; + } + ret = get_average_ref_vlt(&g_voltage); + if (ret != HI_ERR_SUCCESS) { + return; + } + /* 2.3V ~ 3.6V, select the SFC frequency. */ + if (g_voltage > HI_FLASH_VOLTAGE_TH1) { /* 297*0.01V */ + val = flash_info->freq_high; + } else if (g_voltage > HI_FLASH_VOLTAGE_TH0) { /* 270*0.01V */ + val = flash_info->freq_midle; + } else { + val = flash_info->freq_low; + } + reg_val |= val << 8; /* 8 */ + hi_reg_write16(PMU_CMU_CTL_CMU_CLK_SEL_REG, reg_val); +} + +hi_void sfc_config_cmu_clk_sel(hi_u8 clk) +{ + if (clk == CMU_CLK_SEL_96M) { + hi_reg_clrbits(PMU_CMU_CTL_CMU_CLK_SEL_REG, 8, 2); /* 8, 2 96M */ + } else if (clk == CMU_CLK_SEL_80M) { + hi_reg_clrbits(PMU_CMU_CTL_CMU_CLK_SEL_REG, 8, 2); /* set 8 left shift 2 */ + hi_reg_setbit(PMU_CMU_CTL_CMU_CLK_SEL_REG, 8); /* 80M */ + } else if (clk == CMU_CLK_SEL_48M) { + hi_reg_clrbits(PMU_CMU_CTL_CMU_CLK_SEL_REG, 8, 2); /* set 8 left shift 2 */ + hi_reg_setbit(PMU_CMU_CTL_CMU_CLK_SEL_REG, 8); /* 48M */ + hi_reg_setbit(PMU_CMU_CTL_CMU_CLK_SEL_REG, 9); /* 9 */ + } +} +#endif +#define HI_FLASH_SUPPORT_FLASH_PROTECT +#ifdef HI_FLASH_SUPPORT_FLASH_PROTECT +#define FLASH_PROTECT_32K_ADDR 0x8000 +#define FLASH_PROTECT_32K_INSTRUCT 0x1C +hi_u32 g_flash_current_addr = 0xFFFFFFFF; +static hi_bool g_flash_protect_enable = HI_FALSE; +hi_u32 spi_flash_write_sr_reg(hi_u8 cmd, hi_u8* data, hi_u8 data_len, hi_bool is_volatile) +{ + hi_u32 temp_data = 0; + hi_u32 ret = HI_ERR_SUCCESS; + if (data_len > 0) { + hi_u32 cs = ((uintptr_t)&temp_data) ^ sizeof(temp_data) ^ (uintptr_t)data ^ (uintptr_t)data_len; + if (memcpy_s(&temp_data, sizeof(temp_data), data, data_len, cs) != EOK) { + return HI_ERR_FAILURE; + } + } + if (is_volatile) { + hisfc_write(SFC_REG_CMD_INS, SPI_CMD_VSR_WREN); + hisfc_write(SFC_REG_CMD_CONFIG, (hi_u32)(SFC_CMD_CONFIG_SEL_CS | SFC_CMD_CONFIG_START)); + spif_wait_config_start(); + } else { + ret = spif_write_enable(HI_TRUE); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + } + hisfc_write(SFC_REG_CMD_INS, cmd); + hisfc_write(SFC_REG_CMD_DATABUF1, temp_data); + + hisfc_write(SFC_REG_CMD_CONFIG, + SFC_CMD_CONFIG_SEL_CS + | SFC_CMD_CONFIG_DATA_EN + | sfc_cmd_config_data_cnt(data_len) + | SFC_CMD_CONFIG_START); + + spif_wait_config_start(); + return ret; +} + +hi_u32 flash_protect_check_nonprotect(hi_u8 low, hi_u8 high) +{ + /* none protect cmp:0 bp[2:0]:0 */ + if (((high & (0x1 << 0x6)) == 0) && ((low & (0x7 << 0x2)) == 0)) { + return HI_ERR_SUCCESS; + } + /* none protect cmp:1 bp[2:1]:0x3 bp0:x */ + if (((high & (0x1 << 0x6)) == (0x1 << 0x6)) && ((low & (0x3 << 0x3)) == (0x3 << 0x3))) { + return HI_ERR_SUCCESS; + } + return HI_ERR_FAILURE; +} + +hi_u32 flash_protect_set_protect(hi_u8 cmp_bp, hi_bool is_volatile) +{ + hi_u8 p_data[2] = {0}; /* 2 */ + hi_u8 cmp = (cmp_bp>>5) & 0x1; /* 5 */ + hi_u8 bp = cmp_bp & 0x1F; + hi_u32 ret = spif_wait_ready(HI_TRUE, SPI_CMD_SR_WIPN, SPI_SR_BIT_WIP); /* wait WIP set zero */ + if (ret != HI_ERR_SUCCESS) { + return ret; + } + ret = spi_flash_read_reg(SPI_CMD_RDSR, &p_data[0], 1); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + ret = spi_flash_read_reg(SPI_CMD_RDSR2, &p_data[1], 1); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + if (((p_data[0] & (0x1F<<2)) == (bp<<2)) && ((p_data[1] & (0x1<<6)) == (cmp<<6))) { /* 2 6 */ + return HI_ERR_SUCCESS; + } + /* none protect cmp:0 bp[2:0]:0 */ + if (flash_protect_check_nonprotect(p_data[0], p_data[1]) == HI_ERR_SUCCESS) { + return HI_ERR_SUCCESS; + } + p_data[0] &= ~(0x1f<<2); /* 2 */ + p_data[0] |= (hi_u8)(bp<<2); /* 2 */ + p_data[1] &= ~(0x1<<6); /* 6 */ + p_data[1] |= (hi_u8)(cmp<<6); /* 6 */ + ret = spi_flash_write_sr_reg(SPI_CMD_WRSR1, p_data, 2, is_volatile); /* 2 */ + if (ret != HI_ERR_SUCCESS) { + return ret; + } + ret = spif_wait_ready(HI_TRUE, SPI_CMD_SR_WIPN, SPI_SR_BIT_WIP); /* wait WIP set zero */ + if (ret != HI_ERR_SUCCESS) { + return ret; + } + ret = spi_flash_read_reg(SPI_CMD_RDSR, &p_data[0], 1); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + ret = spi_flash_read_reg(SPI_CMD_RDSR2, &p_data[1], 1); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + if (((p_data[0] & (0x1F<<2)) == (bp<<2)) && ((p_data[1] & (0x1<<6)) == (cmp<<6))) { /* 2 6 */ + return HI_ERR_SUCCESS; + } else { + boot_msg2("flash_protect_set_protect pdata:", p_data[0], p_data[1]); + return HI_ERR_FAILURE; + } +} + +hi_void flash_protect_enable(hi_bool enable, const hi_char *chip_name) +{ + const hi_char unknown_chip[] = "UNKNOWN"; + if (chip_name == HI_NULL) { + return; + } + if (memcmp(chip_name, unknown_chip, sizeof(unknown_chip)) == HI_ERR_SUCCESS) { + boot_msg0("unknown flash chip\n"); + return; + } + g_flash_protect_enable = enable; +} + +hi_u32 flash_protect_cancel(hi_u32 flash_offset) +{ + hi_u32 ret; + if (!g_flash_protect_enable) { + return HI_ERR_SUCCESS; + } + if (flash_offset >= g_flash_current_addr) { + return HI_ERR_SUCCESS; + } + if (flash_offset < FLASH_PROTECT_32K_ADDR) { + g_flash_current_addr = 0; + ret = flash_protect_set_protect(0, HI_FALSE); /* full flash chip unlock protection */ + } else { + g_flash_current_addr = FLASH_PROTECT_32K_ADDR; + ret = flash_protect_set_protect(FLASH_PROTECT_32K_INSTRUCT, HI_FALSE); /* protect low 32KB */ + } + return ret; +} + +#endif + +hi_void flash_clk_config(hi_void) +{ + hi_u16 reg_val; + /* set 0: FPGA 80M, ASIC 96M. */ +#ifdef HI_FLASH_SUPPORT_REF_VBAT + hi_reg_clrbits(PMU_CMU_CTL_CMU_CLK_SEL_REG, 8, 2); /* set 8 left shift 2 */ + hi_reg_setbit(PMU_CMU_CTL_CMU_CLK_SEL_REG, 8); /* 48M */ + hi_reg_setbit(PMU_CMU_CTL_CMU_CLK_SEL_REG, 9); /* 9 */ +#else + /* When the VBAT reference voltage is unavailable, set this parameter based on the actual flash model. */ + hi_reg_clrbits(PMU_CMU_CTL_CMU_CLK_SEL_REG, 8, 2); /* set 8 left shift 2 */ + hi_reg_setbit(PMU_CMU_CTL_CMU_CLK_SEL_REG, 8); /* 8 80M */ +#endif + hi_reg_clrbit(PMU_CMU_CTL_CLK_192M_GT_REG, 0); + hi_reg_setbit(CLDO_CTL_CLK_SEL_REG, 1); + hi_reg_clrbits(PMU_CMU_CTL_CMU_CLK_SEL_REG, 4, 3); /* set 4 left shift 3 */ + + /* set sfc not div: in fpga, clk is 80M */ + hi_reg_clrbits(CLDO_CTL_CLK_DIV1_REG, 4, 3); /* 4, 3 */ + /* en flash ldo bypass */ + hi_reg_read16(PMU_CMU_CTL_FLASHLDO_CFG_1_REG, reg_val); + reg_val &= ~(0x1 << 6); /* 6 */ + reg_val |= 0x1 << 6; /* 6 */ + hi_reg_write16(PMU_CMU_CTL_FLASHLDO_CFG_1_REG, reg_val); + +#ifdef HI_BOARD_ASIC + /* + * Check whether the built-in flash memory exists based on the chip ID. If no built-in flash memory exists, + * disable flash_ldo. + */ + hi_u8 chip_id; + hi_u32 ret; + ret = hi_efuse_read(HI_EFUSE_CHIP_RW_ID, (hi_u8 *)&chip_id, (hi_u8)sizeof(hi_u8)); + if (ret == HI_ERR_SUCCESS) { + if (chip_id == HI_CHIP_ID_1131SV200) { + hi_reg_setbit(PMU_CMU_CTL_PMU_MAN_CLR_0_REG, 8); /* set 1 left shift 8 */ + hi_reg_setbit(CLDO_CTL_CLK_SEL_REG, 0); + } + } +#endif +} + +hi_u32 hi_flash_erase(hi_u32 flash_addr, hi_u32 flash_erase_size) +{ + hi_u32 ret; + hi_spi_flash_ctrl *spif_ctrl = &g_flash_drv_ctrl; + ret = sfc_check_para(spif_ctrl, flash_addr, flash_erase_size, HI_FLASH_CHECK_PARAM_OPT_ERASE); + if (ret != HI_ERR_SUCCESS) { + return ret; + } +#ifdef HI_FLASH_SUPPORT_REF_VBAT + if ((g_voltage <= HI_FLASH_VOLTAGE_TH0) && (memcmp(g_flash_vlt_sfc_info.chip_id, + g_flash_vlt_sfc_info_tbl[2].chip_id, HI_FLASH_CHIP_ID_NUM) == HI_ERR_SUCCESS)) { // 2 + sfc_config_cmu_clk_sel(CMU_CLK_SEL_48M); + } +#endif +#ifdef HI_FLASH_SUPPORT_FLASH_PROTECT + ret = flash_protect_cancel(flash_addr); + if (ret != HI_ERR_SUCCESS) { + return ret; + } +#endif + ret = flash_erase_prv(spif_ctrl, flash_addr, flash_erase_size); +#ifdef HI_FLASH_SUPPORT_REF_VBAT + if ((g_voltage <= HI_FLASH_VOLTAGE_TH0) && (memcmp(g_flash_vlt_sfc_info.chip_id, + g_flash_vlt_sfc_info_tbl[2].chip_id, HI_FLASH_CHIP_ID_NUM) == HI_ERR_SUCCESS)) { // 2 + sfc_config_cmu_clk_sel(CMU_CLK_SEL_80M); + } +#endif + flash_info_print("hi_flash_erase ret:%x addr:%x len:%x\r\n", ret, flash_addr, flash_erase_size); + return ret; +} + +hi_u32 hi_flash_write(hi_u32 flash_addr, hi_u32 flash_write_size, const hi_u8 *flash_write_data, hi_bool do_erase) +{ + hi_u32 ret; + hi_spi_flash_ctrl *spif_ctrl = &g_flash_drv_ctrl; + if (flash_write_data == HI_NULL) { + return HI_ERR_FLASH_INVALID_PARAMETER; + } + ret = sfc_check_para(spif_ctrl, flash_addr, flash_write_size, HI_FLASH_CHECK_PARAM_OPT_WRITE); + if (ret != HI_ERR_SUCCESS) { + return ret; + } +#ifdef HI_FLASH_SUPPORT_REF_VBAT + if ((g_voltage <= HI_FLASH_VOLTAGE_TH0) && (memcmp(g_flash_vlt_sfc_info.chip_id, + g_flash_vlt_sfc_info_tbl[2].chip_id, HI_FLASH_CHIP_ID_NUM) == HI_ERR_SUCCESS)) { // 2 + sfc_config_cmu_clk_sel(CMU_CLK_SEL_48M); + } +#endif +#ifdef HI_FLASH_SUPPORT_FLASH_PROTECT + ret = flash_protect_cancel(flash_addr); + if (ret != HI_ERR_SUCCESS) { + return ret; + } +#endif + ret = flash_write_prv(spif_ctrl, flash_addr, flash_write_data, flash_write_size, do_erase); +#ifdef HI_FLASH_SUPPORT_REF_VBAT + if ((g_voltage <= HI_FLASH_VOLTAGE_TH0) && (memcmp(g_flash_vlt_sfc_info.chip_id, + g_flash_vlt_sfc_info_tbl[2].chip_id, HI_FLASH_CHIP_ID_NUM) == HI_ERR_SUCCESS)) { // 2 + sfc_config_cmu_clk_sel(CMU_CLK_SEL_80M); + } +#endif + flash_info_print("hi_flash_write ret:%x addr:%x len:%x\r\n", ret, flash_addr, flash_write_size); + return ret; +} + +hi_u32 hi_flash_read(hi_u32 flash_addr, hi_u32 flash_read_size, hi_u8 *flash_read_data) +{ + hi_spi_flash_ctrl *spif_ctrl = &g_flash_drv_ctrl; + hi_u32 ret; + if (flash_read_data == HI_NULL) { + return HI_ERR_FLASH_INVALID_PARAMETER; + } + ret = sfc_check_para(spif_ctrl, flash_addr, flash_read_size, HI_FLASH_CHECK_PARAM_OPT_READ); + if (ret != HI_ERR_SUCCESS) { + return ret; + } +#ifdef HI_FLASH_SUPPORT_REF_VBAT + if ((g_voltage <= HI_FLASH_VOLTAGE_TH0) && (memcmp(g_flash_vlt_sfc_info.chip_id, + g_flash_vlt_sfc_info_tbl[2].chip_id, HI_FLASH_CHIP_ID_NUM) == HI_ERR_SUCCESS)) { // 2 + sfc_config_cmu_clk_sel(CMU_CLK_SEL_48M); + } +#endif + ret = flash_read_prv(spif_ctrl, flash_addr, flash_read_data, flash_read_size); +#ifdef HI_FLASH_SUPPORT_REF_VBAT + if ((g_voltage <= HI_FLASH_VOLTAGE_TH0) && (memcmp(g_flash_vlt_sfc_info.chip_id, + g_flash_vlt_sfc_info_tbl[2].chip_id, HI_FLASH_CHIP_ID_NUM) == HI_ERR_SUCCESS)) { // 2 + sfc_config_cmu_clk_sel(CMU_CLK_SEL_80M); + } +#endif + flash_info_print("hi_flash_read ret2:%x addr:%x len:%x\r\n", ret, flash_addr, flash_read_size); + return ret; +} + +hi_u32 flash_init_cfg(hi_spi_flash_ctrl *spif_ctrl, const hi_u8 *chip_id, hi_u32 idlen) +{ + hi_u32 ret; + if ((spif_ctrl == HI_NULL) || (chip_id == HI_NULL) || (idlen != HI_FLASH_CHIP_ID_NUM)) { + return HI_ERR_FAILURE; + } + flash_clk_config(); +#ifdef HI_FLASH_SUPPORT_REF_VBAT + /* set voltage vs. frequency */ + sfc_config_set_experience(chip_id, &g_flash_vlt_sfc_info, g_flash_vlt_sfc_info_tbl, + sizeof(g_flash_vlt_sfc_info_tbl) / sizeof(g_flash_vlt_sfc_info_tbl[0])); + sfc_config_update_freq((hi_u32)(uintptr_t)&g_flash_vlt_sfc_info); +#endif + /* temply compatible with MX flash chip at FPGA debug phase. */ + if (chip_id[0] == 0xC2 && chip_id[1] == 0x20 && chip_id[2] == 0x19) { /* check chip id 0,1,2 byte */ + ret = spi_flash_enable_quad_mode_mx(); + } else { + ret = spi_flash_enable_quad_mode(); + } + hi_io_set_pull(HI_IO_NAME_SFC_IO2, HI_IO_PULL_NONE); + hi_io_set_pull(HI_IO_NAME_SFC_IO3, HI_IO_PULL_NONE); + if (ret == HI_ERR_SUCCESS) { +#ifdef HI_FLASH_SUPPORT_REF_VBAT + if ((g_voltage <= HI_FLASH_VOLTAGE_TH0) && + (memcmp(chip_id, g_flash_vlt_sfc_info_tbl[2].chip_id, HI_FLASH_CHIP_ID_NUM) == HI_ERR_SUCCESS)) { /* 2 wb */ + if (memcpy_s(&spif_ctrl->opt_read, sizeof(spi_flash_operation), &g_spi_opt_fast_quad_out_read, + sizeof(spi_flash_operation), ((uintptr_t)&spif_ctrl->opt_read) ^ sizeof(spi_flash_operation) ^ + ((uintptr_t)&g_spi_opt_fast_quad_out_read) ^ sizeof(spi_flash_operation)) != EOK) { + return HI_ERR_FAILURE; + } + } else { + if (memcpy_s(&spif_ctrl->opt_read, sizeof(spi_flash_operation), &g_spi_opt_fast_quad_eb_out_read, + sizeof(spi_flash_operation), ((uintptr_t)&spif_ctrl->opt_read) ^ sizeof(spi_flash_operation) ^ + ((uintptr_t)&g_spi_opt_fast_quad_eb_out_read) ^ sizeof(spi_flash_operation)) != EOK) { + return HI_ERR_FAILURE; + } + } +#else + if (memcpy_s(&spif_ctrl->opt_read, sizeof(spi_flash_operation), &g_spi_opt_fast_quad_eb_out_read, + sizeof(spi_flash_operation), ((uintptr_t)&spif_ctrl->opt_read) ^ sizeof(spi_flash_operation) ^ + ((uintptr_t)&g_spi_opt_fast_quad_eb_out_read) ^ sizeof(spi_flash_operation)) != EOK) { + return HI_ERR_FAILURE; + } +#endif + } + /* config flash sfc after flash init. */ + spif_config(&(spif_ctrl->opt_read), spif_ctrl->opt_read.cmd, HI_TRUE); +#ifdef HI_FLASH_SUPPORT_FLASH_PROTECT + flash_protect_enable(HI_TRUE, spif_ctrl->basic_info.chip_name); +#endif + return ret; +} + +hi_u32 hi_flash_init(hi_void) +{ + hi_u32 ret; + hi_spi_flash_ctrl* spif_ctrl = &g_flash_drv_ctrl; + hi_u8 chip_id[HI_FLASH_CHIP_ID_NUM] = {0}; + hi_u32 sfc_clock; + + if (spif_ctrl->is_inited == HI_TRUE) { + return HI_ERR_FLASH_RE_INIT; + } + spif_ctrl->dma_ram_buffer = (hi_u8*)g_dma_buffer; + spif_ctrl->dma_ram_size = FLASH_DMA_RAM_SIZE; + spif_ctrl->back_up_buf = (hi_u8 *)g_back_buffer; + ret = spi_flash_basic_info_probe(spif_ctrl, chip_id, HI_FLASH_CHIP_ID_NUM, + (hi_spi_flash_basic_info*)g_flash_default_info_tbl, HI_FLASH_DEFAULT_TYPE_NUM); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + ret = flash_init_cfg(spif_ctrl, chip_id, HI_FLASH_CHIP_ID_NUM); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + spif_ctrl->is_inited = HI_TRUE; + + if (chip_id[0] == 0xC2 && chip_id[1] == 0x20 && chip_id[2] == 0x19) { /* check chip id 0,1,2 byte */ + sfc_clock = hisfc_read(SFC_REG_GLOBAL_CONFIG); + sfc_clock = sfc_clock & 0xFFFFFFE7; + sfc_clock = sfc_clock | 0x08; + hisfc_write(SFC_REG_GLOBAL_CONFIG, sfc_clock); + } + hisfc_write(SFC_REG_TIMING, 0x1); + + return ret; +} + diff --git a/sdk_liteos/boot/flashboot/drivers/gpio/SConscript b/sdk_liteos/boot/flashboot/drivers/gpio/SConscript new file mode 100755 index 0000000000000000000000000000000000000000..aceb2b6a9464ce64030c1f9c5374ec933dcab384 --- /dev/null +++ b/sdk_liteos/boot/flashboot/drivers/gpio/SConscript @@ -0,0 +1,6 @@ +Import('env') + +env = env.Clone() + +objs = env.Object(Glob('*.c')) +Return('objs') diff --git a/sdk_liteos/boot/flashboot/drivers/gpio/hi_flashboot_gpio.c b/sdk_liteos/boot/flashboot/drivers/gpio/hi_flashboot_gpio.c new file mode 100644 index 0000000000000000000000000000000000000000..78f7439ec8aa181f00a22cf6f4a14f65249fb009 --- /dev/null +++ b/sdk_liteos/boot/flashboot/drivers/gpio/hi_flashboot_gpio.c @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "hi_flashboot_gpio.h" + +#include +#include + +#define GPIO_SWPORT_DR 0x00 +#define GPIO_SWPORT_DDR 0x04 +#define GPIO_INTEN 0x30 +#define GPIO_INTMASK 0x34 +#define GPIO_INTTYPE_LEVEL 0x38 +#define GPIO_INT_POLARITY 0x3c +#define GPIO_INTSTATUS 0x40 +#define GPIO_RAWINTSTATUS 0x44 +#define GPIO_PORT_EOI 0x4c +#define GPIO_EXT_PORT 0x50 + +hi_u32 hi_gpio_get_dir(hi_gpio_idx id, hi_gpio_dir *dir) +{ + if (id >= HI_GPIO_IDX_MAX || dir == HI_NULL) { + return HI_ERR_GPIO_INVALID_PARAMETER; + } + + hi_u16 reg_val = 0; + // Obtains the input or output. The default value is 0. + hi_reg_read16((HI_GPIO_REG_BASE + GPIO_SWPORT_DDR), reg_val); + hi_io_dir_get(reg_val, (hi_u16) id, dir); + + return HI_ERR_SUCCESS; +} + +hi_u32 hi_gpio_get_output_val(hi_gpio_idx id, hi_gpio_value* val) +{ + if ((id >= HI_GPIO_IDX_MAX) || (val == HI_NULL)) { + return HI_ERR_GPIO_INVALID_PARAMETER; + } + + hi_u16 reg_val = 0; + + hi_reg_read16((HI_GPIO_REG_BASE + GPIO_SWPORT_DR), reg_val); + hi_io_val_get(reg_val, (hi_u16) id, val); + + return HI_ERR_SUCCESS; +} + +hi_u32 hi_gpio_set_output_val(hi_gpio_idx id, hi_gpio_value val) +{ + if (id >= HI_GPIO_IDX_MAX || val > HI_GPIO_VALUE1) { + return HI_ERR_GPIO_INVALID_PARAMETER; + } + + hi_u16 reg_val = 0; + + hi_reg_read16((HI_GPIO_REG_BASE + GPIO_SWPORT_DR), reg_val); + hi_io_val_set(val, (hi_u16) id, reg_val); + hi_reg_write16((HI_GPIO_REG_BASE + GPIO_SWPORT_DR), reg_val); + + return HI_ERR_SUCCESS; +} + +hi_u32 hi_gpio_get_input_val(hi_gpio_idx id, hi_gpio_value* val) +{ + if ((id >= HI_GPIO_IDX_MAX) || (val == HI_NULL)) { + return HI_ERR_GPIO_INVALID_PARAMETER; + } + hi_u16 reg_val = 0; + + hi_reg_read16((HI_GPIO_REG_BASE + GPIO_EXT_PORT), reg_val); + hi_io_val_get(reg_val, (hi_u16) id, val); + + return HI_ERR_SUCCESS; +} + +hi_u32 hi_gpio_set_dir(hi_gpio_idx id, hi_gpio_dir dir) +{ + if (id >= HI_GPIO_IDX_MAX || dir > HI_GPIO_DIR_OUT) { + return HI_ERR_GPIO_INVALID_PARAMETER; + } + hi_u16 dir_val = 0; + + hi_reg_read16((HI_GPIO_REG_BASE + GPIO_SWPORT_DDR), dir_val); + hi_io_val_set(dir, (hi_u16) id, dir_val); + hi_reg_write16((HI_GPIO_REG_BASE + GPIO_SWPORT_DDR), dir_val); + + return HI_ERR_SUCCESS; +} diff --git a/sdk_liteos/boot/flashboot/drivers/io/SConscript b/sdk_liteos/boot/flashboot/drivers/io/SConscript new file mode 100755 index 0000000000000000000000000000000000000000..aceb2b6a9464ce64030c1f9c5374ec933dcab384 --- /dev/null +++ b/sdk_liteos/boot/flashboot/drivers/io/SConscript @@ -0,0 +1,6 @@ +Import('env') + +env = env.Clone() + +objs = env.Object(Glob('*.c')) +Return('objs') diff --git a/sdk_liteos/boot/flashboot/drivers/io/hi_flashboot_io.c b/sdk_liteos/boot/flashboot/drivers/io/hi_flashboot_io.c new file mode 100644 index 0000000000000000000000000000000000000000..bbd9089668286b8db29430629701d3fb8ecbb04f --- /dev/null +++ b/sdk_liteos/boot/flashboot/drivers/io/hi_flashboot_io.c @@ -0,0 +1,113 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "hi_flashboot_io.h" + +#include + +#define GPIO_SWPORT_DR 0x00 +#define GPIO_SWPORT_DDR 0x04 +#define GPIO_EXT_PORT 0x50 +#define IO_MUX_REG_BASE_ADDR 0x604 /* Base address for the I/O function multiplexing register */ +#define IO_CTRL_REG_BASE_ADDR 0x904 /* Base address of the I/O control register, which is used to + configure the drive capability and pull-up/pull-down */ +#define IO_DRV_PULL_MASK 0x3 +#define IO_DRV_STRENGTH_MASK 0x7 +#define IO_DRV_PULL_START_BIT 8 +#define IO_DRV_STRENGTH_START_BIT 4 +#define OFFSET_10_B 10 +#define OFFSET_2_B 2 +#define IE_MSK 0x1 + +hi_u32 hi_io_get_func(hi_io_name id, hi_u8* val) +{ + if ((id >= HI_IO_NAME_MAX) || (val == HI_NULL)) { + return HI_ERR_GPIO_INVALID_PARAMETER; + } + hi_u32 reg_addr; + hi_u32 reg_val = 0; + reg_addr = HI_IOCFG_REG_BASE + IO_MUX_REG_BASE_ADDR + ((hi_u32)id << 2); /* lift shift 2 bits */ + hi_reg_read(reg_addr, reg_val); + *val = (hi_u8)reg_val; + return HI_ERR_SUCCESS; +} + +hi_u32 hi_io_get_pull(hi_io_name id, hi_io_pull* val) +{ + if ((id >= HI_IO_NAME_MAX) || (val == HI_NULL)) { + return HI_ERR_GPIO_INVALID_PARAMETER; + } + hi_u32 reg_val = 0; + hi_reg_read((HI_IOCFG_REG_BASE + IO_CTRL_REG_BASE_ADDR + ((hi_u32)id << 2)), reg_val); /* lift shift 2 bits */ + *val = (hi_io_pull) ((reg_val >> IO_DRV_PULL_START_BIT) & IO_DRV_PULL_MASK); + + return HI_ERR_SUCCESS; +} + +hi_u32 hi_io_set_driver_strength(hi_io_name id, hi_io_driver_strength val) +{ + if ((id >= HI_IO_NAME_MAX) || (val >= HI_IO_DRIVER_STRENGTH_MAX)) { + return HI_ERR_GPIO_INVALID_PARAMETER; + } + hi_u32 reg_val = 0; + + if (((id <= HI_IO_NAME_GPIO_11) || (id == HI_IO_NAME_GPIO_13) || (id == HI_IO_NAME_GPIO_14)) + && (val >= HI_IO_DRIVER_STRENGTH_4)) { + return HI_ERR_GPIO_NOT_SUPPORT; + } + hi_reg_read((HI_IOCFG_REG_BASE + IO_CTRL_REG_BASE_ADDR + ((hi_u32)id << 2)), reg_val); /* lift shift 2 bits */ + reg_val &= ~(IO_DRV_STRENGTH_MASK << IO_DRV_STRENGTH_START_BIT); + reg_val |= ((hi_u32) val & IO_DRV_STRENGTH_MASK) << IO_DRV_STRENGTH_START_BIT; + hi_reg_write((HI_IOCFG_REG_BASE + IO_CTRL_REG_BASE_ADDR + ((hi_u32)id << 2)), reg_val); /* lift shift 2 bits */ + + return HI_ERR_SUCCESS; +} + +hi_u32 hi_io_get_driver_strength(hi_io_name id, hi_io_driver_strength* val) +{ + if ((id >= HI_IO_NAME_MAX) || (val == HI_NULL)) { + return HI_ERR_GPIO_INVALID_PARAMETER; + } + hi_u32 reg_val = 0; + + hi_reg_read((HI_IOCFG_REG_BASE + IO_CTRL_REG_BASE_ADDR + ((hi_u32)id << 2)), reg_val); /* lift shift 2 bits */ + + *val = (hi_io_driver_strength) ((reg_val >> IO_DRV_STRENGTH_START_BIT) & IO_DRV_STRENGTH_MASK); + return HI_ERR_SUCCESS; +} + +hi_u32 hi_io_set_input_enable(hi_io_name id, hi_bool state) +{ + hi_u32 reg_val; + if (id >= HI_IO_NAME_MAX) { + return HI_ERR_GPIO_INVALID_PARAMETER; + } + hi_reg_read((HI_IOCFG_REG_BASE + IO_CTRL_REG_BASE_ADDR + ((hi_u32)id << OFFSET_2_B)), reg_val); + reg_val &= ~(IE_MSK << OFFSET_10_B); + reg_val |= (state & IE_MSK) << OFFSET_10_B; + hi_reg_write((HI_IOCFG_REG_BASE + IO_CTRL_REG_BASE_ADDR + ((hi_u32)id << OFFSET_2_B)), reg_val); + return HI_ERR_SUCCESS; +} + +hi_u32 hi_io_get_input_enable(hi_io_name id, hi_bool *state) +{ + hi_u32 reg_val; + if ((id >= HI_IO_NAME_MAX) || (state == HI_NULL)) { + return HI_ERR_GPIO_INVALID_PARAMETER; + } + hi_reg_read((HI_IOCFG_REG_BASE + IO_CTRL_REG_BASE_ADDR + ((hi_u32)id << OFFSET_2_B)), reg_val); + *state = (reg_val >> OFFSET_10_B) & IE_MSK; + return HI_ERR_SUCCESS; +} diff --git a/sdk_liteos/boot/flashboot/drivers/lsadc/SConscript b/sdk_liteos/boot/flashboot/drivers/lsadc/SConscript new file mode 100755 index 0000000000000000000000000000000000000000..aceb2b6a9464ce64030c1f9c5374ec933dcab384 --- /dev/null +++ b/sdk_liteos/boot/flashboot/drivers/lsadc/SConscript @@ -0,0 +1,6 @@ +Import('env') + +env = env.Clone() + +objs = env.Object(Glob('*.c')) +Return('objs') diff --git a/sdk_liteos/boot/flashboot/drivers/lsadc/adc_drv.c b/sdk_liteos/boot/flashboot/drivers/lsadc/adc_drv.c new file mode 100644 index 0000000000000000000000000000000000000000..1aa1cb93e80fdef6f30a301892d2897c03d915e8 --- /dev/null +++ b/sdk_liteos/boot/flashboot/drivers/lsadc/adc_drv.c @@ -0,0 +1,119 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "adc_drv.h" + +#include + +hi_bool adc_fifo_is_empty(hi_void) +{ + hi_u32 reg_val = hi_reg_read_val32(REG_ADC_SR); + if (reg_val & ADC_SR_RNE) { + return HI_FALSE; + } + return HI_TRUE; +} + +hi_void adc_scan_stop(hi_void) +{ + hi_reg_write(REG_ADC_STOP, ADC_SCAN_STOP); + hi_reg_write(REG_ADC_IMSC, ADC_ISR_DISABLE); + while (adc_fifo_is_empty() == HI_FALSE) { + (hi_void)hi_reg_read_val32(REG_ADC_DR); + } +} + +#define hi_reg_getbits16(addr, pos, bits) ((hi_reg_read_val16(addr) >> (pos)) & (((unsigned short)1 << (bits)) - 1)) +#define GLB_CTL_REFCLK_FEQ_START_BIT 0 +#define GLB_CTL_REFCLK_FEQ_BITS 1 + + +hi_u32 get_ref_voltage(hi_u16 *voltage) +{ + hi_u16 data = 0; + hi_u16 reg_val; + hi_u16 timeout_cnt = 0; + /* set adc clk div */ + hi_reg_read16(LS_ADC_CLK_DIV1_REG, reg_val); + reg_val &= ~(0xF << LS_ADC_CLK_DIV1_OFFSET); + if (hi_reg_getbits16(GLB_CTL_REFCLK_FEQ_STATUS_REG, GLB_CTL_REFCLK_FEQ_START_BIT, GLB_CTL_REFCLK_FEQ_BITS)) { + reg_val |= (0x7 << LS_ADC_CLK_DIV1_OFFSET); + } else { + reg_val |= (0xC << LS_ADC_CLK_DIV1_OFFSET); + } + hi_reg_write16(LS_ADC_CLK_DIV1_REG, reg_val); + /* adc power on */ + hi_reg_write(REG_ADC_EN, ADC_POWER_OFF); + udelay(1); + hi_reg_write(REG_ADC_EN, ADC_POWER_ON); + /* set basic info */ + /* + channel: 0x80 << 0 + equ_model_sel: 0x2 << 8 + rst_cnt: 0xF << 12 + adc_cfg->cur_bais: 0 << 24 + fifo_water_line: 0x6 + */ + hi_reg_write(REG_ADC_CFG, 0xf280); /* 0xf280 */ + hi_reg_write(REG_ADC_FIFO_CFG, 0x6); + /* determine is busy */ + if (hi_reg_read_val32(REG_ADC_SR) & ADC_SR_BSY) { + adc_scan_stop(); + } + /* start scan */ + hi_reg_write(REG_ADC_START, ADC_SCAN_START); + while (timeout_cnt < ADC_PER_DATA_TIMEOUT_CNT) { + if (!adc_fifo_is_empty()) { + data = (hi_u16)hi_reg_read_val32(REG_ADC_DR); + break; + } + timeout_cnt++; + udelay(ADC_LOOP_DELAY_US); + } + adc_scan_stop(); + hi_reg_write(REG_ADC_EN, ADC_POWER_OFF); /* POWER DOWN */ + if (timeout_cnt >= ADC_PER_DATA_TIMEOUT_CNT) { + return HI_ERR_TIMEOUT; + } + data = data & 0xFFF; /* 0xFFF Obtains the lower 12 bits */ + *voltage = ((hi_u32)data * 180) >> 10; /* bypass:180, flashLDO: 171 = 180*0.95,coefficients:10 Units: 0.01V */ + return HI_ERR_SUCCESS; +} + +hi_u32 get_average_ref_vlt(hi_u16 *voltage) +{ + hi_u32 ret; + hi_u16 vlt; + hi_u32 vlt_total = 0; + ret = get_ref_voltage(&vlt); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + vlt_total += vlt; + ret = get_ref_voltage(&vlt); + if (ret != HI_ERR_SUCCESS) { + *voltage = (hi_u16) vlt_total; + return HI_ERR_SUCCESS; + } + vlt_total += vlt; + ret = get_ref_voltage(&vlt); + if (ret != HI_ERR_SUCCESS) { + *voltage = (hi_u16) (vlt_total>>1); + return HI_ERR_SUCCESS; + } + vlt_total += vlt; + *voltage = (hi_u16) ((vlt_total) / 3); /* 3 */ + return HI_ERR_SUCCESS; +} \ No newline at end of file diff --git a/sdk_liteos/boot/flashboot/include/hi_boot_rom.h b/sdk_liteos/boot/flashboot/include/hi_boot_rom.h new file mode 100644 index 0000000000000000000000000000000000000000..698a4b69ac796f713af7297247fe38a5947dddbc --- /dev/null +++ b/sdk_liteos/boot/flashboot/include/hi_boot_rom.h @@ -0,0 +1,1236 @@ +/* + * @file hi_boot_rom.h + * + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** @defgroup iot_romboot BootRom */ +#ifndef _HI_BOOT_ROM_H_ +#define _HI_BOOT_ROM_H_ +#include +#include +#include +#include + +/** @defgroup iot_reg Registers APIs +* @ingroup iot_romboot +*/ +/** +* @ingroup iot_reg +* +*/ +#define hi_reg_write(addr, val) (*(volatile hi_u32*)(uintptr_t)(addr) = (val)) + +/** +* @ingroup iot_reg +* +*/ +#define hi_reg_read(addr, val) ((val) = *(volatile hi_u32*)(uintptr_t)(addr)) + +/** +* @ingroup iot_reg +* +*/ +#define hi_reg_write16(addr, val) (*(volatile hi_u16*)(uintptr_t)(addr) = (val)) + +/** +* @ingroup iot_reg +* +*/ +#define hi_reg_read16(addr, val) ((val) = *(volatile hi_u16*)(uintptr_t)(addr)) + +/** +* @ingroup iot_reg +* +*/ +#define hi_reg_read_val32(addr) (*(volatile hi_u32*)(uintptr_t)(addr)) + +/** +* @ingroup iot_reg +* +*/ +#define hi_reg_read_val16(addr) (*(volatile hi_u16*)(uintptr_t)(addr)) + +/** +* @ingroup iot_reg +* +*/ +#define hi_reg_setbitmsk(addr, msk) ((hi_reg_read_val32(addr)) |= (msk)) + +/** +* @ingroup iot_reg +* +*/ +#define hi_reg_clrbitmsk(addr, msk) ((hi_reg_read_val32(addr)) &= ~(msk)) + +/** +* @ingroup iot_reg +* +*/ +#define hi_reg_clrbit(addr, pos) ((hi_reg_read_val32(addr)) &= ~((hi_u32)(1) << (pos))) + +/** +* @ingroup iot_reg +* +*/ +#define hi_reg_setbit(addr, pos) ((hi_reg_read_val32(addr)) |= ((hi_u32)(1) << (pos))) + +/** +* @ingroup iot_reg +* +*/ +#define hi_reg_clrbits(addr, pos, bits) (hi_reg_read_val32(addr) &= ~((((hi_u32)1 << (bits)) - 1) << (pos))) + +/** +* @ingroup iot_reg +* +*/ +#define hi_reg_clrbits16(addr, pos, bits) (hi_reg_read_val16(addr) &= ~((((unsigned short)1 << (bits)) - 1) << (pos))) + +/** +* @ingroup iot_reg +* +*/ +#define hi_reg_clrbit16(addr, pos) ((hi_reg_read_val16(addr)) &= ~((unsigned short)(1) << (pos))) + +/** +* @ingroup iot_reg +* +*/ +#define hi_reg_setbit16(addr, pos) ((hi_reg_read_val16(addr)) |= ((unsigned short)(1) << (pos))) + +/** @defgroup iot_time time APIs +* @ingroup iot_romboot +*/ +/** +* @ingroup iot_time +* @brief Delay, in microseconds.CNcomment:延时,毫秒级。CNend +* +* @par 描述: +* Delay operation implemented by software based on the system clock, blocking the CPU. +CNcomment:延时操作,阻塞CPU。CNend +* +* @attention None +* +* @param msecs [IN] type #hi_u32,delay period (unit: millisecond). +CNcomment:延时时间(单位:ms)。CNend +* +* @retval None +* @par 依赖: +* @li hi_boot_rom.h:Describes BootRom APIs.CNcomment:文件包含BootRom相关接口。CNend +* @see None +*/ +hi_void mdelay(hi_u32 msecs); + +/** +* @ingroup iot_time +* @brief Delay, in microseconds.CNcomment:延时,微秒级。CNend +* +* @par 描述: +* Delay operation implemented by software based on the system clock, blocking the CPU. +CNcomment:延时操作,阻塞CPU。CNend +* +* @attention None +* +* @param usecs [IN] type #hi_u32,delay period (unit: microsecond). +CNcomment:延时时间(单位:μs)。CNend +* +* @retval None +* @par 依赖: +* @li hi_boot_rom.h:Describes BootRom APIs.CNcomment:文件包含BootRom相关接口。CNend +* @see None +*/ +hi_void udelay(hi_u32 usecs); + +extern hi_u32 memcmp(const hi_void *cs, const hi_void *ct, hi_u32 count); + +/** @defgroup iot_secure_c Secure C library APIs +* @ingroup iot_romboot +*/ +/** +* @ingroup iot_secure_c +* @brief Sets the size of the destination buffer to a specific value. +CNcomment:设置目的缓冲区为特定值。CNend +* +* @par 描述: Sets the size of the destination buffer to a specific value. +CNcomment:设置目的缓冲区为特定值。CNend +* @attention None +* +* @param dest [IN] type #hi_void *, Destination buffer.CNcomment:目的缓冲区。CNend +* @param dest_max [IN] type #hi_u32, Size of the destination buffer.CNcomment:目的缓冲区大小。CNend +* @param c [IN] type #hi_u8, Specific value.CNcomment:特定值。CNend +* @param count [IN] type #hi_u32, Number of specific values set in destination buffer. +CNcomment:目的缓冲区设置特定值的个数。CNend +* @param check_sum [IN] type #hi_u32,Exclusive or of the above four parameter values,used as security check. +* example:check_sum = (uintptr_t)dest ^ (uintptr_t)dest_max ^ (uintptr_t)c ^ (uintptr_t)count. +CNcomment:上面4个参数值的异或,用作安全检查, +示例:check_sum = (uintptr_t)dest ^ (uintptr_t)dest_max ^ (uintptr_t)c ^ (uintptr_t)count。CNend +* +* @retval #EOK Success +* @retval #Other Failure +* +* @par 依赖: +* @li hi_boot_rom.h: This file declares the APIs.CNcomment:该接口声明所在的头文件。CNend +* @see None +*/ +hi_u32 memset_s(hi_void *dest, hi_u32 dest_max, hi_u8 c, hi_u32 count, hi_u32 check_sum); + +/** +* @ingroup iot_secure_c +* @brief Copies the data from the source buffer to the destination buffer. +CNcomment:复制源缓冲区的数据到目的缓冲区。CNend +* +* @par 描述: Copies the data from the source buffer to the destination buffer. +CNcomment:复制源缓冲区的数据到目的缓冲区。CNend +* @attention None +* +* @param dest [IN] type #hi_void *, Destination buffer.CNcomment:目的缓冲区。CNend +* @param dest_max [IN] type #hi_u32, Size of the destination buffer.CNcomment:目的缓冲区大小。CNend +* @param src [IN] type #const hi_void *, Source buffer.CNcomment:源缓冲区。CNend +* @param count [IN] type #hi_u32, Number of characters copied from the source buffer. +CNcomment:从源缓冲区中复制的字符数。CNend +* @param check_sum [IN] type #hi_u32,Exclusive or of the above four parameter values,used as security check. +* example:check_sum = (uintptr_t)dest ^ (uintptr_t)dest_max ^ (uintptr_t)src ^ (uintptr_t)count. +CNcomment:上面4个参数值的异或,用作安全检查, +示例:check_sum = (uintptr_t)dest ^ (uintptr_t)dest_max ^ (uintptr_t)src ^ (uintptr_t)count。CNend +* +* @retval #EOK Success +* @retval #Other Failure +* +* @par 依赖: +* @li hi_boot_rom.h: This file declares the APIs.CNcomment:该接口声明所在的头文件。CNend +* @see None +*/ +hi_u32 memcpy_s(hi_void *dest, hi_u32 dest_max, const hi_void *src, hi_u32 count, hi_u32 check_sum); + +/** @defgroup iot_dfx Debug APIs +* @ingroup iot_romboot +*/ +/** + * @ingroup iot_dfx + * + * Print error code type, 0x3615 and its previous value cannot be modified. + CNcomment:打印错误码类型,0x3615及之前的值不可修改。CNend + */ +typedef enum { + HI_PRINT_ERRNO_UART_INIT = 0x3600, /* UART authentication initialization failed */ + HI_PRINT_ERRNO_LOADER_ERR = 0x3601, /* Failed to load loaderboot */ + HI_PRINT_ERRNO_BOOT_DECRYPT_ERR = 0x3602, /* Boot decryption failed */ + HI_PRINT_ERRNO_BOOT_LEN_ERR = 0x3603, /* Boot length check failed */ + HI_PRINT_ERRNO_BOOT_HEAD_ERR = 0x3604, /* Boot header verification failed */ + HI_PRINT_ERRNO_BOOT_SECURE_BOOT_ERR = 0x3605, /* Secure boot read failed */ + HI_PRINT_ERRNO_BOOT_ROOT_KEY_LEN_ERR = 0x3606, /* Rootkye length incorrect */ + HI_PRINT_ERRNO_BOOT_ROOT_KEY_ERR = 0x3607, /* Rootkey certificate failed */ + HI_PRINT_ERRNO_BOOT_READ_ENCPT_ERR = 0x3608, /* Secure flag read failed */ + HI_PRINT_ERRNO_BOOT_SUB_KEY_LEN_ERR = 0x3609, /* Subkey length incorrect */ + HI_PRINT_ERRNO_BOOT_SUB_KEY_CAT_ERR = 0x360A, /* Subkey category is incorrect */ + HI_PRINT_ERRNO_BOOT_SUB_KEY_RSIM_ERR = 0x360B, /* Subkey rsim verification failed */ + HI_PRINT_ERRNO_BOOT_SUB_KEY_ERR = 0x360C, /* Subkey authentication failed */ + HI_PRINT_ERRNO_BOOT_CODE_VERIFY_ERR = 0x360D, /* Code verification failed */ + HI_PRINT_ERRNO_BOOT_DIE_ID_ERR = 0x360E, /* Die ID verification failed */ + HI_PRINT_ERRNO_BOOT_VER_ERR = 0x360F, /* Flash boot version number verification failed */ + HI_PRINT_ERRNO_BOOT_GET_TAIL_ERR = 0x3610, /* Failed to get flash tail address */ + HI_PRINT_ERRNO_BOOT_BACKUP_TAIL_ERR = 0x3611, /* Backup flash boot magic word and length verification failed */ + HI_PRINT_ERRNO_BOOT_MAIN_CHECK_ERR = 0x3612, /* Fail to check the integrity of the main flashboot + in non-secure boot */ + HI_PRINT_ERRNO_BOOT_BACKUP_CHECK_ERR = 0x3613, /* Fail to check the integrity of the backup flashboot + in non-secure boot */ + HI_PRINT_ERRNO_MALLOC_EXAUST_ERR = 0x3614, /* Out of heap memory */ + HI_PRINT_ERRNO_MALLOC_STRUCT_ERR = 0x3615, /* Heap memory management structure destroyed */ + HI_PRINT_ERRNO_NO_ENCPT_CNT_LEFT_ERR = 0x3616, /* Flash encryption burn out times */ + HI_PRINT_ERRNO_CRYPTO_PREPARE_ERR = 0x3617, /* Flash encryption and decryption preparation failed */ + HI_PRINT_ERRNO_CRYPTO_KEY_EMPTY_ERR = 0x3618, /* Flash encryption and decryption work key is empty */ + HI_PRINT_ERRNO_CRYPTO_KEY_INVALID_ERR = 0x3619, /* Flash encryption and decryption work key is invalid */ + HI_PRINT_ERRNO_CRYPTO_KEY_SAVE_ERR = 0x361A, /* Flash encryption and decryption work key save failed */ + HI_PRINT_ERRNO_CRYPTO_KEY_DECRYPT_ERR = 0x361B, /* Flash encryption and decryption work key decryption failed */ + HI_PRINT_ERRNO_CRYPTO_FW_DECRYPT_ERR = 0x361C, /* Flash encryption and decryption kernel encryption failed */ + HI_PRINT_ERRNO_CRYPTO_FW_ENCRYPT_ERR = 0x361D, /* Flash encryption and decryption kernel decryption failed */ + HI_PRINT_ERRNO_CRYPTO_NV_ENCRYPT_ERR = 0x361E, /* Flash encryption and decryption NV area encryption failed */ + HI_PRINT_ERRNO_CRYPTO_CHECK_KERNEL_ERR = 0x361F, /* Flash encryption and decryption check kernel failed */ + HI_PRINT_ERRNO_CRYPTO_KERNEL_ADDR_ERR = 0x3620, /* Flash encryption and decryption check kernel addr failed */ + HI_PRINT_ERRNO_UPG_CRYPTO_PREPARE_ERR = 0x3621, /* Upg file decryption preparation failed */ + HI_PRINT_ERRNO_UPG_CRYPTO_DECRYPT_ERR = 0x3622, /* Upg file decryption failed */ + HI_PRINT_ERRNO_CRYPTO_SALT_EMPTY_ERR = 0x3623, /* Flash encryption and decryption root key salt is empty */ + HI_PRINT_ERRNO_IDX_MAX, /* Error code type maximum */ +} hi_print_errno; + +/** +* @ingroup iot_dfx +* @brief The error code is forced to be printed out in romboot. The hi_print_errno definition cannot be modified. +CNcomment:romboot中强制打印输出错误码,不可修改hi_print_errno定义。CNend +* +* @par 描述: +* Force to print out error codes to help users locate errors. +CNcomment:强制打印输出错误码,帮助用户定位错误。CNend +* +* @attention None. +* +* @param print_errno [IN] type #hi_u32, error code. +* +* @retval None. +* @par 依赖: +* @li hi_boot_rom.h:Describes Boot APIs.CNcomment:文件用于描述Boot模块接口。CNend +* @see boot_puthex|boot_msg0|boot_msg1|boot_msg2|boot_msg4. +*/ +hi_void boot_put_errno(hi_u32 print_errno); + +/** +* @ingroup iot_dfx +* @brief Output hexadecimal number.CNcomment:输出16进制数。CNend +* +* @par 描述: +* Output hexadecimal number.CNcomment:输出16进制数。CNend +* +* @attention None. +* +* @param h [IN] type #hi_u32, Hexadecimal number to output. +* @param print0 [IN] type #hi_bool, HI_TRUE: fill 0 to 4 bytes when printing. HI_FALSE: do not fill 0 alignment. +* +* @retval None. +* @par 依赖: +* @li hi_boot_rom.h:Describes Boot APIs.CNcomment:文件用于描述Boot模块接口。CNend +* @see boot_put_errno|boot_msg0|boot_msg1|boot_msg2|boot_msg4. +*/ +hi_void boot_puthex(hi_u32 h, hi_bool print0); + +/** +* @ingroup iot_dfx +* @brief Printout information, string only.CNcomment:打印输出信息,只输出字符串。CNend +* +* @par 描述: +* Printout information, string only.CNcomment:打印输出信息,只输出字符串。CNend +* +* @attention None. +* +* @param s [IN] type #hi_char*, String to output. +* +* @retval None. +* @par 依赖: +* @li hi_boot_rom.h:Describes Boot APIs.CNcomment:文件用于描述Boot模块接口。CNend +* @see boot_put_errno|boot_puthex|boot_msg1|boot_msg2|boot_msg4. +*/ +hi_void boot_msg0(const hi_char *s); + +/** +* @ingroup iot_dfx +* @brief Print out information, output string and 1 values.CNcomment:打印输出信息,输出字符串及1个数值。CNend +* +* @par 描述: +* Print out information, output string and 1 values.CNcomment:打印输出信息,输出字符串及1个数值。CNend +* +* @attention None. +* +* @param s [IN] type #hi_char*, String to output. +* @param h [IN] type #hi_u32, Value to be output, hexadecimal. +* +* @retval None. +* @par 依赖: +* @li hi_boot_rom.h:Describes Boot APIs.CNcomment:文件用于描述Boot模块接口。CNend +* @see boot_put_errno|boot_puthex|boot_msg0|boot_msg2|boot_msg4. +*/ +hi_void boot_msg1(const hi_char *s, hi_u32 h); + +/** +* @ingroup iot_dfx +* @brief Print out information, output string and 2 values.CNcomment:打印输出信息,输出字符串及2个数值。CNend +* +* @par 描述: +* Print out information, output string and 2 values.CNcomment:打印输出信息,输出字符串及2个数值。CNend +* +* @attention None. +* +* @param s [IN] type #hi_char*, String to output. +* @param h1 [IN] type #hi_u32, Value to be output 1, hexadecimal. +* @param h2 [IN] type #hi_u32, Value to be output 2, hexadecimal. +* +* @retval None. +* @par 依赖: +* @li hi_boot_rom.h:Describes Boot APIs.CNcomment:文件用于描述Boot模块接口。CNend +* @see boot_put_errno|boot_puthex|boot_msg0|boot_msg1|boot_msg4. +*/ +hi_void boot_msg2(const hi_char *s, hi_u32 h1, hi_u32 h2); + +/** +* @ingroup iot_dfx +* @brief Print out information, output string and 4 values.CNcomment:打印输出信息,输出字符串及4个数值。CNend +* +* @par 描述: +* Print out information, output string and 4 values.CNcomment:打印输出信息,输出字符串及4个数值。CNend +* +* @attention None. +* +* @param s [IN] type #hi_char*, String to output. +* @param h1 [IN] type #hi_u32, Value to be output 1, hexadecimal. +* @param h2 [IN] type #hi_u32, Value to be output 2, hexadecimal. +* @param h3 [IN] type #hi_u32, Value to be output 3, hexadecimal. +* @param h4 [IN] type #hi_u32, Value to be output 4, hexadecimal. +* +* @retval None. +* @par 依赖: +* @li hi_boot_rom.h:Describes Boot APIs.CNcomment:文件用于描述Boot模块接口。CNend +* @see boot_put_errno|boot_puthex|boot_msg0|boot_msg1|boot_msg2. +*/ +hi_void boot_msg4(const hi_char *s, hi_u32 h1, hi_u32 h2, hi_u32 h3, hi_u32 h4); + +/** @defgroup iot_uart Uart APIs +* @ingroup iot_romboot +*/ +/** + * @ingroup iot_uart + * + * Uart ID. CNcomment:串口号。CNend + */ +typedef enum { + UART0 = 0, /* uart0 */ + UART1 = 1, /* uart1 */ + UART2 = 2, /* uart2 */ + UART_MAX = 3, +} hi_uart; + +/** + * @ingroup iot_uart + * + * Uart parameter struct. CNcomment:串口参数结构体。CNend + */ +typedef struct { + hi_u32 baudrate; /* Baud rate */ + hi_uchar databit; /* 5; 6; 7; 8 */ + hi_uchar stopbit; /* 1:stop_bit 1; 2: stop_bit 2. */ + hi_uchar parity; /* 0: None; 1:Odd; 2:Even */ + hi_uchar flow_ctrl; /* 0: None; 1:rts&&cts. 2:only rts; 3:only cts */ + hi_uchar fifoline_tx_int; /* 0:tx FIFO≤1/8full; 1:tx FIFO≤1/4full; 2:tx FIFO≤1/2full; + 3:tx FIFO≤3/4full; 4:tx FIFO≤7/8full */ + hi_uchar fifoline_rx_int; /* 0:rx FIFO≥1/8full; 1:rx FIFO≥1/4full; 2:rx FIFO≥1/2full; + 3:rx FIFO≥3/4full; 4:rx FIFO≥7/8full */ + hi_uchar fifoline_rts; /* 0:rx FIFO≥1/8full; 1:rx FIFO≥1/4full; 2:rx FIFO≥1/2full; + 3:rx FIFO≥3/4full; 4:rx FIFO≥7/8full */ + hi_uchar pad; +} uart_param_stru; + +/** +* @ingroup iot_uart +* @brief Serial output forbidden.CNcomment:串口输出禁言。CNend +* +* @par 描述: +* Serial output forbidden.CNcomment:串口输出禁言。CNend +* +* @attention None. +* +* @param None. +* +* @retval None. +* @par 依赖: +* @li hi_boot_rom.h:Describes Boot APIs.CNcomment:文件用于描述Boot模块接口。CNend +* @see serial_cancel_mute. +*/ +hi_void serial_set_mute(hi_void); + +/** +* @ingroup iot_uart +* @brief Cancel serial output forbidden.CNcomment:串口输出取消禁言。CNend +* +* @par 描述: +* Cancel serial output forbidden.CNcomment:串口输出取消禁言。CNend +* +* @attention None. +* +* @param None. +* +* @retval None. +* @par 依赖: +* @li hi_boot_rom.h:Describes Boot APIs.CNcomment:文件用于描述Boot模块接口。CNend +* @see serial_set_mute. +*/ +hi_void serial_cancel_mute(hi_void); + +/** +* @ingroup iot_uart +* @brief Serial port initialization.CNcomment:串口初始化。CNend +* +* @par 描述: +* Serial port initialization.CNcomment:串口初始化。CNend +* +* @attention None. +* +* @param uart_num [IN] type #hi_uart, Uart ID. +* @param default_uart_param [IN] type #uart_param_stru, Uart parameters. +* +* @retval #HI_ERR_FAILURE Failure. +* @retval #HI_ERR_SUCCESS Success. +* @par 依赖: +* @li hi_boot_rom.h:Describes Boot APIs.CNcomment:文件用于描述Boot模块接口。CNend +* @see serial_init|serial_putc|serial_puts|serial_put_buf|serial_getc|serial_tstc|serial_puthex。 +*/ +hi_u32 serial_init(hi_uart uart_num, uart_param_stru default_uart_param); + +/** +* @ingroup iot_uart +* @brief Serial output single character.CNcomment:串口输出单个字符。CNend +* +* @par 描述: +* Serial output single character.CNcomment:串口输出单个字符。CNend +* +* @attention None. +* +* @param c [IN] type #const hi_char, Char to output. +* +* @retval None. +* @par 依赖: +* @li hi_boot_rom.h:Describes Boot APIs.CNcomment:文件用于描述Boot模块接口。CNend +* @see serial_init|serial_putc|serial_puts|serial_put_buf|serial_getc|serial_tstc|serial_puthex。 +*/ +hi_void serial_putc(const hi_char c); + +/** +* @ingroup iot_uart +* @brief Serial output string.CNcomment:串口输出字符串。CNend +* +* @par 描述: +* Serial output string.CNcomment:串口输出字符串。CNend +* +* @attention None. +* +* @param s [IN] type #const hi_char*, String to output. +* +* @retval None. +* @par 依赖: +* @li hi_boot_rom.h:Describes Boot APIs.CNcomment:文件用于描述Boot模块接口。CNend +* @see serial_init|serial_putc|serial_puts|serial_put_buf|serial_getc|serial_tstc|serial_puthex。 +*/ +hi_void serial_puts(const hi_char *s); + +/** +* @ingroup iot_uart +* @brief Serial output character buffer, specify buffer length.CNcomment:串口输出字符缓冲区,指定缓冲区长度。CNend +* +* @par 描述: +* Serial output character buffer, specify buffer length.CNcomment:串口输出字符缓冲区,指定缓冲区长度。CNend +* +* @attention The difference between the serial_puts() function is that the serial_puts function is for strings and +* stops the output when '\ 0' is encountered. However, this interface is not affected by '\ 0' for a +* specified length of character buffer.CNcomment:与serial_puts()函数的区别是:serial_puts函数是针对字符串, +* 遇到'\0'后停止输出;而本接口针对指定长度的字符缓冲区,不受'\0'影响。CNend +* @param buffer [IN] type #const hi_char*, String to output. +* @param length [IN] type #hi_s32, Length of string to be output. +* +* @retval None. +* @par 依赖: +* @li hi_boot_rom.h:Describes Boot APIs.CNcomment:文件用于描述Boot模块接口。CNend +* @see serial_init|serial_putc|serial_puts|serial_put_buf|serial_getc|serial_tstc|serial_puthex。 +*/ +hi_void serial_put_buf(const hi_char *buffer, hi_s32 length); + +/** +* @ingroup iot_uart +* @brief Read a character from the serial port.CNcomment:从串口读取一个字符。CNend +* +* @par 描述: +* Read a character from the serial port.CNcomment:从串口读取一个字符。CNend +* +* @attention This function is a blocking interface. If the serial port does not receive characters, it will wait. +CNcomment:本函数为阻塞接口,如果串口没有接收到字符,会一直等待。CNend +* @param None. +* +* @retval #Character Characters read from serial port. +* @retval #-1 Failure. +* @par 依赖: +* @li hi_boot_rom.h:Describes Boot APIs.CNcomment:文件用于描述Boot模块接口。CNend +* @see serial_init|serial_putc|serial_puts|serial_put_buf|serial_getc|serial_tstc|serial_puthex。 +*/ +hi_u8 serial_getc(hi_void); + +/** +* @ingroup iot_uart +* @brief Whether the serial port has characters to be received.CNcomment:串口是否有字符待接收。CNend +* +* @par 描述: +* Whether the serial port has characters to be received.CNcomment:串口是否有字符待接收。CNend +* +* @attention None. +* @param None. +* +* @retval #0 Not received date from serial port. +* @retval #1 Received date from serial port. +* @par 依赖: +* @li hi_boot_rom.h:Describes Boot APIs.CNcomment:文件用于描述Boot模块接口。CNend +* @see serial_init|serial_putc|serial_puts|serial_put_buf|serial_getc|serial_tstc|serial_puthex。 +*/ +hi_s32 serial_tstc(hi_void); + +/** +* @ingroup iot_uart +* @brief Output hexadecimal number to serial port.CNcomment:向串口输出16进制数。CNend +* +* @par 描述: +* 向串口输出16进制数.CNcomment:向串口输出16进制数。CNend +* +* @attention None. +* @param h [IN] type #hi_u32,Hexadecimal number to be output.CNcomment:待输出的16进制数。CNend +* @param print_all [IN] type #hi_u8 *,Whether to fill in 0, Align according to 4 bytes. 1 : fill, 0 : not to fill. +CNcomment:打印时前面是否补0,按照4字节对齐,1表示补,0表示不补。CNend +* +* @retval None. +* @par 依赖: +* @li hi_boot_rom.h:Describes Boot APIs.CNcomment:文件用于描述Boot模块接口。CNend +* @see serial_init|serial_putc|serial_puts|serial_put_buf|serial_getc|serial_tstc|serial_puthex。 +*/ +hi_void serial_puthex(hi_u32 h, hi_bool print_all); + +/** +* @ingroup iot_uart +* @brief Read a character from the serial port, and end if it is not read after waiting for the specified time. +CNcomment:从串口读取一个字符,等待指定时间后没有读到则结束。CNend +* +* @par 描述: +* Read a character from the serial port, and end if it is not read after waiting for the specified time. +CNcomment:从串口读取一个字符,等待指定时间后没有读到则结束。CNend +* +* @attention None. +* @param timeout_us [IN] type #hi_u32,Specify timeout in us.CNcomment:指定超时时间,单位:us。CNend +* @param ch [IN] type #hi_u8 *,Output character.CNcomment:输出字符。CNend +* +* @retval #HI_ERR_FAILURE Failure. +* @retval #HI_ERR_SUCCESS Success. +* @par 依赖: +* @li hi_boot_rom.h:Describes Boot APIs.CNcomment:文件用于描述Boot模块接口。CNend +* @see serial_init|serial_putc|serial_puts|serial_put_buf|serial_getc|serial_tstc|serial_puthex。 +*/ +hi_u32 serial_getc_timeout(hi_u32 timeout_us, hi_u8 *ch); + +/** @defgroup iot_mem Memory APIs +* @ingroup iot_romboot +*/ +/** +* @ingroup iot_mem +* +* Dynamic memory management module initialization interface function pointer. +CNcomment:动态内存管理模块初始化接口函数指针。CNend +*/ +typedef hi_void (*malloc_init_func)(hi_u32 heap_start_addr, hi_u32 heap_end_addr, hi_u32 check_sum); + +/** +* @ingroup iot_mem +* +* Request dynamic memory interface function pointer.CNcomment:申请动态内存接口函数指针。CNend +*/ +typedef hi_void *(*malloc_func)(hi_u32 size); + +/** +* @ingroup iot_mem +* +* Release dynamic memory interface function pointer.CNcomment:释放动态内存接口函数指针。CNend +*/ +typedef hi_u32 (*free_func)(hi_void *addr); + +/** +* @ingroup iot_mem +* +* Input parameter of hi_register_malloc interface. +*/ +typedef struct { + malloc_init_func init; /* Initialize heap memory interface */ + malloc_func boot_malloc; /* Request heap memory interface */ + free_func boot_free; /* Release heap memory interface */ +} hi_malloc_func; + +/** +* @ingroup iot_mem +* @brief To register malloc management related functions, be sure to register before using other interfaces. +CNcomment:注册malloc管理相关函数,务必先注册再使用其他接口。CNend +* +* @par 描述: +* Support users to adapt memory management functions.CNcomment:支持用户自己适配内存管理函数。CNend +* +* @attention None. +* @param addr [IN] type #uintptr_t,Heap start address.CNcomment:堆空间起始地址。CNend +* @param funcs [IN] type #const hi_malloc_func *,Request memory related interface register structure pointer. +CNcomment:申请内存相关接口注册结构体指针。CNend +* +* @retval #HI_ERR_FAILURE Failure. +* @retval #HI_ERR_SUCCESS Success. +* @par 依赖: +* @li hi_boot_rom.h:Describes Boot APIs.CNcomment:文件用于描述Boot模块接口。CNend +* @see boot_malloc_init|boot_malloc|boot_free。 +*/ +hi_u32 hi_register_malloc(uintptr_t addr, const hi_malloc_func *funcs); + +/** +* @ingroup iot_mem +* @brief Heap initialize.CNcomment:堆空间初始化。CNend +* +* @par 描述: +* Heap initialize.CNcomment:堆空间初始化。CNend +* +* @attention None. +* @param heap_start_addr [IN] type #uintptr_t,Heap start address.CNcomment:堆空间起始地址。CNend +* @param heap_end_addr [IN] type #uintptr_t,Heap end address.CNcomment:堆空间结束地址。CNend +* @param check_sum [IN] type #hi_u32,Exclusive or of start address and end address. +CNcomment:起始地址与结束地址的异或。CNend +* +* @retval #HI_ERR_FAILURE Failure. +* @retval #HI_ERR_SUCCESS Success. +* @par 依赖: +* @li hi_boot_rom.h:Describes Boot APIs.CNcomment:文件用于描述Boot模块接口。CNend +* @see boot_malloc_init。 +*/ +hi_void boot_malloc_init(uintptr_t heap_start_addr, uintptr_t heap_end_addr, hi_u32 check_sum); + +/** +* @ingroup iot_mem +* @brief Dynamically applies for memory.CNcomment:动态申请内存。CNend +* +* @par 描述: +* Dynamically applies for memory.CNcomment:动态申请内存。CNend +* +* @attention None. +* @param size [IN] type #hi_u32,Requested memory size (unit: byte) +CNcomment:申请内存大小(单位:byte)。CNend +* +* @retval #Other Success +* @retval #HI_NULL Failure. The memory is insufficient. +* @par 依赖: +* @li hi_boot_rom.h:Describes memory APIs.CNcomment:文件用于描述内存相关接口。CNend +* @see boot_free。 +*/ +hi_void *boot_malloc(hi_u32 size); + +/** +* @ingroup iot_mem +* @brief Releases the memory that is dynamically applied for.CNcomment:释放动态申请的内存。CNend +* +* @par 描述: +* Releases the memory that is dynamically applied for.CNcomment:释放动态申请的内存。CNend +* +* @attention None. +* @param addr [IN] type #hi_void *,Start address of the requested memory. The validity of the address is ensured +* by the caller.CNcomment:所申请内存的首地址,地址合法性由调用者保证。CNend +* +* @retval None. +* @par 依赖: +* @li hi_boot_rom.h:Describes memory APIs.CNcomment:文件用于描述内存相关接口。CNend +* @see boot_malloc。 +*/ +hi_u32 boot_free(hi_void *addr); + +/** @defgroup iot_watchdog Watchdog APIs + * @ingroup iot_romboot + */ +/** + * @ingroup iot_watchdog + * The default watchdog configuration time is 26 seconds. The time cannot be modified after romboot is started, + users can call hi_watchdog_enable interface to reconfigure in flashboot.CNcomment:默认看门狗配置时间为26秒。 + romboot启动后时间不可以修改,用户可以在flashboot中调用hi_watchdog_enable接口重新配置。CNend + */ +#define WDG_TIME_US 26000000 /* 默认看门狗配置时间为26秒 */ + +/** +* @ingroup iot_watchdog +* @brief Enables the watchdog.CNcomment:使能看门狗。CNend +* +* @par 描述: +* Enables the watchdog.CNcomment:使能看门狗。CNend +* +* @attention None +* @param None +* +* @retval None +* @par 依赖: +* @li hi_boot_rom.h:describes the watchdog APIs.CNcomment:文件用于描述看门狗相关接口。CNend +* @see None +*/ +hi_void hi_watchdog_enable(hi_u32 over_time_us); + +/** +* @ingroup iot_watchdog +* @brief Feeds the watchdog.CNcomment:喂狗。CNend +* +* @par 描述: Feeds the watchdog.CNcomment:喂狗。CNend +* +* @attention None +* @param None +* +* @retval None +* @par 依赖: +* @li hi_boot_rom.h:describes the watchdog APIs.CNcomment:文件用于描述看门狗相关接口。CNend +* @see None +*/ +hi_void hi_watchdog_feed(hi_void); + +/** +* @ingroup iot_watchdog +* @brief Disables the watchdog.CNcomment:关闭看门狗。CNend +* +* @par 描述: +* @li Disable the clock enable control of the watchdog.CNcomment:禁止WatchDog时钟使能控制位。CNend +* @li Mask the watchdog reset function.CNcomment:屏蔽WatchDog复位功能。CNend +* +* @attention None +* @param None +* +* @retval None +* @par 依赖: +* @li hi_boot_rom.h:describes the watchdog APIs.CNcomment:文件用于描述看门狗相关接口。CNend +* @see None +*/ +hi_void hi_watchdog_disable(hi_void); + +/** @defgroup iot_crc16 CRC16 APIs +* @ingroup iot_romboot +*/ +/** +* @ingroup iot_crc16 +* @brief Generates a 16-bit CRC value.CNcomment:生成16位CRC校验值。CNend +* +* @par 描述: +* Generates a 16-bit CRC value.CNcomment:生成16位CRC校验值。CNend +* +* @attention None +* @param crc_start [IN] type #hi_u16,The CRC initial value.CNcomment:CRC初始值。CNend +* @param buf [IN] type #hi_u8*,Pointer to the buffer to be verified. +CNcomment:被校验Buffer指针。CNend +* @param len [IN] type #hi_u32,Length of the buffer to be verified (unit: Byte). +CNcomment:被校验Buffer长度(单位:byte)。CNend +* +* @retval #HI_ERR_SUCCESS Success +* @retval #Other Failure. For details, see hi_boot_err.h. +* +* @par 依赖: +* @li hi_boot_rom.h:Describes CRC APIs.CNcomment:文件包含CRC校验接口。CNend +* @see None +*/ +hi_u16 hi_crc16(hi_u16 crc_start, hi_u8 *buf, hi_u32 len); + +/** @defgroup iot_io IO APIs + * @ingroup iot_romboot + */ +/** +* @ingroup iot_io +* +* GPIO ID. +*/ +typedef enum { + HI_GPIO_IDX_0, /* GPIO0 */ + HI_GPIO_IDX_1, /* GPIO1 */ + HI_GPIO_IDX_2, /* GPIO2 */ + HI_GPIO_IDX_3, /* GPIO3 */ + HI_GPIO_IDX_4, /* GPIO4 */ + HI_GPIO_IDX_5, /* GPIO5 */ + HI_GPIO_IDX_6, /* GPIO6 */ + HI_GPIO_IDX_7, /* GPIO7 */ + HI_GPIO_IDX_8, /* GPIO8 */ + HI_GPIO_IDX_9, /* GPIO9 */ + HI_GPIO_IDX_10, /* GPIO10 */ + HI_GPIO_IDX_11, /* GPIO11 */ + HI_GPIO_IDX_12, /* GPIO12 */ + HI_GPIO_IDX_13, /* GPIO13 */ + HI_GPIO_IDX_14, /* GPIO14 */ + HI_GPIO_IDX_MAX, /* Maximum value, cannot be used. CNcomment:最大值,不可输入使用。CNend */ +} hi_gpio_idx; + +/** + * @ingroup iot_io + * + * GPIO pin ID. CNcomment:IO硬件管脚编号。CNend + */ +typedef enum { + HI_IO_NAME_GPIO_0, /* GPIO0 */ + HI_IO_NAME_GPIO_1, /* GPIO1 */ + HI_IO_NAME_GPIO_2, /* GPIO2 */ + HI_IO_NAME_GPIO_3, /* GPIO3 */ + HI_IO_NAME_GPIO_4, /* GPIO4 */ + HI_IO_NAME_GPIO_5, /* GPIO5 */ + HI_IO_NAME_GPIO_6, /* GPIO6 */ + HI_IO_NAME_GPIO_7, /* GPIO7 */ + HI_IO_NAME_GPIO_8, /* GPIO8 */ + HI_IO_NAME_GPIO_9, /* GPIO9 */ + HI_IO_NAME_GPIO_10, /* GPIO10 */ + HI_IO_NAME_GPIO_11, /* GPIO11 */ + HI_IO_NAME_GPIO_12, /* GPIO12 */ + HI_IO_NAME_GPIO_13, /* GPIO13 */ + HI_IO_NAME_GPIO_14, /* GPIO14 */ + HI_IO_NAME_SFC_CSN, /* SFC_CSN */ + HI_IO_NAME_SFC_IO1, /* SFC_IO1 */ + HI_IO_NAME_SFC_IO2, /* SFC_IO2 */ + HI_IO_NAME_SFC_IO0, /* SFC_IO0 */ + HI_IO_NAME_SFC_CLK, /* SFC_CLK */ + HI_IO_NAME_SFC_IO3, /* SFC_IO3 */ + HI_IO_NAME_MAX, +} hi_io_name; + +/** + * @ingroup iot_io + * + * GPIO pull-up configuration.CNcomment:IO上下拉功能CNend + */ +typedef enum { + HI_IO_PULL_NONE, /* No pull. CNcomment:无拉。CNend */ + HI_IO_PULL_UP, /* pull up. CNcomment:上拉。CNend */ + HI_IO_PULL_DOWN, /* pull down. CNcomment:下拉。CNend */ + HI_IO_PULL_MAX, /* Invalid value. CNcomment:无效值。CNend */ +} hi_io_pull; + +/** + * @ingroup iot_io + * + * GPIO_0 pin function.CNcomment:GPIO_0管脚功能。CNend + */ +typedef enum { + HI_IO_FUNC_GPIO_0_GPIO, + HI_IO_FUNC_GPIO_0_UART1_TXD = 2, + HI_IO_FUNC_GPIO_0_SPI0_CK, + HI_IO_FUNC_GPIO_0_JTAG_TDO, + HI_IO_FUNC_GPIO_0_PWM3_OUT, + HI_IO_FUNC_GPIO_0_I2C1_SDA, +} hi_io_func_gpio_0; + +/** +* @ingroup iot_io +* +* GPIO_1 pin function.CNcomment:GPIO_1管脚功能。CNend +*/ +typedef enum { + HI_IO_FUNC_GPIO_1_GPIO, + HI_IO_FUNC_GPIO_1_UART1_RXD = 2, + HI_IO_FUNC_GPIO_1_SPI0_RXD, + HI_IO_FUNC_GPIO_1_JTAG_TCK, + HI_IO_FUNC_GPIO_1_PWM4_OUT, + HI_IO_FUNC_GPIO_1_I2C1_SCL, + HI_IO_FUNC_GPIO_1_BT_FREQ, +} hi_io_func_gpio_1; + +/** +* @ingroup iot_io +* +* GPIO_2 pin function.CNcomment:GPIO_2管脚功能。CNend +*/ +typedef enum { + HI_IO_FUNC_GPIO_2_GPIO, + HI_IO_FUNC_GPIO_2_UART1_RTS_N = 2, + HI_IO_FUNC_GPIO_2_SPI0_TXD, + HI_IO_FUNC_GPIO_2_JTAG_TRSTN, + HI_IO_FUNC_GPIO_2_PWM2_OUT, + HI_IO_FUNC_GPIO_2_SSI_CLK = 7, +} hi_io_func_gpio_2; + +/** +* @ingroup iot_io +* +* GPIO_3 pin function.CNcomment:GPIO_3管脚功能。CNend +*/ +typedef enum { + HI_IO_FUNC_GPIO_3_GPIO, + HI_IO_FUNC_GPIO_3_UART0_TXD, + HI_IO_FUNC_GPIO_3_UART1_CTS_N, + HI_IO_FUNC_GPIO_3_SPI0_CSN, + HI_IO_FUNC_GPIO_3_JTAG_TDI, + HI_IO_FUNC_GPIO_3_PWM5_OUT, + HI_IO_FUNC_GPIO_3_I2C1_SDA, + HI_IO_FUNC_GPIO_3_SSI_DATA, +} hi_io_func_gpio_3; + +/** +* @ingroup iot_io +* +* GPIO_4 pin function.CNcomment:GPIO_4管脚功能。CNend +*/ +typedef enum { + HI_IO_FUNC_GPIO_4_GPIO, + HI_IO_FUNC_GPIO_4_UART0_RXD = 2, + HI_IO_FUNC_GPIO_4_JTAG_TMS = 4, + HI_IO_FUNC_GPIO_4_PWM1_OUT, + HI_IO_FUNC_GPIO_4_I2C1_SCL, +} hi_io_func_gpio_4; + +/** +* @ingroup iot_io +* +* GPIO_5 pin function.CNcomment:GPIO_5管脚功能。CNend +*/ +typedef enum { + HI_IO_FUNC_GPIO_5_GPIO, + HI_IO_FUNC_GPIO_5_UART1_RXD = 2, + HI_IO_FUNC_GPIO_5_SPI0_CSN, + HI_IO_FUNC_GPIO_5_PWM2_OUT = 5, + HI_IO_FUNC_GPIO_5_I2S0_MCLK, + HI_IO_FUNC_GPIO_5_BT_STATUS, +} hi_io_func_gpio_5; + +/** +* @ingroup iot_io +* +* GPIO_6 pin function.CNcomment:GPIO_6管脚功能。CNend +*/ +typedef enum { + HI_IO_FUNC_GPIO_6_GPIO, + HI_IO_FUNC_GPIO_6_UART1_TXD = 2, + HI_IO_FUNC_GPIO_6_SPI0_CK, + HI_IO_FUNC_GPIO_6_PWM3_OUT = 5, + HI_IO_FUNC_GPIO_6_I2S0_TX, + HI_IO_FUNC_GPIO_6_COEX_SWITCH, +} hi_io_func_gpio_6; + +/** +* @ingroup iot_io +* +* GPIO_7 pin function.CNcomment:GPIO_7管脚功能。CNend +*/ +typedef enum { + HI_IO_FUNC_GPIO_7_GPIO, + HI_IO_FUNC_GPIO_7_UART1_CTS_N = 2, + HI_IO_FUNC_GPIO_7_SPI0_RXD, + HI_IO_FUNC_GPIO_7_PWM0_OUT = 5, + HI_IO_FUNC_GPIO_7_I2S0_BCLK, + HI_IO_FUNC_GPIO_7_BT_ACTIVE, +} hi_io_func_gpio_7; + +/** +* @ingroup iot_io +* +* GPIO_8 pin function.CNcomment:GPIO_8管脚功能。CNend +*/ +typedef enum { + HI_IO_FUNC_GPIO_8_GPIO, + HI_IO_FUNC_GPIO_8_UART1_RTS_N = 2, + HI_IO_FUNC_GPIO_8_SPI0_TXD, + HI_IO_FUNC_GPIO_8_PWM1_OUT = 5, + HI_IO_FUNC_GPIO_8_I2S0_WS, + HI_IO_FUNC_GPIO_8_WLAN_ACTIVE, +} hi_io_func_gpio_8; + +/** +* @ingroup iot_io +* +* GPIO_9 pin function.CNcomment:GPIO_9管脚功能。CNend +*/ +typedef enum { + HI_IO_FUNC_GPIO_9_GPIO, + HI_IO_FUNC_GPIO_9_I2C0_SCL, + HI_IO_FUNC_GPIO_9_UART2_RTS_N, + HI_IO_FUNC_GPIO_9_SDIO_D2, + HI_IO_FUNC_GPIO_9_SPI1_TXD, + HI_IO_FUNC_GPIO_9_PWM0_OUT, + HI_IO_FUNC_GPIO_9_I2S0_MCLK = 7, +} hi_io_func_gpio_9; + +/** +* @ingroup iot_io +* +* GPIO_10 pin function.CNcomment:GPIO_10管脚功能。CNend +*/ +typedef enum { + HI_IO_FUNC_GPIO_10_GPIO, + HI_IO_FUNC_GPIO_10_I2C0_SDA, + HI_IO_FUNC_GPIO_10_UART2_CTS_N, + HI_IO_FUNC_GPIO_10_SDIO_D3, + HI_IO_FUNC_GPIO_10_SPI1_CK, + HI_IO_FUNC_GPIO_10_PWM1_OUT, + HI_IO_FUNC_GPIO_10_I2S0_TX = 7, +} hi_io_func_gpio_10; + +/** +* @ingroup iot_io +* +* GPIO_11 pin function.CNcomment:GPIO_11管脚功能。CNend +*/ +typedef enum { + HI_IO_FUNC_GPIO_11_GPIO, + HI_IO_FUNC_GPIO_11_UART2_TXD = 2, + HI_IO_FUNC_GPIO_11_SDIO_CMD, + HI_IO_FUNC_GPIO_11_SPI1_RXD, + HI_IO_FUNC_GPIO_11_PWM2_OUT, + HI_IO_FUNC_GPIO_11_RF_TX_EN_EXT, + HI_IO_FUNC_GPIO_11_I2S0_RX, +} hi_io_func_gpio_11; + +/** +* @ingroup iot_io +* +* GPIO_12 pin function.CNcomment:GPIO_12管脚功能。CNend +*/ +typedef enum { + HI_IO_FUNC_GPIO_12_GPIO, + HI_IO_FUNC_GPIO_12_UART2_RXD = 2, + HI_IO_FUNC_GPIO_12_SDIO_CLK, + HI_IO_FUNC_GPIO_12_SPI1_CSN, + HI_IO_FUNC_GPIO_12_PWM3_OUT, + HI_IO_FUNC_GPIO_12_RF_RX_EN_EXT, + HI_IO_FUNC_GPIO_12_I2S0_BCLK, +} hi_io_func_gpio_12; + +/** +* @ingroup iot_io +* +* GPIO_13 pin function.CNcomment:GPIO_13管脚功能。CNend +*/ +typedef enum { + HI_IO_FUNC_GPIO_13_SSI_DATA, + HI_IO_FUNC_GPIO_13_UART0_TXD, + HI_IO_FUNC_GPIO_13_UART2_RTS_N, + HI_IO_FUNC_GPIO_13_SDIO_D0, + HI_IO_FUNC_GPIO_13_GPIO, + HI_IO_FUNC_GPIO_13_PWM4_OUT, + HI_IO_FUNC_GPIO_13_I2C0_SDA, + HI_IO_FUNC_GPIO_13_I2S0_WS, +} hi_io_func_gpio_13; + +/** +* @ingroup iot_io +* +* GPIO_14 pin function.CNcomment:GPIO_14管脚功能。CNend +*/ +typedef enum { + HI_IO_FUNC_GPIO_14_SSI_CLK, + HI_IO_FUNC_GPIO_14_UART0_RXD, + HI_IO_FUNC_GPIO_14_UART2_CTS_N, + HI_IO_FUNC_GPIO_14_SDIO_D1, + HI_IO_FUNC_GPIO_14_GPIO, + HI_IO_FUNC_GPIO_14_PWM5_OUT, + HI_IO_FUNC_GPIO_14_I2C0_SCL, +} hi_io_func_gpio_14; + +/** +* @ingroup iot_io +* +* SFC_CSN pin function.CNcomment:SFC_CSN管脚功能。CNend +*/ +typedef enum { + HI_IO_FUNC_SFC_CSN_SFC_CSN, + HI_IO_FUNC_SFC_CSN_SDIO_D2, + HI_IO_FUNC_SFC_CSN_GPIO9, + HI_IO_FUNC_SFC_CSN_SPI0_TXD = 4, +} hi_io_func_sfc_csn; + +/** +* @ingroup iot_io +* +* SFC_DO pin function.CNcomment:SFC_DO管脚功能。CNend +*/ +typedef enum { + HI_IO_FUNC_SFC_IO_1_SFC_DO, + HI_IO_FUNC_SFC_IO_1_SDIO_D3, + HI_IO_FUNC_SFC_IO_1_GPIO10, + HI_IO_FUNC_SFC_IO_1_SPI0_CK = 4, +} hi_io_func_sfc_io_1; + +/** +* @ingroup iot_io +* +* SFC_WPN pin function.CNcomment:SFC_WPN管脚功能。CNend +*/ +typedef enum { + HI_IO_FUNC_SFC_IO_2_SFC_WPN, + HI_IO_FUNC_SFC_IO_2_SDIO_CMD, + HI_IO_FUNC_SFC_IO_2_GPIO11, + HI_IO_FUNC_SFC_IO_2_RF_TX_EN_EXT, + HI_IO_FUNC_SFC_IO_2_SPI0_RXD, +} hi_io_func_sfc_io_2; + +/** +* @ingroup iot_io +* +* SFC_DI pin function.CNcomment:SFC_DI管脚功能。CNend +*/ +typedef enum { + HI_IO_FUNC_SFC_IO_0_SFC_DI, + HI_IO_FUNC_SFC_IO_0_SDIO_CLK, + HI_IO_FUNC_SFC_IO_0_GPIO12, + HI_IO_FUNC_SFC_IO_0_RF_RX_EN_EXT, + HI_IO_FUNC_SFC_IO_0_SPI0_CSN, +} hi_io_func_sfc_io_0; + +/** +* @ingroup iot_io +* +* SFC_CLK pin function.CNcomment:SFC_CLK管脚功能。CNend +*/ +typedef enum { + HI_IO_FUNC_SFC_CLK_SFC_CLK, + HI_IO_FUNC_SFC_CLK_SDIO_D0, + HI_IO_FUNC_SFC_CLK_GPIO13, + HI_IO_FUNC_SFC_CLK_SSI_DATA = 4, +} hi_io_func_sfc_clk; + +/** +* @ingroup iot_io +* +* SFC_HOLDN pin function.CNcomment:SFC_HOLDN管脚功能。CNend +*/ +typedef enum { + HI_IO_FUNC_SFC_IO_3_SFC_HOLDN, + HI_IO_FUNC_SFC_IO_3_SDIO_D1, + HI_IO_FUNC_SFC_IO_3_GPIO14, + HI_IO_FUNC_SFC_IO_3_SSI_CLK = 4, +} hi_io_func_sfc_io_3; + +/** +* @ingroup iot_io +* @brief Sets the I/O multiplexing.CNcomment:配置某个IO的复用功能。CNend +* +* @par 描述: +* Sets the I/O multiplexing.CNcomment:配置某个IO的复用功能。CNend +* +* @attention None +* @param id [IN] type #hi_io_name,I/O index.CNcomment:硬件管脚。CNend +* @param val [IN] type #hi_u8,I/O multiplexing.See the functions below: CNcomment:IO复用功能。 +根据待设置的硬件管脚,从如下枚举中选择相应功能。CNend + hi_io_func_gpio_0, + hi_io_func_gpio_1, + hi_io_func_gpio_2, + hi_io_func_gpio_3, + hi_io_func_gpio_4, + hi_io_func_gpio_5, + hi_io_func_gpio_6, + hi_io_func_gpio_7, + hi_io_func_gpio_8, + hi_io_func_gpio_9, + hi_io_func_gpio_10, + hi_io_func_gpio_11, + hi_io_func_gpio_12, + hi_io_func_gpio_13, + hi_io_func_gpio_14, + hi_io_func_sfc_csn, + hi_io_func_sfc_io_1, + hi_io_func_sfc_io_2, + hi_io_func_sfc_io_0, + hi_io_func_sfc_clk, + hi_io_func_sfc_io_3 +* +* @retval #HI_ERR_SUCCESS Success +* @retval #HI_ERR_GPIO_INVALID_PARAMETER Failure. Input invalid. +* @par 依赖: +* @li hi_boot_rom.h:Describes I/O APIs.CNcomment:文件用于描述IO相关接口。CNend +* @see hi_io_set_func。 +*/ +hi_u32 hi_io_set_func(hi_io_name id, hi_u8 val); + +/** +* @ingroup iot_io +* @brief Enables the I/O pull-up.CNcomment:设置某个IO上下拉功能。CNend +* +* @par 描述: +* Enables the I/O pull-up.CNcomment:设置某个IO上下拉功能。CNend +* +* @attention None +* @param id [IN] type #hi_io_name,I/O index.CNcomment:硬件管脚。CNend +* @param val [IN] type #hi_io_pull,I/O pull-up enable.CNcomment:待设置的上下拉状态。CNend +* +* @retval #HI_ERR_SUCCESS Success +* @retval #HI_ERR_GPIO_INVALID_PARAMETER Failure. Input invalid. +* @par 依赖: +* @li hi_boot_rom.h:Describes I/O APIs.CNcomment:文件用于描述IO相关接口。CNend +* @see hi_io_get_pull。 +*/ +hi_u32 hi_io_set_pull(hi_io_name id, hi_io_pull val); +#endif + diff --git a/sdk_liteos/boot/flashboot/include/hi_flashboot.h b/sdk_liteos/boot/flashboot/include/hi_flashboot.h new file mode 100644 index 0000000000000000000000000000000000000000..fc69530cac424ae5038fa1b6dcc9ef29c04804aa --- /dev/null +++ b/sdk_liteos/boot/flashboot/include/hi_flashboot.h @@ -0,0 +1,613 @@ +/* + * @file hi_flashboot.h + * + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** @defgroup iot_flashboot Flash Boot */ +#ifndef _HI_FLASHBOOT_H_ +#define _HI_FLASHBOOT_H_ + +#include +#include + +/** @defgroup iot_nv NV Management APIs +* @ingroup iot_flashboot +*/ +/** +* @ingroup iot_nv +* Maximum length of an NV item (unit: byte). CNcomment:NV项最大长度(单位:byte)。CNend +*/ +#define HNV_ITEM_MAXLEN (256 - 4) + +/** +* @ingroup iot_nv +*/ +#define PRODUCT_CFG_NV_REG_NUM_MAX 20 + +/** +* @ingroup iot_nv +*/ +#define HI_FNV_DEFAULT_ADDR 0x8000 + +/** +* @ingroup iot_nv +*/ +#define HI_NV_DEFAULT_TOTAL_SIZE 0x2000 + +/** +* @ingroup iot_nv +*/ +#define HI_NV_DEFAULT_BLOCK_SIZE 0x1000 + +/** +* @ingroup iot_nv +* +* Factory NV area user area end ID. CNcomment:工厂区NV结束ID。CNend +*/ +#define HI_NV_FACTORY_USR_ID_END 0x20 + +/** +* @ingroup iot_nv +*/ +#define HI_NV_FTM_FLASH_PARTIRION_TABLE_ID 0x02 + +/** +* @ingroup iot_nv +* @brief Initializes NV management in the factory partition.CNcomment:工厂区NV初始化。CNend +* +* @par 描述: +* Initializes NV management in the factory partition.CNcomment: 工厂区NV管理初始化。CNend +* +* @attention The parameters cannot be set randomly and must match the product delivery plan. +CNcomment:参数不能随意配置,需要与产品出厂规划匹配。CNend +* @param addr [IN] type #hi_u32,Start address of the NV factory partition in the flash. The address is planned by +* the factory and set by the boot macro #FACTORY_NV_ADDR. +CNcomment:设置工厂区NV FLASH首地址,由出厂规划,boot宏定义FACTORY_NV_ADDR 统一设置。CNend +* @param total_size [IN] type #hi_u32,total size of factory NV. +CNcomment:工厂区NV的总大小。CNend +* @param block_size [IN] type #hi_u32,block size of factory NV. +CNcomment:工厂区NV的块大小。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_flashboot.h:Describes NV APIs.CNcomment:文件用于描述NV相关接口。CNend +* @see hi_factory_nv_write | hi_factory_nv_read。 +*/ +hi_u32 hi_factory_nv_init(hi_u32 addr, hi_u32 total_size, hi_u32 block_size); + +/** +* @ingroup iot_nv +* @brief Sets the NV value in the factory partition. CNcomment:设置工厂区NV值。CNend +* +* @par 描述: +* Sets the NV value in the factory partition.CNcomment:设置工厂区NV值。CNend +* +* @attention None +* @param id [IN] type #hi_u8,NV item ID, ranging from #HI_NV_FACTORY_ID_START to #HI_NV_FACTORY_USR_ID_END. +CNcomment:NV项ID,范围从#HI_NV_FACTORY_ID_START到#HI_NV_FACTORY_USR_ID_END。CNend +* @param pdata [IN] type #hi_pvoid,NV item data.CNcomment:NV项数据。CNend +* @param len [IN] type #hi_u8,Length of an NV item (unit: byte). The maximum value is #HNV_ITEM_MAXLEN. +CNcomment:NV项长度(单位:byte),最大不允许超过HNV_ITEM_MAXLEN。CNend +* @param flag [IN] type #hi_u32,Reserve.CNcomment:保留参数。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_flashboot.h:Describes NV APIs.CNcomment:文件用于描述NV相关接口。CNend +* @see hi_factory_nv_read。 +*/ +hi_u32 hi_factory_nv_write(hi_u8 id, hi_pvoid pdata, hi_u8 len, hi_u32 flag); + +/** +* @ingroup iot_nv +* @brief Reads the NV value in the factory partition.CNcomment:读取工厂区NV值。CNend +* +* @par 描述: +* Reads the NV value in the factory partition.读取工厂区NV值。CNend +* +* @attention None +* +* @param id [IN] type #hi_u8,NV item ID, ranging from #HI_NV_NORMAL_ID_START to #HI_NV_NORMAL_USR_ID_END. +CNcomment:NV项ID,范围从#HI_NV_NORMAL_ID_START到#HI_NV_NORMAL_USR_ID_END。CNend +* @param pdata [IN] type #hi_pvoid,NV item data.CNcomment:NV项数据。CNend +* @param len [IN] type #hi_u8,Length of an NV item (unit: byte). The maximum value is HNV_ITEM_MAXLEN. +CNcomment:NV项长度(单位:byte),最大不允许超过HNV_ITEM_MAXLEN。CNend +* @param flag [IN] type #hi_u32,Reserve.CNcomment:保留参数。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_flashboot.h:Describes NV APIs.CNcomment:文件用于描述NV相关接口。CNend +* @see hi_factory_nv_write。 +*/ +hi_u32 hi_factory_nv_read(hi_u8 id, hi_pvoid pdata, hi_u8 len, hi_u32 flag); + +/** @defgroup iot_flash_partiton Partition Table APIs +* @ingroup iot_flashboot +*/ +/** + * @ingroup iot_flash_partiton + * + * partition number. + */ +#define HI_FLASH_PARTITON_MAX 12 + +/** + * @ingroup iot_flash_partiton + * + * partition ID. + */ +typedef enum { + HI_FLASH_PARTITON_BOOT = 0, /**< Boot partition ID.CNcomment:BOOT分区ID.CNend */ + HI_FLASH_PARTITON_FACTORY_NV, /**< Factory NV working partition ID.CNcomment:工厂NV分区ID.CNend */ + HI_FLASH_PARTITON_NORMAL_NV, /**< NORMAL NV partition ID.CNcomment:非工厂NV分区ID.CNend */ + HI_FLASH_PARTITON_NORMAL_NV_BACKUP, /**< NORMAL backup NV partition ID.CNcomment:非工厂NV备份分区ID,必须和非工厂区连续.CNend */ + HI_FLASH_PARTITON_KERNEL_A, /**< Kernel A running partition ID.CNcomment:内核A区ID.CNend */ + HI_FLASH_PARTITON_KERNEL_B, /**< Kernel B runing partition ID.CNcomment:内核B区ID.CNend */ + HI_FLASH_PARTITON_HILINK, /**< HILINK partition ID.CNcomment:HILINK分区ID(未使用HILINK可不需要).CNend */ + HI_FLASH_PARTITON_FILE_SYSTEM, /**< File system partition ID.CNcomment:文件系统区ID.CNend */ + HI_FLASH_PARTITON_USR_RESERVE, /**< User Reserved partition.CNcomment:用户保留区ID.CNend */ + HI_FLASH_PARTITON_HILINK_PKI, /**< HiLink PKI partition.CNcomment: HILINK PKI证书ID(未使用HILINK可不需要). CNend */ + HI_FLASH_PARTITON_CRASH_INFO, /**< Crash log partition.CNcomment:死机存储区ID.CNend */ + HI_FLASH_PARTITON_BOOT_BACK, /**< Boot backup partition.CNcomment:备份boot区ID. CNend */ +} hi_flash_partition_table_id; + +/** + * @ingroup iot_flash_partiton + * + * Flash partition management. CNcomment:Flash分区表项。CNend + */ +typedef struct { + hi_u32 addr : 24; /* Flash partition address. The value is 16 MB. If the address is in reverse order, + the value is the end low address. CNcomment:Flash分区地址,限制为16MB, + 如果为倒序,存放为结束的低地址值 CNend */ + hi_u32 id : 7; /* Flash partition ID. CNcomment:Flash区ID.CNend */ + hi_u32 dir : 1; /* Flash area storage direction. 0:regular. 1: reversed.CNcomment:Flash区存放方向。 + 0:分区内容正序;1:倒序末地址 CNend */ + + hi_u32 size : 24; /* Size of the parition(Unit:byte). CNcomment:Flash分区大小(单位:byte)CNend */ + hi_u32 reserve : 8; /* Reserved. CNcomment:保留区CNend */ + + hi_u32 addition; /* Supplementary information about the flash partition, such as the address of the Ram. + CNcomment:Flash分区补充信息,如Ram对应地址等 CNend */ +} hi_flash_partition_info; + +/** + * @ingroup iot_flash_partiton + * Flash partiton table. + */ +typedef struct { + hi_flash_partition_info table[HI_FLASH_PARTITON_MAX]; /**< Flash分区表项描述 */ +} hi_flash_partition_table; + +/** +* @ingroup iot_flash_partiton +* @brief Initialize flash partition table. CNcomment:初始化Flash分区表。CNend +* +* @par 描述: +* Initialize flash partition table. CNcomment:初始化Flash分区表。CNend +* +* @attention None. +* @param None. +* +* @retval #HI_ERR_FAILURE Failure. +* @retval #HI_ERR_SUCCESS Success. +* @par 依赖: +* @li hi_flashboot.h:Describes FlashBoot APIs.CNcomment:文件用于描述Boot模块接口。CNend +* @see hi_get_partition_table。 +*/ +hi_u32 hi_flash_partition_init(hi_void); + +/** +* @ingroup iot_flash_partiton +* @brief Get flash partition table. CNcomment:获取Flash分区表。CNend +* +* @par 描述: +* Get flash partition table. CNcomment:获取Flash分区表。CNend +* +* @attention None. +* @param None. +* +* @retval #HI_NULL Failure. +* @retval #Other Success. +* @par 依赖: +* @li hi_flashboot.h:Describes FlashBoot APIs.CNcomment:文件用于描述Boot模块接口。CNend +* @see hi_flash_partition_init。 +*/ +hi_flash_partition_table* hi_get_partition_table(hi_void); + +/** @defgroup iot_efuse eFuse APIs +* @ingroup iot_flashboot +*/ +/** +* @ingroup iot_efuse +* +* Efuse ID. +*/ +typedef enum { + HI_EFUSE_CHIP_RW_ID = 0, + HI_EFUSE_DIE_RW_ID = 1, + HI_EFUSE_PMU_FUSE1_RW_ID = 2, + HI_EFUSE_PMU_FUSE2_RW_ID = 3, + HI_EFUSE_FLASH_ENCPY_CNT3_RW_ID = 4, + HI_EFUSE_FLASH_ENCPY_CNT4_RW_ID = 5, + HI_EFUSE_FLASH_ENCPY_CNT5_RW_ID = 6, + HI_EFUSE_DSLEEP_FLAG_RW_ID = 7, + HI_EFUSE_ROOT_PUBKEY_RW_ID = 8, + HI_EFUSE_ROOT_KEY_WO_ID = 9, + HI_EFUSE_CUSTOMER_RSVD0_RW_ID = 10, + HI_EFUSE_SUBKEY_CAT_RW_ID = 11, + HI_EFUSE_ENCRYPT_FLAG_RW_ID = 12, + HI_EFUSE_SUBKEY_RSIM_RW_ID = 13, + HI_EFUSE_START_TYPE_RW_ID = 14, + HI_EFUSE_JTM_RW_ID = 15, + HI_EFUSE_UTM0_RW_ID = 16, + HI_EFUSE_UTM1_RW_ID = 17, + HI_EFUSE_UTM2_RW_ID = 18, + HI_EFUSE_SDC_RW_ID = 19, + HI_EFUSE_RSVD0_RW_ID = 20, + HI_EFUSE_KDF2ECC_HUK_DISABLE_RW_ID = 21, + HI_EFUSE_SSS_CORNER_RW_ID = 22, + HI_EFUSE_UART_HALT_INTERVAL_RW_ID = 23, + HI_EFUSE_TSENSOR_RIM_RW_ID = 24, + HI_EFUSE_CHIP_BK_RW_ID = 25, + HI_EFUSE_IPV4_MAC_ADDR_RW_ID = 26, + HI_EFUSE_IPV6_MAC_ADDR_RW_ID = 27, + HI_EFUSE_PG2GCCKA0_TRIM0_RW_ID = 28, + HI_EFUSE_PG2GCCKA1_TRIM0_RW_ID = 29, + HI_EFUSE_NVRAM_PA2GA0_TRIM0_RW_ID = 30, + HI_EFUSE_NVRAM_PA2GA1_TRIM0_RW_ID = 31, + HI_EFUSE_PG2GCCKA0_TRIM1_RW_ID = 32, + HI_EFUSE_PG2GCCKA1_TRIM1_RW_ID = 33, + HI_EFUSE_NVRAM_PA2GA0_TRIM1_RW_ID = 34, + HI_EFUSE_NVRAM_PA2GA1_TRIM1_RW_ID = 35, + HI_EFUSE_PG2GCCKA0_TRIM2_RW_ID = 36, + HI_EFUSE_PG2GCCKA1_TRIM2_RW_ID = 37, + HI_EFUSE_NVRAM_PA2GA0_TRIM2_RW_ID = 38, + HI_EFUSE_NVRAM_PA2GA1_TRIM2_RW_ID = 39, + HI_EFUSE_TEE_BOOT_VER_RW_ID = 40, + HI_EFUSE_TEE_KERNEL_VER_RW_ID = 41, + HI_EFUSE_TEE_SALT_RW_ID = 42, + HI_EFUSE_FLASH_ENCPY_CNT0_RW_ID = 43, + HI_EFUSE_FLASH_ENCPY_CNT1_RW_ID = 44, + HI_EFUSE_FLASH_ENCPY_CNT2_RW_ID = 45, + HI_EFUSE_FLASH_ENCPY_CFG_RW_ID = 46, + HI_EFUSE_FLASH_SCRAMBLE_EN_RW_ID = 47, + HI_EFUSE_USER_FLASH_IND_RW_ID = 48, + HI_EFUSE_RF_PDBUFFER_GCAL_RW_ID = 49, + HI_EFUSE_CUSTOMER_RSVD1_RW_ID = 50, + HI_EFUSE_DIE_2_RW_ID = 51, + HI_EFUSE_SEC_BOOT_RW_ID = 52, + HI_EFUSE_IDX_MAX, +} hi_efuse_idx; + +/** +* @ingroup iot_efuse +* +* Efuse Lock ID. +*/ +typedef enum { + HI_EFUSE_LOCK_CHIP_ID = 0, + HI_EFUSE_LOCK_DIE_ID = 1, + HI_EFUSE_LOCK_PMU_FUSE1_FUSE2_START_TYPE_TSENSOR_ID = 2, + HI_EFUSE_LOCK_ROOT_PUBKEY_ID = 3, + HI_EFUSE_LOCK_ROOT_KEY_ID = 4, + HI_EFUSE_LOCK_CUSTOMER_RSVD0_ID = 5, + HI_EFUSE_LOCK_SUBKEY_CAT_ID = 6, + HI_EFUSE_LOCK_ENCRYPT_RSIM_ID = 7, + HI_EFUSE_LOCK_JTM_ID = 8, + HI_EFUSE_LOCK_UTM0_ID = 9, + HI_EFUSE_LOCK_UTM1_ID = 10, + HI_EFUSE_LOCK_UTM2_ID = 11, + HI_EFUSE_LOCK_SDC_ID = 12, + HI_EFUSE_LOCK_RSVD0_ID = 13, + HI_EFUSE_LOCK_SSS_CORNER_ID = 14, + HI_EFUSE_LOCK_UART_HALT_INTERVAL_ID = 15, + HI_EFUSE_LOCK_CHIP_BK_ID = 16, + HI_EFUSE_LOCK_IPV4_IPV6_MAC_ADDR_ID = 17, + HI_EFUSE_LOCK_PG2GCCKA0_PG2GCCKA1_TRIM0_ID = 18, + HI_EFUSE_LOCK_NVRAM_PA2GA0_PA2GA1_TRIM0_ID = 19, + HI_EFUSE_LOCK_PG2GCCKA0_PG2GCCKA1_TRIM1_ID = 20, + HI_EFUSE_LOCK_NVRAM_PA2GA0_PA2GA1_TRIM1_ID = 21, + HI_EFUSE_LOCK_PG2GCCKA0_PG2GCCKA1_TRIM2_ID = 22, + HI_EFUSE_LOCK_NVRAM_PA2GA0_PA2GA1_TRIM2_ID = 23, + HI_EFUSE_LOCK_TEE_BOOT_VER_ID = 24, + HI_EFUSE_LOCK_TEE_KERNEL_VER_ID = 25, + HI_EFUSE_LOCK_TEE_SALT_ID = 26, + HI_EFUSE_LOCK_FLASH_ENCPY_CNT0_ID = 27, + HI_EFUSE_LOCK_FLASH_ENCPY_CNT1_ID = 28, + HI_EFUSE_LOCK_FLASH_ENCPY_CNT2_ID = 29, + HI_EFUSE_LOCK_FLASH_ENCPY_CFG_ID = 30, + HI_EFUSE_LOCK_FLASH_SCRAMBLE_EN_FLASH_IND_ID = 31, + HI_EFUSE_LOCK_RF_PDBUFFER_GCAL_ID = 32, + HI_EFUSE_LOCK_CUSTOMER_RSVD1_ID = 33, + HI_EFUSE_LOCK_DIE_2_ID = 34, + HI_EFUSE_LOCK_KDF2ECC_HUK_DISABLE_ID = 35, + HI_EFUSE_LOCK_FLASH_ENCPY_CNT3_ID = 36, + HI_EFUSE_LOCK_FLASH_ENCPY_CNT4_ID = 37, + HI_EFUSE_LOCK_FLASH_ENCPY_CNT5_ID = 38, + HI_EFUSE_LOCK_SEC_BOOT_ID = 39, + HI_EFUSE_LOCK_DSLEEP_FLAG_ID = 40, + HI_EFUSE_LOCK_MAX, +} hi_efuse_lock_id; + +/** +* @ingroup iot_efuse +* @brief Reads the eFUSE.CNcomment:EFUSE读取数据。CNend +* +* @par 描述: +* Reads the eFUSE.CNcomment:从EFUSE中读取数据。CNend +* +* @attention Ensure that the value of (data_len*8) is not less than efuse_id and the length of the efuse field is 8bit +* aligned.CNcomment:需保证(data_len*8)不小于efuse_id对应efuse字段的长度向上8bit对齐。CNend +* +* @param efuse_id [IN] type #hi_efuse_idx,EFUSE ID +* @param data [OUT] type #hi_u8*,Address for saving the read data.CNcomment:读到的数据放到该地址。CNend +* @param data_len [IN] type #hi_u8 Space allocated to data, in bytes.CNcomment:给data分配的空间,单位byte。CNend +* +* @retval #HI_ERR_SUCCESS Success +* @retval #Other Failure. For details, see hi_boot_err.h. +* @par 依赖: +* @li hi_boot_rom.h:Describes the encryption and decryption APIs. +CNcomment:文件用于描述efuse字段操作相关接口。CNend +* @see hi_efuse_write。 +*/ +hi_u32 hi_efuse_read(hi_efuse_idx efuse_id, hi_u8 *data, hi_u8 data_len); + +/** +* @ingroup iot_efuse +* @brief Writes the eFUSE.CNcomment:写数据到EFUSE。CNend +* +* @par 描述: +* Writes the eFUSE.CNcomment:写数据到EFUSE。CNend +* +* @attention None +* @param efuse_id [IN] type #hi_efuse_idx,EFUSE ID +* @param data [IN] type #const hi_u8*,Data to be written to the eFUSE.CNcomment:写该数据到EFUSE中。CNend +* +* @retval #HI_ERR_SUCCESS Success +* @retval #Other Failure. For details, see hi_boot_err.h. +* @par 依赖: +* @li hi_boot_rom.h:Describes the encryption and decryption APIs. +CNcomment:文件用于描述efuse字段操作相关接口。CNend +* @see hi_efuse_read。 +*/ +hi_u32 hi_efuse_write(hi_efuse_idx efuse_id, const hi_u8 *data); + +/** +* @ingroup iot_efuse +* @brief Locks an area in the eFUSE. After the lock takes effect upon reboot, the area cannot be written. +CNcomment:加锁EFUSE中的某个区域,加锁后重启单板生效,该区域无法再写入。CNend +* +* @par 描述: +* Locks an area in the eFUSE. After the lock takes effect upon reboot, the area cannot be written. +CNcomment:加锁EFUSE中的某个区域,加锁后重启单板生效,该区域无法再写入。CNend +* +* @attention None +* @param lock_id [IN] type #hi_efuse_lock_id,eFUSE ID to be locked.CNcomment:待加锁的EFUSE ID项。CNend +* +* @retval #HI_ERR_SUCCESS Success +* @retval #Other Failure. For details, see hi_boot_err.h. +* @par 依赖: +* @li hi_boot_rom.h:Describes the encryption and decryption APIs. +CNcomment:文件用于描述efuse字段操作相关接口。CNend +* @see hi_efuse_write。 +*/ +hi_u32 hi_efuse_lock(hi_efuse_lock_id efuse_lock_id); + +/** +* @ingroup iot_efuse +* @brief Obtains the lock status of the eFUSE and queries which areas are locked. +CNcomment:获取EFUSE的锁状态,查询哪些区域已锁定。CNend +* +* @par 描述: +* Obtains the lock status of the eFUSE and queries which areas are locked. +CNcomment:获取EFUSE的锁状态,查询哪些区域已锁定。CNend +* +* @attention None +* @param lock_stat [OUT] type #hi_u64*,Lock status of the eFUSE.CNcomment:获取EFUSE的锁状态。CNend +* +* @retval #HI_ERR_SUCCESS Success +* @retval #Other Failure. For details, see hi_boot_err.h. +* @par 依赖: +* @li hi_boot_rom.h:Describes the encryption and decryption APIs. +CNcomment:文件用于描述efuse字段操作相关接口。CNend +* @see hi_efuse_write。 +*/ +hi_u32 hi_efuse_get_lockstat(hi_u64 *lock_stat); + +/** +* @ingroup iot_efuse +* @brief Reads the user eFUSE.CNcomment:EFUSE用户读取数据。CNend +* +* @par 描述: +* Reads a reserved area in the eFUSE.CNcomment:用户从EFUSE中读取数据。CNend +* +* @attention None +* @param start_bit [IN] type #hi_u16,Start bit. The address must be 8-bit aligned. +CNcomment:起始bit位,该地址必须8bit对齐。CNend +* @param size [IN] type #hi_u16,Number of bits to be read. If the input is not 8-bit aligned, +* the function performs 8-bit alignment internally. The user needs to process the read data before using it. +CNcomment:待读取的bit位数,如果输入不是8bit对齐则函数内部会处理为8bit对齐,用户读取数据后需处理后使用。CNend +* @param key_data [OUT] type #hi_u8*,Address for saving the read data. +CNcomment:读到的数据放到该地址。CNend +* +* @retval #HI_ERR_SUCCESS Success +* @retval #Other Failure. For details, see hi_boot_err.h. +* @par 依赖: +* @li hi_boot_rom.h:Describes the encryption and decryption APIs. +CNcomment:文件用于描述efuse字段操作相关接口。CNend +* @see hi_efuse_usr_write。 +*/ +hi_u32 hi_efuse_usr_read(hi_u16 start_bit, hi_u16 size, hi_u8 *key_data); + +/** +* @ingroup iot_efuse +* @brief Writes data to reserved area of the eFUSE.CNcomment:EFUSE用户区写入数据。CNend +* +* @par 描述: +* Writes data to reserved area of the eFUSE.CNcomment:用户往EFUSE写入数据。CNend +* +* @attention Generally, this API is used to write a reserved area. To write other pre-allocated areas, +* should check the design spec to avoid conflict.CNcomment:支持用户写入任意地址数据, +建议用户使用用户预留区,其他区域的写入需要结合方案文档评估是否有冲突。CNend +* +* @param start_bit [IN] type #hi_u16,Start bit.CNcomment:起始bit位。CNend +* @param size [IN] type #hi_u16,Number of bits to be written. 1-to-256-bit write is supported. +CNcomment:待写入bit数,支持单bit写入,最大值为256bit数。CNend +* @param key_data [IN] type #const hi_u8*,Address for the data to be written. The maximum length is 32 bytes. +CNcomment:待写入的数据放到该地址,最长为32byte。CNend +* +* @retval #HI_ERR_SUCCESS Success +* @retval #Other Failure. For details, see hi_boot_err.h. +* @par 依赖: +* @li hi_boot_rom.h:Describes the encryption and decryption APIs. +CNcomment:文件用于描述efuse字段操作相关接口。CNend +* @see hi_efuse_usr_read。 +*/ +hi_u32 hi_efuse_usr_write(hi_u16 start_bit, hi_u16 size, const hi_u8 *key_data); + +/** @defgroup iot_flash Flash Driver APIs +* @ingroup iot_flashboot +*/ +/** +* @ingroup iot_flash +* @brief Initializes the flash device. CNcomment:初始化Flash设备。CNend +* +* @par 描述: +* Initializes the flash device. CNcomment:初始化Flash设备。CNend +* +* @attention Initialize the flash module during system boot. +CNcomment:Flash模块初始化,一般在系统启动时调用。CNend +* @param None +* +* @retval #HI_ERR_SUCCESS Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_flashboot.h:FLASH driver APIs.CNcomment:该接口声明所在的头文件。CNend +* @see None +*/ +hi_u32 hi_flash_init(hi_void); + +/** +* @ingroup iot_flash +* @brief Erases the data in the specified flash partition.CNcomment:把指定的Flash区域数据擦除。CNend +* +* @par 描述: +* Erases the data in the specified flash partition.CNcomment:把指定的Flash区域数据擦除。CNend +* +* @attention +* @li Restriction protection for the relative address of the flash memory. +CNcomment:Flash相对地址的限制保护。CNend +* @li The number of flash erase times must comply with the device data sheet. +CNcomment:Flash擦写次数限制。CNend +* +* @param flash_offset [IN] type #hi_u32,Address offset of the flash memory to be erased. +CNcomment:指定要擦除Flash的地址偏移。CNend +* @param size [IN] type #hi_u32,Length of the data to be erased (unit: byte). +* The value must be a multiple of 4 KB. +CNcomment:需要擦除的长度(单位:byte),必须是4K的倍数。CNend +* +* @retval #HI_ERR_SUCCESS Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_flashboot.h:FLASH driver APIs.CNcomment:该接口声明所在的头文件。CNend +* @see None +*/ +hi_u32 hi_flash_erase(const hi_u32 flash_addr, hi_u32 flash_erase_size); + +/** +* @ingroup iot_flash +* @brief Writes data to the specified flash partition.CNcomment:把数据写入指定的Flash区。CNend +* +* @par 描述: +* Writes data to the specified flash partition.CNcomment:把数据写入指定的Flash区域。CNend +* +* @attention +* @li Restriction protection for the relative address of the flash memory. +CNcomment:Flash相对地址的限制保护。CNend +* @li The number of flash erase times must comply with the device data sheet. +CNcomment:Flash擦写次数限制。CNend +* @li Determine whether to erase the flash before the write based on the actual control scenario. +CNcomment:根据用户实际控制场景决定是否先擦后写。CNend +* @param flash_offset [IN] type #hi_u32,Offset address for writing data to the flash memory. +CNcomment:指定写入Flash偏移地址。CNend +* @param size [IN] type #hi_u32,Length of the data to be written (unit: byte). +CNcomment:需要写入的长度(单位:byte)。CNend +* @param ram_data [IN] type #hi_u8*,Cache address of the data to be written. +CNcomment:需要写入的数据的缓存地址。CNend +* @param do_erase [IN] type #hi_bool,HI_FALSE: Write data to the flash memory directly. +* HI_TRUE: Erase the sector space before write. The user data is written +* to the user operation space and the historical data is written back to other spaces. +CNcomment:表示是否自动擦除并覆盖写入。HI_TRUE:本接口中先擦后写。HI_FALSE:用户已经擦除本接口,可直接写入。CNend +* +* @retval #HI_ERR_SUCCESS Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_flashboot.h:FLASH driver APIs.CNcomment:该接口声明所在的头文件。CNend +* @see None +*/ +hi_u32 hi_flash_write(hi_u32 flash_addr, hi_u32 flash_write_size, const hi_u8 *p_flash_write_data, hi_bool do_erase); + +/** +* @ingroup iot_flash +* @brief Reads the flash data to the specified cache. CNcomment:读出Flash数据到指定缓存区域。CNend +* +* @par 描述: +* Reads the flash data to the specified cache. CNcomment:读出Flash数据到指定缓存区域。CNend +* +* @attention None +* @param flash_offset [IN] type #hi_u32,Offset of the flash address.CNcomment:指定的Flash地址偏移。CNend +* @param size [IN] type #hi_u32,Read length (unit: byte). +CNcomment:指定读取的长度(单位:byte)。CNend +* @param ram_data [IN] type #hi_u8*,Destination cache address.CNcomment:目的缓存地址。CNend +* +* @retval #HI_ERR_SUCCESS Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_flashboot.h:FLASH driver APIs.CNcomment:该接口声明所在的头文件。CNend +* @see None +*/ +hi_u32 hi_flash_read(hi_u32 flash_addr, hi_u32 flash_read_size, hi_u8 *p_flash_read_data); + +/** @defgroup iot_crc32 CRC32 APIs +* @ingroup iot_flashboot +*/ +/** +* @ingroup iot_crc32 +* @brief Generates a 32-bit CRC value.CNcomment:生成32位CRC校验值。CNend +* +* @par 描述: +* Generates a 32-bit CRC value.CNcomment:生成32位CRC校验值。CNend +* +* @attention None +* @param crc [IN] type #hi_u32,The CRC initial value.CNcomment:CRC初始值。CNend +* @param p [IN] type #const hi_u8*,Pointer to the buffer to be verified. +CNcomment:被校验Buffer指针。CNend +* @param len [IN] type #hi_u32,Length of the buffer to be verified (unit: Byte). +CNcomment:被校验Buffer长度(单位:byte)。CNend +* +* @retval #HI_ERR_SUCCESS Success +* @retval #Other Failure. For details, see hi_boot_err.h. +* +* @par 依赖: +* @li hi_flashboot.h:Describes CRC APIs.CNcomment:文件包含CRC校验接口。CNend +* @see None +*/ +hi_u32 hi_crc32 (hi_u32 crc, const hi_u8 *p, hi_u32 len); + +#endif + diff --git a/sdk_liteos/boot/flashboot/include/hi_flashboot_gpio.h b/sdk_liteos/boot/flashboot/include/hi_flashboot_gpio.h new file mode 100644 index 0000000000000000000000000000000000000000..b0e2afdb6f2e43aca6b1ba81758b90d19daf19e8 --- /dev/null +++ b/sdk_liteos/boot/flashboot/include/hi_flashboot_gpio.h @@ -0,0 +1,171 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __BSP_GPIO_H__ +#define __BSP_GPIO_H__ +#include +#define hi_io_val_set(cond, id, reg_val) \ + if (cond) \ + { \ + (reg_val) |= (hi_u16)(1 << (id)); \ + } \ + else \ + { \ + (reg_val) &= ~(hi_u16)(1 << (id)); \ + } + +#define hi_io_dir_get(cond, id, val_addr) \ + if ((cond) & (hi_u16)(1 << (id))) \ + { \ + *(val_addr) = HI_GPIO_DIR_OUT; \ + } \ + else \ + { \ + *(val_addr) = HI_GPIO_DIR_IN; \ + } + +#define hi_io_val_get(cond, id, val_addr) \ + if ((cond) & (hi_u16)(1 << (id))) \ + { \ + *(val_addr) = HI_GPIO_VALUE1; \ + } \ + else \ + { \ + *(val_addr) = HI_GPIO_VALUE0; \ + } + +/** +* @ingroup iot_gpio +* +* I/O level. CNcomment:GPIO电平状态。CNend +*/ +typedef enum { + HI_GPIO_VALUE0 = 0, /**< Low level.CNcomment:低电平CNend*/ + HI_GPIO_VALUE1 /**< High level.CNcomment:高电平CNend*/ +} hi_gpio_value; + +/** +* @ingroup iot_gpio +* +* I/O direction. CNcomment:GPIO方向。CNend +*/ +typedef enum { + HI_GPIO_DIR_IN = 0, /**< Input.CNcomment:输入方向CNend*/ + HI_GPIO_DIR_OUT /**< Output.CNcomment:输出方向CNend*/ +} hi_gpio_dir; + +/** +* @ingroup iot_gpio +* @brief Gets the direction of a single I/O pin.CNcomment:获取某个GPIO管脚方向。CNend +* +* @par 描述: +* Gets the direction of a single I/O pin.CNcomment:获取某个GPIO管脚方向。CNend +* +* @attention None +* @param id [IN] type #hi_gpio_idx,I/O index.CNcomment:GPIO索引。CNend +* @param dir [OUT] type #hi_gpio_dir*,I/O direction.CNcomment:GPIO方向。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_gpio.h:Describes GPIO APIs.CNcomment:文件用于描述GPIO相关接口。CNend +* @see hi_gpio_set_dir +*/ +hi_u32 hi_gpio_get_dir(hi_gpio_idx id, hi_gpio_dir *dir); + +/** +* @ingroup iot_gpio +* @brief Sets the direction of a single I/O pin.CNcomment:设置某个GPIO管脚方向。CNend +* +* @par 描述: +* Sets the direction of a single I/O pin.CNcomment:设置某个GPIO管脚方向。CNend +* +* @attention None +* @param id [IN] type #hi_gpio_idx,I/O index.CNcomment:GPIO索引。CNend +* @param dir [IN] type #hi_gpio_dir,I/O direction.CNcomment:GPIO方向。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_gpio.h:Describes GPIO APIs.CNcomment:文件用于描述GPIO相关接口。CNend +* @see hi_gpio_get_dir +*/ +hi_u32 hi_gpio_set_dir(hi_gpio_idx id, hi_gpio_dir dir); + +/** +* @ingroup iot_gpio +* @brief Obtains the input level of a single I/O pin.CNcomment:获取某个IO管脚输入电平状态。CNend +* +* @par 描述: +* Obtains the input level of a single I/O pin.CNcomment:获取某个IO管脚输入电平状态。CNend +* +* @attention None +* @param id [IN] type #hi_gpio_idx,I/O index.CNcomment:GPIO索引。CNend +* @param val [OUT] type #hi_gpio_value*,Output value.CNcomment:输出值。CNend +* @li 0:low level.CNcomment:低电平。CNend +* @li 1:high level.CNcomment:高电平。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_gpio.h:Describes GPIO APIs.CNcomment:文件用于描述GPIO相关接口。CNend +* @see None +*/ +hi_u32 hi_gpio_get_input_val(hi_gpio_idx id, hi_gpio_value *val); + +/** +* @ingroup iot_gpio +* @brief Obtains the output level of a single I/O pin.CNcomment:获取某个IO管脚输出电平状态。CNend +* +* @par 描述: +* Obtains the output level of a single I/O pin.CNcomment:获取某个IO管脚输出电平状态。CNend +* +* @attention None +* @param id [IN] type #hi_gpio_idx,I/O index.CNcomment:GPIO索引。CNend +* @param val [OUT] type #hi_gpio_value*,Output value.CNcomment:输出值。CNend +* @li 0:low level.CNcomment:低电平。CNend +* @li 1:high level.CNcomment:高电平。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_gpio.h:Describes GPIO APIs.CNcomment:文件用于描述GPIO相关接口。CNend +* @see hi_gpio_set_ouput_val。 +*/ +hi_u32 hi_gpio_get_output_val(hi_gpio_idx id, hi_gpio_value* val); + +/** +* @ingroup iot_gpio +* @brief Sets the output level of a single I/O pin.CNcomment:设置单个GPIO管脚输出电平状态。CNend +* +* @par 描述: +* Sets the output level of a single I/O pin.CNcomment:设置单个GPIO管脚输出电平状态。CNend +* +* @attention None +* +* @param id [IN] type #hi_gpio_idx,I/O index.CNcomment:GPIO索引。CNend +* @param val [IN] type #hi_gpio_value,output value. CNcomment:输出值。CNend +* @li 0:low level.CNcomment:低电平。CNend +* @li 1:high level.CNcomment:高电平。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_gpio.h:Describes GPIO APIs.CNcomment:文件用于描述GPIO相关接口。CNend +* @see hi_gpio_get_input_val。 +*/ +hi_u32 hi_gpio_set_output_val(hi_gpio_idx id, hi_gpio_value val); + +#endif diff --git a/sdk_liteos/boot/flashboot/include/hi_flashboot_io.h b/sdk_liteos/boot/flashboot/include/hi_flashboot_io.h new file mode 100644 index 0000000000000000000000000000000000000000..bbb2c87ff422957b086f42579ec6257b835bffbc --- /dev/null +++ b/sdk_liteos/boot/flashboot/include/hi_flashboot_io.h @@ -0,0 +1,160 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __FLASHBOOT_IO_H__ +#define __FLASHBOOT_IO_H__ +#include + +/** +* @ingroup iot_io +* +* I/O drive capability.CNcomment:IO驱动能力。CNend +* Note: The HI_IO_NAME_GPIO_0~HI_IO_NAME_GPIO_11 and HI_IO_NAME_GPIO_13~HI_IO_NAME_GPIO_14 driver capabilities are +* optional.The value range is HI_IO_DRIVER_STRENGTH_0~HI_IO_DRIVER_STRENGTH_3, and the other I/O ranges are +* HI_IO_DRIVER_STRENGTH_0~HI_IO_DRIVER_STRENGTH_7.CNcomment:注意:HI_IO_NAME_GPIO_0~HI_IO_NAME_GPIO_11、 +* HI_IO_NAME_GPIO_13~HI_IO_NAME_GPIO_14驱动能力可选范围是HI_IO_DRIVER_STRENGTH_0~HI_IO_DRIVER_STRENGTH_3, +* 其余IO范围是HI_IO_DRIVER_STRENGTH_0~HI_IO_DRIVER_STRENGTH_7。CNend +*/ +typedef enum { + HI_IO_DRIVER_STRENGTH_0 = 0, /**< Drive strength level 0 (highest). + CNcomment:驱动能力0级,驱动能力最高CNend */ + HI_IO_DRIVER_STRENGTH_1, /**< Drive strength level 1.CNcomment:驱动能力1级CNend */ + HI_IO_DRIVER_STRENGTH_2, /**< Drive strength level 2.CNcomment:驱动能力2级CNend */ + HI_IO_DRIVER_STRENGTH_3, /**< Drive strength level 3.CNcomment:驱动能力3级CNend */ + HI_IO_DRIVER_STRENGTH_4, /**< Drive strength level 4.CNcomment:驱动能力4级CNend */ + HI_IO_DRIVER_STRENGTH_5, /**< Drive strength level 5.CNcomment:驱动能力5级CNend */ + HI_IO_DRIVER_STRENGTH_6, /**< Drive strength level 6.CNcomment:驱动能力6级CNend */ + HI_IO_DRIVER_STRENGTH_7, /**< Drive strength level 7 (lowest). + CNcomment:驱动能力7级,驱动能力最低CNend */ + HI_IO_DRIVER_STRENGTH_MAX, +} hi_io_driver_strength; + +/** +* @ingroup iot_io +* @brief Obtains the GPIO pull-up status.CNcomment:获取某个GPIO上下拉状态。CNend +* +* @par 描述: +* Obtains the GPIO pull-up status.CNcomment:获取某个GPIO上下拉状态。CNend +* +* @attention None +* @param id [IN] type #hi_io_name,I/O index.CNcomment:硬件管脚。CNend +* @param val [OUT] type #hi_io_pull*,pull-up status.CNcomment:获取到的上下拉状态。CNend. +* +* @retval 0 Success +* @retval #HI_ERR_GPIO_INVALID_PARAMETER Failure. Input invalid. +* @par 依赖: +* @li hi_io.h:Describes I/O APIs.CNcomment:文件用于描述IO相关接口。CNend +* @see hi_io_set_pull。 +*/ +hi_u32 hi_io_get_pull(hi_io_name id, hi_io_pull *val); + +/** +* @ingroup iot_io +* @brief Obtains the I/O multiplexing.CNcomment:获取某个IO复用功能。CNend +* +* @par 描述: +* Obtains the I/O multiplexing.CNcomment:获取某个IO复用功能。CNend +* +* @attention None +* @param id [IN] type #hi_io_name,I/O index.CNcomment:硬件管脚。CNend +* @param val [OUT] type #hi_u8*,I/O multiplexing.CNcomment:IO复用功能。CNend +* +* @retval 0 Success +* @retval #HI_ERR_GPIO_INVALID_PARAMETER Failure. Input invalid. +* @par 依赖: +* @li hi_io.h:Describes I/O APIs.CNcomment:文件用于描述IO相关接口。CNend +* @see hi_io_set_func。 +*/ +hi_u32 hi_io_get_func(hi_io_name id, hi_u8 *val); + +/** +* @ingroup iot_io +* @brief Sets the I/O drive strength.CNcomment:设置某个IO驱动能力。CNend +* +* @par 描述: +* The I/O drive strength is closely related to hardware design. For details, see SoC data sheet. +CNcomment:设置某个IO驱动能力,与硬件设计强相关,详细配置参考芯片手册。CNend +* +* @attention None +* @param id [IN] type #hi_io_name,I/O index.CNcomment:硬件管脚。CNend +* @param level [IN] type #hi_io_driver_strength,I/O drive strength level.CNcomment:IO驱动能力级别。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_io.h:Describes I/O APIs.CNcomment:文件用于描述IO相关接口。CNend +* @see None +*/ +hi_u32 hi_io_set_driver_strength(hi_io_name id, hi_io_driver_strength val); + +/** +* @ingroup iot_io +* @brief Obtains the I/O drive strength.CNcomment:获取某个IO驱动能力。CNend +* +* @par 描述: +* Obtains the I/O drive strength.CNcomment:获取某个IO驱动能力。CNend +* +* @attention None +* @param id [IN] type #hi_io_name,I/O index.CNcomment:硬件管脚。CNend +* @param val [OUT] type #hi_io_driver_strength*,I/O drive strength level.CNcomment:IO驱动能力级别。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_io.h:Describes I/O APIs.CNcomment:文件用于描述IO相关接口。CNend +* @see None +*/ +hi_u32 hi_io_get_driver_strength(hi_io_name id, hi_io_driver_strength *val); + +/** +* @ingroup iot_io +* @brief Set the I/O input enable status.CNcomment:设置某个IO输入使能的状态。CNend +* +* @par 描述: +* Set the I/O input enable status.CNcomment:设置某个IO输入使能的状态。CNend +* +* @attention If the input enable status of an IO is set to FALSE in the input state, the CPU can't read the IO changes. +CNcomment:如果某个IO的输入使能设置为FALSE,CPU将读取不到该IO的变化。CNend +* @param id [IN] type #hi_io_name,I/O index.CNcomment:硬件管脚。CNend +* @param state [IN] type #hi_bool,IO input enable state.CNcomment:要设置的输入使能状态。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_io.h:Describes I/O APIs.CNcomment:文件用于描述IO相关接口。CNend +* @see None +*/ +hi_u32 hi_io_set_input_enable(hi_io_name id, hi_bool state); + +/** +* @ingroup iot_io +* @brief Get the I/O input enable status.CNcomment:获取某个IO输入使能的状态。CNend +* +* @par 描述: +* Get the I/O input enable status.CNcomment:获取某个IO输入使能的状态。CNend +* +* @attention None +* @param id [IN] type #hi_io_name,I/O index.CNcomment:硬件管脚。CNend +* @param state [OUT] type #hi_bool *,IO input enable state.CNcomment:IO的输入使能状态。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_io.h:Describes I/O APIs.CNcomment:文件用于描述IO相关接口。CNend +* @see None +*/ +hi_u32 hi_io_get_input_enable(hi_io_name id, hi_bool *state); + +#endif diff --git a/sdk_liteos/boot/flashboot/include/hi_upg_file.h b/sdk_liteos/boot/flashboot/include/hi_upg_file.h new file mode 100644 index 0000000000000000000000000000000000000000..50a0e654632ff6b5a054a7c07352580955dbdded --- /dev/null +++ b/sdk_liteos/boot/flashboot/include/hi_upg_file.h @@ -0,0 +1,208 @@ +/* + * @file hi_upg_file.h + * + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @defgroup upg Upgrade + * @ingroup system +*/ + +#ifndef __HI_UPG_FILE_H__ +#define __HI_UPG_FILE_H__ + +#include + +/** + * + * Initial vector length.CNcomment:初始向量长度。CNend + */ +#define IV_BYTE_LEN 16 + +/** + * + * RSA2048 parameter length.CNcomment:RSA2048参数长度。CNend + */ +#define RSA_2048_LEN 256 + +/** + * + * RSA2048 parameter E length.CNcomment:RSA2048参数E长度。CNend + */ +#define RSA_EXP_E_LEN 4 + +/** + * + * ECC parameter length.CNcomment:ECC参数长度。CNend + */ +#define ECC_32_BYTES 32 + +/** + * + * SHA256 hash length.CNcomment:SHA256哈希值长度。CNend + */ +#define SHA_256_LEN 32 + +/** + * + * Kernel upgrade file.CNcomment:Kernel升级文件。CNend + */ +#define HI_UPG_FILE_KERNEL 0xF0 /* Kernel upgrade file. */ + +/** + * + * FlashBoot upgrade file.CNcomment:FlashBoot升级文件。CNend + */ +#define HI_UPG_FILE_BOOT 0xE1 /* FlashBoot upgrade file. */ + +/** + * + * Parameter of sign algorithm.CNcomment:签名算法参数。CNend + */ +typedef struct { + hi_u32 hash_alg : 16; /**< HASH algorithm:0:SHA256.CNcomment:HASH算法。CNend */ + hi_u32 sign_alg : 6; /**< Sign algorithm:0:RSA-PKCS;1:RSA-PSS;0x10:ECDSA256;0x3F:SHA256.CNcomment:签名算法。CNend */ + hi_u32 sign_param : 10; /**< Sign parameter, default '0'.CNcomment:HASH算法。CNend */ +} sign_alg_param; + +typedef struct { + hi_u8 mod_n[RSA_2048_LEN]; /**< Mod N.CNcomment:RSA参数N。CNend */ + hi_u8 exp_e[RSA_EXP_E_LEN]; /**< Exp E.CNcomment:RSA参数E。CNend */ + hi_u8 padding[28]; /**< Padding field:28.CNcomment:填充字段。CNend */ +} upg_rsa_key; + +typedef struct { + hi_u8 sign[RSA_2048_LEN]; /**< RSA signature.CNcomment:RSA签名。CNend */ +} upg_rsa_sign; + +typedef struct { + hi_u8 px[ECC_32_BYTES]; /**< Pubkey x.CNcomment:ECC密钥x。CNend */ + hi_u8 py[ECC_32_BYTES]; /**< Pubkey y.CNcomment:ECC密钥y。CNend */ + hi_u8 padding[224]; /**< Padding field:224. CNcomment:填充字段。CNend */ +} upg_ecc_key; + +typedef struct { + hi_u8 r[ECC_32_BYTES]; /**< Signature of ECC.CNcomment:ECC签名信息r。CNend */ + hi_u8 s[ECC_32_BYTES]; /**< Signature of ECC.CNcomment:ECC签名信息s。CNend */ + hi_u8 padding[192]; /**< Padding field:192.CNcomment:填充字段。CNend */ +} upg_ecc_sign; + +typedef struct { + hi_u8 padding[288]; /**< Padding field:288.CNcomment:填充字段。CNend */ +} upg_sha256_key; + +typedef struct { + hi_u8 check_sum[SHA_256_LEN]; /**< Hash value of SHA256.CNcomment:SHA256算法哈希值。CNend */ + hi_u8 padding[224]; /**< Padding field:224.CNcomment:填充字段。CNend */ +} upg_sha256_sign; + +/** + * @ingroup upg + * + * Parameters of user-defined fields.CNcomment:用户自定义字段。CNend + */ +typedef struct { + hi_u8 reserved[32]; /**< 32:Reserved for user.CNcomment:用户自定义字段。CNend */ +}hi_upg_user_info; + +typedef struct { + hi_u32 image_id; /**< Identity of upgrade file Key Area.CNcomment:升级文件魔术字。CNend */ + hi_u32 struct_version; /**< The structure of upgrade file version.CNcomment:升级文件结构体版本号。CNend */ + hi_u32 section_offset; /**< Offset of upgrade Section.CNcomment:Section段偏移。CNend */ + hi_u32 section_len; /**< Length of upgrade Section.CNcomment:Section段长度。CNend */ + hi_upg_user_info user_info; /**< Reserved for user.CNcomment:用户自定义字段。CNend */ + hi_u8 file_type; /**< Upgrade file type:0xF0: kernel file; 0xE1: boot file.CNcomment:升级文件类型。CNend */ + hi_u8 file_version; /**< File Version, for anti-rollback. [0, 16] for boot file and [0, 48] for kernel file. + CNcomment:升级文件结构体版本号。CNend */ + hi_u8 encrypt_flag; /**< 0x42: Section Area is not encrypted; other: Section Area is encrypted. + CNcomment:Section段加密标志。CNend */ + hi_u8 file_attr; /**< File Attributes.CNcomment:文件属性。CNend */ + hi_u32 file_len; /**< Entire file length.CNcomment:升级文件长度。CNend */ + hi_u32 key_len; /**< Length of Key(288Bytes).True length:RSA2048: 272 Bytes, ECDSA: 64Bytes. + CNcomment:密钥长度。CNend */ + sign_alg_param param; /**< Parma of the signature algorithm.CNcomment:签名算法参数。CNend */ + hi_u8 aes_key[IV_BYTE_LEN]; /**< Part of key factor.CNcomment:AES密钥。CNend */ + hi_u8 aes_iv[IV_BYTE_LEN]; /**< The IV (AES-256 CBC-mode) to encrypt Section.CNcomment:AES初始向量。CNend */ +} hi_upg_common_head; + +typedef struct { + hi_u32 image_id; /**< Identity of upgrade file Key Area.CNcomment:升级文件魔术字。CNend */ + hi_u32 struct_version; /**< The structure of upgrade file Section Area.CNcomment:升级文件结构体版本号。CNend */ + sign_alg_param param; /**< The signature algorithm.CNcomment:签名算法参数。CNend */ + hi_u8 section_count; /**< The number of sections.CNcomment:Section段个数。CNend */ + hi_u8 reserved[27]; /**< 27 bytes reserved.CNcomment:保留字段。CNend */ + hi_u8 section0_compress; /**< Whether section 0 is compressed.CNcomment:Section0是否压缩。CNend */ + hi_u8 pad0[3]; /**< 3 bytes padding.CNcomment:填充字段。CNend */ + hi_u32 section0_offset; /**< Offset of Section0.CNcomment:Section0段偏移。CNend */ + hi_u32 section0_len; /**< Length of Section0, aligned to 16 bytes.CNcomment:Section0段长度。CNend */ + hi_u8 section1_compress; /**< Whether section 1 is compressed.CNcomment:Section1是否压缩Nend */ + hi_u8 pad1[3]; /**< 3 bytes padding.CNcomment:填充字段。CNend */ + hi_u32 section1_offset; /**< Offset of Section1.CNcomment:Section1段偏移。CNend */ + hi_u32 section1_len; /**< Length of Section1, aligned to 16 bytes.CNcomment:Section1段长度。CNend */ +} hi_upg_section_head; + +typedef struct { + upg_rsa_key key; /**< Key of rsa.CNcomment:RSA算法密钥。CNend */ + upg_rsa_sign sign; /**< Sign of rsa.CNcomment:RSA算法签名。CNend */ +} hi_upg_rsa_alg; + +typedef struct { + upg_ecc_key key; /**< Key of ecc.CNcomment:ECC算法密钥。CNend */ + upg_ecc_sign sign; /**< Sign of ecc.CNcomment:ECC算法签名。CNend */ +} hi_upg_ecc_alg; + +typedef struct { + upg_sha256_key key; /**< Padding field.CNcomment:填充字段。CNend */ + upg_sha256_sign sign; /**< Hash of sha256.CNcomment:SHA256算法哈希值。CNend */ +} hi_upg_sha256_alg; + +typedef struct { + union { + upg_rsa_key rsa; /**< Key of rsa.CNcomment:rsa密钥。CNend */ + upg_ecc_key ecc; /**< Key of ecc.CNcomment:ecc密钥。CNend */ + upg_sha256_key sha; /**< Padding field.CNcomment:填充字段。CNend */ + } key; +}hi_upg_key; + +typedef struct { + union { + upg_rsa_sign rsa; /**< Sign of rsa.CNcomment:rsa签名。CNend */ + upg_ecc_sign ecc; /**< Sign of ecc.CNcomment:ecc签名。CNend */ + upg_sha256_sign sha; /**< Hash of sha256.CNcomment:SHA256哈希。CNend */ + } sign; +}hi_upg_sign; + +typedef struct { + hi_upg_common_head common; /**< Common head of upg file.CNcomment:公共文件头。CNend */ + union { + hi_upg_rsa_alg rsa; /**< Key and sign of RSA.CNcomment:RSA密钥及签名信息。CNend */ + hi_upg_ecc_alg ecc; /**< Key and sign of ECC.CNcomment:ECC密钥及签名信息。CNend */ + hi_upg_sha256_alg sha;/**< Key and sign of SHA256.CNcomment:SHA256密钥及签名信息。CNend */ + } sign_alg; +} hi_upg_head; + +typedef struct { + hi_upg_common_head common; /**< Common head of upg file.CNcomment:公共文件头。CNend */ + union { + hi_upg_rsa_alg rsa; /**< Key and sign of RSA.CNcomment:RSA密钥及签名信息。CNend */ + hi_upg_ecc_alg ecc; /**< Key and sign of ECC.CNcomment:ECC密钥及签名信息。CNend */ + hi_upg_sha256_alg sha; /**< Key and sign of SHA256.CNcomment:SHA256密钥及签名信息。CNend */ + } sign_alg; + hi_upg_section_head section; /**< Head of code section.CNcomment:Code段头信息。CNend */ + hi_upg_sign section_sign; /**< Sign of code section.CNcomment:Code段签名信息。CNend */ +} hi_upg_file_head; + +#endif + diff --git a/sdk_liteos/boot/flashboot/include/lzmaram.h b/sdk_liteos/boot/flashboot/include/lzmaram.h new file mode 100644 index 0000000000000000000000000000000000000000..87d26bc3de4b719e95d6618d27796faccd38af7c --- /dev/null +++ b/sdk_liteos/boot/flashboot/include/lzmaram.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __LZMARAM_H__ +#define __LZMARAM_H__ + +#include + +typedef hi_u32 (*lzma_stream_fct)(hi_u32 offset, hi_u8 *buffer, hi_u32 size); + +typedef struct { + hi_u32 offset; + lzma_stream_fct func; +} lzma_stream; + +typedef struct { + hi_pbyte (*alloc)(hi_pbyte p, unsigned int size); + void (*free)(hi_pbyte p, hi_pbyte address); /* address can be 0 */ +} i_sz_alloc; + +extern unsigned int LzmaDecode2(const unsigned char *prop_data, unsigned int prop_size, hi_u32 *status, + i_sz_alloc *alloc, lzma_stream *in_stream, lzma_stream *out_stream, + unsigned int uncompress_len, unsigned int compress_len); + +unsigned int hi_lzma_decompress(const hi_u8 lzma_head[13], hi_u32 head_size, /* head 13B */ + unsigned int compress_len, + lzma_stream_fct in_func, lzma_stream_fct out_func); +unsigned int hi_lzma_get_uncompress_len(const hi_u8 lzma_head[13], hi_u32 head_size, /* head 13B */ + unsigned int *pul_decompressed_data_len, unsigned int *dic_size); +unsigned int hi_lzma_mem_detect(const hi_u8 lzma_head[13], hi_u32 head_size); /* head 13B */ + +#endif + diff --git a/sdk_liteos/boot/flashboot/lzmaram/SConscript b/sdk_liteos/boot/flashboot/lzmaram/SConscript new file mode 100755 index 0000000000000000000000000000000000000000..aceb2b6a9464ce64030c1f9c5374ec933dcab384 --- /dev/null +++ b/sdk_liteos/boot/flashboot/lzmaram/SConscript @@ -0,0 +1,6 @@ +Import('env') + +env = env.Clone() + +objs = env.Object(Glob('*.c')) +Return('objs') diff --git a/sdk_liteos/boot/flashboot/lzmaram/lzmaram.c b/sdk_liteos/boot/flashboot/lzmaram/lzmaram.c new file mode 100644 index 0000000000000000000000000000000000000000..8ed8f0735c9a255a1191609e8d76e2d372dc9d3d --- /dev/null +++ b/sdk_liteos/boot/flashboot/lzmaram/lzmaram.c @@ -0,0 +1,224 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include + +#define LZMA_DIC_MIN (1 << 12) +#define LZMA_BASE_SIZE 1846 +#define LZMA_LIT_SIZE 768 +#define IN_BUF_SIZE 0x1000 +#define OUT_BUF_SIZE 0x1000 + +static hi_pbyte lzma_alloc(hi_pbyte unused, size_t size) +{ + hi_unref_param(unused); + hi_pbyte addr = (hi_pbyte)boot_malloc(size); + if (!addr) { + boot_msg1("\n LZMA_Alloc fail= ", size); + } + return addr; +} + +static void lzma_free(hi_pbyte unused, hi_pbyte address) +{ + hi_unref_param(unused); + if (address == HI_NULL) { + return; + } + + boot_free(address); +} + +/** +* @ingroup LZMA +* @brief : get file size and dictionary size before LZMA compressed +* +* @par :description: +* get file size and dictionary size before LZMA compressed +* +* @attention: nothing +* @param lzma_head [IN] type #hi_u8*-LZMA head +* @param pulDecompressedDataLen [OUT] type #unsigned int*, size before compressed +* @param dic_size [OUT] type #unsigned int* , dictionary size +* +* @retval #HI_ERR_SUCCESS success +* @retval # other value: fail, see hi_errno.h for details +* @par dependency: +* +* @see : nothing + */ +unsigned int hi_lzma_get_uncompress_len(const hi_u8 lzma_head[13], hi_u32 head_size, /* head 13B */ + unsigned int *pul_decompressed_data_len, unsigned int *dic_size) +{ + unsigned int uncompressed_len; + unsigned int uncompressed_len_high; + + if ((lzma_head == HI_NULL) + || (pul_decompressed_data_len == HI_NULL) + || head_size > 13) { /* head 13B */ + boot_msg1("[lzma get uncompress len]head size", head_size); + return HI_ERR_LZMA_PARAM; + } + + uncompressed_len = (unsigned int)lzma_head[5] | /* index 5, low 8bits */ + ((unsigned int)lzma_head[6] << 8) | /* index 6, bits 8-15 */ + ((unsigned int)lzma_head[7] << 16) | /* index 7, bits 16-23 */ + ((unsigned int)lzma_head[8] << 24); /* index 8, bits 24-32 */ + uncompressed_len_high = (unsigned int)lzma_head[9] | /* index 9, low 8bits */ + ((unsigned int)lzma_head[10] << 8) | /* index 10, bits 8-15 */ + ((unsigned int)lzma_head[11] << 16) | /* index 11, bits 16-23 */ + ((unsigned int)lzma_head[12] << 24); /* index 12, bits 24-32 */ + + if ((uncompressed_len_high != 0)) { + /* uncompressed file is too long, output buffer is not enough */ + boot_msg1("[lzma get uncompress len]high", uncompressed_len_high); + return HI_ERR_LZMA_LEN; + } + + *dic_size = (unsigned int)lzma_head[1] | /* index 1, low 8bits */ + ((unsigned int)lzma_head[2] << 8) | /* index 2, bits 8-15 */ + ((unsigned int)lzma_head[3] << 16) | /* index 3, bits 16-23 */ + ((unsigned int)lzma_head[4] << 24); /* index 4, bits 24-32 */ + + if (*dic_size < LZMA_DIC_MIN) { + *dic_size = LZMA_DIC_MIN; + } + + *pul_decompressed_data_len = uncompressed_len; + return HI_ERR_SUCCESS; +} + +/** +* @ingroup LZMA +* @brief : LZMA decompress for sections +* +* @par description: +* LZMA decompress for sections +* +* @attention : nothing +* @param lzma_head [IN] type #hi_u8*-LZMA head +* @param compress_len [IN] type #unsigned int, size after compressed +* @param in_func [IN] type #LZMA_STREAM_FCT, get content of compressed +* @param out_func [IN] type #LZMA_STREAM_FCT, save the content after compressed +* +* @retval #HI_ERR_SUCCESS success +* @retval # other value: fail, see hi_errno.h for details +* @par dependency: +* +* @see : nothing + */ +unsigned int hi_lzma_decompress(const hi_u8 lzma_head[13], hi_u32 head_size, /* head 13B */ + unsigned int compress_len, lzma_stream_fct in_func, lzma_stream_fct out_func) +{ + unsigned int ret; + unsigned int lzma_stat = 0; + unsigned int uncompress_len = 0; + unsigned int dic_size = 0; + i_sz_alloc alloc = { 0 }; + lzma_stream in_stream; + lzma_stream out_stream; + in_stream.func = in_func; + in_stream.offset = 13; /* offset 13 */ + out_stream.func = out_func; + out_stream.offset = 0; + + alloc.alloc = lzma_alloc; + alloc.free = lzma_free; + + ret = hi_lzma_get_uncompress_len(lzma_head, head_size, &uncompress_len, &dic_size); + if (ret != HI_ERR_SUCCESS) { + boot_msg1("[hi lzma decompress]get uncompress len:", ret); + } + ret = LzmaDecode2(lzma_head, 5, &lzma_stat, &alloc, &in_stream, /* size 5 */ + &out_stream, compress_len - 13, uncompress_len); /* length subtract 13 */ + if (ret != 0) { + boot_msg1("[hi lzma decompress]decode ret:", ret); + } + + return (ret ? (HI_ERR_LZMA_DECODE + ret) : HI_ERR_SUCCESS); +} + +/** +* @ingroup LZMA +* @brief LZMA RAM usage detect +* +* @par description: +* LZMA RAM usage detect, detect for whether the current RAM is enough for LZMA uncompress +* +* @attention : nothing +* @param lzma_head [IN] type #hi_u8*, LZMA head +* +* @retval #HI_ERR_SUCCESS success +* @retval # other value: fail, see hi_errno.h for details +* @par dependency: +* +* @see : nothing + */ +unsigned int hi_lzma_mem_detect(const hi_u8 lzma_head[13], hi_u32 head_size) /* head 13B */ +{ + unsigned int ret; + unsigned int compress_len = 0; + unsigned int dic_size = 0; + unsigned char d; + unsigned int lc, lp; + unsigned int malloc_size[5] = { /* size 5*4 */ + 0, + }; + unsigned char *addr[5] = { /* addr 5B */ + HI_NULL, + }; + unsigned int array_size = sizeof(addr) / sizeof(addr[0]); + unsigned int i; + + ret = hi_lzma_get_uncompress_len(lzma_head, head_size, &compress_len, &dic_size); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + d = lzma_head[0]; + if (d >= (9 * 5 * 5)) { /* less than 9*5*5 */ + boot_msg1("[hi_lzma_mem_detect]d", d); + return HI_ERR_FAILURE; + } + + lc = d % 9; /* remain of devide 9 */ + d /= 9; /* counts of 9 */ + lp = d % 5; /* remain of devide 5 */ + + malloc_size[0] = (((unsigned int)LZMA_BASE_SIZE + (LZMA_LIT_SIZE << (lc + lp))) * 2); /* shifts (lc+lp)*2 */ + malloc_size[1] = IN_BUF_SIZE; /* index 1 */ + malloc_size[2] = OUT_BUF_SIZE; /* index 2 */ + malloc_size[3] = dic_size; /* index 3 */ + malloc_size[4] = 0x400; /* for security ,index 4:0x400 */ + boot_msg2("[hi_lzma_mem_detect]malloc_size[0-3]", malloc_size[0], dic_size); + + for (i = 0; i < array_size; i++) { + addr[i] = boot_malloc(malloc_size[i]); + + if (addr[i] == HI_NULL) { + ret = HI_ERR_FAILURE; + break; + } + } + + for (i = 0; i < array_size; i++) { + if (addr[array_size - i - 1] != HI_NULL) { + boot_free(addr[array_size - i - 1]); + } + } + + return ret; +} diff --git a/sdk_liteos/boot/flashboot/module_config.mk b/sdk_liteos/boot/flashboot/module_config.mk new file mode 100644 index 0000000000000000000000000000000000000000..8c1d3c5a9fb79444aa496fbfad6c34422d0cfcd8 --- /dev/null +++ b/sdk_liteos/boot/flashboot/module_config.mk @@ -0,0 +1,56 @@ +boot_srcs = startup drivers/lsadc drivers/flash drivers/efuse drivers/gpio drivers/io common/crc32 common/nvm common/partition_table upg lib/lzma lzmaram secure +boot_common_srcs = ../commonboot/crc32 ../commonboot/efuse ../commonboot/flash +BOOT_CCFLAGS := -mabi=ilp32 -march=rv32imc -freorder-blocks-algorithm=simple -fno-schedule-insns -nostdinc -fno-aggressive-loop-optimizations -fno-builtin -fno-exceptions -fno-short-enums -mtune=size -msmall-data-limit=0 -Wall -Werror -Os -std=c99 -falign-functions=2 -fdata-sections -ffunction-sections -fno-common -fstack-protector-strong +BOOT_DEFINE := -DARCH_RISCV -DLOS_COMPILE_LDM -DHI_BOARD_ASIC +BOOT_INC := -I$(MAIN_TOPDIR)/boot/flashboot/fixed/include \ + -I$(MAIN_TOPDIR)/boot/flashboot/upg \ + -I$(MAIN_TOPDIR)/boot/flashboot/include \ + -I$(MAIN_TOPDIR)/boot/flashboot/drivers/lsadc \ + -I$(MAIN_TOPDIR)/boot/flashboot/drivers/gpio \ + -I$(MAIN_TOPDIR)/boot/flashboot/drivers/io \ + -I$(MAIN_TOPDIR)/boot/flashboot/drivers/efuse \ + -I$(MAIN_TOPDIR)/boot/flashboot/include/lzma \ + -I$(MAIN_TOPDIR)/boot/flashboot/lib/lzma \ + -I$(MAIN_TOPDIR)/boot/flashboot/secure \ + -I$(MAIN_TOPDIR)/boot/commonboot + +ifeq ($(CONFIG_COMPRESSION_OTA_SUPPORT), y) + BOOT_DEFINE += -DCONFIG_COMPRESSION_OTA_SUPPORT +endif + +ifeq ($(CONFIG_DUAL_PARTITION_OTA_SUPPORT), y) + BOOT_DEFINE += -DCONFIG_DUAL_PARTITION_OTA_SUPPORT +endif + +ifeq ($(CONFIG_TARGET_SIG_ECC), y) + BOOT_DEFINE += -DCONFIG_TARGET_SIG_ECC +endif + +ifeq ($(CONFIG_TARGET_SIG_RSA_V15), y) + BOOT_DEFINE += -DCONFIG_TARGET_SIG_RSA_V15 +endif + +ifeq ($(CONFIG_TARGET_SIG_RSA_PSS), y) + BOOT_DEFINE += -DCONFIG_TARGET_SIG_RSA_PSS +endif + +ifeq ($(CONFIG_FLASH_ENCRYPT_SUPPORT), y) + BOOT_DEFINE += -DCONFIG_FLASH_ENCRYPT_SUPPORT +endif + +ifeq ($(CONFIG_FACTORY_TEST_SUPPORT), y) + BOOT_DEFINE += -DCONFIG_FACTORY_TEST_SUPPORT +endif + +ifeq ($(CONFIG_QUICK_SEND_MODE), y) + BOOT_DEFINE += -DCONFIG_QUICK_SEND_MODE +endif + +ifeq ($(CONFIG_CHIP_PKT_48K), y) + BOOT_DEFINE += -DCONFIG_CHIP_PKT_48K +else + BOOT_DEFINE += -DCONFIG_CHIP_PKT_32K +endif + +BOOT_ASFLAGS = -mabi=ilp32 -march=rv32imc -x assembler-with-cpp -Os -Wall -Werror -nostdinc -fno-common +BOOT_LINK_FLAGS = -nostdlib -nostartfiles -static --gc-sections diff --git a/sdk_liteos/boot/flashboot/secure/SConscript b/sdk_liteos/boot/flashboot/secure/SConscript new file mode 100755 index 0000000000000000000000000000000000000000..aceb2b6a9464ce64030c1f9c5374ec933dcab384 --- /dev/null +++ b/sdk_liteos/boot/flashboot/secure/SConscript @@ -0,0 +1,6 @@ +Import('env') + +env = env.Clone() + +objs = env.Object(Glob('*.c')) +Return('objs') diff --git a/sdk_liteos/boot/flashboot/secure/crypto.c b/sdk_liteos/boot/flashboot/secure/crypto.c new file mode 100644 index 0000000000000000000000000000000000000000..f319ef509c7852b2a1f0a3079cd7f0051cd7f14b --- /dev/null +++ b/sdk_liteos/boot/flashboot/secure/crypto.c @@ -0,0 +1,1162 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * CONFIG_FLASH_ENCRYPT_SUPPORT: + * --Determine that the flash crypto function is supported; + * This configuration can be modified in menuconfig. + */ +#ifdef CONFIG_FLASH_ENCRYPT_SUPPORT +#include +#include "crypto.h" +#include +#include + +boot_crypto_ctx g_boot_crypto_param = {0}; +boot_crypto_ctx g_boot_decrypt_param = {0}; +boot_crypto_ctx *boot_crypto_get_ctx(hi_void) +{ + return &g_boot_crypto_param; +} + +boot_crypto_ctx *boot_decrypt_get_ctx(hi_void) +{ + return &g_boot_decrypt_param; +} + +hi_u32 crypto_check_image_id(hi_u32 image_id) +{ + if (image_id != PRODUCT_UPG_FILE_IMAGE_ID) { + boot_msg1("[crypto check image id]fail, id:", image_id); + return HI_PRINT_ERRNO_CRYPTO_CHECK_KERNEL_ERR; + } + return HI_ERR_SUCCESS; +} + +hi_bool crypto_check_kernel_file(hi_u32 addr_start) +{ + hi_u32 ret; + hi_upg_head upg_head; + ret = hi_flash_read(addr_start, sizeof(hi_upg_head), (hi_u8 *)&upg_head); + if (ret != HI_ERR_SUCCESS) { + return HI_FALSE; + } + hi_upg_common_head *common_head = &(upg_head.common); + + ret = crypto_check_image_id(common_head->image_id); + if (ret != HI_ERR_SUCCESS) { + return HI_FALSE; + } + + return HI_TRUE; +} + +hi_void change_kernel(hi_void) +{ + hi_nv_ftm_startup_cfg *cfg = boot_upg_get_cfg(); + hi_flash_partition_table *partition = hi_get_partition_table(); + uintptr_t kernel_a_addr = partition->table[HI_FLASH_PARTITON_KERNEL_A].addr; + uintptr_t kernel_b_addr = partition->table[HI_FLASH_PARTITON_KERNEL_B].addr; + + if (cfg->addr_start == kernel_a_addr) { + cfg->addr_start = kernel_b_addr; + } else { + cfg->addr_start = kernel_a_addr; + } +} + +hi_u32 boot_get_crypto_kernel_start(hi_u32 *flash_offset) +{ + hi_nv_ftm_startup_cfg *cfg = boot_upg_get_cfg(); + if (!crypto_check_kernel_file(cfg->addr_start)) { + return HI_PRINT_ERRNO_CRYPTO_CHECK_KERNEL_ERR; + } + + boot_get_start_addr_offset(cfg->addr_start, flash_offset); + + return HI_ERR_SUCCESS; +} + +hi_void crypto_clear_content(hi_u8 *content, hi_u32 content_len) +{ + if ((content == HI_NULL) || (content_len == 0)) { + return; + } + + hi_u32 cs = (uintptr_t)content ^ content_len ^ 0x0 ^ content_len; + (hi_void)memset_s(content, content_len, 0x0, content_len, cs); +} + +static hi_u32 crypto_load_salt(crypto_workkey_partition part, hi_flash_crypto_content *key_content) +{ + hi_u32 ret = HI_ERR_SUCCESS; + hi_u8 salt_e[ROOT_SALT_LENGTH] = { 0 }; + + hi_u32 cs = (uintptr_t)salt_e ^ (hi_u32)sizeof(salt_e) ^ 0x0 ^ ROOT_SALT_LENGTH; + (hi_void) memset_s(salt_e, sizeof(salt_e), 0x0, ROOT_SALT_LENGTH, cs); + if (part == CRYPTO_WORKKEY_KERNEL_A) { + ret = hi_factory_nv_read(HI_NV_FTM_KERNELA_WORK_ID, key_content, sizeof(hi_flash_crypto_content), 0); + if (ret != HI_ERR_SUCCESS) { + goto fail; + } + } else if (part == CRYPTO_WORKKEY_KERNEL_A_BACKUP) { + ret = hi_factory_nv_read(HI_NV_FTM_BACKUP_KERNELA_WORK_ID, key_content, sizeof(hi_flash_crypto_content), 0); + if (ret != HI_ERR_SUCCESS) { + goto fail; + } + } + + if (memcmp(key_content->root_salt, salt_e, ROOT_SALT_LENGTH) == HI_ERR_SUCCESS) { + ret = HI_PRINT_ERRNO_CRYPTO_SALT_EMPTY_ERR; + goto fail; + } +fail: + return ret; +} + +static hi_u32 crypto_get_root_salt(hi_flash_crypto_content *key_content) +{ + hi_u32 ret = crypto_load_salt(CRYPTO_WORKKEY_KERNEL_A, key_content); + if (ret != HI_ERR_SUCCESS) { + ret = crypto_load_salt(CRYPTO_WORKKEY_KERNEL_A_BACKUP, key_content); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + } + + return HI_ERR_SUCCESS; +} + +static hi_u32 crypto_prepare(hi_flash_crypto_content *save_content) +{ + hi_u32 ret; + hi_u8 rootkey_iv[ROOTKEY_IV_BYTE_LENGTH]; + hi_cipher_kdf_ctrl ctrl; + hi_u32 cs; + + ret = hi_cipher_init(); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + ret = crypto_get_root_salt(save_content); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + cs = (uintptr_t)rootkey_iv ^ sizeof(rootkey_iv) ^ ((uintptr_t)save_content->root_salt) ^ ROOT_SALT_LENGTH; + ret = memcpy_s(rootkey_iv, sizeof(rootkey_iv), save_content->root_salt, ROOT_SALT_LENGTH, cs); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + ctrl.salt = rootkey_iv; + ctrl.salt_len = sizeof(rootkey_iv); + ctrl.kdf_cnt = KDF_ITERATION_CNT; + /* The HUK value is automatically generated. The hardware directly obtains the HUK + from the eFUSE and generates a fixed root key. */ + /* 自动生成HUK值的方式,硬件直接从EFUSE中获取HUK,生成根密钥固定 */ + ctrl.kdf_mode = HI_CIPHER_SSS_KDF_KEY_STORAGE; + return hi_cipher_kdf_key_derive(&ctrl); +} + +static hi_u32 crypto_destory(hi_void) +{ + return hi_cipher_deinit(); +} + +hi_bool is_upg_need_crypto(hi_void) +{ + hi_nv_ftm_startup_cfg *cfg = boot_upg_get_cfg(); + if ((cfg->mode == HI_UPG_MODE_UPGRADE) && + ((cfg->reset_cnt >= 1) && (cfg->reset_cnt < cfg->cnt_max))) { + return HI_TRUE; + } + + return HI_FALSE; +} + +static hi_void crpto_set_aes_ctrl_default_value(hi_cipher_aes_ctrl *aes_ctrl) +{ + if (aes_ctrl == HI_NULL) { + return; + } + aes_ctrl->random_en = HI_FALSE; + aes_ctrl->key_from = HI_CIPHER_AES_KEY_FROM_CPU; + aes_ctrl->work_mode = HI_CIPHER_AES_WORK_MODE_CBC; + aes_ctrl->key_len = HI_CIPHER_AES_KEY_LENGTH_256BIT; +} + +static hi_u32 crypto_encrypt_hash(hi_flash_crypto_content *key_content) +{ + hi_cipher_aes_ctrl aes_ctrl; + hi_u32 ret; + hi_u32 content_size = (hi_u32)sizeof(hi_flash_crypto_content); + hi_u32 encrypt_size = content_size - ROOT_SALT_LENGTH - IV_BYTE_LENGTH; + + hi_flash_crypto_content *data_tmp = (hi_flash_crypto_content *)boot_malloc(content_size); + if (data_tmp == HI_NULL) { + return HI_PRINT_ERRNO_MALLOC_EXAUST_ERR; + } + + hi_u32 cs = (uintptr_t)(aes_ctrl.iv) ^ (hi_u32)sizeof(aes_ctrl.iv) ^ (uintptr_t)(key_content->iv_nv) ^ + IV_BYTE_LENGTH; + ret = (hi_u32)memcpy_s(aes_ctrl.iv, sizeof(aes_ctrl.iv), key_content->iv_nv, IV_BYTE_LENGTH, cs); + if (ret != EOK) { + goto fail; + } + + aes_ctrl.random_en = HI_FALSE; + aes_ctrl.key_from = HI_CIPHER_AES_KEY_FROM_KDF; + aes_ctrl.work_mode = HI_CIPHER_AES_WORK_MODE_CBC; + aes_ctrl.key_len = HI_CIPHER_AES_KEY_LENGTH_256BIT; + ret = hi_cipher_aes_config(&aes_ctrl); + if (ret != HI_ERR_SUCCESS) { + goto crypto_fail; + } + ret = hi_cipher_aes_crypto((hi_u32)(uintptr_t)key_content->iv_content, (hi_u32)(uintptr_t)(data_tmp->iv_content), + encrypt_size, HI_TRUE); + if (ret != HI_ERR_SUCCESS) { + goto crypto_fail; + } + + hi_u8* key_content_ptr = key_content->iv_content; + hi_u8* data_tmp_ptr = data_tmp->iv_content; + cs = (uintptr_t)key_content_ptr ^ encrypt_size ^ (uintptr_t)data_tmp_ptr ^ encrypt_size; + ret = memcpy_s(key_content_ptr, encrypt_size, data_tmp_ptr, encrypt_size, cs); + +crypto_fail: + (hi_void) hi_cipher_aes_destroy_config(); +fail: + crypto_clear_content((hi_u8 *)data_tmp, content_size); + crypto_mem_free(data_tmp); + return ret; +} + +static hi_u32 crypto_decrypt_hash(hi_flash_crypto_content *key_content) +{ + hi_u32 ret; + hi_u32 cs; + hi_u32 content_size = (hi_u32)sizeof(hi_flash_crypto_content); + + hi_flash_crypto_content *content_tmp = (hi_flash_crypto_content *)boot_malloc(content_size); + if (content_tmp == HI_NULL) { + return HI_PRINT_ERRNO_MALLOC_EXAUST_ERR; + } + + cs = (uintptr_t)(content_tmp) ^ content_size ^ (uintptr_t)(key_content) ^ content_size; + ret = (hi_u32)memcpy_s(content_tmp, content_size, key_content, content_size, cs); + if (ret != EOK) { + goto fail; + } + + hi_cipher_aes_ctrl aes_ctrl = { + .random_en = HI_FALSE, + .key_from = HI_CIPHER_AES_KEY_FROM_KDF, + .work_mode = HI_CIPHER_AES_WORK_MODE_CBC, + .key_len = HI_CIPHER_AES_KEY_LENGTH_256BIT, + }; + cs = (uintptr_t)(aes_ctrl.iv) ^ (hi_u32)sizeof(aes_ctrl.iv) ^ (uintptr_t)(content_tmp->iv_nv) ^ IV_BYTE_LENGTH; + ret = (hi_u32)memcpy_s(aes_ctrl.iv, sizeof(aes_ctrl.iv), content_tmp->iv_nv, IV_BYTE_LENGTH, cs); + if (ret != EOK) { + goto fail; + } + ret = hi_cipher_aes_config(&aes_ctrl); + if (ret != HI_ERR_SUCCESS) { + goto crypto_fail; + } + ret = hi_cipher_aes_crypto((uintptr_t)content_tmp->iv_content, (uintptr_t)key_content->iv_content, + content_size - ROOT_SALT_LENGTH - IV_BYTE_LENGTH, HI_FALSE); + if (ret != HI_ERR_SUCCESS) { + goto crypto_fail; + } + +crypto_fail: + (hi_void) hi_cipher_aes_destroy_config(); +fail: + crypto_clear_content((hi_u8 *)content_tmp, content_size); + crypto_mem_free(content_tmp); + return ret; +} + +static hi_u32 crypto_save_work_key(crypto_workkey_partition part, hi_flash_crypto_content *key_content) +{ + hi_u32 ret; + hi_u32 cs; + hi_u32 content_size = (hi_u32)sizeof(hi_flash_crypto_content); + hi_flash_crypto_content *content_tmp = (hi_flash_crypto_content *)boot_malloc(content_size); + if (content_tmp == HI_NULL) { + return HI_PRINT_ERRNO_MALLOC_EXAUST_ERR; + } + + cs = (uintptr_t)(content_tmp) ^ content_size ^ (uintptr_t)(key_content) ^ content_size; + ret = (hi_u32)memcpy_s(content_tmp, content_size, key_content, content_size, cs); + if (ret != EOK) { + goto fail; + } + + /* 先加密,再存到工厂区NV中 */ + ret = crypto_encrypt_hash(content_tmp); + if (ret != HI_ERR_SUCCESS) { + goto fail; + } + + if ((hi_u32)part & CRYPTO_WORKKEY_KERNEL_A) { + ret = hi_factory_nv_write(HI_NV_FTM_KERNELA_WORK_ID, content_tmp, content_size, 0); + if (ret != HI_ERR_SUCCESS) { + ret = HI_PRINT_ERRNO_CRYPTO_KEY_SAVE_ERR; + goto fail; + } + } + if ((hi_u32)part & CRYPTO_WORKKEY_KERNEL_A_BACKUP) { + ret = hi_factory_nv_write(HI_NV_FTM_BACKUP_KERNELA_WORK_ID, content_tmp, content_size, 0); + if (ret != HI_ERR_SUCCESS) { + ret = HI_PRINT_ERRNO_CRYPTO_KEY_SAVE_ERR; + goto fail; + } + } + +fail: + crypto_clear_content((hi_u8 *)content_tmp, content_size); + crypto_mem_free(content_tmp); + return ret; +} + +static hi_u32 crypto_load_key_content(crypto_workkey_partition part, hi_flash_crypto_content *key_content) +{ + hi_u32 ret = HI_ERR_SUCCESS; + hi_u8 hash[SHA_256_LENGTH]; + hi_u8 key_e[KEY_BYTE_LENGTH] = { 0 }; + + hi_u32 cs = (uintptr_t)key_e ^ (hi_u32)sizeof(key_e) ^ 0x0 ^ KEY_BYTE_LENGTH; + (hi_void) memset_s(key_e, sizeof(key_e), 0x0, KEY_BYTE_LENGTH, cs); + if (part == CRYPTO_WORKKEY_KERNEL_A) { + ret = hi_factory_nv_read(HI_NV_FTM_KERNELA_WORK_ID, key_content, sizeof(hi_flash_crypto_content), 0); + if (ret != HI_ERR_SUCCESS) { + goto fail; + } + } else if (part == CRYPTO_WORKKEY_KERNEL_A_BACKUP) { + ret = hi_factory_nv_read(HI_NV_FTM_BACKUP_KERNELA_WORK_ID, key_content, sizeof(hi_flash_crypto_content), 0); + if (ret != HI_ERR_SUCCESS) { + goto fail; + } + } else if (part == CRYPTO_WORKKEY_KERNEL_B) { + ret = hi_factory_nv_read(HI_NV_FTM_KERNELB_WORK_ID, key_content, sizeof(hi_flash_crypto_content), 0); + if (ret != HI_ERR_SUCCESS) { + goto fail; + } + } else if (part == CRYPTO_WORKKEY_KERNEL_B_BACKUP) { + ret = hi_factory_nv_read(HI_NV_FTM_BACKUP_KERNELB_WORK_ID, key_content, sizeof(hi_flash_crypto_content), 0); + if (ret != HI_ERR_SUCCESS) { + goto fail; + } + } + + if (memcmp(key_content->work_text, key_e, KEY_BYTE_LENGTH) == HI_ERR_SUCCESS) { + ret = HI_PRINT_ERRNO_CRYPTO_KEY_EMPTY_ERR; + goto fail; + } + + ret = crypto_decrypt_hash(key_content); + if (ret != HI_ERR_SUCCESS) { + goto fail; + } + + ret = hi_cipher_hash_sha256((uintptr_t)(key_content->root_salt), sizeof(hi_flash_crypto_content) - SHA_256_LENGTH, + hash, SHA_256_LENGTH); + if (ret != HI_ERR_SUCCESS) { + goto fail; + } + if (memcmp(key_content->content_sh256, hash, SHA_256_LENGTH) != HI_ERR_SUCCESS) { + ret = HI_PRINT_ERRNO_CRYPTO_KEY_INVALID_ERR; + goto fail; + } +fail: + return ret; +} + +static hi_u32 crypto_gen_key_content(hi_flash_crypto_content *key_content) +{ + hi_u8 salt[IV_BYTE_LENGTH]; + hi_u8 kdf_key[KEY_BYTE_LENGTH]; + hi_cipher_kdf_ctrl ctrl; + + (hi_void)hi_cipher_trng_get_random_bytes(salt, IV_BYTE_LENGTH); + (hi_void)hi_cipher_trng_get_random_bytes(kdf_key, KEY_BYTE_LENGTH); + (hi_void)hi_cipher_trng_get_random_bytes(key_content->iv_nv, IV_BYTE_LENGTH); + (hi_void)hi_cipher_trng_get_random_bytes(key_content->iv_content, IV_BYTE_LENGTH); + + hi_u32 cs = (uintptr_t)(ctrl.key) ^ (hi_u32)sizeof(ctrl.key) ^ (uintptr_t)kdf_key ^ (hi_u32)sizeof(kdf_key); + if ((hi_u32)memcpy_s(ctrl.key, sizeof(ctrl.key), kdf_key, sizeof(kdf_key), cs) != EOK) { + return HI_ERR_FAILURE; + } + ctrl.salt = salt; + ctrl.salt_len = sizeof(salt); + ctrl.kdf_cnt = KDF_ITERATION_CNT; + ctrl.kdf_mode = HI_CIPHER_SSS_KDF_KEY_DEVICE; /* 用户提供HUK值的方式 */ + if (hi_cipher_kdf_key_derive(&ctrl) != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + + cs = (uintptr_t)(key_content->work_text) ^ KEY_BYTE_LENGTH ^ (uintptr_t)(ctrl.result) ^ (hi_u32)sizeof(ctrl.result); + if (memcpy_s(key_content->work_text, KEY_BYTE_LENGTH, ctrl.result, sizeof(ctrl.result), cs) != EOK) { + return HI_ERR_FAILURE; + } + + if (hi_cipher_hash_sha256((uintptr_t)(key_content->root_salt), sizeof(hi_flash_crypto_content) - SHA_256_LENGTH, + key_content->content_sh256, SHA_256_LENGTH) != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + + return HI_ERR_SUCCESS; +} + +static hi_u32 crypto_encrypt_data(hi_flash_crypto_content *content, boot_crypto_ctx *para) +{ + hi_u32 ret = HI_ERR_FAILURE; + hi_cipher_aes_ctrl aes_ctrl; + + hi_u8 *fw_cyp_data = boot_malloc(para->crypto_total_size); + if (fw_cyp_data == HI_NULL) { + return HI_PRINT_ERRNO_CRYPTO_PREPARE_ERR; + } + + hi_u32 cs = (uintptr_t)(aes_ctrl.key) ^ (hi_u32)sizeof(aes_ctrl.key) ^ + (uintptr_t)(content->work_text) ^ KEY_BYTE_LENGTH; + if (memcpy_s(aes_ctrl.key, sizeof(aes_ctrl.key), content->work_text, KEY_BYTE_LENGTH, cs) != EOK) { + goto fail; + } + + cs = (uintptr_t)(aes_ctrl.iv) ^ (hi_u32)sizeof(aes_ctrl.iv) ^ (uintptr_t)(content->iv_content) ^ IV_BYTE_LENGTH; + if (memcpy_s(aes_ctrl.iv, sizeof(aes_ctrl.iv), content->iv_content, IV_BYTE_LENGTH, cs) != EOK) { + goto fail; + } + + crpto_set_aes_ctrl_default_value(&aes_ctrl); + ret = hi_cipher_aes_config(&aes_ctrl); + if (ret != HI_ERR_SUCCESS) { + goto fail; + } + + ret = hi_cipher_aes_crypto((uintptr_t)(para->buf), (uintptr_t)fw_cyp_data, para->crypto_total_size, HI_TRUE); + if (ret != HI_ERR_SUCCESS) { + goto crypto_fail; + } + + ret = g_flash_cmd_funcs.write(para->kernel_addr + para->crypto_start_addr, para->crypto_total_size, + (hi_u8 *)fw_cyp_data, HI_FALSE); + if (ret != HI_ERR_SUCCESS) { + goto crypto_fail; + } + +crypto_fail: + (hi_void) hi_cipher_aes_destroy_config(); +fail: + crypto_mem_free(fw_cyp_data); + return ret; +} + +static hi_u32 crypto_decrypt_kernel(hi_flash_crypto_content *content, hi_u32 ram_addr, hi_u32 ram_size) +{ + hi_u32 ret; + hi_cipher_aes_ctrl aes_ctrl; + hi_u8 *fw_raw_data = (hi_u8 *)(uintptr_t)ram_addr; + hi_u32 cs; + hi_u32 kernel_offset; + hi_unref_param(ram_size); + ret = boot_get_crypto_kernel_start(&kernel_offset); + if (ret != HI_ERR_SUCCESS) { + goto fail; + } + + cs = (uintptr_t)(aes_ctrl.key) ^ (hi_u32)sizeof(aes_ctrl.key) ^ (uintptr_t)(content->work_text) ^ KEY_BYTE_LENGTH; + ret = (hi_u32)memcpy_s(aes_ctrl.key, sizeof(aes_ctrl.key), content->work_text, KEY_BYTE_LENGTH, cs); + if (ret != HI_ERR_SUCCESS) { + goto fail; + } + cs = (uintptr_t)(aes_ctrl.iv) ^ (hi_u32)sizeof(aes_ctrl.iv) ^ (uintptr_t)(content->iv_content) ^ IV_BYTE_LENGTH; + ret = (hi_u32)memcpy_s(aes_ctrl.iv, sizeof(aes_ctrl.iv), content->iv_content, IV_BYTE_LENGTH, cs); + if (ret != HI_ERR_SUCCESS) { + goto fail; + } + + crpto_set_aes_ctrl_default_value(&aes_ctrl); + ret = hi_cipher_aes_config(&aes_ctrl); + if (ret != HI_ERR_SUCCESS) { + goto fail; + } + + ret = hi_cipher_aes_crypto(kernel_offset + SFC_BUFFER_BASE_ADDRESS, (hi_u32)(uintptr_t)fw_raw_data, + CRYPTO_KERNEL_LENGTH, HI_FALSE); + if (ret != HI_ERR_SUCCESS) { + goto crypto_fail; + } + +crypto_fail: + (hi_void) hi_cipher_aes_destroy_config(); +fail: + return ret; +} + + +hi_u32 crypto_load_flash_raw(uintptr_t ram_addr, hi_u32 ram_size) +{ + hi_u32 ret; + hi_u32 flash_offset = 0; + uintptr_t addr_start; + if (ram_addr == 0 || ram_size == 0) { + return HI_PRINT_ERRNO_CRYPTO_PREPARE_ERR; + } + + hi_nv_ftm_startup_cfg *cfg = boot_upg_get_cfg(); + addr_start = cfg->addr_start; +#if defined(CONFIG_COMPRESSION_OTA_SUPPORT) + addr_start = cfg->addr_write; +#endif + boot_get_start_addr_offset(addr_start, &flash_offset); + + ret = g_flash_cmd_funcs.read(flash_offset, ram_size, (hi_u8 *)ram_addr); + + return ret; +} + +hi_u32 crypto_content_id(crypto_workkey_partition *content, crypto_workkey_partition *content_bak) +{ + hi_flash_partition_table *partition = hi_get_partition_table(); + hi_u32 kernel_a = partition->table[HI_FLASH_PARTITON_KERNEL_A].addr; + hi_u32 kernel_b = partition->table[HI_FLASH_PARTITON_KERNEL_B].addr; + + hi_nv_ftm_startup_cfg *cfg = boot_upg_get_cfg(); + if (cfg->addr_start == kernel_a) { + *content = CRYPTO_WORKKEY_KERNEL_A; + *content_bak = CRYPTO_WORKKEY_KERNEL_A_BACKUP; + } else if (cfg->addr_start == kernel_b) { + *content = CRYPTO_WORKKEY_KERNEL_B; + *content_bak = CRYPTO_WORKKEY_KERNEL_B_BACKUP; + } else { +#ifdef CONFIG_FACTORY_TEST_SUPPORT + hi_u32 kernel_factory = 0; + hi_nv_ftm_factory_mode factory_mode_cfg = {0}; + hi_u32 ret = hi_factory_nv_read(HI_NV_FTM_FACTORY_MODE, &factory_mode_cfg, sizeof(hi_nv_ftm_factory_mode), 0); + if (ret != HI_ERR_SUCCESS) { + } else { + if (factory_mode_cfg.factory_mode == 0x1) { + boot_msg0("get ftm addr"); + kernel_factory = factory_mode_cfg.factory_addr_start; /* 0x0: factory mode, start addr:0x14D000. */ + } + } + + if (cfg->addr_start == kernel_factory) { + *content = CRYPTO_WORKKEY_KERNEL_A; + *content_bak = CRYPTO_WORKKEY_KERNEL_A_BACKUP; + } else { + return HI_PRINT_ERRNO_CRYPTO_KERNEL_ADDR_ERR; + } +#else + return HI_PRINT_ERRNO_CRYPTO_KERNEL_ADDR_ERR; +#endif + } + + return HI_ERR_SUCCESS; +} + +hi_u32 crypto_decrypt(hi_u32 ram_addr, hi_u32 ram_size) +{ + hi_bool is_backup_content = HI_FALSE; + crypto_workkey_partition work_content; + crypto_workkey_partition work_content_bak; + hi_u32 ret = crypto_content_id(&work_content, &work_content_bak); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + hi_flash_crypto_content *key_content = (hi_flash_crypto_content *)boot_malloc(sizeof(hi_flash_crypto_content)); + if (key_content == HI_NULL) { + return HI_PRINT_ERRNO_CRYPTO_PREPARE_ERR; + } + + ret = crypto_prepare(key_content); + if (ret != HI_ERR_SUCCESS) { + crypto_clear_content((hi_u8 *)key_content, (hi_u32)sizeof(hi_flash_crypto_content)); + crypto_mem_free(key_content); + return HI_PRINT_ERRNO_CRYPTO_PREPARE_ERR; + } + + ret = crypto_load_key_content(work_content, key_content); + if (ret != HI_ERR_SUCCESS) { + ret = crypto_load_key_content(work_content_bak, key_content); + if (ret != HI_ERR_SUCCESS) { + goto fail; + } else { + ret = crypto_save_work_key(work_content, key_content); + if (ret != HI_ERR_SUCCESS) { + goto fail; + } + is_backup_content = HI_TRUE; + } + } + + ret = crypto_decrypt_kernel(key_content, ram_addr, ram_size); + if ((ret != HI_ERR_SUCCESS) && (is_backup_content == HI_FALSE)) { + ret = crypto_load_key_content(work_content_bak, key_content); + if (ret != HI_ERR_SUCCESS) { + goto fail; + } + ret = crypto_decrypt_kernel(key_content, ram_addr, ram_size); + if (ret != HI_ERR_SUCCESS) { + ret = HI_PRINT_ERRNO_CRYPTO_FW_DECRYPT_ERR; + goto fail; + } + } +fail: + crypto_clear_content((hi_u8 *)key_content, (hi_u32)sizeof(hi_flash_crypto_content)); + crypto_mem_free(key_content); + crypto_destory(); + return ret; +} + +hi_void crypto_check_decrypt(hi_void) +{ + hi_u32 ret; + hi_nv_ftm_startup_cfg *cfg = boot_upg_get_cfg(); + hi_bool upg_encrypt_flag = is_upg_need_crypto(); + if ((upg_encrypt_flag == HI_TRUE) && (cfg->file_type == HI_UPG_FILE_KERNEL)) { +#if !defined(CONFIG_COMPRESSION_OTA_SUPPORT) + /* 双分区升级模式,将升级文件加密数据解密到ram中 */ + ret = crypto_decrypt(KERNEL_RAM_ADDR, CRYPTO_KERNEL_LENGTH); + if (ret != HI_ERR_SUCCESS) { + boot_put_errno(ret); + } +#else + /* 压缩升级模式,将升级加密压缩包原始数据拷贝到ram中 */ + ret = crypto_load_flash_raw(KERNEL_RAM_ADDR, CRYPTO_KERNEL_LENGTH); + if (ret != HI_ERR_SUCCESS) { + boot_put_errno(ret); + } +#endif + } else { + /* 普通模式,将运行区加密数据解密到ram中 */ + ret = crypto_decrypt(KERNEL_RAM_ADDR, CRYPTO_KERNEL_LENGTH); + if (ret != HI_ERR_SUCCESS) { + boot_put_errno(ret); + } + } +} + +hi_u32 encrypt_upg_data(boot_crypto_ctx *para) +{ + hi_u32 ret; + + hi_flash_crypto_content *new_content = (hi_flash_crypto_content *)boot_malloc(sizeof(hi_flash_crypto_content)); + if (new_content == HI_NULL) { + return HI_PRINT_ERRNO_CRYPTO_PREPARE_ERR; + } + + ret = crypto_prepare(new_content); + if (ret != HI_ERR_SUCCESS) { + crypto_clear_content((hi_u8 *)new_content, (hi_u32)sizeof(hi_flash_crypto_content)); + crypto_mem_free(new_content); + return HI_PRINT_ERRNO_CRYPTO_PREPARE_ERR; + } + + hi_u32 cs = KERNEL_RAM_ADDR ^ CRYPTO_KERNEL_LENGTH ^ (uintptr_t)(para->buf) ^ CRYPTO_KERNEL_LENGTH; + ret = memcpy_s((hi_u8 *)KERNEL_RAM_ADDR, CRYPTO_KERNEL_LENGTH, para->buf, CRYPTO_KERNEL_LENGTH, cs); + if (ret != EOK) { + goto fail; + } + + /* 生成新密钥存放到密钥分区 */ + ret = crypto_gen_key_content(new_content); + if (ret != HI_ERR_SUCCESS) { + goto fail; + } + + /* 更新密钥流程中,密钥备份区暂不更新,待旧kernel解密成功后再更新密钥备份区 */ + ret = crypto_save_work_key(CRYPTO_WORKKEY_KERNEL_A, new_content); + if (ret != HI_ERR_SUCCESS) { + goto fail; + } + + ret = crypto_encrypt_data(new_content, para); + if (ret != HI_ERR_SUCCESS) { + goto fail; + } + + /* 新密钥加密数据完毕,更新密钥备份区 */ + ret = crypto_save_work_key(CRYPTO_WORKKEY_KERNEL_A_BACKUP, new_content); + if (ret != HI_ERR_SUCCESS) { + goto fail; + } + +fail: + crypto_clear_content((hi_u8 *)new_content, (hi_u32)sizeof(hi_flash_crypto_content)); + crypto_mem_free(new_content); + crypto_destory(); + return ret; +} + +hi_u32 encrypt_para_init(boot_crypto_ctx *encrypt_para, hi_u32 start) +{ + encrypt_para->para_is_init = HI_TRUE; + encrypt_para->is_crypto_section = HI_TRUE; + encrypt_para->kernel_addr = start; + encrypt_para->crypto_start_addr = sizeof(hi_upg_file_head); + encrypt_para->crypto_total_size = CRYPTO_KERNEL_LENGTH; + encrypt_para->crypto_end_addr = encrypt_para->crypto_start_addr + encrypt_para->crypto_total_size; + encrypt_para->cryptoed_size = 0; + encrypt_para->buf = (hi_u8 *)boot_malloc(CRYPTO_KERNEL_LENGTH); + if (encrypt_para->buf == HI_NULL) { + return HI_PRINT_ERRNO_MALLOC_EXAUST_ERR; + } + + hi_u32 cs = (uintptr_t)(encrypt_para->buf) ^ CRYPTO_KERNEL_LENGTH ^ 0 ^ CRYPTO_KERNEL_LENGTH; + hi_u32 ret = memset_s(encrypt_para->buf, CRYPTO_KERNEL_LENGTH, 0, CRYPTO_KERNEL_LENGTH, cs); + if (ret != HI_ERR_SUCCESS) { + return HI_PRINT_ERRNO_MALLOC_EXAUST_ERR; + } + + return HI_ERR_SUCCESS; +} + +hi_u32 upg_check_encrypt(boot_crypto_ctx *para, hi_u8 *buf, hi_u32 buf_len) +{ + hi_u32 ret; + hi_u32 cs; + + hi_u32 size = para->cryptoed_size + buf_len; + if (size > para->crypto_total_size) { + cs = (uintptr_t)(para->buf + para->cryptoed_size) ^ (para->crypto_total_size - para->cryptoed_size) ^ + (uintptr_t)buf ^ (para->crypto_total_size - para->cryptoed_size); + if (memcpy_s(para->buf + para->cryptoed_size, para->crypto_total_size - para->cryptoed_size, buf, + para->crypto_total_size - para->cryptoed_size, cs) != EOK) { + return HI_PRINT_ERRNO_CRYPTO_KEY_EMPTY_ERR; + } + + ret = encrypt_upg_data(para); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + ret = hi_flash_write(para->kernel_addr + para->crypto_end_addr, size - para->crypto_total_size, + buf + (para->crypto_total_size - para->cryptoed_size), HI_FALSE); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + para->is_crypto_section = HI_FALSE; + } else if (size == para->crypto_total_size) { + cs = (uintptr_t)(para->buf + para->cryptoed_size) ^ buf_len ^ (uintptr_t)buf ^ buf_len; + if (memcpy_s(para->buf + para->cryptoed_size, buf_len, buf, buf_len, cs) != EOK) { + return HI_PRINT_ERRNO_CRYPTO_KEY_EMPTY_ERR; + } + + ret = encrypt_upg_data(para); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + para->is_crypto_section = HI_FALSE; + } else { + cs = (uintptr_t)(para->buf + para->cryptoed_size) ^ (para->crypto_total_size - para->cryptoed_size) ^ + (uintptr_t)buf ^ buf_len; + if (memcpy_s(para->buf + para->cryptoed_size, para->crypto_total_size - para->cryptoed_size, + buf, buf_len, cs) != EOK) { + return HI_PRINT_ERRNO_CRYPTO_KEY_EMPTY_ERR; + } + + para->cryptoed_size += buf_len; + } + + return HI_ERR_SUCCESS; +} + +hi_u32 upg_encrypt_part_write(hi_u32 start, hi_u32 offset, hi_u8 *buf, hi_u32 buf_len) +{ + hi_u32 ret; + boot_crypto_ctx *encrypt_para = boot_crypto_get_ctx(); + if (encrypt_para->para_is_init == HI_FALSE) { + ret = encrypt_para_init(encrypt_para, start); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + } + + if (encrypt_para->crypto_start_addr == offset) { + ret = upg_check_encrypt(encrypt_para, buf, buf_len); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + } else if ((encrypt_para->crypto_start_addr > offset) && + (encrypt_para->crypto_start_addr < (offset + buf_len))) { + ret = hi_flash_write(start + offset, (encrypt_para->crypto_start_addr - offset), buf, HI_FALSE); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + ret = upg_check_encrypt(encrypt_para, buf + encrypt_para->crypto_start_addr - offset, + buf_len - (encrypt_para->crypto_start_addr - offset)); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + } else { + ret = upg_check_encrypt(encrypt_para, buf, buf_len); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + } + + if ((encrypt_para->is_crypto_section == HI_FALSE) && (encrypt_para->buf != HI_NULL)) { + crypto_mem_free(encrypt_para->buf); + } + + return HI_ERR_SUCCESS; +} + +static const hi_u8 g_upg_file_magic[IV_BYTE_LENGTH] = { + 0xE4, 0xEE, 0x10, 0x0E, 0x43, 0x4D, 0x94, 0x24, + 0xC7, 0x54, 0x6D, 0xFB, 0x15, 0xA1, 0x46, 0x97 +}; + +hi_u32 boot_crypto_upg_file_prepare(boot_crypto_ctx *para) +{ + hi_u32 ret; + hi_cipher_kdf_ctrl ctrl; + hi_u8 salt[ROOTKEY_IV_BYTE_LENGTH] = {0}; + + hi_u32 cs = (uintptr_t)salt ^ sizeof(salt) ^ (uintptr_t)(para->upg_salt) ^ IV_BYTE_LENGTH; + ret = memcpy_s((hi_void *)salt, sizeof(salt), (hi_void *)(para->upg_salt), IV_BYTE_LENGTH, cs); + if (ret != EOK) { + return ret; + } + + cs = (uintptr_t)(salt + IV_BYTE_LENGTH) ^ (sizeof(salt) - IV_BYTE_LENGTH) ^ + (uintptr_t)g_upg_file_magic ^ IV_BYTE_LENGTH; + ret = memcpy_s((hi_void *)(salt + IV_BYTE_LENGTH), sizeof(salt) - IV_BYTE_LENGTH, + (hi_void *)g_upg_file_magic, IV_BYTE_LENGTH, cs); + if (ret != EOK) { + return ret; + } + + ctrl.salt = salt; + ctrl.salt_len = ROOTKEY_IV_BYTE_LENGTH; + ctrl.kdf_cnt = KDF_ITERATION_CNT; + ctrl.kdf_mode = HI_CIPHER_SSS_KDF_KEY_STORAGE; + ret = hi_cipher_kdf_key_derive(&ctrl); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + return HI_ERR_SUCCESS; +} + +hi_u32 boot_crypto_upg_file_decrypt(boot_crypto_ctx *para) +{ + hi_u32 ret; + hi_cipher_aes_ctrl aes_ctrl; + + ret = hi_cipher_init(); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + hi_upg_head *fw_raw_data = (hi_upg_head *)boot_malloc(para->crypto_total_size); + if (fw_raw_data == HI_NULL) { + crypto_destory(); + return HI_PRINT_ERRNO_MALLOC_EXAUST_ERR; + } + + ret = boot_crypto_upg_file_prepare(para); + if (ret != HI_ERR_SUCCESS) { + ret = HI_PRINT_ERRNO_UPG_CRYPTO_PREPARE_ERR; + goto fail; + } + + hi_u32 cs = (uintptr_t)(aes_ctrl.iv) ^ sizeof(aes_ctrl.iv) ^ (uintptr_t)(para->upg_iv) ^ IV_BYTE_LENGTH; + ret = memcpy_s(aes_ctrl.iv, sizeof(aes_ctrl.iv), para->upg_iv, IV_BYTE_LENGTH, cs); + if (ret != HI_ERR_SUCCESS) { + goto fail; + } + + aes_ctrl.random_en = HI_FALSE; + aes_ctrl.key_from = HI_CIPHER_AES_KEY_FROM_KDF; + aes_ctrl.work_mode = HI_CIPHER_AES_WORK_MODE_CBC; + aes_ctrl.key_len = HI_CIPHER_AES_KEY_LENGTH_256BIT; + ret = hi_cipher_aes_config(&aes_ctrl); + if (ret != HI_ERR_SUCCESS) { + goto fail; + } + + ret = hi_cipher_aes_crypto((uintptr_t)(para->buf), (uintptr_t)fw_raw_data, para->crypto_total_size, HI_FALSE); + if (ret != HI_ERR_SUCCESS) { + goto crypto_fail; + } + + cs = (uintptr_t)(para->buf) ^ para->crypto_total_size ^ (uintptr_t)(fw_raw_data) ^ para->crypto_total_size; + ret = memcpy_s(para->buf, para->crypto_total_size, fw_raw_data, para->crypto_total_size, cs); + if (ret != HI_ERR_SUCCESS) { + goto crypto_fail; + } + +crypto_fail: + (hi_void) hi_cipher_aes_destroy_config(); +fail: + crypto_mem_free(fw_raw_data); + crypto_destory(); + return ret; +} + +hi_u32 decrypt_para_init(boot_crypto_ctx *para, hi_u32 start) +{ + hi_u32 ret; + uintptr_t addr_write = start - sizeof (hi_upg_file_head); + hi_upg_common_head *upg_head = (hi_upg_common_head *)boot_malloc(sizeof(hi_upg_common_head)); + if (upg_head == HI_NULL) { + return HI_PRINT_ERRNO_MALLOC_EXAUST_ERR; + } + + ret = hi_flash_read(addr_write, sizeof(hi_upg_common_head), (hi_u8 *)upg_head); + if (ret != HI_ERR_SUCCESS) { + goto fail; + } + + para->kernel_addr = start; + para->crypto_start_addr = LZMA_HEAD_SIZE; + para->crypto_total_size = CRYPTO_KERNEL_LENGTH + sizeof(hi_upg_file_head); + para->crypto_end_addr = para->crypto_start_addr + para->crypto_total_size; + + hi_u32 cs = (uintptr_t)(para->upg_salt) ^ IV_BYTE_LENGTH ^ (uintptr_t)(upg_head->aes_key) ^ + sizeof(upg_head->aes_key); + ret = memcpy_s((hi_void *)(para->upg_salt), IV_BYTE_LENGTH, (hi_void *)(upg_head->aes_key), + sizeof(upg_head->aes_key), cs); + if (ret != EOK) { + goto fail; + } + + cs = (uintptr_t)(para->upg_iv) ^ IV_BYTE_LENGTH ^ (uintptr_t)(upg_head->aes_iv) ^ + sizeof(upg_head->aes_iv); + ret = memcpy_s((hi_void *)(para->upg_iv), IV_BYTE_LENGTH, (hi_void *)(upg_head->aes_iv), + sizeof(upg_head->aes_iv), cs); + if (ret != EOK) { + goto fail; + } + + para->buf = (hi_u8 *)boot_malloc(para->crypto_total_size); + if (para->buf == HI_NULL) { + ret = HI_PRINT_ERRNO_MALLOC_EXAUST_ERR; + goto fail; + } + + ret = hi_flash_read(para->kernel_addr + para->crypto_start_addr, para->crypto_total_size, para->buf); + if (ret != HI_ERR_SUCCESS) { + crypto_mem_free(para->buf); + goto fail; + } + +fail: + /* clear salt and iv. */ + crypto_clear_content(upg_head->aes_key, (hi_u32)sizeof(upg_head->aes_key)); + crypto_clear_content(upg_head->aes_iv, (hi_u32)sizeof(upg_head->aes_iv)); + crypto_mem_free(upg_head); + return ret; +} + +hi_void set_upg_decrypt_flag(boot_crypto_ctx *para) +{ + para->para_is_init = HI_TRUE; + para->is_crypto_section = HI_TRUE; + para->is_verify_byte = HI_FALSE; + para->data_medium = DATA_MEDIUM_NOT_INIT; + para->ram_offset = 0; + para->cryptoed_size = 0; +} + +hi_u32 upg_check_decrypt(boot_crypto_ctx *para, hi_u8 *buf, hi_u32 buf_len) +{ + hi_u32 ret; + hi_u32 cs; + + hi_u32 size = para->cryptoed_size + buf_len; + if (size > para->crypto_total_size) { + cs = (uintptr_t)buf ^ (para->crypto_total_size - para->cryptoed_size) ^ + (uintptr_t)(para->buf + para->cryptoed_size) ^ (para->crypto_total_size - para->cryptoed_size); + ret = memcpy_s(buf, para->crypto_total_size - para->cryptoed_size, para->buf + para->cryptoed_size, + para->crypto_total_size - para->cryptoed_size, cs); + if (ret != EOK) { + return ret; + } + + ret = hi_flash_read(para->kernel_addr + para->crypto_end_addr, size - para->crypto_total_size, + buf + (para->crypto_total_size - para->cryptoed_size)); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + para->ram_offset = para->cryptoed_size; + para->cryptoed_size = para->crypto_total_size; + } else if (size == para->crypto_total_size) { + cs = (uintptr_t)buf ^ buf_len ^ (uintptr_t)(para->buf + para->cryptoed_size) ^ buf_len; + ret = memcpy_s(buf, buf_len, para->buf + para->cryptoed_size, buf_len, cs); + if (ret != EOK) { + return ret; + } + + para->ram_offset = para->cryptoed_size; + para->cryptoed_size = para->crypto_total_size; + } else { + cs = (uintptr_t)buf ^ buf_len ^ (uintptr_t)(para->buf + para->cryptoed_size) ^ buf_len; + ret = memcpy_s(buf, buf_len, para->buf + para->cryptoed_size, buf_len, cs); + if (ret != EOK) { + return ret; + } + + para->ram_offset = para->cryptoed_size; + para->cryptoed_size += buf_len; + } + + return HI_ERR_SUCCESS; +} + +hi_u32 upg_decrypt_part_read(hi_u32 start, hi_u32 offset, hi_u8 *buf, hi_u32 buf_len) +{ + hi_u32 ret; + boot_crypto_ctx *decrypt_para = boot_decrypt_get_ctx(); + if (decrypt_para->para_is_init == HI_FALSE) { + set_upg_decrypt_flag(decrypt_para); + } + + if ((decrypt_para->is_verify_byte == HI_TRUE) && (buf_len == 1)) { + decrypt_para->is_verify_byte = HI_FALSE; + if (decrypt_para->cryptoed_size == decrypt_para->crypto_total_size) { + decrypt_para->is_crypto_section = HI_FALSE; + decrypt_para->para_is_init = HI_FALSE; + } + + if (decrypt_para->data_medium == DATA_MEDIUM_RAM) { + buf[0] = decrypt_para->buf[decrypt_para->ram_offset]; + } else if (decrypt_para->data_medium == DATA_MEDIUM_FLASH) { + ret = hi_flash_read(start + offset, buf_len, buf); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + } + + return HI_ERR_SUCCESS; + } + + if (decrypt_para->crypto_start_addr == offset) { + ret = upg_check_decrypt(decrypt_para, buf, buf_len); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + decrypt_para->data_medium = DATA_MEDIUM_RAM; + } else if ((decrypt_para->crypto_start_addr > offset) && (decrypt_para->crypto_start_addr < (offset + buf_len))) { + ret = hi_flash_read(start + offset, (decrypt_para->crypto_start_addr - offset), buf); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + ret = upg_check_decrypt(decrypt_para, buf + decrypt_para->crypto_start_addr - offset, + buf_len - (decrypt_para->crypto_start_addr - offset)); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + decrypt_para->data_medium = DATA_MEDIUM_FLASH; + } else { + ret = upg_check_decrypt(decrypt_para, buf, buf_len); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + decrypt_para->data_medium = DATA_MEDIUM_RAM; + } + decrypt_para->is_verify_byte = HI_TRUE; + + return HI_ERR_SUCCESS; +} + +hi_u32 crypto_kernel_write(hi_u32 start, hi_u32 offset, hi_u8 *buf, hi_u32 buf_len) +{ + hi_u32 ret; + boot_crypto_ctx *para = boot_crypto_get_ctx(); + hi_u32 code_offset = (hi_u32)sizeof(hi_upg_file_head); + + if (((code_offset >= offset) && (code_offset < (offset + buf_len))) || (para->is_crypto_section == HI_TRUE)) { + ret = upg_encrypt_part_write(start, offset, buf, buf_len); + if (ret != HI_ERR_SUCCESS) { + boot_msg1("encrypt flash fail! Err: ", ret); + return ret; + } + } else { + ret = hi_flash_write(start + offset, buf_len, buf, HI_FALSE); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + } + + return HI_ERR_SUCCESS; +} + +hi_u32 crypto_kernel_read(hi_u32 start, hi_u32 offset, hi_u8 *buf, hi_u32 buf_len) +{ + hi_u32 ret; + boot_crypto_ctx *para = boot_decrypt_get_ctx(); + hi_u32 code_offset = LZMA_HEAD_SIZE; + + if (((code_offset >= offset) && (code_offset < (offset + buf_len))) || (para->is_crypto_section == HI_TRUE)) { + ret = upg_decrypt_part_read(start, offset, buf, buf_len); + if (ret != HI_ERR_SUCCESS) { + boot_msg1("decrypt flash fail! Err: ", ret); + return ret; + } + } else { + ret = hi_flash_read(start + offset, buf_len, buf); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + } + + return HI_ERR_SUCCESS; +} + +hi_u32 boot_decrypt_upg_file(hi_u32 addr_write, const hi_upg_section_head *section_head) +{ + hi_u32 ret; + hi_u32 start_offset = addr_write + section_head->section0_offset; + boot_crypto_ctx *decrypt_para = boot_decrypt_get_ctx(); + + ret = decrypt_para_init(decrypt_para, start_offset); + if (ret != HI_ERR_SUCCESS) { + boot_msg1("init decrypt para, err: ", ret); + crypto_mem_free(decrypt_para->buf); + return ret; + } + + ret = boot_crypto_upg_file_decrypt(decrypt_para); + if (ret != HI_ERR_SUCCESS) { + boot_msg1("decrypt upg file, err: ", ret); + crypto_mem_free(decrypt_para->buf); + return HI_PRINT_ERRNO_UPG_CRYPTO_DECRYPT_ERR; + } + + return ret; +} + +hi_void boot_decrypt_free_memory(hi_void) +{ + boot_crypto_ctx *decrypt_para = boot_decrypt_get_ctx(); + crypto_mem_free(decrypt_para->buf); +} + +#endif diff --git a/sdk_liteos/boot/flashboot/secure/crypto.h b/sdk_liteos/boot/flashboot/secure/crypto.h new file mode 100644 index 0000000000000000000000000000000000000000..ad025018f3ee49ac5540417628fd29069daa9c92 --- /dev/null +++ b/sdk_liteos/boot/flashboot/secure/crypto.h @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __CRYPTO_H__ +#define __CRYPTO_H__ +#ifdef CONFIG_FLASH_ENCRYPT_SUPPORT +#include +#include +#include + +#define crypto_mem_free(sz) \ + do { \ + if ((sz) != HI_NULL) { \ + boot_free(sz); \ + } \ + (sz) = HI_NULL; \ + } while (0) + +#define IV_BYTE_LENGTH 16 +#define ROOTKEY_IV_BYTE_LENGTH 32 + +#define DIE_ID_BYTE_LENGTH 24 + +#define KEY_BYTE_LENGTH 32 + +#define SHA_256_LENGTH 32 + +#define ROOT_SALT_LENGTH 32 + +#define CRYPTO_CNT_NUM 6 + +#define CRYPTO_KERNEL_LENGTH 4096 + +#define KERNEL_RAM_ADDR 0xD8400 + +#define KDF_ITERATION_CNT 1024 + +#define MIN_CRYPTO_BLOCK_SIZE 16 + +#define HI_NV_FTM_KERNELA_WORK_ID 0x4 +#define HI_NV_FTM_BACKUP_KERNELA_WORK_ID 0x5 +#define HI_NV_FTM_KERNELB_WORK_ID 0x6 +#define HI_NV_FTM_BACKUP_KERNELB_WORK_ID 0x7 + +#define LZMA_HEAD_SIZE 13 +#define DATA_MEDIUM_NOT_INIT 0 +#define DATA_MEDIUM_RAM 1 +#define DATA_MEDIUM_FLASH 2 + +typedef enum { + CRYPTO_WORKKEY_KERNEL_A = 0x1, + CRYPTO_WORKKEY_KERNEL_A_BACKUP = 0x2, + CRYPTO_WORKKEY_KERNEL_A_BOTH = 0x3, + CRYPTO_WORKKEY_KERNEL_B = 0x4, + CRYPTO_WORKKEY_KERNEL_B_BACKUP = 0x8, + CRYPTO_WORKKEY_KERNEL_B_BOTH = 0xC, +} crypto_workkey_partition; + +typedef struct { + hi_u8 root_salt[ROOT_SALT_LENGTH]; + hi_u8 iv_nv[IV_BYTE_LENGTH]; /* The root key encrypts the initial vector value of the working key + and stores it in plaintext in the NV. */ + hi_u8 iv_content[IV_BYTE_LENGTH]; + hi_u8 work_text[KEY_BYTE_LENGTH]; /* Working key ciphertext */ + hi_u8 content_sh256[SHA_256_LENGTH]; /* Ciphertext of the preceding three data hash calculation results */ +} hi_flash_crypto_content; + +typedef struct { + uintptr_t kernel_addr; + uintptr_t crypto_start_addr; + uintptr_t crypto_end_addr; + hi_u16 crypto_total_size; + hi_u16 cryptoed_size; + hi_u8 *buf; + hi_u8 upg_iv[IV_BYTE_LENGTH]; + hi_u8 upg_salt[IV_BYTE_LENGTH]; + hi_bool is_verify_byte; + hi_u8 data_medium; + hi_u16 ram_offset; + hi_bool is_crypto_section; + hi_bool para_is_init; +} boot_crypto_ctx; + +boot_crypto_ctx *boot_crypto_get_ctx(hi_void); +boot_crypto_ctx *boot_decrypt_get_ctx(hi_void); +hi_u32 crypto_decrypt(hi_u32 ram_addr, hi_u32 ram_size); +hi_u32 crypto_load_flash_raw(uintptr_t ram_addr, hi_u32 ram_size); +hi_void crypto_check_decrypt(hi_void); +hi_u32 crypto_kernel_write(hi_u32 start, hi_u32 offset, hi_u8 *buffer, hi_u32 size); +hi_u32 crypto_kernel_read(hi_u32 start, hi_u32 offset, hi_u8 *buf, hi_u32 buf_len); + +hi_u32 boot_decrypt_upg_file(hi_u32 addr_write, const hi_upg_section_head *section_head); +hi_void boot_decrypt_free_memory(hi_void); + +#endif +#endif diff --git a/sdk_liteos/boot/flashboot/startup/SConscript b/sdk_liteos/boot/flashboot/startup/SConscript new file mode 100755 index 0000000000000000000000000000000000000000..138c6e2d55f3f22f13bf09f16f22aa31b99ba627 --- /dev/null +++ b/sdk_liteos/boot/flashboot/startup/SConscript @@ -0,0 +1,7 @@ +Import('env') + +env = env.Clone() + +objs = env.Object(Glob('*.c')) +objs += env.Object(Glob('*.S')) +Return('objs') diff --git a/sdk_liteos/boot/flashboot/startup/main.c b/sdk_liteos/boot/flashboot/startup/main.c new file mode 100644 index 0000000000000000000000000000000000000000..d3c7cd9a3f8b08c6ed60dcecbf5043425035b90c --- /dev/null +++ b/sdk_liteos/boot/flashboot/startup/main.c @@ -0,0 +1,138 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include "main.h" +#ifdef CONFIG_FLASH_ENCRYPT_SUPPORT +#include +#endif + +#define KERNEL_START_ADDR 0x40D3C0 + +hi_u32 g_uart_auth; +#define FLASHBOOT_UART_DEFAULT_PARAM {115200, 8, 1, 0, 0, 0, 2, 1, 4} + +hi_void boot_kernel(uintptr_t kaddr) +{ + __asm__ __volatile__("ecall"); /* switch U-MODE -> M-MODE */ + hi_void (*entry)(hi_void) = (hi_void*)(kaddr); + entry(); +} + +hi_void boot_io_init(hi_void) +{ + hi_io_set_func(HI_IO_NAME_GPIO_3, HI_IO_FUNC_GPIO_3_UART0_TXD); /* uart0 tx */ + hi_io_set_func(HI_IO_NAME_GPIO_4, HI_IO_FUNC_GPIO_4_UART0_RXD); /* uart0 rx */ +} + +hi_void boot_flash_init(hi_void) +{ + hi_flash_cmd_func flash_funcs = {0}; + flash_funcs.init = hi_flash_init; + flash_funcs.read = hi_flash_read; + flash_funcs.write = hi_flash_write; + flash_funcs.erase = hi_flash_erase; + hi_cmd_regist_flash_cmd(&flash_funcs); + (hi_void) hi_flash_init(); +} +#define XTAL_DS 0x7 +#define OSC_DRV_CTL 0x2 + +hi_void boot_extern_32k(hi_void) +{ + hi_u16 chip_id, chip_id_bk; + hi_u32 ret; + ret = hi_efuse_read(HI_EFUSE_CHIP_RW_ID, (hi_u8 *)&chip_id, (hi_u8)sizeof(hi_u8)); + if (ret != HI_ERR_SUCCESS) { + return; + } + ret = hi_efuse_read(HI_EFUSE_CHIP_BK_RW_ID, (hi_u8 *)&chip_id_bk, (hi_u8)sizeof(hi_u8)); + if (ret != HI_ERR_SUCCESS) { + return; + } + hi_u8 chip_ver = (chip_id >> OFFSET_4_B) & MSK_3_B; /* chip_id bit[4:7] is chip_ver. */ + hi_u8 chip_ver_bk = (chip_id_bk >> OFFSET_4_B) & MSK_3_B; /* chip_id bit[4:7] is chip_ver. */ + if (chip_ver != HI_CHIP_VER_HI3861L) { + if (chip_ver_bk != HI_CHIP_VER_HI3861L) { + return; + } + } + hi_u32 reg_val; + hi_reg_read(HI_IOCFG_REG_BASE + IO_CTRL_REG_BASE_ADDR, reg_val); + reg_val &= ~(MSK_2_B << OFFSET_4_B); /* Maximum drive capability */ + reg_val |= (MSK_2_B << OFFSET_22_B); /* external xtal, osc enable */ + reg_val &= ~(MSK_3_B << OFFSET_25_B); + reg_val |= XTAL_DS << OFFSET_25_B; /* 1.6ua */ + reg_val &= ~(MSK_2_B << OFFSET_28_B); + reg_val |= OSC_DRV_CTL << OFFSET_28_B; /* 4Mohm */ + hi_reg_write(HI_IOCFG_REG_BASE + IO_CTRL_REG_BASE_ADDR, reg_val); +} + +/* the entry of C. */ +hi_void start_fastboot(hi_void) +{ +#ifndef CONFIG_QUICK_SEND_MODE + hi_u32 ret; + hi_malloc_func malloc_funcs = {0, }; + uart_param_stru default_uart_param = FLASHBOOT_UART_DEFAULT_PARAM; + hi_watchdog_disable(); + hi_watchdog_enable(WDG_TIME_US); + + /* io config */ + boot_io_init(); + + /* Registering and Initializing the Heap Area */ + malloc_funcs.init = rom_boot_malloc_init; + malloc_funcs.boot_malloc = rom_boot_malloc; + malloc_funcs.boot_free = rom_boot_free; + + hi_register_malloc((uintptr_t)&__heap_begin__, &malloc_funcs); + hi_u32 check_sum = ((uintptr_t)&__heap_begin__) ^ ((uintptr_t)&__heap_end__); + boot_malloc_init((uintptr_t)&__heap_begin__, (uintptr_t)&__heap_end__, check_sum); + + /* Initializing the Debugging Serial Port */ + ret = serial_init(UART0, default_uart_param); + if (ret != HI_ERR_SUCCESS) { + boot_msg0("uart err"); /* Use the serial port of the romboot to configure the printing. */ + } + + boot_extern_32k(); + /* Initializing the Flash Driver */ + boot_flash_init(); + /* NV initialization */ + ret = hi_factory_nv_init(HI_FNV_DEFAULT_ADDR, HI_NV_DEFAULT_TOTAL_SIZE, HI_NV_DEFAULT_BLOCK_SIZE); + if (ret != HI_ERR_SUCCESS) { + boot_msg0("fnv err"); + } + + ret = hi_flash_partition_init(); + if (ret != HI_ERR_SUCCESS) { + boot_msg0("parti err"); + } + + execute_upg_boot(); +#else + +#ifdef CHIP_HI3861L + boot_extern_32k(); +#endif + hi_flash_init(); + boot_kernel(KERNEL_START_ADDR); +#endif + mdelay(RESET_DELAY_MS); + global_reset(); +} diff --git a/sdk_liteos/boot/flashboot/startup/main.h b/sdk_liteos/boot/flashboot/startup/main.h new file mode 100644 index 0000000000000000000000000000000000000000..47bea33843e3841eeda97cd4dccda02739a78c1f --- /dev/null +++ b/sdk_liteos/boot/flashboot/startup/main.h @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __MAIN_H__ +#define __MAIN_H__ + +HI_EXTERN hi_u32 __heap_begin__; +HI_EXTERN hi_u32 __heap_end__; + +#define HI_CHIP_VER_HI3861L 0x0 +#define IO_CTRL_REG_BASE_ADDR 0x904 /* Base address of the I/O control register, which is used to + configure the drive capability and pull-up/pull-down */ +/* bit mask */ +#define MSK_2_B 0x3 +#define MSK_3_B 0x7 +/* bit offset */ +#define OFFSET_4_B 4 +#define OFFSET_22_B 22 +#define OFFSET_25_B 25 +#define OFFSET_28_B 28 + +#endif diff --git a/sdk_liteos/boot/flashboot/startup/riscv_init_flashboot.S b/sdk_liteos/boot/flashboot/startup/riscv_init_flashboot.S new file mode 100644 index 0000000000000000000000000000000000000000..34b9842cbb32876575e66133fc4ab4efb64879cc --- /dev/null +++ b/sdk_liteos/boot/flashboot/startup/riscv_init_flashboot.S @@ -0,0 +1,241 @@ +/* + * @file entry.S + * + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * @brief RISC-V trap handling and startup code. + * + */ +#ifndef ENTRY_S +#define ENTRY_S + +.extern __stack_top + +#define LREG lw +#define SREG sw +#define REGBYTES 4 + +#define INT_SIZE_ON_STACK (16 * REGBYTES) + +#define MSTATUS_MPP_MACHINE 0x00001800 +#define MCAULSE_ECALL_FROM_MMODE 11 +#define MCAULSE_ECALL_FROM_UMODE 8 + + .extern trap_entry + .section .text.entry + .global _start + .option norvc +_start: + j handle_reset + +.macro push_reg + addi sp, sp, -(INT_SIZE_ON_STACK) + SREG x1, 0 * REGBYTES(sp) + SREG x5, 1 * REGBYTES(sp) + SREG x6, 2 * REGBYTES(sp) + SREG x7, 3 * REGBYTES(sp) + SREG x10, 4 * REGBYTES(sp) + SREG x11, 5 * REGBYTES(sp) + SREG x12, 6 * REGBYTES(sp) + SREG x13, 7 * REGBYTES(sp) + SREG x14, 8 * REGBYTES(sp) + SREG x15, 9 * REGBYTES(sp) + SREG x16, 10 * REGBYTES(sp) + SREG x17, 11 * REGBYTES(sp) + SREG x28, 12 * REGBYTES(sp) + SREG x29, 13 * REGBYTES(sp) + SREG x30, 14 * REGBYTES(sp) + SREG x31, 15 * REGBYTES(sp) + addi sp, sp, -(INT_SIZE_ON_STACK) +.endm + +.macro pop_reg + addi sp, sp, INT_SIZE_ON_STACK + LREG x1, 0 * REGBYTES(sp) + LREG x5, 1 * REGBYTES(sp) + LREG x6, 2 * REGBYTES(sp) + LREG x7, 3 * REGBYTES(sp) + LREG x10, 4 * REGBYTES(sp) + LREG x11, 5 * REGBYTES(sp) + LREG x12, 6 * REGBYTES(sp) + LREG x13, 7 * REGBYTES(sp) + LREG x14, 8 * REGBYTES(sp) + LREG x15, 9 * REGBYTES(sp) + LREG x16, 10 * REGBYTES(sp) + LREG x17, 11 * REGBYTES(sp) + LREG x28, 12 * REGBYTES(sp) + LREG x29, 13 * REGBYTES(sp) + LREG x30, 14 * REGBYTES(sp) + SREG x31, 15 * REGBYTES(sp) + addi sp, sp, INT_SIZE_ON_STACK +.endm + +trap_entry_wrapper: + j trap_entry + +trap_entry: + push_reg + csrr t0, mcause +#ecall from M-mode + li t1, MCAULSE_ECALL_FROM_MMODE + bne t0, t1, 1f + li t2, MSTATUS_MPP_MACHINE + csrc mstatus, t2 + csrr t0, mepc + addi t0, t0, 4 + csrw mepc, t0 + pop_reg + mret +#ecall from U-mode +1: + li t1, MCAULSE_ECALL_FROM_UMODE + bne t0, t1, 2f + li t2, MSTATUS_MPP_MACHINE + csrs mstatus, t2 + csrr t0, mepc + addi t0, t0, 4 + csrw mepc, t0 + pop_reg + mret +#Other exception. //TODO: reg reset. +2: + pop_reg + j trap_entry + +handle_reset: + csrwi mstatus, 0 + csrwi mie, 0 + csrci mstatus, 0x08 + +/* initialize global pointer */ + .option push + .option norelax + la gp, __global_pointer$ + .option pop + +/* initialize stack pointer */ + la sp, __stack_top + +/* perform the rest of initialization in C */ +clear_bss: + la t0, __bss_begin__ + la t1, __bss_end__ + li t2, 0x00000000 + +clear_bss_loop: + sw t2, (t0) /* clear BSS location */ + addi t0, t0, 4 /* increment clear index pointer */ + blt t0, t1, clear_bss_loop /* are we at the end yet, if not , contiue till the end */ + +clear_rom_bss: + la t0, __rom_bss_start + la t1, __rom_bss_end + li t2, 0x00000000 + +clear_rom_bss_loop: + sw t2, (t0) /* clear ROM_BSS location */ + addi t0, t0, 4 /* increment clear index pointer */ + blt t0, t1, clear_rom_bss_loop /* are we at the end yet, if not , contiue till the end */ + +clear_code_rom_bss: + la t0, __code_rom_bss_start + la t1, __code_rom_bss_end + li t2, 0x00000000 + +clear_code_rom_bss_loop: + sw t2, (t0) /* clear ROM_BSS location */ + addi t0, t0, 4 /* increment clear index pointer */ + blt t0, t1, clear_code_rom_bss_loop /* are we at the end yet, if not , contiue till the end */ + +/* copy .data .sdata section from FIX_ROM to SRAM */ + la t0, __rom_copy_ram_start /* SRAM addr */ + la t1, __rom_copy_start /* ROM addr */ + la t2, __rom_copy_size + add t2, t2, t1 + +start_fixrom_data_loop: + lw t3, (t1) + sw t3, (t0) + addi t0, t0, 4 + addi t1, t1, 4 + blt t1, t2, start_fixrom_data_loop /* are we at the end yet, if not , contiue till the end */ +end_fixrom_data_loop: + +/* copy .data .sdata section from CODE_ROM to SRAM */ + la t0, __code_rom_copy_ram_start /* SRAM addr */ + la t1, __code_rom_copy_start /* ROM addr */ + la t2, __code_rom_copy_size + add t2, t2, t1 + +start_coderom_data_loop: + lw t3, (t1) + sw t3, (t0) + addi t0, t0, 4 + addi t1, t1, 4 + blt t1, t2, start_coderom_data_loop /* are we at the end yet, if not , contiue till the end */ +end_coderom_data_loop: + + +/* pmp init */ +pmp_init: + li t0, 0xB00 + csrw pmpaddr0, t0 + li t0,0x2000 + csrw pmpaddr1, t0 /* (1)11-32K(0x8000) fixrom: disable w;non-cacheable */ +#ifdef HI_BOARD_ASIC + li t0,0x477f0 + csrw pmpaddr2, t0 /* (2)32k(0x8000) - 0x11DFC0 RAM: disable x;non-cacheable */ + li t0,0x47800 + csrw pmpaddr3, t0 /* (3)0x11DFC0 - 0x11E000 checkinfo: disable w x;non-cacheable */ +#else + li t0,0x7fff0 + csrw pmpaddr2, t0 /* (2)32k(0x8000) - 0x1FFFC0 RAM: non-cacheable */ + li t0,0x80000 + csrw pmpaddr3, t0 /* (3)0x1FFFC0 - 0x200000 checkinfo: disable w x;non-cacheable */ +#endif + li t0,0xEE000 + csrw pmpaddr4, t0 /* (4)0x11E000 - 0x3B8000 another romboot: disable r-w-x;non-cacheable */ + li t0,0xFF600 + csrw pmpaddr5, t0 /* (5)0x3B8000 - 0x3FD800 kernel_rombin: diasble r-w-x;non-cacheable */ + li t0,0x100000 + csrw pmpaddr6, t0 /* (6)0x3FD800 - 0x400000 code_rombin(9K): diasble w;non-cacheable */ + li t0,0x18000000 + csrw pmpaddr7, t0 /* (7)0x400000 -> 0x60000000 REG: disable x;non-cacheable */ + + li t0,0xf3333333 /* f:Write-back Read and Write-allocate; 3:Normal Non-cacheable Bufferable */ + csrw 0x7d8,t0 + + li t0,0x090f0d88 /* 0x0d:TOR-R-X; 0x0b:TOR-R-W; 0x08:TOR; 0x0c:TOR-x; 0x09:TOR-R */ + csrw pmpcfg0,t0 + li t0,0x0b0d0808 + csrw pmpcfg1,t0 + +/* disable Icache */ + csrwi 0x7C0, 0x0 /* disable ICACHE */ + fence + +/* disable Dcache */ + csrwi 0x7C1, 0x0 /* disable DCACHE */ + fence + + csrwi mstatus, 0 + csrwi mie, 0 + la t0, trap_entry_wrapper + addi t0, t0, 1 + csrw mtvec, t0 + ecall /* ecall: M-mode -> U-mode */ + +/* jump to C func. */ + tail start_fastboot +#endif diff --git a/sdk_liteos/boot/flashboot/startup/stack_protect.c b/sdk_liteos/boot/flashboot/startup/stack_protect.c new file mode 100644 index 0000000000000000000000000000000000000000..dbb1481dd740fbe5c6df0214079f5e0d12143c85 --- /dev/null +++ b/sdk_liteos/boot/flashboot/startup/stack_protect.c @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "hi_boot_rom.h" + +unsigned long __stack_chk_guard = 0xd00a0dff; + +void __stack_chk_fail(void) +{ + boot_msg1("stack-protector:corrupted in:", (uintptr_t)__builtin_return_address(0)); + udelay(2000); /* delay 2000 us to reset */ + global_reset(); +} \ No newline at end of file diff --git a/sdk_liteos/boot/flashboot/upg/SConscript b/sdk_liteos/boot/flashboot/upg/SConscript new file mode 100755 index 0000000000000000000000000000000000000000..aceb2b6a9464ce64030c1f9c5374ec933dcab384 --- /dev/null +++ b/sdk_liteos/boot/flashboot/upg/SConscript @@ -0,0 +1,6 @@ +Import('env') + +env = env.Clone() + +objs = env.Object(Glob('*.c')) +Return('objs') diff --git a/sdk_liteos/boot/flashboot/upg/boot_start.c b/sdk_liteos/boot/flashboot/upg/boot_start.c new file mode 100644 index 0000000000000000000000000000000000000000..9a024a666c45b3b0e15fe4999c64ec8cbb5baaaf --- /dev/null +++ b/sdk_liteos/boot/flashboot/upg/boot_start.c @@ -0,0 +1,192 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "boot_start.h" +#include "boot_upg_kernel.h" +#include "boot_upg_check.h" +#include "boot_upg_check_secure.h" +#ifdef CONFIG_FLASH_ENCRYPT_SUPPORT +#include +#endif + +#define CRYPTO_FLASH_LENGTH 4096 + +hi_u32 g_upg_kernel_verify_addr; + +hi_u32 check_hupg(hi_void) +{ + hi_u32 ret = boot_upg_check_file(g_upg_kernel_verify_addr); + if (ret != HI_ERR_SUCCESS) { + boot_msg2("[check hupg]fail ret-addr", ret, g_upg_kernel_verify_addr); + } + return ret; +} + +hi_u32 check_hupg_multi_times(hi_u32 check_times) +{ + hi_u32 ret = HI_ERR_SUCCESS; + for (hi_u32 i = 0; i < check_times; i++) { + ret = check_hupg(); + if (ret == HI_ERR_SUCCESS) { + return ret; + } else { + boot_msg2("[hupg multi times]fail ret-index", ret, i); + } + } + return ret; +} + +hi_void change_area(hi_void) +{ + hi_nv_ftm_startup_cfg *cfg = boot_upg_get_cfg(); + +#if defined(CONFIG_COMPRESSION_OTA_SUPPORT) + if (g_upg_kernel_verify_addr == cfg->addr_start) { + g_upg_kernel_verify_addr = cfg->addr_write; + } else { + g_upg_kernel_verify_addr = cfg->addr_start; + } +#else + hi_flash_partition_table *partition = hi_get_partition_table(); + uintptr_t kernel_a_addr = partition->table[HI_FLASH_PARTITON_KERNEL_A].addr; + uintptr_t kernel_b_addr = partition->table[HI_FLASH_PARTITON_KERNEL_B].addr; + + if (cfg->addr_start == kernel_a_addr) { + cfg->addr_start = kernel_b_addr; + } else { + cfg->addr_start = kernel_a_addr; + } + g_upg_kernel_verify_addr = cfg->addr_start; +#endif +} + +hi_void set_running_kernel_flag(hi_u32 offset) +{ + hi_u16 reg_val; + hi_flash_partition_table *ptable = hi_get_partition_table(); + hi_reg_read16(CLDO_CTL_GEN_REG0, reg_val); + reg_val &= ~(0x1 << 15); /* 15 */ + if (offset < ptable->table[HI_FLASH_PARTITON_KERNEL_B].addr) { /* Low address of kernel B */ + reg_val |= 0x1 << 15; /* 15 */ + hi_reg_write16(CLDO_CTL_GEN_REG0, reg_val); + } else { + hi_reg_write16(CLDO_CTL_GEN_REG0, reg_val); + } +} + +#if defined(CONFIG_FLASH_ENCRYPT_SUPPORT) +hi_void check_area_changed_decrypt(hi_void) +{ +#if defined(CONFIG_COMPRESSION_OTA_SUPPORT) + hi_nv_ftm_startup_cfg *cfg = boot_upg_get_cfg(); + if (g_upg_kernel_verify_addr == cfg->addr_write) { + crypto_load_flash_raw(KERNEL_RAM_ADDR, CRYPTO_KERNEL_LENGTH); + } else { + crypto_decrypt(KERNEL_RAM_ADDR, CRYPTO_KERNEL_LENGTH); + } +#else + crypto_decrypt(KERNEL_RAM_ADDR, CRYPTO_KERNEL_LENGTH); +#endif +} +#endif + +hi_void boot_head(hi_void) +{ + hi_u32 offset = 0; + hi_nv_ftm_startup_cfg *cfg = boot_upg_get_cfg(); + hi_u32 ret = check_hupg_multi_times(UPG_MAX_BACKUP_CNT); + if (ret != HI_ERR_SUCCESS) { + change_area(); +#ifdef CONFIG_FLASH_ENCRYPT_SUPPORT + check_area_changed_decrypt(); +#endif + cfg->refresh_nv = ENV_REFRESH_NV; + ret = check_hupg(); + if (ret != HI_ERR_SUCCESS) { + boot_msg1("Check_hupg fail:", ret); + global_reset(); + } else { + boot_upg_save_cfg_to_nv(); + } + } + +#if defined(CONFIG_COMPRESSION_OTA_SUPPORT) + if ((ret == HI_ERR_SUCCESS) && (g_upg_kernel_verify_addr == cfg->addr_write)) { + ret = boot_upg_kernel_process(cfg->addr_start, cfg->addr_write); + if (ret != HI_ERR_SUCCESS) { + boot_msg2("[bootupg kernel process]ret-addr_start", ret, cfg->addr_start); + global_reset(); + } +#ifdef CONFIG_FLASH_ENCRYPT_SUPPORT + ret = crypto_decrypt(KERNEL_RAM_ADDR, CRYPTO_KERNEL_LENGTH); + if (ret != HI_ERR_SUCCESS) { + global_reset(); + } +#endif + ret = boot_upg_check_file(cfg->addr_start); + if (ret != HI_ERR_SUCCESS) { + global_reset(); + } + } +#endif + + boot_get_start_addr_offset(cfg->addr_start, &offset); + set_running_kernel_flag(offset); +#ifdef CONFIG_FLASH_ENCRYPT_SUPPORT + boot_kernel(BOOTLOADER_FLASH_HEAD_ADDR + offset + CRYPTO_FLASH_LENGTH); +#else + boot_kernel(BOOTLOADER_FLASH_HEAD_ADDR + offset); +#endif + global_reset(); +} + +hi_void boot_upg_init_verify_addr(const hi_nv_ftm_startup_cfg *cfg) +{ + g_upg_kernel_verify_addr = cfg->addr_start; +#if defined(CONFIG_COMPRESSION_OTA_SUPPORT) + if ((cfg->mode == HI_UPG_MODE_UPGRADE) && (cfg->file_type == HI_UPG_FILE_KERNEL)) { + g_upg_kernel_verify_addr = cfg->addr_write; + } +#endif +} + +hi_void execute_upg_boot(hi_void) +{ + hi_nv_ftm_startup_cfg *cfg = boot_upg_get_cfg(); + boot_upg_save_key_pos(); + boot_upg_load_cfg_from_nv(); + if ((cfg->cnt_max > 0) && (cfg->mode == HI_UPG_MODE_UPGRADE)) { + cfg->reset_cnt++; + if (cfg->reset_cnt >= cfg->cnt_max) { + change_area(); + + cfg->mode = HI_UPG_MODE_NORMAL; + if (boot_upg_save_cfg_to_nv() != HI_ERR_SUCCESS) { + boot_msg0("To do"); + } + boot_msg0("!!!Upg verify fail."); + } else { + if (boot_upg_save_cfg_to_nv() != HI_ERR_SUCCESS) { + boot_msg0("To do"); + } + } + } + +#ifdef CONFIG_FLASH_ENCRYPT_SUPPORT + crypto_check_decrypt(); +#endif + + boot_head(); +} diff --git a/sdk_liteos/boot/flashboot/upg/boot_start.h b/sdk_liteos/boot/flashboot/upg/boot_start.h new file mode 100644 index 0000000000000000000000000000000000000000..fac5c942b27f023f2e4b275d93e98f2f75cd22b5 --- /dev/null +++ b/sdk_liteos/boot/flashboot/upg/boot_start.h @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __BOOT_START_H__ +#define __BOOT_START_H__ + +#include + +hi_void boot_kernel(uintptr_t kaddr); +hi_void execute_upg_boot(hi_void); +hi_void boot_upg_init_verify_addr(const hi_nv_ftm_startup_cfg *cfg); + +#endif diff --git a/sdk_liteos/boot/flashboot/upg/boot_upg_check.c b/sdk_liteos/boot/flashboot/upg/boot_upg_check.c new file mode 100644 index 0000000000000000000000000000000000000000..ad87385a346b2d34d0ba4ecb3b8ae61276a710bc --- /dev/null +++ b/sdk_liteos/boot/flashboot/upg/boot_upg_check.c @@ -0,0 +1,268 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include + +hi_u32 boot_upg_check_image_id(hi_u32 image_id) +{ + if (image_id != PRODUCT_UPG_FILE_IMAGE_ID) { + boot_msg1("check image id fail:", image_id); + return HI_ERR_UPG_IMAGE_ID; + } + return HI_ERR_SUCCESS; +} + +hi_u32 boot_upg_check_file_type(hi_u8 file_type) +{ + if (file_type != HI_UPG_FILE_KERNEL) { + boot_msg1("check file type fail:", file_type); + return HI_ERR_UPG_FILE_TYPE; + } + return HI_ERR_SUCCESS; +} + +hi_u32 boot_upg_get_efuse_code_ver(hi_u8 *version) +{ + hi_u8 pos; + hi_u8 efuse_data[KERNEL_VER_LEN]; + hi_u32 ret; + hi_u32 check_sum = (uintptr_t)efuse_data ^ KERNEL_VER_LEN ^ 0xFF ^ KERNEL_VER_LEN; + (hi_void) memset_s(efuse_data, KERNEL_VER_LEN, 0xFF, KERNEL_VER_LEN, check_sum); + ret = hi_efuse_read(HI_EFUSE_TEE_KERNEL_VER_RW_ID, efuse_data, sizeof(efuse_data)); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + for (pos = 0; pos < KERELN_VER_MAX; pos++) { + if (boot_upg_tool_bit_test(efuse_data, pos) == HI_FALSE) { + break; + } + } + if (pos >= KERELN_VER_MAX) { + *version = KERELN_VER_MAX; + } else { + *version = pos; + } + return ret; +} + +hi_u32 boot_upg_check_code_ver(hi_u8 ver) +{ + hi_u8 current_ver; + hi_u32 ret = boot_upg_get_efuse_code_ver(¤t_ver); + if (ret != HI_ERR_SUCCESS) { + boot_msg1("get code ver fail:", ret); + return ret; + } + if (ver < current_ver) { + ret = HI_ERR_UPG_KERNEL_VER; + boot_msg2("cur-filever:", current_ver, ver); + } + return ret; +} + +hi_u32 boot_upg_get_max_file_len(hi_u32 *file_len) +{ + hi_flash_partition_table *partition = hi_get_partition_table(); + hi_u32 kernel_a_size = partition->table[HI_FLASH_PARTITON_KERNEL_A].size; + hi_u32 kernel_b_size = partition->table[HI_FLASH_PARTITON_KERNEL_B].size; + +#ifdef CONFIG_FACTORY_TEST_SUPPORT + /* factory mode use fix factory bin size */ + hi_nv_ftm_factory_mode factory_mode_cfg = {0}; + hi_u32 ret = hi_factory_nv_read(HI_NV_FTM_FACTORY_MODE, &factory_mode_cfg, sizeof(hi_nv_ftm_factory_mode), 0); + if (ret != HI_ERR_SUCCESS) { + boot_msg0("read ftm err"); + return HI_ERR_FAILURE; + } else { + if (factory_mode_cfg.factory_mode == 0x1) { + *file_len = factory_mode_cfg.factory_size; + return HI_ERR_SUCCESS; + } + } +#endif + +#if defined(CONFIG_COMPRESSION_OTA_SUPPORT) + *file_len = kernel_a_size + kernel_b_size; +#else + hi_nv_ftm_startup_cfg *cfg = boot_upg_get_cfg(); + + if (cfg->addr_start == partition->table[HI_FLASH_PARTITON_KERNEL_A].addr) { + *file_len = kernel_a_size; + } else if (cfg->addr_start == partition->table[HI_FLASH_PARTITON_KERNEL_B].addr) { + *file_len = kernel_b_size; + } else { + *file_len = hi_max(kernel_a_size, kernel_b_size); + boot_msg1("addr_start err", cfg->addr_start); + } +#endif + return HI_ERR_SUCCESS; +} + +hi_u32 boot_upg_check_code_file_len(hi_u32 file_len) +{ + hi_u32 max_len; + hi_u32 ret = boot_upg_get_max_file_len(&max_len); + if (ret != HI_ERR_SUCCESS) { + boot_msg1("get max file len fail:", ret); + return ret; + } + + if (file_len > max_len) { + boot_msg2("filelen>maxlen:", file_len, max_len); + return HI_ERR_UPG_FILE_LEN_OVER; + } + return HI_ERR_SUCCESS; +} + +hi_u32 boot_upg_get_common_head(hi_u32 addr, hi_upg_common_head *head) +{ + hi_u32 ret = hi_flash_read(addr, sizeof(hi_upg_common_head), (hi_u8 *)head); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + return ret; +} + +hi_u32 boot_upg_get_section_head(hi_u32 addr, hi_upg_section_head *section_head) +{ + hi_upg_common_head head = { 0 }; + hi_u32 ret; + + if (section_head == HI_NULL) { + return HI_ERR_UPG_NULL_POINTER; + } + ret = hi_flash_read(addr, sizeof(hi_upg_common_head), (hi_u8 *)(&head)); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + ret = hi_flash_read(addr + head.section_offset, sizeof(hi_upg_section_head), (hi_u8 *)section_head); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + return ret; +} + +hi_u32 boot_upg_check_alg_param(const hi_upg_common_head *head) +{ + sign_alg_param alg_param; + hi_u32 cs = (uintptr_t)(&alg_param) ^ sizeof(sign_alg_param) ^ + (uintptr_t)(&(head->param)) ^ sizeof(sign_alg_param); + if (memcpy_s(&alg_param, sizeof(sign_alg_param), &(head->param), sizeof(sign_alg_param), cs) != EOK) { + return HI_ERR_FAILURE; + } + if ((alg_param.sign_alg != HI_MODE_PKCS_V15) && (alg_param.sign_alg != HI_MODE_PKCS_PSS) && + (alg_param.sign_alg != HI_MODE_ECC)) { + return HI_ERR_UPG_SIGN_ALG; + } + if (alg_param.sign_alg < HI_MODE_ECC) { + if (head->key_len != sizeof(upg_rsa_key)) { + return HI_ERR_UPG_RSA_KEY_LEN; + } + if (head->section_offset != (sizeof(hi_upg_common_head) + head->key_len + sizeof(upg_rsa_sign))) { + return HI_ERR_UPG_RSA_HEAD_SIGN; + } + return HI_ERR_SUCCESS; + } + if (head->key_len != sizeof(upg_ecc_key)) { + return HI_ERR_UPG_ECC_KEY_LEN; + } + if (head->section_offset != (sizeof(hi_upg_common_head) + head->key_len + sizeof(upg_ecc_sign))) { + return HI_ERR_UPG_ECC_HEAD_SIGN; + } + return HI_ERR_SUCCESS; +} + +hi_u32 boot_upg_check_common_head(const hi_upg_common_head *head) +{ + hi_u32 ret = boot_upg_check_image_id(head->image_id); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + ret = boot_upg_check_file_type(head->file_type); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + ret = boot_upg_check_code_file_len(head->file_len); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + if ((head->file_len != (head->section_offset + head->section_len)) || + (head->section_offset != (sizeof(hi_upg_common_head) + sizeof(hi_upg_key) + sizeof(hi_upg_sign))) || + (head->section_len < (sizeof(hi_upg_section_head) + sizeof(upg_rsa_sign)))) { + return HI_ERR_UPG_FILE_LEN; + } + if (boot_upg_is_secure_efuse() != HI_TRUE) { + return HI_ERR_SUCCESS; + } + ret = boot_upg_check_code_ver(head->file_version); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + return boot_upg_check_alg_param(head); +} + +hi_u32 boot_upg_check_file(hi_u32 flash_addr) +{ + hi_u32 ret = HI_ERR_UPG_MALLOC_FAIL; + hi_upg_head *upg_head = (hi_upg_head *)boot_malloc(sizeof(hi_upg_head)); + + if (upg_head == HI_NULL) { + goto end; + } + ret = hi_flash_read(flash_addr, sizeof(hi_upg_head), (hi_u8 *)upg_head); + if (ret != HI_ERR_SUCCESS) { + goto end; + } + hi_upg_common_head *common_head = &(upg_head->common); + ret = boot_upg_check_common_head(common_head); + if (ret != HI_ERR_SUCCESS) { + goto end; + } + + ret = hi_cipher_init(); + if (ret != HI_ERR_SUCCESS) { + goto end; + } + if (boot_upg_is_secure_efuse() == HI_TRUE) { + ret = boot_upg_check_secure_info(flash_addr, upg_head); + } else { + ret = boot_upg_check_unsecure_info(flash_addr, upg_head); + } + hi_u32 ck = hi_cipher_deinit(); + if (ret == HI_ERR_SUCCESS) { + ret = ck; + } +end: + boot_upg_mem_free(upg_head); + return ret; +} + +hi_void boot_get_start_addr_offset(hi_u32 addr, hi_u32 *offset) +{ + hi_upg_section_head section_head = { 0 }; + hi_u32 ret = boot_upg_get_section_head(addr, §ion_head); + if (ret == HI_ERR_SUCCESS) { + *offset = addr + section_head.section0_offset; + } else { + boot_msg1("get addr offset fail:", ret); + *offset = addr; + } +} + diff --git a/sdk_liteos/boot/flashboot/upg/boot_upg_check.h b/sdk_liteos/boot/flashboot/upg/boot_upg_check.h new file mode 100644 index 0000000000000000000000000000000000000000..fc67eb26990ac675fabed7be52ffc93308e8524a --- /dev/null +++ b/sdk_liteos/boot/flashboot/upg/boot_upg_check.h @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __BOOT_UPG_CHECK_H__ +#define __BOOT_UPG_CHECK_H__ + +#include + +#define PRODUCT_UPG_FILE_IMAGE_ID 0x3C78961E +#define KERELN_VER_MAX 48 +#define KERNEL_VER_LEN 6 +hi_u32 boot_upg_get_common_head(hi_u32 addr, hi_upg_common_head *head); +hi_u32 boot_upg_get_section_head(hi_u32 addr, hi_upg_section_head *section_head); +hi_u32 boot_upg_check_common_head(const hi_upg_common_head *head); +hi_u32 boot_upg_check_file(hi_u32 flash_addr); +hi_void boot_get_start_addr_offset(hi_u32 addr, hi_u32 *offset); +hi_u32 boot_upg_check_code_ver(hi_u8 ver); + +#endif diff --git a/sdk_liteos/boot/flashboot/upg/boot_upg_check_secure.c b/sdk_liteos/boot/flashboot/upg/boot_upg_check_secure.c new file mode 100644 index 0000000000000000000000000000000000000000..1606aa4e2c6d2e0f3f92ef69f1d557d128524c35 --- /dev/null +++ b/sdk_liteos/boot/flashboot/upg/boot_upg_check_secure.c @@ -0,0 +1,432 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "boot_upg_check_secure.h" + +#include +#ifdef CONFIG_FLASH_ENCRYPT_SUPPORT +#include +#endif + +#include "boot_upg_tool.h" + +#ifndef FLASHBOOT_KEY_SECTION +#define FLASHBOOT_KEY_SECTION __attribute__ ((section(".boot.data.key"))) +#endif + +#if (defined(CONFIG_TARGET_SIG_RSA_V15) || defined(CONFIG_TARGET_SIG_RSA_PSS)) +FLASHBOOT_KEY_SECTION hi_u8 g_boot_rsa_key[RSA_2048_LEN] = { + 0xde, 0x6e, 0x28, 0x74, 0x70, 0xf2, 0xee, 0x57, 0x3a, 0x2b, 0x79, 0xec, 0x3f, 0x12, 0xb0, 0x01, + 0xe9, 0x86, 0xe8, 0xa6, 0x4d, 0xad, 0x57, 0xdb, 0x9f, 0x08, 0x8a, 0x07, 0x14, 0x9d, 0x30, 0x4a, + 0xb7, 0x57, 0xac, 0xb7, 0x11, 0xaf, 0xeb, 0x12, 0x69, 0x72, 0x7e, 0x25, 0xb6, 0xb6, 0x06, 0x69, + 0x35, 0x0a, 0x9a, 0x09, 0x42, 0xc7, 0x44, 0xfb, 0x2a, 0xb5, 0x5f, 0x28, 0x58, 0x81, 0x40, 0x3a, + 0xe2, 0x60, 0x81, 0x35, 0x4a, 0xd2, 0xa6, 0x79, 0x39, 0x14, 0xf8, 0xaa, 0x6e, 0xd9, 0x40, 0x6c, + 0xab, 0x4d, 0x7a, 0x12, 0x9f, 0x7f, 0xfb, 0x48, 0xa5, 0x88, 0x15, 0x45, 0x5b, 0xbc, 0x55, 0xc4, + 0xdb, 0x74, 0x48, 0x8c, 0x88, 0x1f, 0x3d, 0xad, 0xf6, 0x3e, 0x28, 0x41, 0xce, 0xef, 0x70, 0xf3, + 0x60, 0x03, 0x69, 0x10, 0xf8, 0x7f, 0x4d, 0xb9, 0xdb, 0xc7, 0x8c, 0x4d, 0x5d, 0x41, 0xc1, 0x0f, + 0xcc, 0x2a, 0x71, 0x80, 0x16, 0xa3, 0x5c, 0x2c, 0xc6, 0x89, 0xbb, 0xd0, 0xcf, 0x86, 0xc8, 0x19, + 0x3f, 0xdb, 0x47, 0x7d, 0xfd, 0xc7, 0x20, 0xb9, 0x6b, 0xad, 0x5d, 0x09, 0x6d, 0xff, 0xd4, 0x86, + 0xe2, 0x04, 0xaa, 0x1e, 0x15, 0x06, 0x7c, 0x0c, 0x8f, 0x53, 0xb3, 0xa4, 0x46, 0x2f, 0xe4, 0xd5, + 0xb0, 0x5a, 0xff, 0x8f, 0xa2, 0x2b, 0xe4, 0x2c, 0x5f, 0x23, 0xa7, 0x03, 0x06, 0xfe, 0x86, 0x38, + 0xde, 0xb8, 0xd9, 0x26, 0xa5, 0xe7, 0x6d, 0x8d, 0x25, 0xea, 0xca, 0x89, 0xc6, 0xf4, 0xfe, 0xf0, + 0x70, 0x54, 0x64, 0x8a, 0xab, 0x92, 0xcf, 0x8a, 0x87, 0xf5, 0x3d, 0x01, 0x07, 0x1d, 0xf2, 0x15, + 0x53, 0xd8, 0x9a, 0xa9, 0x52, 0xde, 0x59, 0x3d, 0x66, 0x1b, 0x63, 0x46, 0x86, 0x78, 0x05, 0x5e, + 0xa4, 0x4a, 0xf9, 0x2d, 0x50, 0xef, 0xca, 0x28, 0x3d, 0xb9, 0x5b, 0x17, 0xec, 0xd5, 0x8a, 0x99 +}; +#endif + +#if defined(CONFIG_TARGET_SIG_ECC) +FLASHBOOT_KEY_SECTION hi_u8 g_boot_ecc_key[ECC_KEY_LEN] = { + 0x47, 0x9c, 0x30, 0xcb, 0x84, 0xe1, 0x05, 0xd1, 0x82, 0x5e, 0xe0, 0xd6, 0x01, 0xb9, 0x96, 0x82, + 0x8f, 0xcd, 0x6e, 0xf7, 0x70, 0xc7, 0x22, 0x9c, 0xeb, 0xdf, 0x02, 0xdb, 0xfd, 0xe6, 0xa6, 0x0c, + 0x19, 0x23, 0x9c, 0x82, 0x69, 0xc8, 0xe7, 0x58, 0xfe, 0x29, 0x6e, 0xa7, 0xaf, 0x2e, 0x0b, 0x36, + 0xc1, 0xd1, 0x7f, 0xd8, 0x88, 0x82, 0x08, 0x03, 0x4f, 0x2b, 0x77, 0xe0, 0x94, 0x30, 0xbf, 0x1b +}; +#endif + +#if (defined(CONFIG_TARGET_SIG_RSA_V15) || defined(CONFIG_TARGET_SIG_RSA_PSS)) +hi_void boot_upg_save_rsa_key_pos(hi_void) +{ + uintptr_t rsa_key_addr = ((uintptr_t)(&g_boot_rsa_key[0]) - (uintptr_t)(&__data_start)) + + ((uintptr_t)(&__data_load) - BOOTLOADER_FLASH_HEAD_ADDR); + hi_reg_write16(DIAG_CTL_GP_REG0_REG, (rsa_key_addr & MASK_U16)); + hi_reg_write16(DIAG_CTL_GP_REG1_REG, (rsa_key_addr >> BIT_U16)); +} +#endif + +#if defined(CONFIG_TARGET_SIG_ECC) +hi_void boot_upg_save_ecc_key_pos(hi_void) +{ + uintptr_t ecc_key_addr = ((uintptr_t)(&g_boot_ecc_key[0]) - (uintptr_t)(&__data_start)) + + ((uintptr_t)(&__data_load) - BOOTLOADER_FLASH_HEAD_ADDR); + hi_reg_write16(DIAG_CTL_GP_REG2_REG, (ecc_key_addr & MASK_U16)); + hi_reg_write16(DIAG_CTL_GP_REG3_REG, (ecc_key_addr >> BIT_U16)); +} +#endif + +hi_void boot_upg_save_key_pos(hi_void) +{ +#if (defined(CONFIG_TARGET_SIG_RSA_V15) || defined(CONFIG_TARGET_SIG_RSA_PSS)) + boot_upg_save_rsa_key_pos(); +#endif +#if defined(CONFIG_TARGET_SIG_ECC) + boot_upg_save_ecc_key_pos(); +#endif +} + +hi_void upg_clear_content(hi_u8 *content, hi_u32 content_len) +{ + if ((content == HI_NULL) || (content_len == 0)) { + return; + } + + hi_u32 cs = (uintptr_t)content ^ content_len ^ 0x0 ^ content_len; + (hi_void)memset_s(content, content_len, 0x0, content_len, cs); +} + +hi_bool boot_upg_is_secure_efuse(hi_void) +{ + hi_u8 data = 0; + hi_u32 ret = hi_efuse_read(HI_EFUSE_SEC_BOOT_RW_ID, &data, sizeof(hi_u8)); + if (ret != HI_ERR_SUCCESS) { + return HI_TRUE; + } + + if (data == UPG_SEC_BOOT_FLAG) { + return HI_FALSE; + } + return HI_TRUE; +} + +hi_u32 boot_upg_secure_get_key_part1(hi_u32 sign_alg, hi_u8 *key_n, hi_u32 key_len) +{ + hi_u32 ret = HI_ERR_UPG_PARAMETER; + hi_unref_param(sign_alg); + hi_unref_param(key_n); + hi_unref_param(key_len); +#if defined(CONFIG_TARGET_SIG_ECC) + if (sign_alg == HI_MODE_ECC) { + hi_u32 cs = (uintptr_t)key_n ^ key_len ^ (uintptr_t)g_boot_ecc_key ^ ECC_256_LEN; + ret = memcpy_s(key_n, key_len, g_boot_ecc_key, ECC_256_LEN, cs); + } +#endif +#if (defined(CONFIG_TARGET_SIG_RSA_V15) || defined(CONFIG_TARGET_SIG_RSA_PSS)) + if ((sign_alg == HI_MODE_PKCS_V15) || (sign_alg == HI_MODE_PKCS_PSS)) { + hi_u32 cs = (uintptr_t)key_n ^ key_len ^ (uintptr_t)g_boot_rsa_key ^ RSA_2048_LEN; + ret = memcpy_s(key_n, key_len, g_boot_rsa_key, RSA_2048_LEN, cs); + } +#endif + return ret; +} + +hi_u32 boot_upg_secure_get_key_part2(hi_u32 sign_alg, hi_u8 *key_e, hi_u32 key_len) +{ + hi_u32 ret = HI_ERR_UPG_PARAMETER; + hi_unref_param(sign_alg); + hi_unref_param(key_e); + hi_unref_param(key_len); +#if defined(CONFIG_TARGET_SIG_ECC) + if (sign_alg == HI_MODE_ECC) { + hi_u32 cs = (uintptr_t)key_e ^ key_len ^ (uintptr_t)(g_boot_ecc_key + ECC_256_LEN) ^ ECC_256_LEN; + ret = memcpy_s(key_e, key_len, g_boot_ecc_key + ECC_256_LEN, ECC_256_LEN, cs); + } +#endif +#if (defined(CONFIG_TARGET_SIG_RSA_V15) || defined(CONFIG_TARGET_SIG_RSA_PSS)) + if ((sign_alg == HI_MODE_PKCS_V15) || (sign_alg == HI_MODE_PKCS_PSS)) { + (key_e)[key_len - 1] = 0x01; /* 1: first byte. 0x01: part of key_e 0x10001 */ + (key_e)[key_len - 3] = 0x01; /* 3: last byte. 0x01: part of key_e 0x10001 */ + ret = HI_ERR_SUCCESS; + } +#endif + return ret; +} + +hi_u32 boot_upg_secure_verify(HI_CONST upg_verify_param *param) +{ + hi_u8 hash[SHA_256_LEN] = { 0 }; + hi_u8 out_hash[SHA_256_LEN] = { 0 }; + hi_u32 ret = boot_upg_hash_more_content(param, hash, sizeof(hash)); + + if (ret != HI_ERR_SUCCESS) { + boot_msg1("hash more content, ret:", ret); + return ret; + } + + if (boot_upg_is_secure_efuse() != HI_TRUE) { + if (memcmp(param->sign, hash, SHA_256_LEN) != EOK) { + ret = HI_ERR_UPG_SECTION_SHA256; + } + /* Common head only check one content. */ + if ((ret != HI_ERR_SUCCESS) && (param->buffer_count < 2)) { /* 2: code section buf cnt */ + ret = HI_ERR_UPG_COMMON_SHA256; + } + return ret; + } + + if (param->pad_mode == HI_MODE_ECC) { + hi_cipher_ecc_verify ecc_verify = { + .px = param->key_n, + .py = param->key_e, + .hash = hash, + .hash_len = PKE_LEN_32_BYTES, + .r = (hi_u8 *)param->sign, + .s = (hi_u8 *)param->sign + ECC_32_BYTES, + .out_r = out_hash, + }; + ret = hi_cipher_ecc_verify_hash(&g_brain_pool_p256r1_verify, &ecc_verify); + } else { + hi_cipher_rsa_verify rsa_verify = { + .n = param->key_n, + .e = param->key_e, + .klen = param->key_len, + .scheme = (hi_cipher_rsa_sign_scheme)(param->pad_mode), + }; + hi_cipher_rsa_data rsa_data = { + .hash = hash, + .out_hash = out_hash, + .hash_len = PKE_LEN_32_BYTES, + .sign = param->sign, + .sign_len = sizeof(upg_rsa_sign), + }; + ret = hi_cipher_rsa_verify_hash(&rsa_verify, &rsa_data); + } + return ret; +} + +hi_u32 boot_upg_set_key(HI_CONST hi_upg_head *upg_head, hi_u8 *key2, hi_u32 key_length) +{ + hi_u32 key2_offset = sizeof(hi_upg_common_head) + key_length; + hi_u32 cs; + + if (upg_head->common.param.sign_alg == HI_MODE_ECC) { + cs = (uintptr_t)key2 ^ ECC_256_LEN ^ (uintptr_t)((hi_u8 *)upg_head + key2_offset) ^ ECC_256_LEN; + memcpy_s(key2, key_length, (hi_u8 *)upg_head + key2_offset, ECC_256_LEN, cs); + } else { + cs = (uintptr_t)(key2 + key_length - RSA_EXP_E_LEN) ^ RSA_EXP_E_LEN ^ + (uintptr_t)((hi_u8 *)upg_head + key2_offset) ^ RSA_EXP_E_LEN; + memcpy_s(key2 + key_length - RSA_EXP_E_LEN, RSA_EXP_E_LEN, (hi_u8 *)upg_head + key2_offset, RSA_EXP_E_LEN, cs); + } + return HI_ERR_SUCCESS; +} + +hi_void boot_upg_set_secure_verify_param(upg_verify_param *param, hi_u32 flash_addr, HI_CONST hi_upg_head *upg_head) +{ + param->flash_addr[0] = (uintptr_t)flash_addr + upg_head->common.section_offset; + param->total_size[0] = sizeof(hi_upg_section_head); + param->flash_flag[0] = HI_TRUE; +#if defined(CONFIG_FLASH_ENCRYPT_SUPPORT) + param->flash_addr[1] = KERNEL_RAM_ADDR; + param->total_size[1] = CRYPTO_KERNEL_LENGTH; + param->flash_flag[1] = HI_FALSE; + param->flash_addr[2] = flash_addr + upg_head->common.section_offset + + sizeof(hi_upg_section_head) + sizeof(hi_upg_sign) + CRYPTO_KERNEL_LENGTH; + param->total_size[2] = upg_head->common.section_len - sizeof(hi_upg_section_head) - sizeof(hi_upg_sign) - + CRYPTO_KERNEL_LENGTH; + param->flash_flag[2] = HI_TRUE; + param->buffer_count = 3; /* 3 segments */ +#else + param->flash_addr[1] = flash_addr + upg_head->common.section_offset + + sizeof(hi_upg_section_head) + sizeof(hi_upg_sign); + param->total_size[1] = upg_head->common.section_len - sizeof(hi_upg_section_head) - sizeof(hi_upg_sign); + param->flash_flag[1] = HI_TRUE; + param->buffer_count = 2; /* 2 segments */ +#endif +} + +hi_u32 boot_upg_secure_verify_code(hi_u32 flash_addr, HI_CONST hi_upg_head *upg_head) +{ + hi_u32 cs; + hi_u32 ret = HI_ERR_UPG_MALLOC_FAIL; + hi_u8 *key2 = HI_NULL; + hi_u8 *section_sign = boot_malloc(sizeof(hi_upg_sign)); + if (section_sign == HI_NULL) { + boot_msg0("[upg verify code]malloc fail."); + goto end; + } + ret = hi_flash_read((flash_addr + upg_head->common.section_offset + sizeof(hi_upg_section_head)), + sizeof(hi_upg_sign), (hi_u8 *)section_sign); + if (ret != HI_ERR_SUCCESS) { + goto end; + } + + hi_u32 key_length = (upg_head->common.param.sign_alg == HI_MODE_ECC)? ECC_256_LEN : RSA_2048_LEN; + key2 = boot_malloc(key_length); + if (key2 == HI_NULL) { + boot_msg0("[upg verify code]malloc fail."); + goto end; + } + cs = (uintptr_t)key2 ^ key_length ^ 0 ^ key_length; + memset_s(key2, key_length, 0, key_length, cs); + (hi_void) boot_upg_set_key(upg_head, key2, key_length); + + upg_verify_param param = { 0 }; + boot_upg_set_secure_verify_param(¶m, flash_addr, upg_head); + param.key_n = (hi_u8 *)upg_head + sizeof(hi_upg_common_head); + param.key_e = key2; + param.key_len = key_length; + param.sign = section_sign; + param.pad_mode = (hi_padding_mode)upg_head->common.param.sign_alg; + ret = boot_upg_secure_verify(¶m); + upg_clear_content((hi_u8 *)key2, key_length); + +end: + boot_upg_mem_free(section_sign); + boot_upg_mem_free(key2); + return ret; +} + +hi_u32 boot_upg_unsecure_verify_code(hi_u32 flash_addr, HI_CONST hi_upg_head *upg_head) +{ + hi_u32 ret = HI_ERR_UPG_MALLOC_FAIL; + hi_u8 *section_sign = boot_malloc(sizeof(hi_upg_sign)); + if (section_sign == HI_NULL) { + boot_msg0("[upg unsecure verify code]malloc fail."); + goto end; + } + ret = hi_flash_read((flash_addr + upg_head->common.section_offset + sizeof(hi_upg_section_head)), + sizeof(hi_upg_sign), (hi_u8 *)section_sign); + if (ret != HI_ERR_SUCCESS) { + goto end; + } + + upg_verify_param param = { 0 }; + param.flash_addr[0] = (uintptr_t)flash_addr + upg_head->common.section_offset; + param.total_size[0] = sizeof(hi_upg_section_head); + param.flash_flag[0] = HI_TRUE; + +#if defined(CONFIG_FLASH_ENCRYPT_SUPPORT) + param.flash_addr[1] = KERNEL_RAM_ADDR; + param.total_size[1] = CRYPTO_KERNEL_LENGTH; + param.flash_flag[1] = HI_FALSE; + param.flash_addr[2] = flash_addr + upg_head->common.section_offset + + sizeof(hi_upg_section_head) + sizeof(hi_upg_sign) + CRYPTO_KERNEL_LENGTH; + param.total_size[2] = upg_head->common.section_len - sizeof(hi_upg_section_head) - sizeof(hi_upg_sign) - + CRYPTO_KERNEL_LENGTH; + param.flash_flag[2] = HI_TRUE; + param.buffer_count = 3; /* 3 segments */ +#else + param.flash_addr[1] = flash_addr + upg_head->common.section_offset + + sizeof(hi_upg_section_head) + sizeof(hi_upg_sign); + param.total_size[1] = upg_head->common.section_len - sizeof(hi_upg_section_head) - sizeof(hi_upg_sign); + param.flash_flag[1] = HI_TRUE; + param.buffer_count = 2; /* 2 segments */ +#endif + param.key_n = (hi_u8 *)upg_head + sizeof(hi_upg_common_head); + param.key_e = HI_NULL; + param.key_len = 0; + param.sign = section_sign; + param.pad_mode = (hi_padding_mode)upg_head->common.param.sign_alg; + ret = boot_upg_secure_verify(¶m); +end: + boot_upg_mem_free(section_sign); + + return ret; +} + +hi_u32 boot_upg_secure_verify_head(hi_upg_head *upg_head) +{ + hi_upg_common_head *head = &(upg_head->common); + hi_u32 ret = HI_ERR_UPG_MALLOC_FAIL; + hi_u32 cs; + hi_u32 key_length = (head->param.sign_alg < HI_MODE_ECC) ? RSA_2048_LEN : ECC_256_LEN; + hi_u8 *key1 = boot_malloc(key_length); + hi_u8 *key2 = boot_malloc(key_length); + if ((key1 == HI_NULL) || (key2 == HI_NULL)) { + boot_msg0("[upg verify head]malloc fail."); + goto end; + } + cs = (uintptr_t)key1 ^ key_length ^ 0 ^ key_length; + memset_s(key1, key_length, 0, key_length, cs); + cs = (uintptr_t)key2 ^ key_length ^ 0 ^ key_length; + memset_s(key2, key_length, 0, key_length, cs); + ret = boot_upg_secure_get_key_part1(head->param.sign_alg, key1, key_length); + if (ret != HI_ERR_SUCCESS) { + goto end; + } + ret = boot_upg_secure_get_key_part2(head->param.sign_alg, key2, key_length); + if (ret != HI_ERR_SUCCESS) { + goto end; + } + + upg_verify_param param = { 0 }; + param.flash_addr[0] = (uintptr_t)upg_head; + param.total_size[0] = sizeof(hi_upg_common_head) + head->key_len; + param.buffer_count = 1; /* 1 segments */ + param.key_n = key1; + param.key_e = key2; + param.key_len = key_length; + param.sign = (hi_u8 *)upg_head + sizeof(hi_upg_common_head) + head->key_len; + param.pad_mode = (hi_padding_mode)head->param.sign_alg; + ret = boot_upg_secure_verify(¶m); +end: + upg_clear_content((hi_u8 *)key1, key_length); + upg_clear_content((hi_u8 *)key2, key_length); + boot_upg_mem_free(key1); + boot_upg_mem_free(key2); + return ret; +} + +hi_u32 boot_upg_unsecure_verify_head(hi_upg_head *upg_head) +{ + hi_upg_common_head *head = &(upg_head->common); + upg_verify_param param = { 0 }; + + param.flash_addr[0] = (uintptr_t)upg_head; + param.total_size[0] = sizeof(hi_upg_common_head) + head->key_len; + param.buffer_count = 1; /* 1 segments */ + param.key_n = HI_NULL; + param.key_e = HI_NULL; + param.key_len = 0; + param.sign = (hi_u8 *)upg_head + sizeof(hi_upg_common_head) + head->key_len; + param.pad_mode = (hi_padding_mode)head->param.sign_alg; + hi_u32 ret = boot_upg_secure_verify(¶m); + if (ret != HI_ERR_SUCCESS) { + boot_msg1("[upg unsecure verify head]ret:0x%x", ret); + } + return ret; +} + +hi_u32 boot_upg_check_secure_info(hi_u32 flash_addr, hi_upg_head *upg_head) +{ + hi_u32 ret = boot_upg_secure_verify_head(upg_head); + if (ret != HI_ERR_SUCCESS) { + boot_msg1("[upg check secure info]head,ret:", ret); + return ret; + } + ret = boot_upg_secure_verify_code(flash_addr, upg_head); + if (ret != HI_ERR_SUCCESS) { + boot_msg1("[upg check secure info]code,ret:", ret); + return ret; + } + + return HI_ERR_SUCCESS; +} + +hi_u32 boot_upg_check_unsecure_info(hi_u32 flash_addr, hi_upg_head *upg_head) +{ + hi_u32 ret = boot_upg_unsecure_verify_head(upg_head); + if (ret != HI_ERR_SUCCESS) { + boot_msg1("[upg check unsecure info]head,ret:", ret); + return ret; + } + ret = boot_upg_unsecure_verify_code(flash_addr, upg_head); + if (ret != HI_ERR_SUCCESS) { + boot_msg1("[upg check unsecure info]code,ret:", ret); + return ret; + } + + return HI_ERR_SUCCESS; +} + diff --git a/sdk_liteos/boot/flashboot/upg/boot_upg_check_secure.h b/sdk_liteos/boot/flashboot/upg/boot_upg_check_secure.h new file mode 100644 index 0000000000000000000000000000000000000000..43a9fafd68b2d573c5795c0ee4092796fe3923c7 --- /dev/null +++ b/sdk_liteos/boot/flashboot/upg/boot_upg_check_secure.h @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __BOOT_UPG_CHECK_SECURE_H__ +#define __BOOT_UPG_CHECK_SECURE_H__ + +#include + +#define RSA_2048_LEN 256 +#define RSA_KEY_LEN 512 +#define ECC_KEY_LEN 64 +#define ECC_256_LEN 32 + +#if defined(CONFIG_FLASH_ENCRYPT_SUPPORT) +#define FLASH_ADDR_NUM 3 +#define TOTAL_SIZE_NUM 3 +#define FLASH_FLAG_NUM 3 +#else +#define FLASH_ADDR_NUM 2 +#define TOTAL_SIZE_NUM 2 +#define FLASH_FLAG_NUM 2 +#endif + +#define UPG_SEC_BOOT_FLAG 0x42 + +extern hi_u32 __data_start; +extern hi_u32 __data_load; + +typedef enum { + HI_MODE_PKCS_V15 = 0x00, + HI_MODE_PKCS_PSS = 0x01, + HI_MODE_ECC = 0x10, +} hi_padding_mode; + +typedef struct { + uintptr_t flash_addr[FLASH_ADDR_NUM]; + uintptr_t total_size[TOTAL_SIZE_NUM]; + hi_u32 buffer_count; + hi_bool flash_flag[FLASH_FLAG_NUM]; + hi_u16 pad; + hi_u8 *key_n; + hi_u8 *key_e; + hi_u8 *sign; + hi_u32 key_len; + hi_padding_mode pad_mode; +} upg_verify_param; + +hi_bool boot_upg_is_secure_efuse(hi_void); +hi_u32 boot_upg_check_secure_info(hi_u32 flash_addr, hi_upg_head *upg_head); +hi_u32 boot_upg_check_unsecure_info(hi_u32 flash_addr, hi_upg_head *upg_head); +hi_void boot_upg_save_key_pos(hi_void); +hi_u32 boot_upg_secure_verify_head(hi_upg_head *upg_head); +hi_u32 boot_upg_unsecure_verify_head(hi_upg_head *upg_head); + +#endif + diff --git a/sdk_liteos/boot/flashboot/upg/boot_upg_common.c b/sdk_liteos/boot/flashboot/upg/boot_upg_common.c new file mode 100644 index 0000000000000000000000000000000000000000..9faf85b317c6ceb58f785bc7dd768703fcd95588 --- /dev/null +++ b/sdk_liteos/boot/flashboot/upg/boot_upg_common.c @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +hi_bool boot_upg_tool_bit_test(const hi_u8 *data, hi_u16 pos) +{ + hi_u16 base = pos / BIT_U8; + hi_u16 i = pos % BIT_U8; + return (hi_bool)bit_get(data[base], i); +} + +hi_void boot_upg_tool_bit_set(hi_u8 *data, hi_u16 pos, hi_u8 val) +{ + hi_u16 base = pos / BIT_U8; + hi_u16 i = pos % BIT_U8; + + bit_set(data[base], i, val); +} \ No newline at end of file diff --git a/sdk_liteos/boot/flashboot/upg/boot_upg_common.h b/sdk_liteos/boot/flashboot/upg/boot_upg_common.h new file mode 100644 index 0000000000000000000000000000000000000000..212c4f3a01c4ac8eb35a4a20597ab0469ceb9220 --- /dev/null +++ b/sdk_liteos/boot/flashboot/upg/boot_upg_common.h @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __BOOT_UPG_COMMON_H__ +#define __BOOT_UPG_COMMON_H__ + +#include +#include +#include +#include +#include + +typedef hi_u8 srv_bit; /* value 0 or 1 */ + +#define BIT_U8 8 +#define BIT_U16 16 +#define MASK_U16 0xFFFF + +#define SRV_BIT_LOW 0 +#define SRV_BIT_HIGH 1 + +/* + i must 0~7 b must 0 or 1 x must a character + high ----------------> low + ************************** + 7 6 5 4 3 2 1 0 + ************************** + */ +#define bit_set(x, i, b) ((x) = (hi_u8)((b) ? ((1 << (i)) | (x)) : ((~(hi_u8)(1 << (i))) & (x)))) +#define bit_get(x, i) (((1 << (i)) & (x)) ? 1 : 0) + +#define boot_upg_mem_free(sz) \ + do { \ + if ((sz) != HI_NULL) { \ + boot_free((sz)); \ + } \ + (sz) = HI_NULL; \ + } while (0) + +hi_bool boot_upg_tool_bit_test(const hi_u8 *data, hi_u16 pos); +hi_void boot_upg_tool_bit_set(hi_u8 *data, hi_u16 pos, hi_u8 val); + +#endif + diff --git a/sdk_liteos/boot/flashboot/upg/boot_upg_kernel.c b/sdk_liteos/boot/flashboot/upg/boot_upg_kernel.c new file mode 100644 index 0000000000000000000000000000000000000000..704d1b539f8cae7ee59b37ee4e8ff8a5810fb121 --- /dev/null +++ b/sdk_liteos/boot/flashboot/upg/boot_upg_kernel.c @@ -0,0 +1,128 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "boot_upg_kernel.h" +#include "boot_upg_tool.h" + +#if defined(CONFIG_FLASH_ENCRYPT_SUPPORT) +#include +#endif + +hi_u32 boot_upg_lzma_detect(hi_u32 addr_write, hi_u32 *uncompress_size, const hi_upg_section_head *section_head) +{ + hi_u8 lzma_head[13] = { 0 }; /* head 13B */ + hi_u32 dic_size = 0; + + /* get LZMA head. get uncompressed size */ + hi_u32 ret = hi_flash_read(addr_write + section_head->section0_offset, 13, lzma_head); /* 13 Bytes:head length */ + if (ret != HI_ERR_SUCCESS) { + return ret; + } + ret = hi_lzma_get_uncompress_len(lzma_head, sizeof(lzma_head), uncompress_size, &dic_size); + if (ret != HI_ERR_SUCCESS) { + boot_msg1("get uncompress len:", ret); + return ret; + } + + /* RAM usage detect for LAMA uncompressing. + * Avoid can't uncompress after erasing file, it'll cause unable to start */ + ret = hi_lzma_mem_detect(lzma_head, sizeof(lzma_head)); + if (ret != HI_ERR_SUCCESS) { + boot_msg1("mem detect:", ret); + } else { + if ((*uncompress_size) == 0) { + ret = HI_ERR_UPG_FILE_LEN_ZERO; + boot_msg0("uncompress size."); + } + } + return ret; +} + +hi_u32 boot_upg_lzma_verify(hi_u32 addr_write, hi_u32 *uncompress_size, const hi_upg_section_head *section_head, + const hi_upg_file_head *file_head) +{ + hi_u32 ret = boot_upg_lzma_detect(addr_write, uncompress_size, section_head); + if (ret != HI_ERR_SUCCESS) { + boot_msg2("detect1 writeaddr-uncompress_size:", addr_write, *uncompress_size); + return ret; + } + + ret = hi_cipher_init(); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + ret = boot_upg_check_before_decompress(addr_write, section_head, file_head); + if (ret != HI_ERR_SUCCESS) { + boot_msg1("check before decompress:", ret); + } + (hi_void)hi_cipher_deinit(); + return ret; +} + +hi_u32 boot_upg_kernel_process(hi_u32 addr_start, hi_u32 addr_write) +{ + hi_u32 uncompress_size; + hi_upg_section_head section_head = { 0 }; + hi_u32 ret = hi_flash_read(addr_write + sizeof(hi_upg_head), sizeof(hi_upg_section_head), (hi_u8 *)(§ion_head)); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + if (section_head.section0_compress == HI_FALSE) { + boot_msg0("Not support uncompressed file."); + return HI_ERR_UPG_PARAMETER; + } + hi_upg_file_head *file_head = boot_malloc(sizeof(hi_upg_file_head)); + if (file_head == HI_NULL) { + return HI_ERR_UPG_MALLOC_FAIL; + } + +#if defined(CONFIG_FLASH_ENCRYPT_SUPPORT) + ret = boot_decrypt_upg_file(addr_write, §ion_head); + if (ret != HI_ERR_SUCCESS) { + boot_msg1("decrypt upg file fail:", ret); + goto end; + } +#endif + + ret = boot_upg_lzma_verify(addr_write, &uncompress_size, §ion_head, file_head); + if (ret != HI_ERR_SUCCESS) { + boot_msg1("lzma verify fail:", ret); + goto end; + } + + ret = boot_upg_lzma_detect(addr_write, &uncompress_size, §ion_head); + if (ret != HI_ERR_SUCCESS) { + boot_msg1("detect2:", ret); + goto end; + } + + /* make 4K allignment for kernal and NV before compression. Erasing target space */ + hi_u32 erase_size = uncompress_size; + erase_size = align_length(erase_size, ALIGNTYPE_4K); + ret = hi_flash_erase(addr_start, erase_size); + boot_msg4("info start-erasesize-write-uncompresssize:", addr_start, erase_size, addr_write, uncompress_size); + /* uncompress kernel and nv file to target space */ + ret = boot_upg_copy_flash_2_flash(addr_write + section_head.section0_offset, section_head.section0_len, + addr_start, uncompress_size, section_head.section0_compress); + if (ret == HI_ERR_SUCCESS) { + boot_msg0("[bootupg kernel process]decompress success."); + } +end: + boot_upg_mem_free(file_head); +#if defined(CONFIG_FLASH_ENCRYPT_SUPPORT) + boot_decrypt_free_memory(); +#endif + return ret; +} \ No newline at end of file diff --git a/sdk_liteos/boot/flashboot/upg/boot_upg_kernel.h b/sdk_liteos/boot/flashboot/upg/boot_upg_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..fb1ac0c7c37420df2b80098a7c77d1ba26bd261f --- /dev/null +++ b/sdk_liteos/boot/flashboot/upg/boot_upg_kernel.h @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __BOOT_UPG_KERNEL_H__ +#define __BOOT_UPG_KERNEL_H__ + +#include "boot_upg_common.h" + +hi_u32 boot_upg_kernel_process(hi_u32 addr_start, hi_u32 addr_write); + +#endif diff --git a/sdk_liteos/boot/flashboot/upg/boot_upg_start_up.c b/sdk_liteos/boot/flashboot/upg/boot_upg_start_up.c new file mode 100644 index 0000000000000000000000000000000000000000..2de01c3dcb038bb7f4430c0b2894865fae812236 --- /dev/null +++ b/sdk_liteos/boot/flashboot/upg/boot_upg_start_up.c @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include "boot_start.h" + +hi_nv_ftm_startup_cfg g_startup_cfg; + +hi_void boot_upg_set_default_cfg(hi_void) +{ + hi_nv_ftm_startup_cfg *cfg = boot_upg_get_cfg(); + hi_flash_partition_table *partition = hi_get_partition_table(); + uintptr_t kernel_a_addr = partition->table[HI_FLASH_PARTITON_KERNEL_A].addr; + hi_u32 cs = (uintptr_t)cfg ^ sizeof(hi_nv_ftm_startup_cfg) ^ 0 ^ sizeof(hi_nv_ftm_startup_cfg); + if (memset_s(cfg, sizeof(hi_nv_ftm_startup_cfg), 0, sizeof(hi_nv_ftm_startup_cfg), cs) != EOK) { + return; + } + cfg->addr_start = kernel_a_addr; + cfg->cnt_max = UPG_MAX_BACKUP_CNT; +} + +hi_u32 boot_upg_save_cfg_to_nv(hi_void) +{ + hi_nv_ftm_startup_cfg *cfg = boot_upg_get_cfg(); + hi_u32 ret = hi_factory_nv_write(HI_NV_FTM_STARTUP_CFG_ID, cfg, sizeof(hi_nv_ftm_startup_cfg), 0); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + return ret; +} + +hi_u32 boot_upg_check_start_addr(hi_u32 addr) +{ + hi_flash_partition_table *partition = hi_get_partition_table(); + uintptr_t kernel_a_addr = partition->table[HI_FLASH_PARTITON_KERNEL_A].addr; +#if defined(CONFIG_COMPRESSION_OTA_SUPPORT) + if (addr != kernel_a_addr) { + return HI_ERR_FAILURE; + } +#else + uintptr_t kernel_b_addr = partition->table[HI_FLASH_PARTITON_KERNEL_B].addr; + if ((addr != kernel_a_addr) && (addr != kernel_b_addr)) { + return HI_ERR_FAILURE; + } +#endif + return HI_ERR_SUCCESS; +} + +hi_void boot_upg_load_cfg_from_nv(hi_void) +{ + hi_bool set_default_nv_flag = HI_FALSE; + hi_u32 cs; + hi_nv_ftm_startup_cfg nv_cfg = { 0 }; + hi_nv_ftm_startup_cfg *cfg = boot_upg_get_cfg(); + hi_u32 ret = hi_factory_nv_read(HI_NV_FTM_STARTUP_CFG_ID, &nv_cfg, sizeof(hi_nv_ftm_startup_cfg), 0); + if (ret != HI_ERR_SUCCESS) { + set_default_nv_flag = HI_TRUE; + } else { + ret = boot_upg_check_start_addr(nv_cfg.addr_start); + if (ret != HI_ERR_SUCCESS) { + set_default_nv_flag = HI_TRUE; + boot_msg1("[bootupg load cfg]check addr start fail", nv_cfg.addr_start); + } else { + cs = (uintptr_t)cfg ^ sizeof(hi_nv_ftm_startup_cfg) ^ ((uintptr_t)&nv_cfg) ^ sizeof(hi_nv_ftm_startup_cfg); + if (memcpy_s(cfg, sizeof(hi_nv_ftm_startup_cfg), &nv_cfg, sizeof(hi_nv_ftm_startup_cfg), cs) != EOK) { + set_default_nv_flag = HI_TRUE; + } + } + } + + if (set_default_nv_flag == HI_TRUE) { + boot_upg_set_default_cfg(); + boot_upg_save_cfg_to_nv(); + } + + /* judge factory test mode */ +#ifdef CONFIG_FACTORY_TEST_SUPPORT + hi_nv_ftm_factory_mode factory_mode_cfg = {0}; + ret = hi_factory_nv_read(HI_NV_FTM_FACTORY_MODE, &factory_mode_cfg, sizeof(hi_nv_ftm_factory_mode), 0); + if (ret != HI_ERR_SUCCESS) { + boot_msg0("read ftm fail"); + } else { + if (factory_mode_cfg.factory_mode == 0x1) { + boot_msg0("set ftm addr"); + cfg->addr_start = factory_mode_cfg.factory_addr_start; /* 0x0: factory mode, start addr example:0x14D000. */ + } + } +#endif + + boot_upg_init_verify_addr(cfg); +} + +hi_nv_ftm_startup_cfg *boot_upg_get_cfg(hi_void) +{ + return &g_startup_cfg; +} diff --git a/sdk_liteos/boot/flashboot/upg/boot_upg_start_up.h b/sdk_liteos/boot/flashboot/upg/boot_upg_start_up.h new file mode 100644 index 0000000000000000000000000000000000000000..40418ded53c9d353d1dfa139dde61209dcb19861 --- /dev/null +++ b/sdk_liteos/boot/flashboot/upg/boot_upg_start_up.h @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __BOOT_UPG_START_UP_H +#define __BOOT_UPG_START_UP_H + +#include + +#define ENV_REFRESH_NV 0x55 + +#define HI_UPG_MODE_NORMAL 0 /* normal mode */ +#define HI_UPG_MODE_UPGRADE 1 /* upgrade mode */ +#define UPG_MAX_BACKUP_CNT 3 + +#define HI_NV_FTM_STARTUP_CFG_ID 0x3 +#define HI_NV_FTM_FACTORY_MODE 0x9 + +typedef struct { + uintptr_t addr_start; /* boot start address */ + hi_u16 mode; /* upgrade mode */ + hi_u8 file_type; /* file type:boot or code+nv */ + hi_u8 refresh_nv; /* refresh nv when the flag bit 0x55 is read */ + hi_u8 reset_cnt; /* number of restarts in upgrade mode */ + hi_u8 cnt_max; /* the maximum number of restarts (default value : 3) */ + hi_u16 reserved1; + uintptr_t addr_write; /* write kernel upgrade file address */ + hi_u32 reserved2; /* 2: reserved bytes */ +} hi_nv_ftm_startup_cfg; + +typedef struct { + hi_u32 factory_mode; /* 0:normal_mode;1:factory_mode */ + uintptr_t factory_addr_start; /* factory bin start address */ + hi_u32 factory_size; /* factory bin size */ + hi_u32 factory_valid; /* 0:invalid;1:valid */ +}hi_nv_ftm_factory_mode; + +hi_u32 boot_upg_save_cfg_to_nv(hi_void); +hi_void boot_upg_load_cfg_from_nv(hi_void); +hi_nv_ftm_startup_cfg *boot_upg_get_cfg(hi_void); + +#endif /* __BOOT_UPG_START_UP_H */ diff --git a/sdk_liteos/boot/flashboot/upg/boot_upg_tool.c b/sdk_liteos/boot/flashboot/upg/boot_upg_tool.c new file mode 100644 index 0000000000000000000000000000000000000000..b35c5a1b63382d1aa5c38231d2cc2c92629e7ee7 --- /dev/null +++ b/sdk_liteos/boot/flashboot/upg/boot_upg_tool.c @@ -0,0 +1,327 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "boot_upg_tool.h" + +#if defined(CONFIG_FLASH_ENCRYPT_SUPPORT) +#include +#endif + +hi_u8 g_upg_tool_block[HI_BLOCK_SIZE]; +static hi_u32 g_compress_src_addr = 0; +static hi_u32 g_compress_dst_addr = 0; + +hi_u32 kernel_comprss_flash_read(hi_u32 offset, hi_u8 *buffer, hi_u32 size) +{ + hi_u32 ret; +#if defined(CONFIG_FLASH_ENCRYPT_SUPPORT) + ret = crypto_kernel_read(g_compress_src_addr, offset, buffer, size); + if (ret == HI_ERR_SUCCESS) { + ret = 0; + } +#else + ret = hi_flash_read(g_compress_src_addr + offset, size, buffer); + if (ret == HI_ERR_SUCCESS) { + ret = 0; + } +#endif + + return ret; +} + +hi_u32 kernel_comprss_flash_write(hi_u32 offset, hi_u8 *buffer, hi_u32 size) +{ + hi_u32 ret; + hi_u32 tmp_size = size + 1; + +#if defined(CONFIG_FLASH_ENCRYPT_SUPPORT) + ret = crypto_kernel_write(g_compress_dst_addr, offset, buffer, size); + if (ret != HI_ERR_SUCCESS) { + return tmp_size; + } +#else + ret = hi_flash_write(g_compress_dst_addr + offset, size, buffer, HI_FALSE); + if (ret != HI_ERR_SUCCESS) { + return tmp_size; + } +#endif + return size; +} + +hi_u32 kernel_comprss_flash_hash(hi_u32 offset, hi_u8 *buffer, hi_u32 size) +{ + hi_u32 cs; + hi_u32 ret = HI_ERR_SUCCESS; + hi_u32 hash_size = size + 1; + + if (offset >= sizeof(hi_upg_file_head)) { + ret = hi_cipher_hash_update((uintptr_t)buffer, size); + if (ret == HI_ERR_SUCCESS) { + hash_size = size; + } else { + boot_msg4("code hash ret-size-offset-headsize", ret, size, offset, hash_size); + } + return hash_size; + } + + /* offset less than sizeof(hi_upg_file_head) */ + if ((offset + size) > sizeof(hi_upg_file_head)) { + hi_u32 cy_size = sizeof(hi_upg_file_head) - offset; + cs = (uintptr_t)(g_compress_dst_addr + offset) ^ cy_size ^ (uintptr_t)buffer ^ cy_size; + (hi_void) memcpy_s((hi_void *)(uintptr_t)(g_compress_dst_addr + offset), cy_size, buffer, cy_size, cs); + + /* Cal hash of common section head */ + ret = hi_cipher_hash_update((uintptr_t)(g_compress_dst_addr + sizeof(hi_upg_head)), + sizeof(hi_upg_section_head)); + if (ret != HI_ERR_SUCCESS) { + boot_msg4("head hash updata ret-size-offset-hashsize", ret, size, offset, hash_size); + return hash_size; + } + /* Cal hash of common section */ + ret = hi_cipher_hash_update((uintptr_t)(buffer + cy_size), (size - cy_size)); + } else { + cs = (uintptr_t)(g_compress_dst_addr + offset) ^ size ^ (uintptr_t)buffer ^ size; + (hi_void) memcpy_s((hi_void *)(uintptr_t)(g_compress_dst_addr + offset), size, buffer, size, cs); + } + if (ret == HI_ERR_SUCCESS) { + hash_size = size; + } else { + boot_msg4("code head hash ret-size-offset-hashsize", ret, size, offset, hash_size); + } + return hash_size; +} + +hi_u32 boot_upg_copy_flash_2_flash(hi_u32 src_addr, hi_u32 src_size, hi_u32 dst_addr, hi_u32 dst_size, hi_bool comprss) +{ + hi_u8 lzma_head[13] = { 0 }; /* head 13B */ + hi_u32 ret = HI_ERR_UPG_PARAMETER; + + if (!comprss) { + boot_msg0("Not support uncompressed file."); + return ret; + } else { + boot_msg4("src-size-dst-size", src_addr, src_size, dst_addr, dst_size); + hi_flash_read(src_addr, 13, lzma_head); /* read 13B */ + g_compress_src_addr = src_addr; + g_compress_dst_addr = dst_addr; + ret = hi_lzma_decompress(lzma_head, sizeof(lzma_head), src_size, kernel_comprss_flash_read, + kernel_comprss_flash_write); + } + return ret; +} + +hi_u32 boot_upg_hash_one_content(hi_u32 flash_addr, hi_u32 total_size, hi_u8 *hash, hi_u32 hash_size) +{ + hi_u32 ret; + hi_u8 *block = g_upg_tool_block; + + ret = hi_cipher_hash_start(); + if (ret != HI_ERR_SUCCESS) { + boot_msg1("[bootupg hash one content]start ret:", ret); + return ret; + } + + for (uintptr_t offset = 0; offset < total_size;) { + uintptr_t this_size = (total_size - offset > HI_BLOCK_SIZE) ? HI_BLOCK_SIZE : (total_size - offset); + ret = hi_flash_read(flash_addr + offset, this_size, block); + if (ret != HI_ERR_SUCCESS) { + (hi_void) hi_cipher_hash_final(hash, hash_size); + return ret; + } + + ret = hi_cipher_hash_update((uintptr_t)block, this_size); + if (ret != HI_ERR_SUCCESS) { + boot_msg1("[bootupg hash one content]update ret:", ret); + return ret; + } + offset += this_size; + } + return hi_cipher_hash_final(hash, hash_size); +} + +hi_u32 boot_upg_hash_more_content(HI_CONST upg_verify_param *param, hi_u8 *hash, hi_u32 hash_size) +{ + hi_u32 cs; + hi_u8 *block = g_upg_tool_block; + + hi_u32 ret = hi_cipher_hash_start(); + if (ret != HI_ERR_SUCCESS) { + boot_msg1("[bootupg hash more content]cipher start ret:", ret); + return ret; + } + + for (hi_u8 i = 0; i < param->buffer_count; i++) { + uintptr_t size = param->total_size[i]; + for (uintptr_t offset = 0; offset < size;) { + uintptr_t this_size = ((size - offset) > HI_BLOCK_SIZE) ? HI_BLOCK_SIZE : (size - offset); + if (param->flash_flag[i]) { + ret = hi_flash_read(param->flash_addr[i] + offset, this_size, block); + } else { + cs = (uintptr_t)block ^ HI_BLOCK_SIZE ^ (uintptr_t)(param->flash_addr[i] + offset) ^ this_size; + ret = (hi_u32)memcpy_s(block, HI_BLOCK_SIZE, (hi_u8 *)(param->flash_addr[i] + offset), this_size, cs); + } + if (ret != HI_ERR_SUCCESS) { + (hi_void) hi_cipher_hash_final(hash, hash_size); + return ret; + } + + ret = hi_cipher_hash_update((uintptr_t)block, this_size); + if (ret != HI_ERR_SUCCESS) { + boot_msg1("[bootupg hash more content]hash update ret: ", ret); + return ret; + } + offset += this_size; + } + } + return hi_cipher_hash_final(hash, hash_size); +} + +hi_u32 boot_upg_lzma_secure_verify(const upg_verify_param *param, hi_u8 *hash, hi_u32 hash_size) +{ + hi_u8 out_hash[SHA_256_LEN] = { 0 }; + hi_u32 ret; + + if (hash_size != SHA_256_LEN) { + return HI_ERR_UPG_PARAMETER; + } + + if (param->pad_mode == HI_MODE_ECC) { + hi_cipher_ecc_verify ecc_verify = { + .px = param->key_n, + .py = param->key_e, + .hash = hash, + .hash_len = PKE_LEN_32_BYTES, + .r = (hi_u8 *)param->sign, + .s = (hi_u8 *)param->sign + ECC_32_BYTES, + .out_r = out_hash, + }; + ret = hi_cipher_ecc_verify_hash(&g_brain_pool_p256r1_verify, &ecc_verify); + } else { + hi_cipher_rsa_verify rsa_verify = { + .n = param->key_n, + .e = param->key_e, + .klen = param->key_len, + .scheme = (hi_cipher_rsa_sign_scheme)(param->pad_mode), + }; + hi_cipher_rsa_data rsa_data = { + .hash = hash, + .out_hash = out_hash, + .hash_len = PKE_LEN_32_BYTES, + .sign = param->sign, + .sign_len = sizeof(upg_rsa_sign), + }; + ret = hi_cipher_rsa_verify_hash(&rsa_verify, &rsa_data); + } + return ret; +} + +hi_u32 boot_upg_lzma_secure_verify_code(const hi_upg_file_head *upg_head, hi_u8 *hash, hi_u32 hash_size) +{ + hi_u32 cs; + hi_u32 ret; + hi_u32 key_length = (upg_head->common.param.sign_alg == HI_MODE_ECC) ? ECC_256_LEN : RSA_2048_LEN; + hi_u32 key2_offset = sizeof(hi_upg_common_head) + key_length; + hi_u8 *key_e = g_upg_tool_block; + + if (key_length > HI_BLOCK_SIZE) { + boot_msg1("[bootupg lzma verify code]key size", key_length); + return HI_ERR_UPG_PARAMETER; + } + cs = (uintptr_t)key_e ^ HI_BLOCK_SIZE ^ 0 ^ HI_BLOCK_SIZE; + memset_s(key_e, HI_BLOCK_SIZE, 0, HI_BLOCK_SIZE, cs); + + if (upg_head->common.param.sign_alg == HI_MODE_ECC) { + cs = (uintptr_t)key_e ^ ECC_256_LEN ^ (uintptr_t)((hi_u8 *)upg_head + key2_offset) ^ ECC_256_LEN; + (hi_void) memcpy_s(key_e, key_length, (hi_u8 *)upg_head + key2_offset, ECC_256_LEN, cs); + } else { + cs = (uintptr_t)(key_e + key_length - RSA_EXP_E_LEN) ^ RSA_EXP_E_LEN ^ + (uintptr_t)((hi_u8 *)upg_head + key2_offset) ^ RSA_EXP_E_LEN; + (hi_void)memcpy_s(key_e + key_length - RSA_EXP_E_LEN, RSA_EXP_E_LEN, + (hi_u8 *)upg_head + key2_offset, RSA_EXP_E_LEN, cs); + } + + upg_verify_param param = { 0 }; + param.key_n = (hi_u8 *)upg_head + sizeof(hi_upg_common_head); + param.key_e = key_e; + param.key_len = key_length; + param.sign = (hi_u8 *)upg_head + sizeof(hi_upg_head) + sizeof(hi_upg_section_head); + param.pad_mode = (hi_padding_mode)upg_head->common.param.sign_alg; + ret = boot_upg_lzma_secure_verify(¶m, hash, hash_size); + if (ret != HI_ERR_SUCCESS) { + boot_msg1("[bootupg lzma verify code]ret", ret); + } + return ret; +} + +hi_u32 boot_upg_lzma_unsecure_verify_code(const hi_upg_file_head *upg_head, hi_u8 *hash, hi_u32 hash_size) +{ + if (hash_size != SHA_256_LEN) { + return HI_ERR_UPG_PARAMETER; + } + + if (memcmp((hi_u8 *)upg_head + sizeof(hi_upg_head) + sizeof(hi_upg_section_head), hash, hash_size) != EOK) { + return HI_ERR_UPG_SECTION_SHA256; + } + return HI_ERR_SUCCESS; +} + +hi_u32 boot_upg_check_before_decompress(hi_u32 addr_write, const hi_upg_section_head *section_head, + const hi_upg_file_head *file_head) +{ + hi_u8 lzma_head[13] = { 0 }; /* head 13B */ + hi_u32 ret; + hi_u8 hash[SHA_256_LEN] = { 0 }; + + hi_flash_read(addr_write + section_head->section0_offset, 13, lzma_head); /* read 13B */ + g_compress_src_addr = addr_write + section_head->section0_offset; + g_compress_dst_addr = (hi_u32)(uintptr_t)file_head; + + ret = hi_cipher_hash_start(); + if (ret != HI_ERR_SUCCESS) { + boot_msg1("[bootupg before decompress]hash start fail", ret); + return ret; + } + ret = hi_lzma_decompress(lzma_head, sizeof(lzma_head), section_head->section0_len, kernel_comprss_flash_read, + kernel_comprss_flash_hash); + if (ret != HI_ERR_SUCCESS) { + boot_msg1("[bootupg before decompress]decompress fail", ret); + return ret; + } + (hi_void)hi_cipher_hash_final(hash, SHA_256_LEN); + + /* verify common & code section */ + hi_upg_head *common_section = (hi_upg_head *)(uintptr_t)g_compress_dst_addr; + if (boot_upg_is_secure_efuse() == HI_TRUE) { + ret = boot_upg_secure_verify_head(common_section); + if (ret != HI_ERR_SUCCESS) { + boot_msg1("[bootupg before decompress]verify head hash ret", ret); + return ret; + } + ret = boot_upg_lzma_secure_verify_code(file_head, hash, SHA_256_LEN); + } else { + ret = boot_upg_unsecure_verify_head(common_section); + if (ret != HI_ERR_SUCCESS) { + boot_msg1("[bootupg before decompress]verify head sha256 ret", ret); + return ret; + } + ret = boot_upg_lzma_unsecure_verify_code(file_head, hash, SHA_256_LEN); + } + + if (ret != HI_ERR_SUCCESS) { + boot_msg1("[bootupg before decompress]verfiy code fail", ret); + } + return ret; +} + diff --git a/sdk_liteos/boot/flashboot/upg/boot_upg_tool.h b/sdk_liteos/boot/flashboot/upg/boot_upg_tool.h new file mode 100644 index 0000000000000000000000000000000000000000..c96cae8f48759cd94534dd7e0d5bb8d370dff4df --- /dev/null +++ b/sdk_liteos/boot/flashboot/upg/boot_upg_tool.h @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __BOOT_UPG_TOOL_H__ +#define __BOOT_UPG_TOOL_H__ +#include "boot_upg_common.h" + +#include "boot_upg_check_secure.h" + +#define HI_BLOCK_SIZE 0x100 + +hi_u32 boot_upg_copy_flash_2_flash(hi_u32 src_addr, hi_u32 src_size, hi_u32 dst_addr, hi_u32 dst_size, hi_bool comprss); +hi_u32 boot_upg_hash_one_content(hi_u32 flash_addr, hi_u32 total_size, hi_u8 *hash, hi_u32 hash_size); +hi_u32 boot_upg_hash_more_content(HI_CONST upg_verify_param *param, hi_u8 *hash, hi_u32 hash_size); +hi_u32 boot_upg_check_before_decompress(hi_u32 addr_write, const hi_upg_section_head *seciton_head, + const hi_upg_file_head *file_head); + +#endif diff --git a/sdk_liteos/boot/loaderboot/Makefile b/sdk_liteos/boot/loaderboot/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..1ee85bc71d52a2af7f8dc9bd1006926079576e7d --- /dev/null +++ b/sdk_liteos/boot/loaderboot/Makefile @@ -0,0 +1,99 @@ +include $(MAIN_TOPDIR)/build/make_scripts/config.mk +-include $(MAIN_TOPDIR)/$(MODULE_DIR)/srcs.mk +include $(MAIN_TOPDIR)/$(MODULE_DIR)/module_config.mk + +override CCFLAGS = $(BOOT_CCFLAGS) $(BOOT_DEFINE) $(BOOT_INC) +override ASFLAGS = $(BOOT_ASFLAGS) $(BOOT_DEFINE) $(BOOT_INC) + +LIBDIR = $(MAIN_TOPDIR)/$(LIB_PATH)/$(MODULE_DIR) +OBJDIR = $(MAIN_TOPDIR)/$(OBJ_PATH)/loaderboot +ID_CFG_FILE = $(MAIN_TOPDIR)/$(MODULE_DIR)/file_id.cfg + +LIB_NAME = lib$(LIB).a +SRCS = $($(LIB)_srcs) +LIBOUT = $(LIBDIR)/$(MODULE_DIR)/$(LIB_NAME) + +ifdef SRC_FILES +OBJ_SRCS = $(filter %.c, $(SRC_FILES)) +ASM_SRCS = $(filter %.S, $(SRC_FILES)) +else +OBJ_SRCS = $(foreach dir, $(SRCS), $(wildcard $(dir)/*.c)) +ASM_SRCS = $(foreach dir, $(SRCS), $(wildcard $(dir)/*.S )) +OBJ_COMMON_SRCS = $(foreach dir, $($(LIB)_common_srcs), $(wildcard $(dir)/*.c)) +ASM_COMMON_SRCS = $(foreach dir, $($(LIB)_common_srcs), $(wildcard $(dir)/*.S )) +endif +OBJ_SRCS += $(MAIN_TOPDIR)/third_party/u-boot-v2019.07/u-boot-v2019.07/lib/crc32.c \ + $(MAIN_TOPDIR)/third_party/u-boot-v2019.07/u-boot-v2019.07/lib/lzma/LzmaDec.c \ + $(MAIN_TOPDIR)/third_party/u-boot-v2019.07/u-boot-v2019.07/lib/lzma/LzmaTools.c +OBJS = $(patsubst %.c, $(OBJDIR)/%.o, $(OBJ_SRCS)) +ASM_OBJS = $(patsubst %.S, $(OBJDIR)/%.o, $(ASM_SRCS)) +COMMON_OBJS = $(patsubst ../%.c, $(OBJDIR)/%.o, $(OBJ_COMMON_SRCS)) +COMMON_ASM_OBJS = $(patsubst ../%.S, $(OBJDIR)/%.o, $(ASM_COMMON_SRCS)) + +SIGN_TOOL = $(MAIN_TOPDIR)/tools/sign_tool/sign_tool +ENCRYPT_KEY_PATH = $(MAIN_TOPDIR)/tools/sign_tool/aes_key.txt +ifeq ($(CONFIG_TARGET_SIG_SHA256), y) + LINK_FILE = $(MAIN_TOPDIR)/build/link/loaderboot_sha256.lds +else ifeq ($(CONFIG_TARGET_SIG_ECC), y) + LINK_FILE = $(MAIN_TOPDIR)/build/link/loaderboot_ecc.lds + ROOT_KEY_PATH = $(MAIN_TOPDIR)/tools/sign_tool/root_ecc.pem + SUB_KEY_PATH = $(MAIN_TOPDIR)/tools/sign_tool/sub_ecc.pem + SIGN_TYPE = 2 +else + LINK_FILE = $(MAIN_TOPDIR)/build/link/loaderboot_rsa.lds + ROOT_KEY_PATH = $(MAIN_TOPDIR)/tools/sign_tool/root_rsa.pem + SUB_KEY_PATH = $(MAIN_TOPDIR)/tools/sign_tool/sub_rsa.pem + ifeq ($(CONFIG_TARGET_SIG_RSA_V15), y) + SIGN_TYPE = 0 + else ifeq ($(CONFIG_TARGET_SIG_RSA_PSS), y) + SIGN_TYPE = 1 + endif +endif + +LIBS := $(patsubst lib%.a, -l%, $(notdir $(wildcard $(MAIN_TOPDIR)/build/libs/boot_libs/*.a))) +LIBPATH := -L$(MAIN_TOPDIR)/build/libs +LIBPATH += -L$(MAIN_TOPDIR)/build/libs/boot_libs +BOOT_ELF = $(MAIN_TOPDIR)/$(CACHE_PATH)/loader_boot.elf +BOOT_BIN = $(MAIN_TOPDIR)/$(CACHE_PATH)/hi_loader_boot.bin +BOOT_SIGNED_BIN = $(MAIN_TOPDIR)/$(BIN_PATH)/$(TARGET_CHIP)_loader_signed.bin + +all: $(OBJS) $(ASM_OBJS) $(COMMON_OBJS) $(COMMON_ASM_OBJS) + $(LINK) $(BOOT_LINK_FLAGS) -T $(LINK_FILE) $(LIBPATH) $(sort $^) -o $(BOOT_ELF) --start-group $(LIBS) --end-group + $(OBJCOPY) -Obinary -R .rom.text -R .rom.code.text -R .u_boot_cmd -R .rom.data -R .rom.code.data -R .rom.bss -R .rom.code.bss -S $(BOOT_ELF) $(BOOT_BIN) +ifeq ($(CONFIG_TARGET_SIG_SHA256), y) + $(SIGN_TOOL) -i $(BOOT_BIN) -o $(BOOT_SIGNED_BIN) -n +else ifeq ($(CONFIG_BOOT_ENCRYPT), y) + $(SIGN_TOOL) -i $(BOOT_BIN) -o $(BOOT_SIGNED_BIN) -r$(ROOT_KEY_PATH) -s$(SUB_KEY_PATH) -v $(CONFIG_TARGET_BOOT_VER) -a $(SIGN_TYPE) -e$(ENCRYPT_KEY_PATH) +else + $(SIGN_TOOL) -i $(BOOT_BIN) -o $(BOOT_SIGNED_BIN) -r$(ROOT_KEY_PATH) -s$(SUB_KEY_PATH) -v $(CONFIG_TARGET_BOOT_VER) -a $(SIGN_TYPE) +endif + $(Q)echo [LOADER_BOOT] SUCCESS + $(RM) $(BOOT_ELF) $(BOOT_BIN) + + +include $(MAIN_TOPDIR)/build/make_scripts/lib.mk +$(COMMON_OBJS): $(OBJDIR)/%.o : ../%.c + $(Q)if [ ! -d $(dir $@) ]; then \ + mkdir -p $(dir $@); \ + fi; + $(Q) echo Compile $<; + $(Q)if [ -e $< ]; \ + then $(CC) $(CCFLAGS) -c $< -o $@; \ + if [ "$$?" != "0" ]; then \ + exit 1;\ + fi; \ + fi; + +$(COMMON_ASM_OBJS): $(OBJDIR)/%.o : ../%.S + $(Q)echo Compile $<; + $(Q)if [ ! -d $(dir $@) ]; \ + then \ + mkdir -p $(dir $@);\ + fi; + $(Q)if [ -f $< ]; \ + then \ + $(CC) $(ASFLAGS) -c $< -o $@ ; \ + if [ "$$?" != "0" ]; then \ + exit 1;\ + fi;\ + fi; diff --git a/sdk_liteos/boot/loaderboot/SConscript b/sdk_liteos/boot/loaderboot/SConscript new file mode 100644 index 0000000000000000000000000000000000000000..b0f2bf4f96d585abdbc5cc6302fc6d1ea493d06d --- /dev/null +++ b/sdk_liteos/boot/loaderboot/SConscript @@ -0,0 +1,117 @@ +#!/usr/bin/env python3 +# coding=utf-8 + +import os +from scripts.scons_utils import scons_usr_bool_option +from scripts.scons_utils import scons_get_cfg_val +from scripts.scons_utils import scons_usr_int_option +from scripts.scons_utils import cleanup +from scripts import scons_env_cfg + +Import('env') +Import('env_cfg') +Import('module') + +if scons_usr_bool_option('CONFIG_TARGET_CHIP_HI3861') == 'y': + CONFIG_TARGET_BIN_NAME="Hi3861" +else: + CONFIG_TARGET_BIN_NAME="Hi3861L" + +obj_path = env_cfg.obj_path +bin_path = env_cfg.bin_path +lib_path = env_cfg.lib_path +cache_path = env_cfg.cache_path + +sign_tool = os.path.join("tools", "sign_tool", "sign_tool") +link_path = os.path.join(env_cfg.root, "build", "link", "loaderboot_sha256.lds") +encrypt_key_path = os.path.join('tools', 'sign_tool', 'aes_key.txt') +if scons_usr_bool_option('CONFIG_TARGET_SIG_SHA256') == 'y': + link_path = os.path.join(env_cfg.root, "build", "link", "loaderboot_sha256.lds") +if scons_usr_bool_option('CONFIG_TARGET_SIG_RSA_V15') == 'y': + link_path = os.path.join(env_cfg.root, "build", "link", "loaderboot_rsa.lds") + root_key_path = os.path.join('tools', 'sign_tool', 'root_rsa.pem') + sub_key_path = os.path.join('tools', 'sign_tool', 'sub_rsa.pem') + sign_type = 0 +if scons_usr_bool_option('CONFIG_TARGET_SIG_RSA_PSS') == 'y': + link_path = os.path.join(env_cfg.root, "build", "link", "loaderboot_rsa.lds") + root_key_path = os.path.join('tools', 'sign_tool', 'root_rsa.pem') + sub_key_path = os.path.join('tools', 'sign_tool', 'sub_rsa.pem') + sign_type = 1 +if scons_usr_bool_option('CONFIG_TARGET_SIG_ECC') == 'y': + link_path = os.path.join(env_cfg.root, "build", "link", "loaderboot_ecc.lds") + root_key_path = os.path.join('tools', 'sign_tool', 'root_ecc.pem') + sub_key_path = os.path.join('tools', 'sign_tool', 'sub_ecc.pem') + sign_type = 2 + +#boot_ver +boot_ver = scons_usr_int_option('CONFIG_TARGET_BOOT_VER') +if (boot_ver < 0 or boot_ver > 16): + raise scons_utils.SconsBuildError("%s============== boot_ver invalied, should be 0-16 =============%s"%(scons_utils.colors['red'], scons_utils.colors['end'])) + +module_path = env_cfg.get_module_dir(module) +module_libs = env_cfg.get_module_libs(module) + +env['LIBS'] = list(map(lambda x:'-l%s'%x, env_cfg.get_boot_libs())) +env['LIBPATH'] = env_cfg.get_bootlib_path() +env.Append(LIBPATH=os.path.join('-Lbuild', 'libs', 'boot_libs')) +env = env.Clone() +ld_flags = ["-nostdlib", "-nostartfiles", "-static", "--gc-sections"] +boot_cflags = ["-mabi=ilp32", "-march=rv32imc", "-freorder-blocks-algorithm=simple", "-fno-schedule-insns", + "-nostdinc", "-fno-aggressive-loop-optimizations", "-fno-builtin", "-fstack-protector-strong", + "-fno-exceptions", "-fno-short-enums", "-mtune=size", "-msmall-data-limit=0", "-Wall", "-Werror", "-Os", + "-std=c99", "-falign-functions=2", "-fdata-sections", "-ffunction-sections", "-fno-common"] +boot_asflags = ["-mabi=ilp32", "-march=rv32imc", "-x", "assembler-with-cpp", "-Os", "-Wall", "-Werror", + "-nostdinc", "-fno-common"] +defines = ["-DARCH_RISCV", "-DLOS_COMPILE_LDM", "-DHI_BOARD_ASIC"] +incs = [os.path.join('#', 'boot', 'loaderboot', 'include'), os.path.join('#', 'boot', 'loaderboot', 'fixed', 'include'), os.path.join('#', 'boot', 'loaderboot', 'secure'), os.path.join('#', 'boot', 'commonboot')] + +if scons_usr_bool_option('CONFIG_COMPRESSION_OTA_SUPPORT') == 'y': + defines.append("-DCONFIG_COMPRESSION_OTA_SUPPORT") +if scons_usr_bool_option('CONFIG_DUAL_PARTITION_OTA_SUPPORT') == 'y': + defines.append("-DCONFIG_DUAL_PARTITION_OTA_SUPPORT") +if scons_usr_bool_option('CONFIG_TARGET_SIG_ECC') == 'y': + defines.append("-DCONFIG_TARGET_SIG_ECC") +if scons_usr_bool_option('CONFIG_TARGET_SIG_RSA_V15') == 'y': + defines.append("-DCONFIG_TARGET_SIG_RSA_V15") +if scons_usr_bool_option('CONFIG_TARGET_SIG_RSA_PSS') == 'y': + defines.append("-DCONFIG_TARGET_SIG_RSA_PSS") +if scons_usr_bool_option('CONFIG_FLASH_ENCRYPT_SUPPORT') == 'y': + defines.append("-DCONFIG_FLASH_ENCRYPT_SUPPORT") + +if scons_get_cfg_val('CONFIG_CHIP_PKT_48K') == 'y': + defines.append("-DCONFIG_CHIP_PKT_48K") +else: + defines.append("-DCONFIG_CHIP_PKT_32K") + +env.Replace(CPPDEFINES=defines) +env.Replace(CCFLAGS=boot_cflags) +env.Replace(ASFLAGS=boot_asflags) +env.Replace(CPPPATH=incs) +env.Replace(LINKFLAGS=ld_flags) + +src_path = module_libs['loaderboot'] + +objs = [] +for src in src_path: + path = src if '..' not in src else os.path.relpath(os.path.realpath(os.path.abspath(src)), os.path.join(env_cfg.root)) + objs += env.SConscript(os.path.join(src, 'SConscript'), {'env':env,}, variant_dir = os.path.join('#', obj_path, "loaderboot", path), duplicate=0) + +boot_elf = env.Command(target=os.path.join("#", cache_path, "loader_boot.elf"), source=sorted(objs), action="$LINK $LINKFLAGS -T%s $LIBPATH $SOURCES -o $TARGET --start-group $LIBS --end-group"%(link_path)) +boot_bin = env.Command(target=os.path.join("#", cache_path, "hi_loader_boot.bin"), source=boot_elf, + action="$OBJCOPY -Obinary -R .rom.text -R .rom.code.text -R .u_boot_cmd -R .rom.data -R .rom.code.data -R .rom.bss \ + -R .rom.code.bss -S $SOURCE $TARGET") +if scons_usr_bool_option('CONFIG_TARGET_SIG_SHA256') == 'y': + loader_signed_bin = env.Command(target=os.path.join("#", bin_path, "%s_loader_signed.bin"%(CONFIG_TARGET_BIN_NAME)), source=boot_bin, + action="%s -i $SOURCE -o $TARGET -n"%(sign_tool)) +else: + if scons_usr_bool_option('CONFIG_BOOT_ENCRYPT') == 'y': + loader_signed_bin = env.Command(target=os.path.join("#", bin_path, "%s_loader_signed.bin"%(CONFIG_TARGET_BIN_NAME)), source=boot_bin, + action="%s -i $SOURCE -o $TARGET -r%s -s%s -v %d -a %d -e%s"%(sign_tool, root_key_path, sub_key_path, boot_ver, sign_type, encrypt_key_path)) + else: + loader_signed_bin = env.Command(target=os.path.join("#", bin_path, "%s_loader_signed.bin"%(CONFIG_TARGET_BIN_NAME)), source=boot_bin, + action="%s -i $SOURCE -o $TARGET -r%s -s%s -v %d -a %d"%(sign_tool, root_key_path, sub_key_path, boot_ver, sign_type)) + +env.AddPostAction(boot_bin, cleanup) + +Return('loader_signed_bin') + diff --git a/sdk_liteos/boot/loaderboot/common/SConscript b/sdk_liteos/boot/loaderboot/common/SConscript new file mode 100755 index 0000000000000000000000000000000000000000..aceb2b6a9464ce64030c1f9c5374ec933dcab384 --- /dev/null +++ b/sdk_liteos/boot/loaderboot/common/SConscript @@ -0,0 +1,6 @@ +Import('env') + +env = env.Clone() + +objs = env.Object(Glob('*.c')) +Return('objs') diff --git a/sdk_liteos/boot/loaderboot/common/cmd_loop.c b/sdk_liteos/boot/loaderboot/common/cmd_loop.c new file mode 100644 index 0000000000000000000000000000000000000000..7284d5c740c2afe2ce824cb3df704319a809d823 --- /dev/null +++ b/sdk_liteos/boot/loaderboot/common/cmd_loop.c @@ -0,0 +1,763 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include + +#define CMD_RX_DELAY_MS 100 /* 100ms */ +#define US_PER_MS 1000 +#define CMD_FRAME_TIMEOUT 20000 /* 20s */ +#define CMD_ABNORMAL_MAX 100 +#define CHECKSUM_SIZE 2 +#define ACK_LEN 0x0C + +#define VER_CFG_BIN_LEN 8 +#define UPDATE_VER_STATUS_NONE 0 +#define UPDATE_VER_STATUS_BOOT 1 +#define UPDATE_VER_STATUS_KERNEL 2 +#define UPDATE_VER_STATUS_BOOT_KERNEL 3 +#define KERELN_VER_MAX 48 +#define KERNEL_VER_LEN 6 +#define BOOT_VER_MAX 16 +#define BOOT_VER_LEN 2 +#define BIT_U8 8 +#define SEC_BOOT_FLAG 0x42 +#define WAIT_VER_UPDATE_TRY_CNT 1000 +#define WAIT_VER_UPDATE_TRY_INTER_US 10000 + +#define NMI_BASE_ADDRESS 0x40010000 +#define NMI_CTRL 0x0258 +#define NMI_INT_MOD_DONE_EN_POS 0 + +volatile hi_u8 g_update_ver_status = UPDATE_VER_STATUS_NONE; +volatile hi_bool g_upg_update_ver_success = HI_FALSE; +hi_u8 g_upg_efuse_data_boot_ver[BOOT_VER_LEN] = {0}; +hi_u8 g_upg_efuse_data_kernel_ver[KERNEL_VER_LEN] = {0}; +void *g_nmi_stack_end = ((void *) &__nmi_stack_top); + +typedef enum { + CMD_RX_STATUS_WAIT_START_0, + CMD_RX_STATUS_WAIT_START_1, + CMD_RX_STATUS_WAIT_START_2, + CMD_RX_STATUS_WAIT_START_3, + CMD_RX_STATUS_WAIT_SIZE_0, + CMD_RX_STATUS_WAIT_SIZE_1, + CMD_RX_STATUS_WAIT_TYPE, + CMD_RX_STATUS_WAIT_PAD, + CMD_RX_STATUS_WAIT_DATA, + CMD_RX_STATUS_WAIT_CS_0, + CMD_RX_STATUS_WAIT_CS_1, +} cmd_rx_status; + +typedef hi_u32(*cmd_func) (const uart_ctx *cmd_ctx); + +typedef struct { + hi_u8 cmd_type; + cmd_func cmdfunc; +} loader_cmd; + +uart_ctx *g_cmd_ctx = HI_NULL; + +const loader_cmd g_loader_cmdtable[LOADER_CMD_MAX] = { + { CMD_DL_IMAGE, loader_download_image }, + { CMD_BURN_EFUSE, loader_burn_efuse }, + { CMD_UL_DATA, loader_upload_data }, + { CMD_READ_EFUSE, loader_read_efuse }, + { CMD_FLASH_PROTECT, loader_flash_protect }, + { CMD_RESET, loader_reset }, + { CMD_FACTORY_IMAGE, loader_download_image }, + { CMD_VERSION, loader_burn_version}, +}; + +hi_void loader_read_flash_protect_state(hi_void) +{ + hi_u32 reg = 0; + hi_reg_write(SFC_REG_BASE_ADDRESS + SFC_REG_CMD_DATABUF1, 0); + spif_wait_config_start(); + hi_reg_write(SFC_REG_BASE_ADDRESS + SFC_REG_CMD_INS, 0x05); + hi_reg_write(SFC_REG_BASE_ADDRESS + SFC_REG_CMD_CONFIG, 0x183); + spif_wait_config_start(); + hi_reg_read(SFC_REG_BASE_ADDRESS + SFC_REG_CMD_DATABUF1, reg); + boot_msg1("S0 ~ S7 : ", reg); + hi_reg_write(SFC_REG_BASE_ADDRESS + SFC_REG_CMD_DATABUF1, 0); + spif_wait_config_start(); + hi_reg_write(SFC_REG_BASE_ADDRESS + SFC_REG_CMD_INS, 0x35); + hi_reg_write(SFC_REG_BASE_ADDRESS + SFC_REG_CMD_CONFIG, 0x183); + spif_wait_config_start(); + hi_reg_read(SFC_REG_BASE_ADDRESS + SFC_REG_CMD_DATABUF1, reg); + boot_msg1("S8 ~ S15 : ", reg); +} + +hi_u32 loader_reset(const uart_ctx *cmd_ctx) +{ + hi_unref_param(cmd_ctx); + boot_msg0("\nReset device...\n"); + loader_ack(ACK_SUCCESS); + mdelay(5); /* delay 5ms */ + global_reset(); + return HI_ERR_SUCCESS; +} + +hi_u32 loader_flash_protect(const uart_ctx *cmd_ctx) +{ + hi_u32 ret; + hi_u16 cmd_type = *(hi_u16 *)(&cmd_ctx->packet.payload[0]); + boot_msg0("Flash protect state"); + loader_read_flash_protect_state(); + if (cmd_type == 1) { + ret = flash_protect_set_protect(0, HI_FALSE); + if (ret == HI_ERR_SUCCESS) { + boot_msg0("\r\nUnlock Succ\r\n"); + loader_read_flash_protect_state(); + } else { + boot_msg0("\r\nUnlock Fail\r\n"); + } + return ret; + } else if (cmd_type > 1) { + boot_msg0("Unknow cmd type"); + return HI_ERR_FAILURE; + } + return HI_ERR_SUCCESS; +} + +hi_u32 loader_download_image(const uart_ctx *cmd_ctx) +{ + hi_u8 chip_id[HI_FLASH_CHIP_ID_NUM] = { 0 }; + hi_u32 flash_size = 0; + hi_u32 download_addr = *(hi_u32 *)(&cmd_ctx->packet.payload[0]); + hi_u32 file_len = *(hi_u32 *)(&cmd_ctx->packet.payload[4]); /* offset 4 is file length */ + hi_u32 erase_size = *(hi_u32 *)(&cmd_ctx->packet.payload[8]); /* offset 8 is erase size */ + hi_u8 burn_efuse = cmd_ctx->packet.payload[12]; /* offset 12 is burn efuse flag */ + hi_u32 ret = spi_flash_read_chip_id(chip_id, HI_FLASH_CHIP_ID_NUM); + if (ret == HI_ERR_SUCCESS) { + flash_size = spi_flash_get_size((const hi_u8 *)chip_id); + } else { + boot_msg0("Get flash size fail"); + return HI_ERR_FAILURE; + } + + if (file_len == 0 || erase_size == 0 || erase_size < file_len || (download_addr + file_len) > flash_size) { + boot_msg0("Invalid params"); + serial_puts("download_addr "); + serial_puthex(download_addr, 1); + serial_puts(" file_len "); + serial_puthex(file_len, 1); + serial_puts(" erase_size "); + serial_puthex(erase_size, 1); + serial_puts("\r\n"); + return HI_ERR_FAILURE; + } + +#ifdef CONFIG_FLASH_ENCRYPT_SUPPORT + hi_u64 efuse_lock_status = 0; + ret = hi_efuse_get_lockstat(&efuse_lock_status); + if (ret != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + if ((efuse_lock_status & 0x10) == 0) { + boot_msg0("Enable flash encryption: "); + boot_msg0("Please write and lock efuse root key field first!"); + return HI_ERR_FAILURE; + } +#endif + + if (cmd_ctx->packet.head.type == CMD_FACTORY_IMAGE) { + return download_factory_image(download_addr, erase_size, flash_size, burn_efuse); + } + + return download_image(download_addr, erase_size, flash_size, burn_efuse); +} + + +hi_bool tool_bit_test(const hi_u8 *data, hi_u16 pos, hi_u16 data_len) +{ + hi_u16 base = pos / BIT_U8; + hi_u16 i = pos % BIT_U8; + if (pos > (data_len * BIT_U8)) { + return HI_FALSE; + } + return (hi_bool)bit_get(data[base], i); +} + +hi_void tool_bit_set(hi_u8 *data, hi_u16 pos, hi_u8 val) +{ + hi_u16 base = pos / BIT_U8; + hi_u16 i = pos % BIT_U8; + bit_set(data[base], i, val); +} + +hi_u32 get_secure_boot_flag(hi_bool *secure_flag) +{ + hi_u8 data = 0; + hi_u32 ret = hi_efuse_read(HI_EFUSE_SEC_BOOT_RW_ID, (hi_u8 *)(&data), (hi_u8)(sizeof(hi_u8))); + if (ret != HI_ERR_SUCCESS) { + boot_msg1("secure boot efuse read err:", ret); + return ret; + } + + if (data == SEC_BOOT_FLAG) { + *secure_flag = HI_FALSE; + } else { + *secure_flag = HI_TRUE; + } + + return HI_ERR_SUCCESS; +} + + +hi_u32 get_efuse_boot_ver(hi_u8 *ver) +{ + hi_u8 pos; + hi_u8 efuse_data[BOOT_VER_LEN] = { 0 }; + hi_u32 ret = hi_efuse_read(HI_EFUSE_TEE_BOOT_VER_RW_ID, efuse_data, sizeof(efuse_data)); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + for (pos = 0; pos < BOOT_VER_MAX; pos++) { + if (tool_bit_test(efuse_data, pos, BOOT_VER_LEN) == HI_FALSE) { + break; + } + } + if (pos >= BOOT_VER_MAX) { + *ver = BOOT_VER_MAX; + } else { + *ver = pos; + } + return ret; +} + +hi_u32 get_efuse_code_ver(hi_u8 *ver) +{ + hi_u8 pos; + hi_u8 efuse_data[KERNEL_VER_LEN]; + hi_u32 ret; + + hi_u32 cs = (uintptr_t)efuse_data ^ KERNEL_VER_LEN ^ 0 ^ KERNEL_VER_LEN; + (hi_void) memset_s(efuse_data, KERNEL_VER_LEN, 0, KERNEL_VER_LEN, cs); + ret = hi_efuse_read(HI_EFUSE_TEE_KERNEL_VER_RW_ID, efuse_data, sizeof(efuse_data)); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + for (pos = 0; pos < KERELN_VER_MAX; pos++) { + if (tool_bit_test(efuse_data, pos, KERNEL_VER_LEN) == HI_FALSE) { + break; + } + } + if (pos >= KERELN_VER_MAX) { + *ver = KERELN_VER_MAX; + } else { + *ver = pos; + } + return ret; +} + +hi_u32 start_and_wait_update_ver() +{ + /* init upg flag */ + g_upg_update_ver_success = HI_FALSE; + + /* trigger upg nmi */ + hi_reg_setbit(NMI_BASE_ADDRESS + NMI_CTRL, NMI_INT_MOD_DONE_EN_POS); + + /* wait nmi handle finish */ + hi_u32 try_cnt; + for (try_cnt = 0; try_cnt < WAIT_VER_UPDATE_TRY_CNT; try_cnt++) { + if (g_update_ver_status == UPDATE_VER_STATUS_NONE) { + break; + } + udelay(WAIT_VER_UPDATE_TRY_INTER_US); /* sleep 10ms */ + } + + if (g_upg_update_ver_success == HI_TRUE) { + return HI_ERR_SUCCESS; + } else if (try_cnt == WAIT_VER_UPDATE_TRY_CNT) { + return HI_ERR_UPG_UPDATE_VER_TIMEOUT; + } else { + return HI_ERR_UPG_UPDATE_VER_FAIL; + } +} + +hi_u32 check_boot_kernel_ver(hi_u8 boot_ver, hi_u8 kernel_ver, hi_u8 *current_boot_ver, hi_u8 *current_kernel_ver) +{ + hi_u32 ret; + + ret = get_efuse_boot_ver(current_boot_ver); + if (ret != HI_ERR_SUCCESS) { + boot_msg1("get boot ver ret:", ret); + return ret; + } + + ret = get_efuse_code_ver(current_kernel_ver); + if (ret != HI_ERR_SUCCESS) { + boot_msg1("get kernel ver ret:", ret); + return ret; + } + + if (boot_ver < *current_boot_ver) { + boot_msg2("current boot ver >boot ver:", *current_boot_ver, boot_ver); + return HI_ERR_UPG_LOW_KERNEL_VER; + } + + if (kernel_ver < *current_kernel_ver) { + boot_msg2("current kernel ver > kernel ver:", *current_kernel_ver, kernel_ver); + return HI_ERR_UPG_LOW_KERNEL_VER; + } + + if (boot_ver > BOOT_VER_MAX || kernel_ver > KERELN_VER_MAX) { + boot_msg2("invalid boot ver, kernel ver:", boot_ver, kernel_ver); + return HI_ERR_UPG_FULL_KERNEL_VER; + } + + return HI_ERR_SUCCESS; +} + +hi_u32 set_efuse_boot_kernel_ver(hi_u8 boot_ver, hi_u8 kernel_ver) +{ + hi_u32 ret; + hi_u8 pos; + hi_u8 current_boot_ver = 0; + hi_u8 current_kernel_ver = 0; + hi_bool flag = HI_FALSE; + + ret = get_secure_boot_flag(&flag); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + if (flag == HI_FALSE) { + boot_msg0("not secure boot."); + return HI_ERR_SUCCESS; + } + + ret = check_boot_kernel_ver(boot_ver, kernel_ver, ¤t_boot_ver, ¤t_kernel_ver); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + hi_bool update_boot_ver = HI_FALSE; + hi_bool update_kernel_ver = HI_FALSE; + if (boot_ver != current_boot_ver) { + hi_u32 cs = (uintptr_t)g_upg_efuse_data_boot_ver ^ BOOT_VER_LEN ^ 0 ^ BOOT_VER_LEN; + (hi_void) memset_s(g_upg_efuse_data_boot_ver, BOOT_VER_LEN, 0, BOOT_VER_LEN, cs); + for (pos = current_boot_ver; pos < boot_ver; pos++) { + tool_bit_set(g_upg_efuse_data_boot_ver, pos, SRV_BIT_HIGH); + } + update_boot_ver = HI_TRUE; + } + + if (kernel_ver != current_kernel_ver) { + hi_u32 cs = (uintptr_t)g_upg_efuse_data_kernel_ver ^ KERNEL_VER_LEN ^ 0 ^ KERNEL_VER_LEN; + (hi_void) memset_s(g_upg_efuse_data_kernel_ver, KERNEL_VER_LEN, 0, KERNEL_VER_LEN, cs); + for (pos = current_kernel_ver; pos < kernel_ver; pos++) { + tool_bit_set(g_upg_efuse_data_kernel_ver, pos, SRV_BIT_HIGH); + } + update_kernel_ver = HI_TRUE; + } + + if (update_boot_ver == HI_FALSE && update_kernel_ver == HI_FALSE) { + boot_msg0("same ver with efuse"); + return HI_ERR_SUCCESS; + } else if (update_boot_ver == HI_TRUE && update_kernel_ver == HI_TRUE) { + g_update_ver_status = UPDATE_VER_STATUS_BOOT_KERNEL; + } else if (update_boot_ver == HI_TRUE) { + g_update_ver_status = UPDATE_VER_STATUS_BOOT; + } else { + g_update_ver_status = UPDATE_VER_STATUS_KERNEL; + } + + ret = start_and_wait_update_ver(); + + return ret; +} + +hi_void nmi_update_ver(hi_void) +{ + if (g_update_ver_status == UPDATE_VER_STATUS_NONE) { + return; + } + + hi_u32 ret; + + if (g_update_ver_status == UPDATE_VER_STATUS_BOOT || g_update_ver_status == UPDATE_VER_STATUS_BOOT_KERNEL) { + ret = hi_efuse_write(HI_EFUSE_TEE_BOOT_VER_RW_ID, g_upg_efuse_data_boot_ver); + if (ret != HI_ERR_SUCCESS) { + boot_msg1("update boot ver fail, ret:", ret); + g_upg_update_ver_success = HI_FALSE; + g_update_ver_status = UPDATE_VER_STATUS_NONE; + return; + } + } + + if (g_update_ver_status == UPDATE_VER_STATUS_KERNEL || g_update_ver_status == UPDATE_VER_STATUS_BOOT_KERNEL) { + ret = hi_efuse_write(HI_EFUSE_TEE_KERNEL_VER_RW_ID, g_upg_efuse_data_kernel_ver); + if (ret != HI_ERR_SUCCESS) { + boot_msg1("update kernel ver fail, ret:", ret); + g_upg_update_ver_success = HI_FALSE; + g_update_ver_status = UPDATE_VER_STATUS_NONE; + return; + } + } + + g_upg_update_ver_success = HI_TRUE; + g_update_ver_status = UPDATE_VER_STATUS_NONE; + + return; +} + +hi_u32 loader_burn_version(const uart_ctx *cmd_ctx) +{ + hi_u32 ret; + hi_u32 file_len = *(hi_u32 *)(&cmd_ctx->packet.payload[0]); + if (file_len != VER_CFG_BIN_LEN) { + boot_msg1("Ver length error : ", file_len); + return HI_ERR_FAILURE; + } + hi_u8 *buf = boot_malloc(file_len); + if (buf == HI_NULL) { + boot_msg0("Malloc buffer error"); + return HI_ERR_FAILURE; + } + + ret = loady_version_file((uintptr_t)buf); + if (ret != HI_ERR_SUCCESS) { + boot_msg1("Loady ver file failed:", ret); + return ret; + } + + hi_u32 boot_ver = *(hi_u32 *)buf; + hi_u32 kernel_ver = *(hi_u32 *)(buf + 4); /* 4: 4 byte as a word(little ending). */ + + boot_msg1("boot ver:", boot_ver); + boot_msg1("kernel_ver:", kernel_ver); + + ret = set_efuse_boot_kernel_ver(boot_ver, kernel_ver); + + return ret; +} + +void boot_nmi_handler(void) +{ + hi_u32 *sp_val = 0; + + /* clear NMI interrupt */ + hi_reg_write(NMI_BASE_ADDRESS + NMI_CTRL, 0x0); + __asm__ __volatile__("fence":::"memory"); + + nmi_update_ver(); + + /* NOTICE: Start Clear NMI Stack, All User nmi service MUST BE DONE at this moment!!! */ + __asm__ volatile ("mv %0, sp" : "=r"(sp_val)); + while (sp_val != (hi_u32 *)(&__nmi_stack_bottom)) { + *sp_val = 0; + sp_val--; + } +} + +hi_u32 loader_burn_efuse(const uart_ctx *cmd_ctx) +{ + hi_u32 ret; + hi_u32 file_len = *(hi_u32 *)(&cmd_ctx->packet.payload[0]); + if (file_len <= EFUSE_CFG_MIN_LEN || file_len > EFUSE_CFG_MAX_LEN) { + boot_msg1("File length error : ", file_len); + return HI_ERR_FAILURE; + } + + hi_u8 *buf = boot_malloc(file_len); + if (buf == HI_NULL) { + boot_msg0("Malloc buffer error"); + return HI_ERR_FAILURE; + } + + ret = loady_file((uintptr_t)buf); + if (ret != HI_ERR_SUCCESS) { + boot_msg1("Loady efuse file failed:", ret); + return ret; + } + + ret = efuse_burn((uintptr_t)buf, file_len); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + /* 复位efuse模块,使得efuse立即生效,应用于在烧写过程中依赖huks根秘钥的场景 */ + /* reset efuse for validate immediately */ + hi_reg_clrbit16(CLDO_CTL_SOFT_RESET2_REG, EFUSE_RST_BIT); + udelay(0x3); + hi_reg_setbit16(CLDO_CTL_SOFT_RESET2_REG, EFUSE_RST_BIT); + + return HI_ERR_SUCCESS; +} + +hi_u32 loader_read_efuse(const uart_ctx *cmd_ctx) +{ + hi_u32 ret; + hi_u16 start_bit = *(hi_u16 *)(&cmd_ctx->packet.payload[0]); + hi_u16 size = *(hi_u16 *)(&cmd_ctx->packet.payload[2]); /* offset 2 is read size */ + boot_msg0("Efuse read"); + serial_puts("Start bit: "); + serial_puthex(start_bit, 1); + serial_puts(" len(bits)="); + serial_puthex(size, 1); + serial_puts("\r\n"); + if ((start_bit >= EFUSE_BIT_NUM) || ((start_bit + size) > EFUSE_BIT_NUM) || size > EFUSE_READ_MAX_BITS) { + boot_msg0("Params err"); + return HI_ERR_FAILURE; + } + + ret = efuse_read(start_bit, size); + if (ret != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + + return HI_ERR_SUCCESS; +} + +hi_u32 loader_upload_data(const uart_ctx *cmd_ctx) +{ + hi_u8 chip_id[HI_FLASH_CHIP_ID_NUM] = {0}; + hi_u32 flash_size = 0; + hi_u32 file_len = *(hi_u32 *)(&cmd_ctx->packet.payload[0]); + hi_u32 upload_addr = *(hi_u32 *)(&cmd_ctx->packet.payload[4]); /* offset 4 is read addr */ + boot_msg2("Upload addr, length :", upload_addr, file_len); + + hi_u32 ret = spi_flash_read_chip_id(chip_id, HI_FLASH_CHIP_ID_NUM); + if (ret == HI_ERR_SUCCESS) { + flash_size = spi_flash_get_size((const hi_u8 *)chip_id); + } else { + boot_msg0("Get flash size fail"); + return HI_ERR_FAILURE; + } + + if (file_len == 0 || file_len > flash_size) { + boot_msg0("Upload length error"); + return HI_ERR_FAILURE; + } + + if ((upload_addr & 0x3) != 0) { + boot_msg0("Upload addr error"); + return HI_ERR_FAILURE; + } + + if ((upload_addr + file_len) > flash_size) { + boot_msg0("Upload addr exceeds flash capacity"); + return HI_ERR_FAILURE; + } + + return upload_data(upload_addr, file_len); +} + +hi_u32 loader_frame_head_rx(uart_ctx *ctx) +{ + hi_u8 ch; + hi_bool reset_flag = HI_FALSE; + hi_u16 rcv = 0; + + packet_data_head *head = &ctx->packet.head; + hi_u8 *payload = (hi_u8 *)head; + + while (rcv <= CMD_ABNORMAL_MAX) { + hi_u32 ret = serial_getc_timeout(CMD_FRAME_TIMEOUT * US_PER_MS, &ch); + if (ret != HI_ERR_SUCCESS) { + continue; + } + + rcv++; + if (reset_flag == HI_TRUE) { + reset_flag = HI_FALSE; + head->start_flag = 0; + ctx->status = CMD_RX_STATUS_WAIT_START_0; + } + if (ctx->status <= CMD_RX_STATUS_WAIT_START_3) { + hi_u32 start_flag = UART_PACKET_START_FLAG; + hi_u8 *start_byte = (hi_u8 *)&start_flag; + if (ch == start_byte[ctx->status]) { + payload[ctx->status] = ch; + ctx->status++; + continue; + } else if (ch == 0xEF) { + payload[CMD_RX_STATUS_WAIT_START_0] = ch; + ctx->status = CMD_RX_STATUS_WAIT_START_1; + continue; + } + reset_flag = HI_TRUE; + continue; + } else { + payload[ctx->status] = ch; + if (ctx->status >= CMD_RX_STATUS_WAIT_START_1 && (head->packet_size > UART_PACKET_PAYLOAD_MAX)) { + reset_flag = HI_TRUE; + continue; + } + ctx->status++; + if (ctx->status >= CMD_RX_STATUS_WAIT_DATA) { + return HI_ERR_SUCCESS; + } + } + } + return HI_ERR_FAILURE; +} + +hi_u32 loader_frame_data_rx(uart_ctx *ctx) +{ + hi_u8 ch; + hi_u32 ret; + ctx->received = 0; + + packet_data_head *head = &ctx->packet.head; + hi_u8 *payload = ctx->packet.payload; + + while (ctx->received < (head->packet_size - sizeof(packet_data_head))) { + ret = serial_getc_timeout(CMD_RX_DELAY_MS * US_PER_MS, &ch); + if (ret == HI_ERR_SUCCESS) { + payload[ctx->received++] = ch; + continue; + } + return HI_ERR_FAILURE; + } + ctx->packet.check_sum = (payload[head->packet_size - 9] << 8) | payload[head->packet_size - 10]; /* 8,9,10: sub */ + payload[head->packet_size - 9] = 0; /* 9: sub 9 */ + payload[head->packet_size - 10] = 0; /* 10: sub 10 */ + + if (ctx->received == (head->packet_size - sizeof(packet_data_head))) { + return HI_ERR_SUCCESS; + } + + return HI_ERR_FAILURE; +} + +hi_void loader_ack(hi_u8 err_code) +{ + uart_ctx *ctx = g_cmd_ctx; + packet_data_head *head = &ctx->packet.head; + + head->start_flag = UART_PACKET_START_FLAG; + head->type = CMD_ACK; + head->pad = (hi_u8)(~(CMD_ACK)); + head->packet_size = ACK_LEN; + ctx->packet.payload[0] = err_code; + ctx->packet.payload[1] = ~err_code; + hi_u32 cs = 0 ^ (uintptr_t)(hi_u8 *)&(ctx->packet) ^ (head->packet_size - CHECKSUM_SIZE); + ctx->packet.check_sum = crc16_ccitt(0, (hi_u8 *)&(ctx->packet), head->packet_size - CHECKSUM_SIZE, cs); + + serial_put_buf ((const char *)&(ctx->packet), (int)(head->packet_size - CHECKSUM_SIZE)); + serial_put_buf ((const char *)&(ctx->packet.check_sum), CHECKSUM_SIZE); +} + +hi_u32 loader_read_frame(uart_ctx *ctx) +{ + packet_data_info *packet = &ctx->packet; + packet_data_head *head = &packet->head; + hi_u32 ret; + hi_u32 cs; + + /* Reset receiving status.CNcomment:复位接收状态 */ + ctx->status = CMD_RX_STATUS_WAIT_START_0; + ctx->received = 0; + cs = (uintptr_t)packet ^ (hi_u32)sizeof(packet_data_info) ^ 0 ^ (hi_u32)sizeof(packet_data_info); + if (memset_s(packet, sizeof(packet_data_info), 0, sizeof(packet_data_info), cs) != EOK) { + return HI_ERR_FAILURE; + } + + ret = loader_frame_head_rx(ctx); + if (ret != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + + ret = loader_frame_data_rx(ctx); + if (ret != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + + cs = 0 ^ (uintptr_t)(hi_u8 *)packet ^ (head->packet_size - CHECKSUM_SIZE); + cs = crc16_ccitt(0, (hi_u8 *)packet, head->packet_size - CHECKSUM_SIZE, cs); + if (cs == packet->check_sum) { + return HI_ERR_SUCCESS; + } + + return HI_ERR_FAILURE; +} + +hi_u32 loader_exe_cmd(uart_ctx *ctx) +{ + hi_u32 i; + + packet_data_info *packet = &ctx->packet; + packet_data_head *head = &packet->head; + for (i = 0; i < LOADER_CMD_MAX; i++) { + if (head->type == g_loader_cmdtable[i].cmd_type) { + if (g_loader_cmdtable[i].cmdfunc != HI_NULL) { + return g_loader_cmdtable[i].cmdfunc(ctx); + } + } + } + + if (i == LOADER_CMD_MAX) { + boot_msg1("Unsupport CMD:", head->type); + } + + return HI_ERR_FAILURE; +} + +uart_ctx *cmd_loop_init(hi_void) +{ + if (g_cmd_ctx == HI_NULL) { + g_cmd_ctx = (uart_ctx *)boot_malloc(sizeof(uart_ctx)); + } + + if (g_cmd_ctx != HI_NULL) { + volatile hi_u32 check_sum = (uintptr_t)g_cmd_ctx ^ (hi_u32)sizeof(uart_ctx) ^ 0 ^ (hi_u32)sizeof(uart_ctx); + (hi_void) memset_s(g_cmd_ctx, sizeof(uart_ctx), 0, sizeof(uart_ctx), check_sum); + return g_cmd_ctx; + } + return HI_NULL; +} + +hi_u32 cmd_loop_deinit(hi_void) +{ + hi_u32 ret = boot_free(g_cmd_ctx); + if (ret == HI_ERR_SUCCESS) { + g_cmd_ctx = HI_NULL; + } + + return ret; +} + +hi_void cmd_loop(uart_ctx *ctx) +{ + hi_u32 ret; + for (;;) { + ret = loader_read_frame(ctx); + if (ret != HI_ERR_SUCCESS) { + boot_msg0("\nGet CMD fail"); + loader_ack(ACK_FAILURE); + continue; + } + + ret = loader_exe_cmd(ctx); + if (ret != HI_ERR_SUCCESS) { + loader_ack(ACK_FAILURE); + boot_msg0("\nExecution Failure : "); + boot_msg0("============================================\n"); + continue; + } + + loader_ack(ACK_SUCCESS); + boot_msg0("\nExecution Successful"); + boot_msg0("============================================\n"); + } +} + diff --git a/sdk_liteos/boot/loaderboot/common/efuse_opt.c b/sdk_liteos/boot/loaderboot/common/efuse_opt.c new file mode 100644 index 0000000000000000000000000000000000000000..c446be905ddf6146c1fca4bc4ea5bb874025052e --- /dev/null +++ b/sdk_liteos/boot/loaderboot/common/efuse_opt.c @@ -0,0 +1,132 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include + +hi_u32 efuse_read(hi_u16 start_bit, hi_u16 size) +{ + hi_u8 count; + hi_u32 print_val; + hi_u8 line_cnt = U32_PER_LINE; + hi_u8 data[EFUSE_MAX_INDEX_SIZE] = { 0 }; + hi_void *tmp_data = HI_NULL; + hi_u32 ret = efuse_bits_read(start_bit, size, data, EFUSE_MAX_INDEX_SIZE); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + if (size < SIZE_32_BITS) { + *(volatile hi_u32 *)data &= ((1 << size) - 1); + size = SIZE_32_BITS; + } else if (size > SIZE_32_BITS && size < SIZE_64_BITS) { + *(volatile hi_u32 *)(data + WORD_WIDTH) &= ((1 << (size - SIZE_32_BITS)) - 1); + size = SIZE_64_BITS; + } + + count = size >> SHIFT_5_BITS; + if (count < U32_PER_LINE) { + line_cnt = count; + } + + tmp_data = (hi_void *)data; + while (count) { + boot_puthex(start_bit, 1); + serial_putc(':'); + if (count < line_cnt) { + line_cnt = count; + } + /* Copy from memory into linebuf and print hex values */ + for (hi_u8 i = 0; i < line_cnt; i++) { + print_val = *(volatile unsigned int *)tmp_data; + boot_puthex(print_val, 1); + tmp_data = (unsigned char *)tmp_data + WORD_WIDTH; + } + serial_putc('\n'); + + /* update references */ + start_bit += line_cnt * WORD_WIDTH * BITS_PER_BYTE; + count -= line_cnt; + } + return HI_ERR_SUCCESS; +} + +hi_u32 efuse_cfg_verify(uintptr_t file_addr, hi_u32 file_len) +{ + hi_u32 ret; + hi_u8 hash[SHA_256_LENGTH] = {0}; + efuse_config_header *header = (efuse_config_header *)file_addr; + + if (header->file_size != file_len) { + return HI_ERR_FAILURE; + } + + ret = hi_cipher_init(); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + ret = hi_cipher_hash_sha256((uintptr_t)&(header->stru_ver), header->file_size - SHA_256_LENGTH, hash, + SHA_256_LENGTH); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + ret = hi_cipher_deinit(); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + if (memcmp(header->hash, hash, SHA_256_LENGTH) != EOK) { + return HI_ERR_FAILURE; + } + + if (header->number > (HI_EFUSE_IDX_MAX + HI_EFUSE_LOCK_MAX)) { + return HI_ERR_FAILURE; + } + + return HI_ERR_SUCCESS; +} + +hi_u32 efuse_burn(uintptr_t file_addr, hi_u32 file_len) +{ + hi_u32 ret = efuse_cfg_verify(file_addr, file_len); + if (ret != HI_ERR_SUCCESS) { + boot_msg0("Efuse config file invalid"); + return HI_ERR_FAILURE; + } + + efuse_config_header *header = (efuse_config_header *)file_addr; + efuse_config_item *item = (efuse_config_item *)(file_addr + header->stru_size); + for (hi_u8 i = 0; i < header->number; i++) { + if (item == HI_NULL) { + return HI_ERR_FAILURE; + } + ret = efuse_bits_write(item->start_bit, item->bit_width, item->value); + if (ret != HI_ERR_SUCCESS) { + boot_msg1("efuse write error, index:", i); + serial_puts("Start bit: "); + serial_puthex(item->start_bit, 1); + serial_puts(" len(bits)="); + serial_puthex(item->bit_width, 1); + serial_puts("\n"); + } + + item = (efuse_config_item *)((uintptr_t)item + item->stru_size + item->value_len); + } + return HI_ERR_SUCCESS; +} + diff --git a/sdk_liteos/boot/loaderboot/common/nvm/SConscript b/sdk_liteos/boot/loaderboot/common/nvm/SConscript new file mode 100755 index 0000000000000000000000000000000000000000..aceb2b6a9464ce64030c1f9c5374ec933dcab384 --- /dev/null +++ b/sdk_liteos/boot/loaderboot/common/nvm/SConscript @@ -0,0 +1,6 @@ +Import('env') + +env = env.Clone() + +objs = env.Object(Glob('*.c')) +Return('objs') diff --git a/sdk_liteos/boot/loaderboot/common/nvm/hi_nvm.c b/sdk_liteos/boot/loaderboot/common/nvm/hi_nvm.c new file mode 100644 index 0000000000000000000000000000000000000000..2d088fa14fe197c7a1b65dde8a945a59ddce4102 --- /dev/null +++ b/sdk_liteos/boot/loaderboot/common/nvm/hi_nvm.c @@ -0,0 +1,438 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "hi_nvm.h" + +#include +#include + +typedef hi_u32(*hi_nvm_changed_notify_f) (hi_u8 id); + +typedef struct { + hi_u8 min_id; + hi_u8 max_id; + hi_u16 count; +} nvm_changed_proc_stru; +typedef struct { + hi_u32 base_addr; + hi_u32 total_size; + hi_u32 block_size; +} nvm_basic_info; + +HI_CONST hi_u32 g_ver_magic = 0x12345678; + +static hi_nv_ctrl g_s_nv_ctrl[HI_TYPE_NV_MAX]; +hi_u16 g_s_nv_change_notify_list_cnt = 0; + +hi_u32 hi_crc32_nv(hi_u32 crc_start, HI_CONST hi_u8* buf, hi_u32 len, hi_u32 *crc_result) +{ + if (!buf || !len || !crc_result) { + return HI_ERR_CRC_INVALID_PARAMETER; + } + *crc_result = hi_crc32(crc_start, buf, len); + return HI_ERR_SUCCESS; +} + +hi_u32 nv_read_flash(hi_u32 addr, hi_u32 size, hi_u8* data) +{ + hi_u32 ret; + + for (hi_u32 i = 0; i < HNV_FAULT_TOLERANT_TIMES; i++) { + ret = hi_flash_read(addr, size, data); + if (ret == HI_ERR_SUCCESS) { + return HI_ERR_SUCCESS; + } + } + + return HI_ERR_NV_FAIL_N_TIMES; +} + +hi_u32 nv_write_flash(hi_u32 addr, hi_u32 size, const hi_u8* data) +{ + hi_u32 ret; + + for (hi_u32 i = 0; i < HNV_FAULT_TOLERANT_TIMES; i++) { + ret = hi_flash_write(addr, size, data, HI_TRUE); + if (ret == HI_ERR_SUCCESS) { + return HI_ERR_SUCCESS; + } + } + + return HI_ERR_NV_FAIL_N_TIMES; +} + +/* Check the validity of the NV file. */ +hi_u32 nv_check_file(hi_u8* pdata, hi_u32 len, hi_nv_type nv_type) +{ + hi_nv_manage* nv_head; + hi_u32 magic = HNV_FILE_SIGNATURE; + hi_u32 crc_val = 0; + + nv_head = (hi_nv_manage*)pdata; + if (nv_type == HI_TYPE_FACTORY_NV) { + magic = FNV_FILE_SIGNATURE; + } + if (magic != nv_head->magic) { + return HI_ERR_NV_INVALID_TYPE; + } + if (nv_head->total_num >= NV_TOTAL_MAX_NUM) { + return HI_ERR_NV_FULL; + } + hi_crc32_nv(0, pdata + HNV_NCRC_SIZE, len - HNV_NCRC_SIZE, &crc_val); + + if (nv_head->crc != crc_val) { + return HI_ERR_NV_BAD_DATA; + } + return HI_ERR_SUCCESS; +} + +/* Returns the corresponding NV index. */ +hi_nv_item_index* nv_find_item(hi_u8* data, hi_u8 id, hi_nv_type nv_type) +{ + hi_nv_item_index* index = HI_NULL; + hi_u16 total_num; + + if (data == HI_NULL) { + total_num = g_s_nv_ctrl[nv_type].total_num; + index = g_s_nv_ctrl[nv_type].index; + } else { + hi_nv_manage* nv_head = (hi_nv_manage*)data; + total_num = nv_head->total_num; + index = (hi_nv_item_index*)&nv_head->nv_item_data[0]; + } + + for (hi_u32 i = 0; i < total_num; i++) { + if (id == index[i].nv_id) { + return &index[i]; + } + } + return (hi_nv_item_index*)HI_NULL; +} +hi_u32 nv_init_start(hi_u32 block_size, hi_u8** data, hi_u8** back, hi_nv_ctrl** nv_ctrl, hi_nv_type nv_type) +{ + if (nv_type >= HI_TYPE_NV_MAX) { + return HI_ERR_NV_INVALID_PARAMETER; + } + *nv_ctrl = &g_s_nv_ctrl[nv_type]; + *data = (hi_u8 *)rom_boot_malloc(block_size); + if (*data == HI_NULL) { + return HI_ERR_MALLOC_FAILUE; + } + *back = (hi_u8 *)rom_boot_malloc(block_size); + if (*back == HI_NULL) { + rom_boot_free(*data); + return HI_ERR_MALLOC_FAILUE; + } + return HI_ERR_SUCCESS; +} + +hi_u32 nv_init_index(hi_nv_ctrl* nv_ctrl, const nvm_basic_info* nv_info, hi_u8* p_index, const hi_u8** data, + const hi_u8** back) +{ + hi_u32 ret, cs; + hi_u32 index_size = sizeof(hi_nv_item_index) * nv_ctrl->total_num; + hi_u16 block_count = (hi_u16)nv_info->total_size / (hi_u16)nv_info->block_size; + nv_ctrl->index = (hi_nv_item_index*)rom_boot_malloc(index_size); + if (nv_ctrl->index == HI_NULL) { + ret = HI_ERR_MALLOC_FAILUE; + rom_boot_free((hi_void *)*back); + rom_boot_free((hi_void *)*data); + return ret; + } + cs = (uintptr_t)(nv_ctrl->index) ^ index_size ^ (uintptr_t)p_index ^ index_size; + ret = (hi_u32)memcpy_s(nv_ctrl->index, index_size, p_index, index_size, cs); + if (ret != HI_ERR_SUCCESS) { + ret = HI_ERR_NV_FILE_ERR; + rom_boot_free(p_index); + rom_boot_free((hi_void *)*back); + rom_boot_free((hi_void *)*data); + return ret; + } + nv_ctrl->base_addr = nv_info->base_addr; + nv_ctrl->block_size = nv_info->block_size; + nv_ctrl->total_block_size = nv_info->block_size * block_count; + nv_ctrl->init_flag = HI_TRUE; + + rom_boot_free((hi_void *)*back); + rom_boot_free((hi_void *)*data); + return HI_ERR_SUCCESS; +} + +hi_u32 nv_init_common(hi_u32 base_addr, hi_u32 total_size, hi_u32 block_size, hi_nv_type nv_type) +{ + hi_nv_ctrl* nv_ctrl = HI_NULL; + nvm_basic_info nv_info; + hi_u8* data = HI_NULL; + hi_u8* back = HI_NULL; + hi_u32 seq_max = 0; + hi_u8* p_index = HI_NULL; + if (block_size == (hi_u32)0) { + return HI_ERR_FAILURE; + } + hi_bool flag_read_success = HI_FALSE; + + hi_u32 ret = nv_init_start(block_size, &data, &back, &nv_ctrl, nv_type); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + for (hi_u16 i = 0; i < (hi_u16)total_size / (hi_u16)block_size; i++) { + hi_u32 flash_addr = base_addr + i * block_size; + if (nv_read_flash(flash_addr, block_size, data) != HI_ERR_SUCCESS) { + /* Continue to process read errors. */ + continue; + } + if (nv_check_file(data, block_size, nv_type) != HI_ERR_SUCCESS) { /* Check the validity of the NV file. */ + continue; + } + hi_nv_manage* nv_head = (hi_nv_manage*)data; + if (nv_head->seq >= seq_max) { + seq_max = nv_head->seq; + nv_ctrl->seq = nv_head->seq; + nv_ctrl->current_addr = flash_addr; + nv_ctrl->total_num = nv_head->total_num; + nv_ctrl->ver_magic = nv_head->ver_magic; + hi_u32 cs = (uintptr_t)back ^ block_size ^ (uintptr_t)data ^ block_size; + if (memcpy_s(back, block_size, data, block_size, cs) != EOK) { + continue; + } + p_index = &(((hi_nv_manage*)back)->nv_item_data[0]); + flag_read_success = HI_TRUE; + } + } + if (flag_read_success != HI_TRUE) { + rom_boot_free(data); + rom_boot_free(back); + return HI_ERR_NV_INITILIZATION; + } + nv_info.base_addr = base_addr; + nv_info.block_size = block_size; + nv_info.total_size = total_size; + /* Applying for Index Space CNcomment:索引空间申请 */ + ret = nv_init_index(nv_ctrl, (const nvm_basic_info*)&nv_info, p_index, (const hi_u8**)&data, (const hi_u8**)&back); + return ret; +} + +hi_u8 nv_get_item_len(hi_u32 id, hi_nv_type nv_type) +{ + hi_nv_item_index* nv_index; + + nv_index = nv_find_item(HI_NULL, (hi_u8)id, nv_type); + if (nv_index == HI_NULL) { + return 0; + } + return nv_index->nv_len; +} +hi_u32 nv_read_common(hi_u8 id, hi_pvoid pdata, hi_u8 len, hi_nv_type nv_type) +{ + hi_u32 ret; + hi_nv_ctrl* nv_ctrl = HI_NULL; + hi_nv_item_index* nv_index = HI_NULL; + hi_u32 crc = 0; + hi_u32 flash_addr; + hi_u8 item_len; + hi_bool to_check_crc; + hi_u32 crc_val = 0; + + if (nv_type >= HI_TYPE_NV_MAX) { + return HI_ERR_NV_INVALID_PARAMETER; + } + nv_ctrl = &g_s_nv_ctrl[nv_type]; + nv_index = nv_find_item(HI_NULL, id, nv_type); + if (nv_index == HI_NULL) { + return HI_ERR_NV_ERROR_READ; + } + if (nv_index->nv_len == len) { + item_len = len; + to_check_crc = HI_TRUE; + } else { + item_len = hi_min(nv_index->nv_len, len); + to_check_crc = HI_FALSE; + } + + flash_addr = nv_ctrl->current_addr + nv_index->nv_offset; + ret = nv_read_flash(flash_addr, item_len, pdata); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + if (to_check_crc == HI_TRUE) { + ret = nv_read_flash(flash_addr + item_len, sizeof(crc), (hi_u8*)&crc); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + hi_crc32_nv(0, pdata, item_len, &crc_val); + if (crc != crc_val) { + return HI_ERR_NV_BAD_DATA; + } + } else { + ret = HI_ERR_NV_LEN_ERR; + } + + return ret; +} + + +hi_u32 nv_next_addr(HI_CONST hi_nv_ctrl *nv_ctrl) +{ + hi_u32 new_addr = ((nv_ctrl->current_addr + nv_ctrl->block_size) < (nv_ctrl->base_addr + nv_ctrl->total_block_size)) + ? (nv_ctrl->current_addr + nv_ctrl->block_size) : (nv_ctrl->base_addr); + + return new_addr; +} + +hi_u32 nv_block_write(hi_u8* p_nv_file, hi_nv_type nv_type) +{ + hi_u32 ret; + hi_nv_ctrl* nv_ctrl = &g_s_nv_ctrl[nv_type]; + hi_nv_manage* nv_head = (hi_nv_manage*)p_nv_file; + hi_u32 flash_addr = nv_next_addr((HI_CONST hi_nv_ctrl *)nv_ctrl); + + nv_head->ver_magic = g_ver_magic; + nv_head->seq = nv_ctrl->seq + 1; + + hi_crc32_nv(0, p_nv_file + 8, nv_ctrl->block_size - 8, &(nv_head->crc)); // 8 + ret = nv_write_flash(flash_addr, nv_ctrl->block_size, p_nv_file); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + nv_ctrl->seq = nv_head->seq; + nv_ctrl->current_addr = flash_addr; + + return ret; +} +hi_u32 nv_common_write(hi_u8 id, hi_nv_type nv_type, hi_u8 len, const hi_pvoid data) +{ + hi_u8 backup_num = 1; + hi_u8 item_len = len; + hi_u32 ret, crc, cs; + hi_nv_ctrl* nv_ctrl = &g_s_nv_ctrl[nv_type]; + + /* Normal write process */ + hi_nv_item_index* nv_index = nv_find_item(HI_NULL, id, nv_type); + if (nv_index == HI_NULL) { + return HI_ERR_NV_ERROR_READ; + } + /* Length processing */ + if (nv_index->nv_len != len) { + item_len = hi_min(nv_index->nv_len, len); + } + + hi_u8* nv_file = (hi_u8 *)rom_boot_malloc(nv_ctrl->block_size); + if (nv_file == HI_NULL) { + return HI_ERR_MALLOC_FAILUE; + } + if (nv_type == HI_TYPE_FACTORY_NV) { + backup_num = 2; /* 2:Two copies of operations in the factory area are backed up. */ + } + for (; backup_num > 0; backup_num--) { + ret = nv_read_flash(nv_ctrl->current_addr, nv_ctrl->block_size, nv_file); + if (ret != HI_ERR_SUCCESS) { + continue; + } + + hi_crc32_nv(0, data, item_len, &crc); + cs = (uintptr_t)(nv_file + nv_index->nv_offset) ^ item_len ^ (uintptr_t)data ^ item_len; + if (memcpy_s(nv_file + nv_index->nv_offset, item_len, data, item_len, cs) != EOK) { + continue; + } + cs = (uintptr_t)(nv_file + nv_index->nv_offset + item_len) ^ sizeof(crc) ^ ((uintptr_t)&crc) ^ sizeof(crc); + if (memcpy_s(nv_file + nv_index->nv_offset + item_len, sizeof(crc), &crc, sizeof(crc), cs) != EOK) { + continue; + } + ret = nv_block_write(nv_file, nv_type); + if (ret != HI_ERR_SUCCESS) { + continue; + } + } + rom_boot_free(nv_file); + return ret; +} + +hi_u32 nv_write_common(hi_u8 id, const hi_pvoid data, hi_u8 len, hi_nv_type nv_type) +{ + if (nv_type >= HI_TYPE_NV_MAX) { + return HI_ERR_NV_INVALID_PARAMETER; + } + + hi_u8* item_readback = (hi_u8 *)rom_boot_malloc(HNV_ITEM_MAXLEN); + if (item_readback == HI_NULL) { + return HI_ERR_MALLOC_FAILUE; + } + + hi_u32 ret = nv_read_common(id, item_readback, len, nv_type); + if (ret != HI_ERR_SUCCESS) { + rom_boot_free(item_readback); + return ret; + } + if (memcmp(data, item_readback, len) == HI_ERR_SUCCESS) { + rom_boot_free(item_readback); + return HI_ERR_SUCCESS; + } + rom_boot_free(item_readback); + + /* Normal write process */ + ret = nv_common_write(id, nv_type, len, data); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + return HI_ERR_SUCCESS; +} + +hi_u32 hi_factory_nv_init(hi_u32 addr, hi_u32 total_size, hi_u32 block_size) +{ + return nv_init_common(addr, total_size, block_size, HI_TYPE_FACTORY_NV); +} + +hi_u32 hi_factory_nv_write(hi_u8 id, hi_pvoid pdata, hi_u8 len, hi_u32 flag) +{ + hi_unref_param(flag); + hi_u32 ret; + hi_nv_ctrl* nv_ctrl = HI_NULL; + + if (id >= HI_NV_FACTORY_USR_ID_END) { + return HI_ERR_NV_NOT_SUPPORT; + } + if ((pdata == HI_NULL) || (len == 0) || (len > HNV_ITEM_MAXLEN)) { + return HI_ERR_NV_INVALID_PARAMETER; + } + nv_ctrl = &g_s_nv_ctrl[HI_TYPE_FACTORY_NV]; + if (nv_ctrl->init_flag != HI_TRUE) { + return HI_ERR_NV_INITILIZATION; + } + ret = nv_write_common(id, (HI_CONST hi_pvoid)pdata, len, HI_TYPE_FACTORY_NV); + + return ret; +} + +hi_u32 hi_factory_nv_read(hi_u8 id, hi_pvoid data, hi_u8 len, hi_u32 flag) +{ + hi_unref_param(flag); + hi_u32 ret; + hi_nv_ctrl* nv_ctrl = HI_NULL; + + if (id >= HI_NV_FACTORY_USR_ID_END) { + return HI_ERR_NV_NOT_SUPPORT; + } + if ((data == HI_NULL) || (len == 0) || (len > HNV_ITEM_MAXLEN)) { + return HI_ERR_NV_INVALID_PARAMETER; + } + nv_ctrl = &g_s_nv_ctrl[HI_TYPE_FACTORY_NV]; + if (nv_ctrl->init_flag != HI_TRUE) { + return HI_ERR_NV_INITILIZATION; + } + ret = nv_read_common(id, data, len, HI_TYPE_FACTORY_NV); + + return ret; +} diff --git a/sdk_liteos/boot/loaderboot/common/partition_table/SConscript b/sdk_liteos/boot/loaderboot/common/partition_table/SConscript new file mode 100755 index 0000000000000000000000000000000000000000..aceb2b6a9464ce64030c1f9c5374ec933dcab384 --- /dev/null +++ b/sdk_liteos/boot/loaderboot/common/partition_table/SConscript @@ -0,0 +1,6 @@ +Import('env') + +env = env.Clone() + +objs = env.Object(Glob('*.c')) +Return('objs') diff --git a/sdk_liteos/boot/loaderboot/common/partition_table/load_partition_table.c b/sdk_liteos/boot/loaderboot/common/partition_table/load_partition_table.c new file mode 100644 index 0000000000000000000000000000000000000000..c3f56b11178e3dd6fa1865447a3f5f83914a66a8 --- /dev/null +++ b/sdk_liteos/boot/loaderboot/common/partition_table/load_partition_table.c @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#define PRODUCT_CFG_DEFAULT_BOOT_ADDR 0x0 +#define PRODUCT_CFG_DEFAULT_FNV_ADDR 0x8000 +#define PRODUCT_CFG_DEFAULT_NORMAL_NV_ADDR 0xA000 +#define PRODUCT_CFG_DEFAULT_NORMAL_NV_BACKUP_ADDR 0xC000 +#define PRODUCT_CFG_DEFAULT_KERNEL_A_ADDR 0xD000 +#define PRODUCT_CFG_DEFAULT_KERNEL_B_ADDR 0xF1000 +#define PRODUCT_CFG_DEFAULT_HILINK_ADDR 0x1E3000 +#define PRODUCT_CFG_DEFAULT_FILE_SYSTEM_ADDR 0x1E5000 +#define PRODUCT_CFG_DEFAULT_USER_RESERVE_ADDR 0x1F0000 +#define PRODUCT_CFG_DEFAULT_HILINK_PKI_ADDR 0x1F5000 +#define PRODUCT_CFG_DEFAULT_CRASH_INFO_ADDR 0x1F7000 +#define PRODUCT_CFG_DEFAULT_BOOT_BACK_ADDR 0x1F8000 + +#define PRODUCT_CFG_DEFAULT_BOOT_SIZE 0x8000 /* 32K */ +#define PRODUCT_CFG_DEFAULT_FNV_SIZE 0x2000 /* 8K */ +#define PRODUCT_CFG_DEFAULT_NORMAL_NV_SIZE 0x2000 /* 8K */ +#define PRODUCT_CFG_DEFAULT_NORMAL_NV_BACKUP_SIZE 0x1000 /* 4K */ +#define PRODUCT_CFG_DEFAULT_KERNEL_A_SIZE 0xE4000 /* 912K */ +#define PRODUCT_CFG_DEFAULT_KERNEL_B_SIZE 0xF2000 /* 968K */ +#define PRODUCT_CFG_DEFAULT_HILINK_SIZE 0x2000 /* 8K */ +#define PRODUCT_CFG_DEFAULT_FILE_SYSTEM_SIZE 0xB000 /* 44K */ +#define PRODUCT_CFG_DEFAULT_USER_RESERVE_SIZE 0x5000 /* 20K */ +#define PRODUCT_CFG_DEFAULT_HILINK_PKI_SIZE 0x2000 /* 8K */ +#define PRODUCT_CFG_DEFAULT_CRASH_INFO_SIZE 0x1000 /* 4K */ +#define PRODUCT_CFG_DEFAULT_BOOT_BACK_SIZE 0x8000 /* 32K */ + +static hi_flash_partition_table g_partition_table; + +hi_flash_partition_table* hi_get_partition_table(hi_void) +{ + return &g_partition_table; +} + + +/* Initializes the flash partition table. */ +hi_u32 hi_flash_partition_init(hi_void) +{ + hi_u32 ret; + hi_flash_partition_table* table = HI_NULL; + (hi_void)hi_factory_nv_init(HI_FNV_DEFAULT_ADDR, HI_NV_DEFAULT_TOTAL_SIZE, HI_NV_DEFAULT_BLOCK_SIZE); + table = hi_get_partition_table(); + ret = hi_factory_nv_read(HI_NV_FTM_FLASH_PARTIRION_TABLE_ID, table, sizeof(hi_flash_partition_table), 0); + if (ret != HI_ERR_SUCCESS) { /* read nv fail, set flash partition table default value */ + table->table[HI_FLASH_PARTITON_BOOT].addr = PRODUCT_CFG_DEFAULT_BOOT_ADDR; + table->table[HI_FLASH_PARTITON_BOOT].size = PRODUCT_CFG_DEFAULT_BOOT_SIZE; + table->table[HI_FLASH_PARTITON_FACTORY_NV].addr = PRODUCT_CFG_DEFAULT_FNV_ADDR; + table->table[HI_FLASH_PARTITON_FACTORY_NV].size = PRODUCT_CFG_DEFAULT_FNV_SIZE; + table->table[HI_FLASH_PARTITON_NORMAL_NV].addr = PRODUCT_CFG_DEFAULT_NORMAL_NV_ADDR; + table->table[HI_FLASH_PARTITON_NORMAL_NV].size = PRODUCT_CFG_DEFAULT_NORMAL_NV_SIZE; + table->table[HI_FLASH_PARTITON_NORMAL_NV_BACKUP].addr = PRODUCT_CFG_DEFAULT_NORMAL_NV_BACKUP_ADDR; + table->table[HI_FLASH_PARTITON_NORMAL_NV_BACKUP].size = PRODUCT_CFG_DEFAULT_NORMAL_NV_BACKUP_SIZE; + table->table[HI_FLASH_PARTITON_KERNEL_A].addr = PRODUCT_CFG_DEFAULT_KERNEL_A_ADDR; + table->table[HI_FLASH_PARTITON_KERNEL_A].size = PRODUCT_CFG_DEFAULT_KERNEL_A_SIZE; + table->table[HI_FLASH_PARTITON_KERNEL_B].addr = PRODUCT_CFG_DEFAULT_KERNEL_B_ADDR; + table->table[HI_FLASH_PARTITON_KERNEL_B].size = PRODUCT_CFG_DEFAULT_KERNEL_B_SIZE; + table->table[HI_FLASH_PARTITON_HILINK].addr = PRODUCT_CFG_DEFAULT_HILINK_ADDR; + table->table[HI_FLASH_PARTITON_HILINK].size = PRODUCT_CFG_DEFAULT_HILINK_SIZE; + table->table[HI_FLASH_PARTITON_FILE_SYSTEM].addr = PRODUCT_CFG_DEFAULT_FILE_SYSTEM_ADDR; + table->table[HI_FLASH_PARTITON_FILE_SYSTEM].size = PRODUCT_CFG_DEFAULT_FILE_SYSTEM_SIZE; + table->table[HI_FLASH_PARTITON_USR_RESERVE].addr = PRODUCT_CFG_DEFAULT_USER_RESERVE_ADDR; + table->table[HI_FLASH_PARTITON_USR_RESERVE].size = PRODUCT_CFG_DEFAULT_USER_RESERVE_SIZE; + table->table[HI_FLASH_PARTITON_HILINK_PKI].addr = PRODUCT_CFG_DEFAULT_HILINK_PKI_ADDR; + table->table[HI_FLASH_PARTITON_HILINK_PKI].size = PRODUCT_CFG_DEFAULT_HILINK_PKI_SIZE; + table->table[HI_FLASH_PARTITON_CRASH_INFO].addr = PRODUCT_CFG_DEFAULT_CRASH_INFO_ADDR; + table->table[HI_FLASH_PARTITON_CRASH_INFO].size = PRODUCT_CFG_DEFAULT_CRASH_INFO_SIZE; + table->table[HI_FLASH_PARTITON_BOOT_BACK].addr = PRODUCT_CFG_DEFAULT_BOOT_BACK_ADDR; + table->table[HI_FLASH_PARTITON_BOOT_BACK].size = PRODUCT_CFG_DEFAULT_BOOT_BACK_SIZE; + } + return ret; +} + diff --git a/sdk_liteos/boot/loaderboot/common/transfer.c b/sdk_liteos/boot/loaderboot/common/transfer.c new file mode 100644 index 0000000000000000000000000000000000000000..e58595dd4b644a5562f3f10678a1bddd1be11df6 --- /dev/null +++ b/sdk_liteos/boot/loaderboot/common/transfer.c @@ -0,0 +1,497 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include + +#ifdef CONFIG_FLASH_ENCRYPT_SUPPORT +#include +#endif + +#define FLASHBOOT_MAX_SIZE 0x8000 +#define DEFAULT_KERNEL_BURN_ADDR 0xD000 + +upload_context *g_upload_ctx = HI_NULL; + +hi_u32 loader_serial_ymodem(hi_u32 offset, hi_u32 erased_size, hi_u32 min, hi_u32 max) +{ + hi_u32 size = 0; + uintptr_t store_addr = offset; + hi_u32 file_length, remain, read_len, ret, cs; + + ret = loader_ymodem_open(); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + file_length = ymodem_get_length(); + if (file_length <= min || file_length > max) { + boot_msg1("file length err : ", file_length); + return HI_ERR_FAILURE; + } + + if (erased_size && (erased_size < file_length)) { + boot_msg0("file_size > erase_size"); + return HI_ERR_FAILURE; + } + + remain = file_length; + + while (remain > 0) { + hi_u32 read_size = (hi_u32)hi_min(remain, SZ_1KB); + read_len = ymodem_read(g_ymodem_buf, read_size, ((uintptr_t)g_ymodem_buf) ^ read_size); + if (read_len == 0 || remain < read_len) { + return HI_ERR_FAILURE; + } + + if (erased_size == 0) { + cs = (uintptr_t)(hi_void *)store_addr ^ (hi_u32)remain ^ (uintptr_t)g_ymodem_buf ^ (hi_u32)read_len; + if (memcpy_s((hi_void *)store_addr, (hi_u32)remain, g_ymodem_buf, read_len, cs) != EOK) { + return HI_ERR_FAILURE; + } + } else { + ret = g_flash_cmd_funcs.write(store_addr, read_len, (hi_u8 *)g_ymodem_buf, HI_FALSE); + if (ret != HI_ERR_SUCCESS) { + boot_msg1("flash write fail", ret); + return HI_ERR_FAILURE; + } + } + remain -= read_len; + size += read_len; + store_addr += (hi_u32)read_len; + } + cs = ((uintptr_t)g_ymodem_buf) ^ SZ_1KB; + (hi_void) ymodem_read(g_ymodem_buf, SZ_1KB, cs); + + ymodem_close(); + if ((hi_u32)size == file_length) { + boot_msg1("total size:", (hi_u32)size); + return HI_ERR_SUCCESS; + } + + return HI_ERR_FAILURE; +} + +hi_u32 loady_file(uintptr_t ram_addr) +{ + hi_u32 ret; + + if (load_malloc_init() != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; /* failure */ + } + + loader_ack(ACK_SUCCESS); + ret = loader_serial_ymodem(ram_addr, 0, sizeof(efuse_config_header), EFUSE_CFG_MAX_LEN); + + load_malloc_deinit(); + + return ret; +} + +hi_u32 loady_version_file(uintptr_t ram_addr) +{ + hi_u32 ret; + + if (load_malloc_init() != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + + loader_ack(ACK_SUCCESS); + + ret = loader_serial_ymodem(ram_addr, 0, 0x7, 0x8); + + load_malloc_deinit(); + + return ret; +} + +hi_u32 download_to_flash(hi_u32 flash_offset, hi_u32 erase_size, hi_u32 flash_size) +{ + hi_u32 ret; + + ret = g_flash_cmd_funcs.init(); + if (ret != HI_ERR_FLASH_RE_INIT && ret != HI_ERR_SUCCESS && + ret != HI_ERR_FLASH_QUAD_MODE_COMPARE_REG) { + boot_msg1("probe ", ret); + return HI_ERR_FAILURE; + } + + if (load_malloc_init() != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; /* failure */ + } + + if (erase_size == 0) { + boot_msg0("len error"); + load_malloc_deinit(); + return HI_ERR_FAILURE; + } + + boot_msg2("erase flash ", flash_offset, erase_size); + + ret = g_flash_cmd_funcs.erase(flash_offset, erase_size); + if (ret != HI_ERR_SUCCESS) { + boot_msg1("erase faild ret=", (hi_u32)ret); + load_malloc_deinit(); + return HI_ERR_FAILURE; + } + + boot_msg0("Ready for download"); + + loader_ack(ACK_SUCCESS); + ret = loader_serial_ymodem(flash_offset, erase_size, 0, flash_size); + load_malloc_deinit(); + return ret; +} + +hi_u32 download_image(hi_u32 addr, hi_u32 erase_size, hi_u32 flash_size, hi_u8 burn_efuse) +{ + hi_u32 ret; + hi_unref_param(burn_efuse); + + ret = download_to_flash(addr, erase_size, flash_size); + if (ret != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + +#ifdef CONFIG_FLASH_ENCRYPT_SUPPORT + if (((addr == DEFAULT_KERNEL_BURN_ADDR) && (erase_size > FLASHBOOT_MAX_SIZE)) || + ((addr == 0) && (erase_size > FLASHBOOT_MAX_SIZE))) { + ret = crypto_check_encrypt(); + if (ret != HI_ERR_SUCCESS) { + boot_put_errno(HI_PRINT_ERRNO_CRYPTO_FW_ENCRYPT_ERR); + return ret; + } + } +#endif + + return HI_ERR_SUCCESS; +} + +hi_u32 download_factory_image(hi_u32 addr, hi_u32 erase_size, hi_u32 flash_size, hi_u8 burn_efuse) +{ + hi_u32 ret; + hi_unref_param(burn_efuse); + + ret = download_to_flash(addr, erase_size, flash_size); + if (ret != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + +#ifdef CONFIG_FLASH_ENCRYPT_SUPPORT + ret = crypto_encrypt_factory_image(addr); + if (ret != HI_ERR_SUCCESS) { + return ret; + } +#endif + + return HI_ERR_SUCCESS; +} + +hi_u32 upload_malloc_init(hi_void) +{ + if (g_upload_ctx == HI_NULL) { + g_upload_ctx = (upload_context *)boot_malloc(sizeof(upload_context)); + } + + if (g_upload_ctx == HI_NULL) { + return HI_ERR_FAILURE; + } + + hi_u32 check_sum = (uintptr_t)g_upload_ctx ^ (hi_u32)sizeof(upload_context) ^ 0 ^ (hi_u32)sizeof(upload_context); + (hi_void) memset_s(g_upload_ctx, sizeof(upload_context), 0, sizeof(upload_context), check_sum); + + return HI_ERR_SUCCESS; +} +hi_u32 upload_malloc_deinit(hi_void) +{ + hi_u32 ret; + ret = boot_free(g_upload_ctx); + if (ret == HI_ERR_SUCCESS) { + g_upload_ctx = HI_NULL; + } + + return ret; +} + +hi_void upload_send_file_info(hi_void) +{ + upload_context *ctx = g_upload_ctx; + hi_u8 name_length = UPLOAD_FILE_NAME_LEN; + hi_u8 *data = HI_NULL; + hi_s32 temp_length = (hi_s32)ctx->file_length; + hi_s32 count = 0; + hi_u8 temp_char; + hi_u16 crc; + hi_s32 i; + hi_u32 check_sum; + + if (ctx->retry > 0) { + serial_put_buf((const char *)ctx->buffer, SOH_MSG_TOTAL_LEN); + return; + } + + hi_u32 check_sum_val = (uintptr_t)(ctx->buffer) ^ (hi_u32)sizeof(ctx->buffer) ^ 0 ^ (hi_u32)sizeof(ctx->buffer); + (hi_void) memset_s(ctx->buffer, sizeof(ctx->buffer), 0, sizeof(ctx->buffer), check_sum_val); + ctx->buffer[0] = MODEM_SOH; + ctx->buffer[1] = ctx->seq; + ctx->buffer[2] = (hi_u8)~ctx->buffer[1]; /* buffer[2] is buffer[1] invert val */ + + check_sum = (uintptr_t)(ctx->buffer + MSG_START_LEN) ^ SOH_MSG_LEN ^ (uintptr_t)(ctx->file_name) ^ + (hi_u32)name_length; + if (memcpy_s(ctx->buffer + MSG_START_LEN, SOH_MSG_LEN, ctx->file_name, name_length, check_sum) != EOK) { + return; + } + + data = ctx->buffer + MSG_START_LEN + name_length; + + while (temp_length > 0) { + data[count++] = (hi_u8)((hi_u8)'0' + (temp_length % DECIMAL)); + temp_length /= DECIMAL; + } + + /* 64 bytes, enough for storing 32-bit decimal digits + CNcomment:64字节足够存放32位10进制数 */ + for (i = 0; i < count / 2; i++) { /* count should be divided by 2 */ + temp_char = data[i]; + data[i] = data[count - i - 1]; + data[count - i - 1] = temp_char; + } + + check_sum = 0 ^ (uintptr_t)(ctx->buffer + MSG_START_LEN) ^ SOH_MSG_LEN; + crc = crc16_ccitt(0, ctx->buffer + MSG_START_LEN, SOH_MSG_LEN, check_sum); + ctx->buffer[131] = (hi_u8)(crc >> 8); /* buffer[131] is crc high 8 bit */ + ctx->buffer[132] = (hi_u8)crc; /* buffer[132] is crc low 8 bit */ + + serial_put_buf((const char *)ctx->buffer, SOH_MSG_TOTAL_LEN); + + ctx->status = UPLOAD_WAIT_INIT_ACK; +} + +hi_void upload_send_null_info(hi_void) +{ + upload_context *ctx = g_upload_ctx; + hi_u16 crc; + + hi_u32 check_sum_val = (uintptr_t)(ctx->buffer) ^ (hi_u32)sizeof(ctx->buffer) ^ 0 ^ SOH_MSG_LEN; + (hi_void) memset_s(ctx->buffer, sizeof(ctx->buffer), 0, SOH_MSG_LEN, check_sum_val); + ctx->buffer[0] = MODEM_SOH; + ctx->buffer[1] = 0; + ctx->buffer[2] = 0xFF; /* buffer[2] is buffer[1] invert val */ + hi_u32 check_sum = 0 ^ (uintptr_t)(ctx->buffer + MSG_START_LEN) ^ SOH_MSG_LEN; + crc = crc16_ccitt(0, ctx->buffer + MSG_START_LEN, SOH_MSG_LEN, check_sum); + ctx->buffer[131] = (hi_u8)(crc >> 8); /* buffer[131] is crc high 8 bit */ + ctx->buffer[132] = (hi_u8)crc; /* buffer[132] is crc low 8 bit */ + serial_put_buf((const char *)ctx->buffer, SOH_MSG_TOTAL_LEN); + + ctx->status = UPLOAD_WAIT_ZERO_ACK; +} + +hi_void upload_send_data(hi_void) +{ + upload_context *ctx = g_upload_ctx; + hi_u32 remain = ctx->file_length - ctx->offset; + hi_u16 crc; + + if (ctx->retry > 0) { + if (ctx->buffer[0] == MODEM_SOH) { + serial_put_buf((const char *)ctx->buffer, SOH_MSG_TOTAL_LEN); + } else { + serial_put_buf((const char *)ctx->buffer, UPLOAD_BUFF_LEN); + } + + return; + } + + ctx->status = UPLOAD_WAIT_FINAL_ACK; + hi_u32 check_sum = (uintptr_t)(ctx->buffer) ^ (hi_u32)sizeof(ctx->buffer) ^ MODEM_EOF ^ (hi_u32)sizeof(ctx->buffer); + (hi_void) memset_s(ctx->buffer, sizeof(ctx->buffer), MODEM_EOF, sizeof(ctx->buffer), check_sum); + + ctx->buffer[0] = MODEM_STX; + ctx->buffer[1] = ++ctx->seq; + ctx->buffer[2] = (hi_u8)~ctx->buffer[1]; /* buffer[2] is buffer[1] invert val */ + + if (remain <= SOH_MSG_LEN) { + ctx->buffer[0] = MODEM_SOH; + if (memcpy_s (ctx->buffer + MSG_START_LEN, SOH_MSG_LEN, + (const hi_void *)(uintptr_t)(ctx->file_addr + ctx->offset), remain, (uintptr_t)(ctx->buffer + MSG_START_LEN) + ^ SOH_MSG_LEN ^ (uintptr_t)(const hi_void *)(uintptr_t)(ctx->file_addr + ctx->offset) ^ remain) != EOK) { + return; + } + check_sum = 0 ^ (uintptr_t)(ctx->buffer + MSG_START_LEN) ^ SOH_MSG_LEN; + crc = crc16_ccitt(0, ctx->buffer + MSG_START_LEN, SOH_MSG_LEN, check_sum); + ctx->buffer[131] = (hi_u8)(crc >> 8); /* buffer[131] is crc high 8 bit */ + ctx->buffer[132] = (hi_u8)crc; /* buffer[132] is crc low 8 bit */ + serial_put_buf((const char *)ctx->buffer, SOH_MSG_TOTAL_LEN); + } else { + if (remain > UPLOAD_DATA_SIZE) { + remain = UPLOAD_DATA_SIZE; + ctx->status = UPLOAD_WAIT_INTER_ACK; + } + check_sum = (uintptr_t)(ctx->buffer + MSG_START_LEN) ^ UPLOAD_DATA_SIZE ^ + (uintptr_t)(const hi_void *)(uintptr_t)(ctx->file_addr + ctx->offset) ^ remain; + if (memcpy_s(ctx->buffer + MSG_START_LEN, UPLOAD_DATA_SIZE, + (const hi_void *)(uintptr_t)(ctx->file_addr + ctx->offset), remain, check_sum) != EOK) { + return; + } + check_sum = 0 ^ (uintptr_t)(ctx->buffer + MSG_START_LEN) ^ UPLOAD_DATA_SIZE; + crc = crc16_ccitt(0, ctx->buffer + MSG_START_LEN, UPLOAD_DATA_SIZE, check_sum); + ctx->buffer[1027] = (hi_u8)(crc >> 8); /* buffer[1027] is crc high 8 bit */ + ctx->buffer[1028] = (hi_u8)crc; /* buffer[1028] is crc low 8 bit */ + serial_put_buf((const char *)ctx->buffer, UPLOAD_BUFF_LEN); + } + + ctx->offset += remain; +} + +hi_s32 upload_modem_c_step(hi_u8 status) +{ + switch (status) { + case UPLOAD_WAIT_START_C: + upload_send_file_info(); + return 1; + case UPLOAD_WAIT_TRANS_C: + upload_send_data(); + return 1; + case UPLOAD_WAIT_EOT_C: + upload_send_null_info(); + return 1; + default: + return 0; + } +} + +hi_s32 upload_modem_ack_step(hi_u8 *status, hi_u32 *timeout) +{ + switch (*status) { + case UPLOAD_WAIT_INIT_ACK: + *timeout = UPLOAD_WAIT_DEFAULT_TIME; + *status = UPLOAD_WAIT_TRANS_C; + return 1; + case UPLOAD_WAIT_INTER_ACK: + upload_send_data(); + return 1; + case UPLOAD_WAIT_FINAL_ACK: + serial_putc(MODEM_EOT); + *status = UPLOAD_WAIT_EOT_C; + return 1; + default: + return 0; + } +} + +hi_s32 upload_modem_nak_step(hi_u8 *status, hi_u32 *timeout) +{ + switch (*status) { + case UPLOAD_WAIT_INIT_ACK: + *timeout = UPLOAD_WAIT_START_C_TIME; + upload_send_file_info(); + return 1; + case UPLOAD_WAIT_INTER_ACK: + case UPLOAD_WAIT_FINAL_ACK: + upload_send_data(); + return 1; + case UPLOAD_WAIT_EOT_C: + serial_putc(MODEM_EOT); + *status = UPLOAD_WAIT_EOT_C; + return 1; + case UPLOAD_WAIT_ZERO_ACK: + upload_send_null_info(); + return 1; + default: + return 0; + } +} + +hi_u32 upload_serial_ymodem(hi_void) +{ + upload_context *ctx = g_upload_ctx; + hi_u8 ch; + hi_u32 timeout = UPLOAD_WAIT_START_C_TIME; + + for (;;) { + hi_u32 ret = serial_getc_timeout(timeout, &ch); + if (ret != HI_ERR_SUCCESS) { + continue; + } + + switch (ch) { + case MODEM_C: + ctx->can_cnt = 0; + ctx->retry = 0; + if (upload_modem_c_step(ctx->status) == 1) { + continue; + } + break; + + case MODEM_ACK: + ctx->can_cnt = 0; + ctx->retry = 0; + if (ctx->status == UPLOAD_WAIT_ZERO_ACK) { + mdelay(WAIT_ZERO_ACK_DELAY); + return HI_ERR_SUCCESS; + } + if (upload_modem_ack_step(&ctx->status, &timeout) == 1) { + continue; + } + break; + + case MODEM_NAK: + ctx->can_cnt = 0; + + if (++ctx->retry == RETRY_COUNT) { + return HI_ERR_FAILURE; + } + if (upload_modem_nak_step(&ctx->status, &timeout) == 1) { + continue; + } + break; + + case MODEM_CAN: + ctx->retry = 0; + + if (++ctx->can_cnt == CAN_COUNT) { + return HI_ERR_FAILURE; + } + + continue; + /* fall-through */ + default: + continue; + } + } +} + +hi_u32 upload_data(hi_u32 addr, hi_u32 length) +{ + if (upload_malloc_init() != HI_ERR_SUCCESS) { + boot_msg0("upload init fail."); + return HI_ERR_FAILURE; + } + + g_upload_ctx->file_addr = addr + FLASH_ADDR_OFFSET; + g_upload_ctx->file_length = length; + g_upload_ctx->file_name = UPLOAD_FILE_NAME; + g_upload_ctx->status = UPLOAD_WAIT_START_C; + + loader_ack(ACK_SUCCESS); + + if (upload_serial_ymodem() == HI_ERR_SUCCESS) { + upload_malloc_deinit(); + return HI_ERR_SUCCESS; + } + upload_malloc_deinit(); + return HI_ERR_FAILURE; +} diff --git a/sdk_liteos/boot/loaderboot/drivers/efuse/SConscript b/sdk_liteos/boot/loaderboot/drivers/efuse/SConscript new file mode 100755 index 0000000000000000000000000000000000000000..aceb2b6a9464ce64030c1f9c5374ec933dcab384 --- /dev/null +++ b/sdk_liteos/boot/loaderboot/drivers/efuse/SConscript @@ -0,0 +1,6 @@ +Import('env') + +env = env.Clone() + +objs = env.Object(Glob('*.c')) +Return('objs') diff --git a/sdk_liteos/boot/loaderboot/drivers/efuse/efuse.c b/sdk_liteos/boot/loaderboot/drivers/efuse/efuse.c new file mode 100644 index 0000000000000000000000000000000000000000..d506a141ccad47675b6bbe8a29460048eea74e37 --- /dev/null +++ b/sdk_liteos/boot/loaderboot/drivers/efuse/efuse.c @@ -0,0 +1,250 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "efuse.h" + +hi_u32 efuse_start_addr_unaligned_read(hi_u16 start_bit, hi_u16 size, hi_u8 diff_head_read, hi_u8 *data) +{ + if (size == SIZE_8_BITS) { + if (efuse_read_bits(start_bit, size, data) != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + + data[0] = data[0] >> diff_head_read; + } else if (size == SIZE_16_BITS) { + hi_u16 tmp_data = 0; + if (efuse_read_bits(start_bit, size, (hi_u8 *)&tmp_data) != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + + tmp_data = tmp_data >> diff_head_read; + if (start_bit == 0xE0) { + *data = (hi_u8)(tmp_data & 0xFF); + } else { + *(hi_u16 *)data = tmp_data; + } + } else if (size == SIZE_24_BITS) { + hi_u32 tmp_data = 0; + if (efuse_read_bits(start_bit, SIZE_24_BITS, (hi_u8 *)&tmp_data) != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + + tmp_data = tmp_data >> diff_head_read; + hi_u32 check_sum = (uintptr_t)data ^ DATA_LENGTH ^ (uintptr_t)(hi_u8 *)&tmp_data ^ DATA_LENGTH; + if (memcpy_s(data, DATA_LENGTH, (hi_u8 *)&tmp_data, DATA_LENGTH, check_sum) != EOK) { + return HI_ERR_FAILURE; + } + } else if (size == SIZE_72_BITS) { + hi_u8 tmp_data[SIZE_72_BITS / SIZE_8_BITS] = { 0 }; + hi_u32 data_u32[2]; /* U64 is divided into 2 U32 */ + hi_u8 end_u8; + if (efuse_read_bits(start_bit, SIZE_72_BITS, &tmp_data[0]) != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + + data_u32[0] = *(hi_u32 *)&tmp_data[0]; /* first U32 offset is 0 */ + data_u32[1] = *(hi_u32 *)&tmp_data[4]; /* sencond U32 offset is 4 */ + end_u8 = *(hi_u8 *)&tmp_data[8]; /* the last u8 bit */ + data_u32[0] = data_u32[0] >> diff_head_read; + data_u32[0] = data_u32[0] | (data_u32[1] << (SIZE_32_BITS - diff_head_read)); + data_u32[1] = data_u32[1] >> diff_head_read; + data_u32[1] = data_u32[1] | ((hi_u32)end_u8 << (SIZE_32_BITS - diff_head_read)); + *(hi_u64 *)data = (((hi_u64)data_u32[1] << SIZE_32_BITS) | data_u32[0]); + } else { + return HI_ERR_FAILURE; + } + + return HI_ERR_SUCCESS; +} + +hi_u32 efuse_bits_read(hi_u16 start_bit, hi_u16 size, hi_u8 *data, hi_u32 data_len) +{ + hi_u8 diff_head_read = 0; + hi_u32 origine_size; + hi_u32 ret; + if (data_len > EFUSE_MAX_INDEX_SIZE) { + return HI_ERR_FAILURE; + } + + origine_size = size; + if ((start_bit & 0x7) != 0x0) { + diff_head_read = start_bit % SIZE_8_BITS; + start_bit = start_bit - diff_head_read; /* Reads the 8-bit aligned start address. */ + size = size + diff_head_read; + } + + if ((size & 0x7) != 0x0) { + size = ((size >> THREE_BITS_OFFSET) + 1) << THREE_BITS_OFFSET; /* Reads data in 8-bit unit. */ + } + + if (diff_head_read == 0) { + /* Reads the 8-bit aligned start address. */ + ret = efuse_read_bits(start_bit, size, data); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + } else { + /* The start address is not 8-bit-aligned. */ + ret = efuse_start_addr_unaligned_read(start_bit, size, diff_head_read, data); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + } + + if (origine_size <= SIZE_8_BITS) { + *data &= ((1 << origine_size) - 1); + } else if (origine_size <= SIZE_16_BITS) { + *(hi_u16 *)data &= ((1 << origine_size) - 1); + } else if (origine_size < SIZE_32_BITS) { + *(hi_u32 *)data &= (((hi_u32)1 << origine_size) - 1); + } + + return HI_ERR_SUCCESS; +} + +hi_u32 hi_efuse_read(hi_efuse_idx efuse_id, hi_u8 *data, hi_u8 data_len) +{ + hi_u16 start_bit = 0; + hi_u16 size = 0; + hi_u16 align_size; + hi_u8 flag = EFUSE_IDX_NRW; + + if (efuse_id >= HI_EFUSE_IDX_MAX || data == HI_NULL) { + return HI_ERR_EFUSE_INVALIDATE_PARA; + } + + get_efuse_cfg_by_id(efuse_id, &start_bit, &size, &flag); + + if (flag == EFUSE_IDX_WO) { + return HI_ERR_EFUSE_INVALIDATE_AUTH; + } + + align_size = ((size & 0x7) != 0x0) ? (((size >> THREE_BITS_OFFSET) + 1) << THREE_BITS_OFFSET) : size; + + if (align_size > ((hi_u16)data_len * EIGHT_BITS)) { + return HI_ERR_EFUSE_INVALIDATE_PARA; + } + + return efuse_bits_read(start_bit, size, data, data_len); +} + +hi_u32 hi_efuse_write(hi_efuse_idx efuse_id, const hi_u8 *data) +{ + hi_u16 start_bit = 0; + hi_u16 size = 0; + hi_u8 flag = EFUSE_IDX_NRW; + hi_char err_state[EFUSE_MAX_INDEX_SIZE] = { + 0, + }; + hi_u32 i; + hi_u32 ret; + + if (efuse_id >= HI_EFUSE_IDX_MAX || data == HI_NULL) { + boot_msg1("parameter err !", efuse_id); + return HI_ERR_EFUSE_INVALIDATE_PARA; + } + + get_efuse_cfg_by_id(efuse_id, &start_bit, &size, &flag); + if (flag == EFUSE_IDX_RO) { + boot_msg1("This section can not be write !flag = ", flag); + return HI_ERR_EFUSE_INVALIDATE_AUTH; + } + + ret = efuse_write_bits(start_bit, size, data, (hi_u8 *)&err_state[0]); + if (ret != HI_ERR_SUCCESS) { + boot_msg0("efuse write err"); + return ret; + } + + for (i = 0; i < EFUSE_MAX_INDEX_SIZE; i++) { + if (err_state[i]) { + boot_msg1("errstate num is", i); + return HI_ERR_EFUSE_WRITE_ERR; + } + } + + return HI_ERR_SUCCESS; +} + +hi_u32 efuse_bits_write(hi_u16 start_bit, hi_u16 size, const hi_u8 *key_data) +{ + hi_u8 usr_err_stat[EFUSE_MAX_INDEX_SIZE]; + hi_u32 i; + hi_u32 ret; + + if (size > (EFUSE_MAX_INDEX_SIZE * SIZE_8_BITS) || key_data == HI_NULL || size == 0) { + return HI_ERR_FAILURE; + } + hi_u32 check_sum = (uintptr_t)usr_err_stat ^ EFUSE_MAX_INDEX_SIZE ^ 0 ^ EFUSE_MAX_INDEX_SIZE; + memset_s(usr_err_stat, EFUSE_MAX_INDEX_SIZE, 0, EFUSE_MAX_INDEX_SIZE, check_sum); + + ret = efuse_write_bits(start_bit, size, key_data, (hi_u8 *)&usr_err_stat[0]); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + for (i = 0; i < EFUSE_MAX_INDEX_SIZE; i++) { + if (usr_err_stat[i]) { + return HI_ERR_FAILURE; + } + } + + return HI_ERR_SUCCESS; +} + +hi_u32 hi_efuse_get_lockstat(hi_u64 *lock_stat) +{ + hi_u16 start_bit = EFUSE_LOCK_START_BITS; + hi_u16 size = EFUSE_LOCK_SIZE; + hi_u8 diff_head_read; + hi_u64 tmp_data = 0; + hi_u64 tmp_data_filed_two = 0; + hi_u32 ret; + + if (lock_stat == HI_NULL) { + return HI_ERR_FAILURE; + } + + /* start address and size 8 bits align. */ + diff_head_read = start_bit % EIGHT_BITS; + start_bit = start_bit - diff_head_read; + size = size + diff_head_read; + + ret = efuse_read_bits(start_bit, size, (hi_u8 *)&tmp_data); + if (ret == HI_ERR_SUCCESS) { + tmp_data = tmp_data >> diff_head_read; + } else { + return HI_ERR_FAILURE; + } + + start_bit = EFUSE_LOCK_FIELD2_START_BITS; + size = EFUSE_LOCK_FIELD2_SIZE; + + /* start address and size 8 bits align. */ + diff_head_read = start_bit % EIGHT_BITS; + start_bit = start_bit - diff_head_read; + size = size + diff_head_read; + + ret = efuse_read_bits(start_bit, size, (hi_u8 *)&tmp_data_filed_two); + if (ret == HI_ERR_SUCCESS) { + tmp_data_filed_two = tmp_data_filed_two >> diff_head_read; + } else { + return HI_ERR_FAILURE; + } + + *lock_stat = (((tmp_data_filed_two << EFUSE_LOCK_SIZE) & 0x1F000000000) | (tmp_data & 0xFFFFFFFFF)); + + return HI_ERR_SUCCESS; +} diff --git a/sdk_liteos/boot/loaderboot/drivers/flash/SConscript b/sdk_liteos/boot/loaderboot/drivers/flash/SConscript new file mode 100755 index 0000000000000000000000000000000000000000..aceb2b6a9464ce64030c1f9c5374ec933dcab384 --- /dev/null +++ b/sdk_liteos/boot/loaderboot/drivers/flash/SConscript @@ -0,0 +1,6 @@ +Import('env') + +env = env.Clone() + +objs = env.Object(Glob('*.c')) +Return('objs') diff --git a/sdk_liteos/boot/loaderboot/drivers/flash/hi_loaderboot_flash.c b/sdk_liteos/boot/loaderboot/drivers/flash/hi_loaderboot_flash.c new file mode 100644 index 0000000000000000000000000000000000000000..3c03c377f1f0d0fd89b22edda2d1bfb6e5c6a107 --- /dev/null +++ b/sdk_liteos/boot/loaderboot/drivers/flash/hi_loaderboot_flash.c @@ -0,0 +1,427 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "hi_loaderboot_flash.h" + +#include + +hi_spi_flash_ctrl g_flash_drv_ctrl = { + 0, +}; + +hi_u32 g_dma_buffer[FLASH_DMA_BUF_LEN] = {0}; +hi_u8 g_back_buffer[SZ_4KB] = { 0 }; + +#define HI_FLASH_SUPPORT_REF_VBAT +#define HI_FLASH_VOLTAGE_TH0 280 +#define HI_FLASH_VOLTAGE_TH1 310 +#define PLL2DBB_192M_MASK 0x3 +#define CMU_CLK_SEL_96M 96 +#define CMU_CLK_SEL_80M 80 +#define CMU_CLK_SEL_48M 48 + +#ifdef HI_FLASH_SUPPORT_REF_VBAT +typedef struct { + hi_u8 chip_id[HI_FLASH_CHIP_ID_NUM]; + hi_u8 freq_high : 2; + hi_u8 freq_midle : 2; + hi_u8 freq_low : 2; + hi_u8 voltage : 2; +} flash_vlt_sfc_info; + +flash_vlt_sfc_info g_flash_vlt_sfc_info_tbl[HI_FLASH_DEFAULT_TYPE_NUM] = { + /* 0-->96Mhz 1-->80Mhz 2-->60Mhz 3-->48Mhz */ + {{0, }, 0x1, 0x1, 0x3, 0x1}, + {{0xef, 0x60, 0x15}, 0x1, 0x1, 0x1, 0x0}, /* w25q16jw 1.8v */ + /* {{0xef, 0x40, 0x15}, 0x1d}, 00,01,11,01}, w25q16jl 3.3v */ + {{0xef, 0x40, 0x15}, 0x0, 0x1, 0x1, 0x1}, /* w25q16jl 3.3v */ + {{0xc8, 0x60, 0x15}, 0x1, 0x1, 0x1, 0x0}, /* gd25le16 1.8v */ + {{0xc8, 0x65, 0x15}, 0x0, 0x1, 0x1, 0x1}, /* gd25wq16 1.65~3.6v use 2.3~3.6v */ + {{0x1c, 0x38, 0x15}, 0x1, 0x1, 0x1, 0x0}, /* en25s16 1.8v */ + {{0x1C, 0x70, 0x15}, 0x0, 0x1, 0x1, 0x1}, /* en25qh16 3.3v */ + {{0x85, 0x60, 0x15}, 0x0, 0x1, 0x1, 0x1}, /* p25q16 1.65~3.6v use 2.3~3.6V */ +}; + +flash_vlt_sfc_info g_flash_vlt_sfc_info = { + 0, +}; +hi_u16 g_voltage = 0; + +hi_void sfc_config_set_experience(const hi_u8 *chip_id, flash_vlt_sfc_info *flash_info, + flash_vlt_sfc_info *flash_info_tbl, hi_u8 tbl_size) +{ + flash_vlt_sfc_info *info = HI_NULL; + hi_u8 i; + hi_u8 cur_chip_idx = 0xFF; /* 0xFF : invalid */ + for (i = 1; i < tbl_size; i++) { + info = &flash_info_tbl[i]; + if (memcmp(info->chip_id, chip_id, HI_FLASH_CHIP_ID_NUM) == HI_ERR_SUCCESS) { + cur_chip_idx = i; + } + } + info = (cur_chip_idx == 0xFF) ? &flash_info_tbl[0] : &flash_info_tbl[cur_chip_idx]; + hi_u32 cs = (uintptr_t)flash_info ^ sizeof(flash_vlt_sfc_info) ^ (uintptr_t)info ^ sizeof(flash_vlt_sfc_info); + if (memcpy_s(flash_info, sizeof(flash_vlt_sfc_info), info, sizeof(flash_vlt_sfc_info), cs) != EOK) { + return; + } +} + +hi_void sfc_config_update_freq(hi_u32 addr) +{ + hi_u32 ret; + hi_u16 val; + hi_u16 reg_val; + flash_vlt_sfc_info *flash_info = (flash_vlt_sfc_info *)(uintptr_t)addr; + if (flash_info == HI_NULL) { + return; + } + hi_reg_read16(PMU_CMU_CTL_CMU_CLK_SEL_REG, reg_val); + reg_val &= ~(PLL2DBB_192M_MASK << 8); /* 8 */ + if (flash_info->voltage == 0) { /* 1.8V flash */ + val = flash_info->freq_high; + reg_val |= val << 8; /* 8 */ + hi_reg_write16(PMU_CMU_CTL_CMU_CLK_SEL_REG, reg_val); + /* Drive Capability Configuration.CNcomment:驱动能力配置 */ + return; + } + ret = get_average_ref_vlt(&g_voltage); + if (ret != HI_ERR_SUCCESS) { + return; + } + /* 2.3V ~ 3.6V, Selecting the SFC frequency */ + if (g_voltage > HI_FLASH_VOLTAGE_TH1) { /* 297*0.01V */ + val = flash_info->freq_high; + } else if (g_voltage > HI_FLASH_VOLTAGE_TH0) { /* 270*0.01V */ + val = flash_info->freq_midle; + } else { + val = flash_info->freq_low; + } + reg_val |= val << 8; /* 8 */ + hi_reg_write16(PMU_CMU_CTL_CMU_CLK_SEL_REG, reg_val); +} + +hi_void sfc_config_cmu_clk_sel(hi_u8 clk) +{ + if (clk == CMU_CLK_SEL_96M) { + hi_reg_clrbits(PMU_CMU_CTL_CMU_CLK_SEL_REG, 8, 2); /* 8, 2 96M */ + } else if (clk == CMU_CLK_SEL_80M) { + hi_reg_clrbits(PMU_CMU_CTL_CMU_CLK_SEL_REG, 8, 2); /* set 8 left shift 2 */ + hi_reg_setbit(PMU_CMU_CTL_CMU_CLK_SEL_REG, 8); /* 80M */ + } else if (clk == CMU_CLK_SEL_48M) { + hi_reg_clrbits(PMU_CMU_CTL_CMU_CLK_SEL_REG, 8, 2); /* set 8 left shift 2 */ + hi_reg_setbit(PMU_CMU_CTL_CMU_CLK_SEL_REG, 8); /* 48M */ + hi_reg_setbit(PMU_CMU_CTL_CMU_CLK_SEL_REG, 9); /* 9 */ + } +} +#endif + +hi_u32 spi_flash_write_sr_reg(hi_u8 cmd, hi_u8* data, hi_u8 data_len, hi_bool is_volatile) +{ + hi_u32 temp_data = 0; + hi_u32 ret = HI_ERR_SUCCESS; + if (data_len > 0) { + hi_u32 check_sum = (uintptr_t)(&temp_data) ^ (hi_u32)sizeof(temp_data) ^ + (uintptr_t)data ^ data_len; + if (memcpy_s(&temp_data, sizeof(temp_data), data, data_len, check_sum) != EOK) { + return HI_ERR_FAILURE; + } + } + if (is_volatile) { + hisfc_write(SFC_REG_CMD_INS, SPI_CMD_VSR_WREN); + hisfc_write(SFC_REG_CMD_CONFIG, (hi_u32)(SFC_CMD_CONFIG_SEL_CS | SFC_CMD_CONFIG_START)); + spif_wait_config_start(); + } else { + ret = spif_write_enable(HI_TRUE); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + } + hisfc_write(SFC_REG_CMD_INS, cmd); + hisfc_write(SFC_REG_CMD_DATABUF1, temp_data); + + hisfc_write(SFC_REG_CMD_CONFIG, + SFC_CMD_CONFIG_SEL_CS + | SFC_CMD_CONFIG_DATA_EN + | sfc_cmd_config_data_cnt(data_len) + | SFC_CMD_CONFIG_START); + + spif_wait_config_start(); + return ret; +} + +hi_u32 flash_protect_set_protect(hi_u8 cmp_bp, hi_bool is_volatile) +{ + hi_u32 ret; + hi_u8 p_data[2] = {0}; /* 2 */ + hi_u8 cmp = (cmp_bp>>5) & 0x1; /* 5 */ + hi_u8 bp = cmp_bp & 0x1F; + ret = spif_wait_ready(HI_TRUE, SPI_CMD_SR_WIPN, SPI_SR_BIT_WIP); /* wait WIP set zero */ + if (ret != HI_ERR_SUCCESS) { + boot_msg1("spif_wait_ready et:", ret); + return ret; + } + ret = spi_flash_read_reg(SPI_CMD_RDSR, &p_data[0], 1); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + ret = spi_flash_read_reg(SPI_CMD_RDSR2, &p_data[1], 1); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + if (((p_data[0] & (0x1F<<2)) == (bp<<2)) && ((p_data[1] & (0x1<<6)) == (cmp<<6))) { /* 2 6 */ + return HI_ERR_SUCCESS; + } + p_data[0] &= ~(0x1f<<2); /* 2 */ + p_data[0] |= (hi_u8)(bp<<2); /* 2 */ + p_data[1] &= ~(0x1<<6); /* 6 */ + p_data[1] |= (hi_u8)(cmp<<6); /* 6 */ + ret = spi_flash_write_sr_reg(SPI_CMD_WRSR1, p_data, 2, is_volatile); /* 2 */ + if (ret != HI_ERR_SUCCESS) { + return ret; + } + ret = spif_wait_ready(HI_TRUE, SPI_CMD_SR_WIPN, SPI_SR_BIT_WIP); /* wait WIP set zero */ + if (ret != HI_ERR_SUCCESS) { + boot_msg1("spif_wait_ready et:", ret); + return ret; + } + ret = spi_flash_read_reg(SPI_CMD_RDSR, &p_data[0], 1); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + ret = spi_flash_read_reg(SPI_CMD_RDSR2, &p_data[1], 1); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + if (((p_data[0] & (0x1F<<2)) == (bp<<2)) && ((p_data[1] & (0x1<<6)) == (cmp<<6))) { /* 2 6 */ + return HI_ERR_SUCCESS; + } else { + return HI_ERR_FAILURE; + } +} + +hi_void flash_clk_config(hi_void) +{ + hi_u16 reg_val; + /* set 0: FPGA 80M, ASIC 96M. */ +#ifdef HI_FLASH_SUPPORT_REF_VBAT + hi_reg_clrbits(PMU_CMU_CTL_CMU_CLK_SEL_REG, 8, 2); /* set 8 left shift 2 */ + hi_reg_setbit(PMU_CMU_CTL_CMU_CLK_SEL_REG, 8); /* 48M */ + hi_reg_setbit(PMU_CMU_CTL_CMU_CLK_SEL_REG, 9); /* 9 */ +#else + /* When the VBAT reference voltage is unavailable, set this parameter based on the actual flash model. */ + hi_reg_clrbits(PMU_CMU_CTL_CMU_CLK_SEL_REG, 8, 2); /* set 8 left shift 2 */ + hi_reg_setbit(PMU_CMU_CTL_CMU_CLK_SEL_REG, 8); /* 8 80M */ +#endif + hi_reg_clrbit(PMU_CMU_CTL_CLK_192M_GT_REG, 0); + hi_reg_setbit(CLDO_CTL_CLK_SEL_REG, 1); + hi_reg_clrbits(PMU_CMU_CTL_CMU_CLK_SEL_REG, 4, 3); /* set 4 left shift 3 */ + + /* set sfc not div: in fpga, clk is 80M */ + hi_reg_clrbits(CLDO_CTL_CLK_DIV1_REG, 4, 3); /* 4, 3 */ + /* en flash ldo bypass */ + hi_reg_read16(PMU_CMU_CTL_FLASHLDO_CFG_1_REG, reg_val); + reg_val &= ~(0x1 << 6); /* 6 */ + reg_val |= 0x1 << 6; /* 6 */ + hi_reg_write16(PMU_CMU_CTL_FLASHLDO_CFG_1_REG, reg_val); + +#ifdef HI_BOARD_ASIC + /* Check whether the built-in flash memory exists based on the chip ID. If no built-in flash memory exists, + disable flash_ldo. */ + hi_u8 chip_id; + hi_u32 ret; + ret = hi_efuse_read(HI_EFUSE_CHIP_RW_ID, (hi_u8 *)&chip_id, (hi_u8)sizeof(hi_u8)); + if (ret == HI_ERR_SUCCESS) { + if (chip_id == HI_CHIP_ID_1131SV200) { + hi_reg_setbit(PMU_CMU_CTL_PMU_MAN_CLR_0_REG, 8); /* set 1 left shift 8 */ + hi_reg_setbit(CLDO_CTL_CLK_SEL_REG, 0); + } + } +#endif +} + +hi_u32 hi_flash_erase(hi_u32 flash_addr, hi_u32 flash_erase_size) +{ + hi_u32 ret; + hi_spi_flash_ctrl *spif_ctrl = &g_flash_drv_ctrl; + ret = sfc_check_para(spif_ctrl, flash_addr, flash_erase_size, HI_FLASH_CHECK_PARAM_OPT_ERASE); + if (ret != HI_ERR_SUCCESS) { + return ret; + } +#ifdef HI_FLASH_SUPPORT_REF_VBAT + if ((g_voltage <= HI_FLASH_VOLTAGE_TH0) && (memcmp(g_flash_vlt_sfc_info.chip_id, + g_flash_vlt_sfc_info_tbl[2].chip_id, HI_FLASH_CHIP_ID_NUM) == HI_ERR_SUCCESS)) { // 2 + sfc_config_cmu_clk_sel(CMU_CLK_SEL_48M); + } +#endif + ret = flash_erase_prv(spif_ctrl, flash_addr, flash_erase_size); +#ifdef HI_FLASH_SUPPORT_REF_VBAT + if ((g_voltage <= HI_FLASH_VOLTAGE_TH0) && (memcmp(g_flash_vlt_sfc_info.chip_id, + g_flash_vlt_sfc_info_tbl[2].chip_id, HI_FLASH_CHIP_ID_NUM) == HI_ERR_SUCCESS)) { // 2 + sfc_config_cmu_clk_sel(CMU_CLK_SEL_80M); + } +#endif + + flash_info_print("hi_flash_erase ret:%x addr:%x len:%x\r\n", ret, flash_addr, flash_erase_size); + return ret; +} + +hi_u32 hi_flash_write(hi_u32 flash_addr, hi_u32 flash_write_size, const hi_u8 *flash_write_data, hi_bool do_erase) +{ + hi_u32 ret; + hi_spi_flash_ctrl *spif_ctrl = &g_flash_drv_ctrl; + if (flash_write_data == HI_NULL) { + return HI_ERR_FLASH_INVALID_PARAMETER; + } + ret = sfc_check_para(spif_ctrl, flash_addr, flash_write_size, HI_FLASH_CHECK_PARAM_OPT_WRITE); + if (ret != HI_ERR_SUCCESS) { + return ret; + } +#ifdef HI_FLASH_SUPPORT_REF_VBAT + if ((g_voltage <= HI_FLASH_VOLTAGE_TH0) && (memcmp(g_flash_vlt_sfc_info.chip_id, + g_flash_vlt_sfc_info_tbl[2].chip_id, HI_FLASH_CHIP_ID_NUM) == HI_ERR_SUCCESS)) { // 2 + sfc_config_cmu_clk_sel(CMU_CLK_SEL_48M); + } +#endif + ret = flash_write_prv(spif_ctrl, flash_addr, flash_write_data, flash_write_size, do_erase); +#ifdef HI_FLASH_SUPPORT_REF_VBAT + if ((g_voltage <= HI_FLASH_VOLTAGE_TH0) && (memcmp(g_flash_vlt_sfc_info.chip_id, + g_flash_vlt_sfc_info_tbl[2].chip_id, HI_FLASH_CHIP_ID_NUM) == HI_ERR_SUCCESS)) { // 2 + sfc_config_cmu_clk_sel(CMU_CLK_SEL_80M); + } +#endif + flash_info_print("hi_flash_write ret:%x addr:%x len:%x\r\n", ret, flash_addr, flash_write_size); + return ret; +} + +hi_u32 hi_flash_read(hi_u32 flash_addr, hi_u32 flash_read_size, hi_u8 *flash_read_data) +{ + hi_u32 ret; + hi_spi_flash_ctrl *spif_ctrl = &g_flash_drv_ctrl; + if (flash_read_data == HI_NULL) { + return HI_ERR_FLASH_INVALID_PARAMETER; + } + ret = sfc_check_para(spif_ctrl, flash_addr, flash_read_size, HI_FLASH_CHECK_PARAM_OPT_READ); + if (ret != HI_ERR_SUCCESS) { + return ret; + } +#ifdef HI_FLASH_SUPPORT_REF_VBAT + if ((g_voltage <= HI_FLASH_VOLTAGE_TH0) && (memcmp(g_flash_vlt_sfc_info.chip_id, + g_flash_vlt_sfc_info_tbl[2].chip_id, HI_FLASH_CHIP_ID_NUM) == HI_ERR_SUCCESS)) { // 2 + sfc_config_cmu_clk_sel(CMU_CLK_SEL_48M); + } +#endif + ret = flash_read_prv(spif_ctrl, flash_addr, flash_read_data, flash_read_size); +#ifdef HI_FLASH_SUPPORT_REF_VBAT + if ((g_voltage <= HI_FLASH_VOLTAGE_TH0) && (memcmp(g_flash_vlt_sfc_info.chip_id, + g_flash_vlt_sfc_info_tbl[2].chip_id, HI_FLASH_CHIP_ID_NUM) == HI_ERR_SUCCESS)) { // 2 + sfc_config_cmu_clk_sel(CMU_CLK_SEL_80M); + } +#endif + flash_info_print("hi_flash_read ret2:%x addr:%x len:%x\r\n", ret, flash_addr, flash_read_size); + return ret; +} + +hi_u32 flash_init_cfg(hi_spi_flash_ctrl *spif_ctrl, const hi_u8 *chip_id, hi_u32 idlen) +{ + hi_u32 ret; + + if ((spif_ctrl == HI_NULL) || (chip_id == HI_NULL) || (idlen != HI_FLASH_CHIP_ID_NUM)) { + return HI_ERR_FAILURE; + } + flash_clk_config(); +#ifdef HI_FLASH_SUPPORT_REF_VBAT + /* set voltage vs. frequency */ + sfc_config_set_experience(chip_id, &g_flash_vlt_sfc_info, g_flash_vlt_sfc_info_tbl, + sizeof(g_flash_vlt_sfc_info_tbl) / sizeof(g_flash_vlt_sfc_info_tbl[0])); + sfc_config_update_freq((hi_u32)(uintptr_t)&g_flash_vlt_sfc_info); +#endif + /* temply compatible with MX flash chip at FPGA debug phase. */ + if (chip_id[0] == 0xC2 && chip_id[1] == 0x20 && chip_id[2] == 0x19) { /* check chip id 0,1,2 byte */ + ret = spi_flash_enable_quad_mode_mx(); + } else { + ret = spi_flash_enable_quad_mode(); + } + hi_io_set_pull(HI_IO_NAME_SFC_IO2, HI_IO_PULL_NONE); + hi_io_set_pull(HI_IO_NAME_SFC_IO3, HI_IO_PULL_NONE); + if (ret == HI_ERR_SUCCESS) { + hi_u32 cs; +#ifdef HI_FLASH_SUPPORT_REF_VBAT + if ((g_voltage <= HI_FLASH_VOLTAGE_TH0) && + (memcmp(chip_id, g_flash_vlt_sfc_info_tbl[2].chip_id, HI_FLASH_CHIP_ID_NUM) == HI_ERR_SUCCESS)) { /* 2 wb */ + cs = ((uintptr_t)&spif_ctrl->opt_read) ^ sizeof(spi_flash_operation) ^ + ((uintptr_t)&g_spi_opt_fast_quad_out_read) ^ sizeof(spi_flash_operation); + if (memcpy_s(&spif_ctrl->opt_read, sizeof(spi_flash_operation), &g_spi_opt_fast_quad_out_read, + sizeof(spi_flash_operation), cs) != EOK) { + return HI_ERR_FAILURE; + } + } else { + cs = ((uintptr_t)&spif_ctrl->opt_read) ^ sizeof(spi_flash_operation) ^ + ((uintptr_t)&g_spi_opt_fast_quad_eb_out_read) ^ sizeof(spi_flash_operation); + if (memcpy_s(&spif_ctrl->opt_read, sizeof(spi_flash_operation), &g_spi_opt_fast_quad_eb_out_read, + sizeof(spi_flash_operation), cs) != EOK) { + return HI_ERR_FAILURE; + } + } +#else + cs = ((uintptr_t)&spif_ctrl->opt_read) ^ sizeof(spi_flash_operation) ^ + ((uintptr_t)&g_spi_opt_fast_quad_eb_out_read) ^ sizeof(spi_flash_operation); + if (memcpy_s(&spif_ctrl->opt_read, sizeof(spi_flash_operation), &g_spi_opt_fast_quad_eb_out_read, + sizeof(spi_flash_operation), cs) != EOK) { + return HI_ERR_FAILURE; + } +#endif + } + /* config flash sfc after flash init. */ + spif_config(&(spif_ctrl->opt_read), spif_ctrl->opt_read.cmd, HI_TRUE); + return ret; +} + +hi_u32 hi_flash_init(hi_void) +{ + hi_u32 ret; + hi_spi_flash_ctrl *spif_ctrl = &g_flash_drv_ctrl; + hi_u8 chip_id[HI_FLASH_CHIP_ID_NUM] = {0}; + hi_u32 sfc_clock; + + if (spif_ctrl->is_inited == HI_TRUE) { + return HI_ERR_FLASH_RE_INIT; + } + + spif_ctrl->dma_ram_buffer = (hi_u8*)g_dma_buffer; + spif_ctrl->dma_ram_size = FLASH_DMA_RAM_SIZE; + spif_ctrl->back_up_buf = (hi_u8 *)g_back_buffer; + ret = spi_flash_basic_info_probe(spif_ctrl, chip_id, HI_FLASH_CHIP_ID_NUM, + (hi_spi_flash_basic_info*)g_flash_default_info_tbl, HI_FLASH_DEFAULT_TYPE_NUM); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + ret = flash_init_cfg(spif_ctrl, chip_id, HI_FLASH_CHIP_ID_NUM); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + spif_ctrl->is_inited = HI_TRUE; + + if (chip_id[0] == 0xC2 && chip_id[1] == 0x20 && chip_id[2] == 0x19) { /* check chip id 0,1,2 byte */ + sfc_clock = hisfc_read(SFC_REG_GLOBAL_CONFIG); + sfc_clock = sfc_clock & 0xFFFFFFE7; + sfc_clock = sfc_clock | 0x08; + hisfc_write(SFC_REG_GLOBAL_CONFIG, sfc_clock); + } + hisfc_write(SFC_REG_TIMING, 0x1); + + return ret; +} + diff --git a/sdk_liteos/boot/loaderboot/drivers/lsadc/SConscript b/sdk_liteos/boot/loaderboot/drivers/lsadc/SConscript new file mode 100755 index 0000000000000000000000000000000000000000..aceb2b6a9464ce64030c1f9c5374ec933dcab384 --- /dev/null +++ b/sdk_liteos/boot/loaderboot/drivers/lsadc/SConscript @@ -0,0 +1,6 @@ +Import('env') + +env = env.Clone() + +objs = env.Object(Glob('*.c')) +Return('objs') diff --git a/sdk_liteos/boot/loaderboot/drivers/lsadc/adc_drv.c b/sdk_liteos/boot/loaderboot/drivers/lsadc/adc_drv.c new file mode 100644 index 0000000000000000000000000000000000000000..b4b0c875d62f34b55adb4967168e8c2a8b4c8df0 --- /dev/null +++ b/sdk_liteos/boot/loaderboot/drivers/lsadc/adc_drv.c @@ -0,0 +1,119 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "adc_drv.h" + +#include + +hi_bool adc_fifo_is_empty(hi_void) +{ + hi_u32 reg_val = hi_reg_read_val32(REG_ADC_SR); + if (reg_val & ADC_SR_RNE) { + return HI_FALSE; + } + return HI_TRUE; +} + +hi_void adc_scan_stop(hi_void) +{ + hi_reg_write(REG_ADC_STOP, ADC_SCAN_STOP); + hi_reg_write(REG_ADC_IMSC, ADC_ISR_DISABLE); + while (adc_fifo_is_empty() == HI_FALSE) { + (hi_void)hi_reg_read_val32(REG_ADC_DR); + } +} + +#define hi_reg_getbits16(addr, pos, bits) ((hi_reg_read_val16(addr) >> (pos)) & (((unsigned short)1 << (bits)) - 1)) +#define GLB_CTL_REFCLK_FEQ_START_BIT 0 +#define GLB_CTL_REFCLK_FEQ_BITS 1 + + +hi_u32 get_ref_voltage(hi_u16 *voltage) +{ + hi_u16 data = 0; + hi_u16 reg_val; + hi_u16 timeout_cnt = 0; + /* set adc clk div */ + hi_reg_read16(LS_ADC_CLK_DIV1_REG, reg_val); + reg_val &= ~(0xF << LS_ADC_CLK_DIV1_OFFSET); + if (hi_reg_getbits16(GLB_CTL_REFCLK_FEQ_STATUS_REG, GLB_CTL_REFCLK_FEQ_START_BIT, GLB_CTL_REFCLK_FEQ_BITS)) { + reg_val |= (0x7 << LS_ADC_CLK_DIV1_OFFSET); + } else { + reg_val |= (0xC << LS_ADC_CLK_DIV1_OFFSET); + } + hi_reg_write16(LS_ADC_CLK_DIV1_REG, reg_val); + /* adc power on */ + hi_reg_write(REG_ADC_EN, ADC_POWER_OFF); + udelay(1); + hi_reg_write(REG_ADC_EN, ADC_POWER_ON); + /* set basic info */ + /* + channel: 0x80 << 0 + equ_model_sel: 0x2 << 8 + rst_cnt: 0xF << 12 + adc_cfg->cur_bais: 0 << 24 + fifo_water_line: 0x6 + */ + hi_reg_write(REG_ADC_CFG, 0xf280); /* 0xf280 */ + hi_reg_write(REG_ADC_FIFO_CFG, 0x6); + /* determine is busy */ + if (hi_reg_read_val32(REG_ADC_SR) & ADC_SR_BSY) { + adc_scan_stop(); + } + /* start scan */ + hi_reg_write(REG_ADC_START, ADC_SCAN_START); + while (timeout_cnt < ADC_PER_DATA_TIMEOUT_CNT) { + if (!adc_fifo_is_empty()) { + data = (hi_u16)hi_reg_read_val32(REG_ADC_DR); + break; + } + timeout_cnt++; + udelay(ADC_LOOP_DELAY_US); + } + adc_scan_stop(); + hi_reg_write(REG_ADC_EN, ADC_POWER_OFF); /* POWER DOWN */ + if (timeout_cnt >= ADC_PER_DATA_TIMEOUT_CNT) { + return HI_ERR_TIMEOUT; + } + data = data & 0xFFF; /* 0xFFF Obtains the lower 12 bits.CNcomment:获取低12bit数据位 */ + *voltage = ((hi_u32)data * 180) >> 10; /* bypass:180, flashLDO: 171 = 180*0.95,coefficients: 10 Units: 0.01V */ + return HI_ERR_SUCCESS; +} + +hi_u32 get_average_ref_vlt(hi_u16 *voltage) +{ + hi_u32 ret; + hi_u16 vlt; + hi_u32 vlt_total = 0; + ret = get_ref_voltage(&vlt); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + vlt_total += vlt; + ret = get_ref_voltage(&vlt); + if (ret != HI_ERR_SUCCESS) { + *voltage = (hi_u16) vlt_total; + return HI_ERR_SUCCESS; + } + vlt_total += vlt; + ret = get_ref_voltage(&vlt); + if (ret != HI_ERR_SUCCESS) { + *voltage = (hi_u16) (vlt_total>>1); + return HI_ERR_SUCCESS; + } + vlt_total += vlt; + *voltage = (hi_u16) ((vlt_total) / 3); /* 3 */ + return HI_ERR_SUCCESS; +} diff --git a/sdk_liteos/boot/loaderboot/fixed/include/load.h b/sdk_liteos/boot/loaderboot/fixed/include/load.h new file mode 100644 index 0000000000000000000000000000000000000000..7e3a335d092baf7253221d75080f0d0209b329e5 --- /dev/null +++ b/sdk_liteos/boot/loaderboot/fixed/include/load.h @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __LOAD_H__ +#define __LOAD_H__ + +#include + +extern hi_char *g_ymodem_buf; +hi_u32 load_malloc_init(hi_void); +hi_s32 load_malloc_deinit(hi_void); +hi_u32 load_serial_ymodem(hi_u32 offset, hi_u32 *addr, hi_u32 check_sum); + +#endif diff --git a/sdk_liteos/boot/loaderboot/fixed/include/secure.h b/sdk_liteos/boot/loaderboot/fixed/include/secure.h new file mode 100644 index 0000000000000000000000000000000000000000..c69a174a189889cc7d4252a4e4be7db703d967dc --- /dev/null +++ b/sdk_liteos/boot/loaderboot/fixed/include/secure.h @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __BOOT_ROM_SECURE_H__ +#define __BOOT_ROM_SECURE_H__ + +#define RSA_4096_LENGTH 512 +#define RSA_2048_LENGTH 256 + +#define SHA_256_LENGTH 32 +#define ECC_32_BYTES 32 +#define ECC_64_BYTES 64 + +#define HI_FIRST_CHAR_TIMEOUT 0x80002001 + +#endif diff --git a/sdk_liteos/boot/loaderboot/fixed/include/serial_dw.h b/sdk_liteos/boot/loaderboot/fixed/include/serial_dw.h new file mode 100644 index 0000000000000000000000000000000000000000..45e9c39e7ccf915939e318d6ed2b9cf378ede5da --- /dev/null +++ b/sdk_liteos/boot/loaderboot/fixed/include/serial_dw.h @@ -0,0 +1,131 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __SERIAL_DW_H__ +#define __SERIAL_DW_H__ + +#include + +/* UART register OFFSET */ +#define UART_DR 0x0 +#define UART_RSR_ECR 0x04 +#define UART_FR 0x18 +#define UART_ILPR 0x20 +#define UART_IBRD 0x24 +#define UART_FBRD 0x28 +#define UART_LCR_H 0x2C +#define UART_CR 0x30 +#define UART_IFLS 0x34 +#define UART_IMSC 0x38 +#define UART_RIS 0x3C +#define UART_MIS 0x40 +#define UART_ICR 0x44 +#define UART_DMACR 0x48 + +#define UARTFR_TXFE_MASK 0x80 +#define UARTFR_RXFF_MASK 0x40 +#define UARTFR_TXFF_MASK 0x20 +#define UARTFR_RXFE_MASK 0x10 +#define UARTFR_BUSY_MASK 0x04 +#define UARTDR_DATA_MASK 0xFF + +#define UARTLCR_H_CFG 0x60 /* 8bit, no parity, FIFO disable */ +#define UARTLCR_H_CFG_ODD 0x72 /* 8bit, odd parity,FIFO enable */ +#define UARTLCR_H_CFG_FIFO 0x70 /* 8bit, no parity, FIFO enable */ +#define UARTCR_CFG 0x301 /* UART tx enable, rx enable, uart enable */ +#define UARTCR_CFG_FLOWENABLE 0xC301 /* UART tx enable, rx enable, uart enable, flow control enable */ +#define UARTCR_RTX_FC_SHIFT 14 +#define UARTCR_CTX_FC_SHIFT 15 +#define UARTIMSC_CFG 0x0 /* Disable all uart interrupt */ +#define UARTIMSC_CFG_INT 0x50 /* enable rx time out interrupt */ +#define UARTIFS_CFG 0x10A /* FIFO water mark:Rx 16 Tx 32 RTS 56 */ +#define UARTIFS_RXFF_SHIFT 3 +#define UARTIFS_RTSFF_SHIFT 6 + +#define UART_DMA_ENABLE 0X03 +#define UART_DMA_DISABLE 0X04 +#define UARTICR_CFG 0x7FF /* Clear up all uart interrupt */ + +typedef struct { + hi_u32 baudrate; + hi_u16 ibrd; + hi_u16 fbrd; +} hi_uart_brd; +typedef enum { + HI_UART_BRD_IDX_1200 = 0, + HI_UART_BRD_IDX_2400 = 1, + HI_UART_BRD_IDX_9600 = 2, + HI_UART_BRD_IDX_19200 = 3, + HI_UART_BRD_IDX_115200 = 4, + HI_UART_BRD_IDX_230400 = 5, + HI_UART_BRD_IDX_460800 = 6, + HI_UART_BRD_IDX_921600 = 7, + HI_UART_BRD_IDX_1000000 = 8, + HI_UART_BRD_IDX_1024000 = 9, + HI_UART_BRD_IDX_1500000 = 10, + HI_UART_BRD_IDX_1536000 = 11, + HI_UART_BRD_IDX_2000000 = 12, + HI_UART_BRD_IDX_2048000 = 13, + HI_UART_BRD_IDX_2252800 = 14, + HI_UART_BRD_IDX_2304000 = 15, + HI_UART_BRD_IDX_2500000 = 16, + HI_UART_BRD_IDX_2560000 = 17, + HI_UART_BRD_IDX_3000000 = 18, + HI_UART_BRD_IDX_3072000 = 19, + HI_UART_BRD_IDX_3500000 = 20, + HI_UART_BRD_IDX_3584000 = 21, + HI_UART_BRD_IDX_3840000 = 22, + HI_UART_BRD_IDX_4000000 = 23, + HI_UART_BRD_IDX_4096000 = 24, + HI_UART_BRD_IDX_4500000 = 25, + HI_UART_BRD_IDX_4608000 = 26, + HI_UART_BRD_IDX_5000000 = 27, + HI_UART_BRD_IDX_6000000 = 28, + HI_UART_BRD_IDX_MAX, +} hi_uart_brd_idx_e; + +typedef enum { + HI_UART_BRD_1200 = 1200, + HI_UART_BRD_2400 = 2400, + HI_UART_BRD_9600 = 9600, + HI_UART_BRD_19200 = 19200, + HI_UART_BRD_115200 = 115200, + HI_UART_BRD_230400 = 230400, + HI_UART_BRD_460800 = 460800, + HI_UART_BRD_921600 = 921600, + HI_UART_BRD_1000000 = 1000000, + HI_UART_BRD_1024000 = 1024000, + HI_UART_BRD_1500000 = 1500000, + HI_UART_BRD_1536000 = 1536000, + HI_UART_BRD_2000000 = 2000000, + HI_UART_BRD_2048000 = 2048000, + HI_UART_BRD_2252800 = 2252800, + HI_UART_BRD_2304000 = 2304000, + HI_UART_BRD_2500000 = 2500000, + HI_UART_BRD_2560000 = 2560000, + HI_UART_BRD_3000000 = 3000000, + HI_UART_BRD_3072000 = 3072000, + HI_UART_BRD_3500000 = 3500000, + HI_UART_BRD_3584000 = 3584000, + HI_UART_BRD_3840000 = 3840000, + HI_UART_BRD_4000000 = 4000000, + HI_UART_BRD_4096000 = 4096000, + HI_UART_BRD_4500000 = 4500000, + HI_UART_BRD_4608000 = 4608000, + HI_UART_BRD_5000000 = 5000000, + HI_UART_BRD_6000000 = 6000000, +} hi_uart_baudrate_e; +hi_u32 set_uart_param(uart_param_stru uart_param); +#endif diff --git a/sdk_liteos/boot/loaderboot/fixed/include/uart_auth.h b/sdk_liteos/boot/loaderboot/fixed/include/uart_auth.h new file mode 100644 index 0000000000000000000000000000000000000000..b44c5cd48dcbebbae42f490cd60c5f23d3802889 --- /dev/null +++ b/sdk_liteos/boot/loaderboot/fixed/include/uart_auth.h @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __UART_AUTH_H__ +#define __UART_AUTH_H__ + +#include +#include "hi_boot_rom.h" +#include + +#define UART_PACKET_START_FLAG 0xDEADBEEF + +#define UART_PACKET_PAYLOAD_MAX 1024 + +HI_EXTERN uart_param_stru g_uart_param; +HI_EXTERN hi_u32 g_uart_int_type; + +enum { + UART_TYPE_ROMBOOT_HANDSHAKE = 0xF0, + UART_TYPE_ACK = 0xE1, + UART_TYPE_FILE_START = 0xD2, + UART_TYPE_FILE_END = 0xC3, + UART_TYPE_CMD = 0xB4, + UART_TYPE_DATA = 0xA5, + UART_TYPE_FLASHBOOT_HANDSHAKE = 0x0F, +}; + +typedef struct { + hi_u32 start_flag; /* start flag: 0xDEADBEEF */ + hi_u16 packet_size; /* Packet length: actual length of data to be transmitted. + The length cannot exceed 1024 bytes. + CNcomment:报文长度:真实传输数据长度,要求不超过1024 */ + hi_u8 type; /* Packet Type。CNcomment:报文类型 */ + hi_u8 pad; +} packet_data_head; + +typedef struct { + packet_data_head head; + hi_u8 payload[UART_PACKET_PAYLOAD_MAX]; /**< Packet data */ + hi_u16 check_sum; /* Checksum */ + hi_u8 rev[2]; /* 2: rev */ +} packet_data_info; + +/* UART AUTH context */ +typedef struct { + hi_u8 status; + hi_u8 pad; + hi_u16 received; + packet_data_info packet; +} uart_ctx; + +hi_u32 uart_process(hi_uart uart, hi_u32 interrupt_timeout_ms); + +#endif /* __UART_AUTH_H__ */ diff --git a/sdk_liteos/boot/loaderboot/fixed/include/ymodem.h b/sdk_liteos/boot/loaderboot/fixed/include/ymodem.h new file mode 100644 index 0000000000000000000000000000000000000000..7f796a3d27b501d5e7876a03be1dc8a5ccaddf70 --- /dev/null +++ b/sdk_liteos/boot/loaderboot/fixed/include/ymodem.h @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __YMODEM_H__ +#define __YMODEM_H__ + +#include +#define LOADER_RAM_TEXT __attribute__ ((section(".ram.text"))) + +hi_u32 ymodem_open(hi_void); +hi_void ymodem_close(hi_void); +hi_u32 ymodem_read(hi_char* buf, hi_u32 size, hi_u32 cs); +hi_u32 ymodem_get_length(hi_void); +hi_u32 loader_ymodem_open(hi_void); + +#endif + diff --git a/sdk_liteos/boot/loaderboot/include/cmd_loop.h b/sdk_liteos/boot/loaderboot/include/cmd_loop.h new file mode 100644 index 0000000000000000000000000000000000000000..ff4df3f25b245d5211fdf264210b06651b44151e --- /dev/null +++ b/sdk_liteos/boot/loaderboot/include/cmd_loop.h @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __CMD_LOOP_H__ +#define __CMD_LOOP_H__ + +#include + +#define ACK_SUCCESS 0x5A +#define ACK_FAILURE 0xA5 + +enum { + CMD_ACK = 0xE1, + CMD_DL_IMAGE = 0xD2, + CMD_BURN_EFUSE = 0xC3, + CMD_UL_DATA = 0xB4, + CMD_READ_EFUSE = 0xA5, + CMD_FLASH_PROTECT = 0x96, + CMD_RESET = 0x87, + CMD_FACTORY_IMAGE = 0x78, + CMD_VERSION = 0x69 +}; + +#define LOADER_CMD_MAX 8 + +hi_u32 loader_download_image(const uart_ctx *cmd_ctx); +hi_u32 loader_burn_efuse(const uart_ctx *cmd_ctx); +hi_u32 loader_upload_data(const uart_ctx *cmd_ctx); +hi_u32 loader_read_efuse(const uart_ctx *cmd_ctx); +hi_u32 loader_flash_protect(const uart_ctx *cmd_ctx); +hi_u32 loader_reset(const uart_ctx *cmd_ctx); +hi_u32 loader_burn_version(const uart_ctx *cmd_ctx); +uart_ctx *cmd_loop_init(hi_void); +hi_u32 cmd_loop_deinit(hi_void); +hi_void cmd_loop(uart_ctx *ctx); +hi_void loader_ack(hi_u8 err_code); + +extern void *__nmi_stack_top; /* defined in link scripts. */ +extern void *__nmi_stack_bottom; /* defined in link scripts. */ +#define bit_set(x, i, b) ((x) = (hi_u8)((b) ? ((1 << (i)) | (x)) : ((~(hi_u8)(1 << (i))) & (x)))) +#define bit_get(x, i) (((1 << (i)) & (x)) ? 1 : 0) +#define SRV_BIT_LOW 0 +#define SRV_BIT_HIGH 1 + +#endif /* __CMD_LOOP_H__ */ + diff --git a/sdk_liteos/boot/loaderboot/include/crc.h b/sdk_liteos/boot/loaderboot/include/crc.h new file mode 100644 index 0000000000000000000000000000000000000000..69763fa534d9c22e92e50dc2ba471bb5c0a461fa --- /dev/null +++ b/sdk_liteos/boot/loaderboot/include/crc.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __CRC_H__ +#define __CRC_H__ + +hi_u16 crc16_ccitt(hi_u16 crc_start, hi_u8* buf, hi_u32 len, hi_u32 check_sum); +#endif + diff --git a/sdk_liteos/boot/loaderboot/include/efuse.h b/sdk_liteos/boot/loaderboot/include/efuse.h new file mode 100644 index 0000000000000000000000000000000000000000..07bd59b592b9786cefa91add2c044c2bb9e1fc11 --- /dev/null +++ b/sdk_liteos/boot/loaderboot/include/efuse.h @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __EFUSE_H__ +#define __EFUSE_H__ +#include "efuse_drv.h" + +#define EIGHT_BITS 8 +#define THREE_BITS_OFFSET 3 +#define SIZE_8_BITS 8 +#define SIZE_16_BITS 16 +#define SIZE_24_BITS 24 +#define SIZE_32_BITS 32 +#define SIZE_64_BITS 64 +#define SIZE_72_BITS 72 +#define DATA_LENGTH 4 + +hi_u32 efuse_bits_read(hi_u16 start_bit, hi_u16 size, hi_u8 *data, hi_u32 data_len); +hi_u32 efuse_bits_write(hi_u16 start_bit, hi_u16 size, const hi_u8 *key_data); + +#endif /* __EFUSE_H__ */ + diff --git a/sdk_liteos/boot/loaderboot/include/efuse_drv.h b/sdk_liteos/boot/loaderboot/include/efuse_drv.h new file mode 100644 index 0000000000000000000000000000000000000000..7893599334d589e0b01f7ebf71302bfc16f6c6cd --- /dev/null +++ b/sdk_liteos/boot/loaderboot/include/efuse_drv.h @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __EFUSE_DRV_H__ +#define __EFUSE_DRV_H__ +#include + +typedef struct { + hi_u16 id_start_bit; + hi_u16 id_size; + hi_u8 attr; +} hi_efuse_stru; + +#define EFUSE_PGM_EN (HI_EFUSE_REG_BASE + 0x0) +#define EFUSE_PGM_ADDR (HI_EFUSE_REG_BASE + 0x4) +#define EFUSE_RD_EN (HI_EFUSE_REG_BASE + 0x8) +#define EFUSE_RD_ADDR (HI_EFUSE_REG_BASE + 0xc) +#define EFUSE_STATUS (HI_EFUSE_REG_BASE + 0x10) +#define EFUSE_RDATA (HI_EFUSE_REG_BASE + 0x14) + +#define EFUSE_WRITE_READY_STATUS (1 << 0) +#define EFUSE_READ_READY_STATUS (1 << 1) +#define EFUSE_STATUS_MASK (0x7 << 2) +#define EFUSE_PO_STATUS_READY (0x1 << 2) +#define EFUSE_STATUS_READY (0x1 << 4) + +#define EFUSE_CTRL_ST (0x1 << 5) +#define EFUSE_EN_SWITCH (1 << 0) +#define EFUSE_EN_OK 0 + +#define EFUSE_STATUS_RD (1 << 1) +#define EFUSE_8_BIT 8 +#define EFUSE_KEY_LOCK_BIT 2 + +#define EFUSE_TIMEOUT_DEFAULT 1000000 +#define EFUSE_TIMECNT_TICK 10 + +#define EFUSE_PGM_ADDR_SIZE 2048 +#define EFUSE_USER_RESEVED_START_BIT 1884 +#define EFUSE_USER_RESEVED_END_BIT 2011 +#define EFUSE_LOCK_START_BITS 2012 +#define EFUSE_LOCK_FIELD2_START_BITS 235 +#define EFUSE_LOCK_SIZE 36 +#define EFUSE_LOCK_FIELD2_SIZE 5 +#define EFUSE_MAX_INDEX_SIZE 32 + +#define EFUSE_IDX_NRW 0x0 +#define EFUSE_IDX_RO 0x1 +#define EFUSE_IDX_WO 0x2 +#define EFUSE_IDX_RW 0x3 + +hi_efuse_stru *get_efuse_cfg(hi_void); +hi_void get_efuse_cfg_by_id(hi_efuse_idx idx, hi_u16 *start_bit, hi_u16 *size, hi_u8 *attr); +hi_u32 efuse_read_bits(hi_u16 start_bit, hi_u16 size, hi_u8 *key_data); +hi_u32 efuse_write_bits(hi_u16 start_bit, hi_u16 size, const hi_u8 *key_data, hi_u8 *err_state); + +#endif /* __EFUSE_H__ */ diff --git a/sdk_liteos/boot/loaderboot/include/efuse_opt.h b/sdk_liteos/boot/loaderboot/include/efuse_opt.h new file mode 100644 index 0000000000000000000000000000000000000000..916d7be743805cf3642bc5d45dc21da74ea13ca9 --- /dev/null +++ b/sdk_liteos/boot/loaderboot/include/efuse_opt.h @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __EFUSE_OPT_H__ +#define __EFUSE_OPT_H__ +#include + +#define EFUSE_MAX_INDEX_SIZE 32 +#define EFUSE_BIT_NUM 2048 +#define SIZE_32_BITS 32 +#define SIZE_64_BITS 64 +#define SHIFT_5_BITS 5 +#define SHA_256_LENGTH 32 +#define EFUSE_CFG_MAX_LEN 1320 +#define EFUSE_CFG_MIN_LEN 48 +#define U32_PER_LINE 4 +#define EFUSE_READ_MAX_BITS 256 + +typedef struct { + hi_u8 hash[SHA_256_LENGTH]; /* hash of configuration file. */ + hi_u8 stru_ver; /* default 0. */ + hi_u8 stru_size; /* sizeof(struct otp_config_header). */ + hi_u16 number; /* Item number to be burn. */ + hi_u32 file_size; /* Configuration file size. */ + hi_u32 reserved[2]; /* Reserved 2 u32. */ + hi_u8 data[0]; /* Item: size = file_size - stru_size. */ +} efuse_config_header; + +typedef struct { + hi_u8 stru_ver; /* default 0. */ + hi_u8 stru_size; /* sizeof(struct otp_config_item) */ + hi_u16 start_bit; /* Start bit of OTP */ + hi_u16 bit_width; /* Bit width */ + hi_u16 value_len; /* Length of value Byte(s), 4-byte-aligned. */ + hi_u8 value[0]; /* Item, offset: stru_size. */ +} efuse_config_item; + +hi_u32 efuse_burn(uintptr_t file_addr, hi_u32 file_len); +hi_u32 efuse_read(hi_u16 start_bit, hi_u16 size); +hi_u8 get_writeable_encpt_cnt(hi_void); + +#endif diff --git a/sdk_liteos/boot/loaderboot/include/hi_boot_rom.h b/sdk_liteos/boot/loaderboot/include/hi_boot_rom.h new file mode 100755 index 0000000000000000000000000000000000000000..32ace7c8d7620b91d536365eb47f8bdfbd48e62a --- /dev/null +++ b/sdk_liteos/boot/loaderboot/include/hi_boot_rom.h @@ -0,0 +1,1446 @@ +/* + * @file hi_boot_rom.h + * + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** @defgroup iot_romboot BootRom */ +#ifndef _HI_BOOT_ROM_H_ +#define _HI_BOOT_ROM_H_ +#include +#include +#include +#include + +/** @defgroup iot_reg Registers APIs +* @ingroup iot_romboot +*/ +/** +* @ingroup iot_reg +* +*/ +#define hi_reg_write(addr, val) (*(volatile hi_u32*)(uintptr_t)(addr) = (val)) + +/** +* @ingroup iot_reg +* +*/ +#define hi_reg_read(addr, val) ((val) = *(volatile hi_u32*)(uintptr_t)(addr)) + +/** +* @ingroup iot_reg +* +*/ +#define hi_reg_write16(addr, val) (*(volatile hi_u16*)(uintptr_t)(addr) = (val)) + +/** +* @ingroup iot_reg +* +*/ +#define hi_reg_read16(addr, val) ((val) = *(volatile hi_u16*)(uintptr_t)(addr)) + +/** +* @ingroup iot_reg +* +*/ +#define hi_reg_read_val32(addr) (*(volatile hi_u32*)(uintptr_t)(addr)) + +/** +* @ingroup iot_reg +* +*/ +#define hi_reg_read_val16(addr) (*(volatile hi_u16*)(uintptr_t)(addr)) + +/** +* @ingroup iot_reg +* +*/ +#define hi_reg_setbitmsk(addr, msk) ((hi_reg_read_val32(addr)) |= (msk)) + +/** +* @ingroup iot_reg +* +*/ +#define hi_reg_clrbitmsk(addr, msk) ((hi_reg_read_val32(addr)) &= ~(msk)) + +/** +* @ingroup iot_reg +* +*/ +#define hi_reg_clrbit(addr, pos) ((hi_reg_read_val32(addr)) &= ~((hi_u32)(1) << (pos))) + +/** +* @ingroup iot_reg +* +*/ +#define hi_reg_setbit(addr, pos) ((hi_reg_read_val32(addr)) |= ((hi_u32)(1) << (pos))) + +/** +* @ingroup iot_reg +* +*/ +#define hi_reg_clrbits(addr, pos, bits) (hi_reg_read_val32(addr) &= ~((((hi_u32)1 << (bits)) - 1) << (pos))) + +/** +* @ingroup iot_reg +* +*/ +#define hi_reg_clrbits16(addr, pos, bits) (hi_reg_read_val16(addr) &= ~((((unsigned short)1 << (bits)) - 1) << (pos))) + +/** +* @ingroup iot_reg +* +*/ +#define hi_reg_clrbit16(addr, pos) ((hi_reg_read_val16(addr)) &= ~((unsigned short)(1) << (pos))) + +/** +* @ingroup iot_reg +* +*/ +#define hi_reg_setbit16(addr, pos) ((hi_reg_read_val16(addr)) |= ((unsigned short)(1) << (pos))) + +/** @defgroup iot_time time APIs +* @ingroup iot_romboot +*/ +/** +* @ingroup iot_time +* @brief Delay, in microseconds.CNcomment:延时,毫秒级。CNend +* +* @par 描述: +* Delay operation implemented by software based on the system clock, blocking the CPU. +CNcomment:延时操作,阻塞CPU。CNend +* +* @attention None +* +* @param msecs [IN] type #hi_u32,delay period (unit: millisecond). +CNcomment:延时时间(单位:ms)。CNend +* +* @retval None +* @par 依赖: +* @li hi_boot_rom.h:Describes BootRom APIs.CNcomment:文件包含BootRom相关接口。CNend +* @see None +*/ +hi_void mdelay(hi_u32 msecs); + +/** +* @ingroup iot_time +* @brief Delay, in microseconds.CNcomment:延时,微秒级。CNend +* +* @par 描述: +* Delay operation implemented by software based on the system clock, blocking the CPU. +CNcomment:延时操作,阻塞CPU。CNend +* +* @attention None +* +* @param usecs [IN] type #hi_u32,delay period (unit: microsecond). +CNcomment:延时时间(单位:μs)。CNend +* +* @retval None +* @par 依赖: +* @li hi_boot_rom.h:Describes BootRom APIs.CNcomment:文件包含BootRom相关接口。CNend +* @see None +*/ +hi_void udelay(hi_u32 usecs); + +extern hi_u32 memcmp(const hi_void *cs, const hi_void *ct, hi_u32 count); + +/** @defgroup iot_secure_c Secure C library APIs +* @ingroup iot_romboot +*/ +/** +* @ingroup iot_secure_c +* @brief Sets the size of the destination buffer to a specific value. +CNcomment:设置目的缓冲区为特定值。CNend +* +* @par 描述: Sets the size of the destination buffer to a specific value. +CNcomment:设置目的缓冲区为特定值。CNend +* @attention None +* +* @param dest [IN] type #hi_void *, Destination buffer.CNcomment:目的缓冲区。CNend +* @param dest_max [IN] type #hi_u32, Size of the destination buffer.CNcomment:目的缓冲区大小。CNend +* @param c [IN] type #hi_u8, Specific value.CNcomment:特定值。CNend +* @param count [IN] type #hi_u32, Number of specific values set in destination buffer. +CNcomment:目的缓冲区设置特定值的个数。CNend +* @param check_sum [IN] type #hi_u32,Exclusive or of the above four parameter values,used as security check. +* example:check_sum = (uintptr_t)dest ^ (uintptr_t)dest_max ^ (uintptr_t)c ^ (uintptr_t)count. +CNcomment:上面4个参数值的异或,用作安全检查, +示例:check_sum = (uintptr_t)dest ^ (uintptr_t)dest_max ^ (uintptr_t)c ^ (uintptr_t)count。CNend +* +* @retval #EOK Success +* @retval #Other Failure +* +* @par 依赖: +* @li hi_boot_rom.h: This file declares the APIs.CNcomment:该接口声明所在的头文件。CNend +* @see None +*/ +hi_u32 memset_s(hi_void *dest, hi_u32 dest_max, hi_u8 c, hi_u32 count, hi_u32 check_sum); + +/** +* @ingroup iot_secure_c +* @brief Copies the data from the source buffer to the destination buffer. +CNcomment:复制源缓冲区的数据到目的缓冲区。CNend +* +* @par 描述: Copies the data from the source buffer to the destination buffer. +CNcomment:复制源缓冲区的数据到目的缓冲区。CNend +* @attention None +* +* @param dest [IN] type #hi_void *, Destination buffer.CNcomment:目的缓冲区。CNend +* @param dest_max [IN] type #hi_u32, Size of the destination buffer.CNcomment:目的缓冲区大小。CNend +* @param src [IN] type #const hi_void *, Source buffer.CNcomment:源缓冲区。CNend +* @param count [IN] type #hi_u32, Number of characters copied from the source buffer. +CNcomment:从源缓冲区中复制的字符数。CNend +* @param check_sum [IN] type #hi_u32,Exclusive or of the above four parameter values,used as security check. +* example:check_sum = (uintptr_t)dest ^ (uintptr_t)dest_max ^ (uintptr_t)src ^ (uintptr_t)count. +CNcomment:上面4个参数值的异或,用作安全检查, +示例:check_sum = (uintptr_t)dest ^ (uintptr_t)dest_max ^ (uintptr_t)src ^ (uintptr_t)count。CNend +* +* @retval #EOK Success +* @retval #Other Failure +* +* @par 依赖: +* @li hi_boot_rom.h: This file declares the APIs.CNcomment:该接口声明所在的头文件。CNend +* @see None +*/ +hi_u32 memcpy_s(hi_void *dest, hi_u32 dest_max, const hi_void *src, hi_u32 count, hi_u32 check_sum); + +/** @defgroup iot_dfx Debug APIs +* @ingroup iot_romboot +*/ +/** + * @ingroup iot_dfx + * + * Print error code type, 0x3615 and its previous value cannot be modified. + CNcomment:打印错误码类型,0x3615及之前的值不可修改。CNend + */ +typedef enum { + HI_PRINT_ERRNO_UART_INIT = 0x3600, /* UART authentication initialization failed */ + HI_PRINT_ERRNO_LOADER_ERR = 0x3601, /* Failed to load loaderboot */ + HI_PRINT_ERRNO_BOOT_DECRYPT_ERR = 0x3602, /* Boot decryption failed */ + HI_PRINT_ERRNO_BOOT_LEN_ERR = 0x3603, /* Boot length check failed */ + HI_PRINT_ERRNO_BOOT_HEAD_ERR = 0x3604, /* Boot header verification failed */ + HI_PRINT_ERRNO_BOOT_SECURE_BOOT_ERR = 0x3605, /* Secure boot read failed */ + HI_PRINT_ERRNO_BOOT_ROOT_KEY_LEN_ERR = 0x3606, /* Rootkye length incorrect */ + HI_PRINT_ERRNO_BOOT_ROOT_KEY_ERR = 0x3607, /* Rootkey certificate failed */ + HI_PRINT_ERRNO_BOOT_READ_ENCPT_ERR = 0x3608, /* Secure flag read failed */ + HI_PRINT_ERRNO_BOOT_SUB_KEY_LEN_ERR = 0x3609, /* Subkey length incorrect */ + HI_PRINT_ERRNO_BOOT_SUB_KEY_CAT_ERR = 0x360A, /* Subkey category is incorrect */ + HI_PRINT_ERRNO_BOOT_SUB_KEY_RSIM_ERR = 0x360B, /* Subkey rsim verification failed */ + HI_PRINT_ERRNO_BOOT_SUB_KEY_ERR = 0x360C, /* Subkey authentication failed */ + HI_PRINT_ERRNO_BOOT_CODE_VERIFY_ERR = 0x360D, /* Code verification failed */ + HI_PRINT_ERRNO_BOOT_DIE_ID_ERR = 0x360E, /* Die ID verification failed */ + HI_PRINT_ERRNO_BOOT_VER_ERR = 0x360F, /* Flash boot version number verification failed */ + HI_PRINT_ERRNO_BOOT_GET_TAIL_ERR = 0x3610, /* Failed to get flash tail address */ + HI_PRINT_ERRNO_BOOT_BACKUP_TAIL_ERR = 0x3611, /* Backup flash boot magic word and length verification failed */ + HI_PRINT_ERRNO_BOOT_MAIN_CHECK_ERR = 0x3612, /* Fail to check the integrity of the main flashboot + in non-secure boot */ + HI_PRINT_ERRNO_BOOT_BACKUP_CHECK_ERR = 0x3613, /* Fail to check the integrity of the backup flashboot + in non-secure boot */ + HI_PRINT_ERRNO_MALLOC_EXAUST_ERR = 0x3614, /* Out of heap memory */ + HI_PRINT_ERRNO_MALLOC_STRUCT_ERR = 0x3615, /* Heap memory management structure destroyed */ + HI_PRINT_ERRNO_NO_ENCPT_CNT_LEFT_ERR = 0x3616, /* Flash encryption burn out times */ + HI_PRINT_ERRNO_CRYPTO_PREPARE_ERR = 0x3617, /* Flash encryption and decryption preparation failed */ + HI_PRINT_ERRNO_CRYPTO_KEY_EMPTY_ERR = 0x3618, /* Flash encryption and decryption work key is empty */ + HI_PRINT_ERRNO_CRYPTO_KEY_INVALID_ERR = 0x3619, /* Flash encryption and decryption work key is invalid */ + HI_PRINT_ERRNO_CRYPTO_KEY_SAVE_ERR = 0x361A, /* Flash encryption and decryption work key save failed */ + HI_PRINT_ERRNO_CRYPTO_KEY_DECRYPT_ERR = 0x361B, /* Flash encryption and decryption work key decryption failed */ + HI_PRINT_ERRNO_CRYPTO_FW_DECRYPT_ERR = 0x361C, /* Flash encryption and decryption kernel decryption failed */ + HI_PRINT_ERRNO_CRYPTO_FW_ENCRYPT_ERR = 0x361D, /* Flash encryption and decryption kernel encryption failed */ + HI_PRINT_ERRNO_CRYPTO_NV_ENCRYPT_ERR = 0x361E, /* Flash encryption and decryption NV area encryption failed */ + HI_PRINT_ERRNO_CRYPTO_CHECK_KERNEL_ERR = 0x361F, /* Flash encryption and decryption check kernel failed */ + HI_PRINT_ERRNO_CRYPTO_KERNEL_ADDR_ERR = 0x3620, /* Flash encryption and decryption check kernel addr failed */ + HI_PRINT_ERRNO_UPG_CRYPTO_PREPARE_ERR = 0x3621, /* Upg file decryption preparation failed */ + HI_PRINT_ERRNO_UPG_CRYPTO_DECRYPT_ERR = 0x3622, /* Upg file decryption failed */ + HI_PRINT_ERRNO_CRYPTO_SALT_EMPTY_ERR = 0x3623, /* Flash encryption and decryption root key salt is empty */ + HI_PRINT_ERRNO_IDX_MAX, /* Error code type maximum */ +} hi_print_errno; + +/** +* @ingroup iot_dfx +* @brief The error code is forced to be printed out in romboot. The hi_print_errno definition cannot be modified. +CNcomment:romboot中强制打印输出错误码,不可修改hi_print_errno定义。CNend +* +* @par 描述: +* Force to print out error codes to help users locate errors. +CNcomment:强制打印输出错误码,帮助用户定位错误。CNend +* +* @attention None. +* +* @param print_errno [IN] type #hi_u32, error code. +* +* @retval None. +* @par 依赖: +* @li hi_boot_rom.h:Describes Boot APIs.CNcomment:文件用于描述Boot模块接口。CNend +* @see boot_puthex|boot_msg0|boot_msg1|boot_msg2|boot_msg4. +*/ +hi_void boot_put_errno(hi_u32 print_errno); + +/** +* @ingroup iot_dfx +* @brief Output hexadecimal number.CNcomment:输出16进制数。CNend +* +* @par 描述: +* Output hexadecimal number.CNcomment:输出16进制数。CNend +* +* @attention None. +* +* @param h [IN] type #hi_u32, Hexadecimal number to output. +* @param print0 [IN] type #hi_bool, HI_TRUE: fill 0 to 4 bytes when printing. HI_FALSE: do not fill 0 alignment. +* +* @retval None. +* @par 依赖: +* @li hi_boot_rom.h:Describes Boot APIs.CNcomment:文件用于描述Boot模块接口。CNend +* @see boot_put_errno|boot_msg0|boot_msg1|boot_msg2|boot_msg4. +*/ +hi_void boot_puthex(hi_u32 h, hi_bool print0); + +/** +* @ingroup iot_dfx +* @brief Printout information, string only.CNcomment:打印输出信息,只输出字符串。CNend +* +* @par 描述: +* Printout information, string only.CNcomment:打印输出信息,只输出字符串。CNend +* +* @attention None. +* +* @param s [IN] type #hi_char*, String to output. +* +* @retval None. +* @par 依赖: +* @li hi_boot_rom.h:Describes Boot APIs.CNcomment:文件用于描述Boot模块接口。CNend +* @see boot_put_errno|boot_puthex|boot_msg1|boot_msg2|boot_msg4. +*/ +hi_void boot_msg0(const hi_char *s); + +/** +* @ingroup iot_dfx +* @brief Print out information, output string and 1 values.CNcomment:打印输出信息,输出字符串及1个数值。CNend +* +* @par 描述: +* Print out information, output string and 1 values.CNcomment:打印输出信息,输出字符串及1个数值。CNend +* +* @attention None. +* +* @param s [IN] type #hi_char*, String to output. +* @param h [IN] type #hi_u32, Value to be output, hexadecimal. +* +* @retval None. +* @par 依赖: +* @li hi_boot_rom.h:Describes Boot APIs.CNcomment:文件用于描述Boot模块接口。CNend +* @see boot_put_errno|boot_puthex|boot_msg0|boot_msg2|boot_msg4. +*/ +hi_void boot_msg1(const hi_char *s, hi_u32 h); + +/** +* @ingroup iot_dfx +* @brief Print out information, output string and 2 values.CNcomment:打印输出信息,输出字符串及2个数值。CNend +* +* @par 描述: +* Print out information, output string and 2 values.CNcomment:打印输出信息,输出字符串及2个数值。CNend +* +* @attention None. +* +* @param s [IN] type #hi_char*, String to output. +* @param h1 [IN] type #hi_u32, Value to be output 1, hexadecimal. +* @param h2 [IN] type #hi_u32, Value to be output 2, hexadecimal. +* +* @retval None. +* @par 依赖: +* @li hi_boot_rom.h:Describes Boot APIs.CNcomment:文件用于描述Boot模块接口。CNend +* @see boot_put_errno|boot_puthex|boot_msg0|boot_msg1|boot_msg4. +*/ +hi_void boot_msg2(const hi_char *s, hi_u32 h1, hi_u32 h2); + +/** +* @ingroup iot_dfx +* @brief Print out information, output string and 4 values.CNcomment:打印输出信息,输出字符串及4个数值。CNend +* +* @par 描述: +* Print out information, output string and 4 values.CNcomment:打印输出信息,输出字符串及4个数值。CNend +* +* @attention None. +* +* @param s [IN] type #hi_char*, String to output. +* @param h1 [IN] type #hi_u32, Value to be output 1, hexadecimal. +* @param h2 [IN] type #hi_u32, Value to be output 2, hexadecimal. +* @param h3 [IN] type #hi_u32, Value to be output 3, hexadecimal. +* @param h4 [IN] type #hi_u32, Value to be output 4, hexadecimal. +* +* @retval None. +* @par 依赖: +* @li hi_boot_rom.h:Describes Boot APIs.CNcomment:文件用于描述Boot模块接口。CNend +* @see boot_put_errno|boot_puthex|boot_msg0|boot_msg1|boot_msg2. +*/ +hi_void boot_msg4(const hi_char *s, hi_u32 h1, hi_u32 h2, hi_u32 h3, hi_u32 h4); + +/** @defgroup iot_uart Uart APIs +* @ingroup iot_romboot +*/ +/** + * @ingroup iot_uart + * + * Uart ID. CNcomment:串口号。CNend + */ +typedef enum { + UART0 = 0, /* uart0 */ + UART1 = 1, /* uart1 */ + UART2 = 2, /* uart2 */ + UART_MAX = 3, +} hi_uart; + +/** + * @ingroup iot_uart + * + * Uart parameter struct. CNcomment:串口参数结构体。CNend + */ +typedef struct { + hi_u32 baudrate; /* Baud rate */ + hi_uchar databit; /* 5; 6; 7; 8 */ + hi_uchar stopbit; /* 1:stop_bit 1; 2: stop_bit 2. */ + hi_uchar parity; /* 0: None; 1:Odd; 2:Even */ + hi_uchar flow_ctrl; /* 0: None; 1:rts&&cts. 2:only rts; 3:only cts */ + hi_uchar fifoline_tx_int; /* 0:tx FIFO≤1/8full; 1:tx FIFO≤1/4full; 2:tx FIFO≤1/2full; + 3:tx FIFO≤3/4full; 4:tx FIFO≤7/8full */ + hi_uchar fifoline_rx_int; /* 0:rx FIFO≥1/8full; 1:rx FIFO≥1/4full; 2:rx FIFO≥1/2full; + 3:rx FIFO≥3/4full; 4:rx FIFO≥7/8full */ + hi_uchar fifoline_rts; /* 0:rx FIFO≥1/8full; 1:rx FIFO≥1/4full; 2:rx FIFO≥1/2full; + 3:rx FIFO≥3/4full; 4:rx FIFO≥7/8full */ + hi_uchar pad; +} uart_param_stru; + +/** +* @ingroup iot_uart +* @brief Serial output forbidden.CNcomment:串口输出禁言。CNend +* +* @par 描述: +* Serial output forbidden.CNcomment:串口输出禁言。CNend +* +* @attention None. +* +* @param None. +* +* @retval None. +* @par 依赖: +* @li hi_boot_rom.h:Describes Boot APIs.CNcomment:文件用于描述Boot模块接口。CNend +* @see serial_cancel_mute. +*/ +hi_void serial_set_mute(hi_void); + +/** +* @ingroup iot_uart +* @brief Cancel serial output forbidden.CNcomment:串口输出取消禁言。CNend +* +* @par 描述: +* Cancel serial output forbidden.CNcomment:串口输出取消禁言。CNend +* +* @attention None. +* +* @param None. +* +* @retval None. +* @par 依赖: +* @li hi_boot_rom.h:Describes Boot APIs.CNcomment:文件用于描述Boot模块接口。CNend +* @see serial_set_mute. +*/ +hi_void serial_cancel_mute(hi_void); + +/** +* @ingroup iot_uart +* @brief Serial port initialization.CNcomment:串口初始化。CNend +* +* @par 描述: +* Serial port initialization.CNcomment:串口初始化。CNend +* +* @attention None. +* +* @param uart_num [IN] type #hi_uart, Uart ID. +* @param default_uart_param [IN] type #uart_param_stru, Uart parameters. +* +* @retval #HI_ERR_FAILURE Failure. +* @retval #HI_ERR_SUCCESS Success. +* @par 依赖: +* @li hi_boot_rom.h:Describes Boot APIs.CNcomment:文件用于描述Boot模块接口。CNend +* @see serial_init|serial_putc|serial_puts|serial_put_buf|serial_getc|serial_tstc|serial_puthex。 +*/ +hi_u32 serial_init(hi_uart uart_num, uart_param_stru default_uart_param); + +/** +* @ingroup iot_uart +* @brief Serial output single character.CNcomment:串口输出单个字符。CNend +* +* @par 描述: +* Serial output single character.CNcomment:串口输出单个字符。CNend +* +* @attention None. +* +* @param c [IN] type #const hi_char, Char to output. +* +* @retval None. +* @par 依赖: +* @li hi_boot_rom.h:Describes Boot APIs.CNcomment:文件用于描述Boot模块接口。CNend +* @see serial_init|serial_putc|serial_puts|serial_put_buf|serial_getc|serial_tstc|serial_puthex。 +*/ +hi_void serial_putc(const hi_char c); + +/** +* @ingroup iot_uart +* @brief Serial output string.CNcomment:串口输出字符串。CNend +* +* @par 描述: +* Serial output string.CNcomment:串口输出字符串。CNend +* +* @attention None. +* +* @param s [IN] type #const hi_char*, String to output. +* +* @retval None. +* @par 依赖: +* @li hi_boot_rom.h:Describes Boot APIs.CNcomment:文件用于描述Boot模块接口。CNend +* @see serial_init|serial_putc|serial_puts|serial_put_buf|serial_getc|serial_tstc|serial_puthex。 +*/ +hi_void serial_puts(const hi_char *s); + +/** +* @ingroup iot_uart +* @brief Serial output character buffer, specify buffer length.CNcomment:串口输出字符缓冲区,指定缓冲区长度。CNend +* +* @par 描述: +* Serial output character buffer, specify buffer length.CNcomment:串口输出字符缓冲区,指定缓冲区长度。CNend +* +* @attention The difference between the serial_puts() function is that the serial_puts function is for strings and +* stops the output when '\ 0' is encountered. However, this interface is not affected by '\ 0' for a +* specified length of character buffer.CNcomment:与serial_puts()函数的区别是:serial_puts函数是针对字符串, +* 遇到'\0'后停止输出;而本接口针对指定长度的字符缓冲区,不受'\0'影响。CNend +* @param buffer [IN] type #const hi_char*, String to output. +* @param length [IN] type #hi_s32, Length of string to be output. +* +* @retval None. +* @par 依赖: +* @li hi_boot_rom.h:Describes Boot APIs.CNcomment:文件用于描述Boot模块接口。CNend +* @see serial_init|serial_putc|serial_puts|serial_put_buf|serial_getc|serial_tstc|serial_puthex。 +*/ +hi_void serial_put_buf(const hi_char *buffer, hi_s32 length); + +/** +* @ingroup iot_uart +* @brief Read a character from the serial port.CNcomment:从串口读取一个字符。CNend +* +* @par 描述: +* Read a character from the serial port.CNcomment:从串口读取一个字符。CNend +* +* @attention This function is a blocking interface. If the serial port does not receive characters, it will wait. +CNcomment:本函数为阻塞接口,如果串口没有接收到字符,会一直等待。CNend +* @param None. +* +* @retval #Character Characters read from serial port. +* @retval #-1 Failure. +* @par 依赖: +* @li hi_boot_rom.h:Describes Boot APIs.CNcomment:文件用于描述Boot模块接口。CNend +* @see serial_init|serial_putc|serial_puts|serial_put_buf|serial_getc|serial_tstc|serial_puthex。 +*/ +hi_u8 serial_getc(hi_void); + +/** +* @ingroup iot_uart +* @brief Whether the serial port has characters to be received.CNcomment:串口是否有字符待接收。CNend +* +* @par 描述: +* Whether the serial port has characters to be received.CNcomment:串口是否有字符待接收。CNend +* +* @attention None. +* @param None. +* +* @retval #0 Not received date from serial port. +* @retval #1 Received date from serial port. +* @par 依赖: +* @li hi_boot_rom.h:Describes Boot APIs.CNcomment:文件用于描述Boot模块接口。CNend +* @see serial_init|serial_putc|serial_puts|serial_put_buf|serial_getc|serial_tstc|serial_puthex。 +*/ +hi_s32 serial_tstc(hi_void); + +/** +* @ingroup iot_uart +* @brief Output hexadecimal number to serial port.CNcomment:向串口输出16进制数。CNend +* +* @par 描述: +* 向串口输出16进制数.CNcomment:向串口输出16进制数。CNend +* +* @attention None. +* @param h [IN] type #hi_u32,Hexadecimal number to be output.CNcomment:待输出的16进制数。CNend +* @param print_all [IN] type #hi_u8 *,Whether to fill in 0, Align according to 4 bytes. 1 : fill, 0 : not to fill. +CNcomment:打印时前面是否补0,按照4字节对齐,1表示补,0表示不补。CNend +* +* @retval None. +* @par 依赖: +* @li hi_boot_rom.h:Describes Boot APIs.CNcomment:文件用于描述Boot模块接口。CNend +* @see serial_init|serial_putc|serial_puts|serial_put_buf|serial_getc|serial_tstc|serial_puthex。 +*/ +hi_void serial_puthex(hi_u32 h, hi_bool print_all); + +/** +* @ingroup iot_uart +* @brief Read a character from the serial port, and end if it is not read after waiting for the specified time. +CNcomment:从串口读取一个字符,等待指定时间后没有读到则结束。CNend +* +* @par 描述: +* Read a character from the serial port, and end if it is not read after waiting for the specified time. +CNcomment:从串口读取一个字符,等待指定时间后没有读到则结束。CNend +* +* @attention None. +* @param timeout_us [IN] type #hi_u32,Specify timeout in us.CNcomment:指定超时时间,单位:us。CNend +* @param ch [IN] type #hi_u8 *,Output character.CNcomment:输出字符。CNend +* +* @retval #HI_ERR_FAILURE Failure. +* @retval #HI_ERR_SUCCESS Success. +* @par 依赖: +* @li hi_boot_rom.h:Describes Boot APIs.CNcomment:文件用于描述Boot模块接口。CNend +* @see serial_init|serial_putc|serial_puts|serial_put_buf|serial_getc|serial_tstc|serial_puthex。 +*/ +hi_u32 serial_getc_timeout(hi_u32 timeout_us, hi_u8 *ch); + +/** @defgroup iot_mem Memory APIs +* @ingroup iot_romboot +*/ +/** +* @ingroup iot_mem +* +* Dynamic memory management module initialization interface function pointer. +CNcomment:动态内存管理模块初始化接口函数指针。CNend +*/ +typedef hi_void (*malloc_init_func)(hi_u32 heap_start_addr, hi_u32 heap_end_addr, hi_u32 check_sum); + +/** +* @ingroup iot_mem +* +* Request dynamic memory interface function pointer.CNcomment:申请动态内存接口函数指针。CNend +*/ +typedef hi_void *(*malloc_func)(hi_u32 size); + +/** +* @ingroup iot_mem +* +* Release dynamic memory interface function pointer.CNcomment:释放动态内存接口函数指针。CNend +*/ +typedef hi_u32 (*free_func)(hi_void *addr); + +/** +* @ingroup iot_mem +* +* Input parameter of hi_register_malloc interface. +*/ +typedef struct { + malloc_init_func init; /* Initialize heap memory interface */ + malloc_func boot_malloc; /* Request heap memory interface */ + free_func boot_free; /* Release heap memory interface */ +} hi_malloc_func; + +/** +* @ingroup iot_mem +* @brief To register malloc management related functions, be sure to register before using other interfaces. +CNcomment:注册malloc管理相关函数,务必先注册再使用其他接口。CNend +* +* @par 描述: +* Support users to adapt memory management functions.CNcomment:支持用户自己适配内存管理函数。CNend +* +* @attention None. +* @param addr [IN] type #uintptr_t,Heap start address.CNcomment:堆空间起始地址。CNend +* @param funcs [IN] type #const hi_malloc_func *,Request memory related interface register structure pointer. +CNcomment:申请内存相关接口注册结构体指针。CNend +* +* @retval #HI_ERR_FAILURE Failure. +* @retval #HI_ERR_SUCCESS Success. +* @par 依赖: +* @li hi_boot_rom.h:Describes Boot APIs.CNcomment:文件用于描述Boot模块接口。CNend +* @see boot_malloc_init|boot_malloc|boot_free。 +*/ +hi_u32 hi_register_malloc(uintptr_t addr, const hi_malloc_func *funcs); + +/** +* @ingroup iot_mem +* @brief Heap initialize.CNcomment:堆空间初始化。CNend +* +* @par 描述: +* Heap initialize.CNcomment:堆空间初始化。CNend +* +* @attention None. +* @param heap_start_addr [IN] type #uintptr_t,Heap start address.CNcomment:堆空间起始地址。CNend +* @param heap_end_addr [IN] type #uintptr_t,Heap end address.CNcomment:堆空间结束地址。CNend +* @param check_sum [IN] type #hi_u32,Exclusive or of start address and end address. +CNcomment:起始地址与结束地址的异或。CNend +* +* @retval #HI_ERR_FAILURE Failure. +* @retval #HI_ERR_SUCCESS Success. +* @par 依赖: +* @li hi_boot_rom.h:Describes Boot APIs.CNcomment:文件用于描述Boot模块接口。CNend +* @see boot_malloc_init。 +*/ +hi_void boot_malloc_init(uintptr_t heap_start_addr, uintptr_t heap_end_addr, hi_u32 check_sum); + +/** +* @ingroup iot_mem +* @brief Dynamically applies for memory.CNcomment:动态申请内存。CNend +* +* @par 描述: +* Dynamically applies for memory.CNcomment:动态申请内存。CNend +* +* @attention None. +* @param size [IN] type #hi_u32,Requested memory size (unit: byte) +CNcomment:申请内存大小(单位:byte)。CNend +* +* @retval #Other Success +* @retval #HI_NULL Failure. The memory is insufficient. +* @par 依赖: +* @li hi_boot_rom.h:Describes memory APIs.CNcomment:文件用于描述内存相关接口。CNend +* @see boot_free。 +*/ +hi_void *boot_malloc(hi_u32 size); + +/** +* @ingroup iot_mem +* @brief Releases the memory that is dynamically applied for.CNcomment:释放动态申请的内存。CNend +* +* @par 描述: +* Releases the memory that is dynamically applied for.CNcomment:释放动态申请的内存。CNend +* +* @attention None. +* @param addr [IN] type #hi_void *,Start address of the requested memory. The validity of the address is ensured +* by the caller.CNcomment:所申请内存的首地址,地址合法性由调用者保证。CNend +* +* @retval None. +* @par 依赖: +* @li hi_boot_rom.h:Describes memory APIs.CNcomment:文件用于描述内存相关接口。CNend +* @see boot_malloc。 +*/ +hi_u32 boot_free(hi_void *addr); + +typedef enum { + HI_EFUSE_CHIP_RW_ID = 0, + HI_EFUSE_DIE_RW_ID = 1, + HI_EFUSE_PMU_FUSE1_RW_ID = 2, + HI_EFUSE_PMU_FUSE2_RW_ID = 3, + HI_EFUSE_FLASH_ENCPY_CNT3_RW_ID = 4, + HI_EFUSE_FLASH_ENCPY_CNT4_RW_ID = 5, + HI_EFUSE_FLASH_ENCPY_CNT5_RW_ID = 6, + HI_EFUSE_DSLEEP_FLAG_RW_ID = 7, + HI_EFUSE_ROOT_PUBKEY_RW_ID = 8, + HI_EFUSE_ROOT_KEY_WO_ID = 9, + HI_EFUSE_CUSTOMER_RSVD0_RW_ID = 10, + HI_EFUSE_SUBKEY_CAT_RW_ID = 11, + HI_EFUSE_ENCRYPT_FLAG_RW_ID = 12, + HI_EFUSE_SUBKEY_RSIM_RW_ID = 13, + HI_EFUSE_START_TYPE_RW_ID = 14, + HI_EFUSE_JTM_RW_ID = 15, + HI_EFUSE_UTM0_RW_ID = 16, + HI_EFUSE_UTM1_RW_ID = 17, + HI_EFUSE_UTM2_RW_ID = 18, + HI_EFUSE_SDC_RW_ID = 19, + HI_EFUSE_RSVD0_RW_ID = 20, + HI_EFUSE_KDF2ECC_HUK_DISABLE_RW_ID = 21, + HI_EFUSE_SSS_CORNER_RW_ID = 22, + HI_EFUSE_UART_HALT_INTERVAL_RW_ID = 23, + HI_EFUSE_TSENSOR_RIM_RW_ID = 24, + HI_EFUSE_CHIP_BK_RW_ID = 25, + HI_EFUSE_IPV4_MAC_ADDR_RW_ID = 26, + HI_EFUSE_IPV6_MAC_ADDR_RW_ID = 27, + HI_EFUSE_PG2GCCKA0_TRIM0_RW_ID = 28, + HI_EFUSE_PG2GCCKA1_TRIM0_RW_ID = 29, + HI_EFUSE_NVRAM_PA2GA0_TRIM0_RW_ID = 30, + HI_EFUSE_NVRAM_PA2GA1_TRIM0_RW_ID = 31, + HI_EFUSE_PG2GCCKA0_TRIM1_RW_ID = 32, + HI_EFUSE_PG2GCCKA1_TRIM1_RW_ID = 33, + HI_EFUSE_NVRAM_PA2GA0_TRIM1_RW_ID = 34, + HI_EFUSE_NVRAM_PA2GA1_TRIM1_RW_ID = 35, + HI_EFUSE_PG2GCCKA0_TRIM2_RW_ID = 36, + HI_EFUSE_PG2GCCKA1_TRIM2_RW_ID = 37, + HI_EFUSE_NVRAM_PA2GA0_TRIM2_RW_ID = 38, + HI_EFUSE_NVRAM_PA2GA1_TRIM2_RW_ID = 39, + HI_EFUSE_TEE_BOOT_VER_RW_ID = 40, + HI_EFUSE_TEE_KERNEL_VER_RW_ID = 41, + HI_EFUSE_TEE_SALT_RW_ID = 42, + HI_EFUSE_FLASH_ENCPY_CNT0_RW_ID = 43, + HI_EFUSE_FLASH_ENCPY_CNT1_RW_ID = 44, + HI_EFUSE_FLASH_ENCPY_CNT2_RW_ID = 45, + HI_EFUSE_FLASH_ENCPY_CFG_RW_ID = 46, + HI_EFUSE_FLASH_SCRAMBLE_EN_RW_ID = 47, + HI_EFUSE_USER_FLASH_IND_RW_ID = 48, + HI_EFUSE_RF_PDBUFFER_GCAL_RW_ID = 49, + HI_EFUSE_CUSTOMER_RSVD1_RW_ID = 50, + HI_EFUSE_DIE_2_RW_ID = 51, + HI_EFUSE_SEC_BOOT_RW_ID = 52, + HI_EFUSE_IDX_MAX, +} hi_efuse_idx; + +typedef enum { + HI_EFUSE_LOCK_CHIP_ID = 0, + HI_EFUSE_LOCK_DIE_ID = 1, + HI_EFUSE_LOCK_PMU_FUSE1_FUSE2_START_TYPE_TSENSOR_ID = 2, + HI_EFUSE_LOCK_ROOT_PUBKEY_ID = 3, + HI_EFUSE_LOCK_ROOT_KEY_ID = 4, + HI_EFUSE_LOCK_CUSTOMER_RSVD0_ID = 5, + HI_EFUSE_LOCK_SUBKEY_CAT_ID = 6, + HI_EFUSE_LOCK_ENCRYPT_RSIM_ID = 7, + HI_EFUSE_LOCK_JTM_ID = 8, + HI_EFUSE_LOCK_UTM0_ID = 9, + HI_EFUSE_LOCK_UTM1_ID = 10, + HI_EFUSE_LOCK_UTM2_ID = 11, + HI_EFUSE_LOCK_SDC_ID = 12, + HI_EFUSE_LOCK_RSVD0_ID = 13, + HI_EFUSE_LOCK_SSS_CORNER_ID = 14, + HI_EFUSE_LOCK_UART_HALT_INTERVAL_ID = 15, + HI_EFUSE_LOCK_CHIP_BK_ID = 16, + HI_EFUSE_LOCK_IPV4_IPV6_MAC_ADDR_ID = 17, + HI_EFUSE_LOCK_PG2GCCKA0_PG2GCCKA1_TRIM0_ID = 18, + HI_EFUSE_LOCK_NVRAM_PA2GA0_PA2GA1_TRIM0_ID = 19, + HI_EFUSE_LOCK_PG2GCCKA0_PG2GCCKA1_TRIM1_ID = 20, + HI_EFUSE_LOCK_NVRAM_PA2GA0_PA2GA1_TRIM1_ID = 21, + HI_EFUSE_LOCK_PG2GCCKA0_PG2GCCKA1_TRIM2_ID = 22, + HI_EFUSE_LOCK_NVRAM_PA2GA0_PA2GA1_TRIM2_ID = 23, + HI_EFUSE_LOCK_TEE_BOOT_VER_ID = 24, + HI_EFUSE_LOCK_TEE_KERNEL_VER_ID = 25, + HI_EFUSE_LOCK_TEE_SALT_ID = 26, + HI_EFUSE_LOCK_FLASH_ENCPY_CNT0_ID = 27, + HI_EFUSE_LOCK_FLASH_ENCPY_CNT1_ID = 28, + HI_EFUSE_LOCK_FLASH_ENCPY_CNT2_ID = 29, + HI_EFUSE_LOCK_FLASH_ENCPY_CFG_ID = 30, + HI_EFUSE_LOCK_FLASH_SCRAMBLE_EN_FLASH_IND_ID = 31, + HI_EFUSE_LOCK_RF_PDBUFFER_GCAL_ID = 32, + HI_EFUSE_LOCK_CUSTOMER_RSVD1_ID = 33, + HI_EFUSE_LOCK_DIE_2_ID = 34, + HI_EFUSE_LOCK_KDF2ECC_HUK_DISABLE_ID = 35, + HI_EFUSE_LOCK_FLASH_ENCPY_CNT3_ID = 36, + HI_EFUSE_LOCK_FLASH_ENCPY_CNT4_ID = 37, + HI_EFUSE_LOCK_FLASH_ENCPY_CNT5_ID = 38, + HI_EFUSE_LOCK_SEC_BOOT_ID = 39, + HI_EFUSE_LOCK_DSLEEP_FLAG_ID = 40, + HI_EFUSE_LOCK_MAX, +} hi_efuse_lock_id; + +#define EFUSE_IDX_NRW 0x0 /* Unreadable and unwritable */ +#define EFUSE_IDX_RO 0x1 /* Read-only */ +#define EFUSE_IDX_WO 0x2 /* Write-only */ +#define EFUSE_IDX_RW 0x3 /* Read and write */ + +/** +* @ingroup iot_boot_api +* @brief efuse读取数据。 +* +* @par 描述: +* 从efuse中读取数据。 +* @attention 无。 +* @param efuse_id[IN] 类型 #hi_efuse_idx efuseID号。 +* @param data[OUT] 类型 #hi_u8 * 用户需要先调用hi_get_efuse_cfg_by_id获取该区域长度,然后申请空间后传入该空间地址。 +* @param data_len[IN] 类型 #hi_u8 efuse读取长度,用户需保证给data申请的bit空间不小于hi_get_efuse_cfg_by_id获取到的efuse长度向上8bit对齐。 +* @retval #HI_ERR_SUCCESS success. +* @retval #非HI_ERR_SUCCESS failed. +* @par Dependency: +*
  • hi_boot_rom.h: 该接口声明所在的头文件.
+* @see hi_efuse_write。 + */ +hi_u32 hi_efuse_read(hi_efuse_idx efuse_id, hi_u8 *data, hi_u8 data_len); + +/** +* @ingroup iot_boot_api +* @brief 写数据到efuse。 +* +* @par 描述: +* 无。 +* @attention 无。 +* @param efuse_id[IN] 类型 #hi_efuse_idx efuseID号。 +* @param data[IN] 类型 #hi_u8 * 用户需要先调用hi_get_efuse_cfg_by_id获取该区域长度,申请指定大小空间后填上内容,然后传入该空间地址。 +* @retval #HI_ERR_SUCCESS success. +* @retval #非HI_ERR_SUCCESS failed. +* @par Dependency: +*
  • hi_boot_rom.h: 该接口声明所在的头文件.
+* @see hi_efuse_read。 + */ +hi_u32 hi_efuse_write(hi_efuse_idx efuse_id, const hi_u8 *data); + +/** +* @ingroup iot_boot_api +* @brief 加锁efuse中的某个区域,加锁后该区域无法再写入。 +* +* @par 描述: +* 加锁efuse中的某个区域,加锁后该区域无法再写入,每bit对应存储区域的128 bits。 +* @attention 本加锁操作需要系统重启后才能生效。 +* @param efuse_lock_id[IN] 类型 #hi_efuse_lock_id 待加锁的efuseID号。 +* @retval #HI_ERR_SUCCESS success. +* @retval #非HI_ERR_SUCCESS failed.详见hi_errno.h +* @par Dependency: +*
  • hi_boot_rom.h: 该接口声明所在的头文件.
+* @see hi_efuse_write。 + */ +hi_u32 hi_efuse_lock(hi_efuse_lock_id efuse_lock_id); + +/** +* @ingroup iot_boot_api +* @brief 获取efuse的锁状态,查询存储区域的锁定状态。 +* +* @par 描述: +* 获取efuse的锁状态,查询存储区域的锁定状态,大小为64 bits。 +* @attention 无。 +* @param lock_stat[IN] 类型 #hi_u64 获取efuse的锁状态。 +* @retval #HI_ERR_SUCCESS success. +* @retval #非HI_ERR_SUCCESS failed.详见hi_errno.h +* @par Dependency: +*
  • hi_boot_rom.h: 该接口声明所在的头文件.
+* @see hi_efuse_write。 + */ +hi_u32 hi_efuse_get_lockstat(hi_u64 *lock_stat); + +/** +* @ingroup iot_boot_api +* @brief 用户从efuse指定位置读取数据。 +* +* @par 描述: +* 通常用于从efuse用户区中读取数据,但支持从任意指定地址读取。 +* @attention 此接口一般情况下用于操作用户保留区内容,其他预分配的区域#hi_efuse_idx建议使用hi_efuse_read接口。 +* @attention 无。 +* @param start_bit [IN]类型 #hi_u16 起始bit位,该地址必须8 bits对齐。 +* @param size [IN] 类型 #hi_u16,待读取的bit位数,如果输入不是8bit对齐则函数内部会处理为8bit对齐,用户读取数据后需处理后使用。 +* @param key_data [OUT] 类型 #hi_u8*,读到的数据放到该地址。 +* +* @retval #HI_ERR_SUCCESS success. +* @retval #非HI_ERR_SUCCESS failed. +* @par Dependency: +*
  • hi_boot_rom.h: 该接口声明所在的头文件.
+* @see hi_efuse_usr_write。 + */ +hi_u32 hi_efuse_usr_read(hi_u16 start_bit, hi_u16 size, hi_u8 *key_data); + +/** +* @ingroup iot_boot_api +* @brief 用户向efuse指定位置写入数据。 +* +* @par 描述: +* 通常用于往efuse用户区中写入数据,但支持往任意指定地址写入。 +* @attention +* @li 此接口一般情况下用于操作用户保留区内容,其他预分配的区域#hi_efuse_idx建议使用hi_efuse_write接口和hi_efuse_lock接口。 +* @li 支持用户写入任意地址数据,详细地址的写入需要结合方案文档评估是否有冲突。 +* @param start_bit [IN] 类型 #hi_u16 写efuse入地址的起始位。 +* @param size [IN] 类型 #hi_u16 待写入bit数,支持单bit写入,最大值为256bits数。 +* @param key_data [IN] 类型 #hi_u8 * 待写入的数据放到该地址,最长为32字节。 +* @retval #HI_ERR_SUCCESS success. +* @retval #非HI_ERR_SUCCESS failed. +* @par Dependency: +*
  • hi_boot_rom.h: 该接口声明所在的头文件.
+* @see hi_efuse_usr_read。 + */ +hi_u32 hi_efuse_usr_write(hi_u16 start_bit, hi_u16 size, const hi_u8 *key_data); + +/** + * @ingroup iot_boot_api + * 默认看门狗配置时间为26秒。 + * romboot启动后时间不可以修改,用户可以在flashboot中调用hi_watchdog_enable接口重新配置。 + */ +#define WDG_TIME_US 26000000 /* 默认看门狗配置时间为26秒 */ + +/** +* @ingroup iot_watchdog +* @brief Enables the watchdog.CNcomment:使能看门狗。CNend +* +* @par 描述: +* Enables the watchdog.CNcomment:使能看门狗。CNend +* +* @attention None +* @param None +* +* @retval None +* @par 依赖: +* @li hi_boot_rom.h:describes the watchdog APIs.CNcomment:文件用于描述看门狗相关接口。CNend +* @see None +*/ +hi_void hi_watchdog_enable(hi_u32 over_time_us); + +/** +* @ingroup iot_watchdog +* @brief Feeds the watchdog.CNcomment:喂狗。CNend +* +* @par 描述: Feeds the watchdog.CNcomment:喂狗。CNend +* +* @attention None +* @param None +* +* @retval None +* @par 依赖: +* @li hi_boot_rom.h:describes the watchdog APIs.CNcomment:文件用于描述看门狗相关接口。CNend +* @see None +*/ +hi_void hi_watchdog_feed(hi_void); + +/** +* @ingroup iot_watchdog +* @brief Disables the watchdog.CNcomment:关闭看门狗。CNend +* +* @par 描述: +* @li Disable the clock enable control of the watchdog.CNcomment:禁止WatchDog时钟使能控制位。CNend +* @li Mask the watchdog reset function.CNcomment:屏蔽WatchDog复位功能。CNend +* +* @attention None +* @param None +* +* @retval None +* @par 依赖: +* @li hi_boot_rom.h:describes the watchdog APIs.CNcomment:文件用于描述看门狗相关接口。CNend +* @see None +*/ +hi_void hi_watchdog_disable(hi_void); + +/** @defgroup iot_crc16 CRC16 APIs +* @ingroup iot_romboot +*/ +/** +* @ingroup iot_crc16 +* @brief Generates a 16-bit CRC value.CNcomment:生成16位CRC校验值。CNend +* +* @par 描述: +* Generates a 16-bit CRC value.CNcomment:生成16位CRC校验值。CNend +* +* @attention None +* @param crc_start [IN] type #hi_u16,The CRC initial value.CNcomment:CRC初始值。CNend +* @param buf [IN] type #hi_u8*,Pointer to the buffer to be verified. +CNcomment:被校验Buffer指针。CNend +* @param len [IN] type #hi_u32,Length of the buffer to be verified (unit: Byte). +CNcomment:被校验Buffer长度(单位:byte)。CNend +* +* @retval #HI_ERR_SUCCESS Success +* @retval #Other Failure. For details, see hi_boot_err.h. +* +* @par 依赖: +* @li hi_boot_rom.h:Describes CRC APIs.CNcomment:文件包含CRC校验接口。CNend +* @see None +*/ +hi_u16 hi_crc16(hi_u16 crc_start, hi_u8 *buf, hi_u32 len); + +/** @defgroup iot_io IO APIs + * @ingroup iot_romboot + */ +/** +* @ingroup iot_io +* +* GPIO ID. +*/ +typedef enum { + HI_GPIO_IDX_0, /* GPIO0 */ + HI_GPIO_IDX_1, /* GPIO1 */ + HI_GPIO_IDX_2, /* GPIO2 */ + HI_GPIO_IDX_3, /* GPIO3 */ + HI_GPIO_IDX_4, /* GPIO4 */ + HI_GPIO_IDX_5, /* GPIO5 */ + HI_GPIO_IDX_6, /* GPIO6 */ + HI_GPIO_IDX_7, /* GPIO7 */ + HI_GPIO_IDX_8, /* GPIO8 */ + HI_GPIO_IDX_9, /* GPIO9 */ + HI_GPIO_IDX_10, /* GPIO10 */ + HI_GPIO_IDX_11, /* GPIO11 */ + HI_GPIO_IDX_12, /* GPIO12 */ + HI_GPIO_IDX_13, /* GPIO13 */ + HI_GPIO_IDX_14, /* GPIO14 */ + HI_GPIO_IDX_MAX, /* Maximum value, cannot be used. CNcomment:最大值,不可输入使用。CNend */ +} hi_gpio_idx; + +/** + * @ingroup iot_io + * + * GPIO pin ID. CNcomment:IO硬件管脚编号。CNend + */ +typedef enum { + HI_IO_NAME_GPIO_0, /* GPIO0 */ + HI_IO_NAME_GPIO_1, /* GPIO1 */ + HI_IO_NAME_GPIO_2, /* GPIO2 */ + HI_IO_NAME_GPIO_3, /* GPIO3 */ + HI_IO_NAME_GPIO_4, /* GPIO4 */ + HI_IO_NAME_GPIO_5, /* GPIO5 */ + HI_IO_NAME_GPIO_6, /* GPIO6 */ + HI_IO_NAME_GPIO_7, /* GPIO7 */ + HI_IO_NAME_GPIO_8, /* GPIO8 */ + HI_IO_NAME_GPIO_9, /* GPIO9 */ + HI_IO_NAME_GPIO_10, /* GPIO10 */ + HI_IO_NAME_GPIO_11, /* GPIO11 */ + HI_IO_NAME_GPIO_12, /* GPIO12 */ + HI_IO_NAME_GPIO_13, /* GPIO13 */ + HI_IO_NAME_GPIO_14, /* GPIO14 */ + HI_IO_NAME_SFC_CSN, /* SFC_CSN */ + HI_IO_NAME_SFC_IO1, /* SFC_IO1 */ + HI_IO_NAME_SFC_IO2, /* SFC_IO2 */ + HI_IO_NAME_SFC_IO0, /* SFC_IO0 */ + HI_IO_NAME_SFC_CLK, /* SFC_CLK */ + HI_IO_NAME_SFC_IO3, /* SFC_IO3 */ + HI_IO_NAME_MAX, +} hi_io_name; + +/** + * @ingroup iot_io + * + * GPIO pull-up configuration.CNcomment:IO上下拉功能CNend + */ +typedef enum { + HI_IO_PULL_NONE, /* No pull. CNcomment:无拉。CNend */ + HI_IO_PULL_UP, /* pull up. CNcomment:上拉。CNend */ + HI_IO_PULL_DOWN, /* pull down. CNcomment:下拉。CNend */ + HI_IO_PULL_MAX, /* Invalid value. CNcomment:无效值。CNend */ +} hi_io_pull; + +/** + * @ingroup iot_io + * + * GPIO_0 pin function.CNcomment:GPIO_0管脚功能。CNend + */ +typedef enum { + HI_IO_FUNC_GPIO_0_GPIO, + HI_IO_FUNC_GPIO_0_UART1_TXD = 2, + HI_IO_FUNC_GPIO_0_SPI0_CK, + HI_IO_FUNC_GPIO_0_JTAG_TDO, + HI_IO_FUNC_GPIO_0_PWM3_OUT, + HI_IO_FUNC_GPIO_0_I2C1_SDA, +} hi_io_func_gpio_0; + +/** +* @ingroup iot_io +* +* GPIO_1 pin function.CNcomment:GPIO_1管脚功能。CNend +*/ +typedef enum { + HI_IO_FUNC_GPIO_1_GPIO, + HI_IO_FUNC_GPIO_1_UART1_RXD = 2, + HI_IO_FUNC_GPIO_1_SPI0_RXD, + HI_IO_FUNC_GPIO_1_JTAG_TCK, + HI_IO_FUNC_GPIO_1_PWM4_OUT, + HI_IO_FUNC_GPIO_1_I2C1_SCL, + HI_IO_FUNC_GPIO_1_BT_FREQ, +} hi_io_func_gpio_1; + +/** +* @ingroup iot_io +* +* GPIO_2 pin function.CNcomment:GPIO_2管脚功能。CNend +*/ +typedef enum { + HI_IO_FUNC_GPIO_2_GPIO, + HI_IO_FUNC_GPIO_2_UART1_RTS_N = 2, + HI_IO_FUNC_GPIO_2_SPI0_TXD, + HI_IO_FUNC_GPIO_2_JTAG_TRSTN, + HI_IO_FUNC_GPIO_2_PWM2_OUT, + HI_IO_FUNC_GPIO_2_SSI_CLK = 7, +} hi_io_func_gpio_2; + +/** +* @ingroup iot_io +* +* GPIO_3 pin function.CNcomment:GPIO_3管脚功能。CNend +*/ +typedef enum { + HI_IO_FUNC_GPIO_3_GPIO, + HI_IO_FUNC_GPIO_3_UART0_TXD, + HI_IO_FUNC_GPIO_3_UART1_CTS_N, + HI_IO_FUNC_GPIO_3_SPI0_CSN, + HI_IO_FUNC_GPIO_3_JTAG_TDI, + HI_IO_FUNC_GPIO_3_PWM5_OUT, + HI_IO_FUNC_GPIO_3_I2C1_SDA, + HI_IO_FUNC_GPIO_3_SSI_DATA, +} hi_io_func_gpio_3; + +/** +* @ingroup iot_io +* +* GPIO_4 pin function.CNcomment:GPIO_4管脚功能。CNend +*/ +typedef enum { + HI_IO_FUNC_GPIO_4_GPIO, + HI_IO_FUNC_GPIO_4_UART0_RXD = 2, + HI_IO_FUNC_GPIO_4_JTAG_TMS = 4, + HI_IO_FUNC_GPIO_4_PWM1_OUT, + HI_IO_FUNC_GPIO_4_I2C1_SCL, +} hi_io_func_gpio_4; + +/** +* @ingroup iot_io +* +* GPIO_5 pin function.CNcomment:GPIO_5管脚功能。CNend +*/ +typedef enum { + HI_IO_FUNC_GPIO_5_GPIO, + HI_IO_FUNC_GPIO_5_UART1_RXD = 2, + HI_IO_FUNC_GPIO_5_SPI0_CSN, + HI_IO_FUNC_GPIO_5_PWM2_OUT = 5, + HI_IO_FUNC_GPIO_5_I2S0_MCLK, + HI_IO_FUNC_GPIO_5_BT_STATUS, +} hi_io_func_gpio_5; + +/** +* @ingroup iot_io +* +* GPIO_6 pin function.CNcomment:GPIO_6管脚功能。CNend +*/ +typedef enum { + HI_IO_FUNC_GPIO_6_GPIO, + HI_IO_FUNC_GPIO_6_UART1_TXD = 2, + HI_IO_FUNC_GPIO_6_SPI0_CK, + HI_IO_FUNC_GPIO_6_PWM3_OUT = 5, + HI_IO_FUNC_GPIO_6_I2S0_TX, + HI_IO_FUNC_GPIO_6_COEX_SWITCH, +} hi_io_func_gpio_6; + +/** +* @ingroup iot_io +* +* GPIO_7 pin function.CNcomment:GPIO_7管脚功能。CNend +*/ +typedef enum { + HI_IO_FUNC_GPIO_7_GPIO, + HI_IO_FUNC_GPIO_7_UART1_CTS_N = 2, + HI_IO_FUNC_GPIO_7_SPI0_RXD, + HI_IO_FUNC_GPIO_7_PWM0_OUT = 5, + HI_IO_FUNC_GPIO_7_I2S0_BCLK, + HI_IO_FUNC_GPIO_7_BT_ACTIVE, +} hi_io_func_gpio_7; + +/** +* @ingroup iot_io +* +* GPIO_8 pin function.CNcomment:GPIO_8管脚功能。CNend +*/ +typedef enum { + HI_IO_FUNC_GPIO_8_GPIO, + HI_IO_FUNC_GPIO_8_UART1_RTS_N = 2, + HI_IO_FUNC_GPIO_8_SPI0_TXD, + HI_IO_FUNC_GPIO_8_PWM1_OUT = 5, + HI_IO_FUNC_GPIO_8_I2S0_WS, + HI_IO_FUNC_GPIO_8_WLAN_ACTIVE, +} hi_io_func_gpio_8; + +/** +* @ingroup iot_io +* +* GPIO_9 pin function.CNcomment:GPIO_9管脚功能。CNend +*/ +typedef enum { + HI_IO_FUNC_GPIO_9_GPIO, + HI_IO_FUNC_GPIO_9_I2C0_SCL, + HI_IO_FUNC_GPIO_9_UART2_RTS_N, + HI_IO_FUNC_GPIO_9_SDIO_D2, + HI_IO_FUNC_GPIO_9_SPI1_TXD, + HI_IO_FUNC_GPIO_9_PWM0_OUT, + HI_IO_FUNC_GPIO_9_I2S0_MCLK = 7, +} hi_io_func_gpio_9; + +/** +* @ingroup iot_io +* +* GPIO_10 pin function.CNcomment:GPIO_10管脚功能。CNend +*/ +typedef enum { + HI_IO_FUNC_GPIO_10_GPIO, + HI_IO_FUNC_GPIO_10_I2C0_SDA, + HI_IO_FUNC_GPIO_10_UART2_CTS_N, + HI_IO_FUNC_GPIO_10_SDIO_D3, + HI_IO_FUNC_GPIO_10_SPI1_CK, + HI_IO_FUNC_GPIO_10_PWM1_OUT, + HI_IO_FUNC_GPIO_10_I2S0_TX = 7, +} hi_io_func_gpio_10; + +/** +* @ingroup iot_io +* +* GPIO_11 pin function.CNcomment:GPIO_11管脚功能。CNend +*/ +typedef enum { + HI_IO_FUNC_GPIO_11_GPIO, + HI_IO_FUNC_GPIO_11_UART2_TXD = 2, + HI_IO_FUNC_GPIO_11_SDIO_CMD, + HI_IO_FUNC_GPIO_11_SPI1_RXD, + HI_IO_FUNC_GPIO_11_PWM2_OUT, + HI_IO_FUNC_GPIO_11_RF_TX_EN_EXT, + HI_IO_FUNC_GPIO_11_I2S0_RX, +} hi_io_func_gpio_11; + +/** +* @ingroup iot_io +* +* GPIO_12 pin function.CNcomment:GPIO_12管脚功能。CNend +*/ +typedef enum { + HI_IO_FUNC_GPIO_12_GPIO, + HI_IO_FUNC_GPIO_12_UART2_RXD = 2, + HI_IO_FUNC_GPIO_12_SDIO_CLK, + HI_IO_FUNC_GPIO_12_SPI1_CSN, + HI_IO_FUNC_GPIO_12_PWM3_OUT, + HI_IO_FUNC_GPIO_12_RF_RX_EN_EXT, + HI_IO_FUNC_GPIO_12_I2S0_BCLK, +} hi_io_func_gpio_12; + +/** +* @ingroup iot_io +* +* GPIO_13 pin function.CNcomment:GPIO_13管脚功能。CNend +*/ +typedef enum { + HI_IO_FUNC_GPIO_13_SSI_DATA, + HI_IO_FUNC_GPIO_13_UART0_TXD, + HI_IO_FUNC_GPIO_13_UART2_RTS_N, + HI_IO_FUNC_GPIO_13_SDIO_D0, + HI_IO_FUNC_GPIO_13_GPIO, + HI_IO_FUNC_GPIO_13_PWM4_OUT, + HI_IO_FUNC_GPIO_13_I2C0_SDA, + HI_IO_FUNC_GPIO_13_I2S0_WS, +} hi_io_func_gpio_13; + +/** +* @ingroup iot_io +* +* GPIO_14 pin function.CNcomment:GPIO_14管脚功能。CNend +*/ +typedef enum { + HI_IO_FUNC_GPIO_14_SSI_CLK, + HI_IO_FUNC_GPIO_14_UART0_RXD, + HI_IO_FUNC_GPIO_14_UART2_CTS_N, + HI_IO_FUNC_GPIO_14_SDIO_D1, + HI_IO_FUNC_GPIO_14_GPIO, + HI_IO_FUNC_GPIO_14_PWM5_OUT, + HI_IO_FUNC_GPIO_14_I2C0_SCL, +} hi_io_func_gpio_14; + +/** +* @ingroup iot_io +* +* SFC_CSN pin function.CNcomment:SFC_CSN管脚功能。CNend +*/ +typedef enum { + HI_IO_FUNC_SFC_CSN_SFC_CSN, + HI_IO_FUNC_SFC_CSN_SDIO_D2, + HI_IO_FUNC_SFC_CSN_GPIO9, + HI_IO_FUNC_SFC_CSN_SPI0_TXD = 4, +} hi_io_func_sfc_csn; + +/** +* @ingroup iot_io +* +* SFC_DO pin function.CNcomment:SFC_DO管脚功能。CNend +*/ +typedef enum { + HI_IO_FUNC_SFC_IO_1_SFC_DO, + HI_IO_FUNC_SFC_IO_1_SDIO_D3, + HI_IO_FUNC_SFC_IO_1_GPIO10, + HI_IO_FUNC_SFC_IO_1_SPI0_CK = 4, +} hi_io_func_sfc_io_1; + +/** +* @ingroup iot_io +* +* SFC_WPN pin function.CNcomment:SFC_WPN管脚功能。CNend +*/ +typedef enum { + HI_IO_FUNC_SFC_IO_2_SFC_WPN, + HI_IO_FUNC_SFC_IO_2_SDIO_CMD, + HI_IO_FUNC_SFC_IO_2_GPIO11, + HI_IO_FUNC_SFC_IO_2_RF_TX_EN_EXT, + HI_IO_FUNC_SFC_IO_2_SPI0_RXD, +} hi_io_func_sfc_io_2; + +/** +* @ingroup iot_io +* +* SFC_DI pin function.CNcomment:SFC_DI管脚功能。CNend +*/ +typedef enum { + HI_IO_FUNC_SFC_IO_0_SFC_DI, + HI_IO_FUNC_SFC_IO_0_SDIO_CLK, + HI_IO_FUNC_SFC_IO_0_GPIO12, + HI_IO_FUNC_SFC_IO_0_RF_RX_EN_EXT, + HI_IO_FUNC_SFC_IO_0_SPI0_CSN, +} hi_io_func_sfc_io_0; + +/** +* @ingroup iot_io +* +* SFC_CLK pin function.CNcomment:SFC_CLK管脚功能。CNend +*/ +typedef enum { + HI_IO_FUNC_SFC_CLK_SFC_CLK, + HI_IO_FUNC_SFC_CLK_SDIO_D0, + HI_IO_FUNC_SFC_CLK_GPIO13, + HI_IO_FUNC_SFC_CLK_SSI_DATA = 4, +} hi_io_func_sfc_clk; + +/** +* @ingroup iot_io +* +* SFC_HOLDN pin function.CNcomment:SFC_HOLDN管脚功能。CNend +*/ +typedef enum { + HI_IO_FUNC_SFC_IO_3_SFC_HOLDN, + HI_IO_FUNC_SFC_IO_3_SDIO_D1, + HI_IO_FUNC_SFC_IO_3_GPIO14, + HI_IO_FUNC_SFC_IO_3_SSI_CLK = 4, +} hi_io_func_sfc_io_3; + +/** +* @ingroup iot_io +* @brief Sets the I/O multiplexing.CNcomment:配置某个IO的复用功能。CNend +* +* @par 描述: +* Sets the I/O multiplexing.CNcomment:配置某个IO的复用功能。CNend +* +* @attention None +* @param id [IN] type #hi_io_name,I/O index.CNcomment:硬件管脚。CNend +* @param val [IN] type #hi_u8,I/O multiplexing.See the functions below: CNcomment:IO复用功能。 +根据待设置的硬件管脚,从如下枚举中选择相应功能。CNend + hi_io_func_gpio_0, + hi_io_func_gpio_1, + hi_io_func_gpio_2, + hi_io_func_gpio_3, + hi_io_func_gpio_4, + hi_io_func_gpio_5, + hi_io_func_gpio_6, + hi_io_func_gpio_7, + hi_io_func_gpio_8, + hi_io_func_gpio_9, + hi_io_func_gpio_10, + hi_io_func_gpio_11, + hi_io_func_gpio_12, + hi_io_func_gpio_13, + hi_io_func_gpio_14, + hi_io_func_sfc_csn, + hi_io_func_sfc_io_1, + hi_io_func_sfc_io_2, + hi_io_func_sfc_io_0, + hi_io_func_sfc_clk, + hi_io_func_sfc_io_3 +* +* @retval #HI_ERR_SUCCESS Success +* @retval #HI_ERR_GPIO_INVALID_PARAMETER Failure. Input invalid. +* @par 依赖: +* @li hi_boot_rom.h:Describes I/O APIs.CNcomment:文件用于描述IO相关接口。CNend +* @see hi_io_set_func。 +*/ +hi_u32 hi_io_set_func(hi_io_name id, hi_u8 val); + +/** +* @ingroup iot_io +* @brief Enables the I/O pull-up.CNcomment:设置某个IO上下拉功能。CNend +* +* @par 描述: +* Enables the I/O pull-up.CNcomment:设置某个IO上下拉功能。CNend +* +* @attention None +* @param id [IN] type #hi_io_name,I/O index.CNcomment:硬件管脚。CNend +* @param val [IN] type #hi_io_pull,I/O pull-up enable.CNcomment:待设置的上下拉状态。CNend +* +* @retval #HI_ERR_SUCCESS Success +* @retval #HI_ERR_GPIO_INVALID_PARAMETER Failure. Input invalid. +* @par 依赖: +* @li hi_boot_rom.h:Describes I/O APIs.CNcomment:文件用于描述IO相关接口。CNend +* @see hi_io_get_pull。 +*/ +hi_u32 hi_io_set_pull(hi_io_name id, hi_io_pull val); +#endif + diff --git a/sdk_liteos/boot/loaderboot/include/hi_loaderboot_flash.h b/sdk_liteos/boot/loaderboot/include/hi_loaderboot_flash.h new file mode 100644 index 0000000000000000000000000000000000000000..44175207e175cd6b1b3ae9bc315ae8e42c7158fc --- /dev/null +++ b/sdk_liteos/boot/loaderboot/include/hi_loaderboot_flash.h @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __HI_LOADERBOOT_FLASH_H__ +#define __HI_LOADERBOOT_FLASH_H__ +#include "hi_boot_rom.h" + +/** +* @ingroup hct_boot_flash +* @brief Flash初始化 +* +* @par 描述: +* 初始化Flash模块。 +* @attention +* @retval #0 success. +* @retval #非0 failed.详见hi_errno.h +* +* @par Dependency: +*
  • hi_loaderboot_flash.h: 该接口声明所在的头文件.
+* @see +*/ +hi_u32 hi_flash_init(hi_void); + +/** +* @ingroup hct_boot_flash +* @brief flash数据删除 +* +* @par 描述: +* 删除flash上的数据内容。 +* @attention +* +* @param flash_addr [IN] 类型 #hi_u32 待删除Flash的起始地址 +* @param flash_erase_size [IN] 类型 #hi_u32 待删除的Flash内容长度 +* +* @retval #0 success. +* @retval #非0 failed.详见hi_errno.h +* +* @par Dependency: +*
  • hi_loaderboot_flash.h: 该接口声明所在的头文件.
+* @see hi_flash_write|hi_flash_read +*/ +hi_u32 hi_flash_erase(const hi_u32 flash_addr, hi_u32 flash_erase_size); + +/** +* @ingroup hct_boot_flash +* @brief flash数据写入 +* +* @par 描述: +* 向flash上的写入数据内容。 +* @attention +* @li 只有在flash初始化时,配置flash回读比较空间才可以使用do_erase为HI_TRUE的选项。具体配置方法参考kernel下hi_flash_init实现。 +* +* @param flash_addr [IN] 类型 #hi_u32 Flash的起始地址 +* @param flash_write_size [IN] 类型 #hi_u32 待写入Flash的数据长度 +* @param flash_write_data [IN] 类型 #hi_u8* 待写入Flash的数据内容 +* @param do_erase [IN] 类型 #hi_bool HI_FALSE:直接写FLASH HI_TRUE:写之前擦除操作区域对应的sector空间,用户操作空间写用户数据其它空间回写历史数据。 +* +* @retval #0 success. +* @retval #非0 failed.详见hi_errno.h +* +* @par Dependency: +*
  • hi_loaderboot_flash.h: 该接口声明所在的头文件.
+* @see hi_flash_erase|hi_flash_read +*/ +hi_u32 hi_flash_write(hi_u32 flash_addr, hi_u32 flash_write_size, const hi_u8 *flash_write_data, hi_bool do_erase); + +/** +* @ingroup hct_boot_flash +* @brief flash数据读取 +* +* @par 描述: +* 从flash上的读取数据内容。 +* @attention +* +* @param flash_addr [IN] 类型 #hi_u32 Flash的起始地址 +* @param flash_read_size [IN] 类型 #hi_u32 待读取的数据长度 +* @param flash_read_data [OUT] 类型 #hi_u8* 数据内容缓冲区,用于存放从Flash中读取到的数据 +* +* @retval #0 success. +* @retval #非0 failed.详见hi_errno.h +* +* @par Dependency: +*
  • hi_loaderboot_flash.h: 该接口声明所在的头文件.
+* @see hi_flash_write|hi_flash_erase +*/ +hi_u32 hi_flash_read(hi_u32 flash_addr, hi_u32 flash_read_size, hi_u8 *flash_read_data); +#endif + diff --git a/sdk_liteos/boot/loaderboot/include/hi_nvm.h b/sdk_liteos/boot/loaderboot/include/hi_nvm.h new file mode 100644 index 0000000000000000000000000000000000000000..2fb7149581126d38a8318f9075ccc69c3ed9e792 --- /dev/null +++ b/sdk_liteos/boot/loaderboot/include/hi_nvm.h @@ -0,0 +1,217 @@ +/** + * @file hi_nvm.h + * + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __HI_NVM_H__ +#define __HI_NVM_H__ + +#include +#include + +#define hi_make_identifier(a, b, c, d) hi_makeu32(hi_makeu16(a, b), hi_makeu16(c, d)) +#define HNV_FILE_SIGNATURE hi_make_identifier('H', 'N', 'V', '$') +#define FNV_FILE_SIGNATURE hi_make_identifier('F', 'N', 'V', '#') + +#define FACTORY_NV_SIZE 0x2000 +#define FLASH_BLOCK_SIZE 0x1000 +#define HNV_NCRC_SIZE 8 +#define NV_TOTAL_MAX_NUM 255 +#define HNV_FAULT_TOLERANT_TIMES 3 + +#define HNV_MANAGE_FIXED_LEN 24 + +/* The NV structure in the factory area must be the same as that in the kernel and + cannot be modified after being fixed. */ +typedef struct _hi_nvm_manage_s_ { + hi_u32 magic; + hi_u32 crc; + hi_u8 ver; + hi_u8 head_len; + hi_u16 total_num; + hi_u32 seq; + hi_u32 ver_magic; + hi_u32 flash_size; + hi_u8 keep_id_range[2]; /* Reserved upg id, size:2 bytes, byte0:upper boundary, byte1:lower boundary */ + hi_u8 reserve[2]; /* Reserved 2 bytes */ + hi_u8 nv_item_data[0]; +} hi_nv_manage; + +typedef struct hi_nv_item_index_s_ { + hi_u8 nv_id; + hi_u8 nv_len; + hi_u16 nv_offset; +} hi_nv_item_index; + +typedef struct _hi_nv_ctrl_s_ { + hi_u32 base_addr; + hi_u32 block_size; + hi_u32 total_block_size; + hi_u32 current_addr; + hi_u32 seq; + hi_u32 sem_handle; + + hi_u8 init_flag; + hi_u8 reserve; + hi_u16 total_num; + hi_u32 ver_magic; + hi_nv_item_index* index; +} hi_nv_ctrl; + +typedef enum _hi_nv_type_e_ { + HI_TYPE_NV = 0, + HI_TYPE_FACTORY_NV, + HI_TYPE_TEMP, + HI_TYPE_NV_MAX, +} hi_nv_type; + +hi_u32 hi_nv_flush_keep_ids(hi_u8* addr, hi_u32 len); +hi_u32 hi_nv_block_write(hi_u8* nv_file, hi_u32 len, hi_u32 flag); + +/** @defgroup iot_nv NV Management APIs +* @ingroup iot_flashboot +*/ +/** +* @ingroup iot_nv +* Maximum length of an NV item (unit: byte). CNcomment:NV项最大长度(单位:byte)。CNend +*/ +#define HNV_ITEM_MAXLEN (256 - 4) + +/** +* @ingroup iot_nv +*/ +#define PRODUCT_CFG_NV_REG_NUM_MAX 20 + +/** +* @ingroup iot_nv +*/ +#define HI_FNV_DEFAULT_ADDR 0x8000 + +/** +* @ingroup iot_nv +*/ +#define HI_NV_DEFAULT_TOTAL_SIZE 0x2000 + +/** +* @ingroup iot_nv +*/ +#define HI_NV_DEFAULT_BLOCK_SIZE 0x1000 + +/** +* @ingroup iot_nv +* +* Factory NV area user area end ID. CNcomment:工厂区NV结束ID。CNend +*/ +#define HI_NV_FACTORY_USR_ID_END 0x20 + +/** +* @ingroup iot_nv +*/ +#define HI_NV_FTM_FLASH_PARTIRION_TABLE_ID 0x02 + +/** +* @ingroup iot_nv +* @brief Initializes NV management in the factory partition.CNcomment:工厂区NV初始化。CNend +* +* @par 描述: +* Initializes NV management in the factory partition.CNcomment: 工厂区NV管理初始化。CNend +* +* @attention The parameters cannot be set randomly and must match the product delivery plan. +CNcomment:参数不能随意配置,需要与产品出厂规划匹配。CNend +* @param addr [IN] type #hi_u32,Start address of the NV factory partition in the flash. The address is planned by +* the factory and set by the boot macro #FACTORY_NV_ADDR. +CNcomment:设置工厂区NV FLASH首地址,由出厂规划,boot宏定义FACTORY_NV_ADDR 统一设置。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_flashboot.h:Describes NV APIs.CNcomment:文件用于描述NV相关接口。CNend +* @see hi_factory_nv_write | hi_factory_nv_read。 +*/ +hi_u32 hi_factory_nv_init(hi_u32 addr, hi_u32 total_size, hi_u32 block_size); + +/** +* @ingroup iot_nv +* @brief Sets the NV value in the factory partition. CNcomment:设置工厂区NV值。CNend +* +* @par 描述: +* Sets the NV value in the factory partition.CNcomment:设置工厂区NV值。CNend +* +* @attention None +* @param id [IN] type #hi_u8,NV item ID, ranging from #HI_NV_FACTORY_ID_START to #HI_NV_FACTORY_USR_ID_END. +CNcomment:NV项ID,范围从#HI_NV_FACTORY_ID_START到#HI_NV_FACTORY_USR_ID_END。CNend +* @param pdata [IN] type #hi_pvoid,NV item data.CNcomment:NV项数据。CNend +* @param len [IN] type #hi_u8,Length of an NV item (unit: byte). The maximum value is #HNV_ITEM_MAXLEN. +CNcomment:NV项长度(单位:byte),最大不允许超过HNV_ITEM_MAXLEN。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_flashboot.h:Describes NV APIs.CNcomment:文件用于描述NV相关接口。CNend +* @see hi_factory_nv_read。 +*/ +hi_u32 hi_factory_nv_write(hi_u8 id, hi_pvoid pdata, hi_u8 len, hi_u32 flag); + +/** +* @ingroup iot_nv +* @brief Reads the NV value in the factory partition.CNcomment:读取工厂区NV值。CNend +* +* @par 描述: +* Reads the NV value in the factory partition.读取工厂区NV值。CNend +* +* @attention None +* +* @param id [IN] type #hi_u8,NV item ID, ranging from #HI_NV_NORMAL_ID_START to #HI_NV_NORMAL_USR_ID_END. +CNcomment:NV项ID,范围从#HI_NV_NORMAL_ID_START到#HI_NV_NORMAL_USR_ID_END。CNend +* @param pdata [IN] type #hi_pvoid,NV item data.CNcomment:NV项数据。CNend +* @param len [IN] type #hi_u8,Length of an NV item (unit: byte). The maximum value is HNV_ITEM_MAXLEN. +CNcomment:NV项长度(单位:byte),最大不允许超过HNV_ITEM_MAXLEN。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_flashboot.h:Describes NV APIs.CNcomment:文件用于描述NV相关接口。CNend +* @see hi_factory_nv_write。 +*/ +hi_u32 hi_factory_nv_read(hi_u8 id, hi_pvoid pdata, hi_u8 len, hi_u32 flag); + +/** @defgroup iot_crc32 CRC32 APIs +* @ingroup iot_flashboot +*/ +/** +* @ingroup iot_crc32 +* @brief Generates a 16-bit CRC value.CNcomment:生成16位CRC校验值。CNend +* +* @par 描述: +* Generates a 16-bit CRC value.CNcomment:生成16位CRC校验值。CNend +* +* @attention None +* @param crc [IN] type #hi_u16,The CRC initial value.CNcomment:CRC初始值。CNend +* @param p [IN] type #const hi_u8*,Pointer to the buffer to be verified. +CNcomment:被校验Buffer指针。CNend +* @param len [IN] type #hi_u32,Length of the buffer to be verified (unit: Byte). +CNcomment:被校验Buffer长度(单位:byte)。CNend +* +* @retval #HI_ERR_SUCCESS Success +* @retval #Other Failure. For details, see hi_boot_err.h. +* +* @par 依赖: +* @li hi_flashboot.h:Describes CRC APIs.CNcomment:文件包含CRC校验接口。CNend +* @see None +*/ +hi_u32 hi_crc32 (hi_u32 crc, const hi_u8 *p, hi_u32 len); + +#endif /* __HI_NVM_H__ */ + diff --git a/sdk_liteos/boot/loaderboot/include/load_partition_table.h b/sdk_liteos/boot/loaderboot/include/load_partition_table.h new file mode 100644 index 0000000000000000000000000000000000000000..ac267fc376a493ed12fa8902c7c5b9ea3f0ff519 --- /dev/null +++ b/sdk_liteos/boot/loaderboot/include/load_partition_table.h @@ -0,0 +1,112 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#define SFC_BUFFER_BASE_ADDRESS 0x400000 + +/** @defgroup iot_flash_partiton Partition Table APIs +* @ingroup iot_flashboot +*/ +/** + * @ingroup iot_flash_partiton + * + * partition number. + */ +#define HI_FLASH_PARTITON_MAX 12 + +/** + * @ingroup iot_flash_partiton + * + * partition ID. + */ +typedef enum { + HI_FLASH_PARTITON_BOOT = 0, /**< Boot partition ID.CNcomment:BOOT分区ID.CNend */ + HI_FLASH_PARTITON_FACTORY_NV, /**< Factory NV working partition ID.CNcomment:工厂NV分区ID.CNend */ + HI_FLASH_PARTITON_NORMAL_NV, /**< NORMAL NV partition ID.CNcomment:非工厂NV分区ID.CNend */ + HI_FLASH_PARTITON_NORMAL_NV_BACKUP, /**< NORMAL backup NV partition ID.CNcomment:非工厂NV备份分区ID,必须和非工厂区连续.CNend */ + HI_FLASH_PARTITON_KERNEL_A, /**< Kernel A running partition ID.CNcomment:内核A区ID.CNend */ + HI_FLASH_PARTITON_KERNEL_B, /**< Kernel B runing partition ID.CNcomment:内核B区ID.CNend */ + HI_FLASH_PARTITON_HILINK, /**< HILINK partition ID.CNcomment:HILINK分区ID(未使用HILINK可不需要).CNend */ + HI_FLASH_PARTITON_FILE_SYSTEM, /**< File system partition ID.CNcomment:文件系统区ID.CNend */ + HI_FLASH_PARTITON_USR_RESERVE, /**< User Reserved partition.CNcomment:用户保留区ID.CNend */ + HI_FLASH_PARTITON_HILINK_PKI, /**< HiLink PKI partition.CNcomment: HILINK PKI证书ID(未使用HILINK可不需要). CNend */ + HI_FLASH_PARTITON_CRASH_INFO, /**< Crash log partition.CNcomment:死机存储区ID.CNend */ + HI_FLASH_PARTITON_BOOT_BACK, /**< Boot backup partition.CNcomment:备份boot区ID. CNend */ +} hi_flash_partition_table_id; + +/** + * @ingroup iot_flash_partiton + * + * Flash partition management. CNcomment:Flash分区表项。CNend + */ +typedef struct { + hi_u32 addr : 24; /* Flash partition address. The value is 16 MB. If the address is in reverse order, + the value is the end low address. CNcomment:Flash分区地址,限制为16MB, + 如果为倒序,存放为结束的低地址值 CNend */ + hi_u32 id : 7; /* Flash partition ID. CNcomment:Flash区ID.CNend */ + hi_u32 dir : 1; /* Flash area storage direction. 0:regular. 1: reversed.CNcomment:Flash区存放方向。 + 0:分区内容正序;1:倒序末地址 CNend */ + + hi_u32 size : 24; /* Size of the parition(Unit:byte). CNcomment:Flash分区大小(单位:byte)CNend */ + hi_u32 reserve : 8; /* Reserved. CNcomment:保留区CNend */ + + hi_u32 addition; /* Supplementary information about the flash partition, such as the address of the Ram. + CNcomment:Flash分区补充信息,如Ram对应地址等 CNend */ +} hi_flash_partition_info; + +/** + * @ingroup iot_flash_partiton + * Flash partiton table. + */ +typedef struct { + hi_flash_partition_info table[HI_FLASH_PARTITON_MAX]; /**< Flash分区表项描述 */ +} hi_flash_partition_table; + +/** +* @ingroup iot_flash_partiton +* @brief Initialize flash partition table. CNcomment:初始化Flash分区表。CNend +* +* @par 描述: +* Initialize flash partition table. CNcomment:初始化Flash分区表。CNend +* +* @attention None. +* @param None. +* +* @retval #HI_ERR_FAILURE Failure. +* @retval #HI_ERR_SUCCESS Success. +* @par 依赖: +* @li hi_flashboot.h:Describes FlashBoot APIs.CNcomment:文件用于描述Boot模块接口。CNend +* @see hi_get_partition_table。 +*/ +hi_u32 hi_flash_partition_init(hi_void); + +/** +* @ingroup iot_flash_partiton +* @brief Get flash partition table. CNcomment:获取Flash分区表。CNend +* +* @par 描述: +* Get flash partition table. CNcomment:获取Flash分区表。CNend +* +* @attention None. +* @param None. +* +* @retval #HI_NULL Failure. +* @retval #Other Success. +* @par 依赖: +* @li hi_flashboot.h:Describes FlashBoot APIs.CNcomment:文件用于描述Boot模块接口。CNend +* @see hi_flash_partition_init。 +*/ +hi_flash_partition_table* hi_get_partition_table(hi_void); diff --git a/sdk_liteos/boot/loaderboot/module_config.mk b/sdk_liteos/boot/loaderboot/module_config.mk new file mode 100644 index 0000000000000000000000000000000000000000..9780043864c7b0f349da390b4115dec66192f244 --- /dev/null +++ b/sdk_liteos/boot/loaderboot/module_config.mk @@ -0,0 +1,41 @@ +loaderboot_srcs = startup common common/crc32 common/nvm common/partition_table drivers/lsadc drivers/flash drivers/efuse secure +loaderboot_common_srcs = ../commonboot/crc32 ../commonboot/efuse ../commonboot/flash +BOOT_CCFLAGS := -mabi=ilp32 -march=rv32imc -freorder-blocks-algorithm=simple -fno-schedule-insns -nostdinc -fno-aggressive-loop-optimizations -fno-builtin -fno-exceptions -fno-short-enums -mtune=size -msmall-data-limit=0 -Wall -Werror -Os -std=c99 -falign-functions=2 -fdata-sections -ffunction-sections -fno-common -fstack-protector-strong +BOOT_DEFINE := -DARCH_RISCV -DLOS_COMPILE_LDM -DHI_BOARD_ASIC +BOOT_INC := -I$(MAIN_TOPDIR)/boot/loaderboot/include \ + -I$(MAIN_TOPDIR)/boot/loaderboot/fixed/include \ + -I$(MAIN_TOPDIR)/boot/loaderboot/secure \ + -I$(MAIN_TOPDIR)/boot/commonboot + +ifeq ($(CONFIG_COMPRESSION_OTA_SUPPORT), y) + BOOT_DEFINE += -DCONFIG_COMPRESSION_OTA_SUPPORT +endif + +ifeq ($(CONFIG_DUAL_PARTITION_OTA_SUPPORT), y) + BOOT_DEFINE += -DCONFIG_DUAL_PARTITION_OTA_SUPPORT +endif + +ifeq ($(CONFIG_TARGET_SIG_ECC), y) + BOOT_DEFINE += -DCONFIG_TARGET_SIG_ECC +endif + +ifeq ($(CONFIG_TARGET_SIG_RSA_V15), y) + BOOT_DEFINE += -DCONFIG_TARGET_SIG_RSA_V15 +endif + +ifeq ($(CONFIG_TARGET_SIG_RSA_PSS), y) + BOOT_DEFINE += -DCONFIG_TARGET_SIG_RSA_PSS +endif + +ifeq ($(CONFIG_FLASH_ENCRYPT_SUPPORT), y) + BOOT_DEFINE += -DCONFIG_FLASH_ENCRYPT_SUPPORT +endif + +ifeq ($(CONFIG_CHIP_PKT_48K), y) + BOOT_DEFINE += -DCONFIG_CHIP_PKT_48K +else + BOOT_DEFINE += -DCONFIG_CHIP_PKT_32K +endif + +BOOT_ASFLAGS = -mabi=ilp32 -march=rv32imc -x assembler-with-cpp -Os -Wall -Werror -nostdinc -fno-common +BOOT_LINK_FLAGS = -nostdlib -nostartfiles -static --gc-sections diff --git a/sdk_liteos/boot/loaderboot/secure/SConscript b/sdk_liteos/boot/loaderboot/secure/SConscript new file mode 100755 index 0000000000000000000000000000000000000000..aceb2b6a9464ce64030c1f9c5374ec933dcab384 --- /dev/null +++ b/sdk_liteos/boot/loaderboot/secure/SConscript @@ -0,0 +1,6 @@ +Import('env') + +env = env.Clone() + +objs = env.Object(Glob('*.c')) +Return('objs') diff --git a/sdk_liteos/boot/loaderboot/secure/burn_file.c b/sdk_liteos/boot/loaderboot/secure/burn_file.c new file mode 100644 index 0000000000000000000000000000000000000000..749ad993e5c12b86ab31bac3b74cd4c5ad0e5afa --- /dev/null +++ b/sdk_liteos/boot/loaderboot/secure/burn_file.c @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include "burn_file.h" + +hi_u32 loaderboot_get_section_head(hi_u32 addr, hi_upg_section_head *section_head) +{ + hi_upg_common_head head = { 0 }; + hi_u32 ret; + + if (section_head == HI_NULL) { + return HI_ERR_UPG_NULL_POINTER; + } + ret = hi_flash_read(addr, sizeof(hi_upg_common_head), (hi_u8 *)(&head)); + if (ret != HI_ERR_SUCCESS) { + boot_msg1("[bootupg get section head]flash read ret:", ret); + return ret; + } + ret = hi_flash_read(addr + head.section_offset, sizeof(hi_upg_section_head), (hi_u8 *)section_head); + if (ret != HI_ERR_SUCCESS) { + boot_msg1("[bootupg get section head]flash read ret:", ret); + return ret; + } + + return ret; +} + +hi_void loaderboot_get_start_addr_offset(hi_u32 addr, hi_u32 *offset) +{ + hi_upg_section_head section_head = { 0 }; + hi_u32 ret = loaderboot_get_section_head(addr, §ion_head); + if (ret == HI_ERR_SUCCESS) { + *offset = addr + section_head.section0_offset; + } else { + boot_msg1("[boot get start addr offset]fail.", ret); + *offset = addr; + } +} \ No newline at end of file diff --git a/sdk_liteos/boot/loaderboot/secure/burn_file.h b/sdk_liteos/boot/loaderboot/secure/burn_file.h new file mode 100644 index 0000000000000000000000000000000000000000..2d3cf6f4d2363897944569744ae94978f4f18a0d --- /dev/null +++ b/sdk_liteos/boot/loaderboot/secure/burn_file.h @@ -0,0 +1,187 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __HI_BURN_FILE_H__ +#define __HI_BURN_FILE_H__ + +#include + +/** + * + * Initial vector length.CNcomment:初始向量长度。CNend + */ +#define IV_BYTE_LEN 16 + +/** + * + * RSA2048 parameter length.CNcomment:RSA2048参数长度。CNend + */ +#define RSA_2048_LEN 256 + +/** + * + * RSA2048 parameter E length.CNcomment:RSA2048参数E长度。CNend + */ +#define RSA_EXP_E_LEN 4 + +/** + * + * ECC parameter length.CNcomment:ECC参数长度。CNend + */ +#define ECC_32_BYTES 32 + +/** + * + * SHA256 hash length.CNcomment:SHA256哈希值长度。CNend + */ +#define SHA_256_LEN 32 + +/** + * + * Kernel upgrade file.CNcomment:Kernel升级文件。CNend + */ +#define HI_UPG_FILE_KERNEL 0xF0 /* Kernel upgrade file. */ + +/** + * + * FlashBoot upgrade file.CNcomment:FlashBoot升级文件。CNend + */ +#define HI_UPG_FILE_BOOT 0xE1 /* FlashBoot upgrade file. */ + +/** + * + * Parameter of sign algorithm.CNcomment:签名算法参数。CNend + */ +typedef struct { + hi_u32 hash_alg : 16; /**< HASH algorithm:0:SHA256.CNcomment:HASH算法。CNend */ + hi_u32 sign_alg : 6; /**< Sign algorithm:0:RSA-PKCS;1:RSA-PSS;0x10:ECDSA256;0x3F:SHA256.CNcomment:签名算法。CNend */ + hi_u32 sign_param : 10; /**< Sign parameter, default '0'.CNcomment:HASH算法。CNend */ +} sign_alg_param; + +typedef struct { + hi_u8 mod_n[RSA_2048_LEN]; /**< Mod N.CNcomment:RSA参数N。CNend */ + hi_u8 exp_e[RSA_EXP_E_LEN]; /**< Exp E.CNcomment:RSA参数E。CNend */ + hi_u8 padding[28]; /**< Padding field:28.CNcomment:填充字段。CNend */ +} upg_rsa_key; + +typedef struct { + hi_u8 sign[RSA_2048_LEN]; /**< RSA signature.CNcomment:RSA签名。CNend */ +} upg_rsa_sign; + +typedef struct { + hi_u8 px[ECC_32_BYTES]; /**< Pubkey x.CNcomment:ECC密钥x。CNend */ + hi_u8 py[ECC_32_BYTES]; /**< Pubkey y.CNcomment:ECC密钥y。CNend */ + hi_u8 padding[224]; /**< Padding field:224. CNcomment:填充字段。CNend */ +} upg_ecc_key; + +typedef struct { + hi_u8 r[ECC_32_BYTES]; /**< Signature of ECC.CNcomment:ECC签名信息r。CNend */ + hi_u8 s[ECC_32_BYTES]; /**< Signature of ECC.CNcomment:ECC签名信息s。CNend */ + hi_u8 padding[192]; /**< Padding field:192.CNcomment:填充字段。CNend */ +} upg_ecc_sign; + +typedef struct { + hi_u8 padding[288]; /**< Padding field:288.CNcomment:填充字段。CNend */ +} upg_sha256_key; + +typedef struct { + hi_u8 check_sum[SHA_256_LEN]; /**< Hash value of SHA256.CNcomment:SHA256算法哈希值。CNend */ + hi_u8 padding[224]; /**< Padding field:224.CNcomment:填充字段。CNend */ +} upg_sha256_sign; + +typedef struct { + hi_u8 reserved[32]; /**< 32:Reserved for user.CNcomment:用户字段定义字段。CNend */ +}hi_upg_user_info; + +typedef struct { + hi_u32 image_id; /**< Identity of upgrade file Key Area.CNcomment:升级文件魔术字。CNend */ + hi_u32 struct_version; /**< The structure of upgrade file version.CNcomment:升级文件结构体版本号。CNend */ + hi_u32 section_offset; /**< Offset of upgrade Section.CNcomment:Section段偏移。CNend */ + hi_u32 section_len; /**< Length of upgrade Section.CNcomment:Section段长度。CNend */ + hi_upg_user_info user_info; /**< Reserved for user.CNcomment:用户自定义字段。CNend */ + hi_u8 file_type; /**< Upgrade file type:0xF0: kernel file; 0xE1: boot file.CNcomment:升级文件类型。CNend */ + hi_u8 file_version; /**< File Version, for anti-rollback. [0, 16] for boot file and [0, 48] for kernel file. + CNcomment:升级文件结构体版本号。CNend */ + hi_u8 encrypt_flag; /**< 0x42: Section Area is not encrypted; other: Section Area is encrypted. + CNcomment:Section段加密标志。CNend */ + hi_u8 file_attr; /**< File Attributes.CNcomment:文件属性。CNend */ + hi_u32 file_len; /**< Entire file length.CNcomment:升级文件长度。CNend */ + hi_u32 key_len; /**< Length of Key(288Bytes).True length:RSA2048: 272 Bytes, ECDSA: 64Bytes. + CNcomment:密钥长度。CNend */ + sign_alg_param param; /**< Parma of the signature algorithm.CNcomment:签名算法参数。CNend */ + hi_u8 aes_key[IV_BYTE_LEN]; /**< Part of key factor.CNcomment:AES密钥。CNend */ + hi_u8 aes_iv[IV_BYTE_LEN]; /**< The IV (AES-256 CBC-mode) to encrypt Section.CNcomment:AES初始向量。CNend */ +} hi_upg_common_head; + +typedef struct { + hi_u32 image_id; /**< Identity of upgrade file Key Area.CNcomment:升级文件魔术字。CNend */ + hi_u32 struct_version; /**< The structure of upgrade file Section Area.CNcomment:升级文件结构体版本号。CNend */ + sign_alg_param param; /**< The signature algorithm.CNcomment:签名算法参数。CNend */ + hi_u8 section_count; /**< The number of sections.CNcomment:Section段个数。CNend */ + hi_u8 reserved[27]; /**< 27 bytes reserved.CNcomment:保留字段。CNend */ + hi_u8 section0_compress; /**< Whether section 0 is compressed.CNcomment:Section0是否压缩。CNend */ + hi_u8 pad0[3]; /**< 3 bytes padding.CNcomment:填充字段。CNend */ + hi_u32 section0_offset; /**< Offset of Section0.CNcomment:Section0段偏移。CNend */ + hi_u32 section0_len; /**< Length of Section0, aligned to 16 bytes.CNcomment:Section0段长度。CNend */ + hi_u8 section1_compress; /**< Whether section 1 is compressed.CNcomment:Section1是否压缩Nend */ + hi_u8 pad1[3]; /**< 3 bytes padding.CNcomment:填充字段。CNend */ + hi_u32 section1_offset; /**< Offset of Section1.CNcomment:Section1段偏移。CNend */ + hi_u32 section1_len; /**< Length of Section1, aligned to 16 bytes.CNcomment:Section1段长度。CNend */ +} hi_upg_section_head; + +typedef struct { + upg_rsa_key key; /**< Key of rsa.CNcomment:RSA算法密钥。CNend */ + upg_rsa_sign sign; /**< Sign of rsa.CNcomment:RSA算法签名。CNend */ +} hi_upg_rsa_alg; + +typedef struct { + upg_ecc_key key; /**< Key of ecc.CNcomment:ECC算法密钥。CNend */ + upg_ecc_sign sign; /**< Sign of ecc.CNcomment:ECC算法签名。CNend */ +} hi_upg_ecc_alg; + +typedef struct { + upg_sha256_key key; /**< Padding field.CNcomment:填充字段。CNend */ + upg_sha256_sign sign; /**< Hash of sha256.CNcomment:SHA256算法哈希值。CNend */ +} hi_upg_sha256_alg; + +typedef struct { + union { + upg_rsa_key rsa; /**< Key of rsa.CNcomment:rsa密钥。CNend */ + upg_ecc_key ecc; /**< Key of ecc.CNcomment:ecc密钥。CNend */ + upg_sha256_key sha; /**< Padding field.CNcomment:填充字段。CNend */ + } key; +}hi_upg_key; + +typedef struct { + union { + upg_rsa_sign rsa; /**< Sign of rsa.CNcomment:rsa签名。CNend */ + upg_ecc_sign ecc; /**< Sign of ecc.CNcomment:ecc签名。CNend */ + upg_sha256_sign sha; /**< Hash of sha256.CNcomment:SHA256哈希。CNend */ + } sign; +}hi_upg_sign; + +typedef struct { + hi_upg_common_head common; /**< Common head of upg file.CNcomment:公共文件头。CNend */ + union { + hi_upg_rsa_alg rsa; /**< Key and sign of RSA.CNcomment:RSA密钥及签名信息。CNend */ + hi_upg_ecc_alg ecc; /**< Key and sign of ECC.CNcomment:ECC密钥及签名信息。CNend */ + hi_upg_sha256_alg sha;/**< Key and sign of SHA256.CNcomment:SHA256密钥及签名信息。CNend */ + } sign_alg; +} hi_upg_head; + + +hi_void loaderboot_get_start_addr_offset(hi_u32 addr, hi_u32 *offset); + +#endif diff --git a/sdk_liteos/boot/loaderboot/secure/load_crypto.c b/sdk_liteos/boot/loaderboot/secure/load_crypto.c new file mode 100644 index 0000000000000000000000000000000000000000..cd548dd0a8f198fb7178b0fe878012d3262c5970 --- /dev/null +++ b/sdk_liteos/boot/loaderboot/secure/load_crypto.c @@ -0,0 +1,504 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef CONFIG_FLASH_ENCRYPT_SUPPORT +#include +#include +#include "load_crypto.h" +#include "burn_file.h" + +hi_void loader_clear_content(hi_u8 *content, hi_u32 content_len) +{ + if ((content == HI_NULL) || (content_len == 0)) { + return; + } + + hi_u32 cs = (uintptr_t)content ^ content_len ^ 0x0 ^ content_len; + (hi_void)memset_s(content, content_len, 0x0, content_len, cs); +} + +static hi_void crpto_set_aes_ctrl_default_value(hi_cipher_aes_ctrl *aes_ctrl) +{ + if (aes_ctrl == HI_NULL) { + return; + } + aes_ctrl->random_en = HI_FALSE; + aes_ctrl->key_from = HI_CIPHER_AES_KEY_FROM_CPU; + aes_ctrl->work_mode = HI_CIPHER_AES_WORK_MODE_CBC; + aes_ctrl->key_len = HI_CIPHER_AES_KEY_LENGTH_256BIT; +} + +static hi_u32 crypto_destory(hi_void) +{ + return hi_cipher_deinit(); +} + +static hi_u32 crypto_load_salt(crypto_workkey_partition part, hi_flash_crypto_content *key_content) +{ + hi_u32 ret = HI_ERR_SUCCESS; + hi_u8 salt_e[ROOT_SALT_LENGTH] = { 0 }; + + hi_u32 cs = (uintptr_t)salt_e ^ (hi_u32)sizeof(salt_e) ^ 0x0 ^ ROOT_SALT_LENGTH; + (hi_void) memset_s(salt_e, sizeof(salt_e), 0x0, ROOT_SALT_LENGTH, cs); + + if (part == CRYPTO_WORKKEY_KERNEL_A) { + ret = hi_factory_nv_read(HI_NV_FTM_KERNELA_WORK_ID, key_content, sizeof(hi_flash_crypto_content), 0); + if (ret != HI_ERR_SUCCESS) { + goto fail; + } + } else if (part == CRYPTO_WORKKEY_KERNEL_A_BACKUP) { + ret = hi_factory_nv_read(HI_NV_FTM_BACKUP_KERNELA_WORK_ID, key_content, sizeof(hi_flash_crypto_content), 0); + if (ret != HI_ERR_SUCCESS) { + goto fail; + } + } + + if (memcmp(key_content->root_salt, salt_e, ROOT_SALT_LENGTH) == HI_ERR_SUCCESS) { + ret = HI_PRINT_ERRNO_CRYPTO_SALT_EMPTY_ERR; + goto fail; + } +fail: + return ret; +} + +static hi_u32 crypto_get_root_salt(hi_flash_crypto_content *key_content) +{ + hi_u32 ret = crypto_load_salt(CRYPTO_WORKKEY_KERNEL_A, key_content); + if (ret != HI_ERR_SUCCESS) { + ret = crypto_load_salt(CRYPTO_WORKKEY_KERNEL_A_BACKUP, key_content); + if (ret == HI_PRINT_ERRNO_CRYPTO_SALT_EMPTY_ERR) { + ret = hi_cipher_trng_get_random_bytes(key_content->root_salt, ROOT_SALT_LENGTH); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + } + } + + return ret; +} + +static hi_u32 crypto_prepare(hi_flash_crypto_content *save_content) +{ + hi_u32 ret; + hi_u8 rootkey_iv[ROOTKEY_IV_BYTE_LENGTH]; + hi_cipher_kdf_ctrl ctrl; + hi_u32 cs; + + ret = hi_cipher_init(); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + ret = crypto_get_root_salt(save_content); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + cs = (uintptr_t)rootkey_iv ^ sizeof(rootkey_iv) ^ ((uintptr_t)save_content->root_salt) ^ ROOT_SALT_LENGTH; + ret = memcpy_s(rootkey_iv, sizeof(rootkey_iv), save_content->root_salt, ROOT_SALT_LENGTH, cs); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + ctrl.salt = rootkey_iv; + ctrl.salt_len = sizeof(rootkey_iv); + ctrl.kdf_cnt = KDF_ITERATION_CNT; + ctrl.kdf_mode = HI_CIPHER_SSS_KDF_KEY_STORAGE; + return hi_cipher_kdf_key_derive(&ctrl); +} + +hi_u32 boot_get_crypto_kernel_start(uintptr_t file_addr) +{ + hi_u32 flash_offset = 0; + loaderboot_get_start_addr_offset(file_addr, &flash_offset); + + return flash_offset; +} + +static hi_u32 crypto_decrypt_hash(hi_flash_crypto_content *key_content) +{ + hi_u32 ret; + hi_u32 cs; + hi_u32 content_size = (hi_u32)sizeof(hi_flash_crypto_content); + + hi_flash_crypto_content *content_tmp = (hi_flash_crypto_content *)boot_malloc(content_size); + if (content_tmp == HI_NULL) { + return HI_PRINT_ERRNO_MALLOC_EXAUST_ERR; + } + + cs = (uintptr_t)(content_tmp) ^ content_size ^ (uintptr_t)(key_content) ^ content_size; + ret = (hi_u32)memcpy_s(content_tmp, content_size, key_content, content_size, cs); + if (ret != EOK) { + goto fail; + } + + hi_cipher_aes_ctrl aes_ctrl = { + .random_en = HI_FALSE, + .key_from = HI_CIPHER_AES_KEY_FROM_KDF, + .work_mode = HI_CIPHER_AES_WORK_MODE_CBC, + .key_len = HI_CIPHER_AES_KEY_LENGTH_256BIT, + }; + cs = (uintptr_t)(aes_ctrl.iv) ^ (hi_u32)sizeof(aes_ctrl.iv) ^ (uintptr_t)(content_tmp->iv_nv) ^ IV_BYTE_LENGTH; + ret = (hi_u32)memcpy_s(aes_ctrl.iv, sizeof(aes_ctrl.iv), content_tmp->iv_nv, IV_BYTE_LENGTH, cs); + if (ret != EOK) { + goto fail; + } + ret = hi_cipher_aes_config(&aes_ctrl); + if (ret != HI_ERR_SUCCESS) { + goto crypto_fail; + } + ret = hi_cipher_aes_crypto((uintptr_t)content_tmp->iv_content, (uintptr_t)key_content->iv_content, + content_size - ROOT_SALT_LENGTH - IV_BYTE_LENGTH, HI_FALSE); + if (ret != HI_ERR_SUCCESS) { + goto crypto_fail; + } + +crypto_fail: + (hi_void) hi_cipher_aes_destroy_config(); +fail: + loader_clear_content((hi_u8 *)content_tmp, content_size); + crypto_mem_free(content_tmp); + return ret; +} + +static hi_u32 crypto_encrypt_hash(hi_flash_crypto_content *key_content) +{ + hi_cipher_aes_ctrl aes_ctrl; + hi_u32 ret; + hi_u32 content_size = (hi_u32)sizeof(hi_flash_crypto_content); + hi_u32 encrypt_size = content_size - ROOT_SALT_LENGTH - IV_BYTE_LENGTH; + + hi_flash_crypto_content *data_tmp = (hi_flash_crypto_content *)boot_malloc(content_size); + if (data_tmp == HI_NULL) { + return HI_PRINT_ERRNO_MALLOC_EXAUST_ERR; + } + + hi_u32 cs = (uintptr_t)(aes_ctrl.iv) ^ (hi_u32)sizeof(aes_ctrl.iv) ^ (uintptr_t)(key_content->iv_nv) ^ + IV_BYTE_LENGTH; + ret = (hi_u32)memcpy_s(aes_ctrl.iv, sizeof(aes_ctrl.iv), key_content->iv_nv, IV_BYTE_LENGTH, cs); + if (ret != EOK) { + goto fail; + } + + aes_ctrl.random_en = HI_FALSE; + aes_ctrl.key_from = HI_CIPHER_AES_KEY_FROM_KDF; + aes_ctrl.work_mode = HI_CIPHER_AES_WORK_MODE_CBC; + aes_ctrl.key_len = HI_CIPHER_AES_KEY_LENGTH_256BIT; + ret = hi_cipher_aes_config(&aes_ctrl); + if (ret != HI_ERR_SUCCESS) { + goto crypto_fail; + } + ret = hi_cipher_aes_crypto((uintptr_t)key_content->iv_content, (uintptr_t)(data_tmp->iv_content), + encrypt_size, HI_TRUE); + if (ret != HI_ERR_SUCCESS) { + goto crypto_fail; + } + + cs = (uintptr_t)(key_content->iv_content) ^ encrypt_size ^ (uintptr_t)(data_tmp->iv_content) ^ encrypt_size; + ret = (hi_u32)memcpy_s(key_content->iv_content, encrypt_size, data_tmp->iv_content, encrypt_size, cs); + +crypto_fail: + (hi_void) hi_cipher_aes_destroy_config(); +fail: + loader_clear_content((hi_u8 *)data_tmp, content_size); + crypto_mem_free(data_tmp); + return ret; +} + +static hi_u32 crypto_load_key_content(crypto_workkey_partition part, hi_flash_crypto_content *key_content) +{ + hi_u32 ret = HI_ERR_SUCCESS; + hi_u8 hash[SHA_256_LENGTH]; + hi_u8 key_e[KEY_BYTE_LENGTH] = { 0 }; + + hi_u32 cs = (uintptr_t)key_e ^ (hi_u32)sizeof(key_e) ^ 0x0 ^ KEY_BYTE_LENGTH; + (hi_void) memset_s(key_e, sizeof(key_e), 0x0, KEY_BYTE_LENGTH, cs); + if (part == CRYPTO_WORKKEY_KERNEL_A) { + ret = hi_factory_nv_read(HI_NV_FTM_KERNELA_WORK_ID, key_content, sizeof(hi_flash_crypto_content), 0); + if (ret != HI_ERR_SUCCESS) { + goto fail; + } + } else if (part == CRYPTO_WORKKEY_KERNEL_A_BACKUP) { + ret = hi_factory_nv_read(HI_NV_FTM_BACKUP_KERNELA_WORK_ID, key_content, sizeof(hi_flash_crypto_content), 0); + if (ret != HI_ERR_SUCCESS) { + goto fail; + } + } + + if (memcmp(key_content->work_text, key_e, KEY_BYTE_LENGTH) == HI_ERR_SUCCESS) { + ret = HI_PRINT_ERRNO_CRYPTO_KEY_EMPTY_ERR; + goto fail; + } + + ret = crypto_decrypt_hash(key_content); + if (ret != HI_ERR_SUCCESS) { + goto fail; + } + + ret = hi_cipher_hash_sha256((uintptr_t)(key_content->root_salt), sizeof(hi_flash_crypto_content) - SHA_256_LENGTH, + hash, SHA_256_LENGTH); + if (ret != HI_ERR_SUCCESS) { + goto fail; + } + if (memcmp(key_content->content_sh256, hash, SHA_256_LENGTH) != HI_ERR_SUCCESS) { + ret = HI_PRINT_ERRNO_CRYPTO_KEY_INVALID_ERR; + goto fail; + } +fail: + return ret; +} + +static hi_u32 crypto_save_work_key(crypto_workkey_partition part, hi_flash_crypto_content *key_content) +{ + hi_u32 ret; + hi_u32 cs; + hi_u32 content_size = (hi_u32)sizeof(hi_flash_crypto_content); + hi_flash_crypto_content *content_tmp = (hi_flash_crypto_content *)boot_malloc(content_size); + if (content_tmp == HI_NULL) { + return HI_PRINT_ERRNO_MALLOC_EXAUST_ERR; + } + + cs = (uintptr_t)(content_tmp) ^ content_size ^ (uintptr_t)(key_content) ^ content_size; + ret = (hi_u32)memcpy_s(content_tmp, content_size, key_content, content_size, cs); + if (ret != EOK) { + goto fail; + } + + /* Encrypt,then save to factory NV */ + ret = crypto_encrypt_hash(content_tmp); + if (ret != HI_ERR_SUCCESS) { + goto fail; + } + + if ((hi_u32)part & CRYPTO_WORKKEY_KERNEL_A) { + ret = hi_factory_nv_write(HI_NV_FTM_KERNELA_WORK_ID, content_tmp, content_size, 0); + if (ret != HI_ERR_SUCCESS) { + ret = HI_PRINT_ERRNO_CRYPTO_KEY_SAVE_ERR; + goto fail; + } + } + if ((hi_u32)part & CRYPTO_WORKKEY_KERNEL_A_BACKUP) { + ret = hi_factory_nv_write(HI_NV_FTM_BACKUP_KERNELA_WORK_ID, content_tmp, content_size, 0); + if (ret != HI_ERR_SUCCESS) { + ret = HI_PRINT_ERRNO_CRYPTO_KEY_SAVE_ERR; + goto fail; + } + } + +fail: + loader_clear_content((hi_u8 *)content_tmp, content_size); + crypto_mem_free(content_tmp); + return ret; +} + +static hi_u32 crypto_is_need_gen_key(hi_flash_crypto_content *key_content, hi_u8 *need_gen_key) +{ + hi_u32 cs; + hi_flash_crypto_content tmp_content = {0}; + hi_u32 content_size = sizeof(hi_flash_crypto_content); + + hi_u32 ret = crypto_load_key_content(CRYPTO_WORKKEY_KERNEL_A, &tmp_content); + if (ret != HI_ERR_SUCCESS) { + ret = crypto_load_key_content(CRYPTO_WORKKEY_KERNEL_A_BACKUP, &tmp_content); + if (ret == HI_PRINT_ERRNO_CRYPTO_KEY_EMPTY_ERR) { + *need_gen_key = 1; + return HI_ERR_SUCCESS; + } else if (ret != HI_ERR_SUCCESS) { + goto fail; + } else { + ret = crypto_save_work_key(CRYPTO_WORKKEY_KERNEL_A, &tmp_content); + } + } + + if (ret == HI_ERR_SUCCESS) { + cs = (uintptr_t)(key_content) ^ content_size ^ (uintptr_t)(&tmp_content) ^ content_size; + ret = (hi_u32)memcpy_s(key_content, content_size, &tmp_content, content_size, cs); + } + + cs = (uintptr_t)(&tmp_content) ^ content_size ^ 0x0 ^ content_size; + (hi_void)memset_s(&tmp_content, content_size, 0x0, content_size, cs); + +fail: + return ret; +} + +static hi_u32 crypto_gen_key_content(hi_flash_crypto_content *key_content) +{ + hi_u8 salt[IV_BYTE_LENGTH]; + hi_u8 kdf_key[KEY_BYTE_LENGTH]; + hi_cipher_kdf_ctrl ctrl; + + (hi_void)hi_cipher_trng_get_random_bytes(salt, IV_BYTE_LENGTH); + (hi_void)hi_cipher_trng_get_random_bytes(kdf_key, KEY_BYTE_LENGTH); + (hi_void)hi_cipher_trng_get_random_bytes(key_content->iv_nv, IV_BYTE_LENGTH); + (hi_void)hi_cipher_trng_get_random_bytes(key_content->iv_content, IV_BYTE_LENGTH); + + hi_u32 cs = (uintptr_t)(ctrl.key) ^ (hi_u32)sizeof(ctrl.key) ^ (uintptr_t)kdf_key ^ (hi_u32)sizeof(kdf_key); + if ((hi_u32)memcpy_s(ctrl.key, sizeof(ctrl.key), kdf_key, sizeof(kdf_key), cs) != EOK) { + return HI_ERR_FAILURE; + } + ctrl.salt = salt; + ctrl.salt_len = sizeof(salt); + ctrl.kdf_cnt = KDF_ITERATION_CNT; + ctrl.kdf_mode = HI_CIPHER_SSS_KDF_KEY_DEVICE; /* In this mode, user should provide root key. */ + if (hi_cipher_kdf_key_derive(&ctrl) != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + + cs = (uintptr_t)(key_content->work_text) ^ KEY_BYTE_LENGTH ^ (uintptr_t)(ctrl.result) ^ + (hi_u32)sizeof(ctrl.result); + if (memcpy_s(key_content->work_text, KEY_BYTE_LENGTH, ctrl.result, sizeof(ctrl.result), cs) != EOK) { + return HI_ERR_FAILURE; + } + + if (hi_cipher_hash_sha256((uintptr_t)(key_content->root_salt), sizeof(hi_flash_crypto_content) - SHA_256_LENGTH, + key_content->content_sh256, SHA_256_LENGTH) != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + + return HI_ERR_SUCCESS; +} + +static hi_u32 crypto_encrypt_data(hi_flash_crypto_content *content, hi_u32 flash_addr, hi_u32 len) +{ + hi_u32 ret = HI_ERR_FAILURE; + hi_cipher_aes_ctrl aes_ctrl; + + hi_u8 *fw_cyp_data = boot_malloc(len); + if (fw_cyp_data == HI_NULL) { + return HI_PRINT_ERRNO_CRYPTO_PREPARE_ERR; + } + + hi_u32 cs = (uintptr_t)(aes_ctrl.key) ^ (hi_u32)sizeof(aes_ctrl.key) ^ + (uintptr_t)(content->work_text) ^ KEY_BYTE_LENGTH; + if (memcpy_s(aes_ctrl.key, sizeof(aes_ctrl.key), content->work_text, KEY_BYTE_LENGTH, cs) != EOK) { + goto fail; + } + + cs = (uintptr_t)(aes_ctrl.iv) ^ (hi_u32)sizeof(aes_ctrl.iv) ^ (uintptr_t)(content->iv_content) ^ IV_BYTE_LENGTH; + if (memcpy_s(aes_ctrl.iv, sizeof(aes_ctrl.iv), content->iv_content, IV_BYTE_LENGTH, cs) != EOK) { + goto fail; + } + + crpto_set_aes_ctrl_default_value(&aes_ctrl); + ret = hi_cipher_aes_config(&aes_ctrl); + if (ret != HI_ERR_SUCCESS) { + goto fail; + } + + ret = hi_cipher_aes_crypto(flash_addr + SFC_BUFFER_BASE_ADDRESS, (uintptr_t)fw_cyp_data, len, HI_TRUE); + if (ret != HI_ERR_SUCCESS) { + goto crypto_fail; + } + + ret = g_flash_cmd_funcs.write(flash_addr, len, (hi_u8 *)fw_cyp_data, HI_TRUE); + if (ret != HI_ERR_SUCCESS) { + goto crypto_fail; + } + +crypto_fail: + (hi_void) hi_cipher_aes_destroy_config(); +fail: + crypto_mem_free(fw_cyp_data); + return ret; +} + +hi_u32 crypto_burn_encrypt(uintptr_t file_addr) +{ + hi_u8 need_gen_key = 0; + hi_u32 crypto_kernel_addr = boot_get_crypto_kernel_start(file_addr); + + hi_flash_crypto_content *key_content = (hi_flash_crypto_content *)boot_malloc(sizeof(hi_flash_crypto_content)); + if (key_content == HI_NULL) { + return HI_PRINT_ERRNO_CRYPTO_PREPARE_ERR; + } + + hi_u32 ret = crypto_prepare(key_content); + if (ret != HI_ERR_SUCCESS) { + loader_clear_content((hi_u8 *)key_content, sizeof(hi_flash_crypto_content)); + crypto_mem_free(key_content); + return HI_PRINT_ERRNO_CRYPTO_PREPARE_ERR; + } + + ret = crypto_is_need_gen_key(key_content, &need_gen_key); + if (ret != HI_ERR_SUCCESS) { + goto fail; + } + + if (need_gen_key == 1) { + ret = crypto_gen_key_content(key_content); + if (ret != HI_ERR_SUCCESS) { + goto fail; + } + + if (crypto_save_work_key(CRYPTO_WORKKEY_KERNEL_A_BOTH, key_content) != HI_ERR_SUCCESS) { + goto fail; + } + } + + ret = crypto_encrypt_data(key_content, crypto_kernel_addr, CRYPTO_KERNEL_LENGTH); + if (ret != HI_ERR_SUCCESS) { + ret = HI_PRINT_ERRNO_CRYPTO_FW_ENCRYPT_ERR; + goto fail; + } + +fail: + loader_clear_content((hi_u8 *)key_content, sizeof(hi_flash_crypto_content)); + crypto_mem_free(key_content); + crypto_destory(); + return ret; +} + +hi_u32 crypto_check_encrypt(hi_void) +{ + hi_u32 ret; + ret = hi_factory_nv_init(HI_FNV_DEFAULT_ADDR, HI_NV_DEFAULT_TOTAL_SIZE, HI_NV_DEFAULT_BLOCK_SIZE); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + ret = hi_flash_partition_init(); + if (ret != HI_ERR_SUCCESS) { /* use flash table */ + return ret; + } + + hi_flash_partition_table *partition = hi_get_partition_table(); + uintptr_t kernel_a_addr = partition->table[HI_FLASH_PARTITON_KERNEL_A].addr; + + /* 应用程序加密流程 */ + /* Application bin encryption process */ + ret = crypto_burn_encrypt(kernel_a_addr); + if (ret != HI_ERR_SUCCESS) { + boot_put_errno(ret); + return ret; + } + + return HI_ERR_SUCCESS; +} + +hi_u32 crypto_encrypt_factory_image(uintptr_t file_addr) +{ + /* 产测程序加密流程 */ + /* Factory test bin encryption process */ + hi_u32 ret = crypto_burn_encrypt(file_addr); + if (ret != HI_ERR_SUCCESS) { + boot_put_errno(ret); + return ret; + } + + return HI_ERR_SUCCESS; +} + +#endif diff --git a/sdk_liteos/boot/loaderboot/secure/load_crypto.h b/sdk_liteos/boot/loaderboot/secure/load_crypto.h new file mode 100644 index 0000000000000000000000000000000000000000..20d25f541aea4e212787a36ea8dd671594ecd27f --- /dev/null +++ b/sdk_liteos/boot/loaderboot/secure/load_crypto.h @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __LOAD_CRYPTO_H__ +#define __LOAD_CRYPTO_H__ +#ifdef CONFIG_FLASH_ENCRYPT_SUPPORT +#include + +#define crypto_mem_free(sz) \ + do { \ + if ((sz) != HI_NULL) { \ + boot_free(sz); \ + } \ + (sz) = HI_NULL; \ + } while (0) + +#define IV_BYTE_LENGTH 16 +#define ROOTKEY_IV_BYTE_LENGTH 32 + +#define DIE_ID_BYTE_LENGTH 24 + +#define KEY_BYTE_LENGTH 32 + +#define SHA_256_LENGTH 32 + +#define ROOT_SALT_LENGTH 32 + +#define CRYPTO_CNT_NUM 6 + +#define CRYPTO_KERNEL_LENGTH 4096 + +#define KERNEL_RAM_ADDR 0xD8400 + +#define KDF_ITERATION_CNT 1024 + +#define MIN_CRYPTO_BLOCK_SIZE 16 + +#define HI_NV_FTM_STARTUP_CFG_ID 0x3 +#define HI_NV_FTM_KERNELA_WORK_ID 0x4 +#define HI_NV_FTM_BACKUP_KERNELA_WORK_ID 0x5 + +typedef enum { + CRYPTO_WORKKEY_KERNEL_A = 0x1, + CRYPTO_WORKKEY_KERNEL_A_BACKUP = 0x2, + CRYPTO_WORKKEY_KERNEL_A_BOTH = 0x3, +} crypto_workkey_partition; + +typedef struct { + uintptr_t addr_start; /* boot start address */ + hi_u16 mode; /* upgrade mode */ + hi_u8 file_type; /* file type:boot or code+nv */ + hi_u8 refresh_nv; /* refresh nv when the flag bit 0x55 is read */ + hi_u8 reset_cnt; /* number of restarts in upgrade mode */ + hi_u8 cnt_max; /* the maximum number of restarts (default value : 3) */ + hi_u16 reserved1; + uintptr_t addr_write; /* write kernel upgrade file address */ + hi_u32 reserved2; /* 2: reserved bytes */ +} hi_nv_ftm_startup_cfg; + +typedef struct { + hi_u8 root_salt[ROOT_SALT_LENGTH]; + hi_u8 iv_nv[IV_BYTE_LENGTH]; + hi_u8 iv_content[IV_BYTE_LENGTH]; + hi_u8 work_text[KEY_BYTE_LENGTH]; + hi_u8 content_sh256[SHA_256_LENGTH]; +} hi_flash_crypto_content; + +hi_u32 crypto_check_encrypt(hi_void); +hi_u32 crypto_encrypt_factory_image(uintptr_t file_addr); + +#endif +#endif diff --git a/sdk_liteos/boot/loaderboot/startup/SConscript b/sdk_liteos/boot/loaderboot/startup/SConscript new file mode 100755 index 0000000000000000000000000000000000000000..138c6e2d55f3f22f13bf09f16f22aa31b99ba627 --- /dev/null +++ b/sdk_liteos/boot/loaderboot/startup/SConscript @@ -0,0 +1,7 @@ +Import('env') + +env = env.Clone() + +objs = env.Object(Glob('*.c')) +objs += env.Object(Glob('*.S')) +Return('objs') diff --git a/sdk_liteos/boot/loaderboot/startup/main.c b/sdk_liteos/boot/loaderboot/startup/main.c new file mode 100644 index 0000000000000000000000000000000000000000..9a05d56cb09878ce12ac98d19701c3b7a9ed70b4 --- /dev/null +++ b/sdk_liteos/boot/loaderboot/startup/main.c @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include "main.h" + +hi_void boot_io_init(hi_void) +{ + hi_io_set_func(HI_IO_NAME_GPIO_3, HI_IO_FUNC_GPIO_3_UART0_TXD); /* uart0 tx */ + hi_io_set_func(HI_IO_NAME_GPIO_4, HI_IO_FUNC_GPIO_4_UART0_RXD); /* uart0 rx */ + hi_io_set_func(HI_IO_NAME_GPIO_13, HI_IO_FUNC_GPIO_13_SSI_DATA); + hi_io_set_func(HI_IO_NAME_GPIO_14, HI_IO_FUNC_GPIO_14_SSI_CLK); + hi_io_set_func(HI_IO_NAME_SFC_CLK, HI_IO_FUNC_SFC_CLK_SFC_CLK); + hi_io_set_func(HI_IO_NAME_SFC_IO3, HI_IO_FUNC_SFC_IO_3_SFC_HOLDN); +} + +hi_void boot_flash_init(hi_void) +{ + hi_flash_cmd_func flash_funcs = {0}; + flash_funcs.init = hi_flash_init; + flash_funcs.read = hi_flash_read; + flash_funcs.write = hi_flash_write; + flash_funcs.erase = hi_flash_erase; + hi_cmd_regist_flash_cmd(&flash_funcs); + (hi_void) hi_flash_init(); +} + +/* the entry of C. */ +hi_void start_loaderboot(hi_void) +{ + uart_ctx *cmd_ctx = HI_NULL; + hi_malloc_func malloc_funcs = {0, }; + + /* io config */ + boot_io_init(); + + /* Heap registration and initialization */ + malloc_funcs.init = rom_boot_malloc_init; + malloc_funcs.boot_malloc = rom_boot_malloc; + malloc_funcs.boot_free = rom_boot_free; + + hi_register_malloc((uintptr_t)&__heap_begin__, &malloc_funcs); + hi_u32 check_sum = (uintptr_t)(&__heap_begin__) ^ (uintptr_t)(&__heap_end__); + boot_malloc_init((uintptr_t)&__heap_begin__, (uintptr_t)&__heap_end__, check_sum); + + /* Flash initialization */ + boot_flash_init(); + + cmd_ctx = cmd_loop_init(); + if (cmd_ctx == HI_NULL) { + boot_msg0("cmd init fail"); + reset(); + while (1) {} + } + + /* Enter the waiting command cycle and disable the watchdog. */ + hi_watchdog_disable(); + loader_ack(ACK_SUCCESS); + boot_msg0("Entry loader"); + + hi_u32 ret = flash_protect_set_protect(0, HI_FALSE); + if (ret != HI_ERR_SUCCESS) { + boot_msg0("Unlock Fail!"); + } + + boot_msg0("============================================\n"); + cmd_loop(cmd_ctx); + reset(); + while (1) {} +} diff --git a/sdk_liteos/boot/loaderboot/startup/main.h b/sdk_liteos/boot/loaderboot/startup/main.h new file mode 100644 index 0000000000000000000000000000000000000000..ccc113d31090bd8a98bed7a1c58872c6e0b3b69f --- /dev/null +++ b/sdk_liteos/boot/loaderboot/startup/main.h @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __MAIN_H__ +#define __MAIN_H__ + +HI_EXTERN hi_u32 __heap_begin__; +HI_EXTERN hi_u32 __heap_end__; + +#endif diff --git a/sdk_liteos/boot/loaderboot/startup/riscv_init_loaderboot.S b/sdk_liteos/boot/loaderboot/startup/riscv_init_loaderboot.S new file mode 100644 index 0000000000000000000000000000000000000000..0becd181243dfcd24d84bb390af5559276cd3440 --- /dev/null +++ b/sdk_liteos/boot/loaderboot/startup/riscv_init_loaderboot.S @@ -0,0 +1,372 @@ +/* + * @file entry.S + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * @brief RISC-V trap handling and startup code. + */ +#ifndef ENTRY_S +#define ENTRY_S + +.extern __stack_top +.extern g_nmi_stack_end + +#define LREG lw +#define SREG sw +#define REGBYTES 4 + +#define INT_SIZE_ON_STACK (16 * REGBYTES) + +#define MSTATUS_MPP_MACHINE 0x00001800 +#define MCAULSE_ECALL_FROM_MMODE 11 +#define MCAULSE_ECALL_FROM_UMODE 8 +#define EXC_SIZE_ON_STACK (160) + + .extern trap_entry + .extern nmi_entry + .section .text.entry + .global _start + .option norvc +_start: + j handle_reset + +trap_vector: + j trap_entry_wrapper + j trap_entry_wrapper /* 1 */ + j trap_entry_wrapper /* 2 */ + j trap_entry_wrapper /* 3 Software_IRQHandler, NIY(not implemented yet) */ + j trap_entry_wrapper /* 4 */ + j trap_entry_wrapper /* 5 */ + j trap_entry_wrapper /* 6 */ + j trap_entry_wrapper /* 7 handle_timer_interrupt, use external clock */ + j trap_entry_wrapper /* 8 */ + j trap_entry_wrapper /* 9 */ + j trap_entry_wrapper /* 10 */ + j trap_entry_wrapper /* 11 handle_external_interrupt, NIY(not implemented yet) */ + j nmi_entry_wrapper /* 12 nmi entry*/ + j trap_entry_wrapper /* 13 */ + j trap_entry_wrapper /* 14 */ + .option rvc + +.macro push_reg + addi sp, sp, -(INT_SIZE_ON_STACK) + SREG x1, 0 * REGBYTES(sp) + SREG x5, 1 * REGBYTES(sp) + SREG x6, 2 * REGBYTES(sp) + SREG x7, 3 * REGBYTES(sp) + SREG x10, 4 * REGBYTES(sp) + SREG x11, 5 * REGBYTES(sp) + SREG x12, 6 * REGBYTES(sp) + SREG x13, 7 * REGBYTES(sp) + SREG x14, 8 * REGBYTES(sp) + SREG x15, 9 * REGBYTES(sp) + SREG x16, 10 * REGBYTES(sp) + SREG x17, 11 * REGBYTES(sp) + SREG x28, 12 * REGBYTES(sp) + SREG x29, 13 * REGBYTES(sp) + SREG x30, 14 * REGBYTES(sp) + SREG x31, 15 * REGBYTES(sp) + addi sp, sp, -(INT_SIZE_ON_STACK) +.endm + +.macro pop_reg + addi sp, sp, INT_SIZE_ON_STACK + LREG x1, 0 * REGBYTES(sp) + LREG x5, 1 * REGBYTES(sp) + LREG x6, 2 * REGBYTES(sp) + LREG x7, 3 * REGBYTES(sp) + LREG x10, 4 * REGBYTES(sp) + LREG x11, 5 * REGBYTES(sp) + LREG x12, 6 * REGBYTES(sp) + LREG x13, 7 * REGBYTES(sp) + LREG x14, 8 * REGBYTES(sp) + LREG x15, 9 * REGBYTES(sp) + LREG x16, 10 * REGBYTES(sp) + LREG x17, 11 * REGBYTES(sp) + LREG x28, 12 * REGBYTES(sp) + LREG x29, 13 * REGBYTES(sp) + LREG x30, 14 * REGBYTES(sp) + SREG x31, 15 * REGBYTES(sp) + addi sp, sp, INT_SIZE_ON_STACK +.endm + +.macro SAVE_ALL + addi sp, sp, -(EXC_SIZE_ON_STACK) + SREG x1, 1 * REGBYTES(sp) + SREG x2, 2 * REGBYTES(sp) + SREG x3, 3 * REGBYTES(sp) + SREG x4, 4 * REGBYTES(sp) + SREG x5, 5 * REGBYTES(sp) + SREG x6, 6 * REGBYTES(sp) + SREG x7, 7 * REGBYTES(sp) + SREG x8, 8 * REGBYTES(sp) + SREG x9, 9 * REGBYTES(sp) + SREG x10, 10 * REGBYTES(sp) + SREG x11, 11 * REGBYTES(sp) + SREG x12, 12 * REGBYTES(sp) + SREG x13, 13 * REGBYTES(sp) + SREG x14, 14 * REGBYTES(sp) + SREG x15, 15 * REGBYTES(sp) + SREG x16, 16 * REGBYTES(sp) + SREG x17, 17 * REGBYTES(sp) + SREG x18, 18 * REGBYTES(sp) + SREG x19, 19 * REGBYTES(sp) + SREG x20, 20 * REGBYTES(sp) + SREG x21, 21 * REGBYTES(sp) + SREG x22, 22 * REGBYTES(sp) + SREG x23, 23 * REGBYTES(sp) + SREG x24, 24 * REGBYTES(sp) + SREG x25, 25 * REGBYTES(sp) + SREG x26, 26 * REGBYTES(sp) + SREG x27, 27 * REGBYTES(sp) + SREG x28, 28 * REGBYTES(sp) + SREG x29, 29 * REGBYTES(sp) + SREG x30, 30 * REGBYTES(sp) + SREG x31, 31 * REGBYTES(sp) + + csrr s0, mepc + csrr s1, mstatus + csrr s2, mbadaddr + csrr s3, mcause + /* csrr s4, ccause */ + + SREG s0, 0 * REGBYTES(sp) + SREG s1, 32 * REGBYTES(sp) + SREG s2, 33 * REGBYTES(sp) + SREG s3, 34 * REGBYTES(sp) + /* SREG s4, 35 * REGBYTES(sp) */ +.endm + +.macro RESTORE_ALL + LREG a0, 32 * REGBYTES(sp) + LREG a1, 0 * REGBYTES(sp) + csrw mstatus, a0 + csrw mepc, a1 + + LREG x1, 1 * REGBYTES(sp) + LREG x3, 3 * REGBYTES(sp) + LREG x4, 4 * REGBYTES(sp) + LREG x5, 5 * REGBYTES(sp) + LREG x6, 6 * REGBYTES(sp) + LREG x7, 7 * REGBYTES(sp) + LREG x8, 8 * REGBYTES(sp) + LREG x9, 9 * REGBYTES(sp) + LREG x10, 10 * REGBYTES(sp) + LREG x11, 11 * REGBYTES(sp) + LREG x12, 12 * REGBYTES(sp) + LREG x13, 13 * REGBYTES(sp) + LREG x14, 14 * REGBYTES(sp) + LREG x15, 15 * REGBYTES(sp) + LREG x16, 16 * REGBYTES(sp) + LREG x17, 17 * REGBYTES(sp) + LREG x18, 18 * REGBYTES(sp) + LREG x19, 19 * REGBYTES(sp) + LREG x20, 20 * REGBYTES(sp) + LREG x21, 21 * REGBYTES(sp) + LREG x22, 22 * REGBYTES(sp) + LREG x23, 23 * REGBYTES(sp) + LREG x24, 24 * REGBYTES(sp) + LREG x25, 25 * REGBYTES(sp) + LREG x26, 26 * REGBYTES(sp) + LREG x27, 27 * REGBYTES(sp) + LREG x28, 28 * REGBYTES(sp) + LREG x29, 29 * REGBYTES(sp) + LREG x30, 30 * REGBYTES(sp) + LREG x31, 31 * REGBYTES(sp) + + LREG x2, 2 * REGBYTES(sp) + addi sp, sp, (EXC_SIZE_ON_STACK) +.endm + +trap_entry_wrapper: + j trap_entry + +nmi_entry_wrapper: + j nmi_entry + +trap_entry: + push_reg + csrr t0, mcause +#ecall from M-mode + li t1, MCAULSE_ECALL_FROM_MMODE + bne t0, t1, 1f + li t2, MSTATUS_MPP_MACHINE + csrc mstatus, t2 + csrr t0, mepc + addi t0, t0, 4 + csrw mepc, t0 + pop_reg + mret +#ecall from U-mode +1: + li t1, MCAULSE_ECALL_FROM_UMODE + bne t0, t1, 2f + li t2, MSTATUS_MPP_MACHINE + csrs mstatus, t2 + csrr t0, mepc + addi t0, t0, 4 + csrw mepc, t0 + pop_reg + mret +#Other exception. //TODO: reg reset. +2: + pop_reg + j trap_entry + +.align 4 +nmi_entry: + SAVE_ALL + + csrw mscratch, sp + lw sp, g_nmi_stack_end + csrr a0, mscratch + call boot_nmi_handler + csrr sp, mscratch + +# Remain in M-mode after mret. + li t0, MSTATUS_MPP_MACHINE + csrs mstatus, t0 + RESTORE_ALL + mret + +handle_reset: + csrwi mstatus, 0 + csrwi mie, 0 + csrci mstatus, 0x08 + la t0, trap_vector + addi t0, t0, 1 + csrw mtvec, t0 +/* lock mtvec */ + csrwi 0x7EF, 0x1 + +/* initialize global pointer */ + .option push + .option norelax + la gp, __global_pointer$ + .option pop + +/* initialize stack pointer */ + la sp, __stack_top + +/* perform the rest of initialization in C */ +clear_bss: + la t0, __bss_begin__ + la t1, __bss_end__ + li t2, 0x00000000 + +clear_bss_loop: + sw t2, (t0) /* clear BSS location */ + addi t0, t0, 4 /* increment clear index pointer */ + blt t0, t1, clear_bss_loop /* are we at the end yet, if not , contiue till the end */ + +clear_rom_bss: + la t0, __rom_bss_start + la t1, __rom_bss_end + li t2, 0x00000000 + +clear_rom_bss_loop: + sw t2, (t0) /* clear ROM_BSS location */ + addi t0, t0, 4 /* increment clear index pointer */ + blt t0, t1, clear_rom_bss_loop /* are we at the end yet, if not , contiue till the end */ + +clear_code_rom_bss: + la t0, __code_rom_bss_start + la t1, __code_rom_bss_end + li t2, 0x00000000 + +clear_code_rom_bss_loop: + sw t2, (t0) /* clear ROM_BSS location */ + addi t0, t0, 4 /* increment clear index pointer */ + blt t0, t1, clear_code_rom_bss_loop /* are we at the end yet, if not , contiue till the end */ + +/* copy .data .sdata section from FIX_ROM to SRAM */ + la t0, __rom_copy_ram_start /* SRAM addr */ + la t1, __rom_copy_start /* ROM addr */ + la t2, __rom_copy_size + add t2, t2, t1 + +start_fixrom_data_loop: + lw t3, (t1) + sw t3, (t0) + addi t0, t0, 4 + addi t1, t1, 4 + blt t1, t2, start_fixrom_data_loop /* are we at the end yet, if not , contiue till the end */ +end_fixrom_data_loop: + +/* copy .data .sdata section from CODE_ROM to SRAM */ + la t0, __code_rom_copy_ram_start /* SRAM addr */ + la t1, __code_rom_copy_start /* ROM addr */ + la t2, __code_rom_copy_size + add t2, t2, t1 + +start_coderom_data_loop: + lw t3, (t1) + sw t3, (t0) + addi t0, t0, 4 + addi t1, t1, 4 + blt t1, t2, start_coderom_data_loop /* are we at the end yet, if not , contiue till the end */ +end_coderom_data_loop: + + +/* pmp init */ +pmp_init: + li t0, 0xB00 + csrw pmpaddr0, t0 + li t0,0x2000 + csrw pmpaddr1, t0 /* (1)11-32K(0x8000) fixrom: disable w;non-cacheable */ +#ifdef HI_BOARD_FPGA + li t0,0x7fff0 + csrw pmpaddr2, t0 /* (2)32k(0x8000) - 0x1FFFC0 RAM: non-cacheable */ + li t0,0x80000 + csrw pmpaddr3, t0 /* (3)0x1FFFC0 - 0x200000 checkinfo: disable w x;non-cacheable */ +#else + li t0,0x477f0 + csrw pmpaddr2, t0 /* (2)32k(0x8000) - 0x11DFC0 RAM: disable x;non-cacheable */ + li t0,0x47800 + csrw pmpaddr3, t0 /* (3)0x11DFC0 - 0x11E000 checkinfo: disable w x;non-cacheable */ +#endif + li t0,0xEE000 + csrw pmpaddr4, t0 /* (4)0x11E000 - 0x3B8000 another romboot: disable r-w-x;non-cacheable */ + li t0,0xFF600 + csrw pmpaddr5, t0 /* (5)0x3B8000 - 0x3FD800 kernel_rombin: diasble r-w-x;non-cacheable */ + li t0,0x100000 + csrw pmpaddr6, t0 /* (6)0x3FD800 - 0x400000 code_rombin(9K): diasble w;non-cacheable */ + li t0,0x18000000 + csrw pmpaddr7, t0 /* (7)0x400000 -> 0x60000000 REG: disable x;non-cacheable */ + + li t0,0xf3333333 /* f:Write-back Read and Write-allocate; 3:Normal Non-cacheable Bufferable */ + csrw 0x7d8,t0 + + li t0,0x090f0d88 /* 0x0d:TOR-R-X; 0x0b:TOR-R-W; 0x08:TOR; 0x0c:TOR-x; 0x09:TOR-R */ + csrw pmpcfg0,t0 + li t0,0x0b0d0808 + csrw pmpcfg1,t0 + +/* disable Icache */ + csrwi 0x7C0, 0x0 /* disable ICACHE */ + fence + +/* disable Dcache */ + csrwi 0x7C1, 0x0 /* disable DCACHE */ + fence + + csrwi mstatus, 0 + csrwi mie, 0 + la t0, trap_entry_wrapper + addi t0, t0, 1 + csrw mtvec, t0 + ecall /* ecall: M-mode -> U-mode */ + +/* jump to C func. */ + tail start_loaderboot +#endif diff --git a/sdk_liteos/boot/loaderboot/startup/stack_protect.c b/sdk_liteos/boot/loaderboot/startup/stack_protect.c new file mode 100644 index 0000000000000000000000000000000000000000..dbb1481dd740fbe5c6df0214079f5e0d12143c85 --- /dev/null +++ b/sdk_liteos/boot/loaderboot/startup/stack_protect.c @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "hi_boot_rom.h" + +unsigned long __stack_chk_guard = 0xd00a0dff; + +void __stack_chk_fail(void) +{ + boot_msg1("stack-protector:corrupted in:", (uintptr_t)__builtin_return_address(0)); + udelay(2000); /* delay 2000 us to reset */ + global_reset(); +} \ No newline at end of file diff --git a/sdk_liteos/build.sh b/sdk_liteos/build.sh new file mode 100755 index 0000000000000000000000000000000000000000..914999276601cb03f6ff87e7a63e834896484dda --- /dev/null +++ b/sdk_liteos/build.sh @@ -0,0 +1,114 @@ +#!/bin/bash +# +# Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Description: Menuconfig entry +# +set -e +set -o pipefail +CROOT=$(pwd) +source $CROOT/build_patch.sh +BUILD_SELECT=$1 + +cd $CROOT/third_party/u-boot-v2019.07 +build_uboot_patch +cd $CROOT + +if [ "$BUILD_SELECT" = "menuconfig" ]; then + python3 $CROOT/tools/menuconfig/usr_config.py +elif [ "$BUILD_SELECT" = "clean" ]; then + scons -c +elif [ "$BUILD_SELECT" = "all_clean" ]; then + scons -c + rm -rf third_party/u-boot-v2019.07/u-boot-v2019.07 + rm -rf .sconsign.dblite + rm -rf build/config/usr_config.mk.old +elif [ "$BUILD_SELECT" = "all" ]; then + if [ $(grep -cw "CONFIG_FACTORY_TEST_SUPPORT=y" $CROOT/build/config/usr_config.mk) != 0 ]; then + echo Start build factory bin. + rm -rf build/libs/factory_bin + scons -c + if [ ! -d $CROOT/build/build_tmp/logs/ ]; then + mkdir -p $CROOT/build/build_tmp/logs + fi + scons -Q factory_mode='yes' 2>&1 | tee $CROOT/build/build_tmp/logs/build_kernel.log + if [ -f build/libs/factory_bin/*_factory.bin ]; then + scons -c + if [ ! -d $CROOT/build/build_tmp/logs/ ]; then + mkdir -p $CROOT/build/build_tmp/logs + fi + scons -Q 2>&1 | tee $CROOT/build/build_tmp/logs/build_kernel.log + echo See build log from: $CROOT/build/build_tmp/logs/build_kernel.log + fi + else + rm -rf build/libs/factory_bin + if [ ! -d $CROOT/build/build_tmp/logs/ ]; then + mkdir -p $CROOT/build/build_tmp/logs + fi + scons -Q 2>&1 | tee $CROOT/build/build_tmp/logs/build_kernel.log + echo See build log from: $CROOT/build/build_tmp/logs/build_kernel.log + fi +elif [ -z $BUILD_SELECT ]; then + if [ -d "output/bin" ]; then + rm -rf output/bin + fi + if [ $(grep -cw "CONFIG_FACTORY_TEST_SUPPORT=y" $CROOT/build/config/usr_config.mk) != 0 ]; then + echo Start build factory bin. + rm -rf build/libs/factory_bin + scons -c + if [ ! -d $CROOT/build/build_tmp/logs/ ]; then + mkdir -p $CROOT/build/build_tmp/logs + fi + scons -Q factory_mode='yes' 2>&1 | tee $CROOT/build/build_tmp/logs/build_kernel.log + if [ -f build/libs/factory_bin/*_factory.bin ]; then + scons -c + if [ ! -d $CROOT/build/build_tmp/logs/ ]; then + mkdir -p $CROOT/build/build_tmp/logs + fi + scons -Q 2>&1 | tee $CROOT/build/build_tmp/logs/build_kernel.log + echo See build log from: $CROOT/build/build_tmp/logs/build_kernel.log + fi + else + rm -rf build/libs/factory_bin + if [ ! -d $CROOT/build/build_tmp/logs/ ]; then + mkdir -p $CROOT/build/build_tmp/logs + fi + scons -Q 2>&1 | tee $CROOT/build/build_tmp/logs/build_kernel.log + echo See build log from: $CROOT/build/build_tmp/logs/build_kernel.log + fi +else + if [ $(grep -cw "CONFIG_FACTORY_TEST_SUPPORT=y" $CROOT/build/config/usr_config.mk) != 0 ]; then + echo Start build factory bin. + rm -rf build/libs/factory_bin + scons -c + if [ ! -d $CROOT/build/build_tmp/logs/ ]; then + mkdir -p $CROOT/build/build_tmp/logs + fi + scons -Q app=$BUILD_SELECT factory_mode='yes' 2>&1 | tee $CROOT/build/build_tmp/logs/build_kernel.log + if [ -f build/libs/factory_bin/*_factory.bin ]; then + scons -c + if [ ! -d $CROOT/build/build_tmp/logs/ ]; then + mkdir -p $CROOT/build/build_tmp/logs + fi + scons -Q app=$BUILD_SELECT 2>&1 | tee $CROOT/build/build_tmp/logs/build_kernel.log + echo See build log from: $CROOT/build/build_tmp/logs/build_kernel.log + fi + else + rm -rf build/libs/factory_bin + if [ ! -d $CROOT/build/build_tmp/logs/ ]; then + mkdir -p $CROOT/build/build_tmp/logs + fi + scons -Q app=$BUILD_SELECT 2>&1 | tee $CROOT/build/build_tmp/logs/build_kernel.log + echo See build log from: $CROOT/build/build_tmp/logs/build_kernel.log + fi +fi diff --git a/sdk_liteos/build/basebin/LICENSE b/sdk_liteos/build/basebin/LICENSE new file mode 100755 index 0000000000000000000000000000000000000000..8f4e29934050fbd54304ff7039dde3036a42491c --- /dev/null +++ b/sdk_liteos/build/basebin/LICENSE @@ -0,0 +1,63 @@ +End User License Agreement + +THIS END USER LICENSE AGREEMENT (“AGREEMENT”) IS A LEGAL AGREEMENT BETWEEN YOU (EITHER A SINGLE INDIVIDUAL, OR SINGLE LEGAL ENTITY) AND HISILICON (SHANGHAI) TECHNOLOGIES CO., LTD. ("HISILICON") FOR THE USE OF THE SOFTWARE ACCOMPANYING THIS AGREEMENT. HISILICON IS ONLY WILLING TO LICENSE THE SOFTWARE TO YOU ON CONDITION THAT YOU ACCEPT ALL OF THE TERMS IN THIS AGREEMENT. BY CLICKING “I AGREE” OR BY INSTALLING OR OTHERWISE USING OR COPYING THE SOFTWARE YOU INDICATE THAT YOU AGREE TO BE BOUND BY ALL OF THE TERMS OF THIS AGREEMENT. IF YOU DO NOT AGREE TO THE TERMS OF THIS AGREEMENT, HISILICON IS UNWILLING TO LICENSE THE SOFTWARE TO YOU AND YOU MAY NOT INSTALL, USE OR COPY THE SOFTWARE, AND YOU SHALL PROMPTLY DESTROY, DELETE, OR RETURN THE SOFTWARE TO YOUR SUPPLIER. + +“SOFTWARE” means the software in object code provided under the terms of this Agreement. + +Shenzhen Longgang District is the signing place of this Agreement. + +1. GRANT OF LICENSE +In consideration of your agreement to abide by the following terms, and subject to the terms and conditions of this Agreement, HISILICON hereby grants YOU, a non-transferable, non-exclusive, royalty-free, revocable, worldwide copyright license (without the right to sublicense) to use and copy the SOFTWARE solely for the purpose of designing or developing applications for use in conjunction with Hisilicon chip. +. + +All rights to the SOFTWARE and all intellectual property rights contained therein shall remain the sole and exclusive property of HISILICON. The SOFTWARE is licensed not sold. Except as expressly licensed in Clause 1, in no event shall the license granted in this Clause 1 be construed as granting YOU expressly or by implication, estoppels or otherwise, licenses to any intellectual property rights, including but not limited to patent rights, copyrights, trademark or trade secret in the SOFTWARE. + +No right is granted to YOU under this Agreement to manufacture, have manufactured, or sell, supply or distribute any products which have taken into use or which embody any of the SOFTWARE or any of the intellectual property rights embodied therein. + +2. RESTRICTIONS +This Agreement does not prevent YOU from using the SOFTWARE for internal benchmarking purposes. + +However, YOU shall treat any and all benchmarking data relating to the SOFTWARE, and any other results of your use or testing of the SOFTWARE which are indicative of its performance, efficacy, reliability or quality, as confidential information and YOU shall not disclose such information to any third party without the express written permission of HISILICON. + +YOU shall reproduce and not remove or obscure any notice incorporated by HISILICON in the SOFTWARE to protect HISILICON’s intellectual property rights embodied therein. + +YOU shall not decompile, disassemble, or reverse engineer the SOFTWARE. + +YOU shall not distribute the SOFTWARE under an open source license as listed by the Open Source Initiative (a non-profit corporation whose website is www.opensource.org), or other license which requires the source code or object code of the SOFTWARE to be licensed or otherwise shared with any third party. + +3. FEEDBACK +YOU may choose to provide suggestions, comments, feedback, ideas, modifications or know-how (whether in oral or written form) relating to the use of the SOFTWARE ("Feedback") to HISILICON under the terms of this Agreement. YOU hereby grants to HISILICON and its affiliates, under all of you and your affiliates’ (as applicable) intellectual property rights, a perpetual, irrevocable, royalty free, non-exclusive, worldwide license to (i) use, copy and modify the Feedback; (ii) sell, supply, or otherwise distribute the Feedback; (iii) design, have designed, manufacture, have manufactured, use, import, sell, and otherwise distribute and dispose of products that incorporate the Feedback; and (iv) sublicense (together with the rights to further sublicense) the rights granted in this paragraph to any third party. + +4. NO WARRANTY +YOU AGREE THAT THE SOFTWARE IS PROVIDED BY HISILICON ON AN "AS IS" BASIS. HISILICON MAKES NO WARRANTY, EXPRESSED OR IMPLIED OR STATUTORY, WITH RESPECT TO ANY OF THE SOFTWARE, INCLUDING WITHOUT LIMITATION, ANY IMPLIED WARRANTIES OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. + +YOU EXPRESSLY ASSUME ALL LIABILITIES AND RISKS, FOR USE OR OPERATION OF THE SOFTWARE, INCLUDING WITHOUT LIMITATION, SOFTWARE APPLICATIONS DESIGNED OR INTENDED FOR MISSION CRITICAL APPLICATIONS, SUCH AS PACEMAKERS, WEAPONRY, AIRCRAFT NAVIGATION, FACTORY CONTROL SYSTEMS, ETC. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE ENTIRE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +5. NO LIABILITY +PLEASE READ THE INSTRUCTIONS COMPLETELY, AND PLEASE NOTE THAT YOU SHOULD USE THE SOFTWARE AT YOUR OWN RISK. + +IN NO EVENT SHALL HISILICON BE LIABLE FOR ANY DIRECT OR INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE OF OR INABILITY TO USE THE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHER LEGAL THEORY, EVEN IF HISILICON HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. EVEN IF THE SOFTWARE HAS ANY MATERIAL, VERIFIABLE, AND REPRODUCIBLE PROGRAM ERRORS, HISILICON SHALL HAVE NO LIABILITY TO MODIFY SUCH ERRORS. + +NOTWITHSTANDING ANYTHING TO THE CONTRARY CONTAINED IN THIS AGREEMENT, THE MAXIMUM LIABILITY OF HISILICON TO YOU IN AGGREGATE FOR ALL CLAIMS MADE AGAINST HISILICON IN CONTRACT TORT OR OTHERWISE UNDER OR IN CONNECTION WITH THE SUBJECT MATTER OF THIS AGREEMENT SHALL NOT EXCEED THE TOTAL OF SUMS RECEIVED BY HISILICON FROM YOU FOR THIS AGREEMENT. THE EXISTENCE OF MORE THAN ONE CLAIM WILL NOT ENLARGE OR EXTEND THE LIMIT. + +6. CONFIDENTIALITY +YOU acknowledge and agree that the SOFTWARE and any benchmarking data and related information provided under this Agreement contain trade secrets and confidential material of HISILICON and YOU agree to maintain all such information in confidence and apply security measures no less stringent than the measures which YOU apply to protect your own like information, but not less than a reasonable degree of care, to prevent their unauthorized disclosure and use. The period of confidentiality shall be indefinite. YOU agree not to use any such information other than in normal use of the SOFTWARE under the license granted in this Agreement. + +7. TERM AND TERMINATION +This Agreement shall remain in force until terminated. HISILICON may terminate this Agreement at any time with or without any cause. Upon termination of this Agreement, YOU shall immediately stop using the SOFTWARE and confidential information and destroy all copies of the SOFTWARE and confidential information in your possession, together with all documentation and related materials. The provisions of clauses 3, 4, 5, 6, 7 and 8 shall survive termination of this Agreement. + +8. GENERAL +Any provision of this Agreement which is prohibited or unenforceable in any jurisdiction shall be ineffective to the extent of such prohibition or unenforceability without affecting, impairing or invalidating the remaining provisions hereof. + +The failure by HISILICON to enforce any of the provisions of this Agreement, unless waived in writing, shall not constitute a waiver of HISILICON's rights to enforce such provision or any other provision of this Agreement in the future. +At HISILICON’s request, YOU agree to check your computers for installations of the SOFTWARE and any other information requested by HISILICON relating to SOFTWARE installation and to provide this information to HISILICON. YOU agree that employees or auditors nominated by HISILICON may also perform such checking and reporting on behalf of HISILICON by prior appointment during your normal business hours on seven (7) days’ notice. HISILICON shall bear the auditors’ costs for that audit unless it reveals unlicensed usage in which case YOU shall promptly reimburse HISILICON for all reasonable costs and expenses, including professional fees, relating to such audit. + +The SOFTWARE provided under this Agreement is subject to U.S. export control laws, including the U.S. Export Administration Act and its associated regulations, and may be subject to export or import regulations in other countries. YOU agree to comply fully with all laws and regulations of the United States and other countries ("Export Laws") to assure that the SOFTWARE, is not (1) exported, directly or indirectly, in violation of Export Laws, either to any countries that are subject to U.S.A. export restrictions or to any end user who has been prohibited from participating in the U.S.A. export transactions by any federal agency of the U.S.A. government; or (2) intended to be used for any purpose prohibited by Export Laws, including, without limitation, nuclear, chemical, or biological weapons proliferation. + +This Agreement shall be governed by and construed in accordance with the laws of People’s Republic of China, without reference to the principles of conflicts of laws. Any dispute arising out of or relating to this Agreement shall be submitted to Shenzhen Longgang District People’s court and the parties waive all objections to that jurisdiction and venue. + +Some open-source software components may be used in the Software. If the applicable licenses of these open-source software components conflict with the content in this Agreement, the licenses of the open-source software components will prevail. + +--------------------------------------------------------------------- +Copyright (C) 2020 Hisilicon (Shanghai) Technologies Co., Ltd. All rights reserved. + diff --git a/sdk_liteos/build/basebin/burn_for_erase_4k.bin b/sdk_liteos/build/basebin/burn_for_erase_4k.bin new file mode 100755 index 0000000000000000000000000000000000000000..7de9e36a64119c698897e5d1f9b66fbfa7f3243d --- /dev/null +++ b/sdk_liteos/build/basebin/burn_for_erase_4k.bin @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/sdk_liteos/build/config/sdk.mk b/sdk_liteos/build/config/sdk.mk new file mode 100644 index 0000000000000000000000000000000000000000..d3862ceff2c10939efeae2ebab7aabbaf29ccded --- /dev/null +++ b/sdk_liteos/build/config/sdk.mk @@ -0,0 +1,131 @@ +# +# Automatically generated make config: don't edit +# + +# pkt setting. +CONFIG_CHIP_PKT_32K=y +#CONFIG_CHIP_PKT_48K=y + +CONFIG_TARGET_CHIP_HI3861=y +# ohos setting. +CONFIG_OHOS=y + +# +# Compiler +# +LOSCFG_COMPILER_HUAWEILITEOS=y + +# +# testcase +# +#HB_LITEOS_COMPILE_TESTCASE=y + +# +# Platform +# +#FLASH:IOT or RAM:NON-IOT +LOSCFG_COMPILER_HI3861_FLASH=y + +#FPGA or ASIC +LOSCFG_COMPILER_HI3861_ASIC=y + +#CHIP ver: Hi3861L;Hi3861;Hi3881 +LOSCFG_COMPILER_CHIP_VER=Hi3861 +#!!notice:customer ver, please open the following macro. +LOSCFG_COMPILER_CHECK_CHIP_VER=y + +CONFIG_CHIP_PKT=32k + +CONFIG_FACTORY_TEST_MODE=n + +CONFIG_QUICK_SEND_MODE=n +# +# Kernel +# +LOSCFG_KERNEL_LITEKERNEL=y +LOSCFG_KERNEL_EXTKERNEL=y +# LOSCFG_KERNEL_CPP_EXCEPTIONS_SUPPORT is not set +LOSCFG_KERNEL_CPUP=y +LOSCFG_KERNEL_RUNSTOP=y + +# +# Backtrace +# +#LOSCFG_BACKTRACE=y + +# +# Kasan +# +#LOSCFG_KASAN=y +LOSCFG_KASAN_CODE_WIFI=y +LOSCFG_KASAN_CODE_BSP_DIAG=y +LOSCFG_KASAN_CODE_BSP_DRIVER=y +LOSCFG_KASAN_CODE_BSP_ROM=y +LOSCFG_KASAN_CODE_BSP_SYSTEM=y +LOSCFG_KASAN_CODE_COM_SIGMA=y +LOSCFG_KASAN_EXAMPLES_DEMO=y +LOSCFG_KASAN_LITEOS_NET_LWIP=y +LOSCFG_KASAN_LITEOS_NET_WPA=y +#LOSCFG_KASAN_LITEOS_NET_COAP=y +#LOSCFG_KASAN_LITEOS_NET_RIPPLE=y + +# +# Lib +# +LOSCFG_LIB_LIBC=y +LOSCFG_LIB_LIBM=y + +# +# Compat +# +LOSCFG_COMPAT_POSIX=y +LOSCFG_COMPAT_LINUX=y + +# +# Net +# +LOSCFG_NET_LWIP_SACK=y +LOSCFG_NET_RIPPLE=y +LOSCFG_NET_WPA=y +LOSCFG_NET_WPA_MESH=y +LOSCFG_NET_WPA_WPS=y +LOSCFG_XTAL_FREQUENCY_COMPESATION=y +LOSCFG_NET_LIBCOAP=y +#LOSCFG_NET_MQTT=y +LOSCFG_NET_MCAST6=n +# +# Debug +# +# LOSCFG_COMPILE_DEBUG is not set +# LOSCFG_PLATFORM_ADAPT is not set +# LOSCFG_THUMB is not set +# LOSCFG_PLATFORM_DVFS is not set +LOSCFG_DEBUG_VERSION=y +LOSCFG_SHELL=y +LOSCFG_SHELL_EXCINFO=y +LOSCFG_NET_LWIP_SACK_TFTP=y +LOSCFG_NET_TELNET=y +LOSCFG_RAM_MONITOR=n +# LOSCFG_TOOLS_IPERF is not set +# LOSCFG_NET_PCAP is not set +# LOSCFG_MEMORY_CHECK is not set +LOSCFG_DRIVERS_UART=y +# LOSCFG_PLATFORM_UART_WITHOUT_VFS is not set +LOSCFG_PLATFORM_OSAPPINIT=y +#close printf for all moudle if controlled by +LOSCFG_DEBUG_CLOSE_PRINT=y + +# +# Stack Smashing Protector (SSP) Compiler Feature +# +# LOSCFG_CC_NO_STACKPROTECTOR is not set +LOSCFG_CC_STACKPROTECTOR=y +# LOSCFG_CC_STACKPROTECTOR_ALL is not set + +LOSCFG_PERSISTENT_STORAGE=y + +# LOSCFG_TEST_NET is not set + +# data aquire +LOSCFG_DAQ = n +CONFIG_DIAG_SUPPORT_AUTO_LINK=n diff --git a/sdk_liteos/build/config/usr_config.mk b/sdk_liteos/build/config/usr_config.mk new file mode 100644 index 0000000000000000000000000000000000000000..438e419f39363179be0a8b8f4f4df54b78616d55 --- /dev/null +++ b/sdk_liteos/build/config/usr_config.mk @@ -0,0 +1,102 @@ +# Generated by Kconfiglib (https://github.com/ulfalizer/Kconfiglib) + +# +# Target Chip +# +CONFIG_TARGET_CHIP_HI3861=y +# end of Target Chip + +# +# Security Settings +# +# CONFIG_TARGET_SIG_RSA_V15 is not set +# CONFIG_TARGET_SIG_RSA_PSS is not set +# CONFIG_TARGET_SIG_ECC is not set +CONFIG_TARGET_SIG_SHA256=y +# CONFIG_BOOT_ENCRYPT is not set +CONFIG_TARGET_KERNEL_VER=0 +CONFIG_TARGET_BOOT_VER=0 +CONFIG_TEE_HUKS_SUPPORT=y +# CONFIG_TEE_HUKS_DEMO_SUPPORT is not set +# CONFIG_FLASH_ENCRYPT_SUPPORT is not set +# end of Security Settings + +# +# Factory Test Settings +# +# CONFIG_FACTORY_TEST_SUPPORT is not set +# end of Factory Test Settings + +# +# BSP Settings +# +# CONFIG_I2C_SUPPORT is not set +# CONFIG_I2S_SUPPORT is not set +# CONFIG_SPI_SUPPORT is not set +# CONFIG_DMA_SUPPORT is not set +# CONFIG_SDIO_SUPPORT is not set +# CONFIG_SPI_DMA_SUPPORT is not set +# CONFIG_UART_DMA_SUPPORT is not set +# CONFIG_PWM_SUPPORT is not set +# CONFIG_PWM_HOLD_AFTER_REBOOT is not set +CONFIG_PWM_SUPPORT=y +CONFIG_I2C_SUPPORT=y +CONFIG_SPI_SUPPORT=y +CONFIG_AT_SUPPORT=y +CONFIG_FILE_SYSTEM_SUPPORT=y +CONFIG_UART0_SUPPORT=y +CONFIG_UART1_SUPPORT=y +# CONFIG_UART2_SUPPORT is not set +# end of BSP Settings + +# +# WiFi Settings +# +CONFIG_CE_SUPPORT=y +# CONFIG_FCC_SUPPORT is not set +# CONFIG_MAX_POWER_SUPPORT is not set +# end of WiFi Settings + +# +# Third Party library +# +# CONFIG_CJSON is not set +# CONFIG_CJSON_NESTING_LIMIT=1000 +# CONFIG_LIBCOAP is not set +# CONFIG_MQTT is not set +CONFIG_IPERF=y +# end of Third Party library + +# +# Lwip Settings +# +CONFIG_DHCPS_GW=y +# CONFIG_NETIF_HOSTNAME is not set +# CONFIG_DHCP_VENDOR_CLASS_IDENTIFIER is not set +# CONFIG_LWIP_LOWPOWER is not set +# end of Lwip Settings + +# +# OTA Settings +# +CONFIG_COMPRESSION_OTA_SUPPORT=y +# CONFIG_DUAL_PARTITION_OTA_SUPPORT is not set +# end of OTA Settings + +# +# Link Settings +# +# CONFIG_HILINK is not set +# end of Link Settings + +# +# File System Settings +# +CONFIG_FILE_SYSTEM_SUPPORT=y +# end of File System Settings + +# +# Debug Log Settings +# +# CONFIG_DIAG_SUPPORT is not set +# end of Debug Log Settings diff --git a/sdk_liteos/build/libs/LICENSE b/sdk_liteos/build/libs/LICENSE new file mode 100755 index 0000000000000000000000000000000000000000..8f4e29934050fbd54304ff7039dde3036a42491c --- /dev/null +++ b/sdk_liteos/build/libs/LICENSE @@ -0,0 +1,63 @@ +End User License Agreement + +THIS END USER LICENSE AGREEMENT (“AGREEMENT”) IS A LEGAL AGREEMENT BETWEEN YOU (EITHER A SINGLE INDIVIDUAL, OR SINGLE LEGAL ENTITY) AND HISILICON (SHANGHAI) TECHNOLOGIES CO., LTD. ("HISILICON") FOR THE USE OF THE SOFTWARE ACCOMPANYING THIS AGREEMENT. HISILICON IS ONLY WILLING TO LICENSE THE SOFTWARE TO YOU ON CONDITION THAT YOU ACCEPT ALL OF THE TERMS IN THIS AGREEMENT. BY CLICKING “I AGREE” OR BY INSTALLING OR OTHERWISE USING OR COPYING THE SOFTWARE YOU INDICATE THAT YOU AGREE TO BE BOUND BY ALL OF THE TERMS OF THIS AGREEMENT. IF YOU DO NOT AGREE TO THE TERMS OF THIS AGREEMENT, HISILICON IS UNWILLING TO LICENSE THE SOFTWARE TO YOU AND YOU MAY NOT INSTALL, USE OR COPY THE SOFTWARE, AND YOU SHALL PROMPTLY DESTROY, DELETE, OR RETURN THE SOFTWARE TO YOUR SUPPLIER. + +“SOFTWARE” means the software in object code provided under the terms of this Agreement. + +Shenzhen Longgang District is the signing place of this Agreement. + +1. GRANT OF LICENSE +In consideration of your agreement to abide by the following terms, and subject to the terms and conditions of this Agreement, HISILICON hereby grants YOU, a non-transferable, non-exclusive, royalty-free, revocable, worldwide copyright license (without the right to sublicense) to use and copy the SOFTWARE solely for the purpose of designing or developing applications for use in conjunction with Hisilicon chip. +. + +All rights to the SOFTWARE and all intellectual property rights contained therein shall remain the sole and exclusive property of HISILICON. The SOFTWARE is licensed not sold. Except as expressly licensed in Clause 1, in no event shall the license granted in this Clause 1 be construed as granting YOU expressly or by implication, estoppels or otherwise, licenses to any intellectual property rights, including but not limited to patent rights, copyrights, trademark or trade secret in the SOFTWARE. + +No right is granted to YOU under this Agreement to manufacture, have manufactured, or sell, supply or distribute any products which have taken into use or which embody any of the SOFTWARE or any of the intellectual property rights embodied therein. + +2. RESTRICTIONS +This Agreement does not prevent YOU from using the SOFTWARE for internal benchmarking purposes. + +However, YOU shall treat any and all benchmarking data relating to the SOFTWARE, and any other results of your use or testing of the SOFTWARE which are indicative of its performance, efficacy, reliability or quality, as confidential information and YOU shall not disclose such information to any third party without the express written permission of HISILICON. + +YOU shall reproduce and not remove or obscure any notice incorporated by HISILICON in the SOFTWARE to protect HISILICON’s intellectual property rights embodied therein. + +YOU shall not decompile, disassemble, or reverse engineer the SOFTWARE. + +YOU shall not distribute the SOFTWARE under an open source license as listed by the Open Source Initiative (a non-profit corporation whose website is www.opensource.org), or other license which requires the source code or object code of the SOFTWARE to be licensed or otherwise shared with any third party. + +3. FEEDBACK +YOU may choose to provide suggestions, comments, feedback, ideas, modifications or know-how (whether in oral or written form) relating to the use of the SOFTWARE ("Feedback") to HISILICON under the terms of this Agreement. YOU hereby grants to HISILICON and its affiliates, under all of you and your affiliates’ (as applicable) intellectual property rights, a perpetual, irrevocable, royalty free, non-exclusive, worldwide license to (i) use, copy and modify the Feedback; (ii) sell, supply, or otherwise distribute the Feedback; (iii) design, have designed, manufacture, have manufactured, use, import, sell, and otherwise distribute and dispose of products that incorporate the Feedback; and (iv) sublicense (together with the rights to further sublicense) the rights granted in this paragraph to any third party. + +4. NO WARRANTY +YOU AGREE THAT THE SOFTWARE IS PROVIDED BY HISILICON ON AN "AS IS" BASIS. HISILICON MAKES NO WARRANTY, EXPRESSED OR IMPLIED OR STATUTORY, WITH RESPECT TO ANY OF THE SOFTWARE, INCLUDING WITHOUT LIMITATION, ANY IMPLIED WARRANTIES OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. + +YOU EXPRESSLY ASSUME ALL LIABILITIES AND RISKS, FOR USE OR OPERATION OF THE SOFTWARE, INCLUDING WITHOUT LIMITATION, SOFTWARE APPLICATIONS DESIGNED OR INTENDED FOR MISSION CRITICAL APPLICATIONS, SUCH AS PACEMAKERS, WEAPONRY, AIRCRAFT NAVIGATION, FACTORY CONTROL SYSTEMS, ETC. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE ENTIRE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +5. NO LIABILITY +PLEASE READ THE INSTRUCTIONS COMPLETELY, AND PLEASE NOTE THAT YOU SHOULD USE THE SOFTWARE AT YOUR OWN RISK. + +IN NO EVENT SHALL HISILICON BE LIABLE FOR ANY DIRECT OR INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE OF OR INABILITY TO USE THE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHER LEGAL THEORY, EVEN IF HISILICON HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. EVEN IF THE SOFTWARE HAS ANY MATERIAL, VERIFIABLE, AND REPRODUCIBLE PROGRAM ERRORS, HISILICON SHALL HAVE NO LIABILITY TO MODIFY SUCH ERRORS. + +NOTWITHSTANDING ANYTHING TO THE CONTRARY CONTAINED IN THIS AGREEMENT, THE MAXIMUM LIABILITY OF HISILICON TO YOU IN AGGREGATE FOR ALL CLAIMS MADE AGAINST HISILICON IN CONTRACT TORT OR OTHERWISE UNDER OR IN CONNECTION WITH THE SUBJECT MATTER OF THIS AGREEMENT SHALL NOT EXCEED THE TOTAL OF SUMS RECEIVED BY HISILICON FROM YOU FOR THIS AGREEMENT. THE EXISTENCE OF MORE THAN ONE CLAIM WILL NOT ENLARGE OR EXTEND THE LIMIT. + +6. CONFIDENTIALITY +YOU acknowledge and agree that the SOFTWARE and any benchmarking data and related information provided under this Agreement contain trade secrets and confidential material of HISILICON and YOU agree to maintain all such information in confidence and apply security measures no less stringent than the measures which YOU apply to protect your own like information, but not less than a reasonable degree of care, to prevent their unauthorized disclosure and use. The period of confidentiality shall be indefinite. YOU agree not to use any such information other than in normal use of the SOFTWARE under the license granted in this Agreement. + +7. TERM AND TERMINATION +This Agreement shall remain in force until terminated. HISILICON may terminate this Agreement at any time with or without any cause. Upon termination of this Agreement, YOU shall immediately stop using the SOFTWARE and confidential information and destroy all copies of the SOFTWARE and confidential information in your possession, together with all documentation and related materials. The provisions of clauses 3, 4, 5, 6, 7 and 8 shall survive termination of this Agreement. + +8. GENERAL +Any provision of this Agreement which is prohibited or unenforceable in any jurisdiction shall be ineffective to the extent of such prohibition or unenforceability without affecting, impairing or invalidating the remaining provisions hereof. + +The failure by HISILICON to enforce any of the provisions of this Agreement, unless waived in writing, shall not constitute a waiver of HISILICON's rights to enforce such provision or any other provision of this Agreement in the future. +At HISILICON’s request, YOU agree to check your computers for installations of the SOFTWARE and any other information requested by HISILICON relating to SOFTWARE installation and to provide this information to HISILICON. YOU agree that employees or auditors nominated by HISILICON may also perform such checking and reporting on behalf of HISILICON by prior appointment during your normal business hours on seven (7) days’ notice. HISILICON shall bear the auditors’ costs for that audit unless it reveals unlicensed usage in which case YOU shall promptly reimburse HISILICON for all reasonable costs and expenses, including professional fees, relating to such audit. + +The SOFTWARE provided under this Agreement is subject to U.S. export control laws, including the U.S. Export Administration Act and its associated regulations, and may be subject to export or import regulations in other countries. YOU agree to comply fully with all laws and regulations of the United States and other countries ("Export Laws") to assure that the SOFTWARE, is not (1) exported, directly or indirectly, in violation of Export Laws, either to any countries that are subject to U.S.A. export restrictions or to any end user who has been prohibited from participating in the U.S.A. export transactions by any federal agency of the U.S.A. government; or (2) intended to be used for any purpose prohibited by Export Laws, including, without limitation, nuclear, chemical, or biological weapons proliferation. + +This Agreement shall be governed by and construed in accordance with the laws of People’s Republic of China, without reference to the principles of conflicts of laws. Any dispute arising out of or relating to this Agreement shall be submitted to Shenzhen Longgang District People’s court and the parties waive all objections to that jurisdiction and venue. + +Some open-source software components may be used in the Software. If the applicable licenses of these open-source software components conflict with the content in this Agreement, the licenses of the open-source software components will prevail. + +--------------------------------------------------------------------- +Copyright (C) 2020 Hisilicon (Shanghai) Technologies Co., Ltd. All rights reserved. + diff --git a/sdk_liteos/build/libs/boot_libs/README.txt b/sdk_liteos/build/libs/boot_libs/README.txt new file mode 100644 index 0000000000000000000000000000000000000000..6f83c973c30fd5d001d0e20d554472650499a58e --- /dev/null +++ b/sdk_liteos/build/libs/boot_libs/README.txt @@ -0,0 +1 @@ +This is an empty directory, reserve. diff --git a/sdk_liteos/build/link/flashboot_ecc.lds b/sdk_liteos/build/link/flashboot_ecc.lds new file mode 100755 index 0000000000000000000000000000000000000000..f66fad80758a201d0540c622b9a8e743634964ea --- /dev/null +++ b/sdk_liteos/build/link/flashboot_ecc.lds @@ -0,0 +1,151 @@ +OUTPUT_ARCH( "riscv" ) +ENTRY(_start) + +MEMORY +{ + /* FlashBoot location on Flash */ + FLASH (rwx) : ORIGIN = 0x400000+0x150, LENGTH = 32K-0x150-0x3C0 + /* ram for stack */ + STACK(xrw) : ORIGIN = 0x100000,LENGTH = 8K + /* ram for common bss and data */ + SRAM(xrw) : ORIGIN = 0x100000+8K,LENGTH = 8K + /* ram for fix rom bss and data */ + ROM_BSS_DATA(rx): ORIGIN = 0x100000+16K,LENGTH = 2K + /* ram for code rom bss and data */ + CODE_ROM_BSS_DATA(rx): ORIGIN = 0x100000+18K,LENGTH = 2K + /* signature */ + SIGN(rx): ORIGIN = 0x100000+40K,LENGTH = 0x150 + /* ram for flashboot */ + FLASH_BOOT(rx): ORIGIN = 0x100000+40K+0x150,LENGTH = 80K-0x150 + /* ram for heap */ + HEAP(xrw): ORIGIN = 0xdc000,LENGTH = 144K + /* rom for fixed rom */ + FIXED_ROM(rx): ORIGIN = 0x00000000+11K,LENGTH = 21K + /* rom for code rom */ + CODE_ROM(rx): ORIGIN = 0x003b8000+278K,LENGTH = 10K +} + +SECTIONS +{ + /* The startup code goes first into FLASH */ + .text.entry : ALIGN(4) + { + KEEP(*(.text.entry)) + } > FLASH_BOOT AT>FLASH + + .rom.text : + { + . = ALIGN(4); + KEEP(SORT(libbase.o)(.text*)) + KEEP(SORT(libbase.o)(.rodata*)) + . = ALIGN(4); + } > FIXED_ROM + + .rom.code.text : + { + . = ALIGN(4); + KEEP(SORT(libcodebase.o)(.text*)) + KEEP(SORT(libcodebase.o)(.rodata*)) + . = ALIGN(4); + } > CODE_ROM + + /* Stack in SRAM at Highest addresses */ + .stacks (NOLOAD) : + { + . = ALIGN(4); + __SYSTEM_STACK_BEGIN__ = ORIGIN(STACK); + KEEP(*(.stacks)) + __SYSTEM_STACK_END__ = ORIGIN(STACK) + LENGTH(STACK); + } > STACK + __SYSTEM_STACK_SIZE__ = __SYSTEM_STACK_END__ - __SYSTEM_STACK_BEGIN__; + __stack_top = __SYSTEM_STACK_END__; + + .rom.data : + { + . = ALIGN(4); + __rom_copy_start = LOADADDR(.rom.data); + . = ALIGN(4); + __rom_copy_ram_start = .; + __global_pointer$ = .; + KEEP(SORT(libbase.o) (.data*)) + . = ALIGN(4); + __rom_copy_ram_end = .; + } > ROM_BSS_DATA AT>FIXED_ROM + __rom_copy_size = __rom_copy_ram_end - __rom_copy_ram_start; + + .rom.code.data : + { + . = ALIGN(4); + __code_rom_copy_start = LOADADDR(.rom.code.data); + . = ALIGN(4); + __code_rom_copy_ram_start = .; + KEEP(SORT(libcodebase.o) (.data*)) + . = ALIGN(4); + __code_rom_copy_ram_end = .; + }>CODE_ROM_BSS_DATA AT>CODE_ROM + __code_rom_copy_size = __code_rom_copy_ram_end - __code_rom_copy_ram_start; + + .rom.bss : + { + . = ALIGN(4); + __rom_bss_start = .; + KEEP(libbase.o (.bss)) + KEEP(libbase.o (.bss*)) + KEEP(libbase.o (COMMON)) + . = ALIGN(4); + __rom_bss_end = .; + } > ROM_BSS_DATA AT>FIXED_ROM + + .rom.code.bss : + { + . = ALIGN(4); + __code_rom_bss_start = .; + KEEP(libcodebase.o (.bss)) + KEEP(libcodebase.o (.bss*)) + KEEP(libcodebase.o (COMMON)) + . = ALIGN(4); + __code_rom_bss_end = .; + }>CODE_ROM_BSS_DATA AT>CODE_ROM + + .text : ALIGN(4) + { + __start_addr = .; + SORT(*)(.boot.data.key) + *(.text*) + . = ALIGN(4); + __rodata_start = .; + *(.rodata*) + . = ALIGN(4); + __rodata_end = .; + __text_end = .; + } > FLASH_BOOT AT>FLASH + + /* data section */ + .data : ALIGN(4) + { + __data_load = LOADADDR(.data); + __data_start = .; + *(.data*) + . = ALIGN(4); + __data_end = .; + } > FLASH_BOOT AT>FLASH + + /* bss section */ + .bss (NOLOAD) : ALIGN(4) + { + __bss_begin__ = .; + *(.bss*) + *(COMMON) + . = ALIGN(4); + __bss_end__ = .; + } > FLASH_BOOT + __bss_size__ = __bss_end__ - __bss_begin__; + + .heap (NOLOAD) : + { + . = ALIGN(4); + __heap_begin__ = ORIGIN(HEAP); + KEEP(*(.heap)) + __heap_end__ = __heap_begin__ + LENGTH(HEAP); + } > HEAP +} diff --git a/sdk_liteos/build/link/flashboot_rsa.lds b/sdk_liteos/build/link/flashboot_rsa.lds new file mode 100755 index 0000000000000000000000000000000000000000..2f1f6340f11989e05c6d080cd4919471c9b33390 --- /dev/null +++ b/sdk_liteos/build/link/flashboot_rsa.lds @@ -0,0 +1,151 @@ +OUTPUT_ARCH( "riscv" ) +ENTRY(_start) + +MEMORY +{ + /* FlashBoot location on Flash */ + FLASH (rwx) : ORIGIN = 0x400000+0x5A0, LENGTH = 32K-0x5A0-0x3C0 + /* ram for stack */ + STACK(xrw) : ORIGIN = 0x100000,LENGTH = 8K + /* ram for common bss and data */ + SRAM(xrw) : ORIGIN = 0x100000+8K,LENGTH = 8K + /* ram for fix rom bss and data */ + ROM_BSS_DATA(rx): ORIGIN = 0x100000+16K,LENGTH = 2K + /* ram for code rom bss and data */ + CODE_ROM_BSS_DATA(rx): ORIGIN = 0x100000+18K,LENGTH = 2K + /* signature */ + SIGN(rx): ORIGIN = 0x100000+40K,LENGTH = 0x5A0 + /* ram for flashboot */ + FLASH_BOOT(rx): ORIGIN = 0x100000+40K+0x5A0,LENGTH = 80K-0x5A0 + /* ram for heap */ + HEAP(xrw): ORIGIN = 0xdc000,LENGTH = 144K + /* rom for fixed rom */ + FIXED_ROM(rx): ORIGIN = 0x00000000+11K,LENGTH = 21K + /* rom for code rom */ + CODE_ROM(rx): ORIGIN = 0x003b8000+278K,LENGTH = 10K +} + +SECTIONS +{ + /* The startup code goes first into FLASH */ + .text.entry : ALIGN(4) + { + KEEP(*(.text.entry)) + } > FLASH_BOOT AT>FLASH + + .rom.text : + { + . = ALIGN(4); + KEEP(SORT(libbase.o)(.text*)) + KEEP(SORT(libbase.o)(.rodata*)) + . = ALIGN(4); + } > FIXED_ROM + + .rom.code.text : + { + . = ALIGN(4); + KEEP(SORT(libcodebase.o)(.text*)) + KEEP(SORT(libcodebase.o)(.rodata*)) + . = ALIGN(4); + } > CODE_ROM + + /* Stack in SRAM at Highest addresses */ + .stacks (NOLOAD) : + { + . = ALIGN(4); + __SYSTEM_STACK_BEGIN__ = ORIGIN(STACK); + KEEP(*(.stacks)) + __SYSTEM_STACK_END__ = ORIGIN(STACK) + LENGTH(STACK); + } > STACK + __SYSTEM_STACK_SIZE__ = __SYSTEM_STACK_END__ - __SYSTEM_STACK_BEGIN__; + __stack_top = __SYSTEM_STACK_END__; + + .rom.data : + { + . = ALIGN(4); + __rom_copy_start = LOADADDR(.rom.data); + . = ALIGN(4); + __rom_copy_ram_start = .; + __global_pointer$ = .; + KEEP(SORT(libbase.o) (.data*)) + . = ALIGN(4); + __rom_copy_ram_end = .; + } > ROM_BSS_DATA AT>FIXED_ROM + __rom_copy_size = __rom_copy_ram_end - __rom_copy_ram_start; + + .rom.code.data : + { + . = ALIGN(4); + __code_rom_copy_start = LOADADDR(.rom.code.data); + . = ALIGN(4); + __code_rom_copy_ram_start = .; + KEEP(SORT(libcodebase.o) (.data*)) + . = ALIGN(4); + __code_rom_copy_ram_end = .; + }>CODE_ROM_BSS_DATA AT>CODE_ROM + __code_rom_copy_size = __code_rom_copy_ram_end - __code_rom_copy_ram_start; + + .rom.bss : + { + . = ALIGN(4); + __rom_bss_start = .; + KEEP(libbase.o (.bss)) + KEEP(libbase.o (.bss*)) + KEEP(libbase.o (COMMON)) + . = ALIGN(4); + __rom_bss_end = .; + } > ROM_BSS_DATA AT>FIXED_ROM + + .rom.code.bss : + { + . = ALIGN(4); + __code_rom_bss_start = .; + KEEP(libcodebase.o (.bss)) + KEEP(libcodebase.o (.bss*)) + KEEP(libcodebase.o (COMMON)) + . = ALIGN(4); + __code_rom_bss_end = .; + }>CODE_ROM_BSS_DATA AT>CODE_ROM + + .text : ALIGN(4) + { + __start_addr = .; + SORT(*)(.boot.data.key) + *(.text*) + . = ALIGN(4); + __rodata_start = .; + *(.rodata*) + . = ALIGN(4); + __rodata_end = .; + __text_end = .; + } > FLASH_BOOT AT>FLASH + + /* data section */ + .data : ALIGN(4) + { + __data_load = LOADADDR(.data); + __data_start = .; + *(.data*) + . = ALIGN(4); + __data_end = .; + } > FLASH_BOOT AT>FLASH + + /* bss section */ + .bss (NOLOAD) : ALIGN(4) + { + __bss_begin__ = .; + *(.bss*) + *(COMMON) + . = ALIGN(4); + __bss_end__ = .; + } > FLASH_BOOT + __bss_size__ = __bss_end__ - __bss_begin__; + + .heap (NOLOAD) : + { + . = ALIGN(4); + __heap_begin__ = ORIGIN(HEAP); + KEEP(*(.heap)) + __heap_end__ = __heap_begin__ + LENGTH(HEAP); + } > HEAP +} diff --git a/sdk_liteos/build/link/flashboot_sha256.lds b/sdk_liteos/build/link/flashboot_sha256.lds new file mode 100755 index 0000000000000000000000000000000000000000..e97024442bf70bfd5264a926c8a35cee81f2e3ea --- /dev/null +++ b/sdk_liteos/build/link/flashboot_sha256.lds @@ -0,0 +1,150 @@ +OUTPUT_ARCH( "riscv" ) +ENTRY(_start) + +MEMORY +{ + /* FlashBoot location on Flash */ + FLASH (rwx) : ORIGIN = 0x400000+0x40, LENGTH = 32K-0x040-0x3C0 + /* ram for stack */ + STACK(xrw) : ORIGIN = 0x100000,LENGTH = 8K + /* ram for common bss and data */ + SRAM(xrw) : ORIGIN = 0x100000+8K,LENGTH = 8K + /* ram for fix rom bss and data */ + ROM_BSS_DATA(rx): ORIGIN = 0x100000+16K,LENGTH = 2K + /* ram for code rom bss and data */ + CODE_ROM_BSS_DATA(rx): ORIGIN = 0x100000+18K,LENGTH = 2K + /* signature */ + SIGN(rx): ORIGIN = 0x100000+40K,LENGTH = 0x040 + /* ram for flashboot */ + FLASH_BOOT(rx): ORIGIN = 0x100000+40K+0x040,LENGTH = 80K-0x040 + /* ram for heap */ + HEAP(xrw): ORIGIN = 0xdc000,LENGTH = 144K + /* rom for fixed rom */ + FIXED_ROM(rx): ORIGIN = 0x00000000+11K,LENGTH = 21K + /* rom for code rom */ + CODE_ROM(rx): ORIGIN = 0x003b8000+278K,LENGTH = 10K +} + +SECTIONS +{ + /* The startup code goes first into FLASH */ + .text.entry : ALIGN(4) + { + KEEP(*(.text.entry)) + } > FLASH_BOOT AT>FLASH + + .rom.text : + { + . = ALIGN(4); + KEEP(SORT(libbase.o)(.text*)) + KEEP(SORT(libbase.o)(.rodata*)) + . = ALIGN(4); + } > FIXED_ROM + + .rom.code.text : + { + . = ALIGN(4); + KEEP(SORT(libcodebase.o)(.text*)) + KEEP(SORT(libcodebase.o)(.rodata*)) + . = ALIGN(4); + } > CODE_ROM + + /* Stack in SRAM at Highest addresses */ + .stacks (NOLOAD) : + { + . = ALIGN(4); + __SYSTEM_STACK_BEGIN__ = ORIGIN(STACK); + KEEP(*(.stacks)) + __SYSTEM_STACK_END__ = ORIGIN(STACK) + LENGTH(STACK); + } > STACK + __SYSTEM_STACK_SIZE__ = __SYSTEM_STACK_END__ - __SYSTEM_STACK_BEGIN__; + __stack_top = __SYSTEM_STACK_END__; + + .rom.data : + { + . = ALIGN(4); + __rom_copy_start = LOADADDR(.rom.data); + . = ALIGN(4); + __rom_copy_ram_start = .; + __global_pointer$ = .; + KEEP(SORT(libbase.o) (.data*)) + . = ALIGN(4); + __rom_copy_ram_end = .; + } > ROM_BSS_DATA AT>FIXED_ROM + __rom_copy_size = __rom_copy_ram_end - __rom_copy_ram_start; + + .rom.code.data : + { + . = ALIGN(4); + __code_rom_copy_start = LOADADDR(.rom.code.data); + . = ALIGN(4); + __code_rom_copy_ram_start = .; + KEEP(SORT(libcodebase.o) (.data*)) + . = ALIGN(4); + __code_rom_copy_ram_end = .; + }>CODE_ROM_BSS_DATA AT>CODE_ROM + __code_rom_copy_size = __code_rom_copy_ram_end - __code_rom_copy_ram_start; + + .rom.bss : + { + . = ALIGN(4); + __rom_bss_start = .; + KEEP(libbase.o (.bss)) + KEEP(libbase.o (.bss*)) + KEEP(libbase.o (COMMON)) + . = ALIGN(4); + __rom_bss_end = .; + } > ROM_BSS_DATA AT>FIXED_ROM + + .rom.code.bss : + { + . = ALIGN(4); + __code_rom_bss_start = .; + KEEP(libcodebase.o (.bss)) + KEEP(libcodebase.o (.bss*)) + KEEP(libcodebase.o (COMMON)) + . = ALIGN(4); + __code_rom_bss_end = .; + }>CODE_ROM_BSS_DATA AT>CODE_ROM + + .text : ALIGN(4) + { + __start_addr = .; + *(.text*) + . = ALIGN(4); + __rodata_start = .; + *(.rodata*) + . = ALIGN(4); + __rodata_end = .; + __text_end = .; + } > FLASH_BOOT AT>FLASH + + /* data section */ + .data : ALIGN(4) + { + __data_load = LOADADDR(.data); + __data_start = .; + *(.data*) + . = ALIGN(4); + __data_end = .; + } > FLASH_BOOT AT>FLASH + + /* bss section */ + .bss (NOLOAD) : ALIGN(4) + { + __bss_begin__ = .; + *(.bss*) + *(COMMON) + . = ALIGN(4); + __bss_end__ = .; + } > FLASH_BOOT + __bss_size__ = __bss_end__ - __bss_begin__; + + .heap (NOLOAD) : + { + . = ALIGN(4); + __heap_begin__ = ORIGIN(HEAP); + KEEP(*(.heap)) + __heap_end__ = __heap_begin__ + LENGTH(HEAP); + } > HEAP +} diff --git a/sdk_liteos/build/link/link.ld.S b/sdk_liteos/build/link/link.ld.S new file mode 100755 index 0000000000000000000000000000000000000000..38faa99f99d00e19d3fb6f0d84e0f199366f3d06 --- /dev/null +++ b/sdk_liteos/build/link/link.ld.S @@ -0,0 +1,597 @@ +OUTPUT_ARCH( "riscv" ) +ENTRY(_start) + +#ifdef LOSCFG_DEBUG_KASAN +#define MAX_BIN_SIZE 3M +#else +#define MAX_BIN_SIZE 2M +#endif + +#ifdef HI_BOARD_ASIC +#ifdef HI_ON_FLASH + +#ifdef CONFIG_CHIP_PKT_48K +#define RAM_SIZE 264K /* PKT_B:48K */ +#define RAM_START 0x000dc000 /* PKT_B:48K */ +#else +#define RAM_SIZE 280K /* PKT_B:32K*/ +#define RAM_START 0x000d8000 /* PKT_B:32K */ +#endif + +#else +#define RAM_SIZE 248K /* PKT_B:64K + NO DC */ +#define RAM_START 0x000e0000 /* PKT_B:64K */ +#endif +#else +#ifdef HI_ON_FLASH +#ifdef LOSCFG_DEBUG_KASAN +#define RAM_SIZE 896K +#else +#define RAM_SIZE 1M +#endif +#define RAM_START 0x00100000 +#else +#define RAM_SIZE 248K /* PKT_B:64K + NO DC */ +#define RAM_START 0x000e0000 /* PKT_B:64K */ +#endif +#endif + +#ifdef LOSCFG_DEBUG_KASAN +#define FLASH_SIZE 3M +#else +#define FLASH_SIZE 2M +#endif + +#ifdef CONFIG_FLASH_ENCRYPT_SUPPORT +#define CRYPTO_RAM_LEN 4096 +#endif + +STACK_SIZE = 2k; /* needs to be calculated for your application */ +IRQ_STACK_SIZE = 3K; +EXC_STACK_SIZE = 2K; +#if (defined CONFIG_TEE_HUKS_SUPPORT) || (defined CONFIG_TARGET_SIG_RSA_V15) || (defined CONFIG_TARGET_SIG_RSA_PSS) || (defined CONFIG_TARGET_SIG_ECC) +NMI_STACK_SIZE = 2K; +#else +NMI_STACK_SIZE = 0K; +#endif +DOWNLOAD_STACK_SIZE = 4K; +DOWNLOAD_IRQ_STACK_SIZE = 2K; + +/* actually rom data0 size is 944 byte, when rom fixed, may all data can be placed in rom. */ +#define ROM_DATA0_LEN 32 /* 32 bytes align */ + +#ifdef LOSCFG_DEBUG_KASAN +#define ROM_DATA1_LEN 5056 /* 32 bytes align */ +#else +#define ROM_DATA1_LEN 2016 /* 32 bytes align */ +#endif + +#define ROM_BSS_LEN 11776 /* 32 bytes align */ +#define PATCH_BSS_LEN 1024 /* 1024 bytes align */ + +#ifdef HI_ON_FLASH +#define SECURE_HEAD 0 /* iot has no Signature head */ +#else +#define SECURE_HEAD 0x5A0 /* non-iot Signature lenth */ +#endif + +#define ROM_TEXT_LEN (278K - ROM_DATA0_LEN) +#define CHECK_INFO_LEN 0x40 +#if (defined HI_BOARD_ASIC) || (!defined HI_ON_FLASH) +#define STACK_LEN (STACK_SIZE + IRQ_STACK_SIZE + EXC_STACK_SIZE + NMI_STACK_SIZE) +#endif + +#define ROM_RAM_LEN (ROM_DATA0_LEN + ROM_DATA1_LEN + ROM_BSS_LEN + CHECK_INFO_LEN) +#define ROM_RAM_START (0x11DFFF - ROM_RAM_LEN + 1) +#define ROM_START 0x003b8000 +#define FLASH_START 0x00400000 +#define BIN_START FLASH_FIRM_START /* The value of macro is transfered by scons. And the value varies with the signature. */ + +#ifndef HI_BOARD_ASIC +/* only use in FPGA. */ +#define RAM_FPGA_START 0x11E000 +#define RAM_FPGA_LEN (1M - 120K) +#endif + +#if defined(ROM_BIN_TEST) +#define TEST_OFFSET 7 +#else +#define TEST_OFFSET 0 +#endif + +#define ROM_TEXT_VMA ROM_START + +#define ROM_BSS_VMA ROM_RAM_START +#define ROM_DATA0_VMA (ROM_RAM_START + ROM_BSS_LEN) +#define ROM_DATA1_VMA (ROM_DATA0_VMA + ROM_DATA0_LEN) +#define CHECK_INFO_VMA (ROM_DATA1_VMA + ROM_DATA1_LEN) +#define PATCH_BSS_START RAM_START +#ifdef CONFIG_FLASH_ENCRYPT_SUPPORT +#define CRYPTO_RAM_START (PATCH_BSS_START + PATCH_BSS_LEN + SECURE_HEAD) +#define NON_ROM_RAM_START (CRYPTO_RAM_START + CRYPTO_RAM_LEN) +#else +#define NON_ROM_RAM_START (PATCH_BSS_START + PATCH_BSS_LEN + SECURE_HEAD) +#endif +#if (defined HI_BOARD_ASIC) || (!defined HI_ON_FLASH) +#define STACK_VMA ROM_RAM_START - STACK_LEN +#endif + +#define ROM_TEXT_LMA (BIN_START - ROM_TEXT_LEN - ROM_DATA0_LEN) +#define ROM_DATA0_LMA (ROM_TEXT_LMA + ROM_TEXT_LEN) + +#ifdef HI_ON_FLASH +#define NON_ROM_TEXT_REGION FLASH +#else +#define NON_ROM_TEXT_REGION RAM +#endif + +#ifdef CONFIG_FLASH_ENCRYPT_SUPPORT +#define RAM_CRYPTO_TEXT_LMA (ROM_DATA0_LMA + ROM_DATA0_LEN) +#define NON_ROM_TEXT_LMA (RAM_CRYPTO_TEXT_LMA + CRYPTO_RAM_LEN) +#else +#define NON_ROM_TEXT_LMA (ROM_DATA0_LMA + ROM_DATA0_LEN) +#endif + +#define ZINIT_NO_ROM_TEXT_LMA ((NON_ROM_TEXT_LMA + SIZEOF (.text_non_rom) + (0x20) - 1) & ~ ((0x20) - 1)) +#define RAM_TEXT_LMA ((ZINIT_NO_ROM_TEXT_LMA + SIZEOF (.zInit) + (0x20) - 1) & ~ ((0x20) - 1)) +#define NON_ROM_DATA_LMA ((RAM_TEXT_LMA + SIZEOF (.ram_text) + (0x20) -1) & ~ ((0x20) - 1)) +#define ROM_DATA1_LMA ((NON_ROM_DATA_LMA + SIZEOF(.data) + (0x20) - 1) & ~ ((0x20) - 1)) + +#if (defined HI_BOARD_ASIC) || (!defined HI_ON_FLASH) + +#ifdef CONFIG_FLASH_ENCRYPT_SUPPORT +#define RAM_LEN (RAM_SIZE - ROM_RAM_LEN - PATCH_BSS_LEN - STACK_LEN- SECURE_HEAD - CRYPTO_RAM_LEN) +#else +#define RAM_LEN (RAM_SIZE - ROM_RAM_LEN - PATCH_BSS_LEN - STACK_LEN - SECURE_HEAD) +#endif + +#else +#define RAM_LEN (RAM_SIZE - ROM_RAM_LEN - PATCH_BSS_LEN - SECURE_HEAD) +#endif + +#define KEEP_SORT_GCC_TEXT(obj) KEEP(SORT(*libgcc.a:obj)(.text*)) +#define KEEP_SORT_GCC_RODATA(obj) KEEP(SORT(*libgcc.a:obj)(.rodata*)) +#define KEEP_SORT_GCC_DATA(obj) KEEP(SORT(*libgcc.a:obj)(.data*)) +#define KEEP_SORT_GCC_BSS(obj) KEEP(SORT(*libgcc.a:obj)(.bss*)) +#define LIBGCC_ROM_FUN(func) func(save-restore.o) func(_clzsi2.o) func(_umoddi3.o) func(_clz.o) func(_ashldi3.o) func(_lshrdi3.o) func(fixdfsi.o) func(_udivdi3.o) + +MEMORY +{ + BIN(rx) : ORIGIN = BIN_START, LENGTH = MAX_BIN_SIZE + ROM_TEXT(rx) : ORIGIN = ROM_TEXT_VMA, LENGTH = ROM_TEXT_LEN /* code and rodata of download,kernel,lib,bsp,wifi... */ + ROM_DATA0(rwx) : ORIGIN = ROM_DATA0_VMA, LENGTH = ROM_DATA0_LEN /* data used by download rom code */ + ROM_DATA1(rwx) : ORIGIN = ROM_DATA1_VMA, LENGTH = 1768 /* data used by other rom code:1768 byte */ + ROM_BSS(rwx) : ORIGIN = ROM_BSS_VMA, LENGTH = ROM_BSS_LEN /* bss used by rom code */ +#if (defined HI_BOARD_ASIC) || (!defined HI_ON_FLASH) + STACK(rw) : ORIGIN = STACK_VMA, LENGTH = STACK_LEN /* stack */ +#endif + CHECK_INFO(rw) : ORIGIN = CHECK_INFO_VMA, LENGTH = CHECK_INFO_LEN /* check info used by rom code */ +#ifdef CONFIG_FLASH_ENCRYPT_SUPPORT + FLASH(rwx) : ORIGIN = FLASH_FIRM_START + CRYPTO_RAM_LEN, LENGTH = FLASH_START + FLASH_SIZE - FLASH_FIRM_START - CRYPTO_RAM_LEN +#else + FLASH(rwx) : ORIGIN = FLASH_FIRM_START, LENGTH = FLASH_START + FLASH_SIZE - FLASH_FIRM_START +#endif + PATCH_BSS(rwx) : ORIGIN = PATCH_BSS_START, LENGTH = PATCH_BSS_LEN /* flash patch remap */ +#ifdef CONFIG_FLASH_ENCRYPT_SUPPORT + CRYPTO_RAM(rwx) : ORIGIN = CRYPTO_RAM_START, LENGTH = CRYPTO_RAM_LEN /* 4K kernel crypto */ +#endif + RAM(rwx) : ORIGIN = NON_ROM_RAM_START, LENGTH = RAM_LEN /* non rom data,bss,stack,heap */ + EXTERN_ROM_DATA1_BSS(rwx) : ORIGIN = 0x11dec8, LENGTH = ROM_DATA1_LEN-1768 /* use extern rom data 1 as non_rom bss */ +#if (defined HI_BOARD_FPGA) && (defined HI_ON_FLASH) + RAM_FPGA(rwx) : ORIGIN = RAM_FPGA_START, LENGTH = RAM_FPGA_LEN /* FPGA stack and heap */ +#endif +} + +SECTIONS +{ + .text_rom : AT (ROM_TEXT_LMA) + { + . = ALIGN(0x20); + __rom_text_begin__ = .; + __text_cache_start1_ = .; + _rom_size_download_start = .; + KEEP(SORT(*)(.text.download_entry)) + . = ALIGN(0x4); + KEEP(SORT(*)(.text.trap_download_vector)) + KEEP(SORT(*)(.text.download_assemble)) + . = ALIGN(0x4); + _rom_size_download_end = .; + _rom_size_download = _rom_size_download_end - _rom_size_download_start; + KEEP(SORT(libwifi_base.o)(.text*)) + KEEP(SORT(*)(.wifi.rom.text*)) + . = ALIGN(0x20); + _rom_wifi_rom_end = .; + _rom_size_libwifi = _rom_wifi_rom_end - _rom_size_download; + KEEP(SORT(libbsp_base.o)(.text*)) + _rom_bsp_rom_end = .; + _rom_size_libbsp = _rom_bsp_rom_end - _rom_wifi_rom_end; + KEEP(SORT(liblitekernel_base.o)(.text*)) + _rom_kernel_rom_end = .; + _rom_size_kernel = _rom_kernel_rom_end - _rom_bsp_rom_end; + LIBGCC_ROM_FUN(KEEP_SORT_GCC_TEXT) + _rom_libgcc_end = .; + _rom_size_libgcc = _rom_libgcc_end - _rom_kernel_rom_end; + KEEP(SORT(libc_base.o)(.text*)) + _rom_libc_rom_end = .; + _rom_size_libc = _rom_libc_rom_end - _rom_libgcc_end; + KEEP(SORT(libsec_base.o)(.text*)) + _rom_sec_rom_end = .; + _rom_size_libsec = _rom_sec_rom_end - _rom_libc_rom_end; + __text_cache_end1_ = .; + KEEP(SORT(libwifi_base.o)(.rodata*)) + KEEP(SORT(*)(.wifi.rom.rodata*)) + . = ALIGN(0x4); + _rom_hi1131_wifi_rom_rodata_end = .; + _rom_size_rodata_wifi = _rom_hi1131_wifi_rom_rodata_end - _rom_sec_rom_end; + KEEP(SORT(libbsp_base.o)(.rodata*)) + KEEP(SORT(*)(.bsp.rom.rodata)) + _rom_libbsp_rom_rodata_end = .; + _rom_size_rodata_bsp = _rom_libbsp_rom_rodata_end - _rom_hi1131_wifi_rom_rodata_end; + KEEP(SORT(liblitekernel_base.o)(.rodata*)) + _rom_litekenel_rom_rodata_end = .; + _rom_size_rodata_kernel = _rom_litekenel_rom_rodata_end - _rom_size_rodata_bsp; + LIBGCC_ROM_FUN(KEEP_SORT_GCC_RODATA) + _rom_libgcc_rodata_end = .; + _rom_size_rodata_libgcc = _rom_libgcc_rodata_end - _rom_litekenel_rom_rodata_end; + KEEP(SORT(libc_base.o)(.rodata*)) + _rom_libcrom_rodata_end = .; + _rom_size_rodata_libc = _rom_libcrom_rodata_end - _rom_libgcc_rodata_end; + KEEP(SORT(libsec_base.o)(.rodata*)) + _rom_libsec_rom_rodata_end = .; + _rom_size_rodata_sec = _rom_libsec_rom_rodata_end - _rom_libcrom_rodata_end; + __rom_text_end__ = .; + } > ROM_TEXT + __rom_text_size__ = __rom_text_end__ - __rom_text_begin__; + + .data_rom0 : AT (ROM_DATA0_LMA) + { + . = ALIGN(0x20); + __rom_data0_begin__ = .; + KEEP(SORT(liblitekernel_base.o) (.data.kernel.rom*)) + KEEP(SORT(*)(.bsp.rom.data0)) + . = ALIGN(0x4); + __rom_data0_end__ = .; + } > ROM_DATA0 + __rom_data0_size__ = __rom_data0_end__ - __rom_data0_begin__; + _rom_size_total = __rom_data0_size__ + __rom_text_size__; + __rom_data0_load = ROM_TEXT_VMA + ROM_TEXT_LEN; + +#if defined(CONFIG_FLASH_ENCRYPT_SUPPORT) + .crypto_ram_text : AT (RAM_CRYPTO_TEXT_LMA) + { + __crypto_ram_text_load = LOADADDR(.crypto_ram_text); + __crypto_ram_text_start = .; + . = ALIGN(0x20); + KEEP(*(.crypto.ram.text)) + . = ALIGN(0x20); + __crypto_ram_text_end = .; + } > CRYPTO_RAM + __crypto_ram_text_size = __crypto_ram_text_end - __crypto_ram_text_start; +#endif + + .text_non_rom : AT (NON_ROM_TEXT_LMA) + { + . = ALIGN(0x20); + __text_cache_start2_ = .; + KEEP(*(.entry.text)) + . = ALIGN(0x20); + #if defined(ROM_BIN_TEST) + . += TEST_OFFSET; + #endif + SORT(*)(.init*) + SORT(*)(.rom.text.patch) + SORT(*)(EXCLUDE_FILE(*libasm_flash.o) .text*) + /* temply add the following for hks. */ + SORT(*)(EXCLUDE_FILE(*libasm_flash.o) .got*) + . = ALIGN(0x20); + __text_cache_end2_ = .; + SORT(*)(.rodata*) + . = ALIGN(0x20); + __text_rodata_end_ = .; + . = ALIGN(0x20); + } > NON_ROM_TEXT_REGION + + /* zInit code and data - will be freed after init */ + .zInit : AT (ADDR(.text_non_rom) + SIZEOF(.text_non_rom)) + { + __zinitcall_bsp_start = .; + KEEP (*(.zinitcall.bsp0.init)) + KEEP (*(.zinitcall.bsp1.init)) + KEEP (*(.zinitcall.bsp2.init)) + KEEP (*(.zinitcall.bsp3.init)) + KEEP (*(.zinitcall.bsp4.init)) + __zinitcall_bsp_end = .; + __zinitcall_device_start = .; + KEEP (*(.zinitcall.device0.init)) + KEEP (*(.zinitcall.device1.init)) + KEEP (*(.zinitcall.device2.init)) + KEEP (*(.zinitcall.device3.init)) + KEEP (*(.zinitcall.device4.init)) + __zinitcall_device_end = .; + __zinitcall_core_start = .; + KEEP (*(.zinitcall.core0.init)) + KEEP (*(.zinitcall.core1.init)) + KEEP (*(.zinitcall.core2.init)) + KEEP (*(.zinitcall.core3.init)) + KEEP (*(.zinitcall.core4.init)) + __zinitcall_core_end = .; + __zinitcall_sys_service_start = .; + KEEP (*(.zinitcall.sys.service0.init)) + KEEP (*(.zinitcall.sys.service1.init)) + KEEP (*(.zinitcall.sys.service2.init)) + KEEP (*(.zinitcall.sys.service3.init)) + KEEP (*(.zinitcall.sys.service4.init)) + __zinitcall_sys_service_end = .; + __zinitcall_sys_feature_start = .; + KEEP (*(.zinitcall.sys.feature0.init)) + KEEP (*(.zinitcall.sys.feature1.init)) + KEEP (*(.zinitcall.sys.feature2.init)) + KEEP (*(.zinitcall.sys.feature3.init)) + KEEP (*(.zinitcall.sys.feature4.init)) + __zinitcall_sys_feature_end = .; + __zinitcall_run_start = .; + KEEP (*(.zinitcall.run0.init)) + KEEP (*(.zinitcall.run1.init)) + KEEP (*(.zinitcall.run2.init)) + KEEP (*(.zinitcall.run3.init)) + KEEP (*(.zinitcall.run4.init)) + __zinitcall_run_end = .; + __zinitcall_app_service_start = .; + KEEP (*(.zinitcall.app.service0.init)) + KEEP (*(.zinitcall.app.service1.init)) + KEEP (*(.zinitcall.app.service2.init)) + KEEP (*(.zinitcall.app.service3.init)) + KEEP (*(.zinitcall.app.service4.init)) + __zinitcall_app_service_end = .; + __zinitcall_app_feature_start = .; + KEEP (*(.zinitcall.app.feature0.init)) + KEEP (*(.zinitcall.app.feature1.init)) + KEEP (*(.zinitcall.app.feature2.init)) + KEEP (*(.zinitcall.app.feature3.init)) + KEEP (*(.zinitcall.app.feature4.init)) + __zinitcall_app_feature_end = .; + __zinitcall_test_start = .; + KEEP (*(.zinitcall.test0.init)) + KEEP (*(.zinitcall.test1.init)) + KEEP (*(.zinitcall.test2.init)) + KEEP (*(.zinitcall.test3.init)) + KEEP (*(.zinitcall.test4.init)) + __zinitcall_test_end = .; + __zinitcall_exit_start = .; + KEEP (*(.zinitcall.exit0.init)) + KEEP (*(.zinitcall.exit1.init)) + KEEP (*(.zinitcall.exit2.init)) + KEEP (*(.zinitcall.exit3.init)) + KEEP (*(.zinitcall.exit4.init)) + __zinitcall_exit_end = .; + } > NON_ROM_TEXT_REGION + + .ram_text : AT (RAM_TEXT_LMA) + { + __ram_text_load = LOADADDR(.ram_text); + __ram_text_start = .; + . = ALIGN(0x20); + #if defined(ROM_BIN_TEST) + . += TEST_OFFSET; + #endif + #if defined(HI1131TEST) + KEEP(*(.trap_vector.text)) + KEEP(*(.kernel.ram.text)) + KEEP(*(.ram.kernel)) + KEEP(*(.bsp.ram.text)) + KEEP(SORT(libasm_flash.o)(.text*)) + #else + SORT(*)(.trap_vector.text) + SORT(*)(.kernel.ram.text) + SORT(*)(.ram.kernel) + SORT(*)(.bsp.ram.text) + SORT(libasm_flash.o)(.text*) + #endif + . = ALIGN(0x20); + __ram_text_end = .; + } > RAM + __ram_text_size = __ram_text_end - __ram_text_start; + + /* data section */ + .data : AT (NON_ROM_DATA_LMA) + { +#if defined(HI_ON_FLASH) + __data_load = LOADADDR(.data); +#else + __data_load = LOADADDR(.data) - ORIGIN(FLASH) + ORIGIN(RAM); +#endif + . = ALIGN(0x20); + __data_start = .; + #if defined(ROM_BIN_TEST) + . += TEST_OFFSET; + #endif + SORT(*)(EXCLUDE_FILE(*liblitekernel_base.o *libc_base.o *libsec_base.o *libwifi_base.o *libbsp_base.o) .data*) + SORT(*)(EXCLUDE_FILE(*.o) .wifi.rom.data*) + SORT(*)(EXCLUDE_FILE(*.o) .data.system.rom*) + SORT(*)(.rom.data.patch) + SORT(*)(.sdata*) + . = ALIGN(4); + INCLUDE system_config.ld + . = ALIGN(0x20); + __data_end = .; + } > RAM + __data_size = __data_end - __data_start; + + .data_rom1 : AT (ROM_DATA1_LMA) + { +#if defined(HI_ON_FLASH) + __rom_data1_load = LOADADDR(.data_rom1); +#else + __rom_data1_load = LOADADDR(.data_rom1) - ORIGIN(FLASH) + ORIGIN(RAM); +#endif + . = ALIGN(0x20); + __rom_data1_begin__ = .; + LIBGCC_ROM_FUN(KEEP_SORT_GCC_DATA) + KEEP(SORT(liblitekernel_base.o) (.data*)) + KEEP(SORT(libbsp_base.o) (.data*)) + KEEP(SORT(*)(.data.system.rom*)) + KEEP(SORT(libc_base.o) (.data*)) + KEEP(SORT(libsec_base.o) (.data*)) + KEEP(SORT(libwifi_base.o) (.data*)) + KEEP(SORT(*)(.wifi.rom.data*)) + . = ALIGN(4); + __rom_data1_end__ = .; + } > ROM_DATA1 + __rom_data1_size__ = __rom_data1_end__ - __rom_data1_begin__; + + /* used for fpb remap table g_fpbRemap declaration in los_fpb.c */ + .patch_bss (NOLOAD) : + { + __patch_bss_start = .; + KEEP(SORT(*)(.fpb.remap)) + . = ALIGN(4); + __patch_bss_end__ = .; + } > PATCH_BSS + + .bss_rom (NOLOAD) : + { + . = ALIGN(0x20); + __rom_bss_begin__ = .; + __global_pointer$ = .; + LIBGCC_ROM_FUN(KEEP_SORT_GCC_BSS) + KEEP(SORT(liblitekernel_base.o )(.bss*)) + KEEP(SORT(libc_base.o)(.bss*)) + KEEP(SORT(libsec_base.o)(.bss*)) + KEEP(SORT(libbsp_base.o)(.bss*)) + KEEP(SORT(libwifi_base.o) (.bss*)) + KEEP(SORT(*)(.wifi.rom.bss*)) + . = ALIGN(4); + __rom_bss_end__ = .; + /* ԭrom_bssδװӷrom bss(1568 byte:1.53K) */ + SORT(*)(.extern.rom.bss*) + . = ALIGN(4); + __extern_rom_bss_end__ = .; + } > ROM_BSS + __rom_bss_size__ = __extern_rom_bss_end__ - __rom_bss_begin__; + + /* rom_data_extern1 section */ + .extern_rom_data1_bss (NOLOAD) : + { + . = ALIGN(0x20); + __extern_rom_data1_bss_begin__ = .; + #if defined(ROM_BIN_TEST) + . += TEST_OFFSET; + #endif + SORT(*)(.extern.rom.data1.bss*) + . = ALIGN(4); + __extern_rom_data1_bss_end__ = .; + } > EXTERN_ROM_DATA1_BSS + __extern_rom_data1_bss_size__ = __extern_rom_data1_bss_end__ - __extern_rom_data1_bss_begin__; + + __RAM_BEGIN__ = ORIGIN(RAM); + __RAM_SIZE__ = LENGTH(RAM); + __DOWNLOAD_IRQ_STACK = ORIGIN(ROM_BSS) - DOWNLOAD_STACK_SIZE; /* overlap with STACK*/ + __DOWNLOAD_STACK_END = ORIGIN(ROM_BSS); /* relate to KERNEL_MALLOC_STAR_ADDR and KERNEL_MALLOC_END_ADDR */ + + /* bss section */ +#ifdef LOSCFG_DEBUG_KASAN + .bss (NOLOAD) : ALIGN(0x20) + { + . = ALIGN(0x20); + __bss_begin = .; + #if defined(ROM_BIN_TEST) + . += TEST_OFFSET; + #endif + SORT(*)(.bss*) + SORT(*)(.rom.bss.patch) + SORT(*)(.sbss*) + . = ALIGN(0x20); + __bss_end = .; + } > RAM_FPGA +#else + .bss (NOLOAD) : ALIGN(0x20) + { + . = ALIGN(0x20); + __bss_begin = .; + #if defined(ROM_BIN_TEST) + . += TEST_OFFSET; + #endif + SORT(*)(.bss*) + SORT(*)(.rom.bss.patch) + SORT(*)(.sbss*) + . = ALIGN(0x20); + __bss_end = .; + } > RAM +#endif + __bss_size__ = __bss_end - __bss_begin; + + /* End of uninitialized data segment */ + _end = .; +#if (defined HI_BOARD_ASIC) || (!defined HI_ON_FLASH) + .heap (NOLOAD) : + { + . = ALIGN(64); + __HEAP_BEGIN__ = ABSOLUTE(.); + } > RAM + __HEAP_SIZE__ = (__RAM_BEGIN__ + __RAM_SIZE__) - __HEAP_BEGIN__; + + .stack (NOLOAD) : ALIGN(0x20) + { + __SYSTEM_STACK_BEGIN__ = .; + . += STACK_SIZE; + __SYSTEM_STACK_END__ = .; + . = ALIGN(0x20); + __irq_stack_bottom = .; + . += IRQ_STACK_SIZE; + __irq_stack_top = .; + . = ALIGN(0x20); + __nmi_stack_bottom = .; + . += NMI_STACK_SIZE; + __nmi_stack_top = .; + . = ALIGN(0x20); + __exc_stack_bottom = .; + . += EXC_STACK_SIZE; + __exc_stack_top = .; + } > STACK + __SYSTEM_STACK_SIZE__ = __SYSTEM_STACK_END__ - __SYSTEM_STACK_BEGIN__; + + .check_info (NOLOAD) : + { + __check_info_addr = .; + KEEP(SORT(*)(.lowpower.ram.bss*)) + } > CHECK_INFO +#else + .stack (NOLOAD) : ALIGN(0x20) + { + __SYSTEM_STACK_BEGIN__ = .; + . += STACK_SIZE; + __SYSTEM_STACK_END__ = .; + . = ALIGN(0x20); + __irq_stack_bottom = .; + . += IRQ_STACK_SIZE; + __irq_stack_top = .; + . = ALIGN(0x20); + __nmi_stack_bottom = .; + . += NMI_STACK_SIZE; + __nmi_stack_top = .; + __exc_stack_bottom = .; + . += EXC_STACK_SIZE; + __exc_stack_top = .; + . = ALIGN(0x20); + } > RAM_FPGA + __SYSTEM_STACK_SIZE__ = __SYSTEM_STACK_END__ - __SYSTEM_STACK_BEGIN__; + + .heap (NOLOAD) : + { + . = ALIGN(64); + __HEAP_BEGIN__ = ABSOLUTE(.); + } > RAM_FPGA + __HEAP_SIZE__ = (RAM_FPGA_START + RAM_FPGA_LEN) - __HEAP_BEGIN__; + + .check_info (NOLOAD) : + { + __check_info_addr = .; + KEEP(SORT(*)(.lowpower.ram.bss*)) + } > CHECK_INFO +#endif + __ram_start = RAM_START; + __ram_end = RAM_START + RAM_SIZE; + . = ALIGN(4); + end = . ; +} + diff --git a/sdk_liteos/build/link/loaderboot_ecc.lds b/sdk_liteos/build/link/loaderboot_ecc.lds new file mode 100755 index 0000000000000000000000000000000000000000..5bf6e8cb4eab4ed98406a3e84aa7c33594b77dd8 --- /dev/null +++ b/sdk_liteos/build/link/loaderboot_ecc.lds @@ -0,0 +1,154 @@ +OUTPUT_ARCH( "riscv" ) +ENTRY(_start) + +MEMORY +{ + /* ram for stack */ + STACK(xrw) : ORIGIN = 0x100000,LENGTH = 8K + /* ram for common bss and data */ + SRAM(xrw) : ORIGIN = 0x100000+8K,LENGTH = 8K + /* ram for fix rom bss and data */ + ROM_BSS_DATA(rx): ORIGIN = 0x100000+16K,LENGTH = 2K + /* ram for code rom bss and data */ + CODE_ROM_BSS_DATA(rx): ORIGIN = 0x100000+18K,LENGTH = 2K + /* ram for heap */ + HEAP(xrw): ORIGIN = 0x100000+20K,LENGTH = 20K + /* ram for loaderboot */ + LOADER_BOOT_ADDR(rx): ORIGIN = 0x100000+40K+0x150,LENGTH = 80K + /* rom for fixed rom */ + FIXED_ROM_ADDR(rx): ORIGIN = 0x00000000+11K,LENGTH = 21K + /* rom for code rom */ + CODE_ROM_ADDR(rx): ORIGIN = 0x003b8000+278K,LENGTH = 10K +} + +STACK_SIZE = 6k; +NMI_STACK_SIZE = 2K; + +SECTIONS +{ + /* The startup code goes first into FLASH */ + .text.entry : ALIGN(4) + { + KEEP(*(.text.entry)) + } > LOADER_BOOT_ADDR + + .rom.text : + { + . = ALIGN(4); + KEEP(SORT(libbase.o)(.text*)) + KEEP(SORT(libbase.o)(.rodata*)) + . = ALIGN(4); + } > FIXED_ROM_ADDR + + .rom.code.text : + { + . = ALIGN(4); + KEEP(SORT(libcodebase.o)(.text*)) + KEEP(SORT(libcodebase.o)(.rodata*)) + . = ALIGN(4); + } > CODE_ROM_ADDR + + /* Stack in SRAM at Highest addresses */ + .stacks (NOLOAD) : + { + . = ALIGN(4); + __SYSTEM_STACK_BEGIN__ = ORIGIN(STACK); + KEEP(*(.stacks)) + __SYSTEM_STACK_END__ = ORIGIN(STACK) + STACK_SIZE; + . = ALIGN(0x20); + __nmi_stack_bottom = .; + . += NMI_STACK_SIZE; + __nmi_stack_top = .; + } > STACK + __SYSTEM_STACK_SIZE__ = __SYSTEM_STACK_END__ - __SYSTEM_STACK_BEGIN__; + __stack_top = __SYSTEM_STACK_END__; + + .rom.data : + { + . = ALIGN(4); + __rom_copy_start = LOADADDR(.rom.data); + . = ALIGN(4); + __rom_copy_ram_start = .; + __global_pointer$ = .; + KEEP(SORT(libbase.o) (.data*)) + . = ALIGN(4); + __rom_copy_ram_end = .; + } > ROM_BSS_DATA AT>FIXED_ROM_ADDR + __rom_copy_size = __rom_copy_ram_end - __rom_copy_ram_start; + + .rom.code.data : + { + . = ALIGN(4); + __code_rom_copy_start = LOADADDR(.rom.code.data); + . = ALIGN(4); + __code_rom_copy_ram_start = .; + KEEP(SORT(libcodebase.o) (.data*)) + . = ALIGN(4); + __code_rom_copy_ram_end = .; + }>CODE_ROM_BSS_DATA AT>CODE_ROM_ADDR + __code_rom_copy_size = __code_rom_copy_ram_end - __code_rom_copy_ram_start; + + .rom.bss : + { + . = ALIGN(4); + __rom_bss_start = .; + KEEP(libbase.o (.bss)) + KEEP(libbase.o (.bss*)) + KEEP(libbase.o (COMMON)) + . = ALIGN(4); + __rom_bss_end = .; + } > ROM_BSS_DATA AT>FIXED_ROM_ADDR + + .rom.code.bss : + { + . = ALIGN(4); + __code_rom_bss_start = .; + KEEP(libcodebase.o (.bss)) + KEEP(libcodebase.o (.bss*)) + KEEP(libcodebase.o (COMMON)) + . = ALIGN(4); + __code_rom_bss_end = .; + }>CODE_ROM_BSS_DATA AT>CODE_ROM_ADDR + + .text : ALIGN(4) + { + __start_addr = .; + *(.text*) + *(.ram.text*) + . = ALIGN(4); + __rodata_start = .; + *(.rodata*) + . = ALIGN(4); + __rodata_end = .; + __text_end = .; + } > LOADER_BOOT_ADDR + + /* data section */ + .data : ALIGN(4) + { + __data_load = LOADADDR(.data); + __data_start = .; + *(.data*) + . = ALIGN(4); + __data_end = .; + } > LOADER_BOOT_ADDR + + /* bss section */ + .bss (NOLOAD) : ALIGN(4) + { + __bss_begin__ = .; + *(.bss*) + *(COMMON) + . = ALIGN(4); + __bss_end__ = .; + } > LOADER_BOOT_ADDR + __bss_size__ = __bss_end__ - __bss_begin__; + + .heap (NOLOAD) : + { + . = ALIGN(4); + __heap_begin__ = ORIGIN(HEAP); + KEEP(*(.heap)) + __heap_end__ = __heap_begin__ + LENGTH(HEAP); + } > HEAP +} diff --git a/sdk_liteos/build/link/loaderboot_rsa.lds b/sdk_liteos/build/link/loaderboot_rsa.lds new file mode 100755 index 0000000000000000000000000000000000000000..4ecf0b7b5e22369fb147abd5132b6e744c36c124 --- /dev/null +++ b/sdk_liteos/build/link/loaderboot_rsa.lds @@ -0,0 +1,154 @@ +OUTPUT_ARCH( "riscv" ) +ENTRY(_start) + +MEMORY +{ + /* ram for stack */ + STACK(xrw) : ORIGIN = 0x100000,LENGTH = 8K + /* ram for common bss and data */ + SRAM(xrw) : ORIGIN = 0x100000+8K,LENGTH = 8K + /* ram for fix rom bss and data */ + ROM_BSS_DATA(rx): ORIGIN = 0x100000+16K,LENGTH = 2K + /* ram for code rom bss and data */ + CODE_ROM_BSS_DATA(rx): ORIGIN = 0x100000+18K,LENGTH = 2K + /* ram for heap */ + HEAP(xrw): ORIGIN = 0x100000+20K,LENGTH = 20K + /* ram for loaderboot */ + LOADER_BOOT_ADDR(rx): ORIGIN = 0x100000+40K+0x5A0,LENGTH = 80K + /* rom for fixed rom */ + FIXED_ROM_ADDR(rx): ORIGIN = 0x00000000+11K,LENGTH = 21K + /* rom for code rom */ + CODE_ROM_ADDR(rx): ORIGIN = 0x003b8000+278K,LENGTH = 10K +} + +STACK_SIZE = 6k; +NMI_STACK_SIZE = 2K; + +SECTIONS +{ + /* The startup code goes first into FLASH */ + .text.entry : ALIGN(4) + { + KEEP(*(.text.entry)) + } > LOADER_BOOT_ADDR + + .rom.text : + { + . = ALIGN(4); + KEEP(SORT(libbase.o)(.text*)) + KEEP(SORT(libbase.o)(.rodata*)) + . = ALIGN(4); + } > FIXED_ROM_ADDR + + .rom.code.text : + { + . = ALIGN(4); + KEEP(SORT(libcodebase.o)(.text*)) + KEEP(SORT(libcodebase.o)(.rodata*)) + . = ALIGN(4); + } > CODE_ROM_ADDR + + /* Stack in SRAM at Highest addresses */ + .stacks (NOLOAD) : + { + . = ALIGN(4); + __SYSTEM_STACK_BEGIN__ = ORIGIN(STACK); + KEEP(*(.stacks)) + __SYSTEM_STACK_END__ = ORIGIN(STACK) + STACK_SIZE; + . = ALIGN(0x20); + __nmi_stack_bottom = .; + . += NMI_STACK_SIZE; + __nmi_stack_top = .; + } > STACK + __SYSTEM_STACK_SIZE__ = __SYSTEM_STACK_END__ - __SYSTEM_STACK_BEGIN__; + __stack_top = __SYSTEM_STACK_END__; + + .rom.data : + { + . = ALIGN(4); + __rom_copy_start = LOADADDR(.rom.data); + . = ALIGN(4); + __rom_copy_ram_start = .; + __global_pointer$ = .; + KEEP(SORT(libbase.o) (.data*)) + . = ALIGN(4); + __rom_copy_ram_end = .; + } > ROM_BSS_DATA AT>FIXED_ROM_ADDR + __rom_copy_size = __rom_copy_ram_end - __rom_copy_ram_start; + + .rom.code.data : + { + . = ALIGN(4); + __code_rom_copy_start = LOADADDR(.rom.code.data); + . = ALIGN(4); + __code_rom_copy_ram_start = .; + KEEP(SORT(libcodebase.o) (.data*)) + . = ALIGN(4); + __code_rom_copy_ram_end = .; + }>CODE_ROM_BSS_DATA AT>CODE_ROM_ADDR + __code_rom_copy_size = __code_rom_copy_ram_end - __code_rom_copy_ram_start; + + .rom.bss : + { + . = ALIGN(4); + __rom_bss_start = .; + KEEP(libbase.o (.bss)) + KEEP(libbase.o (.bss*)) + KEEP(libbase.o (COMMON)) + . = ALIGN(4); + __rom_bss_end = .; + } > ROM_BSS_DATA AT>FIXED_ROM_ADDR + + .rom.code.bss : + { + . = ALIGN(4); + __code_rom_bss_start = .; + KEEP(libcodebase.o (.bss)) + KEEP(libcodebase.o (.bss*)) + KEEP(libcodebase.o (COMMON)) + . = ALIGN(4); + __code_rom_bss_end = .; + }>CODE_ROM_BSS_DATA AT>CODE_ROM_ADDR + + .text : ALIGN(4) + { + __start_addr = .; + *(.text*) + *(.ram.text*) + . = ALIGN(4); + __rodata_start = .; + *(.rodata*) + . = ALIGN(4); + __rodata_end = .; + __text_end = .; + } > LOADER_BOOT_ADDR + + /* data section */ + .data : ALIGN(4) + { + __data_load = LOADADDR(.data); + __data_start = .; + *(.data*) + . = ALIGN(4); + __data_end = .; + } > LOADER_BOOT_ADDR + + /* bss section */ + .bss (NOLOAD) : ALIGN(4) + { + __bss_begin__ = .; + *(.bss*) + *(COMMON) + . = ALIGN(4); + __bss_end__ = .; + } > LOADER_BOOT_ADDR + __bss_size__ = __bss_end__ - __bss_begin__; + + .heap (NOLOAD) : + { + . = ALIGN(4); + __heap_begin__ = ORIGIN(HEAP); + KEEP(*(.heap)) + __heap_end__ = __heap_begin__ + LENGTH(HEAP); + } > HEAP +} diff --git a/sdk_liteos/build/link/loaderboot_sha256.lds b/sdk_liteos/build/link/loaderboot_sha256.lds new file mode 100755 index 0000000000000000000000000000000000000000..d660907ba9425a9020d8bac5cec06d7b9f4f112e --- /dev/null +++ b/sdk_liteos/build/link/loaderboot_sha256.lds @@ -0,0 +1,154 @@ +OUTPUT_ARCH( "riscv" ) +ENTRY(_start) + +MEMORY +{ + /* ram for stack */ + STACK(xrw) : ORIGIN = 0x100000,LENGTH = 8K + /* ram for common bss and data */ + SRAM(xrw) : ORIGIN = 0x100000+8K,LENGTH = 8K + /* ram for fix rom bss and data */ + ROM_BSS_DATA(rx): ORIGIN = 0x100000+16K,LENGTH = 2K + /* ram for code rom bss and data */ + CODE_ROM_BSS_DATA(rx): ORIGIN = 0x100000+18K,LENGTH = 2K + /* ram for heap */ + HEAP(xrw): ORIGIN = 0x100000+20K,LENGTH = 20K + /* ram for loaderboot */ + LOADER_BOOT_ADDR(rx): ORIGIN = 0x100000+40K+0x040,LENGTH = 80K + /* rom for fixed rom */ + FIXED_ROM_ADDR(rx): ORIGIN = 0x00000000+11K,LENGTH = 21K + /* rom for code rom */ + CODE_ROM_ADDR(rx): ORIGIN = 0x003b8000+278K,LENGTH = 10K +} + +STACK_SIZE = 6k; +NMI_STACK_SIZE = 2K; + +SECTIONS +{ + /* The startup code goes first into FLASH */ + .text.entry : ALIGN(4) + { + KEEP(*(.text.entry)) + } > LOADER_BOOT_ADDR + + .rom.text : + { + . = ALIGN(4); + KEEP(SORT(libbase.o)(.text*)) + KEEP(SORT(libbase.o)(.rodata*)) + . = ALIGN(4); + } > FIXED_ROM_ADDR + + .rom.code.text : + { + . = ALIGN(4); + KEEP(SORT(libcodebase.o)(.text*)) + KEEP(SORT(libcodebase.o)(.rodata*)) + . = ALIGN(4); + } > CODE_ROM_ADDR + + /* Stack in SRAM at Highest addresses */ + .stacks (NOLOAD) : + { + . = ALIGN(4); + __SYSTEM_STACK_BEGIN__ = ORIGIN(STACK); + KEEP(*(.stacks)) + __SYSTEM_STACK_END__ = ORIGIN(STACK) + STACK_SIZE; + . = ALIGN(0x20); + __nmi_stack_bottom = .; + . += NMI_STACK_SIZE; + __nmi_stack_top = .; + } > STACK + __SYSTEM_STACK_SIZE__ = __SYSTEM_STACK_END__ - __SYSTEM_STACK_BEGIN__; + __stack_top = __SYSTEM_STACK_END__; + + .rom.data : + { + . = ALIGN(4); + __rom_copy_start = LOADADDR(.rom.data); + . = ALIGN(4); + __rom_copy_ram_start = .; + __global_pointer$ = .; + KEEP(SORT(libbase.o) (.data*)) + . = ALIGN(4); + __rom_copy_ram_end = .; + } > ROM_BSS_DATA AT>FIXED_ROM_ADDR + __rom_copy_size = __rom_copy_ram_end - __rom_copy_ram_start; + + .rom.code.data : + { + . = ALIGN(4); + __code_rom_copy_start = LOADADDR(.rom.code.data); + . = ALIGN(4); + __code_rom_copy_ram_start = .; + KEEP(SORT(libcodebase.o) (.data*)) + . = ALIGN(4); + __code_rom_copy_ram_end = .; + }>CODE_ROM_BSS_DATA AT>CODE_ROM_ADDR + __code_rom_copy_size = __code_rom_copy_ram_end - __code_rom_copy_ram_start; + + .rom.bss : + { + . = ALIGN(4); + __rom_bss_start = .; + KEEP(libbase.o (.bss)) + KEEP(libbase.o (.bss*)) + KEEP(libbase.o (COMMON)) + . = ALIGN(4); + __rom_bss_end = .; + } > ROM_BSS_DATA AT>FIXED_ROM_ADDR + + .rom.code.bss : + { + . = ALIGN(4); + __code_rom_bss_start = .; + KEEP(libcodebase.o (.bss)) + KEEP(libcodebase.o (.bss*)) + KEEP(libcodebase.o (COMMON)) + . = ALIGN(4); + __code_rom_bss_end = .; + }>CODE_ROM_BSS_DATA AT>CODE_ROM_ADDR + + .text : ALIGN(4) + { + __start_addr = .; + *(.text*) + *(.ram.text*) + . = ALIGN(4); + __rodata_start = .; + *(.rodata*) + . = ALIGN(4); + __rodata_end = .; + __text_end = .; + } > LOADER_BOOT_ADDR + + /* data section */ + .data : ALIGN(4) + { + __data_load = LOADADDR(.data); + __data_start = .; + *(.data*) + . = ALIGN(4); + __data_end = .; + } > LOADER_BOOT_ADDR + + /* bss section */ + .bss (NOLOAD) : ALIGN(4) + { + __bss_begin__ = .; + *(.bss*) + *(COMMON) + . = ALIGN(4); + __bss_end__ = .; + } > LOADER_BOOT_ADDR + __bss_size__ = __bss_end__ - __bss_begin__; + + .heap (NOLOAD) : + { + . = ALIGN(4); + __heap_begin__ = ORIGIN(HEAP); + KEEP(*(.heap)) + __heap_end__ = __heap_begin__ + LENGTH(HEAP); + } > HEAP +} diff --git a/sdk_liteos/build/link/system_config.ld.S b/sdk_liteos/build/link/system_config.ld.S new file mode 100755 index 0000000000000000000000000000000000000000..fc79e66a60f82dfc390883daeba10ad892fc663b --- /dev/null +++ b/sdk_liteos/build/link/system_config.ld.S @@ -0,0 +1,18 @@ +#include "system_config.h" + +#define LOS_CB_START(module) __##module##_start +#define LOS_CB_END(module) __##module##_end +#define LOS_BLOCK_START(module) __block_##module##_start +#define LOS_BLOCK_END(module) __block_##module##_end +#define LOS_GET_SPACE_FOR_SYSTEM(module, X) \ + . = ALIGN(8);\ + LOS_BLOCK_START(module) = .;\ + LOS_CB_START(module) = .;\ + KEEP(*(.##module)); \ + LOS_CB_END(module) = .;\ + . += (LOS_CB_END(module) - LOS_CB_START(module))*((X) - 1);\ + LOS_BLOCK_END(module) = . + +LOS_GET_SPACE_FOR_SYSTEM(sysmemused,(LOSCFG_BASE_CORE_TSK_LIMIT_CONFIG + 1)); +LOS_GET_SPACE_FOR_SYSTEM(errno,(LOSCFG_BASE_CORE_TSK_LIMIT_CONFIG + 1)); + diff --git a/sdk_liteos/build/make_scripts/config.mk b/sdk_liteos/build/make_scripts/config.mk new file mode 100644 index 0000000000000000000000000000000000000000..4ae749b6e1d2917a5b3e1de744e4bae15e6cee19 --- /dev/null +++ b/sdk_liteos/build/make_scripts/config.mk @@ -0,0 +1,303 @@ +include $(MAIN_TOPDIR)/build/config/sdk.mk +include $(MAIN_TOPDIR)/build/make_scripts/usr.mk +SHELL = /bin/bash +COMPILE_MODULE += drv sys at +boot_dir := boot/flashboot +loaderboot_dir := boot/loaderboot +drv_dir := platform/drivers +sys_dir := platform/system +at_dir := components/at +hilink_dir := components/hilink +boot_libs := boot +loaderboot_libs := loaderboot +drv_libs := uart adc tsensor +sys_libs := cfg parttab upg +at_libs := at +hilink_libs := hilink +RM := rm -rf +MAKE := make +MV := mv +MAKE_DIR := mkdir -p +CC := $(TOOLS_PREFIX)gcc +AR := $(TOOLS_PREFIX)ar +AS := $(TOOLS_PREFIX)as +CXX := $(TOOLS_PREFIX)cpp +LINK := $(TOOLS_PREFIX)ld +RANLIB := $(TOOLS_PREFIX)ranlib +OBJCOPY := $(TOOLS_PREFIX)objcopy +OBJDUMP := $(TOOLS_PREFIX)objdump +NV_CFG_NAME := mss_nvi_db.xml +BASE_NUM := d11133fff0d435d699e27817e165cf1d10c1a951452bd07d40da5bcfc41ef773 +LOG_PATH := build/build_tmp/logs +OBJ_PATH := build/build_tmp/objs +LIB_PATH := build/build_tmp/libs +CACHE_PATH := build/build_tmp/cache +LINK_PATH := build/build_tmp/scripts +NV_PATH := build/build_tmp/nv + +LIBS += $(patsubst lib%.a, -l%, $(notdir $(wildcard $(MAIN_TOPDIR)/build/libs/*.a))) +LIBPATH += -Lbuild/scripts -Lbuild/libs -Lbuild/build_tmp/scripts +LIBS += -lwifi -lwifi_flash -lsystem -llitekernel_flash -lgcc +ifeq ($(USR_APP_ON), n) +COMPILE_MODULE += $(APP_NAME) +$(APP_NAME)_dir := app/$(APP_NAME) +$(APP_NAME)_libs := $(APP_NAME) +endif +LIBS += $(USR_LIBS) + +PYTHON_SCRIPTS = y +ifeq ($(PYTHON_SCRIPTS),y) +NV_TOOL := python3 $(MAIN_TOPDIR)/tools/nvtool/build_nv.py +OTA_TOOL := python3 $(MAIN_TOPDIR)/build/scripts/pkt_builder.py +else +NV_TOOL := cd $(MAIN_TOPDIR)/tools/nvtool;\ + $(MAIN_TOPDIR)/tools/nvtool/nv_builder +OTA_TOOL := cd $(MAIN_TOPDIR)/build/scripts;\ + $(MAIN_TOPDIR)/build/scripts/ota_builder +endif + + +ARFLAGS := cr +CCFLAGS := -mabi=ilp32 -march=rv32imc -falign-functions=2 -msave-restore -fno-optimize-strlen -freorder-blocks-algorithm=simple -fno-schedule-insns -fno-inline-small-functions -fno-inline-functions-called-once -mtune=size -fno-strict-aliasing -msmall-data-limit=0 -nostdinc -fno-aggressive-loop-optimizations -fno-builtin -std=c99 -Os -ffunction-sections -fdata-sections -fno-exceptions -fno-short-enums -fno-common -Wall -Wundef -DLOS_COMPILE_LDM -fstack-protector-strong -freg-struct-return -fvisibility=hidden -pipe +ASLAGS := +DEFINES := -DCYGPKG_POSIX_SIGNALS \ + -D__ECOS__ \ + -D__RTOS_ \ + -DPRODUCT_CFG_HAVE_FEATURE_SYS_ERR_INFO \ + -D__LITEOS__ \ + -DLIB_CONFIGURABLE \ + -DLOSCFG_SHELL \ + -DLOSCFG_CACHE_STATICS \ + -DCUSTOM_AT_COMMAND \ + -DLOS_COMPILE_LDM \ + -DLOS_CONFIG_IPERF3 \ + -DPRODUCT_USR_SOFT_VER_STR=\"None\" \ + -DSECUREC_ENABLE_SCANF_FILE=0 +INCLUDE := -I$(MAIN_TOPDIR)/include \ + -I$(MAIN_TOPDIR)/platform/include \ + -I$(MAIN_TOPDIR)/config \ + -I$(MAIN_TOPDIR)/config/nv \ + -I$(MAIN_TOPDIR)/../../../../utils/native/lite/include \ + -I$(MAIN_TOPDIR)/platform/os/Huawei_LiteOS/kernel/include \ + -I$(MAIN_TOPDIR)/platform/os/Huawei_LiteOS/kernel/base/include \ + -I$(MAIN_TOPDIR)/platform/os/Huawei_LiteOS/targets/hi3861v100/include \ + -I$(MAIN_TOPDIR)/platform/os/Huawei_LiteOS/targets/hi3861v100/plat/riscv +LINKFLAGS := -nostartfiles -nostdlib -static --gc-sections + +LINK_SCRIPTS_FLAG := -I$(MAIN_TOPDIR)/platform/os/Huawei_LiteOS/kernel/include -I$(MAIN_TOPDIR)/config +LINK_SCRIPTS_FLAG += +ifeq ($(CONFIG_I2C_SUPPORT), y) + drv_libs += i2c +endif +ifeq ($(CONFIG_SPI_SUPPORT), y) + drv_libs += spi +endif +ifeq ($(CONFIG_PWM_SUPPORT), y) + drv_libs += pwm +endif +ifeq ($(CONFIG_I2C_SUPPORT), y) + DEFINES += -DCONFIG_I2C_SUPPORT +endif +ifeq ($(CONFIG_DMA_SUPPORT), y) + DEFINES += -DCONFIG_DMA_SUPPORT +endif +ifeq ($(CONFIG_SPI_SUPPORT), y) + DEFINES += -DCONFIG_SPI_SUPPORT +endif +ifeq ($(CONFIG_PWM_SUPPORT), y) + DEFINES += -DCONFIG_PWM_SUPPORT +endif +ifeq ($(CONFIG_PWM_HOLD_AFTER_REBOOT), y) + DEFINES += -DCONFIG_PWM_HOLD_AFTER_REBOOT +endif +ifeq ($(CONFIG_I2S_SUPPORT), y) + DEFINES += -DCONFIG_I2S_SUPPORT +endif +ifeq ($(CONFIG_COMPRESSION_OTA_SUPPORT), y) + DEFINES += -DCONFIG_COMPRESSION_OTA_SUPPORT +endif +ifeq ($(CONFIG_DUAL_PARTITION_OTA_SUPPORT), y) + DEFINES += -DCONFIG_DUAL_PARTITION_OTA_SUPPORT +endif +ifeq ($(CONFIG_AT_SUPPORT), y) + DEFINES += -DCONFIG_AT_COMMAND +endif +ifeq ($(LOSCFG_DAQ), y) + DEFINES += -DFEATURE_DAQ +endif +ifeq ($(LOSCFG_BACKTRACE), y) + DEFINES += -DLOS_BACKTRACE +endif +ifeq ($(CONFIG_UART0_SUPPORT), y) + DEFINES += -DCONFIG_UART0_SUPPORT +endif +ifeq ($(CONFIG_UART1_SUPPORT), y) + DEFINES += -DCONFIG_UART1_SUPPORT +endif +ifeq ($(CONFIG_UART2_SUPPORT), y) + DEFINES += -DCONFIG_UART2_SUPPORT +endif +ifeq ($(CONFIG_TARGET_CHIP_HI3861), y) + DEFINES += -DCHIP_VER_Hi3861 -DPRODUCT_CFG_CHIP_VER_STR=\"Hi3861V100\" -DCONFIG_CHIP_PRODUCT_NAME=\"Hi3861\" +endif +ifeq ($(CONFIG_CHIP_PKT_48K), y) + DEFINES += -DCONFIG_CHIP_PKT_48K +endif +ifeq ($(CONFIG_CHIP_PKT_32K), y) + DEFINES += -DCONFIG_CHIP_PKT_32K +endif +ifeq ($(LOSCFG_COMPILER_HI3861_ASIC), y) + DEFINES += -DHI_BOARD_ASIC +else + DEFINES += -DHI_BOARD_FPGA +endif +ifeq ($(LOSCFG_COMPILER_HI3861_FLASH), y) + DEFINES += -DHI_ON_FLASH +else + DEFINES += -DHI_ON_RAM +endif +ifeq ($(CONFIG_MESH_SUPPORT), y) + DEFINES += -DCONFIG_MESH_SUPPORT -DLOS_CONFIG_MESH -DLOS_CONFIG_MESH_GTK -DCONFIG_MESH -DCONFIG_SAE -DCONFIG_ECC -DLOS_CONFIG_HOSTAPD_MGMT -DLOSCFG_APP_MESH -DLWIP_DEBUG_OPEN -DLWIP_SMALL_SIZE_MESH=1 +else + DEFINES += -DLWIP_SMALL_SIZE_MESH=0 +endif +ifeq ($(CONFIG_LWIP_SMALL_SIZE), y) + DEFINES += -DCONFIG_LWIP_SMALL_SIZE +endif +ifeq ($(CONFIG_LWIP_SMALL_SIZE_MESH), y) + DEFINES += -DCONFIG_LWIP_SMALL_SIZE_MESH +endif +ifeq ($(CONFIG_NETIF_HOSTNAME), y) + DEFINES += -DCONFIG_NETIF_HOSTNAME +endif +ifeq ($(CONFIG_DHCP_VENDOR_CLASS_IDENTIFIER), y) + DEFINES += -DCONFIG_DHCP_VENDOR_CLASS_IDENTIFIER +endif +ifeq ($(CONFIG_DHCPS_GW), y) + DEFINES += -DCONFIG_DHCPS_GW +endif +ifeq ($(CONFIG_UART_DMA_SUPPORT), y) + DEFINES += -DCONFIG_UART_DMA_SUPPORT +endif +ifeq ($(CONFIG_SDIO_SUPPORT), y) + DEFINES += -DCONFIG_SDIO_SUPPORT +endif +ifeq ($(CONFIG_SPI_DMA_SUPPORT), y) + DEFINES += -DCONFIG_SPI_DMA_SUPPORT +endif +ifeq ($(CONFIG_TEE_HUKS_SUPPORT), y) + DEFINES += -DCONFIG_TEE_HUKS_SUPPORT +endif +ifeq ($(CONFIG_TEE_HUKS_DEMO_SUPPORT), y) + DEFINES += -DCONFIG_TEE_HUKS_DEMO_SUPPORT +endif +ifeq ($(CONFIG_FLASH_ENCRYPT_SUPPORT), y) + DEFINES += -DCONFIG_FLASH_ENCRYPT_SUPPORT +endif +ifeq ($(LOSCFG_KASAN)_$(LOSCFG_KASAN_EXAMPLES_DEMO), y_y) + DEFINES += -DLOSCFG_DEBUG_KASAN +endif +ifeq ($(LOSCFG_KASAN)_$(LOSCFG_KASAN_LITEOS_NET_COAP), y_y) + DEFINES += -DLOSCFG_DEBUG_KASAN +endif +ifeq ($(LOSCFG_BACKTRACE), y) + ASLAGS += -fno-omit-frame-pointer +endif +ifeq ($(HB_LITEOS_COMPILE_TESTCASE), y) + LINK_SCRIPTS_FLAG += -DHI1131TEST +endif +ifeq ($(LOSCFG_KASAN), y) + LINK_SCRIPTS_FLAG += -DLOSCFG_DEBUG_KASAN +endif +ifeq ($(CONFIG_FLASH_ENCRYPT_SUPPORT), y) + LINK_SCRIPTS_FLAG += -DCONFIG_FLASH_ENCRYPT_SUPPORT +endif +ifeq ($(CONFIG_TEE_HUKS_SUPPORT), y) + LINK_SCRIPTS_FLAG += -DCONFIG_TEE_HUKS_SUPPORT +endif +ifeq ($(CONFIG_TARGET_SIG_RSA_V15), y) + LINK_SCRIPTS_FLAG += -DCONFIG_TARGET_SIG_RSA_V15 +endif +ifeq ($(CONFIG_TARGET_SIG_RSA_PSS), y) + LINK_SCRIPTS_FLAG += -DCONFIG_TARGET_SIG_RSA_PSS +endif +ifeq ($(CONFIG_TARGET_SIG_ECC), y) + LINK_SCRIPTS_FLAG += -DCONFIG_TARGET_SIG_ECC +endif +ifeq ($(CONFIG_CHIP_PKT_48K), y) + LINK_SCRIPTS_FLAG += -DCONFIG_CHIP_PKT_48K +endif +ifeq ($(CONFIG_CHIP_PKT_32K), y) + LINK_SCRIPTS_FLAG += -DCONFIG_CHIP_PKT_32K +endif +ifeq ($(LOSCFG_COMPILER_HI3861_ASIC), y) + LINK_SCRIPTS_FLAG += -DHI_BOARD_ASIC +else + LINK_SCRIPTS_FLAG += -DHI_BOARD_FPGA +endif +ifeq ($(LOSCFG_COMPILER_HI3861_FLASH), y) + LINK_SCRIPTS_FLAG += -DHI_ON_FLASH +else + LINK_SCRIPTS_FLAG += -DHI_ON_RAM +endif +ifeq ($(LOSCFG_KERNEL_RUNSTOP), y) + INCLUDE += -I$(MAIN_TOPDIR)/platform/os/Huawei_LiteOS/kernel/extended/runstop +endif +ifeq ($(LOSCFG_COMPAT_POSIX), y) + INCLUDE += -I$(MAIN_TOPDIR)/platform/os/Huawei_LiteOS/components/posix/include +endif +ifeq ($(LOSCFG_COMPAT_LINUX), y) + INCLUDE += -I$(MAIN_TOPDIR)/platform/os/Huawei_LiteOS/components/linux/include +endif +ifeq ($(LOSCFG_SHELL), y) + INCLUDE += -I$(MAIN_TOPDIR)/platform/os/Huawei_LiteOS/shell/include +endif +ifeq ($(LOSCFG_NET_TELNET), y) + INCLUDE += -I$(MAIN_TOPDIR)/platform/os/Huawei_LiteOS/net/telnet/include +endif +ifeq ($(LOSCFG_LIB_LIBC), y) + INCLUDE += -I$(MAIN_TOPDIR)/platform/os/Huawei_LiteOS/components/lib/libc/hw/include\ + -I$(MAIN_TOPDIR)/platform/os/Huawei_LiteOS/components/lib/libc/musl/include\ + -I$(MAIN_TOPDIR)/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic\ + -I$(MAIN_TOPDIR)/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/riscv32\ + -I$(MAIN_TOPDIR)/platform/os/Huawei_LiteOS/components/lib/libc/nuttx/include\ + -I$(MAIN_TOPDIR)/platform/os/Huawei_LiteOS/components/lib/libsec/include\ + -I$(MAIN_TOPDIR)/platform/os/Huawei_LiteOS/targets/hi3861v100/config\ + -I$(MAIN_TOPDIR)/platform/os/Huawei_LiteOS/targets/hi3861v100/user\ + -I$(MAIN_TOPDIR)/platform/os/Huawei_LiteOS/targets/hi3861v100/plat\ + -I$(MAIN_TOPDIR)/platform/os/Huawei_LiteOS/targets/hi3861v100/extend/include\ + -I$(MAIN_TOPDIR)/platform/os/Huawei_LiteOS/arch +endif +ifeq ($(LOSCFG_NET_LWIP_SACK), y) + INCLUDE += -I$(MAIN_TOPDIR)/third_party/lwip_sack/include +endif +ifeq ($(LOSCFG_BACKTRACE), y) + CCFLAGS += -fno-omit-frame-pointer +endif +ifeq ($(LOSCFG_KASAN)_$(LOSCFG_KASAN_EXAMPLES_DEMO), y_y) + CCFLAGS += -fsanitize=kernel-address -fasan-shadow-offset=1835008 --param asan-stack=1 -fsanitize=bounds-strict +endif +ifeq ($(LOSCFG_KASAN)_$(LOSCFG_KASAN_LITEOS_NET_COAP), y_y) + CCFLAGS += -fsanitize=kernel-address -fasan-shadow-offset=1835008 --param asan-stack=1 -fsanitize=bounds-strict +endif +ifeq ($(CONFIG_HILINK), y) + COMPILE_MODULE += hilink +endif +ifeq ($(CONFIG_HILINK), y) + DEFINES += -DCONFIG_HILINK +endif + +ifeq ($(FACTORY_MODE), y) +DEFINES += -DCONFIG_FACTORY_TEST_MODE +endif +LIBS += $(addprefix -l, $(foreach module, $(COMPILE_MODULE), $($(module)_libs))) +ifeq ($(CONFIG_CE_SUPPORT), y) + NV_CFG_NAME = mss_nvi_db.xml +endif +ifeq ($(CONFIG_FCC_SUPPORT), y) + NV_CFG_NAME = mss_nvi_db_fcc.xml +endif +ifeq ($(CONFIG_MAX_POWER_SUPPORT), y) + NV_CFG_NAME = mss_nvi_db_max.xml +endif +CCFLAGS += $(DEFINES) $(INCLUDE) diff --git a/sdk_liteos/build/make_scripts/config_lib_factory.mk b/sdk_liteos/build/make_scripts/config_lib_factory.mk new file mode 100755 index 0000000000000000000000000000000000000000..d5c697b661f396778c84d4bfb9b84c2a98bca6c1 --- /dev/null +++ b/sdk_liteos/build/make_scripts/config_lib_factory.mk @@ -0,0 +1,23 @@ +ifeq ($(CONFIG_TARGET_CHIP_HI3861), y) + ifeq ($(CONFIG_DIAG_SUPPORT), y) + LIBPATH += -Lbuild/libs/hi3861/debug/factory + endif +else + ifeq ($(CONFIG_DIAG_SUPPORT), y) + LIBPATH += -Lbuild/libs/hi3861l/debug/factory + endif +endif + +ifeq ($(CONFIG_TARGET_CHIP_HI3861), y) + ifneq ($(CONFIG_DIAG_SUPPORT), y) + LIBPATH += -Lbuild/libs/hi3861/release/factory + endif +else + ifneq ($(CONFIG_DIAG_SUPPORT), y) + LIBPATH += -Lbuild/libs/hi3861l/release/factory + endif +endif + +ifeq ($(CONFIG_HILINK), y) + LIBPATH += -Lcomponents/hilink/lib +endif diff --git a/sdk_liteos/build/make_scripts/config_lib_non_factory.mk b/sdk_liteos/build/make_scripts/config_lib_non_factory.mk new file mode 100644 index 0000000000000000000000000000000000000000..4129739882c3e3bf4eb0c4b1598e1af627858368 --- /dev/null +++ b/sdk_liteos/build/make_scripts/config_lib_non_factory.mk @@ -0,0 +1,47 @@ +ifeq ($(CONFIG_TARGET_CHIP_HI3861), y) + ifeq ($(CONFIG_DIAG_SUPPORT), y) + ifeq ($(CONFIG_QUICK_SEND_MODE), y) + LIBPATH += -Lbuild/libs/hi3861/debug/no_mesh_quick_start + else ifeq ($(CONFIG_MESH_SUPPORT), y) + LIBPATH += -Lbuild/libs/hi3861/debug/mesh + else + LIBPATH += -Lbuild/libs/hi3861/debug/no_mesh + endif + endif +else + ifeq ($(CONFIG_DIAG_SUPPORT), y) + ifeq ($(CONFIG_CHIP_PKT_48K), y) + LIBPATH += -Lbuild/libs/hi3861l/debug/no_mesh_pkt_48k + else ifeq ($(CONFIG_MESH_SUPPORT), y) + LIBPATH += -Lbuild/libs/hi3861l/debug/mesh + else + LIBPATH += -Lbuild/libs/hi3861l/debug/no_mesh + endif + endif +endif + +ifeq ($(CONFIG_TARGET_CHIP_HI3861), y) + ifneq ($(CONFIG_DIAG_SUPPORT), y) + ifeq ($(CONFIG_QUICK_SEND_MODE), y) + LIBPATH += -Lbuild/libs/hi3861/release/no_mesh_quick_start + else ifeq ($(CONFIG_MESH_SUPPORT), y) + LIBPATH += -Lbuild/libs/hi3861/release/mesh + else + LIBPATH += -Lbuild/libs/hi3861/release/no_mesh + endif + endif +else + ifneq ($(CONFIG_DIAG_SUPPORT), y) + ifeq ($(CONFIG_CHIP_PKT_48K), y) + LIBPATH += -Lbuild/libs/hi3861l/release/no_mesh_pkt_48k + else ifeq ($(CONFIG_MESH_SUPPORT), y) + LIBPATH += -Lbuild/libs/hi3861l/release/mesh + else + LIBPATH += -Lbuild/libs/hi3861l/release/no_mesh + endif + endif +endif + +ifeq ($(CONFIG_HILINK), y) + LIBPATH += -Lcomponents/hilink/lib +endif diff --git a/sdk_liteos/build/make_scripts/lib.mk b/sdk_liteos/build/make_scripts/lib.mk new file mode 100755 index 0000000000000000000000000000000000000000..206dc6830ccb376001362ddb35ac3102e296338a --- /dev/null +++ b/sdk_liteos/build/make_scripts/lib.mk @@ -0,0 +1,48 @@ +#all: $(LIBOUT) +$(OBJS): $(OBJDIR)/%.o : %.c + $(Q)if [ ! -d $(dir $@) ]; then \ + mkdir -p $(dir $@); \ + fi; + $(Q) echo Compile $<; +ifeq ($(ID_CFG_FILE), $(wildcard $(ID_CFG_FILE))) + $(Q)if [ -e $(ID_CFG_FILE) ]; \ + then ID=$(shell grep -e $(notdir $<) -w -m1 $(ID_CFG_FILE) | grep -e "\s[0-9]*" -o |tr -cd "[0-9]"); \ + if [ -z $$ID ]; \ + then $(CC) $(CCFLAGS) -c $< -o $@; \ + else $(CC) $(CCFLAGS) -D__NEW_FILE_ID__=$$ID -c $< -o $@; \ + fi; \ + if [ "$$?" != "0" ]; then \ + exit 1;\ + fi; \ + fi; +else + $(Q)if [ -e $< ]; \ + then $(CC) $(CCFLAGS) -c $< -o $@; \ + if [ "$$?" != "0" ]; then \ + exit 1;\ + fi; \ + fi; +endif + +$(ASM_OBJS): $(OBJDIR)/%.o : %.S + $(Q)echo Compile $<; + $(Q)if [ ! -d $(dir $@) ]; \ + then \ + mkdir -p $(dir $@);\ + fi; + $(Q)if [ -f $< ]; \ + then \ + $(CC) $(ASFLAGS) -c $< -o $@ ; \ + if [ "$$?" != "0" ]; then \ + exit 1;\ + fi;\ + fi; + +$(LIBOUT): $(OBJS) $(ASM_OBJS) + $(Q)if [ ! -d $(dir $@) ]; \ + then \ + mkdir -p $(dir $@);\ + fi; + $(Q)$(AR) $(ARFLAGS) $@ $(sort $^) + $(Q)echo make [$(LIB_NAME)] SUCCESS + diff --git a/sdk_liteos/build/make_scripts/module.mk b/sdk_liteos/build/make_scripts/module.mk new file mode 100755 index 0000000000000000000000000000000000000000..e8dffa9b51c1d121072661effec703d019677df4 --- /dev/null +++ b/sdk_liteos/build/make_scripts/module.mk @@ -0,0 +1,36 @@ +include $(MAIN_TOPDIR)/build/make_scripts/config.mk +include $(MAIN_TOPDIR)/$(MODULE_DIR)/module_config.mk +-include $(MAIN_TOPDIR)/$(MODULE_DIR)/srcs.mk + +OBJDIR = $(MAIN_TOPDIR)/$(OBJ_PATH)/$(MODULE_DIR) + +ID_CFG_FILE = $(MAIN_TOPDIR)/$(MODULE_DIR)/file_id.cfg + +LIB_NAME = lib$(LIB).a +SRCS = $($(LIB)_srcs) +LIBOUT = $(MAIN_TOPDIR)/$(LIB_PATH)/$(MODULE_DIR)/$(LIB_NAME) + +ifdef SRC_FILES +OBJ_SRCS := $(filter %.c, $(SRC_FILES)) +ASM_SRCS := $(filter %.S, $(SRC_FILES)) +else +OBJ_SRCS := $(foreach dir, $(SRCS), $(wildcard $(dir)/*.c)) +ASM_SRCS := $(foreach dir, $(SRCS), $(wildcard $(dir)/*.S )) +endif + +OBJ_SRCS := $(filter-out %/ethernetif.c, $(OBJ_SRCS)) +OBJS = $(patsubst %.c, $(OBJDIR)/%.o, $(OBJ_SRCS)) +ASM_OBJS = $(patsubst %.S, $(OBJDIR)/%.o, $(ASM_SRCS)) + +all: $(LIBOUT) +include $(MAIN_TOPDIR)/build/make_scripts/lib.mk + +clean: + $(Q)$(foreach x, $(OBJS) $(ASM_OBJS) $(LIBOUT), \ + if [ -d $(dir $x) ]; \ + then $(RM) $(dir $x); \ + echo clean dir $(dir $x) success; \ + fi;) + +.PHONY: all clean + diff --git a/sdk_liteos/build/make_scripts/prepare.py b/sdk_liteos/build/make_scripts/prepare.py new file mode 100644 index 0000000000000000000000000000000000000000..c9a6ab9739b30c674a7163665b0ffaf1acf41b15 --- /dev/null +++ b/sdk_liteos/build/make_scripts/prepare.py @@ -0,0 +1,244 @@ +#!/usr/bin/env python3 +# coding=utf-8 + +''' +* Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +* Description: .config parser, bases on kconfig format. +''' + +import os +import sys +import shutil +proj_top_dir = os.path.realpath(os.path.join(__file__, '..', '..', '..')) +print('proj_top_dir:',proj_top_dir) +sys.path.append(os.path.join(proj_top_dir, 'build')) +from scripts.scons_env_cfg import SconsEnvCfg as EnvCfg +from scripts.scons_utils import flag +from scripts.scons_utils import flag_r +from scripts.common_env import get_fixed_config +from scripts.common_env import get_make_str +from scripts import scons_app + +def mkdir(path): + isExists=os.path.exists(path) + if not isExists: + os.makedirs(path) + print ('%s create success'% path) + return True + else: + return False + +def create_output_dirs(env_cfg): + dir_list = [env_cfg.bin_path, env_cfg.log_path, env_cfg.cache_path, env_cfg.link_path] + #env_cfg.obj_path, env_cfg.lib_path, + [mkdir(x) for x in dir_list] + +def transform_env_to_make(env_cfg, module = 'common'): + fixed_env_cfg = get_fixed_config('env_cfg') + line = '' + for flg in flag: + flg_cfg = None + if flg != 'CPPPATH': + flg_cfg = fixed_env_cfg[flag[flg]][module] if module in fixed_env_cfg[flag[flg]] else None + else: + cfg_list = [] + common_inc = fixed_env_cfg['common_inc_path'] + inc_path = common_inc[module] if module in common_inc else None + if inc_path is not None: + for x in inc_path: + if x.startswith('#'): + cfg_list.append(x[2:]) + else: + cfg_list.append(x) + os_inc = fixed_env_cfg['liteos_inc_path'] + inc_path = os_inc[module] if module in os_inc else None + if inc_path is not None: + cfg_list.extend([os.path.join(os.path.relpath(env_cfg.os_root, env_cfg.root), y) for y in inc_path]) + flg_cfg = cfg_list + + if flg_cfg is None: + continue + if flg == 'CPPDEFINES': + defines = ['-D%s'%x for x in flg_cfg if isinstance(x, str)] + defines.extend(['-D%s=%s'%x for x in flg_cfg if isinstance(x, tuple)]) + line = '%sDEFINES := %s\n'%(line, ' \\\n\t'.join(defines)) + elif flg == 'CPPPATH': + line = '%sINCLUDE := -I$(MAIN_TOPDIR)/%s\n'%(line, ' \\\n\t-I$(MAIN_TOPDIR)/'.join(flg_cfg)) + elif flg == 'LINK_SCRIPTS_FLAG': + line = '\n'.join([ + line, + '%s := -I$(MAIN_TOPDIR)/%s'%(flg, ' -I$(MAIN_TOPDIR)/'.join([x[2:] for x in flg_cfg if x.startswith('-I')])), + '%s += %s'%(flg, ' '.join([x for x in flg_cfg if not x.startswith('-I')])) + ]) + else: + line = '%s%s := %s\n'%(line, flg, ' '.join(flg_cfg)) + return line + +def prepare_config_file(env_cfg): + config_file = os.path.join(proj_top_dir, 'build', 'make_scripts', 'config.mk') + with open(config_file, 'w+') as fp: + environs = env_cfg.get_makefile_environs() + var = environs['var'] + append_var = environs['append_var'] + mod_dir = environs['mod_dir'] + modules = get_fixed_config('module') + lib_cfg = get_fixed_config('lib_cfg') + #env_cfg = get_fixed_config('env_cfg') + line = '\n'.join(['include $(MAIN_TOPDIR)/build/config/sdk.mk', + 'include $(MAIN_TOPDIR)/build/make_scripts/usr.mk', + 'SHELL = /bin/bash', + 'COMPILE_MODULE += %s\n'%(' '.join(modules))]) + for item in mod_dir: + line = '%s%s := %s\n'%(line, item, mod_dir[item]) + + for module_name in lib_cfg: + libs = list(lib_cfg[module_name].keys()) + line = '%s%s_libs := %s\n'%(line, module_name, ' '.join(libs)) + + for item in var: + line = '%s%s := %s\n'%(line, item, var[item]) + + #for item in append_var: + #line = '%s%s += %s\n'%(line, item, append_var[item]) + + line = '\n'.join([line, + 'LIBS += $(patsubst lib%.a, -l%, $(notdir $(wildcard $(MAIN_TOPDIR)/build/libs/*.a)))', + '\n'.join(['%s += %s'%(item, append_var[item]) for item in append_var]), + 'ifeq ($(USR_APP_ON), n)', + 'COMPILE_MODULE += $(APP_NAME)', + '$(APP_NAME)_dir := app/$(APP_NAME)', + '$(APP_NAME)_libs := $(APP_NAME)', + 'endif', + 'LIBS += $(USR_LIBS)\n']) + #line = '\n'.join([line, + #'LIBS += $(patsubst lib%.a, -l%, $(notdir $(wildcard $(MAIN_TOPDIR)/build/libs/*.a)))']) + line = '\n'.join([line, + 'PYTHON_SCRIPTS = y', + 'ifeq ($(PYTHON_SCRIPTS),y)', + 'NV_TOOL := python3 $(MAIN_TOPDIR)/tools/nvtool/build_nv.py', + 'OTA_TOOL := python3 $(MAIN_TOPDIR)/build/scripts/pkt_builder.py', + 'else', + 'NV_TOOL := cd $(MAIN_TOPDIR)/tools/nvtool;\\', + ' $(MAIN_TOPDIR)/tools/nvtool/nv_builder', + 'OTA_TOOL := cd $(MAIN_TOPDIR)/build/scripts;\\', + ' $(MAIN_TOPDIR)/build/scripts/ota_builder', + 'endif\n\n']) + + line = '\n'.join([line, + transform_env_to_make(env_cfg = env_cfg), + get_make_str(), + 'ifeq ($(FACTORY_MODE), y)', + 'DEFINES += -DCONFIG_FACTORY_TEST_MODE', + 'endif', + 'LIBS += $(addprefix -l, $(foreach module, $(COMPILE_MODULE), $($(module)_libs)))', + 'ifeq ($(CONFIG_CE_SUPPORT), y)', + '\tNV_CFG_NAME = mss_nvi_db.xml', + 'endif', + 'ifeq ($(CONFIG_FCC_SUPPORT), y)', + '\tNV_CFG_NAME = mss_nvi_db_fcc.xml', + 'endif', + 'ifeq ($(CONFIG_MAX_POWER_SUPPORT), y)', + '\tNV_CFG_NAME = mss_nvi_db_max.xml', + 'endif', + 'CCFLAGS += $(DEFINES) $(INCLUDE)\n']) + print('+'*20,'config.mk','+'*20,'\n',line) + fp.write(line) +# +def prepare_module_makefile(env_cfg): + modules = env_cfg.get_all_modules() + for x in modules: + dst_dir = os.path.join(proj_top_dir, env_cfg.get_module_dir(x)) + dst_makefile = os.path.join(dst_dir, 'Makefile') + print("---------dst_dir: %s proj_top_dir :%s -"%(dst_dir, proj_top_dir)) + module_mk = os.path.join(dst_dir, 'module.mk') + if not os.path.exists(module_mk): + src_makefile = os.path.join(proj_top_dir, 'build', 'make_scripts', 'module.mk') + shutil.copyfile(src_makefile, dst_makefile) + else: + shutil.move(module_mk, dst_makefile) +# +def prepare_module_lib_cfg(env_cfg, module): + src_makefile = os.path.join(proj_top_dir, env_cfg.get_module_dir(module), 'module_config.mk') + print('module:',module) + if os.path.exists(src_makefile): + return + + with open(src_makefile, 'w+') as fp: + lib_cfg = get_fixed_config('lib_cfg')[module] + line = '' + for lib_name in lib_cfg: + line = '%s%s_srcs := %s\n'%(line, lib_name, ' '.join(lib_cfg[lib_name])) + + #transform_env_to_make(env_cfg, module) + fixed_env_cfg = get_fixed_config('env_cfg') + for flg in flag: + #flg_cfg = env_cfg.get_module_cfg(module, flg, fixed=True) + flg_cfg = None + if flg != 'CPPPATH': + flg_cfg = fixed_env_cfg[flag[flg]][module] if module in fixed_env_cfg[flag[flg]] else None + else: + cfg_list = [] + common_inc = fixed_env_cfg['common_inc_path'] + inc_path = common_inc[module] if module in common_inc else None + if inc_path is not None: + for x in inc_path: + if x.startswith('#'): + cfg_list.append(x[2:]) + else: + cfg_list.append(x) + os_inc = fixed_env_cfg['liteos_inc_path'] + inc_path = os_inc[module] if module in os_inc else None + if inc_path is not None: + cfg_list.extend([os.path.join(os.path.relpath(env_cfg.os_root, env_cfg.root), y) for y in inc_path]) + flg_cfg = cfg_list + + if flg_cfg is None: + continue + if flg == 'CPPDEFINES': + defines = ['-D%s'%x for x in flg_cfg if isinstance(x, str)] + defines.extend(['-D%s=%s'%x for x in flg_cfg if isinstance(x, tuple)]) + line = '%sCCFLAGS += %s\n'%(line, ' '.join(defines)) + elif flg == 'CPPPATH': + line = '%sCCFLAGS += -I$(MAIN_TOPDIR)/%s\n'%(line, ' \\\n\t-I$(MAIN_TOPDIR)/'.join(flg_cfg)) + else: + line = '%s%s += %s\n'%(line, flg, ' '.join(flg_cfg)) + + module_cfg = get_make_str(module) + line = '%s%s\n'%(line, module_cfg) if module_cfg is not None else line + print('+'*10, ' %s module config'%module, '+'*10, '\n', line) + fp.write(line) +# +def do_prepare(env_cfg): + create_output_dirs(env_cfg) + print("------------------------------------env_cfg1: %s"%(env_cfg)) + prepare_config_file(env_cfg) + print("------------------------------------env_cfg2: %s"%(env_cfg)) + prepare_module_makefile(env_cfg) + print("------------------------------------env_cfg3: %s"%(env_cfg)) + [prepare_module_lib_cfg(env_cfg, module) for module in env_cfg.get_all_modules()] + + + +if __name__ == "__main__": + args = len(sys.argv) + print('+'*40, 'PREPARE', '+'*40) + env_cfg = EnvCfg() + #app_builder = scons_app.AppTarget('demo') + #env_cfg.set_app_builder(app_builder) + do_prepare(env_cfg) + + #print('common str','+'*50) + #print(get_make_str()) + #print('+'*50) diff --git a/sdk_liteos/build/make_scripts/usr.mk b/sdk_liteos/build/make_scripts/usr.mk new file mode 100755 index 0000000000000000000000000000000000000000..fe1d96829acbf1c1db2ac40603d31ad74cef1c55 --- /dev/null +++ b/sdk_liteos/build/make_scripts/usr.mk @@ -0,0 +1,22 @@ +include $(MAIN_TOPDIR)/build/config/usr_config.mk + +COMPILE_MODULE := +USR_APP_ON ?= n +APP_NAME ?= demo +Q := @ +TOOLS_PREFIX := riscv32-unknown-elf- +GCC_VER_NUM := 7.3.0 +USR_OUTPUT_DIR ?= +USR_LIBS ?= +LIBPATH := +ifeq ($(USR_OUTPUT_DIR), ) +BIN_PATH := output/bin +else +BIN_PATH := $(USR_OUTPUT_DIR)/output/bin +endif +ifeq ($(CONFIG_TARGET_CHIP_HI3861), y) +TARGET_CHIP ?= Hi3861 +else +TARGET_CHIP ?= Hi3861L +endif +TARGET_NAME ?= $(TARGET_CHIP)_$(APP_NAME) diff --git a/sdk_liteos/build/scripts/__init__.py b/sdk_liteos/build/scripts/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6b1bf1a176dd5f00aca8cfecd5258f338c2b1710 --- /dev/null +++ b/sdk_liteos/build/scripts/__init__.py @@ -0,0 +1,27 @@ +#!/usr/bin/env python3 +# coding=utf-8 + +''' +* Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +* Description: package entry +''' + +import os +import sys + +sys.path.append(os.path.join(os.getcwd(), 'build', 'scripts')) + +__all__ = ['common_env', 'scons_env_cfg', 'scons_utils', 'hi_config_parser', 'scons_app', 'pkt_builder', 'make_upg_file'] + diff --git a/sdk_liteos/build/scripts/common_env.py b/sdk_liteos/build/scripts/common_env.py new file mode 100644 index 0000000000000000000000000000000000000000..27d76356056116610fbb85ffeb293a75884c4de2 --- /dev/null +++ b/sdk_liteos/build/scripts/common_env.py @@ -0,0 +1,542 @@ +#!/usr/bin/env python3 +# coding=utf-8 + +""" +* Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +* Description: SCons Compile environment init. +""" + +import os +import sys + +from copy import deepcopy +from scons_utils import scons_usr_string_option +from scons_utils import scons_pre_check +from scons_utils import select_added_cfg +from scons_utils import scons_get_cfg_val +from scons_utils import condition_str +from scons_utils import scons_usr_bool_option +from scons_utils import scons_get_cfg_val +from scons_utils import traverse_subdir + +#Module to be built by default. +compile_module = ['drv', 'sys', 'at'] + +#Get settings from menuconfig +product_soft_ver_str = scons_usr_string_option('CONFIG_TARGET_SOFT_VER') +log_output_flag = False + +#library path for linking +cur_file_path = os.path.split(os.path.realpath(__file__))[0] +netcfg_lib_dir = os.path.join(cur_file_path, '..', '..', '..', '..', '..', + 'huawei', 'hms', 'hilink', 'ohos', 'l0', 'hi3861', 'lib', 'wifi') +os_lib_path = [ + os.path.join('build', 'scripts'), + os.path.join('build', 'libs'), + netcfg_lib_dir, + os.path.join('ohos', 'libs'), +] + +#library path for boot linking +os_boot_path = [ + os.path.join('build', 'libs'), +] + +""" +module_dir dictionary. Format as +module name : relative directory where the module is located +""" +module_dir = { + 'boot': os.path.join('boot', 'flashboot'), + 'loaderboot': os.path.join('boot', 'loaderboot'), + 'drv': os.path.join('platform', 'drivers'), + 'sys': os.path.join('platform', 'system'), + 'at': os.path.join('components', 'at'), + 'hilink': os.path.join('components', 'hilink'), + #'OHOS': os.path.join('components', 'OHOS', 'kv'), +} + +""" +proj_lib_cfg dictionary, contains the sub-folders which includes the source code. +Format as + module name : {library name:["folder1", "folder2"]} +""" +proj_lib_cfg = { + #flashboot + 'boot':{ #module name + 'boot': [ #library name + 'startup', #source code folders + os.path.join('drivers', 'lsadc'), + os.path.join('drivers', 'flash'), + os.path.join('drivers', 'efuse'), + os.path.join('drivers', 'gpio'), + os.path.join('drivers', 'io'), + os.path.join('common', 'nvm'), + os.path.join('common', 'partition_table'), + os.path.join('..', '..', 'third_party', 'u-boot-v2019.07', 'u-boot-v2019.07', 'lib'), + os.path.join('..', 'commonboot', 'efuse'), + os.path.join('..', 'commonboot', 'flash'), + 'lzmaram', + 'upg', + 'secure' + ] + }, + #loaderboot + 'loaderboot':{ #module name + 'loaderboot': [ #library name + 'startup', #source code folders + 'common', + os.path.join('common', 'nvm'), + os.path.join('common', 'partition_table'), + os.path.join('drivers', 'lsadc'), + os.path.join('drivers', 'efuse'), + os.path.join('drivers', 'flash'), + os.path.join('..', '..', 'third_party', 'u-boot-v2019.07', 'u-boot-v2019.07', 'lib'), + os.path.join('..', 'commonboot', 'efuse'), + os.path.join('..', 'commonboot', 'flash'), + 'secure' + ] + }, + #drivers + 'drv':{ + 'uart' : [ + 'uart' + ], + 'adc' : [ + 'adc' + ], + 'tsensor' : [ + 'tsensor' + ], + }, + #system module + 'sys':{ + 'cfg' : [ + 'cfg' + ], + 'parttab' : [ + 'partition_table' + ], + 'upg' : [ + 'upg' + ], + }, + #third parties and components + 'at':{'at':['src']}, + 'hilink':{'hilink':['.']}, + #'OHOS':{'OHOS':['src']}, +} + +""" +Base Settings. +defines: + common: + Modify common would take effect in each module building process. + Insert global defines if needed. + others, like coap, at: + Insert module defines below, only affects the module compiling. + +liteos_inc_path: + Separate os header path to avoid the path too deep. + common: global setting. + +common_inc_path: + include path contains the head files, MUST start with '#'. + common: global setting. + +""" +proj_environment = { + 'ar_flags':{ + 'common':['cr'] + }, + + 'cc_flags':{ + 'common':[] + }, + + 'link_flags':{ + 'common':['-nostartfiles', '-nostdlib', '-static', '--gc-sections'] + }, + + 'link_scripts_flag':{ + 'common':[os.path.join('-Iplatform', 'os', 'Huawei_LiteOS', 'kernel', 'include'),'-Iconfig'] + }, + + 'as_flags':{ + 'common':[] + }, + + 'defines':{ + 'common':[ + ('PRODUCT_USR_SOFT_VER_STR', r'\"%s\"'%product_soft_ver_str), + 'CYGPKG_POSIX_SIGNALS', + '__ECOS__', + '__RTOS_', + 'PRODUCT_CFG_HAVE_FEATURE_SYS_ERR_INFO', + '__LITEOS__', + 'LIB_CONFIGURABLE', + 'LOSCFG_SHELL', + 'LOSCFG_CACHE_STATICS', # This option is used to control whether Cache hit ratio statistics are supported. + 'CUSTOM_AT_COMMAND', + 'LOS_COMPILE_LDM', + 'LOS_CONFIG_IPERF3', + ('SECUREC_ENABLE_SCANF_FILE', 0), + ], + 'at':['_PRE_WLAN_FEATURE_MFG_TEST'], + }, + + 'opts':{ + 'common':['-mabi=ilp32', '-march=rv32imc', '-falign-functions=2', '-msave-restore', + '-fno-optimize-strlen', '-freorder-blocks-algorithm=simple', '-fno-schedule-insns', + '-fno-inline-small-functions', + '-fno-inline-functions-called-once', '-mtune=size', '-fno-strict-aliasing', + '-msmall-data-limit=0', '-nostdinc', '-fno-aggressive-loop-optimizations', '-fno-builtin', '-std=c99', + '-Os', '-ffunction-sections', '-fdata-sections', '-fno-exceptions', '-fno-short-enums', + '-fno-common', '-Wall', '-Wundef', '-DLOS_COMPILE_LDM', + '-fstack-protector-strong', '-freg-struct-return', '-fvisibility=hidden', '-pipe' + ], + + 'drv':['-Werror', '-fsigned-char'], + + 'sys':['-Werror', '-fsigned-char'], + }, + + 'liteos_inc_path':{ + 'common':[ + os.path.join('kernel', 'include'), + os.path.join('kernel', 'base', 'include'), + os.path.join('targets', 'hi3861v100', 'include'), + os.path.join('targets', 'hi3861v100', 'plat', 'riscv'), + ], + 'drv':[], + + 'sys':[ + os.path.join('kernel', 'extended', 'include'), + ], + + 'os':[os.path.join('kernel', 'extended', 'include'),], + + 'mbedtls':[], + + 'at':[ + os.path.join('targets', 'hi3861v100', 'commons'), + ], + }, + + 'common_inc_path':{ + 'common':[ + os.path.join('#', 'include'), + os.path.join('#', 'platform', 'include'), + os.path.join('#', 'config'), + os.path.join('#', 'config', 'nv'), + os.path.join('#', '..', '..', '..', '..', 'utils','native','liteos','include'), + ], + 'drv':[os.path.join('#', 'platform', 'drivers', 'dma'), + os.path.join('#', 'platform', 'drivers', 'flash'), + ], + + 'sys':[ + os.path.join('#', 'platform', 'system', 'include'), + os.path.join('#', 'platform', 'system', 'upg'), + os.path.join('#', 'platform', 'drivers', 'flash'), + ], + 'os':[ + ], + + 'mbedtls':[ + os.path.join('#', 'third_party', 'mbedtls', 'include'), + os.path.join('#', 'third_party', 'mbedtls', 'include', 'mbedtls'), + os.path.join('#', 'platform', 'drivers', 'cipher'), + os.path.join('#', 'third_party', 'lwip_sack', 'include'), + ], + + 'at':[ + os.path.join('#', 'platform', 'drivers', 'uart'), + os.path.join('#', 'platform', 'system', 'cpup'), + os.path.join('#', 'platform', 'at'), + os.path.join('#', 'components', 'at', 'src'), + os.path.join('#', 'components', 'wifi', 'include'), + os.path.join('#', 'components', 'iperf2', 'include'), + os.path.join('#', 'config', 'diag'), + os.path.join('#', 'third_party', 'lwip_sack', 'include'), + ], + + 'hilink':[ + os.path.join('#', 'components', 'hilink', 'include'), + ], + }, +} # End of proj_environment + +# env for makefile +common_str = '' +module_str = {} +fixed_config = {'module':deepcopy(compile_module), 'lib_cfg':deepcopy(proj_lib_cfg), 'env_cfg':deepcopy(proj_environment)} + +def set_str_2make(type, macro, macro_val, macro_cfg, env_type = None, env_mod_type = None, depends = None): + type_list = ['module', 'lib_cfg', 'env_cfg'] + global common_str + global module_str + if type not in type_list: + print('[ERROR] type err') + sys.exit(1) + elif type == 'module': + strs = 'ifeq ($(%s), %s)\n'%(macro, macro_val) + strs = '%s\tCOMPILE_MODULE += %s\n'%(strs, macro_cfg) + #strs = '%s\tLIBS += $(addprefix -l, $(%s_libs))\n'%(strs, macro_cfg) + strs = '%sendif\n'%strs + common_str = '%s%s'%(common_str, strs) + elif type == 'lib_cfg': + strs = 'ifeq ($(%s), %s)\n'%(macro, macro_val) + for mod in macro_cfg: + libs = macro_cfg[mod] + str_2_mod = 'ifeq ($(%s), %s)\n'%(macro, macro_val) + for lib in libs: + src = macro_cfg[mod][lib] + str_2_mod = '%s\t%s_srcs += %s\n'%(str_2_mod, lib, ' '.join(src)) + str_2_mod = '%sendif\n'%(str_2_mod) + if mod not in module_str: + module_str[mod] = str_2_mod + else: + org_str = module_str[mod] + module_str[mod] = '%s%s'%(org_str, str_2_mod) + strs = '%s\t%s_libs += %s\n'%(strs, mod, lib) + strs = '%sendif\n'%strs + common_str = '%s%s'%(common_str, strs) + elif type == 'env_cfg': + if env_mod_type == 'common': + strs = condition_str(macro, macro_val, macro_cfg, env_type, depends) + common_str = '%s%s'%(common_str, strs) + elif env_mod_type in module_str: + strs = condition_str(macro, macro_val, macro_cfg, env_type, depends, True) + org_str = module_str[env_mod_type] + module_str[env_mod_type] = '%s%s'%(org_str, strs) + else: + module_str[env_mod_type] = condition_str(macro, macro_val, macro_cfg, env_type, depends, True) + +def set_config(type, macro, macro_val, macro_cfg, env_type = None, env_mod_type = None, depends = None): + type_list = ['module', 'lib_cfg', 'env_cfg'] + if type not in type_list: + print('[ERROR] type err') + sys.exit(1) + elif type == 'module': + if scons_get_cfg_val(macro) == macro_val: + compile_module.append(macro_cfg) + elif type == 'lib_cfg': + if scons_get_cfg_val(macro) == macro_val: + for mod in macro_cfg: + libs = macro_cfg[mod] + for lib in libs: + src = macro_cfg[mod][lib] + if lib not in proj_lib_cfg[mod]: + proj_lib_cfg[mod][lib] = src + else: + proj_lib_cfg[mod][lib].extend(src) + elif type == 'env_cfg': + cfg = select_added_cfg(macro, macro_val, macro_cfg, depends) + if cfg is not None: + proj_environment[env_type][env_mod_type].extend(cfg) + + set_str_2make(type, macro, macro_val, macro_cfg, env_type, env_mod_type, depends) + +# Configrations + +set_config('lib_cfg', 'CONFIG_I2C_SUPPORT', 'y', {'drv': {'i2c': ['i2c']}}) +set_config('lib_cfg', 'CONFIG_SPI_SUPPORT', 'y', {'drv': {'spi': ['spi']}}) +set_config('lib_cfg', 'CONFIG_PWM_SUPPORT', 'y', {'drv': {'pwm': ['pwm']}}) + +set_config('env_cfg', 'CONFIG_I2C_SUPPORT', 'y', ['CONFIG_I2C_SUPPORT'], 'defines', 'common') +set_config('env_cfg', 'CONFIG_DMA_SUPPORT', 'y', ['CONFIG_DMA_SUPPORT'], 'defines', 'common') +set_config('env_cfg', 'CONFIG_SPI_SUPPORT', 'y', ['CONFIG_SPI_SUPPORT'], 'defines', 'common') +set_config('env_cfg', 'CONFIG_PWM_SUPPORT', 'y', ['CONFIG_PWM_SUPPORT'], 'defines', 'common') +set_config('env_cfg', 'CONFIG_PWM_HOLD_AFTER_REBOOT', 'y', ['CONFIG_PWM_HOLD_AFTER_REBOOT'], 'defines', 'common') +set_config('env_cfg', 'CONFIG_I2S_SUPPORT', 'y', ['CONFIG_I2S_SUPPORT'], 'defines', 'common') +set_config('env_cfg', 'CONFIG_COMPRESSION_OTA_SUPPORT', 'y', ['CONFIG_COMPRESSION_OTA_SUPPORT'], 'defines', 'common') +set_config('env_cfg', 'CONFIG_DUAL_PARTITION_OTA_SUPPORT', 'y', ['CONFIG_DUAL_PARTITION_OTA_SUPPORT'], 'defines', 'common') +set_config('env_cfg', 'CONFIG_AT_SUPPORT', 'y', ['CONFIG_AT_COMMAND'], 'defines', 'common') +set_config('env_cfg', 'LOSCFG_DAQ', 'y', ['FEATURE_DAQ'], 'defines', 'common') +set_config('env_cfg', 'LOSCFG_BACKTRACE', 'y', ['LOS_BACKTRACE'], 'defines', 'common') +set_config('env_cfg', 'CONFIG_UART0_SUPPORT', 'y', ['CONFIG_UART0_SUPPORT'], 'defines', 'common') +set_config('env_cfg', 'CONFIG_UART1_SUPPORT', 'y', ['CONFIG_UART1_SUPPORT'], 'defines', 'common') +set_config('env_cfg', 'CONFIG_UART2_SUPPORT', 'y', ['CONFIG_UART2_SUPPORT'], 'defines', 'common') + +set_config('env_cfg', 'CONFIG_TARGET_CHIP_HI3861', 'y', [('PRODUCT_CFG_CHIP_VER_STR', r'\"Hi3861V100\"'), 'CHIP_VER_Hi3861', ('CONFIG_CHIP_PRODUCT_NAME', r'\"Hi3861\"')], 'defines', 'common') +set_config('env_cfg', 'CONFIG_CHIP_PKT_48K', 'y', ['CONFIG_CHIP_PKT_48K'], 'defines', 'common') +set_config('env_cfg', 'CONFIG_CHIP_PKT_32K', 'y', ['CONFIG_CHIP_PKT_32K'], 'defines', 'common') + +macro = 'LOSCFG_COMPILER_HI3861_ASIC' +macro_cfg = { + 'y': ['HI_BOARD_ASIC'], + 'others': ['HI_BOARD_FPGA']} +macro_val = list(macro_cfg.keys()) +set_config('env_cfg', macro, macro_val, macro_cfg, 'defines', 'common') + +macro = 'LOSCFG_COMPILER_HI3861_FLASH' +macro_cfg = { + 'y': ['HI_ON_FLASH'], + 'others': ['HI_ON_RAM']} +macro_val = list(macro_cfg.keys()) +set_config('env_cfg', macro, macro_val, macro_cfg, 'defines', 'common') + +macro = 'CONFIG_MESH_SUPPORT' +macro_cfg = { + 'y': ['CONFIG_MESH_SUPPORT', 'LOS_CONFIG_MESH', 'LOS_CONFIG_MESH_GTK', 'CONFIG_MESH', 'CONFIG_SAE', 'CONFIG_ECC', 'LOS_CONFIG_HOSTAPD_MGMT', 'LOSCFG_APP_MESH', 'LWIP_DEBUG_OPEN', 'LWIP_SMALL_SIZE_MESH=1'], + 'others': ['LWIP_SMALL_SIZE_MESH=0']} +macro_val = list(macro_cfg.keys()) +set_config('env_cfg', macro, macro_val, macro_cfg, 'defines', 'common') + +set_config('env_cfg', 'CONFIG_LWIP_SMALL_SIZE', 'y', ['CONFIG_LWIP_SMALL_SIZE'], 'defines', 'common') +set_config('env_cfg', 'CONFIG_LWIP_SMALL_SIZE_MESH', 'y', ['CONFIG_LWIP_SMALL_SIZE_MESH'], 'defines', 'common') +set_config('env_cfg', 'CONFIG_NETIF_HOSTNAME', 'y', ['CONFIG_NETIF_HOSTNAME'], 'defines', 'common') +set_config('env_cfg', 'CONFIG_DHCP_VENDOR_CLASS_IDENTIFIER', 'y', ['CONFIG_DHCP_VENDOR_CLASS_IDENTIFIER'], 'defines', 'common') +set_config('env_cfg', 'CONFIG_DHCPS_GW', 'y', ['CONFIG_DHCPS_GW'], 'defines', 'common') +set_config('env_cfg', 'CONFIG_UART_DMA_SUPPORT', 'y', ['CONFIG_UART_DMA_SUPPORT'], 'defines', 'common') +set_config('env_cfg', 'CONFIG_SDIO_SUPPORT', 'y', ['CONFIG_SDIO_SUPPORT'], 'defines', 'common') +set_config('env_cfg', 'CONFIG_SPI_DMA_SUPPORT', 'y', ['CONFIG_SPI_DMA_SUPPORT'], 'defines', 'common') +set_config('env_cfg', 'CONFIG_TEE_HUKS_SUPPORT', 'y', ['CONFIG_TEE_HUKS_SUPPORT'], 'defines', 'common') +set_config('env_cfg', 'CONFIG_TEE_HUKS_DEMO_SUPPORT', 'y', ['CONFIG_TEE_HUKS_DEMO_SUPPORT'], 'defines', 'common') +set_config('env_cfg', 'CONFIG_FLASH_ENCRYPT_SUPPORT', 'y', ['CONFIG_FLASH_ENCRYPT_SUPPORT'], 'defines', 'common') +set_config('env_cfg', 'LOSCFG_KASAN', 'y', ['LOSCFG_DEBUG_KASAN'], 'defines', 'common', depends=('LOSCFG_KASAN_EXAMPLES_DEMO', 'y')) +set_config('env_cfg', 'LOSCFG_KASAN', 'y', ['LOSCFG_DEBUG_KASAN'], 'defines', 'common', depends=('LOSCFG_KASAN_LITEOS_NET_COAP', 'y')) + +set_config('env_cfg', 'LOSCFG_BACKTRACE', 'y', ['-fno-omit-frame-pointer'], 'as_flags', 'common') + + +set_config('env_cfg', 'HB_LITEOS_COMPILE_TESTCASE', 'y', ['-DHI1131TEST'], 'link_scripts_flag', 'common') +set_config('env_cfg', 'LOSCFG_KASAN', 'y', ['-DLOSCFG_DEBUG_KASAN'], 'link_scripts_flag', 'common') +set_config('env_cfg', 'CONFIG_FLASH_ENCRYPT_SUPPORT', 'y', ['-DCONFIG_FLASH_ENCRYPT_SUPPORT'], 'link_scripts_flag', 'common') +set_config('env_cfg', 'CONFIG_TEE_HUKS_SUPPORT', 'y', ['-DCONFIG_TEE_HUKS_SUPPORT'], 'link_scripts_flag', 'common') +set_config('env_cfg', 'CONFIG_TARGET_SIG_RSA_V15', 'y', ['-DCONFIG_TARGET_SIG_RSA_V15'], 'link_scripts_flag', 'common') +set_config('env_cfg', 'CONFIG_TARGET_SIG_RSA_PSS', 'y', ['-DCONFIG_TARGET_SIG_RSA_PSS'], 'link_scripts_flag', 'common') +set_config('env_cfg', 'CONFIG_TARGET_SIG_ECC', 'y', ['-DCONFIG_TARGET_SIG_ECC'], 'link_scripts_flag', 'common') +set_config('env_cfg', 'CONFIG_CHIP_PKT_48K', 'y', ['-DCONFIG_CHIP_PKT_48K'], 'link_scripts_flag', 'common') +set_config('env_cfg', 'CONFIG_CHIP_PKT_32K', 'y', ['-DCONFIG_CHIP_PKT_32K'], 'link_scripts_flag', 'common') + +macro = 'LOSCFG_COMPILER_HI3861_ASIC' +macro_cfg = { + 'y': ['-DHI_BOARD_ASIC'], + 'others': ['-DHI_BOARD_FPGA']} +macro_val = list(macro_cfg.keys()) +set_config('env_cfg', macro, macro_val, macro_cfg, 'link_scripts_flag', 'common') + +macro = 'LOSCFG_COMPILER_HI3861_FLASH' +macro_cfg = { + 'y': ['-DHI_ON_FLASH'], + 'others': ['-DHI_ON_RAM']} +macro_val = list(macro_cfg.keys()) +set_config('env_cfg', macro, macro_val, macro_cfg, 'link_scripts_flag', 'common') + + +set_config('env_cfg', 'LOSCFG_KERNEL_RUNSTOP', 'y', [os.path.join('kernel', 'extended', 'runstop'),], 'liteos_inc_path', 'common') +set_config('env_cfg', 'LOSCFG_COMPAT_POSIX', 'y', [os.path.join('components', 'posix', 'include')], 'liteos_inc_path', 'common') +set_config('env_cfg', 'LOSCFG_COMPAT_LINUX', 'y', [os.path.join('components', 'linux', 'include')], 'liteos_inc_path', 'common') +set_config('env_cfg', 'LOSCFG_SHELL', 'y', [os.path.join('shell', 'include')], 'liteos_inc_path', 'common') +set_config('env_cfg', 'LOSCFG_NET_TELNET', 'y', [os.path.join('net', 'telnet', 'include')], 'liteos_inc_path', 'common') +set_config('env_cfg', 'LOSCFG_LIB_LIBC', 'y', + [os.path.join('components', 'lib', 'libc', 'hw', 'include'), + os.path.join('components', 'lib', 'libc', 'musl', 'include'), + os.path.join('components', 'lib', 'libc', 'musl', 'arch', 'generic'), + os.path.join('components', 'lib', 'libc', 'musl', 'arch', 'riscv32'), + os.path.join('components', 'lib', 'libc', 'nuttx', 'include'), + os.path.join('components', 'lib', 'libsec', 'include'), + os.path.join('targets', 'hi3861v100', 'config'), + os.path.join('targets', 'hi3861v100', 'user'), + os.path.join('targets', 'hi3861v100', 'plat'), + os.path.join('targets', 'hi3861v100', 'extend', 'include'), + os.path.join('arch'), + ], 'liteos_inc_path', 'common') + +set_config('env_cfg', 'LOSCFG_NET_LWIP_SACK', 'y', [os.path.join('#', 'third_party', 'lwip_sack', 'include'),], 'common_inc_path', 'common') + +set_config('env_cfg', 'LOSCFG_BACKTRACE', 'y', ['-fno-omit-frame-pointer'], 'opts', 'common') +set_config('env_cfg', 'LOSCFG_KASAN', 'y', ['-fsanitize=kernel-address', '-fasan-shadow-offset=1835008', '--param asan-stack=1', '-fsanitize=bounds-strict'], 'opts', 'common', depends=('LOSCFG_KASAN_EXAMPLES_DEMO', 'y')) +set_config('env_cfg', 'LOSCFG_KASAN', 'y', ['-fsanitize=kernel-address', '-fasan-shadow-offset=1835008', '--param asan-stack=1', '-fsanitize=bounds-strict'], 'opts', 'common', depends=('LOSCFG_KASAN_LITEOS_NET_COAP', 'y')) + +# -------------------------------hilink support------------------------------- +if scons_usr_bool_option('CONFIG_HILINK') == 'y': + os_lib_path.append(os.path.join('components', 'hilink', 'lib')) +set_config('module', 'CONFIG_HILINK', 'y', 'hilink') +set_config('env_cfg', 'CONFIG_HILINK', 'y', ['CONFIG_HILINK'], 'defines', 'common') + +def get_fixed_config(type = 'all'): + if type == 'all': + return fixed_config + elif type in ['module', 'lib_cfg', 'env_cfg']: + return fixed_config[type] + else: + print('[ERROR] type err!') + +def get_make_str(module = 'common'): + if module == 'common': + return common_str + elif module in module_str: + return module_str[module] + else: + print('[INFO] %s not exists module config for makefile!'%module) + +def get_str_dict(): + return (common_str, module_str) + +def get_proj_env(): + return proj_environment + +def get_proj_env_value(env_name, module): + if module in proj_environment[env_name].keys(): + return proj_environment[env_name].get(module) + else: + return None + +def set_proj_env_value_by_macro(env_name, module, env_value, macro='', macro_value=''): + pass + +def print_log_env(env, cwd_path): + if log_output_flag is False: + return + print('----------------------------enter real:', os.path.realpath(str(cwd_path))) + print('CPPPATH:', env['CPPPATH']) + print('DEFINES:', env['CPPDEFINES']) + print('CC:', env['CC']) + +def insert_module(module): + compile_module.append(module) + +def insert_module_dir(name, path): + module_dir[name] = path + +def insert_lib_cfg(name, cfg): + proj_lib_cfg[name] = cfg + +def insert_env_defs(name, defs): + proj_environment['defines'][name] = defs + +def insert_os_include(name, includes): + proj_environment['liteos_inc_path'][name] = includes + +def insert_common_include(name, includes): + proj_environment['common_inc_path'][name] = includes + +def insert_ar_flags(name, flags): + proj_environment['ar_flags']['common'].extend(flags) + +def insert_as_flags(name, flags): + proj_environment['as_flags']['common'].extend(flags) + +def insert_ld_flags(name, flags): + proj_environment['link_flags']['common'].extend(flags) + +def insert_cc_flags(name, flags): + proj_environment['opts'][name] = flags + +def set_factory_mode(): + proj_environment['defines']['common'].append('CONFIG_FACTORY_TEST_MODE') diff --git a/sdk_liteos/build/scripts/hi_config_parser.py b/sdk_liteos/build/scripts/hi_config_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..066b02453c3b847f66501be137129360cc5454c9 --- /dev/null +++ b/sdk_liteos/build/scripts/hi_config_parser.py @@ -0,0 +1,118 @@ +#!/usr/bin/env python3 +# coding=utf-8 + +''' +* Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +* Description: .config parser, bases on kconfig format. +''' + +import os +import sys +from inspect import getsourcefile + +__all__ = ["usr_cfg_main", "sys_cfg_main"] + +class UsrCfgParserError(Exception): + """ + Parser exception + """ + pass + +class Translator: + def __init__(self): + ''' + Insert MARCOS if there are different. + ''' + self.marco_table = { + } + pass + + def translate(self, key): + if key in self.marco_table.keys(): + return self.marco_table[key] + return key + +class UsrCfgParser: + """ + Read menuconfig settings. + """ + def __init__(self): + #print('execute with exe...') if getattr(sys, 'frozen', False) else print('execute with python...') + self.config_file = self.get_default_config_file() + #print('config file:',self.config_file) + if os.path.exists(self.config_file) is False: + raise UsrCfgParserError("Config file not found! Please execute 'python usr_config.py' first!") + self.translate = Translator() + + def local_main(self): + pass + + def get_default_config_file(self): + if getattr(sys, 'frozen', False): + dir_path = os.path.dirname(os.path.dirname(os.path.realpath(getsourcefile(self.local_main)))) + return os.path.join(dir_path, 'config', 'usr_config.mk') + else: + return os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'config', 'usr_config.mk') + + def do_parse(self): + cfg_options = {} + if self.config_file is None: + raise UsrCfgParserError("Config file not found! Please execute \'python usr_config.py\' first!") + with open(self.config_file, 'r') as cfg: + for option in cfg.readlines(): + option = option.strip() + if self.cfg_is_valid(option) is True: + marco, value = self.parse_option(option) + marco = self.translate.translate(marco) + cfg_options[marco.strip()] = value.strip() + return cfg_options + + def cfg_is_valid(self, option): + if option is None: + return False + if option is '': + return False + if option.startswith('#') is True: + return False + if option.find('HiSilicon menuconfig tool') > 0: + return False + if option.find('#', 1) >= 0: + raise UsrCfgParserError("Unknown format! Please execute \'python usr_config.py\' first!") + return True + + def parse_option(self, option): + cfg = option.split('=') + if len(cfg) == 2: #Just one setting + return cfg[0], cfg[1] + else: + raise UsrCfgParserError("Unknown format! Please execute \'python usr_config.py\' first!") + +def usr_cfg_main(): + return UsrCfgParser().do_parse() + +class SysCfgParser(UsrCfgParser): + """ + Read system settings + """ + def get_default_config_file(self): + if getattr(sys, 'frozen', False): + dir_path = os.path.dirname(os.path.dirname(os.path.realpath(getsourcefile(self.local_main)))) + return os.path.join(dir_path, 'config', 'sdk.mk') + else: + return os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'config', 'sdk.mk') + +def sys_cfg_main(): + return SysCfgParser().do_parse() + diff --git a/sdk_liteos/build/scripts/make_upg_file.py b/sdk_liteos/build/scripts/make_upg_file.py new file mode 100755 index 0000000000000000000000000000000000000000..f7e914211f19103ecbd3e7cb6c12f594f181c573 --- /dev/null +++ b/sdk_liteos/build/scripts/make_upg_file.py @@ -0,0 +1,822 @@ +#!/usr/bin/env python3 +# coding=utf-8 + +''' +* Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +* Description: part of hupg build scripts +''' + +import os +import re +import hashlib +import sys +import subprocess +import struct +from ctypes import * +from Crypto.Hash import SHA +from Crypto.Hash import SHA256 +from Crypto.PublicKey import RSA +from Crypto.Signature import PKCS1_v1_5 as Signature_pkcs1_v1_5 +from Crypto.Signature import PKCS1_PSS as Signature_pss +from ecdsa import SigningKey +from ecdsa import VerifyingKey +import make_upg_user_info as USER_INFO + +###############################定义基本类型############################################### +hi_char=c_char +hi_s8=c_byte +hi_u8=c_ubyte +hi_s16=c_short +hi_u16=c_ushort +hi_s32=c_int +hi_u32=c_uint + +class sign_alg_param(Structure): + _fields_ = [ + ("hash_alg", hi_u32, 16), + ("sign_alg", hi_u32, 6), + ("sign_param", hi_u32, 10), + ] + +class upg_rsa_key(Structure): + _fields_ = [ + ("mod_n", hi_u8*256), + ("exp_e", hi_u8*4), + ("padding", hi_u8*28), + ] + +class upg_rsa_sign(Structure): + _fields_ = [ + ("sign", hi_u8*256), + ] + +class upg_ecc_key(Structure): + _fields_ = [ + ("px", hi_u8*32), + ("py", hi_u8*32), + ("padding", hi_u8*224), + ] + +class upg_ecc_sign(Structure): + _fields_ = [ + ("r", hi_u8*32), + ("s", hi_u8*32), + ("padding", hi_u8*192), + ] + +class upg_sha256_key(Structure): + _fields_ = [ + ("padding", hi_u8*288), + ] + +class upg_sha256_sign(Structure): + _fields_ = [ + ("check_sum", hi_u8*32), + ("padding", hi_u8*224), + ] + +class hi_upg_user_info(Structure): + _fields_ = [ + ("reserved", hi_u8*32), + ] + +class hi_upg_common_head(Structure): + _fields_ = [ + ("image_id", hi_u32), + ("struct_version", hi_u32), + ("section_offset", hi_u32), + ("section_len", hi_u32), + ("user_info", hi_upg_user_info), + ("file_type", hi_u8), + ("file_version", hi_u8), + ("encrypt_flag", hi_u8), + ("file_attr", hi_u8), + ("file_len", hi_u32), + ("key_len", hi_u32), + ("param", sign_alg_param), + ("aes_key", hi_u8*16), + ("aes_iv", hi_u8*16), + ] + +class hi_upg_section_head(Structure): + _fields_ = [ + ("image_id", hi_u32), + ("struct_version", hi_u32), + ("param", sign_alg_param), + ("section_count", hi_u8), + ("reserved", hi_u8*27), + ("section0_compress", hi_u8), + ("pad0", hi_u8*3), + ("section0_offset", hi_u32), + ("section0_len", hi_u32), + ("section1_compress", hi_u8), + ("pad1", hi_u8*3), + ("section1_offset", hi_u32), + ("section1_len", hi_u32), + ] + +def lzma_compress_bin(src_file, dst_file, lzma_tool): + print('lzma compress tool :', lzma_tool) + print('lzma src file :', src_file) + print('lzma out file :', dst_file) + cmd_list = [] + cmd_list.append(lzma_tool) + cmd_list.append('-d16 -lc2 -lp2 e') + cmd_list.append(src_file) + cmd_list.append(dst_file) + str_cmd=' '.join(cmd_list) + subprocess.run(str_cmd, shell=True) + +def aes_encrypt_bin(src_file, dst_file, offset, size, aes_key_file, aes_encrypt_tool): + print('aes encrypt src file:', src_file) + print('aes encrypt out file:', dst_file) + print('aes key file :', aes_key_file) + print('aes encrypt tool :', aes_encrypt_tool) + cmd_list = [] + cmd_list.append(aes_encrypt_tool) + cmd_list.append('-i') + cmd_list.append(src_file) + cmd_list.append('-o') + cmd_list.append(dst_file) + cmd_list.append('-u') + cmd_list.append(aes_key_file) + cmd_list.append('-f %x'%(offset)) + cmd_list.append('-z %x'%(size)) + str_cmd=' '.join(cmd_list) + print("[aes-str-cmd]", str_cmd) + subprocess.run(str_cmd, shell=True) + +def print_upg_info(image_file, upg_bin): + st_hupg = hi_upg_common_head.from_buffer(upg_bin) + + print("-------------%s image info print start-------------"%(image_file)) + print("[image_id=0x%x][struct_version=0x%x]]"%(st_hupg.image_id, st_hupg.struct_version)) + print("[section_offset=0x%x][section_len=0x%x]"%(st_hupg.section_offset, st_hupg.section_len)) + print("[file_type=0x%x][file_version=0x%x][encrypt_flag=0x%x]"%( + st_hupg.file_type, st_hupg.file_version, st_hupg.encrypt_flag)) + print("[file_len=0x%x][key_len=0x%x]"%(st_hupg.file_len, st_hupg.key_len)) + print("[file_attr=0x%x]"%(st_hupg.file_attr)) + print("[hash_alg=0x%x][sign_alg=0x%x][sign_param=0x%x]"%( + st_hupg.param.hash_alg, st_hupg.param.sign_alg, st_hupg.param.sign_param)) + print("[aes_key[0-1-14-15]=[0x%x][0x%x][0x%x][0x%x]]"%( + st_hupg.aes_key[0], st_hupg.aes_key[1], st_hupg.aes_key[14], st_hupg.aes_key[15])) + print("[aes_iv [0-1-14-15]=[0x%x][0x%x][0x%x][0x%x]]"%( + st_hupg.aes_iv[0], st_hupg.aes_iv[1], st_hupg.aes_iv[14], st_hupg.aes_iv[15])) + + #打印common段key信息、common段签名信息、section段签名信息 + if st_hupg.param.sign_alg < 0x10: + common_key_offset = sizeof(hi_upg_common_head) + common_sign_offset = sizeof(hi_upg_common_head) + st_hupg.key_len + section_sign_offset = st_hupg.section_offset + sizeof(hi_upg_section_head) + print('[common key][000]=[0x%x]'%(upg_bin[common_key_offset])) + print('[common key][001]=[0x%x]'%(upg_bin[common_key_offset + 1])) + print('[common key][254]=[0x%x]'%(upg_bin[common_key_offset + 254])) + print('[common key][255]=[0x%x]'%(upg_bin[common_key_offset + 255])) + print('[common sign][000]=[0x%x]'%(upg_bin[common_sign_offset])) + print('[common sign][001]=[0x%x]'%(upg_bin[common_sign_offset + 1])) + print('[common sign][254]=[0x%x]'%(upg_bin[common_sign_offset + 254])) + print('[common sign][255]=[0x%x]'%(upg_bin[common_sign_offset + 255])) + print('[section sign][000]=[0x%x]'%(upg_bin[section_sign_offset])) + print('[section sign][001]=[0x%x]'%(upg_bin[section_sign_offset + 1])) + print('[section sign][254]=[0x%x]'%(upg_bin[section_sign_offset + 254])) + print('[section sign][255]=[0x%x]'%(upg_bin[section_sign_offset + 255])) + elif st_hupg.param.sign_alg == 0x10: + common_key_offset = sizeof(hi_upg_common_head) + common_sign_offset = sizeof(hi_upg_common_head) + st_hupg.key_len + section_sign_offset = st_hupg.section_offset + sizeof(hi_upg_section_head) + print('[common key][00]=[0x%x]'%(upg_bin[common_key_offset])) + print('[common key][01]=[0x%x]'%(upg_bin[common_key_offset + 1])) + print('[common key][62]=[0x%x]'%(upg_bin[common_key_offset + 62])) + print('[common key][63]=[0x%x]'%(upg_bin[common_key_offset + 63])) + print('[common sign][00]=[0x%x]'%(upg_bin[common_sign_offset])) + print('[common sign][01]=[0x%x]'%(upg_bin[common_sign_offset + 1])) + print('[common sign][62]=[0x%x]'%(upg_bin[common_sign_offset + 62])) + print('[common sign][63]=[0x%x]'%(upg_bin[common_sign_offset + 63])) + print('[section sign][00]=[0x%x]'%(upg_bin[section_sign_offset])) + print('[section sign][01]=[0x%x]'%(upg_bin[section_sign_offset + 1])) + print('[section sign][62]=[0x%x]'%(upg_bin[section_sign_offset + 62])) + print('[section sign][63]=[0x%x]'%(upg_bin[section_sign_offset + 63])) + else: + common_key_offset = sizeof(hi_upg_common_head) + common_sign_offset = sizeof(hi_upg_common_head) + st_hupg.key_len + section_sign_offset = st_hupg.section_offset + sizeof(hi_upg_section_head) + print('[common key][00]=[0x%x]'%(upg_bin[common_key_offset])) + print('[common key][01]=[0x%x]'%(upg_bin[common_key_offset+1])) + print('[common key][30]=[0x%x]'%(upg_bin[common_key_offset+30])) + print('[common key][31]=[0x%x]'%(upg_bin[common_key_offset+31])) + print('[common sign][00]=[0x%x]'%(upg_bin[common_sign_offset])) + print('[common sign][01]=[0x%x]'%(upg_bin[common_sign_offset+1])) + print('[common sign][30]=[0x%x]'%(upg_bin[common_sign_offset+30])) + print('[common sign][31]=[0x%x]'%(upg_bin[common_sign_offset+31])) + print('[section sign][00]=[0x%x]'%(upg_bin[section_sign_offset])) + print('[section sign][01]=[0x%x]'%(upg_bin[section_sign_offset+1])) + print('[section sign][30]=[0x%x]'%(upg_bin[section_sign_offset+30])) + print('[section sign][31]=[0x%x]'%(upg_bin[section_sign_offset+31])) + + #打印section段固定头信息 + section_head = hi_upg_section_head.from_buffer( + upg_bin[st_hupg.section_offset:st_hupg.section_offset + sizeof(hi_upg_section_head)]) + print("[image_id=0x%x][struct_version=0x%x]]"%( + section_head.image_id, section_head.struct_version)) + print("[hash_alg=0x%x][sign_alg=0x%x][sign_param=0x%x]"%( + section_head.param.hash_alg, section_head.param.sign_alg, section_head.param.sign_param)) + print("[section_count=0x%x]"%(section_head.section_count)) + print("[section0_compress=0x%x][section0_offset=0x%x][section0_len=0x%x]"%(section_head.section0_compress, section_head.section0_offset, section_head.section0_len)) + print("[section1_compress=0x%x][section1_offset=0x%x][section1_len=0x%x]"%(section_head.section1_compress, section_head.section1_offset, section_head.section1_len)) + print("-------------%s image info print end--------------"%(image_file)) + +def print_hbin_info(image_file, upg_bin, bin_size): + st_hupg = hi_upg_common_head.from_buffer(upg_bin) + print("-------------%s image info print start-------------"%(image_file)) + print("[bin_size]=[0x%x]"%(bin_size)) + print("[image_id=0x%x][struct_version=0x%x]]"%(st_hupg.image_id, st_hupg.struct_version)) + print("[section_offset=0x%x][section_len=0x%x]"%(st_hupg.section_offset, st_hupg.section_len)) + print("[file_type=0x%x][file_version=0x%x][encrypt_flag=0x%x]"%( + st_hupg.file_type, st_hupg.file_version, st_hupg.encrypt_flag)) + print("[file_len=0x%x][key_len=0x%x]"%(st_hupg.file_len, st_hupg.key_len)) + print("[hash_alg=0x%x][sign_alg=0x%x][sign_param=0x%x]"%( + st_hupg.param.hash_alg, st_hupg.param.sign_alg, st_hupg.param.sign_param)) + print("[aes_key[0,1,14,15]=[0x%x][0x%x][0x%x][0x%x]]"%( + st_hupg.aes_key[0], st_hupg.aes_key[1], st_hupg.aes_key[14], st_hupg.aes_key[15])) + print("[aes_iv[0,1,14,15]=[0x%x][0x%x][0x%x][0x%x]]"%( + st_hupg.aes_iv[0], st_hupg.aes_iv[1], st_hupg.aes_iv[14], st_hupg.aes_iv[15])) + print("-------------%s image info print end--------------"%(image_file)) + +def int_2_bin_list(val, array_size): + L = bytearray(array_size) + i = array_size - 1 + + while i != 0: + L[i] = val%256 + val = val//256 + i = i - 1 + L[0] = val + return (L) + +def convert_int(value): + match1 = re.match(r'\s*0x', value) + match2 = re.match(r'\s*0X', value) + if match1 or match2: + return int(value, 16) + else: + return int(value, 10) + +def make_secure_key(alg_dir_path, sign_alg): + if sign_alg < 0x10: + key_bin = bytearray(sizeof(upg_rsa_key)) + rsa_key = upg_rsa_key.from_buffer(key_bin) + second_key_dir = os.path.join(alg_dir_path, r'upg_private_rsa_2.pem') + with open(second_key_dir, 'rb') as f: + temp_bin = f.read() + second_key = RSA.importKey(temp_bin) + key_n_2 = int_2_bin_list(second_key.n, sizeof(rsa_key.mod_n)) + key_bin[0:sizeof(rsa_key.mod_n)] = key_n_2 + key_bin[sizeof(rsa_key.mod_n):sizeof(rsa_key.mod_n) + sizeof(rsa_key.exp_e)] = int_2_bin_list(65537, sizeof(rsa_key.exp_e)) #exp_e + elif sign_alg == 0x10: + key_bin = bytearray(sizeof(upg_ecc_key)) + ecc_key = upg_ecc_key.from_buffer(key_bin) + second_key_dir = os.path.join(alg_dir_path, r'upg_private_ecc_2.pem') + with open(second_key_dir) as f: + sk = SigningKey.from_pem(f.read()) + vk = sk.verifying_key + second_key = vk.to_string().hex() + key = bytearray.fromhex(second_key) + key_bin[0:(sizeof(ecc_key.px) + sizeof(ecc_key.py))] = key + else: + key_bin = bytearray(sizeof(upg_sha256_key)) + return key_bin + +def make_rsa_pss_signature(alg_dir_path, common_head_content, section_content): + first_key_dir = os.path.join(alg_dir_path, r'upg_private_rsa_1.pem') + second_key_dir = os.path.join(alg_dir_path, r'upg_private_rsa_2.pem') + with open(first_key_dir, 'rb') as f: + temp_bin = f.read() + first_key = RSA.importKey(temp_bin) + + with open(second_key_dir, 'rb') as f: + temp_bin = f.read() + second_key = RSA.importKey(temp_bin) + + signer = Signature_pss.new(first_key) + digest = SHA256.new() + digest.update(bytes(common_head_content)) + signature_1 = signer.sign(digest) + + signer = Signature_pss.new(second_key) + digest = SHA256.new() + digest.update(bytes(section_content)) + signature_2 = signer.sign(digest) + + return (signature_1, signature_2) + +def make_rsa_pkcs_signature(alg_dir_path, common_head_content, section_content): + first_key_dir = os.path.join(alg_dir_path, r'upg_private_rsa_1.pem') + second_key_dir = os.path.join(alg_dir_path, r'upg_private_rsa_2.pem') + with open(first_key_dir, 'rb') as f: + temp_bin = f.read() + first_key = RSA.importKey(temp_bin) + + with open(second_key_dir, 'rb') as f: + temp_bin = f.read() + second_key = RSA.importKey(temp_bin) + + signer = Signature_pkcs1_v1_5.new(first_key) + digest = SHA256.new() + digest.update(bytes(common_head_content)) + signature_1 = signer.sign(digest) + + signer = Signature_pkcs1_v1_5.new(second_key) + digest = SHA256.new() + digest.update(bytes(section_content)) + signature_2 = signer.sign(digest) + + return (signature_1, signature_2) + +def make_ecc_secure_signature(alg_dir_path, common_head_content, section_content): + first_key_dir = os.path.join(alg_dir_path, r'upg_private_ecc_1.pem') + second_key_dir = os.path.join(alg_dir_path, r'upg_private_ecc_2.pem') + with open(first_key_dir, 'rb') as f: + first_key = SigningKey.from_pem(f.read()) + + with open(second_key_dir, 'rb') as f: + second_key = SigningKey.from_pem(f.read()) + + signature_1 = first_key.sign(common_head_content, hashfunc=hashlib.sha256) + signature_2 = second_key.sign(section_content, hashfunc=hashlib.sha256) + + signature_1_bin = bytearray(sizeof(upg_ecc_sign)) + signature = upg_ecc_sign.from_buffer(signature_1_bin) + signature_1_bin[0:sizeof(signature.r) + sizeof(signature.s)] = signature_1 + signature_2_bin = bytearray(sizeof(upg_ecc_sign)) + signature = upg_ecc_sign.from_buffer(signature_2_bin) + signature_2_bin[0:sizeof(signature.r) + sizeof(signature.s)] = signature_2 + + return (signature_1_bin, signature_2_bin) + +def make_sha256_unsecure_signature(common_head_content, section_content): + #common段非安全签名 + signature_1_bin = bytearray(sizeof(upg_sha256_sign)) + signature = upg_sha256_sign.from_buffer(signature_1_bin) + common_head_sh = hashlib.sha256() + common_head_sh.update(common_head_content) + common_head_hash = common_head_sh.digest() + signature_1_bin[0:sizeof(signature.check_sum)] = common_head_hash + + #section段非安全签名 + signature_2_bin = bytearray(sizeof(upg_sha256_sign)) + signature = upg_sha256_sign.from_buffer(signature_2_bin) + section_head_sh = hashlib.sha256() + section_head_sh.update(section_content) + section_head_hash = section_head_sh.digest() + signature_2_bin[0:sizeof(signature.check_sum)] = section_head_hash + return (signature_1_bin, signature_2_bin) + +def make_part_offset_size(temp_offset, bin_size): + if bin_size != 0: + section_offset = temp_offset[0] + section_size = bin_size + else: + section_offset = 0 + section_size = 0 + + temp_offset[0] = temp_offset[0] + section_size + return (section_offset, section_size) + +def make_upg_get_aes_key(alg_dir_path): + aes_key_bin = bytearray(16) + aes_key_file = os.path.join(alg_dir_path, r'upg_aes_key.txt') + with open(aes_key_file) as f: + lines = f.readlines() + aes_key_bin = bytearray.fromhex(lines[1].split(':')[1].split(';')[0].strip()) + return aes_key_bin + +def make_upg_get_aes_iv(alg_dir_path): + aes_iv_bin = bytearray(16) + aes_key_file = os.path.join(alg_dir_path, r'upg_aes_key.txt') + with open(aes_key_file) as f: + lines = f.readlines() + aes_iv_bin = bytearray.fromhex(lines[2].split(':')[1].split(';')[0].strip()) + return aes_iv_bin + +def make_upg_only(image_id, file_ver, encrypt_flag, file_type, section_bin_list, section_compress_list, alg_dir_path, max_size, sign_alg, chip_name, file_attr): + section_count = len(section_bin_list) + section_offset_list = [] + section_size_list = [] + temp_offset = [0] + + #common固定头大小偏移 + (common_head_offset, common_head_size) = make_part_offset_size(temp_offset, sizeof(hi_upg_common_head)) + print('[common_head_offset=%d][common_head_size=%d]'%(common_head_offset, common_head_size)) + + #common密钥区大小偏移、固定头签名大小偏移(不同签名算法统一按最大值处理(密钥288Byte/签名256Byte),填实际长度字节,多余的部分填0) + if sign_alg < 0x10: + #RSA2048 + (common_key_offset, common_key_size) = make_part_offset_size(temp_offset, sizeof(upg_rsa_key)) + (common_head_sign_offset, common_head_sign_size) = make_part_offset_size(temp_offset, sizeof(upg_rsa_sign)) + elif sign_alg == 0x10: + #ECDSA256 + (common_key_offset, common_key_size) = make_part_offset_size(temp_offset, sizeof(upg_ecc_key)) + (common_head_sign_offset, common_head_sign_size) = make_part_offset_size(temp_offset, sizeof(upg_ecc_sign)) + else: + #SHA256 + (common_key_offset, common_key_size) = make_part_offset_size(temp_offset, sizeof(upg_sha256_key)) + (common_head_sign_offset, common_head_sign_size) = make_part_offset_size(temp_offset, sizeof(upg_sha256_sign)) + + print('[common_key_offset=%d][common_key_size=%d]'%(common_key_offset, common_key_size)) + print('[common_head_sign_offset=%d][common_head_sign_size=%d]'%(common_head_sign_offset, common_head_sign_size)) + + #section固定头大小偏移 + (section_head_offset, section_head_size) = make_part_offset_size(temp_offset, sizeof(hi_upg_section_head)) + print('[section_head_offset=%d][section_head_size=%d]'%(section_head_offset, section_head_size)) + #section签名大小偏移、秘钥信息。签名算法不同,填充大小不同 + if sign_alg < 0x10: + (upg_file_sign_offset, upg_file_sign_size) = make_part_offset_size(temp_offset, sizeof(upg_rsa_sign)) + elif sign_alg == 0x10: + (upg_file_sign_offset, upg_file_sign_size) = make_part_offset_size(temp_offset, sizeof(upg_ecc_sign)) + else: + (upg_file_sign_offset, upg_file_sign_size) = make_part_offset_size(temp_offset, sizeof(upg_sha256_sign)) + print('[upg_file_sign_offset=%d][upg_file_sign_size=%d]'%(upg_file_sign_offset, upg_file_sign_size)) + + #section各个镜像大小和偏移 + i = 0 + while i < section_count: + (offset, size) = make_part_offset_size(temp_offset, len(section_bin_list[i])) + section_offset_list.append(offset) + section_size_list.append(size) + i = i + 1 + + #section填充域大小和偏移:AES加密要求16字节对齐 + temp_size_1 = temp_offset[0] + temp_size_2 = temp_size_1//16 + temp_size_2 = temp_size_2*16 + padding_size = temp_size_1 - temp_size_2 + if temp_size_1 == temp_size_2: + padding_size = 0 + else: + padding_size = temp_size_2 + 16 - temp_size_1 + + (padding_offset, padding_size) = make_part_offset_size(temp_offset, padding_size)#hupg+nv部分大小 + print('[padding_offset=%d][padding_size=%d]'%(padding_offset, padding_size)) + + #初始化upg_bin + upg_bin = bytearray(temp_offset[0]) + + #升级文件大小上限从分区获取 + if len(upg_bin) > max_size: + sys.exit("\033[91m[ERR]upg size>%dKB FROM:%s\033[0m"%(max_size/1024, os.path.realpath(__file__))) + + #填充common段固定头 + common_head_bin = upg_bin[common_head_offset:common_head_offset + common_head_size] + common_head = hi_upg_common_head.from_buffer(common_head_bin) + common_head.image_id = image_id + common_head.struct_version = 0 + common_head.section_offset = section_head_offset + common_head.section_len = len(upg_bin) - section_head_offset + common_head.file_type = file_type + common_head.file_version = file_ver + common_head.encrypt_flag = encrypt_flag + common_head.file_attr = file_attr + common_head.file_len = len(upg_bin) + common_head.key_len = common_key_size + common_head.param.hash_alg = 0 + common_head.param.sign_alg = sign_alg + common_head.param.sign_param = 0 + #image_id struct_version section_offset section_offset + user_info_offset = sizeof(c_int) + sizeof(c_int) + sizeof(c_int) + sizeof(c_int) + common_head_bin[user_info_offset : (user_info_offset + sizeof(hi_upg_user_info))] = USER_INFO.fill_user_info(chip_name) + if encrypt_flag != 0x42: + common_head_bin[(common_head_size - 32) : (common_head_size - 16)] = make_upg_get_aes_key(alg_dir_path) + common_head_bin[(common_head_size - 16) : common_head_size] = make_upg_get_aes_iv(alg_dir_path) + upg_bin[common_head_offset:common_head_offset + common_head_size] = common_head_bin + + #填充section段固定头 + section_head_bin = upg_bin[section_head_offset:section_head_offset+section_head_size] + section_head = hi_upg_section_head.from_buffer(section_head_bin) + section_head.image_id = image_id + section_head.struct_version = 0 + section_head.param.hash_alg = 0 + section_head.param.sign_alg = sign_alg + section_head.param.sign_param = 0 + section_head.section_count = section_count + if section_count > 2: + sys.exit("[ERR]upg section count more than 2 FROM:%s"%os.path.realpath(__file__)) + elif section_count == 2: + section_head.section0_compress = section_compress_list[0] + section_head.section0_offset = section_offset_list[0] + section_head.section0_len = section_size_list[0] + section_head.section1_compress = section_compress_list[1] + section_head.section1_offset = section_offset_list[1] + section_head.section1_len = section_size_list[1] + elif section_count == 1: + section_head.section0_compress = section_compress_list[0] + section_head.section0_offset = section_offset_list[0] + section_head.section0_len = section_size_list[0] + section_head.section1_offset = 0 + section_head.section1_len = 0 + else: + section_head.section0_offset = 0 + section_head.section0_len = 0 + section_head.section1_offset = 0 + section_head.section1_len = 0 + upg_bin[section_head_offset:section_head_offset + section_head_size] = section_head_bin + + #填充section段内容 + i = 0 + while i < section_count: + upg_bin[section_offset_list[i]:section_offset_list[i] + section_size_list[i]] = section_bin_list[i] + i = i + 1 + + #填充common段key + key_2_n = make_secure_key(alg_dir_path, common_head.param.sign_alg) + upg_bin[common_key_offset:common_key_offset + common_key_size] = key_2_n + + #填充common段签名及section段签名(不同签名算法统一按最大值256Byte处理,填实际长度字节,多余的部分填0) + if sign_alg == 0x0: + (signature_1, signature_2) = make_rsa_pkcs_signature(alg_dir_path, upg_bin[common_head_offset:common_head_sign_offset], upg_bin[section_head_offset:section_head_offset+sizeof(hi_upg_section_head)]+upg_bin[upg_file_sign_offset+upg_file_sign_size:common_head.file_len]) + elif sign_alg == 0x1: + (signature_1, signature_2) = make_rsa_pss_signature(alg_dir_path, upg_bin[common_head_offset:common_head_sign_offset], upg_bin[section_head_offset:section_head_offset+sizeof(hi_upg_section_head)]+upg_bin[upg_file_sign_offset+upg_file_sign_size:common_head.file_len]) + elif sign_alg == 0x10: + (signature_1, signature_2) = make_ecc_secure_signature(alg_dir_path, upg_bin[common_head_offset:common_head_sign_offset], upg_bin[section_head_offset:section_head_offset+sizeof(hi_upg_section_head)]+upg_bin[upg_file_sign_offset+upg_file_sign_size:common_head.file_len]) + else: + (signature_1, signature_2) = make_sha256_unsecure_signature(upg_bin[common_head_offset:common_head_sign_offset], upg_bin[section_head_offset:section_head_offset+sizeof(hi_upg_section_head)]+upg_bin[upg_file_sign_offset+upg_file_sign_size:common_head.file_len]) + + upg_bin[common_head_sign_offset:common_head_sign_offset+common_head_sign_size] = signature_1 + upg_bin[upg_file_sign_offset:upg_file_sign_offset+upg_file_sign_size] = signature_2 + + return upg_bin + +def make_hupg(image_id, file_ver, encrypt_flag, kernel_file, normal_nv_file, image_file, alg_dir_path, max_size, sign_alg, chip_name, file_attr): + print('upg kernel file in:', kernel_file) + print('upg normal nv file in:', normal_nv_file) + print('upg file out:', image_file) + + with open(kernel_file, 'rb') as fp: + kernel_bin = fp.read() + with open(normal_nv_file, 'rb') as fp: + nv_bin = fp.read() + + section_bin_list = [] + section_bin_list.append(kernel_bin) + section_bin_list.append(nv_bin) + + section_compress_list = [] + section_compress_list.append(0) + section_compress_list.append(0) + hupg_bin = make_upg_only(image_id, file_ver, encrypt_flag, 0xF0, section_bin_list, section_compress_list, alg_dir_path, max_size, sign_alg, chip_name, file_attr) + + print_upg_info(image_file, hupg_bin) + #如果标记加密 + unencrypted = 0x42 + if encrypt_flag != unencrypted: + (filepath, tempfilename) = os.path.split(kernel_file) + (filename, extension) = os.path.splitext(tempfilename) + upg_unenrypt_file = os.path.join(filepath, '%s_unencrypt.bin'%filename) + with open(upg_unenrypt_file, 'wb+') as fp: + fp.write(hupg_bin) + + aes_key_file = os.path.join(alg_dir_path, r'upg_aes_key.txt') + aes_encrypt_tool = os.path.join(alg_dir_path, r'sign_tool') + #双分区升级文件需要加密 + src_file_len = len(hupg_bin) + if src_file_len < 0x1000: + sys.exit("\033[91m[ERR]upg size %d< 0x1000 FROM:%s\033[0m"%(src_file_len, os.path.realpath(__file__))) + aes_encrypt_bin(upg_unenrypt_file, image_file, 0x3C0, 0x1000, aes_key_file, aes_encrypt_tool) + else: + with open(image_file, 'wb+') as fp: + fp.write(hupg_bin) + return + +def make_compress_hupg(image_id, file_ver, encrypt_flag, upg_file, image_file, alg_dir_path, kernel_upg_max_size, sign_alg, lzma_tool, build_tmp, chip_name, file_attr): + print('compress upg file in: ', upg_file) + print('compress upg file out:', image_file) + + (filepath, tempfilename) = os.path.split(upg_file) + (filename, extension) = os.path.splitext(tempfilename) + upg_lzma_file = os.path.join(build_tmp, '%s.lzma'%filename) + lzma_compress_bin(upg_file, upg_lzma_file, lzma_tool) + + with open(upg_lzma_file, 'rb') as fp: + upg_lzma_file_bin = fp.read() + + with open(upg_file, 'rb') as fp: + upg_bin = fp.read() + + section_bin_list = [] + if encrypt_flag != 0x42: + upg_lzma_encrypt_file = os.path.join(build_tmp, '%s_encrypt.bin'%filename) + aes_key_file = os.path.join(alg_dir_path, r'upg_aes_key.txt') + aes_encrypt_tool = os.path.join(alg_dir_path, r'sign_tool') + #压缩文件文件需要加密 + src_file_len = len(upg_lzma_file_bin) + if src_file_len < 0x13CD: + sys.exit("\033[91m[ERR]upg size %d< 0x13C0 FROM:%s\033[0m"%(src_file_len, os.path.realpath(__file__))) + aes_encrypt_bin(upg_lzma_file, upg_lzma_encrypt_file, 0xd, 0x13C0, aes_key_file, aes_encrypt_tool) + with open(upg_lzma_encrypt_file, 'rb') as fp: + upg_lzma_encrypt_file_bin = fp.read() + section_bin_list.append(upg_lzma_encrypt_file_bin) + else: + section_bin_list.append(upg_lzma_file_bin) + + section_compress_list = [] + section_compress_list.append(1) + #计算压缩文件大小上限 + upg_bin_len = len(upg_bin) + upg_align_len = (upg_bin_len//4096) * 4096 + upg_len = upg_align_len + if upg_bin_len != upg_align_len: + upg_len = upg_align_len + 4096 + max_compress_size = kernel_upg_max_size - upg_len + print("[upgbin-compressbin]0x%x-0x%x"%(upg_bin_len, max_compress_size)) + hupg_bin = make_upg_only(image_id, file_ver, encrypt_flag, 0xF0, section_bin_list, section_compress_list, alg_dir_path, max_compress_size, sign_alg, chip_name, file_attr) + print_upg_info(image_file, hupg_bin) + with open(image_file, 'wb+') as fp: + fp.write(hupg_bin) + return + +def make_hbin(flash_boot_file, factory_nv_file, normal_nv_file, upg_file, image_file): + print('hbin flash boot file in :', flash_boot_file) + print('hbin factory nv file in :', factory_nv_file) + print('hbin normal nv file in :', upg_file) + print('hbin upg file in :', factory_nv_file) + print('hbin file out :', image_file) + + with open(flash_boot_file, 'rb') as fp: + flash_boot_bin = fp.read() + + with open(factory_nv_file, 'rb') as fp: + factory_nv_bin = fp.read() + + with open(normal_nv_file, 'rb') as fp: + normal_nv_bin = fp.read() + + with open(upg_file, 'rb') as fp: + upg_file_bin = fp.read() + + #Todo:从分表获取信息 + boot_st_addr = 0 #BOOT 32KB + boot_size = 0x8000 + ftm1_st_addr = 0x8000 #工厂区NV 4KB+4KB + ftm1_size = 0x1000 + ftm2_st_addr = 0x9000 + ftm2_size = 0x1000 + nv_file_st_addr = 0xa000 #NV工作区 4KB+4KB + nv_file_size = 0x1000 + nv_file_origin_st_addr = 0xc000 #NV工作区的原始备份 + kernel_st_addr = 0xd000 #KernelA 912KB + + bin_total_size = boot_size + ftm1_size + ftm2_size + nv_file_size + nv_file_size + nv_file_size + len(upg_file_bin) + + boot_nv_kernel_bin = bytearray(bin_total_size) + boot_nv_kernel_bin[boot_st_addr:boot_st_addr + boot_size] = flash_boot_bin + boot_nv_kernel_bin[ftm1_st_addr:ftm1_st_addr + ftm1_size] = factory_nv_bin + #boot_nv_kernel_bin[ftm2_st_addr:ftm2_st_addr + ftm2_size] = factory_nv_bin 当前只放1份工厂区NV + boot_nv_kernel_bin[nv_file_st_addr:nv_file_st_addr + nv_file_size] = normal_nv_bin + boot_nv_kernel_bin[nv_file_origin_st_addr:nv_file_origin_st_addr + nv_file_size] = normal_nv_bin #NV区原始备份 + boot_nv_kernel_bin[kernel_st_addr:kernel_st_addr + len(upg_file_bin)] = upg_file_bin + print_hbin_info(image_file, boot_nv_kernel_bin[kernel_st_addr:kernel_st_addr + len(upg_file_bin)], bin_total_size) + with open(image_file, "wb+") as fp: + fp.write(boot_nv_kernel_bin) + return + +def make_bootupg(image_id, file_ver, encrypt_flag, flash_boot_file, image_file, alg_dir_path, max_size, sign_alg, chip_name, file_attr): + print('boot upg file in:', flash_boot_file) + print('boot upg file out:', image_file) + with open(flash_boot_file, 'rb') as fp: + boot_bin = fp.read() + + hupg_bin = make_upg_boot_only(image_id, file_ver, encrypt_flag, 0xE1, boot_bin, alg_dir_path, max_size, sign_alg, chip_name, file_attr) + print_upg_info(image_file, hupg_bin) + with open(image_file, 'wb+') as fp: + fp.write(hupg_bin) + return + +#配置romboot下用法boot升级文件的填充字段放到section前面 +def make_upg_boot_only(image_id, file_ver, encrypt_flag, file_type, section_bin, alg_dir_path, max_size, sign_alg, chip_name, file_attr): + temp_offset = [0] + + #common固定头大小偏移 + (common_head_offset, common_head_size) = make_part_offset_size(temp_offset, sizeof(hi_upg_common_head)) + print('[common_head_offset=%d][common_head_size=%d]'%(common_head_offset, common_head_size)) + + #common密钥区大小偏移、固定头签名大小偏移 + if sign_alg < 0x10: + #RSA2048 + (common_key_offset, common_key_size) = make_part_offset_size(temp_offset, sizeof(upg_rsa_key)) + (common_head_sign_offset, common_head_sign_size) = make_part_offset_size(temp_offset, sizeof(upg_rsa_sign)) + elif sign_alg == 0x10: + #ECDSA256 + (common_key_offset, common_key_size) = make_part_offset_size(temp_offset, sizeof(upg_ecc_key)) + (common_head_sign_offset, common_head_sign_size) = make_part_offset_size(temp_offset, sizeof(upg_ecc_sign)) + else: + #SHA256 + (common_key_offset, common_key_size) = make_part_offset_size(temp_offset, sizeof(upg_sha256_key)) + (common_head_sign_offset, common_head_sign_size) = make_part_offset_size(temp_offset, sizeof(upg_sha256_sign)) + print('[common_key_offset=%d][common_key_size=%d]'%(common_key_offset, common_key_size)) + print('[common_head_sign_offset=%d][common_head_sign_size=%d]'%(common_head_sign_offset, common_head_sign_size)) + #section固定头大小偏移 + (section_head_offset, section_head_size) = make_part_offset_size(temp_offset, sizeof(hi_upg_section_head)) + print('[section_head_offset=%d][section_head_size=%d]'%(section_head_offset, section_head_size)) + #section签名大小偏移、秘钥信息。签名算法不同,填充大小不同 + if sign_alg < 0x10: + (upg_file_sign_offset, upg_file_sign_size) = make_part_offset_size(temp_offset, sizeof(upg_rsa_sign)) + elif sign_alg == 0x10: + (upg_file_sign_offset, upg_file_sign_size) = make_part_offset_size(temp_offset, sizeof(upg_ecc_sign)) + else: + (upg_file_sign_offset, upg_file_sign_size) = make_part_offset_size(temp_offset, sizeof(upg_sha256_sign)) + print('[upg_file_sign_offset=%d][upg_file_sign_size=%d]'%(upg_file_sign_offset, upg_file_sign_size)) + #填充大小和偏移 + temp_size_1 = temp_offset[0] + len(section_bin) + temp_size_2 = temp_size_1//16 + temp_size_2 = temp_size_2*16 + padding_size = temp_size_1 - temp_size_2 + if temp_size_1 == temp_size_2: + padding_size = 0 + else: + padding_size = temp_size_2 + 16 - temp_size_1 + + (padding_offset, padding_size) = make_part_offset_size(temp_offset, padding_size) + print('[padding_offset=%d][padding_size=%d]'%(padding_offset, padding_size)) + + #镜像大小和偏移 + (section_offset, section_size) = make_part_offset_size(temp_offset, len(section_bin))#BOOT部分大小 + + #初始化upg_bin + upg_bin = bytearray(temp_offset[0]) + + #升级文件大小上限从分区获取 + if len(upg_bin) > max_size: + sys.exit("\033[91m[ERR]upg boot size>%dKB FROM:%s\033[0m"%(max_size/1024, os.path.realpath(__file__))) + + #填充common段固定头 + common_head_bin = upg_bin[common_head_offset:common_head_offset + common_head_size] + common_head = hi_upg_common_head.from_buffer(common_head_bin) + common_head.image_id = image_id + common_head.struct_version = 0 + common_head.section_offset = section_head_offset + common_head.section_len = len(upg_bin) - section_head_offset + common_head.file_type = file_type + common_head.file_version = file_ver + common_head.encrypt_flag = encrypt_flag + common_head.file_attr = file_attr + common_head.file_len = len(upg_bin) + common_head.key_len = common_key_size + common_head.param.hash_alg = 0 + common_head.param.sign_alg = sign_alg + common_head.param.sign_param = 0 + #common_head.aes_key[16] = + #common_head.aes_iv[16] = + #image_id struct_version section_offset section_offset + user_info_offset = sizeof(c_int) + sizeof(c_int) + sizeof(c_int) + sizeof(c_int) + common_head_bin[user_info_offset : (user_info_offset + sizeof(hi_upg_user_info))] = USER_INFO.fill_user_info(chip_name) + upg_bin[common_head_offset:common_head_offset+common_head_size] = common_head_bin + + #填充section段固定头 + section_head_bin = upg_bin[section_head_offset:section_head_offset+section_head_size] + section_head = hi_upg_section_head.from_buffer(section_head_bin) + section_head.image_id = image_id + section_head.struct_version = 0 + section_head.param.hash_alg = 0 + section_head.param.sign_alg = sign_alg + section_head.param.sign_param = 0 + section_head.section_count = 1 + section_head.section0_compress = 0 + section_head.section0_offset = section_offset + section_head.section0_len = section_size + section_head.section1_compress = 0 + section_head.section1_offset = 0 + section_head.section1_len = 0 + upg_bin[section_head_offset:section_head_offset + section_head_size] = section_head_bin + + #填充section段内容 + upg_bin[section_offset:section_offset + section_size] = section_bin + + #填充common段key + key_2_n = make_secure_key(alg_dir_path, common_head.param.sign_alg) + upg_bin[common_key_offset:common_key_offset + common_key_size] = key_2_n + + #填充common段签名及section段签名 + if sign_alg == 0x0: + (signature_1, signature_2) = make_rsa_pkcs_signature(alg_dir_path, upg_bin[common_head_offset:common_head_sign_offset], upg_bin[section_head_offset:section_head_offset+sizeof(hi_upg_section_head)]+upg_bin[upg_file_sign_offset+upg_file_sign_size:common_head.file_len]) + elif sign_alg == 0x1: + (signature_1, signature_2) = make_rsa_pss_signature(alg_dir_path, upg_bin[common_head_offset:common_head_sign_offset], upg_bin[section_head_offset:section_head_offset+sizeof(hi_upg_section_head)]+upg_bin[upg_file_sign_offset+upg_file_sign_size:common_head.file_len]) + elif sign_alg == 0x10: + (signature_1, signature_2) = make_ecc_secure_signature(alg_dir_path, upg_bin[common_head_offset:common_head_sign_offset], upg_bin[section_head_offset:section_head_offset+sizeof(hi_upg_section_head)]+upg_bin[upg_file_sign_offset+upg_file_sign_size:common_head.file_len]) + else: + (signature_1, signature_2) = make_sha256_unsecure_signature(upg_bin[common_head_offset:common_head_sign_offset], upg_bin[section_head_offset:section_head_offset+sizeof(hi_upg_section_head)]+upg_bin[upg_file_sign_offset+upg_file_sign_size:common_head.file_len]) + + upg_bin[common_head_sign_offset:common_head_sign_offset+common_head_sign_size] = signature_1 + upg_bin[upg_file_sign_offset:upg_file_sign_offset+upg_file_sign_size] = signature_2 + + return upg_bin \ No newline at end of file diff --git a/sdk_liteos/build/scripts/make_upg_user_info.py b/sdk_liteos/build/scripts/make_upg_user_info.py new file mode 100755 index 0000000000000000000000000000000000000000..83d7b478f32fdb144fd4601803c18fb6ff6c7c12 --- /dev/null +++ b/sdk_liteos/build/scripts/make_upg_user_info.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python3 +# coding=utf-8 + +''' +* Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +* Description: part of hupg build scripts +''' + +from ctypes import * + +###############################定义基本类型############################################### +hi_char=c_char +hi_s8=c_byte +hi_u8=c_ubyte +hi_s16=c_short +hi_u16=c_ushort +hi_s32=c_int +hi_u32=c_uint + +#升级文件头中提供了32字节预留字段供用户使用。 +#示例为默认填充了8字节,用于存储芯片产品类型;如不需要,屏蔽即可;或者填充其他内容。 +class app_upg_user_info(Structure): + _fields_ = [ + ("chip_product", hi_char*8), + ("reserved", hi_u8*24), + ] + +def fill_user_info(chip_name): + info_bin = bytearray(sizeof(app_upg_user_info)) + info = app_upg_user_info.from_buffer(info_bin) + info.chip_product = bytes(chip_name, encoding='utf8')#如不需要填充芯片产品字段,屏蔽此行 + print("[upg fill user info]chip:%s"%(info.chip_product)) + + return info_bin diff --git a/sdk_liteos/build/scripts/mk_prim_xml_step1.py b/sdk_liteos/build/scripts/mk_prim_xml_step1.py new file mode 100644 index 0000000000000000000000000000000000000000..1841e29a08485deb573aeac2ebe14d7bbe4b49d0 --- /dev/null +++ b/sdk_liteos/build/scripts/mk_prim_xml_step1.py @@ -0,0 +1,214 @@ +#!/usr/bin/env python3 +# coding=utf-8 + +''' +* Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +* Description: extract strings from .c file, then, generate .cfg file. +''' + +import os +import time +import string +import re +import shutil +import hashlib +import binascii +import sys +import io +import subprocess + +g_params = {} +g_file_id_dic = {} +g_mod_id_dic = {} + +#convert sys argvs from str to dictionary +def mk_param_dic(): + key='default_key' + key_val='' + i=0 + while i< len(sys.argv): + if sys.argv[i]=='_PYTHON_ARG_': + if key!='default_key': + g_params[key]=key_val + else: + pass + + key = sys.argv[i + 1] + key_val = '' + i = i + 1 + else: + key_val = '%s%s '%(key_val, sys.argv[i]) + i = i + 1 + + #last key process + if key!='default_key': + g_params[key]=key_val + #add interl param + g_params['I_FILE_DIR'] = os.path.join(g_params['PRIM_XML_TEMP_ROOT_DIR'].strip(), g_params['PRIM_XML_KEY_WORD']) + +#convert file_id_file(lm_file_id.cfg) to dictionary +def create_file_id_dic(path = None): + file_name = g_params['PRIM_XML_FILE_ID_FILE'].strip(' ') if path is None else path + with open(file_name, 'r') as f1: + for line in f1: + list_temp=re.split('[ \t\n\r\f\v]+', line) + if len(list_temp) >= 2 and list_temp[0][-2:]=='.c' and list_temp[1].isdigit(): + g_file_id_dic[list_temp[0]]=list_temp[1] + print('g_file_id_dic', g_file_id_dic) + return g_file_id_dic + +#convert mod_id_file(lm_file_id.cfg) to dictionary +def create_mod_id_dic(): + file_name = g_params['PRIM_XML_MOD_ID_FILE'].strip(' ') + with open(file_name, 'r') as f1: + for line in f1: + list_temp=re.split('[ \t\n\r\f\v]+', line) + if len(list_temp) >= 2 and list_temp[0][-2:]=='.c' and list_temp[1].isdigit(): + g_mod_id_dic[list_temp[0]]=list_temp[1] + print('g_mod_id_dic', g_mod_id_dic) + +#Generates a list of files(.c) from all subdirectories +def creat_src_file_list(): + full_file_name_list = [] + sub_dir_list = g_params['PRIM_XML_SRC_SUB_DIR'].split(' ') + print('sub_dir_list') + print(sub_dir_list) + for sub_dir in sub_dir_list: + sub_dir=sub_dir.strip() + if sub_dir: + full_dir = g_params['PRIM_XML_SRC_ROOT_DIR'] + full_dir = full_dir.strip() + full_dir = os.path.join(full_dir, sub_dir) + print('full_dir=', full_dir) + file_name_list = os.listdir(full_dir) + print('file_name_list=', file_name_list) + for file_name in file_name_list: + full_file_name = os.path.join(full_dir, file_name) + if os.path.isfile(full_file_name): + print('isfile=', full_file_name) + if full_file_name.endswith('.c'): + print('cfile=', full_file_name) + full_file_name_list.append(full_file_name) + print('full_file_name_list=', full_file_name_list) + return full_file_name_list + +#pre-compile .c to .i +def conver_c_2_i(full_file_name_list): + dst_full_file_name_list = [] + print('conver_c_2_i=', full_file_name_list) + temp_dir = g_params['I_FILE_DIR'].strip() + if os.path.isdir(temp_dir): + shutil.rmtree(temp_dir) + os.makedirs(temp_dir) + cc=g_params['CC'].strip() + cflag = g_params['CFLAGS'].strip() + for src_full_file_name in full_file_name_list: + src_file_name = src_full_file_name.split('/')[-1] + +# if src_file_name in g_file_id_dic and src_file_name in g_mod_id_dic: + if src_file_name in g_file_id_dic: + print('E2I:', src_file_name) + dst_file_name = src_file_name + dst_file_name=dst_file_name.replace('.c', '.i') + dst_full_file_name = os.path.join(temp_dir, dst_file_name) + + cmd_line = [cc, '-E', src_full_file_name, cflag, '-D__FILE_NAME__=%s'%src_file_name, + '-D__FILE_IDX__=%s'%g_file_id_dic[src_file_name], '-P', '>', dst_full_file_name] + print('cmd_line=', cmd_line) + subprocess.run(cmd_line) + dst_full_file_name_list.append(dst_full_file_name) + return dst_full_file_name_list + +def para_exist_i_file(file_name): + key_word = g_params['PRIM_XML_KEY_WORD'].strip() + parse_file = os.path.join(os.path.dirname(file_name), '%s.cfg'%key_word) + print('file_name parse_file=', file_name, parse_file) + with open(file_name, 'r') as f1, open(parse_file, 'w+') as f2: + for line in f1: + match=re.search('PRIM_XML_HI_DIAG_LOG_MSG_', line) + if match: + match_id=re.search('_PRIM_ID_:', line) + match_sz=re.search(',_PRIM_SZ_:', line) + match_line=re.search(',_PRIM_LINE_:', line) + match_file=re.search(',_PRIM_FILE_:', line) + match_file=re.search(',_PRIM_FILE_:', line) +#parse file :get print info +def cp_effect_content_on_file(cfg_fp, file_name): + with open(file_name, 'r') as src_fp: + print('file_name-----', file_name) + #time.sleep(5) + for line in src_fp: + match=re.search('_PRIM_PRI_', line) + if match: + print('line-----', line) + cfg_fp.write(line.encode("UTF-8")) + +def cp_effect_content(dst_full_file_name_list, cfg_file = None, scons_flag = False): + print('cfg file:', cfg_file) + base_folder = g_params['PRIM_XML_TEMP_BASE_ROOT_DIR'].strip() if cfg_file is None else os.path.dirname(cfg_file) + key_word = g_params['PRIM_XML_KEY_WORD'].strip() if cfg_file is None else None + #cfg dir not exist-->mk dir + print('base_folder', base_folder) + #if scons_flag == False and not os.path.isdir(base_folder): + if not os.path.isdir(base_folder): + print('base_folder2', base_folder) + os.makedirs(base_folder) + + cfg_file_name = os.path.join(base_folder, '%s.cfg'%key_word) if cfg_file is None else cfg_file + #cfg file is exist-->recreate it + if os.path.isfile(cfg_file_name): + os.remove(cfg_file_name) + + with open(cfg_file_name, 'ab+') as cfg_fp: + #cfg_fp=io.open(cfg_file_name, 'wb+') + for src_file_name in dst_full_file_name_list: + if os.path.isfile(src_file_name): + cp_effect_content_on_file(cfg_fp, src_file_name) + + #cfg_fp.close() + +#main func +def mk_prim_main(): + print('mk_prim_main in') + #creat sys params dictionary + mk_param_dic() + #print('g_params', g_params) + print('set_print_target') + print(g_params['LOG_FILE_NAME'].strip()) + + log_file_name = g_params['LOG_FILE_NAME'].strip() + log_file_dir = os.path.dirname(log_file_name) + if not os.path.isdir(log_file_dir): + os.makedirs(log_file_dir) + with open(log_file_name, 'w+') as log_file_fp: + last_print_target = sys.stdout + sys.stdout = log_file_fp + + print('create_file_id_dic') + create_file_id_dic() + #print('create_mod_id_dic') + #create_mod_id_dic() + full_file_name_list = creat_src_file_list() + print('full_file*****') + print(full_file_name_list) + dst_full_file_name_list = conver_c_2_i(full_file_name_list) + print(dst_full_file_name_list) + cp_effect_content(dst_full_file_name_list) + + sys.stdout = last_print_target + exit(0) + +if __name__ == '__main__': + mk_prim_main() diff --git a/sdk_liteos/build/scripts/ota_builder b/sdk_liteos/build/scripts/ota_builder new file mode 100644 index 0000000000000000000000000000000000000000..e6f851ec314d54d325ec68dbd0335beb9da219af Binary files /dev/null and b/sdk_liteos/build/scripts/ota_builder differ diff --git a/sdk_liteos/build/scripts/packet_create.py b/sdk_liteos/build/scripts/packet_create.py new file mode 100644 index 0000000000000000000000000000000000000000..5236d2c0924eb94c89dc5ed817afb507b53480c8 --- /dev/null +++ b/sdk_liteos/build/scripts/packet_create.py @@ -0,0 +1,199 @@ +#!/usr/bin/env python3 +# coding=utf-8 + +''' +* Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +* Description: packet allinone bin file +''' +import struct +import sys +import os + +class crc16: + POLYNOMIAL = 0x1021 + PRESET = 0x0000 + _tab = [] + def __init__(self): + self._tab = [self._initial(i) for i in range(256)] + + def _initial(self, c): + crc = 0 + c = c << 8 + for j in range(8): + if (crc ^ c) & 0x8000: + crc = (crc << 1) ^ self.POLYNOMIAL + else: + crc = crc << 1 + c = c << 1 + return crc + + def _update_crc(self, crc, c): + cc = 0xff & int(c) + + tmp = (crc >> 8) ^ cc + crc = (crc << 8) ^ self._tab[tmp & 0xff] + crc = crc & 0xffff + + return crc + + def crc(self, str): + crc = self.PRESET + for c in str: + crc = self._update_crc(crc, ord(c)) + return crc + + def crcb(self, i): + crc = self.PRESET + for c in i: + crc = self._update_crc(crc, c) + return crc + +t = crc16() +def packet_bin(outputPath, inputList): + pathList = [] + burnAddrList = [] + burnSizeList = [] + imageSizeList = [] + typeList = [] + for item in inputList: + path, burnAddr, burnSize, type = item.split("|") + imageSize = os.path.getsize(path) + pathList.append(path) + burnAddrList.append(int(burnAddr)) + burnSizeList.append(int(burnSize)) + imageSizeList.append(imageSize) + typeList.append(int(type)) + + print(pathList) + print(burnAddrList) + print(burnSizeList) + print(imageSizeList) + print(typeList) + + flag = 0xefbeaddf + print(flag) + crc = 0 + imageNum = len(pathList) + headLen = imageNum*52 + 12 + totalFileSize = sum(imageSizeList) + headLen + + with open(outputPath, 'wb+') as file: + file.write(struct.pack('IHHI', flag, crc, imageNum, totalFileSize)) + startIndex = headLen + times = 0 + for path in pathList: + pathName = os.path.basename(path) + file.write( + struct.pack('32sIIIII', bytes(pathName, 'ascii'), startIndex, imageSizeList[times], burnAddrList[times], + burnSizeList[times], typeList[times])) + startIndex = startIndex + imageSizeList[times] + 16 + times += 1 + + for path in pathList: + with open(path, 'rb+') as subfile: + data = subfile.read() + file.write(data) + file.write(struct.pack('IIII', 0, 0, 0, 0)) + + file.flush() + file.seek(6) + newdata = file.read(headLen - 6) + crc16 = t.crcb(newdata) + file.seek(4) + file.write(struct.pack('H', crc16)) + +if __name__=="__main__": + print("main") + args = len(sys.argv) + argv = sys.argv + print(args) + print(argv) + if(args <= 2): + print("param should be : python main.py \"outputPath\" \"name|burnAddr|burnSize|type\"...") + ''' + enum IMAGE_TYPE { + IMAGE_TYPE_LOADER, + IMAGE_TYPE_NORMAL, + IMAGE_TYPE_PARAM, + IMAGE_TYPE_EFUSE, + IMAGE_TYPE_OTP, + IMAGE_TYPE_FORMALBIN, + }; + ''' + sys.exit() + + outputPath = argv[1] + print(outputPath) + del argv[1] + del argv[0] + packet_bin(outputPath, argv) + +'''' +pathList = [] +burnAddrList = [] +burnSizeList = [] +imageSizeList = [] +typeList = [] + +for arg in argv: + path, burnAddr, burnSize, type = arg.split("|") + imageSize = os.path.getsize(path) + pathList.append(path) + burnAddrList.append(int(burnAddr)) + burnSizeList.append(int(burnSize)) + imageSizeList.append(imageSize) + typeList.append(int(type)) + +print(pathList) +print(burnAddrList) +print(burnSizeList) +print(imageSizeList) +print(typeList) + +flag = 0xefbeaddf +print(flag) +crc = 0 +imageNum = len(pathList) +headLen = imageNum*52 + 12 +totalFileSize = sum(imageSizeList) + headLen + +file = open(outputPath, 'wb+') + +file.write(struct.pack('IHHI', flag, crc, imageNum, totalFileSize)) +startIndex = headLen +times = 0 +for path in pathList: + pathName = path.split("\\")[-1] + file.write(struct.pack('32sIIIII', bytes(pathName, 'ascii'), startIndex, imageSizeList[times], burnAddrList[times], + burnSizeList[times], typeList[times])) + startIndex = startIndex + imageSizeList[times] + 16 + times += 1 + +for path in pathList: + subfile = open(path, 'rb+') + data = subfile.read() + file.write(data) + file.write(struct.pack('IIII', 0, 0, 0, 0)) + +file.flush() +file.seek(6) +newdata = file.read(headLen - 6) +t = crc16() +crc16 = t.crcb(newdata) +file.seek(4) +file.write(struct.pack('H', crc16)) +file.close() +''''' + diff --git a/sdk_liteos/build/scripts/pkt_builder.py b/sdk_liteos/build/scripts/pkt_builder.py new file mode 100755 index 0000000000000000000000000000000000000000..edee64bb3abbec0606b88469efc42cfccbbf1aa9 --- /dev/null +++ b/sdk_liteos/build/scripts/pkt_builder.py @@ -0,0 +1,440 @@ +#!/usr/bin/env python3 +# coding=utf-8 + +''' +* Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +* Description: hupg main build scripts +''' + +import os +import time +import sys +import make_upg_file as MAKE_IMAGE +from packet_create import packet_bin +from scons_utils import scons_get_cfg_val +import shutil + +root_path = os.path.join(os.getcwd(), '..', '..') if getattr(sys, 'frozen', False) else os.path.join(os.path.dirname(__file__), '..', '..') +print('execute ota_builder with exe...') if getattr(sys, 'frozen', False) else print('execute ota_builder with python...') +class ImageBuild: + def __init__(self, app_name="Hi3861_demo", sign_alg=0x3F, kernel_file_ver=0, flashboot_file_ver=0, chip_product="Hi3861", usr_realtive_output='', ota_mode=0): + self.__app_name = app_name + self.__bootBinPath = os.path.join(root_path, usr_realtive_output, 'build', 'flashboot', 'Hi3861_flash_boot.bin') + self.__kernelBinPath = os.path.join(root_path, usr_realtive_output, 'output', 'bin', '%s_non_rom.bin'%self.__app_name) + self.__normalNvPath = os.path.join(root_path, 'build', 'build_tmp', 'nv', '%s_normal.hnv'%app_name) + self.__factoryNvPath = os.path.join(root_path, 'build', 'build_tmp', 'nv', '%s_factory.hnv'%app_name) + self.__pktPath = os.path.join(root_path, usr_realtive_output, 'output', 'bin') + self.__key_dir_path = os.path.join(root_path, 'tools', 'sign_tool') + self.__lzma_tool_path = os.path.join(root_path, r'tools', r'lzma_tool', r'lzma_tool') + self.__build_tmp_path = os.path.join(root_path, usr_realtive_output, 'output', 'bin') + self.__image_id = 0x3C78961E + self.__kernel_file_ver = kernel_file_ver + self.__flashboot_file_ver = flashboot_file_ver + self.__encrypt_flag = 0x42 + self.__sign_alg = sign_alg + self.__boot_bin_max_size = 32*1024 #32K + self.__kernel_1st_bin_max_size = 912*1024 #912K + self.__kernel_2nd_bin_max_size = 968*1024 #968K + self.__kernel_bin_max_size = self.__kernel_1st_bin_max_size + self.__kernel_upg_max_size = (912 + 968) * 1024 + self.__factory_bin_max_size = 600*1024 #600K + self.__chip_product_name = chip_product + self.__file_attr_encrypt = 0x2 # encrypt + self.__kernel_file_attr_ota = 0x4 # compression ota + self.__flashboot_file_attr_ota = 0x4 # compression ota + self.__ota_mode = ota_mode #0:compression ota; 1: dual partition ota + + def set_file_attr_encrypt(self, attr_encrypt): + self.__file_attr_encrypt = attr_encrypt + + def set_kernel_file_attr_ota(self, attr_ota): + if attr_ota == 'A': + attr_ota = 1 + elif attr_ota == 'B': + attr_ota = 2 + self.__kernel_file_attr_ota = attr_ota + + def set_flashboot_file_attr_ota(self, attr_ota): + self.__flashboot_file_attr_ota = attr_ota + + def set_chip_product_name(self, name): + self.__chip_product_name = name + + def set_kernel_max_size(self, signature): + if signature == 'A': + self.__kernel_bin_max_size = self.__kernel_1st_bin_max_size + elif signature == 'B': + self.__kernel_bin_max_size = self.__kernel_2nd_bin_max_size + elif signature == 0: + self.__kernel_bin_max_size = self.__kernel_upg_max_size + elif signature == 4: + self.__kernel_bin_max_size = self.__factory_bin_max_size + else: + sys.exit("[ERR]signature err: < %s >, from: %s"%(signature, os.path.realpath(__file__))) + + def set_src_path(self, boot_bin_path = None, kernel_bin_path = None, normal_nv_path = None, factory_nv_path = None): + self.__bootBinPath = boot_bin_path if boot_bin_path is not None else self.__bootBinPath + self.__kernelBinPath = kernel_bin_path if kernel_bin_path is not None else self.__kernelBinPath + self.__normalNvPath = normal_nv_path if normal_nv_path is not None else self.__normalNvPath + self.__factoryNvPath = factory_nv_path if factory_nv_path is not None else self.__factoryNvPath + + def set_pkt_path(self, pkt_dir_path): + self.__pktPath = pkt_dir_path + + def set_build_temp_path(self, build_temp_path): + self.__build_tmp_path = build_temp_path + + def set_app_name(self, app_name): + self.__app_name = app_name + + def set_image_id(self, image_id): + self.__image_id = image_id + + def set_kernel_file_ver(self, file_version): + self.__kernel_file_ver = file_version + + def set_flashboot_file_ver(self, file_version): + self.__flashboot_file_ver = file_version + + def get_kernel_file_ver(self): + return self.__kernel_file_ver + + def get_flashboot_file_ver(self): + return self.__flashboot_file_ver + + def set_encrypt_flag(self, encrypt_flag): + self.__encrypt_flag = encrypt_flag + + def set_sign_alg(self, sign_alg): + self.__sign_alg = sign_alg + + def dual_partion_ota_work(self, signature = None): + self.BuildUpgBoot() + #制作升级文件和烧写文件先后顺序不能调整 + #self.set_encrypt_flag(0xFF) #顺序不能调整,需要在编译flupgbin结束后设置 + self.BuildUpgBin() + self.BuildHiburnBin() + + def compress_ota_work(self, signature = None): + app_name = self.__app_name + pkt_dir_path = self.__pktPath + ota_ori_file = os.path.join(pkt_dir_path, '%s_ota_tmp.bin'%app_name) + self.BuildUpgBoot() + #制作升级文件和烧写文件先后顺序不能调整 + self.BuildUpgBin(target = ota_ori_file) + self.BuildHiburnBin(ota_file = ota_ori_file) + #self.set_encrypt_flag(0xFF) #顺序不能调整,需要在编译upgbin结束后设置 + self.BuildCompressUpgBin(ota_file = ota_ori_file) + + def BuildUpgBoot(self, target = None, source = None): + app_name = self.__app_name + pkt_dir_path = self.__pktPath + file_attr = (self.__file_attr_encrypt << 6) + self.__flashboot_file_attr_ota + + #bootupg配置 + flash_boot_file = self.__bootBinPath + if not os.path.exists(flash_boot_file): + print("flash_boot_file from: ", flash_boot_file) + sys.exit("[ERR]flash boot file is not exist, from: %s"%os.path.realpath(__file__)) + + # 构造输出文件名 # + image_file = os.path.join(pkt_dir_path, '%s_flash_boot_ota.bin'%app_name) if target is None else target + print("********************package boot upgrade file********************") + MAKE_IMAGE.make_bootupg(self.__image_id, self.__flashboot_file_ver, self.__encrypt_flag, flash_boot_file, image_file, self.__key_dir_path, self.__boot_bin_max_size, self.__sign_alg, self.__chip_product_name, file_attr) + return image_file + + def BuildUpgBin(self, target = None): + app_name = self.__app_name + pkt_dir_path = self.__pktPath + file_attr = (self.__file_attr_encrypt << 6) + self.__kernel_file_attr_ota + + #升级文件配置 + kernel_file = self.__kernelBinPath + normal_nv_file = self.__normalNvPath + if not os.path.exists(normal_nv_file): + print("normal_nv_file from: ", normal_nv_file) + sys.exit("[ERR]normal nv file is not exist, from: %s"%os.path.realpath(__file__)) + + if not os.path.exists(kernel_file): + print("kernel_file from: ", kernel_file) + sys.exit("[ERR]kernel file is not exist, from: %s"%os.path.realpath(__file__)) + + # 构造输出文件名 # + image_file = os.path.join(pkt_dir_path, '%s_ota.bin'%app_name) if target is None else target + print("********************package kernel&nv upgrade file********************") + MAKE_IMAGE.make_hupg(self.__image_id, self.__kernel_file_ver, self.__encrypt_flag, kernel_file, normal_nv_file, image_file, self.__key_dir_path, self.__kernel_bin_max_size, self.__sign_alg, self.__chip_product_name, file_attr) + return image_file + + def BuildUpgBurnBin(self, target = None): + app_name = self.__app_name + pkt_dir_path = self.__build_tmp_path + file_attr = (self.__file_attr_encrypt << 6) + self.__kernel_file_attr_ota + + #升级文件配置 + kernel_file = self.__kernelBinPath + normal_nv_file = self.__normalNvPath + if not os.path.exists(normal_nv_file): + print("normal_nv_file from: ", normal_nv_file) + sys.exit("[ERR]normal nv file is not exist, from: %s"%os.path.realpath(__file__)) + + if not os.path.exists(kernel_file): + print("kernel_file from: ", kernel_file) + sys.exit("[ERR]kernel file is not exist, from: %s"%os.path.realpath(__file__)) + + # 构造输出文件名 # + image_file = os.path.join(pkt_dir_path, '%s_ota_unencrypt.bin'%app_name) if target is None else target + print("********************package kernel&nv upgrade file********************") + MAKE_IMAGE.make_hupg(self.__image_id, self.__kernel_file_ver, 0x42, kernel_file, normal_nv_file, image_file, self.__key_dir_path, self.__kernel_bin_max_size, self.__sign_alg, self.__chip_product_name, file_attr) + return image_file + + def BuildHiburnBin(self, burn_bin = None, ota_file = None): + app_name = self.__app_name + pkt_dir_path = self.__pktPath + ota_mode = self.__ota_mode + + #烧写文件配置 + flash_boot_file = self.__bootBinPath + factory_nv_file = self.__factoryNvPath + normal_nv_file = self.__normalNvPath + if ota_mode == 1: + upg_file = self.BuildUpgBurnBin() + else: + upg_file = os.path.join(pkt_dir_path, '%s_%s.%s'%(app_name, 'ota', 'bin')) if ota_file is None else ota_file + + if not os.path.exists(flash_boot_file): + print("flash_boot_file from: ", flash_boot_file) + sys.exit("[ERR]flash boot file is not exist, from: %s"%os.path.realpath(__file__)) + + if not os.path.exists(factory_nv_file): + print("factory_nv_file from: ", factory_nv_file) + sys.exit("[ERR]factory nv file is not exist, from: %s"%os.path.realpath(__file__)) + + if not os.path.exists(normal_nv_file): + print("normal_nv_file from: ", normal_nv_file) + sys.exit("[ERR]normal nv file is not exist, from: %s"%os.path.realpath(__file__)) + + if not os.path.exists(upg_file): + print("ota file from: ", upg_file) + sys.exit("[ERR]ota file is not exist, from: %s"%os.path.realpath(__file__)) + + # 构造输出文件名 # + image_file = os.path.join(pkt_dir_path, '%s_burn.bin'%app_name) if burn_bin is None else burn_bin + print("********************package hiburn file********************") + MAKE_IMAGE.make_hbin(flash_boot_file, factory_nv_file, normal_nv_file, upg_file, image_file) + return image_file + + def BuildCompressUpgBin(self, compress_ota_bin = None, ota_file = None): + app_name = self.__app_name + pkt_dir_path = self.__pktPath + file_attr = (self.__file_attr_encrypt << 6) + self.__kernel_file_attr_ota + + #制作压缩升级文件依赖文件 + upg_file = os.path.join(pkt_dir_path, '%s_%s.%s'%(app_name, 'ota', 'bin')) if ota_file == None else ota_file + + if not os.path.exists(upg_file): + print("compress ota file from: ", upg_file) + sys.exit("[ERR]ota file is not exist, from: %s"%os.path.realpath(__file__)) + + # 构造输出文件名 # + image_file = os.path.join(pkt_dir_path, '%s_ota.bin'%app_name) if compress_ota_bin == None else compress_ota_bin + print("********************package compress upgrade file********************") + MAKE_IMAGE.make_compress_hupg(self.__image_id, self.__kernel_file_ver, self.__encrypt_flag, upg_file, image_file, self.__key_dir_path, self.__kernel_upg_max_size, self.__sign_alg, self.__lzma_tool_path, self.__build_tmp_path, self.__chip_product_name, file_attr) + return image_file + +# main function # +if __name__ == '__main__': + args = len(sys.argv) + list = ['boot_ota', 'ota', 'burn_bin', 'ota_compress', 'factory_bin'] + if args >= 6 and sys.argv[1] in list: + type = sys.argv[1] + app_name = sys.argv[2] + sign_alg = int(sys.argv[3], 16) + kernel_file_ver = int(sys.argv[4]) + flashboot_file_ver = int(sys.argv[5]) + target = sys.argv[6] + usr_output = sys.argv[7].split('=')[1] if len(sys.argv[7].split('='))==2 else '' + ota_flag = 1 if scons_get_cfg_val('CONFIG_COMPRESSION_OTA_SUPPORT') != 'y' else 0 + chip_product = 'Hi3861' if scons_get_cfg_val('CONFIG_TARGET_CHIP_HI3861') == 'y' else 'Hi3861L' + fu = ImageBuild(app_name, sign_alg, kernel_file_ver, flashboot_file_ver, chip_product, usr_realtive_output=usr_output, ota_mode=ota_flag) + fu.set_pkt_path(os.path.join(root_path, usr_output, 'output', 'bin')) + bootBinPath = os.path.join(root_path, usr_output, 'output', 'bin', '%s_boot_signed.bin'%chip_product) + fu.set_src_path(bootBinPath) + fu.set_file_attr_encrypt(0x1) if scons_get_cfg_val('CONFIG_FLASH_ENCRYPT_SUPPORT') != 'y' else None + fu.set_flashboot_file_attr_ota(0x3) if scons_get_cfg_val('CONFIG_COMPRESSION_OTA_SUPPORT') != 'y' else None + fu.set_encrypt_flag(0x42) + + version_bin = bytearray(8) + boot_ver_bytes = flashboot_file_ver.to_bytes(4, byteorder = 'little', signed = True) + kernel_ver_bytes = kernel_file_ver.to_bytes(4, byteorder = 'little', signed = True) + version_bin[0:4] = boot_ver_bytes + version_bin[4:8] = kernel_ver_bytes + version_file = os.path.join(os.path.dirname(target), '%s_vercfg.bin'%app_name) + + if type == 'boot_ota': + print('boot_ota') + fu.BuildUpgBoot(target) + elif type == 'ota': + print('ota') + kernelBinPath = sys.argv[8] + sign = sys.argv[9] + fu.set_src_path(kernel_bin_path = kernelBinPath) + fu.set_kernel_max_size(sign) if scons_get_cfg_val('CONFIG_COMPRESSION_OTA_SUPPORT') != 'y' else fu.set_kernel_max_size(0) + fu.set_kernel_file_attr_ota(sign) if scons_get_cfg_val('CONFIG_COMPRESSION_OTA_SUPPORT') != 'y' else None + if (scons_get_cfg_val('CONFIG_COMPRESSION_OTA_SUPPORT') != 'y') and (scons_get_cfg_val('CONFIG_FLASH_ENCRYPT_SUPPORT') == 'y'): + fu.set_encrypt_flag(0xFF) + fu.BuildUpgBin(target) + elif type == 'factory_bin': + print('factory_bin') + kernelBinPath = sys.argv[8] + fu.set_src_path(kernel_bin_path = kernelBinPath) + fu.set_kernel_max_size(0x4) + fu.set_kernel_file_attr_ota('A') + fu.BuildUpgBin(target) + elif type == 'burn_bin': + print('burn_bin') + ota_bin = None if scons_get_cfg_val('CONFIG_COMPRESSION_OTA_SUPPORT') != 'y' else sys.argv[8] + fu.set_src_path(kernel_bin_path = sys.argv[8]) if scons_get_cfg_val('CONFIG_COMPRESSION_OTA_SUPPORT') != 'y' else None + fu.set_build_temp_path(build_temp_path = os.path.join(root_path, 'build', 'build_tmp', 'cache')) + fu.BuildHiburnBin(target, ota_bin) + with open(version_file, 'wb+') as fp: + fp.write(version_bin) + + hilink_enable = False + if (scons_get_cfg_val('CONFIG_HILINK') == 'y'): + hilink_enable = True + + burn_for_erase_bin = os.path.join(root_path, 'build', 'basebin', 'burn_for_erase_4k.bin') + allinone = os.path.join(os.path.dirname(target), '%s_allinone.bin'%app_name) + loader_bin = os.path.join(os.path.dirname(target), '%s_loader_signed.bin'%chip_product) + efuse_bin = os.path.join(root_path, 'build', 'basebin', 'efuse_cfg.bin') + efuse_bin = None if not os.path.exists(efuse_bin) else efuse_bin + boot_b = os.path.join(os.path.dirname(target), "%s_boot_signed_B.bin"%(chip_product)) + boot_b_size = os.path.getsize(boot_b) + factory_bin_path = os.path.join(root_path, 'build', 'libs', 'factory_bin') + factory_bin = os.path.join(factory_bin_path, '%s_factory.bin'%app_name) + #证书安全存储示例 + tee_cert1_file = os.path.join(root_path, 'build', 'basebin', 'tee_cert1.bin'); + tee_cert2_file = os.path.join(root_path, 'build', 'basebin', 'tee_cert2.bin'); + tee_key_file = os.path.join(root_path, 'build', 'basebin', 'tee_key.bin'); + tee_cert_key_bin_max = 12*1024; #必须为4KB证书倍,需匹配分区表确定烧写地址和大小 + tee_total_file_cnt = 3; #3个文件:2个证书,1个key。 + burn_tee_cert = False + if ((os.path.exists(tee_cert1_file)) and (os.path.exists(tee_cert2_file)) and (os.path.exists(tee_key_file))): + burn_tee_cert = True + + burn_bin_ease_size = 0x200000; + if (hilink_enable == True): + burn_bin_ease_size = 0x200000 - 0x8000 - 0x1000 - 0x2000 + if (burn_tee_cert == True): + burn_bin_ease_size = 0x200000 - 0x8000 - 0x1000 - 0x2000 - 0x5000 + + if os.path.exists(factory_bin): + list = ['%s|0|0|0'%loader_bin, '%s|0|0|3'%efuse_bin, '%s|0|%d|1'%(target, burn_bin_ease_size), '%s|%d|%d|6'%(factory_bin, 0x14D000, 0x96000)] if efuse_bin!=None else ['%s|0|0|0'%loader_bin, '%s|0|%d|1'%(target, burn_bin_ease_size), '%s|%d|%d|6'%(factory_bin, 0x14D000, 0x96000)] + shutil.copytree(factory_bin_path, os.path.join(os.path.dirname(target), 'factory_bin')) + else: + list = ['%s|0|0|0'%loader_bin, '%s|0|0|3'%efuse_bin, '%s|0|%d|1'%(target, burn_bin_ease_size)] if efuse_bin!=None else ['%s|0|0|0'%loader_bin, '%s|0|%d|1'%(target, burn_bin_ease_size)] + + if ((hilink_enable == True) or (burn_tee_cert == True)): + list.append('%s|%d|%d|1'%(burn_for_erase_bin, 0x200000 - 0x8000 - 0x1000, 0x1000)) + + list.append('%s|%d|%d|1'%(boot_b, 0x200000 - boot_b_size, boot_b_size)); + + if (burn_tee_cert == True): + cert_key_bin = bytearray(tee_cert_key_bin_max) + tee_cert1_size = os.path.getsize(tee_cert1_file) + tee_cert2_size = os.path.getsize(tee_cert2_file) + tee_key_size = os.path.getsize(tee_key_file) + total_cert_key_size = tee_cert1_size + tee_cert2_size + tee_key_size + if (total_cert_key_size > tee_cert_key_bin_max - 4 - 4 - 4*tee_total_file_cnt): + print('[ERROR]: cert total len bigger than tee_cert_key_bin_max!!!') + sys.exit(1) + else: + with open(tee_cert1_file, 'rb') as fp: + tee_cert1_bin = fp.read() + with open(tee_cert2_file, 'rb') as fp: + tee_cert2_bin = fp.read() + with open(tee_key_file, 'rb') as fp: + tee_key_bin = fp.read() + + #填充头部结构 + start_flag = 0xDEADBEEF + start_flag_bytes = start_flag.to_bytes(4, byteorder = 'little', signed = False) + cert_key_bin[0:4] = start_flag_bytes #填充魔术字 + tee_total_file_cnt_bytes = tee_total_file_cnt.to_bytes(4, byteorder = 'little', signed = True) + cert_key_bin[4:8] = tee_total_file_cnt_bytes #填充总的文件数 + #填充各文件的大小 + cert_key_bin[8:12] = tee_cert1_size.to_bytes(4, byteorder = 'little', signed = True) + cert_key_bin[12:16] = tee_cert2_size.to_bytes(4, byteorder = 'little', signed = True) + cert_key_bin[16:20] = tee_key_size.to_bytes(4, byteorder = 'little', signed = True) + #填充各文件 + cert_key_bin[20:20 + tee_cert1_size] = tee_cert1_bin + cert_key_bin[20 + tee_cert1_size:20 + tee_cert1_size + tee_cert2_size] = tee_cert2_bin + cert_key_bin[20 + tee_cert1_size + tee_cert2_size:20 + tee_cert1_size + tee_cert2_size + tee_key_size] = tee_key_bin + #写文件 + cert_bin_file = os.path.join(root_path, "output", "bin", '%s_tee_cert_key.bin'%app_name) + with open(cert_bin_file, 'wb+') as fp: + fp.write(cert_key_bin) + list.append('%s|%d|%d|1'%(cert_bin_file, 0x200000 - 0x8000 - 0x1000 - 0x2000 - 0x5000, tee_cert_key_bin_max)) + + if (sign_alg != 0x3F): #only need write ver file in secure boot mode. + list.append('%s|0|0|7'%version_file) + packet_bin(allinone, list) + if os.path.exists(factory_bin_path): + shutil.rmtree(factory_bin_path) + elif type == 'ota_compress': + print('ota_compress') + ota_bin = sys.argv[8] + fu.set_kernel_file_attr_ota(0x4) + fu.set_kernel_max_size(0) #(912+968)KB + fu.set_build_temp_path(build_temp_path = os.path.dirname(ota_bin)) + if scons_get_cfg_val('CONFIG_FLASH_ENCRYPT_SUPPORT') == 'y': + fu.set_encrypt_flag(0xFF) + fu.BuildCompressUpgBin(target, ota_bin) + elif args == 5 or args == 3: + sign_alg = int(sys.argv[1], 16) + dual_ota_flag = sys.argv[2] + flashboot_file_ver = 0 if args != 5 else int(sys.argv[3]) + kernel_file_ver = 0 if args != 5 else int(sys.argv[4]) + lib_path = os.path.join(root_path, 'build', 'scripts') + sys.path.append(lib_path) + from hi_config_parser import UsrCfgParser + + class BaseCfgParser(UsrCfgParser): + def get_default_config_file(self): + return os.path.join(root_path, 'platform', 'os', 'Huawei_LiteOS', '.config') + + options = BaseCfgParser().do_parse() + chip_product = options.get('LOSCFG_COMPILER_CHIP_VER') + app_name = chip_product + '_demo' + if app_name: + app_name = app_name.strip('"') + + t1 = time.time() + print("&&&&&&&&&&&&&args", sign_alg, dual_ota_flag, flashboot_file_ver, kernel_file_ver) + fu = ImageBuild(app_name, sign_alg, kernel_file_ver, flashboot_file_ver, chip_product, ota_mode=int(dual_ota_flag)) + fu.set_encrypt_flag(0x42) + if int(dual_ota_flag) == 0: + fu.set_kernel_max_size(0) + fu.compress_ota_work() + else: + fu.set_kernel_file_attr_ota('A') #kernelA + fu.set_flashboot_file_attr_ota(0x3) #kernelA|kernelB + fu.dual_partion_ota_work() + + print ("Package finish!! \r\n") + print('TOTAL TIME:%ss'%str(time.time() - t1)) + else: + print('[ERROR]: build ota parameters err!!!') + sys.exit(1) diff --git a/sdk_liteos/build/scripts/scons_app.py b/sdk_liteos/build/scripts/scons_app.py new file mode 100644 index 0000000000000000000000000000000000000000..69bf700b166ff483592580c5af60857b5dceb659 --- /dev/null +++ b/sdk_liteos/build/scripts/scons_app.py @@ -0,0 +1,160 @@ +#!/usr/bin/env python3 +# coding=utf-8 + +''' +* Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +* Description: APP utilities +''' + +import os +import json +from scripts.common_env import insert_module +from scripts.common_env import insert_module_dir +from scripts.common_env import insert_lib_cfg +from scripts.common_env import insert_env_defs +from scripts.common_env import insert_os_include +from scripts.common_env import insert_common_include +from scripts.common_env import insert_ar_flags +from scripts.common_env import insert_as_flags +from scripts.common_env import insert_ld_flags +from scripts.common_env import insert_cc_flags +from scripts.common_env import set_factory_mode +from scons_utils import colors + +__all__ = ["AppTarget"] + +class AppBuildError(Exception): + """ + Build exception. + """ + pass + +class AppTarget: + """ + APP config + """ + def __init__(self, app_name, factory_mode): + self.app_name = app_name + self.factory_mode = factory_mode + self.app_env = None + self.app_cfg_file = None + self.proj_root = os.path.realpath(os.path.join(__file__, '..', '..', '..')) + self.app_root = self.app_lookup() + self.settings = {} + self.app_ld_dirs = [] + + def app_lookup(self): + """ + Found app folder. + """ + dirs = os.listdir(os.path.join(self.proj_root, 'app')) + if self.app_name in dirs: + return os.path.join('app', self.app_name) + raise AppBuildError("%s============== Can NOT found the APP project --- %s! =============%s" % + (colors['red'], self.app_name, colors['end'])) + + def read_env(self): + """ + Parse app settings + """ + if self.app_pre_check() is False: + return; + try: + with open(self.app_cfg_file) as app_cfg: + self.settings = json.load(app_cfg) + except Exception as e: + raise AppBuildError("%s============== Read APP settings error: %s! =============%s" % + (colors['red'], e, colors['end'])) + + self.app_env_parse(self.settings) + pass + + def get_app_libs(self): + """ + Parse app libraries + """ + libs = [] + for folder in self.app_ld_dirs: + libs.extend([lib[3:-2] for lib in os.listdir(folder) if lib.startswith('lib') and lib.endswith('.a')]) + return list(map(lambda x:'-l%s'%x, libs)) + + def get_app_lib_path(self): + """ + Parse app library path + """ + if len(self.app_ld_dirs) > 0: + return list(map(lambda x:'-L%s'%x, self.app_ld_dirs)) + return [] + + def get_app_name(self): + return self.app_name + + def get_app_cfg(self, key): + return self.settings.get(key, None) + + def app_pre_check(self): + app_scons = os.path.join(self.proj_root, self.app_root, 'SConscript') + if os.path.isfile(app_scons) == False: + raise AppBuildError("%s============== Can NOT found the APP %s! =============%s" % + (colors['red'], app_scons, colors['end'])) + self.app_cfg_file = os.path.join(self.proj_root, self.app_root, 'app.json') + if os.path.isfile(self.app_cfg_file) == False: + raise AppBuildError("%s============== Can NOT found the APP %s! =============%s" % + (colors['red'], self.app_cfg_file, colors['end'])) + return True + + def app_env_parse(self, settings): + try: + insert_module(self.app_name) + insert_module_dir(self.app_name, self.app_root) + insert_lib_cfg(self.app_name, {settings["TARGET_LIB"] : settings["APP_SRCS"]}) + + if settings.get("DEFINES") is not None: + insert_env_defs(self.app_name, settings["DEFINES"]) + + if settings.get("OS_INCLUDE") is not None: + insert_os_include(self.app_name, settings["OS_INCLUDE"]) + if settings.get("INCLUDE") is not None: + incs = [] + for inc in settings["INCLUDE"]: + incs.append(os.path.join('#', inc)); + insert_common_include(self.app_name, incs) + + if settings.get("LD_DIRS") is not None: + self.app_ld_dirs.extend(settings.get("LD_DIRS")) + if settings.get("AR_FLAGS") is not None: + insert_ar_flags(self.app_name, settings["AR_FLAGS"]) + if settings.get("LD_FLAGS") is not None: + insert_ld_flags(self.app_name, settings["LD_FLAGS"]) + if settings.get("CC_FLAGS") is not None: + insert_cc_flags(self.app_name, settings["CC_FLAGS"]) + if settings.get("AS_FLAGS") is not None: + insert_as_flags(self.app_name, settings["AS_FLAGS"]) + if self.factory_mode == 'yes': + set_factory_mode() + except Exception as e: + raise AppBuildError("%s============== APP settings error: %s! =============%s" % + (colors['red'], e, colors['end'])) + +""" +for test only +""" +def test(): + app_obj = AppTarget('demo') + app_obj.read_env() + +if __name__ == '__main__': + test() + diff --git a/sdk_liteos/build/scripts/scons_env_cfg.py b/sdk_liteos/build/scripts/scons_env_cfg.py new file mode 100644 index 0000000000000000000000000000000000000000..bfb40a0f96f4028573faf721bc35c2faeed31405 --- /dev/null +++ b/sdk_liteos/build/scripts/scons_env_cfg.py @@ -0,0 +1,361 @@ +#!/usr/bin/env python3 +# coding=utf-8 + +''' +* Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +* Description: Default configrations of the project. +''' + +import os +import hashlib + +from scons_utils import colors +from scons_utils import flag_r +from scons_utils import flag +from scons_utils import scons_pre_check +from scons_utils import scons_usr_bool_option +from scons_utils import SconsBuildError +from scripts.common_env import * +from scripts.common_env import module_dir + +class SconsEnvCfg: + def __init__(self): + """ + Make sure compiler is ready + """ + if (scons_pre_check([]) == False): + raise SconsBuildError("%s============== COULD NOT FIND COMPILER! =============%s"% + (colors['red'], colors['end'])) + self.root = os.path.realpath(os.path.join(__file__, '..', '..', '..')) + self.os_root = os.path.realpath(os.path.join(self.root, 'platform', 'os', 'Huawei_LiteOS')) + self.tools_prefix = 'riscv32-unknown-elf-' + + #Set input/output folders + tmp_dir = os.path.join('build', 'build_tmp') + final_dir = 'output' + self.log_path = os.path.join(tmp_dir, 'logs') + self.obj_path = os.path.join(tmp_dir, 'objs') + self.lib_path = os.path.join(tmp_dir, 'libs') + self.cache_path = os.path.join(tmp_dir, 'cache') + self.link_path = os.path.join(tmp_dir, 'scripts') + self.nv_path = os.path.join(tmp_dir, 'nv') + self.bin_path = os.path.join(final_dir, 'bin') + + #NV settings. + self.nv_src_path = os.path.join('app', 'demo', 'nv') + self.nv_factory_name = 'hi3861_demo_factory.hnv' + self.nv_normal_name = 'hi3861_demo_normal.hnv' + #mss_nvi_db_fcc.xml FCC + #mss_nvi_db.xml CE + #mss_nvi_db_max.xml MAX_POWER + if scons_usr_bool_option('CONFIG_CE_SUPPORT') == 'y': + self.nv_cfg_name = 'mss_nvi_db.xml' + + if scons_usr_bool_option('CONFIG_FCC_SUPPORT') == 'y': + self.nv_cfg_name = 'mss_nvi_db_fcc.xml' + + if scons_usr_bool_option('CONFIG_MAX_POWER_SUPPORT') == 'y': + self.nv_cfg_name = 'mss_nvi_db_max.xml' + + #chip type + if scons_usr_bool_option('CONFIG_TARGET_CHIP_HI3861') == 'y': + self.chip_type = "Hi3861" + else: + self.chip_type = "Hi3861L" + + #Link settings + self.base_sum = 'd11133fff0d435d699e27817e165cf1d10c1a951452bd07d40da5bcfc41ef773' + self.link_file = os.path.join(self.link_path, 'link.lds') + self.map_file = os.path.join(self.bin_path, '%s_demo.map'%(self.chip_type)) + self.gcc_ver_num = '7.3.0' + self.app_name = None + self.target_name = None + self.app_builder = None + self.clean_list = [tmp_dir, final_dir] + self.clean_list.append(os.path.join('build', 'scripts', '__pycache__')) + + def set_tools(self, env, tool_name='all', tool_value='default'): + #set compiler + if tool_name != 'all' and tool_value != 'default' and env.get(tool_name): + env[tool_name] = tool_value + return + + if self.tools_prefix: + env['CC'] = '%sgcc'%self.tools_prefix + env['AR'] = '%sar'%self.tools_prefix + env['AS'] = '%sas'%self.tools_prefix + env['CXX'] = '%scpp'%self.tools_prefix + env['LINK'] = '%sld'%self.tools_prefix + env['RANLIB'] = '%sranlib'%self.tools_prefix + env['OBJCOPY'] = '%sobjcopy'%self.tools_prefix + env['OBJDUMP'] = '%sobjdump'%self.tools_prefix + else: + #default compiler without prefix, like gcc, g++, etc. + print("USE DEFAULT COMPILER...") + + def get_tools(self, env, tool_name): + if env.get(tool_name) is None: + print('Not find tool:%s'%tool_name) + return env.get(tool_name) + + def set_environs(self, env, env_name='all', env_value=None, module='common'): + #Set default compile environment. + if env_name != 'all' and env_value is not None and env.get(env_name): + env[env_name] = env_value + return + + env['CHIP_TYPE'] = self.chip_type + env['ARFLAGS'] = get_proj_env_value('ar_flags', module) + env.Append(CCFLAGS=get_proj_env_value('opts', module)) + env.Append(ASLAGS=get_proj_env_value('as_flags', module)) + env.Append(LINKFLAGS=get_proj_env_value('link_flags', module)) + env['LINK_SCRIPTS_FLAG'] = get_proj_env_value('link_scripts_flag', module) + env['CCCOMSTR'] = 'Compiling $SOURCE' + env['ARCOMSTR'] = 'Archiving $TARGET' + env.Append(CPPPATH=get_proj_env_value('common_inc_path', module)) + env.Append(CPPDEFINES=get_proj_env_value('defines', module)) + if get_proj_env_value('liteos_inc_path', module) is not None: + env.Append(CPPPATH = [os.path.join(self.os_root, x) for x in get_proj_env_value('liteos_inc_path', module)]) + + def append_environs(self, env, module, env_name = None): + if env_name is None: + env_name = [] + for key in get_proj_env(): + if get_proj_env_value(key, module) is not None: + env_name.append(flag_r[key]) + + for x in set(env_name): + if x != 'CPPPATH': + env[x].extend(get_proj_env_value(flag[x], module)) + else: + env[x].extend(get_proj_env_value('common_inc_path', module)) + if get_proj_env_value('liteos_inc_path', module) is not None: + env[x].extend([os.path.join(self.os_root, y) for y in get_proj_env_value('liteos_inc_path', module)]) + + def get_module_cfg(self, module, env_name, fixed=False): + if env_name != 'CPPPATH': + return get_proj_env_value(flag[env_name], module) + else: + cfg_list = [] + inc_path = get_proj_env_value('common_inc_path', module) + if inc_path is not None: + for x in inc_path: + if x.startswith('#'): + cfg_list.append(x[2:]) + else: + cfg_list.append(x) + if get_proj_env_value('liteos_inc_path', module) is not None: + cfg_list.extend([os.path.join(os.path.relpath(self.os_root, self.root), y) for y in get_proj_env_value('liteos_inc_path', module)]) + return cfg_list + + def get_module_dir(self, module): + """ + Get module folder. + """ + if module in module_dir: + return '%s'%(module_dir[module]) + else: + print('PROJECT HAS NO MODULE NAMED [%s]'%module) + sys.exit(1) + + def get_all_modules(self): + module_names = list(module_dir.keys()) + return module_names + + def get_module_libs(self, module, lib_name_only=False): + """ + Get build module library settings + """ + if module in proj_lib_cfg: + if lib_name_only == True: + return [lib_name for lib_name in proj_lib_cfg[module]] + else: + return proj_lib_cfg[module] + else: + print('PROJECT HAS NO MODULE NAMED [%s]'%module) + sys.exit(1) + + def get_build_modules(self): + """ + Get default build modules + """ + return compile_module + + def get_bootlib_path(self): + """ + Get boot library path to be inclouded. + """ + lib_paths = os_boot_path + return list(map(lambda x:'-L%s'%x, lib_paths)) + + def get_lib_path(self): + """ + Get library path to be inclouded. + """ + lib_paths = os_lib_path + gcc = '%sgcc'%self.tools_prefix + gcc_lib_path = '' + # found and include libgcc.a + env_path_param = os.environ['PATH'].split(':') + for param in env_path_param: + compiler = os.path.join(param, 'riscv32-unknown-elf-gcc') + if os.path.isfile(compiler): # make sure the dir is accessable + gcc_lib_path = param + break + + gcc_lib_path = os.path.join(gcc_lib_path, '..', 'lib', 'gcc', 'riscv32-unknown-elf', self.gcc_ver_num) + lib_paths.append(gcc_lib_path) + lib_paths.extend([os.path.join(self.lib_path, self.get_module_dir(module)) for module in self.get_build_modules()]) + lib_paths.append(self.link_path) + return list(map(lambda x:'-L%s'%x, lib_paths)) + + def get_boot_libs(self): + """ + Get library name to be inclouded. Linker option -l follows the lib name without + prefix "lib" and surffix ".a", has to remove those parts from a library file name. + """ + libs = [lib[3:-2] for lib in os.listdir(os.path.join(self.root, 'build', 'libs', 'boot_libs')) if lib.startswith('lib') and lib.endswith('.a')] + return libs + + def get_libs(self): + """ + Get library name to be inclouded. Linker option -l follows the lib name without + prefix "lib" and surffix ".a", has to remove those parts from a library file name. + """ + libs = [lib[3:-2] for lib in os.listdir(os.path.join(self.root, 'build', 'libs')) if lib.startswith('lib') and lib.endswith('.a')] + libs.append('gcc') + for module_lib in [self.get_module_libs(module, True) for module in self.get_build_modules()]: + libs.extend(module_lib) + if scons_usr_bool_option('CONFIG_I2S_SUPPORT') == 'n': + libs.remove('i2s') + if scons_usr_bool_option('CONFIG_HILINK') == 'y': + libs.extend(['hilinkdevicesdk', 'hilinkota']) + return libs + + def get_ohos_libs(self): + """ + Get library name to be inclouded. Linker option -l follows the lib name without + prefix "lib" and surffix ".a", has to remove those parts from a library file name. + """ + libs = [lib[3:-2] for lib in os.listdir(os.path.join(self.root, 'ohos', 'libs')) \ + if lib.startswith('lib') and lib.endswith('.a')] + return libs + + def del_tmp_files(self, file_path): + if os.path.isfile(file_path): + os.unlink(file_path) + + def base_bin_check(self, target): + """ + Check the output base bin everytime to make sure the binary would not break the core. + """ + sha256sum = '' + with open (target, "rb") as base_bin: + bytes = base_bin.read() + sha256sum = hashlib.sha256(bytes).hexdigest() + #self.del_tmp_files(target) + if self.base_sum == sha256sum: + return None + raise SconsBuildError("%s============== BASE BIN IS DIFFERENT WITH FIRST COMPILE! =============%s" % + (colors['red'], colors['end'])) + + def set_clean_items(self, items): + """ + Hook the clean items. Items would be deleted with "scons -c". + """ + if items is None: + return + if isinstance(items, list): + self.clean_list.extend(items) + return + if isinstance(items, str): + self.clean_list.append(items) + return + raise SconsBuildError("%s============== PLEASE INPUT A LIST OR A STRING! =============%s" % + (colors['red'], colors['end'])) + + def set_app_builder(self, builder): + """ + For new app. + """ + self.app_builder = builder + self.app_builder.read_env() + self.app_param_update(builder.get_app_name()) + + def app_param_update(self, app_name): + """ + Get settings for the new app. + """ + self.app_name = app_name + self.target_name = '%s_%s'%((self.chip_type), self.app_name) + self.map_file = os.path.join(self.bin_path, '%s_%s.map'%((self.chip_type), self.app_name)) + + self.nv_src_path = os.path.join('app', app_name, 'nv') + self.nv_factory_name = '%s_%s_factory.hnv'%((self.chip_type), app_name) + self.nv_normal_name = '%s_%s_normal.hnv'%((self.chip_type), app_name) + + if self.app_builder: + items = self.app_builder.get_app_cfg('CLEAN') + self.set_clean_items(items) + self.set_clean_items([os.path.join("tools", "nvtool", "out_nv_bin"), + os.path.join("tools", "nvtool", "__pycache__")]) + + def get_makefile_environs(self, module = 'common'): + makefile_environs = { + 'var' : { + 'RM':'rm -rf', + 'MAKE':'make', + 'MV':'mv', + 'MAKE_DIR':'mkdir -p', + + # set compiler + 'CC':'$(TOOLS_PREFIX)gcc', + 'AR':'$(TOOLS_PREFIX)ar', + 'AS':'$(TOOLS_PREFIX)as', + 'CXX':'$(TOOLS_PREFIX)cpp', + 'LINK':'$(TOOLS_PREFIX)ld', + 'RANLIB':'$(TOOLS_PREFIX)ranlib', + 'OBJCOPY':'$(TOOLS_PREFIX)objcopy', + 'OBJDUMP':'$(TOOLS_PREFIX)objdump', + 'NV_CFG_NAME':self.nv_cfg_name, + 'BASE_NUM': self.base_sum, + 'LOG_PATH': self.log_path, + 'OBJ_PATH': self.obj_path, + 'LIB_PATH': self.lib_path, + 'CACHE_PATH': self.cache_path, + 'LINK_PATH': self.link_path, + 'NV_PATH': self.nv_path + }, + 'append_var' : { + 'LIBPATH':'-L%s -L%s'%(' -L'.join(os_lib_path), self.link_path), + #'LIBS':'-l%s'%(' -l'.join(self.get_libs())), + 'LIBS':'-l%s'%(' -l'.join(['wifi', 'wifi_flash', 'system', 'litekernel_flash', 'gcc'])), + }, + 'mod_dir': { + } + } + + for mod in module_dir: + makefile_environs['mod_dir']['%s_dir'%mod] = module_dir[mod] + print('-'*50,'\n',makefile_environs) + # Set input/output folders + ''' + for flg in flag: + flg_cfg = self.get_module_cfg(module, flg, fixed=True) + if flg_cfg is None: + continue + makefile_environs[flg] = flg_cfg + ''' + return makefile_environs diff --git a/sdk_liteos/build/scripts/scons_utils.py b/sdk_liteos/build/scripts/scons_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..bd972518c1d50929cf414e9115474315865a7827 --- /dev/null +++ b/sdk_liteos/build/scripts/scons_utils.py @@ -0,0 +1,301 @@ +#!/usr/bin/env python3 +# coding=utf-8 + +''' +* Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +* Description: Utilities. +''' + +import os +import shutil +from copy import deepcopy + +from hi_config_parser import usr_cfg_main +from hi_config_parser import sys_cfg_main + +class SconsBuildError(Exception): + """ + Error exception. + """ + pass + +""" +Colors to display the messages. +""" +colors = {} +colors['cyan'] = '\033[96m' +colors['purple'] = '\033[95m' +colors['blue'] = '\033[94m' +colors['green'] = '\033[92m' +colors['yellow'] = '\033[93m' +colors['red'] = '\033[91m' +colors['end'] = '\033[0m' + +flag = { + 'ARFLAGS' : 'ar_flags', + 'CCFLAGS' : 'opts', #'cc_flags', + 'ASLAGS' : 'as_flags', + 'CPPDEFINES' : 'defines', + 'CPPPATH' : ['liteos_inc_path', 'common_inc_path'], + 'LINKFLAGS' : 'link_flags', + 'LINK_SCRIPTS_FLAG' : 'link_scripts_flag' +} + +flag_r = { + 'ar_flags' : 'ARFLAGS', + 'opts' : 'CCFLAGS', + 'as_flags' : 'ASLAGS', + 'defines' : 'CPPDEFINES', + 'liteos_inc_path' : 'CPPPATH', + 'common_inc_path' : 'CPPPATH', + 'link_flags' : 'LINKFLAGS', + 'link_scripts_flag' : 'LINK_SCRIPTS_FLAG' +} + +def traverse_subdir(search_dir = '.', full_path = False): + src_path = [] + for root, dirs, files in os.walk(search_dir): + if files != []: + src_path.append(os.path.relpath(root, search_dir)) if full_path == False else src_path.append(root) + print('relative dir:',os.path.relpath(root, search_dir) if full_path == False else root) + return src_path + +#compiler check +def scons_env_param_check(): + env_path_param = os.environ['PATH'].split(':') + for param in env_path_param: + compiler = os.path.join(param, 'riscv32-unknown-elf-gcc') + if os.path.isfile(compiler): + return True + return False + +#settings check +def scons_pre_check(dir_list): + if len(dir_list) > 0 : + for dir in dir_list: + os.makedir(dir) + usr_config_path = os.path.join('build', 'config', 'usr_config.mk') + if os.path.isfile(usr_config_path) == False: + shutil.copyfile(os.path.join('tools', 'menuconfig', 'default.config'), usr_config_path) + return scons_env_param_check() + +#delete files while compiling. +def cleanup(target, source, env): + for src in source: + name = str(src) + try: + if os.path.isfile(name): + os.remove(name) + elif os.path.isdir(name): + shutil.rmtree(name) + else: + print("%s not found! Skipped!"%src) + except: + print("Remove %s error! Skipped!"%src) + +#Display tips +def show_burn_tips(): + burn_tips_str = ''.join( + ["%s\n< ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ >\n"%colors['purple'], + " BUILD SUCCESS \n", + "< ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ >\n%s"%colors['end'] + ]) + print(burn_tips_str) + +#Display alert +def show_alert(msg): + print("%s%s%s"%(colors['red'], msg, colors['end'])) + +#Simple dd tool. +def scons_bin_dd(source, target, **kw): + seek = kw.get('seek') + skip = kw.get('skip') + count = kw.get('count') + bs = kw.get('bs', 1024) + data = None + img_data = None + if seek is not None: + with open(source, 'rb') as src: + data = bytearray(src.read()) + mode = 'ab+' + if os.path.exists(target): + mode = 'rb+' + with open(target, mode) as image: + image.seek(0, 1) + img_data = bytearray(image.read()) + with open(target, 'wb') as image: + if count is not None: + append_len = count*bs + else: + append_len = len(data) + old_len = len(img_data) + new_len = seek*bs + append_len + if new_len > old_len: + wr_data = bytearray(new_len) + if old_len > 0: + wr_data[0:old_len] = img_data + img_data = wr_data + img_data[seek*bs : new_len] = data[0 : append_len] + image.seek(0, 1) + image.write(img_data) + return True + if skip is not None: + with open(source, 'rb') as src: + src.seek(skip*bs) + data = src.read() + with open(target, 'wb') as image: + image.write(data) + return True + raise SconsBuildError("%s============== dd PARAMETER INPUT ERROR! =============%s"%(colors['red'], colors['end'])) + +def bf_to_str(bf): + if bf is None: + return '(unknown targets product None in list)' + elif bf.node: + return '%s: %s'%(str(bf.node), bf.errstr) + elif bf.filename: + return '%s: %s'%(bf.filename, bf.errstr) + else: + return str(bf) + +""" +Interfaces for reading the settings made by menuconfig. +""" +def scons_usr_string_option(option): + options = usr_cfg_main() + value = options.get(option) + if value: + value = value.strip('"') + return value + +def scons_usr_int_option(option): + options = usr_cfg_main() + return int(options.get(option)) + +def scons_usr_bool_option(option): + options = usr_cfg_main() + if option in options.keys(): + return options[option].lower() + return 'n' + +""" +Interfaces for reading the settings of system. +""" +def scons_sys_string_option(option): + options = sys_cfg_main() + if option in options.keys(): + return options[option].strip('"') + return None + +def scons_sys_bool_option(option): + options = sys_cfg_main() + if option in options.keys(): + return options[option].lower() + return 'n' + +def get_opt_val(options, option): + bool_list = ['Y', 'y', 'N', 'n'] + if options[option].isdigit(): + return int(options.get(option)) + elif options[option] in bool_list: + return options[option].lower() + else: + return options[option].strip('"') + +def scons_get_cfg_val(option): + usr_config = usr_cfg_main() + sys_config = sys_cfg_main() + if option in usr_config.keys(): + return get_opt_val(usr_config, option) + elif option in sys_config.keys(): + return get_opt_val(sys_config, option) + else: + return 'n' + +def select_added_cfg(macro, macro_val, macro_cfg, depends=None): + if isinstance(macro_val, str) and scons_get_cfg_val(macro) == macro_val: + if depends is None: + temp = deepcopy(macro_cfg) + for cfg in macro_cfg: + if '$' not in cfg: + pass + else: + tmp_cfg = cfg.split('=')[1].strip('$').strip('(').strip(')').strip() + tmp_cfg_val = '%s=%s'%(cfg.split('=')[0], scons_get_cfg_val(tmp_cfg)) + temp.append(tmp_cfg_val) + temp.remove(cfg) + return temp + (macro_2, macro_2_val) = depends + if scons_get_cfg_val(macro_2) == macro_2_val: + return macro_cfg + elif not isinstance(macro_val, str): + val = scons_get_cfg_val(macro) + if 'others' in macro_val: + except_list = deepcopy(macro_val) + except_list.remove('others') + if val in except_list: + return macro_cfg[val] + else: + return macro_cfg['others'] + elif val in macro_val: + return macro_cfg[val] + + return None + +def translate_env_value_to_str(name, macro_cfg, mod_flag): + if name == 'defines': + if isinstance(macro_cfg, str): + return 'DEFINES += -D%s'%macro_cfg if mod_flag is False else 'CCFLAGS += -D%s'%macro_cfg + else: + defines = ['-D%s'%x for x in macro_cfg if isinstance(x, str)] + defines.extend(['-D%s=%s'%x for x in macro_cfg if isinstance(x, tuple)]) + return 'DEFINES += %s'%(' '.join(defines)) if mod_flag is False else 'CCFLAGS += %s'%(' '.join(defines)) + elif name == 'liteos_inc_path': + os_path = '$(MAIN_TOPDIR)/platform/os/Huawei_LiteOS' + if isinstance(macro_cfg, str): + return 'INCLUDE += -I%s/%s'%(os_path, macro_cfg) if mod_flag is False else 'CCFLAGS += -I%s/%s'%(os_path, macro_cfg) + else: + includes = ['-I%s/%s'%(os_path, x) for x in macro_cfg] + return 'INCLUDE += %s'%('\\\n\t'.join(includes)) if mod_flag is False else 'CCFLAGS += %s'%('\\\n\t'.join(includes)) + elif name == 'common_inc_path': + if isinstance(macro_cfg, str): + inc_str = '-I%s'%(macro_cfg[2:] if macro_cfg.startswith('#') else macro_cfg) + return 'INCLUDE += %s'%inc_str if mod_flag is False else 'CCFLAGS += %s'%inc_str + else: + inc_str = '-I$(MAIN_TOPDIR)/%s'%('\\\n\t-I$(MAIN_TOPDIR)/'.join([x[2:] for x in macro_cfg])) + return 'INCLUDE += %s'%inc_str if mod_flag is False else 'CCFLAGS += %s'%inc_str + else: + if isinstance(macro_cfg, str): + return '%s += %s'%(flag_r[name], macro_cfg) + else: + return '%s += %s'%(flag_r[name], ' '.join(macro_cfg)) + +def condition_str(macro, macro_val, macro_cfg, env_type, depends = None, mod_flag = False): + if isinstance(macro_val, str): + if depends is None: + return 'ifeq ($(%s), %s)\n\t%s\nendif\n'%(macro, macro_val, translate_env_value_to_str(env_type, macro_cfg, mod_flag)) + else: + (macro_2, macro_2_val) = depends + return 'ifeq ($(%s)_$(%s), %s_%s)\n\t%s\nendif\n'%(macro, macro_2, macro_val, macro_2_val, translate_env_value_to_str(env_type, macro_cfg, mod_flag)) + else: + strs = '' + val_list = deepcopy(macro_val) + val_list.remove('others') if 'others' in val_list else None + strs = '%sifeq ($(%s), %s)\n\t%s\n'%(strs, macro, val_list[0], translate_env_value_to_str(env_type, macro_cfg[val_list[0]], mod_flag)) + for val in val_list[1:]: + strs = '%selse ifeq ($(%s), %s)\n\t%s\n'%(strs, macro, val, translate_env_value_to_str(env_type, macro_cfg[val], mod_flag)) + strs = '%selse\n\t%s\n'%(strs, translate_env_value_to_str(env_type, macro_cfg['others'], mod_flag)) if 'others' in macro_val else None + strs = '%sendif\n'%strs + return strs diff --git a/sdk_liteos/build_patch.sh b/sdk_liteos/build_patch.sh new file mode 100755 index 0000000000000000000000000000000000000000..8e8ed1f999feafcaaf1ce0c151e7e8095bd2be74 --- /dev/null +++ b/sdk_liteos/build_patch.sh @@ -0,0 +1,36 @@ +#!/bin/bash +# +# Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Description: Menuconfig entry +# +set -e +CROOT=$(pwd) + +build_uboot_patch() { + if [ ! -d $CROOT/third_party/u-boot-v2019.07/u-boot-v2019.07/ ]; then + tar -zxf u-boot-v2019.07.tar.gz + cd u-boot-v2019.07 + patch -p1 < ./../patch/CVE-2019-13103.patch + patch -p1 < ./../patch/CVE-2019-13104.patch + patch -p1 < ./../patch/CVE-2019-13105.patch + patch -p1 < ./../patch/CVE-2019-13106.patch + patch -p1 < ./../patch/CVE-2019-14192-14193-14199.patch + patch -p1 < ./../patch/CVE-2019-14194-14198.patch + patch -p1 < ./../patch/CVE-2019-14195.patch + patch -p1 < ./../patch/CVE-2019-14196.patch + patch -p1 < ./../patch/CVE-2019-14197-14200-14201-14202-14203-14204.patch + patch -p1 < ./../hisilicon_patch/hisilicon-u-boot-v2019.07.patch + fi +} \ No newline at end of file diff --git a/sdk_liteos/components/at/Makefile b/sdk_liteos/components/at/Makefile new file mode 100755 index 0000000000000000000000000000000000000000..e8dffa9b51c1d121072661effec703d019677df4 --- /dev/null +++ b/sdk_liteos/components/at/Makefile @@ -0,0 +1,36 @@ +include $(MAIN_TOPDIR)/build/make_scripts/config.mk +include $(MAIN_TOPDIR)/$(MODULE_DIR)/module_config.mk +-include $(MAIN_TOPDIR)/$(MODULE_DIR)/srcs.mk + +OBJDIR = $(MAIN_TOPDIR)/$(OBJ_PATH)/$(MODULE_DIR) + +ID_CFG_FILE = $(MAIN_TOPDIR)/$(MODULE_DIR)/file_id.cfg + +LIB_NAME = lib$(LIB).a +SRCS = $($(LIB)_srcs) +LIBOUT = $(MAIN_TOPDIR)/$(LIB_PATH)/$(MODULE_DIR)/$(LIB_NAME) + +ifdef SRC_FILES +OBJ_SRCS := $(filter %.c, $(SRC_FILES)) +ASM_SRCS := $(filter %.S, $(SRC_FILES)) +else +OBJ_SRCS := $(foreach dir, $(SRCS), $(wildcard $(dir)/*.c)) +ASM_SRCS := $(foreach dir, $(SRCS), $(wildcard $(dir)/*.S )) +endif + +OBJ_SRCS := $(filter-out %/ethernetif.c, $(OBJ_SRCS)) +OBJS = $(patsubst %.c, $(OBJDIR)/%.o, $(OBJ_SRCS)) +ASM_OBJS = $(patsubst %.S, $(OBJDIR)/%.o, $(ASM_SRCS)) + +all: $(LIBOUT) +include $(MAIN_TOPDIR)/build/make_scripts/lib.mk + +clean: + $(Q)$(foreach x, $(OBJS) $(ASM_OBJS) $(LIBOUT), \ + if [ -d $(dir $x) ]; \ + then $(RM) $(dir $x); \ + echo clean dir $(dir $x) success; \ + fi;) + +.PHONY: all clean + diff --git a/sdk_liteos/components/at/SConscript b/sdk_liteos/components/at/SConscript new file mode 100755 index 0000000000000000000000000000000000000000..0e8bbca948cd4392d26dd5a72dd9bff5d58c6974 --- /dev/null +++ b/sdk_liteos/components/at/SConscript @@ -0,0 +1,26 @@ +#!/usr/bin/env python3 +# coding=utf-8 + +import os +from scripts import common_env +Import('env') +Import('env_cfg') +Import('module') + +module_path = env_cfg.get_module_dir(module) +obj_path = env_cfg.obj_path +module_libs = env_cfg.get_module_libs(module) +libs = [] + +env = env.Clone() +env_cfg.append_environs(env, module) +common_env.print_log_env(env, env_cfg.get_module_dir(module)) + +for lib in module_libs: + print('lib_name:',lib) + src_path = module_libs[lib] + objs = [] + for src in src_path: + objs += env.SConscript(os.path.join(src, 'SConscript'), {'env':env}, variant_dir = os.path.join('#', obj_path, module_path, src), duplicate = 0) + libs += env.Library(lib,objs) +Return('libs') diff --git a/sdk_liteos/components/at/module_config.mk b/sdk_liteos/components/at/module_config.mk new file mode 100644 index 0000000000000000000000000000000000000000..e196208b1df208cbeeca22044f84d1e9ee08710b --- /dev/null +++ b/sdk_liteos/components/at/module_config.mk @@ -0,0 +1,11 @@ +at_srcs := src +CCFLAGS += -D_PRE_WLAN_FEATURE_MFG_TEST +CCFLAGS += -I$(MAIN_TOPDIR)/platform/drivers/uart \ + -I$(MAIN_TOPDIR)/platform/system/cpup \ + -I$(MAIN_TOPDIR)/platform/at \ + -I$(MAIN_TOPDIR)/components/at/src \ + -I$(MAIN_TOPDIR)/components/wifi/include \ + -I$(MAIN_TOPDIR)/components/iperf2/include \ + -I$(MAIN_TOPDIR)/config/diag \ + -I$(MAIN_TOPDIR)/third_party/lwip_sack/include \ + -I$(MAIN_TOPDIR)/platform/os/Huawei_LiteOS/targets/hi3861v100/commons diff --git a/sdk_liteos/components/at/src/SConscript b/sdk_liteos/components/at/src/SConscript new file mode 100755 index 0000000000000000000000000000000000000000..aceb2b6a9464ce64030c1f9c5374ec933dcab384 --- /dev/null +++ b/sdk_liteos/components/at/src/SConscript @@ -0,0 +1,6 @@ +Import('env') + +env = env.Clone() + +objs = env.Object(Glob('*.c')) +Return('objs') diff --git a/sdk_liteos/components/at/src/at.c b/sdk_liteos/components/at/src/at.c new file mode 100644 index 0000000000000000000000000000000000000000..5cb23ca2786a43641b49ce2e6ca5c3f908347d75 --- /dev/null +++ b/sdk_liteos/components/at/src/at.c @@ -0,0 +1,641 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include "hi_config.h" + +#include "stdio.h" +#include "string.h" +#include "malloc.h" +#include "stdarg.h" +#include "securec.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif + +#define AT_SSID_MAX_LEN 32 + +at_cmd_ctrl g_at_ctrl = { + .at_state = AT_IDLE, + .send_len = 0, + .trans_len = 0, + .is_first_recv_data = HI_TRUE, + .is_first_over_data = HI_TRUE, + .is_recv_end_char_flag = 0, +}; + +hi_u32 at_cmd_excute(const at_cmd_func *cmd_func, at_cmd_attr *cmd_parsed) +{ + hi_u32 ret; + + if (cmd_func == HI_NULL || cmd_parsed == HI_NULL) { + return HI_ERR_FAILURE; + } + + if (cmd_parsed->at_cmd_type == AT_CMD_TYPE_TEST) { + if (cmd_func->at_test_cmd) { + ret = cmd_func->at_test_cmd((hi_s32)cmd_parsed->at_param_cnt, + (const hi_char **)&cmd_parsed->param_array[0]); + } else { + at_printf("COMMAND TYPE NOT SUPPORT!\r\n"); + ret = HI_ERR_FAILURE; + at_printf("err at %s line: %d\n", __FUNCTION__, __LINE__); + } + } else if (cmd_parsed->at_cmd_type == AT_CMD_TYPE_QUERY) { + if (cmd_func->at_query_cmd) { + ret = cmd_func->at_query_cmd((hi_s32)cmd_parsed->at_param_cnt, + (const hi_char **)&cmd_parsed->param_array[0]); + } else { + at_printf("COMMAND TYPE NOT SUPPORT!\r\n"); + ret = HI_ERR_FAILURE; + at_printf("err at %s line: %d\n", __FUNCTION__, __LINE__); + } + } else if (cmd_parsed->at_cmd_type == AT_CMD_TYPE_SETUP) { + if (cmd_func->at_setup_cmd) { + ret = cmd_func->at_setup_cmd((hi_s32)cmd_parsed->at_param_cnt, + (const hi_char **)&cmd_parsed->param_array[0]); + } else { + at_printf("COMMAND TYPE NOT SUPPORT!\r\n"); + ret = HI_ERR_FAILURE; + at_printf("err at %s line: %d\n", __FUNCTION__, __LINE__); + } + } else if (cmd_parsed->at_cmd_type == AT_CMD_TYPE_EXE) { + if (cmd_func->at_exe_cmd) { + ret = cmd_func->at_exe_cmd((hi_s32)cmd_parsed->at_param_cnt, + (const hi_char **)&cmd_parsed->param_array[0]); + } else { + at_printf("COMMAND TYPE NOT SUPPORT!\r\n"); + ret = HI_ERR_FAILURE; + at_printf("err at %s line: %d\n", __FUNCTION__, __LINE__); + } + } else { + at_printf("COMMAND TYPE NOT SUPPORT!\r\n"); + ret = HI_ERR_FAILURE; + at_printf("err at %s line: %d\n", __FUNCTION__, __LINE__); + } + + return ret; +} + +static hi_void at_get_cmd_name(hi_char *cmd_line, at_cmd_attr *cmd_parsed) +{ + hi_s8 n = 0; + + for (hi_u8 i = AT_CMD_MAX_LEN; i > 0; i--) { + if ((*cmd_line == '\0') || (*cmd_line == '=') || (*cmd_line == '?')) { + cmd_parsed->at_cmd_len = n; + return; + } else { + cmd_parsed->cmd_name[n] = *cmd_line; + cmd_line++; + n++; + } + } + + cmd_parsed->at_cmd_len = -1; + memset_s(cmd_parsed->cmd_name, AT_CMD_MAX_LEN, 0, AT_CMD_MAX_LEN); +} + +hi_u32 at_func_process(hi_char *out_cmd_line, at_cmd_attr *cmd_parsed) +{ + hi_u32 ret; + at_cmd_func *cmd_func = HI_NULL; + at_get_cmd_name(out_cmd_line, cmd_parsed); + if (cmd_parsed->at_cmd_len != (-1)) { + cmd_func = at_find_proc_func(cmd_parsed); + } + + if (cmd_func != HI_NULL) { + ret = at_cmd_parse(out_cmd_line, cmd_parsed); + if (ret != HI_ERR_SUCCESS) { + at_printf("%s line: %d PARSE CMD FAIL!\r\n", __FUNCTION__, __LINE__); + return ret; + } + + ret = at_cmd_excute(cmd_func, cmd_parsed); + } else { + ret = HI_ERR_FAILURE; + at_printf("%s line: %d COMMAND NOT SUPPORT!\r\n", __FUNCTION__, __LINE__); + } + + return ret; +} + +hi_u32 at_cmd_process(const hi_char *at_cmd_line) +{ + hi_u32 at_cmd_line_len; + hi_char *out_cmd_line = HI_NULL; + at_cmd_attr cmd_parsed = {0}; + hi_u32 ret; + + AT_ENTER; + if (at_cmd_line == HI_NULL) { + at_printf("INVALID NULL CMD!\r\n"); + AT_RESPONSE_ERROR; + return HI_ERR_FAILURE; + } + + at_cmd_line_len = (hi_u32)strlen(at_cmd_line) + 1; + out_cmd_line = (hi_char *)hi_malloc(HI_MOD_ID_SAL_DFX, at_cmd_line_len); + if (out_cmd_line == HI_NULL) { + at_printf("%s line%d NO ENOUGH MEMORY!\r\n", __FUNCTION__, __LINE__); + AT_RESPONSE_ERROR; + return HI_ERR_FAILURE; + } + memset_s(out_cmd_line, at_cmd_line_len, 0, at_cmd_line_len); + + ret = (hi_u32)strncpy_s(out_cmd_line, at_cmd_line_len, at_cmd_line, at_cmd_line_len - 1); + if (ret != EOK) { + at_printf("%s,%d strncpy_s failed, err:%d!\n", __FUNCTION__, __LINE__, ret); + AT_RESPONSE_ERROR; + hi_free(HI_MOD_ID_SAL_DFX, out_cmd_line); + return HI_ERR_FAILURE; + } + out_cmd_line[at_cmd_line_len - 1] = '\0'; + + ret = at_func_process(out_cmd_line, &cmd_parsed); + if (ret != HI_ERR_SUCCESS && ret != HI_ERR_RECVING) { + at_printf("err at %s line: %d\n", __FUNCTION__, __LINE__); + AT_RESPONSE_ERROR; + } else if (ret == HI_ERR_RECVING) { + g_at_ctrl.at_state = AT_DATA_RECVING; + } else { + g_at_ctrl.at_state = AT_IDLE; + } + + hi_free(HI_MOD_ID_SAL_DFX, out_cmd_line); + out_cmd_line = HI_NULL; + + return ret; +} + +hi_u32 at_param_null_check(hi_s32 argc, const hi_char **argv) +{ + for (hi_s32 i = 0; i < argc; i++) { + if (argv[i] == HI_NULL) { + return HI_ERR_FAILURE; + } + } + return HI_ERR_SUCCESS; +} + +hi_u32 integer_check(const hi_char *val) +{ + hi_u32 len; + hi_u32 i; + hi_char *buf = (hi_char *)val; + if (buf == HI_NULL) { + return HI_ERR_FAILURE; + } + len = strlen(buf); + if ((*buf == '0') && (len != 1)) { + return HI_ERR_FAILURE; + } + for (i = 0; i < len; i++) { + if ((*buf < '0') || (*buf > '9')) { + return HI_ERR_FAILURE; + } + buf++; + } + return HI_ERR_SUCCESS; +} + +static hi_u32 at_check_mac_elem(const hi_char elem) +{ + if (elem >= '0' && elem <= '9') { + return HI_ERR_SUCCESS; + } else if (elem >= 'A' && elem <= 'F') { + return HI_ERR_SUCCESS; + } else if (elem >= 'a' && elem <= 'f') { + return HI_ERR_SUCCESS; + } else if (elem == ':') { + return HI_ERR_SUCCESS; + } + + return HI_ERR_FAILURE; +} + +hi_u32 cmd_strtoaddr(const hi_char *param, hi_uchar *mac_addr, hi_u32 addr_len) +{ + hi_u32 cnt; + hi_char *tmp1 = (hi_char *)param; + hi_char *tmp2 = NULL; + hi_char *tmp3 = NULL; + + for (cnt = 0; cnt < 17; cnt++) { /* 17 */ + if (at_check_mac_elem(param[cnt]) != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + } + + for (cnt = 0; cnt < (addr_len - 1); cnt++) { + tmp2 = (char*)strsep(&tmp1, ":"); + if (tmp2 == NULL) { + return HI_ERR_APP_INVALID_PARAMETER; + } + mac_addr[cnt] = (hi_uchar)strtoul(tmp2, &tmp3, 16); /* 16 */ + } + + if (tmp1 == NULL) { + return HI_ERR_APP_INVALID_PARAMETER; + } + mac_addr[cnt] = (hi_uchar)strtoul(tmp1, &tmp3, 16); /* 16 */ + return HI_ERR_SUCCESS; +} + +char *at_strrchr(const char *src, int c) +{ + return strrchr(src, c); +} + +void *at_malloc(size_t size) +{ + if (size > 4096) { /* max alloc mem 4096 */ + return NULL; + } + void *ptr = malloc(size); + return ptr; +} + +void at_free(char *ptr) +{ + if (ptr) { + free(ptr); + } +} + +size_t at_strlen(const char *src) +{ + return strlen(src); +} + +int at_pading(char *str, size_t size, const char *format, ...) +{ + va_list ap = NULL; + int ret; + + va_start(ap, format); + ret = vsnprintf_s(str, AT_SSID_MAX_LEN * 4 + 1, size, format, ap); /* 4 length */ + va_end(ap); + if (size > 0) { + str[size - 1] = '\0'; + } + return ret; +} + +char* at_dup_binstr(const char *src, size_t len) +{ + char *res = NULL; + int ret; + + if (src == NULL) { + return NULL; + } + res = at_malloc(len + 1); + if (res == NULL) { + return NULL; + } + ret = memcpy_s(res, len, src, len); + if (ret != EOK) { + at_free(res); + res = NULL; + return NULL; + } + res[len] = '\0'; + + return res; +} + +static int at_hex2num(char c) +{ + if (c >= '0' && c <= '9') { + return c - '0'; + } + if (c >= 'a' && c <= 'f') { + return c - 'a' + 10; /* add 10 */ + } + if (c >= 'A' && c <= 'F') { + return c - 'A' + 10; /* add 10 */ + } + return -1; +} + +int at_hex2byte(const char *hex) +{ + int a, b; + a = at_hex2num(*hex++); + if (a < 0) { + return -1; + } + b = at_hex2num(*hex++); + if (b < 0) { + return -1; + } + return ((hi_u32)a << 4) | (hi_u32)b; /* 4 */ +} + +/** + * at_hexstr2bin - Convert ASCII hex string into binary data + * @hex: ASCII hex string (e.g., "01ab") + * @buf: Buffer for the binary data + * @len: Length of the text to convert in bytes (of buf); hex will be double + * this size + * Returns: 0 on success, -1 on failure (invalid hex string) + */ +int at_hexstr2bin(const char *hex, hi_u8 *buf, size_t len) +{ + size_t i; + const char *ipos = hex; + hi_u8 *opos = buf; + + for (i = 0; i < len; i++) { + int a = at_hex2byte(ipos); + if (a < 0) { + return -1; + } + *opos++ = a; + ipos += 2; /* add 2 */ + } + return 0; +} + +void at_printf_encode(char *txt, size_t maxlen, const hi_u8 *data, size_t len) +{ + char *end = txt + maxlen; + size_t i; + + for (i = 0; i < len; i++) { + if (txt + 4 >= end) { /* add 4 */ + break; + } + + switch (data[i]) { + case '\"': + *txt++ = '\\'; + *txt++ = '\"'; + break; + case '\\': + *txt++ = '\\'; + *txt++ = '\\'; + break; + case '\033': + *txt++ = '\\'; + *txt++ = 'e'; + break; + case '\n': + *txt++ = '\\'; + *txt++ = 'n'; + break; + case '\r': + *txt++ = '\\'; + *txt++ = 'r'; + break; + case '\t': + *txt++ = '\\'; + *txt++ = 't'; + break; + default: + if (data[i] >= 32 && data[i] <= 126) { /* range [32,126] */ + *txt++ = data[i]; + } else { + txt += at_pading(txt, end - txt, "\\x%02x", data[i]); + } + break; + } + } + + *txt = '\0'; +} + +hi_void at_printf_decode_slash(hi_u8 *buf, const char **str_pos, size_t *str_len) +{ + const char *pos = *str_pos; + size_t len = *str_len; + int val; + + pos++; + switch (*pos) { + case '\\': + buf[len++] = '\\'; + pos++; + break; + case '"': + buf[len++] = '"'; + pos++; + break; + case 'n': + buf[len++] = '\n'; + pos++; + break; + case 'r': + buf[len++] = '\r'; + pos++; + break; + case 't': + buf[len++] = '\t'; + pos++; + break; + case 'e': + buf[len++] = '\033'; + pos++; + break; + case 'x': + pos++; + val = at_hex2byte(pos); + if (val < 0) { + val = at_hex2num(*pos); + if (val < 0) { + break; + } + buf[len++] = val; + pos++; + } else { + buf[len++] = val; + pos += 2; /* add 2 */ + } + break; + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + val = *pos++ - '0'; + if (*pos >= '0' && *pos <= '7') { + val = val * 8 + (*pos++ - '0'); /* 8 */ + } + if (*pos >= '0' && *pos <= '7') { + val = val * 8 + (*pos++ - '0'); /* 8 */ + } + buf[len++] = val; + break; + default: + break; + } + + *str_pos = pos; + *str_len = len; +} + +size_t at_printf_decode(hi_u8 *buf, size_t maxlen, const char *str) +{ + const char *pos = str; + size_t len = 0; + + while (*pos) { + if (len + 1 >= maxlen) { + break; + } + switch (*pos) { + case '\\': + at_printf_decode_slash(buf, &pos, &len); + break; + default: + buf[len++] = *pos++; + break; + } + } + if (maxlen > len) { + buf[len] = '\0'; + } + + return len; +} + +char* at_parse_string_normal(const char *value, size_t *len) +{ + const char *pos = NULL; + char *str = NULL; + + value++; + pos = at_strrchr(value, '"'); + if (pos == NULL || pos[1] != '\0') { + return NULL; + } + *len = pos - value; + str = at_dup_binstr(value, *len); + if (str == NULL) { + return NULL; + } + return str; +} + +char* at_parse_string_with_p(const char *value, size_t *len) +{ + const char *pos = NULL; + char *tstr = NULL; + char *str = NULL; + size_t tlen; + + value += 2; /* add 2 */ + pos = at_strrchr(value, '"'); + if (pos == NULL || pos[1] != '\0') { + return NULL; + } + tlen = pos - value; + tstr = at_dup_binstr(value, tlen); + if (tstr == NULL) { + return NULL; + } + + str = at_malloc(tlen + 1); + if (str == NULL) { + at_free(tstr); + return NULL; + } + + *len = at_printf_decode((hi_u8 *) str, tlen + 1, tstr); + at_free(tstr); + + return str; +} + +char* at_parse_string_other(const char *value, size_t *len) +{ + hi_u8 *str = NULL; + size_t tlen; + size_t hlen = at_strlen(value); + if (hlen & 1) { + return NULL; + } + tlen = hlen / 2; /* 2 */ + str = at_malloc(tlen + 1); + if (str == NULL) { + return NULL; + } + if (at_hexstr2bin(value, str, tlen)) { + at_free((char*)str); + return NULL; + } + str[tlen] = '\0'; + *len = tlen; + return (char *) str; +} + + +char* at_parse_string(const char *value, size_t *len) +{ + if (len == HI_NULL) { + return HI_NULL; + } + if (*value == '"') { + return at_parse_string_normal(value, len); + } else if (*value == 'P' && value[1] == '"') { + return at_parse_string_with_p(value, len); + } else { + return at_parse_string_other(value, len); + } +} + +/** + * at_ssid_txt - Convert SSID to a printable string + * @ssid: SSID (32-octet string) + * @ssid_len: Length of ssid in octets + * Returns: Pointer to a printable string + * + * This function can be used to convert SSIDs into printable form. In most + * cases, SSIDs do not use unprintable characters, but IEEE 802.11 standard + * does not limit the used character set, so anything could be used in an SSID. + * + * This function uses a static buffer, so only one call can be used at the + * time, i.e., this is not re-entrant and the returned buffer must be used + * before calling this again. + */ +const char* at_ssid_txt(const hi_u8 *ssid, size_t ssid_len) +{ + static char ssid_txt[AT_SSID_MAX_LEN * 4 + 1]; /* 4 */ + + if (ssid == NULL) { + ssid_txt[0] = '\0'; + return ssid_txt; + } + + at_printf_encode(ssid_txt, sizeof(ssid_txt), ssid, ssid_len); + return ssid_txt; +} + +#ifdef __cplusplus +#if __cplusplus + } +#endif +#endif diff --git a/sdk_liteos/components/at/src/at.h b/sdk_liteos/components/at/src/at.h new file mode 100644 index 0000000000000000000000000000000000000000..9d3acd84d505738a0c0630f298ae28aef60a1899 --- /dev/null +++ b/sdk_liteos/components/at/src/at.h @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __AT_H__ +#define __AT_H__ + +#include +#include +#include +#include +#include + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif + +#define AT_CMD_MAX_PARAS 64 +#define AT_CMD_MAX_LEN 128 +#define AT_CMD_LIST_NUM 20 + +#define AT_RESPONSE_OK do { \ + hi_at_printf("OK\r\n"); \ + } while (0) + +#define AT_RESPONSE_ERROR do { \ + hi_at_printf("ERROR\r\n"); \ + } while (0) + +#define AT_ENTER do { \ + hi_at_printf("\r\n"); \ + } while (0) + +#ifdef AT_CMD_DEBUG +#define at_printf(fmt...) printf(fmt) +#else +#define at_printf(fmt...) +#endif + +#define AT_MACSTR "%02x:%02x:%02x:%02x:%02x:%02x" +#define at_mac2str(a) (a)[0], (a)[1], (a)[2], (a)[3], (a)[4], (a)[5] + + +typedef enum { + AT_CMD_TYPE_TEST = 1, + AT_CMD_TYPE_QUERY = 2, + AT_CMD_TYPE_SETUP = 3, + AT_CMD_TYPE_EXE = 4, +} at_cmd_type; + +typedef struct { + hi_s8 at_cmd_len; + hi_char cmd_name[AT_CMD_MAX_LEN]; + at_cmd_type at_cmd_type; + hi_s32 at_param_cnt; /* command actual para num */ + hi_u32 param_array[AT_CMD_MAX_PARAS]; +} at_cmd_attr; + +typedef struct { + HI_CONST at_cmd_func *at_cmd_list[AT_CMD_LIST_NUM]; /* user input at cmd list */ + hi_u16 at_cmd_num[AT_CMD_LIST_NUM]; /* command number */ +} at_cmd_func_list; + +extern at_cmd_ctrl g_at_ctrl; + +hi_u32 at_cmd_process(const hi_char *at_cmd_line); +hi_u32 at_param_null_check(hi_s32 argc, const hi_char **argv); +hi_u32 integer_check(const hi_char *val); +hi_u32 cmd_strtoaddr(const hi_char *param, hi_uchar *mac_addr, hi_u32 addr_len); +char* at_parse_string(const char *value, size_t *len); +const char* at_ssid_txt(const hi_u8 *ssid, size_t ssid_len); +void* at_malloc(size_t size); +void at_free(char *ptr); + +#ifdef __cplusplus +#if __cplusplus + } +#endif +#endif + +#endif diff --git a/sdk_liteos/components/at/src/at_cmd.c b/sdk_liteos/components/at/src/at_cmd.c new file mode 100644 index 0000000000000000000000000000000000000000..5f9bdd1b1b2708214bd075324109a4b9c203826d --- /dev/null +++ b/sdk_liteos/components/at/src/at_cmd.c @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif + +HI_PRV at_cmd_func_list g_at_cmd_list = { 0 }; + +at_cmd_func_list* at_get_list(hi_void) +{ + return (at_cmd_func_list*)&g_at_cmd_list; +} + +at_cmd_func *at_find_proc_func(const at_cmd_attr *cmd_parsed) +{ + at_cmd_func_list *cmd_list = at_get_list(); + hi_u32 i; + + for (i = 0; i < AT_CMD_LIST_NUM; i++) { + hi_u16 j; + + for (j = 0; j < cmd_list->at_cmd_num[i]; j++) { + at_cmd_func *cmd_func = (at_cmd_func *) ((cmd_list->at_cmd_list[i] + j)); + if ((cmd_parsed->at_cmd_len == cmd_func->at_cmd_len) && + (strcmp(cmd_parsed->cmd_name, cmd_func->at_cmd_name) == 0)) { + return cmd_func; + } + } + } + + return HI_NULL; +} + +#ifdef __cplusplus +#if __cplusplus + } +#endif +#endif diff --git a/sdk_liteos/components/at/src/at_cmd.h b/sdk_liteos/components/at/src/at_cmd.h new file mode 100644 index 0000000000000000000000000000000000000000..93bb21d287b47f8e53004dd5d5305e1a8cd3dc99 --- /dev/null +++ b/sdk_liteos/components/at/src/at_cmd.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __AT_CMD_H__ +#define __AT_CMD_H__ + +#include + +#include "at.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif + +at_cmd_func_list *at_get_list(hi_void); +at_cmd_func *at_find_proc_func(const at_cmd_attr *cmd_parsed); + +#ifdef __cplusplus +#if __cplusplus + } +#endif +#endif + +#endif diff --git a/sdk_liteos/components/at/src/at_demo_hks.c b/sdk_liteos/components/at/src/at_demo_hks.c new file mode 100644 index 0000000000000000000000000000000000000000..323292c03b5bff8b13f4119967c1afe8d4fa21ab --- /dev/null +++ b/sdk_liteos/components/at/src/at_demo_hks.c @@ -0,0 +1,879 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef CONFIG_TEE_HUKS_DEMO_SUPPORT + +#include "stdio.h" +#include "stdlib.h" +#include +#include "hks_client.h" +#include "hks_types.h" +#include "hks_errno.h" +#include +#include +#include "hi_flash.h" +#include "hi3861_platform_base.h" +#include "hi_partition_table.h" +#include "hi_nv.h" +#include "hi_efuse.h" +#include "hi_time.h" +#include "hi_wifi_api.h" + +#define FLASH_BASE_ADDR 0x400000 + +#define CERT_STORE_START_ADDR 0 +#define CERT_TOTAL_LEN (1024*12) +#define MAX_CERT_KEY_CNT 100 +#define CERT_KEY_START_FLAG 0xDEADBEEF + +#define KEY_STORE_START_ADDR (1024 * 12) +#define KEY_LEN 512 +#define MAX_KEY_CNT 8 +#define KEY_DATA_MAX_LEN 380 +#define KYY_PARAM_MAX_LEN 128 +#define LEN_BYTE 4 +#define CIPHER_PLAIN_LEN_MIN_DIFF 16 + +#define USR_DATA_START_ADDR (1024 * 16) +#define USR_DATA_LEN (1024 * 4) + +hi_void app_hks_get_cert_bin_start_store_addr(hi_u32 *addr, hi_u32 *size) +{ + hi_u32 usr_partion_addr; + hi_u32 usr_partion_size; + hi_get_usr_partition_table(&usr_partion_addr, &usr_partion_size); + + *addr = usr_partion_addr + CERT_STORE_START_ADDR; + *size = CERT_TOTAL_LEN; +} + +hi_u32 get_cert_text_addr(hi_u32 start_addr, hi_u32 *len_array, hi_u32 cert_index) +{ + int before_total_len = 0; + for (hi_u32 i = 0; i < cert_index; i++) { + before_total_len += len_array[i]; + } + + return (start_addr + before_total_len); +} + +hi_u32 app_hks_get_cert_store_addr(hi_u32 *addr, hi_u32 *size, hi_u32 cert_index) +{ + if (addr == HI_NULL || size == HI_NULL) { + return HI_ERR_FAILURE; + } + hi_u32 usr_partion_addr; + hi_u32 usr_partion_size; + hi_get_usr_partition_table(&usr_partion_addr, &usr_partion_size); + + hi_u32 cert_key_start_addr = 0; + hi_u32 cert_bin_max_len = 0; + app_hks_get_cert_bin_start_store_addr(&cert_key_start_addr, &cert_bin_max_len); + + hi_u32 start_flag = *((hi_u32 *)(HI_FLASH_BASE + cert_key_start_addr)); + if (start_flag != CERT_KEY_START_FLAG) { + hi_at_printf("invalid cert:0x%x\r\n", start_flag); + return HI_ERR_FAILURE; + } + + hi_u32 cert_key_cnt = *((hi_u32 *)(HI_FLASH_BASE + cert_key_start_addr + 0x4)); + if (cert_index >= cert_key_cnt || cert_key_cnt > MAX_CERT_KEY_CNT) { + hi_at_printf("invalid cert index or cert_key_cnt\r\n"); + return HI_ERR_FAILURE; + } + + hi_u32 *cert_len_array = (hi_u32 *)malloc(cert_key_cnt * sizeof(hi_u32)); + if (cert_len_array == HI_NULL) { + return HI_ERR_FAILURE; + } + for (hi_u32 i = 0; i < cert_key_cnt; i++) { + cert_len_array[i] = *((hi_u32 *)(HI_FLASH_BASE + cert_key_start_addr + 0x8 + i * 0x4)); + } + + hi_u32 cert_key_plain_size = cert_len_array[cert_index]; + hi_u32 cert_key_plain_addr = get_cert_text_addr(cert_key_start_addr + 0x8 + cert_key_cnt * 0x4, + &cert_len_array[0], cert_index); + if (cert_key_plain_addr + cert_key_plain_size > cert_key_start_addr + cert_bin_max_len) { + hi_at_printf("cert size invalid:%d\r\n", cert_index); + free(cert_len_array); + return HI_ERR_FAILURE; + } + + *addr = cert_key_plain_addr; + *size = cert_key_plain_size; + + free(cert_len_array); + return HI_ERR_SUCCESS; +} + +hi_u32 app_hks_get_key_store_addr(hi_u32 *addr, hi_u32 *size, hi_u32 key_index) +{ + if (addr == HI_NULL || size == HI_NULL) { + return HI_ERR_FAILURE; + } + hi_u32 usr_partion_addr; + hi_u32 usr_partion_size; + hi_get_usr_partition_table(&usr_partion_addr, &usr_partion_size); + if (key_index >= MAX_KEY_CNT) { + return HI_ERR_FAILURE; + } + + *addr = usr_partion_addr + KEY_STORE_START_ADDR + key_index * KEY_LEN; + *size = KEY_LEN; + + return HI_ERR_SUCCESS; +} + +hi_u32 app_hks_get_usr_data_store_addr(hi_u32 *addr, hi_u32 *size) +{ + if (addr == HI_NULL || size == HI_NULL) { + return HI_ERR_FAILURE; + } + + hi_u32 usr_partion_addr; + hi_u32 usr_partion_size; + hi_get_usr_partition_table(&usr_partion_addr, &usr_partion_size); + + *addr = usr_partion_addr + USR_DATA_START_ADDR; + *size = USR_DATA_LEN; + + return HI_ERR_SUCCESS; +} + +#define ENC_PARAM_NONCE_LEN 16 +#define ENC_PARAM_AAD_LEN 12 + +typedef struct encrypt_param_ { + hi_u16 nonce_size; + hi_u16 aad_size; + hi_u8 nonce[ENC_PARAM_NONCE_LEN]; + hi_u8 aad[ENC_PARAM_AAD_LEN]; +} encrypt_param; + +hi_u32 hks_set_blob(hi_u8 type, hi_u32 size, hi_char *data, struct hks_blob *hks_blob_param) +{ + hi_u32 ret = HI_ERR_SUCCESS; + + hks_blob_param->type = type; + hks_blob_param->size = size; + + if (hks_blob_param->data != HI_NULL) { + /* free mem before malloc again */ + free(hks_blob_param->data); + hks_blob_param->data = HI_NULL; + } + + hks_blob_param->data = malloc(hks_blob_param->size + 1); + if (hks_blob_param->data == HI_NULL) { + printf("blob malloc fail\r\n"); + return HI_ERR_FAILURE; + } + + if (data != HI_NULL && hks_blob_param->size != 0) { + ret = memcpy_s(hks_blob_param->data, hks_blob_param->size, data, size); + if (ret != HI_ERR_SUCCESS) { + free(hks_blob_param->data); + hks_blob_param->data = HI_NULL; + } + } + + return ret; +} + +hi_void hks_get_key_data(hi_u32 flash_addr, struct hks_blob *blob_key_data) +{ + blob_key_data->type = HKS_BLOB_TYPE_ENCRYPTED_KEY; + blob_key_data->data = (hi_u8*)(FLASH_BASE_ADDR + flash_addr + KYY_PARAM_MAX_LEN + LEN_BYTE); + blob_key_data->size = *((hi_u32 *)(FLASH_BASE_ADDR + flash_addr + KYY_PARAM_MAX_LEN)); +} + +hi_u32 hks_get_enc_param(hi_u32 flash_addr, encrypt_param *enc_param, struct hks_crypt_param *hks_encry_param) +{ + hi_u32 ret; + + ret = hi_flash_read(flash_addr, sizeof(encrypt_param), (hi_u8 *)enc_param); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + hks_encry_param->nonce.data = enc_param->nonce; + hks_encry_param->nonce.size = enc_param->nonce_size; + hks_encry_param->aad.data = enc_param->aad; + hks_encry_param->aad.size = enc_param->aad_size; + + return ret; +} + +#define CONN_DATA_KEY_LEN 64 +#define CONN_DATA_CIPHER_DATA_MAX_LEN 220 +#define CONN_DATA_ENC_PARAM_NONCE_SIZE 13 + +typedef struct encrypt_data_ { + hi_u32 cipher_data_size; + hi_u8 cipher_data[CONN_DATA_CIPHER_DATA_MAX_LEN]; +} encrypt_cipher_data; + +hi_u32 hks_set_conn_key_param(hi_u32 key_usage, struct hks_key_param *key_param) +{ + key_param->key_type = HKS_KEY_TYPE_AES; + key_param->key_len = HKS_MAX_KEY_LEN_128; + key_param->key_usage = key_usage; + key_param->key_pad = 1; + key_param->key_mode = HKS_ALG_GCM; + key_param->key_domain = 0; + key_param->key_role = 0; + + key_param->key_auth_id.type = 0; + key_param->key_auth_id.size = 0; + + if (key_param->key_auth_id.data != HI_NULL) { + /* free mem before malloc again */ + free(key_param->key_auth_id.data); + key_param->key_auth_id.data = HI_NULL; + } + + return HI_ERR_SUCCESS; +} + +hi_u32 hks_encrypt_conn_para(struct hks_crypt_param *crypt_param_conn, struct hks_blob *plain_text, + struct hks_blob *cipher_text) +{ + hi_u32 ret; + + hi_u32 key_save_partition_addr = 0; + hi_u32 key_save_partition_size = 0; + ret = app_hks_get_key_store_addr(&key_save_partition_addr, &key_save_partition_size, 0); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + /* get key param */ + struct hks_key_param key_param = {0}; + ret = hi_flash_read(key_save_partition_addr, sizeof(key_param), (hi_u8 *)&key_param); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + key_param.key_usage = HKS_KEY_USAGE_ENCRYPT; + + /* get key data */ + struct hks_blob key_data_blob = {0}; + hi_u32 key_size = 0; + ret = hi_flash_read(key_save_partition_addr + KYY_PARAM_MAX_LEN, LEN_BYTE, (hi_u8 *)&key_size); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + hi_u8 key_data[KEY_DATA_MAX_LEN] = {0}; /* The data on the flash memory cannot be directly used here. */ + ret = hi_flash_read(key_save_partition_addr + KYY_PARAM_MAX_LEN + LEN_BYTE, key_size, &key_data[0]); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + key_data_blob.type = HKS_BLOB_TYPE_ENCRYPTED_KEY; + key_data_blob.data = &key_data[0]; + key_data_blob.size = key_size; + + /* encrypt */ + ret = hks_symmetric_encrypt(&key_data_blob, &key_param, crypt_param_conn, plain_text, cipher_text); + if (ret != HI_ERR_SUCCESS) { + printf("hks_symmetric_encrypt ret = %d\n", ret); + return ret; + } + + return ret; +} + +hi_void hks_create_conn_enc_param(encrypt_param *enc_param, struct hks_crypt_param *blob_enc_param) +{ + hi_char nonce_data[CONN_DATA_ENC_PARAM_NONCE_SIZE] = "1234"; + hi_char* aad_data = "a"; + memcpy_s(enc_param->nonce, sizeof(enc_param->nonce), nonce_data, sizeof(nonce_data)); + enc_param->nonce_size = sizeof(nonce_data); + memcpy_s(enc_param->aad, sizeof(enc_param->aad), aad_data, strlen(aad_data)); + enc_param->aad_size = strlen(aad_data); + blob_enc_param->nonce.data = enc_param->nonce; + blob_enc_param->nonce.size = enc_param->nonce_size; + blob_enc_param->aad.data = enc_param->aad; + blob_enc_param->aad.size = enc_param->aad_size; +} + + +hi_void hks_get_conn_cipher_data(hi_u32 flash_addr, struct hks_blob *blob_cipher_data) +{ + hi_u32 cipher_data_size = *((hi_u32*)(FLASH_BASE_ADDR + flash_addr + sizeof(encrypt_param))); + hi_u8 *cipher_data = (hi_u8*)(FLASH_BASE_ADDR + flash_addr + sizeof(encrypt_param) + LEN_BYTE); + blob_cipher_data->data = cipher_data; + blob_cipher_data->size = cipher_data_size; +} + +hi_u32 app_hks_generate_conn_key(void) +{ + hi_u32 ret; + hi_u8 *flash_write_buffer = HI_NULL; + + hi_u32 key_save_partition_addr = 0; + hi_u32 key_save_partition_size = 0; + struct hks_key_param conn_key_param = {0}; + struct hks_blob blob_key = {0}; + + ret = app_hks_get_key_store_addr(&key_save_partition_addr, &key_save_partition_size, 0); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + /* set key param */ + ret = hks_set_conn_key_param(HKS_KEY_USAGE_ENCRYPT, &conn_key_param); + if (ret != HI_ERR_SUCCESS) { + printf("hks_set_key_param fail!\r\n"); + return ret; + } + + /* set key blob */ + ret = hks_set_blob(HKS_BLOB_TYPE_BUFFER, CONN_DATA_KEY_LEN, "123", &blob_key); + if (ret != HI_ERR_SUCCESS) { + printf("hks_set_blob fail!\r\n"); + return ret; + } + + /* generate key */ + ret = hks_generate_symmetric_key(&blob_key, &conn_key_param); + if (ret != HI_ERR_SUCCESS) { + free(blob_key.data); + printf("hks_generate_symmetric_key ret = %d\n", ret); + return ret; + } + + /* save key param */ + ret = hi_flash_write(key_save_partition_addr, sizeof(conn_key_param), (const hi_u8*)&conn_key_param, HI_TRUE); + if (ret != HI_ERR_SUCCESS) { + free(blob_key.data); + printf("save key param fail, ret:0x%x\r\n", ret); + return ret; + } + + /* save key data */ + flash_write_buffer = malloc(blob_key.size + sizeof(uint32_t)); + if (flash_write_buffer == HI_NULL) { + free(blob_key.data); + return HI_ERR_FAILURE; + } + + ret = memcpy_s(flash_write_buffer, sizeof(uint32_t), &(blob_key.size), sizeof(uint32_t)); + ret |= memcpy_s(flash_write_buffer + sizeof(uint32_t), key_save_partition_size, blob_key.data, blob_key.size); + ret |= hi_flash_write(key_save_partition_addr + KYY_PARAM_MAX_LEN, blob_key.size + sizeof(uint32_t), + flash_write_buffer, HI_TRUE); + free(flash_write_buffer); + free(blob_key.data); + + if (ret != HI_ERR_SUCCESS) { + printf("save key data fail, ret:0x%x\r\n", ret); + } + + return ret; +} + +hi_u32 app_hks_encrypt_conn_para(hi_wifi_assoc_request *req) +{ + hi_u32 ret; + struct hks_crypt_param blob_crypt_param_conn = {0}; + struct hks_blob blob_plain_text = {0}; + struct hks_blob blob_cipher_text_with_tag = {0}; + + hi_u32 encrpt_param_data_save_partition_addr = 0; + hi_u32 encrpt_param_data_save_partition_size = 0; + ret = app_hks_get_usr_data_store_addr(&encrpt_param_data_save_partition_addr, + &encrpt_param_data_save_partition_size); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + /* get plain connect data */ + blob_plain_text.data = (hi_u8 *)req; + blob_plain_text.size = sizeof(hi_wifi_assoc_request); + + /* create enc param */ + encrypt_param enc_param = {0}; + hks_create_conn_enc_param(&enc_param, &blob_crypt_param_conn); + + /* create cipher blob */ + ret = hks_set_blob(0, sizeof(hi_wifi_assoc_request) + CIPHER_PLAIN_LEN_MIN_DIFF, "1234", + &blob_cipher_text_with_tag); + if (ret != HI_ERR_SUCCESS) { + printf("set_value_of_hks_blob fail!\r\n"); + return ret; + } + + /* start encrypt */ + ret = hks_encrypt_conn_para(&blob_crypt_param_conn, &blob_plain_text, &blob_cipher_text_with_tag); + if (ret != HI_ERR_SUCCESS) { + free(blob_cipher_text_with_tag.data); + printf("hks_encrypt conn para fail!\r\n"); + return HI_ERR_FAILURE; + } + + if (blob_cipher_text_with_tag.size > (sizeof(encrypt_cipher_data) - sizeof(hi_u32))) { + free(blob_cipher_text_with_tag.data); + printf("cipher text too long\r\n"); + return HI_ERR_FAILURE; + } + + /* save enc param and cipher conn data */ + ret = hi_flash_write(encrpt_param_data_save_partition_addr, sizeof(enc_param), (const hi_u8*)&enc_param, HI_TRUE); + + encrypt_cipher_data enc_data = {0}; + enc_data.cipher_data_size = blob_cipher_text_with_tag.size; + ret |= memcpy_s(enc_data.cipher_data, sizeof(enc_data.cipher_data), blob_cipher_text_with_tag.data, + blob_cipher_text_with_tag.size); + ret |= hi_flash_write(encrpt_param_data_save_partition_addr + sizeof(encrypt_param), + sizeof(hi_u32) + blob_cipher_text_with_tag.size, (const hi_u8*)&enc_data, HI_TRUE); + + free(blob_cipher_text_with_tag.data); + + return ret; +} + +hi_u32 app_hks_decrypt_conn_param(hi_wifi_assoc_request *req) +{ + if (req == HI_NULL) { + return HI_ERR_FAILURE; + } + + hi_u32 ret; + hi_u32 key_save_partition_addr = 0; + hi_u32 key_save_partition_size = 0; + ret = app_hks_get_key_store_addr(&key_save_partition_addr, &key_save_partition_size, 0); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + /* get key param */ + struct hks_key_param key_param = {0}; + ret = hi_flash_read(key_save_partition_addr, sizeof(key_param), (hi_u8 *)&key_param); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + key_param.key_usage = HKS_KEY_USAGE_DECRYPT; + + /* get key data */ + struct hks_blob key_data_blob = {0}; + hks_get_key_data(key_save_partition_addr, &key_data_blob); + + hi_u32 cipher_data_save_addr = 0; + hi_u32 cipher_data_partition_size = 0; + ret = app_hks_get_usr_data_store_addr(&cipher_data_save_addr, &cipher_data_partition_size); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + /* get enc param */ + encrypt_param enc_param = {0}; + struct hks_crypt_param hks_encry_param = {0}; + ret = hks_get_enc_param(cipher_data_save_addr, &enc_param, &hks_encry_param); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + /* get cipher data */ + struct hks_blob cipher_text_blob = {0}; + hks_get_conn_cipher_data(cipher_data_save_addr, &cipher_text_blob); + + /* start decrypt */ + struct hks_blob plain_text_blob = {0}; + plain_text_blob.size = cipher_text_blob.size - CIPHER_PLAIN_LEN_MIN_DIFF; + plain_text_blob.data = (hi_u8 *)req; + + ret = hks_symmetric_decrypt(&key_data_blob, &key_param, &hks_encry_param, &plain_text_blob, &cipher_text_blob); + if (ret != HI_ERR_SUCCESS) { + printf("hks_symmetric_decrypt ret = %d\r\n", ret); + return ret; + } + + return ret; +} + +#define CERT_KEY_LEN 64 +#define CERT_ENC_PARAM_NONCE_SIZE 13 + +hi_u32 hks_set_cert_key_param(hi_u32 key_usage, struct hks_key_param *key_param) +{ + key_param->key_type = HKS_KEY_TYPE_AES; + key_param->key_len = HKS_MAX_KEY_LEN_128; + key_param->key_usage = key_usage; + key_param->key_pad = 1; + key_param->key_mode = HKS_ALG_GCM; + key_param->key_domain = 0; + key_param->key_role = 0; + + key_param->key_auth_id.type = 0; + key_param->key_auth_id.size = 0; + + if (key_param->key_auth_id.data != HI_NULL) { + free(key_param->key_auth_id.data); + key_param->key_auth_id.data = HI_NULL; + } + + return HI_ERR_SUCCESS; +} + +hi_u32 hks_encrypt_cert(struct hks_crypt_param *crypt_param_conn, struct hks_blob *plain_text, + struct hks_blob *cipher_text) +{ + hi_u32 ret; + + hi_u32 key_save_partition_addr = 0; + hi_u32 key_save_partition_size = 0; + ret = app_hks_get_key_store_addr(&key_save_partition_addr, &key_save_partition_size, 1); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + /* get key param */ + struct hks_key_param key_param = {0}; + ret = hi_flash_read(key_save_partition_addr, sizeof(key_param), (hi_u8 *)&key_param); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + key_param.key_usage = HKS_KEY_USAGE_ENCRYPT; + + /* get key data */ + struct hks_blob key_data_blob = {0}; + hi_u32 key_size = 0; + hi_flash_read(key_save_partition_addr + KYY_PARAM_MAX_LEN, LEN_BYTE, (hi_u8 *)&key_size); + hi_u8 key_data[KEY_DATA_MAX_LEN] = {0}; /* 此处不能直接使用flash上数据 */ + ret = hi_flash_read(key_save_partition_addr + KYY_PARAM_MAX_LEN + LEN_BYTE, key_size, &key_data[0]); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + key_data_blob.type = HKS_BLOB_TYPE_ENCRYPTED_KEY; + key_data_blob.data = &key_data[0]; + key_data_blob.size = key_size; + + /* encrypt */ + ret = hks_symmetric_encrypt(&key_data_blob, &key_param, crypt_param_conn, plain_text, cipher_text); + if (ret != HI_ERR_SUCCESS) { + hi_at_printf("hks_symmetric_encrypt ret = %d\n", ret); + return ret; + } + + return ret; +} + +hi_void hks_create_cert_enc_param(encrypt_param *enc_param, struct hks_crypt_param *blob_enc_param) +{ + hi_char nonce_data[CONN_DATA_ENC_PARAM_NONCE_SIZE] = "1234"; + hi_char* aad_data = "a"; + memcpy_s(enc_param->nonce, sizeof(enc_param->nonce), nonce_data, sizeof(nonce_data)); + enc_param->nonce_size = sizeof(nonce_data); + memcpy_s(enc_param->aad, sizeof(enc_param->aad), aad_data, strlen(aad_data)); + enc_param->aad_size = strlen(aad_data); + blob_enc_param->nonce.data = enc_param->nonce; + blob_enc_param->nonce.size = enc_param->nonce_size; + blob_enc_param->aad.data = enc_param->aad; + blob_enc_param->aad.size = enc_param->aad_size; +} + +hi_void hks_get_cert_cipher_data(hi_u32 flash_addr, struct hks_blob *blob_cipher_data, hi_u32 cipher_data_size) +{ + hi_u8 *cipher_data = (hi_u8*)(FLASH_BASE_ADDR + flash_addr + sizeof(encrypt_param)); + blob_cipher_data->data = cipher_data; + blob_cipher_data->size = cipher_data_size - sizeof(encrypt_param); +} + +hi_u32 hks_encrypt_cert_get_cipher(struct hks_crypt_param *param, struct hks_blob *plain_blob, + struct hks_blob *cipher_blob, hi_u32 cert_index) +{ + hi_u32 ret; + /* create cipher blob */ + ret = hks_set_blob(0, plain_blob->size + CIPHER_PLAIN_LEN_MIN_DIFF, "1234", cipher_blob); + if (ret != HI_ERR_SUCCESS) { + hi_at_printf("cipher set blob fail:%d\r\n", cert_index); + return ret; + } + + /* start encrypt */ + ret = hks_encrypt_cert(param, plain_blob, cipher_blob); + if (ret != HI_ERR_SUCCESS) { + free(cipher_blob->data); + cipher_blob->data = HI_NULL; + hi_at_printf("encrypt cert fail:%d\r\n", cert_index); + return ret; + } + + return HI_ERR_SUCCESS; +} + +hi_void free_ciphert_text_blob(struct hks_blob *blob_cipher_text_cert1, struct hks_blob *blob_cipher_text_cert2, + struct hks_blob *blob_cipher_text_key3) +{ + if (blob_cipher_text_cert1->data != HI_NULL) { + free(blob_cipher_text_cert1->data); + blob_cipher_text_cert1->data = HI_NULL; + } + if (blob_cipher_text_cert2->data != HI_NULL) { + free(blob_cipher_text_cert2->data); + blob_cipher_text_cert2->data = HI_NULL; + } + if (blob_cipher_text_key3->data != HI_NULL) { + free(blob_cipher_text_key3->data); + blob_cipher_text_key3->data = HI_NULL; + } +} + +hi_u32 write_cert_text_to_flash(hi_u32 base_addr, encrypt_param *param, struct hks_blob *cipher_blob, + hi_u32 *size_array, hi_u32 cert_index) +{ + hi_u32 ret = HI_ERR_SUCCESS; + + hi_u32 cert_write_addr = base_addr; + if (cert_index != 0) { + int before_total_len = 0; + for (hi_u32 i = 0; i < cert_index; i++) { + before_total_len += size_array[i]; + } + cert_write_addr += before_total_len; + } + + ret |= hi_flash_write(cert_write_addr, sizeof(encrypt_param), (const hi_u8 *)param, HI_TRUE); + ret |= hi_flash_write(cert_write_addr + sizeof(encrypt_param), cipher_blob->size, cipher_blob->data, HI_TRUE); + + return ret; +} + +hi_u32 hks_encrypt_init_plain_blob(struct hks_blob *plain1, struct hks_blob *plain2, struct hks_blob *plain3) +{ + hi_u32 ret; + /* get plain cert store addr */ + hi_u32 cert1_partition_addr, cert1_partition_size, cert2_partition_addr, cert2_partition_size; + hi_u32 key3_partition_addr, key3_partition_size; + ret = app_hks_get_cert_store_addr(&cert1_partition_addr, &cert1_partition_size, 0x0); + ret |= app_hks_get_cert_store_addr(&cert2_partition_addr, &cert2_partition_size, 0x1); + ret |= app_hks_get_cert_store_addr(&key3_partition_addr, &key3_partition_size, 0x2); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + /* get plain cert */ + hi_u32 cert1_plain_addr = FLASH_BASE_ADDR + cert1_partition_addr; + hi_u32 cert2_plain_addr = FLASH_BASE_ADDR + cert2_partition_addr; + hi_u32 key3_plain_addr = FLASH_BASE_ADDR + key3_partition_addr; + + plain1->data = (hi_u8 *)cert1_plain_addr; + plain1->size = cert1_partition_size; + plain2->data = (hi_u8 *)cert2_plain_addr; + plain2->size = cert2_partition_size; + plain3->data = (hi_u8 *)key3_plain_addr; + plain3->size = key3_partition_size; + + return HI_ERR_SUCCESS; +} + +hi_u32 app_hks_generate_cert_key(void) +{ + hi_u32 ret; + hi_u8 *flash_write_buffer = HI_NULL; + + struct hks_key_param conn_key_param = {0}; + struct hks_blob blob_key = {0}; + + hi_u32 key_save_partition_addr = 0; + hi_u32 key_save_partition_size = 0; + ret = app_hks_get_key_store_addr(&key_save_partition_addr, &key_save_partition_size, 1); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + /* set key param */ + ret = hks_set_cert_key_param(HKS_KEY_USAGE_ENCRYPT, &conn_key_param); + if (ret != HI_ERR_SUCCESS) { + printf("hks_set_key_param fail!\r\n"); + return ret; + } + + /* set key blob */ + ret = hks_set_blob(HKS_BLOB_TYPE_BUFFER, CERT_KEY_LEN, "123", &blob_key); + if (ret != HI_ERR_SUCCESS) { + printf("hks_set_blob fail!\r\n"); + return ret; + } + + /* generate key */ + ret = hks_generate_symmetric_key(&blob_key, &conn_key_param); + if (ret != HI_ERR_SUCCESS) { + free(blob_key.data); + printf("hks_generate_symmetric_key ret = %d\n", ret); + return ret; + } + + /* save key param */ + ret = hi_flash_write(key_save_partition_addr, sizeof(conn_key_param), (const hi_u8*)&conn_key_param, HI_TRUE); + if (ret != HI_ERR_SUCCESS) { + free(blob_key.data); + printf("save key param fail, ret:0x%x\r\n", ret); + return ret; + } + + /* save key data */ + flash_write_buffer = malloc(blob_key.size + sizeof(uint32_t)); + if (flash_write_buffer == HI_NULL) { + free(blob_key.data); + return HI_ERR_FAILURE; + } + memcpy_s(flash_write_buffer, sizeof(uint32_t), &(blob_key.size), sizeof(uint32_t)); + memcpy_s(flash_write_buffer + sizeof(uint32_t), key_save_partition_size, blob_key.data, blob_key.size); + ret = hi_flash_write(key_save_partition_addr + KYY_PARAM_MAX_LEN, blob_key.size + sizeof(uint32_t), + flash_write_buffer, HI_TRUE); + free(flash_write_buffer); + free(blob_key.data); + if (ret != HI_ERR_SUCCESS) { + printf("save key data fail, ret:0x%x\r\n", ret); + } + + return ret; +} + +hi_u32 app_hks_encrypt_cert(hi_void) +{ + hi_u32 ret; + + struct hks_blob blob_plain1 = {0}; + struct hks_blob blob_plain2 = {0}; + struct hks_blob blob_plain3 = {0}; + ret = hks_encrypt_init_plain_blob(&blob_plain1, &blob_plain2, &blob_plain3); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + struct hks_blob blob_cipher1 = {0}; + struct hks_blob blob_cipher2 = {0}; + struct hks_blob blob_cipher3 = {0}; + + /* create enc param */ + encrypt_param enc_param = {0}; + struct hks_crypt_param blob_crypt_param_cert = {0}; + hks_create_cert_enc_param(&enc_param, &blob_crypt_param_cert); + + /* start encrypt */ + ret = hks_encrypt_cert_get_cipher(&blob_crypt_param_cert, &blob_plain1, &blob_cipher1, 0x0); + ret |= hks_encrypt_cert_get_cipher(&blob_crypt_param_cert, &blob_plain2, &blob_cipher2, 0x1); + ret |= hks_encrypt_cert_get_cipher(&blob_crypt_param_cert, &blob_plain3, &blob_cipher3, 0x2); + if (ret != HI_ERR_SUCCESS) { + free_ciphert_text_blob(&blob_cipher1, &blob_cipher2, &blob_cipher3); + return ret; + } + + hi_u32 cipher_size_array[0x3] = {blob_cipher1.size, blob_cipher2.size, blob_cipher3.size}; + hi_u32 cipher_text_total_len = cipher_size_array[0x0] + cipher_size_array[0x1] + cipher_size_array[0x2]; + + hi_u32 cipher_store_addr = 0; + hi_u32 cipher_store_size = 0; + app_hks_get_cert_bin_start_store_addr(&cipher_store_addr, &cipher_store_size); + if (cipher_text_total_len > (cipher_store_size - 0x5 * sizeof(hi_u32))) { + hi_at_printf("cipher total len bigger than:%d", cipher_store_size); + free_ciphert_text_blob(&blob_cipher1, &blob_cipher2, &blob_cipher3); + return HI_ERR_FAILURE; + } + + /* overwrite cipher cert to plain cert */ + /* Write Header Structure.CNcomment:写入头结构 */ + hi_u32 cert_start_flag = CERT_KEY_START_FLAG; + hi_u32 cert_total_cnt = 0x3; + ret = hi_flash_write(cipher_store_addr, sizeof(hi_u32), (const hi_u8*)&cert_start_flag, HI_TRUE); + ret = hi_flash_write(cipher_store_addr + sizeof(hi_u32), sizeof(hi_u32), (const hi_u8*)&cert_total_cnt, HI_TRUE); + for (hi_u32 i = 0; i < cert_total_cnt; i++) { + cipher_size_array[i] += sizeof(encrypt_param); + } + ret = hi_flash_write(cipher_store_addr + 0x2 * sizeof(hi_u32), 0x3 * sizeof(hi_u32), + (const hi_u8*)&cipher_size_array, HI_TRUE); + + /* Writing the Ciphertext Certificate/Key Content.CNcomment:写入密文证书/秘钥内容 */ + hi_u32 cert_text_write_addr = cipher_store_addr + 0x5 * sizeof(hi_u32); + /* write cert1 */ + ret = write_cert_text_to_flash(cert_text_write_addr, &enc_param, &blob_cipher1, &cipher_size_array[0], 0x0); + /* write cert2 */ + ret |= write_cert_text_to_flash(cert_text_write_addr, &enc_param, &blob_cipher2, &cipher_size_array[0], 0x1); + /* write cert3 */ + ret |= write_cert_text_to_flash(cert_text_write_addr, &enc_param, &blob_cipher3, &cipher_size_array[0], 0x2); + + free_ciphert_text_blob(&blob_cipher1, &blob_cipher2, &blob_cipher3); + + return ret; +} + +hi_u32 app_hks_decrypt_cert(hi_u32 *plain_size, hi_u8 *plain_data) +{ + hi_u32 ret; + + if (plain_data == HI_NULL) { + return HI_ERR_FAILURE; + } + + hi_u32 key_save_partition_addr = 0; + hi_u32 key_save_partition_size = 0; + ret = app_hks_get_key_store_addr(&key_save_partition_addr, &key_save_partition_size, 1); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + /* get key param */ + struct hks_key_param key_param = {0}; + ret = hi_flash_read(key_save_partition_addr, sizeof(key_param), (hi_u8 *)&key_param); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + key_param.key_usage = HKS_KEY_USAGE_DECRYPT; + + /* get key data */ + struct hks_blob key_data_blob = {0}; + hks_get_key_data(key_save_partition_addr, &key_data_blob); + + /* get cipher text addr and size */ + /* The demo decrypts only the first certificate file.CNcomment:demo仅解密第1个证书文件 */ + hi_u32 cipher_data_save_addr = 0; + hi_u32 cipher_data_size = 0; + ret = app_hks_get_cert_store_addr(&cipher_data_save_addr, &cipher_data_size, 0); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + /* get enc param */ + encrypt_param enc_param = {0}; + struct hks_crypt_param hks_encry_param = {0}; + ret = hks_get_enc_param(cipher_data_save_addr, &enc_param, &hks_encry_param); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + /* get cipher data */ + struct hks_blob cipher_text_blob = {0}; + hks_get_cert_cipher_data(cipher_data_save_addr, &cipher_text_blob, cipher_data_size); + + /* start decrypt */ + struct hks_blob plain_text_blob = {0}; + plain_text_blob.size = cipher_text_blob.size - CIPHER_PLAIN_LEN_MIN_DIFF; + if ((*plain_size) < plain_text_blob.size) { + hi_at_printf("plain_size too small\r\n"); + return HI_ERR_FAILURE; + } + plain_text_blob.data = plain_data; + + ret = hks_symmetric_decrypt(&key_data_blob, &key_param, &hks_encry_param, &plain_text_blob, &cipher_text_blob); + if (ret != HI_ERR_SUCCESS) { + hi_at_printf("hks_symmetric_decrypt ret = %d\r\n", ret); + return ret; + } + *plain_size = plain_text_blob.size; + + return HI_ERR_SUCCESS; +} + +#endif diff --git a/sdk_liteos/components/at/src/at_demo_hks.h b/sdk_liteos/components/at/src/at_demo_hks.h new file mode 100644 index 0000000000000000000000000000000000000000..679312142d0e26700d46f7d944a22d15826b9d92 --- /dev/null +++ b/sdk_liteos/components/at/src/at_demo_hks.h @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __APP_HKS_H__ +#define __APP_HKS_H__ + +#include "hi_wifi_api.h" + +hi_u32 app_hks_generate_conn_key(void); +hi_u32 app_hks_encrypt_conn_para(hi_wifi_assoc_request *req); +hi_u32 app_hks_decrypt_conn_param(hi_wifi_assoc_request *req); + +hi_u32 app_hks_generate_cert_key(void); +hi_u32 app_hks_encrypt_cert(hi_void); +hi_u32 app_hks_decrypt_cert(hi_u32 *plain_size, hi_u8 *plain_data); + +#endif + diff --git a/sdk_liteos/components/at/src/at_general.c b/sdk_liteos/components/at/src/at_general.c new file mode 100644 index 0000000000000000000000000000000000000000..f4f6eec37584dcc2fe9ae46e0d3601fe43d39a82 --- /dev/null +++ b/sdk_liteos/components/at/src/at_general.c @@ -0,0 +1,1636 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "at_general.h" + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef CONFIG_FACTORY_TEST_MODE +#include "lwip/netifapi.h" +#include "lwip/api_shell.h" +#include "lwip/sockets.h" +#ifdef CONFIG_IPERF_SUPPORT +#include "iperf.h" +#endif +#endif +#ifdef CONFIG_SIGMA_SUPPORT +#include "hi_wifitest.h" +#endif +#include "hi_config.h" +#include "sal_common.h" + +#include "at.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif + +#define HI_AT_VER_FULL_PRODUCT_NAME_MAX_SIZE 100 + + +#ifdef CONFIG_IPERF_SUPPORT +HI_EXTERN hi_u32 cmd_iperf(hi_s32 argc, const hi_char **argv); +#endif + +#define IP_LINK_ID_MAX 8 +#define IP_TCP_SERVER_LISTEN_NUM 4 /* TCP Maximum number of clients that can be received by the server */ +#define IP_RESV_BUF_LEN 1024 /* IP packet receiving buffer */ +#define IP_SEND_BUF_LEN 1024 /* IP packet sending buffer, which must be the same as the value of + AT_DATA_MAX_LEN. */ +#define IP_MUX_WAIT_TIME HI_SYS_WAIT_FOREVER +#define PRINT_SIZE_MAX 128 +#define IP_UDP_LINK_MAX 4 /* Maximum number of manually created UDP links */ + +typedef struct { + hi_s32 sfd; + hi_u8 link_stats; + hi_u8 link_res; + hi_u8 ip_protocol; + hi_u8 res; +} ip_conn_ctl_stru; + +typedef struct { + hi_s32 sfd; + hi_u8 link_stats; + hi_u8 res[3]; /* 3 bytes reserved */ +} ip_listen_socket_stru; + +typedef enum { + IP_NULL = 0, + IP_TCP = 1, + IP_UDP = 2, + + IP_PROTOCAL_BUTT +} ip_protocol; +typedef hi_u8 ip_protocol_uint8; + +typedef enum { + IP_LINK_RES_INIT = 0, /* Initial Value */ + IP_LINK_MANUAL = 1, /* Creating a Link manually */ + IP_LINK_AUTO = 2, /* Creating Links automatically */ + + IP_LINK_RES_BUTT +} ip_link_res; +typedef hi_u8 ip_link_res_uint8; + +typedef enum { + IP_LINK_ID_IDLE = 0, /* Idle state */ + IP_LINK_WAIT_RESV, + IP_LINK_WAIT_CLOSE, + IP_LINK_USER_CLOSE, + IP_LINK_SERVER_LISTEN, /* SERVER Listening state */ + + IP_LINK_STAUS_BUTT +} ip_link_stats; +typedef hi_u8 ip_link_stats_uint8; + +#ifndef CONFIG_FACTORY_TEST_MODE +static ip_conn_ctl_stru g_ip_link_ctl[IP_LINK_ID_MAX]; +static hi_s8 g_ip_task_exit; +static ip_listen_socket_stru g_listen_fd; +static hi_s32 g_ip_taskid = -1; +static hi_s8 g_link_id = -1; +static in_addr_t g_peer_ipaddr; +static hi_u16 g_peer_port; +static hi_u32 g_ip_mux_id; +#endif + +hi_u32 at_exe_at_cmd(void) +{ + AT_RESPONSE_OK; + return HI_ERR_SUCCESS; +} + +hi_u32 at_task_show(void) +{ +#ifndef CONFIG_FACTORY_TEST_MODE + TSK_INFO_S* ptask_info = HI_NULL; + + hi_u32 i; + + ptask_info = (TSK_INFO_S*)hi_malloc(HI_MOD_ID_SAL_DFX, sizeof(TSK_INFO_S)); + if (ptask_info == HI_NULL) { + return HI_ERR_MALLOC_FAILUE; + } + + hi_at_printf("task_info:\r\n"); + for (i = 0; i < g_taskMaxNum; i++) { + memset_s(ptask_info, sizeof(TSK_INFO_S), 0, sizeof(TSK_INFO_S)); + hi_u32 ret = LOS_TaskInfoGet(i, ptask_info); + if (ret == HI_ERR_SUCCESS) { + hi_at_printf("%s,id=%d,status=%hd,pri=%hd,size=0x%x,cur_size=0x%x,peak_size=0x%x\r\n", + ptask_info->acName, ptask_info->uwTaskID, ptask_info->usTaskStatus, ptask_info->usTaskPrio, + ptask_info->uwStackSize, ptask_info->uwCurrUsed, ptask_info->uwPeakUsed); + } + } + + hi_free(HI_MOD_ID_SAL_DFX, ptask_info); +#endif + return HI_ERR_SUCCESS; +} + +#ifndef CONFIG_FACTORY_TEST_MODE +hi_u32 at_query_sysinfo_cmd(hi_void) +{ + hi_os_resource_use_stat os_resource_stat = {0}; + hi_mdm_mem_info mem_inf = {0}; + + (hi_void)hi_os_get_resource_status(&os_resource_stat); + (hi_void)hi_mem_get_sys_info(&mem_inf); + + hi_at_printf("+SYSINFO:\r\n"); + hi_at_printf("mem:\r\n"); + hi_at_printf("total=%d,", (mem_inf.total + mem_inf.total_lmp)); + hi_at_printf("used=%d,", (mem_inf.used + mem_inf.used_lmp)); + hi_at_printf("free=%d,", (mem_inf.free + mem_inf.free_lmp)); + hi_at_printf("peek_size=%d\r\n", mem_inf.peek_size); + hi_at_printf("os_resource:\r\n"); + hi_at_printf("timer_usage=%d,", os_resource_stat.timer_usage); + hi_at_printf("task_usage=%d,", os_resource_stat.task_usage); + hi_at_printf("sem_usage=%d,", os_resource_stat.sem_usage); + hi_at_printf("queue_usage=%d,", os_resource_stat.queue_usage); + hi_at_printf("mux_usage=%d,", os_resource_stat.mux_usage); + hi_at_printf("event_usage=%d\r\n", os_resource_stat.event_usage); + + hi_u32 ret = at_task_show(); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + hi_at_printf("cpup:\r\n"); + cmd_get_cpup(0, HI_NULL); + sal_show_run_time(); + + AT_RESPONSE_OK; + + return HI_ERR_SUCCESS; +} +#endif + +hi_u32 at_query_ver_cmd(hi_void) +{ + hi_char soft_ver[HI_AT_VER_FULL_PRODUCT_NAME_MAX_SIZE]; + if (sprintf_s(soft_ver, HI_AT_VER_FULL_PRODUCT_NAME_MAX_SIZE, "+CSV:%s\r\n", + hi_get_sdk_version()) == -1) { + return HI_ERR_FAILURE; + } + + hi_at_printf("%s", soft_ver); + AT_RESPONSE_OK; + + return HI_ERR_SUCCESS; +} + +hi_u32 factory_check_common_head(const hi_upg_common_head *head, hi_u32 bin_len) +{ + if (head->image_id != HI_UPG_FILE_IMAGE_ID) { + return HI_ERR_UPG_IMAGE_ID; + } + + if (head->file_type != HI_UPG_FILE_KERNEL) { + return HI_ERR_UPG_FILE_TYPE; + } + + if (head->file_len > bin_len) { + return HI_ERR_UPG_FILE_LEN_OVER; + } + + if ((head->file_len != (head->section_offset + head->section_len)) || + (head->section_offset != (sizeof(hi_upg_common_head) + sizeof(hi_upg_key) + sizeof(hi_upg_sign))) || + (head->section_len < (sizeof(hi_upg_section_head) + sizeof(upg_rsa_sign)))) { + return HI_ERR_UPG_FILE_LEN; + } + + return HI_ERR_SUCCESS; +} + +hi_u32 factory_check_file(hi_u32 flash_addr, hi_u32 bin_len) +{ + hi_u32 ret; + hi_upg_head *upg_head = (hi_upg_head *)hi_malloc(HI_MOD_ID_SAL_DFX, sizeof(hi_upg_head)); + if (upg_head == HI_NULL) { + return HI_ERR_FAILURE; + } + + ret = hi_flash_read(flash_addr, sizeof(hi_upg_head), (hi_u8 *)upg_head); + if (ret != HI_ERR_SUCCESS) { + hi_free(HI_MOD_ID_SAL_DFX, upg_head); + return HI_ERR_FAILURE; + } + + hi_upg_common_head *common_head = &(upg_head->common); + ret = factory_check_common_head(common_head, bin_len); + + hi_free(HI_MOD_ID_SAL_DFX, upg_head); + + return ret; +} + +static hi_u32 at_factory_mode_switch(hi_s32 argc, const hi_char *argv[]) +{ + if ((argc != 1) || (argv[0] == HI_NULL)) { + return HI_ERR_FAILURE; + } + + if (integer_check(argv[0]) != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + + /* switch_mode:0 normal_mode; switch_mode:1 factory_test_mode */ + hi_u32 switch_mode = strtoul((const hi_char*)argv[0], NULL, 10); /* 10: convert to integer */ + if (switch_mode != 0x0 && switch_mode != 0x1) { + return HI_ERR_FAILURE; + } + + hi_nv_ftm_factory_mode factory_mode_cfg = {0}; + hi_u32 ret = hi_factory_nv_read(HI_NV_FTM_FACTORY_MODE, &factory_mode_cfg, sizeof(hi_nv_ftm_factory_mode), 0); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + if (switch_mode == 0x0) { /* switch to normal mode */ + if (factory_mode_cfg.factory_mode != 0x0) { + factory_mode_cfg.factory_mode = 0x0; + ret = hi_factory_nv_write(HI_NV_FTM_FACTORY_MODE, &factory_mode_cfg, sizeof(factory_mode_cfg), 0); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + /* refresh bachup nv after factory test finish. */ + ret = hi_nv_refresh_backup(); + if (ret != HI_ERR_SUCCESS) { + hi_at_printf("refresh backup nv fail.\r\n"); + return ret; + } + } + } else { /* switch to factory mode */ + if (factory_mode_cfg.factory_valid == 0x0 || + factory_check_file(factory_mode_cfg.factory_addr_start, factory_mode_cfg.factory_size) != HI_ERR_SUCCESS) { + hi_at_printf("invalid factory_bin\r\n"); + return HI_ERR_FAILURE; + } + + if (factory_mode_cfg.factory_mode == 0x0) { + factory_mode_cfg.factory_mode = 0x1; + ret = hi_factory_nv_write(HI_NV_FTM_FACTORY_MODE, &factory_mode_cfg, sizeof(factory_mode_cfg), 0); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + } + } + + AT_RESPONSE_OK; + + return HI_ERR_SUCCESS; +} + +static hi_u32 at_factory_mode_query(hi_void) +{ +#ifndef CONFIG_FACTORY_TEST_MODE + hi_at_printf("non_factory mode\r\n"); +#else + hi_at_printf("factory mode\r\n"); +#endif + + AT_RESPONSE_OK; + + return HI_ERR_SUCCESS; +} + +#ifndef CONFIG_FACTORY_TEST_MODE +static hi_u32 at_factory_erase(hi_void) +{ + hi_nv_ftm_factory_mode factory_mode_cfg = {0}; + hi_u32 ret = hi_factory_nv_read(HI_NV_FTM_FACTORY_MODE, &factory_mode_cfg, sizeof(hi_nv_ftm_factory_mode), 0); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + hi_at_printf("erase addr:0x%x, size:0x%x.\r\n", factory_mode_cfg.factory_addr_start, factory_mode_cfg.factory_size); + ret = hi_flash_erase(factory_mode_cfg.factory_addr_start, factory_mode_cfg.factory_size); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + /* set normal mode after erase factory. inorder to let start success after reboot. */ + if (factory_mode_cfg.factory_mode != 0) { + factory_mode_cfg.factory_mode = 0x0; + ret = hi_factory_nv_write(HI_NV_FTM_FACTORY_MODE, &factory_mode_cfg, sizeof(factory_mode_cfg), 0); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + } + + AT_RESPONSE_OK; + + return HI_ERR_SUCCESS; +} +#endif + +hi_void at_exe_reset_cmd(hi_void) +{ + AT_RESPONSE_OK; + hi_watchdog_disable(); + /* Wait for 3000 μs until the AT_RESPONSE_OK print is complete.CNcomment:延时3000us, 待AT_RESPONSE_OK打印结束 */ + hi_udelay(3000); + hi_soft_reboot(HI_SYS_REBOOT_CAUSE_CMD); +} + +hi_u32 at_setup_reset_cmd(hi_s32 argc, const hi_char *argv[]) +{ + hi_u32 delay; + if ((argc != 1) || (argv[0] == HI_NULL)) { + return HI_ERR_FAILURE; + } + + if (integer_check(argv[0]) != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + + hi_watchdog_disable(); + delay = strtoul((const hi_char*)argv[0], NULL, 10); /* 10:Decimal */ + hi_at_printf("+RST:%u\r\n", delay); + hi_udelay(delay); + + AT_RESPONSE_OK; + hi_udelay(3000); /* Wait for 3000 μs until the AT_RESPONSE_OK message is displayed. */ + hi_soft_reboot(HI_SYS_REBOOT_CAUSE_CMD); + + return HI_ERR_SUCCESS; +} + +hi_u32 at_exe_help_cmd(void) +{ + at_cmd_func_list *cmd_list = at_get_list(); + hi_u32 i; + hi_u32 cnt = 0; + + hi_at_printf("+HELP:\r\n"); + for (i = 0; i < AT_CMD_LIST_NUM; i++) { + hi_u16 j; + + for (j = 0; j < cmd_list->at_cmd_num[i]; j++) { + at_cmd_func *cmd_func = (at_cmd_func *) ((cmd_list->at_cmd_list[i] + j)); + + hi_at_printf("AT%-16s ", cmd_func->at_cmd_name); + cnt++; + if (cnt % 4 == 0) { /* 每4个换行 */ + hi_at_printf("\r\n"); + } + } + } + + AT_ENTER; + AT_RESPONSE_OK; + return HI_ERR_SUCCESS; +} + +/***************************************************************************** + Description: Sets the MAC address. +*****************************************************************************/ +hi_u32 cmd_set_macaddr(hi_s32 argc, const hi_char* argv[]) +{ + hi_uchar mac_addr[6]; /* 6 mac len */ + + if (argc != 1) { + return HI_ERR_FAILURE; + } + if (at_param_null_check(argc, argv) == HI_ERR_FAILURE) { + return HI_ERR_FAILURE; + } + + if (strlen(argv[0]) != 17) { /* 17 mac string len */ + return HI_ERR_FAILURE; + } + + hi_u32 ret = cmd_strtoaddr(argv[0], mac_addr, 6); /* 6 mac len */ + if (ret != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + + if (hi_wifi_set_macaddr((hi_char*)mac_addr, 6) != 0) { /* 6 mac len */ + return HI_ERR_FAILURE; + } + hi_at_printf("OK\r\n"); + return HI_ERR_SUCCESS; +} + +/***************************************************************************** + Description: Gets the MAC address. +*****************************************************************************/ +hi_u32 cmd_get_macaddr(hi_s32 argc, const hi_char* argv[]) +{ + hi_uchar mac_addr[6] = {0}; /* 6 mac len */ + hi_unref_param(argc); + hi_unref_param(argv); + + if (hi_wifi_get_macaddr((hi_char*)mac_addr, 6) != HI_ERR_SUCCESS) { /* 6 mac len */ + return HI_ERR_FAILURE; + } + hi_at_printf("+MAC:" AT_MACSTR "\r\n", at_mac2str(mac_addr)); + hi_at_printf("OK\r\n"); + + return HI_ERR_SUCCESS; +} + +#ifndef CONFIG_FACTORY_TEST_MODE +#ifdef CONFIG_IPERF_SUPPORT +hi_u32 at_iperf(hi_s32 argc, const hi_char **argv) +{ + if (at_param_null_check(argc, argv) == HI_ERR_FAILURE) { + return HI_ERR_FAILURE; + } + if (cmd_iperf(argc, argv) == 0) { + return HI_ERR_SUCCESS; + } + + return HI_ERR_FAILURE; +} +#endif + +hi_u32 at_ping(hi_s32 argc, const hi_char **argv) +{ + if (at_param_null_check(argc, argv) == HI_ERR_FAILURE) { + return HI_ERR_FAILURE; + } + if (os_shell_ping(argc, argv) == LOS_OK) { + return HI_ERR_SUCCESS; + } + + return HI_ERR_FAILURE; +} + +hi_u32 at_ping6(hi_s32 argc, const hi_char **argv) +{ + if (at_param_null_check(argc, argv) == HI_ERR_FAILURE) { + return HI_ERR_FAILURE; + } + if (os_shell_ping6(argc, argv) == LOS_OK) { + return HI_ERR_SUCCESS; + } + + return HI_ERR_FAILURE; +} + +hi_u32 at_dns(hi_s32 argc, const hi_char **argv) +{ + if (at_param_null_check(argc, argv) == HI_ERR_FAILURE) { + return HI_ERR_FAILURE; + } + if (os_shell_dns(argc, argv) == LOS_OK) { + return HI_ERR_SUCCESS; + } + + return HI_ERR_FAILURE; +} + +hi_u32 at_show_dns(hi_s32 argc, hi_char **argv) +{ + hi_unref_param(argc); + hi_unref_param(argv); + if (os_shell_show_dns() == LOS_OK) { + return HI_ERR_SUCCESS; + } + + return HI_ERR_FAILURE; +} + +hi_u32 at_netstat(hi_s32 argc, hi_char **argv) +{ + if (os_shell_netstat(argc, argv) == LOS_OK) { + return HI_ERR_SUCCESS; + } + + return HI_ERR_FAILURE; +} + +hi_u32 at_setup_dhcp(hi_s32 argc, const hi_char **argv) +{ + hi_s32 ret = 0; + + if (at_param_null_check(argc, argv) == HI_ERR_FAILURE) { + return HI_ERR_FAILURE; + } + + if (argc != 2) { /* at+dhcp cmd length equl 2 */ + return HI_ERR_FAILURE; + } +#ifndef CONFIG_FACTORY_TEST_MODE + struct netif *netif_p = netifapi_netif_find(argv[0]); + if (netif_p == NULL) { + return HI_ERR_FAILURE; + } + + if (strcmp(argv[1], "1") == 0) { + ret = netifapi_dhcp_start(netif_p); + } else if (strcmp(argv[1], "0") == 0) { + ret = netifapi_dhcp_stop(netif_p); + } else if (strcmp(argv[1], "2") == 0) { + ret = netifapi_netif_common(netif_p, dhcp_clients_info_show, NULL); + } else { + return HI_ERR_FAILURE; + } +#endif + if (ret == LOS_OK) { + hi_at_printf("OK\r\n"); + } + + return ret; +} + +hi_u32 at_setup_dhcps(hi_s32 argc, const hi_char **argv) +{ + hi_s32 ret = 0; + + if (at_param_null_check(argc, argv) == HI_ERR_FAILURE) { + return HI_ERR_FAILURE; + } + + if (argc != 2) { /* at+dhcps cmd length equl 2 */ + return HI_ERR_FAILURE; + } +#ifndef CONFIG_FACTORY_TEST_MODE + struct netif *netif_p = netifapi_netif_find(argv[0]); + if (netif_p == NULL) { + return HI_ERR_FAILURE; + } + if (ip_addr_isany_val(netif_p->ip_addr)) { + hi_at_printf("Please set ip address for dhcp server\r\n"); + return HI_ERR_FAILURE; + } + if (strcmp(argv[1], "1") == 0) { + ret = netifapi_dhcps_start(netif_p, NULL, 0); + } else if (strcmp(argv[1], "0") == 0) { + ret = netifapi_dhcps_stop(netif_p); + } else { + return HI_ERR_FAILURE; + } +#endif + if (ret == LOS_OK) { + hi_at_printf("OK\r\n"); + } + + return ret; +} + +hi_u32 at_get_dump(hi_s32 argc, const hi_char **argv) +{ + hi_unref_param(argc); + hi_unref_param(argv); + hi_u32 ret; + + hi_u16 err_id = 0; + hi_u32 rid = 0; + ret = hi_syserr_get_reboot_reason(&err_id, &rid); + if (ret == HI_ERR_SUCCESS) { + hi_at_printf("latest reboot reason:\r\n"); + hi_at_printf("eid:%d, rid:%d:\r\n", err_id, rid); + } + hi_at_printf("\r\nlatest crash info:\r\n"); + + hi_syserr_info* info = hi_malloc(HI_MOD_ID_SAL_DFX, sizeof(hi_syserr_info)); + if (info == HI_NULL) { + return HI_ERR_MALLOC_FAILUE; + } + + ret = hi_syserr_get_at_printf(info); + if (ret == HI_ERR_SYSERROR_NOT_FOUND) { + hi_at_printf("No crash dump found!\r\n"); + hi_at_printf("OK\r\n"); + ret = HI_ERR_SUCCESS; + } else if (ret == HI_ERR_SUCCESS) { + hi_at_printf("OK\r\n"); + ret = HI_ERR_SUCCESS; + } + hi_free(HI_MOD_ID_SAL_DFX, info); + + return ret; +} +#endif + +hi_u32 lwip_ifconfig_check(hi_s32 argc, const hi_char **argv) +{ + if ((argc == 0) || (argc == 1)) { + return HI_ERR_SUCCESS; + } else if (argc == 2) { /* 2 Parameters */ + if ((strcmp("up", argv[1]) == 0) || (strcmp("down", argv[1]) == 0)) { + return HI_ERR_SUCCESS; + } else { + return HI_ERR_FAILURE; + } + } else if (argc == 6) { /* 6 Parameter */ + if ((strcmp("netmask", argv[2]) == 0) && (strcmp("gateway", argv[4]) == 0) && /* 2/4:Members of parameters */ + (strcmp("inet", argv[1]) != 0) && (strcmp("inet6", argv[1]) != 0)) { + return HI_ERR_SUCCESS; + } else { + return HI_ERR_FAILURE; + } + } else { + return HI_ERR_FAILURE; + } +} + +hi_u32 at_lwip_ifconfig(hi_s32 argc, const hi_char **argv) +{ + if (at_param_null_check(argc, argv) == HI_ERR_FAILURE) { + return HI_ERR_FAILURE; + } + + hi_u32 ret = lwip_ifconfig_check(argc, argv); + if (ret != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } +#ifndef CONFIG_FACTORY_TEST_MODE + if (argc == 2) { /* 2:Number of parameters */ + struct netif *netif = netifapi_netif_find(argv[0]); + if (netif == HI_NULL) { + return HI_ERR_FAILURE; + } + ip4_addr_t loop_ipaddr, loop_netmask, loop_gw; + if (strcmp(argv[1], "down") == 0) { + (void)netifapi_netif_set_link_down(netif); + (void)netifapi_netif_set_down(netif); + (void)netif_l2_netdev_status_callback(netif); + (void)netifapi_netif_set_addr(netif, HI_NULL, HI_NULL, HI_NULL); + for (hi_u8 index = 0; index < LWIP_IPV6_NUM_ADDRESSES; index++) { + (void)netifapi_netif_rmv_ip6_address(netif, &netif->ip6_addr[index]); + } + } else if (strcmp(argv[1], "up") == 0) { + (void)netifapi_netif_set_up(netif); + (void)netif_l2_netdev_status_callback(netif); + if ((strcmp(argv[0], DEFAULT_IFNAME_AP) == 0) || (strcmp(argv[0], DEFAULT_IFNAME_MESH) == 0)) { + (void)netifapi_netif_set_link_up(netif); + (hi_void)netifapi_netif_add_ip6_linklocal_address(netif, HI_TRUE); + } else if (strcmp(argv[0], DEFAULT_IFNAME_LOCALHOST) == 0) { + (void)netifapi_netif_set_link_up(netif); + IP4_ADDR(&loop_gw, 127, 0, 0, 1); /* gateway 127.0.0.1 */ + IP4_ADDR(&loop_ipaddr, 127, 0, 0, 1); /* ipaddr 127.0.0.1 */ + IP4_ADDR(&loop_netmask, 255, 0, 0, 0); /* netmask 255.0.0.0 */ + (void)netifapi_netif_set_addr(netif, &loop_ipaddr, &loop_netmask, &loop_gw); + (void)netifapi_netif_set_up(netif); + } + } + } else { + ret = lwip_ifconfig(argc, argv); + if (ret == 0) { + return HI_ERR_SUCCESS; + } else if (ret == 3) { /* 3:up down execution succeeded. */ + hi_at_printf("OK\r\n"); + return HI_ERR_SUCCESS; + } + return HI_ERR_FAILURE; + } +#endif + hi_at_printf("OK\r\n"); + return HI_ERR_SUCCESS; +} + +#ifndef CONFIG_FACTORY_TEST_MODE + +static hi_void ip_link_release(hi_u8 link_id) +{ + closesocket(g_ip_link_ctl[link_id].sfd); + g_ip_link_ctl[link_id].sfd = -1; + g_ip_link_ctl[link_id].link_stats = IP_LINK_ID_IDLE; + g_ip_link_ctl[link_id].link_res = IP_LINK_RES_INIT; + g_ip_link_ctl[link_id].ip_protocol = IP_NULL; +} + +static hi_u32 ip_is_all_link_idle(hi_void) +{ + int i; + hi_mux_pend(g_ip_mux_id, IP_MUX_WAIT_TIME); + for (i = 0; i < IP_LINK_ID_MAX; i++) { + if (g_ip_link_ctl[i].link_stats != IP_LINK_ID_IDLE) { + hi_mux_post(g_ip_mux_id); + return HI_ERR_FAILURE; + } + } + hi_mux_post(g_ip_mux_id); + return HI_ERR_SUCCESS; +} + +static hi_void ip_monitor_link_close(hi_void) +{ + hi_u8 i; + hi_mux_pend(g_ip_mux_id, IP_MUX_WAIT_TIME); + for (i = 0; i < IP_LINK_ID_MAX; i++) { + if (g_ip_link_ctl[i].link_stats == IP_LINK_WAIT_CLOSE) { + hi_at_printf("link %d CLOSED\r\n", i); + ip_link_release(i); + } else if (g_ip_link_ctl[i].link_stats == IP_LINK_USER_CLOSE) { + hi_at_printf("link %d CLOSED\r\n", i); + ip_link_release(i); + hi_at_printf("OK\r\n"); + } + } + + if (g_listen_fd.link_stats == IP_LINK_WAIT_CLOSE) { + closesocket(g_listen_fd.sfd); + g_listen_fd.sfd = -1; + g_listen_fd.link_stats = IP_LINK_ID_IDLE; + } else if (g_listen_fd.link_stats == IP_LINK_USER_CLOSE) { + closesocket(g_listen_fd.sfd); + g_listen_fd.sfd = -1; + g_listen_fd.link_stats = IP_LINK_ID_IDLE; + hi_at_printf("OK\r\n"); + } + hi_mux_post(g_ip_mux_id); +} + +static hi_void ip_set_monitor_socket(fd_set *read_set, hi_s32 *sfd_max) +{ + hi_s32 sfd_max_inter = 0; + hi_u8 i; + hi_mux_pend(g_ip_mux_id, IP_MUX_WAIT_TIME); + for (i = 0; i < IP_LINK_ID_MAX; i++) { + if (g_ip_link_ctl[i].link_stats == IP_LINK_WAIT_RESV) { + FD_SET(g_ip_link_ctl[i].sfd, read_set); + if (g_ip_link_ctl[i].sfd > sfd_max_inter) { + sfd_max_inter = g_ip_link_ctl[i].sfd; + } + } + } + if (g_listen_fd.link_stats == IP_LINK_SERVER_LISTEN) { + FD_SET(g_listen_fd.sfd, read_set); + if (g_listen_fd.sfd > sfd_max_inter) { + sfd_max_inter = g_listen_fd.sfd; + } + } + *sfd_max = sfd_max_inter; + hi_mux_post(g_ip_mux_id); + + return; +} + +static hi_u32 ip_ip_resv_show_msg(hi_u8 link_id) +{ + struct sockaddr_in cln_addr = {0}; + socklen_t cln_addr_len = (socklen_t)sizeof(cln_addr); + hi_u32 print_len = 0; + hi_s32 ret; + + hi_char *ip_buffer = (hi_char*)malloc(IP_RESV_BUF_LEN + 1); + if (ip_buffer == HI_NULL) { + printf("{ip_ip_resv_output:ip buffer malloc fail}\r\n"); + return HI_ERR_FAILURE; + } + + memset_s(ip_buffer, IP_RESV_BUF_LEN + 1, 0, IP_RESV_BUF_LEN + 1); + errno = 0; + ret = recvfrom(g_ip_link_ctl[link_id].sfd, ip_buffer, IP_RESV_BUF_LEN, 0, + (struct sockaddr *)&cln_addr, (socklen_t *)&cln_addr_len); + if (ret < 0) { + hi_at_printf("link %d RESV FAIL\r\n", link_id); + if ((errno != EINTR) && (errno != EAGAIN)) { + g_ip_link_ctl[link_id].link_stats = IP_LINK_WAIT_CLOSE; + } + free(ip_buffer); + return HI_ERR_FAILURE; + } else if (ret == 0) { + g_ip_link_ctl[link_id].link_stats = IP_LINK_WAIT_CLOSE; + free(ip_buffer); + return HI_ERR_FAILURE; + } + + if (ret < PRINT_SIZE_MAX) { + hi_at_printf("\r\n+IPD,%d,%d,%s,%d:%s", link_id, ret, inet_ntoa(cln_addr.sin_addr), htons(cln_addr.sin_port), + ip_buffer); + } else if ((ret >= PRINT_SIZE_MAX) && (ret <= IP_RESV_BUF_LEN)) { + hi_at_printf("\r\n+IPD,%d,%d,%s,%d:", link_id, ret, inet_ntoa(cln_addr.sin_addr), htons(cln_addr.sin_port)); + do { + char print_out_buff[PRINT_SIZE_MAX] = {0}; + if ((memset_s(print_out_buff, sizeof(print_out_buff), 0x0, sizeof(print_out_buff)) != EOK) || + (memcpy_s(print_out_buff, sizeof(print_out_buff) - 1, ip_buffer + print_len, + sizeof(print_out_buff)-1) != EOK)) { + printf("{ip_ip_resv_output: print_out_buff memset_s/memcpy_s fail\r\n}"); + } + hi_at_printf("%s", print_out_buff); + + ret -= sizeof(print_out_buff) - 1; + print_len += sizeof(print_out_buff) - 1; + } while (ret >= (PRINT_SIZE_MAX - 1)); + + if (ret > 0) { + hi_at_printf("%s", ip_buffer + print_len); + } + } + free(ip_buffer); + return HI_ERR_SUCCESS; +} + +static hi_void ip_ip_resv_output(const fd_set *read_set) +{ + hi_u8 link_id; + + hi_mux_pend(g_ip_mux_id, IP_MUX_WAIT_TIME); + for (link_id = 0; link_id < IP_LINK_ID_MAX; link_id++) { + if ((g_ip_link_ctl[link_id].link_stats == IP_LINK_WAIT_RESV) && (FD_ISSET(g_ip_link_ctl[link_id].sfd, + read_set))) { + if (ip_ip_resv_show_msg(link_id) != HI_ERR_SUCCESS) { + continue; + } + } + } + hi_mux_post(g_ip_mux_id); + return; +} + +static hi_void ip_tcp_accept(hi_void) +{ + struct sockaddr_in cln_addr = {0}; + socklen_t cln_addr_len = (socklen_t)sizeof(cln_addr); + hi_s32 resv_fd; + hi_s8 link_id = -1; + hi_s8 i; + hi_u32 opt = 1; + + hi_mux_pend(g_ip_mux_id, IP_MUX_WAIT_TIME); + resv_fd = accept(g_listen_fd.sfd, (struct sockaddr *)&cln_addr, (socklen_t *)&cln_addr_len); + if (resv_fd < 0) { + printf("{accept failed, return is %d}\r\n", resv_fd); + hi_mux_post(g_ip_mux_id); + return; + } + + /* An unused link ID is found.CNcomment:找到一个没有被使用的link id */ + for (i = 0; i < IP_LINK_ID_MAX; i++) { + if (g_ip_link_ctl[i].link_stats == IP_LINK_ID_IDLE) { + link_id = i; + break; + } + } + if ((i >= IP_LINK_ID_MAX) || (link_id == -1)) { + hi_at_printf("no link id to use now\r\n"); + closesocket(resv_fd); + hi_mux_post(g_ip_mux_id); + return; + } + setsockopt(g_ip_link_ctl[link_id].sfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)); + /* Updating Connection Information */ + g_ip_link_ctl[link_id].sfd = resv_fd; + g_ip_link_ctl[link_id].link_stats = IP_LINK_WAIT_RESV; + g_ip_link_ctl[link_id].link_res = IP_LINK_AUTO; + g_ip_link_ctl[link_id].ip_protocol = IP_TCP; + hi_at_printf("%d,CONNECT\r\n", link_id); + hi_mux_post(g_ip_mux_id); + + return; +} + +static hi_void ip_monitor(hi_void) +{ + hi_s32 sfd_max; + fd_set read_set; + struct timeval time_val; + hi_s32 ret; + int i; + + hi_mux_create(&g_ip_mux_id); + g_ip_task_exit = 0; + while (!g_ip_task_exit) { + hi_cpup_load_check_proc(hi_task_get_current_id(), LOAD_SLEEP_TIME_DEFAULT); + /* When all links are in the idle state and no socket is listened on, exit ip_monitor. */ + if ((ip_is_all_link_idle() == HI_ERR_SUCCESS) && (g_listen_fd.link_stats == IP_LINK_ID_IDLE)) { + hi_mux_delete(g_ip_mux_id); + g_ip_task_exit = 1; + continue; + } + + ip_monitor_link_close(); + + FD_ZERO(&read_set); + sfd_max = 0; + ip_set_monitor_socket(&read_set, &sfd_max); + time_val.tv_sec = 0; + time_val.tv_usec = 500000; /* 500000 Timeout interval is 500ms */ + ret = lwip_select(sfd_max + 1, &read_set, 0, 0, &time_val); + if (ret < 0) { + printf("{ip_monitor : socket select failure\r\n"); + goto failure; + } else if (ret == 0) { + continue; + } + ip_ip_resv_output(&read_set); + + if ((g_listen_fd.link_stats == IP_LINK_SERVER_LISTEN) && (FD_ISSET(g_listen_fd.sfd, &read_set))) { + ip_tcp_accept(); + } + } + g_ip_taskid = -1; + return; + +failure: + for (i = 0; i < IP_LINK_ID_MAX; i++) { + if (g_ip_link_ctl[i].link_stats != IP_LINK_ID_IDLE) { + ip_link_release(i); + } + } + if (g_listen_fd.link_stats != IP_LINK_ID_IDLE) { + closesocket(g_listen_fd.sfd); + g_listen_fd.sfd = -1; + g_listen_fd.link_stats = IP_LINK_ID_IDLE; + } + g_ip_taskid = -1; + printf("{ip_monitor : ip monitor exit}\r\n"); +} + +static hi_u32 ip_creat_ip_task(hi_void) +{ +#if LWIP_LITEOS_TASK + TSK_INIT_PARAM_S start_ip_task; + if (g_ip_taskid > 0) { + return HI_ERR_SUCCESS; + } + start_ip_task.pfnTaskEntry = (TSK_ENTRY_FUNC)ip_monitor; + start_ip_task.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE; + start_ip_task.pcName = "at_ip_monitor_task"; + start_ip_task.usTaskPrio = 28; /* 28:Task Priority */ + start_ip_task.uwResved = LOS_TASK_STATUS_DETACHED; + hi_u32 ret = LOS_TaskCreate((UINT32 *)(&g_ip_taskid), &start_ip_task); + if (ret != HI_ERR_SUCCESS) { + printf("{ip_creat_ip_task:task create failed 0x%08x.}\r\n", ret); + return HI_ERR_FAILURE; + } +#endif + return HI_ERR_SUCCESS; +} + +static void ip_set_tcp_link_info(hi_u8 link_id, hi_s32 sfd) +{ + hi_mux_pend(g_ip_mux_id, IP_MUX_WAIT_TIME); + g_ip_link_ctl[link_id].sfd = sfd; + g_ip_link_ctl[link_id].link_stats = IP_LINK_WAIT_RESV; + g_ip_link_ctl[link_id].link_res = IP_LINK_MANUAL; + g_ip_link_ctl[link_id].ip_protocol = IP_TCP; + hi_mux_post(g_ip_mux_id); +} + +static hi_u32 ip_start_tcp_client(hi_u8 link_id, const hi_char *peer_ipaddr, hi_u16 peer_port) +{ + hi_s32 ret; + hi_u32 opt = 0; + hi_s32 tos; + struct sockaddr_in srv_addr = {0}; + + if (link_id >= IP_LINK_ID_MAX) { + return HI_ERR_FAILURE; + } + hi_mux_pend(g_ip_mux_id, IP_MUX_WAIT_TIME); + if (g_ip_link_ctl[link_id].link_stats != IP_LINK_ID_IDLE) { + hi_at_printf("invalid link\r\n"); + hi_mux_post(g_ip_mux_id); + return HI_ERR_FAILURE; + } + hi_mux_post(g_ip_mux_id); + + hi_s32 sfd = socket(AF_INET, SOCK_STREAM, 0); + if (sfd == -1) { + printf("{ip_start_tcp_client: socket fail}\r\n"); + return HI_ERR_FAILURE; + } + + setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)); + tos = 128; /* 128:TOS设定为128,对应tid = 4,WLAN_WME_AC_VI */ + ret = setsockopt(sfd, IPPROTO_IP, IP_TOS, &tos, sizeof(tos)); + if (ret) { + printf("{ip_start_tcp_client: setsockopt TOPS fail, return is %d}\r\n", ret); + closesocket(sfd); + return HI_ERR_FAILURE; + } + srv_addr.sin_family = AF_INET; + srv_addr.sin_addr.s_addr = inet_addr(peer_ipaddr); + srv_addr.sin_port = htons (peer_port); + ret = connect(sfd, (struct sockaddr *)&srv_addr, sizeof(srv_addr)); + if (ret != 0) { + printf("{ip_start_tcp_client: connect fail, return is %d}\r\n", ret); + closesocket(sfd); + return HI_ERR_FAILURE; + } + + ip_set_tcp_link_info(link_id, sfd); + if (ip_creat_ip_task() != HI_ERR_SUCCESS) { + printf("{ip_start_tcp_client: creat ip task fail}\r\n"); + hi_mux_pend(g_ip_mux_id, IP_MUX_WAIT_TIME); + ip_link_release(link_id); + hi_mux_post(g_ip_mux_id); + return HI_ERR_FAILURE; + } + + return HI_ERR_SUCCESS; +} + +static hi_u32 ip_has_idle_udp_link(hi_void) +{ + hi_u8 udp_link_count = 0; + hi_u8 link_id; + + hi_mux_pend(g_ip_mux_id, IP_MUX_WAIT_TIME); + for (link_id = 0; link_id < IP_LINK_ID_MAX; link_id++) { + if (g_ip_link_ctl[link_id].ip_protocol == IP_UDP) { + udp_link_count++; + } + } + hi_mux_post(g_ip_mux_id); + if (udp_link_count >= IP_UDP_LINK_MAX) { + return HI_ERR_FAILURE; + } + return HI_ERR_SUCCESS; +} + +static hi_void ip_set_udp_link_info(hi_u8 link_id, hi_s32 sfd) +{ + hi_mux_pend(g_ip_mux_id, IP_MUX_WAIT_TIME); + g_ip_link_ctl[link_id].sfd = sfd; + g_ip_link_ctl[link_id].link_stats = IP_LINK_WAIT_RESV; + g_ip_link_ctl[link_id].link_res = IP_LINK_MANUAL; + g_ip_link_ctl[link_id].ip_protocol = IP_UDP; + hi_mux_post(g_ip_mux_id); +} + +static hi_u32 ip_start_udp(hi_u8 link_id, hi_u16 local_port) +{ + struct sockaddr_in srv_addr = {0}; + hi_s32 ret; + hi_u32 opt = 0; + hi_u32 tos; + + if ((link_id >= IP_LINK_ID_MAX) || (ip_has_idle_udp_link() != HI_ERR_SUCCESS)) { + return HI_ERR_FAILURE; + } + hi_mux_pend(g_ip_mux_id, IP_MUX_WAIT_TIME); + if (g_ip_link_ctl[link_id].link_stats != IP_LINK_ID_IDLE) { + hi_at_printf("invalid link\r\n"); + hi_mux_post(g_ip_mux_id); + return HI_ERR_FAILURE; + } + hi_mux_post(g_ip_mux_id); + + hi_s32 sfd = socket(AF_INET, SOCK_DGRAM, 0); + if (sfd == -1) { + printf("{ip_start_udp: socket fail}\r\n"); + return HI_ERR_FAILURE; + } + + srv_addr.sin_family = AF_INET; + srv_addr.sin_addr.s_addr = htonl(INADDR_ANY); + srv_addr.sin_port = htons(local_port); + ret = bind(sfd, (struct sockaddr*)&srv_addr, sizeof(srv_addr)); + if (ret != 0) { + printf("{ip_start_udp:bind failed, return is %d}\r\n", ret); + closesocket(sfd); + return HI_ERR_FAILURE; + } + setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)); + tos = 128; /* 128:TOS is set to 128, corresponding to tid = 4,WLAN_WME_AC_VI */ + ret = setsockopt(sfd, IPPROTO_IP, IP_TOS, &tos, sizeof(tos)); + if (ret) { + printf("{ip_start_udp: setsockopt TOPS fail, return is %d}\r\n", ret); + closesocket(sfd); + return HI_ERR_FAILURE; + } + + ip_set_udp_link_info(link_id, sfd); + if (ip_creat_ip_task() != HI_ERR_SUCCESS) { + printf("{ip_start_tcp_client: creat ip task fail}\r\n"); + hi_mux_pend(g_ip_mux_id, IP_MUX_WAIT_TIME); + ip_link_release(link_id); + hi_mux_post(g_ip_mux_id); + return HI_ERR_FAILURE; + } + + return HI_ERR_SUCCESS; +} + +static hi_u32 at_start_ip(hi_s32 argc, const hi_char **argv) +{ + hi_u8 link_id; + hi_u16 peer_port; + hi_u16 local_port; + + if (((argc != 3) && (argc != 4)) || (at_param_null_check(argc, argv) == HI_ERR_FAILURE)) { /* 3 4 */ + return HI_ERR_FAILURE; + } + + if (integer_check(argv[0]) == HI_ERR_FAILURE) { + return HI_ERR_FAILURE; + } + link_id = (hi_u8)atoi(argv[0]); + const hi_char *protocol = argv[1]; + + if (strcmp(protocol, "tcp") == 0) { + if ((argc != 4) || (integer_check(argv[3]) == HI_ERR_FAILURE)) { /* 4 3 Parameter verification */ + return HI_ERR_FAILURE; + } + const hi_char *peer_ipaddr = argv[2]; /* 2 Parameter verification */ + peer_port = (hi_u16)atoi(argv[3]); /* 3 Parameter verification */ + if (ip_start_tcp_client(link_id, peer_ipaddr, peer_port) != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + } else if (strcmp(protocol, "udp") == 0) { + if ((argc != 3) || (integer_check(argv[2]) == HI_ERR_FAILURE)) { /* 3 2 Parameter verification */ + return HI_ERR_FAILURE; + } + local_port = (hi_u16)atoi(argv[2]); /* 2 Parameter verification */ + if (ip_start_udp(link_id, local_port) != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + } else { + return HI_ERR_FAILURE; + } + hi_at_printf("OK\r\n"); + return HI_ERR_SUCCESS; +} + +static hi_void ip_tcp_send(hi_u8 link_id, const hi_char *send_msg) +{ + hi_s32 ret; + hi_u32 send_len; + send_len = strlen(send_msg); + hi_mux_pend(g_ip_mux_id, IP_MUX_WAIT_TIME); + ret = send(g_ip_link_ctl[link_id].sfd, send_msg, send_len, 0); + hi_mux_post(g_ip_mux_id); + if (ret <= 0) { + hi_at_printf("ERROR\r\n"); + return; + } + hi_at_printf("SEND %d bytes\r\nOK\r\n", ret); + return; +} + +static hi_void ip_udp_send(hi_u8 link_id, in_addr_t peer_ipaddr, hi_u16 peer_port, const hi_char *send_msg) +{ + hi_s32 ret; + struct sockaddr_in cln_addr = {0}; + hi_u32 send_len; + send_len = strlen(send_msg); + cln_addr.sin_family = AF_INET; + cln_addr.sin_addr.s_addr = peer_ipaddr; + cln_addr.sin_port = htons(peer_port); + hi_mux_pend(g_ip_mux_id, IP_MUX_WAIT_TIME); + ret = sendto(g_ip_link_ctl[link_id].sfd, send_msg, send_len, 0, + (struct sockaddr *)&cln_addr, (socklen_t)sizeof(cln_addr)); + hi_mux_post(g_ip_mux_id); + if (ret <= 0) { + hi_at_printf("ERROR\r\n"); + return; + } + hi_at_printf("SEND %d bytes\r\nOK\r\n", ret); + return; +} + +static hi_u32 at_ip_send(hi_s32 argc, const hi_char **argv) +{ + if ((at_param_null_check(argc, argv) == HI_ERR_FAILURE) || ((argc != 2) && (argc != 4)) || /* 2 4 */ + ((integer_check(argv[0]) == HI_ERR_FAILURE) || (integer_check(argv[1]) == HI_ERR_FAILURE))) { + return HI_ERR_FAILURE; + } + + g_link_id = (hi_u16)atoi(argv[0]); + if ((g_link_id < 0) || (g_link_id >= IP_LINK_ID_MAX)) { + hi_at_printf("invalid link\r\n"); + return HI_ERR_FAILURE; + } + + hi_mux_pend(g_ip_mux_id, IP_MUX_WAIT_TIME); + if (g_ip_link_ctl[g_link_id].link_stats == IP_LINK_ID_IDLE) { + hi_at_printf("invalid link\r\n"); + hi_mux_post(g_ip_mux_id); + return HI_ERR_FAILURE; + } + hi_mux_post(g_ip_mux_id); + + if ((atoi(argv[1]) <= 0) || (atoi(argv[1]) > IP_SEND_BUF_LEN)) { + return HI_ERR_FAILURE; + } + + g_at_ctrl.send_len = (hi_u16)atoi(argv[1]); + + hi_mux_pend(g_ip_mux_id, IP_MUX_WAIT_TIME); + if (g_ip_link_ctl[g_link_id].ip_protocol == IP_TCP) { + if (argc != 2) { /* 2 Parameter verification */ + hi_at_printf("invalid link\r\n"); + hi_mux_post(g_ip_mux_id); + return HI_ERR_FAILURE; + } + } else if (g_ip_link_ctl[g_link_id].ip_protocol == IP_UDP) { + if (argc != 4) { /* 4 Parameter verification */ + hi_at_printf("invalid link\r\n"); + hi_mux_post(g_ip_mux_id); + return HI_ERR_FAILURE; + } + g_peer_ipaddr = inet_addr(argv[2]); /* 2 Parameter verification */ + if (integer_check(argv[3]) == HI_ERR_FAILURE) { /* 3 Parameter verification */ + hi_mux_post(g_ip_mux_id); + return HI_ERR_FAILURE; + } + g_peer_port = (hi_u16)atoi(argv[3]); /* 3 Parameter verification */ + } else { + hi_mux_post(g_ip_mux_id); + return HI_ERR_FAILURE; + } + hi_mux_post(g_ip_mux_id); + + g_at_ctrl.at_state = AT_DATA_RECVING; + hi_at_printf(">"); + return HI_ERR_RECVING; +} + +hi_void at_send_serial_data(hi_char *serial_data) +{ + hi_char *send_msg = serial_data; + hi_mux_pend(g_ip_mux_id, IP_MUX_WAIT_TIME); + if (g_ip_link_ctl[g_link_id].ip_protocol == IP_TCP) { + ip_tcp_send(g_link_id, send_msg); + } else if (g_ip_link_ctl[g_link_id].ip_protocol == IP_UDP) { + ip_udp_send(g_link_id, g_peer_ipaddr, g_peer_port, send_msg); + g_peer_ipaddr = 0; + g_peer_port = 0; + } + g_link_id = -1; + hi_mux_post(g_ip_mux_id); + return; +} +#endif + +static hi_u32 at_set_uart_func_nv(hi_s32 argc, const hi_char *argv[]) +{ + hi_u32 ret; + hi_nv_uart_port_alloc nv; + + if (argc != 3) { /* 3 */ + return HI_ERR_FAILURE; + } + + ret = hi_nv_read(HI_NV_SYS_UART_PORT_ID, &nv, sizeof(hi_nv_uart_port_alloc), 0); + if (ret != HI_ERR_SUCCESS) { + hi_at_printf("read nv fail\r\n"); + return HI_ERR_FAILURE; + } + + if (argv[0] != HI_NULL) { /* 0:uart_port_at */ + if (integer_check(argv[0]) != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + nv.uart_port_at = strtoul((const char*)argv[0], NULL, 10); /* param 0; 10:hexadecimal */ + } + + if (argv[1] != HI_NULL) { /* 1:uart_port_debug */ + if (integer_check(argv[1]) != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + nv.uart_port_debug = strtoul((const char*)argv[1], NULL, 10); /* param 1; 10:hexadecimal */ + } + + if (argv[2] != HI_NULL) { /* 2:uart_port_sigma */ + if (integer_check(argv[2]) != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + nv.uart_port_sigma = strtoul((const char*)argv[2], NULL, 10); /* param 2; 10:hexadecimal */ + } + + if (nv.uart_port_at > HI_UART_IDX_2 || + nv.uart_port_debug > HI_UART_IDX_2 || + nv.uart_port_sigma > HI_UART_IDX_2) { + return HI_ERR_FAILURE; + } + + if (nv.uart_port_at == nv.uart_port_debug || + nv.uart_port_at == nv.uart_port_sigma || + nv.uart_port_debug == nv.uart_port_sigma) { + hi_at_printf("reuse of a uart port %d:%d:%d\r\n", nv.uart_port_at, nv.uart_port_debug, nv.uart_port_sigma); + return HI_ERR_FAILURE; + } + + ret = hi_nv_write(HI_NV_SYS_UART_PORT_ID, &nv, sizeof(hi_nv_uart_port_alloc), 0); + if (ret != 0) { + hi_at_printf("write nv fail\r\n"); + return HI_ERR_FAILURE; + } + hi_at_printf("OK\r\n"); + return HI_ERR_SUCCESS; +} + +#ifndef CONFIG_FACTORY_TEST_MODE +static hi_u32 ip_close_link(hi_s32 link_id) +{ + if (link_id >= IP_LINK_ID_MAX) { + hi_at_printf("invalid link\r\n"); + return HI_ERR_FAILURE; + } + + hi_mux_pend(g_ip_mux_id, IP_MUX_WAIT_TIME); + if (g_ip_link_ctl[link_id].link_stats == IP_LINK_ID_IDLE) { + hi_at_printf("invalid link\r\n"); + hi_mux_post(g_ip_mux_id); + return HI_ERR_FAILURE; + } + + g_ip_link_ctl[link_id].link_stats = IP_LINK_USER_CLOSE; + hi_mux_post(g_ip_mux_id); + return HI_ERR_SUCCESS; +} + +static hi_u32 at_ip_close_link(hi_s32 argc, const hi_char **argv) +{ + hi_s32 link_id; + if ((argc != 1) || (integer_check(argv[0]) == HI_ERR_FAILURE)) { + return HI_ERR_FAILURE; + } + + link_id = atoi(argv[0]); + if (ip_close_link(link_id) != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + return HI_ERR_SUCCESS; +} + +static hi_u32 ip_tcp_server_close(hi_void) +{ + int i; + hi_mux_pend(g_ip_mux_id, IP_MUX_WAIT_TIME); + if (g_listen_fd.link_stats == IP_LINK_ID_IDLE) { + hi_at_printf("no server\r\n"); + hi_mux_post(g_ip_mux_id); + return HI_ERR_FAILURE; + } + + g_listen_fd.link_stats = IP_LINK_USER_CLOSE; + + for (i = 0; i < IP_LINK_ID_MAX; i++) { + if (g_ip_link_ctl[i].link_res == IP_LINK_AUTO) { + g_ip_link_ctl[i].link_stats = IP_LINK_WAIT_CLOSE; + } + } + hi_mux_post(g_ip_mux_id); + return HI_ERR_SUCCESS; +} + +static hi_u32 ip_tcp_server_start(hi_u16 local_port) +{ + struct sockaddr_in srv_addr = {0}; + hi_s32 ret; + hi_u32 opt = 1; + + if (g_listen_fd.link_stats == IP_LINK_SERVER_LISTEN) { + hi_at_printf("server is running\r\n"); + return HI_ERR_FAILURE; + } + + g_listen_fd.sfd = socket(AF_INET, SOCK_STREAM, 0); + if (g_listen_fd.sfd == -1) { + printf("{ip_tcp_server_start: creat socket failed}\r\n"); + return HI_ERR_FAILURE; + } + + setsockopt(g_listen_fd.sfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)); + + srv_addr.sin_family = AF_INET; + srv_addr.sin_addr.s_addr = htonl(INADDR_ANY); + srv_addr.sin_port = htons(local_port); + ret = bind(g_listen_fd.sfd, (struct sockaddr *)&srv_addr, sizeof(srv_addr)); + if (ret != 0) { + printf("{ip_tcp_server_start:bind failed, return is %d}\r\n", ret); + + closesocket(g_listen_fd.sfd); + g_listen_fd.sfd = -1; + g_listen_fd.link_stats = IP_LINK_ID_IDLE; + return HI_ERR_FAILURE; + } + + ret = listen(g_listen_fd.sfd, IP_TCP_SERVER_LISTEN_NUM); + if (ret != 0) { + printf("{ip_tcp_server_start:listen failed, return is %d\n}", ret); + + closesocket(g_listen_fd.sfd); + g_listen_fd.sfd = -1; + g_listen_fd.link_stats = IP_LINK_ID_IDLE; + return HI_ERR_FAILURE; + } + + if (ip_creat_ip_task() != HI_ERR_SUCCESS) { + printf("{ip_tcp_server_start:ip_creat_ip_task fail}\r\n"); + + closesocket(g_listen_fd.sfd); + g_listen_fd.sfd = -1; + g_listen_fd.link_stats = IP_LINK_ID_IDLE; + return HI_ERR_FAILURE; + } + + g_listen_fd.link_stats = IP_LINK_SERVER_LISTEN; + + return HI_ERR_SUCCESS; +} + +static hi_u32 at_ip_tcp_server(hi_s32 argc, const hi_char **argv) +{ + hi_u16 local_port; + hi_s32 server_ctl; + + if (at_param_null_check(argc, argv) == HI_ERR_FAILURE) { + return HI_ERR_FAILURE; + } + if ((argc != 1) && (argc != 2)) { /* 1 2 Parameter verification */ + return HI_ERR_FAILURE; + } + if (integer_check(argv[0]) == HI_ERR_FAILURE) { + return HI_ERR_FAILURE; + } + + server_ctl = atoi(argv[0]); + if (server_ctl == 1) { + if ((argv[1] == HI_NULL) || (integer_check(argv[1]) == HI_ERR_FAILURE)) { + return HI_ERR_FAILURE; + } + local_port = (hi_u16)atoi(argv[1]); + if (ip_tcp_server_start(local_port) != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + } else if (server_ctl == 0) { + if (argc != 1) { + return HI_ERR_FAILURE; + } + if (ip_tcp_server_close() != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + return HI_ERR_SUCCESS; + } else { + return HI_ERR_FAILURE; + } + hi_at_printf("OK\r\n"); + + return HI_ERR_SUCCESS; +} + +hi_u32 at_query_xtal_compesation(hi_void) +{ + hi_u32 ret; + hi_s16 high_temp_threshold = 0; + hi_s16 low_temp_threshold = 0; + hi_s16 pll_compesation = 0; + + ret = get_rf_cmu_pll_param(&high_temp_threshold, &low_temp_threshold, &pll_compesation); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + hi_at_printf("+XTALCOM:%d,%d,%d\r\n", high_temp_threshold, low_temp_threshold, pll_compesation); + AT_RESPONSE_OK; + + return HI_ERR_SUCCESS; +} +#endif + +#define TSENSOR_TEMPERATURE_MAX 140 /* Maximum temperature */ +#define TSENSOR_TEMPERATURE_MIN (-40) /* Minimum temperature */ + +static hi_u32 at_query_tsensor_temp(hi_void) +{ + hi_u32 ret; + hi_u32 i; + hi_s16 temp; + + if (hi_wifi_get_init_status() == 0) { + ret = hi_tsensor_start(HI_TSENSOR_MODE_16_POINTS_SINGLE, 0); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + hi_udelay(10000); /* delay 10000 us */ + } + + for (i = 0; i < 3; i++) { /* loop 3 times */ + ret = hi_tsensor_read_temperature(&temp); + if (ret == HI_ERR_SUCCESS) { + break; + } + hi_udelay(10000); /* delay 10000 us */ + } + + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + if (temp < TSENSOR_TEMPERATURE_MIN || temp > TSENSOR_TEMPERATURE_MAX) { + return HI_ERR_FAILURE; + } + + hi_at_printf("+RDTEMP:%d\r\n", temp); + AT_RESPONSE_OK; + + return HI_ERR_SUCCESS; +} + +#ifdef CONFIG_SIGMA_SUPPORT +hi_u32 at_sigma_start(hi_s32 argc, const hi_char **argv) +{ + hi_unref_param(argc); + hi_unref_param(argv); + + if (hi_sigma_init() != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + + hi_at_printf("OK\r\n"); + return HI_ERR_SUCCESS; +} +#endif + +const at_cmd_func g_at_general_func_tbl[] = { + {"", 0, HI_NULL, HI_NULL, HI_NULL, (at_call_back_func)at_exe_at_cmd}, + {"+RST", 4, HI_NULL, HI_NULL, (at_call_back_func)at_setup_reset_cmd, (at_call_back_func)at_exe_reset_cmd}, + {"+MAC", 4, HI_NULL, (at_call_back_func)cmd_get_macaddr, (at_call_back_func)cmd_set_macaddr, HI_NULL}, + {"+HELP", 5, HI_NULL, HI_NULL, HI_NULL, (at_call_back_func)at_exe_help_cmd}, + +#ifndef CONFIG_FACTORY_TEST_MODE + {"+SYSINFO", 8, HI_NULL, HI_NULL, HI_NULL, (at_call_back_func)at_query_sysinfo_cmd}, + {"+DHCP", 5, HI_NULL, HI_NULL, (at_call_back_func)at_setup_dhcp, HI_NULL}, + {"+DHCPS", 6, HI_NULL, HI_NULL, (at_call_back_func)at_setup_dhcps, HI_NULL}, + {"+NETSTAT", 8, HI_NULL, HI_NULL, HI_NULL, (at_call_back_func)at_netstat}, +#ifdef CONFIG_IPERF_SUPPORT + {"+IPERF", 6, HI_NULL, HI_NULL, (at_call_back_func)at_iperf, HI_NULL}, +#endif +#ifdef CONFIG_SIGMA_SUPPORT + {"+SIGMA", 6, HI_NULL, HI_NULL, HI_NULL, (at_call_back_func)at_sigma_start}, +#endif + {"+PING", 5, HI_NULL, HI_NULL, (at_call_back_func)at_ping, HI_NULL}, + {"+PING6", 6, HI_NULL, HI_NULL, (at_call_back_func)at_ping6, HI_NULL}, +#if LWIP_DNS + {"+DNS", 4, HI_NULL, (at_call_back_func)at_show_dns, (at_call_back_func)at_dns, HI_NULL}, +#endif + {"+DUMP", 5, HI_NULL, HI_NULL, HI_NULL, (at_call_back_func)at_get_dump}, + {"+IPSTART", 8, HI_NULL, HI_NULL, (at_call_back_func)at_start_ip, HI_NULL}, + {"+IPLISTEN", 9, HI_NULL, HI_NULL, (at_call_back_func)at_ip_tcp_server, HI_NULL}, + {"+IPSEND", 7, HI_NULL, HI_NULL, (at_call_back_func)at_ip_send, HI_NULL}, + {"+IPCLOSE", 8, HI_NULL, HI_NULL, (at_call_back_func)at_ip_close_link, HI_NULL}, + {"+XTALCOM", 8, HI_NULL, (at_call_back_func)at_query_xtal_compesation, HI_NULL, HI_NULL}, +#endif + {"+RDTEMP", 7, HI_NULL, (at_call_back_func)at_query_tsensor_temp, HI_NULL, HI_NULL}, +}; + +#define AT_GENERAL_FUNC_NUM (sizeof(g_at_general_func_tbl) / sizeof(g_at_general_func_tbl[0])) + +void hi_at_general_cmd_register(void) +{ + hi_at_register_cmd(g_at_general_func_tbl, AT_GENERAL_FUNC_NUM); +} + +const at_cmd_func g_at_general_factory_test_func_tbl[] = { + {"+CSV", 4, HI_NULL, HI_NULL, HI_NULL, (at_call_back_func)at_query_ver_cmd}, + {"+FTM", 4, (at_call_back_func)at_factory_mode_query, (at_call_back_func)at_factory_mode_query, + (at_call_back_func)at_factory_mode_switch, HI_NULL}, +#ifndef CONFIG_FACTORY_TEST_MODE + {"+FTMERASE", 9, HI_NULL, HI_NULL, HI_NULL, (at_call_back_func)at_factory_erase}, +#endif + {"+SETUART", 8, HI_NULL, HI_NULL, (at_call_back_func)at_set_uart_func_nv, HI_NULL}, + {"+IFCFG", 6, HI_NULL, HI_NULL, (at_call_back_func)at_lwip_ifconfig, (at_call_back_func)at_lwip_ifconfig}, +}; +#define AT_GENERAL_FACTORY_TEST_FUNC_NUM (sizeof(g_at_general_factory_test_func_tbl) / \ + sizeof(g_at_general_factory_test_func_tbl[0])) + +void hi_at_general_factory_test_cmd_register(void) +{ + hi_at_register_cmd(g_at_general_factory_test_func_tbl, AT_GENERAL_FACTORY_TEST_FUNC_NUM); +} + +#ifdef __cplusplus +#if __cplusplus + } +#endif +#endif diff --git a/sdk_liteos/components/at/src/at_general.h b/sdk_liteos/components/at/src/at_general.h new file mode 100644 index 0000000000000000000000000000000000000000..a83c87c210a4c493e17fd4079a431c0efd7419fe --- /dev/null +++ b/sdk_liteos/components/at/src/at_general.h @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __AT_GENERAL_H__ +#define __AT_GENERAL_H__ + +#include "hi_types.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif + +#define DEFAULT_IFNAME_LOCALHOST "lo" +#define DEFAULT_IFNAME_AP "ap0" +#define DEFAULT_IFNAME_STA "wlan0" +#define DEFAULT_IFNAME_MESH "mesh0" + +hi_void hi_at_general_cmd_register(hi_void); +hi_void hi_at_general_factory_test_cmd_register(hi_void); +hi_u32 at_wifi_ifconfig(hi_s32 argc, const hi_char **argv); +hi_u32 osShellDhcps(hi_s32 argc, const hi_char **argv); +hi_u32 at_lwip_ifconfig(hi_s32 argc, const hi_char **argv); +hi_void at_send_serial_data(hi_char *serial_data); + +extern hi_u32 get_rf_cmu_pll_param(hi_s16 *high_temp, hi_s16 *low_temp, hi_s16 *compesation); + +#ifdef __cplusplus +#if __cplusplus + } +#endif +#endif + +#endif diff --git a/sdk_liteos/components/at/src/at_hipriv.c b/sdk_liteos/components/at/src/at_hipriv.c new file mode 100644 index 0000000000000000000000000000000000000000..aab2005e55e1e39e867a65b27a0ba18e4509b74b --- /dev/null +++ b/sdk_liteos/components/at/src/at_hipriv.c @@ -0,0 +1,401 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "at_hipriv.h" + +#include +#include +#include + +#include + +#include "hi_wifi_mfg_test_if.h" +#include "hi_wifi_api.h" + +#include "at.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif +hi_u32 at_hi_wifi_al_tx(hi_s32 argc, const hi_char *argv[]) +{ + if (at_param_null_check(argc, argv) == HI_ERR_FAILURE) { + return HI_ERR_FAILURE; + } + hi_u32 ret = hi_wifi_at_start(argc, argv, HISI_AT_AL_TX); + return ret; +} + +hi_u32 at_hi_wifi_al_rx(hi_s32 argc, const hi_char *argv[]) +{ + if (at_param_null_check(argc, argv) == HI_ERR_FAILURE) { + return HI_ERR_FAILURE; + } + hi_u32 ret = hi_wifi_at_start(argc, argv, HISI_AT_AL_RX); + return ret; +} + +hi_u32 at_hi_wifi_rx_info(hi_s32 argc, const hi_char *argv[]) +{ + hi_u32 ret = hi_wifi_at_start(argc, argv, HISI_AT_RX_INFO); + return ret; +} + +hi_u32 at_hi_wifi_set_country(hi_s32 argc, const hi_char *argv[]) +{ + if (at_param_null_check(argc, argv) == HI_ERR_FAILURE) { + return HI_ERR_FAILURE; + } + hi_u32 ret = hi_wifi_at_start(argc, argv, HISI_AT_SET_COUNTRY); + return ret; +} + +hi_u32 at_hi_wifi_get_country(hi_s32 argc, const hi_char *argv[]) +{ + hi_u32 ret = hi_wifi_at_start(argc, argv, HISI_AT_GET_COUNTRY); + return ret; +} + +hi_u32 at_hi_wifi_set_tpc(hi_s32 argc, const hi_char *argv[]) +{ + if (at_param_null_check(argc, argv) == HI_ERR_FAILURE) { + return HI_ERR_FAILURE; + } + hi_u32 ret = hi_wifi_at_start(argc, argv, HISI_AT_SET_TPC); + return ret; +} + +hi_u32 at_hi_wifi_set_rate_power_sub(hi_s32 argc, const hi_char *argv[], hi_bool tuning) +{ + hi_u8 protol, rate; + hi_s32 val; + hi_u8 ofs = tuning ? 1 : 0; + hi_u8 protol_ofs = tuning ? 10 : 0; /* 10:Offset of the command */ + hi_s32 low_limit = tuning ? -100 : -8; /* -100:Debug Command Lower Limit,-8:Lower Limit of Test Command */ + hi_s32 up_limit = tuning ? 40 : 7; /* 40:Upper limit of debugging commands.,7:Upper Limit of Test Commands */ + + if ((at_param_null_check(argc, argv) == HI_ERR_FAILURE) || (argc != 3)) { /* Parameter verification, argc 3 */ + return HI_ERR_FAILURE; + } + + /* get protol */ + if ((integer_check(argv[0]) != HI_ERR_SUCCESS) || + (atoi(argv[0]) < HI_WIFI_PHY_MODE_11BGN) || (atoi(argv[0]) > HI_WIFI_PHY_MODE_11B)) { + return HI_ERR_FAILURE; + } + protol = (hi_u8)atoi(argv[0]); + + /* get rate */ + if (integer_check(argv[1]) != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + if (((protol == HI_WIFI_PHY_MODE_11BGN) && ((atoi(argv[1]) < 0) || (atoi(argv[1]) > 7 + ofs))) || /* 0~7 */ + ((protol == HI_WIFI_PHY_MODE_11BG) && ((atoi(argv[1]) < 0) || (atoi(argv[1]) > 7 + ofs))) || /* 0~7 */ + ((protol == HI_WIFI_PHY_MODE_11B) && ((atoi(argv[1]) < 0) || (atoi(argv[1]) > 3 + ofs)))) { /* 0~3 */ + return HI_ERR_FAILURE; + } + rate = (hi_u8)atoi(argv[1]); + + /* get val */ + if (argv[2][0] == '-') { /* 2 */ + if (((argv[2][1] != '\0') && (integer_check(&argv[2][1]) != HI_ERR_SUCCESS)) || /* 2:array subscript */ + (argv[2][1] == '\0')) { /* 2:array subscript */ + return HI_ERR_FAILURE; + } + } else { + if (integer_check(argv[2]) != HI_ERR_SUCCESS) { /* 2:array subscript */ + return HI_ERR_FAILURE; + } + } + if ((atoi(argv[2]) < low_limit) || (atoi(argv[2]) > up_limit)) { /* 2:array subscript */ + return HI_ERR_FAILURE; + } + val = atoi(argv[2]); /* 2:array subscript */ + protol += protol_ofs; + + hi_u32 ret = wal_set_cal_rate_power(protol, rate, val); + if (ret == HI_ERR_SUCCESS) { + hi_at_printf("OK\r\n"); + } + + return ret; +} + +hi_u32 at_hi_wifi_set_rate_power(hi_s32 argc, const hi_char *argv[]) +{ + return at_hi_wifi_set_rate_power_sub(argc, argv, HI_TRUE); +} + +hi_u32 at_hi_wifi_set_cal_freq(hi_s32 argc, const hi_char *argv[]) +{ + hi_s32 freq_offset; + + if ((at_param_null_check(argc, argv) == HI_ERR_FAILURE) || (argc != 1)) { /* 1:Parameter verification */ + return HI_ERR_FAILURE; + } + + /* get freq offset */ + if (argv[0][0] == '-') { + if (((argv[0][1] != '\0') && (integer_check(&argv[0][1]) != HI_ERR_SUCCESS)) || + (argv[0][1] == '\0')) { + return HI_ERR_FAILURE; + } + } else { + if (integer_check(argv[0]) != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + } + if ((atoi(argv[0]) < -128) || (atoi(argv[0]) > 127)) { /* Scope-128~127 */ + return HI_ERR_FAILURE; + } + freq_offset = atoi(argv[0]); + + hi_u32 ret = wal_set_cal_freq(freq_offset); + if (ret == HI_ERR_SUCCESS) { + hi_at_printf("OK\r\n"); + } + + return ret; +} + +#ifdef CONFIG_FACTORY_TEST_MODE +hi_u32 at_hi_wifi_set_cal_band_power(hi_s32 argc, const hi_char *argv[]) +{ + hi_u8 band_num; + hi_s32 offset; + + if ((at_param_null_check(argc, argv) == HI_ERR_FAILURE) || (argc != 2)) { /* 2:Parameter verification */ + return HI_ERR_FAILURE; + } + + /* get band num */ + if ((integer_check(argv[0]) != HI_ERR_SUCCESS) || (atoi(argv[0]) < 0) || (atoi(argv[0]) > 2)) { /* 0~2:subscript */ + return HI_ERR_FAILURE; + } + band_num = (hi_u8)atoi(argv[0]); + + /* get power offset */ + if (argv[1][0] == '-') { + if (((argv[1][1] != '\0') && (integer_check(&argv[1][1]) != HI_ERR_SUCCESS)) || + (argv[1][1] == '\0')) { + return HI_ERR_FAILURE; + } + } else { + if (integer_check(argv[1]) != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + } + if ((atoi(argv[1]) < -60) || (atoi(argv[1]) > 60)) { /* Scope-60~60 */ + return HI_ERR_FAILURE; + } + offset = atoi(argv[1]); + + hi_u32 ret = wal_set_cal_band_power(band_num, offset); + if (ret == HI_ERR_SUCCESS) { + hi_at_printf("OK\r\n"); + } + + return ret; +} + +hi_u32 at_hi_wifi_set_cal_rate_power(hi_s32 argc, const hi_char *argv[]) +{ + return at_hi_wifi_set_rate_power_sub(argc, argv, HI_FALSE); +} + +hi_u32 at_hi_wifi_get_customer_mac(hi_s32 argc, const hi_char *argv[]) +{ + hi_unref_param(argc); + hi_unref_param(argv); + + hi_u32 ret = wal_get_customer_mac(); + if (ret != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + + return HI_ERR_SUCCESS; +} + +hi_u32 at_hi_wifi_set_customer_mac(hi_s32 argc, const hi_char *argv[]) +{ + hi_uchar mac_addr[6]; /* 6:array subscript */ + hi_u8 type = 0; + if ((argc < 1) || (argc > 2) || (at_param_null_check(argc, argv) == HI_ERR_FAILURE)) { /* 2 */ + return HI_ERR_FAILURE; + } + + if (strlen(argv[0]) != 17) { /* 17:MAC_ADDR_LEN */ + return HI_ERR_FAILURE; + } + + hi_u32 ret = cmd_strtoaddr(argv[0], mac_addr, 6); /* 6:lenth */ + if (ret != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + if (argc == 2) { /* 2:Parameter verification */ + /* get type */ + if (integer_check(argv[1]) != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + type = (hi_u8)atoi(argv[1]); + if ((type != 0) && (type != 1)) { /* Parameter verification 0,1 */ + return HI_ERR_FAILURE; + } + } + if (wal_set_customer_mac((hi_char*)mac_addr, type) != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + + return HI_ERR_SUCCESS; +} + +hi_u32 at_hi_wifi_set_dataefuse(hi_s32 argc, const hi_char *argv[]) +{ + hi_u32 type = 0; + + if ((argc == 1) && (at_param_null_check(argc, argv) == HI_ERR_FAILURE)) { + return HI_ERR_FAILURE; + } + + if (argc == 1) { + /* get type */ + if (integer_check(argv[0]) != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + type = (hi_u32)atoi(argv[0]); + if ((type != 0) && (type != 1)) { /* Scope:0,1 */ + return HI_ERR_FAILURE; + } + } + + hi_u32 ret = wal_set_dataefuse(type); + if (ret != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + + return HI_ERR_SUCCESS; +} +#endif + +hi_u32 at_hi_wifi_get_cal_data(hi_s32 argc, const hi_char *argv[]) +{ + hi_unref_param(argc); + hi_unref_param(argv); + + hi_u32 ret = wal_get_cal_data(); + if (ret != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + + return HI_ERR_SUCCESS; +} + +hi_u32 at_hi_wifi_set_trc(hi_s32 argc, const hi_char *argv[]) +{ + if (at_param_null_check(argc, argv) == HI_ERR_FAILURE) { + return HI_ERR_FAILURE; + } + hi_u32 ret = hi_wifi_at_start(argc, argv, HISI_AT_SET_TRC); + return ret; +} + +hi_u32 at_hi_wifi_set_rate(hi_s32 argc, const hi_char *argv[]) +{ + if (at_param_null_check(argc, argv) == HI_ERR_FAILURE) { + return HI_ERR_FAILURE; + } + hi_u32 ret = hi_wifi_at_start(argc, argv, HISI_AT_SET_RATE); + return ret; +} + +hi_u32 at_hi_wifi_set_arlog(hi_s32 argc, const hi_char *argv[]) +{ + if (at_param_null_check(argc, argv) == HI_ERR_FAILURE) { + return HI_ERR_FAILURE; + } + hi_u32 ret = hi_wifi_at_start(argc, argv, HISI_AT_SET_ARLOG); + return ret; +} + +hi_u32 at_hi_wifi_get_vap_info(hi_s32 argc, const hi_char *argv[]) +{ + if (at_param_null_check(argc, argv) == HI_ERR_FAILURE) { + return HI_ERR_FAILURE; + } + hi_u32 ret = hi_wifi_at_start(argc, argv, HISI_AT_GET_VAP_INFO); + return ret; +} + +hi_u32 at_hi_wifi_get_usr_info(hi_s32 argc, const hi_char *argv[]) +{ + if (at_param_null_check(argc, argv) == HI_ERR_FAILURE) { + return HI_ERR_FAILURE; + } + hi_u32 ret = hi_wifi_at_start(argc, argv, HISI_AT_GET_USR_INFO); + return ret; +} + + +const at_cmd_func g_at_hipriv_func_tbl[] = { + {"+RXINFO", 7, HI_NULL, HI_NULL, HI_NULL, (at_call_back_func)at_hi_wifi_rx_info}, + {"+CC", 3, HI_NULL, (at_call_back_func)at_hi_wifi_get_country, (at_call_back_func)at_hi_wifi_set_country, HI_NULL}, +#ifndef CONFIG_FACTORY_TEST_MODE + {"+TPC", 4, HI_NULL, HI_NULL, (at_call_back_func)at_hi_wifi_set_tpc, HI_NULL}, + {"+TRC", 4, HI_NULL, HI_NULL, (at_call_back_func)at_hi_wifi_set_trc, HI_NULL}, + {"+SETRATE", 8, HI_NULL, HI_NULL, (at_call_back_func)at_hi_wifi_set_rate, HI_NULL}, + {"+ARLOG", 6, HI_NULL, HI_NULL, (at_call_back_func)at_hi_wifi_set_arlog, HI_NULL}, + {"+VAPINFO", 8, HI_NULL, HI_NULL, (at_call_back_func)at_hi_wifi_get_vap_info, HI_NULL}, + {"+USRINFO", 8, HI_NULL, HI_NULL, (at_call_back_func)at_hi_wifi_get_usr_info, HI_NULL}, +#endif +}; + +#define AT_HIPRIV_FUNC_NUM (sizeof(g_at_hipriv_func_tbl) / sizeof(g_at_hipriv_func_tbl[0])) + +void hi_at_hipriv_cmd_register(void) +{ + hi_at_register_cmd(g_at_hipriv_func_tbl, AT_HIPRIV_FUNC_NUM); +} + +const at_cmd_func g_at_hipriv_factory_test_func_tbl[] = { + {"+ALTX", 5, HI_NULL, HI_NULL, (at_call_back_func)at_hi_wifi_al_tx, HI_NULL}, + {"+ALRX", 5, HI_NULL, HI_NULL, (at_call_back_func)at_hi_wifi_al_rx, HI_NULL}, +#ifdef CONFIG_FACTORY_TEST_MODE + {"+CALBPWR", 8, HI_NULL, HI_NULL, (at_call_back_func)at_hi_wifi_set_cal_band_power, HI_NULL}, + {"+CALRPWR", 8, HI_NULL, HI_NULL, (at_call_back_func)at_hi_wifi_set_cal_rate_power, HI_NULL}, + {"+EFUSEMAC", 9, HI_NULL, (at_call_back_func)at_hi_wifi_get_customer_mac, + (at_call_back_func)at_hi_wifi_set_customer_mac, HI_NULL}, + {"+WCALDATA", 9, HI_NULL, HI_NULL, (at_call_back_func)at_hi_wifi_set_dataefuse, + (at_call_back_func)at_hi_wifi_set_dataefuse}, +#endif + {"+CALFREQ", 8, HI_NULL, HI_NULL, (at_call_back_func)at_hi_wifi_set_cal_freq, HI_NULL}, + {"+SETRPWR", 8, HI_NULL, HI_NULL, (at_call_back_func)at_hi_wifi_set_rate_power, HI_NULL}, + {"+RCALDATA", 9, HI_NULL, HI_NULL, HI_NULL, (at_call_back_func)at_hi_wifi_get_cal_data}, +}; +#define AT_HIPRIV_FACTORY_TEST_FUNC_NUM (sizeof(g_at_hipriv_factory_test_func_tbl) / \ + sizeof(g_at_hipriv_factory_test_func_tbl[0])) + +void hi_at_hipriv_factory_test_cmd_register(void) +{ + hi_at_register_cmd(g_at_hipriv_factory_test_func_tbl, AT_HIPRIV_FACTORY_TEST_FUNC_NUM); +} + +#ifdef __cplusplus +#if __cplusplus + } +#endif +#endif + diff --git a/sdk_liteos/components/at/src/at_hipriv.h b/sdk_liteos/components/at/src/at_hipriv.h new file mode 100644 index 0000000000000000000000000000000000000000..46b14e58cb3dde354ba9b382b1fcdf2f190d70b5 --- /dev/null +++ b/sdk_liteos/components/at/src/at_hipriv.h @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __AT_HIPRIV_H__ +#define __AT_HIPRIV_H__ + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif + +void hi_at_hipriv_cmd_register(void); +void hi_at_hipriv_factory_test_cmd_register(void); + +#ifdef __cplusplus +#if __cplusplus + } +#endif +#endif + +#endif diff --git a/sdk_liteos/components/at/src/at_io.c b/sdk_liteos/components/at/src/at_io.c new file mode 100644 index 0000000000000000000000000000000000000000..38f6a91b3d4e3df83164c0fad61f47e5375ba40c --- /dev/null +++ b/sdk_liteos/components/at/src/at_io.c @@ -0,0 +1,323 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "at_io.h" + +#include +#include +#include +#include +#include +#include + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif + +#define io_dir_get(cond, id, val_addr) \ + if ((cond) & (hi_u16)(1 << (id))) { \ + *(val_addr) = HI_GPIO_DIR_OUT; \ + } else { \ + *(val_addr) = HI_GPIO_DIR_IN; \ + } + +#define IO_MAX_WORK_MODE 7 + +hi_u32 gpio_get_dir(hi_gpio_idx id, hi_gpio_dir *dir) +{ + if (id >= HI_GPIO_IDX_MAX || dir == HI_NULL) { + return HI_ERR_GPIO_INVALID_PARAMETER; + } + hi_u32 int_val; + hi_u16 reg_val = 0; + + int_val = hi_int_lock(); + hi_reg_read16(0x50006004, reg_val); + io_dir_get(reg_val, (hi_u16) id, dir); + hi_int_restore(int_val); + + return HI_ERR_SUCCESS; +} + +hi_u32 at_setup_iosetmode_cmd(hi_s32 argc, const hi_char *argv[]) +{ + hi_io_name io_num; + hi_u8 io_mode; + hi_io_pull io_pull_stat; + hi_io_driver_strength io_power_level; + hi_u32 ret; + hi_s32 i; + + if (argc < 3 || argc > 4) { /* argc 3/4 */ + return HI_ERR_FAILURE; + } + + for (i = 0; i < argc; i++) { + if (integer_check(argv[i]) != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + } + + io_num = (hi_io_name)atoi(argv[0]); + if (io_num > HI_IO_NAME_GPIO_14) { + return HI_ERR_FAILURE; + } + + io_mode = (hi_u8)atoi(argv[1]); + if (io_mode > IO_MAX_WORK_MODE) { + return HI_ERR_FAILURE; + } + + io_pull_stat = (hi_io_pull)atoi(argv[2]); /* argc 2 */ + if (io_pull_stat > HI_IO_PULL_DOWN) { + return HI_ERR_FAILURE; + } + + if (argc == 3) { /* argc 3 */ + io_power_level = HI_IO_DRIVER_STRENGTH_3; + } else { + io_power_level = (hi_io_driver_strength)atoi(argv[3]); /* argc 3 */ + } + + ret = hi_io_set_func(io_num, io_mode); + if (ret != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + + ret = hi_io_set_pull(io_num, io_pull_stat); + if (ret != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + ret = hi_io_set_driver_strength(io_num, io_power_level); + if (ret != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + + AT_RESPONSE_OK; + return HI_ERR_SUCCESS; +} + +hi_u32 at_setup_iogetmode_cmd(hi_s32 argc, const hi_char *argv[]) +{ + hi_io_name io_num; + hi_u8 io_mode; + hi_io_pull io_pull_stat; + hi_io_driver_strength io_capalibity; + hi_u32 ret; + + if (argc != 1) { + return HI_ERR_FAILURE; + } + + if (integer_check(argv[0]) != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + + io_num = (hi_io_name)atoi(argv[0]); + if (io_num > HI_IO_NAME_GPIO_14) { + return HI_ERR_FAILURE; + } + + ret = hi_io_get_func(io_num, &io_mode); + if (ret != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + + ret = hi_io_get_pull(io_num, &io_pull_stat); + if (ret != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + + ret = hi_io_get_driver_strength(io_num, &io_capalibity); + if (ret != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + + hi_at_printf("+GETIOMODE:%d,%d,%d,%d\r\n", io_num, io_mode, io_pull_stat, io_capalibity); + AT_RESPONSE_OK; + return HI_ERR_SUCCESS; +} + +hi_u32 at_setup_gpiodir_cmd(hi_s32 argc, const hi_char *argv[]) +{ + hi_io_name io_num; + hi_gpio_dir io_dir; + hi_u8 io_mode; + hi_u32 ret; + hi_s32 i; + + if (argc != 2) { /* argc 2 */ + return HI_ERR_FAILURE; + } + + for (i = 0; i < argc; i++) { + if (integer_check(argv[i]) != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + } + + io_num = (hi_io_name)atoi(argv[0]); + if (io_num > HI_IO_NAME_GPIO_14) { + return HI_ERR_FAILURE; + } + + io_dir = (hi_gpio_dir)atoi(argv[1]); + if (io_dir > HI_GPIO_DIR_OUT) { + return HI_ERR_FAILURE; + } + + ret = hi_io_get_func(io_num, &io_mode); + if (ret != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + + if ((io_num < HI_IO_NAME_GPIO_13) && (io_mode != 0)) { + return HI_ERR_FAILURE; + } else if ((io_num >= HI_IO_NAME_GPIO_13) && (io_mode != (hi_u8)HI_IO_FUNC_GPIO_13_GPIO)) { + return HI_ERR_FAILURE; + } + + ret = hi_gpio_set_dir((hi_gpio_idx)io_num, io_dir); + if (ret != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + + AT_RESPONSE_OK; + return HI_ERR_SUCCESS; +} + +hi_u32 at_setup_gpiowt_cmd(hi_s32 argc, const hi_char *argv[]) +{ + hi_io_name io_num; + hi_gpio_value io_level; + hi_u8 io_mode; + hi_gpio_dir io_dir; + hi_u32 ret; + hi_s32 i; + + if (argc != 2) { /* argc 2 */ + return HI_ERR_FAILURE; + } + + for (i = 0; i < argc; i++) { + if (integer_check(argv[i]) != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + } + + io_num = (hi_io_name)atoi(argv[0]); + if (io_num > HI_IO_NAME_GPIO_14) { + return HI_ERR_FAILURE; + } + + io_level = (hi_gpio_value)atoi(argv[1]); + if (io_level > HI_GPIO_VALUE1) { + return HI_ERR_FAILURE; + } + + ret = hi_io_get_func(io_num, &io_mode); + if (ret != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + + if ((io_num < HI_IO_NAME_GPIO_13) && (io_mode != 0)) { + return HI_ERR_FAILURE; + } else if ((io_num >= HI_IO_NAME_GPIO_13) && (io_mode != (hi_u8)HI_IO_FUNC_GPIO_13_GPIO)) { + return HI_ERR_FAILURE; + } + + ret = gpio_get_dir((hi_gpio_idx)io_num, &io_dir); + if ((ret != HI_ERR_SUCCESS) || (io_dir != HI_GPIO_DIR_OUT)) { + return HI_ERR_FAILURE; + } + + ret = hi_gpio_set_ouput_val((hi_gpio_idx)io_num, io_level); + if (ret != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + + AT_RESPONSE_OK; + return HI_ERR_SUCCESS; +} + +hi_u32 at_setup_gpiord_cmd(hi_s32 argc, const hi_char *argv[]) +{ + hi_io_name io_num; + hi_gpio_value io_level; + hi_u8 io_mode; + hi_gpio_dir io_dir; + hi_u32 ret; + + if (argc != 1) { + return HI_ERR_FAILURE; + } + + if (integer_check(argv[0]) != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + + io_num = (hi_io_name)atoi(argv[0]); + if (io_num > HI_IO_NAME_GPIO_14) { + return HI_ERR_FAILURE; + } + + ret = hi_io_get_func(io_num, &io_mode); + if (ret != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + + if ((io_num < HI_IO_NAME_GPIO_13) && (io_mode != 0)) { + return HI_ERR_FAILURE; + } else if ((io_num >= HI_IO_NAME_GPIO_13) && (io_mode != (hi_u8)HI_IO_FUNC_GPIO_13_GPIO)) { + return HI_ERR_FAILURE; + } + + ret = gpio_get_dir((hi_gpio_idx)io_num, &io_dir); + if (ret != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + + ret = hi_gpio_get_input_val((hi_gpio_idx)io_num, &io_level); + if (ret != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + + hi_at_printf("+RDGPIO:%d,%d,%d\r\n", io_num, io_dir, io_level); + AT_RESPONSE_OK; + return HI_ERR_SUCCESS; +} + +const at_cmd_func g_at_io_func_tbl[] = { + {"+SETIOMODE", 10, HI_NULL, HI_NULL, (at_call_back_func)at_setup_iosetmode_cmd, HI_NULL}, + {"+GETIOMODE", 10, HI_NULL, HI_NULL, (at_call_back_func)at_setup_iogetmode_cmd, HI_NULL}, + {"+GPIODIR", 8, HI_NULL, HI_NULL, (at_call_back_func)at_setup_gpiodir_cmd, HI_NULL}, + {"+WTGPIO", 7, HI_NULL, HI_NULL, (at_call_back_func)at_setup_gpiowt_cmd, HI_NULL}, + {"+RDGPIO", 7, HI_NULL, HI_NULL, (at_call_back_func)at_setup_gpiord_cmd, HI_NULL}, +}; + +#define AT_IO_FUNC_NUM (sizeof(g_at_io_func_tbl) / sizeof(g_at_io_func_tbl[0])) + +void hi_at_io_cmd_register(void) +{ + hi_at_register_cmd(g_at_io_func_tbl, AT_IO_FUNC_NUM); +} + +#ifdef __cplusplus +#if __cplusplus + } +#endif +#endif diff --git a/sdk_liteos/components/at/src/at_io.h b/sdk_liteos/components/at/src/at_io.h new file mode 100644 index 0000000000000000000000000000000000000000..64cdc1220cafaceedd6330e866d6b4c50b5c7250 --- /dev/null +++ b/sdk_liteos/components/at/src/at_io.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __AT_IO_H__ +#define __AT_IO_H__ + +#include + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif + +void hi_at_io_cmd_register(void); + +hi_u32 gpio_get_dir(hi_gpio_idx id, hi_gpio_dir *dir); + +#ifdef __cplusplus +#if __cplusplus + } +#endif +#endif + +#endif diff --git a/sdk_liteos/components/at/src/at_lowpower.c b/sdk_liteos/components/at/src/at_lowpower.c new file mode 100644 index 0000000000000000000000000000000000000000..05549762143707ace9e07314dd00f716a584ea93 --- /dev/null +++ b/sdk_liteos/components/at/src/at_lowpower.c @@ -0,0 +1,465 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "at_lowpower.h" + +#ifndef CONFIG_FACTORY_TEST_MODE +#include "lwip/ip_addr.h" +#endif +#include "hi_at.h" +#include "hi_gpio.h" +#include "hi_io.h" +#include "hi_lowpower.h" +#include "hi_stdlib.h" +#include "hi_time.h" +#include "hi_types_base.h" +#include "hi_watchdog.h" +#include "hi_wifi_api.h" + +#include "at.h" +#include "at_io.h" + +#define MILLISECOND_PER_TICK 10 +#define GPIO3_WAKE_UP_SOURCE 3 +#define GPIO5_WAKE_UP_SOURCE 5 +#define GPIO7_WAKE_UP_SOURCE 7 +#define GPIO14_WAKE_UP_SOURCE 14 +#define ALL_GPIO_WAKE_UP_SOURCE 0 + +#define IO0_GPIO_MODE 0 +#define IO1_GPIO_MODE 0 +#define IO2_GPIO_MODE 0 +#define IO3_GPIO_MODE 0 +#define IO4_GPIO_MODE 0 +#define IO5_GPIO_MODE 0 +#define IO6_GPIO_MODE 0 +#define IO7_GPIO_MODE 0 +#define IO8_GPIO_MODE 0 +#define IO9_GPIO_MODE 0 +#define IO10_GPIO_MODE 0 +#define IO11_GPIO_MODE 0 +#define IO12_GPIO_MODE 0 +#define IO13_GPIO_MODE 4 +#define IO14_GPIO_MODE 4 + +hi_u8 g_io_gpio_mode[] = { + IO0_GPIO_MODE, + IO1_GPIO_MODE, + IO2_GPIO_MODE, + IO3_GPIO_MODE, + IO4_GPIO_MODE, + IO5_GPIO_MODE, + IO6_GPIO_MODE, + IO7_GPIO_MODE, + IO8_GPIO_MODE, + IO9_GPIO_MODE, + IO10_GPIO_MODE, + IO11_GPIO_MODE, + IO12_GPIO_MODE, + IO13_GPIO_MODE, + IO14_GPIO_MODE, +}; + +hi_u32 ms_to_systick(hi_u32 ms, hi_bool include0) +{ + hi_u32 tick; + + /* >10ms Align Down */ + if (ms > MILLISECOND_PER_TICK) { + tick = ms / MILLISECOND_PER_TICK; /* convert from ms to ticks */ + } else { + if ((include0 == HI_TRUE) && (ms == 0)) { + tick = 0; + } else { + tick = 1; + } + } + + return tick; +} +#ifndef CONFIG_FACTORY_TEST_MODE +hi_u32 at_setup_sleep(hi_s32 argc, hi_char *argv[]) +{ + hi_u8 sleep_mode; + + if (argc != 1 || argv == HI_NULL) { /* just support sleep mode param */ + return HI_ERR_FAILURE; + } + + if ((at_param_null_check(argc, (const hi_char **)argv) != HI_ERR_SUCCESS) || + (integer_check(argv[0]) != HI_ERR_SUCCESS)) { + return HI_ERR_FAILURE; + } + + sleep_mode = (hi_u8)atoi(argv[0]); + if (sleep_mode > 2) { /* 0:wake up; 1:light sleep; 2:deep sleep */ + return HI_ERR_FAILURE; + } + + hi_lpc_set_type((hi_lpc_type)sleep_mode); + + hi_at_printf("OK\r\n"); + return HI_ERR_SUCCESS; +} + +hi_void wake_gpio_callback(hi_void *arg) +{ + /* Add processing code based on service scenarios. */ + hi_unref_param(arg); + /* To prevent the watchdog from being triggered by frequent reporting of GPIO interrupts + in some abnormal scenarios,the watchdog is reset. */ + hi_watchdog_feed(); + hi_at_printf("+WKGPIO: GPIO INT TRIGGER!\r\n"); +} + +hi_u32 check_io_status(hi_gpio_idx io_num) +{ + hi_u8 io_current_func = 0; + hi_gpio_dir gpio_dir = HI_GPIO_DIR_IN; + + hi_io_get_func((hi_io_name)io_num, &io_current_func); + if (io_num < HI_GPIO_IDX_13) { + if (io_current_func != 0) { + return HI_ERR_FAILURE; + } + } else { + if ((io_current_func != 0) && (io_current_func != IO13_GPIO_MODE)) { + return HI_ERR_FAILURE; + } + } + + gpio_get_dir(io_num, &gpio_dir); + if (gpio_dir == HI_GPIO_DIR_OUT) { + return HI_ERR_FAILURE; + } + + return HI_ERR_SUCCESS; +} + +hi_u32 wake_gpio_init(hi_gpio_idx io_num) +{ + hi_u32 ret; + ret = hi_io_set_func((hi_io_name)io_num, g_io_gpio_mode[io_num]); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + ret = hi_gpio_init(); + if ((ret != HI_ERR_SUCCESS) && (ret != HI_ERR_GPIO_REPEAT_INIT)) { + return ret; + } + + ret = hi_gpio_set_dir(io_num, HI_GPIO_DIR_IN); + if (ret != HI_ERR_SUCCESS) { + hi_gpio_deinit(); + return ret; + } + + return HI_ERR_SUCCESS; +} + +hi_u32 at_setup_wake_gpio(hi_s32 argc, hi_char *argv[]) +{ + hi_u32 ret; + hi_s32 i; + hi_gpio_idx io_num; + hi_gpio_int_type int_type; + hi_gpio_int_polarity int_level; + + if (argc != 3 || argv == HI_NULL) { /* 3 param: io_num, int_type, int_level */ + return HI_ERR_FAILURE; + } + + ret = at_param_null_check(argc, (const hi_char **)argv); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + for (i = 0; i < argc; i++) { + if (integer_check(argv[i]) != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + } + + io_num = (hi_gpio_idx)atoi(argv[0]); + if (io_num > HI_GPIO_IDX_14) { + return HI_ERR_FAILURE; + } + + int_type = (hi_gpio_int_type)atoi(argv[1]); + if (int_type > HI_INT_TYPE_EDGE) { + return HI_ERR_FAILURE; + } + + int_level = (hi_gpio_int_polarity)atoi(argv[2]); /* 2: int_level */ + if (int_level > HI_GPIO_EDGE_RISE_LEVEL_HIGH) { + return HI_ERR_FAILURE; + } + + ret = check_io_status(io_num); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + ret = wake_gpio_init(io_num); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + ret = hi_gpio_register_isr_function(io_num, int_type, int_level, wake_gpio_callback, HI_NULL); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + ret = hi_lpc_config_dsleep_wakeup_io(io_num, HI_TRUE); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + hi_at_printf("OK\r\n"); + return HI_ERR_SUCCESS; +} + +hi_u32 at_setup_ultra_dsleep(hi_s32 argc, hi_char *argv[]) +{ + hi_udsleep_src wake_gpio; + hi_s32 i; + hi_u32 ret; + hi_u8 wake_param; + + if (argc != 1 || argv[0] == HI_NULL) { + return HI_ERR_FAILURE; + } + + ret = at_param_null_check(argc, (const hi_char **)argv); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + for (i = 0; i < argc; i++) { + if (integer_check(argv[i]) != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + } + + wake_param = (hi_u8)atoi(argv[0]); + switch (wake_param) { + case ALL_GPIO_WAKE_UP_SOURCE: + wake_gpio = HI_UDS_GPIO3 | HI_UDS_GPIO5 + | HI_UDS_GPIO7 | HI_UDS_GPIO14; + break; + case GPIO3_WAKE_UP_SOURCE: + wake_gpio = HI_UDS_GPIO3; + break; + case GPIO5_WAKE_UP_SOURCE: + wake_gpio = HI_UDS_GPIO5; + break; + case GPIO7_WAKE_UP_SOURCE: + wake_gpio = HI_UDS_GPIO7; + break; + case GPIO14_WAKE_UP_SOURCE: + wake_gpio = HI_UDS_GPIO14; + break; + default: + return HI_ERR_FAILURE; + } + + hi_at_printf("OK\r\n"); + hi_udelay(3000); /* 3000:delay 3ms */ + hi_lpc_enable_udsleep(wake_gpio); + + return HI_ERR_SUCCESS; +} + +hi_u32 arp_offload_parse_ipv4_check(char *ip_str, unsigned int *ip_result) +{ + char *ip_str_cpy = ip_str; + const char delim = '.'; + unsigned char count = 0; + char *str_value = NULL; + hi_u32 value; + char *pos = NULL; + + if (strlen(ip_str) > 15) { /* 15 */ + return HI_ERR_FAILURE; + } + + pos = strchr(ip_str_cpy, delim); + while (pos != NULL && pos < (ip_str + 15)) { /* 15 */ + *pos = '\0'; + str_value = ip_str_cpy; + ip_str_cpy = pos + 1; + if ((strlen(str_value) < 1 || strlen(str_value) > 3) || /* 3 */ + (integer_check(str_value) != HI_ERR_SUCCESS)) { + return HI_ERR_FAILURE; + } + value = (hi_u32)atoi(str_value); + value <<= count * 8; /* 8 */ + count++; + *ip_result += value; + pos = strchr(ip_str_cpy, delim); + } + if (count != 3) { /* 3 */ + return HI_ERR_FAILURE; + } + + if ((strlen(ip_str_cpy) < 1 || strlen(ip_str_cpy) > 3) || /* 3 */ + (integer_check(ip_str_cpy) != HI_ERR_SUCCESS)) { + return HI_ERR_FAILURE; + } + value = (hi_u32)atoi(ip_str_cpy); + value <<= 3 * 8; /* 3*8 */ + *ip_result += value; + + return HI_ERR_SUCCESS; +} + + +hi_u32 at_set_arpoffload(hi_s32 argc, const hi_char **argv) +{ + const char *ifname = "wlan0"; + unsigned char enable; + unsigned int ip_addr = 0; + + if ((argc < 1) || (argc > 2) || (argv == NULL)) { /* 1/2 */ + return HI_ERR_FAILURE; + } + + if ((at_param_null_check(argc, argv) == HI_ERR_FAILURE) || (integer_check(argv[0]) != HI_ERR_SUCCESS)) { + return HI_ERR_FAILURE; + } + + enable = (unsigned char)atoi(argv[0]); + if (argc == 1) { + if (enable != 0) { + return HI_ERR_FAILURE; + } + } else { + if (enable != 1) { + return HI_ERR_FAILURE; + } + + if (arp_offload_parse_ipv4_check((char *)argv[1], &ip_addr) != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + } + + if (hi_wifi_arp_offload_setting(ifname, enable, ip_addr) != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + + hi_at_printf("OK\r\n"); + return HI_ERR_SUCCESS; +} + +hi_u32 at_set_powersave(hi_s32 argc, const hi_char **argv) +{ + unsigned char ps_switch; + int ret; + unsigned int wifi_sleep_time = 0; + + if ((argc < 1) || (argc > 2) || (argv == NULL)) { /* 1/2 */ + return HI_ERR_FAILURE; + } + + if ((at_param_null_check(argc, (const hi_char **)argv) != HI_ERR_SUCCESS) || + (integer_check(argv[0]) != HI_ERR_SUCCESS)) { + return HI_ERR_FAILURE; + } + + ps_switch = (unsigned char)atoi(argv[0]); + if (argc == 1) { + if ((ps_switch != 0) && (ps_switch != 1)) { + return HI_ERR_FAILURE; + } + } else { /* 2 parameters */ + if (ps_switch != 1) { + return HI_ERR_FAILURE; + } + + if (integer_check(argv[1]) != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + wifi_sleep_time = (unsigned int)atoi(argv[1]); + if ((wifi_sleep_time < 33) || (wifi_sleep_time > 4000)) { /* 33/4000 */ + return HI_ERR_FAILURE; + } + } + + ret = (hi_u32)hi_wifi_set_pm_switch(ps_switch, wifi_sleep_time); + if (ret != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + + hi_at_printf("OK\r\n"); + return HI_ERR_SUCCESS; +} + +hi_u32 at_set_ndoffload(hi_s32 argc, const hi_char **argv) +{ + const char *ifname = "wlan0"; + unsigned char enable; + ip6_addr_t ip6_addr = { 0 }; + + if ((argc < 1) || (argc > 2) || (argv == NULL)) { /* 1/2 */ + return HI_ERR_FAILURE; + } + + if ((at_param_null_check(argc, argv) == HI_ERR_FAILURE) || (integer_check(argv[0]) != HI_ERR_SUCCESS)) { + return HI_ERR_FAILURE; + } + + enable = (unsigned char)atoi(argv[0]); + if (argc == 1) { + if (enable != 0) { + return HI_ERR_FAILURE; + } + } else { + if (enable != 1) { + return HI_ERR_FAILURE; + } + + if (ip6addr_aton((char *)argv[1], &ip6_addr) != 1) { + return HI_ERR_FAILURE; + } + } + + if (hi_wifi_nd_offload_setting(ifname, enable, (unsigned char *)&ip6_addr) != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + + hi_at_printf("OK\r\n"); + return HI_ERR_SUCCESS; +} +#endif + +const at_cmd_func g_at_lowpower_func_tbl[] = { +#ifndef CONFIG_FACTORY_TEST_MODE + {"+SLP", 4, HI_NULL, HI_NULL, (at_call_back_func)at_setup_sleep, HI_NULL}, + {"+WKGPIO", 7, HI_NULL, HI_NULL, (at_call_back_func)at_setup_wake_gpio, HI_NULL}, + {"+USLP", 5, HI_NULL, HI_NULL, (at_call_back_func)at_setup_ultra_dsleep, HI_NULL}, + {"+ARP", 4, HI_NULL, HI_NULL, (at_call_back_func)at_set_arpoffload, HI_NULL}, + {"+PS", 3, HI_NULL, HI_NULL, (at_call_back_func)at_set_powersave, HI_NULL}, + {"+ND", 3, HI_NULL, HI_NULL, (at_call_back_func)at_set_ndoffload, HI_NULL}, +#endif +}; + +#define AT_LOWPOWER_FUNC_NUM (sizeof(g_at_lowpower_func_tbl) / sizeof(g_at_lowpower_func_tbl[0])) + +hi_void hi_at_lowpower_cmd_register(hi_void) +{ + hi_at_register_cmd(g_at_lowpower_func_tbl, AT_LOWPOWER_FUNC_NUM); +} + diff --git a/sdk_liteos/components/at/src/at_lowpower.h b/sdk_liteos/components/at/src/at_lowpower.h new file mode 100644 index 0000000000000000000000000000000000000000..8843c40a941f1d288d14486cd5889ebba7c6692b --- /dev/null +++ b/sdk_liteos/components/at/src/at_lowpower.h @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __AT_LOWPOWER_H__ +#define __AT_LOWPOWER_H__ + +#include "hi_types.h" + +hi_void hi_at_lowpower_cmd_register(hi_void); + +#endif diff --git a/sdk_liteos/components/at/src/at_parse.c b/sdk_liteos/components/at/src/at_parse.c new file mode 100644 index 0000000000000000000000000000000000000000..204765f894dfdb2f00c70af48dbcb4150190ba67 --- /dev/null +++ b/sdk_liteos/components/at/src/at_parse.c @@ -0,0 +1,233 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include "hi_config.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif + +hi_u32 at_param_shift(const hi_char *cmd_in, hi_char *cmd_out, hi_u32 size) +{ + hi_char *output = (hi_char *)NULL; + hi_char *out_bak = (hi_char *)NULL; + hi_u32 len = size; + hi_s32 ret; + + if ((cmd_in == NULL) || (cmd_out == NULL)) { + at_printf("cmd_in and cmd_out = NULL in %s[%d]", __FUNCTION__, __LINE__); + return HI_ERR_FAILURE; + } + + output = (hi_char *)hi_malloc(HI_MOD_ID_SAL_DFX, len); + if (output == NULL) { + at_printf("malloc failure in %s[%d]", __FUNCTION__, __LINE__); + return HI_ERR_FAILURE; + } + /* Backup the 'output' start address */ + out_bak = output; + /* Scan each charactor in 'cmd_in',and squeeze the overmuch space and ignore invaild charactor */ + for (; *cmd_in != '\0'; cmd_in++) { + if ((*cmd_in == '\\') && ((*(cmd_in + 1) == '\"') || (*(cmd_in + 1) == ','))) { + continue; + } + *output = *cmd_in; + output++; + } + *output = '\0'; + /* Restore the 'pscOutput' start address */ + output = out_bak; + len = strlen(output); + + /* Copy out the buffer which is been operated already */ + ret = strncpy_s(cmd_out, size, output, len); + if (ret != EOK) { + at_printf("%s,%d strncpy_s failed, err:%d!\n", __FUNCTION__, __LINE__, ret); + hi_free(HI_MOD_ID_SAL_DFX, out_bak); + return HI_ERR_FAILURE; + } + cmd_out[len] = '\0'; + + hi_free(HI_MOD_ID_SAL_DFX, out_bak); + + return HI_ERR_SUCCESS; +} + +hi_u32 cmd_parse_para_get(hi_u32 *value, hi_char *para_token_str) +{ + if ((para_token_str == NULL) || (value == NULL)) { + return HI_ERR_FAILURE; + } + hi_u32 ret; + hi_u32 value_in_len; + hi_char *value_in = HI_NULL; + + value_in_len = strlen(para_token_str) + 1; + value_in = (hi_char *)hi_malloc(HI_MOD_ID_SAL_DFX, value_in_len); + if (value_in == HI_NULL) { + at_printf("%s,%d hi_malloc failed!\n", __FUNCTION__, __LINE__); + return HI_ERR_FAILURE; + } + + memset_s(value_in, value_in_len, 0, value_in_len); + + ret = (hi_u32)strncpy_s(value_in, value_in_len, para_token_str, strlen(para_token_str)); + if (ret != EOK) { + at_printf("%s,%d strncpy_s failed, err:%d!\n", __FUNCTION__, __LINE__, ret); + hi_free(HI_MOD_ID_SAL_DFX, value_in); + return HI_ERR_FAILURE; + } + + ret = at_param_shift(value_in, para_token_str, value_in_len); + if (ret != HI_ERR_SUCCESS) { + at_printf("%s,%d at_param_shift failed, err:%d!\n", __FUNCTION__, __LINE__, ret); + hi_free(HI_MOD_ID_SAL_DFX, value_in); + return HI_ERR_FAILURE; + } + *value = (hi_u32)(uintptr_t)para_token_str; + + hi_free(HI_MOD_ID_SAL_DFX, value_in); + return HI_ERR_SUCCESS; +} + +hi_u32 cmd_parse_one_token(at_cmd_attr *cmd_parsed, hi_u32 index, hi_char *token) +{ + hi_u32 ret = HI_ERR_SUCCESS; + + if (cmd_parsed == NULL) { + return HI_ERR_FAILURE; + } + + if (index == 0) { + if (cmd_parsed->at_cmd_type != AT_CMD_TYPE_SETUP) { + return ret; + } + } + + if (index >= AT_CMD_MAX_PARAS) { + return HI_ERR_FAILURE; + } + + if (token[0] == '\0') { + hi_u32 len = cmd_parsed->at_param_cnt; + cmd_parsed->param_array[len] = NULL; + cmd_parsed->at_param_cnt++; + return ret; + } + + if (cmd_parsed->at_param_cnt < AT_CMD_MAX_PARAS) { + hi_u32 len = cmd_parsed->at_param_cnt; + ret = cmd_parse_para_get(&(cmd_parsed->param_array[len]), token); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + cmd_parsed->at_param_cnt++; + } + + return ret; +} + +hi_u32 at_cmd_token_split(hi_char *cmd, hi_char split, at_cmd_attr *cmd_parsed) +{ + enum { + STAT_INIT, + STAT_TOKEN_IN, + STAT_TOKEN_OUT + } state = STAT_INIT; + + hi_char *token = NULL; + hi_char *p = NULL; + hi_u32 count = 0; + hi_u32 ret = HI_ERR_SUCCESS; + + if (cmd == NULL) { + return HI_ERR_FAILURE; + } + + token = cmd; + + for (p = cmd; (*p != '\0') && (ret == HI_ERR_SUCCESS); p++) { + if (state == STAT_TOKEN_OUT) { + token = p; + state = STAT_TOKEN_IN; + } + + if (state == STAT_INIT || state == STAT_TOKEN_IN) { + if ((*p == split) && (*(p - 1) != '\\')) { + *p = '\0'; + ret = cmd_parse_one_token(cmd_parsed, count++, token); + state = STAT_TOKEN_OUT; + } + } + } + + if (*(p - 1) == '\0') { + token = p; + } + if ((ret == HI_ERR_SUCCESS) || (state == STAT_INIT)) { + ret = cmd_parse_one_token(cmd_parsed, count, token); + } + + return ret; +} + +hi_u32 at_para_parse(hi_char *cmd_line, at_cmd_attr *cmd_parsed) +{ + if ((cmd_line == NULL) || (cmd_parsed == NULL) || (strlen(cmd_line) == 0)) { + return HI_ERR_FAILURE; + } + + return at_cmd_token_split(cmd_line, ',', cmd_parsed); +} + +hi_u32 at_cmd_parse(hi_char *cmd_line, at_cmd_attr *cmd_parsed) +{ + hi_u32 ret; + if (cmd_line == HI_NULL || cmd_parsed == HI_NULL) { + return HI_ERR_FAILURE; + } + + cmd_line += cmd_parsed->at_cmd_len; + at_printf("at_cmd_parse line %d: cmd_line = %s\n", __LINE__, cmd_line); + if (*cmd_line == '\0') { + cmd_parsed->at_cmd_type = AT_CMD_TYPE_EXE; + } else if (*cmd_line == '?' && (cmd_line[1] == '\0')) { + cmd_parsed->at_cmd_type = AT_CMD_TYPE_QUERY; + } else if ((*cmd_line == '=') && (cmd_line[1] == '?') && (cmd_line[2] == '\0')) { /* 2: the third character */ + cmd_parsed->at_cmd_type = AT_CMD_TYPE_TEST; + } else if ((*cmd_line == '=') && (cmd_line[1] != '?')) { + cmd_parsed->at_cmd_type = AT_CMD_TYPE_SETUP; + + if (cmd_line[1] != '\0') { + ret = at_para_parse(cmd_line + 1, cmd_parsed); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + } + } + + return HI_ERR_SUCCESS; +} + +#ifdef __cplusplus +#if __cplusplus + } +#endif +#endif \ No newline at end of file diff --git a/sdk_liteos/components/at/src/at_parse.h b/sdk_liteos/components/at/src/at_parse.h new file mode 100644 index 0000000000000000000000000000000000000000..8a9bb0615c251a186e2c4156db6e56b182ea0831 --- /dev/null +++ b/sdk_liteos/components/at/src/at_parse.h @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __AT_PARSE_H__ +#define __AT_PARSE_H__ + +#include "at.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif + +hi_u32 at_cmd_parse(hi_char *cmd_line, at_cmd_attr *cmd_parsed); + +#ifdef __cplusplus +#if __cplusplus + } +#endif +#endif + +#endif \ No newline at end of file diff --git a/sdk_liteos/components/at/src/at_printf.c b/sdk_liteos/components/at/src/at_printf.c new file mode 100644 index 0000000000000000000000000000000000000000..1550975fb44ed1255659a7dadc9486b184ad52f3 --- /dev/null +++ b/sdk_liteos/components/at/src/at_printf.c @@ -0,0 +1,145 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "at_printf.h" + +#include +#include +#include + +#include "hi_at.h" + +uintptr_t g_at_uart_baseaddr = HI_UART1_REG_BASE; +uintptr_t g_sysinfo_uart_baseaddr = HI_UART0_REG_BASE; + +/* send */ +hi_void serial_putc_at(hi_char c) +{ + /* Wait until there is space in the FIFO */ + while ((hi_reg_read_val16(g_at_uart_baseaddr + UART_FR) & UARTFR_TXFF_MASK) != 0) {} + + /* Send the character */ + hi_reg_write16(g_at_uart_baseaddr + UART_DR, (hi_uchar)c); +} + +hi_s32 uart_puts_at(const hi_char *ptr, hi_u32 len, const hi_void *state) +{ + hi_s32 len_ret = (hi_s32)len; + hi_at_output_func at_output_func = hi_at_get_register_output_func(); + + (hi_void)state; + while (len-- && (*ptr != 0)) { + if (*ptr == '\n') { + if (at_output_func == HI_NULL) { + serial_putc_at(*ptr++); + } else { + at_output_func((const hi_u8*)ptr++, 1); + } + } else { + if (at_output_func == HI_NULL) { + serial_putc_at(*ptr++); + } else { + at_output_func((const hi_u8*)ptr++, 1); + } + } + } + return len_ret; +} + + +hi_s32 hi_at_printf(const hi_char *fmt, ...) +{ + va_list ap = 0; + hi_s32 len; + va_start(ap, fmt); + +#if defined(CONFIG_AT_COMMAND) || defined(CONFIG_FACTORY_TEST_MODE) + OUTPUT_FUNC fn_put = (OUTPUT_FUNC)uart_puts_at; + len = __dprintf(fmt, ap, fn_put, (void *)NULL); +#else + len = 0; +#endif + + va_end(ap); + return len; +} + +/* send */ +hi_void serial_putc_crashinfo(hi_char c) +{ +#if defined(CONFIG_AT_COMMAND) || defined(CONFIG_FACTORY_TEST_MODE) + /* Wait until there is space in the FIFO */ + while ((hi_reg_read_val16(g_at_uart_baseaddr + UART_FR) & UARTFR_TXFF_MASK) != 0) {} + + /* Send the character */ + hi_reg_write16(g_at_uart_baseaddr + UART_DR, (hi_uchar)c); +#else + /* Wait until there is space in the FIFO */ + while ((hi_reg_read_val16(g_sysinfo_uart_baseaddr + UART_FR) & UARTFR_TXFF_MASK) != 0) {} + + /* Send the character */ + hi_reg_write16(g_sysinfo_uart_baseaddr + UART_DR, (hi_uchar)c); +#endif +} + +hi_s32 uart_puts_sysinfo(const hi_char *ptr, hi_u32 len, const hi_void *state) +{ + hi_s32 len_ret = (hi_s32)len; + hi_at_output_func at_output_func = hi_at_get_register_output_func(); + + (hi_void)state; + while (len-- && (*ptr != 0)) { + if (*ptr == '\n') { + if (at_output_func == HI_NULL) { + serial_putc_crashinfo('\r'); + serial_putc_crashinfo(*ptr++); + } else { +#if defined(CONFIG_AT_COMMAND) || defined(CONFIG_FACTORY_TEST_MODE) + hi_char tmp_char = '\r'; + at_output_func((const hi_u8*)&tmp_char, 1); + at_output_func((const hi_u8*)ptr++, 1); +#else + serial_putc_crashinfo('\r'); + serial_putc_crashinfo(*ptr++); +#endif + } + } else { + if (at_output_func == HI_NULL) { + serial_putc_crashinfo(*ptr++); + } else { +#if defined(CONFIG_AT_COMMAND) || defined(CONFIG_FACTORY_TEST_MODE) + at_output_func((const hi_u8*)ptr++, 1); +#else + serial_putc_crashinfo(*ptr++); +#endif + } + } + } + return len_ret; +} + +hi_s32 hi_at_printf_crashinfo(const hi_char *fmt, ...) +{ + va_list ap = 0; + hi_s32 len; + va_start(ap, fmt); + + OUTPUT_FUNC fn_put = (OUTPUT_FUNC)uart_puts_sysinfo; + len = __dprintf(fmt, ap, fn_put, (void *)NULL); + + va_end(ap); + return len; +} + diff --git a/sdk_liteos/components/at/src/at_printf.h b/sdk_liteos/components/at/src/at_printf.h new file mode 100644 index 0000000000000000000000000000000000000000..fb9809169ea733841fefdd2fe3b2a7253591ede0 --- /dev/null +++ b/sdk_liteos/components/at/src/at_printf.h @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __AT_PRINTF_H__ +#define __AT_PRINTF_H__ + +#include +#include "hi_types.h" + +hi_void serial_putc_at(hi_char c); + +extern uintptr_t g_at_uart_baseaddr; +extern LITE_OS_SEC_TEXT INT32 __dprintf(const CHAR *format, va_list arg_v, OUTPUT_FUNC pFputc, VOID *cookie); + +hi_s32 hi_at_printf_crashinfo(const hi_char *fmt, ...); + +#endif diff --git a/sdk_liteos/components/at/src/at_wifi.c b/sdk_liteos/components/at/src/at_wifi.c new file mode 100755 index 0000000000000000000000000000000000000000..6b6ee56156b6c97ac7f3b958a8165cdd0df8ea32 --- /dev/null +++ b/sdk_liteos/components/at/src/at_wifi.c @@ -0,0 +1,1390 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "at_wifi.h" + +#include +#include + +#include + +#ifndef CONFIG_FACTORY_TEST_MODE +#include "lwip/netifapi.h" +#endif +#include "hi_early_debug.h" +#include "hi_stdlib.h" +#include "hi_wifi_api.h" +#include "hi_wifi_mfg_test_if.h" +#ifdef LOSCFG_APP_MESH +#include "hi_wifi_mesh_api.h" +#include "hi_mesh_autolink_api.h" +#endif + +#include "at.h" +#ifndef CONFIG_FACTORY_TEST_MODE +#include "lwip/netifapi.h" +#include "lwip/dns.h" +#endif +#include "hi_wifi_mfg_test_if.h" +#include "at_demo_hks.h" +#include "at_general.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif + +hi_wifi_bw g_bw_setup_value = HI_WIFI_BW_LEGACY_20M; +#ifdef _PRE_PSK_CALC_USER +unsigned char g_psk_calc[HI_WIFI_STA_PSK_LEN] = {0}; +#endif +hi_wifi_sta_psk_config g_set_psk_config = { + .ssid = {0}, + .key = {0} +}; + +hi_u32 ssid_prefix_scan(hi_s32 argc, const hi_char *argv[], hi_u32 prefix_flag) +{ + hi_s32 ret; + errno_t rc; + char *tmp = HI_NULL; + size_t ssid_len = 0; + hi_wifi_scan_params scan_params = {0}; + + if ((argc != 1) || (at_param_null_check(argc, argv) == HI_ERR_FAILURE)) { + return HI_ERR_FAILURE; + } + + /* get ssid */ + if (argv[0][0] == 'P') { + if (strlen(argv[0]) > HI_WIFI_MAX_SSID_LEN * 4 + 3) { /* ssid length should less than 32*4+3 */ + return HI_ERR_FAILURE; + } + } else { + if (strlen(argv[0]) > HI_WIFI_MAX_SSID_LEN + 2) { /* ssid length should less than 32+2 */ + return HI_ERR_FAILURE; + } + } + /* ssid hex to string */ + tmp = at_parse_string(argv[0], &ssid_len); + scan_params.ssid_len = (unsigned char)ssid_len; + if (tmp == HI_NULL) { + return HI_ERR_FAILURE; + } + if ((scan_params.ssid_len > HI_WIFI_MAX_SSID_LEN) || (scan_params.ssid_len == 0)) { + at_free(tmp); + return HI_ERR_FAILURE; + } + rc = memcpy_s(scan_params.ssid, HI_WIFI_MAX_SSID_LEN + 1, tmp, strlen(tmp) + 1); + at_free(tmp); + if (rc != EOK) { + return HI_ERR_FAILURE; + } + + scan_params.ssid[scan_params.ssid_len] = '\0'; + + scan_params.scan_type = (prefix_flag == 1) ? HI_WIFI_SSID_PREFIX_SCAN : HI_WIFI_SSID_SCAN; + + ret = hi_wifi_sta_advance_scan(&scan_params); + if (ret != HISI_OK) { + return HI_ERR_FAILURE; + } + + hi_at_printf("OK\r\n"); + return HI_ERR_SUCCESS; +} + + +/***************************************************************************** +* Func description: wpa ssid scan +*****************************************************************************/ +hi_u32 cmd_wpa_ssid_scan(hi_s32 argc, const hi_char *argv[]) +{ + hi_u32 ret = ssid_prefix_scan(argc, argv, 0); + return ret; +} + +/***************************************************************************** +* Func description: wpa channel scan +*****************************************************************************/ +hi_u32 cmd_wpa_channel_scan(hi_s32 argc, const hi_char *argv[]) +{ + hi_s32 ret; + hi_wifi_scan_params scan_params = {0}; + + if ((argc != 1) || (integer_check(argv[0]) != HI_ERR_SUCCESS)) { + return HI_ERR_FAILURE; + } + + scan_params.channel = (hi_uchar)atoi(argv[0]); + if ((scan_params.channel < 1) || (scan_params.channel > 14)) { /* 信道范围1~14 */ + return HI_ERR_FAILURE; + } + scan_params.scan_type = HI_WIFI_CHANNEL_SCAN; + ret = hi_wifi_sta_advance_scan(&scan_params); + if (ret != HISI_OK) { + return HI_ERR_FAILURE; + } + + hi_at_printf("OK\r\n"); + return HI_ERR_SUCCESS; +} + +/***************************************************************************** +* Func description: wpa scan +*****************************************************************************/ +hi_u32 cmd_wpa_scan(hi_s32 argc, const hi_char *argv[]) +{ + hi_s32 ret; + + hi_unref_param(argc); + hi_unref_param(argv); + + ret = hi_wifi_sta_scan(); + if (ret != HISI_OK) { + return HI_ERR_FAILURE; + } + + hi_at_printf("OK\r\n"); + return HI_ERR_SUCCESS; +} + +/***************************************************************************** +* Func description: ssid prefix scan +* example: AT+SCANPRSSID="hisi" +*****************************************************************************/ +hi_u32 cmd_ssid_prefix_scan(hi_s32 argc, const hi_char *argv[]) +{ + hi_u32 ret = ssid_prefix_scan(argc, argv, 1); + return ret; +} + +hi_u32 at_check_ccharacter(const hi_char *tmp) +{ + if (tmp == HI_NULL) { + return HI_ERR_FAILURE; + } + for (; *tmp != '\0'; tmp++) { + if (*tmp == '\\') { + if (*(tmp + 1) == '\\') { + tmp++; + continue; + } else if (*(tmp + 1) == 'x') { + return HI_ERR_SUCCESS; + } + } + } + return HI_ERR_FAILURE; +} + +/***************************************************************************** +* Func description: wpa get scan results +*****************************************************************************/ +hi_u32 cmd_wpa_scan_results(hi_s32 argc, const hi_char *argv[]) +{ + hi_u32 num = WIFI_SCAN_AP_LIMIT; + hi_char ssid_str[HI_WIFI_MAX_SSID_LEN * 4 + 3]; /* ssid length should less 32*4+3 */ + + hi_unref_param(argv); + hi_unref_param(argc); + + hi_wifi_ap_info *results = malloc(sizeof(hi_wifi_ap_info) * WIFI_SCAN_AP_LIMIT); + if (results == HI_NULL) { + return HI_ERR_FAILURE; + } + + memset_s(results, sizeof(hi_wifi_ap_info) * WIFI_SCAN_AP_LIMIT, 0, sizeof(hi_wifi_ap_info) * WIFI_SCAN_AP_LIMIT); + + hi_s32 ret = hi_wifi_sta_scan_results(results, &num); + if (ret != HISI_OK) { + free(results); + return HI_ERR_FAILURE; + } + + for (hi_u32 ul_loop = 0; (ul_loop < num) && (ul_loop < WIFI_SCAN_AP_LIMIT); ul_loop++) { + if ((results[ul_loop].auth < HI_WIFI_SECURITY_OPEN) || (results[ul_loop].auth > HI_WIFI_SECURITY_UNKNOWN)) { + results[ul_loop].auth = HI_WIFI_SECURITY_UNKNOWN; + } + + hi_u32 service_flag = 0; + if (results[ul_loop].wps_flag) { + service_flag = 1; + } else if (results[ul_loop].hisi_mesh_flag) { + service_flag = 2; /* 2:Mesh scenario.CNcomment:Mesh场景 */ + } + + size_t ssid_len = strlen(results[ul_loop].ssid); + const char* tmp = at_ssid_txt((unsigned char*)results[ul_loop].ssid, ssid_len); + if (at_check_ccharacter(tmp) == HI_ERR_SUCCESS) { + ret = sprintf_s(ssid_str, HI_WIFI_MAX_SSID_LEN * 4 + 3, "P\"%s\"", tmp); /* ssid len should less 32*4+3 */ + } else { + ret = sprintf_s(ssid_str, HI_WIFI_MAX_SSID_LEN * 4 + 3, "%s", results[ul_loop].ssid); /* less 32*4+3 */ + } + if (ret < 0) { + free(results); + return HI_ERR_FAILURE; + } + + if (service_flag != 0) { + hi_at_printf("+SCANRESULT:%s,"AT_MACSTR",%d,%d,%d,%d\r\n", ssid_str, at_mac2str(results[ul_loop].bssid), + results[ul_loop].channel, results[ul_loop].rssi / 100, results[ul_loop].auth, service_flag); + } else { + hi_at_printf("+SCANRESULT:%s,"AT_MACSTR",%d,%d,%d\r\n", ssid_str, at_mac2str(results[ul_loop].bssid), + results[ul_loop].channel, results[ul_loop].rssi / 100, results[ul_loop].auth); + } + } + + free(results); + + hi_at_printf("OK\r\n"); + return HI_ERR_SUCCESS; +} + +/***************************************************************************** +* Func description: start sta +*****************************************************************************/ +hi_u32 cmd_sta_start(hi_s32 argc, const hi_char *argv[]) +{ + hi_unref_param(argv); + hi_unref_param(argc); +#ifndef CONFIG_FACTORY_TEST_MODE + hi_s32 ret; + hi_char ifname[WIFI_IFNAME_MAX_SIZE + 1] = {0}; + hi_s32 len = sizeof(ifname); + + ret = hi_wifi_sta_start(ifname, &len); + if (ret != HISI_OK) { + return HI_ERR_FAILURE; + } +#else + if (wal_add_cfg_vap() != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } +#endif + hi_at_printf("OK\r\n"); + return HI_ERR_SUCCESS; +} + +hi_u32 sta_start_adv_param(hi_s32 argc, const hi_char *argv[], hi_wifi_bw *bw) +{ + hi_s32 ret, value, i; + for (i = 0; i < argc; i++) { + if ((argv[i] != HI_NULL) && (integer_check(argv[i]) != HI_ERR_SUCCESS)) { + return HI_ERR_FAILURE; + } + switch (i) { + case 0: /* case 0: Protocol Type */ + value = (argv[i] != HI_NULL) ? atoi(argv[i]) : HI_WIFI_PHY_MODE_11BGN; + if ((value == HI_WIFI_PHY_MODE_11B) && (argv[1] != HI_NULL) && (strcmp(argv[1], "20"))) { /* 20:bw */ + return HI_ERR_FAILURE; + } +#ifndef CONFIG_FACTORY_TEST_MODE + ret = hi_wifi_sta_set_protocol_mode((hi_wifi_protocol_mode)value); +#endif + break; + case 1: /* case 1: Bandwidth */ + if ((argv[i] == HI_NULL) || !(strcmp(argv[i], "20"))) { /* bw 20M */ + *bw = HI_WIFI_BW_LEGACY_20M; + } else if (!(strcmp(argv[i], "10"))) { /* bw 10M */ + *bw = HI_WIFI_BW_HIEX_10M; + } else if (!(strcmp(argv[i], "5"))) { /* bw 5M */ + *bw = HI_WIFI_BW_HIEX_5M; + } else { + return HI_ERR_FAILURE; + } + ret = HISI_OK; + break; + case 2: /* case 2: pmf */ +#ifndef CONFIG_FACTORY_TEST_MODE + value = (argv[i] != HI_NULL) ? atoi(argv[i]) : HI_WIFI_MGMT_FRAME_PROTECTION_OPTIONAL; + ret = hi_wifi_set_pmf((hi_wifi_pmf_options)value); +#endif + break; + default: + return HI_ERR_FAILURE; + } +#ifndef CONFIG_FACTORY_TEST_MODE + if (ret != HISI_OK) { + return HI_ERR_FAILURE; + } +#endif + } + hi_unref_param(ret); + return HI_ERR_SUCCESS; +} + +hi_u32 cmd_sta_start_adv(hi_s32 argc, const hi_char *argv[]) +{ + hi_s32 ret; + hi_wifi_bw bw = HI_WIFI_BW_LEGACY_20M; + + if (argc != 3) { /* "+STARTSTA" command fix 3 parameters */ + return HI_ERR_FAILURE; + } + + ret = (hi_s32)sta_start_adv_param(argc, argv, &bw); + if (ret != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } +#ifndef CONFIG_FACTORY_TEST_MODE + hi_char ifname[WIFI_IFNAME_MAX_SIZE + 1] = {0}; + hi_s32 len = sizeof(ifname); + ret = hi_wifi_sta_start(ifname, &len); + if (ret != HISI_OK) { + return HI_ERR_FAILURE; + } +#endif + ret = hi_wifi_set_bandwidth(DEFAULT_IFNAME_STA, strlen(DEFAULT_IFNAME_STA) + 1, bw); + if (ret != HI_ERR_SUCCESS) { +#ifndef CONFIG_FACTORY_TEST_MODE + hi_wifi_sta_stop(); +#endif + return HI_ERR_FAILURE; + } + + hi_at_printf("OK\r\n"); + return HI_ERR_SUCCESS; +} + +/***************************************************************************** +* Func description: stop station +*****************************************************************************/ +hi_u32 cmd_sta_stop(hi_s32 argc, const hi_char *argv[]) +{ + hi_unref_param(argv); + hi_unref_param(argc); +#ifndef CONFIG_FACTORY_TEST_MODE + hi_s32 ret = hi_wifi_sta_stop(); + if (ret != HISI_OK) { + return HI_ERR_FAILURE; + } + + for (int index = 0; index < DNS_MAX_SERVERS; index++) { + lwip_dns_setserver(index, HI_NULL); + } +#endif + hi_at_printf("OK\r\n"); + return HI_ERR_SUCCESS; +} + +hi_u32 cmd_sta_connect_get_ssid(const hi_char *argv[], hi_wifi_assoc_request *assoc_req, + hi_wifi_fast_assoc_request *fast_assoc_req, hi_u32 fast_flag) +{ + size_t ssid_len = 0; + errno_t rc; + + if (argv[0][0] == 'P') { + if (strlen(argv[0]) > HI_WIFI_MAX_SSID_LEN * 4 + 3) { /* ssid length should less than 32*4+3 */ + return HI_ERR_FAILURE; + } + } else { + if (strlen(argv[0]) > HI_WIFI_MAX_SSID_LEN + 2) { /* ssid length should less than 32+2 */ + return HI_ERR_FAILURE; + } + } + + /* ssid hex to string */ + hi_char *tmp = at_parse_string(argv[0], &ssid_len); + if (tmp == HI_NULL) { + return HI_ERR_FAILURE; + } + if ((ssid_len > HI_WIFI_MAX_SSID_LEN) || (ssid_len == 0)) { + at_free(tmp); + return HI_ERR_FAILURE; + } + + if ((fast_flag == 0) && (assoc_req != HI_NULL)) { + rc = memcpy_s(assoc_req->ssid, HI_WIFI_MAX_SSID_LEN + 1, tmp, strlen(tmp) + 1); + at_free(tmp); + if (rc != EOK) { + return HI_ERR_FAILURE; + } + } else if ((fast_flag == 1) && (fast_assoc_req != HI_NULL)) { + rc = memcpy_s(fast_assoc_req->req.ssid, HI_WIFI_MAX_SSID_LEN + 1, tmp, strlen(tmp) + 1); + at_free(tmp); + if (rc != EOK) { + return HI_ERR_FAILURE; + } + } else { + at_free(tmp); + } + return HI_ERR_SUCCESS; +} + +hi_u32 cmd_sta_connect_get_key(hi_s32 argc, const hi_char *argv[], hi_wifi_fast_assoc_request *fast_assoc_req) +{ + if ((fast_assoc_req->req.auth != HI_WIFI_SECURITY_OPEN) && (argc == 5)) { /* 5 parameters */ + if (argv[4] == HI_NULL) { /* 4:key */ + return HI_ERR_FAILURE; + } + const hi_char *buf = argv[4]; /* 4:key */ + + size_t len = strlen(argv[4]); /* 4:key */ + if ((atoi(argv[3]) == HI_WIFI_SECURITY_WEP) && (len != 9) && (len != 17) && /* 3:encrypt type, 9 17:len */ + (len != 12) && (len != 28)) { /* 12 28: password len */ + return HI_ERR_FAILURE; + } else if ((atoi(argv[3]) != HI_WIFI_SECURITY_WEP) && ((len > HI_WIFI_AP_KEY_LEN_MAX + 2) || /* argc 3,2 */ + (len < HI_WIFI_AP_KEY_LEN_MIN + 2))) { /* len plus 2 */ + return HI_ERR_FAILURE; + } + if ((buf == HI_NULL) || (*buf != '\"') || (*(buf + strlen(argv[4]) - 1) != '\"') || /* 4 */ + (memcpy_s(fast_assoc_req->req.key, HI_WIFI_MAX_KEY_LEN + 1, buf + 1, strlen(argv[4]) - 2) /* 4 2 */ + != EOK)) { + return HI_ERR_FAILURE; + } + } + fast_assoc_req->psk_flag = HI_WIFI_WPA_PSK_NOT_USE; + + return HI_ERR_SUCCESS; +} + +hi_u32 parse_conn_para(hi_s32 argc, const hi_char *argv[], hi_wifi_assoc_request *assoc_req) +{ + if ((argc < 3) || (argc > 4)) { /* The number of "+CONN" command parameters should be 3 or 4 */ + return HI_ERR_FAILURE; + } + + /* get ssid */ + if ((argv[0] != HI_NULL) && (cmd_sta_connect_get_ssid(argv, assoc_req, HI_NULL, 0) != HI_ERR_SUCCESS)) { + return HI_ERR_FAILURE; + } + + /* get bssid */ + if (argv[1] == HI_NULL) { + memset_s(assoc_req->bssid, sizeof(assoc_req->bssid), 0, sizeof(assoc_req->bssid)); + } else if (strlen(argv[1]) == HI_WIFI_TXT_ADDR_LEN) { + if (cmd_strtoaddr(argv[1], assoc_req->bssid, HI_WIFI_MAC_LEN) != HISI_OK) { + return HI_ERR_FAILURE; + } + } else { + return HI_ERR_FAILURE; + } + + /* get auth_type */ + if ((integer_check(argv[2]) != HI_ERR_SUCCESS) || (atoi(argv[2]) < HI_WIFI_SECURITY_OPEN) || /* 2 */ + (atoi(argv[2]) > HI_WIFI_SECURITY_WPAPSK_WPA2PSK_MIX) || ((atoi(argv[2]) == HI_WIFI_SECURITY_OPEN) && /* 2 */ + (argc != 3)) || ((atoi(argv[2]) != HI_WIFI_SECURITY_OPEN) && (argc != 4))) { /* argc 3/2/4 */ + return HI_ERR_FAILURE; + } + assoc_req->auth = (hi_wifi_auth_mode)atoi(argv[2]); /* 2 */ + + /* The encipher mode is set to 0 by default, that is, HI_WIFI_PARIWISE_UNKNOWN. + CNcomment:encipher mode 默认设置为0,即HI_WIFI_PARIWISE_UNKNOWN */ + assoc_req->pairwise = HI_WIFI_PARIWISE_UNKNOWN; + + /* get key */ + if (argc == 4) { /* 4 parameters */ + const hi_char *buf = argv[3]; /* 3:The fourth parameter */ + if (buf == HI_NULL) { + return HI_ERR_FAILURE; + } + size_t len = strlen(argv[3]); /* 3:key */ + if ((atoi(argv[2]) == HI_WIFI_SECURITY_WEP) && (len != 9) && (len != 17) && /* argc 2, len 9/17 */ + (len != 12) && (len != 28)) { /* len 12/28 */ + return HI_ERR_FAILURE; + } else if ((atoi(argv[2]) != HI_WIFI_SECURITY_WEP) && ((len > HI_WIFI_AP_KEY_LEN_MAX + 2) || /* argc 2 */ + (len < HI_WIFI_AP_KEY_LEN_MIN + 2))) { /* len plus 2 */ + return HI_ERR_FAILURE; + } + if ((*buf != '\"') || (*(buf + strlen(argv[3]) - 1) != '\"') || /* argc 3 */ + (memcpy_s(assoc_req->key, HI_WIFI_MAX_KEY_LEN + 1, buf + 1, strlen(argv[3]) - 2) != EOK)) { /* 3 2 */ + return HI_ERR_FAILURE; + } + } + + return HI_ERR_SUCCESS; +} + +/***************************************************************************** +* Func description: station connect network +* example: AT+CONN="hisilicon",,3,"123456789" +*****************************************************************************/ +hi_u32 cmd_sta_secure_connect(hi_s32 argc, const hi_char *argv[]) +{ + hi_wifi_assoc_request assoc_req = {0}; + + if (parse_conn_para(argc, argv, &assoc_req) != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + + if (hi_wifi_sta_connect(&assoc_req) != HISI_OK) { + return HI_ERR_FAILURE; + } + + hi_u32 ret = app_hks_encrypt_conn_para(&assoc_req); + if (ret != HI_ERR_SUCCESS) { + hi_at_printf("save enc conn param fail:0x%x\r\n", ret); + return HI_ERR_FAILURE; + } + + hi_at_printf("OK\r\n"); + return HI_ERR_SUCCESS; +} + +hi_u32 cmd_sta_secure_re_connect(hi_s32 argc, const hi_char *argv[]) +{ + hi_unref_param(argc); + hi_unref_param(argv); + + hi_wifi_assoc_request assoc_req = {0}; + + hi_u32 ret = app_hks_decrypt_conn_param(&assoc_req); + if (ret != HI_ERR_SUCCESS) { + hi_at_printf("get reconn param fail:0x%x\r\n", ret); + return HI_ERR_FAILURE; + } + hi_at_printf("get reconn param ok\r\n"); + + if (hi_wifi_sta_connect(&assoc_req) != HISI_OK) { + return HI_ERR_FAILURE; + } + + hi_at_printf("OK\r\n"); + return HI_ERR_SUCCESS; +} + +hi_u32 cmd_generate_save_conn_key(hi_s32 argc, const hi_char *argv[]) +{ + hi_unref_param(argc); + hi_unref_param(argv); + + hi_u32 ret = app_hks_generate_conn_key(); + if (ret != HI_ERR_SUCCESS) { + hi_at_printf("generate conn key fail:0x%x\r\n", ret); + return HI_ERR_FAILURE; + } + + hi_at_printf("generate conn key ok\r\n"); + hi_at_printf("OK\r\n"); + return HI_ERR_SUCCESS; +} + +hi_u32 cmd_generate_save_cert_key(hi_s32 argc, const hi_char *argv[]) +{ + hi_unref_param(argc); + hi_unref_param(argv); + + hi_u32 ret = app_hks_generate_cert_key(); + if (ret != HI_ERR_SUCCESS) { + hi_at_printf("generate cert key fail\r\n"); + return HI_ERR_FAILURE; + } + + hi_at_printf("generate cert key ok\r\n"); + hi_at_printf("OK\r\n"); + return HI_ERR_SUCCESS; +} + +hi_u32 cmd_encrypt_cert(hi_s32 argc, const hi_char *argv[]) +{ + hi_unref_param(argc); + hi_unref_param(argv); + + hi_u32 ret = app_hks_encrypt_cert(); + if (ret != HI_ERR_SUCCESS) { + hi_at_printf("encrpyt cert fail\r\n"); + return HI_ERR_FAILURE; + } + hi_at_printf("encrpyt cert success\r\n"); + + hi_at_printf("OK\r\n"); + return HI_ERR_SUCCESS; +} + +#define CERT_PLAIN_SIZE (1024*8) + +hi_u32 cmd_decrypt_cert(hi_s32 argc, const hi_char *argv[]) +{ + hi_unref_param(argc); + hi_unref_param(argv); + + hi_u32 plain_size = CERT_PLAIN_SIZE; + hi_u8 *plain_data = malloc(plain_size); + if (plain_data == HI_NULL) { + hi_at_printf("plain data malloc fail\r\n"); + return HI_ERR_FAILURE; + } + + hi_u32 ret = app_hks_decrypt_cert(&plain_size, plain_data); + if (ret != HI_ERR_SUCCESS) { + free(plain_data); + hi_at_printf("decrpyt cert fail:0x%x\r\n", ret); + return HI_ERR_FAILURE; + } + + hi_at_printf("decrpyt cert success, plain_size:%d\r\n", plain_size); + hi_u32 print_size = 0x40; + if (plain_size < print_size) { + print_size = plain_size; + } + for (hi_u32 i = 1; i <= print_size; i++) { + hi_at_printf("0x%x ", plain_data[i - 1]); + if (i % 0x4 == 0) { + hi_at_printf("\r\n"); + } + } + + free(plain_data); + + hi_at_printf("OK\r\n"); + return HI_ERR_SUCCESS; +} + +/***************************************************************************** +* Func description: station connect network +* example: AT+CONN="hisilicon",,3,"123456789" +*****************************************************************************/ +hi_u32 cmd_sta_connect(hi_s32 argc, const hi_char *argv[]) +{ + hi_wifi_assoc_request assoc_req = {0}; + + if ((argc < 3) || (argc > 4)) { /* argc 3/4 */ + return HI_ERR_FAILURE; + } + + /* get ssid */ + if ((argv[0] != HI_NULL) && (cmd_sta_connect_get_ssid(argv, &assoc_req, HI_NULL, 0) != HI_ERR_SUCCESS)) { + return HI_ERR_FAILURE; + } + + /* get bssid */ + if (argv[1] == HI_NULL) { + memset_s(assoc_req.bssid, sizeof(assoc_req.bssid), 0, sizeof(assoc_req.bssid)); + } else if (strlen(argv[1]) == HI_WIFI_TXT_ADDR_LEN) { + if (cmd_strtoaddr(argv[1], assoc_req.bssid, HI_WIFI_MAC_LEN) != HISI_OK) { + return HI_ERR_FAILURE; + } + } else { + return HI_ERR_FAILURE; + } + + /* get auth_type */ + if ((integer_check(argv[2]) != HI_ERR_SUCCESS) || (atoi(argv[2]) < HI_WIFI_SECURITY_OPEN) || /* argc 2 */ + (atoi(argv[2]) == HI_WIFI_SECURITY_WPA) || (atoi(argv[2]) == HI_WIFI_SECURITY_WPA2) || /* argc 2 */ + (atoi(argv[2]) == HI_WIFI_SECURITY_WPAPSK) || (atoi(argv[2]) >= HI_WIFI_SECURITY_UNKNOWN) || /* argc 2 */ + ((atoi(argv[2]) == HI_WIFI_SECURITY_OPEN) && (argc != 3)) || /* argc 2/3/4 */ + ((atoi(argv[2]) != HI_WIFI_SECURITY_OPEN) && (argc != 4))) { /* argc 2/3/4 */ + return HI_ERR_FAILURE; + } + assoc_req.auth = (hi_wifi_auth_mode)atoi(argv[2]); /* 2 */ + + assoc_req.pairwise = HI_WIFI_PARIWISE_UNKNOWN; + + /* get key */ + if (argc == 4) { /* argc 4 */ + const hi_char *buf = argv[3]; /* argc 3 */ + if (buf == HI_NULL) { + return HI_ERR_FAILURE; + } + size_t len = strlen(argv[3]); /* 3:key */ + if ((atoi(argv[2]) == HI_WIFI_SECURITY_WEP) && (len != 9) && (len != 17) && /* argc 2, len 9/17 */ + (len != 12) && (len != 28)) { /* 12 28: password len */ + return HI_ERR_FAILURE; + } else if ((atoi(argv[2]) != HI_WIFI_SECURITY_WEP) && ((len > HI_WIFI_AP_KEY_LEN_MAX + 2) || /* argc 2 */ + (len < HI_WIFI_AP_KEY_LEN_MIN + 2))) { /* len plus 2 */ + return HI_ERR_FAILURE; + } + if ((*buf != '\"') || (*(buf + strlen(argv[3]) - 1) != '\"') || /* argc 3 */ + (memcpy_s(assoc_req.key, HI_WIFI_MAX_KEY_LEN + 1, buf + 1, strlen(argv[3]) - 2) != EOK)) { /* 3 2 */ + return HI_ERR_FAILURE; + } + } + + if (hi_wifi_sta_connect(&assoc_req) != HISI_OK) { + return HI_ERR_FAILURE; + } + + hi_at_printf("OK\r\n"); + return HI_ERR_SUCCESS; +} + +/***************************************************************************** +* Func description: station quick connect +* example: AT+FCONN="hisilicon",,6,2,"123456789" + AT+FCONN=,90:2B:D2:E4:CE:28,6,2,"123456789" +*****************************************************************************/ +hi_u32 cmd_sta_quick_connect(hi_s32 argc, const hi_char *argv[]) +{ + hi_wifi_fast_assoc_request fast_assoc_req = {0}; + hi_u32 ret; + + if ((argc < 4) || (argc > 5)) { /* argc 4 / 5 */ + return HI_ERR_FAILURE; + } + + /* get ssid */ + if (argv[0] != HI_NULL) { + ret = cmd_sta_connect_get_ssid(argv, HI_NULL, &fast_assoc_req, 1); + if (ret != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + } + + /* get bssid */ + if (argv[1] == HI_NULL) { + memset_s(fast_assoc_req.req.bssid, sizeof(fast_assoc_req.req.bssid), 0, sizeof(fast_assoc_req.req.bssid)); + } else if (strlen(argv[1]) == HI_WIFI_TXT_ADDR_LEN) { + if (cmd_strtoaddr(argv[1], fast_assoc_req.req.bssid, HI_WIFI_MAC_LEN) != HISI_OK) { + return HI_ERR_FAILURE; + } + } else { + return HI_ERR_FAILURE; + } + + /* get channel,Scope1~14 */ + if ((integer_check(argv[2]) != HI_ERR_SUCCESS) || (atoi(argv[2]) <= 0) || (atoi(argv[2]) > 14)) { /* 2 14 */ + return HI_ERR_FAILURE; + } + fast_assoc_req.channel = (hi_uchar)atoi(argv[2]); /* 2 */ + + /* get auth_type */ + if ((integer_check(argv[3]) != HI_ERR_SUCCESS) || (atoi(argv[3]) < HI_WIFI_SECURITY_OPEN) || /* argv 3 */ + (atoi(argv[3]) == HI_WIFI_SECURITY_WPA) || (atoi(argv[3]) == HI_WIFI_SECURITY_WPA2) || /* argv 3 */ + (atoi(argv[3]) == HI_WIFI_SECURITY_WPAPSK) || (atoi(argv[3]) >= HI_WIFI_SECURITY_UNKNOWN) || /* argv 3 */ + ((atoi(argv[3]) == HI_WIFI_SECURITY_OPEN) && (argc != 4)) || /* argc 3/4/5 */ + ((atoi(argv[3]) != HI_WIFI_SECURITY_OPEN) && (argc != 5))) { /* argc 3/4/5 */ + return HI_ERR_FAILURE; + } + + fast_assoc_req.req.auth = (hi_wifi_auth_mode)atoi(argv[3]); /* 3 */ + + /* get encipher mode 0,HI_WIFI_PARIWISE_UNKNOWN */ + fast_assoc_req.req.pairwise = HI_WIFI_PARIWISE_UNKNOWN; + + /* get key */ + ret = cmd_sta_connect_get_key(argc, argv, &fast_assoc_req); + if (ret != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + + if (hi_wifi_sta_fast_connect(&fast_assoc_req) != HISI_OK) { + return HI_ERR_FAILURE; + } + + hi_at_printf("OK\r\n"); + return HI_ERR_SUCCESS; +} + +/***************************************************************************** +* Func description: sta disconnect network +*****************************************************************************/ +hi_u32 cmd_sta_disconnect(hi_s32 argc, const hi_char *argv[]) +{ + hi_unref_param(argv); + hi_unref_param(argc); + + hi_s32 ret = hi_wifi_sta_disconnect(); + if (ret != HISI_OK) { + return HI_ERR_FAILURE; + } + + hi_at_printf("OK\r\n"); + return HI_ERR_SUCCESS; +} + +/***************************************************************************** +* Func description: get station connection status +*****************************************************************************/ +hi_u32 cmd_sta_status(hi_s32 argc, const hi_char *argv[]) +{ + hi_s32 ret; + hi_wifi_status wifi_status; + + hi_unref_param(argv); + hi_unref_param(argc); + + memset_s(&wifi_status, sizeof(hi_wifi_status), 0, sizeof(hi_wifi_status)); + + ret = hi_wifi_sta_get_connect_info(&wifi_status); + if (ret != HISI_OK) { + return HI_ERR_FAILURE; + } + if (wifi_status.status == HI_WIFI_CONNECTED) { + const hi_char *tmp = at_ssid_txt((unsigned char*)wifi_status.ssid, strlen(wifi_status.ssid)); + if (at_check_ccharacter(tmp) == HI_ERR_SUCCESS) { + hi_at_printf("+STASTAT:1,P\"%s\","AT_MACSTR",%d\r\n", tmp, at_mac2str(wifi_status.bssid), + wifi_status.channel); + } else { + hi_at_printf("+STASTAT:1,%s,"AT_MACSTR",%d\r\n", wifi_status.ssid, at_mac2str(wifi_status.bssid), + wifi_status.channel); + } + } else { + hi_at_printf("+STASTAT:0,0,0,0\r\n"); + } + hi_at_printf("OK\r\n"); + return HI_ERR_SUCCESS; +} + +#ifdef CONFIG_WPS_SUPPORT +/***************************************************************************** +* Func description: using wps pbc to connect network +* example: sta wps_pbc +*****************************************************************************/ +hi_u32 cmd_wpa_wps_pbc(hi_s32 argc, const hi_char *argv[]) +{ + hi_unref_param(argv); + hi_unref_param(argc); + + hi_s32 ret = hi_wifi_sta_wps_pbc(HI_NULL); + if (ret != HISI_OK) { + return HI_ERR_FAILURE; + } + + hi_at_printf("OK\r\n"); + return HI_ERR_SUCCESS; +} + +/***************************************************************************** +* Func description: get wps pin value +*****************************************************************************/ +hi_u32 cmd_wpa_wps_pin_get(hi_s32 argc, const hi_char *argv[]) +{ + hi_char pin_txt[WIFI_WPS_PIN_LEN + 1] = {0}; + hi_u32 len = WIFI_WPS_PIN_LEN + 1; + hi_s32 ret; + + hi_unref_param(argv); + hi_unref_param(argc); + + ret = hi_wifi_sta_wps_pin_get(pin_txt, len); + if (ret != HISI_OK) { + return HI_ERR_FAILURE; + } + pin_txt[WIFI_WPS_PIN_LEN] = '\0'; + + hi_at_printf("+PINSHOW:%s\r\n", pin_txt); + hi_at_printf("OK\r\n"); + return HI_ERR_SUCCESS; +} + +/***************************************************************************** +* Func description: using wps pin to connect network +* example: AT+PIN=03882368 +*****************************************************************************/ +hi_u32 cmd_wpa_wps_pin(hi_s32 argc, const hi_char *argv[]) +{ + hi_char pin[WIFI_WPS_PIN_LEN + 1] = {0}; + hi_char *ppin = pin; + + if ((argc != 1) || (at_param_null_check(argc, argv) == HI_ERR_FAILURE)) { + return HI_ERR_FAILURE; + } + + hi_u32 len = strlen(argv[0]); + if ((len != WIFI_WPS_PIN_LEN) || (memcpy_s(pin, WIFI_WPS_PIN_LEN + 1, argv[0], len) != EOK)) { + return HI_ERR_FAILURE; + } + + if (hi_wifi_sta_wps_pin(ppin, HI_NULL) != HISI_OK) { + return HI_ERR_FAILURE; + } + + hi_at_printf("OK\r\n"); + return HI_ERR_SUCCESS; +} +#endif /* LOSCFG_APP_WPS */ + +hi_u32 cmd_set_reconn(hi_s32 argc, const hi_char *argv[]) +{ + hi_s32 enable; + hi_s32 seconds = RECONN_TIMEOUT_MIN; + hi_u32 period = RECONN_PERIOD_MIN; + hi_u32 max_try_count = RECONN_COUNT_MIN; + if ((argc != 1) && (argc != 4)) { /* argc 1/4 */ + return HI_ERR_FAILURE; + } + if (argc == 1) { + if ((integer_check(argv[0]) != HI_ERR_SUCCESS) || (atoi(argv[0]) != 0)) { + return HI_ERR_FAILURE; + } + enable = 0; + } else { + for (hi_s32 i = 0; i < argc - 1; i++) { + if (integer_check(argv[i]) != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + } + enable = atoi(argv[0]); + if (enable == 0) { + return HI_ERR_FAILURE; + } + period = (hi_u32)atoi(argv[1]); /* argc 1 */ + max_try_count = (hi_u32)atoi(argv[2]); /* argc 2 */ + if (argv[3] != HI_NULL) { /* argc 3 */ + if (integer_check(argv[3]) != HI_ERR_SUCCESS) { /* argc 3 */ + return HI_ERR_FAILURE; + } + seconds = atoi(argv[3]); /* argc 3 */ + } + + if (seconds < RECONN_TIMEOUT_MIN || period < RECONN_PERIOD_MIN || period > RECONN_PERIOD_MAX || + max_try_count < RECONN_COUNT_MIN || max_try_count > RECONN_COUNT_MAX) { + return HI_ERR_FAILURE; + } + } + hi_s32 ret = hi_wifi_sta_set_reconnect_policy(enable, seconds, period, max_try_count); + if (ret != HISI_OK) { + return HI_ERR_FAILURE; + } + + hi_at_printf("OK\r\n"); + + return HI_ERR_SUCCESS; +} + +const at_cmd_func g_sta_func_tbl[] = { + {"+STOPSTA", 8, HI_NULL, HI_NULL, HI_NULL, (at_call_back_func)cmd_sta_stop}, + {"+SCAN", 5, HI_NULL, HI_NULL, HI_NULL, (at_call_back_func)cmd_wpa_scan}, + {"+SCANCHN", 8, HI_NULL, HI_NULL, (at_call_back_func)cmd_wpa_channel_scan, HI_NULL}, + {"+SCANSSID", 9, HI_NULL, HI_NULL, (at_call_back_func)cmd_wpa_ssid_scan, HI_NULL}, + {"+SCANPRSSID", 11, HI_NULL, HI_NULL, (at_call_back_func)cmd_ssid_prefix_scan, HI_NULL}, + {"+SCANRESULT", 11, HI_NULL, HI_NULL, HI_NULL, (at_call_back_func)cmd_wpa_scan_results}, + {"+CONN", 5, HI_NULL, HI_NULL, (at_call_back_func)cmd_sta_connect, HI_NULL}, + {"+FCONN", 6, HI_NULL, HI_NULL, (at_call_back_func)cmd_sta_quick_connect, HI_NULL}, + {"+DISCONN", 8, HI_NULL, HI_NULL, HI_NULL, (at_call_back_func)cmd_sta_disconnect}, + {"+STASTAT", 8, HI_NULL, HI_NULL, HI_NULL, (at_call_back_func)cmd_sta_status}, + {"+RECONN", 7, HI_NULL, HI_NULL, (at_call_back_func)cmd_set_reconn, HI_NULL}, +#ifdef CONFIG_WPS_SUPPORT + {"+PBC", 4, HI_NULL, HI_NULL, HI_NULL, (at_call_back_func)cmd_wpa_wps_pbc}, + {"+PIN", 4, HI_NULL, HI_NULL, (at_call_back_func)cmd_wpa_wps_pin, HI_NULL}, + {"+PINSHOW", 8, HI_NULL, HI_NULL, HI_NULL, (at_call_back_func)cmd_wpa_wps_pin_get}, +#endif /* LOSCFG_APP_WPS */ +#ifdef CONFIG_TEE_HUKS_DEMO_SUPPORT + {"+GCONNKEY", 9, HI_NULL, HI_NULL, HI_NULL, (at_call_back_func)cmd_generate_save_conn_key}, + {"+SCONN", 6, HI_NULL, HI_NULL, (at_call_back_func)cmd_sta_secure_connect, HI_NULL}, + {"+SRCONN", 7, HI_NULL, HI_NULL, HI_NULL, (at_call_back_func)cmd_sta_secure_re_connect}, +#endif +}; + +#define AT_STA_FUNC_NUM (sizeof(g_sta_func_tbl) / sizeof(g_sta_func_tbl[0])) + +hi_void hi_at_sta_cmd_register(hi_void) +{ + hi_at_register_cmd(g_sta_func_tbl, AT_STA_FUNC_NUM); +} + +const at_cmd_func g_sta_factory_test_func_tbl[] = { + {"+STARTSTA", 9, HI_NULL, HI_NULL, (at_call_back_func)cmd_sta_start_adv, (at_call_back_func)cmd_sta_start}, +#ifdef CONFIG_TEE_HUKS_DEMO_SUPPORT + {"+GCERTKEY", 9, HI_NULL, HI_NULL, HI_NULL, (at_call_back_func)cmd_generate_save_cert_key}, + {"+CERTENC", 8, HI_NULL, HI_NULL, HI_NULL, (at_call_back_func)cmd_encrypt_cert}, + {"+CERTDEC", 8, HI_NULL, HI_NULL, HI_NULL, (at_call_back_func)cmd_decrypt_cert}, +#endif +}; + +#define AT_STA_FACTORY_TEST_FUNC_NUM (sizeof(g_sta_factory_test_func_tbl) / sizeof(g_sta_factory_test_func_tbl[0])) + +hi_void hi_at_sta_factory_test_cmd_register(hi_void) +{ + hi_at_register_cmd(g_sta_factory_test_func_tbl, AT_STA_FACTORY_TEST_FUNC_NUM); +} + +/***************************************************************************** +* Func description: show mesh or softap connected sta information +*****************************************************************************/ +hi_u32 cmd_softap_show_sta(hi_s32 argc, const hi_char *argv[]) +{ + hi_s32 ret; + hi_u32 sta_index; + hi_u32 sta_num = WIFI_DEFAULT_MAX_NUM_STA; + hi_wifi_ap_sta_info sta_list[WIFI_DEFAULT_MAX_NUM_STA]; + hi_wifi_ap_sta_info *sta_list_node = HI_NULL; + + hi_unref_param(argc); + hi_unref_param(argv); + + ret = hi_wifi_softap_get_connected_sta(sta_list, &sta_num); + if (ret != HISI_OK) { + return HI_ERR_FAILURE; + } + + sta_list_node = sta_list; + for (sta_index = 0; sta_index < sta_num; sta_index++, sta_list_node++) { + hi_at_printf("+SHOWSTA:" AT_MACSTR, at_mac2str(sta_list_node->mac)); + hi_at_printf("\r\n"); + } + + hi_at_printf("OK\r\n"); + return HI_ERR_SUCCESS; +} + +/***************************************************************************** +* Func description: start softap +* example: AT+STARTAP="hisilicon",0,6,1,"123456789" + AT+STARTAP="hisilicon",0,6,0 +*****************************************************************************/ +hi_u32 cmd_start_softap(hi_s32 argc, const hi_char *argv[]) +{ + hi_wifi_softap_config hapd_conf = {0}; + hi_char ifname[WIFI_IFNAME_MAX_SIZE + 1] = {0}; + hi_s32 ifname_len = sizeof(ifname); + hi_s32 len; + + if (((argc != 4) && (argc != 5)) || (at_param_null_check(argc, argv) == HI_ERR_FAILURE)) { /* argc 4/5 */ + return HI_ERR_FAILURE; + } + + /* get ssid */ + if ((argv[0][0] != '\"') || (*(argv[0] + strlen(argv[0]) - 1) != '\"') || + (memcpy_s(hapd_conf.ssid, HI_WIFI_MAX_SSID_LEN + 1, argv[0] + 1, strlen(argv[0]) - 2) != EOK)) { /* 2 */ + return HI_ERR_FAILURE; + } + + /* get ssid_hidden,Scope 0~1 */ + if ((integer_check(argv[1]) != HI_ERR_SUCCESS) || (atoi(argv[1]) < 0) || (atoi(argv[1]) > 1)) { + return HI_ERR_FAILURE; + } + hapd_conf.ssid_hidden = atoi(argv[1]); + + /* get channel,Scope1~14 */ + if ((integer_check(argv[2]) != HI_ERR_SUCCESS) || (atoi(argv[2]) <= 0) || (atoi(argv[2]) > 14)) { /* argc 2 */ + return HI_ERR_FAILURE; + } + hapd_conf.channel_num = (hi_uchar)atoi(argv[2]); /* 2 */ + + if ((integer_check(argv[3]) == HI_ERR_FAILURE) || /* 3 */ + ((atoi(argv[3]) != HI_WIFI_SECURITY_OPEN) && (atoi(argv[3]) != HI_WIFI_SECURITY_WPA2PSK) && /* 3 */ + (atoi(argv[3]) != HI_WIFI_SECURITY_WPAPSK_WPA2PSK_MIX)) || /* 3 */ + ((atoi(argv[3]) == HI_WIFI_SECURITY_OPEN) && (argc != 4))) { /* argc 3/4 */ + return HI_ERR_FAILURE; + } + hapd_conf.authmode = (hi_wifi_auth_mode)atoi(argv[3]); /* 3 */ + + /* get authmode */ + if ((hapd_conf.authmode != HI_WIFI_SECURITY_OPEN)) { + if ((argc != 5) || (strlen(argv[4]) > HI_WIFI_AP_KEY_LEN_MAX + 2) || /* argc 4/5, len plus 2 */ + (strlen(argv[4]) < HI_WIFI_AP_KEY_LEN_MIN + 2)) { /* argc 4, len plus 2 */ + return HI_ERR_FAILURE; + } + const hi_char *buf = argv[4]; /* argc 4 */ + len = (int)strlen(argv[4]); /* argc 4 */ + if ((*buf != '\"') || (*(buf + len - 1) != '\"') || + (memcpy_s((hi_char*)hapd_conf.key, HI_WIFI_AP_KEY_LEN + 1, buf + 1, len - 2) != EOK)) { /* len minus 2 */ + return HI_ERR_FAILURE; + } + } + if (hi_wifi_softap_start(&hapd_conf, ifname, &ifname_len) != HISI_OK) { + return HI_ERR_FAILURE; + } + + if (hi_wifi_set_bandwidth(DEFAULT_IFNAME_AP, strlen(DEFAULT_IFNAME_AP) + 1, g_bw_setup_value) != HI_ERR_SUCCESS) { + hi_wifi_softap_stop(); + return HI_ERR_FAILURE; + } + + hi_at_printf("OK\r\n"); + return HI_ERR_SUCCESS; +} + +/***************************************************************************** +* Func description: start softap +* example: AT+SETAPADV=2,10,100,2,3600,0 +*****************************************************************************/ +hi_u32 cmd_set_softap_advance(hi_s32 argc, const hi_char *argv[]) +{ + hi_s32 ret, value, i; + + if (argc != 6) { /* The command has six fixed parameters.CNcomment:"+SETAPADV"命令固定6个命令参数 */ + return HI_ERR_FAILURE; + } + for (i = 0; i < argc; i++) { + if ((argv[i] != HI_NULL) && (integer_check(argv[i]) != HI_ERR_SUCCESS)) { + return HI_ERR_FAILURE; + } + + if (i == 0) { + value = (argv[i] != HI_NULL) ? atoi(argv[i]) : HI_WIFI_PHY_MODE_11BGN; + if ((value == HI_WIFI_PHY_MODE_11B) && (argv[1] != HI_NULL) && (strcmp(argv[1], "20"))) { /* 20:bw */ + return HI_ERR_FAILURE; + } + ret = hi_wifi_softap_set_protocol_mode((hi_wifi_protocol_mode)value); + } else if (i == 1) { + if ((argv[i] == HI_NULL) || !(strcmp(argv[i], "20"))) { /* 20M */ + g_bw_setup_value = HI_WIFI_BW_LEGACY_20M; + } else if (!(strcmp(argv[i], "10"))) { /* 10M */ + g_bw_setup_value = HI_WIFI_BW_HIEX_10M; + } else if (!(strcmp(argv[i], "5"))) { /* 5M */ + g_bw_setup_value = HI_WIFI_BW_HIEX_5M; + } else { + return HI_ERR_FAILURE; + } + ret = HISI_OK; + } else if (i == 2) { /* i is 2 */ + ret = (argv[i] != HI_NULL) ? hi_wifi_softap_set_beacon_period(atoi(argv[i])) : HISI_OK; + } else if (i == 3) { /* i is 3 */ + ret = (argv[i] != HI_NULL) ? hi_wifi_softap_set_dtim_period(atoi(argv[i])) : HISI_OK; + } else if (i == 4) { /* i is 4 */ + ret = (argv[i] != HI_NULL) ? hi_wifi_softap_set_group_rekey(atoi(argv[i])) : HISI_OK; + } else if (i == 5) { /* i is 5 */ + ret = (argv[i] != HI_NULL) ? hi_wifi_softap_set_shortgi(atoi(argv[i])) : HISI_OK; + } else { + return HI_ERR_FAILURE; + } + if (ret != HISI_OK) { + return HI_ERR_FAILURE; + } + } + + hi_at_printf("OK\r\n"); + return HI_ERR_SUCCESS; +} + +/***************************************************************************** +* Func description: stop softap +*****************************************************************************/ +hi_u32 cmd_stop_softap(hi_s32 argc, const hi_char *argv[]) +{ + hi_unref_param(argc); + hi_unref_param(argv); + + if (hi_wifi_softap_stop() != HISI_OK) { + return HI_ERR_FAILURE; + } + + hi_at_printf("OK\r\n"); + return HI_ERR_SUCCESS; +} + +/***************************************************************************** +* Func description: softap disconnect station +* example: AT+DEAUTHSTA=90:2B:D2:E4:CE:28 +*****************************************************************************/ +hi_u32 cmd_softap_deauth_sta(hi_s32 argc, const hi_char *argv[]) +{ + hi_uchar mac_addr[HI_WIFI_MAC_LEN + 1] = {0}; + hi_s32 ret; + + if ((argc != 1) || (argv[0] == HI_NULL) || (strlen(argv[0]) != HI_WIFI_TXT_ADDR_LEN)) { + return HI_ERR_FAILURE; + } + + if (cmd_strtoaddr(argv[0], mac_addr, HI_WIFI_MAC_LEN) != HISI_OK) { + return HI_ERR_FAILURE; + } + + ret = hi_wifi_softap_deauth_sta(mac_addr, HI_WIFI_MAC_LEN); + if (ret != HISI_OK) { + return HI_ERR_FAILURE; + } + + hi_at_printf("OK\r\n"); + return HI_ERR_SUCCESS; +} + +hi_u32 at_ap_scan(hi_void) +{ + hi_at_printf("ERROR:TBD\r\n"); + return HI_ERR_SUCCESS; +} + +const at_cmd_func g_at_ap_func_tbl[] = { + {"+STARTAP", 8, HI_NULL, HI_NULL, (at_call_back_func)cmd_start_softap, HI_NULL}, + {"+SETAPADV", 9, HI_NULL, HI_NULL, (at_call_back_func)cmd_set_softap_advance, HI_NULL}, + {"+STOPAP", 7, HI_NULL, HI_NULL, HI_NULL, (at_call_back_func)cmd_stop_softap}, + {"+SHOWSTA", 8, HI_NULL, HI_NULL, HI_NULL, (at_call_back_func)cmd_softap_show_sta}, + {"+DEAUTHSTA", 10, HI_NULL, HI_NULL, (at_call_back_func)cmd_softap_deauth_sta, HI_NULL}, + {"+APSCAN", 7, HI_NULL, HI_NULL, HI_NULL, (at_call_back_func)at_ap_scan}, +}; + +#define AT_AP_FUNC_NUM (sizeof(g_at_ap_func_tbl) / sizeof(g_at_ap_func_tbl[0])) + +hi_void hi_at_softap_cmd_register(void) +{ + hi_at_register_cmd(g_at_ap_func_tbl, AT_AP_FUNC_NUM); +} + +#ifdef LOSCFG_APP_MESH +hi_u32 cmd_mesh_auto_get_ssid(const hi_char *argv[], hi_mesh_autolink_config *mesh_auto_config) +{ + size_t ssid_len = 0; + errno_t rc; + + /* get ssid */ + if (argv[1][0] == 'P') { + if (strlen(argv[1]) > HI_WIFI_MAX_SSID_LEN * 4 + 3) { /* ssid length should less than 32*4+3 */ + return HI_ERR_FAILURE; + } + } else if (strlen(argv[1]) > HI_WIFI_MAX_SSID_LEN + 2) { /* ssid length should less than 32+2 */ + return HI_ERR_FAILURE; + } + + /* ssid hex to string */ + hi_char *tmp = at_parse_string(argv[1], &ssid_len); + if (tmp == HI_NULL) { + return HI_ERR_FAILURE; + } + if ((ssid_len > HI_WIFI_MAX_SSID_LEN) || (ssid_len == 0)) { + at_free(tmp); + return HI_ERR_FAILURE; + } + + rc = memcpy_s(mesh_auto_config->ssid, HI_WIFI_MAX_SSID_LEN + 1, tmp, strlen(tmp) + 1); + at_free(tmp); + if (rc != EOK) { + return HI_ERR_FAILURE; + } + + return HI_ERR_SUCCESS; +} + +/***************************************************************************** +* Func description: start mesh auto join +* example: AT+MAUTOJOIN=1,"router_mesh",0 +AT+MAUTOJOIN=1,"router_mesh",1,"123456789" +*****************************************************************************/ +hi_s32 cmd_mesh_auto_connect(hi_s32 argc, const hi_char* argv[]) +{ + hi_mesh_autolink_config mesh_auto_config = {0}; + + if ((argc < 3) || (argc > 4)) { /* argc 3/4 */ + return HI_ERR_FAILURE; + } + + /* get usr config mesh type */ + if ((integer_check(argv[0]) != HI_ERR_SUCCESS) || (atoi(argv[0]) < HI_MESH_USRCONFIG_MBR) || + (atoi(argv[0]) > HI_MESH_USRCONFIG_AUTO)) { + return HI_ERR_FAILURE; + } + mesh_auto_config.usr_cfg_role = (hi_mesh_autolink_usrcfg_node_type)atoi(argv[0]); + + /* get ssid */ + if (cmd_mesh_auto_get_ssid(argv, &mesh_auto_config) != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + + /* get auth_type */ + if ((integer_check(argv[2]) == HI_ERR_FAILURE) || /* argc 2 */ + ((atoi(argv[2]) != HI_MESH_OPEN) && (atoi(argv[2]) != HI_MESH_AUTH)) || /* argc 2 */ + ((atoi(argv[2]) == HI_MESH_OPEN) && (argc != 3))) { /* argc 2/3 */ + return HI_ERR_FAILURE; + } + mesh_auto_config.auth = (hi_mesh_autolink_auth_type)atoi(argv[2]); /* 2 */ + + /* get key */ + if (mesh_auto_config.auth == HI_MESH_AUTH) { + if ((argc != 4) || (strlen(argv[3]) > HI_WIFI_MS_KEY_LEN_MAX + 2) || /* 4,3,2 */ + (strlen(argv[3]) < HI_WIFI_MS_KEY_LEN_MIN + 2)) { /* 3,2 */ + return HI_ERR_FAILURE; + } + const hi_char *buf = argv[3]; /* 3 */ + size_t len = strlen(argv[3]); /* 3 */ + if ((*buf != '\"') || (*(buf + len - 1) != '\"') || + (memcpy_s((hi_char*)mesh_auto_config.key, HI_WIFI_MESH_KEY_LEN_MAX + 1, buf + 1, len - 2) != EOK)) { /* 2 */ + return HI_ERR_FAILURE; + } + } + + if (hi_mesh_start_autolink(&mesh_auto_config) != HISI_OK) { + return HI_ERR_FAILURE; + } + + hi_at_printf("OK\r\n"); + return HI_ERR_SUCCESS; +} + +/***************************************************************************** +* Func description: exit mesh network +* example: AT+MEXIT +* AT+MEXIT +*****************************************************************************/ +hi_s32 cmd_mesh_exit_network(hi_s32 argc, const hi_char* argv[]) +{ + hi_s32 ret; + + hi_unref_param(argv); + hi_unref_param(argc); + + ret = hi_mesh_exit_autolink(); + if (ret != HISI_OK) { + return HI_ERR_FAILURE; + } + + hi_at_printf("OK\r\n"); + return HI_ERR_SUCCESS; +} + +/***************************************************************************** +* Func description: set mesh router rssi threshold +* example: AT+MSETRSSI=-50 +*****************************************************************************/ +hi_s32 cmd_mesh_set_rssi_threshold(hi_s32 argc, const hi_char* argv[]) +{ + hi_s32 ret; + hi_s32 usr_rssi_config; + + if ((argc != 1) || (argv[0] == HI_NULL)) { + return HI_ERR_FAILURE; + } + + usr_rssi_config = atoi(argv[0]); + if ((usr_rssi_config < -127) || (usr_rssi_config > 10)) { /* range -127,10 */ + return HI_ERR_FAILURE; + } + ret = hi_mesh_autolink_set_router_rssi_threshold(usr_rssi_config); + if (ret != HISI_OK) { + return HI_ERR_FAILURE; + } + + hi_at_printf("OK\r\n"); + return HI_ERR_SUCCESS; +} + +/***************************************************************************** +* Func description: set mesh autonetwork bw value +* example: AT+MSETBW=5 +*****************************************************************************/ +hi_s32 cmd_mesh_set_autonetwork_bw(hi_s32 argc, const hi_char* argv[]) +{ + hi_wifi_bw bw_value; + if (argc != 1) { /* "+MSETBW"命令固定1个命令参数 */ + return HI_ERR_FAILURE; + } + + if ((argv[0] != HI_NULL) && (integer_check(argv[0]) != HI_ERR_SUCCESS)) { + return HI_ERR_FAILURE; + } + + if ((argv[0] != HI_NULL) && (atoi(argv[0]) == 5)) { /* bw 5 */ + bw_value = HI_WIFI_BW_HIEX_5M; + } else if ((argv[0] != HI_NULL) && (atoi(argv[0]) == 10)) { /* bw 10 */ + bw_value = HI_WIFI_BW_HIEX_10M; + } else { + bw_value = HI_WIFI_BW_LEGACY_20M; + } + + hi_mesh_autolink_set_bw(bw_value); + hi_at_printf("OK\r\n"); + return HI_ERR_SUCCESS; +} + +const at_cmd_func g_at_mesh_func_tbl[] = { + {"+MAUTOJOIN", 10, HI_NULL, HI_NULL, (at_call_back_func)cmd_mesh_auto_connect, HI_NULL}, + {"+MEXIT", 6, HI_NULL, HI_NULL, HI_NULL, (at_call_back_func)cmd_mesh_exit_network}, + {"+MSETRSSI", 9, HI_NULL, HI_NULL, (at_call_back_func)cmd_mesh_set_rssi_threshold, HI_NULL}, + {"+MSETBW", 7, HI_NULL, HI_NULL, (at_call_back_func)cmd_mesh_set_autonetwork_bw, HI_NULL}, +}; + +#define AT_MESH_FUNC_NUM (sizeof(g_at_mesh_func_tbl) / sizeof(g_at_mesh_func_tbl[0])) + +hi_void hi_at_mesh_cmd_register(void) +{ + hi_at_register_cmd(g_at_mesh_func_tbl, AT_MESH_FUNC_NUM); +} +#endif +#ifdef __cplusplus +#if __cplusplus + } +#endif +#endif diff --git a/sdk_liteos/components/at/src/at_wifi.h b/sdk_liteos/components/at/src/at_wifi.h new file mode 100644 index 0000000000000000000000000000000000000000..af26c6c73aa6c73f4ef6b1978bcf0f0c1018fc3f --- /dev/null +++ b/sdk_liteos/components/at/src/at_wifi.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __AT_WIFI_H__ +#define __AT_WIFI_H__ + +#include "hi_types.h" +#include "hi_wifi_api.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif +#define RECONN_PERIOD_MAX 65535 +#define RECONN_PERIOD_MIN 1 +#define RECONN_COUNT_MAX 65535 +#define RECONN_COUNT_MIN 1 +#define RECONN_TIMEOUT_MIN 2 +#define HI_WIFI_AP_KEY_LEN_MAX 64 +#define HI_WIFI_AP_KEY_LEN_MIN 8 +#define HI_WIFI_MS_KEY_LEN_MAX 63 +#define HI_WIFI_MS_KEY_LEN_MIN 8 + +void hi_at_sta_cmd_register(void); +hi_void hi_at_sta_factory_test_cmd_register(hi_void); +void hi_at_softap_cmd_register(void); +void hi_at_mesh_cmd_register(void); + +#ifdef __cplusplus +#if __cplusplus + } +#endif +#endif + +#endif /* end of app_sta.h */ diff --git a/sdk_liteos/components/at/src/hi_at.c b/sdk_liteos/components/at/src/hi_at.c new file mode 100644 index 0000000000000000000000000000000000000000..654745c9cf53cfea615c2b53b14af31c0dcce0c1 --- /dev/null +++ b/sdk_liteos/components/at/src/hi_at.c @@ -0,0 +1,725 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "hi_at.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "at_hipriv.h" +#include "at_general.h" +#include "at_wifi.h" +#include "at_io.h" +#include "at_lowpower.h" +#include "at_printf.h" +#include "hi_uart.h" +#include "hi_task.h" +#include "serial_dw.h" +#include "securec.h" +#include "unistd.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif + +#define CMD_MAX_LEN 256 +#define AT_DEFAULT_UART_TASK_SIZE 0x600 +#define AT_DEFAULT_PROC_TASK_SIZE 0xC00 /* 0x800:softap start would fail. */ +#define AT_UART_TASK_PRIO 9 +#define AT_PROC_TASK_PRIO 10 +#define AT_CMD_HEADER "AT" +#define AT_UART_SLEEP 1000 +#define AT_DATA_MAX_LEN 1024 + +#define RECV_DATA_NORMAL_CHAR 0 +#define RECV_DATA_END_CHAR 1 +#define RECV_DATA_END_CHAR_REPEAT 2 + +#define STAT_NOMAL_KEY 0 +#define STAT_ESC_KEY 1 +#define STAT_MULTI_KEY 2 + +/* ATbusy20ϵͳλ */ +/* If the AT returns the busy message for more than 20 times, system soft reboot. */ +#define SOFT_REBOOT_MAX_BUSY_CNT 20 + +hi_u32 g_at_event = 0; +hi_uart_idx g_at_uart_port = HI_UART_IDX_1; +const hi_uart_attribute g_at_uart_cfg = {115200, 8, 1, 0, 0}; +static hi_char g_at_buf[CMD_MAX_LEN]; +hi_char *g_at_data = HI_NULL; + +hi_at_input_func g_at_input_func = HI_NULL; +static hi_at_output_func g_at_output_func = HI_NULL; + +hi_u16 g_at_uart_task_size = AT_DEFAULT_UART_TASK_SIZE; +hi_u16 g_at_proc_task_size = AT_DEFAULT_PROC_TASK_SIZE; + +hi_bool g_at_init = HI_FALSE; +/* ATbusy */ +/* Busy message count */ +hi_u8 g_busy_count = 0; + +hi_at_output_func hi_at_get_register_output_func(hi_void) +{ + return g_at_output_func; +} + +hi_s32 at_monitor_input_func(hi_u8 *data, hi_u32 data_len) +{ + (hi_void)data; + (hi_void)data_len; + + return 0; +} + +hi_s32 at_monitor_output_func(const hi_u8 *data, hi_u32 data_len) +{ + (hi_void)data; + (hi_void)data_len; + + return 0; +} + +hi_u32 hi_at_register_input_func(hi_at_input_func at_input_func) +{ + hi_u32 ret = HI_ERR_SUCCESS; + + hi_task_lock(); + if (at_input_func != HI_NULL) { + hi_bool last_uart_input = HI_FALSE; + if (g_at_input_func == HI_NULL && g_at_uart_port != 0xFF) { + last_uart_input = HI_TRUE; + } + + g_at_input_func = at_input_func; + + if (last_uart_input == HI_TRUE) { + ret = hi_uart_quit_read(g_at_uart_port); + ret |= hi_uart_deinit(g_at_uart_port); + } + } else { + if (g_at_uart_port == 0xFF) { + g_at_input_func = at_monitor_input_func; + } else { + g_at_input_func = HI_NULL; + ret = hi_uart_deinit(g_at_uart_port); + ret |= hi_uart_init(g_at_uart_port, &g_at_uart_cfg, HI_NULL); + } + } + hi_task_unlock(); + + return ret; +} + +hi_void hi_at_register_output_func(hi_at_output_func at_output_func) +{ + hi_task_lock(); + if (at_output_func != HI_NULL) { + g_at_output_func = at_output_func; + } else { + if (g_at_uart_port == 0xFF) { + g_at_output_func = at_monitor_output_func; + } else { + g_at_output_func = HI_NULL; + } + } + hi_task_unlock(); + + return; +} + +hi_char* at_get_buf(hi_void) +{ + hi_char *buf = NULL; + hi_u32 buf_len; + + if (g_at_ctrl.at_state == AT_CMD_PROCESS) { + buf_len = strlen(g_at_buf) + 1; + buf = hi_malloc(HI_MOD_ID_APP_AT, buf_len); + if (buf != NULL) { + memset_s(buf, buf_len, 0, buf_len); + if (memcpy_s(buf, buf_len, g_at_buf, strlen(g_at_buf)) != EOK) { + hi_at_printf("buf copy fail in %s[%d]", __FUNCTION__, __LINE__); + hi_free(HI_MOD_ID_APP_AT, buf); + buf = NULL; + } + } + } else if (g_at_ctrl.at_state == AT_DATA_SENDING) { + buf_len = g_at_ctrl.send_len + 1; + buf = hi_malloc(HI_MOD_ID_APP_AT, buf_len); + if (buf != NULL) { + memset_s(buf, buf_len, 0, buf_len); + if (memcpy_s(buf, buf_len, g_at_data, g_at_ctrl.send_len) != EOK) { + hi_at_printf("buf copy fail in %s[%d]", __FUNCTION__, __LINE__); + hi_free(HI_MOD_ID_APP_AT, buf); + buf = NULL; + } + } + } + hi_event_send(g_at_event, 0x1000); + return buf; +} + +static hi_void at_notify(hi_void) +{ + hi_u32 event_bit = 0; + hi_u32 ret; + hi_watchdog_feed(); + hi_event_send(g_at_event, 0x111); + ret = hi_event_wait(g_at_event, 0x1000, &event_bit, HI_SYS_WAIT_FOREVER, + HI_EVENT_WAITMODE_OR | HI_EVENT_WAITMODE_CLR); + if (ret == HI_ERR_EVENT_WAIT_TIME_OUT) { + hi_at_printf("wait event timeout"); + } +} + +hi_void at_put_c(hi_char ch) +{ + if (g_at_output_func == HI_NULL) { + (hi_void)serial_putc_at(ch); + } else { + g_at_output_func((const hi_u8*)&ch, 1); + } +} + +hi_u32 at_key_filter(hi_char ch, hi_u32 *index, hi_s32 *key_value) +{ + if (ch == '\b') { /* backspace */ + if (((*index) > 0) && ((*index) < (CMD_MAX_LEN - 1))) { + g_at_buf[(*index) - 1] = '\0'; + (*index)--; + at_put_c('\b'); + at_put_c(' '); + at_put_c('\b'); + } + return HI_ERR_FAILURE; + } else if (ch == 0x1b) { + *key_value = STAT_ESC_KEY; + return HI_ERR_FAILURE; + } else if (ch == 0x5b) { + if (*key_value == STAT_ESC_KEY) { + *key_value = STAT_MULTI_KEY; + return HI_ERR_FAILURE; + } + } else if (ch == 0x41) { /* up */ + if (*key_value == STAT_MULTI_KEY) { + *key_value = STAT_NOMAL_KEY; + return HI_ERR_FAILURE; + } + } else if (ch == 0x42) { /* down */ + if (*key_value == STAT_MULTI_KEY) { + *key_value = STAT_NOMAL_KEY; + return HI_ERR_FAILURE; + } + } else if ((ch == 0x43) || (ch == 0x44)) { /* right */ + if (*key_value == STAT_MULTI_KEY) { + *key_value = STAT_NOMAL_KEY; + return HI_ERR_FAILURE; + } + } + + return HI_ERR_SUCCESS; +} + + +hi_void at_cmd_print_back(hi_u32 i, hi_char ch) +{ + if (i < (CMD_MAX_LEN - 1)) { + g_at_buf[i] = ch; + } else { + g_at_buf[CMD_MAX_LEN - 1] = '\0'; + } + + at_put_c(ch); +} + +hi_void at_cmd_line_parse(hi_char c) +{ + hi_char ch = c; + static hi_u32 i = 0; + static hi_s32 key_value = 0; + static hi_u32 enter_flag = 0; + + if ((i == 0) && (ch != '\n')) { + (hi_void)memset_s(g_at_buf, CMD_MAX_LEN, 0, CMD_MAX_LEN); + } + + if (ch == '\n') { + if (i == 0) { + hi_at_printf("\r\nERROR\r\n"); + g_at_ctrl.at_state = AT_IDLE; + return; + } + + if (enter_flag == (i - 1)) { + i = 0; + g_at_ctrl.at_state = AT_CMD_PROCESS; + at_notify(); + } + return; + } + + enter_flag = 0; + + if (ch == '\r') { + if (i == 0) { + hi_at_printf("\r\nERROR\r\n"); + g_at_ctrl.at_state = AT_IDLE; + return; + } + if (i < (CMD_MAX_LEN - 1)) { + g_at_buf[i] = '\0'; + } + enter_flag = i; + i++; + return; + } + + if (at_key_filter(ch, &i, &key_value) != HI_ERR_SUCCESS) { + return; + } + + if (ch != '\n') { + at_cmd_print_back(i, ch); + i++; + } + + key_value = STAT_NOMAL_KEY; +} + +hi_void at_get_send_data(hi_char c) +{ + static hi_u16 i = 0; + + g_at_data[i] = c; + if ((g_at_ctrl.is_recv_end_char_flag == RECV_DATA_END_CHAR_REPEAT) && (c == '0')) { + g_at_data[i - 2] = g_at_data[i - 1]; /* 2:delete '\' */ + g_at_data[i - 1] = g_at_data[i]; + i -= 1; + } + if ((i >= (g_at_ctrl.send_len - 1)) || (i >= (AT_DATA_MAX_LEN - 1)) || + ((g_at_ctrl.is_recv_end_char_flag == RECV_DATA_END_CHAR) && (c == '0'))) { + g_at_ctrl.at_state = AT_DATA_SENDING; + g_at_ctrl.is_first_recv_data = HI_TRUE; + g_at_ctrl.send_len = i + 1; + if ((g_at_ctrl.is_recv_end_char_flag == RECV_DATA_END_CHAR) && c == '0') { + g_at_ctrl.is_recv_end_char_flag = RECV_DATA_NORMAL_CHAR; + g_at_ctrl.send_len = i - 1; + } + + i = 0; + at_notify(); + hi_free(HI_MOD_ID_APP_AT, g_at_data); + g_at_data = HI_NULL; + } else { + if (c == '\\') { + if (g_at_ctrl.is_recv_end_char_flag == RECV_DATA_NORMAL_CHAR) { + g_at_ctrl.is_recv_end_char_flag = RECV_DATA_END_CHAR; + } else if (g_at_ctrl.is_recv_end_char_flag == RECV_DATA_END_CHAR) { + g_at_ctrl.is_recv_end_char_flag = RECV_DATA_END_CHAR_REPEAT; + } + } else { + g_at_ctrl.is_recv_end_char_flag = RECV_DATA_NORMAL_CHAR; + } + i++; + } +} + +hi_u32 at_data_recving(hi_void) +{ + if (g_at_ctrl.is_first_recv_data) { + g_at_data = hi_malloc(HI_MOD_ID_APP_AT, AT_DATA_MAX_LEN); + if (g_at_data == HI_NULL) { + printf("Malloc fail!\r\n"); + return HI_ERR_FAILURE; + } + memset_s(g_at_data, AT_DATA_MAX_LEN, 0, AT_DATA_MAX_LEN); + g_at_ctrl.is_first_recv_data = HI_FALSE; + } + return HI_ERR_SUCCESS; +} + +hi_u32 g_at_uart_timer_handle; +volatile hi_bool g_at_have_uart_data; +hi_bool g_at_check_empty = HI_TRUE; + +#define AT_WAIT_TIME 10000 /* wait 10 seconds */ + +static hi_void timer_handle(hi_u32 data) +{ + hi_unref_param(data); + g_at_have_uart_data = HI_FALSE; +} + +hi_void hi_at_set_check_uart_busy(hi_bool enable) +{ + g_at_check_empty = enable; +} + +BSP_RAM_TEXT_SECTION hi_u32 lp_at_uart_vote(hi_void) +{ + hi_bool val; + + if (g_at_check_empty) { + if (g_at_have_uart_data) { + return HI_NO_SLEEP; + } + hi_u32 ret = hi_uart_is_busy(g_at_uart_port, &val); + if ((ret == HI_ERR_SUCCESS) && (val == HI_TRUE)) { + return HI_NO_SLEEP; + } + val = HI_FALSE; + ret = hi_uart_is_buf_empty(g_at_uart_port, &val); + if (ret == HI_ERR_SUCCESS && val == HI_FALSE) { + return HI_NO_SLEEP; + } + } + return HI_DEEP_SLEEP; +} + +hi_void at_parse_uart_char(hi_char ch) +{ + switch (g_at_ctrl.at_state) { + case AT_IDLE: + g_busy_count = 0; + at_cmd_line_parse(ch); + break; + case AT_CMD_PROCESS: + hi_cpup_load_check_proc(hi_task_get_current_id(), LOAD_SLEEP_TIME_DEFAULT); + + if (ch == '\n') { + if (g_busy_count >= SOFT_REBOOT_MAX_BUSY_CNT) { + g_busy_count = 0; + hi_soft_reboot(HI_SYS_REBOOT_CAUSE_AT_BUSY); + } + hi_at_printf("busy!\r\n"); + g_busy_count++; + } + break; + case AT_DATA_RECVING: + g_busy_count = 0; + if (at_data_recving() != HI_ERR_SUCCESS) { + break; + } + at_get_send_data(ch); + break; + case AT_DATA_SENDING: + hi_cpup_load_check_proc(hi_task_get_current_id(), LOAD_SLEEP_TIME_DEFAULT); + if (g_at_ctrl.is_first_over_data) { + g_at_ctrl.is_first_over_data = HI_FALSE; + hi_at_printf("busy!\r\n"); + } + break; + case AT_TRANSPARENT: + hi_at_printf("==TBD==\r\n"); + break; + default: + break; + } +} + +hi_void *at_uart_task_body(hi_void* param) +{ + hi_unref_param(param); + hi_char ch; + hi_s32 n; + for (;;) { + if (g_at_input_func == NULL) { + n = hi_uart_read(g_at_uart_port, (hi_u8 *)&ch, 1); + } else { + n = g_at_input_func((UINT8 *)&ch, 1); + } + if (n != 1) { + (hi_void)hi_sleep(AT_UART_SLEEP); + continue; + } + if ((hi_lpc_get_type() != HI_NO_SLEEP) && (g_at_check_empty == HI_TRUE)) { + g_at_have_uart_data = HI_TRUE; + hi_timer_start(g_at_uart_timer_handle, HI_TIMER_TYPE_ONCE, AT_WAIT_TIME, timer_handle, 0); + } + + at_parse_uart_char(ch); + } +} + +hi_void at_cmd_execute(hi_char *buf) +{ + hi_u32 ret; + if (memcmp(buf, AT_CMD_HEADER, strlen(AT_CMD_HEADER)) == EOK) { + hi_char *at_buf = buf + strlen(AT_CMD_HEADER); + + ret = at_cmd_process(at_buf); + if ((ret != HI_ERR_SUCCESS) && (ret != HI_ERR_RECVING)) { + g_at_ctrl.at_state = AT_IDLE; + } + } else { + AT_ENTER; + AT_RESPONSE_ERROR; + g_at_ctrl.at_state = AT_IDLE; + } +} + +hi_void *at_proc_task_body(hi_void* param) +{ + hi_unref_param(param); + hi_u32 ret; + hi_u32 event_bit; + hi_char *buf = NULL; + for (;;) { + if (g_at_ctrl.at_state != AT_DATA_RECVING) { + hi_at_printf("\r\n"); + } + event_bit = 0; + ret = hi_event_wait(g_at_event, 0xFFF, &event_bit, HI_SYS_WAIT_FOREVER, + HI_EVENT_WAITMODE_OR | HI_EVENT_WAITMODE_CLR); + if (ret == HI_ERR_EVENT_WAIT_TIME_OUT) { + hi_at_printf("get event timeout\r\n"); + continue; + } + if (event_bit == 0x111) { + buf = at_get_buf(); + if (buf == NULL) { + g_at_ctrl.at_state = AT_IDLE; + continue; + } + if (g_at_ctrl.at_state == AT_CMD_PROCESS) { + at_cmd_execute(buf); + } else if (g_at_ctrl.at_state == AT_DATA_SENDING) { +#ifndef CONFIG_FACTORY_TEST_MODE + at_send_serial_data(buf); + g_at_ctrl.at_state = AT_IDLE; + g_at_ctrl.is_first_over_data = HI_TRUE; +#endif + } + hi_free(HI_MOD_ID_APP_AT, buf); + } + } +} + +hi_u32 at_uart_init(hi_void) +{ + hi_u32 ret; +#ifndef CONFIG_QUICK_SEND_MODE + hi_u8 uart_port = 0; + ret = sal_uart_port_allocation(UART_FUNC_AT, &uart_port); + if (ret != HI_ERR_SUCCESS) { + hi_at_printf("Get at uart port fail, use default port.\r\n"); + } + + g_at_uart_port = uart_port; +#endif + + if (g_at_uart_port == 0xFF) { + if (g_at_input_func == HI_NULL || g_at_output_func == HI_NULL) { + g_at_input_func = at_monitor_input_func; + g_at_output_func = at_monitor_output_func; + } + return HI_ERR_SUCCESS; + } + + (hi_void)hi_uart_deinit(g_at_uart_port); + ret = hi_uart_init(g_at_uart_port, &g_at_uart_cfg, HI_NULL); + if (ret != HI_ERR_SUCCESS) { + hi_at_printf("open uart%d failed.\r\n", (hi_u32)g_at_uart_port); + return HI_ERR_FAILURE; + } + if (g_at_uart_port == HI_UART_IDX_0) { + g_at_uart_baseaddr = HI_UART0_REG_BASE; + } else if (g_at_uart_port == HI_UART_IDX_1) { + g_at_uart_baseaddr = HI_UART1_REG_BASE; + } else if (g_at_uart_port == HI_UART_IDX_2) { + g_at_uart_baseaddr = HI_UART2_REG_BASE; + } + return HI_ERR_SUCCESS; +} + +static hi_u32 check_name_and_callback(const at_cmd_func_list *ctx, hi_u8 tbl_index, HI_CONST at_cmd_func *cmd_tbl, + hi_u16 cmd_num) +{ + hi_u32 ret = HI_ERR_SUCCESS; + hi_u16 i; + hi_u16 j; + + for (i = 0; i < ctx->at_cmd_num[tbl_index]; i++) { + HI_CONST at_cmd_func *cmd_func = (at_cmd_func *)((ctx->at_cmd_list[tbl_index] + i)); + + for (j = 0; j < cmd_num; j++) { + if (((cmd_func->at_cmd_len == cmd_tbl[j].at_cmd_len) && + (strcmp(cmd_func->at_cmd_name, cmd_tbl[j].at_cmd_name) == 0)) || + ((cmd_tbl[j].at_test_cmd != HI_NULL) && (cmd_func->at_test_cmd == cmd_tbl[j].at_test_cmd)) || + ((cmd_tbl[j].at_query_cmd != HI_NULL) && (cmd_func->at_query_cmd == cmd_tbl[j].at_query_cmd)) || + ((cmd_tbl[j].at_setup_cmd != HI_NULL) && (cmd_func->at_setup_cmd == cmd_tbl[j].at_setup_cmd)) || + ((cmd_tbl[j].at_exe_cmd != HI_NULL) && (cmd_func->at_exe_cmd == cmd_tbl[j].at_exe_cmd))) { + return HI_ERR_AT_NAME_OR_FUNC_REPEAT_REGISTERED; + } + } + } + + return ret; +} + +static hi_u32 check_cmd_tbl(HI_CONST at_cmd_func *cmd_tbl, hi_u16 cmd_num) +{ + hi_u16 i; + hi_u16 j; + + for (i = 0; i < cmd_num; i++) { + if (cmd_tbl[i].at_cmd_len != (hi_s8)strlen(cmd_tbl[i].at_cmd_name)) { + return HI_ERR_AT_INVALID_PARAMETER; + } + + for (j = 0; j < cmd_num; j++) { + if (i == j) { + continue; + } + + if (((cmd_tbl[j].at_cmd_len == cmd_tbl[i].at_cmd_len) && + (strcmp(cmd_tbl[j].at_cmd_name, cmd_tbl[i].at_cmd_name) == 0)) || + ((cmd_tbl[j].at_test_cmd != HI_NULL) && (cmd_tbl[j].at_test_cmd == cmd_tbl[i].at_test_cmd)) || + ((cmd_tbl[j].at_query_cmd != HI_NULL) && (cmd_tbl[j].at_query_cmd == cmd_tbl[i].at_query_cmd)) || + ((cmd_tbl[j].at_setup_cmd != HI_NULL) && (cmd_tbl[j].at_setup_cmd == cmd_tbl[i].at_setup_cmd)) || + ((cmd_tbl[j].at_exe_cmd != HI_NULL) && (cmd_tbl[j].at_exe_cmd == cmd_tbl[i].at_exe_cmd))) { + return HI_ERR_AT_NAME_OR_FUNC_REPEAT_REGISTERED; + } + } + } + + return HI_ERR_SUCCESS; +} + +hi_u32 hi_at_register_cmd(HI_CONST at_cmd_func *cmd_tbl, hi_u16 cmd_num) +{ + hi_u32 ret = HI_ERR_FAILURE; + hi_u8 i; + + if (cmd_tbl == HI_NULL || cmd_num == 0) { + return HI_ERR_FAILURE; + } + + ret = check_cmd_tbl(cmd_tbl, cmd_num); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + at_cmd_func_list *cmd_list = at_get_list(); + for (i = 0; i < AT_CMD_LIST_NUM; i++) { + if ((cmd_list->at_cmd_list[i] == HI_NULL) || (cmd_list->at_cmd_num[i] == 0)) { + cmd_list->at_cmd_list[i] = cmd_tbl; + cmd_list->at_cmd_num[i] = cmd_num; + ret = HI_ERR_SUCCESS; + break; + } + + ret = check_name_and_callback(cmd_list, i, cmd_tbl, cmd_num); + if (ret != HI_ERR_SUCCESS) { + break; + } + } + + return ret; +} + +hi_void hi_at_sys_cmd_register(hi_void) +{ + hi_at_general_cmd_register(); +#ifndef CONFIG_FACTORY_TEST_MODE + hi_at_sta_cmd_register(); + hi_at_softap_cmd_register(); +#endif + hi_at_hipriv_cmd_register(); +#ifndef CONFIG_FACTORY_TEST_MODE +#ifdef LOSCFG_APP_MESH + hi_at_mesh_cmd_register(); +#endif + hi_at_lowpower_cmd_register(); +#endif + hi_at_general_factory_test_cmd_register(); + hi_at_sta_factory_test_cmd_register(); + hi_at_hipriv_factory_test_cmd_register(); + hi_at_io_cmd_register(); +} + +hi_u32 hi_at_init(hi_void) +{ + hi_u32 ret; + hi_u32 at_uart_task, at_proc_task; + + if (g_at_init == HI_TRUE) { + return HI_ERR_SUCCESS; + } + + ret = at_uart_init(); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + hi_event_create(&g_at_event); + + hi_task_attr attr = {0}; + + attr.stack_size = g_at_proc_task_size; + attr.task_prio = AT_PROC_TASK_PRIO; + attr.task_name = (hi_char*)"at_proc"; + ret = hi_task_create(&at_proc_task, &attr, at_proc_task_body, 0); + if (ret != HI_ERR_SUCCESS) { + hi_at_printf("AT_PROC_TSK init fail\r\n"); + return ret; + } + + attr.stack_size = g_at_uart_task_size; + attr.task_prio = AT_UART_TASK_PRIO; + attr.task_name = (hi_char*)"at_uart"; + ret = hi_task_create(&at_uart_task, &attr, at_uart_task_body, 0); + if (ret != HI_ERR_SUCCESS) { + hi_at_printf("AT_UART_TSK init fail\r\n"); + return ret; + } + hi_timer_create(&g_at_uart_timer_handle); + hi_lpc_register_check_handler((hi_u32_void_callback) lp_at_uart_vote); + + g_at_init = HI_TRUE; + + return HI_ERR_SUCCESS; +} + +hi_void hi_at_set_task_size(hi_u16 uart_task_size, hi_u16 process_task_size) +{ + if (uart_task_size < AT_DEFAULT_UART_TASK_SIZE) { + g_at_uart_task_size = AT_DEFAULT_UART_TASK_SIZE; + } else { + g_at_uart_task_size = uart_task_size; + } + + if (process_task_size < AT_DEFAULT_PROC_TASK_SIZE) { + g_at_proc_task_size = AT_DEFAULT_PROC_TASK_SIZE; + } else { + g_at_proc_task_size = process_task_size; + } +} + +#ifdef __cplusplus +#if __cplusplus + } +#endif +#endif diff --git a/sdk_liteos/components/hilink/Makefile b/sdk_liteos/components/hilink/Makefile new file mode 100755 index 0000000000000000000000000000000000000000..e8dffa9b51c1d121072661effec703d019677df4 --- /dev/null +++ b/sdk_liteos/components/hilink/Makefile @@ -0,0 +1,36 @@ +include $(MAIN_TOPDIR)/build/make_scripts/config.mk +include $(MAIN_TOPDIR)/$(MODULE_DIR)/module_config.mk +-include $(MAIN_TOPDIR)/$(MODULE_DIR)/srcs.mk + +OBJDIR = $(MAIN_TOPDIR)/$(OBJ_PATH)/$(MODULE_DIR) + +ID_CFG_FILE = $(MAIN_TOPDIR)/$(MODULE_DIR)/file_id.cfg + +LIB_NAME = lib$(LIB).a +SRCS = $($(LIB)_srcs) +LIBOUT = $(MAIN_TOPDIR)/$(LIB_PATH)/$(MODULE_DIR)/$(LIB_NAME) + +ifdef SRC_FILES +OBJ_SRCS := $(filter %.c, $(SRC_FILES)) +ASM_SRCS := $(filter %.S, $(SRC_FILES)) +else +OBJ_SRCS := $(foreach dir, $(SRCS), $(wildcard $(dir)/*.c)) +ASM_SRCS := $(foreach dir, $(SRCS), $(wildcard $(dir)/*.S )) +endif + +OBJ_SRCS := $(filter-out %/ethernetif.c, $(OBJ_SRCS)) +OBJS = $(patsubst %.c, $(OBJDIR)/%.o, $(OBJ_SRCS)) +ASM_OBJS = $(patsubst %.S, $(OBJDIR)/%.o, $(ASM_SRCS)) + +all: $(LIBOUT) +include $(MAIN_TOPDIR)/build/make_scripts/lib.mk + +clean: + $(Q)$(foreach x, $(OBJS) $(ASM_OBJS) $(LIBOUT), \ + if [ -d $(dir $x) ]; \ + then $(RM) $(dir $x); \ + echo clean dir $(dir $x) success; \ + fi;) + +.PHONY: all clean + diff --git a/sdk_liteos/components/hilink/SConscript b/sdk_liteos/components/hilink/SConscript new file mode 100755 index 0000000000000000000000000000000000000000..3bd647a070602733ccc9ad6da10f099de97bc4fe --- /dev/null +++ b/sdk_liteos/components/hilink/SConscript @@ -0,0 +1,27 @@ +#!/usr/bin/env python3 +# coding=utf-8 + +import os +from scripts import common_env +Import('env') +Import('env_cfg') +Import('module') + +module_path = env_cfg.get_module_dir(module) +obj_path = env_cfg.obj_path +module_libs = env_cfg.get_module_libs(module) +libs = [] + +env = env.Clone() +env_cfg.append_environs(env, module) +common_env.print_log_env(env, env_cfg.get_module_dir(module)) + +for lib in module_libs: + print('lib_name:', lib) + src_path = module_libs[lib] + objs = [] + for src in src_path: + objs += env.Object(Glob('*.c')) + objs.sort() + libs += env.Library(lib, objs) +Return('libs') diff --git a/sdk_liteos/components/hilink/module_config.mk b/sdk_liteos/components/hilink/module_config.mk new file mode 100755 index 0000000000000000000000000000000000000000..b53dc6141d8678b1b71a5285aa43f92fdab9df11 --- /dev/null +++ b/sdk_liteos/components/hilink/module_config.mk @@ -0,0 +1,2 @@ +hilink_srcs := . +CCFLAGS += -I$(MAIN_TOPDIR)/components/hilink/include diff --git a/sdk_liteos/components/iperf2/include/iperf.h b/sdk_liteos/components/iperf2/include/iperf.h new file mode 100644 index 0000000000000000000000000000000000000000..2dd8060864a055f5df93cb8e0f758784360e256c --- /dev/null +++ b/sdk_liteos/components/iperf2/include/iperf.h @@ -0,0 +1,45 @@ +/* ---------------------------------------------------------------------------- + * Copyright (c) Huawei Technologies Co., Ltd. 2020-2020. All rights reserved. + * Description: implementation for iperf2. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * --------------------------------------------------------------------------- */ + +#ifndef __IPERF_H__ +#define __IPERF_H__ + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif + +uint32_t cmd_iperf(int32_t argc, const char **argv); + +#ifdef __cplusplus +#if __cplusplus + } +#endif +#endif + +#endif /* __IPERF_H__ */ diff --git a/sdk_liteos/components/wifi/include/hi_wifi_driver_wpa_if.h b/sdk_liteos/components/wifi/include/hi_wifi_driver_wpa_if.h new file mode 100644 index 0000000000000000000000000000000000000000..dc810d24a0c1f6c74ab12d7b1f5eeddd06de330e --- /dev/null +++ b/sdk_liteos/components/wifi/include/hi_wifi_driver_wpa_if.h @@ -0,0 +1,607 @@ +/** + * @file hi_wifi_driver_wpa_if.h + * + * + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Description: header file for wifi api.CNcomment:描述:WiFi api wpa接口头文件CNend\n + */ + +/** + * @defgroup hi_wifi WiFi API + */ +/** + * @defgroup hi_wifi_driver_wpa Basic Settings + * @ingroup hi_wifi + */ + +#ifndef __DRIVER_HISI_COMMON_H__ +#define __DRIVER_HISI_COMMON_H__ + +#include "hi_types.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif + +#ifndef ETH_ADDR_LEN +#define ETH_ADDR_LEN 6 +#endif + +#define HISI_SUCC 0 +#define HISI_EFAIL 1 +#define HISI_EINVAL 22 + +#ifndef MAX_SSID_LEN +#define MAX_SSID_LEN 32 +#endif + +#ifndef HISI_MAX_NR_CIPHER_SUITES +#define HISI_MAX_NR_CIPHER_SUITES 5 +#endif + +#ifndef HISI_WPAS_MAX_SCAN_SSIDS +#define HISI_WPAS_MAX_SCAN_SSIDS 2 +#endif + +#ifndef HISI_PTR_NULL +#define HISI_PTR_NULL NULL +#endif + +#ifndef HISI_MAX_NR_AKM_SUITES +#define HISI_MAX_NR_AKM_SUITES 2 +#endif + + +#ifndef NOTIFY_DONE +#define NOTIFY_DONE 0x0000 +#endif +#ifndef NETDEV_UP +#define NETDEV_UP 0x0001 +#endif +#ifndef SCAN_AP_LIMIT +#define SCAN_AP_LIMIT 64 +#endif +#ifndef NETDEV_DOWN +#define NETDEV_DOWN 0x0002 +#endif + +#ifdef _PRE_WLAN_FEATURE_REKEY_OFFLOAD +#define HISI_REKEY_OFFLOAD_KCK_LEN 16 +#define HISI_REKEY_OFFLOAD_KEK_LEN 16 +#define HISI_REKEY_OFFLOAD_REPLAY_COUNTER_LEN 8 +#endif + +#define HI_WIFI_HIPRIV_ARGC_MAX 10 + +typedef enum { + HISI_FALSE = 0, + HISI_TRUE = 1, + + HISI_BUTT +}hisi_bool_enum; + +typedef hi_u8 hisi_bool_enum_uint8; + +typedef enum { + HISI_IFTYPE_UNSPECIFIED, + HISI_IFTYPE_ADHOC, + HISI_IFTYPE_STATION, + HISI_IFTYPE_AP, + HISI_IFTYPE_AP_VLAN, + HISI_IFTYPE_WDS, + HISI_IFTYPE_MONITOR, + HISI_IFTYPE_MESH_POINT, + HISI_IFTYPE_P2P_CLIENT, + HISI_IFTYPE_P2P_GO, + HISI_IFTYPE_P2P_DEVICE, + + /* keep last */ + NUM_HISI_IFTYPES, + HISI_IFTYPE_MAX = NUM_HISI_IFTYPES - 1 +}hisi_iftype_enum; +typedef hi_u8 hisi_iftype_enum_uint8; + +typedef enum { + HISI_KEYTYPE_GROUP, + HISI_KEYTYPE_PAIRWISE, + HISI_KEYTYPE_PEERKEY, + + NUM_HISI_KEYTYPES +}hisi_key_type_enum; +typedef hi_u8 hisi_key_type_enum_uint8; + +typedef enum { + __HISI_KEY_DEFAULT_TYPE_INVALID, + HISI_KEY_DEFAULT_TYPE_UNICAST, + HISI_KEY_DEFAULT_TYPE_MULTICAST, + + NUM_HISI_KEY_DEFAULT_TYPES +}hisi_key_default_types_enum; +typedef hi_u8 hisi_key_default_types_enum_uint8; + +typedef enum { + HISI_NO_SSID_HIDING, + HISI_HIDDEN_SSID_ZERO_LEN, + HISI_HIDDEN_SSID_ZERO_CONTENTS +}hisi_hidden_ssid_enum; +typedef hi_u8 hisi_hidden_ssid_enum_uint8; + +typedef enum { + HISI_IOCTL_SET_AP = 0, + HISI_IOCTL_NEW_KEY, + HISI_IOCTL_DEL_KEY, + HISI_IOCTL_SET_KEY, + HISI_IOCTL_SEND_MLME, + HISI_IOCTL_SEND_EAPOL, + HISI_IOCTL_RECEIVE_EAPOL, + HISI_IOCTL_ENALBE_EAPOL, + HISI_IOCTL_DISABLE_EAPOL, + HIIS_IOCTL_GET_ADDR, + HISI_IOCTL_SET_MODE, + HIIS_IOCTL_GET_HW_FEATURE, + HISI_IOCTL_SCAN, + HISI_IOCTL_DISCONNET, + HISI_IOCTL_ASSOC, + HISI_IOCTL_SET_NETDEV, + HISI_IOCTL_CHANGE_BEACON, + HISI_IOCTL_SET_REKEY_INFO, + HISI_IOCTL_STA_REMOVE, + HISI_IOCTL_SEND_ACTION, + HISI_IOCTL_SET_MESH_USER, + HISI_IOCTL_SET_MESH_GTK, + HISI_IOCTL_EN_ACCEPT_PEER, + HISI_IOCTL_EN_ACCEPT_STA, + HISI_IOCTL_ADD_IF, + HISI_IOCTL_PROBE_REQUEST_REPORT, + HISI_IOCTL_REMAIN_ON_CHANNEL, + HISI_IOCTL_CANCEL_REMAIN_ON_CHANNEL, + HISI_IOCTL_SET_P2P_NOA, + HISI_IOCTL_SET_P2P_POWERSAVE, + HISI_IOCTL_SET_AP_WPS_P2P_IE, + HISI_IOCTL_REMOVE_IF, + HISI_IOCTL_GET_P2P_MAC_ADDR, + HISI_IOCTL_GET_DRIVER_FLAGS, + HISI_IOCTL_SET_USR_APP_IE, + HISI_IOCTL_DELAY_REPORT, + HISI_IOCTL_SEND_EXT_AUTH_STATUS, + HWAL_EVENT_BUTT +}hisi_event_enum; +typedef hi_u8 hisi_event_enum_uint8; + +typedef enum { + HISI_ELOOP_EVENT_NEW_STA = 0, + HISI_ELOOP_EVENT_DEL_STA, + HISI_ELOOP_EVENT_RX_MGMT, + HISI_ELOOP_EVENT_TX_STATUS, + HISI_ELOOP_EVENT_SCAN_DONE, + HISI_ELOOP_EVENT_SCAN_RESULT, + HISI_ELOOP_EVENT_CONNECT_RESULT, + HISI_ELOOP_EVENT_DISCONNECT, + HISI_ELOOP_EVENT_MESH_CLOSE, + HISI_ELOOP_EVENT_REMAIN_ON_CHANNEL, + HISI_ELOOP_EVENT_CANCEL_REMAIN_ON_CHANNEL, + HISI_ELOOP_EVENT_CHANNEL_SWITCH, + HISI_ELOOP_EVENT_TIMEOUT_DISCONN, + HISI_ELOOP_EVENT_EXTERNAL_AUTH, + HISI_ELOOP_EVENT_BUTT +}hisi_eloop_event_enum; +typedef hi_u8 hisi_eloop_event_enum_uint8; + +typedef enum { + HISI_MFP_NO, + HISI_MFP_OPTIONAL, + HISI_MFP_REQUIRED, +}hisi_mfp_enum; +typedef hi_u8 hisi_mfp_enum_uint8; + +typedef enum { + HISI_AUTHTYPE_OPEN_SYSTEM = 0, + HISI_AUTHTYPE_SHARED_KEY, + HISI_AUTHTYPE_FT, + HISI_AUTHTYPE_SAE, + HISI_AUTHTYPE_NETWORK_EAP, + + /* keep last */ + __HISI_AUTHTYPE_NUM, + HISI_AUTHTYPE_MAX = __HISI_AUTHTYPE_NUM - 1, + HISI_AUTHTYPE_AUTOMATIC, + + HISI_AUTHTYPE_BUTT +}hisi_auth_type_enum; +typedef hi_u8 hisi_auth_type_enum_uint8; + +typedef enum { + HISI_SCAN_SUCCESS = 0, + HISI_SCAN_FAILED = 1, + HISI_SCAN_REFUSED = 2, + HISI_SCAN_TIMEOUT = 3, +} hisi_scan_status_enum; +typedef hi_u8 hisi_scan_status_enum_uint8; + +typedef enum { + HISI_FRAME_TYPE_BEACON = bit(0), + HISI_FRAME_TYPE_PROBE_REQ = bit(1), + HISI_FRAME_TYPE_PROBE_RSP = bit(2), + HISI_FRAME_TYPE_BUTT +} hisi_frame_app_ie_enum; + +/** + * Action to perform with external authentication request. + * @HISI_EXTERNAL_AUTH_START: Start the authentication. + * @HISI_EXTERNAL_AUTH_ABORT: Abort the ongoing authentication. + */ +typedef enum { + HISI_EXTERNAL_AUTH_START, + HISI_EXTERNAL_AUTH_ABORT, + + HISI_EXTERNAL_AUTH_BUTT, +}hisi_external_auth_action_enum; +typedef hi_u8 hisi_external_auth_action_enum_uint8; + +typedef struct _hisi_driver_scan_status_stru { + hisi_scan_status_enum scan_status; +} hisi_driver_scan_status_stru; + +typedef struct _hisi_ioctl_command_stru { + hi_u32 cmd; + hi_void *buf; +}hisi_ioctl_command_stru; + +typedef hi_s32 (*hisi_send_event_cb)(const hi_char*, hi_s32, hi_u8*, hi_u32); + +#ifdef _PRE_WLAN_FEATURE_P2P +typedef struct _hisi_remain_on_channel_stru { + hi_s32 freq; + hi_s32 duration; +} hisi_on_channel_stru; + +typedef struct _hisi_if_add_stru { + hi_s8 type; +} hisi_if_add_stru; + +typedef struct _hisi_if_remove_stru { + hi_u8 ifname[IFNAMSIZ]; +} hisi_if_remove_stru; + +typedef struct _hisi_get_p2p_addr_stru { + hi_s8 type; + hi_u8 mac_addr[ETH_ADDR_LEN]; + hi_u8 resv; +} hisi_get_p2p_addr_stru; + +typedef struct _hisi_p2p_noa_stru { + hi_s32 start; + hi_s32 duration; + hi_u8 count; + hi_u8 resv[3]; /* 3 byte reserved */ +} hisi_p2p_noa_stru; + +typedef struct _hisi_p2p_power_save_stru { + hi_s32 legacy_ps; + hi_s8 opp_ps; + hi_u8 ctwindow; + hi_u8 resv[2]; /* 2 BYTE reserved */ +} hisi_p2p_power_save_stru; +#endif + +typedef struct _hisi_get_drv_flags_stru { + hi_u64 drv_flags; +} hisi_get_drv_flags_stru; + +typedef struct _hisi_new_sta_info_stru { + hi_s32 l_reassoc; + hi_u32 ielen; + hi_u8 *puc_ie; + hi_u8 auc_macaddr[ETH_ADDR_LEN]; + hi_u8 resv[2]; /* 2 BYTE reserved */ +}hisi_new_sta_info_stru; + +typedef struct _hisi_rx_mgmt_stru { + hi_u8 *puc_buf; + hi_u32 len; + hi_s32 l_sig_mbm; + hi_u32 freq; +}hisi_rx_mgmt_stru; + +typedef struct _hisi_tx_status_stru { + hi_u8 *puc_buf; + hi_u32 len; + hisi_bool_enum_uint8 ack; + hi_u8 resv[3]; /* 3 BYTE */ +}hisi_tx_status_stru; + +typedef struct _hisi_mlme_data_stru { + hi_u32 freq; + hi_u32 data_len; + hi_u8 *puc_data; + hi_u64 *pull_send_action_cookie; +}hisi_mlme_data_stru; + +typedef struct _hisi_beacon_data_stru { + hi_u32 head_len; + hi_u32 tail_len; + hi_u8 *puc_head; + hi_u8 *puc_tail; +}hisi_beacon_data_stru; + +typedef struct _hisi_action_data_stru { + hi_u8 *puc_dst; + hi_u8 *puc_src; + hi_u8 *puc_bssid; + hi_u8 *puc_data; + hi_u32 data_len; +}hisi_action_data_stru; + +#ifdef _PRE_WLAN_FEATURE_MESH +typedef struct _hisi_set_mesh_user_data_stru { + hi_u8 *puc_addr; + hi_u8 plink_state; + hi_u8 set; + hi_u8 bcn_prio; + hi_u8 is_mbr; + hi_u8 mesh_initiative_peering; +}hisi_set_mesh_user_data_stru; + +typedef struct _hisi_enable_auto_peer_stru { + hi_u8 enable_auto_peer; +}hisi_enable_auto_peer_stru; + +typedef struct _hisi_set_mesh_user_gtk_stru { + hi_u8 *puc_addr; + hi_u8 *puc_gtk; + hi_u8 gtk_len; + hi_u8 resv[3]; /* 3 bytes reserved */ +}hisi_set_mesh_user_gtk_stru; + +typedef struct _hisi_enable_accept_peer_stru { + hi_u8 enable_accept_peer; +}hisi_enable_accept_peer_stru; + +typedef struct _hisi_enable_accept_sta_stru { + hi_u8 enable_accept_sta; +}hisi_enable_accept_sta_stru; +#endif + +typedef struct _hisi_delay_report_stru { + hi_u8 enable; + hi_u16 timeout; + hi_u8 resv; +}hisi_delay_report_stru; + +typedef struct _hisi_freq_params_stru { + hi_s32 l_mode; + hi_s32 l_freq; + hi_s32 l_channel; + + /* for HT */ + hi_s32 l_ht_enabled; + + /* 0 = HT40 disabled, -1 = HT40 enabled, + * secondary channel below primary, 1 = HT40 + * enabled, secondary channel above primary */ + hi_s32 l_sec_channel_offset; + + /* for VHT */ + hi_s32 l_vht_enabled; + + /* valid for both HT and VHT, center_freq2 is non-zero + * only for bandwidth 80 and an 80+80 channel */ + hi_s32 l_center_freq1; + hi_s32 l_center_freq2; + hi_s32 l_bandwidth; +}hisi_freq_params_stru; + +typedef struct _hisi_key_ext_stru { + hi_s32 l_type; + hi_u32 key_idx; + hi_u32 key_len; + hi_u32 seq_len; + hi_u32 cipher; + hi_u8 *puc_addr; + hi_u8 *puc_key; + hi_u8 *puc_seq; + hisi_bool_enum_uint8 def; + hisi_bool_enum_uint8 defmgmt; + hisi_key_default_types_enum_uint8 default_types; + hi_u8 resv; +}hisi_key_ext_stru; + +/* Data transfer structure related to AP information configuration */ +typedef struct _hisi_ap_settings_stru { + hisi_freq_params_stru freq_params; + hisi_beacon_data_stru beacon_data; + hi_u32 ssid_len; + hi_s32 l_beacon_interval; + hi_s32 l_dtim_period; + hi_u8 *puc_ssid; + hisi_hidden_ssid_enum_uint8 hidden_ssid; + hisi_auth_type_enum_uint8 auth_type; + hi_u8 resv[2]; /* 2 bytes reserved */ +}hisi_ap_settings_stru; + +typedef struct _hisi_set_mode_stru { + hi_u8 auc_bssid[ETH_ADDR_LEN]; + hisi_iftype_enum_uint8 iftype; + hi_u8 resv; +}hisi_set_mode_stru; + +typedef struct _hisi_tx_eapol_stru { + hi_u8 *puc_buf; + hi_u32 len; +}hisi_tx_eapol_stru; + +typedef struct _hisi_rx_eapol_stru { + hi_u8 *puc_buf; + hi_u32 len; +}hisi_rx_eapol_stru; + +typedef struct _hisi_enable_eapol_stru { + hi_void *callback; + hi_void *contex; +}hisi_enable_eapol_stru; + +typedef struct _hisi_ieee80211_channel_stru { + hi_u16 us_channel; + hi_u8 resv[2]; /* 2 bytes reserved */ + hi_u32 freq; + hi_u32 flags; +}hisi_ieee80211_channel_stru; + +typedef struct _hisi_hw_feature_data_stru { + hi_s32 l_channel_num; + hi_u16 aus_bitrate[12]; /* Take 12 short integer space */ + hi_u16 us_ht_capab; + hi_u8 resv[2]; /* 2 bytes reserved */ + hisi_ieee80211_channel_stru ast_iee80211_channel[14]; /* 14 dimensions */ +}hisi_hw_feature_data_stru; + +typedef struct _hisi_driver_scan_ssid_stru { + hi_u8 auc_ssid[MAX_SSID_LEN]; + hi_u32 ssid_len; +} hisi_driver_scan_ssid_stru; + +typedef struct _hisi_scan_stru { + hisi_driver_scan_ssid_stru *ast_ssids; + hi_s32 *pl_freqs; + hi_u8 *puc_extra_ies; + hi_u8 *puc_bssid; + hi_u8 num_ssids; + hi_u8 num_freqs; + hi_u8 prefix_ssid_scan_flag; + hi_u8 fast_connect_flag; + hi_u32 extra_ies_len; +}hisi_scan_stru; + +typedef struct _hisi_crypto_settings_stru { + hi_u32 wpa_versions; + hi_u32 cipher_group; + hi_s32 l_n_ciphers_pairwise; + hi_u32 aul_ciphers_pairwise[HISI_MAX_NR_CIPHER_SUITES]; + hi_s32 l_n_akm_suites; + hi_u32 aul_akm_suites[HISI_MAX_NR_AKM_SUITES]; +}hisi_crypto_settings_stru; + +typedef struct _hisi_associate_params_stru { + hi_u8 *puc_bssid; + hi_u8 *puc_ssid; + hi_u8 *puc_ie; + hi_u8 *puc_key; + hi_u8 auth_type; + hi_u8 privacy; + hi_u8 key_len; + hi_u8 key_idx; + hi_u8 mfp; + hi_u8 auto_conn; + hi_u8 resv[2]; /* 2 bytes reserved */ + hi_u32 freq; + hi_u32 ssid_len; + hi_u32 ie_len; + hisi_crypto_settings_stru *crypto; +} hisi_associate_params_stru; + +typedef struct _hisi_connect_result_stru { + hi_u8 *puc_req_ie; + hi_u32 req_ie_len; + hi_u8 *puc_resp_ie; + hi_u32 resp_ie_len; + hi_u8 auc_bssid[ETH_ADDR_LEN]; + hi_u8 resv[2]; /* 2 bytes reserved */ + hi_u16 us_status; + hi_u16 us_freq; +} hisi_connect_result_stru; + +typedef struct _hisi_scan_result_stru { + hi_s32 l_flags; + hi_u8 auc_bssid[ETH_ADDR_LEN]; + hi_s16 s_caps; + hi_s32 l_freq; + hi_s32 l_level; + hi_u32 age; + hi_u32 ie_len; + hi_u8 *puc_variable; +} hisi_scan_result_stru; + +typedef struct _hisi_disconnect_stru { + hi_u8 *puc_ie; + hi_u16 us_reason; + hi_u8 auc_rsv[2]; /* 2 bytes reserved */ + hi_u32 ie_len; +} hisi_disconnect_stru; + +#ifdef _PRE_WLAN_FEATURE_P2P +typedef struct _hisi_app_ie_stru { + hi_u32 ie_len; + hi_u8 app_ie_type; + hi_u8 auc_rsv[3]; /* 3 bytes reserved */ + hi_u8 *puc_ie; +}hisi_app_ie_stru; +#endif +#ifdef _PRE_WLAN_FEATURE_REKEY_OFFLOAD +typedef struct _hisi_rekey_offload_stru { + hi_u8 auc_kck[HISI_REKEY_OFFLOAD_KCK_LEN]; + hi_u8 auc_kek[HISI_REKEY_OFFLOAD_KEK_LEN]; + hi_u8 auc_replay_ctr[HISI_REKEY_OFFLOAD_REPLAY_COUNTER_LEN]; +}hisi_rekey_offload_stru; +#endif +#ifdef _PRE_WLAN_FEATURE_MESH +typedef struct _hisi_mesh_close_peer_stru { + hi_u8 auc_macaddr[ETH_ADDR_LEN]; + hi_u16 us_reason; +} hisi_mesh_close_peer_stru; + +typedef struct _hisi_mesh_new_peer_candidate_stru { + hi_u8 auc_peer_addr[ETH_ADDR_LEN]; + hi_u8 bcn_prio; + hi_u8 is_mbr; + hi_s8 rssi; + hi_u8 reserved[3]; /* 3 BYTE reserved */ +}hisi_mesh_new_peer_candidate_stru; +#endif + +typedef struct { + hi_u8 set; /* 0: del, 1: add */ + hi_u8 ie_type; + hi_u16 ie_len; + hisi_frame_app_ie_enum frame_type; + hi_u8 *ie; +} hisi_usr_app_ie_stru; + +typedef struct _hisi_ch_switch_stru { + hi_s32 freq; +} hisi_ch_switch_stru; + +#ifdef _PRE_WLAN_FEATURE_SAE +/* The driver reports an event to trigger WPA to start SAE authentication. */ +/* 驱动上报事件触发WPA开始SAE认证 */ +typedef struct { + hisi_external_auth_action_enum auth_action; + hi_u8 bssid[ETH_ADDR_LEN]; + hi_u8 *ssid; + hi_u32 ssid_len; + hi_u32 key_mgmt_suite; + hi_u16 status; + hi_u8 *pmkid; +}hisi_external_auth_stru; +#endif + +#ifdef __cplusplus +#if __cplusplus + } +#endif +#endif + +#endif /* end of driver_hisi_common.h */ diff --git a/sdk_liteos/components/wifi/include/hi_wifi_mfg_test_if.h b/sdk_liteos/components/wifi/include/hi_wifi_mfg_test_if.h new file mode 100644 index 0000000000000000000000000000000000000000..3bdf005767be3a26948882fdc64d2ee55eb71972 --- /dev/null +++ b/sdk_liteos/components/wifi/include/hi_wifi_mfg_test_if.h @@ -0,0 +1,236 @@ +/** + * @file hi_wifi_mfg_test_if.h + * + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Description: header file for wifi manufacturing test interference.CNcomment:描述:WiFi 产测接口头文件CNend\n + */ + +/** + * @defgroup hi_wifi_mfg_test_if + */ +/** + * @defgroup hi_wifi_mfg_test_if Basic Settings + * @ingroup hi_wifi + */ + +#ifndef __HI_WIFI_MFG_TEST_IF_H__ +#define __HI_WIFI_MFG_TEST_IF_H__ + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif + +typedef enum { + HISI_AT_AL_TX, + HISI_AT_AL_RX, + HISI_AT_RX_INFO, + HISI_AT_SET_COUNTRY, + HISI_AT_GET_COUNTRY, + HISI_AT_SET_WLAN0_BW, + HISI_AT_SET_AP0_BW, + HISI_AT_SET_MESH0_BW, + HISI_AT_GET_WLAN0_MESHINFO, + HISI_AT_GET_MESH0_MESHINFO, + HISI_AT_SET_TPC, + HISI_AT_SET_TRC, + HISI_AT_SET_RATE, + HISI_AT_SET_ARLOG, + HISI_AT_GET_VAP_INFO, + HISI_AT_GET_USR_INFO, + + HISI_AT_TYPE_BUTT +}hisi_at_type_enum; + +/** +* @ingroup hi_wifi_mfg_test_if +* @brief Set cal rate power.CNcomment:对不同协议场景、不用速率分别做功率补偿CNend +* +* @par Description: +* Set cal band power.CNcomment:对不同协议场景、不用速率分别做功率补偿CNend +* +* @attention NULL +* @param protol [IN] Type #unsigned char protol.CNcomment:协议序号CNend +* @param rate [IN] Type #unsigned char rate.CNcomment:速率CNend +* @param val [IN] Type #int power val.CNcomment:补偿值CNend +* +* @retval #HI_ERR_SUCCESS Excute successfully +* @retval #Other Error code +* @par Dependency: +* @li hi_wifi_mfg_test_if.h: WiFi mfg_test +* @see NULL +*/ +unsigned int wal_set_cal_rate_power(unsigned char protol, unsigned char rate, int val); + +/** +* @ingroup hi_wifi_mfg_test_if +* @brief Set cal freq.CNcomment:进行常温频偏功率补偿CNend +* +* @par Description: +* Set cal freq.CNcomment:进行常温频偏功率补偿CNend +* +* @attention NULL +* @param freq_offset [IN] Type #int freq offset.CNcomment:补偿值CNend +* +* @retval #HI_ERR_SUCCESS Excute successfully +* @retval #Other Error code +* @par Dependency: +* @li hi_wifi_mfg_test_if.h: WiFi mfg_test +* @see NULL +*/ +unsigned int wal_set_cal_freq(int freq_offset); + +#ifdef _PRE_WLAN_FEATURE_MFG_TEST +/** +* @ingroup hi_wifi_mfg_test_if +* @brief Set cal band power.CNcomment:设置各band平均功率补偿CNend +* +* @par Description: +* Set cal band power.CNcomment:设置各band平均功率补偿CNend +* +* @attention NULL +* @param band_num [IN] Type #unsigned char band num.CNcomment:band序号CNend +* @param offset [IN] Type #int power offset.CNcomment:功率补偿值CNend +* +* @retval #HI_ERR_SUCCESS Excute successfully +* @retval #Other Error code +* @par Dependency: +* @li hi_wifi_mfg_test_if.h: WiFi mfg_test +* @see NULL +*/ +unsigned int wal_set_cal_band_power(unsigned char band_num, int offset); + +/** +* @ingroup hi_wifi_mfg_test_if +* @brief set macefuse mac addr.CNcomment:将MAC地址写入efuse或nvCNend +* +* @par Description: +* set macefuse mac addr.CNcomment:将MAC地址写入efuse或nvCNend +* +* @attention NULL +* @param mac_addr [IN] Type #const char * mac addr.CNcomment:mac地址CNend +* @param type [IN] Type #unsigned char type.CNcomment:写入类型,0:efuse,1:nvCNend +* +* @retval #HI_ERR_SUCCESS Excute successfully +* @retval #Other Error code +* @par Dependency: +* @li hi_wifi_mfg_test_if.h: WiFi mfg_test +* @see NULL +*/ +unsigned int wal_set_customer_mac(const char *mac_addr, unsigned char type); + +/** +* @ingroup hi_wifi_mfg_test_if +* @brief get macefuse mac addr.CNcomment:获取efuse中的MAC地址CNend +* +* @par Description: +* get macefuse mac addr.CNcomment:获取efuse中的MAC地址CNend +* +* @attention NULL +* @param NULL +* +* @retval #HI_ERR_SUCCESS Excute successfully +* @retval #Other Error code +* @par Dependency: +* @li hi_wifi_mfg_test_if.h: WiFi mfg_test +* @see NULL +*/ +unsigned int wal_get_customer_mac(void); + +/** +* @ingroup hi_wifi_mfg_test_if +* @brief write data into efuse.CNcomment:将校准值写入efuseCNend +* +* @par Description: +* write data into efuse.CNcomment:将校准值写入efuseCNend +* +* @attention NULL +* @param type [IN] Type #unsigned char type.CNcomment:写入类型,0:efuse,1:nvCNend +* +* @retval #HI_ERR_SUCCESS Excute successfully +* @retval #Other Error code +* @par Dependency: +* @li hi_wifi_mfg_test_if.h: WiFi mfg_test +* @see NULL +*/ +unsigned int wal_set_dataefuse(hi_u32 type); +#endif + +/** +* @ingroup hi_wifi_mfg_test_if +* @brief get cur cal data.CNcomment:获取当前产测校准值CNend +* +* @par Description: +* get cur cal data.CNcomment:获取当前产测校准值CNend +* +* @attention NULL +* @param NULL +* +* @retval #HI_ERR_SUCCESS Excute successfully +* @retval #Other Error code +* @par Dependency: +* @li hi_wifi_mfg_test_if.h: WiFi mfg_test +* @see NULL +*/ +unsigned int wal_get_cal_data(void); + +#if defined(CONFIG_FACTORY_TEST_MODE) || defined(_PRE_WLAN_QUICK_SEND) +/** +* @ingroup hi_wifi_mfg_test_if +* @brief add cfg vap.CNcomment:添加配置vapCNend +* +* @par Description: +* add cfg vap.CNcomment:添加配置vapCNend +* +* @attention NULL +* @param NULL +* +* @retval #HI_ERR_SUCCESS Excute successfully +* @retval #Other Error code +* @par Dependency: +* @li hi_wifi_mfg_test_if.h: WiFi mfg_test +* @see NULL +*/ +unsigned int wal_add_cfg_vap(void); +#endif + +/** +* @ingroup hi_wifi_mfg_test_if +* @brief always rx/tx interference function.CNcomment:常发常收等接口函数CNend +* +* @par Description: +* always rx/tx interference function.CNcomment:常发常收等接口函数CNend +* +* @attention NULL +* @param argc [IN] Type #int argc.CNcomment:命令参数个数CNend +* @param argv [IN] Type #const char *argv.CNcomment:命令各参数对应的字符串数组CNend +* @param cmd_type [IN] Type #unsigned int cmd_type.CNcomment:命令类型CNend +* +* @retval #HI_ERR_SUCCESS Excute successfully +* @retval #Other Error code +* @par Dependency: +* @li hi_wifi_mfg_test_if.h: WiFi mfg_test +* @see NULL +*/ +unsigned int hi_wifi_at_start(int argc, const char *argv[], unsigned int cmd_type); + +#ifdef __cplusplus +#if __cplusplus + } +#endif +#endif + +#endif diff --git a/sdk_liteos/components/wifi/include/hi_wifi_tmp_api.h b/sdk_liteos/components/wifi/include/hi_wifi_tmp_api.h new file mode 100644 index 0000000000000000000000000000000000000000..746890f5af0144d6c10c9838827286b3251014da --- /dev/null +++ b/sdk_liteos/components/wifi/include/hi_wifi_tmp_api.h @@ -0,0 +1,66 @@ +/** + * @file hi_wifi_tmp_api.h + * + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Description: header file for wifi api.CNcomment:描述:WiFi api接口头文件CNend\n + */ + +/** + * @defgroup hi_wifi WiFi API + */ +/** + * @defgroup hi_wifi_tmp TMP + * @ingroup hi_wifi + */ + +#ifndef __HI_WIFI_TMP_API_H__ +#define __HI_WIFI_TMP_API_H__ + +#include "hi_wifi_api.h" + +#ifdef __cplusplus +#if __cplusplus + extern "C" { +#endif +#endif + +/** +* @ingroup hi_wifi_pm +* @brief Set dhcp offload on/off.CNcomment:设置dhcp offload 打开/关闭。CNend +* +* @par Description: +* Set dhcp offload on with ip address, or set dhcp offload off. +* CNcomment:设置arp offload打开、并且设置相应ip地址,或者设置arp offload关闭。CNend +* +* @attention NULL +* @param ifname [IN] Type #const char *, device name. +* @param en [IN] Type #unsigned char, dhcp offload type, 1-on, 0-off. +* @param ip [IN] Type #unsigned int *, ip address in network byte order. +* +* @retval #HISI_OK Excute successfully +* @retval #Other Error code +* @par Dependency: +* @li hi_wifi_tmp_api.h: WiFi API +* @see NULL +*/ +unsigned char hi_wifi_dhcp_offload_setting(const char *ifname, unsigned char en, unsigned int ip); + +#ifdef __cplusplus +#if __cplusplus + } +#endif +#endif + +#endif diff --git a/sdk_liteos/config.gni b/sdk_liteos/config.gni new file mode 100755 index 0000000000000000000000000000000000000000..7ee08dd403031582961633799b6cc5ba590a83b8 --- /dev/null +++ b/sdk_liteos/config.gni @@ -0,0 +1,125 @@ +# Copyright (C) 2020 Hisilicon (Shanghai) Technologies Co., Ltd. All rights reserved. + +# Kernel type, e.g. "linux", "liteos_a", "liteos_m". +kernel_type = "liteos_m" + +# Kernel version. +kernel_version = "" + +# Board CPU type, e.g. "cortex-a7", "riscv32". +board_cpu = "" + +# Board arch, e.g. "armv7-a", "rv32imac". +board_arch = "rv32imac" + +# Toolchain name used for system compiling. +# E.g. gcc-arm-none-eabi, arm-linux-harmonyeabi-gcc, ohos-clang, riscv32-unknown-elf. +# Note: The default toolchain is "ohos-clang". It's not mandatory if you use the default toochain. +board_toolchain = "riscv32-unknown-elf" + +# The toolchain path instatlled, it's not mandatory if you have added toolchian path to your ~/.bashrc. +board_toolchain_path = "" + +# Compiler prefix. +board_toolchain_prefix = "riscv32-unknown-elf-" + +# Compiler type, "gcc" or "clang". +board_toolchain_type = "gcc" + +# Board related common compile flags. +board_cflags = [ + "-mabi=ilp32", + "-falign-functions=2", + "-msave-restore", + "-fno-optimize-strlen", + "-freorder-blocks-algorithm=simple", + "-fno-schedule-insns", + "-fno-inline-small-functions", + "-fno-inline-functions-called-once", + "-mtune=size", + "-mno-small-data-limit=0", + "-fno-aggressive-loop-optimizations", + "-std=c99", + "-Wpointer-arith", + "-Wstrict-prototypes", + "-ffunction-sections", + "-fdata-sections", + "-fno-exceptions", + "-fno-short-enums", + "-Wextra", + "-Wundef", + "-U", + "PRODUCT_CFG_BUILD_TIME", + "-DLOS_COMPILE_LDM", + "-DPRODUCT_USR_SOFT_VER_STR=None", + "-DCYGPKG_POSIX_SIGNALS", + "-D__ECOS__", + "-D__RTOS_", + "-DPRODUCT_CFG_HAVE_FEATURE_SYS_ERR_INFO", + "-D__LITEOS__", + "-DLIB_CONFIGURABLE", + "-DLOSCFG_SHELL", + "-DLOSCFG_CACHE_STATICS", + "-DCUSTOM_AT_COMMAND", + "-DLOS_COMPILE_LDM", + "-DLOS_CONFIG_IPERF3", + "-DCMSIS_OS_VER=2", + "-DSECUREC_ENABLE_SCANF_FILE=0", + "-DCONFIG_AT_COMMAND", + "-DPRODUCT_CFG_CHIP_VER_STR=Hi3861V100", + "-DCHIP_VER_Hi3861", + "-DPRODUCT_CFG_SOFT_VER_STR=Hi3861", + "-DHI_BOARD_ASIC", + "-DHI_ON_FLASH", + "-DLITEOS_WIFI_IOT_VERSION", +] +board_cxx_flags = board_cflags +board_ld_flags = [] + +# Board related headfiles search path. +board_include_dirs = [ + "${ohos_root_path}device/itcast/genkipi/sdk_liteos/include", + "${ohos_root_path}device/itcast/genkipi/sdk_liteos/platform/include", + "${ohos_root_path}device/itcast/genkipi/sdk_liteos/platform/system/include", + "${ohos_root_path}device/itcast/genkipi/sdk_liteos/config", + "${ohos_root_path}device/itcast/genkipi/sdk_liteos/config/nv", + "${ohos_root_path}utils/native/lite/include", + "${ohos_root_path}kernel/liteos_m/kal/cmsis", + "${ohos_root_path}device/itcast/genkipi/sdk_liteos/platform/os/Huawei_LiteOS/kernel/base/include", + "${ohos_root_path}device/itcast/genkipi/sdk_liteos/platform/os/Huawei_LiteOS/targets/hi3861v100/include", + "${ohos_root_path}device/itcast/genkipi/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include", + "${ohos_root_path}device/itcast/genkipi/sdk_liteos/platform/os/Huawei_LiteOS/arch/risc-v/rv32im", + "${ohos_root_path}device/itcast/genkipi/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libm/include", + "${ohos_root_path}device/itcast/genkipi/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libsec/include", + "${ohos_root_path}device/itcast/genkipi/sdk_liteos/platform/os/Huawei_LiteOS/net/wpa_supplicant-2.7/src/common", + "${ohos_root_path}device/itcast/genkipi/sdk_liteos/platform/os/Huawei_LiteOS/targets/hi3861v100/plat/riscv", + "${ohos_root_path}device/itcast/genkipi/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include", + "${ohos_root_path}device/itcast/genkipi/sdk_liteos/platform/os/Huawei_LiteOS/kernel/extended/runstop", + "${ohos_root_path}device/itcast/genkipi/sdk_liteos/platform/os/Huawei_LiteOS/components/posix/include", + "${ohos_root_path}device/itcast/genkipi/sdk_liteos/platform/os/Huawei_LiteOS/components/linux/include", + "${ohos_root_path}device/itcast/genkipi/sdk_liteos/third_party/lwip_sack/include", + "${ohos_root_path}device/itcast/genkipi/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include", + "${ohos_root_path}device/itcast/genkipi/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic", + "${ohos_root_path}device/itcast/genkipi/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/riscv32", + "${ohos_root_path}device/itcast/genkipi/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/hw/include", + "${ohos_root_path}device/itcast/genkipi/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/nuttx/include", + "${ohos_root_path}device/itcast/genkipi/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libsec/include", + "${ohos_root_path}device/itcast/genkipi/sdk_liteos/platform/os/Huawei_LiteOS/targets/hi3861v100/config", + "${ohos_root_path}device/itcast/genkipi/sdk_liteos/platform/os/Huawei_LiteOS/targets/hi3861v100/user", + "${ohos_root_path}device/itcast/genkipi/sdk_liteos/platform/os/Huawei_LiteOS/targets/hi3861v100/plat", + "${ohos_root_path}device/itcast/genkipi/sdk_liteos/platform/os/Huawei_LiteOS/targets/hi3861v100/extend/include", + "${ohos_root_path}device/itcast/genkipi/sdk_liteos/platform/os/Huawei_LiteOS/arch", + "${ohos_root_path}device/itcast/genkipi/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/bionic/libm", + "${ohos_root_path}device/itcast/genkipi/sdk_liteos/platform/os/Huawei_LiteOS/shell/include", + "${ohos_root_path}device/itcast/genkipi/sdk_liteos/platform/os/Huawei_LiteOS/net/telnet/include", +] + +# Board adapter dir for OHOS components. +board_adapter_dir = + "${ohos_root_path}device/itcast/genkipi/hi3861_adapter" + +# Sysroot path. +board_configed_sysroot = "" + +# Board storage type, it used for file system generation. +storage_type = "" diff --git a/sdk_liteos/config/diag/dfx_sal.h b/sdk_liteos/config/diag/dfx_sal.h new file mode 100644 index 0000000000000000000000000000000000000000..f35cb7b61df7b43318790ae728c485651775e2a7 --- /dev/null +++ b/sdk_liteos/config/diag/dfx_sal.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __DFX_SAL_H__ +#define __DFX_SAL_H__ +#include +#include + +#define ID_DIAG_CMD_REMOTE 0x7000 +#define ID_DIAG_CMD_DO_FRAME_ERR 0x7007 /* DIAG error report */ + +#define HI_DIAG_VER_FULL_PRODUCT_NAME_MAX_SIZE 60 /* Version Description */ +#define HI_DIAG_VER_SDK_PRODUCT_NAME_MAX_SIZE 24 /* SDK Version */ +#define HI_DIAG_VER_BOOT_NAME_MAX_SIZE 8 +#define HI_DIAG_VER_FULL_HW_INFO_MAX_SIZE 40 /* Hardware information */ +#define HI_DIAG_VER_FULL_DEV_VER_NAME_MAX_SIZE 40 /* Device information */ + +typedef struct { + hi_char ver[HI_DIAG_VER_FULL_PRODUCT_NAME_MAX_SIZE]; + hi_char sdk_ver[HI_DIAG_VER_SDK_PRODUCT_NAME_MAX_SIZE]; + hi_char dev[HI_DIAG_VER_FULL_DEV_VER_NAME_MAX_SIZE]; + hi_char hw[HI_DIAG_VER_FULL_HW_INFO_MAX_SIZE]; + hi_char boot_ver[HI_DIAG_VER_BOOT_NAME_MAX_SIZE]; +} diag_cmd_soft_new_ver; + +#define HI_SYS_ERR_SIGNATURE hi_make_identifier('s', 'y', 's', 'E') + +typedef struct { + hi_u32 id; +} hi_dbg_stat_q; + +#endif /* __DFX_SAL_H__ */ + diff --git a/sdk_liteos/config/diag/dfx_sys.h b/sdk_liteos/config/diag/dfx_sys.h new file mode 100644 index 0000000000000000000000000000000000000000..447cb7f3851b88a61947e60eea51c36f514484c6 --- /dev/null +++ b/sdk_liteos/config/diag/dfx_sys.h @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __DFX_SYS_H__ +#define __DFX_SYS_H__ + +#include "hi_types.h" +#include "hi_mdm_types.h" +#include + +HI_START_HEADER + +typedef struct { + hi_u16 send_uart_fail_cnt; + hi_u16 ack_ind_malloc_fail_cnt; + hi_u16 msg_malloc_fail_cnt; + hi_u16 msg_send_fail_cnt; + hi_u16 msg_overbig_cnt; + hi_u16 ind_send_fail_cnt; + hi_u16 ind_malloc_fail_cnt; + hi_u8 diag_queue_used_cnt; + hi_u8 diag_queue_total_cnt; + hi_u8 dec_fail_cnt; + hi_u8 enc_fail_cnt; + hi_u16 pkt_size_err_cnt; + hi_u32 local_req_cnt; + hi_u16 req_cache_overflow_cnt; + hi_u8 conn_excep_cnt; + hi_u8 conn_bu_cnt; + hi_u8 chl_busy_cnt; + hi_u8 req_overbig1_cnt; + hi_u8 cmd_list_total_cnt; + hi_u8 cmd_list_used_cnt; + hi_u8 stat_list_total_cnt; + hi_u8 stat_list_used_cnt; + hi_u8 req_overbig2_cnt; + hi_u8 invalid_dec_id; + hi_u8 heart_beat_timeout_cnt; + hi_u8 rx_start_flag_wrong_cnt; + hi_u8 rx_cs_wrong_cnt; + hi_u8 rx_pkt_data_size_wrong_cnt; + hi_u16 msg_enqueue_fail_cnt; + hi_u16 pad; +} hi_stat_diag; + +HI_END_HEADER +#endif /* __DFX_SYS_H__ */ diff --git a/sdk_liteos/config/nv/hi_ft_nv.h b/sdk_liteos/config/nv/hi_ft_nv.h new file mode 100644 index 0000000000000000000000000000000000000000..ebafbe1b12bbb2b97c310c04bf67fdcb7edfb177 --- /dev/null +++ b/sdk_liteos/config/nv/hi_ft_nv.h @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __FT_NV_H__ +#define __FT_NV_H__ +#include + +/****************************************************************************** + NV ID[0xF00, 0xFFF] + *****************************************************************************/ +#define HI_NV_FTM_FLASH_PARTIRION_TABLE_ID 0x02 +#define HI_FTM_PRODUCT_ID_RANGE_MRS 500 + +#define HI_NV_FTM_STARTUP_CFG_ID 0x3 /* hi_nv_ftm_startup_cfg */ +#define HI_NV_FTM_FACTORY_MODE 0x9 /* hi_nv_ftm_factory_mode */ +#define HI_NV_FTM_UPG_WAIT_MODE 0xA /* hi_nv_ftm_upg_wait_mode */ + +typedef struct { + uintptr_t addr_start; /* boot start address */ + hi_u16 mode; /* upgrade mode */ + hi_u8 file_type; /* file type:boot or code+nv */ + hi_u8 refresh_nv; /* refresh nv when the flag bit 0x55 is read */ + hi_u8 reset_cnt; /* number of restarts in upgrade mode */ + hi_u8 cnt_max; /* the maximum number of restarts (default value : 3) */ + hi_u16 reserved1; + uintptr_t addr_write; /* write kernel upgrade file address */ + hi_u32 reserved2; /* reserved */ +} hi_nv_ftm_startup_cfg; + +typedef struct { + hi_u32 factory_mode; /* 0:normal_mode;1:factory_mode */ + uintptr_t factory_addr_start; /* factory bin start address */ + hi_u32 factory_size; /* factory bin size */ + hi_u32 factory_valid; /* 0:invalid;1:valid */ +} hi_nv_ftm_factory_mode; + +typedef struct { + hi_u32 file_addr; + hi_u8 file_type; + hi_u8 boot_version; + hi_u8 is_upg_process; + hi_u8 trans_finish_flag; +} hi_nv_ftm_upg_wait_mode; + +#endif /* __FT_NV_H__ */ + diff --git a/sdk_liteos/config/nv/hi_sal_nv.h b/sdk_liteos/config/nv/hi_sal_nv.h new file mode 100644 index 0000000000000000000000000000000000000000..815dae8728f85788897833e528f93bc540b5b349 --- /dev/null +++ b/sdk_liteos/config/nv/hi_sal_nv.h @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __HI_SAL_NV_H__ +#define __HI_SAL_NV_H__ + +#define HI_NV_SYS_RST_TIMES 0x40 +#define HI_NV_SYS_RST_CFG_ID 0x41 +#define HI_NV_SYS_UART_PORT_ID 0x42 + +typedef struct { + hi_u32 rst_times; + hi_u32 enable_save; +} hi_sys_reset_times; + +typedef struct { + hi_u8 enable_rst; + hi_u8 rsv[3]; /* 3 bytes reserved */ + hi_u32 secure_begin_time; + hi_u32 secure_end_time; + hi_u32 max_time_usr0; + hi_u32 max_time_usr1; +} hi_nv_reset_cfg_id; + +typedef enum { + UART_FUNC_AT, + UART_FUNC_SHELL, + UART_FUNC_DIAG, + UART_FUNC_SIGMA, + UART_FUNC_MAX, +} hi_uart_func_idx; + +/* uart port allocation */ +typedef struct { + hi_u8 uart_port_at; + hi_u8 uart_port_debug; + hi_u8 uart_port_sigma; + hi_u8 uart_port_reserved; +} hi_nv_uart_port_alloc; + +#endif /* __HI_SAL_NV_H__ */ + diff --git a/sdk_liteos/config/system_config.h b/sdk_liteos/config/system_config.h new file mode 100644 index 0000000000000000000000000000000000000000..ed6696dcf0ad72cbe13a91026a76e15862342d6e --- /dev/null +++ b/sdk_liteos/config/system_config.h @@ -0,0 +1,132 @@ +/* + * Copyright (c) 2020 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _SYSTEM_CONFIG_H +#define _SYSTEM_CONFIG_H + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +/* ============================================================================= + LiteOS kernel version configuration +============================================================================= */ +/** + * @ingroup los_config + * Version number + */ +#define LITEOS_VER + +/** system source configuration**/ +/** + * @ingroup los_config + * system clock + */ +#ifdef HI_BOARD_ASIC +#define OS_SYS_CLOCK_CONFIG 160000000 +#else +#define OS_SYS_CLOCK_CONFIG 53000000 +#endif + +/** system source configuration**/ +/** + * @ingroup los_config + * Number of Ticks in one second + */ +#define LOSCFG_BASE_CORE_TICK_PER_SECOND_CONFIG 100 + +/** system source configuration**/ +/** + * @ingroup los_config + * Maximum supported number of tasks except the idle task rather than the number of usable tasks + */ +#define LOSCFG_BASE_CORE_TSK_LIMIT_CONFIG 32 + +/** + * @ingroup los_config + * Maximum supported number of semaphores + */ +#define LOSCFG_BASE_IPC_SEM_LIMIT_CONFIG 32 +/** + * @ingroup los_config + * Maximum supported number of mutexes + */ +#define LOSCFG_BASE_IPC_MUX_LIMIT_CONFIG 32 + +/** + * @ingroup los_config + * Maximum supported number of queues rather than the number of usable queues + */ +#define LOSCFG_BASE_IPC_QUEUE_LIMIT_CONFIG 32 +/** + * @ingroup los_config + * Maximum supported number of software timers rather than the number of usable software timers + */ +#define LOSCFG_BASE_CORE_SWTMR_LIMIT_CONFIG 32 + +/** + * @ingroup los_config + * Default task stack size + */ +#define LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE_CONFIG (0x1000UL) +/** + * @ingroup los_config + * Idle task stack size. + */ +#define LOSCFG_BASE_CORE_TSK_IDLE_STACK_SIZE_CONFIG (0x400UL) +/** + * @ingroup los_config + * Idle task stack size. + */ +#define LOSCFG_BASE_CORE_TSK_SWTMR_STACK_SIZE_CONFIG (0x800UL) + +/** + * @ingroup los_config + * Minimum stack size. + */ +#define LOSCFG_BASE_CORE_TSK_MIN_STACK_SIZE_CONFIG (0x180UL) +/** + * @ingroup los_config + * Stack point align size. + */ +#define LOSCFG_STACK_POINT_ALIGN_SIZE 16 +/** + * @ingroup los_config + * Longest execution time of tasks with the same priorities + */ +#define LOSCFG_BASE_CORE_TIMESLICE_TIMEOUT_CONFIG 2 +/** + * @ingroup los_cpup + * Number of track items + */ +#define LOSCFG_BASE_MISC_TRACK_COUNT_CONFIG 10 + +#define LOSCFG_NMI_SERVICE 0 + +#ifdef LOSCFG_DEBUG_KASAN +#define LOSCFG_KASAN_TASK_STACK_LIMIT_NUM 3 +#endif + +#define LOSCFG_MEM_POOL_SIZE 0x3C00 + +#ifdef __cplusplus +#if __cplusplus +} +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +#endif /* _SYSTEM_CONFIG_H */ diff --git a/sdk_liteos/factory.mk b/sdk_liteos/factory.mk new file mode 100644 index 0000000000000000000000000000000000000000..e15a18a357580f7f8a8a75a1145295c0d84406dc --- /dev/null +++ b/sdk_liteos/factory.mk @@ -0,0 +1,130 @@ +# Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# ֱʹmakeбʹ÷ +# make make all : ɾн±ģ +# make clean : ɾн +# make link : +MAIN_TOPDIR = $(shell pwd) +THIRD_DIR = $(MAIN_TOPDIR)/third_party +U_BOOT_DIR = $(MAIN_TOPDIR)/third_party/u-boot-v2019.07 + +include $(MAIN_TOPDIR)/build/make_scripts/config.mk +include $(MAIN_TOPDIR)/build/make_scripts/config_lib_factory.mk +export MAIN_TOPDIR + +GCC_PATH := $(dir $(shell which $(CC))) +GCC_LIBPATH := -L$(GCC_PATH)../lib/gcc/riscv32-unknown-elf/$(GCC_VER_NUM) +LIBPATH += $(addprefix -Lbuild/build_tmp/libs/, $(foreach module, $(COMPILE_MODULE), $($(module)_dir))) +ifneq ($(USR_LIBS),) + LIBPATH := $(foreach path, $(LIBPATH), $(patsubst -L%, -L$(MAIN_TOPDIR)/%, $(path))) +endif +COMPILE_MODULE += boot loaderboot +SIGN_CFG = A B +A_SIGN = 0x0040d3c0 +B_SIGN = 0x004f13c0 +FACTORY_SIGN = 0x0054d3c0 +LIBS := $(filter-out -lboot -lloaderboot, $(LIBS)) + +CCFLAGS += -DCONFIG_FACTORY_TEST_MODE + +FIRM_WARE_VER := $(shell if [ $(CONFIG_TARGET_KERNEL_VER) -gt -1 ] && [ $(CONFIG_TARGET_KERNEL_VER) -lt 49 ];then echo $(CONFIG_TARGET_KERNEL_VER);fi;) +ifneq ($(FIRM_WARE_VER), $(CONFIG_TARGET_KERNEL_VER)) +$(error [ERROR]:FIRM_WARE_VER=$(FIRM_WARE_VER) Ranges From 0 To 48) +endif + +BOOT_VER = $(shell if [ $(CONFIG_TARGET_BOOT_VER) -gt -1 ] && [ $(CONFIG_TARGET_BOOT_VER) -lt 17 ];then echo $(CONFIG_TARGET_BOOT_VER);fi;) +ifneq ($(BOOT_VER), $(CONFIG_TARGET_BOOT_VER)) +$(error [ERROR]:BOOT_VER Ranges From 0 To 16) +endif + +ifeq ($(CONFIG_TARGET_SIG_RSA_V15), y) + SIGN_ALG = 0x0 +else ifeq ($(CONFIG_TARGET_SIG_RSA_PSS), y) + SIGN_ALG = 0x1 +else ifeq ($(CONFIG_TARGET_SIG_ECC), y) + SIGN_ALG = 0x10 +else ifeq ($(CONFIG_TARGET_SIG_SHA256), y) + SIGN_ALG = 0x3F +endif + +OUT_DIRS = $(MAIN_TOPDIR)/$(LOG_PATH) $(MAIN_TOPDIR)/$(CACHE_PATH) $(MAIN_TOPDIR)/$(LINK_PATH) $(MAIN_TOPDIR)/$(NV_PATH) $(MAIN_TOPDIR)/$(BIN_PATH) +all:prepare build_libs_factory nv link_factory check_factory ota_factory + $(Q)echo "< ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ >" + $(Q)echo " FACTORY BIN BUILD SUCCESS " + $(Q)echo "< ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ >" + +build_libs_factory: + $(Q)$(foreach module, $(COMPILE_MODULE), \ + $(foreach lib, $($(module)_libs), \ + $(MAKE) -C $(MAIN_TOPDIR)/$($(module)_dir) MODULE_DIR=$($(module)_dir) LIB=$(lib) FACTORY_MODE=y all;)) + +nv: + $(NV_TOOL) $(MAIN_TOPDIR)/$(NV_PATH) $(TARGET_NAME) $(NV_CFG_NAME) + +link_factory: + $(CC) $(LINK_SCRIPTS_FLAG) -E $(MAIN_TOPDIR)/build/link/system_config.ld.S -o $(MAIN_TOPDIR)/$(LINK_PATH)/system_config.ld -P + $(CC) $(LINK_SCRIPTS_FLAG) -DFLASH_FIRM_START=$(FACTORY_SIGN) -E $(MAIN_TOPDIR)/build/link/link.ld.S -o $(MAIN_TOPDIR)/$(LINK_PATH)/link_factory.lds -P; + $(LINK) $(LINKFLAGS) $(GCC_LIBPATH) $(sort $(LIBPATH)) -T$(MAIN_TOPDIR)/$(LINK_PATH)/link_factory.lds -Map=$(MAIN_TOPDIR)/$(BIN_PATH)/$(TARGET_NAME)_factory.map -o $(MAIN_TOPDIR)/$(BIN_PATH)/$(TARGET_NAME)_factory.out --start-group $(LIBS) --end-group; + $(OBJCOPY) -O binary $(MAIN_TOPDIR)/$(BIN_PATH)/$(TARGET_NAME)_factory.out $(MAIN_TOPDIR)/$(CACHE_PATH)/$(TARGET_NAME)_factory.bin; + $(OBJDUMP) -d $(MAIN_TOPDIR)/$(BIN_PATH)/$(TARGET_NAME)_factory.out >$(MAIN_TOPDIR)/$(BIN_PATH)/$(TARGET_NAME)_factory.asm; + dd if=$(MAIN_TOPDIR)/$(CACHE_PATH)/$(TARGET_NAME)_factory.bin of=$(MAIN_TOPDIR)/$(CACHE_PATH)/$(TARGET_NAME)_base_factory.bin seek=0 count=278 bs=1K; + dd if=$(MAIN_TOPDIR)/$(CACHE_PATH)/$(TARGET_NAME)_factory.bin of=$(MAIN_TOPDIR)/$(CACHE_PATH)/$(TARGET_NAME)_kernel_factory.bin skip=278 bs=1K + +ota_factory: + $(OTA_TOOL) factory_bin $(TARGET_NAME) $(SIGN_ALG) $(FIRM_WARE_VER) $(BOOT_VER) $(MAIN_TOPDIR)/$(BIN_PATH)/$(TARGET_NAME)_factory.bin usr_output=$(USR_OUTPUT_DIR) $(MAIN_TOPDIR)/$(CACHE_PATH)/$(TARGET_NAME)_kernel_factory.bin A + cp -rf $(MAIN_TOPDIR)/$(BIN_PATH)/ $(MAIN_TOPDIR)/build/libs/factory_bin/ + +check_factory: link_factory + TARGET_SUM=$(shell sha256sum $(MAIN_TOPDIR)/$(CACHE_PATH)/$(TARGET_NAME)_base_factory.bin | cut -d ' ' -f1) && \ + if [ "$$TARGET_SUM" == '$(BASE_NUM)' ]; \ + then echo "#########BASE BIN IS SAME WITH FIRST COMPILE!#########"; \ + else echo "\033[32m#########BASE BIN IS DIFFERENT WITH FIRST COMPILE!#########\033[0m"; exit 1; fi; + +prepare: + $(Q)$(foreach x, $(OUT_DIRS),\ + if [ ! -d $x ]; \ + then \ + mkdir -p $x; \ + echo create dir $(x) success; \ + fi;) + if [ ! -d $(MAIN_TOPDIR)/third_party/u-boot-v2019.07/u-boot-v2019.07/ ]; \ + then \ + cd $(THIRD_DIR)/u-boot-v2019.07; \ + tar -xvf u-boot-v2019.07.tar.gz; \ + cd $(U_BOOT_DIR)/u-boot-v2019.07; \ + patch -p1 < ./../patch/CVE-2019-13103.patch; \ + patch -p1 < ./../patch/CVE-2019-13104.patch; \ + patch -p1 < ./../patch/CVE-2019-13105.patch; \ + patch -p1 < ./../patch/CVE-2019-13106.patch; \ + patch -p1 < ./../patch/CVE-2019-14192-14193-14199.patch; \ + patch -p1 < ./../patch/CVE-2019-14194-14198.patch; \ + patch -p1 < ./../patch/CVE-2019-14195.patch; \ + patch -p1 < ./../patch/CVE-2019-14196.patch; \ + patch -p1 < ./../patch/CVE-2019-14197-14200-14201-14202-14203-14204.patch; \ + patch -p1 < ./../hisilicon_patch/hisilicon-u-boot-v2019.07.patch ; \ + cd $(MAIN_TOPDIR); \ + fi; + +clean: + $(Q)$(foreach x, $(OUT_DIRS),\ + if [ -d $(dir $x) ]; \ + then \ + $(RM) $(dir $x); \ + echo clean dir $(dir $x) success; \ + fi;) + $(RM) $(MAIN_TOPDIR)/build/scripts/__pycache__/ + $(RM) $(MAIN_TOPDIR)/third_party/u-boot-v2019.07/u-boot-v2019.07 + + + diff --git a/sdk_liteos/hm_build.sh b/sdk_liteos/hm_build.sh new file mode 100755 index 0000000000000000000000000000000000000000..7f680bf1bd9446facbaef8d07ace4448795657cb --- /dev/null +++ b/sdk_liteos/hm_build.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -e +product_out_dir="$1" +# prebuild # +cd ../../../../device/itcast/genkipi/sdk_liteos +CROOT=$(pwd) + +OUTPUT_SRC_DIR=$CROOT/output/bin +OUTPUT_DST_DIR=$1 + +OHOS_LIBS_DIR=$CROOT/ohos/libs + +rm $OHOS_LIBS_DIR -rf + +mkdir -p $OHOS_LIBS_DIR +find $OUTPUT_DST_DIR/libs/ -name '*.a' -exec cp "{}" $OHOS_LIBS_DIR \; +find $CROOT/3rd_sdk/ -name '*.a' -exec cp "{}" $OHOS_LIBS_DIR \; + + +# build # +./build.sh wifiiot_app + +# after build # +if [ ! -d $OUTPUT_DST_DIR ]; then + mkdir $OUTPUT_DST_DIR +fi +cp $OUTPUT_SRC_DIR/* $OUTPUT_DST_DIR/ -rf + diff --git a/sdk_liteos/include/hi3861.h b/sdk_liteos/include/hi3861.h new file mode 100644 index 0000000000000000000000000000000000000000..c5e704f7f179ddd6caf7bc9820a2da5effe95091 --- /dev/null +++ b/sdk_liteos/include/hi3861.h @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2020 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __HI3861_H__ +#define __HI3861_H__ + +typedef enum IRQn { + /****** RISC-V Privilege Interrupts ***************************************************/ + MACHINE_SOFTWARE_IRQ = 3, + MACHINE_TIMER_IRQ = 7, + MACHINE_EXTERNAL_IRQ = 11, + NMI_IRQ = 12, + + /****** HiMedeer local Interrupts ***************************************************/ + TIMER_0_IRQ = 26, + TIMER_1_IRQ = 27, + TIMER_2_IRQ = 28, + RTC_0_IRQ = 29, + RTC_1_IRQ = 30, + RTC_2_IRQ = 31, + RTC_3_IRQ = 32, + WDT_IRQ = 33, + WLAN_IRQ = 34, + DMA_IRQ = 35, + SFC_IRQ = 36, + SDIO_IRQ = 37, + UART_0_IRQ = 38, + UART_1_IRQ = 39, + UART_2_IRQ = 40, + I2C_0_IRQ = 41, + I2C_1_IRQ = 42, + SSP_0_IRQ = 43, + SSP_1_IRQ = 44, + GPIO_IRQ = 45, + TSENSOR_IRQ = 46, + WLAN_SLEEP_IRQ = 47, + WLAN_WAKEUPT_IRQ = 48, + OVER_TEMP_IRQ = 49, + PMU_CMU_ERR_IRQ = 50, + CPU_SOFT_0_IRQ = 51, + CPU_SOFT_1_IRQ = 52, + CPU_SOFT_2_IRQ = 53, + CPU_SOFT_3_IRQ = 54, + SSS_PKE_IRQ = 55, + SSS_SYM_IRQ = 56, + SSS_TRNG_IRQ = 57, + ISADC_IRQ = 58, + I2S_IRQ = 59, + UDSLEEP_IRQ = 60, + RAMMONITOR_IRQ = 61 +} IRQn_Type; + +#endif // __HI3861_H__ + diff --git a/sdk_liteos/include/hi3861_platform.h b/sdk_liteos/include/hi3861_platform.h new file mode 100644 index 0000000000000000000000000000000000000000..a014bf547ee2f4a1cafc1d456dbacc0575785232 --- /dev/null +++ b/sdk_liteos/include/hi3861_platform.h @@ -0,0 +1,50 @@ +/** + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __HI3861_PLATFORM_H +#define __HI3861_PLATFORM_H + +#include +#include + +#ifdef HI_BOARD_FPGA +#define PKT_H_START_ADDR (0x03100000 + 0x4000) /* 16K use for MAC data collect */ +#define PKT_H_LEN 0x2000 /* PKT_H:8K MIN:7K */ +#define PKT_B_START_ADDR (0x03100000 + 0x2000 + 0x4000) +#define PKT_B_LEN 0x8000 /* PKT_B:32K MIN:32K */ + +#else + +#define PKT_H_START_ADDR 0x02400000 +#define PKT_H_LEN 0x2000 /* PKT_H:8K MIN:7K */ +#define PKT_B_START_ADDR (0x03100000) +#ifdef CONFIG_CHIP_PKT_48K +#define PKT_B_LEN 0xC000 /* PKT_B:32K */ +#else +#define PKT_B_LEN 0x8000 /* PKT_B:48K */ +#endif + +#endif + +#define HI_CHIP_ID_1131SV200 0xFF +#define HI_CHIP_VER_HI3861L 0x0 +#define HI_CHIP_VER_HI3861 0x1 +#define HI_CHIP_VER_HI3881 0x2 + +hi_void app_io_init(hi_void); +hi_void app_main(hi_void); + +#endif /* __HI3861_PLATFORM_H */ + diff --git a/sdk_liteos/include/hi3861_platform_base.h b/sdk_liteos/include/hi3861_platform_base.h new file mode 100644 index 0000000000000000000000000000000000000000..c5d0863b88634bc09c6eaa6fc7a5eaedc545aa60 --- /dev/null +++ b/sdk_liteos/include/hi3861_platform_base.h @@ -0,0 +1,436 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef __HI3861_PLATFORM_ROM_H +#define __HI3861_PLATFORM_ROM_H + +#include +#include + +HI_EXTERN hi_u32 g_cfg_apb_clock; +HI_EXTERN hi_u32 g_cfg_arm_clock; +HI_EXTERN hi_u32 g_cfg_uart_clock; + +#define HI_XTAL_CLOCK_BASE 24 +#define HI_XTAL_CLOCK (HI_XTAL_CLOCK_BASE * 1000000) +#define HI_XTAL_CYCLE_PER_MS (HI_XTAL_CLOCK_BASE * 1000) +#define CLK32K_DELAY_US 63 /* Wait for 1 / 32K seconds. Reserve 2 / 32K seconds. */ + +#ifdef HI_BOARD_FPGA +/* #error */ +#define CONFIG_CPU_CLOCK 53000000 +#define CONFIG_UART_CLOCK 160000000 +#else +#define CONFIG_CPU_CLOCK 160000000 +#define CONFIG_UART_CLOCK 80000000 +#endif +#define CONFIG_WDT_CLOCK 80000000 + +#define HI_FLASH_BASE 0x00400000 +#define HI_FLASH_SIZE 0x00200000 +#define HI_SFC_REG_BASE 0x40800000 + +#define HI_SYSCTRL_REG_BASE 0x40030000 +#define HI_WDG_REG_BASE 0x40000000 +#define HI_TIMER_REG_BASE 0x40032000 +#define HI_GPIO_REG_BASE 0x50006000 +#define HI_IOCFG_REG_BASE 0x5000A000 +#define HI_BUCK_REG_BASE 0x40034000 +#define HI_SSP0_REG_BASE 0x40058000 +#define HI_I2C0_REG_BASE 0x40018000 +#define HI_I2C1_REG_BASE 0x40019000 +#define HI_SPACC_REG_BASE 0x40038000 +#define HI_RSA_REG_BASE 0x40038c00 +#define HI_EFUSE_REG_BASE 0x40078000 +#define HI_RNG_REG_BASE 0x40038f00 +#define HI_LED_REG_BASE 0x40039000 +#define HI_TIMECNT_REG_BASE 0x4003A000 +#define HI_CRG_REG_BASE 0x4003B000 +#define HI_UART0_REG_BASE 0x40008000 +#define HI_UART1_REG_BASE 0x40009000 +#define HI_UART2_REG_BASE 0x4000a000 + +#define HI_TSENSOR_REG_BASE 0x4003D100 +#define HI_PWM_REG_BASE 0x40040000 +#define HI_OSC_REG_BASE 0x4003D300 +#define HI_TIMECNT1_REG_BASE 0x4003D500 +#define HI_SSP1_REG_BASE 0x40059000 +#define HI_HPM_REG_BASE 0x4003F000 +#define HI_AFE_REG_BASE 0x40040000 +#define HI_MMU_REG_BASE 0x40041000 + +#define W_CTL_BASE_ADDR 0x40028000 +#define W_CTL_MAC_WDT_RST_SEL_REG (W_CTL_BASE_ADDR + 0x34) +#define W_CTL_PHY_WDT_RST_SEL_REG (W_CTL_BASE_ADDR + 0x38) +#define W_CTL_WDT_RST_SEL_REG (W_CTL_BASE_ADDR + 0x3C) +#define W_CTL_UART_MAC80M_CLKEN_REG (W_CTL_BASE_ADDR + 0x40) +#define W_CTL_WLPHY_CLKEN_CLKEN_REG (W_CTL_BASE_ADDR + 0x4C) +#define W_CTL_CPU_MAC_CLK_DIV_REG (W_CTL_BASE_ADDR + 0x70) +#define W_CTL_UART01_CKDIV_OFFSET (W_CTL_BASE_ADDR + 0x74) +#define W_CTL_WLPHY_CLK_DIV_0_REG (W_CTL_BASE_ADDR + 0x78) +#define W_CTL_WLPHY_CLK_DIV_1_REG (W_CTL_BASE_ADDR + 0x7C) +#define W_CTL_WLPHY_CLK_DIV_2_REG (W_CTL_BASE_ADDR + 0x80) +#define W_CTL_TSENSOR_DIV_REG (W_CTL_BASE_ADDR + 0x88) +#define W_CTL_UART2_CKDIV_OFFSET (W_CTL_BASE_ADDR + 0x90) +#define W_CTL_W_TCXO_SEL_REG (W_CTL_BASE_ADDR + 0x0118) +#define W_CTL_CLKMUX_STS_DIV_STS_REG (W_CTL_BASE_ADDR + 0x0130) +#define W_CTL_TSENSOR_CTRL_REG (W_CTL_BASE_ADDR + 0x0504) + + +#define GLB_CTL_RB_BASE_ADDR 0x50000000 +#define CLDO_CTL_RB_BASE_ADDR 0x40010000 +#define CLDO_CTL_GEN_REG0 (CLDO_CTL_RB_BASE_ADDR + 0x10) /* used for romboot */ +#define CLDO_CTL_GEN_REG1 (CLDO_CTL_RB_BASE_ADDR + 0x14) /* used for romboot */ +#define CLDO_CTL_GEN_REG2 (CLDO_CTL_RB_BASE_ADDR + 0x18) /* used for romboot */ +#define CLDO_CTL_GEN_REG3 (CLDO_CTL_RB_BASE_ADDR + 0x1C) /* used for romboot */ +#define CLDO_CTL_SOFT_RESET_REG (CLDO_CTL_RB_BASE_ADDR + 0x20) +#define CLDO_CTL_WDG_RST_SEL_REG (CLDO_CTL_RB_BASE_ADDR + 0x28) +#define CLDO_CTL_CLKEN_REG (CLDO_CTL_RB_BASE_ADDR + 0x30) +#define CLDO_CTL_CLKEN1_REG (CLDO_CTL_RB_BASE_ADDR + 0x34) +#define CLDO_CTL_CLK_SEL_REG (CLDO_CTL_RB_BASE_ADDR + 0x38) +#define CLDO_CTL_CLKEN2_REG (CLDO_CTL_RB_BASE_ADDR + 0x48) +#define CLDO_CTL_WDG_RST_SEL1_REG (CLDO_CTL_RB_BASE_ADDR + 0x4C) +#define CLDO_CTL_CLKMUX_STS_REG (CLDO_CTL_RB_BASE_ADDR + 0x64) +#define CLDO_CTL_CLK_DIV1_REG (CLDO_CTL_RB_BASE_ADDR + 0x78) +#define CLDO_CTL_PKT_CPU_MEM_SEL (CLDO_CTL_RB_BASE_ADDR + 0x100) + +/*************************Timer**********************/ +#define HI_TIMER_CLOCK_BASE 24 /* 24Mhz timer */ +#define TIMER_BASE_ADDR 0x40050000 +#define TIMER_0_BASE_ADDR (TIMER_BASE_ADDR + 0x00) +#define TIMER_1_BASE_ADDR (TIMER_BASE_ADDR + 0x14) +#define TIMER_2_BASE_ADDR (TIMER_BASE_ADDR + 0x28) +#define TIMER_3_BASE_ADDR (TIMER_BASE_ADDR + 0x3C) + +#define TIMER_LOAD_COUNT 0x00 +#define TIMER_LOAD_COUNT_L 0x00 +#define TIMER_LOAD_COUNT_H 0x02 +#define TIMER_CURRENT_VALUE 0x04 +#define TIMER_CONTROL_REG 0x08 +#define TIMER_EOI 0x0C +#define TIMER_INT_STATUS 0x10 + +#define TIMER_CTL_CFG_DISABLE 0x0 +#define TIMER_CTL_CFG_FREERUN 0x01 +#define TIMER_CTL_CFG_USERDEF 0x03 +/*************************RTC**********************/ +#define HI_RTC_CLOCK_BASE 32 /* 32kHZ */ +#define RTC_TIMER_BASE_ADDR 0x50007000 +#define RTC_TIMER_0_BASE_ADDR (RTC_TIMER_BASE_ADDR + 0x00) +#define RTC_TIMER_1_BASE_ADDR (RTC_TIMER_BASE_ADDR + 0x14) +#define RTC_TIMER_2_BASE_ADDR (RTC_TIMER_BASE_ADDR + 0x28) +#define RTC_TIMER_3_BASE_ADDR (RTC_TIMER_BASE_ADDR + 0x3C) +/*****************************************************/ +#define CACHE_ALIGNED_SIZE 32 + + +#define GLB_CTL_BASE 0x50000000 +#define GLB_CTL_SYS_CTL_ID_REG (GLB_CTL_BASE + 0x0) +#define GLB_CTL_GP_REG0_REG (GLB_CTL_BASE + 0x10) +#define GLB_CTL_GP_REG1_REG (GLB_CTL_BASE + 0x14) +#define GLB_CTL_GP_REG2_REG (GLB_CTL_BASE + 0x18) +#define GLB_CTL_GP_REG3_REG (GLB_CTL_BASE + 0x1C) +#define GLB_CTL_AON_SOFT_RST_W_REG (GLB_CTL_BASE + 0x20) +#define GLB_CTL_SOFT_RST_WCPU_REG (GLB_CTL_BASE + 0x24) +#define GLB_CTL_SOFT_GLB_RST_REG (GLB_CTL_BASE + 0x28) +#define GLB_CTL_GLB_WDT_RST_SEL_REG (GLB_CTL_BASE + 0x30) +#define GLB_CTL_WDT_RST_SEL_REG (GLB_CTL_BASE + 0x34) +#define GLB_CTL_AON_CKEN_REG (GLB_CTL_BASE + 0x40) +#define GLB_CTL_GLB_AON_32K_CLKEN_REG (GLB_CTL_BASE + 0x50) +#define GLB_CTL_USB_RST_STS_REG (GLB_CTL_BASE + 0x60) +#define GLB_CTL_A32K_DIV_REG (GLB_CTL_BASE + 0x70) +#define GLB_CTL_TCXO_DIV_REG (GLB_CTL_BASE + 0x74) /* 24M/40M div reg */ +#define GLB_CTL_AON_PERP_CLKSEL_W_REG (GLB_CTL_BASE + 0x90) +#define GLB_CTL_RC_32K_TCXO_SEL_REG (GLB_CTL_BASE + 0x94) +#define GLB_CTL_AON_32K_SEL_REG (GLB_CTL_BASE + 0x98) +#define GLB_CTL_USB_BUS_CLK_SEL_REG (GLB_CTL_BASE + 0x9C) +#define GLB_CTL_SYS_TICK_CFG_REG (GLB_CTL_BASE + 0xC0) /* systick */ +#define GLB_CTL_SYS_TICK_VALUE_0_REG (GLB_CTL_BASE + 0xD0) +#define GLB_CTL_SYS_TICK_VALUE_1_REG (GLB_CTL_BASE + 0xD4) +#define GLB_CTL_SYS_TICK_VALUE_2_REG (GLB_CTL_BASE + 0xD8) +#define GLB_CTL_SYS_TICK_VALUE_3_REG (GLB_CTL_BASE + 0xDC) +#define GLB_CTL_CLKMUX_STS_REG (GLB_CTL_BASE + 0x110) +#define GLB_CTL_DEBUG_CLKEN_REG (GLB_CTL_BASE + 0x170) +#define GLB_CTL_SOFT_INT_EN_REG (GLB_CTL_BASE + 0x280) +#define GLB_CTL_SOFT_INT_SET_REG (GLB_CTL_BASE + 0x284) +#define GLB_CTL_SOFT_INT_CLR_REG (GLB_CTL_BASE + 0x288) +#define GLB_CTL_SOFT_INT_STS_REG (GLB_CTL_BASE + 0x28C) +#define GLB_CTL_INT_SEL_REG (GLB_CTL_BASE + 0x290) +#define GLB_CTL_PAD_IO_SDIO_SR_CFG_REG (GLB_CTL_BASE + 0x2FC) +#define GLB_CTL_PAD_SDIO_CFG0_REG (GLB_CTL_BASE + 0x300) +#define GLB_CTL_PAD_SDIO_CFG1_REG (GLB_CTL_BASE + 0x304) +#define GLB_CTL_PAD_IO_SYSLDO_CFG0_REG (GLB_CTL_BASE + 0x310) +#define GLB_CTL_PAD_IO_SYSLDO_CFG1_REG (GLB_CTL_BASE + 0x314) +#define GLB_CTL_PAD_IO_SYSLDO_CFG2_REG (GLB_CTL_BASE + 0x31C) +#define GLB_CTL_PAD_MAN_CFG_0_REG (GLB_CTL_BASE + 0x320) +#define GLB_CTL_PAD_MAN_CFG_1_REG (GLB_CTL_BASE + 0x324) +#define GLB_CTL_PAD_OEN_CFG_0_REG (GLB_CTL_BASE + 0x328) +#define GLB_CTL_PAD_OEN_CFG_1_REG (GLB_CTL_BASE + 0x32C) +#define GLB_CTL_PAD_VALUE_CFG_0_REG (GLB_CTL_BASE + 0x330) +#define GLB_CTL_PAD_VALUE_CFG_1_REG (GLB_CTL_BASE + 0x334) +#define GLB_CTL_PAD_VALUE_0_REG (GLB_CTL_BASE + 0x338) +#define GLB_CTL_PAD_VALUE_1_REG (GLB_CTL_BASE + 0x33C) +#define GLB_CTL_PAD_PINMUX_CFG0_REG (GLB_CTL_BASE + 0x350) +#define GLB_CTL_PAD_PINMUX_CFG1_REG (GLB_CTL_BASE + 0x354) +#define GLB_CTL_REFCLK_FEQ_STATUS_REG (GLB_CTL_BASE + 0x358) +#define GLB_CTL_EXT_TSF_CLK_PERIOD_H_REG (GLB_CTL_BASE + 0x414) +#define GLB_CTL_EXT_TSF_CLK_PERIOD_L_REG (GLB_CTL_BASE + 0x418) +#define GLB_CTL_EFUSE_WR_DATA0_REG (GLB_CTL_BASE + 0x700) +#define GLB_CTL_EFUSE_WR_DATA1_REG (GLB_CTL_BASE + 0x704) +#define GLB_CTL_EFUSE_WR_DATA2_REG (GLB_CTL_BASE + 0x708) +#define GLB_CTL_EFUSE_WR_DATA3_REG (GLB_CTL_BASE + 0x70C) +#define GLB_CTL_EFUSE_WR_DATA4_REG (GLB_CTL_BASE + 0x710) +#define GLB_CTL_EFUSE_WR_DATA5_REG (GLB_CTL_BASE + 0x714) +#define GLB_CTL_EFUSE_WR_DATA6_REG (GLB_CTL_BASE + 0x718) +#define GLB_CTL_EFUSE_WR_DATA7_REG (GLB_CTL_BASE + 0x71C) +#define GLB_CTL_EFUSE_WR_DATA8_REG (GLB_CTL_BASE + 0x720) +#define GLB_CTL_EFUSE_WR_DATA9_REG (GLB_CTL_BASE + 0x724) +#define GLB_CTL_EFUSE_WR_DATA10_REG (GLB_CTL_BASE + 0x728) +#define GLB_CTL_EFUSE_WR_DATA11_REG (GLB_CTL_BASE + 0x72C) +#define GLB_CTL_EFUSE_WR_DATA12_REG (GLB_CTL_BASE + 0x730) +#define GLB_CTL_EFUSE_WR_DATA13_REG (GLB_CTL_BASE + 0x734) +#define GLB_CTL_EFUSE_WR_DATA14_REG (GLB_CTL_BASE + 0x738) +#define GLB_CTL_EFUSE_WR_DATA15_REG (GLB_CTL_BASE + 0x73C) +#define GLB_CTL_EFUSE_RD_DATA0_REG (GLB_CTL_BASE + 0x740) +#define GLB_CTL_EFUSE_RD_DATA1_REG (GLB_CTL_BASE + 0x744) +#define GLB_CTL_EFUSE_RD_DATA2_REG (GLB_CTL_BASE + 0x748) +#define GLB_CTL_EFUSE_RD_DATA3_REG (GLB_CTL_BASE + 0x74C) +#define GLB_CTL_EFUSE_RD_DATA4_REG (GLB_CTL_BASE + 0x750) +#define GLB_CTL_EFUSE_RD_DATA5_REG (GLB_CTL_BASE + 0x754) +#define GLB_CTL_EFUSE_RD_DATA6_REG (GLB_CTL_BASE + 0x758) +#define GLB_CTL_EFUSE_RD_DATA7_REG (GLB_CTL_BASE + 0x75C) +#define GLB_CTL_EFUSE_RD_DATA8_REG (GLB_CTL_BASE + 0x760) +#define GLB_CTL_EFUSE_RD_DATA9_REG (GLB_CTL_BASE + 0x764) +#define GLB_CTL_EFUSE_RD_DATA10_REG (GLB_CTL_BASE + 0x768) +#define GLB_CTL_EFUSE_RD_DATA11_REG (GLB_CTL_BASE + 0x76C) +#define GLB_CTL_EFUSE_RD_DATA12_REG (GLB_CTL_BASE + 0x770) +#define GLB_CTL_EFUSE_RD_DATA13_REG (GLB_CTL_BASE + 0x774) +#define GLB_CTL_EFUSE_RD_DATA14_REG (GLB_CTL_BASE + 0x778) +#define GLB_CTL_EFUSE_RD_DATA15_REG (GLB_CTL_BASE + 0x77C) +#define GLB_CTL_EFUSE_CLK_SEL_REG (GLB_CTL_BASE + 0x780) +#define GLB_CTL_EFUSE_CTL_REG (GLB_CTL_BASE + 0x784) +#define GLB_CTL_EFUSE_SOFT_RST_REG (GLB_CTL_BASE + 0x788) +#define GLB_CTL_CALI_32K_TCXO_CTL_REG (GLB_CTL_BASE + 0x800) +#define GLB_CTL_CALI_32K_TCXO_CNT_L_REG (GLB_CTL_BASE + 0x810) +#define GLB_CTL_CALI_32K_TCXO_CNT_H_REG (GLB_CTL_BASE + 0x814) +#define GLB_CTL_CALI_32K_TCXO_RESULT_L_REG (GLB_CTL_BASE + 0x818) +#define GLB_CTL_CALI_32K_TCXO_RESULT_H_REG (GLB_CTL_BASE + 0x81C) +#define GLB_CTL_AON_ICM_PRIORITY_REG (GLB_CTL_BASE + 0xF30) +#define GLB_CTL_MEM_CLK_FORCE_ON_REG (GLB_CTL_BASE + 0xF50) +#define GLB_CTL_MARGIN_ADJ_REG (GLB_CTL_BASE + 0xF54) +#define GLB_CTL_POR_RESET_REG (GLB_CTL_BASE + 0xF70) +#define GLB_CTL_UTMI_RESET_REG (GLB_CTL_BASE + 0xF74) +#define GLB_CTL_PHY_BIST_CTL_REG (GLB_CTL_BASE + 0xF78) +#define GLB_CTL_PHY_BIST_STS_REG (GLB_CTL_BASE + 0xF7C) +#define GLB_CTL_USB_REFCLK_CFG_REG (GLB_CTL_BASE + 0xF80) +#define GLB_CTL_DEFAULT_SLV_EN_REG (GLB_CTL_BASE + 0xF84) +#define GLB_CTL_DEFAULT_SLV_HIT_STATUS_REG (GLB_CTL_BASE + 0xF88) +#define GLB_CTL_DEFAULT_SLV_HIT_CLR_REG (GLB_CTL_BASE + 0xF8C) +#define GLB_CTL_REFCLK_FEQ_START_BIT 0 +#define GLB_CTL_REFCLK_FEQ_BITS 1 + +/* PMU CMU */ +#define PMU_CMU_CTL_BASE 0x50002000 +#define PMU_CMU_CTL_GP_REG0_REG (PMU_CMU_CTL_BASE + 0x010) +#define PMU_CMU_CTL_GP_REG1_REG (PMU_CMU_CTL_BASE + 0x014) +#define PMU_CMU_CTL_GP_REG2_REG (PMU_CMU_CTL_BASE + 0x018) +#define PMU_CMU_CTL_GP_REG3_REG (PMU_CMU_CTL_BASE + 0x01C) +#define PMU_CMU_CTL_UDSLEEP_BUTTON_CTRL_REG (PMU_CMU_CTL_BASE + 0x020) +#define PMU_CMU_CTL_UDSLEEP_BUTTON_RPT_REG (PMU_CMU_CTL_BASE + 0x024) +#define PMU_CMU_CTL_UDSLEEP_BUTTON_INT_EN_REG (PMU_CMU_CTL_BASE + 0x028) +#define PMU_CMU_CTL_FUSE_L_REG (PMU_CMU_CTL_BASE + 0x040) +#define PMU_CMU_CTL_FUSE_H_REG (PMU_CMU_CTL_BASE + 0x044) +#define PMU_CMU_CTL_FUSE_L_MAN_REG (PMU_CMU_CTL_BASE + 0x050) +#define PMU_CMU_CTL_FUSE_H_MAN_REG (PMU_CMU_CTL_BASE + 0x054) +#define PMU_CMU_CTL_FUSE_L_SEL_REG (PMU_CMU_CTL_BASE + 0x058) +#define PMU_CMU_CTL_FUSE_H_SEL_REG (PMU_CMU_CTL_BASE + 0x05C) +#define PMU_CMU_CTL_AON_PERP_CLKSEL_W_REG (PMU_CMU_CTL_BASE + 0x090) +#define PMU_CMU_CTL_PMU_MAN_CLR_0_REG (PMU_CMU_CTL_BASE + 0x104) +#define PMU_CMU_CTL_PMU_DBG_1_REG (PMU_CMU_CTL_BASE + 0x130) +#define PMU_CMU_CTL_PMU_DBG_SEL_1_REG (PMU_CMU_CTL_BASE + 0x134) +#define PMU_CMU_CTL_PMU_MAN_SEL_2 (PMU_CMU_CTL_BASE + 0x14C) +#define PMU_CMU_CTL_SYSLDO_CFG_0_REG (PMU_CMU_CTL_BASE + 0x200) +#define PMU_CMU_CTL_CLDO_CFG_0_REG (PMU_CMU_CTL_BASE + 0x208) +#define PMU_CMU_CTL_CLDO_CFG_1_REG (PMU_CMU_CTL_BASE + 0x20C) +#define PMU_CMU_CTL_VSET_AUTO_REG (PMU_CMU_CTL_BASE + 0x210) +#define PMU_CMU_CTL_VBATD_CFG_REG (PMU_CMU_CTL_BASE + 0x214) +#define PMU_CMU_CTL_PHYLDO_CFG_0_REG (PMU_CMU_CTL_BASE + 0x218) +#define PMU_CMU_CTL_PHYLDO_CFG_1_REG (PMU_CMU_CTL_BASE + 0x21C) +#define PMU_CMU_CTL_RFLDO1_CFG_0_REG (PMU_CMU_CTL_BASE + 0x220) +#define PMU_CMU_CTL_RFLDO1_CFG_1_REG (PMU_CMU_CTL_BASE + 0x224) +#define PMU_CMU_CTL_RFLDO2_CFG_0_REG (PMU_CMU_CTL_BASE + 0x228) +#define PMU_CMU_CTL_RFLDO2_CFG_1_REG (PMU_CMU_CTL_BASE + 0x22C) +#define PMU_CMU_CTL_RFLDO3_CFG_0_REG (PMU_CMU_CTL_BASE + 0x230) +#define PMU_CMU_CTL_RFLDO3_CFG_1_REG (PMU_CMU_CTL_BASE + 0x234) +#define PMU_CMU_CTL_RFLDO4_CFG_0_REG (PMU_CMU_CTL_BASE + 0x238) +#define PMU_CMU_CTL_RFLDO4_CFG_1_REG (PMU_CMU_CTL_BASE + 0x23c) +#define PMU_CMU_CTL_RFLDO5_CFG_0_REG (PMU_CMU_CTL_BASE + 0x240) +#define PMU_CMU_CTL_RFLDO5_CFG_1_REG (PMU_CMU_CTL_BASE + 0x244) +#define PMU_CMU_CTL_RFLDO6_CFG_0_REG (PMU_CMU_CTL_BASE + 0x248) +#define PMU_CMU_CTL_RFLDO6_CFG_1_REG (PMU_CMU_CTL_BASE + 0x24c) +#define PMU_CMU_CTL_EN_XLDO_CFG_0_REG (PMU_CMU_CTL_BASE + 0x250) +#define PMU_CMU_CTL_EN_XLDO_CFG_1_REG (PMU_CMU_CTL_BASE + 0x254) +#define PMU_CMU_CTL_EN_XLDO_CFG_2_REG (PMU_CMU_CTL_BASE + 0x258) +#define PMU_CMU_CTL_FLASHLDO_CFG_0_REG (PMU_CMU_CTL_BASE + 0x25c) +#define PMU_CMU_CTL_FLASHLDO_CFG_1_REG (PMU_CMU_CTL_BASE + 0x260) +#define PMU_CMU_CTL_PMU_MISC_CFG_0_REG (PMU_CMU_CTL_BASE + 0x270) +#define PMU_CMU_CTL_PMU_MISC_CFG_1_REG (PMU_CMU_CTL_BASE + 0x274) +#define PMU_CMU_CTL_PMU_MISC_CFG_2_REG (PMU_CMU_CTL_BASE + 0x278) +#define PMU_CMU_CTL_PMU_MISC_CFG_3_REG (PMU_CMU_CTL_BASE + 0x27c) +#define PMU_CMU_CTL_BUCK_VSET_REG (PMU_CMU_CTL_BASE + 0x280) +#define PMU_CMU_CTL_BUCK_CFG_0_REG (PMU_CMU_CTL_BASE + 0x284) +#define PMU_CMU_CTL_BUCK_CFG_1_REG (PMU_CMU_CTL_BASE + 0x288) +#define PMU_CMU_CTL_BUCK_CFG_2_REG (PMU_CMU_CTL_BASE + 0x28c) +#define PMU_CMU_CTL_BUCK_CFG_3_REG (PMU_CMU_CTL_BASE + 0x290) +#define PMU_CMU_CTL_VBAT_TH_CFG_REG (PMU_CMU_CTL_BASE + 0x294) + +#define PMU_CMU_CTL_PMU_STATUS_RAW_REG (PMU_CMU_CTL_BASE + 0x300) +#define PMU_CMU_CTL_PMU_STATUS_GRM_STICK_CLR_REG (PMU_CMU_CTL_BASE + 0x328) +#define PMU_CMU_CTL_PMU_STATUS_GRM_TIME_REG (PMU_CMU_CTL_BASE + 0x330) +#define PMU_CMU_CTL_PMU_STATUS_GRM_TIME1_REG (PMU_CMU_CTL_BASE + 0x334) +#define PMU_CMU_CTL_PMU_STATUS_GRM_INT_EN_REG (PMU_CMU_CTL_BASE + 0x344) +#define PMU_CMU_CTL_GATE_TSENSOR_VDDIO_REG (PMU_CMU_CTL_BASE + 0x350) +#define PMU_CMU_CTL_BUCK_SLEEP3_REG (PMU_CMU_CTL_BASE + 0x364) +#define PMU_CMU_CTL_CMU_DBG_SEL_REG (PMU_CMU_CTL_BASE + 0x414) +#define PMU_CMU_CTL_CLK_480M_GT_REG (PMU_CMU_CTL_BASE + 0x420) +#define PMU_CMU_CTL_CLK_192M_GT_REG (PMU_CMU_CTL_BASE + 0x42C) +#define PMU_CMU_CTL_CLK_960M_GT_REG (PMU_CMU_CTL_BASE + 0x430) +#define PMU_CMU_CTL_REFDIV_REG (PMU_CMU_CTL_BASE + 0x500) +#define PMU_CMU_CTL_FBDIV_REG (PMU_CMU_CTL_BASE + 0x504) +#define PMU_CMU_CTL_FRAC_L_REG (PMU_CMU_CTL_BASE + 0x508) +#define PMU_CMU_CTL_FRAC_H_REG (PMU_CMU_CTL_BASE + 0x50C) +#define PMU_CMU_CTL_CMU_MISC_PD_REG (PMU_CMU_CTL_BASE + 0x514) +#define PMU_CMU_CTL_CMU_CLK_SEL_REG (PMU_CMU_CTL_BASE + 0x518) +#define PMU_CMU_CTL_CMU_STATUS_RAW_REG (PMU_CMU_CTL_BASE + 0x600) +#define PMU_CMU_CTL_SYS_STATUS_REG (PMU_CMU_CTL_BASE + 0x804) +#define PMU_CMU_CTL_WKUP_TIME_WLAN_EN_FLASH_REG (PMU_CMU_CTL_BASE + 0x810) +#define PMU_CMU_CTL_WKUP_TIME_WLAN_EN_PMU_REF2_REG (PMU_CMU_CTL_BASE + 0x814) +#define PMU_CMU_CTL_WKUP_TIME_WLAN_EN_PMU_REG (PMU_CMU_CTL_BASE + 0x818) +#define PMU_CMU_CTL_WKUP_TIME_WLAN_CMU_XLDO_EN_REG (PMU_CMU_CTL_BASE + 0x81C) +#define PMU_CMU_CTL_WKUP_TIME_WLAN_BUCK_EN_REG (PMU_CMU_CTL_BASE + 0x820) +#define PMU_CMU_CTL_WKUP_TIME_WLAN_EN_CLDO_REG (PMU_CMU_CTL_BASE + 0x824) +#define PMU_CMU_CTL_WKUP_TIME_WLAN_EN_RFLDO4_REG (PMU_CMU_CTL_BASE + 0x828) +#define PMU_CMU_CTL_WKUP_TIME_WLAN_SDIO_SUB_PWR_EN_REG (PMU_CMU_CTL_BASE + 0x838) +#define PMU_CMU_CTL_WKUP_TIME_WLAN_XO2PLL_BUF_PD_REG (PMU_CMU_CTL_BASE + 0x83C) +#define PMU_CMU_CTL_WKUP_TIME_WLAN_CMU_ISO_EN_REG (PMU_CMU_CTL_BASE + 0x840) +#define PMU_CMU_CTL_WKUP_TIME_WLAN_XLDO_VCO_GT_REG (PMU_CMU_CTL_BASE + 0x844) +#define PMU_CMU_CTL_WKUP_TIME_WLAN_TCXO2DBB_GT_REG (PMU_CMU_CTL_BASE + 0x848) +#define PMU_CMU_CTL_WKUP_TIME_WLAN_CLK_TCXO_EN_REG (PMU_CMU_CTL_BASE + 0x84C) +#define PMU_CMU_CTL_WKUP_TIME_WLAN_PD_REG (PMU_CMU_CTL_BASE + 0x854) +#define PMU_CMU_CTL_WKUP_TIME_WLAN_CLK_FON_REG (PMU_CMU_CTL_BASE + 0x858) +#define PMU_CMU_CTL_WKUP_TIME_WLAN_RST_RELEASE_REG (PMU_CMU_CTL_BASE + 0x85C) +#define PMU_CMU_CTL_WLAN_STA0_ALLOW_TO_SLEEP_REG (PMU_CMU_CTL_BASE + 0x900) +#define PMU_CMU_CTL_WLAN_STA1_ALLOW_TO_SLEEP_REG (PMU_CMU_CTL_BASE + 0x904) +#define PMU_CMU_CTL_WLAN_AP0_ALLOW_TO_SLEEP_REG (PMU_CMU_CTL_BASE + 0x908) +#define PMU_CMU_CTL_WLAN_PF_ALLOW_TO_SLEEP_REG (PMU_CMU_CTL_BASE + 0x90C) +#define PMU_CMU_CTL_WLAN_HOST_ALLOW_TO_SLEEP_REG (PMU_CMU_CTL_BASE + 0x910) +#define PMU_CMU_CTL_WLAN_SLP_EVT_EN_REG (PMU_CMU_CTL_BASE + 0x920) +#define PMU_CMU_CTL_WLAN_SLP_EVT_CLR_REG (PMU_CMU_CTL_BASE + 0x924) +#define PMU_CMU_CTL_WLAN_SLP_INT_CLR_REG (PMU_CMU_CTL_BASE + 0x934) +#define PMU_CMU_CTL_WLAN_WKUP_EVT_EN_REG (PMU_CMU_CTL_BASE + 0x940) +#define PMU_CMU_CTL_WLAN_WKUP_EVT_CLR_REG (PMU_CMU_CTL_BASE + 0x944) +#define PMU_CMU_CTL_WLAN_WKUP_EVT_STS_REG (PMU_CMU_CTL_BASE + 0x948) +#define PMU_CMU_CTL_WLAN_WKUP_INT_EN_REG (PMU_CMU_CTL_BASE + 0x950) +#define PMU_CMU_CTL_WLAN_WKUP_INT_CLR_REG (PMU_CMU_CTL_BASE + 0x954) +#define PMU_CMU_CTL_WLAN_WKUP_INT_STS_REG (PMU_CMU_CTL_BASE + 0x958) +#define PMU_CMU_CTL_DEBUG_GLB_SIGNAL_SEL_2_REG (PMU_CMU_CTL_BASE + 0xF24) + +#define CRG_REG_SC_PLLLOCK_STAT_REG (HI_CRG_REG_BASE + 0x0) +#define CRG_REG_SC_APLL_CTRL0_REG (HI_CRG_REG_BASE + 0x4) +#define CRG_REG_SC_APLL_CTRL1_REG (HI_CRG_REG_BASE + 0x8) +#define CRG_REG_SC_PERI_CLKEN0_REG (HI_CRG_REG_BASE + 0x14) +#define CRG_REG_SC_PERI_CLKEN1_REG (HI_CRG_REG_BASE + 0x18) +#define CRG_REG_SC_PERI_CLKSTAT0_REG (HI_CRG_REG_BASE + 0x1C) +#define CRG_REG_SC_PERI_CLKSTAT1_REG (HI_CRG_REG_BASE + 0x20) +#define CRG_REG_SC_PERI_CLKSEL_REG (HI_CRG_REG_BASE + 0x24) +#define CRG_REG_SC_PERI_SRST_REG (HI_CRG_REG_BASE + 0x28) +#define CRG_REG_SC_SLEEP0_CTRL_REG (HI_CRG_REG_BASE + 0x2C) + +#define CRG_REG_SC_PHY_CLK_EN_REG (HI_CRG_REG_BASE + 0x30) +#define CRG_REG_SC_PHY_SRST_REG (HI_CRG_REG_BASE + 0x34) +#define CRG_REG_SC_PHY_RST_MASK_REG (HI_CRG_REG_BASE + 0x38) +#define CRG_REG_MEM_TOP_GATE_EN_REG (HI_CRG_REG_BASE + 0x3C) +#define CRG_REG_BOOT_ROM_GATE_EN_REG (HI_CRG_REG_BASE + 0x40) +#define CRG_REG_SC_PHY_RST1_MASK_REG (HI_CRG_REG_BASE + 0x44) +#define CRG_REG_SC_SLEEP1_CTRL_REG (HI_CRG_REG_BASE + 0x48) + +#define CRG_REG_SC_DEEP_SLEEP0_CTRL_REG (HI_CRG_REG_BASE + 0x4C) + +#define CRG_REG_SC_DEEP_SLEEP1_CTRL_REG (HI_CRG_REG_BASE + 0x50) + +#define CRG_REG_SC_PERI_SRST1_REG (HI_CRG_REG_BASE + 0x54) +#define CRG_REG_SC_PHY1_SRST1_REG (HI_CRG_REG_BASE + 0x58) +#define CRG_REG_XTAL_IO_CTRL_REG (HI_CRG_REG_BASE + 0x5C) + +#define CRG_REG_SSP_SRST_REQ_LEN 1 +#define CRG_REG_SSP_SRST_REQ_OFFSET 7 +#define CRG_REG_SSP2_SRST_REQ_LEN 1 +#define CRG_REG_SSP2_SRST_REQ_OFFSET 5 +#define CRG_REG_I2C_SRST_REQ_LEN 1 +#define CRG_REG_I2C_SRST_REQ_OFFSET 12 +#define CRG_REG_SFC_SRST_REQ_LEN 1 +#define CRG_REG_SFC_SRST_REQ_OFFSET 2 +#define CRG_REG_SFC_BUS_CLK_EN_LEN 1 +#define CRG_REG_SFC_BUS_CLK_EN_OFFSET 17 +#define CRG_REG_SFC_CLK_EN_LEN 1 +#define CRG_REG_SFC_CLK_EN_OFFSET 16 + +#define SYSCTRL_SC_CTRL_REG (HI_SYSCTRL_REG_BASE + 0x0) +#define SYSCTRL_SC_SYSRES_REG (HI_SYSCTRL_REG_BASE + 0x4) +#define SYSCTRL_SC_IMCTRL_REG (HI_SYSCTRL_REG_BASE + 0x8) +#define SYSCTRL_SC_IMSTAT_REG (HI_SYSCTRL_REG_BASE + 0xC) +#define SYSCTRL_SC_XTALCTRL_REG (HI_SYSCTRL_REG_BASE + 0x10) +#define SYSCTRL_SC_PLLCTRL_REG (HI_SYSCTRL_REG_BASE + 0x14) +#define SYSCTRL_SC_AFE_CTRL_REG (HI_SYSCTRL_REG_BASE + 0x20) +#define SYSCTRL_SC_VERSION_ID_REG (HI_SYSCTRL_REG_BASE + 0x24) +#define SYSCTRL_SC_HW_ID_REG (HI_SYSCTRL_REG_BASE + 0x28) +#define SYSCTRL_SC_PERI_CTRL_REG (HI_SYSCTRL_REG_BASE + 0x2C) +#define SYSCTRL_SC_LOCKEN_REG (HI_SYSCTRL_REG_BASE + 0x38) +#define SYSCTRL_SC_PAD_CONFIG_REG (HI_SYSCTRL_REG_BASE + 0x3C) +#define SYSCTRL_SC_GEN_REG0_REG (HI_SYSCTRL_REG_BASE + 0x40) +#define SYSCTRL_SC_GEN_REG1_REG (HI_SYSCTRL_REG_BASE + 0x44) +#define SYSCTRL_SC_GEN_REG2_REG (HI_SYSCTRL_REG_BASE + 0x48) +#define SYSCTRL_SC_GEN_REG3_REG (HI_SYSCTRL_REG_BASE + 0x4C) +#define SYSCTRL_SC_GEN_REG4_REG (HI_SYSCTRL_REG_BASE + 0x50) +#define SYSCTRL_SC_GEN_REG5_REG (HI_SYSCTRL_REG_BASE + 0x54) +#define SYSCTRL_SC_GEN_REG6_REG (HI_SYSCTRL_REG_BASE + 0x58) +#define SYSCTRL_SC_GEN_REG7_REG (HI_SYSCTRL_REG_BASE + 0x5C) + +#define PKTB_MODE_NOT_CHANGE 0 +#define PKTB_MODE_32K 1 +#define PKTB_MODE_48K 2 +#define PKTB_MODE_64K 3 +#define PKTB_MODE_80K 4 +#define PKTB_MODE_96K 5 +#define PKTB_MODE_112K 6 +#define PKTB_MODE_128K 7 +#define PKTB_MODE_144K 8 +#define PKTB_MODE_160K 9 +#define PKTB_MODE_176K 10 +#define PKTB_MODE_192K 11 +#define PKTB_MODE_DEFAULT PKTB_MODE_64K + +/* DIAG CTL REG */ +#define DIAG_CTL_BASE 0x40060000 +#define DIAG_CTL_GP_REG0_REG (DIAG_CTL_BASE + 0x010) /* used to save rsa key */ +#define DIAG_CTL_GP_REG1_REG (DIAG_CTL_BASE + 0x014) /* used to save rsa key */ +#define DIAG_CTL_GP_REG2_REG (DIAG_CTL_BASE + 0x018) /* used to save ecc key */ +#define DIAG_CTL_GP_REG3_REG (DIAG_CTL_BASE + 0x01C) /* used to save ecc key */ +#define DIAG_CTL_DIAG_MUX (DIAG_CTL_BASE + 0x0BC) /* diag mux */ +#define DIAG_CTL_CLOCK_TEST_SEL (DIAG_CTL_BASE + 0x0D0) /* clock test div */ +#define DIAG_CTL_CLOCK_TEST_DIV (DIAG_CTL_BASE + 0x0D4) /* clock test div */ +#define DIAG_CTL_CLOCK_TEST_EN (DIAG_CTL_BASE + 0x0D8) /* clock test en */ + + +#endif /* __HI3861_PLATFORM_BASE_H */ diff --git a/sdk_liteos/include/hi_adc.h b/sdk_liteos/include/hi_adc.h new file mode 100644 index 0000000000000000000000000000000000000000..f5b62647fba79ace731a8c30f99b5775f6201c23 --- /dev/null +++ b/sdk_liteos/include/hi_adc.h @@ -0,0 +1,143 @@ +/** +* @file hi_adc.h +* +* Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +* 描述:Analog-to-digital conversion (ADC) module interface. +* @li Provides 8 ADC channels. +CNcomment:提供8个ADC通道,通道7为参考电压,不能adc转换。CNend +* @li LSADC reading rate is slow, please avoid used in interruption. +CNcomment: LSADC读数速率较慢,请避免在中断使用。CNend +* Author: Hisilicon \n +* Create: 2019-4-3 +*/ + +/** +* @defgroup iot_ls_adc ADC +* @ingroup drivers +*/ + +#ifndef __HI_ADC_H__ +#define __HI_ADC_H__ + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @ingroup iot_ls_adc + * + * channel ID。CNcomment:通道编号.CNend + */ +typedef enum { + HI_ADC_CHANNEL_0, + HI_ADC_CHANNEL_1, + HI_ADC_CHANNEL_2, + HI_ADC_CHANNEL_3, + HI_ADC_CHANNEL_4, + HI_ADC_CHANNEL_5, + HI_ADC_CHANNEL_6, + HI_ADC_CHANNEL_7, + HI_ADC_CHANNEL_BUTT, +} hi_adc_channel_index; + +/** + * @ingroup iot_ls_adc + * + * Analog power control. CNcomment:模拟电源控制。CNend + */ +typedef enum { + HI_ADC_CUR_BAIS_DEFAULT, /**< 0:Auto control. + CNcomment:自动识别模式 */ + HI_ADC_CUR_BAIS_AUTO, /**< 1:Auto control. + CNcomment:自动识别模式 */ + HI_ADC_CUR_BAIS_1P8V, /**< 2:Manual control, AVDD=1.8V. + CNcomment:手动控制,AVDD=1.8V */ + HI_ADC_CUR_BAIS_3P3V, /**< 3:Manual control, AVDD=3.3V. + CNcomment:手动控制,AVDD=3.3V */ + HI_ADC_CUR_BAIS_BUTT, +} hi_adc_cur_bais; + +/** + * @ingroup iot_ls_adc + * + * Average algorithm mode CNcoment:平均算法模式。CNend + */ +typedef enum { + HI_ADC_EQU_MODEL_1, /**< 0:The average value is not used. + CNcomment:1次平均,即不进行 + 平均 CNend */ + HI_ADC_EQU_MODEL_2, /**< 1:2-time average algorithm mode. + CNcomment:2次平均算法模式 CNend */ + HI_ADC_EQU_MODEL_4, /**< 2:4-time average algorithm mode. + CNcomment:4次平均算法模式 CNend */ + HI_ADC_EQU_MODEL_8, /**< 3:8-time average algorithm mode. + CNcomment:8次平均算法模式 CNend */ + HI_ADC_EQU_MODEL_BUTT, +} hi_adc_equ_model_sel; + +/** +* @ingroup iot_ls_adc +* @brief Read one data in single ADC channel. CNcomment:从一个ADC通道读一个数据。CNend +* +* @par 描述: +* Read one data in single ADC channel. +CNcomment:从一个ADC通道读一个数据。CNend +* +* @attention None +* @param channel [IN] type #hi_adc_channel_index,channel to be read. CNcomment:要读的channel。CNend +* @param data [OUT] type #hi_u16 * ,data point to store the data. +CNcomment:读取的ADC数据保存地址。CNend +* @param equ_model [IN] type #hi_adc_equ_model_sel ,Average algorithm mode. +CNcomment:平均算法模式。CNend +* @param cur_bais [IN] type #hi_adc_cur_bais ,Analog power control. +CNcomment:模拟电源控制。CNend +* @param delay_cnt [IN] type #hi_u16 ,Countings from config to start collect,One count is 334ns,[0, 0xFF0]. +CNcomment:从配置采样到启动采样的延时时间计数,一次计数是334ns,其值需在0~0xFF0之间。CNend +* @retval #HI_ERR_SUCCESS Success. +* @retval #Other Failure. See hi_errno.h for details. +* @par 依赖: +* @li hi_adc.h:Describes ADC APIs. +CNcomment:文件用于描述ADC相关接口。CNend +* @see hi_adc_read。 +*/ +hi_u32 hi_adc_read(hi_adc_channel_index channel, hi_u16 *data, hi_adc_equ_model_sel equ_model, + hi_adc_cur_bais cur_bais, hi_u16 delay_cnt); + + +/** +* @ingroup iot_ls_adc +* @brief Convert adc read data to voltage. CNcomment:将ADC读取到的码字转换为电压。CNend +* +* @par 描述: +* Convert adc read data to voltage. +CNcomment:将ADC读取到的码字转换为电压。CNend +* +* @attention None +* @param data [IN] type #hi_u16,data read by adc. CNcomment:ADC读取到的码字。CNend +* @retval votalge converted by data. CNcomment: 码字转换得到的电压。CNend +* @par 依赖: +* @li hi_adc.h:Describes ADC APIs. +CNcomment:文件用于描述ADC相关接口。CNend +* @see hi_adc_read。 +*/ +hi_float hi_adc_convert_to_voltage(hi_u16 data); + + +#ifdef __cplusplus +} +#endif +#endif diff --git a/sdk_liteos/include/hi_any_api.h b/sdk_liteos/include/hi_any_api.h new file mode 100644 index 0000000000000000000000000000000000000000..7e4b9e86dd61e32eab6b0ab573440fd4082dd1f2 --- /dev/null +++ b/sdk_liteos/include/hi_any_api.h @@ -0,0 +1,370 @@ +/* + * @file hi_any_api.h + * + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @defgroup hi_wifi_any ANY API + * @ingroup hi_wifi + */ + +#ifndef __HI_ANY_API_H__ +#define __HI_ANY_API_H__ + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif + +/** + * @ingroup hi_wifi_any + * + * Max length of data for a single ANY transmit.CNcomment:单次ANY发送允许的最大数据长度。CNend + */ +#define WIFI_ANY_MAX_USER_DATA 250 +/** + * @ingroup hi_wifi_any + * + * Length of key in octets used in ANY communication.CNcomment:ANY加密通信的密钥长度,固定为16字节。CNend + */ +#define WIFI_ANY_KEY_LEN 16 +/** + * @ingroup hi_wifi_any + * + * Length of MAC address.CNcomment:MAC地址长度定义CNend + */ +#define WIFI_ANY_MAC_LEN 6 +/** + * @ingroup hi_wifi_any + * + * Max length of wlan ssid(for driver).CNcomment:wifi驱动SSID最大长度,+1为\0预留空间CNend + */ +#define WIFI_ANY_MAX_SSID_LEN (32 + 1) + +/** + * @ingroup hi_wifi_any + * + * Struct of peer's information.CNcomment:用户向驱动配置的对端设备信息数据CNend + */ +typedef struct { + unsigned char mac[WIFI_ANY_MAC_LEN]; /**< the MAC address for peer device. */ + /**< CNcomment: 收发操作的对端MAC地址 */ + unsigned char channel; /**< the channel number of peer device,the value + 0xFF means current channel. */ + /**< CNcomment: 对端所在信道号,驱动对该信息仅做存储,0xFF表示当前信道 */ + bool has_key; /**< whether need key for packet encryption,if true,key shall be specified. */ + /**< CNcomment: 是否配置通信密钥,是则填true,并在key中传入密钥,否则填false */ + unsigned char key[WIFI_ANY_KEY_LEN]; /**< the key for packet encryption,it consists of 16 bytes. */ + /**< CNcomment: 用于加密通信的密钥,填充的密钥固定为16字节长度 */ +} hi_wifi_any_peer_info; + +/** + * @ingroup hi_wifi_any + * + * Struct of information of ANY device discovered.CNcomment:扫描发现的ANY设备的参数定义CNend + */ +typedef struct { + unsigned char bssid[WIFI_ANY_MAC_LEN]; /**< the MAC address of peer device. */ + /**< CNcomment: BSSID,若对端为STA则为其MAC地址 */ + unsigned char channel; /**< the channel number of peer device. */ + /**< CNcomment: 信道号,取值范围1-14,不同区域取值范围有差异 */ + unsigned char sta_flag; /**< if peer device is a STA,the value is true,otherwise false. */ + /**< CNcomment: true表示对端是STA,否则为普通AP */ + unsigned char ssid[WIFI_ANY_MAX_SSID_LEN]; /**< SSID. *//**< CNcomment: SSID */ + unsigned char ssid_len; /**< the string length of SSID. *//**< CNcomment: SSID字符串长度 */ + char rssi; /**< RSSI value of peer device. *//**< CNcomment: 信号强度 */ + unsigned char resv; /**< Reserved. *//**< CNcomment: 保留 */ +} hi_wifi_any_device; + +/** +* @ingroup hi_wifi_any +* @brief Callback function invoked when ANY scan is finished.CNcomment:ANY扫描完成回调函数CNend +* +* @par Description: +* When registered,the driver uses this callback to deliver ANY devices found after an ANY scan. \n +* CNcomment:注册该回调函数之后,驱动每次完成ANY扫描调用该接口反馈结果给上层.CNend +* +* @attention 1. This function is called in driver context,should not be blocked or do long time waiting.\n + CNcomment:1. 该回调函数运行于驱动线程,不能阻塞或长时间等待.CNend \n +* 2. The memories of are requested and freed by the driver automatically.\n +* CNcomment:2. 由驱动申请内存,也由驱动释放,回调中不应释放.CNend +* @param devices [IN] Type #hi_wifi_any_device *, array of poniter of ANY devices found.CNcomment:发现的ANY设备信息, +* 该参数为指针类型的数组。CNend +* @param num [IN] Type #unsigned char, the number of ANY devices found, maximum is 32.CNcomment:发现的设备数量, +* 最大不超过32.CNend +* +* @retval #void no return value.CNcomment:无返回值.CNend +* @par Dependency: +* @li hi_any_api.h: ANY API +* @see hi_wifi_any_discover_peer +*/ +typedef void (*hi_wifi_any_scan_result_cb)(hi_wifi_any_device *devices[], unsigned char num); + +/** +* @ingroup hi_wifi_any +* @brief Callback function for ANY RX.CNcomment:ANY驱动接收回调函数CNend +* +* @par Description: +* When registered,the driver uses this callback to deliver data received. \n +* CNcomment:注册该回调函数之后,驱动收到ANY报文则调用该回调函数传递给上层应用.CNend +* +* @attention 1. This function is called in driver context,should not be blocked or do long time waiting.\n + CNcomment:1. 该回调函数运行于驱动线程,不能阻塞或长时间等待.CNend\n +* 2. The memories of and are requested and freed by the driver.\n +* CNcomment:2. 由驱动申请内存,也由驱动释放,回调中不应释放.CNend +* @param mac [IN] Type #unsigned char *, MAC address with 6 octets length.CNcomment:6字节长度MAC地址.CNend +* @param data [IN] Type #unsigned char *, the address of data received.CNcomment:接收到数据的缓存地址.CNend +* @param len [IN] Type #unsigned short, the length in octet of data received.CNcomment:接收的数据长度, +* 最大为250字节.CNend +* @param seqnum [IN] Type #unsigned char, the sequence number of the ANY frame, range [0-255]. +* CNcomment:接收到的ANY帧的序列号,范围0-255.CNend +* +* @retval #void no return value.CNcomment:无返回值.CNend +* @par Dependency: +* @li hi_any_api.h: ANY API +* @see hi_wifi_any_set_callback +*/ +typedef void (*hi_wifi_any_recv_cb)(unsigned char *mac, unsigned char *data, unsigned short len, unsigned char seqnum); + +/** +* @ingroup hi_wifi_any +* @brief Callback function for ANY TX.CNcomment:ANY驱动发送回调函数CNend +* +* @par Description: +* When registered,the driver uses this callback to notify whether an ACK has received. \n +* CNcomment:注册该回调函数之后,驱动将发送结果(是否收到ACK)反馈给上层应用.CNend +* +* @attention 1. This function is called in driver context,should not be blocked or do long time waiting.\n + CNcomment:1. 该回调函数运行于驱动线程,不能阻塞或长时间等待.CNend \n +* 2. The memories of are requested and freed by the driver.\n +* CNcomment:2. 由驱动申请内存,也由驱动释放,回调中不应释放.CNend +* @param mac [IN] Type #unsigned char *, MAC address with 6 octets length.CNcomment:6字节长度MAC地址.CNend +* @param status [IN] Type #unsigned char, the result of a single transmit,return 1 if transmitted successfully. + CNcomment:单次发送的结果, 值为1代表发送成功,其他值代表发送失败.CNend +* @param seqnum [IN] Type #unsigned char, the sequence number of the ANY frame, range [0-255]. +* CNcomment:接收到的ANY帧的序列号,范围0-255.CNend +* +* @retval #void no return value.CNcomment:无返回值.CNend +* @par Dependency: +* @li hi_any_api.h: ANY API +* @see hi_wifi_any_set_callback +*/ +typedef void (*hi_wifi_any_send_complete_cb)(unsigned char *mac, unsigned char status, unsigned char seqnum); + +/** + * @ingroup hi_wifi_any + * + * Struct of ANY callback function.CNcomment:ANY收发回调接口定义CNend + */ +typedef struct { + hi_wifi_any_send_complete_cb send_cb; /**< the callback function invoked when an ANY frame is sent. */ + /**< CNcomment: ANY发送完成驱动回调函数,用于将驱动发送结果反馈给上层 */ + hi_wifi_any_recv_cb recv_cb; /**< the callback function invoked when an ANY frame is received. */ + /**< CNcomment: ANY接收数据驱动回调函数,用于将驱动接收的数据传递给上层 */ +} hi_wifi_any_callback; + +/** +* @ingroup hi_wifi_any +* @brief Use this funtion to initialize ANY feature.CNcomment:ANY功能初始化函数CNend +* +* @par Description: +* Use this funtion to initialize ANY feature.CNcomment:ANY功能初始化函数CNend +* +* @attention A device shall be intialized only once, do de-initialzing first before perform a new initialization.\n + CNcomment:一个设备只允许一次初始化,重新初始化之前需要先调用去ANY初始化.CNend \n +* @param seqnum [IN] Type #const char *, the interface name used to TX/RX ANY frames, eg.wlan0/ap0/mesh0. +* CNcomment:用于收发ANY报文的接口名称,常用值为"wlan0","ap0"或"mesh0".CNend +* +* @retval #HISI_OK Excute successfully +* @retval #Other Error code +* @par Dependency: +* @li hi_any_api.h: ANY API +* @see NULL +*/ +int hi_wifi_any_init(const char *ifname); + +/** +* @ingroup hi_wifi_any +* @brief Use this funtion to de-initialize ANY feature.CNcomment:ANY功能去初始化函数CNend +* +* @par Description: +* Use this funtion to de-initialize ANY feature.CNcomment:ANY功能去初始化函数CNend +* +* @attention NULL +* @param NULL +* +* @retval #HISI_OK Excute successfully +* @retval #Other Error code +* @par Dependency: +* @li hi_any_api.h: ANY API +* @see NULL +*/ +int hi_wifi_any_deinit(void); + +/** +* @ingroup hi_wifi_any +* @brief Register callback functions for ANY TX and RX.CNcomment:注册ANY驱动发送回调函数和接收回调函数CNend +* +* @par Description: +* Register callback functions for ANY TX and RX.CNcomment:注册ANY驱动发送回调函数和接收回调函数CNend +* +* @attention APP shall implement the TX/RX callbacks and register them to driver through this function.\n + CNcomment:需要用户自己实现该回调函数功能并通过上述接口注册给驱动.CNend +* @param send_cb [IN] Type #hi_wifi_any_send_complete_cb, callback function for ANY TX. +* CNcomment:ANY驱动发送回调函数.CNend +* @param recv_cb [IN] Type #hi_wifi_any_recv_cb, callback function for ANY RX. +* CNcomment:ANY驱动接收回调函数.CNend +* +* @retval #void no return value.CNcomment:无返回值.CNend +* @par Dependency: +* @li hi_any_api.h: ANY API +* @see hi_wifi_any_send_complete_cb | hi_wifi_any_recv_cb +*/ +void hi_wifi_any_set_callback(hi_wifi_any_send_complete_cb send_cb, hi_wifi_any_recv_cb recv_cb); + +/** +* @ingroup hi_wifi_any +* @brief Send ANY frame to specific mac address.CNcomment:向指定MAC地址的设备发送ANY数据。CNend +* +* @par Description: +* Frame TX interface of ANY, specify frame's sequece number by seq. \n +* the mac_len shall be constant 6 and data_len for a frame should not exceed 250 octets. \n +* CNcomment:ANY报文发送接口,可以通过seq指定该报文的发送序列号。\n +* 其中MAC地址长度固定填6字节,待发送的数据长度data_len不能超过250字节 CNend +* +* @attention The memories of and are requested and freed by user APP.\n +* CNcomment:内存由用户申请和管理,执行完成后驱动不会释放.CNend +* @param mac [IN] Type #const unsigned char *, destination MAC address, it may be unicast or broadcast. +* CNcomment:6字节长度目的MAC地址, 可为单播或者广播地址, 不支持组播地址.CNend +* @param mac_len [IN] Type #unsigned char, length of MAC address which shall be 6 in octet. +* CNcomment:MAC地址长度, 需为6字节.CNend +* @param data [IN] Type #unsigned char *, the address of data.CNcomment:待发送数据的缓存地址.CNend +* @param len [IN] Type #unsigned short, the length in octet of data, maximum is 250. +* CNcomment:待发送的数据长度, 最大为250字节.CNend +* @param seqnum [IN] Type #unsigned char, the sequence number of the ANY frame, range [0-255]. +* CNcomment:待发送的ANY帧的序列号,范围0-255.CNend +* +* @retval #HISI_OK Excute successfully +* @retval #Other Error code +* @par Dependency: +* @li hi_any_api.h: ANY API +* @see hi_wifi_any_send_complete_cb +*/ +int hi_wifi_any_send(const unsigned char *mac, unsigned char mac_len, unsigned char *data, + unsigned short data_len, unsigned char seq); + +/** +* @ingroup hi_wifi_any +* @brief Add information of ANY peer device.CNcomment:添加ANY对端设备信息。CNend +* +* @par Description: +* Add information of ANY peer device(mac address, channel and key). \n +* the number of peer devices must not exceed 16, among which the encrypted must not exceed 6. \n +* CNcomment:添加对端设备的MAC地址,所在信道信息和用于加密通信的密钥。\n +* 对端设备总数最多16个,其中加密通信的对端个数最多6个。CNend +* +* @attention 1. The driver just stores the channels of peer devices.\n +* It will not switch to a channel automatically which differs with the current channel. \n +* CNcomment:1. 驱动仅保存对端设备的信道号,通信过程不会自动切到对应信道.CNend \n +* 2. The memories of are requested and freed by user APP.\n +* CNcomment:2. 内存由用户管理,驱动接口中不会释放.CNend +* @param peer_info [IN] Type #hi_wifi_any_peer_info *, information of peer device. +* CNcomment:对端设备的信息.CNend +* +* @retval #HISI_OK Excute successfully +* @retval #Other Error code +* @par Dependency: +* @li hi_any_api.h: ANY API +* @see NULL +*/ +int hi_wifi_any_add_peer(const hi_wifi_any_peer_info *peer_info); + +/** +* @ingroup hi_wifi_any +* @brief Delete specific peer device.CNcomment:删除指定MAC地址的对端设备信息。CNend +* +* @par Description: +* Delete peer device specified by MAC address, the should be constant 6. \n +* CNcomment:删除指定MAC地址的对端设备信息,MAC地址长度需固定填6字节。CNend +* +* @attention The memories of are requested and freed by user APP. \n +* CNcomment:内存由用户申请和管理,执行完成后驱动不会释放.CNend +* @param mac [IN] Type #const unsigned char *, peer device's MAC address. +* CNcomment:待删除的对端设备的MAC地址.CNend +* @param len [IN] Type #unsigned char, length of MAC address which shall be constant 6. +* CNcomment:对端设备的MAC地址长度,固定填6字节.CNend +* +* @retval #HISI_OK Excute successfully +* @retval #Other Error code +* @par Dependency: +* @li hi_any_api.h: ANY API +* @see NULL +*/ +int hi_wifi_any_del_peer(const unsigned char *mac, unsigned char len); + +/** +* @ingroup hi_wifi_any +* @brief Get ANY peer device's information by index.CNcomment:获取指定索引的对端设备信息。CNend +* +* @par Description: +* Get ANY peer device's information by index.Index starts from 0 and should not exceed 15. \n +* CNcomment:获取指定索引的对端设备信息。其中传入的index从0开始指定查询第几个对端,最大不能超过15。CNend +* +* @attention The memories of are requested and freed by user APP. \n +* CNcomment:内存由用户申请和管理,由驱动填充查询到的信息.CNend +* @param index [IN] Type #unsigned char, peer device's index, start from 0. +* CNcomment:待查询的对端设备的索引,从0开始.CNend +* @param peer [OUT] Type #hi_wifi_any_peer_info *, peer device's information. +* CNcomment:查询到的对端设备的信息.CNend +* +* @retval #HISI_OK Excute successfully +* @retval #Other Error code +* @par Dependency: +* @li hi_any_api.h: ANY API +* @see NULL +*/ +int hi_wifi_any_fetch_peer(unsigned char index, hi_wifi_any_peer_info *peer); + +/** +* @ingroup hi_wifi_any +* @brief Start ANY scan and register callback to handle scan results. \n +* CNcomment:发起ANY扫描并注册回调函数处理扫描完成之后的结果。CNend +* +* @par Description: +* Start ANY scan and register callback to handle scan results. \n +* The limit to the number of peers discoverd is 32 for a single scan. \n +* CNcomment:发起ANY扫描并注册回调函数处理扫描完成之后的结果,单次扫描最多返回32个对端设备信息。CNend +* +* @attention NULL +* @param p_fn_cb [IN] Type #hi_wifi_any_scan_result_cb, callback function to handle scan results. +* CNcomment:由用户实现的回调函数, 扫描完成之后驱动调用该回调处理扫描结果.CNend +* +* @retval #HISI_OK Excute successfully +* @retval #Other Error code +* @par Dependency: +* @li hi_any_api.h: ANY API +* @see hi_wifi_any_scan_result_cb +*/ +int hi_wifi_any_discover_peer(hi_wifi_any_scan_result_cb p_fn_cb); + +#ifdef __cplusplus +#if __cplusplus + } +#endif +#endif + +#endif /* end of hi_any_api.h */ + diff --git a/sdk_liteos/include/hi_at.h b/sdk_liteos/include/hi_at.h new file mode 100644 index 0000000000000000000000000000000000000000..33098809fa68938b3015c6abba0ea80bf6244007 --- /dev/null +++ b/sdk_liteos/include/hi_at.h @@ -0,0 +1,241 @@ +/** +* @file hi_at.h +* Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/** @defgroup iot_at AT Command + * @ingroup dfx + */ +#ifndef __HI_AT_H__ +#define __HI_AT_H__ +#include + +typedef hi_u32 (*at_call_back_func)(hi_s32 argc, const hi_char **argv); + +typedef struct { + hi_char *at_cmd_name; + hi_s8 at_cmd_len; + at_call_back_func at_test_cmd; + at_call_back_func at_query_cmd; + at_call_back_func at_setup_cmd; + at_call_back_func at_exe_cmd; +} at_cmd_func; + +typedef enum { + AT_IDLE, + AT_CMD_PROCESS, + AT_DATA_RECVING, + AT_DATA_SENDING, + AT_TRANSPARENT, +} at_state_machine; + +typedef struct { + at_state_machine at_state; + hi_u16 send_len; + hi_u16 trans_len; + hi_bool is_first_recv_data; + hi_bool is_first_over_data; + hi_u16 is_recv_end_char_flag; +} at_cmd_ctrl; + +typedef hi_s32 (*hi_at_input_func)(hi_u8 *data, hi_u32 data_len); +typedef hi_s32 (*hi_at_output_func)(const hi_u8 *data, hi_u32 data_len); + +/** +* @ingroup iot_at +* @brief Get at registered output function. +CNcomment:获取AT注册的输出函数。CNend +* +* @par 描述: +* Get at registered output function. +CNcomment:获取AT注册的输出函数。CNend +* +* @attention None. +* @param None. +* +* @retval #g_at_output_func At output function. +* @par 依赖: +* @li hi_at.h:Describes at command APIs. CNcomment:文件用于描述at指令相关接口。CNend +* @see None +*/ +hi_at_output_func hi_at_get_register_output_func(hi_void); + +/** +* @ingroup iot_at +* @brief Registration command processing function.CNcomment:注册命令处理函数。CNend +* +* @par 描述: +* @li This command is invoked during initialization and cannot be invoked by multiple tasks. +CNcomment:在初始化阶段调用, 不支持多任务调用。CNend +* @li A maximum of 20 different command tables can be registered. +CNcomment:最多能注册20个不同的命令表。CNend +* +* @attention None +* @param cmd_tbl [IN] type #at_cmd_func*,Command table, which must be declared as a constant array and +* transferred to this parameter.CNcomment:命令表, +必须申明为常量数组传给该参数。CNend +* @param cmd_num [IN] type #hi_u16,The number of commands. The value must be equal to the actual number of +* commands in the command table. If it is less than the actual command number, only the number of +* commands equal to this value is registered. If it is greater than the actual command number, +* the command table will be accessed out of bounds. +CNcomment:命令表中命令的个数,该值必须等于命令表中实际的命令个数,如果小于实际命令数,则只注册等于该值的命令个数, + 大于实际命令个数将会导致越界访问命令表。CNend +* +* @retval #HI_ERR_SUCCESS Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_at.h:Describes at command APIs. CNcomment:文件用于描述at指令相关接口。CNend +* @see None +*/ +hi_u32 hi_at_register_cmd(HI_CONST at_cmd_func *cmd_tbl, hi_u16 cmd_num); + +/** +* @ingroup iot_at +* @brief Register system AT command. CNcomment:注册系统AT命令。CNend +* +* @par 描述: +* Register system AT command. CNcomment:该函数用于注册系统AT命令。CNend +* @param None +* @retval None +* +* @par 依赖: +* @li hi_at.h:Describes at command APIs. CNcomment:文件用于描述at指令相关接口。CNend +* @see None +*/ +hi_void hi_at_sys_cmd_register(hi_void); + +/** +* @ingroup iot_at +* @brief Formats the data and outputs it to AT command terminal. +CNcomment:将数据格式化输出到AT命令终端。CNend +* +* @par 描述: Formats the data and outputs it to AT command terminal. +CNcomment:将数据格式化输出到AT命令终端。CNend +* @attention None +* +* @param fmt [IN] type #const hi_char *。 Formatting control string.CNcomment:格式化控制字符串。CNend +* @param ... [IN] Optional parameter CNcomment:可选参数。CNend +* +* @retval #>=0 Return the number of bytes stored in terminal, not counting the terminating null character. +CNcomment:返回输出到终端的字节数,不包括结束符CNend +* @retval #-1 Failure +* +* @par 依赖: +* @li hi_at.h:Describes at command APIs. CNcomment:文件用于描述at指令相关接口。CNend +* @see None +*/ +hi_s32 hi_at_printf(const hi_char *fmt, ...); + +/** +* @ingroup iot_at +* @brief Initializes the AT task. CNcomment:AT命令任务初始化。CNend +* +* @par 描述: +* Initializes the AT task. CNcomment:该函数用于初始化AT命令任务。CNend +* @param None +* @retval #HI_ERR_SUCCESS Success. +* @retval #Other Failure. For details, see hi_errno.h. +* +* @par 依赖: +* @li hi_at.h:Describes at command APIs. CNcomment:文件用于描述at指令相关接口。CNend +* @see None +*/ +hi_u32 hi_at_init(hi_void); + +/** +* @ingroup iot_at +* @brief Set taks size of AT. CNcomment:设置AT相关任务栈大小。CNend +* +* @par 描述: +* Set taks size of AT. CNcomment:设置AT相关任务栈大小。CNend +* +* @attention AT task stack size needs to be set before AT initialization. +CNcomment:AT任务栈大小需要在AT初始化之前设置。CNend +* @param channel_task_size [IN] type #hi_u16 channel task size, task size should not smaller than 0x600. +CNcomment:通道任务栈大小, 任务栈大小不低于0x600。Nend +* @param process_task_size [IN] type #hi_u16 process task size, task size should not smaller than 0xc00. +CNcomment:处理任务栈大小, 任务栈大小不低于0xc00。CNend +* +* @retval None +* @par 依赖: +* @li hi_at.h:Describes at command APIs. CNcomment:文件用于描述at指令相关接口。CNend +* @see None +*/ +hi_void hi_at_set_task_size(hi_u16 channel_task_size, hi_u16 process_task_size); + +/** +* @ingroup iot_at +* @brief Set whether to check the UART busy status when low power vote. +CNcomment:设置低功耗投票时是否检查UART busy状态。CNend +* +* @par 描述: +* Set whether to check the UART busy status when low power vote. +CNcomment:设置低功耗投票时是否检查UART busy状态。CNend +* +* @attention UART busy status is checked by default. +CNcomment:默认低功耗睡眠投票时检查UART busy状态。CNend +* @param enable [IN] type #hi_bool,enable status. CNcomment:设置是否检查UART busy状态。CNend +* +* @retval None +* @par 依赖: +* @li hi_at.h:Describes at command APIs. CNcomment:文件用于描述at指令相关接口。CNend +* @see None +*/ +hi_void hi_at_set_check_uart_busy(hi_bool enable); + +/** +* @ingroup iot_at +* @brief Register at input function to replace uart input. +CNcomment:注册AT输入函数,代替默认从UART读取AT输入数据。CNend +* +* @par 描述: +* Register at input function to replace uart input. +CNcomment:注册AT输入函数,代替默认从UART读取AT输入数据。CNend +* +* @attention Should set suitable task size; input func should not continuous read data without break. otherwise, +a watchdog may happen.not support register HI_NULL when at channel is already uart. +CNcomment:根据输入函数实现,设置合适的栈大小;输入函数不能持续 +返回有效数据避免触发看门狗。当AT通道已经是UART时,不支持注 +册AT 输入函数为HI_NULL。CNend +* @param at_input_func [IN] type #hi_at_input_func,at input funciton. +CNcomment:AT输入函数。CNend +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_at.h:Describes at command APIs. CNcomment:文件用于描述at指令相关接口。CNend +* @see None +*/ +hi_u32 hi_at_register_input_func(hi_at_input_func at_input_func); + +/** +* @ingroup iot_at +* @brief Register at output function to replace uart output. +CNcomment:注册AT命令输出函数,代替默认从UART输出AT相关数据。CNend +* +* @par 描述: +* Register at output function to replace uart output. +CNcomment:注册AT命令输出函数,代替默认从UART输出AT相关数据。CNend +* +* @attention Should set suitable task size according to implementation of output func. +CNcomment:根据输出函数实现,设置合适的栈大小。CNend +* @param at_output_func [IN] type #hi_at_output_func,at output function. +CNcomment:AT输出函数。CNend +* @retval None +* @par 依赖: +* @li hi_at.h:Describes at command APIs. CNcomment:文件用于描述at指令相关接口。CNend +* @see None +*/ +hi_void hi_at_register_output_func(hi_at_output_func at_output_func); + +#endif diff --git a/sdk_liteos/include/hi_atomic.h b/sdk_liteos/include/hi_atomic.h new file mode 100644 index 0000000000000000000000000000000000000000..0ef1be0356a7f88a412a803150fd5646935ecab1 --- /dev/null +++ b/sdk_liteos/include/hi_atomic.h @@ -0,0 +1,187 @@ +/** + * @file hi_atomic.h + * + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @defgroup iot_atomic Atomic Operation + * @ingroup osa + */ +#ifndef __HI_ATOMIC_H__ +#define __HI_ATOMIC_H__ +#include +#include + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif + +typedef struct { + volatile hi_s32 counter; +} hi_atomic; + +#define hi_atomic_init(i) { (i) } +#define hi_atomic_read(v) ((v)->counter) +#define hi_atomic_set(v, i) (((v)->counter) = (i)) + +#define hi_atomic_inc(v) hi_atomic_add_return(1, v) +#define hi_atomic_dec(v) hi_atomic_sub_return(1, v) + +#define hi_atomic_inc_return(v) (hi_atomic_add_return(1, v)) +#define hi_atomic_dec_return(v) (hi_atomic_sub_return(1, v)) + +/** + * @ingroup iot_atomic + * If the atomic operation is performed, the operation result is returned. +CNcomment:原子加操作,返回操作结果CNend + */ +#define hi_atomic_add_return_op(i, v) (hi_atomic_add_return(i, v)) + +/** + * @ingroup iot_atomic + * The operation result is returned when the atomic subtraction operation is performed. +CNcomment:原子减操作,返回操作结果CNend + */ +#define hi_atomic_sub_return_op(i, v) (hi_atomic_sub_return(i, v)) + +/** + * @ingroup iot_atomic + * The specified bit in the atomic setting variable is 1. +CNcomment:原子设置变量中指定bit位为1CNend + */ +#define hi_atomic_bit_set_op(bit, v) (hi_atomic_bit_set(bit, v)) +/** + * @ingroup iot_atomic + * The specified bit in the atomic setting variable is 0. +CNcomment:原子设置变量中指定bit位为0CNend + */ +#define hi_atomic_bit_clear_op(bit, v) (hi_atomic_bit_clear(bit, v)) + +/* +* If the atomic operation is performed, the operation result is returned. +CNcomment:原子加操作,返回操作结果CNend +* +* 描述: +* If the atomic operation is performed, the operation result is returned. +CNcomment:原子加操作,返回操作结果CNend +* +* param i [IN] type #hi_s32, The number of operands added to an atom.CNcomment:与原子相加的操作数CNend +* param v [IN] type #hi_atomic*,Pointer to the atomic structure address.CNcomment:原子结构地址指针CNend +* +* retval #hi_s32 Add Operation Result.CNcomment:加操作结果CNend +* par 依赖: +* hi_atomic.h:Header file where the interface declaration is located. +CNcomment:该接口声明所在的头文件。CNend +*/ +__attribute__((always_inline)) static inline hi_s32 hi_atomic_add_return(hi_s32 i, hi_atomic *v) +{ + hi_u32 irq_status; + + irq_status = LOS_IntLock(); + v->counter += i; + (hi_void)LOS_IntRestore(irq_status); + return v->counter; +} + +/* +* The operation result is returned when the atomic subtraction operation is performed. +CNcomment:原子减操作,返回操作结果CNend +* +* 描述: +* The operation result is returned when the atomic subtraction operation is performed. +CNcomment:原子减操作,返回操作结果CNend +* +* param i [IN] type #hi_s32, The number of operands subtracted from the atom. +CNcomment:被原子相减的操作数CNend +* param v [IN] type #hi_atomic*,Pointer to the atomic structure address.CNcomment:原子结构地址指针CNend +* +* retval #hi_s32 Reduce the operation result. CNcomment:减操作结果CNend +* par 依赖: +* hi_atomic.h:Header file where the interface declaration is located. +CNcomment:该接口声明所在的头文件。CNend +*/ +__attribute__((always_inline)) static inline hi_s32 hi_atomic_sub_return(hi_s32 i, hi_atomic *v) +{ + hi_u32 irq_status; + + irq_status = LOS_IntLock(); + v->counter = v->counter - i; + (hi_void)LOS_IntRestore(irq_status); + + return v->counter; +} + +/* +* The specified bit in the atomic setting variable is 1.CNcomment:原子设置变量中指定bit位为1CNend +* +* 描述: +* The specified bit in the atomic setting variable is 1.CNcomment:原子设置变量中指定bit位为1CNend +* +* param bit [IN] type #hi_s32, Position of the bit that is set to 1. The value range is 0-31. +CNcomment:被置1的bit位置,范围0-31.CNend +* param value [IN] type #hi_u32*,Address pointer of the set variable.CNcomment:置位变量的地址指针CNend +* +* retval #None +* par 依赖: +* hi_atomic.h:Header file where the interface declaration is located. +CNcomment:该接口声明所在的头文件。CNend +*/ +__attribute__((always_inline)) static inline hi_void hi_atomic_bit_set(hi_s32 bit, volatile hi_u32 *value) +{ + hi_u32 irq_status; + irq_status = LOS_IntLock(); + + *value |= (1 << bit); + + (hi_void)LOS_IntRestore(irq_status); +} + +/* +* The specified bit in the atomic setting variable is 0.CNcomment:原子设置变量中指定bit位为0CNend +* +* 描述: +* The specified bit in the atomic setting variable is 0.CNcomment:原子设置变量中指定bit位为0CNend +* +* param bit [IN] type #hi_s32, Position of the bit that is set to 0. The value range is 0-31. +CNcomment:被置0的bit位置,范围0-31.CNend +* param value [IN] type #hi_u32*,Address pointer of the set variable.CNcomment:置位变量的地址指针CNend +* +* retval #None +* par 依赖: +* hi_atomic.h:Header file where the interface declaration is located. +CNcomment:该接口声明所在的头文件。CNend +*/ +__attribute__((always_inline)) static inline hi_void hi_atomic_bit_clear(hi_s32 bit, volatile hi_u32 *value) +{ + hi_u32 irq_status; + hi_u32 mask; + + irq_status = LOS_IntLock(); + mask = 1 << bit; + *value = (*value) & (~mask); + + (hi_void)LOS_IntRestore(irq_status); +} + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif + +#endif /* end of hi_atomic.h */ + diff --git a/sdk_liteos/include/hi_btcoex_api.h b/sdk_liteos/include/hi_btcoex_api.h new file mode 100644 index 0000000000000000000000000000000000000000..d606086db698eecb38edcdb8bde759fb8aa04128 --- /dev/null +++ b/sdk_liteos/include/hi_btcoex_api.h @@ -0,0 +1,72 @@ +/** + * @file hi_btcoex_api.h + * + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** +* @defgroup hi_wifi_btcoex BTCOEX +* @ingroup hi_wifi +*/ + +#ifndef __HI_BTCOEX_API_H__ +#define __HI_BTCOEX_API_H__ + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif + +/** +* @ingroup hi_wifi_btcoex +* @brief Set wifi & bt coexist on/off. +* CNcomment:蓝牙共存打开/关闭。CNend +* +* @par Description: +* Set wifi & bt coexist on while wifi and bt are both turned on. +* or set wifi & bt coexist off while bt is turned off. +* CNcomment:wifi & bt 都打开时打开coexist共存,bt 关闭时关掉coexist共存。CNend +* +* @param ifname [IN] Type #const char *, device name, e.g. wlan0.CNcomment:设备名称,如 wlan0。CNend +* @param enable [IN] Type #enable, whether turn wifi & bt coexist on or off, 0:off, 1:on. +* CNcomment:是否打开蓝牙wifi共存,0:关闭, 1:打开。CNend +* @param mode [IN] Type #mode, wifi & bt coexist mode, 1:2-wired, 2:3-wired. +* CNcomment:蓝牙wifi共存模式,1:二线, 2:三线。CNend +* @param share_ant [IN] Type #share_ant, whether wifi & bt share ant, 0:no share ant, 1:share ant. +* CNcomment:蓝牙wifi是否共用天线,0:不共用,1:共用。CNend +* @param preempt [IN] Type #preempt, whether send wifi & bt preempt frame (NULL data), 0:no send, 1:send. +* CNcomment:是否发送共存preemp帧(NULL data),0:不发送,1:发送。CNend +* +* @attention +* It will occupy some space time for sending preempt frame (NULL data), the performance of not sending preempt frame +* is better than sending in lab test, while sending preempt frame could tell the peer sta that the bt is working +* at this moment.CNcomment:发送共存preemp帧(NULL data),会占用一定空口资源,实测不发送preemp帧 +* 性能比发送preemp帧性能更高,发送preemp帧可以明确告知对端AP当前wifi的工作状态。CNend +* +* @retval #HISI_OK Excute successfully +* @retval #Other Error code +* @par Dependency: +* @li hi_btcoex_api.h: WiFi API +* @see NULL +*/ +hi_u32 hi_wifi_btcoex_enable(const hi_char *ifname, hi_bool enable, hi_u8 mode, hi_u8 share_ant, hi_u8 preempt); + +#ifdef __cplusplus +#if __cplusplus + } +#endif +#endif + +#endif /* end of hi_btcoex_api.h */ diff --git a/sdk_liteos/include/hi_cipher.h b/sdk_liteos/include/hi_cipher.h new file mode 100644 index 0000000000000000000000000000000000000000..8dbc7aceab35d41d5814cc2515475f67f5edfbb2 --- /dev/null +++ b/sdk_liteos/include/hi_cipher.h @@ -0,0 +1,651 @@ +/** + * @file hi_cipher.h + * + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @defgroup iot_cipher Encryption and Decryption. + * @ingroup drivers + */ +#ifndef __HI_CIPHER_H__ +#define __HI_CIPHER_H__ + +#include + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ + +#define PKE_LEN_32_BYTES 32 +#define PKE_LEN_256_BYTES 256 +#define PKE_LEN_384_BYTES 384 +#define PKE_LEN_512_BYTES 512 +#define RSA_KEY_LEN_2048 256 +#define AES_MAX_KEY_IN_WORD 16 +#define AES_IV_LEN_IN_WORD 4 +#define KDF_KEY_LEN_IN_BYTES 32 + +/** +* @ingroup iot_cipher +* Hash algrithm type +*/ +typedef enum { + HI_CIPHER_HASH_TYPE_SHA256 = 0x0, + HI_CIPHER_HASH_TYPE_HMAC_SHA256, + HI_CIPHER_HASH_TYPE_MAX, + HI_CIPHER_HASH_TYPE_INVALID = 0xffffffff, +}hi_cipher_hash_type; + +/** +* @ingroup iot_cipher +* Rsa sign and veriry scheme +*/ +typedef enum { + HI_CIPHER_RSA_SIGN_SCHEME_RSASSA_PKCS1_V15_SHA256 = 0x00, /**< PKCS#1 RSASSA_PKCS1_V15_SHA256 signature */ + HI_CIPHER_RSA_SIGN_SCHEME_RSASSA_PKCS1_PSS_SHA256, /**< PKCS#1 RSASSA_PKCS1_PSS_SHA256 signature */ + HI_CIPHER_RSA_SIGN_SCHEME_MAX, + HI_CIPHER_RSA_SIGN_SCHEME_INVALID = 0xffffffff, +}hi_cipher_rsa_sign_scheme; + +/** +* @ingroup iot_cipher +* Aes key from +*/ +typedef enum { + HI_CIPHER_AES_KEY_FROM_CPU = 0x00, + HI_CIPHER_AES_KEY_FROM_KDF, + HI_CIPHER_AES_KEY_FROM_MAX, + HI_CIPHER_AES_KEY_FROM_INVALID = 0xffffffff, +}hi_cipher_aes_key_from; + +/** +* @ingroup iot_cipher +* Aes work mode +*/ +typedef enum { + HI_CIPHER_AES_WORK_MODE_ECB = 0x00, /**< Electronic codebook (ECB) mode, ECB has been considered insecure and + it is recommended not to use it. */ + HI_CIPHER_AES_WORK_MODE_CBC, /**< Cipher block chaining (CBC) mode. */ + HI_CIPHER_AES_WORK_MODE_CTR, /**< Counter (CTR) mode. */ + HI_CIPHER_AES_WORK_MODE_CCM, /**< Counter (CCM) mode. */ + HI_CIPHER_AES_WORK_MODE_XTS, /**< XTS-AES (XTS) mode. */ + HI_CIPHER_AES_WORK_MODE_MAX, + HI_CIPHER_AES_WORK_MODE_INVALID = 0xffffffff, +}hi_cipher_aes_work_mode; + +/** +* @ingroup iot_cipher +* Aes key length +*/ +typedef enum { + HI_CIPHER_AES_KEY_LENGTH_128BIT = 0x00, + HI_CIPHER_AES_KEY_LENGTH_192BIT, + HI_CIPHER_AES_KEY_LENGTH_256BIT, + HI_CIPHER_AES_KEY_LENGTH_512BIT, /**< 512bit, just used for xts. */ + HI_CIPHER_AES_KEY_LENGTH_MAX, + HI_CIPHER_AES_KEY_LENGTH_INVALID = 0xffffffff, +}hi_cipher_aes_key_length; + +/** +* @ingroup iot_cipher +* Rsa private key sign +*/ +typedef struct { + hi_cipher_rsa_sign_scheme scheme; /**< The rsa sign type */ + hi_u8 *d; /**< The private exponent */ + hi_u8 *n; /**< The modulus */ + hi_u32 klen; /**< The key length */ +} hi_cipher_rsa_sign; + +/** +* @ingroup iot_cipher +* Rsa public key verify +*/ +typedef struct { + hi_cipher_rsa_sign_scheme scheme; /**< The rsa sign type */ + hi_u8 *e; /**< The public exponent */ + hi_u8 *n; /**< The modulus */ + hi_u32 klen; /**< The key length */ +} hi_cipher_rsa_verify; + +/** +* @ingroup iot_cipher +* cipher struct for output +*/ +typedef struct { + hi_u8 *out; /**< Point for output */ + hi_u32 out_buf_len; /**< Length of output buffer */ + hi_u32 *out_len; /**< Length of valid output data */ +} hi_cipher_output; + +/** +* @ingroup iot_cipher +* Struct of ecc curves parameters +*/ +typedef struct { + const hi_u8 *p; /**< Finite field: equal to p in case of prime field curves or equal to 2^n in case of binary + field curves. */ + const hi_u8 *a; /**< Curve parameter a (q-3 in Suite B). */ + const hi_u8 *b; /**< Curve parameter b. */ + const hi_u8 *gx; /**< X coordinates of G which is a base point on the curve. */ + const hi_u8 *gy; /**< Y coordinates of G which is a base point on the curve. */ + const hi_u8 *n; /**< Prime which is the order of G point. */ + hi_u32 h; /**< Cofactor, which is the order of the elliptic curve divided by the order of the point G. For + the Suite B curves, h = 1. */ + hi_u32 ksize; /**< Ecc key size in bytes. It corresponds to the size in bytes of the prime, should be 32bytes. */ +}hi_cipher_ecc_param; + +/** +* @ingroup iot_cipher +* Struct of ecc sign +*/ +typedef struct { + const hi_u8 *d; /**< Ecdh private key, the caller ensures it is padded with leading zeros if the effective size of + this key is smaller than ecc key size. */ + const hi_u8 *hash; /**< Hash data for ecc sign. */ + hi_u32 hash_len; /**< The length of hash data, just 32 bytes is valid data. */ + hi_u8 *r; /**< Output ecc sign result R, its length is ecc key size. */ + hi_u8 *s; /**< Output ecc sign result S, its length is ecc key size. */ +}hi_cipher_ecc_sign; + +/** +* @ingroup iot_cipher +* Struct of ecc verify +*/ +typedef struct { + const hi_u8 *px; /**< Ecdh X coordinates of the generated public key, the caller ensures it is padded with leading + zeros if the effective size of this key is smaller than ecc key size. */ + const hi_u8 *py; /**< Ecdh Y coordinates of the generated public key, the caller ensures it is padded with leading + zeros if the effective size of this key is smaller than ecc key size. */ + const hi_u8 *hash; /**< Hash data for ecc verify. */ + hi_u32 hash_len; /**< The length of hash data, just 32 bytes is valid data. */ + const hi_u8 *r; /**< Output ecc sign result R, its length is ecc key size. */ + const hi_u8 *s; /**< Output ecc sign result S, its length is ecc key size. */ +}hi_cipher_ecc_verify; + +/** +* @ingroup iot_cipher +* Aes ccm struct +*/ +typedef struct { + hi_u8 *n; /**< Nonce. */ + hi_u32 n_len; /**< Nonce length for CCM, which is an element of {7,8,9,10,11,12,13}. */ + hi_u32 tag_len; /**< Tag lenght for CCM which is an element of {4,6,8,10,12,14,16}. */ + hi_u32 aad_len; /**< Associated data length for CCM. */ + uintptr_t aad_addr; /**< Physical address of Associated data for CCM. */ +}hi_cipher_aes_ccm; + +/** +* @ingroup iot_cipher +* Aes ctrl struct +*/ +typedef struct { + hi_u32 key[AES_MAX_KEY_IN_WORD]; /**< Key input. */ + hi_u32 iv[AES_IV_LEN_IN_WORD]; /**< Initialization vector (IV). */ + hi_bool random_en; /**< Enable random delay or not. */ + hi_u8 resv[3]; /* 3 byte reserved */ + hi_cipher_aes_key_from key_from; /**< Key from, When using kdf key, no nead to configure the input key. */ + hi_cipher_aes_work_mode work_mode; /**< Work mode. */ + hi_cipher_aes_key_length key_len; /**< Key length. aes-ecb/cbc/ctr support 128/192/256 bits key, ccm just support + 128 bits key, xts just support 256/512 bits key. */ + hi_cipher_aes_ccm *ccm; /**< Struct for ccm. */ +}hi_cipher_aes_ctrl; + +/** +* @ingroup iot_cipher +* Kdf key type +*/ +typedef enum { + HI_CIPHER_SSS_KDF_KEY_DEVICE = 0x0, /**< kdf device key derivation. */ + HI_CIPHER_SSS_KDF_KEY_STORAGE, /**< kdf storage key derivation. */ + HI_CIPHER_SSS_KDF_KEY_MAX, + HI_CIPHER_SSS_KDF_KEY_INVALID = 0xFFFFFFFF, +}hi_cipher_kdf_mode; + +/** +* @ingroup iot_cipher +* Kdf ctrl struct +*/ +typedef struct { + const hi_u8 *salt; /**< salt for kdf key derivation. */ + hi_u32 salt_len; /**< salt_len should be 16 bytes for kdf device key derivation, + 32 bytes for kdf storage key derivation. */ + hi_u8 key[KDF_KEY_LEN_IN_BYTES]; + hi_cipher_kdf_mode kdf_mode; /**< kdf mode for key derivation. */ + hi_u32 kdf_cnt; /**< kdf cnt for iteration.It is recommended that the number of iterations be + not less than 10000 times, if performance requirement, no less than 1000 + times, and not more than 0xffff times. */ + hi_u8 result[KDF_KEY_LEN_IN_BYTES]; +}hi_cipher_kdf_ctrl; + +/** +* @ingroup iot_cipher +* Hash/hmac init struct input +*/ +typedef struct { + const hi_u8 *hmac_key; /**< hmac_key, just used for hmac. */ + hi_u32 hmac_key_len; /**< hmac_key_len, just used for hmac. */ + hi_cipher_hash_type sha_type; /**< sha_type, hash or hmac type. */ +}hi_cipher_hash_atts; + +/** +* @ingroup iot_cipher +* @brief Initializes the Cipher module. CNcomment:Cipher 模块初始化。CNend +* +* @par 描述: +* Initializes the Cipher module, does NOT support multi-tasks. +CNcomment:Cipher模块初始化,不支持多任务。CNend +* +* @attention This function must be called before using cipher module. +CNcomment:使用Cipher模块算法前调用本接口初始化。CNend +* @param None +* +* @retval #0 Success +* @retval #Other Failure, for details, see file hi_errno.h. +* @par 依赖: +* @li hi_cipher.h:Describes Cipher module APIs. +CNcomment:文件用于描述Cipher模块相关接口。CNend +* @see hi_cipher_init。 +*/ +hi_u32 hi_cipher_init(hi_void); + +/** +* @ingroup iot_cipher +* @brief Settings of AES. CNcomment:AES算法参数配置。CNend +* +* @par 描述: +* Configure of AES. CNcomment:AES算法参数配置。CNend +* +* @attention None +* @param ctrl [IN] type #hi_cipher_aes_ctrl *,AES parameters. CNcomment:AES算法参数配置。CNend +* +* @retval #0 Success +* @retval #Other Failure, for details, see file hi_errno.h. +* @par 依赖: +* @li hi_cipher.h:Describes Cipher module APIs. +CNcomment:文件用于描述Cipher模块相关接口。CNend +* @see hi_cipher_aes_config。 +*/ +hi_u32 hi_cipher_aes_config(hi_cipher_aes_ctrl *ctrl); + +/** +* @ingroup iot_cipher +* @brief Encryption/Decryption of AES, if execution fails, hi_cipher_aes_destroy_config must be called to +release resources. +CNcomment:AES算法加解密,如果执行失败,必须调用hi_cipher_aes_destroy_config接口释放资源。CNend +* +* @par 描述: +* Encryption/Decryption of AES. CNcomment:AES算法加解密。CNend +* +* @attention 无。 +* @param src_addr [IN] type #uintptr_t,Input data source address. +CNcomment:待加密或解密的源数据物理地址,地址要求4对齐。CNend +* @param dest_addr [OUT] type #uintptr_t,output data physical address, the address must be +aligned in 4 bytes. +CNcomment:加密或解密结果数据物理地址,地址要求4对齐。CNend +* @param length [IN] type #hi_u32,data length, ECB/CBC/CTR must be aligned in 16 bytes, +CCM doesn't need to. +CNcomment:数据长度, ECB/CBC/CTR要求16bytes对齐, CCM可以不要求16bytes对齐。CNend +* @param encrypt [IN] type #hi_bool,options of encryption/decryption, HI_TRUE is for encryption, +HI_FALSE is for decryption.CNcomment:加解密配置选项,配置HI_TRUE为加密,配置HI_FALSE为解密。CNend +* +* @retval #0 Success +* @retval #Other Failure, for details, see file hi_errno.h. +* @par 依赖: +* @li hi_cipher.h:Describes Cipher module APIs. +CNcomment:文件用于描述Cipher模块相关接口。CNend +* @see hi_cipher_aes_crypto。 +*/ +hi_u32 hi_cipher_aes_crypto(uintptr_t src_addr, uintptr_t dest_addr, hi_u32 length, hi_bool encrypt); + +/** +* @ingroup iot_cipher +* @brief Output Tag, if execution fails, hi_cipher_aes_destroy_config must be called to release resources. +CNcomment:输出Tag,如果执行失败,必须调用hi_cipher_aes_destroy_config接口释放资源。CNend +* +* @par 描述: +* Output Tag, AES and CCM will output Tag after encrypting or decrypting. +CNcomment:输出Tag, AES CCM 模式加密或解密计算完成后,输出Tag值。CNend +* +* @attention None +* @param tag [OUT] type #hi_u8 *,Pointer to output Tag. CNcomment:输出Tag指针。CNend +* @param tag_buf_len [IN] type #hi_u32,Length of the buffer which tag points to. +CNcomment:tag指针指向的输出buff长度。CNend +* @param tag_len [OUT] type #hi_u32*,Length of the output tag. +CNcomment: 输出的tag数据长度。CNend. +* +* @retval #0 Success +* @retval #Other Failure, for details, see file hi_errno.h. +* @par 依赖: +* @li hi_cipher.h:Describes Cipher module APIs. +CNcomment:文件用于描述Cipher模块相关接口。CNend +* @see hi_cipher_aes_get_tag。 +*/ +hi_u32 hi_cipher_aes_get_tag(hi_u8 *tag, hi_u32 tag_buf_len, hi_u32 *tag_len); + +/** +* @ingroup iot_cipher +* @brief Destory AES configures. CNcomment:AES算法销毁配置的参数CNend +* +* @par 描述: +* Destory AES configures. CNcomment:AES算法销毁配置的参数CNend +* +* @attention In pair with hi_cipher_aes_config.CNcomment:与参数配置成对使用CNend +* @param None + +* @retval #0 Success +* @retval #Other Failure, for details, see file hi_errno.h. +* @par 依赖: +* @li hi_cipher.h:Describes Cipher module APIs. +CNcomment:文件用于描述Cipher模块相关接口。CNend +* @see hi_cipher_aes_destroy_config。 +*/ +hi_u32 hi_cipher_aes_destroy_config(hi_void); + +/** +* @ingroup iot_cipher +* @brief Settings of HASH/HMAC, if execution success, hi_cipher_hash_final must be called to release +resources.CNcomment:HASH/HMAC算法参数配置,执行成功后必须调用hi_cipher_hash_final接口释放资源。CNend +* +* @par 描述: +* Settings of HASH/HMAC, this function should be called before calculating. +CNcomment:HASH/HMAC算法参数配置,HASH/HMAC计算前调用 +* +* @attention None +* @param atts [IN] type #const hi_cipher_hash_atts *,HASH attribute.CNcomment:HASH算法类型配置。CNend + +* @retval #0 Success +* @retval #Other Failure, for details, see file hi_errno.h. +* @par 依赖: +* @li hi_cipher.h:Describes Cipher module APIs. +CNcomment:文件用于描述Cipher模块相关接口。CNend +* @see hi_cipher_hash_start。 +*/ +hi_u32 hi_cipher_hash_start(const hi_cipher_hash_atts *atts); + +/** +* @ingroup iot_cipher +* @brief Calculating by HASH/HMAC, if execution success, hi_cipher_hash_final must be called to release +resources.CNcomment:HASH/HMAC计算,执行成功后必须调用hi_cipher_hash_final接口释放资源。CNend +* +* @par 描述: +* Hash calculation. Multiple segments can be calculated. HMAC calculation supports only single-segment +calculation.CNcomment:HASH计算,支持多段计算,HMAC计算只支持单段计算。CNend +* +* @attention None +* @param src_addr [IN] type #uintptr_t,Data address to be calculated by HASH. +CNcomment:待HASH计算的数据地址。CNend +* @param length [IN] type #hi_u32,Data length to be calculated by HASH. +CNcomment:待HASH计算的数据长度。CNend +* +* @retval #0 Success +* @retval #Other Failure, for details, see file hi_errno.h. +* @par 依赖: +* @li hi_cipher.h:Describes Cipher module APIs. +CNcomment:文件用于描述Cipher模块相关接口。CNend +* @see hi_cipher_hash_update。 +*/ +hi_u32 hi_cipher_hash_update(uintptr_t src_addr, hi_u32 length); + +/** +* @ingroup iot_cipher +* @brief HASH/HMAC calculation finished.CNcomment:HASH/HMAC计算结束CNend +* +* @par 描述: +* Ouput results after HASH/HMAC finished calculating.CNcomment:HASH/HMAC计算结束, +输出计算结果。CNend +* +* @attention None +* +* @param out [OUT] type #hi_u8 *,Pointer to the output of the HASH/HMAC calculation result. +CNcomment:HASH/HMAC计算结果输出指针。CNend +* @param out_len [IN] type #hi_u32,HASH/HMAC The output pointer of the calculation result points to +* the space length. The output length must be greater than or equal to 32 bytes. +CNcomment:HASH/HMAC计算结果输出指针指向空间长度,要求输出长度满足不小于32bytes。CNend +* +* @retval #0 Success +* @retval #Other Failure, for details, see file hi_errno.h. +* @par 依赖: +* @li hi_cipher.h:Describes Cipher module APIs. +CNcomment:文件用于描述Cipher模块相关接口。CNend +* @see hi_cipher_hash_final。 +*/ +hi_u32 hi_cipher_hash_final(hi_u8 *out, hi_u32 out_len); + +/** +* @ingroup iot_cipher +* @brief HASH calculation.CNcomment:HASH计算CNend +* +* @par 描述: +* Performs hash calculation on a segment of data and outputs the hash result. +CNcomment:对一段数据做HASH计算,并输出HASH结果。CNend +* +* @attention None +* +* @param input [IN] type #uintptr_t,Enter the data address. The address must be 4-bytes-aligned. +CNcomment:输入数据地址,地址要求4对齐。CNend +* @param input_len [IN] type #hi_u32, Input data length.CNcomment:输入数据长度。CNend +* @param hash [OUT] type #hi_u8 *,Output the hash result. The length is 32 bytes. +CNcomment:输出HASH结果, 长度为 32 bytes。CNend +* @param hash_len [IN] type #hi_u32, BUF length of the hash result. The value must be greater than or +* equal to 32 bytes.CNcomment:输出HASH结果的BUF长度,需要满足不小于32bytes。CNend +* +* @retval #0 Success +* @retval #Other Failure, for details, see file hi_errno.h. +* @par 依赖: +* @li hi_cipher.h:Describes Cipher module APIs. +CNcomment:文件用于描述Cipher模块相关接口。CNend +* @see hi_cipher_hash_sha256。 +*/ +hi_u32 hi_cipher_hash_sha256(uintptr_t input, hi_u32 input_len, hi_u8 *hash, hi_u32 hash_len); + +/** +* @ingroup iot_cipher +* @brief KDF calculation.CNcomment:KDF算法计算。CNend +* +* @par 描述: +* KDF calculation.CNcomment:KDF算法计算。CNend +* +* @attention None +* @param ctrl [IN] type #hi_cipher_kdf_ctrl*,Poninter to KDF algorithm parameter configuration + control structure.CNcomment:KDF算法参数配置控制结构体。CNend +* +* @retval #0 Success +* @retval #Other Failure, for details, see file hi_errno.h. +* @par 依赖: +* @li hi_cipher.h:Describes Cipher module APIs. +CNcomment:文件用于描述Cipher模块相关接口。CNend +* @see hi_cipher_kdf_key_derive。 +*/ +hi_u32 hi_cipher_kdf_key_derive(hi_cipher_kdf_ctrl *ctrl); + +/** +* @ingroup iot_cipher +* @brief Rsa signature.CNcomment:Rsa 签名CNend +* +* @par 描述: +* Rsa signature and output of the signature result.CNcomment:Rsa签名,输出签名结果。CNend +* +* @attention None +* @param rsa_sign [IN] type #hi_cipher_rsa_sign *,Pointer to RSA signature structure. +CNcomment:Rsa签名算法结构体。CNend +* @param hash_data [IN] type #const hi_u8 *,Indicates the hash data to be signed. +CNcomment:待签名的HASH数据。CNend +* @param hash_data_len [IN] type #hi_u32, Length of the hash data to be signed, 32 bytes data. +CNcomment:待签名的HASH数据的长度,32bytes数据。CNend +* @param sign [OUT] type #const hi_cipher_output *,Signature result output structure. The length +* of the output signature result is the length of the key. +CNcomment:签名结果输出结构体,输出的签名结果长度为key的长度。CNend +* +* @retval #0 Success +* @retval #Other Failure, for details, see file hi_errno.h. +* @par 依赖: +* @li hi_cipher.h:Describes Cipher module APIs. +CNcomment:文件用于描述Cipher模块相关接口。CNend +* @see hi_cipher_rsa_sign_hash。 +*/ +hi_u32 hi_cipher_rsa_sign_hash(const hi_cipher_rsa_sign *rsa_sign, const hi_u8 *hash_data, hi_u32 hash_data_len, + const hi_cipher_output *sign); + +/** +* @ingroup iot_cipher +* @brief Rsa Signature Verification.CNcomment:Rsa 签名结果校验CNend +* +* @par 描述: +* Rsa Signature Verification.CNcomment:Rsa 签名结果校验。CNend +* +* @attention None +* @param rsa_verify [IN] type #hi_cipher_rsa_verify *,Structure of the Rsa signature result +* verification algorithm.CNcomment:Rsa签名结果校验算法结构体。CNend +* @param hash [IN] type #const hi_u8 *,Hash data to be checked. +CNcomment:待校验的HASH数据。CNend +* @param hash_len [IN] type #hi_u32, Indicates the length of the hash data to be verified. +* The value is 32 bytes valid data. +CNcomment:待校验的HASH数据的长度,为32bytes有效数据。CNend +* @param sign [IN] type #const hi_u8 *,Signature input pointer.CNcomment:签名输入指针。CNend +* @param sign_len [IN] type #hi_u32,Length of the signature result. The length is the same as the +* length of the key.CNcomment:签名结果长度, 长度与key的长度相同。CNend +* +* @retval #0 Success +* @retval #Other Failure, for details, see file hi_errno.h. +* @par 依赖: +* @li hi_cipher.h:Describes Cipher module APIs. +CNcomment:文件用于描述Cipher模块相关接口。CNend +* @see hi_cipher_rsa_verify_hash。 +*/ +hi_u32 hi_cipher_rsa_verify_hash(const hi_cipher_rsa_verify *rsa_verify, const hi_u8 *hash, hi_u32 hash_len, + const hi_u8 *sign, hi_u32 sign_len); + +/** +* @ingroup iot_cipher +* @brief Ecdsa signature.CNcomment:Ecdsa 签名CNend +* +* @par 描述: +* Ecdsa signature and output of the signature result.CNcomment:Ecdsa 签名,输出签名结果。CNend +* +* @attention None +* @param ecc [IN] type #const hi_cipher_ecc_param *,ECC elliptic curve parameter. If the +* length is less than the size of the key, add 0 before the key.CNcomment:ECC椭圆曲线 +参数,长度不足Key的大小,前面补0。CNend +* @param sign [IN/OUT] type #const hi_cipher_ecc_sign *,Pointer to private key of ECDH. +CNcomment:ECDH私钥签名结构体。CNend +* +* @retval #0 Success +* @retval #Other Failure, for details, see file hi_errno.h. +* @par 依赖: +* @li hi_cipher.h:Describes Cipher module APIs. +CNcomment:文件用于描述Cipher模块相关接口。CNend +* @see hi_cipher_ecc_sign_hash。 +*/ +hi_u32 hi_cipher_ecc_sign_hash(const hi_cipher_ecc_param *ecc, const hi_cipher_ecc_sign *sign); + +/** +* @ingroup iot_cipher +* @brief Ecdsa Signature Verification.CNcomment:Ecdsa 签名结果校验CNend +* +* @par 描述: +* Ecdsa Signature Verification.CNcomment:Ecdsa 签名结果校验。CNend +* +* @attention None +* @param ecc [IN] type #const hi_cipher_ecc_param *,ECC elliptic curve parameter. If the length +* is less than the size of the key, add 0 before the key. +CNcomment:ECC椭圆曲线参数,长度不足Key的大小,前面补0。CNend +* @param verify [IN] type #const hi_cipher_ecc_verify *,Pointer to structure of the ECC public key +* verification parameter.CNcomment:ECC公钥验证参数结构体。CNend +* +* @retval #0 Success +* @retval #Other Failure, for details, see file hi_errno.h. +* @par 依赖: +* @li hi_cipher.h:Describes Cipher module APIs. +CNcomment:文件用于描述Cipher模块相关接口。CNend +* @see hi_cipher_ecc_sign_hash。 +*/ +hi_u32 hi_cipher_ecc_verify_hash(const hi_cipher_ecc_param *ecc, const hi_cipher_ecc_verify *verify); + +/** +* @ingroup iot_cipher +* @brief TRNG Obtain a random number.CNcomment:TRNG获取随机数CNend +* +* @par 描述: +* TRNG Obtain a random number. Only one word size can be obtained at a time. +CNcomment:TRNG获取随机数,每次只能获取一个WORD大小的随机数。CNend +* +* @attention None +* @param randnum [OUT] type #hi_u32 *,Random number output pointer. +CNcomment:随机数输出指针。CNend +* +* @retval #0 Success +* @retval #Other Failure, for details, see file hi_errno.h. +* @par 依赖: +* @li hi_cipher.h:Describes Cipher module APIs. +CNcomment:文件用于描述Cipher模块相关接口。CNend +* @see hi_cipher_trng_get_random。 +*/ +hi_u32 hi_cipher_trng_get_random(hi_u32 *randnum); + +/** +* @ingroup iot_cipher +* @brief TRNG Obtain a random number.CNcomment:TRNG获取随机数CNend +* +* @par 描述: +* The TRNG obtains the random number and obtains the random number of multiple bytes at a time. +CNcomment:TRNG获取随机数,每次获取多个byte的随机数。CNend +* +* @attention None +* @param randbyte [OUT] type #hi_u8 *,Random number output pointer. +CNcomment:随机数输出指针。CNend +* @param size [IN] type #hi_u32,Length of the obtained random number. +CNcomment:获取的随机数长度。CNend +* +* @retval #0 Success +* @retval #Other Failure, for details, see file hi_errno.h. +* @par 依赖: +* @li hi_cipher.h:Describes Cipher module APIs. +CNcomment:文件用于描述Cipher模块相关接口。CNend +* @see hi_cipher_trng_get_random。 +*/ +hi_u32 hi_cipher_trng_get_random_bytes(hi_u8 *randbyte, hi_u32 size); + +/** +* @ingroup iot_cipher +* @brief Set the clock switch of cipher module.CNcomment:设置cipher模块时钟切换开关。CNend +* +* @par 描述: +* Set the clock switch of cipher module, which is false by default, The clock is always on. +When it is true, clock will be turned on when cipher algorithm is used and turned off when calculation is finished. +CNcomment:设置cipher模块时钟切换开关,默认为FALSE,时钟常开,设为TRUE后在使用cipher算法时打开,计算结束后关闭。CNend +* +* @attention None +* @param enable [IN] type #hi_bool,Random number output pointer. +CNcomment:随机数输出指针。CNend +* +* @retval None +* @par 依赖: +* @li hi_cipher.h:Describes Cipher module APIs. +CNcomment:文件用于描述Cipher模块相关接口。CNend +* @see hi_cipher_set_clk_ctrl。 +*/ +hi_void hi_cipher_set_clk_switch(hi_bool enable); + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif /* __HI_CIPHER_H__ */ + diff --git a/sdk_liteos/include/hi_clock.h b/sdk_liteos/include/hi_clock.h new file mode 100644 index 0000000000000000000000000000000000000000..676131fa3d5b2eee4a2fca736b3179e7caf6e8c7 --- /dev/null +++ b/sdk_liteos/include/hi_clock.h @@ -0,0 +1,89 @@ +/** + * @file hi_clock.h + * + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @defgroup iot_clock Crystal Clock + * @ingroup drivers + */ + +#ifndef __HI_CLOCK_H__ +#define __HI_CLOCK_H__ +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define HI_XTAL_24MHZ_VAL 24000000 +#define HI_XTAL_40MHZ_VAL 40000000 + +/** + * @ingroup iot_clock Xtal Clock Configuration + * + * Crystal clock frequency.CNcomment:晶体时钟频率。CNend + */ +typedef enum { + HI_XTAL_CLOCK_24M, /**< 24M crystal clock frequency.CNcomment:24M晶体时钟CNend */ + HI_XTAL_CLOCK_40M, /**< 40M crystal clock frequency.CNcomment:40M晶体时钟CNend */ + HI_XTAL_CLOCK_MAX /**< MAX value, invalid.CNcomment:最大值,不可使用CNend */ +}hi_xtal_clock; + +/** +* @ingroup iot_clock +* @brief Obtains the crystal clock frequency.CNcomment:获取晶体时钟频率。CNend +* +* @par 描述: +* Obtains the crystal clock frequency.CNcomment:获取晶体时钟频率。CNend +* +* @attention None +* @param None +* +* @retval #HI_XTAL_CLOCK_24M 24M crystal clock frequency.CNcomment:24M晶体时钟。CNend +* @retval #HI_XTAL_CLOCK_40M 40M crystal clock frequency.CNcomment:40M晶体时钟。CNend +* @retval #HI_XTAL_CLOCK_MAX MAX value, invalid.CNcomment:最大值,不可使用。CNend +* @par 依赖: +* @li hi_clock.h:Describes hardware clock APIS. +CNcomment:文件用于描述硬件时钟相关接口。CNend +* @see None +*/ +HI_EXTERN hi_xtal_clock hi_get_xtal_clock(hi_void); + +/** +* @ingroup iot_clock +* @brief Configure the frequency divider of the 24M/40M crystal oscillator to generate the 32K clock. +CNcomment:配置24M/40M晶体分频值,产生32K时钟。CNend +* +* @par 描述: +* Configure the frequency divider of the 24M/40M crystal oscillator to generate the 32K clock. +CNcomment:配置24M/40M晶体分频值,产生32K时钟。CNend +* +* @attention Impact Scope:systick、rtc.CNcomment:影响范围:systick、rtc。CNend +* @param None +* +* @retval None +* @par 依赖: +* @li hi_clock.h:Describes hardware clock APIS. +CNcomment:文件用于描述硬件时钟相关接口。CNend +* @see None +*/ +HI_EXTERN hi_void hi_cfg_xtal_clk_div(hi_void); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/include/hi_config.h b/sdk_liteos/include/hi_config.h new file mode 100644 index 0000000000000000000000000000000000000000..47971c2ab898137b4c2185b7234518f1fb3d2ecf --- /dev/null +++ b/sdk_liteos/include/hi_config.h @@ -0,0 +1,265 @@ +/** + * @file hi_config.h + * + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __HI_CONFIG_H__ +#define __HI_CONFIG_H__ +/*****************************************************************************/ +#include + +/* + * Global module/submodule ID setting.CNcomment:全局模块/子模块ID设置 + * Note that HI_MOD_MAX_NUM needs to be increased or decreased after the number of modules is increased or decreased. + * CNcomment:注意增减模块个数后,需要增减 HI_MOD_MAX_NUM + * SAL : [200, 300) + * BSP : [300, 400) -- [12c, 190) + * MAC : [500, 600) -- [1F4, 258) + * APP : [800, 900) -- [320, 384) + */ +#ifndef PRODUCT_CFG_DIAG_MODULE_ID_MAX_NUM +#define PRODUCT_CFG_DIAG_MODULE_ID_MAX_NUM 60 +#endif +#define HI_MOD_MAX_NUM (PRODUCT_CFG_DIAG_MODULE_ID_MAX_NUM) /* Number of Modules */ + +/* SAL: [200, 300) */ +#define HI_MOD_ID_SAL_SYS 201 +#define HI_MOD_ID_SAL_NVM 203 +#define HI_MOD_ID_SAL_DIAG 204 +#define HI_MOD_ID_SAL_DFX 205 +#define HI_MOD_ID_CPUP_DFX 210 +#define HI_MOD_ID_CIPHER 211 + +/* BSP: [300, 400) */ +#define HI_MOD_ID_DRV 300 /* 0x12C */ +#define HI_MOD_ID_DRV_SPI 307 /* 0x133 */ +#define HI_MOD_ID_DRV_DMA 316 /* 0x13c */ +#define HI_MOD_ID_UPG 317 +#define HI_MOD_ID_CRYPTO 318 +#define HI_MOD_ID_I2S 319 +#define HI_MOD_ID_UART 320 +#define HI_MOD_ID_WIFI_DRV 400 /* 0x190 */ + +/* APP : [800, 900) */ +#define HI_MOD_ID_APP_COMMON 812 /* 32C */ +#define HI_MOD_ID_APP_AT 813 /* 32C */ + +/* Module name size in bytes */ +#define HI_SYS_MOD_NAME_LEN 16 +#ifdef __NEW_FILE_ID__ +#define HI_DIAG_LOG_MSG_MOD_ID __NEW_MOD_ID__ +#define HI_DIAG_LOG_MSG_FILE_ID __NEW_FILE_ID__ +#else +#define HI_DIAG_LOG_MSG_MOD_ID 0 +#define HI_DIAG_LOG_MSG_FILE_ID 0 +#endif + +/* Maximum size of a single DIAG packet buffer.CNcomment:DIAG包缓存单包最大大小设置 */ +#define HI_DIAG_BUFFERING_MSG_MAX_LEN 100 +#define HI_DIAG_BUFFERING_CMD_MAX_LEN 100 + +/* Sets the buffer queue size in a DAIG channel. CNcomment:DAIG 通道中缓存队列大小设置 */ +/* Messages,if the memory usage is greater than the threshold, the memory is dynamically allocated. + CNcomment:消息 大于该门限则动态分配内存 */ +#define HI_DIAG_BUFFERING_MSG_NUM 5 +/* Command,if the memory usage is greater than the threshold, the memory is dynamically allocated. + CNcomment:命令 大于该门限则动态分配内存 */ +#define HI_DIAG_BUFFERING_CMD_NUM 2 + + +/***************************************************************************** + Global Static Settings + *****************************************************************************/ +#define HI_MAC_ADDR_LEN 6 + +/* Maximum size of the received DIAG packet, including the channel frame header and payload. + CNcomment:接收DIAG包最大大小,包括通道帧头和payload */ +#define HI_DIAG_PACKET_REQ_CACHE_MAX_SIZE 320 +#define HI_DIAG_PACKET_ACK_MAX_SIZE 1024 +#define HI_DIAG_PACKET_REQ_DATA_MAX_SIZE 320 + +/* Task waiting exception. */ +#define HI_SYS_TASK_WAIT_EXCEPTION_TIME_OUT 10000 + +/* The total size of the RAM */ +HI_EXTERN hi_u32 g_halSectorsRamSize; +/* The start address of RAM */ +HI_EXTERN hi_void *g_halSectorsRamStart; + +#define hi_is_valid_ram_addr(_x) (((hi_u32)(_x) >= (hi_u32)(uintptr_t)g_halSectorsRamStart) && \ + ((hi_u32)(_x) < ((hi_u32)(uintptr_t)g_halSectorsRamStart + (uintptr_t)g_halSectorsRamSize))) +#define hi_is_valid_code_addr(_x) (_x) + + +/******************************************************************************* + NV range + *****************************************************************************/ +/** +* @ingroup iot_nv +* +* Factory NV area start ID (including this ID).CNcomment:工厂NV区起始ID(包含此ID)。CNend +*/ +#define HI_NV_FACTORY_ID_START 0x0 + +/** +* @ingroup iot_nv +* +* Factory NV area end ID (not included).CNcomment:工厂NV区结束ID(不包含此ID)。CNend +*/ +#define HI_NV_FACTORY_ID_END 0x16 + +/** +* @ingroup iot_nv +* +* Factory NV user area start ID (including this ID).CNcomment:工厂NV区用户区起始ID(包含此ID)。CNend +*/ +#define HI_NV_FACTORY_USR_ID_START HI_NV_FACTORY_ID_END + +/** +* @ingroup iot_nv +* +* Factory NV user area end ID (not included).CNcomment:工厂NV区用户区结束ID(不包含此ID)。CNend +*/ +#define HI_NV_FACTORY_USR_ID_END 0x20 + +/** +* @ingroup iot_nv +* +* Non factory NV area start ID (including this ID).CNcomment:非工厂NV区起始ID(包含此ID)。CNend +*/ +#define HI_NV_NORMAL_ID_START HI_NV_FACTORY_USR_ID_END + +/** +* @ingroup iot_nv +* +* Non factory NV user area end ID (not included).CNcomment:非工厂NV区结束ID(不包含此ID)。CNend +*/ +#define HI_NV_NORMAL_ID_END 0x80 + +/** +* @ingroup iot_nv +* +* Non factory NV Upgrade Reserved area start ID (including this ID).CNcomment:非工厂NV升级保留区起始ID(包含此ID)。CNend +*/ +#define HI_NV_STABLE_ID_START HI_NV_NORMAL_ID_END + +/** +* @ingroup iot_nv +* +* Non factory NV Upgrade Reserved area end ID (not included).CNcomment:非工厂NV升级保留区结束ID(不包含此ID)。CNend +*/ +#define HI_NV_STABLE_ID_END 0x98 + +/** +* @ingroup hct_nv +* +* Non factory NV user Upgrade Reserved area start ID (including this ID). + CNcomment:非工厂NV升级保留区用户区起始ID(包含此ID)。CNend +*/ +#define HI_NV_STABLE_USR_ID_START HI_NV_STABLE_ID_END + +/** +* @ingroup iot_nv +* +* Non factory NV user Upgrade Reserved area end ID (not included). + CNcomment:非工厂NV升级保留区用户区结束ID(不包含此ID)。CNend +*/ +#define HI_NV_STABLE_USR_ID_END 0xA0 + +/** +* @ingroup iot_nv +* +* Non factory NV user Reserved area start ID (including this ID).CNcomment:非工厂NV区用户预留区起始ID(包含此ID)。CNend +*/ +#define HI_NV_NORMAL_USR_ID_START HI_NV_STABLE_USR_ID_END + +/** +* @ingroup hct_nv +* +* Non factory NV user Reserved area end ID (including this ID).CNcomment:非工厂NV区用户预留区结束ID(包含此ID)。CNend +*/ +#define HI_NV_NORMAL_USR_ID_END 0xFF + +/***************************************************************************** + Channel Settings +*****************************************************************************/ +/* UART port number supported by the DIAG channel. The value must be smaller than the value of + HI_DMS_CHL_UART_PORT_NUM_MAX. CNcomment:DIAG通道支持的UART端口号, 必须小于 HI_DMS_CHL_UART_PORT_NUM_MAX */ +#define HI_DMS_CHL_UART_PORT_DIAG 1 /* */ +#define HI_DMS_CHL_PORT_ANY 0xFFF0 + +#define HI_DIAG_CHL_UART_BLOCK_WRITE_TIMEOUT 10 /* ms block write timeout */ +#define HI_DMS_CHL_UART_BLOCK_WRITE_TIMEOUT 10 /* ms block write timeout */ +#define HI_DMS_CHL_EXCEPTION_POLLING_WAIT 5000 /* ms task read dev task waiting exception Sleep */ +#define HI_DMS_CHL_FLASH_BLOCK_WRITE_TIMEOUT 10 /* ms block write timeout */ +#define HI_DMS_UART_EXCEPTION_POLLING_WAIT 1000 /* ms UART waiting exception Sleep */ +#define HI_DMS_CHL_CONNECT_DETECT_NUM 3 /* Number of client detection failures in heartbeat + mode after the channel is connected */ +#define HI_DMS_CHL_REPORT_PACKET_TIMEOUT 10 /* Batch report delay */ +#define HI_DIAG_MODULE_SYS 5 /* MSG SYS numbers of configurable categories */ +#define HI_DIAG_MODULE_DEV 30 /* MSG DEV numbers of configurable Module */ +#define HI_DIAG_MODULE_USR 5 /* MSG USR numbers of configurable categories */ + +#ifndef PRODUCT_CFG_DIAG_MSG_CFG_MAX_NUM +#define PRODUCT_CFG_DIAG_MSG_CFG_MAX_NUM 10 +#endif +#define HI_DIAG_MSG_ID_NUM (PRODUCT_CFG_DIAG_MSG_CFG_MAX_NUM) /* Number of configuration messages */ + +#define HI_DIAG_WAIT_MESSAGE_TIMEOUT 50 /* ms */ +#define HI_DIAG_WAI_DIAG_MESSAGE_TIMEOUT 100 /* Minimum interval for reporting DIAG packets. ms */ + +/* Definition range of system diagnosis IDs.CNcomment:系统诊断ID定义范围 */ +#define HI_DFX_STAT_ID_BASE_SYS 0xA000 /* SYS STAT的包ID范围: [0xA000, 0xF000) */ +#define HI_DFX_STAT_ID_MAX_SYS 0xF000 + +/* MSG SYS USR Subcategory Definition(16bit) */ +#define HI_MSG_SYS_L0 0xff10 // MSG SYS Level0 +#define HI_MSG_SYS_L1 0xff20 // MSG SYS Level1 +#define HI_MSG_SYS_L2 0xff01 // MSG SYS Level2 + +#define HI_MSG_USR_L0 0xf3e8 // MSG USR Level0 +#define HI_MSG_USR_L1 0xf3e9 // MSG USR Level1 +#define HI_MSG_USR_L2 0xf3ea // MSG USR Level2 +#define HI_MSG_USR_L3 0xf3eb // MSG USR Level3 +#define HI_MSG_USR_L4 0xf3ec // MSG USR Level4 + +#define DIAG_PROC_TASK_STACK_SIZE 2048 +#define DIAG_UART_TASK_STACK_SIZE 1536 +#define FLASH_PROTECT_TASK_STACK_SIZE 1024 +#define DATA_COLLECT_TASK_STACK_SIZE 2048 /* this statck will destroy after dc finish */ + +#ifdef HI_BOARD_ASIC +#define DIAG_QUEUE_MSG_NUM 48 +#else +#define DIAG_QUEUE_MSG_NUM 100 +#endif +#define DIAG_PROC_TASK_PRIO 25 +#define DIAG_UART_TASK_PRIO 20 +#define FLASH_PROTECT_TASK_PRIO 1 +#define DATA_COLLECT_TASK_PRIO 21 + +#define HI_MILLISECOND_PER_TICK 10 + +#define PRODUCT_CFG_FLASH_BLOCK_SIZE 0x1000 +#define PRODUCT_CFG_AUTO_WDG_RESET_SYSTEM_TIMEOUT 30000 + +#if (PRODUCT_CFG_AUTO_WDG_RESET_SYSTEM_TIMEOUT < 6500) +#error "watchdog timeout value must be more than 6500ms!" +#endif + +#define PRODUCT_CFG_DEEP_SLEEP_DEFAULT_MAX_MS (0xFFFFFFFF / 64) + +#endif /* __HI_CONFIG_H__ */ + diff --git a/sdk_liteos/include/hi_cpu.h b/sdk_liteos/include/hi_cpu.h new file mode 100644 index 0000000000000000000000000000000000000000..8e28cad6a59f2b49c094cf7fee35788c32bdd747 --- /dev/null +++ b/sdk_liteos/include/hi_cpu.h @@ -0,0 +1,257 @@ +/** + * @file hi_cpu.h + * + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @defgroup iot_cpu CPU + * @ingroup osa + */ + +#ifndef __HI_CPU_H__ +#define __HI_CPU_H__ +#include + +#define LOAD_SLEEP_TIME_DEFAULT 30 + +/** + * @ingroup iot_cpu + * + * CPU usage information structure. CNcomment:cpu使用情况信息结构 CNend + */ +typedef struct { + hi_u8 b_valid : 1; /**< Whether the information is valid. HI_TRUE: yes; HI_FALSE: no. + CNcomment:表示该条信息是否为有效信息,HI_TRUE:该条信息有效 + HI_FALSE:该条信息无效 CNend */ + hi_u8 b_task : 1; /**< Whether the message is a task or an interrupt. HI_TRUE: task; HI_FALSE: interrupt. + CNcomment:表示该条信息是任务或中断,HI_TRUE:任务 HI_FALSE:中断 CNend */ + hi_u8 pad0 : 6; /**< Reserved. CNcomment:保留 CNend */ + hi_u8 id; /**< Task ID/Interrupt number. CNcomment:当该条信息表示任务时为任务ID, + 当该条信息为中断信息时表示中断号 CNend */ + hi_u16 pad1; /**< Reserved. CNcomment:保留 CNend */ + hi_u32 permillage; /**< CPU usage (per mil). CNcomment:cpu占用率,千分比 CNend */ + hi_u64 cpu_time; /**< CPU usage time (unit: cputick), where, cputick x 160000000 = 1s. + CNcomment:cpu占用时间(单位:cputick),160000000个cputick等于1秒 CNend */ +} hi_cpup_item; + + +typedef enum { + HI_CPU_CLK_80M, /**< cpu clock:80M. CNcomment:CPU工作频率:80M CNend */ + HI_CPU_CLK_120M, /**< cpu clock:120M. CNcomment:CPU工作频率:120M CNend */ + HI_CPU_CLK_160M, /**< cpu clock:160M. CNcomment:CPU工作频率:160M CNend */ + HI_CPU_CLK_MAX /**< Maximum cpu clock, which cannot be used. CNcomment:CPU最大工作频率, + 不可使用CNend */ +} hi_cpu_clk; + +/** +* @ingroup iot_cpu +* @brief Obtains the CPU usage. CNcomment:获取CPU使用情况。CNend +* +* @par 描述: +* Obtains the CPU usage between the initialization of the CPU usage module is started or +* the CPU usage statistics are reset to each task/interrupt. +CNcomment:获取cpu占用率模块初始化开始或cpu占用率统计信息重置开始统计到个各任务(中断) +CPU占用情况。CNend +* +* @attention +* @li A task/interrupt not scheduled after the CPU usage module is initialized or +* the CPU usage statistics are reset is excluded. +CNcomment:cpu占用率模块初始化或cpu占用率统计信息重置之后没有调度到的任务或中断 +不会被统计。CNend +* +* @param array_count [IN] type #hi_u32 Number of CPU usage records that can be stored +* in the space corresponding to cpup_items. CNcomment:表示p_cpup_items对应的空间可以 +存储多少条cpu使用情况信息。CNend +* @param p_cpup_items [OUT] type #hi_cpup_item* CPU usage information space, applied by the caller. +CNcomment:cpu使用情况信息空间,由调用者申请。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par Dependency: +* @li hi_cpu.h: Describes CPU usage APIs. +CNcomment:文件用于描述cpu相关接口。CNend +* @see None +*/ +hi_u32 hi_cpup_get_usage(hi_u32 array_count, hi_cpup_item *p_cpup_items); + +/** +* @ingroup iot_cpu +* @brief Resets CPU usage statistics. CNcomment:重置cpu使用情况信息。CNend +* +* @param None +* +* @retval #None +* @par 描述: +* Resets CPU usage statistics. After the reset, the CPU usage statistics of all tasks and interrupts are +* cleared. CNcomment:重置cpu使用情况信息,重置后所有任务和中断的cpu占用率清0。CNend +* +* @attention None +* +* @par Dependency: +* @li hi_cpu.h: Describes CPU usage APIs. +CNcomment:文件用于描述cpu相关接口。CNend +* @see None +*/ +hi_void hi_cpup_reset_usage(hi_void); + +/** +* @ingroup iot_cpu +* @brief Set CPU clock. CNcomment:设置CPU的工作频率。CNend +* +* @par 描述: +* Set CPU clock, such as 80M/120M/160M. +* CNcomment:设置CPU的工作频率,如80M/120M/160M。CNend +* +* @attention Default CPU clock is 160M, if change CPU clock, Shoud config it +both in System Startup and DeepSleep Wakeup stage.CNcomment:CPU默认工作频率为160M, +如果改变CPU的工作频率,需要在系统启动和深睡唤醒阶段均进行配置。CNend +* @param clk [IN] type #hi_cpu_clk,cpu clk. CNcomment:CPU工作频率。CNend +* +* @retval #HI_ERR_SUCCESS Success. +* @retval #HI_ERR_CPU_CLK_INVALID_PARAM invalid clk. CNcomment:工作频率无效。CNend +* +* @par Dependency: +* @li hi_cpu.h: Describes CPU usage APIs. +CNcomment:文件用于描述cpu相关接口。CNend +* @see None +*/ +hi_u32 hi_cpu_set_clk(hi_cpu_clk clk); + +/** +* @ingroup iot_cpu +* @brief Get CPU clock. CNcomment:获取CPU的工作频率。CNend +* +* @par 描述: +* Get CPU clock, such as 80M/120M/160M. +* CNcomment:获取CPU的工作频率,如80M/120M/160M。CNend +* +* @attention None +* @param None +* +* @retval #hi_cpu_clk cpu clk. +* +* @par Dependency: +* @li hi_cpu.h: Describes CPU usage APIs. +CNcomment:文件用于描述cpu相关接口。CNend +* @see None +*/ +hi_cpu_clk hi_cpu_get_clk(hi_void); + +/** +* @ingroup iot_cpu +* @brief check cpu load percent and sleep. CNcomment:检查idle任务cpu占有率, +如果小于门限则对当前任务进行睡眠。CNend +* +* @par 描述: +* check cpu load percent of idle task, if smaller than the threshold +(5%), Then sleep. CNcomment:检查idle任务cpu占有率,如果小于门限(5%)则对当前任务 +进行睡眠。CNend +* +* @attention None +* +* @param task_id [IN] type #hi_u32,current task ID. +CNcomment:当前固定填写当前任务ID。CNend +* @param ms [IN] type #hi_u32,sleep time:当前任务睡眠时间。CNend +* +* @retval None +* @par Dependency: +* @li hi_cpu.h: Describes CPU usage APIs. +CNcomment:文件用于描述cpu相关接口。CNend +* @see None +*/ +hi_void hi_cpup_load_check_proc(hi_u32 task_id, hi_u32 ms); + +/** +* @ingroup iot_cpu +* @brief Enable Dcache. CNcomment:使能DCache。CNend +* +* +* @par 描述: +* Enable Dcache,system default Enable Dcache after startup. +CNcomment:使能DCache,系统启动默认使能。CNend +* +* @attention None +* +* @param None +* +* @retval #None +* @par Dependency: +* @li hi_cpu.h: Describes CPU usage APIs. +CNcomment:文件用于描述cpu相关接口。CNend +* @see None +*/ +hi_void hi_cache_enable(hi_void); + +/** +* @ingroup iot_cpu +* @brief Disable Dcache. CNcomment:禁用DCache。CNend +* +* @par 描述: +* Disable Dcache. CNcomment:禁用DCache。CNend +* +* @attention: +* flush cache before disable. CNcomment:禁用Dcache前需要刷Cache。CNend +* +* @param None +* +* @retval #None +* @par Dependency: +* @li hi_cpu.h: Describes CPU usage APIs. +CNcomment:文件用于描述cpu相关接口。CNend +* @see None +*/ +hi_void hi_cache_disable(hi_void); + +/** +* @ingroup iot_cpu +* @brief Flush Dcache. CNcomment:Flush DCache。CNend +* +* @par 描述: +* Flush Dcache, synchronize Dcache and memory. +CNcomment:刷新DCache,维持DCache和memory同步。CNend +* +* @attention None +* +* @param None +* +* @retval #None +* @par Dependency: +* @li hi_cpu.h: Describes CPU usage APIs. +CNcomment:文件用于描述cpu相关接口。CNend +* @see None +*/ +hi_void hi_cache_flush(hi_void); + +/** +* @ingroup iot_cpu +* @brief Flush Icache. CNcomment:Flush ICache。CNend +* +* @par 描述: +* Flush Icache, synchronize Icache and memory. +CNcomment:刷新ICache,维持ICache和memory同步。CNend +* +* @attention None +* +* @param None +* +* @retval #None +* @par Dependency: +* @li hi_cpu.h: Describes CPU usage APIs. +CNcomment:文件用于描述cpu相关接口。CNend +* @see None +*/ +hi_void hi_icache_flush(hi_void); + +#endif diff --git a/sdk_liteos/include/hi_crash.h b/sdk_liteos/include/hi_crash.h new file mode 100644 index 0000000000000000000000000000000000000000..9a154a64de92afb64b15caa3b47fa18de95ba3ba --- /dev/null +++ b/sdk_liteos/include/hi_crash.h @@ -0,0 +1,444 @@ +/** +* @file hi_crash.h +* +* Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/** @defgroup iot_crash_info Crash Log Management + * @ingroup system + */ + +#ifndef __HI_CRASH_H__ +#define __HI_CRASH_H__ +#include +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** +* @ingroup iot_crash_info +* +* Version of the crash log module. CNcomment:死机存储模块版本号。CNend +*/ +#define HI_SYSERR_VERSION 1 + +/** +* @ingroup iot_crash_info +* +* Power down flag. CNcomment:下电标识。CNend +*/ +#define HI_SYSERR_POWER_DOWN 0x646F776E /* 下电标志 */ + +/** +* @ingroup iot_crash_info +* +* No power down flag. CNcomment:未下电标识。CNend +*/ +#define HI_SYSERR_NO_POWER_DOWN 0xFFFFFFFF + +/** +* @ingroup iot_crash_info +* +* Length of the name string of an exception type. CNcomment:异常类型的名字字符串长度限制。CNend +*/ +#define HI_SYSERR_EXC_TYPE_NAME_SIZE 8 + +/** +* @ingroup iot_crash_info +* +* Length of the task name string of a logged exception. +CNcomment:异常存储的任务名字字符串长度限制。CNend +*/ +#define HI_SYSERR_EXC_TASK_NAME_SIZE 8 + +/** +* @ingroup iot_crash_info +* +* Depth of the scheduling track before an exception. CNcomment:异常前调度轨迹深度。CNend +*/ +#define HI_SYSERR_EXC_TRACE_DEPTH 10 + +/** +* @ingroup iot_crash_info +* +* Exception stack information depth (unit: word). CNcomment:异常栈信息深度(word为单位)CNend +*/ +#define HI_SYSERR_ESP_DATA_MAX_NUM 36 + +/** +* @ingroup iot_crash_info +* +* Extended depth of the exception stack SP to the stack bottom (unit: word). +CNcomment:异常栈sp向栈底扩展深度(word为单位)CNend +*/ +#define HI_SYSERR_ESP_PRE_DATA_MAX_NUM 8 + +/** +* @ingroup iot_crash_info +* +* Version of the running kernel when the exception occurs. CNcomment:异常时对应的运行版本的版本号CNend +*/ +#define HI_SYSERR_EXC_KERNEL_VER_LEN_MAX 60 +#if !defined(PRODUCT_CFG_HSO) +#if (HI_SYSERR_EXC_KERNEL_VER_LEN_MAX < HI_BUILD_VER_PRODUCT_LEN_MAX) +#error "HI_SYSERR_EXC_KERNEL_VER_LEN_MAX != HI_BUILD_VER_PRODUCT_LEN_MAX" +#endif +#endif + +/** +* @ingroup iot_crash_info +* Crash type eid.CNcomment:死机类型eid.CNend +*/ +typedef enum { + HI_SYSERR_EID_POWER_DOWN, /**< Power Down or first Power on.CNcomment:下电重启或首次上电.CNend */ + HI_SYSERR_EID_FAULT_IN_TASK, /**< fault in task.CNcomment:任务中死机.CNend */ + HI_SYSERR_EID_FAULT_IN_ISR, /**< fault in isr.CNcomment:中断中死机.CNend */ + HI_SYSERR_EID_WATCHDOG_TSK, /**< watchdog reset(in task).CNcomment:看门狗死机(任务中).CNend */ + HI_SYSERR_EID_WATCHDOG_ISR, /**< watchdog reset(in isr).CNcomment:看门狗死机(中断中).CNend */ + HI_SYSERR_EID_SYS_SOFT_REBOOT, /**< system soft reboot.CNcomment:系统软复位.CNend */ + HI_SYSERR_EID_RESERVE, + HI_SYSERR_EID_MAX = 0xFF, +} hi_syserr_eid; + +/* cpu registers */ +typedef struct { + hi_u32 mepc; + hi_u32 ra; + hi_u32 sp; + hi_u32 gp; + hi_u32 tp; + hi_u32 t0; + hi_u32 t1; + hi_u32 t2; + hi_u32 s0; + hi_u32 s1; + hi_u32 a0; + hi_u32 a1; + hi_u32 a2; + hi_u32 a3; + hi_u32 a4; + hi_u32 a5; + hi_u32 a6; + hi_u32 a7; + hi_u32 s2; + hi_u32 s3; + hi_u32 s4; + hi_u32 s5; + hi_u32 s6; + hi_u32 s7; + hi_u32 s8; + hi_u32 s9; + hi_u32 s10; + hi_u32 s11; + hi_u32 t3; + hi_u32 t4; + hi_u32 t5; + hi_u32 t6; +} syserr_reg_info; + +/** +* @ingroup iot_crash_info +* Task information.CNcomment:任务信息.CNend +*/ +typedef struct { + hi_char name[HI_SYSERR_EXC_TASK_NAME_SIZE]; + hi_u32 id; /**< task id.CNcomment:任务ID.CNend */ + hi_u32 status; /**< task status.CNcomment:任务运行状态.CNend */ + hi_u8 reserve[3]; /* reserve's size 3 */ + hi_u8 stack_data_index; /**< extended stack information index from stack bottom.CNcomment: + 向栈底扩展的栈信息个数.CNend */ + hi_u16 stack_peak; /**< stack peak.CNcomment:栈使用峰值.CNend */ + hi_u16 stack_size; /**< stack size.CNcomment:任务栈大小.CNend */ + hi_u32 sp; /**< stack point.CNcomment:栈指针.CNend */ + hi_u32 stack[2]; /**< stack[2] is stack top and end address.CNcomment:栈顶和栈底地址.CNend */ + hi_u32 real_sp; /**< real stack point.CNcomment:真实栈指针.CNend */ + hi_u32 stack_pre_data[HI_SYSERR_ESP_PRE_DATA_MAX_NUM]; /**< extended stack information from stack bottom.CNcomment: + 向栈底扩展的栈信息,用于回退栈类错误参考.CNend */ + hi_u32 stack_data[HI_SYSERR_ESP_DATA_MAX_NUM]; /**< stack data.CNcomment:栈数据.CNend */ + hi_u32 overflow_flag; /**< stack overflow flag.CNcomment:栈溢出标识.CNend */ +} syserr_task_info; + +/** +* @ingroup iot_crash_info +* OS information.CNcomment:操作系统信息.CNend +*/ +typedef struct { + hi_os_resource_use_stat usage; /**< os resource used count.CNcomment:系统资源使用个数.CNend */ + syserr_task_info task; /**< task information.CNcomment:任务信息.CNend */ + hi_mem_pool_crash_info mem; /**< memory pool information.CNcomment:动态内存池信息.CNend */ +} syserr_os_info; + +/** +* @ingroup iot_crash_info +* Basic information.CNcomment:基础信息.CNend +*/ +typedef struct { + hi_u16 log_ver; /**< log version.CNcomment:Log版本号.CNend */ + hi_u16 eid; /**< reset reason id.CNcomment:复位类型.CNend */ + hi_u32 rid; /**< exception id.CNcomment:异常类型.CNend */ + hi_u32 now_tsec; /**< current time relative start time.CNcomment:当前运行相对启动时间.CNend */ + hi_u32 crash_tsec; /**< crash time relative start time.CNcomment:异常时相对当次启动时间.CNend */ + hi_u32 boot_ver; + hi_char kernel_ver[HI_SYSERR_EXC_KERNEL_VER_LEN_MAX]; /**< kernel version.CNcomment:异常时运行版本的版本号.CNend */ + hi_char type_name[HI_SYSERR_EXC_TYPE_NAME_SIZE]; /**< reset reason name.CNcomment:类型名:与eid对应.CNend */ +} syserr_basic_info; + +/** +* @ingroup iot_crash_info +* Watchdog information.CNcomment:看门狗信息.CNend +*/ +typedef struct { + hi_u32 wdg_reset_pc; /**< watchdog reset reserved PC.CNcomment:看门狗复位PC.CNend */ + hi_u32 time_ms : 31; /**< watchdog timeout.CNcomment:看门狗超时时间.CNend */ + hi_u32 enable : 1; /**< watchdog enable.CNcomment:看门狗使能状态.CNend */ +} syserr_wdg_info; + +/** +* @ingroup iot_crash_info +* Flash protect information.CNcomment:Flash保护信息.CNend +*/ +typedef struct { + hi_u32 current_block : 13; /**< flash protect current block.CNcomment:Flash保护当前block.CNend */ + hi_u32 reserve : 18; + hi_u32 enable : 1; /**< flash protect enable.CNcomment:Flash保护使能状态.CNend */ + hi_u32 status_reg; /**< flash protect status.CNcomment:Flash保护状态寄存器.CNend */ +} syserr_fp_info; + +/** +* @ingroup iot_crash_info +* Track item information.CNcomment:调度项信息.CNend +*/ +typedef struct { + hi_u16 type; /**< track type.CNcomment:调度类型.CNend */ + hi_u16 id; /**< track ID.CNcomment:调度项id.CNend */ + hi_u32 data; /**< track userdata.CNcomment:调度用户数据.CNend */ + hi_u32 entry; /**< track Hook function Entry.CNcomment:调度回调勾子函数.CNend */ + hi_u32 timestamp; /**< The low 32 bit of the current time,us.CNcomment:调度时间戳.CNend */ +} syserr_track_item; + +/** +* @ingroup iot_crash_info +* Track information.CNcomment:调度轨迹信息.CNend +*/ +typedef struct { + hi_u16 current_item; /**< current track item.CNcomment:当前调度项.CNend */ + hi_u16 item_cnt; /**< track count of track information.CNcomment:调度项记录个数.CNend */ + syserr_track_item item[HI_SYSERR_EXC_TRACE_DEPTH]; /**< track item data.CNcomment:调度项数据.CNend */ +} syserr_track_info; + +/** +* @ingroup iot_crash_info +* CPU csr registers information.CNcomment:CPU CSR寄存器信息.CNend +*/ +typedef struct { + hi_u32 mstatus; /**< CPU mstatus register value.CNcomment:CPU mstatus寄存器值.CNend */ + hi_u32 mtval; /**< CPU mtval register value.CNcomment:CPU mtval寄存器值.CNend */ + hi_u32 mcause; /**< CPU mcause register value.CNcomment:CPU mcause寄存器值.CNend */ + hi_u32 ccause; /**< CPU ccause register value.CNcomment:CPU ccause寄存器值.CNend */ + hi_u16 cur_task_id; /**< current task id.CNcomment:当前任务ID.CNend */ +} syserr_core_info; + +/** +* @ingroup iot_crash_info +* Saved exception information.CNcomment:异常时对应存储信息。CNend +*/ +typedef struct { + hi_u32 sig_s; /**< header flag of crash information.CNcomment:异常信息前标识.CNend */ + hi_u32 power_down : 1; /**< power down flag.CNcomment:下电标识.CNend */ + hi_u32 crc_usable : 1; /**< CRC check enable of crash information.CNcomment:死机信息CRC校验使能.CNend */ + hi_u32 info_len : 14; /**< crash information length.CNcomment:死机信息长度.CNend */ + hi_u32 crc_val : 16; /**< CRC16 calue of crash information.CNcomment:CRC16校验值.CNend */ + + syserr_basic_info basic_info; /**< basic data of crash information.CNcomment:死机基础信息.CNend */ + syserr_os_info os_info; /**< OS data of crash information.CNcomment:死机OS信息.CNend */ + syserr_reg_info reg_info; /**< CPU registers of crash information.CNcomment:死机CPU寄存器信息.CNend */ + syserr_wdg_info wdg_info; /**< watchdog data of crash information.CNcomment:死机看门狗.CNend */ + syserr_fp_info protect_info; /**< flash protect data of crash information.CNcomment:死机Flash保护信息.CNend */ + syserr_track_info track_info; /**< track data of crash information.CNcomment:死机调度信息.CNend */ + syserr_core_info core_info; /**< CPU CSR registers of crash information.CNcomment:死机CPU状态寄存器信息.CNend */ + hi_u32 sig_e; /**< end flag of crash information.CNcomment:异常信息后标识.CNend */ +} hi_syserr_info; + +typedef hi_void (*hi_syserr_exc_callback)(hi_void); + +/** +* @ingroup iot_crash_info +* @brief Initializes the exception information module. CNcomment:异常信息模块初始化。CNend +* +* @par 描述: +* Initializes the exception information module. CNcomment:异常信息模块初始化。CNend +* +* @attention s API can be called only once. Repeated initialization and multi-task calling are not supported. +CNcomment:仅初始化一次,未考虑多次初始化及多任务调用场景。CNend +* @param None +* +* @retval None +* @par 依赖: +* @li hi_crash.h:Describes Crash log APIs. CNcomment:文件用于描述死机相关接口。CNend +* @see None +*/ +hi_void hi_syserr_init(hi_void); + +/** +* @ingroup iot_crash_info +* @brief Obtains the system exception information pointer (in the memory). +CNcomment:获取系统异常信息指针(内存中)。CNend +* +* @par 描述: +* Obtains the system exception information pointer (in the memory). +CNcomment:获取系统异常信息指针(内存中)。CNend +* +* @attention None +* @param None +* +* @retval Pointer to the hi_syserr_info structure. CNcomment:hi_syserr_info结构体指针。CNend +* @par 依赖: +* @li hi_crash.h:Describes Crash log APIs. CNcomment:文件用于描述死机相关接口。CNend +* @see None +*/ +hi_syserr_info *hi_syserr_ptr(hi_void); + +/** +* @ingroup iot_crash_info +* @brief Obtains the system exception information pointer (in the flash). +CNcomment:获取系统异常信息指针(flash中)。CNend +* +* @par 描述: +* Obtains the system exception information pointer (in the flash). +CNcomment:获取系统异常信息指针(flash中)。CNend +* +* @attention None +* @param info [OUT] type #hi_syserr_info* ,Pointer to the hi_syserr_info structure. +CNcomment:异常信息读出后存放地址。CNend +* +* @retval #HI_ERR_SUCCESS Success. +* @retval #Other values Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_crash.h:Describes Crash log APIs. CNcomment:文件用于描述死机相关接口。CNend +* @see None +*/ +hi_u32 hi_syserr_get(hi_syserr_info *info); + +/** +* @ingroup iot_crash_info +* @brief Register exception handling callback. CNcomment:注册异常死机处理回调函数。CNend +* +* @par 描述: +* Register exception handling callback. CNcomment:注册异常死机处理回调函数。CNend +* +* @attention None +* @param func [IN] type #hi_syserr_exc_callback ,Callback function of exception happens +CNcoment:异常回调函数。CNend +* +* @retval None +* @par 依赖: +* @li hi_crash.h:Describes Crash log APIs. CNcomment:文件用于描述死机相关接口。CNend +* @see None +*/ +hi_void hi_syserr_exc_register(hi_syserr_exc_callback func); + +/** +* @ingroup iot_crash_info +* @brief Retains the PC pointer when the watchdog reset in interrupt. CNcomment:中断中看门狗复位时记录PC值。CNend +* +* @par 描述: +* Retains the PC pointer when the watchdog reset in interrupt. +CNcomment:中断中看门狗复位时记录PC值,打开此功能后看门狗复位有复位不完全的风险,量产版本请务必关闭。CNend +* +* @attention None +* @param enable [IN] type #hi_bool ,Enable/Disable retains reset PC pointer function. +CNcoment:打开/关闭记录中断中看门狗复位PC值功能。CNend +* +* @retval None +* @par 依赖: +* @li hi_crash.h:Describes Crash log APIs. CNcomment:文件用于描述死机相关接口。CNend +* @see None +*/ +hi_void hi_syserr_watchdog_debug(hi_bool enable); + +/** +* @ingroup iot_crash_info +* @brief Whether reset after watchdog in task, default yes. CNcomment: 任务中触发看门狗时是否主动复位,默认复位。CNend +* +* @par 描述: +* Whether reset after wdt in task, default yes. +CNcomment: 任务中触发看门狗时是否主动复位,默认复位。CNend +* +* @attention None +* @param reset [IN] type #hi_bool ,Reset/Not reset after watchdog in task. +CNcoment:任务中触发看门狗时是否主动复位。CNend +* +* @retval None +* @par 依赖: +* @li hi_crash.h:Describes Crash log APIs. CNcomment:文件用于描述死机相关接口。CNend +* @see None +*/ +hi_void hi_syserr_reset_after_wdg(hi_bool reset); + +/** +* @ingroup iot_crash_info +* @brief Whether record crash info in flash, default no. CNcomment: 是否记录宕机信息到FLASH,默认不记录。CNend +* +* @par 描述: +* Whether record crash info in flash, default no. +CNcomment: 是否记录宕机信息到FLASH,默认不记录。CNend +* +* @attention None +* @param record [IN] type #hi_bool ,Record/Not record crash info in flash. +CNcoment:宕机时是否记录宕机信息到FLASH。CNend +* +* @retval None +* @par 依赖: +* @li hi_crash.h:Describes Crash log APIs. CNcomment:文件用于描述死机相关接口。CNend +* @see None +*/ +hi_void hi_syserr_record_crash_info(hi_bool record); + +/** +* @ingroup iot_crash_info +* @brief Retains the latest reboot reason. CNcomment:获取最近一次重启原因。CNend +* +* @par 描述: +* Retains the latest reboot reason. +CNcomment:获取最近一次重启原因。CNend +* +* @attention None +* @param err_id [OUT] type #hi_u16 * , error id, see hi_syserr_eid. +power_down or hard rebootwould always be 0. +CNcomment:重启原因ID,取值含义参见hi_syserr_eid,掉电重启和硬复位值均为0。CNend +* @param reboot_cause [OUT] type #hi_u32* , when err_id is soft reboot, see hi_sys_reboot_cause; +when err_id is fault in task or isr, reboot_cause would be mcause of cpu regs. Otherwise, reboot_cause would be 0. +CNcomment:当重启原因ID 为软复位时,取值含义见hi_sys_reboot_cause; +当为任务或中断中异常时,取值为cpu mcause寄存器,否则为0。 +CNend +* +* @retval #HI_ERR_SUCCESS Success. +* @retval #Other Failure. See hi_errno.h for details. +* @par 依赖: +* @li hi_crash.h:Describes Crash log APIs. CNcomment:文件用于描述死机相关接口。CNend +* @see None +*/ +hi_u32 hi_syserr_get_reboot_reason(hi_u16 *err_id, hi_u32 *reboot_cause); + + +#ifdef __cplusplus +} +#endif + +#endif /* __HI_CRASH_H__ */ diff --git a/sdk_liteos/include/hi_crc.h b/sdk_liteos/include/hi_crc.h new file mode 100644 index 0000000000000000000000000000000000000000..7635a31817b2d91fedb1bb5ce5de0f8740121835 --- /dev/null +++ b/sdk_liteos/include/hi_crc.h @@ -0,0 +1,76 @@ +/** + * @file hi_crc.h + * + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @defgroup iot_crc CRC Verification + * @ingroup system + */ + +#ifndef __HI_CRC_H__ +#define __HI_CRC_H__ +#include + +/** +* @ingroup iot_crc +* @brief Generates a 16-bit CRC value.CNcomment:生成16位CRC校验值。CNend +* +* @par 描述: +* Generates a 16-bit CRC value.CNcomment:生成16位CRC校验值。CNend +* +* @attention None +* @param crc_start [IN] type #hi_u16,The CRC initial value.CNcomment:CRC初始值。CNend +* @param buf [IN] type #const hi_u8*,Pointer to the buffer to be verified. +CNcomment:被校验Buffer指针。CNend +* @param len [IN] type #hi_u32,Length of the buffer to be verified (unit: Byte). +CNcomment:被校验Buffer长度(单位:byte)。CNend +* @param crc_result [OUT]type #hi_u16*,CRC calculation result.CNcomment:CRC计算结果。CNend +* +* @retval #0 Success. +* @retval #Other Failure. +* +* @par 依赖: +* @li hi_crc.h:Describes CRC APIs.CNcomment:文件包含CRC校验接口。CNend +* @see None +*/ +hi_u32 hi_crc16(hi_u16 crc_start, const hi_u8 *buf, hi_u32 len, hi_u16 *crc_result); + +/** +* @ingroup iot_crc +* @brief Generates a 32-bit CRC value.CNcomment:生成32位CRC校验值。CNend +* +* @par 描述: +* Generates a 32-bit CRC value.CNcomment:生成32位CRC校验值。CNend +* +* @attention None +* @param crc_start [IN] type #hi_u32,The CRC initial value.CNcomment:CRC初始值。CNend +* @param buf [IN] type #const hi_u8*,Pointer to the buffer to be verified. +CNcomment:被校验Buffer指针。CNend +* @param len [IN] type #hi_u32,Length of the buffer to be verified (unit: Byte). +CNcomment:被校验Buffer长度(单位:byte)。CNend +* @param crc_result [OUT]type #hi_u32*,CRC calculation result.CNcomment:CRC计算结果。CNend +* +* @retval #0 Success. +* @retval #Other Failure. +* +* @par 依赖: +* @li hi_crc.h:Describes CRC APIs.CNcomment:文件包含CRC校验接口。CNend +* @see None +*/ +hi_u32 hi_crc32(hi_u32 crc_start, const hi_u8 *buf, hi_u32 len, hi_u32 *crc_result); + +#endif + diff --git a/sdk_liteos/include/hi_diag.h b/sdk_liteos/include/hi_diag.h new file mode 100644 index 0000000000000000000000000000000000000000..3c420c686776ff5d96ee34641a0ee141352eac6e --- /dev/null +++ b/sdk_liteos/include/hi_diag.h @@ -0,0 +1,725 @@ +/** +* @file hi_diag.h +* +* Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/** @defgroup iot_diag Diagnostic + * @ingroup dfx + */ + +#ifndef __HI_DIAG_H__ +#define __HI_DIAG_H__ + +#include +#include + +/** +* @ingroup iot_diag +* @brief Registers the callback function for DIAG channel status changes. +CNcomment:注册DIAG通道状态变更回调函数。CNend +* +* @par 描述: +* Registers the callback function for DIAG channel status changes. That is, when the DIAG channel is +* connected or disconnected, the function registered by this API is called back. +CNcomment:注册DIAG通道变更回调函数(即:当DIAG通道连接或断开时,会回调本接口注册的函数)。CNend +* +* @attention None +* @param connect_notify_func [IN] type #hi_diag_connect_f,User function. CNcomment:用户函数。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_diag.h:Describes DIAG APIs. +CNcomment:文件用于描述DIAG相关接口。CNend +* @see None +*/ +HI_EXTERN hi_u32 hi_diag_register_connect_notify(hi_diag_connect_f connect_notify_func); + +/** +* @ingroup iot_diag +* @brief Checks the connection status of the DIAG channel. CNcomment:检测DIAG通道连接状态的函数。CNend +* +* @par 描述: +* Checks the connection status of the DIAG channel. CNcomment:检测DIAG通道是否处于连接状态的函数 。CNend +* +* @attention None +* @param None +* +* @retval HI_FALSE disconnected. CNcomment:处于非连接状态。CNend +* @retval HI_TRUE connected. CNcomment:处于连接状态。CNend +* @par 依赖: +* @li hi_diag.h:Describes DIAG APIs. +CNcomment:文件用于描述DIAG相关接口。CNend +* @see None +*/ +HI_EXTERN hi_bool hi_diag_is_connect(hi_void); + +/** +* @ingroup iot_diag +* @brief Registers the command handling function. CNcomment:注册命令处理函数。CNend +* +* @par 描述: +* @li Called at initialize stage, does NOT support multiable task calls. +CNcomment:在初始化阶段调用, 不支持多任务调用。CNend +* @li The DIAG subsystem supports a maximum of 10 different command tables. +CNcomment:最多能注册10个不同的命令表。CNend +* +* @attention None +* @param p_cmd_tbl [IN] type #const hi_diag_cmd_reg_obj*,Command table, which must be declared as a constant array +* and transmitted to this parameter. +CNcomment:命令表,必须申明为常量数组传给该参数。CNend +* @param cmd_num [IN] type #hi_u16,Number of commands. The value cannot be 0. CNcomment:命令个数, +如果usCmdNum为0而pstCmdTbl不为0,则取消注册。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_diag.h:Describes DIAG APIs. +CNcomment:文件用于描述DIAG相关接口。CNend +* @see None +*/ +HI_EXTERN hi_u32 hi_diag_register_cmd(const hi_diag_cmd_reg_obj* cmd_tbl, hi_u16 cmd_num); + +/** +* @ingroup iot_diag +* @brief Reports DIAG packets. CNcomment:DIAG包上报。CNend +* +* @par 描述: +* Reports DIAG channel packets to the DIAG client. +CNcomment:该函数用于将DIAG通道报文上报给DIAG客户端。CNend +* +* @attention +* This API can not be used in interrupt when report data synchronously. +CNcomment:当同步上报数据时,该接口不支持在中断中调用。CNend +* @param cmd_id [IN] type #hi_u16,DIAG data packet ID. CNcomment:DIAG应答包ID。CNend +* @param instance_id [IN] type #hi_u8,Command type.This parameter is used to obtain the command type in the +* option parameter of the command callback function hi_diag_cmd_f.currently only support +* HI_DIAG_CMD_INSTANCE_LOCAL. +CNcomment:命令类型。在命令回调函数hi_diag_cmd_f的option参数中获取命令类型,在函数中使用 +此接口回复报文时,通过本参数传递。当前仅支持HI_DIAG_CMD_INSTANCE_LOCAL。CNend +* @param buffer [IN] type #hi_pbyte,Buffer address of the data packet. This function does not release the +* pointer. CNcomment:数据包的buffer地址,该函数不会释放该指针。CNend +* @param buffer_size [IN] type #hi_u16,Data packet size (unit: byte), range[0, 65507] +CNcomment:数据包大小(单位:byte),取值范围[0, 65507]。CNend +* @param sync [IN] type #hi_bool,Synchronous or asynchronous DIAG packet pushing. TRUE indicates that the +* packets are pushed synchronously and the operation is blocked. FALSE indicates the packets +* are pushed asynchronously (with the memory allocated, the packet is cashed by the OS queue +* before being pushed), and the operation is not blocked. +CNcomment:DIAG包同步/异步上报设置。TRUE表示同步上报, 阻塞操作; FALSE表示异步 +(通过分配内存后, 由OS队列缓存再上报), 非阻塞操作。CNend +* +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_diag.h:Describes DIAG APIs. +CNcomment:文件用于描述DIAG相关接口。CNend +* @see None +*/ +HI_EXTERN hi_u32 hi_diag_report_packet(hi_u16 cmd_id, hi_u8 instance_id, hi_pbyte buffer, + hi_u16 buffer_size, hi_bool sync); + +/** +* @ingroup iot_diag +* @brief Sends ACK packets to the DIAG client. CNcomment:应答回复。CNend +* +* @par 描述: +* Sends ACK packets to the DIAG client. CNcomment:该函数用于回复报文或ACK给DIAG客户端。CNend +* +* @attention +* This API can not be used in interrupt.CNcomment:该接口不支持在中断中调用。CNend +* @param cmd_id [IN] type #hi_u16,DIAG ACK packet ID. CNcomment:DIAG包ID。CNend +* @param instance_id [IN] type #hi_u8,Command type.This parameter is used to obtain the command type in the +* option parameter of the command callback function hi_diag_cmd_f.currently only support +* HI_DIAG_CMD_INSTANCE_LOCAL. +CNcoment:在命令回调函数HI_DIAG_CMD_F的option参数中获取命令类型,在函数中使用此接口回复 +报文时,通过本参数传递。当前仅支持HI_DIAG_CMD_INSTANCE_LOCAL。CNend +* @param buffer [IN] type #hi_pbyte,Buffer address of the data packet. This function does not release the +* pointer. CNcomment:数据包的buffer地址,该函数不会释放该指针。CNend +* @param buffer_size [IN] type #hi_u16,Data packet size(unit: byte), range[0, 1024] +CNcomment:数据包大小(单位:byte),取值范围[0, 1024]。CNend +* +* @retval #HI_ERR_CONSUMED Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_diag.h:Describes DIAG APIs. +CNcomment:文件用于描述DIAG相关接口。CNend +* @see None +*/ +HI_EXTERN hi_u32 hi_diag_send_ack_packet(hi_u16 cmd_id, hi_u8 instance_id, hi_pvoid buffer, hi_u16 buffer_size); + +/** +* @ingroup iot_diag +* @brief Registers the callback function for notifying DIAG operations. +CNcomment:注册DIAG操作通知回调函数。CNend +* +* @par 描述: +* Carbon copies data to the app layer by using a callback function in the case of data interaction between +* the host and the board.CNcommand:该函数用于当上位机与单板有数据交互发生时, +将数据通过回调函数抄送给应用层。CNend +* +* @attention None +* @param cmd_notify_func [IN] type #hi_diag_cmd_notify_f*,When data interaction occurs between the HSO and the board, +* this API is used to notify the app layer. +CNcomment:当HSO与单板有数据交互发生时,通过该接口通知应用层。CNend +* +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_diag.h:Describes DIAG APIs. +CNcomment:文件用于描述DIAG相关接口。CNend +* @see None +*/ +HI_EXTERN hi_u32 hi_diag_register_cmd_notify(hi_diag_cmd_notify_f cmd_notify_func); + +/** +* @ingroup iot_diag +* @brief Sets the UART parameters of the DIAG channel. CNcomment:设置诊断通道UART参数。CNend +* +* @par 描述: +* Sets the UART parameters of the used by the DIAG subsystem before the DIAG subsystem is initialized. +CNcomment:该函数用于在诊断子系统初始化之前,设置诊断子系统使用的UART的相关参数。CNend +* +* @attention The parameters must be set before the initialization of the DIAG subsystem. +CNcomment:必须在诊断子系统初始化之前设置才可生效。CNend +* @param uart_port [IN] type #hi_uart_idx,UART port number used by the DIAG subsystem. +CNcomment:诊断子系统使用的UART端口号。CNend +* @param uart_cfg [IN] type #hi_uart_attribute,UART configuration used by the DIAG subsystem. +CNcomment:诊断子系统使用的UART配置。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_diag.h:Describes DIAG APIs. +CNcomment:文件用于描述DIAG相关接口。CNend +* @see None +*/ +HI_EXTERN hi_u32 hi_diag_set_uart_param(hi_uart_idx uart_port, hi_uart_attribute uart_cfg); + +/** +* @ingroup iot_diag +* @brief Initializes the DIAG subsystem. CNcomment:诊断子系统初始化。CNend +* +* @par 描述: +* Initializes the DIAG subsystem. CNcomment:该函数用于初始化诊断子系统。CNend +* +* @attention The initialization of the DIAG subsystem needs to be performed only once. Repeated initialization is +* invalid. CNcomment:诊断子系统初始化只需执行一次,多次初始化无效。CNend +* @param None +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_diag.h:Describes DIAG APIs. +CNcomment:文件用于描述DIAG相关接口。CNend +* @see None +*/ +HI_EXTERN hi_u32 hi_diag_init(hi_void); + +/** +* @ingroup iot_diag +* +* Structure for querying the number of command tables and statistic object tables. +CNcomment:命令注册列表和统计量对象注册列表个数查询结构体。CNend +*/ +typedef struct { + hi_u8 cmd_list_total_cnt; /**< Number of command registration tables can be registered. + CNcomment:总共支持注册的命令列表个数 CNend */ + hi_u8 cmd_list_used_cnt; /**< Number of registered command tables. + CNcomment:已经注册的命令列表个数 CNend */ + hi_u8 stat_list_total_cnt; /**< Number of statistic object tables can be registered. Currently not support. + CNcomment:总共支持注册的统计量对象列表个数。当前暂不支持。 CNend */ + hi_u8 stat_list_used_cnt; /**< Number of registered statistic object tables. Currently not support. + CNcomment:已经注册的统计量对象列表个数。当前暂不支持。 CNend */ +} hi_diag_cmd_stat_reg_info; + +/** +* @ingroup iot_diag +* @brief Queries the registration status of the command tables and statistic tables of the DIAG subsystem. +CNcomment:查询诊断子系统命令列表和统计量列表注册情况。CNend +* +* @par 描述: +* Queries the registration status of the command tables and statistic tables of the DIAG subsystem. +* Number of registered command tables and number of command tables can be registered/ Number of registered +* statistic object tables +CNcomment:查询总共支持注册/已经注册的命令列表个数、总共支持注册/已经注册的统计量对象列表个数。CNend +* +* @attention None +* @param None +* +* @retval #hi_diag_cmd_stat_reg_info Structure of the number of registered command tables and statistic tables. +CNcomment:命令列表和统计量列表注册个数信息结构体。CNend +* @par 依赖: +* @li hi_diag.h:Describes DIAG APIs. +CNcomment:文件用于描述DIAG相关接口。CNend +* @see None +*/ +HI_EXTERN hi_diag_cmd_stat_reg_info hi_diag_get_cmd_stat_reg_info(hi_void); + +typedef struct { + hi_u32 data0; + hi_u32 data1; + hi_u32 data2; + hi_u32 data3; +}diag_log_msg; + +/** +* @ingroup iot_diag +* @brief Reports usr packets. CNcomment:上报用户日志。CNend +* +* @par 描述: +* Reports usr packets. CNcomment:上报用户日志消息。CNend +* +* @attention None +* @param diag_usr_msg [IN] type #hi_diag_layer_msg,log message. CNcomment:日志消息。CNend +* @param msg_level [IN] type #hi_u16,level of log message, [HI_MSG_USR_L0, HI_MSG_USR_L4]. +CNcomment:日志消息级别,取值从:HI_MSG_USR_L0- HI_MSG_USR_L4。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_diag.h:Describes DIAG APIs. +CNcomment:文件用于描述DIAG相关接口。CNend +* @see None +*/ +hi_u32 hi_diag_report_usr_msg(const hi_diag_layer_msg* diag_usr_msg, hi_u16 msg_level); + +/** +* @ingroup iot_diag +* @brief Reports simple packet that without data. CNcomment:上报简单日志,不携带数据内容。CNend +* +* @par 描述: +* Reports simple packets, fixed module ID. CNcomment:上报简单日志消息,固定模块ID。 +* +* @attention None +* @param msg_id [IN] type #hi_u32,log message ID. CNcomment:日志消息ID。CNend +* @param msg_level [IN] type #hi_u16,log message level, [HI_MSG_SYS_L0, HI_MSG_SYS_L2] +CNcomment:日志消息级别,取值从:HI_MSG_SYS_L0- HI_MSG_SYS_L2。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_diag.h:Describes DIAG APIs. +CNcomment:文件用于描述DIAG相关接口。CNend +* @see None +*/ +hi_u32 hi_diag_log_msg0(hi_u32 msg_id, hi_u16 msg_level); + +/** +* @ingroup iot_diag +* @brief Reports simple packet that with one word data. CNcomment:上报简单日志,携带1个数据。CNend +* +* @par 描述: +* Reports simple packets, fixed module ID. CNcomment:上报简单日志消息,固定模块ID。CNend +* +* @attention None +* @param msg_id [IN] type #hi_u32,log message ID. CNcomment:日志消息ID。CNend +* @param d0 [IN] type #hi_u32,first data. CNcomment:携带的第1个数据。Cnend +* @param msg_level [IN] type #hi_u16,log message level, [HI_MSG_SYS_L0, HI_MSG_SYS_L2] +CNcomment:日志消息级别,取值从:HI_MSG_SYS_L0- HI_MSG_SYS_L2。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_diag.h:Describes DIAG APIs. +CNcomment:文件用于描述DIAG相关接口。CNend +* @see None +*/ +hi_u32 hi_diag_log_msg1(hi_u32 msg_id, hi_u32 d0, hi_u16 msg_level); + +/** +* @ingroup iot_diag +* @brief Reports simple packet that with 2 words data. CNcomment:上报简单日志,携带2个数据。CNend +* +* @par 描述: +* Reports simple packets, fixed module ID. CNcomment:上报简单日志消息,固定模块ID。CNend +* +* @attention None +* @param msg_id [IN] type #hi_u32,log message ID. CNcomment:日志消息ID。CNend +* @param d0 [IN] type #hi_u32,first data. CNcomment:携带的第1个数据。CNend +* @param d1 [IN] type #hi_u32,second data. CNcomment:携带的第2个数据。CNend +* @param msg_level [IN] type #hi_u16,log message level, [HI_MSG_SYS_L0, HI_MSG_SYS_L2] +CNcomment:日志消息级别,取值从:HI_MSG_SYS_L0- HI_MSG_SYS_L2。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_diag.h:Describes DIAG APIs. +CNcomment:文件用于描述DIAG相关接口。CNend +* @see None +*/ +hi_u32 hi_diag_log_msg2(hi_u32 msg_id, hi_u32 d0, hi_u32 d1, hi_u16 msg_level); + +/** +* @ingroup iot_diag +* @brief Reports simple packet that with three words data. CNcomment:上报简单日志,携带3个数据。CNend +* +* @par 描述: +* Reports simple packets, fixed module ID. CNcomment:上报简单日志消息,固定模块ID。CNend +* +* @attention None +* @param msg_id [IN] type #hi_u32,log message ID. CNcomment:日志消息ID。CNend +* @param d0 [IN] type #hi_u32,first data. CNcomment:携带的第1个数据。Cnend +* @param d1 [IN] type #hi_u32,second data. CNcomment:携带的第2个数据。CNend +* @param d2 [IN] type #hi_u32,third data. CNcomment:携带的第3个数据。CNend +* @param msg_level [IN] type #hi_u16,log message level, [HI_MSG_SYS_L0, HI_MSG_SYS_L2] +CNcomment:日志消息级别,取值从:HI_MSG_SYS_L0- HI_MSG_SYS_L2。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_diag.h:Describes DIAG APIs. +CNcomment:文件用于描述DIAG相关接口。CNend +* @see None +*/ +hi_u32 hi_diag_log_msg3(hi_u32 msg_id, hi_u32 d0, hi_u32 d1, hi_u32 d2, hi_u16 msg_level); + +/** +* @ingroup iot_diag +* @brief Reports simple packet that with four words data. CNcomment:上报简单日志,携带4个数据。CNend +* +* @par 描述: +* Reports simple packets, fixed module ID. CNcomment:上报简单日志消息,固定模块ID。CNend +* +* @attention None +* @param msg_id [IN] type #hi_u32,log message ID. CNcomment:日志消息ID。CNend +* @param log_msg [IN] type #diag_log_msg,four words. CNcomment:携带4个数据。CNend +* @param msg_level [IN] type #hi_u16,log message level, [HI_MSG_SYS_L0, HI_MSG_SYS_L2] +CNcomment:日志消息级别,取值从:HI_MSG_SYS_L0- HI_MSG_SYS_L2。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_diag.h:Describes DIAG APIs. +CNcomment:文件用于描述DIAG相关接口。CNend +* @see None +*/ +hi_u32 hi_diag_log_msg4(hi_u32 msg_id, diag_log_msg log_msg, hi_u16 msg_level); + +/** +* @ingroup iot_diag +* @brief Reports simple packet that with one buffer data. CNcomment:上报简单日志,携带数据buffer。CNend +* +* @par 描述: +* Reports simple packets, fixed module ID. CNcomment:上报简单日志消息,固定模块ID。CNend +* +* @attention A maximum of 99 bytes can be send in one diag packet, so param size cannot be greater than 99. +CNcomment:diag单包最多能发99字节数据,参数size不能大于99。CNend +* @param msg_id [IN] type #hi_u32,log message ID. CNcomment:日志消息ID。CNend +* @param buffer [IN] type #hi_pvoid,address of the data. CNcomment:携带的数据buffer首地址。CNend +* @param size [IN] type #hi_16,buffer size (unit byte). +CNcomment:携带的数据buffer长度(单位byte)。CNend +* @param msg_level [IN] type #hi_u16,log message level, [HI_MSG_SYS_L0, HI_MSG_SYS_L2] +CNcomment:日志消息级别,取值从:HI_MSG_SYS_L0- HI_MSG_SYS_L2。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_diag.h:Describes DIAG APIs. +CNcomment:文件用于描述DIAG相关接口。CNend +* @see None +*/ +hi_u32 hi_diag_log_msg_buffer(hi_u32 msg_id, hi_pvoid buffer, hi_u16 size, hi_u16 msg_level); + +/** +* @ingroup iot_diag +* @brief Reports layer log that without data. CNcomment:上报层间简单日志,不携带数据内容。CNend +* +* @par 描述: +* Reports layer log that without data. CNcomment:上报层间简单日志,不携带数据内容。CNend +* +* @attention None +* @param msg_id [IN] type #hi_u32,log message ID. CNcomment:日志消息ID。CNend +* @param module_id [IN] type #hi_u16,message module ID,describe which module the log belongs to. +CNcomment:消息模块ID,描述日志属于哪个模块。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_diag.h:Describes DIAG APIs. +CNcomment:文件用于描述DIAG相关接口。CNend +* @see None +*/ +hi_u32 hi_diag_layer_msg0(hi_u32 msg_id, hi_u16 module_id); + +/** +* @ingroup iot_diag +* @brief Reports layer log that with one word data. CNcoment:上报层间简单日志,携带1个数据。CNend +* +* @par 描述: +* Reports layer log that with one word data. CNcoment:上报层间简单日志,携带1个数据。CNend +* +* @attention None +* @param msg_id [IN] type #hi_u32,log message ID. CNcomment:日志消息ID。CNend +* @param module_id [IN] type #hi_u16,message module ID,describe which module the log belongs to. +CNcomment:消息模块ID,描述日志属于哪个模块。CNend +* @param d0 [IN] type #hi_u32,first data. CNcomment:携带的第1个数据。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_diag.h:Describes DIAG APIs. +CNcomment:文件用于描述DIAG相关接口。CNend +* @see None +*/ +hi_u32 hi_diag_layer_msg1(hi_u32 msg_id, hi_u16 module_id, hi_u32 d0); + +/** +* @ingroup iot_diag +* @brief Reports layer log that with two words data. CNcoment:上报层间简单日志,携带2个数据。CNend +* +* @par 描述: +* Reports layer log that with two words data. CNcoment:上报层间简单日志,携带2个数据。CNend +* +* @attention None +* @param msg_id [IN] type #hi_u32,log message ID. CNcomment:日志消息ID。CNend +* @param module_id [IN] type #hi_u16,message module ID,describe which module the log belongs to. +CNcomment:消息模块ID,描述日志属于哪个模块。CNend +* @param d0 [IN] type #hi_u32,first data. CNcomment:携带的第1个数据。CNend +* @param d1 [IN] type #hi_u32,second data. CNcomment:携带的第2个数据。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_diag.h:Describes DIAG APIs. +CNcomment:文件用于描述DIAG相关接口。CNend +* @see None +*/ +hi_u32 hi_diag_layer_msg2(hi_u32 msg_id, hi_u16 module_id, hi_u32 d0, hi_u32 d1); + +/** +* @ingroup iot_diag +* @brief Reports layer log that with 3 words data. CNcoment:上报层间简单日志,携带3个数据。CNend +* +* @par 描述: +* Reports layer log that with 3 words data. CNcoment:上报层间简单日志,携带3个数据。CNend +* +* @attention None +* @param msg_id [IN] type #hi_u32,log message ID. CNcomment:日志消息ID。CNend +* @param module_id [IN] type #hi_u16,message module ID,describe which module the log belongs to. +CNcomment:消息模块ID,描述日志属于哪个模块。CNend +* @param d0 [IN] type #hi_u32,first data. CNcomment:携带的第1个数据。CNend +* @param d1 [IN] type #hi_u32,second data. CNcomment:携带的第2个数据。CNend +* @param d2 [IN] type #hi_u32,third data. CNcomment:携带的第3个数据。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_diag.h:Describes DIAG APIs. +CNcomment:文件用于描述DIAG相关接口。CNend +* @see None +*/ +hi_u32 hi_diag_layer_msg3(hi_u32 msg_id, hi_u16 module_id, hi_u32 d0, hi_u32 d1, hi_u32 d2); + +/** +* @ingroup iot_diag +* @brief Reports layer log that with 4 words data. CNcoment:上报层间简单日志,携带4个数据。CNend +* +* @par 描述: +* Reports layer log that with 4 words data. CNcoment:上报层间简单日志,携带4个数据。CNend +* +* @attention None +* @param msg_id [IN] type #hi_u32,log message ID. CNcomment:日志消息ID。CNend +* @param module_id [IN] type #hi_u16,message module ID,describe which module the log belongs to. +CNcomment:消息模块ID,描述日志属于哪个模块。CNend +* @param log_msg [IN] type #diag_log_msg,four data to report. CNcomment:携带4个数据。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_diag.h:Describes DIAG APIs. +*/ +hi_u32 hi_diag_layer_msg4(hi_u32 msg_id, hi_u16 module_id, diag_log_msg log_msg); + +/** +* @ingroup iot_diag +* @brief Reports layer log that with one buffer data. CNcomment:上报层间简单日志,携带数据buffer。CNend +* +* @par 描述: +* Reports layer log that with one buffer data. CNcomment:上报层间简单日志,携带数据buffer。CNend +* +* @attention A maximum of 99 bytes can be send in one diag packet, so param size cannot be greater than 99. +CNcomment:diag单包最多能发99字节数据,参数size不能大于99。CNend +* @param msg_id [IN] type #hi_u32,log message ID. CNcomment:日志消息ID。CNend +* @param module_id [IN] type #hi_u16,message module ID,describe which module the log belongs to. +CNcomment:消息模块ID,描述日志属于哪个模块。CNend +* @param buffer [IN] type #const hi_pvoid,address of the data. CNcomment:携带的数据buffer首地址。CNend +* @param size [IN] type #hi_16,buffer size (unit byte). +CNcomment:携带的数据buffer长度(单位byte)。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_diag.h:Describes DIAG APIs. +CNcomment:文件用于描述DIAG相关接口。CNend +* @see None +*/ +hi_u32 hi_diag_layer_msg_buffer(hi_u32 msg_id, hi_u16 module_id, const hi_void *buffer, hi_u16 size); + +typedef struct { + hi_u16 size1; + hi_u16 size2; +} diag_buffer_size; + +/** +* @ingroup iot_diag +* @brief Reports layer log that with two buffer data. CNcomment:上报层间简单日志,支持携带两个数据buffer。CNend +* +* @par 描述: +* Reports layer log that with two buffer data. CNcomment:上报层间简单日志,支持携带两个数据buffer。CNend +* +* @attention A maximum of 99 bytes can be send in one diag packet.A space is reserved between two buffers. + Therefore, the sum of buffer_size.size1 and buffer_size.size2 cannot be greater than 98. +CNcomment:diag单包最多能发99字节数据,两个buffer之间会预留一个空格,所以参数buffer_size.size1与buffer_size.size2的和不能大于98。CNend +* @param msg_id [IN] type #hi_u32,log message ID. CNcomment:日志消息ID。CNend +* @param module_id [IN] type #hi_u16,message module ID,describe which module the log belongs to. +CNcomment:消息模块ID,描述日志属于哪个模块。CNend +* @param buf1 [IN] type #const hi_void *,address of the first buffer. +CNcomment:携带的数据buffer1首地址。CNend +* @param buf1 [IN] type #const hi_void *,address of the second buffer. +CNcomment:携带的数据buffer2首地址。CNend +* @param buffer_size [IN] type #diag_buffer_size,two buffer size (unit byte). +CNcomment:携带的数据buffer长度(单位byte)。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_diag.h:Describes DIAG APIs. +*/ +hi_u32 hi_diag_layer_two_buffer(hi_u32 msg_id, hi_u16 module_id, const hi_void *buf1, + const hi_void *buf2, diag_buffer_size buffer_size); + +/** +* @ingroup iot_diag +* @brief Set whether to check the UART busy status when low power vote. +CNcomment:设置低功耗投票时是否检查UART busy状态。CNend +* +* @par 描述: +* Set whether to check the UART busy status when low power vote. +CNcomment:设置低功耗投票时是否检查UART busy状态。CNend +* +* @attention UART busy status is not checked by default. +CNcomment:默认低功耗睡眠投票时不检查UART busy状态。CNend +* @param enable [IN] type #hi_bool,enable status. CNcomment:设置是否检查UART busy状态。CNend +* +* @retval None +* @par 依赖: +* @li hi_diag.h:Describes DIAG APIs. +CNcomment:文件用于描述DIAG相关接口。CNend +*/ +hi_void hi_diag_set_check_uart_busy(hi_bool enable); + +typedef hi_s32 (*hi_diag_input_func)(hi_u8 *data, hi_u32 data_len); +typedef hi_s32 (*hi_diag_output_func)(const hi_u8 *data, hi_u32 data_len); + +/** +* @ingroup iot_diag +* @brief Register diag input function to replace uart input. +CNcomment:注册DIAG输入函数,代替默认从UART读取DIAG输入数据。CNend +* +* @par 描述: +* Register diag input function to replace uart input. +CNcomment:注册DIAG输入函数,代替默认从UART读取DIAG输入数据。CNend +* +* @attention Should set suitable task size; input func should not continuous read data without break. otherwise, +a watchdog may happen.not support register HI_NULL when diag channel is already uart. +CNcomment:根据输入函数实现,设置合适的栈大小;输入函数不能持续 +返回有效数据避免触发看门狗。当DIAG 通道已经是UART时,不支持注 +册DIAG 输入函数为HI_NULL。CNend +* @param diag_input_func [IN] type #hi_diag_input_func,diag input function. +CNcomment:DIAG输入函数。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_diag.h:Describes DIAG APIs. +CNcomment:文件用于描述DIAG相关接口。CNend +*/ +hi_u32 hi_diag_register_input_func(hi_diag_input_func diag_input_func); + +/** +* @ingroup iot_diag +* @brief Register diag output function to replace uart output. +CNcomment:注册DIAG输出函数,代替默认从UART输出DIAG相关数据。CNend +* +* @par 描述: +* Register diag output function to replace uart output. +CNcomment:注册DIAG输出函数,代替默认从UART输出DIAG相关数据。CNend +* +* @attention Should set suitable task size according to implementation of output func. +CNcomment:根据输出函数实现,设置合适的栈大小。CNend +* @param diag_output_func [IN] type #hi_diag_output_func,diag output function. +CNcomment:DIAG输出函数。CNend +* +* @retval None +* @par 依赖: +* @li hi_diag.h:Describes DIAG APIs. +CNcomment:文件用于描述DIAG相关接口。CNend +*/ +hi_void hi_diag_register_output_func(hi_diag_output_func diag_output_func); + +/** +* @ingroup iot_diag +* @brief Set taks size of DIAG. CNcomment:设置DIAG相关任务栈大小。CNend +* +* @par 描述: +* Set taks size of DIAG. CNcomment:设置DIAG相关任务栈大小。CNend +* +* @attention diag task stack size needs to be set before diag initialization. +CNcomment:diag任务栈大小需要在diag初始化之前设置。CNend +* @param channel_task_size [IN] type #hi_u16 channel task size,task size should not smaller than 0x600. +CNcomment:通道任务栈大小,任务栈大小不低于0x600。CNend +* @param process_task_size [IN] type #hi_u16 process task size,task size should not smaller than 0x800. +CNcomment:处理任务栈大小,任务栈大小不低于0x800。CNend +* +* @retval None +* @par 依赖: +* @li hi_diag.h:Describes DIAG APIs. +CNcomment:文件用于描述DIAG相关接口。CNend +*/ +hi_void hi_diag_set_task_size(hi_u16 channel_task_size, hi_u16 process_task_size); + + +typedef hi_u32 (*hi_diag_sys_msg_forward_func)(const hi_diag_layer_msg *diag_sys_msg, hi_u16 msg_level); +typedef hi_u32 (*hi_diag_layer_msg_forward_func)(hi_u32 msg_id, hi_u16 src_module_id, hi_u16 dst_module_id, + const hi_void *packet, hi_u16 packet_size); +typedef hi_u32 (*hi_diag_usr_msg_forward_func)(const hi_diag_layer_msg* diag_usr_msg, hi_u16 msg_level); + +/** +* @ingroup iot_diag +* @brief Register msg forward func. CNcomment:设置消息转发函数,替代默认从HSO输出。CNend +* +* @par 描述: +* Register msg forward func. CNcomment:设置消息转发函数,替代默认从HSO输出。CNend +* +* @attention None. +* @param diag_sys_msg_func [IN] type #hi_diag_sys_msg_forward_func forward function of sys_msg. +CNcomment:sys_msg的转发函数。CNend +* @param diag_layer_msg_func [IN] type #hi_diag_layer_msg_forward_func forward function of layer_msg. +CNcomment:layder_msg的转发函数。CNend +* @param diag_usr_msg_func [IN] type #hi_diag_usr_msg_forward_func forward function of usr_msg. +CNcomment:usr_msg的转发函数。CNend +* +* @retval None +* @par 依赖: +* @li hi_diag.h:Describes DIAG APIs. +CNcomment:文件用于描述DIAG相关接口。CNend +*/ +hi_void hi_diag_register_msg_forward_func(hi_diag_sys_msg_forward_func diag_sys_msg_func, + hi_diag_layer_msg_forward_func diag_layer_msg_func, hi_diag_usr_msg_forward_func diag_usr_msg_func); + + +#endif diff --git a/sdk_liteos/include/hi_dma.h b/sdk_liteos/include/hi_dma.h new file mode 100644 index 0000000000000000000000000000000000000000..0e4150d4e966968d43a802cbe6991a6083d5d743 --- /dev/null +++ b/sdk_liteos/include/hi_dma.h @@ -0,0 +1,255 @@ +/** +* @file hi_dma.h +* +* Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +* 描述:DMA module. CNcomment:DMA调用接口。CNend +* @li The DMA transfer is realized by calling internal DMA driver. +CNcomment:通过调用内部DMA驱动实现DMA传输CNend +* @li Supports four transmission modes: Memory to storage, memory to peripheral, peripheral to memory, +and peripheral to peripheral.CNcomment:支持存储器到存储器、存储器到外设、外设到存储器、 +外设到外设四种传输方式CNend +* @li The DMA has four channels. If there is no idle channel, the HI_ERR_DMA_BUSY error is returned. +CNcomment:DMA共有4通道,无空闲通道时返回HI_ERR_DMA_BUSY错误CNend +* @li The callback function is executed in the interrupt context, so you need to comply with the programming +precautions for the interrupt context.CNcomment:回调函数执行在中断上下文, +因此需要遵守中断上下文的编程注意事项。CNend +* @li Before enabling the DMA channel, you need to set the channel parameters. After the channel parameters +are enabled and then modified, an unpredictable result is generated.CNcomment:在DMA通道使能前需设置完通道参数, +使能通道后再修改通道参数会产生无法预知的结果。CNend \n +*/ + +/** @defgroup iot_dma DMA + * @ingroup drivers + */ + +#ifndef _HI_DMA_H +#define _HI_DMA_H + +#include +#include "hi_mdm_types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @ingroup iot_dma + * + * DMA Interruption type. CNcomment: DMA 中断类型。CNend + */ + /* 传输完成中断类型 */ +#define DMA_INT_TC 1 +/* 传输错误中断类型 */ +#define DMA_INT_ERR 2 + +/** + * @ingroup iot_dma + * + * DMA transfer bit width. CNcomment:DMA传输位宽。CNend + */ +typedef enum { + WIDTH_BIT8 = 0, + WIDTH_BIT16, + WIDTH_BIT32, +} hi_dma_data_width; + +/** + * @ingroup iot_dma + * + * DMA configuration structure transferred. CNcomment:用户传入的DMA设置结构体。CNend + */ +typedef struct hi_dma_user_para { + hi_u32 ch_idx; /* 接收DMA传输使用的channel id,不需用户设置, 通道申请成功时赋值 */ + uintptr_t src_addr; /* 源地址,源地址必须4字节对齐 */ + uintptr_t dst_addr; /* 目标地址,目的地址必须4字节对齐 */ + hi_u32 size_bytes; /* 传输长度,以BYTE单位 */ + hi_void (*cb)(hi_u32); /* 传输结束回调,参数为传输完成或传输错误 #DMA_INT_XXX */ +} hi_dma_user_para; + +/** +* @ingroup iot_dma +* @brief Create the dma transmission linked list. CNcomment:创建dma传输链表。CNend +* +* @par 描述: +* Create the dma transmission linked list. CNcomment:创建dma传输链表,分配通道。CNend +* After the command is executed successfully, the channel resources are allocated. +* If the channel resources are not transmitted, the hi_dma_ch_close(usr_para->ch_idx) is invoked to +* release the channels. CNcomment:执行成功后会分配通道资源,如果没有实际进行传输需要调用 +hi_dma_ch_close(usr_para->ch_idx)释放通道。CNend +* +* @attention +* @param usr_para [IN/OUT] type #hi_dma_user_para,Transfer DMA transfer parameter settings +CNcomment:传入DMA传输参数设置。CNend +* +* @retval #HI_ERR_SUCCESS Success. +* @retval #Other values Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_dma.h: Describes DMA driver APIs. CNcomment:DMA驱动实现接口。CNend +* @see None + */ +hi_u32 hi_dma_create_link_list(hi_dma_user_para *usr_para); + +/** +* @ingroup iot_dma +* @brief Insert the DMA transmission linked list at behind. CNcomment:dma传输链表末尾添加结点。CNend +* +* @par 描述: +* Insert the DMA transmission linked list at behind. CNcomment:dma传输链表末尾添加结点CNend +* +* @attention +* @param usr_para [IN] type #const hi_dma_user_para,Transfer DMA transfer parameter settings. +CNcomment:传入DMA传输参数设置。CNend +* +* @retval #HI_ERR_SUCCESS Success. +* @retval #Other values Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_dma.h: Describes DMA driver APIs. CNcomment:DMA驱动实现接口。CNend +* @see None + */ +hi_u32 hi_dma_add_link_list_item(const hi_dma_user_para *usr_para); + +/** +* @ingroup iot_dma +* @brief Start DMA linked list transmission. CNcomment:启动dma链表传输。CNend +* +* @par 描述: +* Start DMA linked list transmission, channel would be released, no matter about the result. +CNcomment:启动dma链表传输,成功或失败后会释放通道。CNend +* +* @attention +* @param ch_num [IN] type #hi_u32,Linked list transmission channel. +This parameter is assigned by the API when a linked list is created. +CNcomment:链表传输通道,创建链表时API内部赋值。CNend +* @param block [IN] type #hi_bool,Indicates whether to block waiting for transmission completion. +CNcomment:是否阻塞等待传输完成。CNend +* +* @retval #HI_ERR_SUCCESS Success. +* @retval #Other values Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_dma.h: Describes DMA driver APIs. CNcomment:DMA驱动实现接口。CNend +* @see None + */ +hi_u32 hi_dma_link_list_transfer(hi_u32 ch_num, hi_bool block); + +/** +* @ingroup iot_dma +* @brief Data transmission from the memory to the memory through DMA. +CNcomment:通过DMA进行存储器到存储器数据传输。CNend +* +* @par 描述: +* Data transmission from the memory to the memory through DMA. +CNcomment:通过DMA进行存储器到存储器数据传输。CNend +* +* @attention +* @param dst_addr [IN] type #hi_u32,Destination address, which must be 4-byte-aligned. +CNcomment:目标地址,需4字节对齐。CNend +* @param src_addr [IN] type #hi_u32,Source address, which must be 4-byte-aligned. +CNcomment:源地址,需4字节对齐。CNend +* @param size_bytes [IN] type #hi_u32,Transmission length, in bytes. +CNcomment:传输长度,以BYTE为单位。CNend +* @param block [IN] type #hi_bool,Indicates whether to block waiting for transmission completion. +CNcomment:是否阻塞等待传输完成。CNend +* @param cb_func [IN] type #hi_void,Callback function for non-blocking transmission. +The parameter is the DMA interrupt type. Set this parameter to HI_NULL when blocking transmission. +CNcomment:非阻塞传输的回调函数,参数为DMA中断类型,阻塞传输时设为HI_NULL。CNend +* +* @retval #HI_ERR_SUCCESS Success. +* @retval #HI_ERR_DMA_BUSY Channel busy. CNcomment:通道全忙。CNend +* @retval #Other values Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_dma.h: Describes DMA driver APIs. CNcomment:DMA驱动实现接口。CNend +* @see None + */ +hi_u32 hi_dma_mem2mem_transfer(hi_u32 dst_addr, hi_u32 src_addr, hi_u32 size_bytes, + hi_bool block, hi_void (*cb_func)(hi_u32 int_type)); + +/** +* @ingroup iot_dma +* @brief Disables the DMA specified channel. CNcomment:关闭DMA指定通道。CNend +* +* @par 描述: +* Disables the DMA specified channel and release rource. +CNcomment:关闭DMA指定通道并释放资源。CNend +* +* @attention None +* @param ch_num [IN] type #hi_u32,DMA channel ID. Value range: 0-3. +CNcomment:DMA通道ID 取值0~3。CNend +* +* @retval #HI_ERR_SUCCESS Success. +* @retval #Other values Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_dma.h: Describes DMA driver APIs. CNcomment:DMA驱动实现接口。CNend +* @see hi_dma_create_link_list。 + */ +hi_u32 hi_dma_ch_close(hi_u32 ch_num); + +/** +* @ingroup iot_dma +* @brief DMA module initialization.CNcomment:DMA模块初始化。CNend +* +* @par 描述: +* DMA module initialization, apply for rources. CNcomment:DMA模块初始化, 申请资源。CNend +* +* @attention None +* @param None +* +* @retval #HI_ERR_SUCCESS Success. +* @retval #Other values Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_dma.h: Describes DMA driver APIs. CNcomment:DMA驱动实现接口。CNend +* @see None + */ +hi_u32 hi_dma_init(hi_void); + +/** +* @ingroup iot_dma +* @brief Deinitializes the DMA module. CNcomment:DMA模块去初始化。CNend +* +* @par 描述: +* Deinitializes the DMA module and release rources. CNcomment:DMA模块去初始化,释放资源。CNend +* +* @attention None +* @param None +* +* @retval None +* @par 依赖: +* @li hi_dma.h: Describes DMA driver APIs. CNcomment:DMA驱动实现接口。CNend +* @see None +*/ +hi_void hi_dma_deinit(hi_void); + +/** +* @ingroup iot_dma +* @brief Judge is DMA module init. CNcomment:DMA模块是否初始化。CNend +* +* @par 描述: +* Is DMA module init. CNcomment:DMA模块是否初始化。CNend +* +* @attention None +* @param None +* +* @retval #HI_TURE dma has been initialized. +* @retval #HI_FALSE DMA has not been initialized. +* @par 依赖: +* @li hi_dma.h: Describes DMA driver APIs. CNcomment:DMA驱动实现接口。CNend +* @see None + */ +hi_bool hi_dma_is_init(hi_void); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/include/hi_early_debug.h b/sdk_liteos/include/hi_early_debug.h new file mode 100644 index 0000000000000000000000000000000000000000..978d5e66287043ce4395a6e7d9b56f5b3c87e8c3 --- /dev/null +++ b/sdk_liteos/include/hi_early_debug.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __HI_EARLY_DEBUG_H__ +#define __HI_EARLY_DEBUG_H__ +#include + +void edb_put_str_only(const char *s); +void edb_put_str_p0(char *str); +void edb_put_str_p1(char *str, unsigned int p1); +void edb_put_str_p2(char *str, unsigned int p1, unsigned int p2); +void edb_put_str_p3(char *str, unsigned int p1, unsigned int p2, unsigned int p3); +void edb_put_str_p4(char *str, unsigned int p1, unsigned int p2, unsigned int p3, unsigned int p4); +void edb_put_buf(char *buf, unsigned int len); +int printf(const char *fmt, ...); +int vprintf(const char *fmt, va_list va); +int dprintf(const char *fmt, ...); +void edb_set_print_level(unsigned int level); +void hi_printf_alloc_uart_by_nv(void); +#endif + diff --git a/sdk_liteos/include/hi_efuse.h b/sdk_liteos/include/hi_efuse.h new file mode 100644 index 0000000000000000000000000000000000000000..d11ff4615fdd933fbccdc96c5bf72f97f91be377 --- /dev/null +++ b/sdk_liteos/include/hi_efuse.h @@ -0,0 +1,295 @@ +/** + * @file hi_efuse.h + * + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @defgroup iot_efuse Efuse + * @ingroup drivers + */ +#ifndef __HI_EFUSE_H__ +#define __HI_EFUSE_H__ +#include + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ + +typedef enum { + HI_EFUSE_CHIP_RW_ID = 0, + HI_EFUSE_DIE_RW_ID = 1, + HI_EFUSE_PMU_FUSE1_RW_ID = 2, + HI_EFUSE_PMU_FUSE2_RW_ID = 3, + HI_EFUSE_FLASH_ENCPY_CNT3_RW_ID = 4, + HI_EFUSE_FLASH_ENCPY_CNT4_RW_ID = 5, + HI_EFUSE_FLASH_ENCPY_CNT5_RW_ID = 6, + HI_EFUSE_DSLEEP_FLAG_RW_ID = 7, + HI_EFUSE_ROOT_PUBKEY_RW_ID = 8, + HI_EFUSE_ROOT_KEY_WO_ID = 9, + HI_EFUSE_CUSTOMER_RSVD0_RW_ID = 10, + HI_EFUSE_SUBKEY_CAT_RW_ID = 11, + HI_EFUSE_ENCRYPT_FLAG_RW_ID = 12, + HI_EFUSE_SUBKEY_RSIM_RW_ID = 13, + HI_EFUSE_START_TYPE_RW_ID = 14, + HI_EFUSE_JTM_RW_ID = 15, + HI_EFUSE_UTM0_RW_ID = 16, + HI_EFUSE_UTM1_RW_ID = 17, + HI_EFUSE_UTM2_RW_ID = 18, + HI_EFUSE_SDC_RW_ID = 19, + HI_EFUSE_RSVD0_RW_ID = 20, + HI_EFUSE_KDF2ECC_HUK_DISABLE_RW_ID = 21, + HI_EFUSE_SSS_CORNER_RW_ID = 22, + HI_EFUSE_UART_HALT_INTERVAL_RW_ID = 23, + HI_EFUSE_TSENSOR_RIM_RW_ID = 24, + HI_EFUSE_CHIP_BK_RW_ID = 25, + HI_EFUSE_IPV4_MAC_ADDR_RW_ID = 26, + HI_EFUSE_IPV6_MAC_ADDR_RW_ID = 27, + HI_EFUSE_PG2GCCKA0_TRIM0_RW_ID = 28, + HI_EFUSE_PG2GCCKA1_TRIM0_RW_ID = 29, + HI_EFUSE_NVRAM_PA2GA0_TRIM0_RW_ID = 30, + HI_EFUSE_NVRAM_PA2GA1_TRIM0_RW_ID = 31, + HI_EFUSE_PG2GCCKA0_TRIM1_RW_ID = 32, + HI_EFUSE_PG2GCCKA1_TRIM1_RW_ID = 33, + HI_EFUSE_NVRAM_PA2GA0_TRIM1_RW_ID = 34, + HI_EFUSE_NVRAM_PA2GA1_TRIM1_RW_ID = 35, + HI_EFUSE_PG2GCCKA0_TRIM2_RW_ID = 36, + HI_EFUSE_PG2GCCKA1_TRIM2_RW_ID = 37, + HI_EFUSE_NVRAM_PA2GA0_TRIM2_RW_ID = 38, + HI_EFUSE_NVRAM_PA2GA1_TRIM2_RW_ID = 39, + HI_EFUSE_TEE_BOOT_VER_RW_ID = 40, + HI_EFUSE_TEE_KERNEL_VER_RW_ID = 41, + HI_EFUSE_TEE_SALT_RW_ID = 42, + HI_EFUSE_FLASH_ENCPY_CNT0_RW_ID = 43, + HI_EFUSE_FLASH_ENCPY_CNT1_RW_ID = 44, + HI_EFUSE_FLASH_ENCPY_CNT2_RW_ID = 45, + HI_EFUSE_FLASH_ENCPY_CFG_RW_ID = 46, + HI_EFUSE_FLASH_SCRAMBLE_EN_RW_ID = 47, + HI_EFUSE_USER_FLASH_IND_RW_ID = 48, + HI_EFUSE_RF_PDBUFFER_GCAL_RW_ID = 49, + HI_EFUSE_CUSTOMER_RSVD1_RW_ID = 50, + HI_EFUSE_DIE_2_RW_ID = 51, + HI_EFUSE_SEC_BOOT_RW_ID = 52, + HI_EFUSE_IDX_MAX, +} hi_efuse_idx; + +typedef enum { + HI_EFUSE_LOCK_CHIP_ID = 0, + HI_EFUSE_LOCK_DIE_ID = 1, + HI_EFUSE_LOCK_PMU_FUSE1_FUSE2_START_TYPE_TSENSOR_ID = 2, + HI_EFUSE_LOCK_ROOT_PUBKEY_ID = 3, + HI_EFUSE_LOCK_ROOT_KEY_ID = 4, + HI_EFUSE_LOCK_CUSTOMER_RSVD0_ID = 5, + HI_EFUSE_LOCK_SUBKEY_CAT_ID = 6, + HI_EFUSE_LOCK_ENCRYPT_RSIM_ID = 7, + HI_EFUSE_LOCK_JTM_ID = 8, + HI_EFUSE_LOCK_UTM0_ID = 9, + HI_EFUSE_LOCK_UTM1_ID = 10, + HI_EFUSE_LOCK_UTM2_ID = 11, + HI_EFUSE_LOCK_SDC_ID = 12, + HI_EFUSE_LOCK_RSVD0_ID = 13, + HI_EFUSE_LOCK_SSS_CORNER_ID = 14, + HI_EFUSE_LOCK_UART_HALT_INTERVAL_ID = 15, + HI_EFUSE_LOCK_CHIP_BK_ID = 16, + HI_EFUSE_LOCK_IPV4_IPV6_MAC_ADDR_ID = 17, + HI_EFUSE_LOCK_PG2GCCKA0_PG2GCCKA1_TRIM0_ID = 18, + HI_EFUSE_LOCK_NVRAM_PA2GA0_PA2GA1_TRIM0_ID = 19, + HI_EFUSE_LOCK_PG2GCCKA0_PG2GCCKA1_TRIM1_ID = 20, + HI_EFUSE_LOCK_NVRAM_PA2GA0_PA2GA1_TRIM1_ID = 21, + HI_EFUSE_LOCK_PG2GCCKA0_PG2GCCKA1_TRIM2_ID = 22, + HI_EFUSE_LOCK_NVRAM_PA2GA0_PA2GA1_TRIM2_ID = 23, + HI_EFUSE_LOCK_TEE_BOOT_VER_ID = 24, + HI_EFUSE_LOCK_TEE_KERNEL_VER_ID = 25, + HI_EFUSE_LOCK_TEE_SALT_ID = 26, + HI_EFUSE_LOCK_FLASH_ENCPY_CNT0_ID = 27, + HI_EFUSE_LOCK_FLASH_ENCPY_CNT1_ID = 28, + HI_EFUSE_LOCK_FLASH_ENCPY_CNT2_ID = 29, + HI_EFUSE_LOCK_FLASH_ENCPY_CFG_ID = 30, + HI_EFUSE_LOCK_FLASH_SCRAMBLE_EN_FLASH_IND_ID = 31, + HI_EFUSE_LOCK_RF_PDBUFFER_GCAL_ID = 32, + HI_EFUSE_LOCK_CUSTOMER_RSVD1_ID = 33, + HI_EFUSE_LOCK_DIE_2_ID = 34, + HI_EFUSE_LOCK_KDF2ECC_HUK_DISABLE_ID = 35, + HI_EFUSE_LOCK_FLASH_ENCPY_CNT3_ID = 36, + HI_EFUSE_LOCK_FLASH_ENCPY_CNT4_ID = 37, + HI_EFUSE_LOCK_FLASH_ENCPY_CNT5_ID = 38, + HI_EFUSE_LOCK_SEC_BOOT_ID = 39, + HI_EFUSE_LOCK_DSLEEP_FLAG_ID = 40, + HI_EFUSE_LOCK_MAX, +} hi_efuse_lock_id; + +/** +* @ingroup iot_efuse +* @brief Obtains the preset length of each eFUSE area.CNcomment:根据EFUSE ID号获取该EFUSE数据长度。CNend +* +* @par 描述: +* Obtains the preset length of each eFUSE area.CNcomment:获取EFUSE数据长度。CNend +* +* @attention None +* @param efuse_id [IN] type #hi_efuse_idx,EFUSE ID +* +* @retval #HI_ERR_EFUSE_INVALIDATE_ID Invalid ID.CNcomment: 无效EFUSE ID。CNend +* @retval #Other Length of EFUSE data.(Unit bytes).CNcomment: EFUSE数据长度(单位为bit)。CNend +* @par 依赖: +* @li hi_efuse.h:Describes the encryption and decryption APIs. +CNcomment:文件用于描述efuse字段操作相关接口。CNend +* @see hi_efuse_get_id_size。 +*/ +hi_u32 hi_efuse_get_id_size(hi_efuse_idx efuse_id); + +/** +* @ingroup iot_efuse +* @brief Reads the eFUSE.CNcomment:EFUSE读取数据。CNend +* +* @par 描述: +* Reads the eFUSE.CNcomment:从EFUSE中读取数据。CNend +* +* @attention Ensure that the value of (data_len*8) is not less than efuse_id and the length of the efuse field is 8bit +* aligned.CNcomment:需保证(data_len*8)不小于efuse_id对应efuse字段的长度向上8bit对齐。CNend +* +* @param efuse_id [IN] type #hi_efuse_idx,EFUSE ID +* @param data [OUT] type #hi_u8*,Address for saving the read data.CNcomment:读到的数据放到该地址。CNend +* @param data_len [IN] type #hi_u8 Space allocated to data, in bytes.CNcomment:给data分配的空间,单位byte。CNend +* +* @retval #0 Success +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_efuse.h:Describes the encryption and decryption APIs. +CNcomment:文件用于描述efuse字段操作相关接口。CNend +* @see hi_efuse_write。 +*/ +hi_u32 hi_efuse_read(hi_efuse_idx efuse_id, hi_u8 *data, hi_u8 data_len); + +/** +* @ingroup iot_efuse +* @brief Writes the eFUSE.CNcomment:写数据到EFUSE。CNend +* +* @par 描述: +* Writes the eFUSE.CNcomment:写数据到EFUSE。CNend +* +* @attention None +* @param efuse_id [IN] type #hi_efuse_idx,EFUSE ID +* @param data [IN] type #const hi_u8*,Data to be written to the eFUSE.CNcomment:写该数据到EFUSE中。CNend +* +* @retval #0 Success +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_efuse.h:Describes the encryption and decryption APIs. +CNcomment:文件用于描述efuse字段操作相关接口。CNend +* @see hi_efuse_read。 +*/ +hi_u32 hi_efuse_write(hi_efuse_idx efuse_id, const hi_u8 *data); + +/** +* @ingroup iot_efuse +* @brief Locks an area in the eFUSE. After the lock takes effect upon reboot, the area cannot be written. +CNcomment:加锁EFUSE中的某个区域,加锁后重启单板生效,该区域无法再写入。CNend +* +* @par 描述: +* Locks an area in the eFUSE. After the lock takes effect upon reboot, the area cannot be written. +CNcomment:加锁EFUSE中的某个区域,加锁后重启单板生效,该区域无法再写入。CNend +* +* @attention None +* @param lock_id [IN] type #hi_efuse_lock_id,eFUSE ID to be locked.CNcomment:待加锁的EFUSE ID项。CNend +* +* @retval #0 Success +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_efuse.h:Describes the encryption and decryption APIs. +CNcomment:文件用于描述efuse字段操作相关接口。CNend +* @see hi_efuse_write。 +*/ +hi_u32 hi_efuse_lock(hi_efuse_lock_id lock_id); + +/** +* @ingroup iot_efuse +* @brief Obtains the lock status of the eFUSE and queries which areas are locked. +CNcomment:获取EFUSE的锁状态,查询哪些区域已锁定。CNend +* +* @par 描述: +* Obtains the lock status of the eFUSE and queries which areas are locked. +CNcomment:获取EFUSE的锁状态,查询哪些区域已锁定。CNend +* +* @attention None +* @param lock_stat [OUT] type #hi_u64*,Lock status of the eFUSE.CNcomment:获取EFUSE的锁状态。CNend +* +* @retval #0 Success +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_efuse.h:Describes the encryption and decryption APIs. +CNcomment:文件用于描述efuse字段操作相关接口。CNend +* @see hi_efuse_write。 +*/ +hi_u32 hi_efuse_get_lockstat(hi_u64 *lock_stat); + +/** +* @ingroup iot_efuse +* @brief Reads the user eFUSE.CNcomment:EFUSE用户读取数据。CNend +* +* @par 描述: +* Reads a reserved area in the eFUSE.CNcomment:用户从EFUSE中读取数据。CNend +* +* @attention None +* @param start_bit [IN] type #hi_u16,Start bit. The address must be 8-bit aligned. +CNcomment:起始bit位,该地址必须8bit对齐。CNend +* @param size [IN] type #hi_u16,Number of bits to be read. If the input is not 8-bit aligned, +* the function performs 8-bit alignment internally. The user needs to process the read data before using it. +CNcomment:待读取的bit位数,如果输入不是8bit对齐则函数内部会处理为8bit对齐,用户读取数据后需处理后使用。CNend +* @param key_data [OUT] type #hi_u8*,Address for saving the read data. +CNcommnet:读到的数据放到该地址。CNend +* +* @retval #0 Success +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_efuse.h:Describes the encryption and decryption APIs. +CNcomment:文件用于描述efuse字段操作相关接口。CNend +* @see hi_efuse_usr_write。 +*/ +hi_u32 hi_efuse_usr_read(hi_u16 start_bit, hi_u16 size, hi_u8 *key_data); + +/** +* @ingroup iot_efuse +* @brief Writes data to reserved area of the eFUSE.CNcomment:EFUSE用户区写入数据。CNend +* +* @par 描述: +* Writes data to reserved area of the eFUSE.CNcomment:用户往EFUSE写入数据。CNend +* +* @attention Generally, this API is used to write a reserved area. To write other pre-allocated areas, +* should check the design spec to avoid conflict.CNcomment:支持用户写入任意地址数据, +建议用户使用用户预留区,其他区域的写入需要结合方案文档评估是否有冲突。CNend +* +* @param start_bit [IN] type #hi_u16,Start bit.CNcomment:起始bit位。CNend +* @param size [IN] type #hi_u16,Number of bits to be written. 1-to-256-bit write is supported. +CNcomment:待写入bit数,支持单bit写入,最大值为256bit数。CNend +* @param key_data [IN] type #const hi_u8*,Address for the data to be written. The maximum length is 32 bytes. +CNcomment:待写入的数据放到该地址,最长为32byte。CNend +* +* @retval #0 Success +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_efuse.h:Describes the encryption and decryption APIs. +CNcomment:文件用于描述efuse字段操作相关接口。CNend +* @see hi_efuse_usr_read。 +*/ +hi_u32 hi_efuse_usr_write(hi_u16 start_bit, hi_u16 size, const hi_u8 *key_data); + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif /* __HI_EFUSE_H__ */ diff --git a/sdk_liteos/include/hi_errno.h b/sdk_liteos/include/hi_errno.h new file mode 100644 index 0000000000000000000000000000000000000000..64d1a1cec9b0fb89786fb0a518dbe372493f77ef --- /dev/null +++ b/sdk_liteos/include/hi_errno.h @@ -0,0 +1,532 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __HI_ERRNO_H__ +#define __HI_ERRNO_H__ + +/***************************************************************************** +* 1、Common error code. Note: 0x8000 0000 is not recommended. If a truncation error occurs, it is considered successful. +* CNcomment:通用错误码。注意0x8000 0000最好别用,产生截断误判为成功 +*****************************************************************************/ +#define HI_ERR_SUCCESS 0 +#define HI_ERR_FAILURE (hi_u32)(-1) +#define HI_ERR_S_FAILURE (-1) +#define HI_ERR_MALLOC_FAILUE 0x80000001 +#define HI_ERR_TIMEOUT 0x80000002 +#define HI_ERR_RECVING 0x80000003 +#define HI_ERR_MEMCPY_S 0x80000004 +#define HI_ERR_MEMSET_S 0x80000005 +#define HI_ERR_SPRINTF_S 0x80000006 +#define HI_ERR_STRCPY_S 0x80000007 + +/***************************************************************************** +* 2、Error codes of the system adaptation layer.CNcomment:系统适配层错误码 +*****************************************************************************/ +/* Task */ +#define HI_ERR_TASK_INVALID_PARAM 0x80000080 +#define HI_ERR_TASK_CREATE_FAIL 0x80000081 +#define HI_ERR_TASK_DELETE_FAIL 0x80000082 +#define HI_ERR_TASK_SUPPEND_FAIL 0x80000083 +#define HI_ERR_TASK_RESUME_FAIL 0x80000084 +#define HI_ERR_TASK_GET_PRI_FAIL 0x80000085 +#define HI_ERR_TASK_SET_PRI_FAIL 0x80000086 +#define HI_ERR_TASK_LOCK_FAIL 0x80000087 +#define HI_ERR_TASK_UNLOCK_FAIL 0x80000088 +#define HI_ERR_TASK_DELAY_FAIL 0x80000089 +#define HI_ERR_TASK_GET_INFO_FAIL 0x8000008A +#define HI_ERR_TASK_REGISTER_SCHEDULE_FAIL 0x8000008B +#define HI_ERR_TASK_NOT_CREATED 0x8000008C + +/* ISR */ +#define HI_ERR_ISR_INVALID_PARAM 0x800000C0 +#define HI_ERR_ISR_REQ_IRQ_FAIL 0x800000C1 +#define HI_ERR_ISR_ADD_JOB_MALLOC_FAIL 0x800000C2 +#define HI_ERR_ISR_ADD_JOB_SYS_FAIL 0x800000C3 +#define HI_ERR_ISR_DEL_IRQ_FAIL 0x800000C4 +#define HI_ERR_ISR_ALREADY_CREATED 0x800000C5 +#define HI_ERR_ISR_NOT_CREATED 0x800000C6 +#define HI_ERR_ISR_ENABLE_IRQ_FAIL 0x800000C7 +#define HI_ERR_ISR_IRQ_ADDR_NOK 0x800000C8 + +/* Memory */ +#define HI_ERR_MEM_INVALID_PARAM 0x80000100 +#define HI_ERR_MEM_CREAT_POOL_FAIL 0x80000101 +#define HI_ERR_MEM_CREATE_POOL_NOT_ENOUGH_HANDLE 0x80000102 +#define HI_ERR_MEM_FREE_FAIL 0x80000103 +#define HI_ERR_MEM_RE_INIT 0x80000104 +#define HI_ERR_MEM_NOT_INIT 0x80000105 +#define HI_ERR_MEM_CREAT_POOL_MALLOC_FAIL 0x80000106 +#define HI_ERR_MEM_GET_INFO_FAIL 0x80000107 +#define HI_ERR_MEM_GET_OS_INFO_NOK 0x80000108 + +/* OSTIMER */ +#define HI_ERR_TIMER_FAILURE 0x80000140 +#define HI_ERR_TIMER_INVALID_PARAM 0x80000141 +#define HI_ERR_TIMER_CREATE_HANDLE_FAIL 0x80000142 +#define HI_ERR_TIMER_START_FAIL 0x80000143 +#define HI_ERR_TIMER_HANDLE_NOT_CREATE 0x80000144 +#define HI_ERR_TIMER_HANDLE_INVALID 0x80000145 +#define HI_ERR_TIMER_STATUS_INVALID 0x80000146 +#define HI_ERR_TIMER_STATUS_START 0x80000147 +#define HI_ERR_TIMER_INVALID_MODE 0x80000148 +#define HI_ERR_TIMER_EXPIRE_INVALID 0x80000149 +#define HI_ERR_TIMER_FUNCTION_NULL 0x8000014A +#define HI_ERR_TIMER_HANDLE_MAXSIZE 0x8000014B +#define HI_ERR_TIMER_MALLOC_FAIL 0x8000014C +#define HI_ERR_TIMER_NOT_INIT 0x8000014D + +/* semaphore */ +#define HI_ERR_SEM_INVALID_PARAM 0x80000180 +#define HI_ERR_SEM_CREATE_FAIL 0x80000181 +#define HI_ERR_SEM_DELETE_FAIL 0x80000182 +#define HI_ERR_SEM_WAIT_FAIL 0x80000183 +#define HI_ERR_SEM_SIG_FAIL 0x80000184 +#define HI_ERR_SEM_WAIT_TIME_OUT 0x80000185 + +/* Mutex */ +#define HI_ERR_MUX_INVALID_PARAM 0x800001C0 +#define HI_ERR_MUX_CREATE_FAIL 0x800001C1 +#define HI_ERR_MUX_DELETE_FAIL 0x800001C2 +#define HI_ERR_MUX_PEND_FAIL 0x800001C3 +#define HI_ERR_MUX_POST_FAIL 0x800001C4 + +/* message */ +#define HI_ERR_MSG_INVALID_PARAM 0x80000200 +#define HI_ERR_MSG_CREATE_Q_FAIL 0x80000201 +#define HI_ERR_MSG_DELETE_Q_FAIL 0x80000202 +#define HI_ERR_MSG_WAIT_FAIL 0x80000203 +#define HI_ERR_MSG_SEND_FAIL 0x80000204 +#define HI_ERR_MSG_GET_Q_INFO_FAIL 0x80000205 +#define HI_ERR_MSG_Q_DELETE_FAIL 0x80000206 +#define HI_ERR_MSG_WAIT_TIME_OUT 0x80000207 + +/* events */ +#define HI_ERR_EVENT_INVALID_PARAM 0x80000240 +#define HI_ERR_EVENT_CREATE_NO_HADNLE 0x80000241 +#define HI_ERR_EVENT_CREATE_SYS_FAIL 0x80000242 +#define HI_ERR_EVENT_SEND_FAIL 0x80000243 +#define HI_ERR_EVENT_WAIT_FAIL 0x80000244 +#define HI_ERR_EVENT_CLEAR_FAIL 0x80000245 +#define HI_ERR_EVENT_RE_INIT 0x80000246 +#define HI_ERR_EVENT_NOT_ENOUGH_MEMORY 0x80000247 +#define HI_ERR_EVENT_NOT_INIT 0x80000248 +#define HI_ERR_EVENT_DELETE_FAIL 0x80000249 +#define HI_ERR_EVENT_WAIT_TIME_OUT 0x8000024A + +/* os Maintenance and test */ +#define HI_ERR_OSSTAT_INVALID_PARAM 0x80000280 +#define HI_ERR_OSSTAT_SYSTEM_CALL_ERROR 0x80000281 + +/* liteos fpb */ +#define HI_ERR_FPB_COMP_REPEAT 0x800002C0 +#define HI_ERR_FPB_NO_COMP 0x800002C1 +#define HI_ERR_FPB_TYPE 0x800002C2 +#define HI_ERR_FPB_NO_FREE_COMP 0x800002C3 +#define HI_ERR_FPB_ADDR_NOT_ALIGN 0x800002C4 +#define HI_ERR_FPB_TARGET_ADDR 0x800002C5 +#define HI_ERR_FPB_BUSY 0x800002C6 /* ????????? */ +#define HI_ERR_FPB_ERROR_INPUT 0x800002C7 + +/* CPU */ +#define HI_ERR_CPUP_NOT_INIT 0x80000300 +#define HI_ERR_CPUP_INVALID_PARAM 0x80000301 +#define HI_ERR_CPU_CLK_INVALID_PARAM 0x80000302 + +/* file system */ +#define HI_ERR_FS_INVALID_PARAM 0x80000400 +#define HI_ERR_FS_NO_DEVICE 0x80000401 +#define HI_ERR_FS_NO_SPACE 0x80000402 /* No space left on device */ +#define HI_ERR_FS_BAD_DESCRIPTOR 0x80000403 +#define HI_ERR_FS_FILE_EXISTS 0x80000404 +#define HI_ERR_FS_NOT_FOUND 0x80000405 +#define HI_ERR_FS_NAME_TOO_LONG 0x80000406 +#define HI_ERR_FS_READ_ONLY_FS 0x80000407 /* Read-only file system */ +#define HI_ERR_FS_IO_ERROR 0x80000408 +#define HI_ERR_FS_NO_MORE_FILES 0x80000409 + +/***************************************************************************** +* 3、Driver error code +*****************************************************************************/ +/* Serial port */ +#define HI_ERR_UART_INVALID_PARAMETER 0x80001000 +#define HI_ERR_UART_INVALID_SUSPEND 0x80001001 +#define HI_ERR_UART_INVALID_PARITY 0x80001002 +#define HI_ERR_UART_INVALID_DATA_BITS 0x80001003 +#define HI_ERR_UART_INVALID_STOP_BITS 0x80001004 +#define HI_ERR_UART_INVALID_BAUD 0x80001005 +#define HI_ERR_UART_INVALID_COM_PORT 0x80001006 +#define HI_ERR_UART_NOT_SUPPORT_DMA 0x80001007 +#define HI_ERR_UART_NOT_BLOCK_MODE 0x80001008 + +/* gpio */ +#define HI_ERR_GPIO_INVALID_PARAMETER 0x80001040 +#define HI_ERR_GPIO_REPEAT_INIT 0x80001041 +#define HI_ERR_GPIO_NOT_INIT 0x80001042 +#define HI_ERR_GPIO_NOT_SUPPORT 0x80001043 + +/* watchdog */ +#define HI_ERR_WATCHDOG_PARA_ERROR 0x80001080 + +/* Flash */ +#define HI_ERR_FLASH_NOT_INIT 0x800010C0 +#define HI_ERR_FLASH_INVALID_PARAM 0x800010C1 +#define HI_ERR_FLASH_INVALID_PARAM_BEYOND_ADDR 0x800010C2 +#define HI_ERR_FLASH_INVALID_PARAM_SIZE_ZERO 0x800010C3 +#define HI_ERR_FLASH_INVALID_PARAM_ERASE_NOT_ALIGN 0x800010C4 +#define HI_ERR_FLASH_INVALID_PARAM_IOCTRL_DATA_NULL 0x800010C5 +#define HI_ERR_FLASH_INVALID_PARAM_DATA_NULL 0x800010C6 +#define HI_ERR_FLASH_INVALID_PARAM_PKI_MODIFY 0x800010C7 +#define HI_ERR_FLASH_INVALID_PARAM_PAD1 0x800010C8 +#define HI_ERR_FLASH_INVALID_PARAM_PAD2 0x800010C9 +#define HI_ERR_FLASH_INVALID_PARAM_PAD3 0x800010CA +#define HI_ERR_FLASH_TIME_OUT_WAIT_READY 0x800010CB +#define HI_ERR_FLASH_QUAD_MODE_READ_REG1 0x800010CC +#define HI_ERR_FLASH_QUAD_MODE_READ_REG2 0x800010CD +#define HI_ERR_FLASH_QUAD_MODE_COMPARE_REG 0x800010CE +#define HI_ERR_FLASH_NO_MATCH_FLASH 0x800010CF +#define HI_ERR_FLASH_WRITE_ENABLE 0x800010D0 +#define HI_ERR_FLASH_NO_MATCH_ERASE_SIZE 0x800010D1 +#define HI_ERR_FLASH_MAX_SPI_OP 0x800010D2 +#define HI_ERR_FLASH_NOT_SUPPORT_IOCTRL_ID 0x800010D3 +#define HI_ERR_FLASH_INVALID_CHIP_ID 0x800010D4 +#define HI_ERR_FLASH_RE_INIT 0x800010D5 +#define HI_ERR_FLASH_WRITE_NOT_SUPPORT_ERASE 0x800010D6 +#define HI_ERR_FLASH_WRITE_COMPARE_WRONG 0x800010D7 +#define HI_ERR_FLASH_WAIT_CFG_START_TIME_OUT 0x800010D8 +#define HI_ERR_FLASH_PATITION_INIT_FAIL 0x800010D9 +#define HI_ERR_FLASH_INITILIZATION 0x800010DA +#define HI_ERR_FLASH_ERASE_NOT_4K_ALIGN 0x800010DB +#define HI_ERR_FLASH_PROTECT_NOT_SUPPORT 0x800010DC +#define HI_ERR_FLASH_PROTECT_NOT_INIT 0x800010DD +#define HI_ERR_FLASH_PROTECT_RE_INIT 0x800010DE +#define HI_ERR_FLASH_PROTECT_NOT_FIND_CHIP 0x800010DF +#define HI_ERR_FLASH_PROTECT_ADDR_WRONG 0x800010E0 +#define HI_ERR_FLASH_CRYPTO_INVALID_PARAM 0x800010F0 +#define HI_ERR_FLASH_CRYPTO_BEYOND_ADDR_SIZE 0x800010F1 +#define HI_ERR_FLASH_CRYPTO_MALLOC_FAIL 0x800001F2 +#define HI_ERR_FLASH_CRYPTO_DATA_ENCRYPT_ERR 0x800001F3 +#define HI_ERR_FLASH_CRYPTO_DATA_DECRYPT_ERR 0x800001F4 +#define HI_ERR_FLASH_CRYPTO_KEY_EMPTY_ERR 0x800001F5 +#define HI_ERR_FLASH_CRYPTO_MEMCPY_FAIL 0x800001F6 +#define HI_ERR_FLASH_CRYPTO_NOT_SUPPORT 0x800001F7 +#define HI_ERR_FLASH_CRYPTO_PREPARE_ERR 0x800001F8 +#define HI_ERR_FLASH_CRYPTO_KEY_INVALID_ERR 0x800001F9 +#define HI_ERR_FLASH_CRYPTO_KEY_SAVE_ERR 0x800001FA +#define HI_ERR_FLASH_CRYPTO_KERNEL_ADDR_ERR 0x800001FB +#define HI_ERR_FLASH_CRYPTO_ROOT_SALT_EMPTY_ERR 0x800001FC + +/* HRTIMER */ +#define HI_ERR_HRTIMER_ALREADY_INIT 0x80001100 +#define HI_ERR_HRTIMER_NOT_INIT 0x80001101 +#define HI_ERR_HRTIMER_HAVE_NO_AVAILABLE_HANDLE 0x80001102 +#define HI_ERR_HRTIMER_NOT_CREATE_HANDLE 0x80001103 +#define HI_ERR_HRTIMER_IN_START_STATUS 0x80001104 +#define HI_ERR_HRTIMER_NOT_START 0x80001105 +#define HI_ERR_HRTIMER_INVALID_ID 0x80001106 +#define HI_ERR_HRTIMER_INVALID_PARAMETER 0x80001107 +#define HI_ERR_HRTIMER_MALLOC_FAILUE 0x80001108 + +/* hardware timer */ +#define HI_ERR_HWTIMER_INVALID_PARAMETER 0x80001140 +#define HI_ERR_HWTIMER_INITILIZATION_ALREADY 0x80001141 +#define HI_ERR_HWTIMER_NO_INIT 0x80001142 + +/* i2c */ +#define HI_ERR_I2C_NOT_INIT 0x80001180 +#define HI_ERR_I2C_INVALID_PARAMETER 0x80001181 +#define HI_ERR_I2C_TIMEOUT_START 0x80001182 +#define HI_ERR_I2C_TIMEOUT_WAIT 0x80001183 +#define HI_ERR_I2C_TIMEOUT_STOP 0x80001184 +#define HI_ERR_I2C_TIMEOUT_RCV_BYTE 0x80001185 +#define HI_ERR_I2C_TIMEOUT_RCV_BYTE_PROC 0x80001186 +#define HI_ERR_I2C_WAIT_SEM_FAIL 0x80001187 +#define HI_ERR_I2C_START_ACK_ERR 0x80001188 +#define HI_ERR_I2C_WAIT_ACK_ERR 0x80001189 + +/* spi */ +#define HI_ERR_SPI_NOT_INIT 0x800011C0 +#define HI_ERR_SPI_REINIT 0x800011C1 +#define HI_ERR_SPI_PARAMETER_WRONG 0x800011C2 +#define HI_ERR_SPI_BUSY 0x800011C3 +#define HI_ERR_SPI_WRITE_TIMEOUT 0x800011C4 +#define HI_ERR_SPI_READ_TIMEOUT 0x800011C5 +#define HI_ERR_SPI_NOT_SUPPORT_DMA 0x800011C6 + +/* efuse */ +#define HI_ERR_EFUSE_INVALIDATE_ID 0x80001200 +#define HI_ERR_EFUSE_INVALIDATE_PARA 0x80001201 +#define HI_ERR_EFUSE_WRITE_ERR 0x80001202 +#define HI_ERR_EFUSE_INVALIDATE_AUTH 0x80001203 +#define HI_ERR_EFUSE_BUSY 0x80001204 +#define HI_ERR_EFUSE_TIMEOUT 0x80001205 + +/* cipher */ +#define HI_ERR_CIPHER_NOT_INIT 0x80001240 +#define HI_ERR_CIPHER_INVALID_POINT 0x80001241 +#define HI_ERR_CIPHER_INVALID_PARAMETER 0x80001242 +#define HI_ERR_CIPHER_NO_AVAILABLE_RNG 0x80001243 +#define HI_ERR_CIPHER_FAILED_MEM 0x80001244 +#define HI_ERR_CIPHER_OVERFLOW 0x80001245 +#define HI_ERR_CIPHER_TIMEOUT 0x80001246 +#define HI_ERR_CIPHER_UNSUPPORTED 0x80001247 +#define HI_ERR_CIPHER_REGISTER_IRQ 0x80001248 +#define HI_ERR_CIPHER_ILLEGAL_KEY 0x80001249 +#define HI_ERR_CIPHER_INVALID_ADDR 0x8000124A +#define HI_ERR_CIPHER_INVALID_LENGTH 0x8000124B +#define HI_ERR_CIPHER_ILLEGAL_DATA 0x8000124C +#define HI_ERR_CIPHER_RSA_SIGN 0x8000124D +#define HI_ERR_CIPHER_RSA_VERIFY 0x8000124E +#define HI_ERR_CIPHER_RESULT_WARNING 0x8000124F +#define HI_ERR_CIPHER_FLUSH_DCACHE_FAILED 0x80001250 + +/* sdio */ +#define HI_ERR_SDIO_INVALID_PARAMETER 0x80001280 + +/* tsensor */ +#define HI_ERR_TSENSOR_INVALID_PARAMETER 0x800012C0 + +/* adc */ +#define HI_ERR_ADC_PARAMETER_WRONG 0x80001300 +#define HI_ERR_ADC_INVALID_CHANNEL_ID 0x80001301 +#define HI_ERR_ADC_TIMEOUT 0x80001302 +#define HI_ERR_ADC_NOT_INIT 0x80001303 + +/* pmw */ +#define HI_ERR_PWM_NO_INIT 0x80001340 +#define HI_ERR_PWM_INITILIZATION_ALREADY 0x80001341 +#define HI_ERR_PWM_INVALID_PARAMETER 0x80001342 + + +/* dma */ +#define HI_ERR_DMA_INVALID_PARA 0x80001380 +#define HI_ERR_DMA_NOT_INIT 0x80001381 +#define HI_ERR_DMA_BUSY 0x80001382 +#define HI_ERR_DMA_TRANSFER_FAIL 0x80001383 +#define HI_ERR_DMA_TRANSFER_TIMEOUT 0x80001384 +#define HI_ERR_DMA_GET_NOTE_FAIL 0x80001385 +#define HI_ERR_DMA_LLI_NOT_CREATE 0x80001386 +#define HI_ERR_DMA_CH_IRQ_ENABLE_FAIL 0x80001387 +/* audio */ +#define HI_ERR_AUDIO_BUSY 0x800013C0 +#define HI_ERR_AUDIO_INVALID_PARAMETER 0x800013C1 + +/* i2s */ +#define HI_ERR_I2S_INVALID_PARAMETER 0x80001400 +#define HI_ERR_I2S_WRITE_TIMEOUT 0x80001401 +#define HI_ERR_I2S_MALLOC_FAIL 0x80001402 +#define HI_ERR_I2S_MEMCPY_FAIL 0x80001403 + +/* shell */ +#define HI_ERR_SHELL_NOT_INIT 0x80001440 +#define HI_ERR_SHELL_CMDREG_PARA_ERROR 0x80001441 +#define HI_ERR_SHELL_CMDREG_CMD_ERROR 0x80001442 +#define HI_ERR_SHELL_CMDREG_CMD_EXIST 0x80001443 +#define HI_ERR_SHELL_CMDREG_MEMALLOC_ERROR 0x80001444 + +/***************************************************************************** +* 4、Intermediate application error code +*****************************************************************************/ +/* NV */ +#define HI_ERR_NV_FILE_ERR 0x80003000 +#define HI_ERR_NV_MEMCPY_FAIL 0x80003001 +#define HI_ERR_NV_WRITE_FILE_FAIL 0x80003002 +#define HI_ERR_NV_UPDATA_DATA_FAIL 0x80003003 +#define HI_ERR_NV_UPDATA_FILE_FAIL 0x80003004 +#define HI_ERR_NV_NOT_SUPPORT_WRITE 0x80003005 +#define HI_ERR_NV_FSEC_TOTAL_NUM_INVALID 0x80003006 /* 工厂NV项个数非法 */ +#define HI_ERR_NV_FAIL_N_TIMES 0x80003007 +#define HI_ERR_NV_SEM_FAIL 0x80003008 +#define HI_ERR_NV_LEN_ERR 0x80003009 +#define HI_ERR_NV_NOT_FOUND 0x8000300A +#define HI_ERR_NV_FULL 0x8000300B +#define HI_ERR_NV_NOT_ENOUGH_MEMORY 0x8000300C +#define HI_ERR_NV_NOT_SUPPORT 0x8000300D +#define HI_ERR_NV_NOT_SUPPORT_ID 0x8000300E +#define HI_ERR_NV_BAD_DATA 0x8000300F +#define HI_ERR_NV_INVALID_TYPE 0x80003010 +/* NV读取失败 CNcomment:Read NVIM Failure */ +#define HI_ERR_NV_ERROR_READ 0x80003011 +/* NV写失败,长度过长CNcomment:Write Error for Length Overflow */ +#define HI_ERR_NV_NOT_SUPPORT_LENTH 0x80003012 +/* NV写失败,Flash坏块 CNcomment:Write Error for Flash Bad Block */ +#define HI_ERR_NV_BAD_BLOCK 0x80003013 +/* NV写失败,其他错误 CNcomment:Write Error for Unknown Reason */ +#define HI_ERR_NV_ERROR_WRITE 0x80003014 +#define HI_ERR_NV_INITILIZATION 0x80003015 +#define HI_ERR_NV_INVALID_PARAMETER 0x80003016 + +/* Low power consumption */ +#define HI_ERR_LOWPOWER_INVALID_PARAMETER 0x80003040 +#define HI_ERR_LOWPOWER_XTAL_UNSTABLE 0x80003041 +#define HI_ERR_LOWPOWER_XTAL_SAMPLING 0x80003042 + +/* upgrade common error */ +#define HI_ERR_UPG_COMMON 0x80003060 +#define HI_ERR_UPG_NULL_POINTER (HI_ERR_UPG_COMMON + 0x0) +#define HI_ERR_UPG_PARAMETER (HI_ERR_UPG_COMMON + 0x1) +#define HI_ERR_UPG_BACKUP_ADDR (HI_ERR_UPG_COMMON + 0x2) +#define HI_ERR_UPG_BUSY (HI_ERR_UPG_COMMON + 0x3) +#define HI_ERR_UPG_FLASH_BAD (HI_ERR_UPG_COMMON + 0x4) +#define HI_ERR_UPG_START_ADDR (HI_ERR_UPG_COMMON + 0x5) +#define HI_ERR_UPG_INITILIZATION_ALREADY (HI_ERR_UPG_COMMON + 0x6) +#define HI_ERR_UPG_FILE_LEN (HI_ERR_UPG_COMMON + 0x7) +#define HI_ERR_UPG_NOT_START (HI_ERR_UPG_COMMON + 0x8) +#define HI_ERR_UPG_MALLOC_FAIL (HI_ERR_UPG_COMMON + 0x9) +#define HI_ERR_UPG_GET_SECTION_HEAD (HI_ERR_UPG_COMMON + 0xA) +#define HI_ERR_UPG_BUF_LEN (HI_ERR_UPG_COMMON + 0xB) +#define HI_ERR_UPG_FLASH_SIZE (HI_ERR_UPG_COMMON + 0xC) +#define HI_ERR_UPG_NV_SIZE (HI_ERR_UPG_COMMON + 0xD) +#define HI_ERR_UPG_ALREADY_FINISH (HI_ERR_UPG_COMMON + 0xE) +#define HI_ERR_UPG_RSA_KEY_ADDR (HI_ERR_UPG_COMMON + 0xF) +#define HI_ERR_UPG_ECC_KEY_ADDR (HI_ERR_UPG_COMMON + 0x10) +#define HI_ERR_UPG_FILE_LEN_OVER (HI_ERR_UPG_COMMON + 0x11) +#define HI_ERR_UPG_STOP (HI_ERR_UPG_COMMON + 0x12) +#define HI_ERR_UPG_LOW_KERNEL_VER (HI_ERR_UPG_COMMON + 0x13) +#define HI_ERR_UPG_FULL_KERNEL_VER (HI_ERR_UPG_COMMON + 0x14) +#define HI_ERR_UPG_LOW_BOOT_VER (HI_ERR_UPG_COMMON + 0x15) +#define HI_ERR_UPG_FULL_BOOT_VER (HI_ERR_UPG_COMMON + 0x16) +#define HI_ERR_UPG_FIRST_PACKET_OFFSET (HI_ERR_UPG_COMMON + 0x17) +#define HI_ERR_UPG_UPDATE_VER_TIMEOUT (HI_ERR_UPG_COMMON + 0x18) +#define HI_ERR_UPG_UPDATE_VER_FAIL (HI_ERR_UPG_COMMON + 0x19) +#define HI_ERR_UPG_UPDATE_VER_INVALID_PARAM (HI_ERR_UPG_COMMON + 0x1A) +#define HI_ERR_UPG_KERNEL_VER_OVER (HI_ERR_UPG_COMMON + 0x1B) +#define HI_ERR_UPG_BOOT_VER_OVER (HI_ERR_UPG_COMMON + 0x1C) +#define HI_ERR_UPG_KERNEL_LEN (HI_ERR_UPG_COMMON + 0x1D) +#define HI_ERR_UPG_KEY_LEN (HI_ERR_UPG_COMMON + 0x1E) + +/* upgrade file check error */ +#define HI_ERR_UPG_CHECK 0x80003080 +#define HI_ERR_UPG_IMAGE_ID (HI_ERR_UPG_CHECK + 0x0) +#define HI_ERR_UPG_FILE_TYPE (HI_ERR_UPG_CHECK + 0x1) +#define HI_ERR_UPG_HEAD_LEN (HI_ERR_UPG_CHECK + 0x2) +#define HI_ERR_UPG_SIGN_ALG (HI_ERR_UPG_CHECK + 0x3) +#define HI_ERR_UPG_RSA_KEY_LEN (HI_ERR_UPG_CHECK + 0x4) +#define HI_ERR_UPG_RSA_HEAD_SIGN (HI_ERR_UPG_CHECK + 0x5) +#define HI_ERR_UPG_ECC_KEY_LEN (HI_ERR_UPG_CHECK + 0x6) +#define HI_ERR_UPG_ECC_HEAD_SIGN (HI_ERR_UPG_CHECK + 0x7) +#define HI_ERR_UPG_COMMON_SHA256 (HI_ERR_UPG_CHECK + 0x8) +#define HI_ERR_UPG_SECTION_SHA256 (HI_ERR_UPG_CHECK + 0x9) +#define HI_ERR_UPG_KERNEL_VER (HI_ERR_UPG_CHECK + 0xA) +#define HI_ERR_UPG_BOOT_VER (HI_ERR_UPG_CHECK + 0xB) +#define HI_ERR_UPG_BOOT_HEAD (HI_ERR_UPG_CHECK + 0xC) +#define HI_ERR_UPG_BOOT_LEN (HI_ERR_UPG_CHECK + 0xD) +#define HI_ERR_UPG_BOOT_ROOT_KEY (HI_ERR_UPG_CHECK + 0xE) +#define HI_ERR_UPG_BOOT_ROOT_KEY_LEN (HI_ERR_UPG_CHECK + 0xF) +#define HI_ERR_UPG_BOOT_KEY_ID (HI_ERR_UPG_CHECK + 0x10) +#define HI_ERR_UPG_BOOT_SIGN_ALG (HI_ERR_UPG_CHECK + 0x11) +#define HI_ERR_UPG_BOOT_SUB_KEY (HI_ERR_UPG_CHECK + 0x12) +#define HI_ERR_UPG_BOOT_SUB_KEY_CAT (HI_ERR_UPG_CHECK + 0x13) +#define HI_ERR_UPG_BOOT_SUB_KEY_RSIM (HI_ERR_UPG_CHECK + 0x14) +#define HI_ERR_UPG_BOOT_DIE_ID (HI_ERR_UPG_CHECK + 0x15) +#define HI_ERR_UPG_BOOT_HASH (HI_ERR_UPG_CHECK + 0x16) +#define HI_ERR_UPG_BOOT_SUB_KEY_LEN (HI_ERR_UPG_CHECK + 0x17) +#define HI_ERR_UPG_USER_VERIFY (HI_ERR_UPG_CHECK + 0x18) +#define HI_ERR_UPG_BOOT_SUB_KEY_HASH (HI_ERR_UPG_CHECK + 0x19) +#define HI_ERR_UPG_BOOT_SECTION_HASH (HI_ERR_UPG_CHECK + 0x1A) +#define HI_ERR_UPG_COMMON_HASH (HI_ERR_UPG_CHECK + 0x1B) +#define HI_ERR_UPG_SECTION_HASH (HI_ERR_UPG_CHECK + 0x1C) +#define HI_ERR_UPG_ADD_START (HI_ERR_UPG_CHECK + 0x1D) +#define HI_ERR_UPG_ENCRYPT_NOT_MATCH (HI_ERR_UPG_CHECK + 0x1E) +#define HI_ERR_UPG_OTA_NOT_MATCH (HI_ERR_UPG_CHECK + 0x1F) + +/* upgrade file crypto error */ +#define HI_ERR_UPG_CRYPTO 0x800030A0 +#define HI_ERR_UPG_CRYPTO_PREPARE_ERR (HI_ERR_UPG_CRYPTO + 0x0) +#define HI_ERR_UPG_FILE_DECRYPT_ERR (HI_ERR_UPG_CRYPTO + 0x1) +#define HI_ERR_UPG_NOT_WITH_CACHE_MODE_ERR (HI_ERR_UPG_CRYPTO + 0x2) +#define HI_ERR_UPG_NOT_DOWNLOAD_FINISH (HI_ERR_UPG_CRYPTO + 0x3) + +/* DIAG */ +#define HI_ERR_DIAG_NOT_FOUND 0x800030C0 +#define HI_ERR_DIAG_INVALID_ID 0x800030C1 +#define HI_ERR_DIAG_FULL 0x800030C2 +#define HI_ERR_DIAG_CONSUMED 0x800030C3 +#define HI_ERR_DIAG_CONTINUE 0x800030C4 +#define HI_ERR_DIAG_TOO_SMALL_BUFFER 0x800030C5 +#define HI_ERR_DIAG_NO_MORE_DATA 0x800030C6 +#define HI_ERR_DIAG_NOT_ENOUGH_MEMORY 0x800030C7 +#define HI_ERR_DIAG_INVALID_HEAP_ADDR 0x800030C8 +#define HI_ERR_DIAG_NOT_CONNECT 0x800030C9 +#define HI_ERR_DIAG_BUSY 0x800030CA +#define HI_ERR_DIAG_TOO_LARGE_FRAME 0x800030CB +#define HI_ERR_DIAG_RAM_ALIGN 0x800030CC +#define HI_ERR_DIAG_NOT_SUPPORT 0x800030CD +#define HI_ERR_DIAG_UNAVAILABLE 0x800030CE +#define HI_ERR_DIAG_CFG_NOT_ALLOW 0x800030CF +#define HI_ERR_DIAG_INVALID_CODE_ADDR 0x800030D0 +#define HI_ERR_DIAG_OBJ_NOT_FOUND 0x800030D1 +#define HI_ERR_DIAG_QUEUE_FULL 0x800030D2 +#define HI_ERR_DIAG_NO_MORE_MEMORY 0x800030D3 +#define HI_ERR_DIAG_SYSTEM_CALL_ERROR 0x800030D4 +#define HI_ERR_DIAG_NO_INIT 0x800030D5 +#define HI_ERR_DIAG_INVALID_PARAMETER 0x800030D6 +#define HI_ERR_DIAG_STAT_NOT_SUPPORT 0x800030D7 +#define HI_ERR_DIAG_ID_OR_CALLBACK_ALREADY_REGISTERED 0x800030D8 +#define HI_ERR_DIAG_SET_CONN_ACK_INFO 0x800030D9 +#define HI_ERR_DIAG_CMD_NUM_EXCEED_UPPER_LIMIT 0x800030DA + +/* reset */ +#define HI_ERR_RESET_TOO_LARGE_DATA 0x80003100 +#define HI_ERR_RESET_INVALID_PARAMETER 0x80003101 + +/* syserror */ +#define HI_ERR_SYSERROR_NOT_FOUND 0x80003140 +#define HI_ERR_SYSERROR_INVALID_PARAMETER 0x80003141 + + +/* APP */ +#define HI_ERR_APP_INITILIZATION_ALREADY 0x80003180 +#define HI_ERR_APP_INVALID_PARAMETER 0x80003181 + +/* CRC */ +#define HI_ERR_CRC_INVALID_PARAMETER 0x800031C0 + + +/* sigma */ +#define HI_ERR_SIGMA_INVALID_PARAMETER 0x80003200 + +/* data collect */ +#define HI_ERR_DATACOLLECT_INVALID_PARAMETER 0x80003240 +#define HI_ERR_DATACOLLECT_BUSY 0x80003241 + +/* AT */ +#define HI_ERR_AT_NAME_OR_FUNC_REPEAT_REGISTERED 0x80003280 +#define HI_ERR_AT_INVALID_PARAMETER 0x80003281 + +/***************************************************************************** +* 5、Protocol stack error codes +*****************************************************************************/ +/* wifi */ +/* Note: The base value of the Wi-Fi error code hi_err_code_enum is changed to the start value, + * and other error codes are delayed at one time. + * CNcomment:说明:wifi错误码hi_err_code_enum 将base基值修改为起始值,其他错误码一次延顺 + */ +/* dmac */ +#define HI_ERR_WIFI_DMAC_NOT_SUPPORT 0x80004000 + +/* hmac */ +#define HI_ERR_WIFI_HMAC_INVALID_PARAMETER 0x80004040 + +/* wal */ +#define HI_ERR_WIFI_WAL_MALLOC_FAIL 0x80004080 +#define HI_ERR_WIFI_WAL_FAILURE 0x80004081 +#define HI_ERR_WIFI_WAL_BUSY 0x80004082 +#define HI_ERR_WIFI_WAL_INVALID_PARAMETER 0x80004083 + +/***************************************************************************** +* 6、128 units reserved for Hisi.CNcomment:Hisi保留 unit128个 +* 7、64 units reserved for customer use. CNcomment:客户使用预留 unit64个 +*****************************************************************************/ +#endif /* __HI_ERRNO_H__ */ diff --git a/sdk_liteos/include/hi_event.h b/sdk_liteos/include/hi_event.h new file mode 100644 index 0000000000000000000000000000000000000000..8fb58606b3389c660ccc172057731eb2515ec97a --- /dev/null +++ b/sdk_liteos/include/hi_event.h @@ -0,0 +1,226 @@ +/** + * @file hi_event.h + * + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Description: system event API.CNcomment:系统事件接口。CNend + * @li Before sending, waiting, or clearing an event, the event must be created to obtain the event ID. +CNcomment:在发送、等待、清空事件之前首先需要创建事件,获取事件使用ID。CNend + * @li Wait event: The wait event API cannot be called in the interrupt, interrupt off, + * and lock task contexts to avoid uncontrollable exceptional scheduling.CNcomment:等待事件:在中断、 +关中断、锁任务上下文禁止调用等待事件接口,进而产生不可控的异常调度。CNend + * @li TX event: The TX event API cannot be called in the interrupt off context to avoid uncontrollable +exceptional scheduling.CNcomment:发送事件:在关中断上下文禁止调用发送事件接口, +进而产生不可控的异常调度。CNend + * @li Each bit of bit[0:23] of an event can represent an event type. The meaning of each bit is allocated by the user. +CNcomment:一个事件的[0:23]bit的每一bit可以表示一种事件,每一位的意义由用户自定义分配。CNend + * @li Bit[24:31] of an event are reserved and cannot be used by the user. +CNcomment:一个事件的[24:31]bit系统保留,用户不得使用。CNend \n + */ + +/** + * @defgroup iot_event Event + * @ingroup osa + */ +#ifndef __HI_EVENT_H__ +#define __HI_EVENT_H__ +#include + +#define HI_INVALID_EVENT_ID 0xffffffff /**< Failed to obtain the event ID.CNcoment:获取事件ID失败CNend */ +#define HI_EVENT_WAITMODE_AND 4 /**< If all expected events occur, the wait is successful. + It cannot be used with HI_EVENT_WAITMODE_OR at the same time. + CNcomment:所有预期等待的事件均发生时,才认定等待成功, + 不允许与HI_EVENT_WAITMODE_OR同时使用 CNend */ +#define HI_EVENT_WAITMODE_OR 2 /**< If any of the expected events occurs, the wait is successful. + It cannot be used with HI_EVENT_WAITMODE_AND at the same time. + CNcomment:所有预期等待的事件发生任意一种,认定等待成功, + 不允许与HI_EVENT_WAITMODE_AND同时使用 CNend */ +#define HI_EVENT_WAITMODE_CLR 1 /**< The waited event is cleared when the wait event is successful. + CNcomment:等待事件成功时,清除等待到的事件CNend */ + +/** +* @ingroup iot_event +* @brief Creates an event.CNcomment:创建事件。CNend +* +* @par 描述: +* Creates an event to obtain the event ID.CNcomment:创建事件,获取事件使用ID。CNend +* +* @attention +* @li The read/write event interface cannot be invoked before system initialization. +CNcomment:在系统初始化之前不能调用读写事件接口。CNend +* @li In the interrupt, the event object can be written, but cannot be read. +CNcomment:在中断中,可以对事件对象进行写操作,但不能读操作。CNend +* @li In the lock task scheduling state, a write operation can be performed on an event object, but the +* read operation cannot be performed.CNcomment:在锁任务调度状态下,可以对事件对象进行写操作, +但不能读操作。CNend +* +* @param id [OUT] type #hi_u32*,Event ID. +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* +* @par 依赖: +* @li hi_event.h:Describes event APIs.CNcomment:文件用于描述事件相关接口。CNend +* @see hi_event_delete。 +*/ +hi_u32 hi_event_create(HI_OUT hi_u32 *id); + +/** +* @ingroup iot_event +* @brief Defines the TX event. CNcomment:发送事件。CNend +* +* @par 描述: +* Defines the TX event.CNcomment:发送事件。CNend +* +* @attention +* @li The read/write event interface cannot be invoked before system initialization. +CNcomment:在系统初始化之前不能调用读写事件接口。CNend +* @li In the interrupt, the event object can be written, but cannot be read. +CNcomment:在中断中,可以对事件对象进行写操作,但不能读操作。CNend +* @li In the lock task scheduling state, a write operation can be performed on an event object, but the +* read operation cannot be performed.CNcomment:在锁任务调度状态下,可以对事件对象进行写操作, +但不能读操作。CNend +* +* @param id [IN] type #hi_u32,Event ID. +* @param event_bits [IN] type #hi_u32,Set of events to be sent.CNcomment:事件bit位。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* +* @par 依赖: +* @li hi_event.h:Describes event APIs.CNcomment:文件用于描述事件相关接口。CNend +* @see hi_event_wait。 +*/ +hi_u32 hi_event_send(hi_u32 id, hi_u32 event_bits); + +/** +* @ingroup iot_event +* @brief Defines the wait event.CNcomment:等待事件。CNend +* +* @par 描述: +* Defines the wait event.CNcomment:等待事件。CNend +* +* @attention +* @li The read/write event interface cannot be invoked before system initialization. +CNcomment:在系统初始化之前不能调用读写事件接口。CNend +* @li In the interrupt, the event object can be written, but cannot be read. +CNcomment:在中断中,可以对事件对象进行写操作,但不能读操作。CNend +* @li In the lock task scheduling state, a write operation can be performed on an event object, but the +* read operation cannot be performed.CNcomment:在锁任务调度状态下,可以对事件对象进行写操作, +但不能读操作。CNend +* +* @param id [IN] type #hi_u32,Event ID. +* @param mask [IN] type #hi_u32,Set of events to be waited for, which may be one bit or multiple bits in +* bits 0-23.CNcomment:预等待的事件集合,可以为0~23bit中的1bit或多bit。CNend +* @param event_bits [OUT] type #hi_u32*,Set of events to be sent.CNcomment:事件bit位。CNend +* @param timeout [IN] type #hi_u32,Waiting timeout period (unit: ms). +CNcomment:等待超时时间(单位:ms)。CNend +* @param flag [IN] type #hi_u32,Waiting option. For details, see #HI_EVENT_WAITMODE_AND, +* #HI_EVENT_WAITMODE_OR, and #HI_EVENT_WAITMODE_CLR. +CNcomment:等待选项,取值见#HI_EVENT_WAITMODE_AND、#HI_EVENT_WAITMODE_OR、#HI_EVENT_WAITMODE_CLR。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* +* @par 依赖: +* @li hi_event.h:Describes event APIs.CNcomment:文件用于描述事件相关接口。CNend +* @see hi_event_send。 +*/ +hi_u32 hi_event_wait(hi_u32 id, hi_u32 mask, HI_OUT hi_u32 *event_bits, hi_u32 timeout, hi_u32 flag); + +/** +* @ingroup iot_event +* @brief Defines the clearing event.CNcomment:清除事件。CNend +* +* @par 描述: +* Defines the clearing event.CNcomment:清除事件。CNend +* +* @attention +* @li The read/write event interface cannot be invoked before system initialization. +CNcomment:在系统初始化之前不能调用读写事件接口。CNend +* @li In the interrupt, the event object can be written, but cannot be read. +CNcomment:在中断中,可以对事件对象进行写操作,但不能读操作。CNend +* @li In the lock task scheduling state, a write operation can be performed on an event object, but the +* read operation cannot be performed.CNcomment:在锁任务调度状态下,可以对事件对象进行写操作, +但不能读操作。CNend +* +* @param id [IN] type #hi_u32,Event ID. +* @param event_bits [IN] type #hi_u32,Set of events to be cleared, which may be one bit or multiple bits in +* bits 0-23.CNcomment:清除的事件集合,可以为0~23bit中的1bit或多bit。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* +* @par 依赖: +* @li hi_event.h:Describes event APIs.CNcomment:文件用于描述事件相关接口。CNend +* @see hi_event_wait。 +*/ +hi_u32 hi_event_clear(hi_u32 id, hi_u32 event_bits); + +/** +* @ingroup iot_event +* @brief Deletion event.CNcomment:删除事件。CNend +* +* @par 描述: +* Defines the deletion event, releasing an event ID.CNcomment:删除事件,释放事件使用id。CNend +* +* @attention +* @li The read/write event interface cannot be invoked before system initialization. +CNcomment:在系统初始化之前不能调用读写事件接口。CNend +* @li In the interrupt, the event object can be written, but cannot be read. +CNcomment:在中断中,可以对事件对象进行写操作,但不能读操作。CNend +* @li In the lock task scheduling state, a write operation can be performed on an event object, but the +* read operation cannot be performed.CNcomment:在锁任务调度状态下,可以对事件对象进行写操作, +但不能读操作。CNend +* +* @param id [IN] type #hi_u32,Event ID. +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* +* @par 依赖: +* @li hi_event.h:Describes event APIs.CNcomment:文件用于描述事件相关接口。CNend +* @see hi_event_create。 +*/ +hi_u32 hi_event_delete(hi_u32 id); + +/** +* @ingroup iot_event +* @brief Initializes event resources.CNcomment:初始化事件资源。CNend +* +* @par 描述: +* Initializes event resources. This API is called during system initialization only once. +CNcomment:初始化event资源,初始化阶段调用。CNend +* +* @attention Change the number of event resources based on the site requirements. +CNcomment:用户需根据实际使用情况修改event资源个数CNend +* +* @param max_event_cnt [IN] type #hi_u8,Number of event resources.CNcomment:event资源个数。CNend +* @param event_space [IN] type #hi_pvoid,Event resource space. If the value is null, +* it indicates that the space is applied internally. If this parameter is not null, +* external space is used to create event resources. Currently, set this parameter to HI_NULL. +CNcomment:event资源空间。传空表示空间由内部申请;非空表示使用外部空间用于创建event资源。 +当前请传HI_NULL。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* +* @par 依赖: +* @li hi_event.h:Describes event APIs.CNcomment:文件用于描述事件相关接口。CNend +* @see None +*/ +hi_u32 hi_event_init(hi_u8 max_event_cnt, hi_pvoid event_space); + +#endif + diff --git a/sdk_liteos/include/hi_flash.h b/sdk_liteos/include/hi_flash.h new file mode 100644 index 0000000000000000000000000000000000000000..d80bd8421809bfcf4d77ac12268ae7d6702d99a4 --- /dev/null +++ b/sdk_liteos/include/hi_flash.h @@ -0,0 +1,170 @@ +/* + * @file hi_flash.h + * + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** @defgroup iot_flash Flash + * @ingroup drivers + */ +#ifndef __HI_FLASH_H__ +#define __HI_FLASH_H__ + +#include +#include +/** +* @ingroup iot_flash +* @brief Reads the flash data to the specified cache. CNcomment:读出Flash数据到指定缓存区域。CNend +* +* @par 描述: +* Reads the flash data to the specified cache. CNcomment:读出Flash数据到指定缓存区域。CNend +* +* @attention None +* @param flash_offset [IN] type #const hi_u32,Offset of the flash address.CNcomment:指定的Flash地址偏移。CNend +* @param size [IN] type #const hi_u32,Read length (unit: byte). +CNcomment:指定读取的长度(单位:byte)。CNend +* @param ram_data [OUT] type #hi_u8*,Destination cache address.CNcomment:目的缓存地址。CNend +* +* @retval #HI_ERR_SUCCESS Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_flash.h:FLASH driver APIs.CNcomment:该接口声明所在的头文件。CNend +* @see None +*/ +hi_u32 hi_flash_read(const hi_u32 flash_offset, const hi_u32 size, hi_u8 *ram_data); + +/** +* @ingroup iot_flash +* @brief Writes data to the specified flash partition.CNcomment:把数据写入指定的Flash区。CNend +* +* @par 描述: +* Writes data to the specified flash partition.CNcomment:把数据写入指定的Flash区域。CNend +* +* @attention +* @li Restriction protection for the relative address of the flash memory. +CNcomment:Flash相对地址的限制保护。CNend +* @li The number of flash erase times must comply with the device data sheet. +CNcomment:Flash擦写次数限制。CNend +* @li Determine whether to erase the flash before the write based on the actual control scenario. +CNcomment:根据用户实际控制场景决定是否先擦后写。CNend +* @param flash_offset [IN] type #const hi_u32,Offset address for writing data to the flash memory. +CNcomment:指定写入Flash偏移地址。CNend +* @param size [IN] type #hi_u32,Length of the data to be written (unit: byte). +CNcomment:需要写入的长度(单位:byte)。CNend +* @param ram_data [IN] type #const hi_u8*,Cache address of the data to be written. +CNcomment:需要写入的数据的缓存地址。CNend +* @param do_erase [IN] type #hi_bool,HI_FALSE: Write data to the flash memory directly. +* HI_TRUE: Erase the sector space before write. +* The user data is written to the user operation space and the historical +* data is written back to other spaces.CNcomment:表示是否自动擦除并覆盖写入。 +* @li HI_TRUE:本接口中先擦后写。 +* @li HI_FALSE:用户已经擦除本接口,可直接写入。CNend +* +* @retval #HI_ERR_SUCCESS Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_flash.h:FLASH driver APIs.CNcomment:该接口声明所在的头文件。CNend +* @see None +*/ +hi_u32 hi_flash_write(const hi_u32 flash_offset, hi_u32 size, const hi_u8 *ram_data, hi_bool do_erase); + +/** +* @ingroup iot_flash +* @brief Erases the data in the specified flash partition.CNcomment:把指定的Flash区域数据擦除。CNend +* +* @par 描述: +* Erases the data in the specified flash partition.CNcomment:把指定的Flash区域数据擦除。CNend +* +* @attention +* @li Restriction protection for the relative address of the flash memory. +CNcomment:Flash相对地址的限制保护。CNend +* @li The number of flash erase times must comply with the device data sheet. +CNcomment:Flash擦写次数限制。CNend +* +* @param flash_offset [IN] type #const hi_u32,Address offset of the flash memory to be erased. +CNcomment:指定要擦除Flash的地址偏移。CNend +* @param size [IN] type #const hi_u32,Length of the data to be erased (unit: byte). +* The value must be a multiple of 4 KB. +CNcomment:需要擦除的长度(单位:byte),必须是4K的倍数。CNend +* +* @retval #HI_ERR_SUCCESS Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_flash.h:FLASH driver APIs.CNcomment:该接口声明所在的头文件。CNend +* @see None +*/ +hi_u32 hi_flash_erase(const hi_u32 flash_offset, const hi_u32 size); + +/** +* @ingroup iot_flash +* @brief Initializes the flash device. CNcomment:初始化Flash设备。CNend +* +* @par 描述: +* Initializes the flash device. CNcomment:初始化Flash设备。CNend +* +* @attention Initialize the flash module during system boot. +CNcomment:Flash模块初始化,一般在系统启动时调用。CNend +* @param None +* +* @retval #HI_ERR_SUCCESS Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_flash.h:FLASH driver APIs.CNcomment:该接口声明所在的头文件。CNend +* @see None +*/ +hi_u32 hi_flash_init(hi_void); + +/** +* @ingroup iot_flash +* @brief Deinitializes the flash device.CNcomment:去初始化Flash设备。CNend +* +* @par 描述: +* Deinitializes the flash device.CNcomment:去初始化Flash设备。CNend +* +* @attention None +* @param None +* +* @retval #HI_ERR_SUCCESS Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_flash.h:FLASH driver APIs.CNcomment:该接口声明所在的头文件。CNend +* @see None +*/ +hi_u32 hi_flash_deinit(hi_void); +/** +* @ingroup iot_flash +* @brief Sets or reads flash information.CNcomment:获取Flash信息。CNend +* +* @par 描述: +* Sets or reads flash information.CNcomment:获取Flash信息。CNend +* +* @attention None +* @param cmd [IN] type #hi_u16,Command ID, currently supports HI_FLASH_CMD_GET_INFO and +* HI_FLASHI_FLASH_CMD_IS_BUSY. +CNcomment:命令ID,当前支持HI_FLASH_CMD_GET_INFO 和 HI_FLASH_CMD_IS_BUSY。CNend +* @param data [IN/OUT] type #hi_void*, Information set or obtained. cmd is HI_FLASH_CMD_GET_INFO, data is +* a pointer of hi_flash_info struct; cmd is HI_FLASH_CMD_IS_BUSY, data is a pointer of type +* hi_bool.CNcomment:数据信息,cmd参数为HI_FLASH_CMD_GET_INFO,data为hi_flash_info结构指针; +* cmd为HI_FLASH_CMD_IS_BUSY,data为hi_bool类型指针。CNend +* +* @retval #HI_ERR_SUCCESS Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_flash.h:FLASH driver APIs.CNcomment:该接口声明所在的头文件。CNend +* @see None +*/ +hi_u32 hi_flash_ioctl(HI_IN hi_u16 cmd, HI_INOUT hi_void *data); + +#endif + diff --git a/sdk_liteos/include/hi_flash_base.h b/sdk_liteos/include/hi_flash_base.h new file mode 100644 index 0000000000000000000000000000000000000000..a07e89080b57cf198b783e902263df7f38f83719 --- /dev/null +++ b/sdk_liteos/include/hi_flash_base.h @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __HI_FLASH_BASE_H__ +#define __HI_FLASH_BASE_H__ + +#include + +#define HI_FLASH_CMD_ADD_FUNC 0 +#define HI_FLASH_CMD_GET_INFO 1 /**< IOCTL command ID for obtaining the flash information. + The corresponding output parameter points to the hi_flash_info structure. +CNcomment:IOCTL获取Flash信息,对应出参指向结构体为hi_flash_info.CNend */ +#define HI_FLASH_CMD_IS_BUSY 2 /**< IOCTL Obtain whether the flash memory is busy. The corresponding output + parameter point type is hi_bool. +CNcomment:IOCTL获取Flash是否busy,对应出参指向类型为hi_bool CNend */ + +#define HI_FLASH_CHIP_ID_NUM 3 +#define HI_FLASH_CAPACITY_ID 2 + +/** +* @ingroup iot_flash +* +* Flash information obtaining structure, used to describe the return structure of the command ID HI_FLASH_CMD_GET_INFO. +CNcomment:Flash信息获取结构体,用于描述命令ID(HI_FLASH_CMD_GET_INFO)的返回结构体。CNend +*/ +typedef struct { + hi_char *name; /**< Flash name.CNcomment:Flash名字CNend */ + hi_u8 id[HI_FLASH_CHIP_ID_NUM]; /**< Flash Id */ + hi_u8 pad; + hi_u32 total_size; /**< Flash totoal size (unit: byte). + CNcomment:Flash总大小(单位:byte)CNend */ + hi_u32 sector_size; /**< Flash block size (unit: byte). + CNcomment:Flash块大小(单位:byte)CNend */ +} hi_flash_info; + +#endif + diff --git a/sdk_liteos/include/hi_fs.h b/sdk_liteos/include/hi_fs.h new file mode 100644 index 0000000000000000000000000000000000000000..a40cb9e10d1ab7bb30f999b9ba74186fa9390caa --- /dev/null +++ b/sdk_liteos/include/hi_fs.h @@ -0,0 +1,349 @@ +/* + * @file hi_fs.h + * + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @defgroup iot_fs Filesystem + * @ingroup osa + */ +#ifndef __HI_FS_H__ +#define __HI_FS_H__ + +#include + +typedef struct { + hi_u32 size; + hi_u32 next_offset; + hi_char name[1]; +}hi_file_list; + + +#define HI_FS_SEEK_SET (0) /**< set file offset to offset */ +#define HI_FS_SEEK_CUR (1) /**< set file offset to current plus offset */ +#define HI_FS_SEEK_END (2) /**< set file offset to EOF plus offset */ + +#define HI_FS_O_RDONLY 00 +#define HI_FS_O_WRONLY 01 +#define HI_FS_O_RDWR 02 + +#define HI_FS_O_CREAT 0100 +#define HI_FS_O_EXCL 0200 +#define HI_FS_O_TRUNC 01000 +#define HI_FS_O_APPEND 02000 +#define HI_FS_O_PATH 010000000 + + +#define HI_FS_O_SEARCH HI_FS_O_PATH +#define HI_FS_O_ACCMODE (HI_FS_O_RDONLY | HI_FS_O_WRONLY | HI_FS_O_RDWR | HI_FS_O_SEARCH) + +/** +* @ingroup iot_fs +* @brief Get filesystem error code.CNcomment:获取错误码。CNend +* +* @par 描述: +* @li Returns the filesystem's most recent error code value.CNcomment:返回文件系统最近的错误代码值。CNend +* +* @attention None +* @param None +* +* @retval filesystem error code.CNcomment:文件系统错误码。CNend +* @par 依赖: +* @li hi_fs.h:describes the filesystem APIs.CNcomment:文件用于描述文件系统相关接口。CNend +* @see hi_get_fs_error +*/ +hi_s32 hi_get_fs_error(hi_void); + +/** +* @ingroup iot_fs +* @brief Set filesystem check and repair.CNcomment:设置文件系统加载时是否自动检查并修复。CNend +* +* @par 描述: +* @li Set filesystem check and repair, default True. +CNcomment:设置文件系统加载时是否自动检查并修复,默认自动检查并修复。CNend +* +* @attention set before fs init.CNcomment:在文件系统初始化之前调用。CNend +* @param check [IN] type #hi_bool,whether check and repair when filesystem mount. +CNcomment:是否自动检查并修复。CNend +* +* @retval None +* @par 依赖: +* @li hi_fs.h:describes the filesystem APIs.CNcomment:文件用于描述文件系统相关接口。CNend +* @see hi_get_fs_check +*/ +hi_void hi_set_fs_check(hi_bool check); + +/** +* @ingroup iot_fs +* @brief Get filesystem check and repair.CNcomment:获取文件系统加载时是否自动检查并修复。CNend +* +* @par 描述: +* @li Get filesystem check and repair, default True. +CNcomment:获取文件系统加载时是否自动检查并修复,默认自动检查并修复。CNend +* +* @attention None +* @param None +* +* @retval #HI_TRUE auto check and repair when filesystem mount. +* @retval #HI_FALSE not check and repair when filesystem mount. +* @par 依赖: +* @li hi_fs.h:describes the filesystem APIs.CNcomment:文件用于描述文件系统相关接口。CNend +* @see hi_set_fs_check +*/ +hi_bool hi_get_fs_check(hi_void); + +/** +* @ingroup iot_fs +* @brief Initialize virtual filesystem.CNcomment:初始化虚拟文件系统。CNend +* +* @par 描述: +* @li Initialize virtual file system configuration related parameters. + CNcomment:初始化虚拟文件系统配置相关参数。CNend +* @li Mount partition to virtual file system work buffer.CNcomment:挂载分区到虚拟文件系统工作缓冲区。CNend +* +* @attention None +* @param None +* +* @retval None +* @par 依赖: +* @li hi_fs.h:describes the file system APIs.CNcomment:文件用于描述文件系统相关接口。CNend +* @see hi_fs_init +*/ +hi_void hi_fs_init(hi_void); + +/** +* @ingroup iot_fs +* @brief Open or create a file.CNcomment:打开或创建文件。 CNend +* +* @par 描述: +* Open or create a file.CNcomment:打开或创建指定的文件。CNend +* +* @attention The path length is less than 31 bytes, excluding the terminator. + Maximum support for opening 32 files at the same time. + +* @param path [IN] type #const hi_char*,file name CNcomment:要打开或创建的目标文件。CNend +* +* @param flags [IN] type #hi_u32,The flag combination is as follows: +* HI_FS_O_RDONLY:Open file as read-only.CNcomment:以只读的方式打开文件。CNend +* HI_FS_O_WRONLY:Open the file in write-only mode.CNcomment:以只写的方式打开文件。CNend +* HI_FS_O_RDWR:Open file in read-write mode.CNcomment:以读写的方式打开文件。CNend +* HI_FS_O_CREAT:If the file you want to open does not exist, the file will be created automatically. + CNcomment:如果要打开的文件不存在则自动建立该文件。CNend +* HI_FS_O_EXCL:If HI_FS_O_CREAT is also set, this command will check to see if the file exists. + If the file does not exist, create the file, otherwise it will cause a file error to open. + CNcomment:如果HI_FS_O_CREAT也被设置,此指令会去检查文件是否存在。 + 文件若不存在则建立该文件,否则将导致打开文件错误。CNend +* HI_FS_O_TRUNC:If the file exists and is opened in write mode, this flag will make the file length + clear to 0, and the data originally stored in the file will disappear. + CNcomment:若文件存在并且以可写的模式打开时,此标志会令文件长度清为0,而原来存于该文件的数据也会消失。CNend +* HI_FS_O_APPEND:When reading and writing a file, it will start moving from the end of the file, that is, + the written data will be added to the file in an additional way. + CNcomment:当读写文件时会从文件尾开始移动,也就是所写入的数据会以附加的方式加入到文件后面。CNend +* CNcomment:打开文件时,可以传入多个参数选项。CNend +* +* @retval #>0 Success. Return file descriptor +* @retval #-1 Failure. For details,Get error code by hi_get_fs_error. +* @par 依赖: +@li hi_fs.h:describes the filesystem APIs.CNcomment:文件用于描述文件系统相关接口。CNend +* @see hi_open +*/ +hi_s32 hi_open(const hi_char* path, hi_u32 flags); + +/** +* @ingroup iot_fs +* @brief Close an open file.CNcomment:关闭已经打开的文件。 CNend +* +* @par 描述: +* Close an open file.CNcomment:关闭一个已经打开的文件。CNend +* +* @attention None +* @param fd [IN] type #hi_s32,file descriptor CNcomment:需要关闭的文件描述符。CNend +* +* +* @retval #0 Success. +* @retval #-1 Failure. For details,Get error code by hi_get_fs_error. +* @par 依赖: +@li hi_fs.h:describes the filesystem APIs.CNcomment:文件用于描述文件系统相关接口。CNend +* @see hi_open +*/ +hi_s32 hi_close(hi_s32 fd); + +/** +* @ingroup iot_fs +* @brief Read file data of the specified size:从文件中,读取指定大小的文件数据。CNend +* +* @par 描述: +* Read file data of the specified size:从文件中,读取指定大小的文件数据。CNend +* +* @attention None +* @param fd [IN] type #hi_s32,file descriptor CNcomment:需要读文件的文件描述符。CNend +* @param buf [OUT] type #hi_char*,save read data buffer CNcomment:保存读数据缓冲区。CNend +* @param len [IN] type #hi_u32,The number of bytes requested to be read + CNcomment:需要读取数据的长度。CNend +* +* +* @retval #>=0 Success. Returns the number of bytes read, if it returns 0, it means that the end of the file + has been reached or there is no data to be read. + CNcomment:返回读取的字节数,如果返回0,表示已到达文件尾或无可读取的数据。CNend +* @retval #-1 Failure. For details,Get error code by hi_get_fs_error. +* @par 依赖: +@li hi_fs.h:describes the filesystem APIs.CNcomment:文件用于描述文件系统相关接口。CNend +* @see hi_open +*/ +hi_s32 hi_read(hi_s32 fd, hi_char* buf, hi_u32 len); + +/** +* @ingroup iot_fs +* @brief Write file data of the specified size:向文件中,写入指定大小的文件数据。CNend +* +* @par 描述: +* Write file data of the specified size:向文件中,写入指定大小的文件数据。CNend +* +* @attention None +* @param fd [IN] type #hi_s32,file descriptor CNcomment:需要写文件的文件描述符。CNend +* @param buf [IN] type #hi_char*,Store data that needs to be written to a file. + CNcomment:存放需要写入文件的数据。CNend +* @param len [IN] type #hi_u32,The number of bytes requested to be write CNcomment:需要写入数据的长度。CNend +* +* +* @retval #>=0 Success. Returns the number of bytes actually written, if it returns 0, it means nothing to do. + reached or there is no data to be read. + CNcomment:返回实际写入的字节数,如果返回0,表示什么也没有做。CNend +* @retval #-1 Failure. For details,Get error code by hi_get_fs_error. +* @par 依赖: +@li hi_fs.h:describes the filesystem APIs.CNcomment:文件用于描述文件系统相关接口。CNend +* @see hi_open +*/ +hi_s32 hi_write(hi_s32 fd, const hi_char* buf, hi_u32 len); + +/** +* @ingroup iot_fs +* @brief Delete a file.CNcomment:删除指定的文件。 CNend +* +* @par 描述: +* Delete a file.CNcomment:删除指定的文件。CNend +* +* @attention If the number of file descriptors currently open has reached the upper limit (32), +* then one of the file descriptors must be closed, otherwise the file will not be deleted. +* CNcomment:如果当前已经打开的文件描述符数已达上限(32个), +* 那么必须要关闭其中一个文件描述符,否则文件将不能被删除。CNend +* @attention The path length is less than 31 bytes, excluding the terminator. +* +* @param path [IN] type #const hi_char*,file name CNcomment:要删除的目标文件。CNend +* +* +* @retval #0 Success. +* @retval #-1 Failure. For details,Get error code by hi_get_fs_error. +* @par 依赖: +@li hi_fs.h:describes the filesystem APIs.CNcomment:文件用于描述文件系统相关接口。CNend +* @see hi_open +*/ +hi_s32 hi_unlink(const hi_char *path); + +/** +* @ingroup iot_fs +* @brief Relocate read/write file offsets.CNcomment:重新定位文件的读/写偏移量。 CNend +* +* @par 描述: +* Relocate read/write file offsets.CNcomment:重新定位文件的读/写偏移量。 CNend +* +* @attention whence is one of the following: + SEEK_SET Point the read and write position to the file header and then increase the offset amount. + CNcomment:将读写位置指向文件头后再增加offset个位移量。CNend + SEEK_CUR Increase the offset by the current read and write position. + CNcomment:以目前的读写位置往后增加offset个位移量。 CNend + SEEK_END Point the read and write position to the end of the file and then increase the offset amount, + only support offset values can only be negative. + CNcomment:将读写位置指向文件尾后再增加offset个位移量,只支持offset的值为负数。CNend + When the whennce value is SEEK_CUR or SEEK_END, the parameter offet allows + the occurrence of a negative value. + CNcomment:当whence 值为SEEK_CUR 或SEEK_END时,参数offet允许负值的出现。CNend + +* @param fd [IN] type #hi_s32,file descriptor CNcomment:需要重新定位读/写偏移量的文件描述符。CNend +* @param offs [IN] type #hi_s32,Move the number of displacements of the read/write position +* according to the parameter whence CNcomment:根据参数whence来移动读写位置的位移数。CNend +* @param whence [IN] type #hi_u32,Read / write file offset. CNcomment:读/写文件偏移。CNend +* +* @retval #>=0 Success. Returns the current read and write position, +* which is how many bytes from the beginning of the file +* @retval #-1 Failure. For details,Get error code by hi_get_fs_error. +* @par 依赖: +@li hi_fs.h:describes the filesystem APIs.CNcomment:文件用于描述文件系统相关接口。CNend +* @see hi_open +*/ +hi_s32 hi_lseek(hi_s32 fd, hi_s32 offs, hi_u32 whence); + +/** +* @ingroup iot_fs +* @brief Relocate Enumerate all files in the directory, the file system does not support multi-level directories. +* CNcomment:枚举目录下的所有文件,文件系统不支持多级目录。 CNend +* +* @par 描述: +* Relocate Enumerate all files in the directory, the file system does not support multi-level directories. +* CNcomment:枚举目录下的所有文件,文件系统不支持多级目录。CNend +* +* @attention +* +* @param buf [OUT] type #hi_char**,Buf stores information about all files and is released by the user. +* CNcomment:buf中存放所有文件的信息,由用户释放。CNend +* +* @retval #>=0 Success. +* @retval #-1 Failure. For details,Get error code by hi_get_fs_error. +* @par 依赖: +@li hi_fs.h:describes the filesystem APIs.CNcomment:文件用于描述文件系统相关接口。CNend +* @see hi_open +*/ +hi_s32 hi_enum_file(hi_char** buf); + +/** +* @ingroup iot_fs +* @brief Relocate Get file size. CNcomment:获取指定文件的大小。 CNend +* +* @par 描述: +* Relocate Get file size. CNcomment:获取指定文件的大小。CNend +* +* @attention +* +* @param file_name [IN] type #const hi_char*,file name CNcomment:文件名。CNend +* @param file_size [OUT] type #hi_u32*,file size. CNcomment:返回文件的大小。CNend +* +* @retval #>=0 Success. +* @retval #-1 Failure. For details,Get error code by hi_get_fs_error. +* @par 依赖: +@li hi_fs.h:describes the filesystem APIs.CNcomment:文件用于描述文件系统相关接口。CNend +* @see hi_open +*/ +hi_s32 hi_stat(const hi_char *file_name, hi_u32* file_size); +/** +* @ingroup iot_fs +* @brief Relocate Get file size. CNcomment:获取指定文件的大小。 CNend +* +* @par 描述: +* Relocate Get file size. CNcomment:获取指定文件的大小。CNend +* +* @attention +* +* @param fd [IN] type #hi_s32,file descriptor CNcomment:文件描述符。CNend +* @param file_size [OUT] type #hi_u32*,file size. CNcomment:返回文件的大小。CNend +* +* @retval #>=0 Success. +* @retval #-1 Failure. For details,Get error code by hi_get_fs_error. +* @par 依赖: +@li hi_fs.h:describes the filesystem APIs.CNcomment:文件用于描述文件系统相关接口。CNend +* @see hi_open +*/ +hi_s32 hi_fstat(hi_s32 fd, hi_u32 *file_size); +#endif + diff --git a/sdk_liteos/include/hi_gpio.h b/sdk_liteos/include/hi_gpio.h new file mode 100644 index 0000000000000000000000000000000000000000..fd7a9aab83f783ed2b5ad4d621d3d3d76d778145 --- /dev/null +++ b/sdk_liteos/include/hi_gpio.h @@ -0,0 +1,351 @@ +/** + * @file hi_gpio.h + * + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** +* @defgroup iot_gpio GPIO +* @ingroup drivers +*/ +#ifndef __HI_GPIO_H__ +#define __HI_GPIO_H__ + + +#include + +/** +* @ingroup iot_gpio +* +* GPIO ID. +*/ +typedef enum { + HI_GPIO_IDX_0, /**< GPIO0*/ + HI_GPIO_IDX_1, /**< GPIO1*/ + HI_GPIO_IDX_2, /**< GPIO2*/ + HI_GPIO_IDX_3, /**< GPIO3*/ + HI_GPIO_IDX_4, /**< GPIO4*/ + HI_GPIO_IDX_5, /**< GPIO5*/ + HI_GPIO_IDX_6, /**< GPIO6*/ + HI_GPIO_IDX_7, /**< GPIO7*/ + HI_GPIO_IDX_8, /**< GPIO8*/ + HI_GPIO_IDX_9, /**< GPIO9*/ + HI_GPIO_IDX_10, /**< GPIO10*/ + HI_GPIO_IDX_11, /**< GPIO11*/ + HI_GPIO_IDX_12, /**< GPIO12*/ + HI_GPIO_IDX_13, /**< GPIO13*/ + HI_GPIO_IDX_14, /**< GPIO14*/ + HI_GPIO_IDX_MAX, /**< Maximum value, which cannot be used.CNcomment:最大值,不可输入使用CNend*/ +} hi_gpio_idx; + + +/** +* @ingroup iot_gpio +* +* I/O level. CNcomment:GPIO电平状态。CNend +*/ +typedef enum { + HI_GPIO_VALUE0 = 0, /**< Low level.CNcomment:低电平CNend*/ + HI_GPIO_VALUE1 /**< High level.CNcomment:高电平CNend*/ +} hi_gpio_value; + +/** +* @ingroup iot_gpio +* +* I/O direction. CNcomment:GPIO方向。CNend +*/ +typedef enum { + HI_GPIO_DIR_IN = 0, /**< Input.CNcomment:输入方向CNend*/ + HI_GPIO_DIR_OUT /**< Output.CNcomment:输出方向CNend*/ +} hi_gpio_dir; + +/** +* @ingroup iot_gpio +* +* I/O interrupt trigger mode. This bit is used with HI_GPIO_INT_POLARITY. +CNcomment:GPIO中断触发方式,与hi_gpio_int_polarity配合使用。CNend +*/ +typedef enum { + HI_INT_TYPE_LEVEL = 0, /**< The interrupt is triggered in level-sensitive mode. CNcomment:电平触发中断CNend */ + HI_INT_TYPE_EDGE /**< Interrupt triggered at the rising edge or falling edge.CNcomment:边沿触发中断CNend */ +} hi_gpio_int_type; + +/** +* @ingroup iot_gpio +* +* I/O interrupt polarity. This pin is used with HI_GPIO_INT. +CNcomment:IO中断极性,与hi_gpio_int_type配合使用。CNend +*/ +typedef enum { + HI_GPIO_EDGE_FALL_LEVEL_LOW = 0, /**< Interrupt triggered at low level or falling edge. + CNcomment:低电平或下降沿触发中断CNend */ + HI_GPIO_EDGE_RISE_LEVEL_HIGH /**< Interrupt triggered at high level or rising edge. + CNcomment:高电平或上升沿触发中断CNend */ +} hi_gpio_int_polarity; + + +/** +* @ingroup iot_gpio +* @brief Callback function when GPIO interruption happens.CNcomment:GPIO中断回调函数。CNend +* +* @par 描述: +* Callback function when GPIO interruption happens.CNcomment:GPIO中断回调函数。CNend +* +* @attention None +* +* @param arg [IN] type #hi_void *,arg of interrupt callback function. CNcomment:中断回调函数入参。CNend +* +* @retval None +* @par 依赖: +* @li hi_gpio.h:Describes GPIO APIs.CNcomment:文件用于描述GPIO相关接口。CNend +* @see None +*/ +typedef hi_void (*gpio_isr_callback) (hi_void *arg); + +/** +* @ingroup iot_gpio +* @brief Initializes GPIO module.CNcomment:GPIO模块初始化。CNend +* +* @par 描述: +* Initializes GPIO module.CNcomment:GPIO模块初始化。CNend +* +* @attention +* @li This API needs to be invoked during initialization to enable the GPIO interrupt so that the I/O interrupt +* can be responded.CNcomment:需要在初始化阶段调用该接口使能GPIO中断,使得IO中断可以得到响应。CNend +* @li This interface cannot be invoked repeatedly. It can be invoked only once in the initialization phase. +CNcomment:该接口不支持重复调用,只能在初始化阶段调用一次。CNend +* +* @param None +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_gpio.h:Describes GPIO APIs.CNcomment:文件用于描述GPIO相关接口。CNend +* @see None +*/ +hi_u32 hi_gpio_init(hi_void); + +/** +* @ingroup iot_gpio +* @brief Deinitializes GPIO module. CNcomment:GPIO模块去初始化。CNend +* +* @par 描述: +* Deinitializes GPIO module. CNcomment:GPIO模块去初始化。CNend +* +* @attention +* @li This interface is used to disable the GPIO interrupt. After the GPIO interrupt is called, the GPIO interrupt +* cannot be responded.CNcomment:该接口功能为去使能GPIO中断,调用后GPIO中断将得不到响应。CNend +* +* @param None +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_gpio.h:Describes GPIO APIs.CNcomment:文件用于描述GPIO相关接口。CNend +* @see None +*/ +hi_u32 hi_gpio_deinit(hi_void); + +/** +* @ingroup iot_gpio +* @brief Sets the direction of a single I/O pin.CNcomment:设置某个GPIO管脚方向。CNend +* +* @par 描述: +* Sets the direction of a single I/O pin.CNcomment:设置某个GPIO管脚方向。CNend +* +* @attention None +* @param id [IN] type #hi_gpio_idx,I/O index.CNcomment:GPIO索引。CNend +* @param dir [IN] type #hi_gpio_dir,I/O direction.CNcomment:GPIO方向。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_gpio.h:Describes GPIO APIs.CNcomment:文件用于描述GPIO相关接口。CNend +* @see hi_gpio_get_dir +*/ +hi_u32 hi_gpio_set_dir(hi_gpio_idx id, hi_gpio_dir dir); + +/** +* @ingroup iot_gpio +* @brief Gets the direction of a single I/O pin.CNcomment:获取某个GPIO管脚方向。CNend +* +* @par 描述: +* Gets the direction of a single I/O pin.CNcomment:获取某个GPIO管脚方向。CNend +* +* @attention None +* @param id [IN] type #hi_gpio_idx,I/O index.CNcomment:GPIO索引。CNend +* @param dir [OUT] type #hi_gpio_dir*,I/O direction.CNcomment:GPIO方向。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_gpio.h:Describes GPIO APIs.CNcomment:文件用于描述GPIO相关接口。CNend +* @see hi_gpio_set_dir +*/ +hi_u32 hi_gpio_get_dir(hi_gpio_idx id, hi_gpio_dir *dir); + +/** +* @ingroup iot_gpio +* @brief Sets the output level of a single I/O pin.CNcomment:设置单个GPIO管脚输出电平状态。CNend +* +* @par 描述: +* Sets the output level of a single I/O pin.CNcomment:设置单个GPIO管脚输出电平状态。CNend +* +* @attention None +* +* @param id [IN] type #hi_gpio_idx,I/O index.CNcomment:GPIO索引。CNend +* @param val [IN] type #hi_gpio_value,output value. CNcomment:输出值。CNend +* @li 0:low level.CNcomment:低电平。CNend +* @li 1:high level.CNcomment:高电平。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_gpio.h:Describes GPIO APIs.CNcomment:文件用于描述GPIO相关接口。CNend +* @see hi_gpio_get_input_val。 +*/ +hi_u32 hi_gpio_set_ouput_val(hi_gpio_idx id, hi_gpio_value val); + +/** +* @ingroup iot_gpio +* @brief Obtains the output level of a single I/O pin.CNcomment:获取某个IO管脚输出电平状态。CNend +* +* @par 描述: +* Obtains the output level of a single I/O pin.CNcomment:获取某个IO管脚输出电平状态。CNend +* +* @attention None +* @param id [IN] type #hi_gpio_idx,I/O index.CNcomment:GPIO索引。CNend +* @param val [OUT] type #hi_gpio_value*,Output value.CNcomment:输出值。CNend +* @li 0:low level.CNcomment:低电平。CNend +* @li 1:high level.CNcomment:高电平。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_gpio.h:Describes GPIO APIs.CNcomment:文件用于描述GPIO相关接口。CNend +* @see hi_gpio_set_ouput_val。 +*/ +hi_u32 hi_gpio_get_output_val(hi_gpio_idx id, hi_gpio_value* val); + +/** +* @ingroup iot_gpio +* @brief Obtains the input level of a single I/O pin.CNcomment:获取某个IO管脚输入电平状态。CNend +* +* @par 描述: +* Obtains the input level of a single I/O pin.CNcomment:获取某个IO管脚输入电平状态。CNend +* +* @attention None +* @param id [IN] type #hi_gpio_idx,I/O index.CNcomment:GPIO索引。CNend +* @param val [OUT] type #hi_gpio_value*,Output value.CNcomment:输出值。CNend +* @li 0:low level.CNcomment:低电平。CNend +* @li 1:high level.CNcomment:高电平。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_gpio.h:Describes GPIO APIs.CNcomment:文件用于描述GPIO相关接口。CNend +* @see None +*/ +hi_u32 hi_gpio_get_input_val(hi_gpio_idx id, hi_gpio_value *val); + +/** +* @ingroup iot_gpio +* @brief Enable GPIO interruption.CNcomment:使能某个GPIO的中断功能。CNend +* +* @par 描述: +* Enable GPIO interruption.CNcomment:使能某个GPIO的中断功能。CNend +* +* @attention None +* @param id [IN] type #hi_gpio_idx,I/O index.CNcomment:GPIO索引。CNend +* @param int_type [IN] type #hi_gpio_int_type,Interruption type.CNcomment:中断类型。CNend +* @param int_polarity [IN] type #hi_gpio_int_polarity,Interruption polarity.CNcomment:中断极性。CNend +* @param func [IN] type #gpio_isr_callback_func,Callback function of interruption. +CNcomment:中断回调函数。CNend +* @param arg [IN] type #hi_void *,arg of interrupt callback function. CNcomment:中断回调函数入参。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_gpio.h:Describes GPIO APIs.CNcomment:文件用于描述GPIO相关接口。CNend +* @see hi_gpio_unregister_isr_function。 +*/ +hi_u32 hi_gpio_register_isr_function(hi_gpio_idx id, hi_gpio_int_type int_type, hi_gpio_int_polarity int_polarity, + gpio_isr_callback func, hi_void *arg); + +/** +* @ingroup iot_gpio +* @brief Disable GPIO interruption.CNcomment:去使能某个GPIO的中断功能。CNend +* +* @par 描述: +* Disable GPIO interruption.CNcomment:去使能某个GPIO的中断功能。CNend +* +* @attention None +* @param id [IN] type #hi_gpio_idx,I/O index.CNcomment:GPIO索引。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_gpio.h:Describes GPIO APIs.CNcomment:文件用于描述GPIO相关接口。CNend +* @see hi_gpio_register_isr_function。 +*/ +hi_u32 hi_gpio_unregister_isr_function(hi_gpio_idx id); + +/** +* @ingroup iot_gpio +* @brief Mask GPIO interruption.CNcomment:屏蔽某个GPIO的中断功能。CNend +* +* @par 描述: +* Mask GPIO interruption.CNcomment:屏蔽某个GPIO的中断功能。CNend +* +* @attention If this interface is called before hi_gpio_register_isr_function, the hi_gpio_register_isr_function +* interface will unmask the GPIO interruption. +* CNcomment:若此接口在hi_gpio_register_isr_function之前调用,hi_gpio_register_isr_function会将配置 +* 修改为不屏蔽GPIO中断。CNend +* @param id [IN] type #hi_gpio_idx,I/O index.CNcomment:GPIO索引。CNend +* @param is_mask [IN] type #hi_bool,Interruption type.CNcomment:中断类型。CNend +* @li HI_FALSE:Unmask I/O interruption.CNcomment:不屏蔽GPIO中断。CNend +* @li HI_TRUE: Mask I/O interruption.CNcomment:屏蔽GPIO中断。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_gpio.h:Describes GPIO APIs.CNcomment:文件用于描述GPIO相关接口。CNend +* @see None +*/ +hi_u32 hi_gpio_set_isr_mask(hi_gpio_idx id, hi_bool is_mask); + +/** +* @ingroup iot_gpio +* @brief Set GPIO interruption type and polarity.CNcomment:设置某个GPIO的中断触发方式。CNend +* +* @par 描述: +* Set GPIO interruption type and polarity.CNcomment:设置某个GPIO的中断触发方式。CNend +* +* @attention If this interface is called before hi_gpio_register_isr_function, hi_gpio_register_isr_function +* will overwrite the configurations. +* CNcomment:若此接口在hi_gpio_register_isr_function之前调用,hi_gpio_register_isr_function会覆盖 +* 本接口的配置。CNend +* @param id [IN] type #hi_gpio_idx,I/O index.CNcomment:GPIO索引。CNend +* @param int_type [IN] type #hi_gpio_int_type,Interruption type.CNcomment:中断类型。CNend +* @param int_polarity [IN] type #hi_gpio_int_polarity,Interruption polarity.CNcomment:中断极性。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_gpio.h:Describes GPIO APIs.CNcomment:文件用于描述GPIO相关接口。CNend +* @see None +*/ +hi_u32 hi_gpio_set_isr_mode(hi_gpio_idx id, hi_gpio_int_type int_type, hi_gpio_int_polarity int_polarity); + +#endif diff --git a/sdk_liteos/include/hi_hook_fuc.h b/sdk_liteos/include/hi_hook_fuc.h new file mode 100644 index 0000000000000000000000000000000000000000..3c9f362859ffabec105d8bebdfbf231ff783f56c --- /dev/null +++ b/sdk_liteos/include/hi_hook_fuc.h @@ -0,0 +1,216 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __HI_HOOK_FUC_H__ +#define __HI_HOOK_FUC_H__ + +#include +#include +#include +#include +#include + +#define fuc_type_name(name) pfn_##name##_hook + +typedef hi_u32 (*fuc_type_name(hi_task_create))(hi_u32 *taskid, + const hi_task_attr *attr, + hi_void* (*task_route)(hi_void *), + hi_void *arg); + +typedef hi_u32 (*fuc_type_name(hi_task_delete))(hi_u32 taskid); + +typedef hi_u32 (*fuc_type_name(hi_task_suspend))(hi_u32 taskid); + +typedef hi_u32 (*fuc_type_name(hi_task_resume))(hi_u32 taskid); + +typedef hi_u32 (*fuc_type_name(hi_task_get_priority))(hi_u32 taskid, + hi_u32 *priority); + +typedef hi_u32 (*fuc_type_name(hi_task_set_priority))(hi_u32 taskid, + hi_u32 priority); + +typedef hi_u32 (*fuc_type_name(hi_task_get_current_id))(hi_void); + +typedef hi_void (*fuc_type_name(hi_task_lock))(hi_void); + +typedef hi_void (*fuc_type_name(hi_task_unlock))(hi_void); + +typedef hi_u32 (*fuc_type_name(hi_sleep))(hi_u32 ms); + +typedef hi_u32 (*fuc_type_name(hi_event_create))(HI_OUT hi_u32 * id); + +typedef hi_u32 (*fuc_type_name(hi_event_init))(hi_u8 max_event_cnt, + hi_pvoid event_space); + +typedef hi_u32 (*fuc_type_name(hi_event_send))(hi_u32 id, + hi_u32 event_bits); + +typedef hi_u32 (*fuc_type_name(hi_event_wait))(hi_u32 id, + hi_u32 mask, + HI_OUT hi_u32 *event_bits, + hi_u32 timeout, + hi_u32 flag); + +typedef hi_u32 (*fuc_type_name(hi_event_clear))(hi_u32 id, + hi_u32 event_bits); + +typedef hi_u32 (*fuc_type_name(hi_event_delete))(hi_u32 id); + +typedef hi_pvoid (*fuc_type_name(hi_malloc))(hi_u32 mod_id, + hi_u32 size); + +typedef hi_void (*fuc_type_name(hi_free))(hi_u32 mod_id, + hi_pvoid addr); + +typedef hi_u32 (*fuc_type_name(hi_msg_queue_create))(HI_OUT hi_u32* id, + hi_u16 queue_len, + hi_u32 msg_size); + +typedef hi_u32 (*fuc_type_name(hi_msg_queue_wait))(hi_u32 id, + hi_pvoid msg, + hi_u32 timeout_ms, + hi_u32* msg_size); + +typedef hi_u32 (*fuc_type_name(hi_msg_queue_send))(hi_u32 id, + hi_pvoid msg, + hi_u32 timeout_ms, + hi_u32 msg_size); + +typedef hi_u32 (*fuc_type_name(hi_msg_queue_delete))(hi_u32 id); + + +typedef hi_u32 (*fuc_type_name(hi_mux_create))(hi_u32* mux_id); + +typedef hi_u32 (*fuc_type_name(hi_mux_delete))(hi_u32 mux_id); + +typedef hi_u32 (*fuc_type_name(hi_mux_pend))(hi_u32 mux_id, + hi_u32 timeout_ms); + +typedef hi_u32 (*fuc_type_name(hi_mux_post))(hi_u32 mux_id); + +typedef hi_u32 (*fuc_type_name(hi_sem_create))(hi_u32* sem_id, hi_u16 init_value); + +typedef hi_u32 (*fuc_type_name(hi_sem_bcreate))(hi_u32* sem_id, hi_u8 init_value); + +typedef hi_u32 (*fuc_type_name(hi_sem_delete))(hi_u32 sem_id); + +typedef hi_u32 (*fuc_type_name(hi_sem_wait))(hi_u32 sem_id, hi_u32 timeout); + +typedef hi_u32 (*fuc_type_name(hi_sem_signal))(hi_u32 sem_id); + + +typedef hi_u32 (*fuc_type_name(hi_get_tick))(hi_void); + +typedef hi_u64 (*fuc_type_name(hi_get_tick64))(hi_void); + +typedef hi_u32 (*fuc_type_name(hi_get_milli_seconds))(hi_void); + +typedef hi_u32 (*fuc_type_name(hi_get_seconds))(hi_void); + +typedef hi_u64 (*fuc_type_name(hi_get_us))(hi_void); + +typedef hi_u32 (*fuc_type_name(hi_get_real_time))(hi_void); + +typedef hi_u32 (*fuc_type_name(hi_set_real_time))(hi_u32 sec); + +typedef hi_u32 (*fuc_type_name(hi_timer_create))(hi_u32 *timer_handle); + +typedef hi_u32 (*fuc_type_name(hi_timer_start))(hi_u32 timer_handle, + hi_timer_type type, + hi_u32 expire, + hi_timer_callback_f timer_func, + hi_u32 data); + +typedef hi_u32 (*fuc_type_name(hi_timer_stop))(hi_u32 timer_handle); + +typedef hi_u32 (*fuc_type_name(hi_timer_delete))(hi_u32 timer_handle); + +typedef hi_u32 (*fuc_type_name(hi_irq_enable))(hi_u32 vector); + +typedef hi_void (*fuc_type_name(hi_irq_disable))(hi_u32 vector); + +typedef hi_u32 (*fuc_type_name(hi_irq_request))(hi_u32 vector, + hi_u32 flags, + irq_routine routine, + hi_u32 param); + +typedef hi_u32 (*fuc_type_name(hi_irq_free))(hi_u32 vector); + +typedef hi_bool (*fuc_type_name(hi_is_int_context))(hi_void); + +typedef struct { + /* task */ + fuc_type_name(hi_task_create) hi_task_create_hook; + fuc_type_name(hi_task_delete) hi_task_delete_hook; + fuc_type_name(hi_task_suspend) hi_task_suspend_hook; + fuc_type_name(hi_task_resume) hi_task_resume_hook; + fuc_type_name(hi_task_get_priority) hi_task_get_priority_hook; + fuc_type_name(hi_task_set_priority) hi_task_set_priority_hook; + fuc_type_name(hi_task_get_current_id) hi_task_get_current_id_hook; + fuc_type_name(hi_task_lock) hi_task_lock_hook; + fuc_type_name(hi_task_unlock) hi_task_unlock_hook; + fuc_type_name(hi_sleep) hi_sleep_hook; + /* event */ + fuc_type_name(hi_event_create) hi_event_create_hook; + fuc_type_name(hi_event_init) hi_event_init_hook; + fuc_type_name(hi_event_send) hi_event_send_hook; + fuc_type_name(hi_event_wait) hi_event_wait_hook; + fuc_type_name(hi_event_clear) hi_event_clear_hook; + fuc_type_name(hi_event_delete) hi_event_delete_hook; + /* memory */ + fuc_type_name(hi_malloc) hi_malloc_hook; + fuc_type_name(hi_free) hi_free_hook; + /* queue */ + fuc_type_name(hi_msg_queue_create) hi_msg_queue_create_hook; + fuc_type_name(hi_msg_queue_send) hi_msg_queue_send_hook; + fuc_type_name(hi_msg_queue_wait) hi_msg_queue_wait_hook; + fuc_type_name(hi_msg_queue_delete) hi_msg_queue_delete_hook; + /* mux */ + fuc_type_name(hi_mux_create) hi_mux_create_hook; + fuc_type_name(hi_mux_delete) hi_mux_delete_hook; + fuc_type_name(hi_mux_pend) hi_mux_pend_hook; + fuc_type_name(hi_mux_post) hi_mux_post_hook; + /* semaphore */ + fuc_type_name(hi_sem_create) hi_sem_create_hook; + fuc_type_name(hi_sem_bcreate) hi_sem_bcreate_hook; + fuc_type_name(hi_sem_delete) hi_sem_delete_hook; + fuc_type_name(hi_sem_wait) hi_sem_wait_hook; + fuc_type_name(hi_sem_signal) hi_sem_signal_hook; + /* time */ + fuc_type_name(hi_get_tick) hi_get_tick_hook; + fuc_type_name(hi_get_tick64) hi_get_tick64_hook; + fuc_type_name(hi_get_milli_seconds) hi_get_milli_seconds_hook; + fuc_type_name(hi_get_seconds) hi_get_seconds_hook; + fuc_type_name(hi_get_us) hi_get_us_hook; + fuc_type_name(hi_get_real_time) hi_get_real_time_hook; + fuc_type_name(hi_set_real_time) hi_set_real_time_hook; + /* timer */ + fuc_type_name(hi_timer_create) hi_timer_create_hook; + fuc_type_name(hi_timer_start) hi_timer_start_hook; + fuc_type_name(hi_timer_stop) hi_timer_stop_hook; + fuc_type_name(hi_timer_delete) hi_timer_delete_hook; + /* interrupt */ + fuc_type_name(hi_irq_enable) hi_irq_enable_hook; + fuc_type_name(hi_irq_disable) hi_irq_disable_hook; + fuc_type_name(hi_irq_request) hi_irq_request_hook; + fuc_type_name(hi_irq_free) hi_irq_free_hook; + fuc_type_name(hi_is_int_context) hi_is_int_context_hook; +} hi_hook_osa; + +HI_EXTERN hi_hook_osa g_hook_osa; + +HI_EXTERN hi_u32 hi_init_hook_osa(const hi_hook_osa *osa); + +#endif diff --git a/sdk_liteos/include/hi_hrtimer.h b/sdk_liteos/include/hi_hrtimer.h new file mode 100644 index 0000000000000000000000000000000000000000..e4574d99ce8fbeaea248739aa6f02f7c62612137 --- /dev/null +++ b/sdk_liteos/include/hi_hrtimer.h @@ -0,0 +1,145 @@ +/** +* @file hi_hrtimer.h +* +* Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. \n +* +* Description: 1、In scenarios where the precision is not high, do not use hrtimer. Instead, use a system timer, +* because each hrtimer startup, stop, and expiration may increase the error of other high-precision +* timers in the queue. CNcomment:在精度要求不高的场景下,尽可能不要使用hrtimer, +* 应使用系统定时器替代,因为每次hrtimer的启动、停止、到期都可能会增加队列中其它 +* 高精度定时器的误差;CNend +* 2、The callback function of hrtimer is executed in the interrupt context, so you need to comply with +* the programming precautions for the interrupt context.CNcomment:hrtimer的回调函数执行在中断上下文, +* 因此需要遵守中断上下文的编程注意事项。CNend \n +*/ + +/** + * @defgroup hrtimer High Resolution Timer + * @ingroup drivers + */ +#ifndef __HI_HRTIMER_H__ +#define __HI_HRTIMER_H__ +#include + +/** +* @ingroup hrtimer +* @brief High resolution timer callback function.CNcomment:高精度定时器回调函数。CNend +* +* @par 描述: +* High resolution timer callback function. When a high resolution timer expires, the high resolution timer +* module calls this function to notify the user.CNcomment:高精度定时器回调函数,当高精度定时器到期时, +* 高精度定时器模块调用该函数通知使用者。CNend +* +* @attention None +* @param data [IN] type #hi_u32,Callback function parameter input when the user starts the timer. +CNcomment:用户启动定时器时传入的回调函数参数。CNend +* +* @retval None +* @par 依赖: +* @li hi_hrtimer.h:Describes timer APIs.CNcomment:文件用于描述定时器相关接口。CNend +* @see None +*/ +typedef hi_void(*hi_hrtimer_callback_f) (hi_u32 data); + +/** +* @ingroup hrtimer +* @brief Obtains the high resolution timer module handler.CNcomment:获取高精定时器句柄。CNend +* +* @par 描述: +* Obtains the high resolution timer module handler.CNcomment:获取高精定时器句柄。CNend +* +* @attention None +* @param timer_handle [OUT] type #hi_u32*,handler obtained. CNcomment:获取到的句柄。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h +* +* @par 依赖: +* @li hi_hrtimer.h:Describes timer APIs.CNcomment:文件用于描述定时器相关接口。CNend +* +* @see hi_hrtimer_delete。 +*/ +hi_u32 hi_hrtimer_create(hi_u32 *timer_handle); + +/** +* @ingroup hrtimer +* @brief Delete the high resolution timer module handle.CNcomment:删除高精定时器句柄。CNend +* +* @par 描述: +* Delete the high resolution timer module handle.CNcomment:删除高精定时器句柄。CNend +* +* @attention None +* @param timer_handle [IN] type #hi_u32,Timer handle, which would be released. +CNcomment:要释放的定时器句柄。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h +* +* @par 依赖: +* @li hi_hrtimer.h:Describes timer APIs.CNcomment:文件用于描述定时器相关接口。CNend +* +* @see hi_hrtimer_create。 +*/ +hi_u32 hi_hrtimer_delete(hi_u32 timer_handle); +/** +* @ingroup hrtimer +* @brief Starts a high resolution timer.CNcomment:启动高精度定时器。CNend +* +* @par 描述: +* Starts the high resolution timer. If the timer has been started, the current timer is stopped and +* restarted when this API is called.CNcomment:调用该接口启动高精度定时器,如果定时器已经启动, +调用该接口时会停止当前定时器重新启动。CNend +* +* @attention None +* @param timer_handle [IN] type #hi_u32,Timer handle.CNcomment:定时器句柄。CNend +* @param expire [IN] type #hi_u32,Expiration time of the timer (unit: microsecond).When the clock is set to +24M,the maximum of the expiration time is 178s.When the clock is set to 40M,the maximum of the expiration time is 107s. +The expiration time of the timer must be set to a value smaller than the maximum. +CNcomment:定时器超时时间(单位:μs)。24M时钟可设置的最大超时时间为178s,40M时钟可设置的最大超时时间为107s。 + 超时时间必须设置为小于最大超时时间的值。CNend +* @param hrtimer_func [IN] type #hi_hrtimer_callback_f,Callback function when the timer expires. +CNcomment:定时器到期回调函数。CNend +* @param data [IN] type #hi_u32,Input parameter of the timer callback function. +CNcomment:定时器回调函数的入参。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h +* +* @par 依赖: +* @li hi_hrtimer.h:Describes timer APIs.CNcomment:文件用于描述定时器相关接口。CNend +* @see hi_hrtimer_stop。 +*/ +hi_u32 hi_hrtimer_start(hi_u32 timer_handle, hi_u32 expire, hi_hrtimer_callback_f hrtimer_func, hi_u32 data); + +/** +* @ingroup hrtimer +* @brief Stops a high resolution timer.CNcomment:停止高精度定时器。CNend +* +* @par 描述: +* Stops a high resolution timer. If the timer is stopped when the API is called, no effect is achieved. +CNcomment:调用该接口停止高精度定时器,如果调用该接口时定时器已经停止,不会有任何效果。CNend +* +* @attention None +* @param timer_handle [IN] type #hi_u32,Timer handle.CNcomment:定时器handle。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h +* +* @par 依赖: +* @li hi_hrtimer.h:Describes timer APIs.CNcomment:文件用于描述定时器相关接口。CNend +* @see hi_hrtimer_start。 +*/ +hi_u32 hi_hrtimer_stop(hi_u32 timer_handle); + +#endif diff --git a/sdk_liteos/include/hi_i2c.h b/sdk_liteos/include/hi_i2c.h new file mode 100644 index 0000000000000000000000000000000000000000..45f40ae19968b4783209eed6bf290bf881c3bddb --- /dev/null +++ b/sdk_liteos/include/hi_i2c.h @@ -0,0 +1,223 @@ +/** + * @file hi_i2c.h + * + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** @defgroup iot_i2c I2C + * @ingroup drivers + */ +#ifndef __HI_I2C_H__ +#define __HI_I2C_H__ + +#include + +/* + * I2C Interface + */ +#define I2C_RATE_DEFAULT 100000 + +typedef hi_void (*i2c_reset_func)(hi_void); +typedef hi_void (*i2c_prepare_func)(hi_void); +typedef hi_void (*i2c_restore_func)(hi_void); + +/** + * @ingroup iot_i2c + * + * I2C callback function. CNcomment:I2C回调函数。CNend + */ +typedef struct { + i2c_reset_func reset_func; /**< This function is called back when the communication with the slave device + is abnormal.CNcomment:I2C从异常处理函数CNend */ + i2c_prepare_func prepare_func; /**< This function is called back before the I2C read/write operation to implement + the preparations before the I2C operation. + CNcomment:I2C操作前准备函数CNend */ + i2c_restore_func restore_func; /**< After the I2C read/write operation is performed, this function is + called back to implement the recovery after the I2C operation. + CNcomment:I2C操作后恢复函数CNend */ +} hi_i2c_func; + +/** + * @ingroup iot_i2c + * + * I2C TX/RX data descriptor. CNcomment:I2C发送/接收数据描述符。CNend + */ +typedef struct { + hi_u8* send_buf; /**< Data TX pointer. The user needs to ensure that no null pointer is transferred. + CNcomment:数据发送指针CNend */ + hi_u32 send_len; /**< Length of sent data (unit: byte). + CNcomment:发送数据长度(单位:byte)CNend */ + hi_u8* receive_buf; /**< Data RX pointer. CNcomment:数据接收指针CNend */ + hi_u32 receive_len; /**< Length of received data (unit: byte). + CNcomment:接收数据长度(单位:byte)CNend */ +} hi_i2c_data; + +/** + * @ingroup iot_i2c + * + * I2C hardware index. CNComment:I2C硬件设备枚举。CNend + */ +typedef enum { + HI_I2C_IDX_0, + HI_I2C_IDX_1, +} hi_i2c_idx; + +/** +* @ingroup iot_i2c +* @brief Set I2C baudrate. CNcomment:I2C设置波特率。CNend +* +* @par 描述: +* Set I2C baudrate. CNcomment:I2C设置波特率。CNend +* +* @attention Multiple tasks are not protected (multiple tasks are not supported). CNcomment:未作 +多任务保护(不支持多任务)。CNend +* @param id [IN] type #hi_i2c_idx,I2C hardware selection. CNcomment:I2C硬件设备选择。CNend +* @param baudrate [IN] type #hi_u32,I2C baudrate. CNcomment:I2C波特率。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_i2c.h:Declares the API.CNcomment:该接口声明所在的头文件。CNend +* @see hi_i2c_write|hi_i2c_receive。 +*/ +hi_u32 hi_i2c_set_baudrate(hi_i2c_idx id, hi_u32 baudrate); + +/** +* @ingroup iot_i2c +* @brief I2C data TX and RX.CNcomment:I2C发送与接收数据。CNend +* +* @par 描述: +* The I2C sends data to the slave device and then receives data from the slave device. +CNcomment:I2C向从机发送数据,然后接收从机数据。CNend +* +* @attention Multi-tasking is not supported. CNcomment:未作多任务保护(不支持多任务)。CNend +* @param id [IN] type #hi_i2c_idx,I2C hardware selection. CNcomment:I2C硬件设备选择。CNend +* @param device_addr [IN] type #hi_u16,The device ID. High three bits of offset address of the I2C device on chipset. +CNcomment:设备号及设备片内偏移地址高3位(从设备哪个地方开始读)。CNend +* @param i2c_data [IN/OUT] type #const hi_i2c_data*,The data descriptor to be received. +* The structure member data sending pointer and data receiving pointer cannot be null. +CNcomment:待接收数据描述符,结构体成员数据发送指针和数据接收指针都不为空。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_i2c.h:Declares the API.CNcomment:该接口声明所在的头文件。CNend +* @see hi_i2c_write|hi_i2c_receive。 +*/ +hi_u32 hi_i2c_writeread(hi_i2c_idx id, hi_u16 device_addr, const hi_i2c_data *i2c_data); + +/** +* @ingroup iot_i2c +* @brief I2C data TX. CNcomment:I2C发送数据。CNend +* +* @par 描述: +* I2C data TX. CNcomment:I2C发送数据。CNend +* +* @attention Multiple tasks are not protected (multiple tasks are not supported). CNcomment:未作 +多任务保护(不支持多任务)。CNend +* @param id [IN] type #hi_i2c_idx,I2C hardware selection. CNcomment:I2C硬件设备选择。CNend +* @param device_addr [IN] type #hi_u16,The device ID. High three bits of offset address of the I2C device on chipset. +CNcomment:设备号及设备片内偏移地址高3位(从设备哪个地方开始读)。CNend +* @param i2c_data [IN] type #const hi_i2c_data*,The data descriptor to be received. The structure member data sending +* pointer and data receiving pointer cannot be null. +CNcomment:待接收数据描述符,结构体成员数据发送指针和数据接收指针都不为空。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_i2c.h:Declares the API.CNcomment:该接口声明所在的头文件。CNend +* @see hi_i2c_writeread|hi_i2c_receive。 +*/ +hi_u32 hi_i2c_write(hi_i2c_idx id, hi_u16 device_addr, const hi_i2c_data *i2c_data); + +/** +* @ingroup iot_i2c +* @brief I2C data RX. CNcomment:I2C接收数据。CNend +* +* @par 描述: +* I2C data RX. CNcomment:I2C接收数据。CNend +* +* @attention Multi-tasking is not supported. CNcomment:未作多任务保护(不支持多任务)。CNend +* @param id [IN] type #hi_i2c_idx,I2C hardware selection. CNcomment:I2C硬件设备选择。CNend +* @param device_addr [IN] type #hi_u16,The device ID. High three bits of offset address of the I2C device on chipset. +CNcomment:设备号及设备片内偏移地址高3位(从设备哪个地方开始读)。CNend +* @param i2c_data [OUT] type #const hi_i2c_data*,The data descriptor to be received. The structure member data sending +* pointer and data receiving pointer cannot be null. +CNcomment:待接收数据描述符,结构体成员数据发送指针和数据接收指针都不为空。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_i2c.h:Declares the API.CNcomment:该接口声明所在的头文件。CNend +* @see hi_i2c_write|hi_i2c_sendreceive。 +*/ +hi_u32 hi_i2c_read(hi_i2c_idx id, hi_u16 device_addr, const hi_i2c_data *i2c_data); + +/** +* @ingroup iot_i2c +* @brief Initializes the I2C controller. CNcomment:I2C初始化。CNend +* +* @par 描述: +* Initializes the I2C controller. CNcomment:I2C初始化。CNend +* +* @attention None +* @param id [IN] type #hi_i2c_idx,I2C hardware selection. CNcomment:I2C硬件设备选择。CNend +* @param baudrate [IN] type #hi_u32,I2C baudrate. CNcomment:I2C波特率。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_i2c.h:Declares the API.CNcomment:该接口声明所在的头文件。CNend +* @see hi_i2c_deinit。 +*/ +hi_u32 hi_i2c_init(hi_i2c_idx id, hi_u32 baudrate); + +/** +* @ingroup iot_i2c +* @brief Exits the I2C module.CNcomment:退出I2C模块。CNend +* +* @par 描述: +* Exits the I2C module. CNcomment:退出I2C模块。CNend +* +* @attention This API is called after hi_i2c_init is called. CNcomment:hi_i2c_init调用后再使用。CNend +* @param id [IN] type #hi_i2c_idx,I2C hardware selection. CNcomment:I2C硬件设备选择。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_i2c.h:Declares the API.CNcomment:该接口声明所在的头文件。CNend +* @see hi_i2c_init。 +*/ +hi_u32 hi_i2c_deinit(hi_i2c_idx id); + +/** +* @ingroup iot_i2c +* @brief Registers the I2C callback function.CNcomment:注册I2C回调函数。CNend +* +* @par 描述: +* Registers the I2C callback function, for extension.CNcomment:注册I2C回调函数,用于扩展。CNend +* +* @attention None +* @param id [IN] type #hi_i2c_idx,I2C hardware selection. CNcomment:I2C硬件设备选择。CNend +* @param pfn [IN] type #hi_i2c_func,Callback function. CNcomment:回调函数。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_i2c.h:Declares the API.CNcomment:该接口声明所在的头文件。CNend +* @see None +*/ +hi_void hi_i2c_register_reset_bus_func(hi_i2c_idx id, hi_i2c_func pfn); + +#endif diff --git a/sdk_liteos/include/hi_i2s.h b/sdk_liteos/include/hi_i2s.h new file mode 100644 index 0000000000000000000000000000000000000000..602b43108b4208ac6098090f7e512d1568fefe9e --- /dev/null +++ b/sdk_liteos/include/hi_i2s.h @@ -0,0 +1,140 @@ +/** + * @file hi_i2s.h + * + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @defgroup iot_i2s I2S + * @ingroup drivers + */ +#ifndef __HI_I2S_H__ +#define __HI_I2S_H__ + +/** +* @ingroup iot_i2s +* +* sample rate. +*/ +typedef enum { + HI_I2S_SAMPLE_RATE_8K = 8, + HI_I2S_SAMPLE_RATE_16K = 16, + HI_I2S_SAMPLE_RATE_32K = 32, + HI_I2S_SAMPLE_RATE_48K = 48, +} hi_i2s_sample_rate; + +/** +* @ingroup iot_i2s +* +* resolution. +*/ +typedef enum { + HI_I2S_RESOLUTION_16BIT = 16, + HI_I2S_RESOLUTION_24BIT = 24, +} hi_i2s_resolution; + +/** +* @ingroup iot_i2s +* +* I2S attributes. +*/ +typedef struct { + hi_i2s_sample_rate sample_rate; /**< i2s sample rate, type hi_i2s_sample_rate.CNcomment:采样率,类型为 + hi_i2s_sample_rate。CNend */ + hi_i2s_resolution resolution; /**< i2s resolution, type hi_i2s_resolution.CNcomment:解析度,类型为 + hi_i2s_resolution。CNend */ +} hi_i2s_attribute; + +/** +* @ingroup iot_i2s +* @brief I2S initialization. CNcomment:I2S初始化。CNend +* +* @par 描述: +* Set I2S with configuration. CNcomment:根据参数配置I2S。CNend +* +* @attention Should init DMA driver before using I2S. CNcomment:使用I2S驱动前,需要初始化DMA驱动。CNend +* +* @param i2s_attribute [IN] type #hi_i2s_attribute*,I2S configuration parameter. CNcomment:I2S配置参数。CNend +* +* @retval #HI_ERR_SUCCESS Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_i2s.h:Describes I2S APIs.CNcomment:I2S相关接口。CNend +* @see hi_i2s_deinit。 +*/ +hi_u32 hi_i2s_init(const hi_i2s_attribute *i2s_attribute); + +/** +* @ingroup iot_i2s +* @brief Deinitializes I2S.CNcomment:去初始化I2S。CNend +* +* @par 描述: +* Deinitializes I2S.CNcomment:去初始化I2S。CNend +* +* @attention This API is used together with hi_i2s_init.CNcomment:与hi_i2s_init成对使用。CNend +* @param None +* +* @retval #HI_ERR_SUCCESS Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_i2s.h:Describes I2S APIs.CNcomment:I2S相关接口。CNend +* @see hi_i2s_deinit。 +*/ +hi_u32 hi_i2s_deinit(hi_void); + +/** +* @ingroup iot_i2s +* @brief TX interface for the I2S.CNcomment:I2S发送接口。CNend +* +* @par 描述: +* TX interface for the I2S.CNcomment:I2S发送接口。CNend +* +* @attention None +* +* @param wr_data [OUT] type #hi_u8*,TX data pointer.CNcomment:接收数据指针。CNend +* @param wr_len [IN] type #hi_u32,length of the target data to be send (unit: byte). +CNcomment:发送数据长度(单位:byte)。CNend +* @param time_out_ms [IN] type #hi_u32,wait timeout period.CNcomment:超时时间。CNend +* +* @retval #HI_ERR_SUCCESS Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_i2s.h:Describes I2S APIs.CNcomment:I2S相关接口。CNend +* @see hi_i2s_read。 +*/ +hi_u32 hi_i2s_write(hi_u8 *wr_data, hi_u32 wr_len, hi_u32 time_out_ms); + +/** +* @ingroup iot_i2s +* @brief Read interface for the I2S.CNcomment:I2S接收接口。CNend +* +* @par 描述: +* Read interface for the I2S.CNcomment:I2S接收接口。CNend +* +* @attention None +* +* @param rd_data [OUT] type #hi_u8*,RX data pointer.CNcomment:接收数据指针。CNend +* @param rd_len [IN] type #hi_u32,length of the target data to be received (unit: byte). +CNcomment:接收数据长度(单位:byte)。CNend +* @param time_out_ms [IN] type #hi_u32,wait timeout period.CNcomment:超时时间。CNend +* +* @retval #HI_ERR_SUCCESS Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_i2s.h:Describes I2S APIs.CNcomment:I2S相关接口。CNend +* @see hi_i2s_write。 +*/ +hi_u32 hi_i2s_read(hi_u8 *rd_data, hi_u32 rd_len, hi_u32 time_out_ms); + +#endif diff --git a/sdk_liteos/include/hi_io.h b/sdk_liteos/include/hi_io.h new file mode 100644 index 0000000000000000000000000000000000000000..402d75d2d9c4af4042b71e093d81cc993985fcd6 --- /dev/null +++ b/sdk_liteos/include/hi_io.h @@ -0,0 +1,606 @@ +/** + * @file hi_io.h + * + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @defgroup iot_io IO + * @ingroup drivers + */ + +#ifndef __HI_IO_H__ +#define __HI_IO_H__ + +#include + +/** + * @ingroup iot_io + * + * GPIO pin ID. CNcomment:IO硬件管脚编号。CNend + */ +typedef enum { + HI_IO_NAME_GPIO_0, /**< GPIO0 */ + HI_IO_NAME_GPIO_1, /**< GPIO1 */ + HI_IO_NAME_GPIO_2, /**< GPIO2 */ + HI_IO_NAME_GPIO_3, /**< GPIO3 */ + HI_IO_NAME_GPIO_4, /**< GPIO4 */ + HI_IO_NAME_GPIO_5, /**< GPIO5 */ + HI_IO_NAME_GPIO_6, /**< GPIO6 */ + HI_IO_NAME_GPIO_7, /**< GPIO7 */ + HI_IO_NAME_GPIO_8, /**< GPIO8 */ + HI_IO_NAME_GPIO_9, /**< GPIO9 */ + HI_IO_NAME_GPIO_10, /**< GPIO10 */ + HI_IO_NAME_GPIO_11, /**< GPIO11 */ + HI_IO_NAME_GPIO_12, /**< GPIO12 */ + HI_IO_NAME_GPIO_13, /**< GPIO13 */ + HI_IO_NAME_GPIO_14, /**< GPIO14 */ + HI_IO_NAME_SFC_CSN, /**< SFC_CSN */ + HI_IO_NAME_SFC_IO1, /**< SFC_IO1 */ + HI_IO_NAME_SFC_IO2, /**< SFC_IO2 */ + HI_IO_NAME_SFC_IO0, /**< SFC_IO0 */ + HI_IO_NAME_SFC_CLK, /**< SFC_CLK */ + HI_IO_NAME_SFC_IO3, /**< SFC_IO3 */ + HI_IO_NAME_MAX, +} hi_io_name; + +/** + * @ingroup iot_io + * + * GPIO_0 pin function.CNcomment:GPIO_0管脚功能。CNend + */ +typedef enum { + HI_IO_FUNC_GPIO_0_GPIO, + HI_IO_FUNC_GPIO_0_UART1_TXD = 2, + HI_IO_FUNC_GPIO_0_SPI1_CK, + HI_IO_FUNC_GPIO_0_JTAG_TDO, + HI_IO_FUNC_GPIO_0_PWM3_OUT, + HI_IO_FUNC_GPIO_0_I2C1_SDA, +} hi_io_func_gpio_0; + +/** +* @ingroup iot_io +* +* GPIO_1 pin function.CNcomment:GPIO_1管脚功能。CNend +*/ +typedef enum { + HI_IO_FUNC_GPIO_1_GPIO, + HI_IO_FUNC_GPIO_1_UART1_RXD = 2, + HI_IO_FUNC_GPIO_1_SPI1_RXD, + HI_IO_FUNC_GPIO_1_JTAG_TCK, + HI_IO_FUNC_GPIO_1_PWM4_OUT, + HI_IO_FUNC_GPIO_1_I2C1_SCL, + HI_IO_FUNC_GPIO_1_BT_FREQ, +} hi_io_func_gpio_1; + +/** +* @ingroup iot_io +* +* GPIO_2 pin function.CNcomment:GPIO_2管脚功能。CNend +*/ +typedef enum { + HI_IO_FUNC_GPIO_2_GPIO, + HI_IO_FUNC_GPIO_2_UART1_RTS_N = 2, + HI_IO_FUNC_GPIO_2_SPI1_TXD, + HI_IO_FUNC_GPIO_2_JTAG_TRSTN, + HI_IO_FUNC_GPIO_2_PWM2_OUT, + HI_IO_FUNC_GPIO_2_SSI_CLK = 7, +} hi_io_func_gpio_2; + +/** +* @ingroup iot_io +* +* GPIO_3 pin function.CNcomment:GPIO_3管脚功能。CNend +*/ +typedef enum { + HI_IO_FUNC_GPIO_3_GPIO, + HI_IO_FUNC_GPIO_3_UART0_TXD, + HI_IO_FUNC_GPIO_3_UART1_CTS_N, + HI_IO_FUNC_GPIO_3_SPI1_CSN, + HI_IO_FUNC_GPIO_3_JTAG_TDI, + HI_IO_FUNC_GPIO_3_PWM5_OUT, + HI_IO_FUNC_GPIO_3_I2C1_SDA, + HI_IO_FUNC_GPIO_3_SSI_DATA, +} hi_io_func_gpio_3; + +/** +* @ingroup iot_io +* +* GPIO_4 pin function.CNcomment:GPIO_4管脚功能。CNend +*/ +typedef enum { + HI_IO_FUNC_GPIO_4_GPIO, + HI_IO_FUNC_GPIO_4_UART0_RXD = 2, + HI_IO_FUNC_GPIO_4_JTAG_TMS = 4, + HI_IO_FUNC_GPIO_4_PWM1_OUT, + HI_IO_FUNC_GPIO_4_I2C1_SCL, +} hi_io_func_gpio_4; + +/** +* @ingroup iot_io +* +* GPIO_5 pin function.CNcomment:GPIO_5管脚功能。CNend +*/ +typedef enum { + HI_IO_FUNC_GPIO_5_GPIO, + HI_IO_FUNC_GPIO_5_UART1_RXD = 2, + HI_IO_FUNC_GPIO_5_SPI0_CSN, + HI_IO_FUNC_GPIO_5_PWM2_OUT = 5, + HI_IO_FUNC_GPIO_5_I2S0_MCLK, + HI_IO_FUNC_GPIO_5_BT_STATUS, +} hi_io_func_gpio_5; + +/** +* @ingroup iot_io +* +* GPIO_6 pin function.CNcomment:GPIO_6管脚功能。CNend +*/ +typedef enum { + HI_IO_FUNC_GPIO_6_GPIO, + HI_IO_FUNC_GPIO_6_UART1_TXD = 2, + HI_IO_FUNC_GPIO_6_SPI0_CK, + HI_IO_FUNC_GPIO_6_PWM3_OUT = 5, + HI_IO_FUNC_GPIO_6_I2S0_TX, + HI_IO_FUNC_GPIO_6_COEX_SWITCH, +} hi_io_func_gpio_6; + +/** +* @ingroup iot_io +* +* GPIO_7 pin function.CNcomment:GPIO_7管脚功能。CNend +*/ +typedef enum { + HI_IO_FUNC_GPIO_7_GPIO, + HI_IO_FUNC_GPIO_7_UART1_CTS_N = 2, + HI_IO_FUNC_GPIO_7_SPI0_RXD, + HI_IO_FUNC_GPIO_7_PWM0_OUT = 5, + HI_IO_FUNC_GPIO_7_I2S0_BCLK, + HI_IO_FUNC_GPIO_7_BT_ACTIVE, +} hi_io_func_gpio_7; + +/** +* @ingroup iot_io +* +* GPIO_8 pin function.CNcomment:GPIO_8管脚功能。CNend +*/ +typedef enum { + HI_IO_FUNC_GPIO_8_GPIO, + HI_IO_FUNC_GPIO_8_UART1_RTS_N = 2, + HI_IO_FUNC_GPIO_8_SPI0_TXD, + HI_IO_FUNC_GPIO_8_PWM1_OUT = 5, + HI_IO_FUNC_GPIO_8_I2S0_WS, + HI_IO_FUNC_GPIO_8_WLAN_ACTIVE, +} hi_io_func_gpio_8; + +/** +* @ingroup iot_io +* +* GPIO_9 pin function.CNcomment:GPIO_9管脚功能。CNend +*/ +typedef enum { + HI_IO_FUNC_GPIO_9_GPIO, + HI_IO_FUNC_GPIO_9_I2C0_SCL, + HI_IO_FUNC_GPIO_9_UART2_RTS_N, + HI_IO_FUNC_GPIO_9_SDIO_D2, + HI_IO_FUNC_GPIO_9_SPI0_TXD, + HI_IO_FUNC_GPIO_9_PWM0_OUT, + HI_IO_FUNC_GPIO_9_I2S0_MCLK = 7, +} hi_io_func_gpio_9; + +/** +* @ingroup iot_io +* +* GPIO_10 pin function.CNcomment:GPIO_10管脚功能。CNend +*/ +typedef enum { + HI_IO_FUNC_GPIO_10_GPIO, + HI_IO_FUNC_GPIO_10_I2C0_SDA, + HI_IO_FUNC_GPIO_10_UART2_CTS_N, + HI_IO_FUNC_GPIO_10_SDIO_D3, + HI_IO_FUNC_GPIO_10_SPI0_CK, + HI_IO_FUNC_GPIO_10_PWM1_OUT, + HI_IO_FUNC_GPIO_10_I2S0_TX = 7, +} hi_io_func_gpio_10; + +/** +* @ingroup iot_io +* +* GPIO_11 pin function.CNcomment:GPIO_11管脚功能。CNend +*/ +typedef enum { + HI_IO_FUNC_GPIO_11_GPIO, + HI_IO_FUNC_GPIO_11_UART2_TXD = 2, + HI_IO_FUNC_GPIO_11_SDIO_CMD, + HI_IO_FUNC_GPIO_11_SPI0_RXD, + HI_IO_FUNC_GPIO_11_PWM2_OUT, + HI_IO_FUNC_GPIO_11_RF_TX_EN_EXT, + HI_IO_FUNC_GPIO_11_I2S0_RX, +} hi_io_func_gpio_11; + +/** +* @ingroup iot_io +* +* GPIO_12 pin function.CNcomment:GPIO_12管脚功能。CNend +*/ +typedef enum { + HI_IO_FUNC_GPIO_12_GPIO, + HI_IO_FUNC_GPIO_12_UART2_RXD = 2, + HI_IO_FUNC_GPIO_12_SDIO_CLK, + HI_IO_FUNC_GPIO_12_SPI0_CSN, + HI_IO_FUNC_GPIO_12_PWM3_OUT, + HI_IO_FUNC_GPIO_12_RF_RX_EN_EXT, + HI_IO_FUNC_GPIO_12_I2S0_BCLK, +} hi_io_func_gpio_12; + +/** +* @ingroup iot_io +* +* GPIO_13 pin function.CNcomment:GPIO_13管脚功能。CNend +*/ +typedef enum { + HI_IO_FUNC_GPIO_13_SSI_DATA, + HI_IO_FUNC_GPIO_13_UART0_TXD, + HI_IO_FUNC_GPIO_13_UART2_RTS_N, + HI_IO_FUNC_GPIO_13_SDIO_D0, + HI_IO_FUNC_GPIO_13_GPIO, + HI_IO_FUNC_GPIO_13_PWM4_OUT, + HI_IO_FUNC_GPIO_13_I2C0_SDA, + HI_IO_FUNC_GPIO_13_I2S0_WS, +} hi_io_func_gpio_13; + +/** +* @ingroup iot_io +* +* GPIO_14 pin function.CNcomment:GPIO_14管脚功能。CNend +*/ +typedef enum { + HI_IO_FUNC_GPIO_14_SSI_CLK, + HI_IO_FUNC_GPIO_14_UART0_RXD, + HI_IO_FUNC_GPIO_14_UART2_CTS_N, + HI_IO_FUNC_GPIO_14_SDIO_D1, + HI_IO_FUNC_GPIO_14_GPIO, + HI_IO_FUNC_GPIO_14_PWM5_OUT, + HI_IO_FUNC_GPIO_14_I2C0_SCL, +} hi_io_func_gpio_14; + +/** +* @ingroup iot_io +* +* SFC_CSN pin function.CNcomment:SFC_CSN管脚功能。CNend +*/ +typedef enum { + HI_IO_FUNC_SFC_CSN_SFC_CSN, + HI_IO_FUNC_SFC_CSN_SDIO_D2, + HI_IO_FUNC_SFC_CSN_GPIO9, + HI_IO_FUNC_SFC_CSN_SPI0_TXD = 4, +} hi_io_func_sfc_csn; + +/** +* @ingroup iot_io +* +* SFC_DO pin function.CNcomment:SFC_DO管脚功能。CNend +*/ +typedef enum { + HI_IO_FUNC_SFC_IO_1_SFC_DO, + HI_IO_FUNC_SFC_IO_1_SDIO_D3, + HI_IO_FUNC_SFC_IO_1_GPIO10, + HI_IO_FUNC_SFC_IO_1_SPI0_CK = 4, +} hi_io_func_sfc_io_1; + +/** +* @ingroup iot_io +* +* SFC_WPN pin function.CNcomment:SFC_WPN管脚功能。CNend +*/ +typedef enum { + HI_IO_FUNC_SFC_IO_2_SFC_WPN, + HI_IO_FUNC_SFC_IO_2_SDIO_CMD, + HI_IO_FUNC_SFC_IO_2_GPIO11, + HI_IO_FUNC_SFC_IO_2_RF_TX_EN_EXT, + HI_IO_FUNC_SFC_IO_2_SPI0_RXD, +} hi_io_func_sfc_io_2; + +/** +* @ingroup iot_io +* +* SFC_DI pin function.CNcomment:SFC_DI管脚功能。CNend +*/ +typedef enum { + HI_IO_FUNC_SFC_IO_0_SFC_DI, + HI_IO_FUNC_SFC_IO_0_SDIO_CLK, + HI_IO_FUNC_SFC_IO_0_GPIO12, + HI_IO_FUNC_SFC_IO_0_RF_RX_EN_EXT, + HI_IO_FUNC_SFC_IO_0_SPI0_CSN, +} hi_io_func_sfc_io_0; + +/** +* @ingroup iot_io +* +* SFC_CLK pin function.CNcomment:SFC_CLK管脚功能。CNend +*/ +typedef enum { + HI_IO_FUNC_SFC_CLK_SFC_CLK, + HI_IO_FUNC_SFC_CLK_SDIO_D0, + HI_IO_FUNC_SFC_CLK_GPIO13, + HI_IO_FUNC_SFC_CLK_SSI_DATA = 4, +} hi_io_func_sfc_clk; + +/** +* @ingroup iot_io +* +* SFC_HOLDN pin function.CNcomment:SFC_HOLDN管脚功能。CNend +*/ +typedef enum { + HI_IO_FUNC_SFC_IO_3_SFC_HOLDN, + HI_IO_FUNC_SFC_IO_3_SDIO_D1, + HI_IO_FUNC_SFC_IO_3_GPIO14, + HI_IO_FUNC_SFC_IO_3_SSI_CLK = 4, +} hi_io_func_sfc_io_3; + +/** +* @ingroup iot_io +* +* I/O drive capability.CNcomment:IO驱动能力。CNend +* Note: The HI_IO_NAME_GPIO_0~HI_IO_NAME_GPIO_11 and HI_IO_NAME_GPIO_13~HI_IO_NAME_GPIO_14 driver capabilities are +* optional.The value range is HI_IO_DRIVER_STRENGTH_0~HI_IO_DRIVER_STRENGTH_3, and the other I/O ranges are +* HI_IO_DRIVER_STRENGTH_0~HI_IO_DRIVER_STRENGTH_7.CNcomment:注意:HI_IO_NAME_GPIO_0~HI_IO_NAME_GPIO_11、 +* HI_IO_NAME_GPIO_13~HI_IO_NAME_GPIO_14驱动能力可选范围是HI_IO_DRIVER_STRENGTH_0~HI_IO_DRIVER_STRENGTH_3, +* 其余IO范围是HI_IO_DRIVER_STRENGTH_0~HI_IO_DRIVER_STRENGTH_7。CNend +*/ +typedef enum { + HI_IO_DRIVER_STRENGTH_0 = 0, /**< Drive strength level 0 (highest). + CNcomment:驱动能力0级,驱动能力最高CNend */ + HI_IO_DRIVER_STRENGTH_1, /**< Drive strength level 1.CNcomment:驱动能力1级CNend */ + HI_IO_DRIVER_STRENGTH_2, /**< Drive strength level 2.CNcomment:驱动能力2级CNend */ + HI_IO_DRIVER_STRENGTH_3, /**< Drive strength level 3.CNcomment:驱动能力3级CNend */ + HI_IO_DRIVER_STRENGTH_4, /**< Drive strength level 4.CNcomment:驱动能力4级CNend */ + HI_IO_DRIVER_STRENGTH_5, /**< Drive strength level 5.CNcomment:驱动能力5级CNend */ + HI_IO_DRIVER_STRENGTH_6, /**< Drive strength level 6.CNcomment:驱动能力6级CNend */ + HI_IO_DRIVER_STRENGTH_7, /**< Drive strength level 7 (lowest). + CNcomment:驱动能力7级,驱动能力最低CNend */ + HI_IO_DRIVER_STRENGTH_MAX, +} hi_io_driver_strength; + +/** + * @ingroup iot_io + * + * GPIO pull-up configuration.CNcomment:IO上下拉功能CNend + */ +typedef enum { + HI_IO_PULL_NONE, /**< Disabled.CNcomment:无拉CNend */ + HI_IO_PULL_UP, /**< Pull-up enabled.CNcomment:上拉CNend */ + HI_IO_PULL_DOWN, /**< Pull-down enabled.CNcomment:下拉CNend */ + HI_IO_PULL_MAX, /**< Invalid.CNcomment:无效值CNend */ +} hi_io_pull; + +/** +* @ingroup iot_io +* @brief Enables the I/O pull-up.CNcomment:设置某个IO上下拉功能。CNend +* +* @par 描述: +* Enables the I/O pull-up.CNcomment:设置某个IO上下拉功能。CNend +* +* @attention None +* @param id [IN] type #hi_io_name,I/O index.CNcomment:硬件管脚。CNend +* @param val [IN] type #hi_io_pull,I/O pull-up enable.CNcomment:待设置的上下拉状态。CNend +* +* @retval 0 Success +* @retval #HI_ERR_GPIO_INVALID_PARAMETER Failure. Input invalid. +* @par 依赖: +* @li hi_io.h:Describes I/O APIs.CNcomment:文件用于描述IO相关接口。CNend +* @see hi_io_get_pull。 +*/ +hi_u32 hi_io_set_pull(hi_io_name id, hi_io_pull val); + +/** +* @ingroup iot_io +* @brief Obtains the GPIO pull-up status.CNcomment:获取某个GPIO上下拉状态。CNend +* +* @par 描述: +* Obtains the GPIO pull-up status.CNcomment:获取某个GPIO上下拉状态。CNend +* +* @attention None +* @param id [IN] type #hi_io_name,I/O index.CNcomment:硬件管脚。CNend +* @param val [OUT] type #hi_io_pull*,pull-up status.CNcomment:获取到的上下拉状态。CNend. +* +* @retval 0 Success +* @retval #HI_ERR_GPIO_INVALID_PARAMETER Failure. Input invalid. +* @par 依赖: +* @li hi_io.h:Describes I/O APIs.CNcomment:文件用于描述IO相关接口。CNend +* @see hi_io_set_pull。 +*/ +hi_u32 hi_io_get_pull(hi_io_name id, hi_io_pull *val); + +/** +* @ingroup iot_io +* @brief Sets the I/O multiplexing.CNcomment:配置某个IO的复用功能。CNend +* +* @par 描述: +* Sets the I/O multiplexing.CNcomment:配置某个IO的复用功能。CNend +* +* @attention None +* @param id [IN] type #hi_io_name,I/O index.CNcomment:硬件管脚。CNend +* @param val [IN] type #hi_u8,I/O multiplexing.See the functions below: CNcomment:IO复用功能。 +根据待设置的硬件管脚,从如下枚举中选择相应功能。CNend + hi_io_func_gpio_0, + hi_io_func_gpio_1, + hi_io_func_gpio_2, + hi_io_func_gpio_3, + hi_io_func_gpio_4, + hi_io_func_gpio_5, + hi_io_func_gpio_6, + hi_io_func_gpio_7, + hi_io_func_gpio_8, + hi_io_func_gpio_9, + hi_io_func_gpio_10, + hi_io_func_gpio_11, + hi_io_func_gpio_12, + hi_io_func_gpio_13, + hi_io_func_gpio_14, + hi_io_func_sfc_csn, + hi_io_func_sfc_io_1, + hi_io_func_sfc_io_2, + hi_io_func_sfc_io_0, + hi_io_func_sfc_clk, + hi_io_func_sfc_io_3 +* +* @retval 0 Success +* @retval #HI_ERR_GPIO_INVALID_PARAMETER Failure. Input invalid. +* @par 依赖: +* @li hi_io.h:Describes I/O APIs.CNcomment:文件用于描述IO相关接口。CNend +* @see hi_io_get_func。 +*/ +hi_u32 hi_io_set_func(hi_io_name id, hi_u8 val); + +/** +* @ingroup iot_io +* @brief Obtains the I/O multiplexing.CNcomment:获取某个IO复用功能。CNend +* +* @par 描述: +* Obtains the I/O multiplexing.CNcomment:获取某个IO复用功能。CNend +* +* @attention None +* @param id [IN] type #hi_io_name,I/O index.CNcomment:硬件管脚。CNend +* @param val [OUT] type #hi_u8*,I/O multiplexing.CNcomment:IO复用功能。CNend +* +* @retval 0 Success +* @retval #HI_ERR_GPIO_INVALID_PARAMETER Failure. Input invalid. +* @par 依赖: +* @li hi_io.h:Describes I/O APIs.CNcomment:文件用于描述IO相关接口。CNend +* @see hi_io_set_func。 +*/ +hi_u32 hi_io_get_func(hi_io_name id, hi_u8 *val); + +/** +* @ingroup iot_io +* @brief Sets the I/O drive strength.CNcomment:设置某个IO驱动能力。CNend +* +* @par 描述: +* The I/O drive strength is closely related to hardware design. For details, see SoC data sheet. +CNcomment:设置某个IO驱动能力,与硬件设计强相关,详细配置参考芯片手册。CNend +* +* @attention None +* @param id [IN] type #hi_io_name,I/O index.CNcomment:硬件管脚。CNend +* @param level [IN] type #hi_io_driver_strength,I/O drive strength level.CNcomment:IO驱动能力级别。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_io.h:Describes I/O APIs.CNcomment:文件用于描述IO相关接口。CNend +* @see None +*/ +hi_u32 hi_io_set_driver_strength(hi_io_name id, hi_io_driver_strength val); + +/** +* @ingroup iot_io +* @brief Obtains the I/O drive strength.CNcomment:获取某个IO驱动能力。CNend +* +* @par 描述: +* Obtains the I/O drive strength.CNcomment:获取某个IO驱动能力。CNend +* +* @attention None +* @param id [IN] type #hi_io_name,I/O index.CNcomment:硬件管脚。CNend +* @param val [OUT] type #hi_io_driver_strength*,I/O drive strength level.CNcomment:IO驱动能力级别。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_io.h:Describes I/O APIs.CNcomment:文件用于描述IO相关接口。CNend +* @see None +*/ +hi_u32 hi_io_get_driver_strength(hi_io_name id, hi_io_driver_strength *val); + +/** +* @ingroup iot_io +* @brief Set the I/O input enable status.CNcomment:设置某个IO输入使能的状态。CNend +* +* @par 描述: +* Set the I/O input enable status.CNcomment:设置某个IO输入使能的状态。CNend +* +* @attention If the input enable status of an IO is set to FALSE in the input state, the CPU can't read the IO changes. +CNcomment:如果某个IO的输入使能设置为FALSE,CPU将读取不到该IO的变化。CNend +* @param id [IN] type #hi_io_name,I/O index.CNcomment:硬件管脚。CNend +* @param state [IN] type #hi_bool,IO input enable state.CNcomment:要设置的输入使能状态。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_io.h:Describes I/O APIs.CNcomment:文件用于描述IO相关接口。CNend +* @see None +*/ +hi_u32 hi_io_set_input_enable(hi_io_name id, hi_bool state); + +/** +* @ingroup iot_io +* @brief Get the I/O input enable status.CNcomment:获取某个IO输入使能的状态。CNend +* +* @par 描述: +* Get the I/O input enable status.CNcomment:获取某个IO输入使能的状态。CNend +* +* @attention None +* @param id [IN] type #hi_io_name,I/O index.CNcomment:硬件管脚。CNend +* @param state [OUT] type #hi_bool *,IO input enable state.CNcomment:IO的输入使能状态。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_io.h:Describes I/O APIs.CNcomment:文件用于描述IO相关接口。CNend +* @see None +*/ +hi_u32 hi_io_get_input_enable(hi_io_name id, hi_bool *state); + +/** +* @ingroup iot_io +* @brief Set the I/O schmitt trigger enable status.CNcomment:设置某个IO斯密特触发器的使能状态。CNend +* +* @par 描述: +* Set the I/O schmitt trigger enable status.CNcomment:设置某个IO斯密特触发器的使能状态。CNend +* +* @attention Advise to enable schmitt trigger in scenarios that need to debounce. +CNcomment:建议在按键等需要消除抖动的场景开启斯密特触发器。CNend +* @param id [IN] type #hi_io_name,I/O index.CNcomment:硬件管脚。CNend +* @param is_enable [IN] type #hi_bool,Schmitt trigger enable status.CNcomment:斯密特触发器的使能状态。CNend +* @li HI_FALSE:No Schmitt.CNcomment:关闭斯密特触发器。CNend +* @li HI_TRUE: Schmitt enable.CNcomment:使能斯密特触发器。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_io.h:Describes I/O APIs.CNcomment:文件用于描述IO相关接口。CNend +* @see hi_io_get_schmitt +*/ +hi_u32 hi_io_set_schmitt(hi_io_name id, hi_bool is_enable); + +/** +* @ingroup iot_io +* @brief Get the I/O schmitt trigger enable status.CNcomment:获取某个IO斯密特触发器的使能状态。CNend +* +* @par 描述: +* Get the I/O schmitt trigger enable status.CNcomment:获取某个IO斯密特触发器的使能状态。CNend +* +* @attention None +* @param id [IN] type #hi_io_name,I/O index.CNcomment:硬件管脚。CNend +* @param is_enable [OUT] type #hi_bool *,Schmitt trigger enable status.CNcomment:斯密特触发器的使能状态。CNend +* @li HI_FALSE:No Schmitt.CNcomment:关闭斯密特触发器。CNend +* @li HI_TRUE: Schmitt enable.CNcomment:使能斯密特触发器。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_io.h:Describes I/O APIs.CNcomment:文件用于描述IO相关接口。CNend +* @see hi_io_set_schmitt +*/ +hi_u32 hi_io_get_schmitt(hi_io_name id, hi_bool *is_enable); + +#endif diff --git a/sdk_liteos/include/hi_isr.h b/sdk_liteos/include/hi_isr.h new file mode 100644 index 0000000000000000000000000000000000000000..584e04737dc1bde04af343fb454d60f0cc09191e --- /dev/null +++ b/sdk_liteos/include/hi_isr.h @@ -0,0 +1,226 @@ +/** + * @file hi_isr.h + * + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @defgroup iot_isr Interruption + * @ingroup osa + */ + +#ifndef __HI_ISR_H__ +#define __HI_ISR_H__ +#include "hi_types.h" + +#define HI_EXC_FLAG_NO_FLOAT 0x10000000 +#define HI_EXC_FLAG_FAULTADDR_VALID 0x01 +#define HI_EXC_FLAG_IN_HWI 0x02 + +typedef struct { + /* handler save */ + hi_u32 r4; + hi_u32 r5; + hi_u32 r6; + hi_u32 r7; + hi_u32 r8; + hi_u32 r9; + hi_u32 r10; + hi_u32 r11; + hi_u32 pri_mask; + /* auto save */ + hi_u32 sp; + hi_u32 r0; + hi_u32 r1; + hi_u32 r2; + hi_u32 r3; + hi_u32 r12; + hi_u32 lr; + hi_u32 pc; + hi_u32 xpsr; +} hi_exc_context; + +/** +* @ingroup iot_isr +* @brief HISR callback function type.CNcomment:HISR中断回调函数的类型。CNend +* +* @par 描述: +* HISR callback function type.CNcomment:HISR中断回调函数的类型。CNend +* +* @attention None +* @param param [IN] type #hi_u32,Callback input parameter.CNcomment:回调入参。CNend +* +* @retval None +* @par 依赖: +* @li hi_isr.h:Describes ISR APIs.CNcomment:文件用于描述ISR相关接口。CNend +* @see None +*/ +typedef hi_void (*irq_routine)(hi_u32 param); + +/** +* @ingroup iot_isr +* @brief Interrupt off.CNcomment:关中断。CNend +* +* @par 描述: +* Interrupt off.CNcomment:关中断。CNend +* +* @attention +* @li A function that causes scheduling cannot be executed in an interrupt off context, for example, +* hi_sleep and other blocked APIs. +* CNcomment:关中断后不能执行引起调度的函数,如hi_sleep或其他阻塞接口。CNend +* @li Interrupt off only protects short-time operations that can be expected. Otherwise, the interrupt +* response and the performance may be affected. +* CNcomment:关中断仅保护可预期的短时间的操作,否则影响中断响应,可能引起性能问题。CNend +* +* @param None +* +* @retval #hi_u32 Interruption status value Interrupt status before interrupt off. +CNcomment:中断状态值 关中断前的中断状态。CNend +* +* @par 依赖: +* @li hi_isr.h:Describes ISR APIs.CNcomment:文件用于描述ISR相关接口。CNend +* @see hi_int_restore。 +*/ +hi_u32 hi_int_lock(hi_void); + +/** +* @ingroup iot_isr +* @brief Restores the status before interrupt off.CNcomment:恢复关中断前的状态。CNend +* +* @par 描述: +* Restores the status before interrupt off.CNcomment:恢复关中断前的状态。CNend +* +* @attention The input argument must be the value of CPSR that is saved before interrupt off. +CNcomment:入参必须是与之对应的关中断时保存的关中断之前的CPSR的值。CNend +* +* @param int_value [IN] type #hi_u32,Interrupt status.CNcomment:中断状态。CNend +* +* @retval None +* @par 依赖: +* @li hi_isr.h:Describes ISR APIs.CNcomment:文件用于描述ISR相关接口。CNend +* @see hi_int_lock。 +*/ +hi_void hi_int_restore(hi_u32 int_value); + +/** +* @ingroup iot_isr +* @brief Enables a specified interrupt.CNcomment:使能指定中断。CNend +* +* @par 描述: +* Enables a specified interrupt.CNcomment:使能指定中断。CNend +* +* @attention None +* +* @param vector [IN] type #hi_u32,Interrupt ID.CNcomment:中断号。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h +* @par 依赖: +* @li hi_isr.h:Describes ISR APIs.CNcomment:文件用于描述ISR相关接口。CNend +* @see hi_irq_disable。 +*/ +hi_u32 hi_irq_enable(hi_u32 vector); + +/** +* @ingroup iot_isr +* @brief Disables a specified interrupt.CNcomment:去使能指定中断。CNend +* +* @par 描述: +* Disables a specified interrupt.CNcomment:去使能指定中断。CNend +* +* @attention None +* @param vector [IN] type #hi_u32,Interrupt ID.CNcomment:中断号。CNend +* +* @retval None +* @par 依赖: +* @li hi_isr.h:Describes ISR APIs.CNcomment:文件用于描述ISR相关接口。CNend +* @see hi_irq_enable。 +*/ +hi_void hi_irq_disable(hi_u32 vector); + +/* 由于不支持中断嵌套,仅当中断同时触发的场景下有效。 */ +#define HI_IRQ_FLAG_PRI1 1 +#define HI_IRQ_FLAG_PRI2 2 +#define HI_IRQ_FLAG_PRI3 3 +#define HI_IRQ_FLAG_PRI4 4 +#define HI_IRQ_FLAG_PRI5 5 +#define HI_IRQ_FLAG_PRI6 6 +#define HI_IRQ_FLAG_PRI7 7 +#define HI_IRQ_FLAG_PRI_MASK 0x7 +#define HI_IRQ_FLAG_NOT_IN_FLASH 0x10 + +#define HI_IRQ_FLAG_DEFAULT HI_IRQ_FLAG_NOT_IN_FLASH + +/** +* @ingroup iot_isr +* @brief Registers an interrupt.CNcomment:注册中断。CNend +* +* @par 描述: +* Registers an interrupt.CNcomment:注册中断。CNend +* +* @attention The interruption handling program cannot take too long a time, which affects the timely response of the +* CPU to the interrupt.CNcomment:中断处理程序耗时不能过长,影响CPU对中断的及时响应。CNend +* +* @param vector [IN] type #hi_u32,Interrupt ID.CNcomment:中断号。CNend +* @param flag [IN] type #hi_u32, attributes like priority,etc.CNcomment:中断优先级等属性。CNend +* @param routine [IN] type #irq_routine,Interrupt callback function.CNcomment:中断回调函数。CNend +* @param param [IN] type #hi_u32,Parameter transferred to the callback function. +CNcomment:中断回调函数的入参。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h +* @par 依赖: +* @li hi_isr.h:Describes ISR APIs.CNcomment:文件用于描述ISR相关接口。CNend +* @see hi_irq_free。 +*/ +hi_u32 hi_irq_request(hi_u32 vector, hi_u32 flags, irq_routine routine, hi_u32 param); + +/** +* @ingroup iot_isr +* @brief Clears a registered interrupt.CNcomment:清除注册中断。CNend +* +* @par 描述: +* Clears a registered interrupt.CNcomment:清除注册中断。CNend +* +* @attention None +* @param vector [IN] type #hi_u32,Interrupt ID.CNcomment:中断号。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h +* @par 依赖: +* @li hi_isr.h:Describes ISR APIs.CNcomment:文件用于描述ISR相关接口。CNend +* @see hi_irq_request。 +*/ +hi_u32 hi_irq_free(hi_u32 vector); + +/** +* @ingroup iot_isr +* @brief Checks whether it is in the interrupt context.CNcomment:检查是否在中断上下文中。CNend +* +* @par 描述: +* Checks whether it is in the interrupt context.CNcomment:检查是否在中断上下文中。CNend +* +* @attention None +* @param None +* +* @retval #HI_FALSE Not in the interrupt context.CNcomment:不在中断上下文中。CNend +* @retval #HI_TRUE In the interrupt context.CNcomment:在中断上下文中。CNend +* @par 依赖: +* @li hi_isr.h:Describes ISR APIs.CNcomment:文件用于描述ISR相关接口。CNend +* @see 无。 +*/ +hi_bool hi_is_int_context(hi_void); + +#endif + diff --git a/sdk_liteos/include/hi_list.h b/sdk_liteos/include/hi_list.h new file mode 100644 index 0000000000000000000000000000000000000000..4d39156e538c8cefba4487c3371555c733a3fd7f --- /dev/null +++ b/sdk_liteos/include/hi_list.h @@ -0,0 +1,238 @@ +/** + * @file hi_list_sdk.h + * + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + /** + * @defgroup iot_list List + * @ingroup system + */ +#ifndef __HI_LIST_SDK_H__ +#define __HI_LIST_SDK_H__ + +#include + +/****************************************************************************/ +HI_START_HEADER + +/* + * Note: This file renames the linked list interface and uses the LTOS interface to implement it again. + * CNcomment:备注:本文件对链表接口重新命名,使用LTOS接口重新实现。 + */ +typedef struct hi_list { + struct hi_list *prev; + struct hi_list *next; +} hi_list; + +/* + * Function description: + * Initialize the head node. Note that this node is used only for management, not the data node entered by the user. + * CNcomment:功能描述:初始化头节点,注意此节点仅用于管理,不是用户输入的数据节点 + */ +__attribute__((always_inline)) static inline hi_void hi_list_init(hi_list *list) +{ + list->next = list; + list->prev = list; +} + +/* + * Function description: Inserts a node as the first node in the list. + * CNcomment:功能描述:把node插入为list的第一个节点 + */ +__attribute__((always_inline)) static inline hi_void hi_list_head_insert(hi_list *node, hi_list *list) +{ + node->next = list->next; + node->prev = list; + list->next->prev = node; + list->next = node; +} + +/* + * Function description: Inserts a node as the last node in the list. + * CNcomment:功能描述:把node插入为list的最后一个节点 + */ +__attribute__((always_inline)) static inline hi_void hi_list_tail_insert(hi_list *node, hi_list *list) +{ + hi_list_head_insert(node, list->prev); +} + +/* + * Function description: Deletes a node from the linked list. + * CNcomment:功能描述:从链表中删除某个节点 + */ +__attribute__((always_inline)) static inline hi_void hi_list_delete(hi_list *node) +{ + if (node->next == HI_NULL || node->prev == HI_NULL) { + return; + } + + node->next->prev = node->prev; + node->prev->next = node->next; + node->next = (hi_list *)HI_NULL; + node->prev = (hi_list *)HI_NULL; +} + +/* + * Function description: Deletes the first node in the linked list without releasing the related memory. + * CNcomment:功能描述:删除链表的第一个节点,不释放相关内存 + */ +__attribute__((always_inline)) static inline hi_list *hi_list_delete_head(hi_list *list) +{ + hi_list *del_node; + + del_node = list->next; + if (del_node == list || del_node == HI_NULL) { + return HI_NULL; + } + + hi_list_delete(del_node); + return del_node; +} + +/* + * Function description: Deletes the tail node of the linked list without releasing the related memory. + * CNcomment:功能描述:删除链表尾部节点,不释放相关内存 + */ +__attribute__((always_inline)) static inline hi_list *hi_list_delete_tail(hi_list *list) +{ + hi_list *del_node; + + del_node = list->prev; + if (del_node == list || del_node == HI_NULL) { + return HI_NULL; + } + + hi_list_delete(del_node); + return del_node; +} + +/* + * Function description: Determines whether the linked list is empty. + * CNcomment:功能描述:判断链表是否为空 + */ +__attribute__((always_inline)) static inline hi_bool hi_is_list_empty(hi_list *list) +{ + if (list->next == HI_NULL || list->prev == HI_NULL) { + return HI_TRUE; + } + return (hi_bool)(list->next == list); +} + +/* + * Function description: Deinitializes the linked list. The management node clears the list. + * Other member nodes are still connected in a bidirectional linked list. + * CNcomment:功能描述:去初始化链表,管理节点清空,其他成员节点首尾相连仍然是一个双向链表。 + */ +__attribute__((always_inline)) static inline hi_void hi_list_del_init(hi_list *list) +{ + list->next->prev = list->prev; + list->prev->next = list->next; + + list->next = list; + list->prev = list; +} + +/* + * Function description: Adds linked list 2 to the end of linked list 1. + * CNcomment:功能描述:将链表2加入链表1的尾部 + */ +__attribute__((always_inline)) static inline hi_void hi_list_join_tail(hi_list *list1, hi_list *list2) +{ + list1->prev->next = list2->next; + list2->next->prev = list1->prev; + list2->prev->next = list1; + list1->prev = list2->prev; +} + +/* + * Function description: Adds linked list 2 to the header of linked list 1. + * CNcomment:功能描述:将链表2加入链表1的头部 + */ +__attribute__((always_inline)) static inline hi_void hi_list_join_head(hi_list *list1, hi_list *list2) +{ + /* list2 is empty. */ + if (list2->next == list2) { + return; + } + + list2->prev->next = list1->next; + list1->next->prev = list2->prev; + list1->next = list2->next; + list2->next->prev = list1; +} + +/* + * Function description: Extracts the first element from the last_node element in linked list 2 and + * adds the first element to the header of empty linked list 1. + * CNcomment:功能描述:将链表2中从第一个元素到last_node元素摘出, 加入空链表1的头部 + */ +__attribute__((always_inline)) static inline hi_void hi_list_remove_head(hi_list *list1, hi_list *list2, + hi_list *last_node) +{ + list1->next = list2->next; + list1->prev = last_node; + + list2->next = last_node->next; + ((hi_list *)(last_node->next))->prev = list2; + + last_node->next = list1; + if (last_node->prev == list2) { + last_node->prev = list1; + } +} + +#define hi_list_init_macro(_list_name) hi_list _list_name = { (hi_list*)&(_list_name), (hi_list*)&(_list_name) } + +/* + * Obtains the pointer of the first node. + * CNcomment:获取第一个节点指针 + */ +#define hi_list_first(object) ((object)->next) + +#define hi_list_last(object) ((object)->prev) + +#define hi_list_entry(item, type, member) \ + ((type*)((char*)(item) - hi_offset_of_member(type, member))) + +#define hi_list_for_each_entry(item, list, type, member) \ + for ((item) = hi_list_entry((list)->next, type, member); \ + &(item)->member != (list); \ + (item) = hi_list_entry((item)->member.next, type, member)) + +#define hi_list_for_each_entry_safe(list, item, pnext, type, member) \ + for ((item) = hi_list_entry((list)->next, type, member), \ + (pnext) = hi_list_entry((item)->member.next, type, member); \ + &(item)->member != (list); \ + (item) = (pnext), (pnext) = hi_list_entry((item)->member.next, type, member)) + +#define hi_list_for_each_entry_continue_safe(pitem, list, item, pnext, type, member) \ + for ((item) = hi_list_entry((pitem)->next, type, member), \ + (pnext) = hi_list_entry((item)->member.next, type, member); \ + &((item)->member) != (list); \ + (item) = (pnext), (pnext) = hi_list_entry((pnext)->member.next, type, member)) + +/* Simple Implementation of Bidirectional Linked List Operation */ +#define hi_list_head(list) \ + hi_list list = { &(list), &(list) } + +#define hi_list_for_each(item, list) \ + for ((item) = (list)->next; (item) != (list); (item) = (item)->next) + +#define hi_list_for_each_safe(item, pnext, list) \ + for ((item) = (list)->next, (pnext) = (item)->next; (item) != (list); \ + (item) = (pnext), (pnext) = (item)->next) + +HI_END_HEADER +#endif /* __HI_STDLIB_H__ */ diff --git a/sdk_liteos/include/hi_lowpower.h b/sdk_liteos/include/hi_lowpower.h new file mode 100644 index 0000000000000000000000000000000000000000..23b0243057067e834cbdb7d5591ffe97865ec416 --- /dev/null +++ b/sdk_liteos/include/hi_lowpower.h @@ -0,0 +1,374 @@ +/** + * @file hi_lowpower.h + * + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @defgroup iot_lp Power consumption management + * @ingroup system + */ + +#ifndef __HI_LOWPOWER_H__ +#define __HI_LOWPOWER_H__ + +#include +#include + +/** + * @ingroup iot_lp + * UDP wakes up source enumeration. + */ +typedef enum { + HI_UDS_GPIO3 = 1 << 0, /**< ultra sleep wakeup source GPIO3.CNcomment:超深睡唤醒源GPIO3 CNend */ + HI_UDS_GPIO5 = 1 << 1, /**< ultra sleep wakeup source GPIO5.CNcomment:超深睡唤醒源GPIO5 CNend */ + HI_UDS_GPIO7 = 1 << 2, /**< ultra sleep wakeup source GPIO7.CNcomment:超深睡唤醒源GPIO7 CNend */ + HI_UDS_GPIO14 = 1 << 3, /**< ultra sleep wakeup source GPIO14.CNcomment:超深睡唤醒源GPIO14 CNend */ +} hi_udsleep_src; + +/** + * @ingroup iot_lp + * Sleep level enumeration. + */ +typedef enum { + HI_NO_SLEEP, /**< no sleep type.CNcomment:不睡模式 CNend */ + HI_LIGHT_SLEEP, /**< light sleep type.CNcomment:浅睡模式 CNend */ + HI_DEEP_SLEEP, /**< deep sleep type.CNcomment:深睡模式 CNend */ +} hi_lpc_type; + +/** + * @ingroup hct_lp + * + * 睡眠模块ID 枚举,每个id占用1个bit,继续扩展时要注意最大为(1 << 31)。 + */ +typedef enum { + HI_LPC_ID_DIAG = 1 << 0, /**< diag uart Id.CNcomment:diag模块 Id */ + HI_LPC_ID_SHELL = 1 << 1, /**< shell Id.CNcomment:shell模块 Id CNend */ + HI_LPC_ID_RSV = 1 << 15, /**< 之前均为内部预留id.CNcomment:内部预留 Id CNend */ + HI_LPC_ID_DEMO = 1 << 16, /**< demo Id.CNcomment:低功耗管理id样例,之后为客户预留Id CNend */ +}hi_lpc_id; + +/** + * @ingroup iot_lp + * Low power management structure. + */ +typedef struct { + hi_u32 wakeup_times; /**< wakeup times.CNcomment:唤醒次数统计 CNend */ + hi_u32 sleep_threshold_refuse_times; /**< sleep threshold refuse times.CNcomment: + 可睡时间小于设定门限次数统计 CNend */ + hi_u32 sleep_check_refuse_times; /**< sleep check refuse times.CNcomment: + 入睡投票睡眠失败次数统计 CNend */ + hi_u32 sleep_times; /**< sleep times.CNcomment:入睡次数统计 CNend */ + hi_u32 sleep_threshold; /**< sleep threshold, unit is ms, only when + the system' Remaining idle time is bigger than the threshold, + system can enter deep sleep state.CNcomment:深睡眠门限,单位 + 为ms,当系统剩余空闲时间大于该门限时,方可进入深睡 CNend */ + hi_u32 dsleep_fail_times; /**< the times of power off fail during deepsleep.CNcomment:深睡下电失败次数统计 CNend */ + hi_u8 type; /**< hi_lpc_type type, enable low power management. + CNcomment:hi_lp_type类型,低功耗类型 CNend */ + hi_u8 evt_sts; /**< wakeup event state, bit0:gpio wkup, bit1:rtc wkup, bit2:sdio wkup, bit4: + sta0 wkup, bit5:sta1 wkup, bit6:ap0 wkup.CNcomment:唤醒事件状态,bit0:gpio 唤醒, + bit1:rtc 唤醒,bit2:sdio 唤醒,bit4:sta0 唤醒, bit5:sta1 唤醒, + bit6:ap0 唤醒。 CNend */ + hi_u8 int_sts; /**< wakeup interrupt state, bit0:gpio wkup, bit1:rtc wkup, bit2:sdio wkup, bit4: + sta0 wkup, bit5:sta1 wkup, bit6:ap0 wkup.CNcomment:唤醒中断状态,bit0:gpio 唤醒, + bit1:rtc 唤醒,bit2:sdio 唤醒,bit4:sta0 唤醒, bit5:sta1 唤醒, + bit6:ap0 唤醒 CNend */ + hi_u8 last_time_vote_state; /**< last time vote state, 0:no sleep, 1: light sleep, 2: deep sleep. + CNcomment:最近一次睡眠状态,0:没有入睡,1:浅睡,2:深睡。 CNend */ + hi_u32 timer_ticks; /**< the time ticks is about to expire, unit is 10 ms, if the value is 0xffffffff, there is + no timer that is about to expire. + CNcomment:定时器即将到期的时间,单位为10ms;如果是0xffffffff,表示没有即将到期的 + 定时器 CNend */ + hi_u32 timer_handle; /**< the callback function address of the timer that is about to expire. if the value is + 0xffffffff, it means that there is no timer that is about to expire. + CNcomment:即将到期定时器回调函数的地址,如果是0xffffffff,表示没有即将到期的定时器 CNend */ + hi_u32 timer_handle_arg; /**< the parameter of the timer callback function, if the value is 0xffffffff, it means + there is no timer to expire.CNcomment:定时器回调函数的参数,如果是0xffffffff, + 表示没有即将到期的定时器 CNend */ + hi_u32 task_ticks; /**< the task ticks is about to expire, unit is 10 ms.CNcomment:任务即将到期的时间, + 单位为10ms。CNend */ + hi_u32 task_id; /**< the task id that is about to expire.CNcomment:即将到期任务的ID。CNend */ + hi_u32 sleep_ticks; /**< last sleep time ticks, unit is 10 ms.CNcomment:最近一次睡眠的tick时间, + 单位为10ms。CNend */ + hi_u32 veto_info; /**< veto_info.CNcomment:投票否决睡眠信息,详见hi_lpc_id。CNend */ + hi_u16 dsleep_wk_gpio; /**< wakeup gpio for deep sleep.CNcomment:唤醒的GPIO,该值(1< +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#endif /* __HI_MDM_H__ */ + diff --git a/sdk_liteos/include/hi_mdm_types.h b/sdk_liteos/include/hi_mdm_types.h new file mode 100644 index 0000000000000000000000000000000000000000..51acbe8b89fe7b31dc3a6d04538c6da3f72f45b7 --- /dev/null +++ b/sdk_liteos/include/hi_mdm_types.h @@ -0,0 +1,240 @@ +/** + * @file hi_mdm_types.h + * + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __HI_MDM_TYPES_H__ +#define __HI_MDM_TYPES_H__ +#ifndef __HI_TYPES_H__ +#error "Please include hi_types.h before using hi_mdm_types.h" +#endif +HI_START_HEADER + +#include + +#define HI_ALL_F_32 0xFFFFFFFF + +typedef struct { + hi_u32 major_minor_version; + hi_u32 revision_version; + hi_u32 build_version; +} hi_ue_soft_version; + +#define HI_BUILD_VER_DATE_LEN 10 +#define HI_BUILD_VER_TIME_LEN 8 +#define HI_BUILD_VER_PRODUCT_NAME_LEN_MAX 28 +#define HI_BUILD_VER_PRODUCT_LEN_MAX (HI_BUILD_VER_PRODUCT_NAME_LEN_MAX + HI_BUILD_VER_DATE_LEN + \ + HI_BUILD_VER_TIME_LEN + 6) +typedef struct { + hi_u16 version_v; + hi_u16 version_r; + hi_u16 version_c; + hi_u16 version_b; + hi_u16 version_spc; + hi_u16 reserved[3]; /* 3 bytes reserved */ +} hi_ue_product_ver; + +typedef struct { + hi_char* build_date; /* pszDate; // For example: 2011-08-01 */ + hi_char* build_time; /* pszTime; // For example: 14:30:26 */ +} hi_product_info; + +/* +* @ingroup iot_diag +* @brief Registers the callback function for DIAG channel status changes. +CNcomment:DIAG通道状态变更回调函数。CNend +* +* @par 描述: +* Registers the callback function for DIAG channel status changes. That is, when the DIAG channel is +* connected or disconnected, the function registered by this API is called back. +CNcomment:注册DIAG通道变更回调函数(即:当DIAG通道连接或断开时,会回调本接口注册的函数)。CNend +* +* @attention None。 +* @param port_num [IN] type #hi_u16,port number. +CNcomment:端口号。CNend +* @param is_connected [IN] type #hi_bool,connection status. +CNcomment:连接状态。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par Dependency: +* @li hi_diag.h: Describes DIAG APIs. +CNcomment:文件用于描述DIAG相关接口。CNend +* @see None + */ +typedef hi_u32 (*hi_diag_connect_f)(hi_u16 port_num, hi_bool is_connected); + +/** +* @ingroup iot_dms +* +* Strcture of Channel interface object. +CNcomment:通道接口实例结构。CNend +*/ +#define HI_DMS_FRM_INTER_INFO1_SIZE (sizeof(hi_u8) + sizeof(hi_u8)) /* mmt, vt */ +#define HI_DMS_FRM_INTER_INFO2_SIZE 4 /* 公用控制字段长度 */ +#define HI_DMS_INTER_INFO_SIZE (HI_DMS_FRM_INTER_INFO1_SIZE + HI_DMS_FRM_INTER_INFO2_SIZE) + +typedef struct { + hi_u16 data_size; /**< Length of data element(Unit: type). + CNcomment: 数据大小,即ucData所占空间大小(单位:byte)CNend */ + hi_u8 inside_info[HI_DMS_INTER_INFO_SIZE]; /**< For internal use. CNcomment:内部使用CNend */ + hi_u8 data[0]; /**< Data. CNcomment:数据CNend */ +} hi_dms_chl_tx_data; + +#define HI_DMS_CHL_FRAME_HRD_SIZE (sizeof(hi_dms_chl_tx_data)) + +typedef struct { + hi_u32 id; /* Specify the message id. */ + hi_u32 src_mod_id; + hi_u32 dest_mod_id; + hi_u32 data_size; /* the data size in bytes. */ + hi_pvoid data; /* Pointer to the data buffer. */ +} hi_diag_layer_msg; + +/** +* @ingroup iot_diag +* @brief Callback function for handling diagnosis commands. +CNcommond:HSO命令处理回调函数。CNend +* +* @par 描述: +* Callback function for handling diagnosis commands, that is, the function body for executing commands. +CNcomment:HSO命令处理回调函数,即命令的执行函数体。CNend +* +* @attention +* @li If the returned value is not HI_ERR_CONSUMED, the DIAG framework automatically forwards +* the returned value to the host. CNcomment:如果返回值不为HI_ERR_CONSUMED, +则表示有DIAG框架自动直接将返回值回复给HSO。CNend +* @li If the return value is HI_ERR_CONSUMED, it indicates that the user sends a response (local connection) +* to the host through the hi_diag_send_ack_packet API. The DIAG framework does not automatically +* respond to the host. CNcomment:如果返回值为HI_ERR_CONSUMED, +则表示用户通过hi_diag_send_ack_packet接口给HSO应答(本地连接),DIAG框架不自动给HSO应答。CNend +* @li The return value of the API cannot be HI_ERR_NOT_FOUND. +CNcomment:该注册接口的返回值不能为HI_ERR_NOT_FOUND。CNend +* @param cmd_id [IN] type #hi_u16,Command ID CNcomment:命令ID。CNend +* @param cmd_param [IN] type #hi_pvoid,Pointer to the use input command. +CNcomment:用户输入命令指针。CNend +* @param cmd_param_size [IN] type #hi_u16,Length of the command input by the user (unit:byte). +CNcomment:用户输入命令长度(单位:byte)。CNend +* @param option [IN] type #hi_u8,#HI_DIAG_CMD_INSTANCE_LOCAL and #HI_DIAG_CMD_INSTANCE_IREMOTE are supported. +CNcomment:支持使用#HI_DIAG_CMD_INSTANCE_LOCAL、#HI_DIAG_CMD_INSTANCE_IREMOTE。CNend. +* +* @retval #0 Success +* @retval #Other Failure. For details, see hi_errno.h +* @par Dependency: +* @li hi_diag.h: Describes DIAG APIs. +CNcomment: 文件用于描述DIAG相关接口。CNend +* @see None. +*/ +typedef hi_u32 (*hi_diag_cmd_f)(hi_u16 cmd_id, hi_pvoid cmd_param, hi_u16 cmd_param_size, hi_u8 option); +/** +* @ingroup iot_diag +* Command registration structure. The same callback function can be used within the command ID range. +CNcommand:命令注册结构体,支持标注命令ID范围内使用同一个回调函数。CNend. +* +* If a single command is used, the maximum and minimum IDs are the same. +CNcommand:如果单命令,则最大和最小填写相同ID号。CNend +*/ +typedef struct { + hi_u16 min_id; /**< Minimum DIAG ID, [0, 65535]. CNcomment:最小的DIAG ID,取值范围[0, 65535]。 CNend */ + hi_u16 max_id; /**< Maximum DIAG ID, [0, 65535]. CNcomment:最大的DIAG ID,取值范围[0, 65535]。 CNend */ + hi_diag_cmd_f input_cmd; /**< This Handler is used to process the HSO command. + CNcomment:处理HSO命令的入口函数。CNend */ +} hi_diag_cmd_reg_obj; + +/** + * @ingroup iot_diag + * Local instance -->HSO Interaction command between the host software and the local station. + CNcomment:本地实例 -->HSO 表示上位机软件和本地站点间的交互命令 CNend + */ +#define HI_DIAG_CMD_INSTANCE_DEFAULT ((hi_u8)0) + +/** + * @ingroup iot_diag + * Local instance -->HSO Interaction command between the host software and the local station. + CNcomment: 本地实例 -->HSO 表示上位机软件和本地站点间的交互命令 CNend + */ +#define HI_DIAG_CMD_INSTANCE_LOCAL HI_DIAG_CMD_INSTANCE_DEFAULT /* Local CMD.CNcomment:本地命令 CNend */ +#define HI_DIAG_CMD_INSTANCE_IREMOTE 1 /* Remote CMD.CNcomment:远程命令 CNend */ + +#if defined(HAVE_PCLINT_CHECK) +#define hi_check_default_id(id) (id) +#else +#define hi_check_default_id(id) (((id) == 0) ? __LINE__ : (id)) +#endif +#define hi_diag_log_msg_mk_id_e(id) hi_makeu32(((((hi_u16)(hi_check_default_id(id))) << 2) + 0), \ + HI_DIAG_LOG_MSG_FILE_ID) +#define hi_diag_log_msg_mk_id_w(id) hi_makeu32(((((hi_u16)(hi_check_default_id(id))) << 2) + 1), \ + HI_DIAG_LOG_MSG_FILE_ID) +#define hi_diag_log_msg_mk_id_i(id) hi_makeu32(((((hi_u16)(hi_check_default_id(id))) << 2) + 2), \ + HI_DIAG_LOG_MSG_FILE_ID) + +#define HI_ND_SYS_BOOT_CAUSE_NORMAL 0x0 +#define HI_ND_SYS_BOOT_CAUSE_EXP 0x1 +#define HI_ND_SYS_BOOT_CAUSE_WD 0x2 +#define HI_ND_SYS_BOOT_CAUSE_UPG_VERIFY 0x3 +#define HI_ND_SYS_BOOT_CAUSE_UPG_FAIL 0x4 +#define HI_ND_SYS_BOOT_CAUSE_UPG_BACK_FAIL 0x5 + +#define CHANLLENGE_SALT_SIZE 16 +/******************************DIAG***********************************************/ +#define HI_DIAG_LOG_OPT_LOCAL_REQ 1 /**< Local command request from the host to DIAG. + CNcomment:本地命令请求 上位机->DIAG CNend */ +#define HI_DIAG_LOG_OPT_LOCAL_IND 2 /**< local response from DIAG to the host. + CNcomment: 本地应答 DIAG ->上位机 CNend */ +#define HI_DIAG_LOG_OPT_LOCAL_ACK 3 /**< Local ACK from DIAG to the host. + CNcomment: 本地ACK DIAG ->上位机 CNend */ + +/** + * @ingroup iot_diag + * Describes the command type transferred to the app layer. + CNcomment: 描述传递给应用层的命令类型。CNend + */ +typedef struct { + /**< Option configuration, which is used to set the command as a local command or a remote + * command. The value is a HI_DIAG_LOG_OPT_XXX macro such as #HI_DIAG_LOG_OPT_LOCAL_REQ. + CNcomment: 选项配置,用于设置此命令为本地命令或远程命令等信息, + 取值为HI_DIAG_LOG_OPT_XXX 宏 CNend */ + hi_u32 opt; +} hi_diag_log_ctrl; + +/** +* @ingroup iot_diag +* @brief Callback function for notifying DIAG operations. +CNcomment:DIAG操作通知回调函数。CNend +* +* @par 描述: +* Carbon copies data to the app layer by using a callback function in +* the case of data interaction between the host and the board. +CNcomment: 该函数用于当HSO与单板有数据交互发生时,将数据通过回调函数抄送给应用层。CNend +* +* @attention 无。 +* @param cmd_id [IN] type #hi_u32,Command ID. CNcomend:命令ID。CNend +* @param buffer [IN] type #hi_pvoid,Data pointer transferred to the app layer. +CNcomment:传递给应用层的数据指针。CNend +* @param buffer_size [IN] type #hi_u16,Length of the data transferred to the app layer (unit: byte) +CNcomment:传递给应用层的数据长度(单位:byte)。CNend +* @param log_ctrl [IN] type #hi_diag_log_ctrl*,Command type sent to the app layer +CNcomment:传递给应用层的命令类型。CNend +* +* @retval #0 Success +* @retval #Other Failure. For details, see hi_errno.h. +* @par Dependency: +* @li hi_diag.h:Describes DIAG APIs. CNcomment:文件用于描述DIAG相关接口。CNend +* @see None + */ +typedef hi_void (*hi_diag_cmd_notify_f)(hi_u16 cmd_id, hi_pvoid buffer, hi_u16 buffer_size, + hi_diag_log_ctrl *log_ctrl); +HI_END_HEADER +#endif /* __HI_MDM_TYPES_H__ */ diff --git a/sdk_liteos/include/hi_mem.h b/sdk_liteos/include/hi_mem.h new file mode 100644 index 0000000000000000000000000000000000000000..efd41c6c4014ca01db106dfde9b6a738cd831096 --- /dev/null +++ b/sdk_liteos/include/hi_mem.h @@ -0,0 +1,140 @@ +/** + * @file hi_men.h + * + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @defgroup iot_mem Memory + * @ingroup osa + */ + +#ifndef __HI_MEM_H__ +#define __HI_MEM_H__ +#include + +/** + * @ingroup iot_mem + * Overall memory information.CNcomment:整体内存信息。CNend + */ +typedef struct { + hi_u32 total; /**< Total space of the memory pool (unit: byte). + CNcomment:内存池总大小(单位:byte)CNend */ + hi_u32 used; /**< Used space of the memory pool (unit: byte). + CNcomment:内存池已经使用大小(单位:byte)CNend */ + hi_u32 free; /**< Free space of the memory pool (unit: byte). + CNcomment:内存池剩余空间(单位:byte)CNend */ + hi_u32 free_node_num; /**< Number of free nodes in the memory pool. + CNcomment:内存池剩余空间节点个数 CNend */ + hi_u32 used_node_num; /**< Number of used nodes in the memory pool. + CNcomment:内存池已经使用的节点个数 CNend */ + hi_u32 max_free_node_size; /**< Maximum size of the node in the free space of the memory pool (unit: byte). + CNcomment:内存池剩余空间节点中最大节点的大小(单位:byte)CNend */ + hi_u32 malloc_fail_count; /**< Number of memory application failures.CNcomment:内存申请失败计数 CNend */ + hi_u32 peek_size; /**< Peak memory usage of the memory pool.CNcomment:内存池使用峰值CNend */ + hi_u32 total_lmp; /**< Total space of the little memory pool (unit: byte). + CNcomment:小内存池总大小(单位:byte)CNend */ + hi_u32 used_lmp; /**< Used space of the little memory pool (unit: byte). + CNcomment:小内存池已经使用大小(单位:byte)CNend */ + hi_u32 free_lmp; /**< Free space of the little memory pool (unit: byte). + CNcomment:小内存池剩余空间(单位:byte)CNend */ +} hi_mdm_mem_info; + +typedef struct { + hi_u32 pool_addr; + hi_u32 pool_size; + hi_u32 fail_count; + hi_u32 peek_size; + hi_u32 cur_use_size; +} hi_mem_pool_crash_info; + +/** +* @ingroup iot_mem +* @brief Dynamically applies for memory.CNcomment:动态申请内存。CNend +* +* @par 描述: +* Dynamically applies for memory.CNcomment:动态申请内存。CNend +* +* @attention None +* @param mod_id [IN] type #hi_u32,ID of the called module.CNcomment:调用模块ID。CNend +* @param size [IN] type #hi_u32,Requested memory size (unit: byte) +CNcomment:申请内存大小(单位:byte)。CNend +* +* @retval #>0 Success +* @retval #HI_NULL Failure. The memory is insufficient. +* @par 依赖: +* @li hi_mem.h:Describes memory APIs.CNcomment:文件用于描述内存相关接口。CNend +* @see hi_free。 +*/ +hi_pvoid hi_malloc(hi_u32 mod_id, hi_u32 size); + +/** +* @ingroup iot_mem +* @brief Releases the memory that is dynamically applied for.CNcomment:释放动态申请的内存。CNend +* +* @par 描述: +* Releases the memory that is dynamically applied for.CNcomment:释放动态申请的内存。CNend +* +* @attention None +* @param mod_id [IN] type #hi_u32,ID of the called module.CNcomment:调用模块ID。CNend +* @param addr [IN] type #hi_pvoid,Start address of the requested memory. The validity of the address is ensured +* by the caller.CNcomment:所申请内存的首地址,地址合法性由调用者保证。CNend +* +* @retval None +* @par 依赖: +* @li hi_mem.h:Describes memory APIs.CNcomment:文件用于描述内存相关接口。CNend +* @see hi_malloc。 +*/ +hi_void hi_free(hi_u32 mod_id, const hi_pvoid addr); + +/** +* @ingroup iot_mem +* @brief Obtains the memory information.CNcomment:获取内存信息。CNend +* +* @par 描述: +* Obtains the memory information.CNcomment:获取内存信息。CNend +* +* @attention None +* @param mem_inf [OUT] type #hi_mdm_mem_info*,Overall memory information.CNcomment:整体内存信息。CNend +* +* @retval #0 Success. +* @retval #Other Failure, for details, see hi_errno.h +* @par 依赖: +* @li hi_mem.h:Describes memory APIs.CNcomment:文件用于描述内存相关接口。CNend +* @see None +*/ +hi_u32 hi_mem_get_sys_info(HI_OUT hi_mdm_mem_info *mem_inf); + +/** +* @ingroup iot_mem +* @brief Obtains memory information, used in a crash process. +CNcomment:获取内存信息,死机流程中使用。CNend +* +* @par 描述: +* Obtains memory information, used in a crash process. When the board is reset due to a memory exception, +* if hi_mem_get_sys_info is used to obtain memory information, another exception may occur. In this case, +* use hi_mem_get_sys_info_crash instead.CNcomment:获取内存信息,死机流程中使用。当内存异常导致单板复位时, +如果通过hi_mem_get_sys_info获取内存信息可能再次产生异常,此时应该使用hi_mem_get_sys_info_crash。CNend +* +* @attention None +* +* @retval #hi_mem_pool_crash_info Memory information.CNcomment:内存信息。CNend +* +* @par 依赖: +* @li hi_mem.h:Describes memory APIs.CNcomment:文件用于描述内存相关接口。CNend +* @see None +*/ +HI_CONST hi_mem_pool_crash_info *hi_mem_get_sys_info_crash(hi_void); + +#endif diff --git a/sdk_liteos/include/hi_msg.h b/sdk_liteos/include/hi_msg.h new file mode 100644 index 0000000000000000000000000000000000000000..87998c32f186f226d380418925fac2c54aba4336 --- /dev/null +++ b/sdk_liteos/include/hi_msg.h @@ -0,0 +1,266 @@ +/** +* @file hi_msg.h +* +* Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. \n +* +* Description: message APIs.CNcomment:消息接口。CNend +* @li Wait message: the wait message API cannot be called, to avoid uncontrollable exception scheduling. +CNcomment:等待消息:在中断、关中断、锁任务上下文禁止调用等待消息接口,进而产生不可控的异常调度。CNend +* @li TX message: In the interrupt off context, the message TX API cannot be called, to avoid uncontrollable exception +* scheduling.CNcomment:发送消息:在关中断上下文禁止调用发送消息接口,进而产生不可控的异常调度。CNend +* @li TX message (the timeout period is not 0): In the interrupt and task locked context, the message TX API cannot be +* called, to avoid uncontrollable exception scheduling.CNcomment:发送消息(超时时间非0):在中断、锁任务上下文禁止调用 +超时时间非0发送消息接口,进而产生不可控的异常调度。CNend \n +*/ + +/** + * @defgroup iot_msgqueue Message Queue + * @ingroup osa + */ +#ifndef __HI_MSG_H__ +#define __HI_MSG_H__ +#include + +/** + * @ingroup iot_msgqueue + * + * Failed to read the message queue.CNcomment:读取消息队列出错。CNend + */ +#define HI_MSG_INVALID_MSG_NUM 0xFFFFFFFF +#define HI_SYS_MSG_PARAM_NUM_MAX 4 + +typedef struct { + hi_u32 msg_id; /* < Message ID.CNcomment:消息ID CNend */ + uintptr_t param[HI_SYS_MSG_PARAM_NUM_MAX]; /* < Message parameter.CNcomment:消息参数 CNend */ +} hi_sys_queue_msg; + +/** +* @ingroup iot_msgqueue +* @brief Creates a message queue.CNcomment:创建消息队列。CNend +* +* @par 描述: +* Creates a message queue.CNcomment:创建消息队列。CNend +* +* @attention The number of message queues supported by the system needs to be set during initialization. +CNcomment:系统支持的总消息队列个数,需要在初始化阶段设置。CNend +* +* @param id [OUT] type #hi_u32*,Handle of the created message queue. +CNcomment:所创建的消息队列句柄。CNend +* @param queue_len [IN] type #hi_u16,Message queue length, that is, the number of messages that can be stored +* in the message queue.CNcomment:消息队列长度,即该消息队列支持存储多少条消息。CNend +* @param msg_size [IN] type #hi_u32,Size of each message in the message queue (unit: byte) +CNcomment:消息队列中一条消息大小(单位:byte)。CNend +* +* @retval #HI_ERR_SUCCESS Success +* @retval #HI_ERR_MSG_INVALID_PARAM An input argument is incorrect, the handle pointer is null, the name address is +* null, or the message queue length is 0.CNcomment:入参错误、句柄指针为空、名字地址为空、消息队列长度为0。CNend +* @retval #HI_ERR_MSG_CREATE_Q_FAIL An error occurred when creating the message queue, for example, insufficient +* memory or insufficient message queue resources. +CNcomment:创建消息队列错误,比如:内存不足、消息队列资源不足。CNend +* @par 依赖: +* @li hi_msg.h:Describes message queue APIs.CNcomment:文件用于描述消息队列相关接口。CNend +* @li hi_config.h:Describes the message queue configuration.CNcomment:文件用于消息队列配置。CNend +* @li hi_errno.h:Describes file configuration error codes.CNcomment:文件配置错误码。CNend +* @see hi_msg_queue_delete。 +*/ +hi_u32 hi_msg_queue_create(HI_OUT hi_u32 *id, hi_u16 queue_len, hi_u32 msg_size); + +/** +* @ingroup iot_msgqueue +* @brief Deletes a message queue.CNcomment:删除消息队列。CNend +* +* @par 描述: +* Deletes a message queue.CNcomment:删除消息队列。CNend +* +* @attention None +* @param id [IN] type #hi_u32,Handle of the created message queue.CNcomment:消息队列句柄。CNend +* +* @retval #HI_ERR_SUCCESS Success +* @retval #HI_ERR_MSG_Q_DELETE_FAIL An error occurred with the message queue, for example, the ID is out of +* range, the message queue is not created, or the message queue is in use.CNcomment:删除消息队列错误, +比如:ID越界、消息队列未创建、消息队列正在使用中无法删除等。CNend +* @par 依赖: +* @li hi_msg.h:Describes message queue APIs.CNcomment:文件用于描述消息队列相关接口。CNend +* @li hi_config.h:Describes the message queue configuration.CNcomment:文件用于消息队列配置。CNend +* @li hi_errno.h:Describes file configuration error codes.CNcomment:文件配置错误码。CNend + @see hi_msg_queue_create。 +*/ +hi_u32 hi_msg_queue_delete(hi_u32 id); + +/** +* @ingroup iot_msgqueue +* @brief Sends a message.CNcomment:发送消息。CNend +* +* @par 描述: +* Sends a message.发送消息。CNend +* +* @attention None +* @param id [IN] type #hi_u32,Message queue handle.CNcomment:消息队列句柄。CNend +* @param msg [IN] type #hi_pvoid,Message content pointer.CNcomment:消息内容指针。CNend +* @param timeout_ms [IN] type #hi_u32,Timeout period for sending a message. The value 0 indicates +* that the message is sent immediately.CNcomment:消息发送的最大超时时间(单位:ms), +立即发送时写0。CNend +* @param msg_size [IN] type #hi_u32,Size of the sent message (unit: byte). +CNcomment:发送消息大小(单位:byte)。CNend +* +* @retval #HI_ERR_SUCCESS Success. +* @retval #HI_ERR_MSG_SEND_FAIL An error occurs with the message queue, for example, an input argument is +* incorrect, the message queue is not created, the size of the sent data is +* greater than the configured size when the queue is created, or the API is +* used in an interrupt but the timeout period is not 0. +CNcomment:发送消息队列错误,包括:入参错误、消息队列未创建、发送数据大于队列创建时设置大小、 +中断中使用但超时时间不为0。CNend +* +* @retval #HI_ERR_MSG_INVALID_PARAM An input argument is incorrect or the message queue pointer is null. +CNcomment:入参错误、消息队列指针为空。CNend +* +* @par 依赖: +* @li hi_msg.h:Describes message queue APIs.CNcomment:文件用于描述消息队列相关接口。CNend +* @li hi_config.h:Describes the message queue configuration.CNcomment:文件用于消息队列配置。CNend +* @li hi_errno.h:Describes file configuration error codes.CNcomment:文件配置错误码。CNend +* @see hi_msg_queue_wait。 +*/ +hi_u32 hi_msg_queue_send(hi_u32 id, hi_pvoid msg, hi_u32 timeout_ms, hi_u32 msg_size); + +/** +* @ingroup iot_msgqueue +* @brief Receives a message.CNcomment:接收消息。CNend +* +* @par 描述: +* Receives a message.CNcomment:接收消息。CNend +* +* @attention None +* @param id [IN] type #hi_u32,Message queue handle.CNcomment:消息队列句柄。CNend +* @param msg [OUT] type #hi_pvoid,Message content pointer.CNcomment:消息内容指针。CNend +* @param timeout_ms [IN] type #hi_u32,Timeout period for receiving a message. The value #HI_SYS_WAIT_FOREVER +* indicates permanent wait.CNcomment:消息接收超时时间(单位:ms), +如果表示永久等待使用#HI_SYS_WAIT_FOREVER。CNend +* @param msg_size [IN] type #hi_u32*,Expected message length (unit: byte),if wait msg success, this val will fill +with actually size of msg. +CNcomment:输入期望的消息长度(单位:byte),如果等待消息成功,该值将被赋值为实际接收到的消息长度。CNend +* +* @retval #HI_ERR_SUCCESS Success.CNcomment:消息接收成功。CNend +* @retval #HI_ERR_MSG_WAIT_FAIL An error occurs with the message queue, for example, an input argument is incorrect, +* the message queue is not created, the size of the waiting message is smaller than +* the size set when the queue is created, or the API is used in an interrupt but the +* timeout period is not 0.CNcomment:等待消息队列错误,比如:入参不正确、消息队列未 +创建、等待消息大小小于队列创建时设置大小、中断中等待超时非零的消息队列。CNend +* @retval #HI_ERR_MSG_INVALID_PARAM An input argument is incorrect or the message queue pointer is null. +CNcomment:入参错误、消息队列指针为空。CNend +* @retval #HI_ERR_MSG_WAIT_TIME_OUT No message is received when the waiting times out. +CNcomment:等待超时未收到消息。CNend +* @par 依赖: +* @li hi_msg.h:Describes message queue APIs.CNcomment:文件用于描述消息队列相关接口。CNend +* @li hi_config.h:Describes the message queue configuration.CNcomment:文件用于消息队列配置。CNend +* @li hi_errno.h:Describes file configuration error codes.CNcomment:文件配置错误码。CNend +* @see hi_msg_queue_send。 +*/ +hi_u32 hi_msg_queue_wait(hi_u32 id, HI_OUT hi_pvoid msg, hi_u32 timeout_ms, hi_u32* msg_size); + +/** +* @ingroup iot_msgqueue +* @brief Checks whether the message queue is full.CNcomment:检查消息队列是否已满。CNend +* +* @par 描述: +* Checks whether the message queue is full.CNcomment:检查消息队列是否已满。CNend +* +* @attention None +* @param id [IN] type #hi_u32,Message queue handle.CNcomment:消息队列句柄。CNend +* +* @retval #HI_TRUE The message queue is full or the message queue information fails to be obtained. +CNcomment:消息队列已满或获取消息队列信息失败。CNend +* @retval #HI_FALSE The message queue is not full.CNcomment:消息队列未满。CNend +* @par 依赖: +* @li hi_msg.h:Describes message queue APIs.CNcomment:文件用于描述消息队列相关接口。CNend +* @see None +*/ +hi_bool hi_msg_queue_is_full(hi_u32 id); + +/** +* @ingroup iot_msgqueue +* @brief Obtains the number of used message queues.CNcomment:获取当前已经使用的消息队列个数。CNend +* +* @par 描述: +* Obtains the number of used message queues.CNcomment:获取当前已经使用的消息队列个数。CNend +* +* @attention None +* @param id [IN] #hi_u32,Handle of the created message queue.CNcomment:消息队列句柄。CNend +* +* @retval #HI_ERR_MSG_INVALID_MSG_NUM Failed to read the message queue.CNcomment:读取消息队列出错。CNend +* @retval value Number of used message queues.CNcomment:消息队列使用个数。CNend +* @par 依赖: +* @li hi_msg.h:Describes message queue APIs.CNcomment:文件用于描述消息队列相关接口。CNend +* @see None +*/ +hi_u32 hi_msg_queue_get_msg_num(hi_u32 id); + +/** +* @ingroup iot_msgqueue +* @brief Obtains the number of message queues.CNcomment:获取消息队列总个数。CNend +* +* @par 描述: +* Obtains the number of message queues.CNcomment:获取消息队列总个数。CNend +* +* @attention None +* @param id [IN] #hi_u32,Handle of the created message queue.CNcomment:消息队列句柄。CNend +* +* @retval #HI_ERR_MSG_INVALID_MSG_NUM An error occurs with the message queue. For example: An input argument is +* incorrect, or the message queue is not created. +CNcomment:读取消息队列出错、入参错误、消息队列未创建。CNend +* @retval value Number of message queues.CNcomment:消息队列总个数。CNend +* @par 依赖: +* @li hi_msg.h:Describes message queue APIs.CNcomment:文件用于描述消息队列相关接口。CNend +* @see None +*/ +hi_u32 hi_msg_queue_get_msg_total(hi_u32 id); + + +/** +* @ingroup iot_msgqueue +* @brief Send a message to the head of the queue.发送消息到队列头。Nend +* +* @par 描述: +* Send a message to the head of the queue.发送消息到队列头。CNend +* +* @attention None +* @param id [IN] type #hi_u32,Message queue handle.CNcomment:消息队列句柄。CNend +* @param msg [IN] type #hi_pvoid,Message content pointer.CNcomment:消息内容指针。CNend +* @param timeout_ms [IN] type #hi_u32,Timeout period for sending a message. The value 0 indicates +* that the message is sent immediately.CNcomment:消息发送的最大超时时间(单位:ms), +立即发送时写0。CNend +* @param msg_size [IN] type #hi_u32,Size of the sent message (unit: byte). +CNcomment:发送消息大小(单位:byte)。CNend +* +* @retval #HI_ERR_SUCCESS Success. +* @retval #HI_ERR_MSG_SEND_FAIL An error occurs with the message queue, for example, an input argument is +* incorrect, the message queue is not created, the size of the sent data is +* greater than the configured size when the queue is created, or the API is +* used in an interrupt but the timeout period is not 0. +CNcomment:发送消息队列错误,包括:入参错误、消息队列未创建、发送数据大于队列创建时设置大小、 +中断中使用但超时时间不为0。CNend +* +* @retval #HI_ERR_MSG_INVALID_PARAM An input argument is incorrect or the message queue pointer is null. +CNcomment:入参错误、消息队列指针为空。CNend +* +* @par 依赖: +* @li hi_msg.h:Describes message queue APIs.CNcomment:文件用于描述消息队列相关接口。CNend +* @li hi_config.h:Describes the message queue configuration.CNcomment:文件用于消息队列配置。CNend +* @li hi_errno.h:Describes file configuration error codes.CNcomment:文件配置错误码。CNend +* @see hi_msg_queue_wait。 +*/ +hi_u32 hi_msg_queue_send_msg_to_front(hi_u32 id, hi_pvoid msg, hi_u32 msg_size, hi_u32 timeout_ms); + + +#endif + diff --git a/sdk_liteos/include/hi_mux.h b/sdk_liteos/include/hi_mux.h new file mode 100644 index 0000000000000000000000000000000000000000..faaac4900c96169cc1cfc3a11569c188883337e9 --- /dev/null +++ b/sdk_liteos/include/hi_mux.h @@ -0,0 +1,104 @@ +/** + * @file hi_mux.h + * + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @defgroup iot_mux Mutex + * @ingroup osa + */ + +#ifndef __HI_MUX_H__ +#define __HI_MUX_H__ +#include + +/** +* @ingroup iot_mux +* @brief Creates a mutex.CNcomment:创建互斥锁。CNend +* +* @par 描述: +* Creates a mutex.CNcomment:创建互斥锁。CNend +* +* @attention None +* @param mux_id [OUT] type #hi_u32*,Mutex handle.CNcomment:互斥锁句柄。CNend +* +* @retval #0 Success +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_mux.h:Describes mutex APIs.CNcomment:文件用于描述互斥锁相关接口。CNend +* @see hi_mux_delete。 +*/ +hi_u32 hi_mux_create (hi_u32 *mux_id); + +/** +* @ingroup iot_mux +* @brief Deletes a mutex.CNcomment:删除互斥锁。CNend +* +* @par 描述: +* Deletes a mutex.CNcomment:删除互斥锁。CNend +* +* @attention None +* +* @param mux_id [IN] type #hi_u32,Mutex handle.CNcomment:互斥锁句柄。CNend +* +* @retval #0 Success +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_mux.h:Describes mutex APIs.CNcomment:文件用于描述互斥锁相关接口。CNend +* @see hi_mux_create。 +*/ +hi_u32 hi_mux_delete(hi_u32 mux_id); + +/** +* @ingroup iot_mux +* @brief Waits for a mutex.CNcomment:等待互斥锁。CNend +* +* @par 描述: +* Waits for a mutex.CNcomment:等待互斥锁。CNend +* +* @attention Mutexes support priority inversion.CNcomment:互斥锁支持优先级翻转。CNend +* @param mux_id [IN] type #hi_u32,Mutex handle.CNcomment:互斥锁句柄。CNend +* @param timeout_ms [IN] type #hi_u32,Timeout period (unit: ms). HI_SYS_WAIT_FOREVER indicates permanent waiting. +CNcomment:超时时间(单位:ms)。HI_SYS_WAIT_FOREVER为永久等待。CNend +* +* @retval #0 Success +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_mux.h:Describes mutex APIs.CNcomment:文件用于描述互斥锁相关接口。CNend +* @see hi_mux_post。 +*/ +hi_u32 hi_mux_pend(hi_u32 mux_id, hi_u32 timeout_ms); + +/** +* @ingroup iot_mux +* @brief Releases a mutex.CNcomment:释放互斥锁。CNend +* +* @par 描述: +* Releases a mutex.CNcomment:释放互斥锁。CNend +* +* @attention A mutex can be released only in the task that has obtained the mutex. +CNcomment:互斥锁只能在获取到互斥锁的任务中释放。CNend +* +* @param mux_id [IN] type #hi_u32,Mutex handle.CNcomment:互斥锁句柄。CNend +* +* @retval #0 Success +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_mux.h:Describes mutex APIs.CNcomment:文件用于描述互斥锁相关接口。CNend +* @see hi_mux_pend。 +*/ +hi_u32 hi_mux_post(hi_u32 mux_id); + +#endif diff --git a/sdk_liteos/include/hi_net_api.h b/sdk_liteos/include/hi_net_api.h new file mode 100644 index 0000000000000000000000000000000000000000..e802d86af638657df5d5f6d203ee3d4cae6d5b2d --- /dev/null +++ b/sdk_liteos/include/hi_net_api.h @@ -0,0 +1,934 @@ +/** + * @file hi_net_api.h + * + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @defgroup hi_net Lwip API + */ +/** + * @defgroup hi_net_basic Lwip Basic Interface + * @ingroup hi_net + */ + +#ifndef __HI_NET_API_H__ +#define __HI_NET_API_H__ + +#include +#include +#include + +#ifdef __cplusplus +extern "C" +{ +#endif + +typedef unsigned char u8_t; +typedef unsigned short u16_t; +typedef unsigned int u32_t; +typedef int err_t; + +#ifndef LWIP_TIMEVAL_PRIVATE +#define LWIP_TIMEVAL_PRIVATE 0 +#endif + +/** + * @ingroup hi_net_basic + * + * max length of INET ADDRESS.CNcomment:INET最大的字符串长度。CNend + */ +#define INET_ADDRSTRLEN 16 + +/** + * @ingroup hi_net_basic + * + * max num of FD.CNcomment:最大的描述符个数。CNend + */ +#define FD_SETSIZE_MAX 1024 + +#define EPERM 1 /* Operation not permitted */ +#define ENOENT 2 /* No such file or directory */ +#define ESRCH 3 /* No such process */ +#define EINTR 4 /* Interrupted system call */ +#define EIO 5 /* I/O error */ +#define ENXIO 6 /* No such device or address */ +#define E2BIG 7 /* Arg list too long */ +#define ENOEXEC 8 /* Exec format error */ +#define EBADF 9 /* Bad file number */ +#define ECHILD 10 /* No child processes */ +#define EAGAIN 11 /* Try again */ +#define ENOMEM 12 /* Out of memory */ +#define EACCES 13 /* Permission denied */ +#define EFAULT 14 /* Bad address */ +#define ENOTBLK 15 /* Block device required */ +#define EBUSY 16 /* Device or resource busy */ +#define EEXIST 17 /* File exists */ +#define EXDEV 18 /* Cross-device link */ +#define ENODEV 19 /* No such device */ +#define ENOTDIR 20 /* Not a directory */ +#define EISDIR 21 /* Is a directory */ +#define ENFILE 23 /* File table overflow */ +#define EMFILE 24 /* Too many open files */ +#define ENOTTY 25 /* Not a typewriter */ +#define ETXTBSY 26 /* Text file busy */ +#define EFBIG 27 /* File too large */ +#define ENOSPC 28 /* No space left on device */ +#define ESPIPE 29 /* Illegal seek */ +#define EROFS 30 /* Read-only file system */ +#define EMLINK 31 /* Too many links */ +#define EPIPE 32 /* Broken pipe */ +#define EDOM 33 /* Math argument out of domain of func */ +#define EDEADLK 35 /* Resource deadlock would occur */ +#define ENAMETOOLONG 36 /* File name too long */ +#define ENOLCK 37 /* No record locks available */ +#define ENOSYS 38 /* Function not implemented */ +#define ENOTEMPTY 39 /* Directory not empty */ +#define ELOOP 40 /* Too many symbolic links encountered */ +#define EWOULDBLOCK EAGAIN /* Operation would block */ +#define ENOMSG 42 /* No message of desired type */ +#define EIDRM 43 /* Identifier removed */ +#define ECHRNG 44 /* Channel number out of range */ +#define EL2NSYNC 45 /* Level 2 not synchronized */ +#define EL3HLT 46 /* Level 3 halted */ +#define EL3RST 47 /* Level 3 reset */ +#define ELNRNG 48 /* Link number out of range */ +#define EUNATCH 49 /* Protocol driver not attached */ +#define ENOCSI 50 /* No CSI structure available */ +#define EL2HLT 51 /* Level 2 halted */ +#define EBADE 52 /* Invalid exchange */ +#define EBADR 53 /* Invalid request descriptor */ +#define EXFULL 54 /* Exchange full */ +#define ENOANO 55 /* No anode */ +#define EBADRQC 56 /* Invalid request code */ +#define EBADSLT 57 /* Invalid slot */ +#define EDEADLOCK EDEADLK +#define EBFONT 59 /* Bad font file format */ +#define ENOSTR 60 /* Device not a stream */ +#define ENODATA 61 /* No data available */ +#define ETIME 62 /* Timer expired */ +#define ENOSR 63 /* Out of streams resources */ +#define ENONET 64 /* Machine is not on the network */ +#define ENOPKG 65 /* Package not installed */ +#define EREMOTE 66 /* Object is remote */ +#define ENOLINK 67 /* Link has been severed */ +#define EADV 68 /* Advertise error */ +#define ESRMNT 69 /* Srmount error */ +#define ECOMM 70 /* Communication error on send */ +#define EPROTO 71 /* Protocol error */ +#define EMULTIHOP 72 /* Multihop attempted */ +#define EDOTDOT 73 /* RFS specific error */ +#define EBADMSG 74 /* Not a data message */ +#define EOVERFLOW 75 /* Value too large for defined data type */ +#define ENOTUNIQ 76 /* Name not unique on network */ +#define EBADFD 77 /* File descriptor in bad state */ +#define EREMCHG 78 /* Remote address changed */ +#define ELIBACC 79 /* Can not access a needed shared library */ +#define ELIBBAD 80 /* Accessing a corrupted shared library */ +#define ELIBSCN 81 /* .lib section in a.out corrupted */ +#define ELIBMAX 82 /* Attempting to link in too many shared libraries */ +#define ELIBEXEC 83 /* Cannot exec a shared library directly */ +#define EILSEQ 84 /* Illegal byte sequence */ +#define ERESTART 85 /* Interrupted system call should be restarted */ +#define ESTRPIPE 86 /* Streams pipe error */ +#define EUSERS 87 /* Too many users */ +#define ENOTSOCK 88 /* Socket operation on non-socket */ +#define EDESTADDRREQ 89 /* Destination address required */ +#define EMSGSIZE 90 /* Message too long */ +#define EPROTOTYPE 91 /* Protocol wrong type for socket */ +#define ENOPROTOOPT 92 /* Protocol not available */ +#define EPROTONOSUPPORT 93 /* Protocol not supported */ +#define ESOCKTNOSUPPORT 94 /* Socket type not supported */ +#define EOPNOTSUPP 95 /* Operation not supported on transport endpoint */ +#define EPFNOSUPPORT 96 /* Protocol family not supported */ +#define EAFNOSUPPORT 97 /* Address family not supported by protocol */ +#define EADDRINUSE 98 /* Address already in use */ +#define EADDRNOTAVAIL 99 /* Cannot assign requested address */ +#define ENETDOWN 100 /* Network is down */ +#define ENETUNREACH 101 /* Network is unreachable */ +#define ENETRESET 102 /* Network dropped connection because of reset */ +#define ECONNABORTED 103 /* Software caused connection abort */ +#define ECONNRESET 104 /* Connection reset by peer */ +#define ENOBUFS 105 /* No buffer space available */ +#define EISCONN 106 /* Transport endpoint is already connected */ +#define ENOTCONN 107 /* Transport endpoint is not connected */ +#define ESHUTDOWN 108 /* Cannot send after transport endpoint shutdown */ +#define ETOOMANYREFS 109 /* Too many references: cannot splice */ +#define ETIMEDOUT 110 /* Connection timed out */ +#define ECONNREFUSED 111 /* Connection refused */ +#define EHOSTDOWN 112 /* Host is down */ +#define EHOSTUNREACH 113 /* No route to host */ +#define EALREADY 114 /* Operation already in progress */ +#define EINPROGRESS 115 /* Operation now in progress */ +#define ESTALE 116 /* Stale NFS file handle */ +#define EUCLEAN 117 /* Structure needs cleaning */ +#define ENOTNAM 118 /* Not a XENIX named type file */ +#define ENAVAIL 119 /* No XENIX semaphores available */ +#define EISNAM 120 /* Is a named type file */ +#define EREMOTEIO 121 /* Remote I/O error */ +#define EDQUOT 122 /* Quota exceeded */ +#define ENOMEDIUM 123 /* No medium found */ +#define EMEDIUMTYPE 124 /* Wrong medium type */ + +#define SOCK_STREAM 1 +#define SOCK_DGRAM 2 +#define SOCK_RAW 3 + +#define AF_UNSPEC 0 +#define AF_INET 2 +#define AF_INET6 AF_UNSPEC +#define PF_INET AF_INET +#define PF_INET6 AF_INET6 +#define PF_UNSPEC AF_UNSPEC + +#define IPPROTO_IP 0 +#define IPPROTO_TCP 6 +#define IPPROTO_UDP 17 +#define IPPROTO_UDPLITE 136 + +#define MSG_PEEK 0x02 +#define MSG_WAITALL 0x100 +#define MSG_OOB 0x01 +#define MSG_DONTWAIT 0x40 +#define MSG_MORE 0x8000 + +#define SOL_SOCKET 1 +#define SO_REUSEADDR 2 +#define SO_TYPE 3 +#define SO_ERROR 4 +#define SO_BROADCAST 6 +#define SO_SNDBUF 7 +#define SO_RCVBUF 8 +#define SO_KEEPALIVE 9 +#define SO_NO_CHECK 11 +#define SO_SNDLOWAT 19 +#define SO_RCVLOWAT 18 +#define SO_SNDTIMEO 67 +#define SO_RCVTIMEO 66 +#define SO_CONTIMEO 0x1009 + + +#ifndef O_NONBLOCK +#define O_NONBLOCK 00004000 +#endif + +#ifndef O_NDELAY +#define O_NDELAY O_NONBLOCK +#endif + +#ifndef F_GETFL +#define F_GETFL 3 +#endif +#ifndef F_SETFL +#define F_SETFL 4 +#endif + +#define IP_MULTICAST_TTL 5 +#define IP_MULTICAST_IF 6 +#define IP_MULTICAST_LOOP 7 +#define IP_ADD_MEMBERSHIP 35 +#define IP_DROP_MEMBERSHIP 36 + +#define IPADDR_NONE ((u32_t)0xffffffffUL) +#define IPADDR_ANY ((u32_t)0x00000000UL) +#define INADDR_ANY IPADDR_ANY + +#define ip4_addr1(ipaddr) (((u8_t*)(ipaddr))[0]) +#define ip4_addr2(ipaddr) (((u8_t*)(ipaddr))[1]) +#define ip4_addr3(ipaddr) (((u8_t*)(ipaddr))[2]) +#define ip4_addr4(ipaddr) (((u8_t*)(ipaddr))[3]) + +#define ip4_addr1_16(ipaddr) ((u16_t)ip4_addr1(ipaddr)) +#define ip4_addr2_16(ipaddr) ((u16_t)ip4_addr2(ipaddr)) +#define ip4_addr3_16(ipaddr) ((u16_t)ip4_addr3(ipaddr)) +#define ip4_addr4_16(ipaddr) ((u16_t)ip4_addr4(ipaddr)) + +/** + * @ingroup hi_net_basic + * + * host Host byte order converted to network byte order.CNcomment:主机序转为网络序。CNend + */ +#define LWIP_PLATFORM_HTONS(_n) ((u16_t)((((_n) & 0xff) << 8) | (((_n) >> 8) & 0xff))) + +/** + * @ingroup hi_net_basic + * + * network bytehost order converted to Host byte order.CNcomment:网络序转为主机序。CNend + */ +#define LWIP_PLATFORM_HTONL(_n) ((u32_t)((((_n) & 0xff) << 24) | (((_n) & 0xff00) << 8) | \ + (((_n) >> 8) & 0xff00) | (((_n) >> 24) & 0xff))) + +/** + * @ingroup hi_net_basic + * + * set ip addr for four address.CNcomment:根据ip四段地址设置相应的值。CNend + */ +#define IP4_ADDR(ipaddr, a, b, c, d) \ + (ipaddr)->addr = ((u32_t)((d) & 0xff) << 24) | \ + ((u32_t)((c) & 0xff) << 16) | \ + ((u32_t)((b) & 0xff) << 8) | \ + (u32_t)((a) & 0xff) + +/***************************************************************************** +* 8、LWIP协议栈bsd socket htons/ntohs/ntohl转换 +*****************************************************************************/ +#define htons(x) lwip_htons(x) +#define ntohs(x) lwip_ntohs(x) +#define htonl(x) lwip_htonl(x) +#define ntohl(x) lwip_ntohl(x) + +#define lwip_htons(x) LWIP_PLATFORM_HTONS(x) +#define lwip_ntohs(x) LWIP_PLATFORM_HTONS(x) +#define lwip_htonl(x) LWIP_PLATFORM_HTONL(x) +#define lwip_ntohl(x) LWIP_PLATFORM_HTONL(x) + +/** +* @ingroup hi_net_basic +* @brief Point to decimal.CNcomment:ip地址点分制转为十进制CNend +* +* @par Description: +* Point to decimal.CNcomment:ip地址点分制转为十进制CNend +* +* @attention cp cannot be empty. CNcomment:传入字符串不能为空CNend +* @param the ip addr in string CNcomment:字符串ip地址CNend +* @retval #IPADDR Execute successfully. +* @retval #IPADDR_NONE Execute failed. +* @par NA: +* NA +* @see NULL + +*/ +u32_t ipaddr_addr(const char *cp); +#define inet_addr(cp) ipaddr_addr(cp) + +#if !defined(in_addr_t) && !defined(IN_ADDR_T_DEFINED) +#ifndef _IN_ADDR_T_DECLARED +typedef u32_t in_addr_t; +#define _IN_ADDR_T_DECLARED +#endif +#endif + +#if !defined(sa_family_t) && !defined(SA_FAMILY_T_DEFINED) +typedef u16_t sa_family_t; +#endif + +#if !defined(in_port_t) && !defined(IN_PORT_T_DEFINED) +typedef u16_t in_port_t; +#endif + +#if !defined(socklen_t) && !defined(SOCKLEN_T_DEFINED) +typedef u32_t socklen_t; +#endif + +/** + * @ingroup hi_net_basic + * + * ip address in decimal.CNcomment:十进制ip地址CNend + * + */ +struct ip_addr { + u32_t addr; +}; + +/** + * @ingroup hi_net_basic + * + * Package structure ip_addr_t to in_addr.CNcomment:封装结构体in_addr_t到in_addrCNend + * + */ +struct in_addr { + in_addr_t s_addr; +}; + +/** + * @ingroup hi_net_basic + * + * Address form of socket in Internet Environment.CNcomment:internet环境下套接字的地址形式CNend + * + */ +struct sockaddr_in { + sa_family_t sin_family; + in_port_t sin_port; + struct in_addr sin_addr; +#define SIN_ZERO_LEN 8 + char sin_zero[SIN_ZERO_LEN]; +}; + +/** + * @ingroup hi_net_basic + * + * General socket address.CNcomment:通用的套接字地址CNend + * + */ +struct sockaddr { + sa_family_t sa_family; +#define SA_DATA_LEN 14 + char sa_data[SA_DATA_LEN]; +}; + +/** + * @ingroup hi_net_basic + * + * Multicast address and interface.CNcomment:多播地址和接口CNend + * + */ +typedef struct ip_mreq { + struct in_addr imr_multiaddr; + struct in_addr imr_interface; +} ip_mreq; + +/** + * @ingroup hi_net_basic + * + * IPv4 address.CNcomment:ipv4的地址CNend + * + */ +struct ip4_addr { + u32_t addr; +}; +typedef struct ip4_addr ip4_addr_t; +typedef ip4_addr_t ip_addr_t; + +/** +* @ingroup hi_net_basic +* @brief Network byte order IP address converted to dotted decimal format. +* CNcomment:网络字节序的IP地址转化为点分十进制格式CNend +* +* @par Description: +* Address translation.CNcomment:地址转换CNend +* +* @attention NULL +* @param cp [IN] Type #ip4_addr_t *, Network byte order IP address.CNcomment:点分十进制格式的IP地址CNend +* @param addr [IN] Type #const char *, length of device name.CNcomment:点分十进制ip地址CNend +* +* @retval #1 Excute successfully +* @retval #0 Excute failure +* @par NULL +* +* @see NULL + +*/ +int ip4addr_aton(const char *cp, ip4_addr_t *addr); +#define inet_aton(cp, addr) ip4addr_aton(cp, (ip4_addr_t*)addr) + +/** +* @ingroup hi_net_basic +* @brief Dotted decimal format IP address converted to Network byte order. +* CNcomment:点分十进制的IP地址转化为网络字节序格式CNend +* +* @par Description: +* Address translation.CNcomment:地址转换CNend +* +* @attention NULL +* @param addr [IN] Type #ip4_addr_t *, addr ip address in network order to convert.CNcomment:网络字节序ip地址CNend +* +* @retval #Not NULL Excute successfully +* @retval #NULL Excute failure +* @par NULL +* +* @see NULL + +*/ +char *ip4addr_ntoa(const ip4_addr_t *addr); +#define inet_ntoa(addr) ip4addr_ntoa((ip4_addr_t*)&(addr)) + + +typedef void (*dns_found_callback)(const char *name, ip_addr_t *ipaddr, void *callback_arg); +err_t dns_gethostbyname(const char *hostname, ip_addr_t *addr, + dns_found_callback found, void *callback_arg); + +/** + * @ingroup hi_net_basic + * + * Domain name and network address structure.CNcomment:域名和网络地址结构体CNend + * + */ +struct hostent { + char *h_name; /**< Indicates the official name of the host. */ + char **h_aliases; /**< Indicates a pointer to an array of pointers to alternative host names, + terminated by a null pointer. */ + int h_addrtype; /**< Indicates the address type. */ + int h_length; /**< Indicates the length, in bytes, of the address. */ + char **h_addr_list; /**< Indicates a pointer to an array of pointers to network addresses (in + network byte order) for the host, terminated by a null pointer. */ +#define h_addr h_addr_list[0] /* for backward compatibility */ +}; + +/** +* @ingroup hi_net_basic +* @brief Get IP address according to domain name.CNcomment:根据域名获取IP地址CNend +* +* @par Description: +* The IP address is obtained by using the domain name in string format, +* and the address information is loaded into the host domain name structure +* CNcomment:利用字符串格式的域名获得IP地址,并且将地址信息装入hostent域名结构体CNend +* +* @attention NULL +* @param name [IN] Type #const char * the hostname to resolve.CNcomment:解析的域名CNend +* +* @retval #hostent Execute successfully. +* @retval #NULL Execute failed. +* @par Dependency: +* #NULL +* @see NULL +*/ +struct hostent *gethostbyname(const char *name); + +/** + * @ingroup hi_net_basic + * + * Network interface structure.CNcomment:网络接口结构体CNend + * + */ +struct netif { +#define NETIF_DATA_LEN 8 + unsigned char data[NETIF_DATA_LEN]; +}; + +/** +* @ingroup hi_net_basic +* @brief Get the corresponding interface pointer according to the interface name. +* CNcomment:根据接口名字获取相应接口指针CNend +* +* @par Description: +* Get the corresponding interface pointer according to the interface name +* CNcomment:根据接口名字获取相应接口指针CNend +* +* @attention NULL +* @param name [IN] Type #const char * the interface name to find.CNcomment:要找的接口名字CNend +* +* @retval #struct netif * Execute successfully. +* @retval #NULL Execute failed. +* @par Dependency: +* #NULL +* @see NULL +*/ +struct netif *netif_find(const char *name); + +/** +* @ingroup hi_net_basic +* @brief Start DHCP client according to interface.CNcomment:根据接口启动dhcp客户端CNend +* +* @par Description: +* Start DHCP client according to interface +* CNcomment:根据接口启动dhcp客户端CNend +* +* @attention NULL +* @param netif [IN] Type #struct netif * Interface address.CNcomment:接口地址CNend +* +* @retval #ERR_OK Execute successfully. +* @retval #OTHERS Execute failed. +* @par Dependency: +* #NULL +* @see NULL +*/ +err_t netifapi_dhcp_start(struct netif *netif); + +/** +* @ingroup hi_net_basic +* @brief Start DHCP server according to interface.CNcomment:根据接口启动dhcp服务端CNend +* +* @par Description: +* Start DHCP server according to interface +* CNcomment:根据接口启动dhcp服务端CNend +* +* @attention NULL +* @param netif [IN] Type #struct netif * Interface address.CNcomment:接口地址CNend +* @param start_ip [IN] Type #char * Assigned client start address.CNcomment:分配的客户端起始地址CNend +* @param ip_num [IN] Type #u16_t Total number of clients assigned.CNcomment:分配的客户端总数目CNend +* @retval #ERR_OK Execute successfully. +* @retval #OTHERS Execute failed. +* @par Dependency: +* #NULL +* @see NULL + +*/ +err_t netifapi_dhcps_start(struct netif *netif, char *start_ip, u16_t ip_num); + +/** +* @ingroup hi_net_basic +* @brief This API is used to set the the vendor class identifier information +* of the netif, which is using in DHCP Message. +* CNcomment:这个API用来设置dhcp的hostname消息CNend +* +* @par Description: +* The hostname string lenght should be less than NETIF_HOSTNAME_MAX_LEN, +* otherwise the hostname will truncate to (NETIF_HOSTNAME_MAX_LEN-1). +* CNcomment:hostname的长度要小于NETIF_HOSTNAME_MAX_LEN,否则会被设置为(NETIF_HOSTNAME_MAX_LEN-1)CNend +* +* @attention NULL +* @param netif [IN] Type #struct netif * Interface address.CNcomment:接口地址CNend +* @param hostname [IN] Type #char * hostname The new hostname to use.CNcomment:传入使用的名字CNend +* @param namelen [IN] Type #u8_t The hostname string length.CNcomment:名称长度CNend +* @retval #ERR_OK Execute successfully. +* @retval #ERR_ARG: On passing invalid arguments. +* @par Dependency: +* #NULL +* @see NULL +*/ +err_t netifapi_set_hostname(struct netif *netif, char *hostname, u8_t namelen); + + +/** +* @ingroup hi_net_basic +* @brief This API is used to set the vendor class identifier information, which is used in DHCP message. +* CNcomment:设置dhcp消息的vci信息CNend +* +* @par Description: +* Length of vendor class identifier information string ,should be not more than DHCP_VCI_MAX_LEN(default 32), +* otherwise it will return with ERR_ARG. vci_len is the real length of vendor class identifier information string. +* CNcomment:vci消息长度不超过32个字节,否则会返回ERR_ARG,vci_len是厂商分类信息的真实长度CNend +* +* @attention NULL +* @param vci [IN] Type #char * The new vendor class identifier information to use.CNcomment:厂商设备信息数据CNend +* @param vci_len [IN] Type #u8_t The length of vendor class identifier information string.CNcomment:上述数据的长度CNend +* @retval #ERR_OK On success +* @retval #ERR_ARG On passing invalid arguments +* @retval #ERR_VAL On failure +* @par Dependency: +* #NULL +* @see NULL +*/ +err_t netifapi_set_vci(char *vci, u8_t vci_len); + +/** +* @ingroup hi_net_basic +* @brief allocate a socket.CNcomment:分配套接字CNend +* +* @par Description: +* It creates an endpoint for communication and returns a file descriptor +* CNcomment:为通信创建一个端点并返回一个文件描述符CNend +* +* @attention NULL +* @param domain [IN] Type #int Specifies a protocol family.CNcomment:指定协议族CNend +* @param type [IN] Type #int Specifies the socket type.CNcomment:指定协议类型CNend +* @param protocol [IN] Type #int Specifies the protocol to be used with the socket. +* CNcomment:指定要与套接字一起使用的协议CNend +* @retval #>0 Execute successfully. +* @retval #-1 Execute failed. +* @par Dependency: +* #NULL +* @see NULL +*/ +int socket(int domain, int type, int protocol); + +/** +* @ingroup hi_net_basic +* @brief bind a socket.CNcomment:绑定套接字CNend +* +* @par Description: +* It creates an endpoint for communication and returns a file descriptor +* CNcomment:为通信创建一个端点并返回一个文件描述符CNend +* +* @attention NULL +* @param s [IN] Type #int Specifies the file descriptor of the socket to be bound.CNcomment:要绑定的描述符CNend +* @param name [IN] Type #struct sockaddr * Points to a sockaddr structure containing the address +* to be bound to the socket. CNcomment:指向包含要绑定到套接字的地址的sockaddr结构CNend +* @param namelen [IN] Type #socklen_t Specifies the length of the sockaddr structure pointed to by the address argument. +* CNcomment:指定address参数指向的sockaddr结构的长度CNend +* @retval #0 Execute successfully. +* @retval #-1 Execute failed. +* @par Dependency: +* #NULL +* @see NULL +*/ +int bind(int s, const struct sockaddr *name, socklen_t namelen); + +/** +* @ingroup hi_net_basic +* @brief Get socket optional fields.CNcomment:获取套接字可选字段CNend +* +* @par Description: +* Get socket optional fields +* CNcomment:获取套接字可选字段CNend +* +* @attention NULL +* @param socket [IN] Type #int Specifies a socket file descriptor.CNcomment:指定的文件描述符CNend +* @param level [IN] Type #int Specifies the protocol level at which the option resides. +* CNcomment:指定选项所在的协议级别CNend +* @param option_name [IN] Type #int Specifies a single option to set.CNcomment:指定选项的名字CNend +* @param option_value [OUT] Type #void * Indicates the pointer to the option value.CNcomment:指示指向选项值的指针CNend +* @param option_len [IN] Type #socklen_t * Specifies the size of option value.CNcomment:指定选项的值CNend +* @retval #0 Execute successfully. +* @retval #-1 Execute failed. +* @par Dependency: +* #NULL +* @see NULL +*/ +int getsockopt(int s, int level, int optname, void *optval, socklen_t *optlen); + +/** +* @ingroup hi_net_basic +* @brief Set socket optional fields.CNcomment:设置套接字可选字段CNend +* +* @par Description: +* Set socket optional fields +* CNcomment:设置套接字可选字段CNend +* +* @attention NULL +* @param socket [IN] Type #int Specifies a socket file descriptor.CNcomment:指定的文件描述符CNend +* @param level [IN] Type #int Specifies the protocol level at which the option resides. +* CNcomment:指定选项所在的协议级别CNend +* @param option_name [IN] Type #int Specifies a single option to set.CNcomment:指定选项的名字CNend +* @param option_value [OUT] Type #void * Indicates the pointer to the option value.CNcomment:指示指向选项值的指针CNend +* @param option_len [IN] Type #socklen_t Specifies the size of option value.CNcomment:指定选项的值CNend +* @retval #0 Execute successfully. +* @retval #-1 Execute failed. +* @par Dependency: +* #NULL +* @see NULL +*/ +int setsockopt(int s, int level, int optname, const void *optval, socklen_t optlen); + +/** +* @ingroup hi_net_basic +* @brief Accepts a new connection on a socket.CNcomment:套接字上接收一个连接CNend +* +* @par Description: +* Accepts a new connection on a socket +* CNcomment:套接字上接收一个连接CNend +* +* @attention NULL +* @param socket [IN] Type #int Specifies a socket that was created with socket(),has been bound to an address +* with bind(),and has issued a successful call to listen(). +* CNcomment:指定用socket()创建的套接字,该套接字已bind()绑定,并已成功调用listen()CNend +* @param address [OUT] Type #struct sockaddr * Indicates either a null pointer, or a pointer to a sockaddr structure +* where the address of the connecting socket shall be returned. +* CNcomment:指示空指针或指向sockaddr结构的指针,其中应返回连接套接字的地址CNend +* @param address_len [IN,OUT] Type #socklen_t * Indicates either a null pointer,if address is a null pointer, +* or a pointer to a socklen_t object which on input +* specifies the length of the supplied sockaddr structure,and on output specifies +* the length of the stored address. +* CNcomment:如果地址是空指针,则指示空指针,或者指示指向socklen_t对象的指针, +* 该对象在输入时指定提供的sockaddr结构的长度,在输出时指定存储地址的长度.CNend +* @retval #>0 Execute successfully. +* @retval #-1 Execute failed. +* @par Dependency: +* #NULL +* @see NULL +*/ +int accept(int s, struct sockaddr *addr, socklen_t *addrlen); + +/** +* @ingroup hi_net_basic +* @brief Connection to peer IP address.CNcomment:连接对端IP地址CNend +* +* @par Description: +* attempt to make a connection on a connection-mode socket or to set or +* reset the peer address of a connectionless-mode socket +* CNcomment:尝试在连接模式套接字上建立连接,或设置或重置无连接模式套接字的对等地址CNend +* +* @attention NULL +* @param s [IN] Type #int Specifies a socket file descriptor.CNcomment:指定套接字CNend +* @param name [IN] Type #struct sockaddr * Specifies a pointer to the sockaddr structure +* which identifies the connection. CNcomment:指定指向sockaddr结构的指针,该结构标识连接CNend +* @param namelen [IN] Type # socklen_t Specifies the size of name structure. +* CNcomment:指定名字结构体的长度CNend +* @retval #0 Execute successfully. +* @retval #-1 Execute failed. +* @par Dependency: +* #NULL +* @see NULL +*/ +int connect(int s, const struct sockaddr *name, socklen_t namelen); + +/** +* @ingroup hi_net_basic +* @brief Recieve a message from connected socket.CNcomment:从已经连接的套接字接收消息CNend +* +* @par Description: +* Recieve a message from connected socket. +* CNcomment:从已经连接的套接字接收消息CNend +* +* @attention NULL +* @param socket [IN] Type #int Specifies the socket file descriptor.CNcomment:指定套接字CNend +* @param buffer [OUT] Type #void * Points to a buffer where the message should be stored. +* CNcomment:接收存储的缓存CNend +* @param length [IN] Type #size_t Specifies the length in bytes of the buffer pointed to by the buffer argument. +* CNcomment:每次接收的长度CNend +* @param flags [IN] Type #int Specifies the type of message reception.CNcomment:指定套接字的标志位CNend +* @retval #>0 Execute successfully. +* @retval #-1 Execute failed. +* @par Dependency: +* #NULL +* @see NULL +*/ +int recv(int s, void *mem, size_t len, int flags); + +/** +* @ingroup hi_net_basic +* @brief Recieve a message from connected socket.CNcomment:从已经连接的套接字接收消息CNend +* +* @par Description: +* Recieve a message from connected socket. +* CNcomment:从已经连接的套接字接收消息CNend +* +* @attention NULL +* @param socket [IN] Type #int Specifies the socket file descriptor.CNcomment:指定套接字CNend +* @param buffer [OUT] Type #void * Points to a buffer where the message should be stored. +* CNcomment:接收存储的缓存CNend +* @param length [IN] Type #size_t Specifies the length in bytes of the buffer pointed to +* by the buffer argument.CNcomment:每次接收的长度CNend +* @param flags [IN] Type #int Specifies the type of message reception.CNcomment:指定套接字的标志位CNend +* @param flags [IN] Type #struct sockaddr * A null pointer, or points to a sockaddr structure in which +* the sending address is to be stored. +* CNcomment:空指针,或指向要存储发送地址的sockaddr结构CNend +* @param flags [IN] Type #socklen_t * Either a null pointer, if address is a null pointer, or a pointer +* to a socklen_t objectwhich on input specifies the length of the supplied sockaddr structure, +* and on output specifies the length of the stored address. +* CNcomment:如果地址是空指针,则为空指针,或者指向socklen_t对象的指针, +* 该对象在输入时指定提供的sockaddr结构的长度,在输出时指定存储地址的长度CNend +* @retval #>0 Execute successfully. +* @retval #-1 Execute failed. +* @par Dependency: +* #NULL +* @see NULL +*/ +int recvfrom(int s, void *mem, size_t len, int flags, + struct sockaddr *from, socklen_t *fromlen); + +/** +* @ingroup hi_net_basic +* @brief Initiates transmission of a message from the specified socket to its peer.CNcomment:传输指定长度消息到对端CNend +* +* @par Description: +* Initiates transmission of a message from the specified socket to its peer +* CNcomment:启动从指定套接字到其对等端的消息传输。CNend +* +* @attention NULL +* @param socket [IN] Type #int Specifies the socket file descriptor.CNcomment:指定套接字CNend +* @param buffer [IN] Type #void * Specifies a buffer containing the message to send. +* CNcomment:指定要发送的缓存CNend +* @param length [IN] Type #size_t Specifies the length of the message to send.CNcomment:指定消息长度CNend +* @param flags [IN] Type #int Specifies the type of message reception.CNcomment:指定套接字的标志位CNend +* @retval #>0 Execute successfully. +* @retval #-1 Execute failed. +* @par Dependency: +* #NULL +* @see NULL +*/ +int send(int s, const void *dataptr, size_t size, int flags); + +/** +* @ingroup hi_net_basic +* @brief send messages from a connection-oriented and connectionless sockets. +* CNcomment:从面向连接和无连接的套接字发送消息CNend +* +* @par Description: +* If the socket is in the connectionless mode, the message is sent to the address specified by the 'to' parameter. +* +* CNcomment:如果套接字处于无连接模式,则将消息发送到“to”参数指定的地址 +* 如果套接字处于连接模式,则忽略“to”参数中的目标地址CNend +* @attention NULL +* @param socket [IN] Type #int Specifies the socket file descriptor.CNcomment:指定套接字CNend +* @param buffer [IN] Type #void * Specifies a buffer containing the message to send. +* CNcomment:指定要发送的缓存CNend +* @param length [IN] Type #size_t Specifies the length of the message to send.CNcomment:指定消息长度CNend +* @param flags [IN] Type #int Specifies the type of message reception.CNcomment:指定套接字的标志位CNend +* @param flags [IN] Type #struct sockaddr * Specifies a pointer to the sockaddr structure +* that contains the destination address. +* CNcomment:指定指向包含目标地址的sockaddr结构的指针CNend +* @param flags [IN] Type #socklen_t * Specifies the size of the 'to' structure. +* CNcomment:指定“to”结构的大小CNend +* @retval #>0 Execute successfully. +* @retval #-1 Execute failed. +* @par Dependency: +* #NULL +* @see NULL +*/ +int sendto(int s, const void *dataptr, size_t size, int flags, + const struct sockaddr *to, socklen_t tolen); + +/** +* @ingroup hi_net_basic +* @brief Allows a program to monitor multiple file descriptors.CNcomment:允许程序监视多个文件描述符CNend +* +* @par Description: +* select() can monitor only file descriptors numbers that are less than FD_SETSIZE. +* select() uses a timeout that is a struct timeval (with seconds and microseconds). +* CNcomment:select()只能监视小于FD_SETSIZE的文件描述符编号. +* select()使用的超时值是struct timeval(秒和微秒)CNend +* @attention NULL +* @param nfds [IN] Type #int Specifies a range of file descriptors.CNcomment:允许程序监视多个文件描述符CNend +* @param readfds [IN] Type #fd_set * Specifies a pointer to struct fd_set, and specifies the descriptor to +* check for being ready to read. +* CNcomment:指定struct fd_set的指针,并要检查是否准备好读取的描述符CNend +* @param writefds [IN] Type #fd_set * Specifies a pointer to struct fd_set, and specifies the descriptor +* to check for being ready to write.CNcomment: +* 指定指向struct fd_set的指针,并指定要检查是否准备好写入的描述符CNend +* @param exceptfds [IN] Type #fd_set * Specifies a pointer to struct fd_set, and specifies the descriptor +* to check for pending error conditions.CNcomment: +* 指定指向struct fd_set的指针,并指定要检查挂起错误条件的描述符CNend +* @param timeout [IN] Type #struct timeval * Specifies a pointer to struct timeval, for timeout application. +* CNcomment:为超时应用程序指定指向struct timeval的指针CNend +* @retval #>0 Execute successfully. +* @retval #-1 Execute failed. +* @par Dependency: +* #NULL +* @see NULL + +*/ +#if LWIP_TIMEVAL_PRIVATE +int select(int maxfdp1, fd_set *readset, fd_set *writeset, fd_set *exceptset, + struct timeval *timeout); +#endif +/** +* @ingroup hi_net_basic +* @brief Initiates transmission of a message from the specified socket to its peer.CNcomment:传输指定长度消息到对端CNend +* +* @par Description: +* Initiates transmission of a message from the specified socket to its peer +* CNcomment:启动从指定套接字到其对等端的消息传输。CNend +* +* @attention NULL +* @param s [IN] Type #int Indicates the socket file descriptor.CNcomment:指定文件描述符CNend +* @param cmd [IN] Type #int Indicates a command to select an operation[F_GETFL, F_SETFL]. +* CNcomment:指示选择操作的命令[F_GETFL, F_SETFL]CNend +* @param val [IN] Type #int Indicates an additional flag, to set non-blocking. +* CNcomment:指示一个附加标志,以设置非阻塞CNend +* @retval #0 Execute successfully. +* @retval #-1 & Others Execute failed. +* @par Dependency: +* #NULL +* @see NULL +*/ +int fcntl(int s, int cmd, int val); + +/** +* @ingroup hi_net_basic +* @brief Close the socket.CNcomment:关闭套接字CNend +* +* @par Description: +* If O_NONBLOCK is not set and if there is data on the module's write queue, +* close() waits for an unspecified time for any output to drain before dismantling the STREAM. +* If the O_NONBLOCK flag is set,close() does not wait for output to drain, and dismantles the STREAM immediately. +* CNcomment:如果未设置O_NONBLOCK,并且模块的写入队列中有数据,close()等待未指定的时间,等待任何输出排出,然后再拆卸流. +* 如果设置了O_NONBLOCK标志,close()不会等待输出耗尽,并立即取消流CNend +* +* @attention NULL +* @param s [IN] Type #int Indicates the socket file descriptor.CNcomment:指定文件描述符CNend +* @retval #0 Execute successfully. +* @retval #-1 & Others Execute failed. +* @par Dependency: +* #NULL +* @see NULL +*/ +int closesocket(int s); +#define close(s) closesocket(s) + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/include/hi_nv.h b/sdk_liteos/include/hi_nv.h new file mode 100644 index 0000000000000000000000000000000000000000..9b8d8c3ff44c2341fa03a14e52fe5520939eb980 --- /dev/null +++ b/sdk_liteos/include/hi_nv.h @@ -0,0 +1,290 @@ +/** + * @file hi_nv.h + * + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Description: NV items consist of the NV items in the factory partition and NV items in the normal partition. + * The NV items in the normal partition are classified into NV items in the reserved partition and + * NV items in the common partition. The values of NV items in the reserved partition won't change + * after OTA upgrade. \n + * CNcomment:NV分为工厂区NV和非工厂区NV,非工厂区NV又分为保留区和普通区,保留区升级后保留NV值。CNend + */ + +/** @defgroup iot_nv NV Management + * @ingroup system + */ +#ifndef __HI_NV_H__ +#define __HI_NV_H__ +#include + +/** +* @ingroup iot_nv +* +* Maximum length of an NV item (unit: byte). CNcomment:NV项最大长度(单位:byte)。CNend +*/ +#define HNV_ITEM_MAXLEN (256 - 4) +#define PRODUCT_CFG_NV_REG_NUM_MAX 4 + +#define HI_FNV_DEFAULT_ADDR 0x8000 +#define HI_NV_DEFAULT_TOTAL_SIZE 0x2000 +#define HI_NV_DEFAULT_BLOCK_SIZE 0x1000 + +/** +* @ingroup iot_nv +* +* Maximum number of registered hi_nv_register_change_nofity_proc functions. +CNcomment:hi_nv_register_change_nofity_proc注册函数个数最大值。CNend +*/ +#define HI_NV_CHANGED_PROC_NUM PRODUCT_CFG_NV_REG_NUM_MAX + +/** +* @ingroup iot_nv +* @brief Initialize Normal NV.CNcomment:非工厂区NV初始化。CNend +* +* @par 描述: +* Initialize Normal NV.CNcomment:非工厂区NV初始化。CNend +* +* @attention Parameters are obtained from the partition table and cannot be set randomly. +CNcomment:参数从分区表中获取,禁止随意设置。CNend +* @param addr [IN] type #hi_u32,Flash address of the normal NV partition, corresponding to the flash +* address of the member #HI_FLASH_PARTITON_NORMAL_NV in the partition table. +CNcomment:非工厂区NV的FLASH地址,对应分区表成员#HI_FLASH_PARTITON_NORMAL_NV的FLASH地址。CNend +* @param total_size [IN] type #hi_u32,total size of normal NV. +CNcomment:非工厂区NV的总大小。CNend +* @param block_size [IN] type #hi_u32,block size of normal NV. +CNcomment:非工厂区NV的块大小。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_nv.h:Describes NV APIs.CNcomment:文件用于描述NV相关接口。CNend +* @see hi_get_partition_table | hi_nv_read | hi_nv_write。 +*/ +HI_EAPI hi_u32 hi_nv_init(hi_u32 addr, hi_u32 total_size, hi_u32 block_size); + +/** +* @ingroup iot_nv +* @brief Set the normal NV value.CNcomment:设置非工厂区NV值。CNend +* +* @par 描述: +* Set the normal NV value.CNcomment:设置非工厂区NV值。CNend +* +* @attention +* @li Only a normal NV item can be operated.CNcomment:仅能操作非工厂区NV。CNend +* @li This API is called only in a task and cannot be called in an interrupt. +CNcomment:仅支持任务中调用,不支持中断中调用。CNend +* @param id [IN] type #hi_u8,NV item ID, ranging from #HI_NV_NORMAL_ID_START to #HI_NV_NORMAL_USR_ID_END. +CNcomment:NV项ID,范围从#HI_NV_NORMAL_ID_START到#HI_NV_NORMAL_USR_ID_END。CNend +* @param pdata [IN] type #const hi_pvoid,NV item data.CNcomment:NV项数据。CNend +* @param len [IN] type #hi_u8,Length of an NV item (unit: byte). The len must be equal to the Length of +the real NV item data.CNcomment:NV项长度(单位:byte)。len必须和NV项的实际长度相等。CNend +* @param flag [IN] type #hi_u32,Reserve.CNcomment:保留参数。CNend +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_nv.h:Describes NV APIs.CNcomment:文件用于描述NV相关接口。CNend +* @see hi_nv_read。 +*/ +HI_EAPI hi_u32 hi_nv_write(hi_u8 id, const hi_pvoid pdata, hi_u8 len, hi_u32 flag); + +/** +* @ingroup iot_nv +* @brief Read the normal NV value.CNcomment:读取非工厂区NV值。CNend +* +* @par 描述: +* Read the normal NV value.CNcomment:读取非工厂区NV值。CNend +* +* @attention +* @li Only a normal NV item can be operated.CNcomment:仅能操作非工厂区NV。CNend +* @li This API is called only in a task and cannot be called in an interrupt. +CNcomment:仅支持任务中调用,不支持中断中调用。CNend +* +* @param id [IN] type #hi_u8,NV item ID, ranging from #HI_NV_NORMAL_ID_START to #HI_NV_NORMAL_USR_ID_END. +CNcomment:NV项ID,范围从#HI_NV_NORMAL_ID_START到#HI_NV_NORMAL_USR_ID_END。CNend +* @param pdata [OUT] type #const hi_pvoid,NV item data.CNcomment:NV项数据。CNend +* @param len [IN] type #hi_u8,Length of an NV item (unit: byte). The len must be equal to the Length of +the real NV item data.CNcomment:NV项长度(单位:byte)。len必须和NV项的实际长度相等。CNend +* @param flag [IN] type #hi_u32,Reserve.CNcomment:保留参数。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_nv.h:Describes NV APIs.CNcomment:文件用于描述NV相关接口。CNend +* @see hi_nv_write。 +*/ +HI_EAPI hi_u32 hi_nv_read(hi_u8 id, const hi_pvoid pdata, hi_u8 len, hi_u32 flag); + +/** +* @ingroup iot_nv +* @brief NV item change callback function.CNcomment:NV项变更回调函数。CNend +* +* @par 描述: +* NV item change callback function.CNcomment:NV项变更回调函数。CNend +* +* @attention This API can be called only after the SAL is initialized. +CNcomment:在SAL初始化结束后才可以调用该接口。CNend +* +* @param id [IN] type #hi_u8,NV item ID, ranging from #HI_NV_NORMAL_ID_START to #HI_NV_NORMAL_USR_ID_END. +CNcomment:NV项ID,范围从#HI_NV_NORMAL_ID_START到#HI_NV_NORMAL_USR_ID_END。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_nv.h:Describes NV APIs.CNcomment:文件用于描述NV相关接口。CNend +* @see None +*/ +typedef hi_u32(*hi_nvm_changed_notify_f) (hi_u8 id); + +/** +* @ingroup iot_nv +* @brief Register the normal NV item change notification function.CNcomment:非工厂区NV项变更通知函数注册。CNend +* +* @par 描述: +* Register the normal NV item change notification function.CNcomment:非工厂区NV项变更通知函数注册。CNend +* +* @attention +* Only the change notification function for normal NV items can be registered. +* The maximum number of registered functions is #HI_NV_CHANGED_PROC_NUM. If the number of registered functions +* exceeds the maximum, an error code is returned. +CNcomment:仅支持非工厂NV项注册变更通知函数处理。注册个数上限为#HI_NV_CHANGED_PROC_NUM,如超过会返回错误码。CNend +* +* @param min_id [IN] type #hi_u8,Minimum value of an NV item ID.CNcomment:NV项ID最小值。CNend +* @param max_id [IN] type #hi_u8,Maximum value of an NV item ID.CNcomment:NV项ID最大值。CNend +* @param func [IN] type #hi_nvm_changed_notify_f,Handling function for NV item changes. That is, after an NV item +* is changed, the NV module automatically calls the registered API. +CNcomment:NV项改变的处理函数, 即NV项变更后,NV模块会自动调用该注册的接口。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_nv.h:Describes NV APIs.CNcomment:文件用于描述NV相关接口。CNend +* @see None +*/ +HI_EAPI hi_u32 hi_nv_register_change_notify_proc(hi_u8 min_id, hi_u8 max_id, hi_nvm_changed_notify_f func); + +/** +* @ingroup iot_nv +* @brief Initialize factory NV.CNcomment:工厂区NV初始化。CNend +* +* @par 描述: +* Initialize factory NV.CNcomment: 工厂区NV初始化。CNend +* +* @attention The parameters cannot be set randomly and must match the product delivery plan. +CNcomment:参数不能随意配置,需要与产品出厂规划匹配。CNend +* @param addr [IN] type #hi_u32,Start address of the NV factory partition in the flash. The address is planned by +* the factory and set by the macro #HI_FNV_DEFAULT_ADDR. +CNcomment:设置工厂区NV FLASH首地址,由出厂规划,宏定义HI_FNV_DEFAULT_ADDR 统一设置。CNend +* @param total_size [IN] type #hi_u32,total size of factory NV. +CNcomment:工厂区NV的总大小。CNend +* @param block_size [IN] type #hi_u32,block size of factory NV. +CNcomment:工厂区NV的块大小。CNend +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_nv.h:Describes NV APIs.CNcomment:文件用于描述NV相关接口。CNend +* @see hi_factory_nv_write | hi_factory_nv_read。 +*/ +HI_EAPI hi_u32 hi_factory_nv_init(hi_u32 addr, hi_u32 total_size, hi_u32 block_size); + +/** +* @ingroup iot_nv +* @brief Set the NV value in the factory partition. CNcomment:设置工厂区NV值。CNend +* +* @par 描述: +* Set the NV value in the factory partition.CNcomment:设置工厂区NV值。CNend +* +* @attention None +* @param id [IN] type #hi_u8,NV item ID, ranging from #HI_NV_FACTORY_ID_START to #HI_NV_FACTORY_USR_ID_END. +CNcomment:NV项ID,范围从#HI_NV_FACTORY_ID_START到#HI_NV_FACTORY_USR_ID_END。CNend +* @param pdata [IN] type #hi_pvoid,NV item data.CNcomment:NV项数据。CNend +* @param len [IN] type #hi_u8,Length of an NV item (unit: byte). The len must be equal to the Length of +the real NV item data.CNcomment:NV项长度(单位:byte)。len必须和NV项的实际长度相等。CNend +* @param flag [IN] type #hi_u32,Reserve.CNcomment:保留参数。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_nv.h:Describes NV APIs.CNcomment:文件用于描述NV相关接口。CNend +* @see hi_factory_nv_read。 +*/ +HI_EAPI hi_u32 hi_factory_nv_write(hi_u8 id, hi_pvoid pdata, hi_u8 len, hi_u32 flag); + +/** +* @ingroup iot_nv +* @brief Read the NV value in the factory partition.CNcomment:读取工厂区NV值。CNend +* +* @par 描述: +* Read the NV value in the factory partition.CNcomment:读取工厂区NV值。CNend +* +* @attention None +* +* @param id [IN] type #hi_u8,NV item ID, ranging from #HI_NV_NORMAL_ID_START to #HI_NV_NORMAL_USR_ID_END. +CNcomment:NV项ID,范围从#HI_NV_NORMAL_ID_START到#HI_NV_NORMAL_USR_ID_END。CNend +* @param pdata [OUT] type #hi_pvoid,NV item data.CNcomment:NV项数据。CNend +* @param len [IN] type #hi_u8,Length of an NV item (unit: byte). The len must be equal to the Length of +the real NV item data.CNcomment:NV项长度(单位:byte)。len必须和NV项的实际长度相等。CNend +* @param flag [IN] type #hi_u32,Reserve.CNcomment:保留参数。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_nv.h:Describes NV APIs.CNcomment:文件用于描述NV相关接口。CNend +* @see hi_factory_nv_write。 +*/ +HI_EAPI hi_u32 hi_factory_nv_read(hi_u8 id, hi_pvoid pdata, hi_u8 len, hi_u32 flag); + +/** +* @ingroup iot_nv +* @brief refresh backup nv, always used after finish factory test. +CNcomment:更新原始备份区NV,常用于产测完成后。CNend +* +* @par 描述: +* refresh backup nv, always used after finish factory test. +CNcomment:更新原始备份区NV,常用于产测完成后。CNend +* +* @attention should refresh backup nv if factory test modified nv. +CNcomment: 如果产测有修改NV参数,应该在产测完成后同步刷新备份区NV。CNend +* +* @param None +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_nv.h:Describes NV APIs.CNcomment:文件用于描述NV相关接口。CNend +*/ +HI_EAPI hi_u32 hi_nv_refresh_backup(hi_void); + +/** +* @ingroup iot_nv +* @brief restore nv by oringinal backup nv. +CNcomment: 使用原始备份NV 覆盖当前NV,常用于恢复出厂设置。CNend +* +* @par 描述: +* restore nv by oringinal backup nv. +CNcomment:使用原始备份NV 覆盖当前NV,常用于恢复出厂设置。CNend +* +* @attention should reset system after restore nv. only restore normal nv, not include factory nv. +CNcomment: 使用备份NV 覆盖原始NV后,须重启系统。 +仅覆盖工作区NV,不包括工厂区NV。CNend +* +* @param None +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_nv.h:Describes NV APIs.CNcomment:文件用于描述NV相关接口。CNend +*/ +HI_EAPI hi_u32 hi_nv_restore_by_backup(hi_void); + +#endif diff --git a/sdk_liteos/include/hi_os_stat.h b/sdk_liteos/include/hi_os_stat.h new file mode 100644 index 0000000000000000000000000000000000000000..101e717366de87a8d2e01b68e5bf901fd83f188c --- /dev/null +++ b/sdk_liteos/include/hi_os_stat.h @@ -0,0 +1,80 @@ +/** + * @file hi_os_stat.h + * + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @defgroup os_stat OS Status + * @ingroup osa + */ + +#ifndef __HI_OS_STAT_H__ +#define __HI_OS_STAT_H__ + +#include + +#define HI_OS_STAT_MSG_WAIT_FAIL 0x1 /**< Used in the interrupt context.CNcomment:中断上下文使用CNend */ +#define HI_OS_STAT_MSG_SEND_FAIL 0x2 /**< The timeout period of the interrupt context configuration is not 0, + and the queue is full.CNcomment:中断上下文配置超时时间不为0, + 队列满 CNend */ +#define HI_OS_STAT_SEM_WAIT_FAIL 0x4 /**< Used in the interrupt context.CNcomment:中断上下文使用CNend */ +#define HI_OS_STAT_SEM_SIGNAL_FAIL 0x8 /**< Repeated release.CNcomment:重复释放CNend */ +#define HI_OS_STAT_MUX_PEND_FAIL 0x10 /**< Used in the interrupt context.CNcomment:中断上下文使用CNend */ +#define HI_OS_STAT_MUX_POST_FAIL 0x20 /**< Cross-task use, not created.CNcomment:跨任务使用,未创建CNend */ +#define HI_OS_STAT_EVENT_WAIT_FAIL 0x40 /**< Used in the interrupt context.CNcomment:中断上下文使用 CNend */ +#define HI_OS_STAT_EVENT_SEND_FAIL 0x80 /**< Initialized EVT resources used up. + CNcomment:初始化EVT资源已经用完 CNend */ +#define HI_OS_STAT_EVENT_CLR_FAIL 0x100 /**< Invalid input argument.CNcomment:入参错误 CNend */ +#define HI_OS_STAT_SLEEP_FAIL 0x200 /**< Used in the interrupt context.CNcomment:中断上下文使用CNend */ +#define HI_OS_STAT_START_TIMER_FAIL 0x400 /**< Invalid input argument.CNcomment:入参错误 CNend */ +#define HI_OS_STAT_CREATE_TIMER_FAIL 0x800 /**< WorkQueue used up.CNcomment:创建定时器句柄失败 CNend */ + +/** + * @ingroup os_stat + * System resource usage statistic.CNcomment:系统资源使用统计量。CNend + */ +typedef struct { + hi_u8 timer_usage; /**< Number of used system timers.CNcomment:当前使用系统定时器个数 CNend */ + hi_u8 task_usage; /**< Number of used tasks.CNcomment:当前使用任务个数 CNend */ + hi_u8 sem_usage; /**< Number of used semaphores.CNcomment:当前使用信号量个数 CNend */ + hi_u8 queue_usage; /**< Number of used message queues.CNcomment:当前使用消息队列个数 CNend */ + hi_u8 mux_usage; /**< Number of used mutexes.CNcomment:当前使用互斥锁个数 CNend */ + hi_u8 event_usage; /**< Number of used events.CNcomment:当前使用事件个数 CNend */ + hi_u16 err_info; /**< Error statistic HI_OS_STAT_XXX, used to log occurred errors. + CNcomment:错误统计量HI_OS_STAT_XXX,用于记录曾经出现过的错误 CNend */ +}hi_os_resource_use_stat; + +/** +* @ingroup os_stat +* @brief Obtains the system resource usage.CNcomment:获取当前系统资源使用情况。CNend +* +* @par 描述: +* Obtains the system resource usage.CNcomment:获取当前系统资源使用情况。CNend +* +* @attention None +* @param os_resource_stat [OUT] type #hi_os_resource_use_stat*,System resource usage statistic. +CNcomment:系统资源使用统计量。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h +* @par 依赖: +* @li hi_os_stat.h:Describes system resource usage APIs. +CNcomment:文件用于描述定时器相关接口。CNend +* @see None +*/ +hi_u32 hi_os_get_resource_status(hi_os_resource_use_stat *os_resource_stat); + +#endif + diff --git a/sdk_liteos/include/hi_partition_table.h b/sdk_liteos/include/hi_partition_table.h new file mode 100644 index 0000000000000000000000000000000000000000..c33b05d9a6af856a559aa1d8225c777e3cb41a5a --- /dev/null +++ b/sdk_liteos/include/hi_partition_table.h @@ -0,0 +1,275 @@ +/** + * @file hi_partition_table.h + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** @defgroup iot_flash_partiton FLASH Partition Management + * @ingroup system + */ +#ifndef __HI_PARTITION_TABLE_H__ +#define __HI_PARTITION_TABLE_H__ +#include + +#define HI_FLASH_PARTITON_MAX 12 +/** + * @ingroup iot_flash_partiton + * + * Partition entry ID. CNcomment:分区项ID。CNend + */ +typedef enum { + HI_FLASH_PARTITON_BOOT = 0, /**< Boot partition ID.CNcomment:BOOT分区ID.CNend */ + HI_FLASH_PARTITON_FACTORY_NV, /**< Factory NV working partition ID.CNcomment:工厂NV分区ID.CNend */ + HI_FLASH_PARTITON_NORMAL_NV, /**< NORMAL NV partition ID.CNcomment:非工厂NV分区ID.CNend */ + HI_FLASH_PARTITON_NORMAL_NV_BACKUP, /**< NORMAL backup NV partition ID.CNcomment:非工厂NV备份分区ID,必须和非工厂区连续.CNend */ + HI_FLASH_PARTITON_KERNEL_A, /**< Kernel A running partition ID.CNcomment:内核A区ID.CNend */ + HI_FLASH_PARTITON_KERNEL_B, /**< Kernel B runing partition ID.CNcomment:内核B区ID.CNend */ + HI_FLASH_PARTITON_HILINK, /**< HILINK partition ID.CNcomment:HILINK分区ID(未使用HILINK可不需要).CNend */ + HI_FLASH_PARTITON_FILE_SYSTEM, /**< File system partition ID.CNcomment:文件系统区ID.CNend */ + HI_FLASH_PARTITON_USR_RESERVE, /**< User Reserved partition.CNcomment:用户保留区ID.CNend */ + HI_FLASH_PARTITON_HILINK_PKI, /**< HiLink PKI partition.CNcomment: HILINK PKI证书ID(未使用HILINK可不需要). CNend */ + HI_FLASH_PARTITON_CRASH_INFO, /**< Crash log partition.CNcomment:死机存储区ID.CNend */ + HI_FLASH_PARTITON_BOOT_BACK, /**< Boot backup partition.CNcomment:备份boot区ID. CNend */ +} hi_flash_partition_table_id; + +/** + * @ingroup iot_flash_partiton + * + * Flash partition management. CNcomment:Flash分区表项。CNend + */ +typedef struct { + hi_u32 addr : 24; /**< Flash partition address.The value is 16 MB.If the address is in reverse order, + the value is the end low address.CNcomment:Flash分区地址,限制为16MB, + 如果为倒序,存放为结束的低地址值 CNend */ + hi_u32 id : 7; /**< Flash partition ID.CNcomment:Flash区ID.CNend */ + hi_u32 dir : 1; /**< Flash area storage direction.0:regular.1: reversed.CNcomment:Flash区存放方向。 + 0:分区内容正序;1:倒序末地址 CNend */ + + hi_u32 size : 24; /**< Size of the parition(Unit:byte).CNcomment:Flash分区大小(单位:byte)CNend */ + hi_u32 reserve : 8; /**< Reserved. CNcomment:保留区CNend */ + + hi_u32 addition; /**< Supplementary information about the flash partition, such as the address of the + Ram.CNcomment:Flash分区补充信息,如Ram对应地址等 CNend */ +} hi_flash_partition_info; + + +/** + * @ingroup iot_flash_partiton + * + * Flash partition table. CNcomment:Flash分区表。CNend + */ +typedef struct { + hi_flash_partition_info table[HI_FLASH_PARTITON_MAX]; /**< Flash partition entry information.CNcomment: + Flash分区表项描述 CNend */ +} hi_flash_partition_table; + +/** +* @ingroup iot_flash_partiton +* @brief Obtains the flash partition table. CNcomment:获取Flash分区表。CNend +* +* @par 描述: +* Obtains the flash partition table. CNcomment:获取Flash分区表。CNend +* +* @attention None +* @param None +* +* @retval #hi_flash_partition_table Pointer to partition table information. CNcomment:分区表指针。CNend +* @par 依赖: +* @li hi_partition_table.h:Describes flash partition APIs. +CNcomment:文件用于描述Flash分区相关接口。CNend +* @see None +*/ +hi_flash_partition_table *hi_get_partition_table(hi_void); + +/** +* @ingroup iot_flash_partiton +* @brief Initializes the flash partition table. CNcomment:Flash分区表初始化。CNend +* +* @par 描述: +* Initializes the flash partition table. CNcomment:Flash分区表初始化。CNend +* +* @attention None +* @param None +* +* @retval #0 Success +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_partition_table.h:Describes flash partition APIs. +CNcomment:文件用于描述Flash分区相关接口。CNend +* @see None +*/ +hi_u32 hi_flash_partition_init(hi_void); + +/** +* @ingroup iot_flash_partiton +* @brief Get HiLink partition table'addr and size. CNcomment:获取HiLink分区地址和大小。CNend +* +* @par 描述: +* Get HiLink partition table'addr and size. CNcomment:获取HiLink分区地址和大小。CNend +* +* @attention Call after hi_flash_partition_init. CNcomment:在hi_flash_partition_init之后调用。CNend +* @param addr [OUT] type #hi_u32*, Address of HiLink partition.CNcomment:HiLink分区地址。CNend +* @param size [OUT] type #hi_u32*, Size of HiLink partitioin, in bytes.CNcomment:HiLink分区大小,单位byte。CNend +* +* @retval #0 Success +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_partition_table.h:Describes flash partition APIs. +CNcomment:文件用于描述Flash分区相关接口。CNend +* @see None +*/ +hi_u32 hi_get_hilink_partition_table(hi_u32 *addr, hi_u32 *size); + +/** +* @ingroup iot_flash_partiton +* @brief Get HiLink PKI partition table'addr and size. CNcomment:获取HiLink PKI 分区地址和大小。CNend +* +* @par 描述: +* Get HiLink PKI partition table'addr and size. CNcomment:获取HiLink PKI 分区地址和大小。CNend +* +* @attention Call after hi_flash_partition_init. CNcomment:在hi_flash_partition_init之后调用。CNend +* @param addr [OUT] type #hi_u32*, Address of HiLink PKI partition.CNcomment:HiLink PKI分区地址。CNend +* @param size [OUT] type #hi_u32*, Size of HiLink PKI partitioin, in bytes.CNcomment:HiLink PKI分区大小,单位byte。CNend +* +* @retval #0 Success +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_partition_table.h:Describes flash partition APIs. +CNcomment:文件用于描述Flash分区相关接口。CNend +* @see None +*/ +hi_u32 hi_get_hilink_pki_partition_table(hi_u32 *addr, hi_u32 *size); + + +/** +* @ingroup iot_flash_partiton +* @brief Get Crash info partition table'addr and size. CNcomment:获取死机信息分区地址和大小。CNend +* +* @par 描述: +* Get Crash info partition table'addr and size. CNcomment:获取死机信息分区地址和大小。CNend +* +* @attention Call after hi_flash_partition_init. CNcomment:在hi_flash_partition_init之后调用。CNend +* @param addr [OUT] type #hi_u32*, Address of Crash info partition.CNcomment:死机信息分区地址。CNend +* @param size [OUT] type #hi_u32*, Size of Crash info partitioin, in bytes.CNcomment:死机信息分区大小,单位byte。CNend +* +* @retval #0 Success +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_partition_table.h:Describes flash partition APIs. +CNcomment:文件用于描述Flash分区相关接口。CNend +* @see None +*/ +hi_u32 hi_get_crash_partition_table(hi_u32 *addr, hi_u32 *size); + +/** +* @ingroup iot_flash_partiton +* @brief Get File system partition table'addr and size. CNcomment:获取文件系统分区地址和大小。CNend +* +* @par 描述: +* Get File system partition table'addr and size. CNcomment:获取文件系统分区地址和大小。CNend +* +* @attention Call after hi_flash_partition_init. CNcomment:在hi_flash_partition_init之后调用。CNend +* @param addr [OUT] type #hi_u32*, Address of File system partition.CNcomment:文件系统分区地址。CNend +* @param size [OUT] type #hi_u32*, Size of HiLink partitioin, in bytes.CNcomment:文件系统分区大小,单位byte。CNend +* +* @retval #0 Success +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_partition_table.h:Describes flash partition APIs. +CNcomment:文件用于描述Flash分区相关接口。CNend +* @see None +*/ +hi_u32 hi_get_fs_partition_table(hi_u32 *addr, hi_u32 *size); + +/** +* @ingroup iot_flash_partiton +* @brief Get Normal NV partition table'addr and size. CNcomment:获取非工厂区分区地址和大小。CNend +* +* @par 描述: +* Get Normal NV partition table'addr and size. CNcomment:获取非工厂区分区地址和大小。CNend +* +* @attention Call after hi_flash_partition_init. CNcomment:在hi_flash_partition_init之后调用。CNend +* @param addr [OUT] type #hi_u32*, Address of Normal NV partition.CNcomment:非工厂区分区地址。CNend +* @param size [OUT] type #hi_u32*, Size of Normal NV partitioin, in bytes.CNcomment:非工厂区分区大小,单位byte。CNend +* +* @retval #0 Success +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_partition_table.h:Describes flash partition APIs. +CNcomment:文件用于描述Flash分区相关接口。CNend +* @see None +*/ +hi_u32 hi_get_normal_nv_partition_table(hi_u32 *addr, hi_u32 *size); + +/** +* @ingroup iot_flash_partiton +* @brief Get Normal NV backup partition table'addr and size. CNcomment:获取非工厂备份区分区地址和大小。CNend +* +* @par 描述: +* Get Normal NV backup partition table'addr and size. CNcomment:获取非工厂备份区分区地址和大小。CNend +* +* @attention Call after hi_flash_partition_init. CNcomment:在hi_flash_partition_init之后调用。CNend +* @param addr [OUT] type #hi_u32*, Address of Normal NV backup partition.CNcomment:非工厂备份区分区地址。CNend +* @param size [OUT] type #hi_u32*, Size of Normal NV backup partitioin, in bytes.CNcomment:非工厂备份区分区大小,单位byte。CNend +* +* @retval #0 Success +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_partition_table.h:Describes flash partition APIs. +CNcomment:文件用于描述Flash分区相关接口。CNend +* @see None +*/ +hi_u32 hi_get_normal_nv_backup_partition_table(hi_u32 *addr, hi_u32 *size); + +/** +* @ingroup iot_flash_partiton +* @brief Get User's reserved NV partition table'addr and size. CNcomment:获取用户保留区分区地址和大小。CNend +* +* @par 描述: +* Get User's reserved NV partition table'addr and size. CNcomment:获取用户保留区分区地址和大小。CNend +* +* @attention Call after hi_flash_partition_init. CNcomment:在hi_flash_partition_init之后调用。CNend +* @param addr [OUT] type #hi_u32*, Address of user partition.CNcomment:用户保留区分区地址。CNend +* @param size [OUT] type #hi_u32*, Size of user partitioin, in bytes.CNcomment:用户保留区分区大小,单位byte。CNend +* +* @retval #0 Success +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_partition_table.h:Describes flash partition APIs. +CNcomment:文件用于描述Flash分区相关接口。CNend +* @see None +*/ +hi_u32 hi_get_usr_partition_table(hi_u32 *addr, hi_u32 *size); + +/** +* @ingroup iot_flash_partiton +* @brief Get Factory bin'addr and size. CNcomment:获取产测BIN 地址和大小。CNend +* +* @par 描述: +* Get Factory bin'addr and size.. CNcomment:获取产测BIN 地址和大小。CNend +* +* @attention Call after hi_flash_partition_init. CNcomment:在hi_flash_partition_init之后调用。CNend +* @param addr [OUT] type #hi_u32*, Address of factory bin.CNcomment:产测BIN 地址。CNend +* @param size [OUT] type #hi_u32*, Size of factory bin, in bytes.CNcomment:产测bin 大小,单位byte。CNend +* +* @retval #0 Success +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_partition_table.h:Describes flash partition APIs. +CNcomment:文件用于描述Flash分区相关接口。CNend +* @see None +*/ +hi_u32 hi_get_factory_bin_partition_table(hi_u32 *addr, hi_u32 *size); + +#endif + diff --git a/sdk_liteos/include/hi_pwm.h b/sdk_liteos/include/hi_pwm.h new file mode 100644 index 0000000000000000000000000000000000000000..1171e930068cacdecca8a68a2c3073c1c287c003 --- /dev/null +++ b/sdk_liteos/include/hi_pwm.h @@ -0,0 +1,177 @@ +/** + * @file hi_pwm.h + * + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Description: PWM driver interfaces. + */ + +/** @defgroup iot_pwm PWM + * @ingroup drivers + */ +#ifndef __HI_PWM_H__ +#define __HI_PWM_H__ + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @ingroup iot_pwm + * + * Enumerates the PWM clock sources.CNcomment:PWM时钟源枚举。CNend + */ +typedef enum { + PWM_CLK_160M, /**< 160M APB clock.CNcomment:160M 工作时钟 CNend */ + PWM_CLK_XTAL, /**< 24M/40M crystal clock.CNcomment:24M或40M 晶体时钟 CNend */ + PWM_CLK_MAX /**< Maximum value, which cannot be used.CNcomment:最大值,不可使用CNend */ +} hi_pwm_clk_source; + +/** + * @ingroup iot_pwm + * + * Enumerates the PWM ports.CNcomment:PWM端口枚举。CNend + */ +typedef enum { + HI_PWM_PORT_PWM0 = 0, /**< PWM port0. Register base address: 0x40040000, multiplexed with GPIOX. + CNcomment:PWM0端口。寄存器基址:0x40040000,复用GPIOX。CNend */ + HI_PWM_PORT_PWM1 = 1, /**< PWM port1. Register base address: 0x40040100, multiplexed with GPIOX. + CNcomment:PWM1端口。寄存器基址:0x40040100,复用GPIOX。CNend */ + HI_PWM_PORT_PWM2 = 2, /**< PWM port2. Register base address: 0x40040200, multiplexed with GPIOX. + CNcomment:PWM2端口。寄存器基址:0x40040200,复用GPIOX。CNend */ + HI_PWM_PORT_PWM3 = 3, /**< PWM port3. Register base address: 0x40040300, multiplexed with GPIOX. + CNcomment:PWM3端口。寄存器基址:0x40040300,复用GPIOX。CNend */ + HI_PWM_PORT_PWM4 = 4, /**< PWM port4. Register base address: 0x40040400, multiplexed with GPIOX. + CNcomment:PWM4端口。寄存器基址:0x40040400,复用GPIOX。CNend */ + HI_PWM_PORT_PWM5 = 5, /**< PWM port5. Register base address: 0x40040500, multiplexed with GPIOX. + CNcomment:PWM5端口。寄存器基址:0x40040500,复用GPIOX。CNend */ + HI_PWM_PORT_MAX /**< Maximum value, which cannot be used.CNcomment:最大值,不可使用CNend */ +} hi_pwm_port; + +/** +* @ingroup iot_pwm +* @brief Initializes the PWM module.CNcomment:PWM初始化。CNend +* +* @par 描述: +* Initializes the PWM module.CNcomment:PWM初始化。CNend +* @attention +* @li Before using the PWM function, ensure that the GPIO multiplexing relationship has been configured. +CNcomment:使用PWM功能前需要确认已配置GPIO复用关系。CNend +* @li For details, see Hi3861 V100 API Development Guide. +CNcomment:具体配置方法请参见Demo介绍小节相关说明。CNend +* @li For details about the multiplexed GPIO, see the Hi3861 V100 Data Sheet. +CNcomment:具体复用的GPIO请参见。CNend +* @li Before using the PWM function, initialize the PWM.CNcomment:使用PWM功能前需要先初始化。CNend +* +* @param port [IN] type #hi_pwm_port PWM port number.CNcomment:PWM端口号。CNend +* +* @retval #HI_ERR_SUCCESS Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_pwm.h: Describes the APIs of the PWM module.CNcomment:文件用于描述PWM对外接口。CNend +* @see hi_pwm_deinit | hi_pwm_start | hi_pwm_stop。 +*/ +hi_u32 hi_pwm_init(hi_pwm_port port); + +/** +* @ingroup iot_pwm +* @brief Deinitializes the PWM module.CNcomment:PWM去初始化。CNend +* +* @par 描述: +* Deinitializes the PWM module.CNcomment:PWM去初始化。CNend +* +* @attention Deinitialize the PWM module when the function iss not used. +CNcomment:不使用PWM功能时去初始化。CNend +* +* @param port [IN] type #hi_pwm_port PWM port number.CNcomment:PWM端口号。CNend +* +* @retval #HI_ERR_SUCCESS Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_pwm.h: Describes the APIs of the PWM module.CNcomment:文件用于描述PWM对外接口。CNend +* @see hi_pwm_init。 +*/ +hi_u32 hi_pwm_deinit(hi_pwm_port port); + +/** +* @ingroup iot_pwm +* @brief Sets the clock type of the PWM module.CNcomment:设置PWM模块时钟类型。CNend +* +* @par 描述: +* This function is used to set the clock type of the PWM module. +CNcomment:该函数用于设置PWM模块时钟类型。CNend +* +* @attention This setting takes effect for all PWM modules. The 160 MHz clock is used by default. +CNcomment:该设置对所有PWM模块均生效。默认为160M时钟。CNend +* +* @param clk_type [IN] type #hi_pwm_clk_source Clock type. CNcomment:时钟类型。CNend +* +* @retval #HI_ERR_SUCCESS Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_pwm.h: Describes the APIs of the PWM module.CNcomment:文件用于描述PWM对外接口。CNend +* @see None +*/ +hi_u32 hi_pwm_set_clock(hi_pwm_clk_source clk_type); + +/** +* @ingroup iot_pwm +* @brief Outputs the PWM signal according to the configured parameter. +* PWM signal duty cycle = duty/freq Frequency = Clock source frequency/freq. +CNcomment:按配置的参数输出PWM信号。PWM信号占空比=duty/freq。频率=时钟源频率/freq。CNend +* +* @par 描述: +* Starts the PWM signal output.CNcomment:启动PWM信号输出。CNend +* +* @attention This API cannot be called in an interrupt.CNcomment:不支持在中断中调用。CNend +* +* @param port [IN] type #hi_pwm_port PWM port number.CNcomment:PWM端口号。CNend +* @param duty [IN] type #hi_u16 PWM duty cycle count. Value range: [1, 65535]. The default value is 750. +CNcomment:PWM占空比计数值。取值范围为:[1, 65535]。默认值为750。CNend +* @param freq [IN] type #hi_u16 Frequency division multiple. Value range: [1, 65535]. The default value is 1500. +CNcomment:分频倍数。取值范围为:[1, 65535]。默认值为1500。CNend +* +* @retval #HI_ERR_SUCCESS Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_pwm.h: Describes the APIs of the PWM module.CNcomment:文件用于描述PWM对外接口。CNend +* @see hi_pwm_init | hi_pwm_stop。 +*/ +hi_u32 hi_pwm_start(hi_pwm_port port, hi_u16 duty, hi_u16 freq); + +/** +* @ingroup iot_pwm +* @brief Stops the PWM signal output.CNcomment:停止PWM信号输出。CNend +* +* @par 描述: +* Stops the PWM signal output.CNcomment: 停止PWM信号输出。CNend +* +* @attention This API cannot be called in an interrupt.CNcomment:不支持在中断中调用。CNend +* +* @param port [IN] type #hi_pwm_port PWM port number.CNcomment:PWM端口号。CNend +* +* @retval #HI_ERR_SUCCESS Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_pwm.h: Describes the APIs of the PWM module.CNcomment:文件用于描述PWM对外接口。CNend +* @see hi_pwm_init | hi_pwm_start。 +*/ +hi_u32 hi_pwm_stop(hi_pwm_port port); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/sdk_liteos/include/hi_reset.h b/sdk_liteos/include/hi_reset.h new file mode 100644 index 0000000000000000000000000000000000000000..486dd8b1654702b28c356ba13f6203bd4e04e1b4 --- /dev/null +++ b/sdk_liteos/include/hi_reset.h @@ -0,0 +1,167 @@ +/** + * @file hi_reset.h + * + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** @defgroup iot_sys Active Reset + * @ingroup system + */ + +#ifndef __HI_RESET_H__ +#define __HI_RESET_H__ +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define HI_SYS_REBOOT_CAUSE_USR_BEGIN 0x8000 +#define HI_SYS_REBOOT_CAUSE_USR_END 63 /* 8bit: 0 - 63 */ + +/** +* @ingroup iot_sys +* +* Cause for active restart. CNcomment:主动重启原因CNend +*/ +typedef enum { + HI_SYS_REBOOT_CAUSE_UNKNOWN = 0, + HI_SYS_REBOOT_CAUSE_CMD, /**< system reset begin. */ + HI_SYS_REBOOT_CAUSE_UPG, /**< upgrade reset begin. */ + HI_SYS_REBOOT_CAUSE_UPG_B, /**< upgrade backup image reset. */ + HI_SYS_REBOOT_CAUSE_WIFI_MODE, /**< wifi module reset begin. */ + HI_SYS_REBOOT_CAUSE_USR_NORMAL_REBOOT, /**< user reset begin. */ + HI_SYS_REBOOT_CAUSE_USR0, + HI_SYS_REBOOT_CAUSE_USR1, + HI_SYS_REBOOT_CAUSE_AT_BUSY, + HI_SYS_REBOOT_CAUSE_MAX = HI_SYS_REBOOT_CAUSE_USR_END + 1, +} hi_sys_reboot_cause; + +/** +* @ingroup iot_sys +* @brief System hard reboot. CNcomment:系统硬重启。CNend +* +* @par 描述: +* System Hard reboot:reset whole chip. CNcomment:硬重启 :整芯片复位。CNend +* +* @attention None +* +* @param cause [IN] type #hi_sys_reboot_cause , reboot cause, see hi_sys_reboot_cause. +CNcomment:重启原因,取值参见hi_sys_reboot_cause。CNend +* +* +* @retval None. +* +* @par 依赖: +* @li hi_reset.h: Describes the APIs for obtaining system information. +CNcomment:文件用于描述系统复位相关接口。CNend +* @see None +*/ +hi_void hi_hard_reboot(hi_sys_reboot_cause cause); + +/** +* @ingroup iot_sys +* @brief System soft reboot. CNcomment:系统软重启。CNend +* +* @par 描述: +* System Soft reboot:part of peripheral won't reset(such as GPIO/PWM). +CNcomment:软重启:部分外设不复位,如GPIO/PWM。CNend +* @attention +* @li only GPIO is the default peripheral that won't reset when soft reboot. +PWM should config in menuconfig. other peripheras need another setting. +CNcomment:仅GPIO在软重启时默认不复位,PWM需要在menuconfig中配置, +其余外设需要额外配置。CNend +* +* @param cause [IN] type #hi_sys_reboot_cause , reboot cause, see hi_sys_reboot_cause. +CNcomment:重启原因,取值参见hi_sys_reboot_cause。CNend +* +* +* @retval None. +* +* @par 依赖: +* @li hi_reset.h: Describes the APIs for obtaining system information. +CNcomment:文件用于描述系统复位相关接口。CNend +* @see None +*/ +hi_void hi_soft_reboot(hi_sys_reboot_cause cause); + +/** +* @ingroup iot_sys +* @brief Enables or disables the function of recording the reset times. +CNcomment:使能(去使能)记录复位次数功能。CNend +* +* @par 描述: +* @li Enables or disables the function of recording the reset times. When the function of recording the reset times +* is enabled, in order to avoid the issue that fast flash life exhaustion caused by writing NV when the system +* is frequently powered on and off, NV will be written 30 seconds after the system is started. +CNcomment:使能(去使能)记录复位次数功能。使能复位次数记录功能后, +为避免系统经常频繁上下电时写NV导致flash寿命快速耗尽问题,每次启动时会在上电后30秒时写NV,正常计数复位次数。CNend +* @li When the number of reset times is updated, the flash memory needs to be written. Generally, when the system +* frequently powers on and off and power-on NV write greatly hurts the flash service life, set enable to +* HI_FALSE and check whether the service function is affected. +CNcomment:复位次数更新需要执行写Flash操作,通常在系统经常频繁上下电, +不能接受上电写NV导致flash寿命快速耗尽的场景时,将enable设置为HI_FALSE, +同时要考虑是否对业务功能造成影响。CNend +* @li Set enable takes effect after the next reset, and set disable takes effect when write NV next time. +CNcomment:配置开启是在下次复位后生效,配置关闭是在下次写NV时生效。CNend +* +* @attention +* @li This feature should be disable by default. CNcomment:该功能默认不使能。CNend +* @li It should be called in the initialization function of the app layer. +CNcomment:应该在应用层初始化函数中调用。CNend +* @li Disabling this function may result in some influences. You are advised to disable it in scenarios where the +* system is frequently powered on and off.CNcomment:关闭该功能需要考虑对使用复位次数业务功能 +的影响,建议在系统经常频繁上下电的场景关闭该功能,其他场景打开该功能。CNend +* +* @param enable [IN] type #hi_bool Enable/Disable. CNcomment:是否使能计数功能。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* +* @par 依赖: +* @li hi_reset.h: Describes the APIs for obtaining system information. +CNcomment:文件用于描述系统复位相关接口。CNend +* @see None +*/ +hi_u32 hi_enable_reset_times_save(hi_bool enable); + +/** +* @ingroup iot_sys +* @brief Obtains reset times recorded in NV. CNcomment:获取NV中记录的系统复位次数。CNend +* +* @par 描述: +* Obtains reset times recorded in NV. CNcomment:获取NV中记录的系统复位次数。CNend +* +* @attention None +* +* @param None +* +* @retval #HI_ERR_FAILURE Read NV Failure. +* @retval #Other Reboot times number. CNcomment:系统复位次数。CNend +* +* @par 依赖: +* @li hi_reset.h: Describes the APIs for obtaining system information. +CNcomment:文件用于描述系统复位相关接口。CNend +* @see None +*/ +hi_u32 hi_get_reset_times(hi_void); + +#ifdef __cplusplus +} +#endif + +#endif /* __HI_RESET_H__ */ + diff --git a/sdk_liteos/include/hi_sdio_device.h b/sdk_liteos/include/hi_sdio_device.h new file mode 100644 index 0000000000000000000000000000000000000000..76c054c2038c83cae8e3f50dff514d07efc25fb6 --- /dev/null +++ b/sdk_liteos/include/hi_sdio_device.h @@ -0,0 +1,564 @@ +/** +* @file hi_sdio_device.h +* +* Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +* Description: sdio slave mode APIs. \n +* Create: 2019-01-17 +*/ + +/** + * @defgroup iot_sdio SDIO Slave + * @ingroup drivers + */ + +#ifndef __HI_SDIO_DEVICE_H__ +#define __HI_SDIO_DEVICE_H__ + +#include + +/** + * @ingroup iot_sdio + * + * SDIO definition.CNcomment:SDIO定义CNend + */ +#define CHAN_TX_BUSY 1 +#define CHAN_TX_IDLE 0 +#define CHAN_RX_BUSY 1 +#define CHAN_RX_IDLE 0 + +#define HISDIO_EXTENDREG_COUNT 64 +#define HISDIO_BLOCK_SIZE 512 + +/** + * @ingroup iot_sdio + * + * Device to Host sdio message type, The name can be modified according to product. +CNcomment:设备到主机的SDIO消息类型,类型名称可以根据产品实际应用场景更改。CNend + */ +typedef enum { + D2H_MSG_WLAN_READY = 0, + D2H_MSG_WOW_COMPLETE = 1, /**< wow complete. */ + D2H_MSG_FLOWCTRL_OFF = 2, /**< can't send data */ + D2H_MSG_FLOWCTRL_ON = 3, /**< can send data */ + D2H_MSG_WAKEUP_SUCC = 4, /**< wakeup done */ + D2H_MSG_ALLOW_SLEEP = 5, /**< allow sleep */ + D2H_MSG_DISALLOW_SLEEP = 6, /**< disalow sleep */ + D2H_MSG_DEVICE_PANIC = 7, /**< device panic */ + D2H_MSG_POWEROFF_ACK = 8, /**< poweroff cmd ack */ + D2H_MSG_CREDIT_UPDATE = 11, /**< update high priority buffer credit value */ + D2H_MSG_HIGH_PKT_LOSS = 12, /**< high pri pkts loss count */ + D2H_MSG_HEARTBEAT = 14, /**< send heartbeat */ + D2H_MSG_WOW_WIFI_REDAY = 15, /**< device ready for host sleep */ + D2H_MSG_COUNT = 32, /**< max support msg count */ +} hi_sdio_d2h_msg_type_e; + +/** + * @ingroup iot_sdio + * + * Host to Device sdio message type, The name can be modified according to product. +CNcomment:主机到设备的SDIO消息类型,类型名称可以根据产品实际应用场景更改。CNend + */ +typedef enum { + H2D_MSG_FLOWCTRL_ON = 0, + H2D_MSG_DEVICE_INFO_DUMP = 1, + H2D_MSG_DEVICE_MEM_DUMP = 2, + H2D_MSG_TEST = 3, + H2D_MSG_PM_WLAN_OFF = 4, + H2D_MSG_SLEEP_REQ = 5, + H2D_MSG_PM_DEBUG = 6, + H2D_MSG_QUERY_RF_TEMP = 8, + H2D_MSG_HCC_SLAVE_THRUPUT_BYPASS = 9, + H2D_MSG_DEVICE_MEM_INFO = 10, + H2D_MSG_STOP_SDIO_TEST = 11, + H2D_MSG_FORCESLP_REQ = 13, + H2D_MSG_WOW_WIFI_SUSPEND = 14, + H2D_MSG_WOW_WIFI_RESUME = 15, + H2D_MSG_COUNT = 32, /**< max support msg value count */ +} hi_sdio_h2d_msg_type_e; + +/** + * @ingroup iot_sdio + * + * max message value between Host and Device. + */ +typedef enum { + SDIO_DEVICE_MSG_WLAN_READY = 0, + SDIO_DEVICE_MSG_COUNT = 32, /**< max support msg count */ + SDIO_DEVICE_MSG_BUTT +} hi_sdio_msg_e; + +/** + * @ingroup iot_sdio + * + * SDIO ADMA table. + */ +typedef struct { + hi_u16 param; + hi_u16 len; + uintptr_t address; +} hi_sdio_admatable; + +/** + * @ingroup iot_sdio + * + * SDIO extend function structure. + */ +typedef struct { + hi_u32 int_stat; + hi_u32 msg_stat; + hi_u32 xfer_count; + hi_u32 credit_info; + hi_s8 credit_isvalid; + hi_u8 comm_reg[HISDIO_EXTENDREG_COUNT]; + hi_s8 commreg_isvalid; + hi_s32 valid_commreg_cnt; +} hi_sdio_extendfunc; + +/** + * @ingroup iot_sdio + * + * use this callback to notify host msg event occurs. + */ +typedef hi_void (*notify_host_message_event)(hi_void); + +/** + * @ingroup iot_sdio + * + * SDIO interrupt callback structure. + */ +typedef struct { + hi_s32 (*rdstart_callback)(hi_u32 len, hi_u8 *admatable); /**< Callback function for HOST reading. + CNcomment:DEV感知到HOST发起了读操作 CNend */ + hi_s32 (*rdover_callback)(hi_void); /**< Callback function for HOST reading over. + CNcomment:DEV感知到HOST读操作结束 CNend */ + hi_void (*rderr_callback)(hi_void); /**< Callback function for HOST read error. + CNcomment:DEV感知到HOST读数据错误 CNend */ + hi_s32 (*wrstart_callback)(hi_u32 len, hi_u8 *admatable); /**< Callback function for HOST writting. + CNcomment:DEV感知到HOST发起了写操作 CNend */ + hi_s32 (*wrover_callback)(hi_void); /**< Callback function for HOST write over. + CNcomment:DEV感知到HOST写操作结束 CNend */ + hi_void (*processmsg_callback)(hi_u32 msg); /**< Callback function for HOST getting message. + CNcomment:DEV接收到HOST发来的消息 CNend */ + hi_void (*soft_rst_callback)(hi_void); /**< Callback function for HOST getting reset + interruption.CNcomment:DEV接收到HOST发来的 + 软复位中断 CNend */ +} hi_sdio_intcallback; + +/** +* @ingroup iot_sdio +* @brief sdio init function +* +* @par 描述: +* sdio initialization function.CNcomment:sdio 初始化函数。CNend +* +* @attention None +* @param None +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. + +* @par 依赖: +* @li hi_sdio_device.h:Describe sdio slave APIs.CNcomment:该接口声明所在的头文件。CNend +* @see None。 +*/ +hi_u32 hi_sdio_init(hi_void); + +/** +* @ingroup iot_sdio +* @brief sdio reinit function +* +* @par 描述: +* sdio Reinitialize the function.CNcomment:sdio 重新初始化函数。CNend +* +* @attention None +* @param None +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. + +* @par 依赖: +* @li hi_sdio_device.h:Describe sdio slave APIs.CNcomment:该接口声明所在的头文件。CNend +* @see None。 +*/ +hi_u32 hi_sdio_reinit(hi_void); + +/** +* @ingroup iot_sdio +* @brief sdio soft reset function +* +* @par 描述: +* sdio software reset function.CNcomment:sdio 软件复位函数。CNend +* +* @attention None +* @param None +* +* @retval None +* +* @par 依赖: +* @li hi_sdio_device.h:Describe sdio slave APIs.CNcomment:该接口声明所在的头文件。CNend +* @see None +*/ +hi_void hi_sdio_soft_reset(hi_void); + +/** +* @ingroup iot_sdio +* @brief sdio register interrupt callback function +* +* @par 描述: +* sdio register interrupt callback function.CNcomment:sdio 注册中断回调 函数。CNend +* +* @attention。 +* @param callback_func [IN] type #const hi_sdio_intcallback,sdio callback function. +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. + +* @par 依赖: +* @li hi_sdio_device.h:Describe sdio slave APIs.CNcomment:该接口声明所在的头文件。CNend +* @see None。 +*/ +hi_u32 hi_sdio_register_callback(const hi_sdio_intcallback *callback_func); + +/** +* @ingroup iot_sdio +* @brief sdio complete send function +* +* @par 描述: +* sdio complete send function.CNcomment:sdio 结束发送接口函数。CNend +* +* @attention。 +* @param admatable [IN] type #hi_u8 *, adma table first address. One channel occupies eight bytes. Ensure that the +* buffer space is sufficient to prevent memory overwriting. CNcomment:adma table首地址,一个通道占用8字节,使 +* 用时请确保足够 +的缓存空间,防止内存越界访问。CNend +* @param adma_index [IN] type hi_u32, adma_index adma Transmission channel number, range: [0-130].CNcomment:adma +* 传输通道号,范围[0-130]。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. + +* @par 依赖: +* @li hi_sdio_device.h:Describe sdio slave APIs.CNcomment:该接口声明所在的头文件。CNend +* @see None。 +*/ +hi_u32 hi_sdio_complete_send(hi_u8 *admatable, hi_u32 adma_index); + +/** +* @ingroup iot_sdio +* @brief set sdio pad adma table function +* +* @par 描述: +* set sdio pad adma table function.CNcomment:sdio 配置数据对齐后的ADMA表CNend +* +* @attention。 +* @param padlen [IN] type #hi_u32, Length of data to be sent after data alignment. +CNcomment:数据对齐后要发送的数据长度。CNend +* @param admatable [IN] type #hi_u8 *, adma table first address. One channel occupies eight bytes. Ensure that the +* buffer space is sufficient to prevent memory overwriting. +CNcomment:adma table首地址,一个通道占用8字节,使用时请确保足够的缓存空间,防止内存越界访问。CNend +* @param adma_index [IN] type #hi_u32, adma Transmission channel number, range: [0-130]. +CNcomment:adma传输通道号,范围[0-130]。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. + +* @par 依赖: +* @li hi_sdio_device.h:Describe sdio slave APIs.CNcomment:该接口声明所在的头文件。CNend +* @see None。 +*/ +hi_u32 hi_sdio_set_pad_admatab(hi_u32 padlen, hi_u8 *admatable, hi_u32 adma_index); + +/** +* @ingroup iot_sdio +* @brief write extend information function +* +* @par 描述: +* write extend information function.CNcomment:写扩展信息接口CNend +* +* @attention。 +* @param extfunc [IN] type #hi_sdio_extendfunc, Extended information pointer.CNcomment:扩展信息指针.CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. + +* @par 依赖: +* @li hi_sdio_device.h:Describe sdio slave APIs.CNcomment:该接口声明所在的头文件。CNend +* @see None。 +*/ +hi_u32 hi_sdio_write_extendinfo(hi_sdio_extendfunc *extfunc); + +/** +* @ingroup iot_sdio +* @brief start to send data +* +* @par 描述: +* start to send data.CNcomment:启动数据发送接口CNend +* +* @attention。 +* @param xfer_bytes [IN] type #hi_u32, Length of sent data.CNcomment:发送数据长度.CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. + +* @par 依赖: +* @li hi_sdio_device.h:Describe sdio slave APIs.CNcomment:该接口声明所在的头文件。CNend +* @see None。 +*/ +hi_void hi_sdio_send_data(hi_u32 xfer_bytes); + +/** +* @ingroup iot_sdio +* @brief set adma table +* +* @par 描述: +* set adma table.CNcomment:设置adma传输通道CNend +* +* @attention。 +* @param admatable [IN] type #hi_u8*, adma table first address. One channel occupies eight bytes. Ensure that the +* buffer space is sufficient to prevent memory overwriting. CNcomment:adma table首地址,一个通道占用8字节,使 +用时请确保足够的缓存空间,防止内存越界访问。CNend +* @param adma_index [IN] type #hi_u32, adma Transmission channel number, range: [0-130].CNcomment:adma传输通道号, +范围[0-130]。CNend +* @param data_addr [IN] type #const hi_u32 *, dama transmission destination address.CNcomment:dama 传输目的地址CNend +* @param data_len [IN] type #hi_u32, adma Transmission data length.CNcomment:adma 传输数据长度CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. + +* @par 依赖: +* @li hi_sdio_device.h:Describe sdio slave APIs.CNcomment:该接口声明所在的头文件。CNend +* @see None。 +*/ +hi_u32 hi_sdio_set_admatable(hi_u8 *admatable, hi_u32 adma_index, const hi_u32 *data_addr, hi_u32 data_len); + +/** +* @ingroup iot_sdio +* @brief schedule sdio pending message. +* +* @par 描述: +* schedule sdio message.CNcomment:将挂起的sdio消息发送出去CNend +* +* @attention。 +* @param None +* +* @retval #true if there is no pending msg or send pending msg success, retun true. +CNcomment:如果没有挂起的消息,或者将挂起的消息发送成功,返回true.CNend +* @retval #false if sdio not in work status or there is msg sending, return false. +CNcomment:如果sdio不在工作状态,或者sdio正在发送消息,返回false.CNend +* +* @par 依赖: +* @li hi_sdio_device.h:Describe sdio slave APIs.CNcomment:该接口声明所在的头文件。CNend +* @see None。 +*/ +hi_bool hi_sdio_sched_msg(hi_void); + +/** +* @ingroup iot_sdio +* @brief sync send message. +* +* @par 描述: +* put msg in pending msg and send.CNcomment:将消息加入消息队列并发送CNend +* +* @attention。 +* @param msg [IN] type #hi_u32, The message, range [0-31].CNcomment:给定消息,范围[0-31].CNend +* +* @retval #true Success. +* @retval #false Failure. +* +* @par 依赖: +* @li hi_sdio_device.h:Describe sdio slave APIs.CNcomment:该接口声明所在的头文件。CNend +* @see None。 +*/ +hi_bool hi_sdio_send_sync_msg(hi_u32 msg); + +/** +* @ingroup iot_sdio +* @brief send given message ack +* +* @par 描述: +* Sending a Specified Signal Message.CNcomment:发送指定消息CNend +* +* @attention: + the current sending msg will be overwrite by this msg. + CNcomment: 当前正在发送的消息将该消息覆盖?CNend +* @param msg [IN] type #hi_u32, The message, range [0-31].CNcomment:给定消息,范围[0-31].CNend +* +* @retval #true Success. +* @retval #false Failure. +* +* @par 依赖: +* @li hi_sdio_device.h:Describe sdio slave APIs.CNcomment:该接口声明所在的头文件。CNend +* @see None。 +*/ +hi_bool hi_sdio_send_msg_ack(hi_u32 msg); + +/** +* @ingroup iot_sdio +* @brief Clear given msg and add new msg to pending msg and send. +* +* @par 描述: +* Clear given msg and add new msg in pending msg and send. +CNcomment:清除消息队列中挂起的指定消息,将新消息加入消息队列并发送CNend +* @attention。 +* @param send_msg [IN] type #hi_u32, Message in range [0~31] which will be sent. +CNcomment:指定发送的消息号,范围[0-31]CNend +* @param clear_msg [IN] type #hi_u32, Message in range [0~31] which will be cleard. +CNcomment:指定清除的消息号,范围[0-31]CNend +* +* @retval #true Success. +* @retval #false Failure. +* +* @par 依赖: +* @li hi_sdio_device.h:Describe sdio slave APIs.CNcomment:该接口声明所在的头文件。CNend +* @see None。 +*/ +hi_bool hi_sdio_process_message(hi_u32 send_msg, hi_u32 clear_msg); + +/** +* @ingroup iot_sdio +* @brief sdio is pending given message +* +* @par 描述: +* sdio is pending given message.CNcomment:判断sdio是否挂起指定的消息CNend +* +* @attention。 +* @param msg [IN] type #hi_u32, The message, range [0-31].CNcomment:给定消息,范围[0-31].CNend +* +* @retval #true message at pending status.CNcomment:指定消息处于挂起状态CNend +* @retval #false message at other status. CNcomment:指定消息不处于挂起状态CNend +* +* @par 依赖: +* @li hi_sdio_device.h:Describe sdio slave APIs.CNcomment:该接口声明所在的头文件。CNend +* @see None。 +*/ +hi_u32 hi_sdio_is_pending_message(hi_u32 msg); + +/** +* @ingroup iot_sdio +* @brief Check whether the sdio is sending a specified message. +* +* @par 描述: +* Check whether the sdio is sending a specified message.CNcomment:判断sdio是否正在发送指定的消息CNend +* +* @attention。 +* @param msg [IN] type #hi_u32, The message, range [0-31].CNcomment:给定消息,范围[0-31].CNend +* +* @retval #true The message at sending status.CNcomment:指定消息处于发送状态CNend +* @retval #false The message at other status.CNcomment:指定消息不处于发送状态CNend +* +* @par 依赖: +* @li hi_sdio_device.h:Describe sdio slave APIs.CNcomment:该接口声明所在的头文件。CNend +* @see None。 +*/ +hi_u32 hi_sdio_is_sending_message(hi_u32 msg); + +/** +* @ingroup iot_sdio +* @brief get sdio extend configuration. +* +* @par 描述: +* get sdio extend configuration.CNcomment:获取扩展区配置信息CNend +* +* @attention None +* @param None +* +* @retval hi_sdio_extendfunc* pointer to extend info buffer. +* +* @par 依赖: +* @li hi_sdio_device.h:Describe sdio slave APIs.CNcomment:该接口声明所在的头文件。CNend +* @see None。 +*/ +hi_sdio_extendfunc *hi_sdio_get_extend_info(hi_void); + +/** +* @ingroup iot_sdio +* @brief register callback to notify host msg or data event occurs. +* +* @par 描述: +* register callback to notify host msg or data event occurs. +CNcomment:注册通知Host发送了消息或数据的回调函数。CNend +* +* @attention None +* @param msg_event_callback [IN] type #notify_host_message_event, notify_host_message_event callback function when +* sending msg or data. +CNcomment:消息或数据发送时调用的回调函数CNend +* +* @retval None +* +* @par 依赖: +* @li hi_sdio_device.h:Describe sdio slave APIs.CNcomment:该接口声明所在的头文件。CNend +* @see None。 +*/ +hi_void hi_sdio_register_notify_message_callback(notify_host_message_event msg_event_callback); + +/** +* @ingroup iot_sdio +* @brief set sdio powerdown or not when system enter deep_sleep. +* +* @par 描述: +* set sdio powerdown or not when system enter deep_sleep. +CNcomment:设置系统深睡模式下,SDIO模块是否掉电。CNend +* +* @attention default powerdown.CNcomment:默认掉电.CNend +* @param power_down [IN] type #hi_bool, powerdown or not.CNcomment:是否掉电.CNend +* +* @retval None +* +* @par 依赖: +* @li hi_sdio_device.h:Describe sdio slave APIs.CNcomment:该接口声明所在的头文件。CNend +* @see None。 +*/ +hi_void hi_sdio_set_powerdown_when_deep_sleep(hi_bool power_down); + +/** +* @ingroup iot_sdio +* @brief Init sdio but not wait host clock ready and not wait func1 enable interrupt. +* +* @par 描述: +* Init sdio but not wait host clock ready and not wait func1 enable interrupt. +CNcomment:初始化SDIO,初始化过程中不判断host时钟是否就绪, +不判断是否接收到了使能function1的中断。CNend +* +* @attention None +* @param None +* +* @retval None +* +* @par 依赖: +* @li hi_sdio_device.h:Describe sdio slave APIs.CNcomment:该接口声明所在的头文件。CNend +* @see None。 +*/ +hi_void hi_sdio_init_no_wait(hi_void); + +/** +* @ingroup iot_sdio +* @brief Get whether host clock ready. +* +* @par 描述: +* Get whether host clock ready. +CNcomment:判断HOST时钟是否就绪。CNend +* +* @attention None +* @param None +* +* @retval None +* +* @par 依赖: +* @li hi_sdio_device.h:Describe sdio slave APIs.CNcomment:该接口声明所在的头文件。CNend +* @see None。 +*/ +hi_bool hi_sdio_host_clk_ready(hi_void); + +#endif /* end of hi_sdio_device.h */ diff --git a/sdk_liteos/include/hi_sem.h b/sdk_liteos/include/hi_sem.h new file mode 100644 index 0000000000000000000000000000000000000000..ad508a3de45aeaf25491ff13b601147c0a594f75 --- /dev/null +++ b/sdk_liteos/include/hi_sem.h @@ -0,0 +1,156 @@ +/** +* @file hi_sem.h +* +* Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +* Description: Semaphore APIs.CNcomment:接口。CNend +* +* @li Wait semaphore. In the interrupt function, disable interrupt context, and lock task context, this API must not be +* called. Otherwise, uncontrollable exception scheduling may result.CNcomment:等待信号量:在中断、关中断、 +锁任务上下文禁止调用等待信号量接口,进而产生不可控的异常调度。CNend +* @li Release semaphore.In the disable interrupt context, this API must not be called. Otherwise, uncontrollable +* exception scheduling may result.CNcomment:释放信号量:在关中断上下文禁止调用释放信号量接口, +进而产生不可控的异常调度。CNend \n +* Create: 2019-05-29 +*/ + +/** + * @defgroup iot_sem Semaphore + * @ingroup osa + */ +#ifndef __HI_SEM_H__ +#define __HI_SEM_H__ +#include + +#define HI_SEM_ONE ((hi_u8)1) /**< ucInit Obtained value of the input: Critical resource protection. + CNcomment:输入的取值: 临界资源保护 CNend */ +#define HI_SEM_ZERO ((hi_u8)0) /**< ucInit Obtained value of the input: Synchronization + CNcomment:输入的取值: 同步 CNend */ + +/** +* @ingroup iot_sem +* @brief Creates a semaphore.CNcomment:创建信号量。CNend +* +* @par 描述: +* Creates a semaphore.CNcomment:创建信号量。CNend +* +* @attention The blocking mode (permanent blocking or timing blocking) of the semaphore application operation cannot +* be used in the interrupt, and the interrupt cannot be blocked.CNcomment:信号量申请操作的阻塞模式 +(永久阻塞和定时阻塞)不能在中断中使用,中断不能被阻塞。CNend +* +* @param sem_id [OUT] type #hi_u32*,semaphore ID.CNcomment:信号量ID号。CNend +* @param init_value [IN] type #hi_u16,Number of initialized valid signals. The value range is [0, 0xFFFF]. +CNcomment:有效信号的初始化个数,范围为:[0, 0xFFFF]CNend +* +* @retval #0 Success. +* @retval #Other Failure, for details, see hi_errno.h +* @par 依赖: +* @li hi_sem.h:Describes the semaphore APIs.CNcomment:文件用于描述信号量相关接口。CNend +* @see hi_sem_delete。 +*/ +hi_u32 hi_sem_create(hi_u32 *sem_id, hi_u16 init_value); + + +/** +* @ingroup iot_sem +* @brief Creates a two-value semaphore(0/1).CNcomment:创建二值信号量(0/1)。CNend +* +* @par 描述: +* Creates a two-value semaphore(0/1).CNcomment:创建二值信号量(0/1)。CNend +* +* @attention The blocking mode (permanent blocking or timing blocking) of the semaphore application operation cannot +* be used in the interrupt, and the interrupt cannot be blocked.CNcomment:信号量申请操作的阻塞模式 +(永久阻塞和定时阻塞)不能在中断中使用,中断不能被阻塞。CNend +* +* @param sem_id [OUT] type #hi_u32*,semaphore ID.CNcomment:信号量ID号。CNend +* @param init_value [IN] type #hi_u8,initial value. Generally, when the value is HI_SEM_ONE, the API is used for +* critical resource protection. When the value is HI_SEM_ZERO, the API is used for synchronization. +CNcomment:初始值。一般情况下,当值为HI_SEM_ONE时,用作临界资源保护;当值为HI_SEM_ZERO时,用作同步。CNend +* +* @retval #0 Success. +* @retval #Other Failure, for details, see hi_errno.h +* @par 依赖: +* @li hi_sem.h:Describes the semaphore APIs.CNcomment:文件用于描述信号量相关接口。CNend +* @see hi_sem_delete。 +*/ +hi_u32 hi_sem_bcreate(hi_u32 *sem_id, hi_u8 init_value); + +/** +* @ingroup iot_sem +* @brief Deletes the semaphore.CNcomment:删除信号量。CNend +* +* @par 描述: +* Deletes the semaphore.CNcomment:删除信号量。CNend +* +* @attention The blocking mode (permanent blocking or timing blocking) of the semaphore application operation cannot +* be used in the interrupt, and the interrupt cannot be blocked.CNcomment:信号量申请操作的阻塞模式 +(永久阻塞和定时阻塞)不能在中断中使用,中断不能被阻塞。CNend +* +* @param sem_id [IN] type #hi_u32,semaphore ID.CNcomment:信号量ID号。CNend +* +* @retval #0 Success. +* @retval #Other Failure, for details, see hi_errno.h +* @par 依赖: +* @li hi_sem.h:Describes the semaphore APIs.CNcomment:文件用于描述信号量相关接口。CNend +* @see hi_sem_bcreate。 +*/ +hi_u32 hi_sem_delete(hi_u32 sem_id); + +/** +* @ingroup iot_sem +* @brief Obtains the semaphore.CNcomment:获取信号量。CNend +* +* @par 描述: +* Obtains the semaphore.CNcomment:获取信号量。CNend +* +* +* @attention The blocking mode (permanent blocking or timing blocking) of the semaphore application operation cannot +* be used in the interrupt, and the interrupt cannot be blocked.CNcomment:信号量申请操作的阻塞模式 +(永久阻塞和定时阻塞)不能在中断中使用,中断不能被阻塞。CNend +* +* @param sem_id [IN] type #hi_u32,semaphore ID.CNcomment:信号量ID号。CNend +* @param timeout_ms [IN] type #hi_u32,timeout period (unit: ms). HI_SYS_WAIT_FOREVER indicates permanent wait. +CNcomment:超时时间(单位:ms),HI_SYS_WAIT_FOREVER为永久等待。CNend +* +* @retval #0 Success. +* @retval #Other Failure, for details, see hi_errno.h +* @par 依赖: +* @li hi_sem.h:Describes the semaphore APIs.CNcomment:文件用于描述信号量相关接口。CNend +* @see hi_sem_signal。 +*/ +hi_u32 hi_sem_wait(hi_u32 sem_id, hi_u32 timeout_ms); + +/** +* @ingroup iot_sem +* @brief Releases the semaphore.CNcomment:释放信号量。CNend +* +* @par 描述: +* Releases the semaphore.CNcomment:释放信号量。CNend +* +* @attention The blocking mode (permanent blocking or timing blocking) of the semaphore application operation cannot +* be used in the interrupt, and the interrupt cannot be blocked.CNcomment:信号量申请操作的阻塞模式 +(永久阻塞和定时阻塞)不能在中断中使用,中断不能被阻塞。CNend +* +* @param sem_id [IN] type #hi_u32,semaphore ID.CNcomment:信号量ID号。CNend +* +* @retval #0 Success. +* @retval #Other Failure, for details, see hi_errno.h +* @par 依赖: +* @li hi_sem.h:Describes the semaphore APIs.CNcomment:文件用于描述信号量相关接口。CNend +* @see hi_sem_wait。 +*/ +hi_u32 hi_sem_signal(hi_u32 sem_id); + +#endif + diff --git a/sdk_liteos/include/hi_shell.h b/sdk_liteos/include/hi_shell.h new file mode 100644 index 0000000000000000000000000000000000000000..f2563072b25399318b5e0a1f66012570db33a9c6 --- /dev/null +++ b/sdk_liteos/include/hi_shell.h @@ -0,0 +1,178 @@ +/** + * @file hi_shell.h + * + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** @defgroup iot_shell Shell + * @ingroup dfx + */ + +#ifndef __HI_SHELL_H__ +#define __HI_SHELL_H__ + +#include +#include + +typedef hi_s32 (*hi_shell_input_func)(hi_u8 *data, hi_u32 data_len); +typedef hi_s32 (*hi_shell_output_func)(const hi_u8 *data, hi_u32 data_len); +typedef hi_u32 (*hi_shell_cmd_callback_func)(hi_u32 argc, hi_char **argv); +/** +* @ingroup iot_shell +* @brief Shell initialization function. +CNcomment:SHELL初始化函数。CNend +* +* @par 描述: +* Shell initialization function. +CNcomment:SHELL初始化函数。CNend +* +* @attention None. +* @param None. +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_shell.h:Describes SHELL APIs. +CNcomment:文件用于描述SHELL相关接口。CNend +*/ +hi_u32 hi_shell_init(hi_void); + +/** +* @ingroup iot_shell +* @brief Set taks size of SHELL. CNcomment:设置SHELL相关任务栈大小。CNend +* +* @par 描述: +* Set taks size of SHELL. CNcomment:设置SHELL相关任务栈大小。CNend +* +* @attention shell task stack size needs to be set before shell initialization. +CNcomment:shell任务栈大小需要在shell初始化之前设置。CNend +* @param channel_task_size [IN] type #hi_u16 channel task size,task size should not smaller than 0x600. +CNcomment:通道任务栈大小,任务栈大小不低于0x600。CNend +* @param process_task_size [IN] type #hi_u16 process task size,task size should not smaller than 0xc00. +CNcomment:处理任务栈大小,任务栈大小不低于0xc00。CNend +* +* @retval None +* @par 依赖: +* @li hi_shell.h:Describes SHELL APIs. +CNcomment:文件用于描述SHELL相关接口。CNend +*/ +hi_void hi_shell_set_task_size(hi_u16 channel_task_size, hi_u16 process_task_size); + +/** +* @ingroup iot_shell +* @brief Get shell registered output function. +CNcomment:获取SHELL注册的输出函数。CNend +* +* @par 描述: +* Get shell registered output function. +CNcomment:获取SHELL注册的输出函数。CNend +* +* @attention None. +* @param None. +* +* @retval #g_shell_output_func Shell output function. +* @par 依赖: +* @li hi_shell.h:Describes SHELL APIs. +CNcomment:文件用于描述SHELL相关接口。CNend +*/ +hi_shell_output_func hi_shell_get_register_output_func(hi_void); + +/** +* @ingroup iot_shell +* @brief Register shell input function to replace uart input. +CNcomment:注册SHELL输入函数,代替默认从UART读取SHELL输入数据。CNend +* +* @par 描述: +* Register shell input function to replace uart input. +CNcomment:注册SHELL输入函数,代替默认从UART读取SHELL输入数据。CNend +* +* @attention Should set suitable task size; input func should not continuous read data without break. otherwise, +a watchdog may happen.not support register HI_NULL when shell channel is already uart. +CNcomment:根据输入函数实现,设置合适的栈大小;输入函数不能持续 +返回有效数据避免触发看门狗。当SHELL 通道已经是UART时,不支持注 +册SHELL 输入函数为HI_NULL。CNend +* @param shell_input_func [IN] type #hi_shell_input_func,shell input function. +CNcomment:SHELL输入函数。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_shell.h:Describes SHELL APIs. +CNcomment:文件用于描述SHELL相关接口。CNend +*/ +hi_u32 hi_shell_register_input_func(hi_shell_input_func shell_input_func); + +/** +* @ingroup iot_shell +* @brief Register shell output function to replace uart output. +CNcomment:注册SHELL输出函数,代替默认从UART输出SHELL相关数据。CNend +* +* @par 描述: +* Register shell output function to replace uart output. +CNcomment:注册SHELL输出函数,代替默认从UART输出SHELL相关数据。CNend +* +* @attention Should set suitable task size according to implementation of output func. +CNcomment:根据输出函数实现,设置合适的栈大小。CNend +* @param shell_output_func [IN] type #hi_shell_output_func,shell output function. +CNcomment:SHELL输出函数。CNend +* +* @retval None +* @par 依赖: +* @li hi_shell.h:Describes SHELL APIs. +CNcomment:文件用于描述SHELL相关接口。CNend +*/ +hi_void hi_shell_register_output_func(hi_shell_output_func shell_output_func); + +/** +* @ingroup iot_shell +* @brief Set whether to check the UART busy status when low power vote. +CNcomment:设置低功耗投票时是否检查UART busy状态。CNend +* +* @par 描述: +* Set whether to check the UART busy status when low power vote. +CNcomment:设置低功耗投票时是否检查UART busy状态。CNend +* +* @attention UART busy status is not checked by default. +CNcomment:默认低功耗睡眠投票时不检查UART busy状态。CNend +* @param enable [IN] type #hi_bool,enable status. CNcomment:设置是否检查UART busy状态。CNend +* +* @retval None +* @par 依赖: +* @li hi_diag.h:Describes SHELL APIs. +CNcomment:文件用于描述SHELL相关接口。CNend +*/ +hi_void hi_shell_set_check_uart_busy(hi_bool enable); + +/** +* @ingroup iot_shell +* @brief Registration shell command processing function.CNcomment:注册shell命令处理函数。CNend +* +* @par 描述:Registration shell command processing function.CNcomment:注册shell命令处理函数。CNend +* +* @attention:Only the first 32 command line arguments are recognized, and the remaining parts are not recognized. +CNcomment:仅识别前32个shell命令行参数,32个之后的命令行参数将不被识别。CNend +* @param cmd_key [IN] type #hi_char*,Register command name, the length must be less than 16 bytes. +CNcomment:shell命令名称,命令长度不能大于16字节。CNend +* @param cmd_callback [IN] type #hi_shell_cmd_callback_func,Shell command processing function. +CNcomment:shell命令处理函数。CNend +* +* @retval #HI_ERR_SUCCESS Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_shell.h:Describes SHELL APIs. CNcomment:文件用于描述SHELL相关接口。CNend +* @see None +*/ +hi_u32 hi_shell_cmd_register(hi_char *cmd_key, hi_shell_cmd_callback_func cmd_callback); + +#endif diff --git a/sdk_liteos/include/hi_spi.h b/sdk_liteos/include/hi_spi.h new file mode 100644 index 0000000000000000000000000000000000000000..095dda58f404ece62f784828a57c4400f2289873 --- /dev/null +++ b/sdk_liteos/include/hi_spi.h @@ -0,0 +1,418 @@ +/** + * @file hi_spi.h + * + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * 描述:SPI SDK APIs. CNcomment:SPI SDK调用接口。CNend + * @li Supports synchronous serial communication with external devices as the master or slave. + CNcomment:支持作为Master或Slave与外部设备进行同步串行通信。CNend + * @li The SPI working reference clock is 160 MHz, the maximum output of Master SPI_CLK is 40 MHz, and the maximum + * output of Slave SPI_CLK is 20 MHz. CNcomment:SPI工作参考时钟为160 MHz, + 作为Master SPI_CLK最大输出为40MHz,作为Slave SPI_CLK最大支持20MHz。CNend + * @li Provides two SPIs. The SPI0 provides one TX/RX FIFO for the 16bit×256, and the SPI1 provides one TX/RX + * FIFO for the 16bit×64. CNcomment:提供两路SPI,SPI0提供16bit×256的TX/RX FIFO各一个, + SPI1提供16bit×64的TX/RX FIFO各一个。CNend + * @li Only full-duplex communication is supported. When the half-duplex mode is used, the fixed value is sent. + * When the half-duplex mode is used, the data in the FIFO is discarded. + CNcomment:只支持全双工通信,半双工收时发送固定数值,半双工收时丢弃FIFO中的数据。CNend \n + */ + +/** + * @defgroup iot_spi SPI + * @ingroup drivers + */ + +#ifndef __HI_SPI_H__ +#define __HI_SPI_H__ +#include + +/** +* @ingroup iot_spi +* +* Channel ID, [0,1]. CNcomment:通道ID:0~1。CNend +*/ +typedef enum { + HI_SPI_ID_0 = 0, + HI_SPI_ID_1, +} hi_spi_idx; + +/** +* @ingroup iot_spi +* +* Communication polarity.CNcomment:通信极性。CNend +*/ +typedef enum { + HI_SPI_CFG_CLOCK_CPOL_0, /**< Polarity 0.CNcomment:极性0 CNend */ + HI_SPI_CFG_CLOCK_CPOL_1, /**< Polarity 1.CNcomment:极性1 CNend */ +} hi_spi_cfg_clock_cpol; + +/** +* @ingroup iot_spi +* +* Communication phase.CNcomment:通信相位。CNend +*/ +typedef enum { + HI_SPI_CFG_CLOCK_CPHA_0, /**< Phase 0.CNcomment:相位0 CNend */ + HI_SPI_CFG_CLOCK_CPHA_1, /**< Phase 1.CNcomment:相位1 CNend */ +} hi_spi_cfg_clock_cpha; + +/** +* @ingroup iot_spi +* +* Communication protocol type. CNcomment:通信协议类型。CNend +*/ +typedef enum { + HI_SPI_CFG_FRAM_MODE_MOTOROLA, /**< Motorola protocol.CNcomment:摩托罗拉协议CNend */ + HI_SPI_CFG_FRAM_MODE_TI, /**< Texas Instruments protocol.CNcomment:德州仪器协议CNend */ + HI_SPI_CFG_FRAM_MODE_MICROWIRE, /**< Microwire protocol.CNcomment:Microware协议CNend */ +} hi_spi_cfg_fram_mode; + +/** +* @ingroup iot_spi +* +* Communication bit width, that is, number of valid bits in each frame.CNcomment:通信位宽, +每帧内的有效bit数。CNend +*/ +typedef enum { + HI_SPI_CFG_DATA_WIDTH_E_4BIT = 0x3, /**< The bit width is 4 bits.CNcomment:位宽为4bit CNend */ + HI_SPI_CFG_DATA_WIDTH_E_5BIT, /**< The bit width is 5 bits.CNcomment:位宽为5bit CNend */ + HI_SPI_CFG_DATA_WIDTH_E_6BIT, /**< The bit width is 6 bits.CNcomment:位宽为6bit CNend */ + HI_SPI_CFG_DATA_WIDTH_E_7BIT, /**< The bit width is 7 bits.CNcomment:位宽为7bit CNend */ + HI_SPI_CFG_DATA_WIDTH_E_8BIT, /**< The bit width is 8 bits.CNcomment:位宽为8bit CNend */ + HI_SPI_CFG_DATA_WIDTH_E_9BIT, /**< The bit width is 9 bits.CNcomment:位宽为9bit CNend */ + HI_SPI_CFG_DATA_WIDTH_E_10BIT, /**< The bit width is 10 bits.CNcomment:位宽为10bit CNend */ + HI_SPI_CFG_DATA_WIDTH_E_11BIT, /**< The bit width is 11 bits.CNcomment:位宽为11bit CNend */ + HI_SPI_CFG_DATA_WIDTH_E_12BIT, /**< The bit width is 12 bits.CNcomment:位宽为12bit CNend */ + HI_SPI_CFG_DATA_WIDTH_E_13BIT, /**< The bit width is 13 bits.CNcomment:位宽为13bit CNend */ + HI_SPI_CFG_DATA_WIDTH_E_14BIT, /**< The bit width is 14 bits.CNcomment:位宽为14bit CNend */ + HI_SPI_CFG_DATA_WIDTH_E_15BIT, /**< The bit width is 15 bits.CNcomment:位宽为15bit CNend */ + HI_SPI_CFG_DATA_WIDTH_E_16BIT, /**< The bit width is 16 bits.CNcomment:位宽为16bit CNend */ +} hi_spi_cfg_data_width; + +/** +* @ingroup iot_spi +* +* Communication parameter: big-endian and little-endian transmission of each frame. +CNcomment:通信参数:每帧的传输大小端。CNend +*/ +typedef enum { + HI_SPI_CFG_ENDIAN_LITTLE, /**< Little-endian transmission.CNcomment:小端传输CNend */ + HI_SPI_CFG_ENDIAN_BIG, /**< Big-endian transmission.CNcomment:大端传输CNend */ +} hi_spi_cfg_endian; + +/** +* @ingroup iot_spi +* @brief Type of the SPI callback function.CNcomment:SPI回调函数的类型。CNend +* +* @par 描述: +* Type of the SPI callback function.CNcomment:SPI回调函数的类型。CNend +* +* @attention None +* +* @param None +* +* @retval None +* +* @par 依赖: +* @li hi_spi.h:Describes the SPI APIs.CNcomment:文件用于描述SPI相关接口。CNend +* @see None +*/ +typedef hi_void (*hi_spi_usr_func)(hi_void); + +/** + * @ingroup iot_spi + * + * Data communication parameter.CNcomment:数据通信参数。CNend + */ +typedef struct { + hi_u32 cpol : 1; /**< Communication polarity, type hi_spi_cfg_clock_cpol.CNcomment:通信极性,类型 + 为hi_spi_cfg_clock_cpol。CNend */ + hi_u32 cpha : 1; /**< Communication phase, type hi_spi_cfg_clock_cpha.CNcomment:通信相位,类型 + 为hi_spi_cfg_clock_cpha。CNend */ + hi_u32 fram_mode : 2; /**< Communication protocol type, type hi_spi_cfg_fram_mode.CNcomment:通信协议类型,类型 + 为hi_spi_cfg_fram_mode。CNend */ + hi_u32 data_width : 4; /**< Communication bit width, type hi_spi_cfg_data_width.CNcomment:通信位宽,类型为 + hi_spi_cfg_data_width。 CNend */ + hi_u32 endian : 1; /**< Big-endian and little-endian, type hi_spi_cfg_endian.CNcomment:大小端,类型为 + hi_spi_cfg_endian。CNend */ + hi_u32 pad : 23; /**< Reserve bits.CNcomment:保留位 CNend */ + hi_u32 freq; /**< Communication frequency, ranges 2460Hz-40MHz.CNcomment:通信频率,取值范围 + 2460Hz-40MHz。CNend */ +} hi_spi_cfg_basic_info; + +/** + * @ingroup iot_spi + * + * Data communication parameter.CNcomment:主从设备设置。CNend + */ +typedef struct { + hi_u32 is_slave : 1; + hi_u32 pad : 31; +} hi_spi_cfg_init_param; +/** +* @ingroup iot_spi +* @brief TX interface for the SPI slave mode.CNcomment:SPI从模式发送接口。CNend +* +* @par 描述: +* TX interface for the SPI slave mode.CNcomment:SPI从模式发送接口。CNend +* +* @attention None +* +* @param spi_id [IN] type #hi_spi_idx,SPI ID。 +* @param write_data [IN] type #hi_pvoid,TX data pointer.CNcomment;发送数据指针。CNend +* @param byte_len [IN] type #hi_u32,length of the target data to be sent (unit: byte). +CNcomment:发送数据长度(单位:byte)。CNend +* @param time_out_ms [IN] type #hi_u32,wait timeout period.CNcomment:超时时间。CNend +* +* @retval #0 Success +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_spi.h:Describes the SPI APIs.CNcomment:文件用于描述SPI相关接口。CNend +* @see None +*/ +hi_u32 hi_spi_slave_write(hi_spi_idx spi_id, hi_pvoid write_data, hi_u32 byte_len, hi_u32 time_out_ms); + +/** +* @ingroup iot_spi +* @brief RX interface for the SPI slave mode.CNcomment:SPI从模式接收接口。CNend +* +* @par 描述: +* RX interface for the SPI slave mode.CNcomment:SPI从模式接收接口。CNend +* +* @attention None +* +* @param spi_id [IN] type #hi_spi_idx,SPI ID。 +* @param read_data [OUT] type #hi_pvoid,RX data pointer.CNcomment:接收数据指针。CNend +* @param byte_len [IN] type #hi_u32,length of the target data to be received (unit: byte). +CNcomment:接收数据长度(单位:byte)。CNend +* @param time_out_ms [IN] type #hi_u32,wait timeout period.CNcomment:超时时间。CNend +* +* @retval #0 Success +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_spi.h:Describes the SPI APIs.CNcomment:文件用于描述SPI相关接口。CNend +* @see None +*/ +hi_u32 hi_spi_slave_read(hi_spi_idx spi_id, hi_pvoid read_data, hi_u32 byte_len, hi_u32 time_out_ms); + +/** +* @ingroup iot_spi +* @brief Half-duplex TX interface for the SPI master mode.CNcomment:SPI主模式半双工发送接口。CNend +* +* @par 描述: +* Half-duplex TX interface for the SPI master mode.CNcomment: SPI主模式半双工发送接口。CNend +* +* @attention None +* +* @param spi_id [IN] type #hi_spi_idx,SPI ID。 +* @param write_data [IN] type #hi_pvoid,TX data pointer.CNcomment;发送数据指针。CNend +* @param byte_len [IN] type #hi_u32,length of the target data to be sent (unit: byte). +CNcomment:发送数据长度(单位:byte)。CNend +* +* @retval #0 Success +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_spi.h:Describes the SPI APIs.CNcomment:文件用于描述SPI相关接口。CNend +* @see None +*/ +hi_u32 hi_spi_host_write(hi_spi_idx spi_id, hi_pvoid write_data, hi_u32 byte_len); + +/** +* @ingroup iot_spi +* @brief Half-duplex RX interface for the SPI master mode.CNcomment:SPI主模式半双工接收接口。CNend +* +* @par 描述: +* Half-duplex RX interface for the SPI master mode.CNcomment:SPI主模式半双工接收接口。CNend +* +* @attention None +* +* @param spi_id [IN] type #hi_spi_idx,SPI ID。 +* @param read_data [OUT] type #hi_pvoid,RX data pointer.CNcomment:接收数据指针。CNend +* @param byte_len [IN] type #hi_u32,length of the target data to be received (unit: byte). +CNcomment:接收数据长度(单位:byte)。CNend +* +* @retval #0 Success +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_spi.h:Describes the SPI APIs.CNcomment:文件用于描述SPI相关接口。CNend +* @see None +*/ +hi_u32 hi_spi_host_read(hi_spi_idx spi_id, hi_pvoid read_data, hi_u32 byte_len); + +/** +* @ingroup iot_spi +* @brief Full-duplex TX/RX interface for the SPI master mode.CNcomment:SPI主模式全双工收发接口。CNend +* +* @par 描述: +* Full-duplex TX/RX interface for the SPI master mode.CNcomment:SPI主模式全双工收发接口。CNend +* +* @attention None. +* +* @param spi_id [IN] type #hi_spi_idx,SPI ID。 +* @param write_data [IN] type #hi_pvoid,TX data pointer.CNcomment;发送数据指针。CNend +* @param read_data [OUT] type #hi_pvoid,RX data pointer.CNcomment:接收数据指针。CNend +* @param byte_len [IN] type #hi_u32,length of the target data to be received (unit: byte). +CNcomment:接收数据长度(单位:byte)。CNend +* +* @retval #0 Success +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_spi.h:Describes the SPI APIs.CNcomment:文件用于描述SPI相关接口。CNend +* @see None +*/ +hi_u32 hi_spi_host_writeread(hi_spi_idx spi_id, hi_pvoid write_data, hi_pvoid read_data, hi_u32 byte_len); + + +/** +* @ingroup iot_spi +* @brief Configures the SPI parameter.CNcomment:配置SPI参数。CNend +* +* @par 描述: +* Configures the SPI parameter.CNcomment:配置SPI参数。CNend +* +* @attention None +* +* @param spi_id [IN] type #hi_spi_idx,SPI ID。 +* @param param [IN] type #hi_spi_cfg_basic_info,SPI parameters.CNcomment:SPI参数。CNend +* +* @retval #0 Success +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_spi.h:Describes the SPI APIs.CNcomment:文件用于描述SPI相关接口。CNend +* @see None +*/ +hi_u32 hi_spi_set_basic_info(hi_spi_idx spi_id, const hi_spi_cfg_basic_info *param); + +/** +* @ingroup iot_spi +* @brief Initializes the SPI module.CNcomment:SPI模块初始化。CNend +* +* @par 描述: +* Initializes the SPI module.CNcomment:SPI模块初始化。CNend +* +* @attention To initialize the SPI module, the user needs to perform the initial configuration on the SPI +* information as follows:CNcomment:对SPI模块初始化,用户需要对SPI如下信息进行初始配置:CNend +* @li Clear spi_ctrl to 0.CNcomment:spi_ctrl进行清空为0操作。CNend +* @li Configure the master/slave mode. CNcomment:配置SPI[id]的主/从模式。CNend +* @li Configure the transfer parameters.CNcomment:配置SPI[id]的传输参数。CNend +* +* @param spi_id [IN] type #hi_spi_idx,SPI ID。 +* @param init_param [IN] type #hi_spi_cfg_init_param,initialize as a slave device.CNcomment:是否做为从设备。CNend +* @param param [IN] type #const hi_spi_cfg_basic_info*,configure parameters.CNcomment:初始化SPI设备参数。CNend +* +* @retval #0 Success +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_spi.h:Describes the SPI APIs.CNcomment:文件用于描述SPI相关接口。CNend +* @see None +*/ +hi_u32 hi_spi_init(hi_spi_idx spi_id, hi_spi_cfg_init_param init_param, const hi_spi_cfg_basic_info *param); + +/** +* @ingroup iot_spi +* @brief Deinitializes the SPI module.CNcomment:SPI模块去初始化。CNend +* +* @par 描述: +* Deinitializes the SPI module.CNcomment:SPI模块去初始化。CNend +* +* @attention None +* @param spi_id [IN] type #hi_spi_idx,SPI ID。 +* +* @retval #0 Success +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_spi.h:Describes the SPI APIs.CNcomment:文件用于描述SPI相关接口。CNend +* @see None + */ +hi_u32 hi_spi_deinit(hi_spi_idx spi_id); + +/** +* @ingroup iot_spi +* @brief Set a master spi to use irq mode.CNcomment:设置是否使用中断方式传输数据。CNend +* +* @par 描述: +* Set a master spi to use irq mode.CNcomment:设置是否使用中断方式传输数据。CNend +* +* @attention None +* @param spi_id [IN] type #hi_spi_idx,SPI ID。 +* @param irq_en [IN] type #hi_bool,enable irq. CNcomment:是否使用中断方式。CNend +* +* @retval #0 Success +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_spi.h:Describes the SPI APIs.CNcomment:文件用于描述SPI相关接口。CNend +* @see None +*/ +hi_u32 hi_spi_set_irq_mode(hi_spi_idx id, hi_bool irq_en); + +/** +* @ingroup iot_spi +* @brief Set a master spi to use dma mode.CNcomment:设置slave 模式下是否使用DMA方式传输数据。CNend +* +* @par 描述: +* Set a master spi to use dma mode.CNcomment:设置slave模式下是否使用DMA方式传输数据。CNend +* +* @attention None +* @param spi_id [IN] type #hi_spi_idx,SPI ID。 +* @param dma_en [IN] type #hi_bool,enable dma. CNcomment:是否使用DMA方式。CNend +* +* @retval #0 Success +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_spi.h:Describes the SPI APIs.CNcomment:文件用于描述SPI相关接口。CNend +* @see None +*/ +hi_u32 hi_spi_set_dma_mode(hi_spi_idx id, hi_bool dma_en); + +/** +* @ingroup iot_spi +* @brief Register a user to prepare or restore function.CNcomment:注册用户准备/恢复函数。CNend +* +* @par 描述: +* Register a user to prepare or restore function.CNcomment:注册用户准备/恢复函数。CNend +* +* @attention None +* @param spi_id [IN] type #hi_spi_idx,SPI ID。 +* @param prepare_f [IN] type #hi_spi_usr_func,user prepare function.CNcomment:用户准备函数。CNend +* @param restore_f [IN] type #hi_spi_usr_func,user restore fucntion.CNcomment:用户恢复函数。CNend +* +* @retval #0 Success +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_spi.h:Describes the SPI APIs.CNcomment:文件用于描述SPI相关接口。CNend +* @see None +*/ +hi_u32 hi_spi_register_usr_func(hi_spi_idx id, hi_spi_usr_func prepare_f, hi_spi_usr_func restore_f); + +/** +* @ingroup iot_spi +* @brief Set whether to loopback test mode.CNcomment:设置是否为回环测试模式。CNend +* +* @par 描述: +* Set whether to loopback test mode.CNcomment:设置是否为回环测试模式。CNend +* +* @attention None +* @param id [IN] type #hi_spi_idx,SPI ID.CNcomment:ID 号。CNend +* @param lb_en [IN] type #hi_bool,loop back enable.CNcomment:使能回环模式。CNend +* +* @retval #0 Success +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_spi.h:Describes the SPI APIs.CNcomment:文件用于描述SPI相关接口。CNend +* @see None +*/ +hi_u32 hi_spi_set_loop_back_mode(hi_spi_idx id, hi_bool lb_en); + + +#endif diff --git a/sdk_liteos/include/hi_stdlib.h b/sdk_liteos/include/hi_stdlib.h new file mode 100644 index 0000000000000000000000000000000000000000..9d33ee1ee4242ddae88af102f42ef07a68a5d71a --- /dev/null +++ b/sdk_liteos/include/hi_stdlib.h @@ -0,0 +1,311 @@ +/** +* @file hi_stdlib.h +* +* Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +* Description: A parameter is added to the security C APIs based on the standard C interface, that is, the upper +* limit of the write operation address space to prevent out-of-bounds write. +CNcomment:安全C接口主要是基于标准C接口增加了一个参数,即写操作地址空间上限,从而防止写越界。CNend \n +* Create: 2019-12-18 +*/ + +/** + * @defgroup iot_secure_c Secure C library APIs + * @ingroup iot_secure + */ + +#ifndef __HI_STDLIB_H__ +#define __HI_STDLIB_H__ +#include + +HI_START_HEADER + +#ifndef EOK +#define EOK 0 +#endif + +#ifndef errno_t +typedef int errno_t; +#endif + +#ifndef size_t +typedef unsigned int size_t; +#endif + +/** +* @ingroup iot_secure_c +* @brief Copies the source string to the destination buffer.CNcomment:复制源字符串到目的缓冲区。CNend +* +* @par 描述: Copies the source string to the destination buffer. +CNcomment:复制源字符串到目的缓冲区。CNend +* +* @attention None +* +* @param dest [OUT] type #char *, Destination buffer.CNcomment:目的缓冲区。CNend +* @param dest_max [IN] type #size_t, Size of the destination buffer.CNcomment:目的缓冲区大小。CNend +* @param src [IN] type #const #char *, Source buffer.CNcomment:源缓冲区。CNend +* +* @retval #EOK Success +* @retval #Other Failure +* +* @par 依赖: +* @li hi_stdlib.h: This file declares the APIs.CNcomment:该接口声明所在的头文件。CNend +* @see None +*/ +extern errno_t strcpy_s(char *dest, size_t dest_max, const char *src); + +/** +* @ingroup iot_secure_c +* @brief Copies the source string of a specified length to the destination buffer. +CNcomment:复制指定长度源字符串到目的缓冲区。CNend +* +* @par 描述:Copies the source string of a specified length to the destination buffer. +CNcomment:复制指定长度源字符串到目的缓冲区。CNend +* @attention None +* +* @param dest [IN] type #char *, Destination buffer.CNcomment:目的缓冲区。CNend +* @param dest_max [IN] type #size_t, Size of the destination buffer.CNcomment:目的缓冲区大小。CNend +* @param src [IN] type #const #char *, Source buffer.CNcomment:源缓冲区。CNend +* @param count [IN] type #size_t, Number of characters copied from the source buffer. +CNcomment:从源缓冲区中复制的字符数。CNend +* +* @retval #EOK Success +* @retval #Other Failure +* +* @par 依赖: +* @li hi_stdlib.h: This file declares the APIs.CNcomment:该接口声明所在的头文件。CNend +* @see None +*/ +extern errno_t strncpy_s(char *dest, size_t dest_max, const char *src, size_t count); + +/** +* @ingroup iot_secure_c +* @brief Concatenates the source string to the end of the destination string. +CNcomment:将源字符串连接到目的字符串后面CNend +* +* @par 描述:Concatenates the source string to the end of the destination string. +CNcomment:将源字符串连接到目的字符串后面。CNend +* @attention None +* +* @param dest [IN] type #char *, Destination buffer.CNcomment:目的缓冲区。CNend +* @param dest_max [IN] type #size_t, Size of the destination buffer.CNcomment:目的缓冲区大小。CNend +* @param src [IN] type #const #char *, Source buffer.CNcomment:源缓冲区。CNend +* +* @retval #EOK Success +* @retval #Other Failure +* +* @par 依赖: +* @li hi_stdlib.h: This file declares the APIs.CNcomment:该接口声明所在的头文件。CNend +* @see None +*/ +extern errno_t strcat_s(char *dest, size_t dest_max, const char *src); + +/** +* @ingroup iot_secure_c +* @brief Concatenates the source string of a specified length to the end of the destination string. +CNcomment:将指定长度的源字符串连接到目的字符串后面。CNend +* +* @par 描述: Concatenates the source string of a specified length to the end of the destination string. +CNcomment:将指定长度的源字符串连接到目的字符串后面。CNend +* @attention None +* +* @param dest [IN] type #char *, Destination buffer.CNcomment:目的缓冲区。CNend +* @param dest_max [IN] type #size_t, Size of the destination buffer.CNcomment:目的缓冲区大小。CNend +* @param src [IN] type #const #char *, Source buffer.CNcomment:源缓冲区。CNend +* @param count [IN] type #size_t, Number of characters copied from the source buffer. +CNcomment:从源缓冲区连接的字符数。CNend +* +* @retval #EOK Success +* @retval #Other Failure +* +* @par 依赖: +* @li hi_stdlib.h: This file declares the APIs.CNcomment:该接口声明所在的头文件。CNend +* @see None +*/ +extern errno_t strncat_s(char *dest, size_t dest_max, const char *src, size_t count); + +/** +* @ingroup iot_secure_c +* @brief Copies the data from the source buffer to the destination buffer. +CNcomment:复制源缓冲区的数据到目的缓冲区。CNend +* +* @par 描述: Copies the data from the source buffer to the destination buffer. +CNcomment:复制源缓冲区的数据到目的缓冲区。CNend +* @attention None +* +* @param dest [IN] type #char *, Destination buffer.CNcomment:目的缓冲区。CNend +* @param dest_max [IN] type #size_t, Size of the destination buffer.CNcomment:目的缓冲区大小。CNend +* @param src [IN] type #const #char *, Source buffer.CNcomment:源缓冲区。CNend +* @param count [IN] type #size_t, Number of characters copied from the source buffer. +CNcomment:从源缓冲区中复制的字符数。CNend +* +* @retval #EOK Success +* @retval #Other Failure +* +* @par 依赖: +* @li hi_stdlib.h: This file declares the APIs.CNcomment:该接口声明所在的头文件。CNend +* @see None +*/ +extern errno_t memcpy_s(void *dest, size_t dest_max, const void *src, size_t count); + +/** +* @ingroup iot_secure_c +* @brief Sets the size of the destination buffer to a specific value. +CNcomment:设置目的缓冲区为特定值。CNend +* +* @par 描述: Sets the size of the destination buffer to a specific value. +CNcomment:设置目的缓冲区为特定值。CNend +* @attention None +* +* @param dest [IN] type #char *, Destination buffer.CNcomment:目的缓冲区。CNend +* @param dest_max [IN] type #size_t, Size of the destination buffer.CNcomment:目的缓冲区大小。CNend +* @param c [IN] type #const #char *, Source buffer.CNcomment:特定值。CNend +* @param count [IN] type #size_t, Number of characters copied from the source buffer. +CNcomment:设置为特定值的字符数。CNend +* +* @retval #EOK Success +* @retval #Other Failure +* +* @par 依赖: +* @li hi_stdlib.h: This file declares the APIs.CNcomment:该接口声明所在的头文件。CNend +* @see None +*/ +extern errno_t memset_s(void *dest, size_t dest_max, int c, size_t count); + +/** +* @ingroup iot_secure_c +* @brief Moves the data from the source buffer to the destination buffer. +CNcomment:移动源缓冲区的数据到目的缓冲区。CNend +* +* @par 描述:Moves the data from the source buffer to the destination buffer. +CNcomment:移动源缓冲区的数据到目的缓冲区。CNend +* @attention None +* +* @param dest [IN] type #char *, Destination buffer.CNcomment:目的缓冲区。CNend +* @param dest_max [IN] type #size_t, Size of the destination buffer.CNcomment:目的缓冲区大小。CNend +* @param src [IN] type #const #char *, Source buffer.CNcomment:源缓冲区。CNend +* @param count [IN] type #size_t, Number of characters copied from the source buffer. +CNcomment:从源缓冲区中移动的字符数。CNend +* +* @retval #EOK Success +* @retval #Other Failure +* +* @par 依赖: +* @li hi_stdlib.h: This file declares the APIs.CNcomment:该接口声明所在的头文件。CNend +* @see None +*/ +extern errno_t memmove_s(void *dest, size_t dest_max, const void *src, size_t count); + +/** +* @ingroup iot_secure_c +* @brief Splits a string into substrings according to the specified separators. +CNcomment:将字符串按照指定的分隔符分割成子字符串。CNend +* +* @par 描述: Splits a string into substrings according to the specified separators. +CNcomment:将字符串按照指定的分隔符分割成子字符串。CNend +* @attention None +* +* @param token [IN] type #char *。 String to be split.CNcomment:要分割的字符串。CNend +* @param delimit [IN] type #const char *。 String separator.CNcomment:字符串分隔符。CNend +* @param context [IN] type #char** 。Position information after a call to HI_strtok_s is saved. +CNcomment:保存调用HI_strtok_s后的位置信息。CNend +* +* @retval #char* Point to the next token. CNcomment:指向在token中的下一个token。CNend +* @retval #HI_NULL A specified substring is not found or an error occurs. +CNcomment:没有找到指定的子字符串或者发生错误。CNend +* +* @par 依赖: +* @li hi_stdlib.h: This file declares the APIs.CNcomment:该接口声明所在的头文件。CNend +* @see None +*/ +extern char *strtok_s(char *token, const char *delimit, char **context); + +/** +* @ingroup iot_secure_c +* @brief Formats the data and outputs it to the destination buffer. +CNcomment:将数据格式化输出到目的缓冲区。CNend +* +* @par 描述: Formats the data and outputs it to the destination buffer. +CNcomment:将数据格式化输出到目的缓冲区。CNend +* @attention None +* +* @param dest [OUT] type #char *。 Destination buffer.CNcomment:目的缓冲区。CNend +* @param dest_max [IN] type #size_t。 Size of the destination buffer.CNcomment:目的缓冲区大小。CNend +* @param format [IN] type #const #char *。 Formatting control string.CNcomment:格式化控制字符串。CNend +* @param ... [IN] Optional parameter CNcomment:可选参数。CNend +* +* @retval #>=0 Return the number of bytes stored in dest, not counting the terminating null character. +CNcomment:返回存储在dest的字节数,不包括结束符CNend +* @retval #-1 Failure +* +* @par 依赖: +* @li hi_stdlib.h: This file declares the APIs.CNcomment:该接口声明所在的头文件。CNend +* @see None +*/ +extern int sprintf_s(char *dest, size_t dest_max, const char *format, ...); + +/** +* @ingroup iot_secure_c +* @brief Formats the data according to a specified length and outputs the data to the destination buffer. +CNcomment:将数据按照指定长度格式化输出到目的缓冲区。CNend +* +* @par 描述: Formats the data according to a specified length and outputs the data to the destination buffer. +CNcomment:将数据按照指定长度格式化输出到目的缓冲区。CNend +* @attention None +* +* @param dest [OUT] type #char *。 Destination buffer.CNcomment:目的缓冲区。CNend +* @param dest_max [IN] type #size_t。 Size of the destination buffer.CNcomment:目的缓冲区大小。CNend +* @param count [IN] type #size_t。 Number of formatted characters to be output to the destination buffer. +CNcomment:要输出到目的缓冲区的格式化字符个数。CNend +* @param format [IN] type #const #char *。 Formatting control string.CNcomment:格式化控制字符串。CNend +* @param ... [IN] Optional parameter CNcomment:可选参数。CNend +* +* @retval #>=0 Return the number of bytes stored in dest, not counting the terminating null character. +CNcomment:返回存储在dest的字节数,不包括结束符CNend +* @retval #-1 Failure +* +* @par 依赖: +* @li hi_stdlib.h: This file declares the APIs.CNcomment:该接口声明所在的头文件。CNend +* @see None +*/ +extern int snprintf_s(char *dest, size_t dest_max, size_t count, const char *format, ...); + +extern int memcmp(const void *str1, const void *str2, size_t n); +extern size_t strlen(const char *src); +extern int strcmp(const char *str1, const char *str2); +extern int strncmp(const char *str1, const char *str2, size_t n); + +#if defined(HAVE_PCLINT_CHECK) +#define UT_CONST const +#else +#define UT_CONST +#endif + +extern unsigned long strtoul(const char *nptr, char **endptr, int base); +extern UT_CONST char *strstr(const char *str1, const char *str2); +extern UT_CONST char *strchr(const char *s, int c); +extern char *strcpy(char* dest, const char *src); +extern char* strsep(char** __s_ptr, const char* __delimiter); +extern long strtol(const char *nptr, char **endptr, int base); + +extern int atoi (const char *s); + +extern void *memset(void *s, int ch, size_t n); +extern void* memmove(void* dst, const void* src, size_t n); +extern void* memcpy(void* dst, const void* src, size_t n); + + +HI_END_HEADER +#endif /* __HI_STDLIB_H__ */ + diff --git a/sdk_liteos/include/hi_systick.h b/sdk_liteos/include/hi_systick.h new file mode 100644 index 0000000000000000000000000000000000000000..824e33fa1edf1e2c5a0e2fc603965b3c3dd5672a --- /dev/null +++ b/sdk_liteos/include/hi_systick.h @@ -0,0 +1,122 @@ +/** + * @file hi_systick.h + * + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @defgroup systick System Tick Status + * @ingroup drivers + */ +#ifndef __HI_SYSTICK_H__ +#define __HI_SYSTICK_H__ +#include + +/** +* @ingroup systick +* @brief Obtains systick currect value. CNcomment:获取systick当前计数值。CNend +* +* @par 描述: +* @li Obtains the current count value of systick. The time of each value is determined by the systick clock source. +* The systick clock is 32Khz, and the tick value is 1/32000 seconds.CNcomment:获取systick当前计数值。 +每个值的时间由systick时钟源决定。systick时钟为32Khz,一个tick值为1/32000秒。CNend +* $li After the system is powered on, systick immediately adds a count from 0.CNcomment:系统上电运行后, +systick立刻从0开始递增加一计数。CNend +* +* @attention The delay interface is invoked in the interface. Therefore, it is prohibited to invoke this interface in +* the interrupt context.CNcomment:接口内调用了延时接口,所以禁止在中断上下文中调用该接口。CNend +* @param None +* +* @retval #hi_u64 Indicates the obtained current count value.CNcomment:获取到的当前计数值。CNend +* +* @par 依赖: +* @li hi_systick.h:Describes systick APIs.CNcomment:文件用于描述SYSTICK相关接口。CNend +* @see hi_systick_clear。 +*/ +hi_u64 hi_systick_get_cur_tick(hi_void); + +/** +* @ingroup systick +* @brief The value of systick is cleared.CNcomment:将systick计数值清零。CNend +* +* @par 描述: +* The value of systick is cleared.CNcomment:将systick计数值清零。CNend +* +* @attention After the interface is returned, the clock cycles of three systick clocks need to be cleared. +CNcomment:接口返回后需要等三个systick的时钟周期才会完成清零。CNend +* @param None +* +* @retval None +* @par 依赖: +* @li hi_systick.h:Describes systick APIs.CNcomment:文件用于描述SYSTICK相关接口。CNend +* @see hi_systick_get_cur_tick。 +*/ +hi_void hi_systick_clear(hi_void); + +/** +* @ingroup systick +* @brief Get the millisecond value counted by systick. CNcomment:获取以systick计数的毫秒值。CNend +* +* @par 描述: +* @li Calculate the current millisecond value according to the current value of systick and the actual frequency of +32K.CNcomment:根据systick的当前值与32K实际的频率计算当前的毫秒值。CNend +* +* @attention The delay interface is invoked in the interface. Therefore, it is prohibited to invoke this interface in +* the interrupt context.CNcomment:接口内调用了延时接口,所以禁止在中断上下文中调用该接口。CNend +* @param None +* +* @retval #hi_u64 Indicates the obtained current millisecond.CNcomment:获取到的当前毫秒计数值。CNend +* +* @par 依赖: +* @li hi_systick.h:Describes systick APIs.CNcomment:文件用于描述SYSTICK相关接口。CNend +* @see hi_systick_get_cur_ms。 +*/ +hi_u64 hi_systick_get_cur_ms(hi_void); + +/** +* @ingroup systick +* @brief Sets the real time of the system, base on systick, not effect by deep sleep. +CNcomment:设置系统实时时间,基于systick,不受深睡影响。CNend +* +* @par 描述: +* Sets the real time of the system.CNcomment:设置系统实时时间。CNend +* +* @attention None +* @param seconds [IN] type #hi_u32,set the real time of the system to this value. +CNcomment:将系统实时时间设置为该值。CNend +* +* @retval None. +* @par 依赖: +* @li hi_systick.h:Describes systick APIs.CNcomment:文件用于描述SYSTICK相关接口。CNend +*/ +hi_void hi_systick_set_real_time(hi_u32 sec); + +/** +* @ingroup systick +* @brief Obtains the real time of the system, base on systick, not effect by deep sleep +CNcomment:获取系统实时时间(单位:s),基于systick,不受深睡影响。CNend +* +* @par 描述: +* Obtains the real time of the system (unit: s).CNcomment:获取系统实时时间(单位:s)。CNend +* +* @attention None +* @param None +* +* @retval #hi_u32 Real time of the system.CNcomment: 系统实时时间。CNend +* @par 依赖: +* @li hi_systick.h:Describes systick APIs.CNcomment:文件用于描述SYSTICK相关接口。CNend +*/ +hi_u32 hi_systick_get_real_time(hi_void); + +#endif diff --git a/sdk_liteos/include/hi_task.h b/sdk_liteos/include/hi_task.h new file mode 100644 index 0000000000000000000000000000000000000000..863795bd165598571fae554fdf75181a37b77530 --- /dev/null +++ b/sdk_liteos/include/hi_task.h @@ -0,0 +1,361 @@ +/** + * @file hi_task.h + * + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @defgroup iot_task Task + * @ingroup osa + */ +#ifndef __HI_TASK_H__ +#define __HI_TASK_H__ + +#include + +#define HI_INVALID_TASK_ID 0xFFFFFFFF +#define HI_TASK_NAME_LEN 32 +#define HI_DEFAULT_TSKNAME "default" /**< hi_task_attr default value. CNcomment:hi_task_attr的默认值CNend */ +#define HI_DEFAULT_TSKPRIO 20 /**< hi_task_attr default value. CNcomment:hi_task_attr的默认值CNend */ +#define HI_DEFAULT_STACKSIZE (4 * 1024) /**< hi_task_attr default value. CNcomment:hi_task_attr的默认值CNend */ +#define NOT_BIND_CPU (-1) + +typedef struct { + hi_char name[HI_TASK_NAME_LEN]; /**< Task entrance function.CNcomment:入口函数CNend */ + hi_u32 id; /**< Task ID.CNcomment:任务ID CNend */ + hi_u16 status; /**< Task status.CNcomment:任务状态 CNend */ + hi_u16 priority; /**< Task priority.CNcomment:任务优先级 CNend */ + hi_pvoid task_sem; /**< Semaphore pointer.CNcomment:信号量指针CNend */ + hi_pvoid task_mutex; /**< Mutex pointer.CNcomment:互斥锁指针CNend */ + hi_u32 event_stru[3]; /**< Event: 3 nums.CNcomment:3个事件CNend */ + hi_u32 event_mask; /**< Event mask.CNcomment:事件掩码CNend */ + hi_u32 stack_size; /**< Task stack size.CNcomment:栈大小CNend */ + hi_u32 top_of_stack; /**< Task stack top.CNcomment:栈顶CNend */ + hi_u32 bottom_of_stack; /**< Task stack bottom.CNcomment:栈底CNend */ + hi_u32 mstatus; /**< Task current mstatus.CNcomment:当前mstatusCNend */ + hi_u32 mepc; /**< Task current mepc.CNcomment:当前mepc.CNend */ + hi_u32 tp; /**< Task current tp.CNcomment:当前tp.CNend */ + hi_u32 ra; /**< Task current ra.CNcomment:当前ra.CNend */ + hi_u32 sp; /**< Task SP pointer.CNcomment:当前SP.CNend */ + hi_u32 curr_used; /**< Current task stack usage.CNcomment:当前任务栈使用率CNend */ + hi_u32 peak_used; /**< Task stack usage peak.CNcomment:栈使用峰值CNend */ + hi_u32 overflow_flag; /**< Flag that indicates whether a task stack overflow occurs. + CNcomment:栈溢出标记位CNend */ +} hi_task_info; + +typedef struct { + hi_u16 task_prio; + hi_u32 stack_size; + hi_u32 task_policy; + hi_u32 task_nice; + hi_u32 task_cpuid; + hi_char *task_name; + hi_void *resved; +} hi_task_attr; + +/** +* @ingroup iot_task +* @brief Creates a task.CNcomment:创建任务。CNend +* +* @par 描述: +* Creates a task.CNcomment:创建任务。CNend +* +* @attention +* @li The space occupied by a task name string must be applied for by the caller and saved statically. +* The task name is not stored internally in the API.CNcomment:任务名字符串占用空间需要调用者 + 申请并静态保存,接口内部不对任务名进行存储。CNend +* @li If the size of the specified task stack is 0, use the default size specified by +* #OS_TSK_DEFAULT_STACK_SIZE. CNcomment:若指定的任务栈大小为0,则使用配置项 + HI_DEFAULT_STACKSIZE指定默认的任务栈大小。CNend +* @li The size of the task stack should be 8-byte aligned. The principle for determining the task stack +* size is as follows: Do not use a too large or too small task stack size (to avoid waste or +* overflow).CNcomment:任务栈的大小按8byte大小对齐。确定任务栈大小的原则:够用即可(多则浪费, + 少则任务栈溢出)。CNend +* @li The recommended user priority should be within the range of [10, 30]. Do not use the priorities of +* [0, 5] and [31].CNcomment:用户优先级配置建议使用[10,30],切记不可使用[0,5]和[31]号的优先级。CNend +* +* @param taskid [OUT] type #hi_u32*,task ID.CNcomment:任务ID号。CNend +* @param attr [IN] type #const task_attr_t*,task attributes,when NULL was set here,the properties + are configured as follows: task_name:"default" task_prio:20 stack_size:(4*1024) + CNcomment:任务属性,当该值为空时配置如下:任务名:"default" + 任务优先级:20 任务栈大小:(4*1024),CNend +* @param task_route [IN] type #task_route task entry function.CNcomment:任务入口函数。CNend +* @param arg [IN] type #hi_void*,parameter that needs to be input to the task entry when a task is +* created. If this parameter does not need to be input, set this parameter to 0. + CNcomment:创建任务时需要传给任务入口的参数。如果不需要传递,参数直接填0。CNend +* +* @retval #0 Success +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_task.h:Describes the task APIs.CNcomment:文件用于描述任务相关接口。CNend +* @see hi_task_delete。 +*/ +hi_u32 hi_task_create(hi_u32 *taskid, const hi_task_attr *attr, + hi_void* (*task_route)(hi_void *), hi_void *arg); + +/** +* @ingroup iot_task +* @brief Deletes a task.CNcomment:删除任务。CNend +* +* @par 描述: +* Deletes a task.CNcomment:删除任务。CNend +* +* @attention +* @li Use this API with caution. A task can be deleted only after the confirmation of the user. The idle task +* and Swt_Task cannot be deleted.idle.CNcomment:任务及Swt_Task任务不能被删除。CNend +* @li When deleting a task, ensure that the resources (such as mutex and semaphore) applied by the task have +* been released.在删除任务时要保证任务申请的资源(如互斥锁、信号量等)已被释放。CNend +* +* @param taskid [IN] type #hi_u32,task ID. CNcomment:任务ID号。CNend +* +* @retval #0 Success +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_task.h:Describes the task APIs.CNcomment:文件用于描述任务相关接口。CNend +* @see hi_task_create。 +*/ +hi_u32 hi_task_delete(hi_u32 taskid); + +/** +* @ingroup iot_task +* @brief Suspends a task.CNcomment:挂起任务。CNend +* +* @par 描述: +* Suspends a task.CNcomment:挂起指定任务。CNend +* +* @attention +* @li A task cannot be suspended if it is the current task and is locked. +CNcomment:挂起任务的时候若为当前任务且已锁任务,则不能被挂起。CNend +* @li The idle task and Swt_Task cannot be suspended. +CNcomment:idle任务及Swt_Task任务不能被挂起。CNend +* @li The task cannot be blocked or suspended in the lock task status. +CNcomment:在锁任务调度状态下,禁止任务阻塞。CNend +* +* @param taskid [IN] type #hi_u32,task ID. CNcomment:任务ID号。CNend +* +* @retval #0 Success +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_task.h:Describes the task APIs.CNcomment:文件用于描述任务相关接口。CNend +* @see hi_task_resume。 +*/ +hi_u32 hi_task_suspend(hi_u32 taskid); + +/** +* @ingroup iot_task +* @brief Resumes a task.CNcomment:恢复挂起任务。CNend +* +* @par 描述: +* Resumes a task.CNcomment:恢复挂起指定任务。CNend +* +* @attention None +* @param taskid [IN] type #hi_u32,task ID. CNcomment:任务ID号。CNend +* +* @retval #0 Success +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_task.h:Describes the task APIs.CNcomment:文件用于描述任务相关接口。CNend +* @see hi_task_suspend。 +*/ +hi_u32 hi_task_resume(hi_u32 taskid); + +/** +* @ingroup iot_task +* @brief Obtains the task priority.CNcomment:获取任务优先级。CNend +* +* @par 描述: +* Obtains the task priority.CNcomment:获取任务优先级。CNend +* +* @attention None +* +* @param taskid [IN] type #hi_u32,task ID. CNcomment:任务ID号。CNend +* @param priority [OUT] type #hi_u32*,task priority.CNcomment:任务优先级。CNend +* +* @retval #0 Success +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_task.h:Describes the task APIs.CNcomment:文件用于描述任务相关接口。CNend +* @see hi_task_set_priority。 +*/ +hi_u32 hi_task_get_priority(hi_u32 taskid, hi_u32 *priority); + +/** +* @ingroup iot_task +* @brief Sets the task priority.CNcomment:设置任务优先级。CNend +* +* @par 描述: + Sets the task priority.CNcomment:设置任务优先级。CNend +* +* @attention +* @li Only the ID of the task created by the user can be configured. +CNcomment:仅可配置用户自己创建的任务ID。CNend +* @li The recommended user priority should be within the range of [10, 30]. Do not use the priorities of +* [0, 5] and [31].CNcomment:用户优先级配置建议使用[10,30],切记不可使用[0,5]和[31]号的优先级。CNend +* @li Setting user priorities may affect task scheduling. The user needs to plan tasks in the SDK. +CNcomment:设置用户优先级有可能影响任务调度,用户需要SDK中对各任务统一规划。CNend +* +* @param taskid [IN] type #hi_u32,task ID. CNcomment:任务ID号。CNend +* @param priority [IN] type #hi_u32,task priority.CNcomment:任务优先级。CNend +* +* @retval #0 Success +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_task.h:Describes the task APIs.CNcomment:文件用于描述任务相关接口。CNend +* @see hi_task_get_priority。 +*/ +hi_u32 hi_task_set_priority(hi_u32 taskid, hi_u32 priority); + +/** +* @ingroup iot_task +* @brief Obtains the task information.CNcomment:获取任务信息。CNend +* +* @par 描述: +* Obtains the task information.CNcomment:获取任务信息。CNend +* +* @attention None +* @param taskid [IN] type #hi_u32,task ID. CNcomment:任务ID号。CNend +* @param inf [OUT] type #hi_task_info* ,task information.CNcomment:任务信息。CNend +* +* @retval #0 Success +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_task.h:Describes the task APIs.CNcomment:文件用于描述任务相关接口。CNend +* @see None +*/ +hi_u32 hi_task_get_info(hi_u32 taskid, hi_task_info *inf); + +/** +* @ingroup iot_task +* @brief Obtains the current task ID.CNcomment:获取当前任务ID。CNend +* +* @par 描述: +* Obtains the current task ID.CNcomment:获取当前任务ID。CNend +* +* @attention None +* @param None +* +* @retval #hi_u32 Task ID. If the task fails, #HI_INVALID_TASK_ID is returned. +CNcomment:任务ID,失败返回#HI_INVALID_TASK_ID。CNend +* @par 依赖: +* @li hi_task.h:Describes the task APIs.CNcomment:文件用于描述任务相关接口。CNend +* @see None +*/ +hi_u32 hi_task_get_current_id(hi_void); + +/** +* @ingroup iot_task +* @brief Lock task switch.CNcomment:禁止系统任务调度。CNend +* +* @par 描述: +* Lock task switch.CNcomment:禁止系统任务调度。CNend +* +* @attention Work pair with hi_task_unlock.CNcomment:与hi_task_unlock配对使用。CNend +* @param None +* +* @retval None +* @par 依赖: +* @li hi_task.h:Describes the task APIs.CNcomment:文件用于描述任务相关接口。CNend +* @see None +*/ +hi_void hi_task_lock(hi_void); + +/** +* @ingroup iot_task +* @brief Unlock task switch. CNcomment:允许系统任务调度。CNend +* +* @par 描述: +* Unlock task switch. CNcomment:允许系统任务调度。CNend +* +* @attention Work pair with hi_task_lock; Call hi_task_lock to disable task switch, then call hi_task_unlock +* reenable it. +CNcomment:与hi_task_lock配对使用;先调用hi_task_lock禁止任务调度,然后调用hi_task_unlock打开任务调度。CNend +* @param None +* +* @retval None +* @par 依赖: +* @li hi_task.h:Describes the task APIs.CNcomment:文件用于描述任务相关接口。CNend +* @see None +*/ +hi_void hi_task_unlock(hi_void); + +/** +* @ingroup iot_task +* @brief Task sleep.CNcomment:任务睡眠。CNend +* +* @par 描述: +* Task sleep.CNcomment:任务睡眠。CNend +* +* @attention +* @li In the interrupt processing function or in the case of a lock task, the hi_sleep operation fails. +CNcomment:在中断处理函数中或者在锁任务的情况下,执行hi_sleep操作会失败。CNend +* @li When less than 10 ms, the input parameter value should be replaced by 10 ms. When greater than 10 ms, +* the input parameter value should be exactly divided and then rounded-down to the nearest integer. +CNcomment:入参小于10ms时,当做10ms处理,Tick=1;大于10ms时,整除向下对齐,Tick = ms/10。CNend +* @li This function cannot be used for precise timing and will be woken up after Tick system scheduling. +* The actual sleep time is related to the time consumed by the Tick when the function is called. +CNcomment:本函数不能用于精确计时,将在Tick个系统调度后唤醒,实际睡眠时间与函数被调用时该Tick已消耗的时间相关。CNend +* @param ms [IN] type #hi_u32,sleep time (unit: ms). The precision is 10 ms. +CNcomment:睡眠时间(单位:ms),精度为10ms。CNend +* +* @retval #0 Success +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_task.h:Describes the task APIs.CNcomment:文件用于描述任务相关接口。CNend +* @see None +*/ +hi_u32 hi_sleep(hi_u32 ms); + +/** +* @ingroup iot_task +* @brief Regiseter idle task callback.CNcomment:注册idle任务回调函数。CNend +* +* @par 描述: +* Regiseter idle task callback, if callback is NULL, means cancel registration. +CNcomment:注册idle任务回调函数,如果回调函数为空,表示取消注册。CNend +* +* @attention +* @li lowper sleep process handle after callback, callback should not contain complicated +operations that affect lowpower process . +CNcomment:低功耗睡眠处理在idle回调执行之后,回调函数避免处理复杂操作影响低功耗流程。CNend +* @li When less than 10 ms, the input parameter value should be replaced by 10 ms. When greater than 10 ms, +* @param cb [IN] type #hi_void_callback, callback in idle task.CNcomment:idle任务中的回调函数。CNend +* +* @retval #None +* @par 依赖: +* @li hi_task.h:Describes the task APIs.CNcomment:文件用于描述任务相关接口。CNend +* @see None +*/ +hi_void hi_task_register_idle_callback(hi_void_callback cb); + +/** +* @ingroup iot_task +* @brief Wait task excute finish.CNcomment:等待任务执行结束。CNend +* +* @par 描述: +* Wait task excute finish.CNcomment:等待任务执行结束。CNend +* +* @attention None +* @param taskid [IN] type #hi_u32, task id of the task to be waited finish. +CNcomment:被等待结束的任务ID。CNend +* @param wait_interval [IN] type #hi_u32, interval time of query task status when waiting. at least one tick. +CNcomment:等待时查询任务状态的间隔时间,至少间隔1个Tick。CNend +* +* @retval #None +* @par 依赖: +* @li hi_task.h:Describes the task APIs.CNcomment:文件用于描述任务相关接口。CNend +* @see None +*/ +hi_void hi_task_join(hi_u32 taskid, hi_u32 wait_interval); + +#endif diff --git a/sdk_liteos/include/hi_time.h b/sdk_liteos/include/hi_time.h new file mode 100644 index 0000000000000000000000000000000000000000..251ef1004daa16abc35b8d17157cdb8060babd04 --- /dev/null +++ b/sdk_liteos/include/hi_time.h @@ -0,0 +1,219 @@ +/** +* @file hi_time.h +* +* Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +* Description: time APIs.CNcomment:时间接口描述CNend +* @li System time of the hi_get_tick, hi_get_tick64, hi_get_milli_seconds, and hi_get_seconds operations. The system +* time is calculated starting from kernel startup and cannot be modified through APIs. +CNcomment:hi_get_tick, hi_get_tick64,hi_get_milli_seconds, hi_get_seconds操作的系统时间, +系统时间从kernel启动开始计时,不可以通过接口进行修改。CNend +* @li The hi_get_real_time and hi_set_real_time APIs are about real-time operations. The real time is calculated +* starting from kernel startup and can be modified by hi_set_real_time.CNcomment:hi_get_real_time, +hi_set_real_time操作的是实时时间,实时时间从kernel启动开始计时,可以通过hi_set_real_time进行修改。CNend \n +* Author: Hisilicon \n +* Create: 2019-05-29 +*/ + +/** + * @defgroup iot_time System Clock + * @ingroup osa + */ +#ifndef __HI_TIME_H__ +#define __HI_TIME_H__ +#include + +/** +* @ingroup iot_time +* @brief Delay, in microseconds.CNcomment:延时,微秒级。CNend +* +* @par 描述: +* Delay operation implemented by software based on the system clock, blocking the CPU. +CNcomment:延时操作,阻塞CPU。CNend +* +* @attention This API cannot be used for a long time in an interrupt.CNcomment:不允许中断中使用。CNend +* +* @param us [IN] type #hi_u32,delay period (unit: microsecond). +CNcomment:延时时间(单位:μs)。CNend +* +* @retval None +* @par 依赖: +* @li hi_time.h:Describes system time APIs.CNcomment:文件包含系统时间相关接口。CNend +* @see None +*/ +hi_void hi_udelay(hi_u32 us); + +/** +* @ingroup iot_time +* @brief Obtains the tick value of the system (32-bit).CNcomment:获取系统tick值(32bit)。CNend +* +* @par 描述: +* Obtains the tick value of the system (32-bit).CNcomment:获取系统tick值(32bit)。CNend +* +* @attention None +* @param None +* +* @retval #hi_u32 Tick value of the system.CNcomment:系统tick值。CNend +* @par 依赖: +* @li hi_time.h:Describes system time APIs.CNcomment:文件包含系统时间相关接口。CNend +*/ +hi_u32 hi_get_tick(hi_void); + +/** +* @ingroup iot_time +* @brief Obtains the tick value of the system (64-bit).CNcomment:获取系统tick值(64bit)。CNend +* +* @par 描述: +* Obtains the tick value of the system (64-bit).CNcomment:获取系统tick值(64bit)。CNend +* +* @attention The hi_mdm_time.h file must be included where the API is called. Otherwise, the API is considered not +* declared, and the tick value is returned as an int type, resulting in a truncation error. +CNcomment:该接口调用处必须包含头文件hi_time.h,否则按照未声明接口处理,会将tick值当做int类型返回,产生截断错误。CNend +* @param None +* +* @retval #hi_u64 Tick value of the system.CNcomment:系统tick值。CNend +* @par 依赖: +* @li hi_time.h:Describes system time APIs.CNcomment:文件包含系统时间相关接口。CNend +*/ +hi_u64 hi_get_tick64(hi_void); + +/** +* @ingroup iot_time +* @brief Obtains the system time (unit: ms).CNcomment:获取系统时间(单位:ms)。CNend +* +* @par 描述: +* Obtains the system time (unit: ms).CNcomment:获取系统时间(单位:ms)。CNend +* +* @attention None +* @param None +* +* @retval #hi_u32 System time.CNcomment:系统时间。CNend +* @par 依赖: +* @li hi_time.h:Describes system time APIs.CNcomment:文件包含系统时间相关接口。CNend +*/ +hi_u32 hi_get_milli_seconds(hi_void); + +/** +* @ingroup iot_time +* @brief Obtains the system time (unit: s).CNcomment:获取系统时间(单位:s)。CNend +* +* @par 描述: +* Obtains the system time (unit: s).CNcomment:获取系统时间(单位:s)。CNend +* +* @attention None +* @param None +* +* @retval #hi_u32 System time.CNcomment:系统时间。CNend +* @retval #HI_ERR_FAILURE failed to be obtained. CNcomment:获取时间失败。CNend +* @par 依赖: +* @li hi_time.h:Describes system time APIs.CNcomment:文件包含系统时间相关接口。CNend +*/ +hi_u32 hi_get_seconds(hi_void); + +/** +* @ingroup iot_time +* @brief Obtains the system time (unit: us).CNcomment:获取系统时间(单位:us)。CNend +* +* @par 描述: +* Obtains the system time (unit: us).CNcomment:获取系统时间(单位:us)。CNend +* +* @attention None +* @param None +* +* @retval #hi_u64 System time.CNcomment:系统时间。CNend +* @retval #HI_ERR_FAILURE failed to be obtained. CNcomment:获取时间失败。CNend +* @par 依赖: +* @li hi_time.h:Describes system time APIs.CNcomment:文件包含系统时间相关接口。CNend +*/ +hi_u64 hi_get_us(hi_void); + +/** +* @ingroup iot_time +* @brief Obtains the real time of the system (unit: s).CNcomment:获取系统实时时间(单位:s)。CNend +* +* @par 描述: +* Obtains the real time of the system (unit: s).CNcomment:获取系统实时时间(单位:s)。CNend +* +* @attention None +* @param None +* +* @retval #hi_u32 Real time of the system.CNcomment: 系统实时时间。CNend +* @retval #HI_ERR_FAILURE failed to be obtained. CNcomment:获取时间失败。CNend +* @par 依赖: +* @li hi_time.h:Describes system time APIs.CNcomment:文件包含系统时间相关接口。CNend +*/ +hi_u32 hi_get_real_time(hi_void); + +/** +* @ingroup iot_time +* @brief Sets the real time of the system.CNcomment:设置系统实时时间。CNend +* +* @par 描述: +* Sets the real time of the system.CNcomment:设置系统实时时间。CNend +* +* @attention None +* @param seconds [IN] type #hi_u32,set the real time of the system to this value. +CNcomment:将系统实时时间设置为该值。CNend +* +* @retval #HI_ERR_SUCCESS Success. +* @retval #HI_ERR_FAILURE Failure. +* @par 依赖: +* @li hi_time.h:Describes system time APIs.CNcomment:文件包含系统时间相关接口。CNend +*/ +hi_u32 hi_set_real_time(hi_u32 seconds); + +extern hi_void_callback g_tick_callback; + +/** +* @ingroup iot_time +* @brief Regiseter system tick callback.CNcomment:注册tick 中断响应回调函数。CNend +* +* @par 描述: +* Regiseter system tick callback, if callback is NULL, means cancel registration. +CNcomment:注册tick中断回调函数,如果回调函数为空,表示取消注册。CNend +* +* @attention +* @li cb should not excute in FLASH, must excute in RAM or ROM. u can specify BSP_RAM_TEXT_SECTION before func +to set func excute in RAM. +CNcomment:回调函数不能在FLASH中运行,必须放置在RAM或ROM中,可以通过在 +函数名前添加BSP_RAM_TEXT_SECTION 冠头指定函数在RAM中运行。CNend +* @param cb [IN] type #hi_void_callback, callback in tick interrupt.CNcomment:tick中断的回调函数。CNend +* +* @retval #None +* @par 依赖: +* @li hi_time.h:Describes system time APIs.CNcomment:文件包含系统时间相关接口。CNend +*/ +hi_void hi_tick_register_callback(hi_void_callback cb); + +/** +* @ingroup iot_time +* @brief Convert milliseconds to ticks CNcomment:将毫秒转换为ticks。CNend +* +* @par 描述: +* Convert milliseconds to ticks,ms is greater than 10ms, ticks = ms / 10, +* otherwise see parameter include0 description. +CNcomment: 将milliseconds换算为ticks,ms大于10ms,ticks=ms/10。CNend +* +* @attention None +* @param ms [IN] type #hi_u32, milliseconds. +* @param include0 [IN] type #hi_bool, ms is 0, if include0 is HI_TRUE, return 0 tick,otherwise return 1 tick. +CNcomment:入参ms为0时,如果include0为HI_TRUE,换算结果为0;否则换算结果为1。CNend +* +* @retval #hi_u32 ticks time.CNcomment:ticks时间数 CNend +* @par 依赖: +* @li hi_time.h:Describes system time APIs.CNcomment:文件包含系统时间相关接口。CNend +*/ +hi_u32 hi_ms2systick (hi_u32 ms, hi_bool include0); + +#endif diff --git a/sdk_liteos/include/hi_timer.h b/sdk_liteos/include/hi_timer.h new file mode 100644 index 0000000000000000000000000000000000000000..0b11f7bc1b9fcc2fbfc5dee844c1f280a9d81c95 --- /dev/null +++ b/sdk_liteos/include/hi_timer.h @@ -0,0 +1,151 @@ +/** + * @file hi_timer.h + * + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @defgroup iot_systimer System Timer + * @ingroup osa + */ +#ifndef __INTERFACE_ROM_HI_TIMER_H__ +#define __INTERFACE_ROM_HI_TIMER_H__ +#include + + +/** + * @ingroup iot_systimer + * + * Specifies the type of the timer to be created.CNcomment:用于设置所创建的定时器类型。CNend + */ +typedef enum { + HI_TIMER_TYPE_ONCE, /**< Single-period timer.CNcomment:表示单次定时器 CNend */ + HI_TIMER_TYPE_PERIOD, /**< Periodic timer.CNcomment:表示周期定时器 CNend */ + HI_TIMER_TYPE_MAX /**< Maximum value, which cannot be used.CNcomment:最大值,不可使用 CNend */ +} hi_timer_type; + +/** +* @ingroup iot_systimer +* @brief Defines the type of the timer callback function.CNcomment:定义定时器回调函数的类型。CNend +* +* @par 描述: +* Defines the type of the timer callback function.CNcomment:定义定时器回调函数的类型。CNend +* +* @attention None +* @param data [IN] type #hi_u32,callback input parameter.CNcomment:回调入参。CNend +* +* @retval None +* @par 依赖: +* @li hi_timer.h:Describes the timer APIs.CNcomment:文件用于描述定时器相关接口。CNend +* @see hi_timer_start | hi_timer_stop +*/ +typedef hi_void (*hi_timer_callback_f)(hi_u32 data); + +/** +* @ingroup iot_systimer +* @brief Creates the system timer.CNcomment:获取定时器句柄。CNend +* +* @par 描述: +* Creates the system timer.CNcomment:获取高精定时器句柄。CNend +* +* @attention None +* @param timer_handle [OUT] type #hi_u32*,handle.CNcomment:获取到的句柄。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* +* @par 依赖: +* @li hi_timer.h:Describes the timer APIs.CNcomment:文件用于描述定时器相关接口。CNend +* @see hi_timer_delete。 +*/ +hi_u32 hi_timer_create(hi_u32 *timer_handle); + +/** +* @ingroup iot_systimer +* @brief Starts the system timer.CNcomment:启动系统定时器。CNend +* +* @par 描述: +* This API is used in the following scenarios:CNcomment:本API接口使用分为以下几个场景:CNend +* @li If no timer is created, create and start a timer. +CNcomment:如果未启动定时器,则直接启动。CNend +* @li If the timer expires and is called again, start the timer directly. +CNcomment:如果该定时器到期后调用,则直接启动定时器。CNend +* @li If the timer does not expire, stop and restart the timer. +CNcomment:如果定时器没有到期,则停止该定时器,重新启动定时器。CNend +* +* @attention This timer callback function is executed in the interrupt context. Therefore, the callback function should +* be as simple as possible and the functions such as sleep and wait semaphores that trigger scheduling +* cannot be used.CNcomment:本定时器回调函数执行于中断上下文,回调函数尽量简单,不能使用睡眠、 +等待信号量等引起调度的函数。CNend +* +* @param timer_handle [IN] type #hi_u32,handle.CNcomment:句柄。CNend +* @param type [IN] type #hi_timer_type,timer type.CNcomment:定时器类型。CNend +* @param expire [IN] type #hi_u32,timeout period of the timer (unit: ms). If this parameter is set to 0, +* the default value is 10 ms.CNcomment:定时器超时时间(单位:ms)。配置为0时,默认为10ms。CNend +* @param timer_func [IN] type #timer_proc_func,timer callback function.CNcomment:定时器回调函数。CNend +* @param data [IN] type #hi_u32,callback input parameter.CNcomment:回调函数传参。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* +* @par 依赖: +* @li hi_timer.h:Describes the timer APIs.CNcomment:文件用于描述定时器相关接口。CNend +* @see hi_timer_stop +*/ +hi_u32 hi_timer_start(hi_u32 timer_handle, hi_timer_type type, hi_u32 expire, + hi_timer_callback_f timer_func, hi_u32 data); + +/** +* @ingroup iot_systimer +* @brief Stops the system timer.CNcomment:停止系统定时器。CNend +* +* @par 描述: +* Stops the system timer.CNcomment:停止系统定时器。CNend +* +* @attention This API only stops the timer and does not delete the timer.CNcomment:本接口仅停止定时器, +并不删除该定时器。CNend +* @param timer_handle [IN] type #hi_u32,handle.CNcomment:句柄。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* +* @par 依赖: +* @li hi_timer.h:Describes the timer APIs.CNcomment:文件用于描述定时器相关接口。CNend +* @see hi_timer_start | hi_timer_delete +*/ +hi_u32 hi_timer_stop(hi_u32 timer_handle); + +/** +* @ingroup iot_systimer +* @brief Deletes the timer.CNcomment:删除定时器。CNend +* +* @par 描述: +* Deletes the timer.CNcomment:删除定时器。CNend +* +* @attention +* @li If the timer does not expire, stop the timer before deleting it. +CNcomment:如果定时器未到期,则先停止该定时器再删除。CNend +* +* @param timer_handle [IN] type #hi_u32,handle.CNcomment:句柄。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* +* @par 依赖: +* @li hi_timer.h:Describes the timer APIs.CNcomment:文件用于描述定时器相关接口。CNend +* @see hi_timer_start | hi_timer_stop +*/ +hi_u32 hi_timer_delete(hi_u32 timer_handle); + +#endif diff --git a/sdk_liteos/include/hi_tsensor.h b/sdk_liteos/include/hi_tsensor.h new file mode 100644 index 0000000000000000000000000000000000000000..21a8d564c1d9a94a739dfb2ba0903416ba6e0356 --- /dev/null +++ b/sdk_liteos/include/hi_tsensor.h @@ -0,0 +1,392 @@ +/** + * @file hi_tsensor.h + * + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @defgroup iot_tsensor Tsensor + * @ingroup drivers + */ + +#ifndef __HI_TSENSOR_H__ +#define __HI_TSENSOR_H__ +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** +* @ingroup iot_tsensor +* @brief Callback function of Tsensor interruption. CNcomment:Tsensor中断回调函数。CNend +* +* @par 描述: +* Callback function of Tsensor interruption. CNcomment:Tsensor回调函数。CNend +* +* @attention None +* @param data [IN] type #hi_s16,Parameter transfer of the callback function, indicating the temperature when the +* interrupt is reported.CNcomment:回调函数参数传递,表示中断上报时的温度值。CNend +* +* @retval None +* @par 依赖: +* @li hi_tsensor.h:Tsensor APIs.CNcomment:文件用于描述获取tsensor相关接口。CNend +* @see None +*/ +typedef hi_void (*hi_tsensor_callback_func)(hi_s16); + +/** + * @ingroup iot_tsensor + * + * Tsensor report mode.CNcomment:Tsensor上报模式。CNend + */ +typedef enum { + HI_TSENSOR_MODE_16_POINTS_SINGLE = 0, /**< Mode: 16 points single.CNcomment:模式:16点平均单次上报 CNend */ + HI_TSENSOR_MODE_16_POINTS_LOOP = 1, /**< Mode: 16 points loop.CNcomment:模式:16点平均循环上报 CNend */ + HI_TSENSOR_MODE_1_POINT_LOOP = 2, /**< Mode: 1 point loop.CNcomment:模式:单点循环上报 CNend */ + HI_TSENSOR_MODE_MAX, /**< Invalid input parameter, which cannot be used. + CNcomment:错误入参,不可使用 CNend */ +}hi_tsensor_mode; + +#define HI_TSENSOR_INVALID_CODE 0xFFFF /* Tsensor 无效温度码,有效温度码为(0-255) */ +#define HI_TSENSOR_INVALID_TEMP (-1000) /* Tsensor 无效温度, 有效温度码为(-40-140) */ + +/** +* @ingroup iot_tsensor +* @brief tsensor module start.CNcomment:tsensor模块启动。CNend +* +* @par 描述: +* tsensor module start.CNcomment:tsensor启动温度采集。CNend +* +* @attention Period is valid when mode = #HI_TSENSOR_MODE_16_POINTS_LOOP or HI_TSENSOR_MODE_1_POINT_LOOP. +* By default, the tsensor HI_TSENSOR_MODE_16_POINTS_SINGLE temperature collection mode is enabled for the +* Wi-Fi module. If this function is repeatedly called, the default mode used by the Wi-Fi module will be +* overwritten. If you want to use the tsensor module for other services, you can register the +* corresponding interrupt callback function in the service. +CNcomment:period仅当mode为HI_TSENSOR_MODE_16_POINTS_SINGLE有效, period范围: period * 31.25us > 16 * 192us; +WiFi模块默认启用tsensor HI_TSENSOR_MODE_16_POINTS_SINGLE温度采集模式,重复调用此函数会覆盖WiFi模块使 +用的默认模式, 如要将tsensor模块用于其他业务,可直接在该业务内注册对应的中断回调函数。CNend +* +* @param mode [IN] type #hi_tsensor_mode,Mode of Tsensor temperature acquisition. +CNcomment:Tsensor温度采集模式。CNend +* @param period [IN] type #hi_u16,Acquisition period, it is the multiple of 2 ms. +CNcomment:温度自动检测周期,为32K时钟数。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_tsensor.h:for Tsensor APIs.CNcomment:文件用于描述tsensor相关接口。CNend +* @see None +*/ +hi_u32 hi_tsensor_start(hi_tsensor_mode mode, hi_u16 period); + +/** +* @ingroup iot_tsensor +* @brief Read temperature data.CNcomment:读取温度值。CNend +* +* @par 描述: +* Read temperature data.CNcomment:在启动tsensor温度采集后,读取温度值。CNend +* +* @attention None +* @param temperature [IN] type #hi_s16*,address wait to be writed the temperature value. +CNcomment:待写入温度值的地址。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_tsensor.h:for Tsensor APIs.CNcomment:文件用于描述tsensor相关接口。CNend +* @see None +*/ +hi_u32 hi_tsensor_read_temperature(hi_s16* temperature); + +/** +* @ingroup iot_tsensor +* @brief Tsensor module stop.CNcomment:停止tsensor温度采集。CNend +* +* @par 描述: +* Tsensor module stop.CNcomment:停止tsensor温度采集。CNend +* +* @attention By default, the tsensor function is enabled for the Wi-Fi module. If this function is invoked, the +* temperature threshold protection function of the Wi-Fi module registration will be affected. +CNcomment:WiFi模块默认启用tsensor,调用此函数将会影响WiFi本身注册的温度阈值保护等功能。CNend +* @param None +* +* @retval None +* @par 依赖: +* @li hi_tsensor.h:for Tsensor APIs.CNcomment:文件用于描述tsensor相关接口。CNend +* @see None +*/ +hi_void hi_tsensor_stop(hi_void); + +/** +* @ingroup iot_tsensor +* @brief Destroy Tsensor module.CNcomment:销毁tsensor模块。CNend +* +* @par 描述: +* On the basis of hi_tsensor_stop, this interface disables the reporting of tsensor interrupts and clears +* the callback functions registered by users.CNcomment:在hi_tsensor_stop的基础上,此接口同时禁用了 +tsensor的中断上报,并清空用户注册的回调函数。CNend +* +* @attention After this API is called, if the interrupt callback function is used, you need to invoke the corresponding +* interface to set the interrupt function before starting the interrupt, and enable the interrupt reporting +* function.By default, the tsensor function is enabled for the Wi-Fi module. If this function is invoked, +* the temperature threshold protection function of the Wi-Fi module registration will be affected. +CNcomment:调用此接口后,对于使用中断回调的场景,在start之前,需再次调用相应接口设置中断函数,开启中断上报; +WiFi模块默认启用tsensor,调用此函数将会影响WiFi本身注册的温度阈值保护等功能。CNend +* +* @param None +* +* @retval None +* @par 依赖: +* @li hi_tsensor.h:for Tsensor APIs.CNcomment:文件用于描述tsensor相关接口。CNend +* @see None +*/ +hi_void hi_tsensor_destroy(hi_void); + +/** +* @ingroup iot_tsensor +* @brief Sets the temperature calibration.CNcomment:温度校准设置。CNend +* +* @par 描述: +* Sets the temperature calibration.CNcomment:温度校准设置。CNend +* +* @attention None +* @param trim_code [IN] type #hi_u8,Low 4bit valid. The corresponding temperature calibration values are +* as follows:CNcomment:低4bit有效,对应的温度校准值如下所示:CNend +* 0000 ―― 0.000 ℃ +* 0001 ―― 1.410 ℃ +* 0010 ―― 2.820 ℃ +* 0011 ―― 4.230 ℃ +* 0100 ―― 5.640 ℃ +* 0101 ―― 7.050 ℃ +* 0110 ―― 8.460 ℃ +* 0111 ―― 9.870 ℃ +* 1000 ―― 0.000℃ +* 1001 ―― -1.410 ℃ +* 1010 ―― -2.820 ℃ +* 1011 ―― -4.230 ℃ +* 1100 ―― -5.640 ℃ +* 1101 ―― -7.050 ℃ +* 1110 ―― -8.460 ℃ +* 1111 ―― -9.870 ℃ +* @param trim_sel [IN] type #hi_bool,0:The temp_trim of the Tsensor IP is directly loaded by the efuse. +CNcomment:选择Tsensor IP的temp_trim由efuse直接加载,CNend +* 1:The temp_trim of the Tsensor IP is configured by the register. +CNcomment:选择Tsensor IP的temp_trim由寄存器配置。CNend +* +* @retval None +* @par 依赖: +* @li hi_tsensor.h:for Tsensor APIs.CNcomment:文件用于描述tsensor相关接口。CNend +* @see None +*/ +hi_void hi_tsensor_set_temp_trim(hi_u8 trim_code, hi_bool trim_sel); + +/** +* @ingroup iot_tsensor +* @brief Converts the temperature code into a temperature value.CNcomment:温度码转换成温度值。CNend +* +* @par 描述: +* Converts the temperature code into a temperature value.CNcomment:将温度码转换成温度值。CNend +* +* @attention None +* @param code [IN] type #hi_u8,temperature value.CNcomment:温度码。CNend +* +* @retval #hi_s16 Valid temperature value or invalid data (HI_TSENSOR_INVALID_TEMP). +CNcomment:有效的温度值或无效数据(HI_TSENSOR_INVALID_TEMP)。CNend +* +* @par 依赖: +* @li hi_tsensor.h:for Tsensor APIs.CNcomment:文件用于描述tsensor相关接口。CNend +* @see None +*/ +hi_s16 hi_tsensor_code_to_temperature(hi_u8 code); + +/** +* @ingroup iot_tsensor +* @brief Converts the temperature into a temperature code.CNcomment:温度值转换成温度码。CNend +* +* @par 描述: +* Converts the temperature into a temperature code.CNcomment:将温度值转换成温度码。CNend +* +* @attention None +* @param temp [IN] type #hi_float,temperature code.CNcomment:温度值。CNend +* +* @retval #hi_u16 Valid temperature value or invalid data (HI_TSENSOR_INVALID_TEMP). +CNcomment:有效的温度值或无效数据(HI_TSENSOR_INVALID_TEMP)。CNend +* @par 依赖: +* @li hi_tsensor.h:for Tsensor APIs.CNcomment:文件用于描述tsensor相关接口。CNend +* @see None +*/ +hi_u16 hi_tsensor_temperature_to_code(hi_s16 temp); + +/** +* @ingroup iot_tsensor +* @brief Sets the temperature threshold.CNcomment:设置温度阈值门限。CNend +* +* @par 描述: +* Sets the temperature threshold.CNcomment:设置温度阈值门限。CNend +* +* @attention This function is invoked before tsensor temperature collection is started. This function is invoked to +* enable the function of reporting the temperature threshold interrupt. A maximum of three temperature +* threshold interrupt callback functions can be registered at the same time. When the Wi-Fi service is +* started, this interface is invoked to set the default high and low temperature thresholds. Before other +* services use this interface, check whether the default high and low temperature thresholds need to be +* changed. CNcomment:在启动tsensor温度采集之前调用,调用此函数将使能温度阈值门限中断上报, 最多可同时注册 +3个温度阈值门限中断回调函数;WiFi业务启动时会调用此接口设置默认的高低温门限,此后其他业务使用此接口前, +请确认是否要修改默认的高低温门限值。CNend +* +* @param low_temp [IN] type #hi_s16,Low Temperature Threshold.CNcomment:低温门限。CNend +* @param high_temp [IN] type #hi_s16,High Temperature Threshold.CNcomment:高温门限。CNend +* @param callback_func [IN] type #hi_tsensor_callback_func,Indicates the callback function when the temperature +* exceeds the threshold.CNcomment:温度超阈值中断回调函数。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_tsensor.h:for Tsensor APIs.CNcomment:文件用于描述tsensor相关接口。CNend +* @see None +*/ +hi_u32 hi_tsensor_set_outtemp_threshold(hi_s16 low_temp, hi_s16 high_temp, + hi_tsensor_callback_func callback_func); + +/** +* @ingroup iot_tsensor +* @brief To set the threshold for the over-high temperature threshold.CNcomment:设置超高温阈值门限。CNend +* +* @par 描述: +* To set the threshold for the over-high temperature threshold.CNcomment:设置超高温阈值门限。CNend +* +* @attention This function is invoked before tsensor temperature collection is started. This function is invoked to +* enable the function of reporting the temperature threshold interrupt. A maximum of three temperature +* threshold interrupt callback functions can be registered at the same time. When the Wi-Fi service is +* started, this interface is invoked to set the default high and low temperature thresholds. Before other +* services use this interface, check whether the default high and low temperature thresholds need to be +* changed. CNcomment:在启动tsensor温度采集之前调用,调用此函数将使能温度阈值门限中断上报, 最多可同时注册 +3个温度阈值门限中断回调函数;WiFi业务启动时会调用此接口设置默认的高低温门限,此后其他业务使用此接口前, +请确认是否要修改默认的高低温门限值。CNend +* +* @param over_temp [IN] type #hi_s16,Ultra-high temperature threshold.CNcomment:超高温门限。CNend +* @param callback_func [IN] type #hi_tsensor_callback_func,Interrupt callback function when the temperature +* exceeds the upper temperature threshold. CNcomment:温度超过超高温门限中断回调函数。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_tsensor.h:for Tsensor APIs.CNcomment:文件用于描述tsensor相关接口。CNend +* @see None +*/ +hi_u32 hi_tsensor_set_overtemp_threshold(hi_s16 over_temp, hi_tsensor_callback_func callback_func); + +/** +* @ingroup iot_tsensor +* @brief Sets the overtemperature power-off threshold.CNcomment:设置过温掉电阈值门限。CNend +* +* @par 描述: +* Sets the overtemperature power-off threshold.CNcomment:设置过温掉电阈值门限。CNend +* +* @attention This function is invoked before tsensor temperature collection is started. This function is invoked to +* enable the function of reporting the temperature threshold interrupt. A maximum of three temperature +* threshold interrupt callback functions can be registered at the same time. When the Wi-Fi service is +* started, this interface is invoked to set the default high and low temperature thresholds. Before other +* services use this interface, check whether the default high and low temperature thresholds need to be +* changed. CNcomment:在启动tsensor温度采集之前调用,调用此函数将使能温度阈值门限中断上报, 最多可同时注册 +3个温度阈值门限中断回调函数;WiFi业务启动时会调用此接口设置默认的高低温门限,此后其他业务使用此接口前, +请确认是否要修改默认的高低温门限值。CNend +* +* @param pd_temp [IN] type #hi_s16,Indicates the threshold of the overtemperature power-off threshold. +CNcomment:过温掉电阈值门限。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_tsensor.h:for Tsensor APIs.CNcomment:文件用于描述tsensor相关接口。CNend +* @see None +*/ +hi_u32 hi_tsensor_set_pdtemp_threshold(hi_s16 pd_temp); + +/** +* @ingroup iot_tsensor +* @brief Registers the callback function for the temperature collection completion interrupt. +CNcomment:注册温度采集完成中断回调函数。CNend +* +* @par 描述: +* Registers the callback function for the temperature collection completion interrupt. +CNcomment:注册温度采集完成中断回调函数。CNend +* +* @attention This function is invoked before tsensor temperature collection is started. This function is invoked to +* enable the function of reporting the temperature threshold interrupt. A maximum of three temperature +* threshold interrupt callback functions can be registered at the same time. The tsensor temperature +* collection period is short. In HI_TSENSOR_MODE_16_POINTS_LOOP and HI_TSENSOR_MODE_1_POINT_LOOP modes, +* the collection completion interrupt is frequently triggered, occupying a large number of CPU resources. +* As a result, other services may fail to be scheduled. In HI_TSENSOR_MODE_16_POINTS_SINGLE mode, a large +* period can be set to avoid this problem, however, if the value of period is too large, the temperature +* monitoring density decreases. Therefore, it is recommended that you do not read the temperature by +* collecting data. CNcomment:在启动tsensor温度采集之前调用,调用此函数将使能温度采集完成中断上报, +最多可同时注册3个温度采集完成中断回调函数;tsensor温度采集周期很短,HI_TSENSOR_MODE_16_POINTS_LOOP和 +HI_TSENSOR_MODE_1_POINT_LOOP模式下采集完成中断会频繁触发,占用大量cpu资源,可能会导致其他业务得不到调度, +HI_TSENSOR_MODE_16_POINTS_SINGLE模式虽然可以通过设置较大的period来避免这个问题,但过大的period值将会导致温度监控密度 +的下降,因此建议尽量不要通过采集完成中断的方式读取温度。CNend +* +* @param callback_func [IN] type #hi_tsensor_callback_func,Temperature collection completion interrupt callback +* function.CNcomment:温度采集完成中断回调函数。CNend +* +* @retval #0 Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_tsensor.h:for Tsensor APIs.CNcomment:文件用于描述tsensor相关接口。CNend +* @see None +*/ +hi_u32 hi_tsensor_register_temp_collect_finish_int_callback(hi_tsensor_callback_func callback_func); + +/** +* @ingroup iot_tsensor +* @brief Save register-related values before going to deep sleep.CNcomment:深睡前保存相关寄存器内容。CNend +* +* @par 描述: +* Regs-related values are saved before entering deep sleep to facilitate sleep recovery. +CNcomment:深睡前保存相关寄存器内容,以便于睡醒恢复Tsensor。CNend +* +* @attention Called before deep sleep. It must be used in pairs with hi_tsensor_lp_restore. +CNcomment:在深睡前调用,必须与hi_tsensor_lp_restore接口成对使用。CNend +* @param None +* +* @retval None +* @par 依赖: +* @li hi_tsensor.h:for Tsensor APIs.CNcomment:文件用于描述tsensor相关接口。CNend +* @see hi_tsensor_lp_restore。 +*/ +hi_void hi_tsensor_lp_save(hi_void); + +/** +* @ingroup iot_tsensor +* @brief Restore register related values after deep sleep wake up.CNcomment:深睡唤醒后恢复寄存器内容。CNend +* +* @par 描述: +* Restore register related values after deep sleep wake up.CNcomment:深睡唤醒后恢复寄存器内容。CNend +* +* @attention Called after deep sleep wake up. It must be used in pairs with hi_tsensor_lp_save. +CNcomment:深睡唤醒后调用,必须与hi_tsensor_lp_save接口成对使用。CNend +* @param None +* +* @retval None +* @par 依赖: +* @li hi_tsensor.h:for Tsensor APIs.CNcomment:文件用于描述tsensor相关接口。CNend +* @see hi_tsensor_lp_save。 +*/ +hi_void hi_tsensor_lp_restore(hi_void); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/include/hi_types.h b/sdk_liteos/include/hi_types.h new file mode 100644 index 0000000000000000000000000000000000000000..a76dc18dded55c323c3dd0b7a8511872bee65675 --- /dev/null +++ b/sdk_liteos/include/hi_types.h @@ -0,0 +1,23 @@ +/** + * @file hi_types.h + * + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __HI_TYPES_H__ +#define __HI_TYPES_H__ + +#include +#include +#endif /* __HI_TYPES_H__ */ diff --git a/sdk_liteos/include/hi_types_base.h b/sdk_liteos/include/hi_types_base.h new file mode 100644 index 0000000000000000000000000000000000000000..82681ebc9312ddaff4b33ac51fc865b6603c765e --- /dev/null +++ b/sdk_liteos/include/hi_types_base.h @@ -0,0 +1,559 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __HI_TYPES_BASE_H__ +#define __HI_TYPES_BASE_H__ + +#if defined(__CC_ARM) +#define HI_HAVE_CROSS_COMPILER_ARM_ARMCC +#elif defined(__GNUC__) +#define HI_HAVE_CROSS_COMPILER_ARM_GCC +#elif defined(__DCC__) +#define HI_HAVE_CROSS_COMPILER_DIAB +#if defined(__HI_ASM_LANGUAGE__) || defined(_ASMLANGUAGE) +#define HI_HAVE_CROSS_COMPILER_DIAB_AS +#endif +#elif defined(_MSC_VER) +#define HI_HAVE_NOTIVE_COMPILER_VC +#endif + +#if !defined(HI_HAVE_CROSS_COMPILER_DIAB_AS) +#if defined(HI_HAVE_CROSS_COMPILER_ARM_GCC) || defined(HI_HAVE_CROSS_COMPILER_ARM_ARMCC) || \ + defined(HI_HAVE_CROSS_COMPILER_DIAB) +#undef HI_HAVE_CROSS_COMPILER +#define HI_HAVE_CROSS_COMPILER +#endif + +#ifdef PRODUCT_CFG_PLATFORM_HI3921 +#define SAL_HAVE_HI3911_VER +#endif + +#ifdef PRODUCT_CFG_OS_WIN +# undef SAL_HAVE_OS_WIN_VER +# undef SAL_HAVE_OS_NU_VER +# undef SAL_HAVE_OS_VX_VER +#define SAL_HAVE_OS_WIN_VER +#endif + +#if defined (PRODUCT_CFG_OS_LOS) +# undef SAL_HAVE_OS_VX_VER +# define SAL_HAVE_OS_VX_VER +#else +# if defined (_WIN32) && defined (_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +# ifndef SAL_HAVE_SIMU_WIN_VER +# define SAL_HAVE_SIMU_WIN_VER +# ifdef _USRDLL +# if !defined(PRODUCT_CFG_MSVC_HIDE_AUTOLINK_OUTPUT_INFO) +# pragma message("Windows VC Simulator DLL Version ") +# endif +# endif +# ifdef _LIB +# if !defined(PRODUCT_CFG_MSVC_HIDE_AUTOLINK_OUTPUT_INFO) +# pragma message("Windows VC Simulator lib Version ") +# endif +# endif +# ifdef _CONSOLE +# if !defined(PRODUCT_CFG_MSVC_HIDE_AUTOLINK_OUTPUT_INFO) +# pragma message("Windows VC Simulator console Version ") +# endif +# endif +# else +# if !defined(PRODUCT_CFG_MSVC_HIDE_AUTOLINK_OUTPUT_INFO) +# pragma message("Windows Version") +# endif +# endif +# endif +#endif + +#undef HI_SYS_DEBUG +#if (defined(PRODUCT_CFG_VERSION_DEBUG) || defined(SAL_HAVE_DEBUG_VERSION)) && !defined(SAL_HAVE_RELEASE_VERSION) +# define HI_SYS_DEBUG +#endif + +#if defined(PRODUCT_CFG_OS_WIN) +#pragma warning(disable:4200) /* disable nonstandard extension used : zero-sized array in struct/union. */ +#pragma warning(disable:4214) /* allows bitfield structure members to be of any integral type. */ +#pragma warning(disable:4201) +#pragma warning(disable:4514) +#pragma warning(disable:4127) +#endif + +/* 基本数据类型定义 */ +typedef unsigned char hi_uchar; +typedef unsigned char hi_u8; +typedef unsigned short hi_u16; +typedef unsigned int hi_u32; +typedef unsigned long long hi_u64; +typedef unsigned long hi_ulong; +typedef char hi_char; +typedef signed char hi_s8; +typedef short hi_s16; +typedef int hi_s32; +typedef long long hi_s64; +typedef long hi_slong; +typedef float hi_float; +typedef double hi_double; +typedef unsigned long hi_size_t; +typedef unsigned long hi_length_t; +typedef hi_u8 hi_bool; +typedef void hi_void; +typedef void* hi_pvoid; +typedef hi_u8 hi_byte; +typedef hi_byte* hi_pbyte; + +/* for 64bits platform, intptr_t/uintptr_t should be defined as 64bits length. */ +typedef int intptr_t; +typedef unsigned int uintptr_t; + +#undef ERROR +#define ERROR (-1) + +/* defines */ +#undef NULL +#ifndef NULL +#define NULL 0 +#endif + +#define HI_CONST const +#define HI_REG register + +#define HI_U32_MAX 0xFFFFFFFF +#define HI_U64_MAX 0xFFFFFFFFFFFFFFFFUL +#define HI_U16_MAX 0xFFFF + +typedef hi_pvoid (*hi_pvoid_callback_f)(hi_void); +typedef hi_void (*hi_void_callback_f)(hi_void); +typedef hi_void (*hi_void_callback)(hi_void); +typedef hi_bool (*hi_bool_callback_f)(hi_void); +typedef hi_void (*hi_void_u32_callback_f)(hi_u32); +typedef hi_u32 (*hi_u32_pvoid_callback_f)(hi_pvoid); +typedef hi_u32 (*hi_u32_void_callback)(hi_void); /* 周边代码待刷新 */ +typedef hi_u32 (*hi_u32_u32_pvoid_callback_f)(hi_pvoid, hi_u32); +typedef hi_s32 (*funcptr)(hi_void); /* ptr to function returning int */ +typedef hi_void (*voidfuncptr)(hi_void); /* ptr to function returning void */ + +typedef HI_CONST hi_char* hi_pcstr; + +#ifdef PRODUCT_CFG_OS_WIN +typedef unsigned __int64 hi_u64; +typedef __int64 hi_s64; +#elif defined(HI_HAVE_CROSS_COMPILER_ARM_ARMCC) +typedef unsigned __int64 hi_u64; +typedef __int64 hi_s64; +#elif defined(HI_HAVE_CROSS_COMPILER_ARM_GCC) || defined(HAVE_PCLINT_CHECK) +typedef unsigned long long hi_u64; +typedef long long hi_s64; +#elif defined(HI_HAVE_CROSS_COMPILER_DIAB) +typedef unsigned long long hi_u64; +typedef long long hi_s64; +#elif !defined(PRODUCT_CFG_HSO) +/* #error "unknown compiler" */ +typedef unsigned __int64 hi_u64; +typedef __int64 hi_s64; +#endif + +#define HI_S32_BITS 32 +#define HI_S32_MAX (~(~0 << (HI_S32_BITS - 1))) + +#define HI_PUBLIC extern +#if !defined(PRODUCT_CFG_FEATURE_UT) +# define HI_PRV static +#else +# define HI_PRV +#endif + +# define STATIC static + +#endif /* HI_HAVE_CROSS_COMPILER_DIAB_AS */ + +#ifdef PRODUCT_CFG_OS_WIN +# define HI_API _declspec(dllexport) +# define HI_INLINE __inline +#elif defined(HI_HAVE_CROSS_COMPILER_ARM_GCC) +# define HI_INLINE inline +# define HI_API +#elif defined(HI_HAVE_CROSS_COMPILER_ARM_ARMCC) +# define HI_INLINE inline +# define HI_API +#elif defined(HI_HAVE_CROSS_COMPILER_DIAB) +# define HI_INLINE __inline__ +# define HI_API +# else +# define HI_INLINE __inline +# define HI_API +#endif + +#define HI_PRVL HI_PRV HI_INLINE + +#if defined(__ONEBUILDER__CROSS_COMPILER_PRODUCT_CONFIG__) +#if defined(HI_HAVE_CROSS_COMPILER_ARM_ARMCC) || defined(HI_HAVE_CROSS_COMPILER_ARM_GCC) +# define hi_section(name_string) __attribute__ ((section(name_string))) +# define HI_PACKED __attribute__((packed)) +# define HI_ALIGNED4 __attribute__ ((aligned (4))) +#elif defined(HI_HAVE_CROSS_COMPILER_DIAB) +# define hi_section(name_string) __attribute__ ((section(name_string))) +# define HI_PACKED __attribute__((packed)) +# define HI_ALIGNED4 __attribute__ ((aligned (4))) +#endif +#elif defined(SAL_HAVE_OS_WIN_VER) || defined(PRODUCT_CFG_HSO) +# define hi_section(name_string) +# define HI_PACKED +# define HI_ALIGNED4 +#else +# define hi_section(name_string) +# define HI_PACKED +# define HI_ALIGNED4 +#endif + +#if defined(SAL_HAVE_OS_WIN_VER) +# if defined(_DEBUG) || defined(PRODUCT_CFG_VERSION_DEBUG) +# define hi_dll_lib_name(x) x ## "_debug.dll" +# else +# define hi_dll_lib_name(x) x ## "_release.dll" +# endif +#else +#if defined(HI_HAVE_CROSS_COMPILER_ARM_GCC) +# define hi_dll_lib_name(x) x +#else +# define hi_dll_lib_name(x) x ## ".lib" +#endif +#endif + +#if defined(SAL_HAVE_NO_EXTERN_DEFINED) +# define HI_EXTERN +# define HI_EXTERN_C +#else +# if defined(PRODUCT_CFG_OS_WIN) +# define HI_EXTERN extern HI_API +# define HI_EXTERN_C HI_EXTERN +# define HI_EAPI extern HI_API +# else +# define HI_EXTERN extern +# define HI_EAPI +# define HI_EXTERN_C +# endif +#endif + +#ifdef __cplusplus +# define HI_CPP_START extern "C" { +# define HI_CPP_END } +#else +# define HI_CPP_START +# define HI_CPP_END +#endif + +#if defined(HI_HAVE_CROSS_COMPILER_ARM_ARMCC) +#define HI_NOP __asm { nop } +#define hi_dbg_break() __asm { swi 0x14DEAD } +#elif defined(HI_HAVE_CROSS_COMPILER_DIAB) +#define HI_NOP +#define hi_dbg_break() +#else +#define HI_NOP +#ifdef PRODUCT_CFG_OS_WIN +#define hi_dbg_break() _asm { int 3 } +#else +#define hi_dbg_break() +#endif +#endif + +#define HI_START_HEADER HI_CPP_START +#define HI_END_HEADER HI_CPP_END + +#undef HI_OUT +#undef HI_IN +#undef HI_INOUT +#define HI_OUT +#define HI_IN +#define HI_INOUT + +#define HI_FALSE 0 +#define HI_TRUE 1 +#define HI_SWITCH_OFF 0 +#define HI_SWITCH_ON 1 + +#ifdef __cplusplus +#define HI_NULL 0 +#else +#define HI_NULL ((void *)0) +#endif + +#ifndef CACHE_ALIGNED_SIZE +#define CACHE_ALIGNED_SIZE 32 +#endif + +#define hi_array_count(x) (sizeof(x) / sizeof((x)[0])) + +#if !defined(hi_unref_param) && !defined(HI_HAVE_CROSS_COMPILER_DIAB) +#define hi_unref_param(P) ((P) = (P)) +#else +#define hi_unref_param(P) +#endif + +#if defined(PRODUCT_CFG_PLATFORM_HI3921) +#if defined(HI_HAVE_CROSS_COMPILER_ARM_ARMCC) +#define HI_VOLATILE volatile +#define hi_sys_get_lr() __return_address() +#elif defined(HAVE_PCLINT_CHECK) +#define HI_VOLATILE +#define hi_sys_get_lr() 0 +#elif defined(HI_HAVE_CROSS_COMPILER_DIAB) +#define HI_VOLATILE volatile +#define hi_sys_get_lr() 0 +#else +#define HI_VOLATILE __volatile__ +#define hi_sys_get_lr() 0 +#endif +#else +#define HI_VOLATILE +#define hi_sys_get_lr() 0 +#endif + +#define hi_aligin_u32_size(x) (((x) & (~3)) + 4) /* 构造4个字节对齐 */ +#define hi_is_align_u32(x) (!((x) & 3)) /* 判断是否为4字节对齐 */ +#define hi_is_unalign_u32(x) ((x) & 3) /* 判断是否为4字节对齐 */ +#if defined(HAVE_PCLINT_CHECK) +#define hi_fieldoffset(s, m) (0) +#else +#define hi_fieldoffset(s, m) ((hi_u32)&(((s *)0)->m)) /* 结构成员偏移 */ +#endif + +#define HI_CHAR_CR '\r' /* 0x0D */ +#define HI_CHAR_LF '\n' /* 0x0A */ +#define hi_tolower(x) ((x) | 0x20) /* Works only for digits and letters, but small and fast */ + +#define hi_array_size(_array) (sizeof(_array) / sizeof((_array)[0])) +#define hi_makeu16(a, b) ((hi_u16)(((hi_u8)(a)) | ((hi_u16)((hi_u8)(b))) << 8)) +#define hi_makeu32(a, b) ((hi_u32)(((hi_u16)(a)) | ((hi_u32)((hi_u16)(b))) << 16)) +#define hi_makeu64(a, b) ((hi_u64)(((hi_u32)(a)) | ((hi_u64)((hi_u32)(b))) <<32)) +#define hi_joinu32(a, b, c, d) ((a) | ((hi_u32)(b) << 8) | ((hi_u32)(c) << 16) | ((hi_u32)(d) << 24)) + +#define hi_hiu32(l) ((hi_u32)(((hi_u64)(l) >> 32) & 0xFFFFFFFF)) +#define hi_lou32(l) ((hi_u32)(l)) + +#define hi_hiu16(l) ((hi_u16)(((hi_u32)(l) >> 16) & 0xFFFF)) +#define hi_lou16(l) ((hi_u16)(l)) +#define hi_hiu8(l) ((hi_u8)(((hi_u16)(l) >> 8) & 0xFF)) +#define hi_lou8(l) ((hi_u8)(l)) + +#define hi_max(a, b) (((a) > (b)) ? (a) : (b)) +#define hi_min(a, b) (((a) < (b)) ? (a) : (b)) +#define hi_sub(a, b) (((a) > (b)) ? ((a) - (b)) : 0) +#define hi_abs_sub(a, b) (((a) > (b)) ? ((a) - (b)) : ((b) - (a))) +#define hi_byte_align(value, align) (((value) + (align) - 1) & (~((align) -1))) +#define hi_is_byte_align(value, align) (((hi_u32)(value) & ((align) - 1))== 0) +#define hi_inc_wraparound(value, round_size) ++(value); (value) &= ((round_size) - 1) +#define hi_dec_wraparound(value, round_size) --(value); (value) &= ((round_size) - 1) + +#define hi_swap_byteorder_16(value) ((((value) & 0xFF) << 8) + (((value) & 0xFF00) >> 8)) + +#define hi_swap_byteorder_32(value) \ + ((hi_u32)(((value) & 0x000000FF) << 24) + \ + (hi_u32)(((value) & 0x0000FF00) << 8) + \ + (hi_u32)(((value) & 0x00FF0000) >> 8) + \ + (hi_u32)(((value) & 0xFF000000) >> 24)) + +#define hi_swap_byteorder_64(value) \ + ((((value) & 0x00000000000000ffULL) << 56) + \ + (((value) & 0x000000000000ff00ULL) << 40) + \ + (((value) & 0x0000000000ff0000ULL) << 24) + \ + (((value) & 0x00000000ff000000ULL) << 8) + \ + (((value) & 0x000000ff00000000ULL) >> 8) + \ + (((value) & 0x0000ff0000000000ULL) >> 24) + \ + (((value) & 0x00ff000000000000ULL) >> 40) + \ + (((value) & 0xff00000000000000ULL) >> 56)) + +#undef MIN_T +#define MIN_T hi_min + +#define hi_make_identifier(a, b, c, d) hi_makeu32(hi_makeu16(a, b), hi_makeu16(c, d)) +#define hi_make_ver16(spc, b) ((hi_u16)(((hi_u8)((spc)&0x0F)) | ((hi_u16)((hi_u8)(b))) << 12)) + +#define hi_set_bit_i(val, n) ((val) |= (1 << (n))) +#define hi_clr_bit_i(val, n) ((val) &= ~(1 << (n))) +#define hi_is_bit_set_i(val, n) ((val) & (1 << (n))) +#define hi_is_bit_clr_i(val, n) (~((val) & (1 << (n)))) +#define hi_switch_bit_i(val, n) ((val) ^= (1 << (n))) +#define hi_get_bit_i(val, n) (((val) >> (n)) & 1) +#define hi_reg_clr_bit_i(reg, n) ((*(volatile unsigned int *)(reg)) &= ~(1 << (n))) + +#define hi_u8_bit_val(b7, b6, b5, b4, b3, b2, b1, b0) \ + (((b7) << 7) | ((b6) << 6) | ((b5) << 5) | ((b4) << 4) | ((b3) << 3) | ((b2) << 2) | ((b1) << 1) | ((b0) << 0)) +#define hi_u16_bit_val(b12, b11, b10, b9, b8, b7, b6, b5, b4, b3, b2, b1, b0) \ + (hi_u16)(((b12) << 12) | ((b11) << 11) | ((b10) << 10) | ((b9) << 9) | ((b8) << 8) | ((b7) << 7) | \ + ((b6) << 6) | ((b5) << 5) | ((b4) << 4) | ((b3) << 3) | ((b2) << 2) | ((b1) << 1) | ((b0) << 0)) + +#if defined(__ONEBUILDER__CROSS_COMPILER_PRODUCT_CONFIG__) +#define HSO_ENUM HI_ALIGNED4 enum +#define HI_U8A HI_ALIGNED4 hi_u8 +#define HI_U16A HI_ALIGNED4 hi_u16 +#define HI_CHARTA HI_ALIGNED4 hi_char +#else +#define HSO_ENUM enum +#define HI_U8A hi_u8 +#define HI_U16A hi_u16 +#define HI_CHARTA hi_char +#endif + +#if defined(PRODUCT_CFG_HSO) && defined(HI_HAVE_NOTIVE_COMPILER_VC) +#define __FUNCTION__ "NA" +#endif + +/*****************************************************************************/ +#define hi_set_u32_ptr_val(ptr, offset, val) (*((hi_u32*)(((hi_u8*)(ptr)) + (offset))) = (val)) +#define hi_get_u32_ptr_val(ptr, offset) *((hi_u32*)(((hi_u8*)(ptr)) + (offset))) +/*****************************************************************************/ +/*****************************************************************************/ +#define HI_SIZE_1K 1024 +#define HI_SIZE_1M (1024 * 1024) +/*****************************************************************************/ +#ifndef bit +#define bit(x) (1UL << (x)) +#endif +#define BIT31 ((hi_u32)(1UL << 31)) +#define BIT30 ((hi_u32)(1 << 30)) +#define BIT29 ((hi_u32)(1 << 29)) +#define BIT28 ((hi_u32)(1 << 28)) +#define BIT27 ((hi_u32)(1 << 27)) +#define BIT26 ((hi_u32)(1 << 26)) +#define BIT25 ((hi_u32)(1 << 25)) +#define BIT24 ((hi_u32)(1 << 24)) +#define BIT23 ((hi_u32)(1 << 23)) +#define BIT22 ((hi_u32)(1 << 22)) +#define BIT21 ((hi_u32)(1 << 21)) +#define BIT20 ((hi_u32)(1 << 20)) +#define BIT19 ((hi_u32)(1 << 19)) +#define BIT18 ((hi_u32)(1 << 18)) +#define BIT17 ((hi_u32)(1 << 17)) +#define BIT16 ((hi_u32)(1 << 16)) +#define BIT15 ((hi_u32)(1 << 15)) +#define BIT14 ((hi_u32)(1 << 14)) +#define BIT13 ((hi_u32)(1 << 13)) +#define BIT12 ((hi_u32)(1 << 12)) +#define BIT11 ((hi_u32)(1 << 11)) +#define BIT10 ((hi_u32)(1 << 10)) +#define BIT9 ((hi_u32)(1 << 9)) +#define BIT8 ((hi_u32)(1 << 8)) +#define BIT7 ((hi_u32)(1 << 7)) +#define BIT6 ((hi_u32)(1 << 6)) +#define BIT5 ((hi_u32)(1 << 5)) +#define BIT4 ((hi_u32)(1 << 4)) +#define BIT3 ((hi_u32)(1 << 3)) +#define BIT2 ((hi_u32)(1 << 2)) +#define BIT1 ((hi_u32)(1 << 1)) +#define BIT0 ((hi_u32)(1 << 0)) + +#define HALFWORD_BIT_WIDTH 16 + +/* 寄存器访问接口 */ +#define hi_reg_write(addr, val) (*(volatile unsigned int *)(uintptr_t)(addr) = (val)) +#define hi_reg_read(addr, val) ((val) = *(volatile unsigned int *)(uintptr_t)(addr)) +#define hi_reg_write32(addr, val) (*(volatile unsigned int *)(uintptr_t)(addr) = (val)) +#define hi_reg_read32(addr, val) ((val) = *(volatile unsigned int *)(uintptr_t)(addr)) +#define hi_reg_read_val32(addr) (*(volatile unsigned int*)(uintptr_t)(addr)) +#define hi_reg_setbitmsk(addr, msk) ((hi_reg_read_val32(addr)) |= (msk)) +#define hi_reg_clrbitmsk(addr, msk) ((hi_reg_read_val32(addr)) &= ~(msk)) +#define hi_reg_clrbit(addr, pos) ((hi_reg_read_val32(addr)) &= ~((unsigned int)(1) << (pos))) +#define hi_reg_setbit(addr, pos) ((hi_reg_read_val32(addr)) |= ((unsigned int)(1) << (pos))) +#define hi_reg_clrbits(addr, pos, bits) (hi_reg_read_val32(addr) &= ~((((unsigned int)1 << (bits)) - 1) << (pos))) +#define hi_reg_setbits(addr, pos, bits, val) (hi_reg_read_val32(addr) = \ + (hi_reg_read_val32(addr) & (~((((unsigned int)1 << (bits)) - 1) << (pos)))) | \ + ((unsigned int)((val) & (((unsigned int)1 << (bits)) - 1)) << (pos))) +#define hi_reg_getbits(addr, pos, bits) ((hi_reg_read_val32(addr) >> (pos)) & (((unsigned int)1 << (bits)) - 1)) + +#define hi_reg_write16(addr, val) (*(volatile unsigned short *)(uintptr_t)(addr) = (val)) +#define hi_reg_read16(addr, val) ((val) = *(volatile unsigned short *)(uintptr_t)(addr)) +#define hi_reg_read_val16(addr) (*(volatile unsigned short*)(uintptr_t)(addr)) +#define hi_reg_clrbit16(addr, pos) ((hi_reg_read_val16(addr)) &= ~((unsigned short)(1) << (pos))) +#define hi_reg_setbit16(addr, pos) ((hi_reg_read_val16(addr)) |= ((unsigned short)(1) << (pos))) +#define hi_reg_clrbits16(addr, pos, bits) (hi_reg_read_val16(addr) &= ~((((unsigned short)1 << (bits)) - 1) << (pos))) +#define hi_reg_setbits16(addr, pos, bits, val) (hi_reg_read_val16(addr) = \ + (hi_reg_read_val16(addr) & (~((((unsigned short)1 << (bits)) - 1) << (pos)))) | \ + ((unsigned short)((val) & (((unsigned short)1 << (bits)) - 1)) << (pos))) +#define hi_reg_getbits16(addr, pos, bits) ((hi_reg_read_val16(addr) >> (pos)) & (((unsigned short)1 << (bits)) - 1)) + +#define reg_write32(addr, val) (*(volatile unsigned int *)(uintptr_t)(addr) = (val)) +#define reg_read32(addr, val) ((val) = *(volatile unsigned int *)(uintptr_t)(addr)) +#define reg_read_val(addr) (*(volatile unsigned *)(uintptr_t)(addr)) + +#ifndef BSP_RAM_TEXT_SECTION +#define BSP_RAM_TEXT_SECTION __attribute__ ((section(".bsp.ram.text"))) +#endif + +#ifndef BSP_ROM_RODATA_SECTION +#define BSP_ROM_RODATA_SECTION __attribute__ ((section(".bsp.rom.rodata"))) +#endif + +#ifndef BSP_ROM_DATA0_SECTION +#define BSP_ROM_DATA0_SECTION __attribute__ ((section(".bsp.rom.data0"))) +#endif + +#ifndef ROM_TEXT_PATCH_SECTION +#define ROM_TEXT_PATCH_SECTION __attribute__ ((section(".rom.text.patch"))) +#endif + +#ifndef LP_RAM_BSS_SECTION +#define LP_RAM_BSS_SECTION __attribute__ ((section(".lowpower.ram.bss"))) +#endif + +#ifndef ROM_DATA_PATCH_SECTION +#define ROM_DATA_PATCH_SECTION __attribute__ ((section(".rom.data.patch"))) +#endif + +#ifndef EXTERN_ROM_BSS_SECTION +#define EXTERN_ROM_BSS_SECTION __attribute__ ((section(".extern.rom.bss"))) +#endif + +#ifndef EXTERN_ROM_DATA1_BSS_SECTION +#define EXTERN_ROM_DATA1_BSS_SECTION __attribute__ ((section(".extern.rom.data1.bss"))) +#endif + +#ifdef CONFIG_FLASH_ENCRYPT_SUPPORT +#ifndef CRYPTO_RAM_TEXT_SECTION +#define CRYPTO_RAM_TEXT_SECTION __attribute__ ((section(".crypto.ram.text"))) +#endif +#else +#ifndef CRYPTO_RAM_TEXT_SECTION +#define CRYPTO_RAM_TEXT_SECTION +#endif +#endif + +#ifdef HAVE_PCLINT_CHECK +#define hi_likely(x) (x) +#define hi_unlikely(x) (x) +#else +#define hi_likely(x) __builtin_expect(!!(x), 1) +#define hi_unlikely(x) __builtin_expect(!!(x), 0) +#endif +#define HI_ALWAYS_STAIC_INLINE __attribute__((always_inline)) static inline + +#ifdef HAVE_PCLINT_CHECK +#define hi_offset_of_member(type, member) 0 +#else +#define hi_offset_of_member(type, member) ((hi_u32)(&((type *)0)->member)) +#endif +#define BITS_PER_BYTE 8 +#define HEXADECIMAL 16 +#define DECIMAL 10 +#define SZ_1KB 1024 +#define SZ_1MB (SZ_1KB * SZ_1KB) +#define SZ_4KB 4096 +/*****************************************************************************/ +#include + +#define HI_SYS_WAIT_FOREVER 0xFFFFFFFF + +#endif /* __HI_TYPES__BASE_H__ */ diff --git a/sdk_liteos/include/hi_uart.h b/sdk_liteos/include/hi_uart.h new file mode 100644 index 0000000000000000000000000000000000000000..17918e0c2e8386b90080efd8fd90421bad88eb18 --- /dev/null +++ b/sdk_liteos/include/hi_uart.h @@ -0,0 +1,445 @@ +/** + * @file hi_uart.h + * + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Description: UART Port APIs. \n + */ +/** @defgroup iot_uart UART Port + * @ingroup drivers + */ +#ifndef __HI_UART_H__ +#define __HI_UART_H__ + +#include +#include "hi_mdm_types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @ingroup iot_uart + * + * UART serial number. CNcomment:UART序号。CNend + */ +typedef enum { + HI_UART_IDX_0, /**< Physical port number 0.CNcomment:物理端口号0 CNend */ + HI_UART_IDX_1, /**< Physical port number 1.CNcomment:物理端口号1 CNend */ + HI_UART_IDX_2, /**< Physical port number 2.CNcomment:物理端口号2 CNend */ + HI_UART_IDX_MAX /**< Maximum physical port number, which cannot be used. CNcomment:物理端口号最大值, + 不可使用CNend */ +} hi_uart_idx; + +/** + * @ingroup iot_uart + * + * UART data bit. CNcomment:UART数据位。CNend + */ +typedef enum { + HI_UART_DATA_BIT_5 = 5, /**< Data bit: support option 5bit.CNcomment:数据位:支持配置5bit.CNend */ + HI_UART_DATA_BIT_6, /**< Data bit: support option 6bit.CNcomment:数据位:支持配置6bit.CNend */ + HI_UART_DATA_BIT_7, /**< Data bit: support option 7bit.CNcomment:数据位:支持配置7bit.CNend */ + HI_UART_DATA_BIT_8, /**< Data bit: support option 8bit.CNcomment:数据位:支持配置8bit.CNend */ +} hi_uart_data_bit; + +/** + * @ingroup iot_uart + * + * UART stop bit. CNcomment:UART停止位。CNend + */ +typedef enum { + HI_UART_STOP_BIT_1 = 1, /**< Stop bit, 1bit.CNcomment:停止位,1bit停止位.CNend */ + HI_UART_STOP_BIT_2 = 2, /**< Stop bit, 2bit.CNcomment:停止位,2bit停止位.CNend */ +} hi_uart_stop_bit; + +/** + * @ingroup iot_uart + * + * UART parity bit. CNcomment:UART校验位。CNend + */ +typedef enum { + HI_UART_PARITY_NONE = 0, /**< Parity bit, None. CNcomment:校验位,无校验CNend */ + HI_UART_PARITY_ODD = 1, /**< Parity bit, odd. CNcomment:校验位,奇校验CNend */ + HI_UART_PARITY_EVEN = 2, /**< Parity bit, even. CNcomment:校验位,偶校验CNend */ +} hi_uart_parity; + +/** + * @ingroup iot_uart + * + * UART FIFO interruption limitation. CNcomment:UART FIFO中断门限。CNend + */ +typedef enum { + HI_FIFO_LINE_ONE_EIGHT = 1, /**< FIFO interruption limitation, FIFO LINE = 1/8full. + CNcomment:FIFO中断门限,FIFO LINE = 1/8full CNend */ + HI_FIFO_LINE_ONE_QUARTER, /**< FIFO interruption limitation, FIFO LINE = 1/4full. + CNcomment:FIFO中断门限,FIFO LINE = 1/4full CNend */ + HI_FIFO_LINE_HALF, /**< FIFO interruption limitation, FIFO LINE = 1/2full. + CNcomment:FIFO中断门限,FIFO LINE = 1/2full CNend */ + HI_FIFO_LINE_THREE_QUARTERS, /**< FIFO interruption limitation, FIFO LINE = 3/4full. + CNcomment:FIFO中断门限,FIFO LINE = 3/4full CNend */ + HI_FIFO_LINE_SEVEN_EIGHTS, /**< FIFO interruption limitation, FIFO LINE = 7/8full. + CNcomment:FIFO中断门限,FIFO LINE = 7/8full CNend */ +} hi_uart_fifo_line; + +/** + * @ingroup iot_uart + * + * UART block mode. CNcomment:UART 阻塞模式。CNend + */ +typedef enum { + HI_UART_BLOCK_STATE_NONE_BLOCK = 1, /**< block mode, none-block. CNcomment:UART阻塞模式,非阻塞传输 CNend */ + HI_UART_BLOCK_STATE_BLOCK, /**< block mode, block. CNcomment:UART阻塞模式,阻塞传输 CNend */ +} hi_uart_block_state; + +/** + * @ingroup iot_uart + * + * UART DMA transmation mode. CNcomment:UART DMA传输模式。CNend + */ +typedef enum { + HI_UART_NONE_DMA = 1, /**< None-DMA mode. CNcomment:DMA传输,不使用DMA CNend */ + HI_UART_USE_DMA, /**< DMA mode. CNcomment:DMA传输,使用DMA CNend */ +} hi_uart_dma_state; + +/** + * @ingroup iot_uart + * + * UART hardware flow control mode. CNcomment:UART 硬件流控控制模式。CNend + */ +typedef enum { + HI_FLOW_CTRL_NONE, /**< hardware flow ctrl: disable flow ctrl.CNcomment:不使用。CNend */ + HI_FLOW_CTRL_RTS_CTS, /**< hardware flow ctrl: enable rts and cts.CNcomment:使用RTS和CTS CNend */ + HI_FLOW_CTRL_RTS_ONLY, /**< hardware flow ctrl: enable rts only.CNcomment:只使用RTS CNend */ + HI_FLOW_CTRL_CTS_ONLY, /**< hardware flow ctrl: enable cts only.CNcomment:只使用CTS CNend */ +} hi_flow_ctrl; + +/** + * @ingroup iot_uart + * + * UART basic settings. CNcomment:UART端口基本配置参数。CNend + */ +typedef struct { + hi_u32 baud_rate; /**< Baud Rate.CNcomment:波特率。CNend */ + hi_u8 data_bits; /**< Data bit. CNcomment:数据位。CNend */ + hi_u8 stop_bits; /**< Stop bit. CNcomment:停止位。CNend */ + hi_u8 parity; /**< Parity check flag. CNcomment:奇偶校验位。CNend */ + hi_u8 pad; /**< reserved pad */ +} hi_uart_attribute; + +/** + * @ingroup iot_uart + * + * UART extra attributes.CNcomment:UART端口额外参数配置。CNend + */ +typedef struct { + hi_uart_fifo_line tx_fifo_line; + hi_uart_fifo_line rx_fifo_line; + hi_uart_fifo_line flow_fifo_line; + hi_uart_block_state tx_block; + hi_uart_block_state rx_block; + hi_u16 tx_buf_size; + hi_u16 rx_buf_size; + hi_uart_dma_state tx_use_dma; + hi_uart_dma_state rx_use_dma; +} hi_uart_extra_attr; + +/** +* @ingroup iot_uart +* @brief UART initialization. CNcomment:UART初始化。CNend +* +* @par 描述: +* Set UART with configuration. CNcomment:根据参数配置指定UART。CNend +* +* @attention 1.If extra_attr is set to HI_NULL, all optimization parameters of the notification driver use the default +* values.CNcomment:extra_attr为HI_NULL表示通知驱动所有优化参数使用默认值;CNend +* 2.If the value of the member parameter in extra_attr is 0, it indicates that the member parameter +* is notified to the driver. The member parameter uses the default value. +* CNcomment:extra_attr中成员参数值为0表示通知驱动该成员参数使用默认值;CNend +* 3.After the UART initialization is complete, if you want to change the UART optimization parameter +* configuration, you need to call hi_uart_deinit to deinitialize the UART before calling hi_uart_init +* to change the optimization parameter configuration. CNcomment:UART初始化完成后,若要变更UART +优化参数配置,需先调用hi_uart_deinit去初始化UART,再调用hi_uart_init变更优化参数配置。CNend +* +* @param id [IN] type #hi_uart_idx,UART port id. CNcomment:UART端口号。CNend +* @param param [IN] type #const hi_uart_attribute*,UART base settings.CNcomment:UART基本参数。CNend +* @param extra_attr [IN] type #const hi_uart_extra_attr*,UART extra settings. CNcomment:UART优化参数。CNend +* +* @retval #HI_ERR_SUCCESS Success. +* @retval #HI_ERR_FAILURE Failure. +* @par 依赖: +* @li hi_uart.h:Describes UART APIs.CNcomment:UART相关接口。CNend +* @see hi_uart_deinit。 +*/ +hi_u32 hi_uart_init(hi_uart_idx id, const hi_uart_attribute *param, const hi_uart_extra_attr *extra_attr); + +/** +* @ingroup iot_uart +* @brief Reads data.CNcomment:读数据。CNend +* +* @par 描述: +* Reads the data received by the UART. CNcomment:将UART接收到的数据读取出来。CNend +* +* @attention This API must be used after the hi_uart_open function is called. +CNcomment:须在调用完hi_uart_init函数之后使用。CNend +* @param id [IN] type #hi_uart_idx,UART port id. CNcomment:UART端口号。CNend +* @param data [OUT] type #hi_u8*,Start address of the data to be read.CNcomment:读到数据的首地址。CNend +* @param data_len [IN] type #hi_u32,Number of bytes to be read.CNcomment:要读取数据的字节数。CNend +* +* @retval #>=0 Number of bytes that are actually read.CNcomment:实际读到数据的字节数。CNend +* @retval #HI_ERR_FAILURE Data read error.CNcomment:读数据失败。CNend +* @par 依赖: +* @li hi_uart.h:Describes UART APIs.CNcomment:UART相关接口。CNend +* @see hi_uart_write。 +*/ +hi_s32 hi_uart_read(hi_uart_idx id, hi_u8 *data, hi_u32 data_len); + +/** +* @ingroup iot_uart +* @brief Reads data in specified timeout time.CNomment:在指定超时时间内读取数据。CNend +* +* @par 描述: +* Reads data in specified timeout time.CNomment:在指定超时时间内读取数据。CNend +* if Reads all data before timeout, function will return. +CNomment:超时前读取完成所有数据后,函数会立即返回。CNend +* +* @attention This API must be used after the hi_uart_open function is called. +CNcomment:须在调用完hi_uart_init函数之后使用。CNend +* @param id [IN] type #hi_uart_idx,UART port id. CNcomment:UART端口号。CNend +* @param data [OUT] type #hi_u8*,Start address of the data to be read.CNcomment:读到数据的首地址。CNend +* @param data_len [IN] type #hi_u32,Number of bytes to be read.CNcomment:要读取数据的字节数。CNend +* @param timeout_ms [IN] type #hi_u32,timeout.CNcomment:超时时间。CNend +* +* @retval #>=0 Number of bytes that are actually read.CNcomment:实际读到数据的字节数。CNend +* @retval #HI_ERR_FAILURE Data read error.CNcomment:读数据失败。CNend +* @par 依赖: +* @li hi_uart.h:Describes UART APIs.CNcomment:UART相关接口。CNend +* @see hi_uart_write。 +*/ +hi_s32 hi_uart_read_timeout(hi_uart_idx id, hi_u8 *data, hi_u32 len, hi_u32 timeout_ms); + +/** +* @ingroup iot_uart +* @brief Writes data.CNcomment:写数据。CNend +* +* @par 描述: +* Writes the data to be sent to the UART. The block mode is used by default. +CNcomment:将待发送的数据写到UART。CNend +* +* @attention This API must be used after the hi_uart_init function is called. +CNcomment:须在调用完hi_uart_init函数之后使用。CNend +* @param id [IN] type #hi_uart_idx,UART port id. CNcomment:UART端口号。CNend +* @param data [IN] type #const hi_u8*,Start address of the data to be written.CNcomment:待写数据的首地址。CNend +* @param data_len [IN] type #hi_u32,Number of bytes to be written.CNcomment:待写数据的字节数。CNend +* +* @retval #>=0 Number of bytes to be sent.CNcomment:实际发送数据的字节数。CNend +* @retval #HI_ERR_FAILURE Data send failure. CNcomment:发送数据失败。CNend +* @par 依赖: +* @li hi_uart.h:Describes UART APIs.CNcomment:UART相关接口。CNend +* @see hi_uart_read。 +*/ +hi_s32 hi_uart_write(hi_uart_idx id, const hi_u8 *data, hi_u32 data_len); + +/** +* @ingroup iot_uart +* @brief Deinitializes UART.CNcomment:去初始化UART。CNend +* +* @par 描述: +* Deinitializes UART.CNcomment:去初始化UART。CNend +* +* @attention This API is used together with hi_uart_init.CNcomment:与hi_uart_init成对使用。CNend +* @param id [IN] type #hi_uart_idx,UART port id. CNcomment:UART端口号。CNend +* +* @retval #HI_ERR_SUCCESS Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_uart.h:Describes UART APIs.CNcomment:UART相关接口。CNend +* @see hi_uart_init。 +*/ +hi_u32 hi_uart_deinit(hi_uart_idx id); + +/** +* @ingroup iot_uart +* @brief Set UART hardware flow control.CNcomment:配置UART硬件流控功能。CNend +* +* @par 描述: +* Set UART hardware flow control.CNcomment:配置UART硬件流控功能。CNend +* +* @attention This API must be used after the hi_uart_init function is called. UART0 doesn't support flow control. +CNcomment:须在调用完hi_uart_init函数之后使用;UART0不支持流控功能。CNend +* +* @param id [IN] type #hi_uart_idx,UART port id. CNcomment:UART端口号。CNend +* @param flow_ctrl [IN] type #hi_flow_ctrl,haredware flow control mode. +CNcomment:硬件流控功能控制模式。CNend +* +* @retval #HI_ERR_SUCCESS Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_uart.h:Describes UART APIs.CNcomment:UART相关接口。CNend +* @see 无。 +*/ +hi_u32 hi_uart_set_flow_ctrl(hi_uart_idx id, hi_flow_ctrl flow_ctrl); + +/** +* @ingroup iot_uart +* @brief Write data by polling. CNcomment:轮询写数据。CNend +* +* @par 描述: +* Write data by polling. CNcomment:通过轮询的方式将待发送的数据写到UART。CNend +* +* @attention This API must be used after the hi_uart_init function is called. +CNcomment:须在调用完hi_uart_init函数之后使用。CNend +* +* @param id [IN] type #hi_uart_idx,UART port id. CNcomment:UART端口号。CNend +* @param data [IN] type #const hi_u8*,Start address of the data to be written.CNcomment:待写数据的首地址。CNend +* @param data_len [IN] type #hi_u32,Number of bytes to be written.CNcomment:待写数据的字节数。CNend +* +* @retval #>=0 Number of bytes to be sent.CNcomment:实际发送数据的字节数。CNend +* @retval #HI_ERR_FAILURE Data send failure. CNcomment:发送数据失败。CNend +* @par 依赖: +* @li hi_uart.h:Describes UART APIs.CNcomment:UART相关接口。CNend +* @see None +*/ +hi_s32 hi_uart_write_immediately(hi_uart_idx id, const hi_u8 *data, hi_u32 data_len); + +/** +* @ingroup iot_uart +* @brief Obtains UART settings. CNcomment:获取UART配置参数。CNend +* +* @par 描述: +* Obtains UART settings. CNcomment:获取指定UART当前配置参数。CNend +* +* @attention If extra_attr is HI_NULL, the current UART optimization parameters are not requested. This parameter +* must be used after the hi_uart_init function is invoked.CNcomment:extra_attr为HI_NULL表示不请求 +当前UART的优化参数;须在调用完hi_uart_init函数之后使用。CNend +* +* @param id [IN] type #hi_uart_idx,UART port id. CNcomment:UART端口号。CNend +* @param attr [OUT] type #hi_uart_attribute*,UART base settings.CNcomment:UART基本参数。CNend +* @param extra_attr [OUT] type #hi_uart_extra_attr*,UART extra settings. CNcomment:UART优化参数。CNend +* +* @retval #HI_ERR_SUCCESS Success. +* @retval #HI_ERR_FAILURE Failure. +* @par 依赖: +* @li hi_uart.h:Describes UART APIs.CNcomment:UART相关接口。CNend +* @see hi_uart_init。 +*/ +hi_u32 hi_uart_get_attribute(hi_uart_idx id, hi_uart_attribute *attr, hi_uart_extra_attr *extra_attr); + +/** +* @ingroup iot_uart +* @brief Determine FIFO and soft buf is empty. CNcomment:判断FIFO与软件BUF是否为空。CNend +* +* @par 描述: +* Determine FIFO and soft buf is empty. CNcomment:判断指定UART的FIFO与软件BUF是否为空。CNend +* +* @attention This API must be used after the hi_uart_init function is called. +CNcomment:须在调用完hi_uart_init函数之后使用。CNend +* +* @param id [IN] type #hi_uart_idx,UART port id. CNcomment:UART端口号。CNend +* @param empty [OUT] type #hi_bool*,Store query result, HI_TRUE means empty, HI_FALSE means non-empty. +CNcomment:存储查询结果,如果为HI_TRUE代表FIFO与软件BUF都为空,如果为HI_FALSE表示非空。CNend +* +* @retval #HI_ERR_SUCCESS Success. +* @retval #HI_ERR_FAILURE Failure. +* @par 依赖: +* @li hi_uart.h:Describes UART APIs.CNcomment:UART相关接口。CNend +* @see hi_uart_init。 +*/ +BSP_RAM_TEXT_SECTION hi_u32 hi_uart_is_buf_empty(hi_uart_idx id, hi_bool *empty); + +/** +* @ingroup iot_uart +* @brief Determine UART is busy. CNcomment:判断UART是否忙。CNend +* +* @par 描述: +* Determine UART is busy. CNcomment:判断指定UART是否忙。CNend +* +* @attention This API must be used after the hi_uart_init function is called. +CNcomment:须在调用完hi_uart_init函数之后使用。CNend +* +* @param id [IN] type #hi_uart_idx,UART port id. CNcomment:UART端口号。CNend +* @param busy [OUT] type #hi_bool*,Store query result, HI_TRUE means busy, HI_FALSE means not busy. +CNcomment:存储查询结果,如果为HI_TRUE代表UART在忙,如果为HI_FALSE表示空闲。CNend +* +* @retval #HI_ERR_SUCCESS Success. +* @retval #HI_ERR_FAILURE Failure. +* @par 依赖: +* @li hi_uart.h:Describes UART APIs.CNcomment:UART相关接口。CNend +* @see hi_uart_init。 +*/ +BSP_RAM_TEXT_SECTION hi_u32 hi_uart_is_busy(hi_uart_idx id, hi_bool *busy); + +/** +* @ingroup iot_uart +* @brief Quits Read data.CNcomment:退出阻塞读数据。CNend +* +* @par 描述: +* Quits Read data. CNcomment:退出阻塞读数据。CNend +* +* @attention Only apply in block read mode. +CNcomment:该接口仅应用在阻塞读数据模式下。CNend +* @param id [IN] type #hi_uart_idx,UART port id. CNcomment:UART端口号。CNend +* +* @retval #HI_ERR_SUCCESS Success. +* @retval #Other Failure. +* @par 依赖: +* @li hi_uart.h:Describes UART APIs.CNcomment:UART相关接口。CNend +* @see hi_uart_quit_read。 +*/ +hi_u32 hi_uart_quit_read(hi_uart_idx id); + +/** +* @ingroup iot_uart +* @brief Save register-related values before going to deep sleep.CNcomment:深睡前保存相关寄存器内容。CNend +* +* @par 描述: +* Regs-related values are saved before entering deep sleep to facilitate sleep recovery. +CNcomment:深睡前保存相关寄存器内容,以便于睡醒恢复UART。CNend +* +* @attention Called before deep sleep. +CNcomment:在深睡前调用。CNend +* @param id [IN] type #hi_uart_idx,UART port id. CNcomment:UART端口号。CNend +* +* @retval #HI_ERR_SUCCESS Success. +* @retval #Other Failure. +* @par 依赖: +* @li hi_uart.h:Describes UART APIs.CNcomment:UART相关接口。CNend +* @see hi_uart_lp_save。 +*/ +hi_u32 hi_uart_lp_save(hi_uart_idx id); + +/** +* @ingroup iot_uart +* @brief Restore register related values after deep sleep wake up.CNcomment:深睡唤醒后恢复寄存器内容。CNend +* +* @par 描述: +* Restore register related values after deep sleep wake up.CNcomment:深睡唤醒后恢复寄存器内容。CNend +* +* @attention Called after deep sleep wake up. +CNcomment:深睡唤醒后调用。CNend +* @param id [IN] type #hi_uart_idx,UART port id. CNcomment:UART端口号。CNend +* +* @retval #HI_ERR_SUCCESS Success. +* @retval #Other Failure. +* @par 依赖: +* @li hi_uart.h:Describes UART APIs.CNcomment:UART相关接口。CNend +* @see hi_uart_lp_restore。 +*/ +hi_u32 hi_uart_lp_restore(hi_uart_idx id); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/include/hi_upg_api.h b/sdk_liteos/include/hi_upg_api.h new file mode 100644 index 0000000000000000000000000000000000000000..3eefe1a46723599d4d18159584eeca4917330fcf --- /dev/null +++ b/sdk_liteos/include/hi_upg_api.h @@ -0,0 +1,267 @@ +/* + * @file hi_upg_api.h + * + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @defgroup upg Upgrade + * @ingroup system +*/ + +#ifndef __HI_UPG_API_H__ +#define __HI_UPG_API_H__ +#include "hi_upg_file.h" +#include + +/** + * @ingroup upg + * Kernel upgrade file. CNcomment:Kernel升级文件。CNend + */ +#define HI_UPG_FILE_KERNEL 0xF0 + +/** + * @ingroup upg + * FlashBoot upgrade file. CNcomment:FlashBoot升级文件。CNend + */ +#define HI_UPG_FILE_BOOT 0xE1 + +/** + * @ingroup upg + * Kernel upgrade file of area A. CNcomment:A区升级文件。CNend + */ +#define HI_UPG_FILE_FOR_AREA_A 1 + +/** + * @ingroup upg + * Kernel upgrade file of area B/Compress kernel upgrade file. CNcomment:B区升级文件/压缩升级文件。CNend + */ +#define HI_UPG_FILE_FOR_AREA_B 2 + +/** + * @ingroup upg + * Kernel upgrade file magic number. CNcomment:Kernel升级文件魔术字。CNend + */ +#define HI_UPG_FILE_IMAGE_ID 0x3C78961E + +/** +* @ingroup upg +* @brief Upgrade module initialization.CNcomment:升级模块初始化。CNend +* +* @par 描述: + Upgrade module initialization.CNcomment:升级模块初始化。CNend +* @attention +* @li Must be called immediately after NV initialization. CNcomment:必须紧跟NV初始化后调用。CNend +* @li This interface does not support multiple calls. CNcomment:该接口不支持多次调用。CNend +* @param None. +* @retval #HI_ERR_SUCCESS Success.CNcomment:升级模块初始化成功。CNend +* @retval #Other Failure.CNcomment:其他值 升级模块初始化失败。CNend +* @par 依赖: +* @li hi_upg_api.h:Describe Upgrade usage APIs.CNcomment:文件用于描述升级对外接口。CNend +* @see None.CNcomment:无。CNend +*/ +hi_u32 hi_upg_init(hi_void); + +/** +* @ingroup upg +* @brief Get upgrade file from the backup flash.CNcomment:从备份区读取升级文件。CNend +* +* @par 描述: + Used to get upgrade data from the backup flash.CNcomment:该函数从备份区读升级文件。CNend +* @attention +* @li Ensure that the actual buffer size is the same as the value of buf_len. +* CNcomment:用户需保证buf实际大小与buf_len相等。CNend +* @li Must be called after calling interface hi_upg_transmit or hi_upg_transmit_finish_save_cache. +CNcomment:必须在调用升级文件传输接口之后调用。CNend +* @li Must be called before calling interface hi_upg_transmit_finish in non-power-off upgrade scenario. +CNcomment:非断电升级场景必须在调用升级文件传输完成之前调用。CNend +* @li Must be called before calling interface hi_upg_finish_with_cache in power-off upgrade scenario. +CNcomment:断电升级场景必须在调用升级结束完成之前调用。CNend +* @param offset [IN] type #hi_u32 Offset relative to the start address of the upgrade cache. +* CNcomment:相对升级备份区起始地址的偏移地址。CNend +* @param buf [IN/OUT] type #hi_u8* Pointer to the upgrade data package.CNcomment:升级数据包指针。CNend +* @param buf_len [IN] type #hi_u32 Length of the upgrade data package.Unit: byte. +* CNcomment:升级数据包长度,单位:byte。CNend +* @retval #HI_ERR_SUCCESS Success.CNcomment:读成功。CNend +* @retval #Other Failure.CNcomment:其他值 读失败。CNend +* @par 依赖: +* @li hi_upg_api.h:Describe Upgrade usage APIs.CNcomment:文件用于描述升级对外接口。CNend +* @see hi_upg_transmit_finish_save_cache; hi_upg_finish_with_cache; hi_upg_transmit; hi_upg_transmit_finish. +*/ +hi_u32 hi_upg_get_content(hi_u32 offset, hi_u8* buf, hi_u32 buf_len); + +/** +* @ingroup upg +* @brief Transmit upgrade file.CNcomment:传输升级文件。CNend +* +* @par 描述: + Transmit upgrade file.CNcomment:传输升级文件。CNend +* @attention +* @li The first packet transmitted is not less than 96 bytes.CNcomment:传输的第1包不小于96字节。CNend +* @param offset [IN] type #hi_u32 Offset relative to the head of the upgrade file.CNcomment:相对升级文件头的偏移地址。CNend +* @param buf [IN] type #hi_u8* Upgrade file data.CNcomment:升级数据包。CNend +* @param buf_len [IN] type #hi_u32 Length of the upgrade file data.Unit:byte.CNcomment:升级数据包长度,单位:byte。CNend +* @retval #HI_ERR_SUCCESS Success.CNcomment:成功。CNend +* @retval #Other Failure.CNcomment:其他值 失败。CNend +* @par 依赖: +* @li hi_upg_api.h:Describe Upgrade usage APIs.CNcomment:文件用于描述升级对外接口。CNend +* @see None.CNcomment:无。CNend +*/ +hi_u32 hi_upg_transmit(hi_u32 offset, hi_u8* buf, hi_u32 buf_len); + +/** +* @ingroup upg +* @brief Upgrade restart.CNcomment:升级重启。CNend +* +* @par 描述: + This interface is used to restart.CNcomment:该接口实现升级重启。CNend +* @attention None. +* @param None. +* @retval None. +* @par 依赖: +* @li hi_upg_api.h:Describe Upgrade usage APIs.CNcomment:文件用于描述升级对外接口。CNend +* @see None.CNcomment:无。CNend +*/ +hi_void hi_upg_finish(hi_void); + +/** +* @ingroup upg +* @brief Notify file transfer end.CNcomment:文件传输结束。CNend +* +* @par 描述: + Used to notify file transfer end.CNcomment:文件传输结束。CNend +* @attention None. +* @param None. +* @retval #HI_ERR_SUCCESS Success.CNcomment:成功。CNend +* @retval #Other Failure.CNcomment:其他值 失败。CNend +* @par 依赖: +* @li hi_upg_api.h:Describe Upgrade usage APIs.CNcomment:文件用于描述升级对外接口。CNend +* @see None.CNcomment:无。CNend +*/ +hi_u32 hi_upg_transmit_finish(hi_void); + +/** +* @ingroup upg +* @brief Upgrade restart. The power-off or restart operation is allowed before upgrade restart. + CNcomment:升级重启,支持断电后执行升级重启操作。CNend +* +* @par 描述: + This interface is used to restart. It works with hi_upg_transmit_finish_save_cache and applies to scenarios + where the upgrade is not required immediately. + CNcomment:该接口实现升级重启,与hi_upg_transmit_finish_save_cache配合使用,适用于不需要立即进行升级的场景。CNend +* @attention +* @li The power-off or restart operation is allowed between hi_upg_transmit_finish_save_cache and + hi_upg_finish_with_cache. +CNcomment:允许在hi_upg_transmit_finish_save_cache和hi_upg_finish_with_cache的调用之间存在掉电或重启操作。CNend. +* @param None. +* @retval #HI_ERR_SUCCESS Success.CNcomment:成功。CNend +* @retval #Other Failure.CNcomment:其他值 失败。CNend +* @par 依赖: +* @li hi_upg_api.h:Describe Upgrade usage APIs.CNcomment:文件用于描述升级对外接口。CNend +* @see None.CNcomment:无。CNend +*/ +hi_u32 hi_upg_finish_with_cache(hi_void); + +/** +* @ingroup upg +* @brief Notify file transfer is complete and save some key parameters of the transfer process. + CNcomment:文件传输结束,保存传输流程的关键参数。CNend +* +* @par 描述: + Used to notify file transfer end and save some key parameters of the transfer process. It works with + hi_upg_finish_with_cache and applies to scenarios where the upgrade is not required immediately. + CNcomment:文件传输结束,保存传输流程的关键参数。与hi_upg_finish_with_cache配合使用,适用于不需要立即 + 进行升级的场景。CNend +* @attention +* @li The power-off or restart operation is allowed between hi_upg_transmit_finish_save_cache and + hi_upg_finish_with_cache. +CNcomment:允许在hi_upg_transmit_finish_save_cache和hi_upg_finish_with_cache的调用之间存在掉电或重启操作。CNend. +* @param None. +* @retval #HI_ERR_SUCCESS Success.CNcomment:成功。CNend +* @retval #Other Failure.CNcomment:其他值 失败。CNend +* @par 依赖: +* @li hi_upg_api.h:Describe Upgrade usage APIs.CNcomment:文件用于描述升级对外接口。CNend +* @see None.CNcomment:无。CNend +*/ +hi_u32 hi_upg_transmit_finish_save_cache(hi_void); + +/** +* @ingroup upg +* @brief Get the maximum upgrade file length.CNcomment:获取最大升级文件长度。CNend +* +* @par 描述: + Used to get the maximum upgrade file length.CNcomment:获取最大升级文件长度。CNend +* @attention None. +* @param file_type [IN] type #hi_u8 Upgrade file type.CNcomment:升级文件类型。CNend +* @param file_len [IN/OUT] type #hi_u32* Max file length.CNcomment:最大升级文件大小。CNend +* @retval #HI_ERR_SUCCESS Success.CNcomment:成功。CNend +* @retval #Other Failure.CNcomment:其他值 失败。CNend +* @par 依赖: +* @li hi_upg_api.h:Describe Upgrade usage APIs.CNcomment:文件用于描述升级对外接口。CNend +* @see None.CNcomment:无。CNend +*/ +hi_u32 hi_upg_get_max_file_len(hi_u8 file_type, hi_u32 *file_len); + +/** +* @ingroup upg +* @brief Get the upgrade file index.CNcomment:获取升级文件编号。CNend +* +* @par 描述: + Get the upgrade file index.CNcomment:获取升级文件编号。CNend +* @attention None.CNcomment:无。CNend +* @param index [IN/OUT] type #hi_u8* Upgrade file index.CNcomment:升级文件编号。CNend +* @retval #1 Upg file for area A.CNcomment:1 A区升级文件。CNend +* @retval #2 Upg file for area B.CNcomment:2 B区升级文件。CNend +* @par 依赖: +* @li hi_upg_api.h:Describe Upgrade usage APIs.CNcomment:文件用于描述升级对外接口。CNend +* @see None.CNcomment:无。CNend +*/ +hi_u32 hi_upg_get_file_index(hi_u8 *index); + +/** +* @ingroup upg +* @brief Stop the upgrade process.CNcomment:停止升级。CNend +* +* @par 描述: + Used to stop the upgrade process.CNcomment:停止升级。CNend +* @attention None. +* @param None. +* @retval #HI_ERR_SUCCESS Success.CNcomment:成功。CNend +* @retval #Other Failure.CNcomment:其他值 失败。CNend +* @par 依赖: +* @li hi_upg_api.h:Describe Upgrade usage APIs.CNcomment:文件用于描述升级对外接口。CNend +* @see None.CNcomment:无。CNend +*/ +hi_u32 hi_upg_stop(hi_void); + +/** +* @ingroup upg +* @brief Register upgrade file validity check interface.CNcomment:注册升级文件合法性校验接口。CNend +* +* @par 描述: + Register upgrade file validity check interface.CNcomment:注册升级文件合法性校验接口。CNend +* @attention Called during the initialization process.CNcomment:初始化流程中调用。CNend +* @param upg_file_check_fn [IN]User-defined upgrade file verification interface.CNcomment:用户自定义接口。CNend +* @param param [IN]Passed back to callback function when callback.CNcomment:用户自定义接口参数。CNend +* @retval #HI_ERR_SUCCESS Success.CNcomment:成功。CNend +* @retval #Other Failure.CNcomment:其他值 失败。CNend +* @par 依赖: +* @li hi_upg_api.h:Describe Upgrade usage APIs.CNcomment:文件用于描述升级对外接口。CNend +* @see None.CNcomment:无。CNend +*/ +hi_u32 hi_upg_register_file_verify_fn( + hi_u32 (*upg_file_check_fn)(const hi_upg_user_info *info, hi_void *param), + hi_void *param); + +#endif \ No newline at end of file diff --git a/sdk_liteos/include/hi_upg_file.h b/sdk_liteos/include/hi_upg_file.h new file mode 100644 index 0000000000000000000000000000000000000000..e69af31159ce6b5ebb8d3e6896f2718778b6090f --- /dev/null +++ b/sdk_liteos/include/hi_upg_file.h @@ -0,0 +1,196 @@ +/* + * @file hi_upg_file.h + * + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @defgroup upg Upgrade + * @ingroup system +*/ + +#ifndef __HI_UPG_FILE_H__ +#define __HI_UPG_FILE_H__ + +#include + +/** + * + * Initial vector length.CNcomment:初始向量长度。CNend + */ +#define IV_BYTE_LEN 16 + +/** + * + * RSA2048 parameter length.CNcomment:RSA2048参数长度。CNend + */ +#define RSA_2048_LEN 256 + +/** + * + * RSA2048 parameter E length.CNcomment:RSA2048参数E长度。CNend + */ +#define RSA_EXP_E_LEN 4 + +/** + * + * ECC parameter length.CNcomment:ECC参数长度。CNend + */ +#define ECC_32_BYTES 32 + +/** + * + * SHA256 hash length.CNcomment:SHA256哈希值长度。CNend + */ +#define SHA_256_LEN 32 + +/** + * @ingroup upg + * + * Parameter of sign algorithm.CNcomment:签名算法参数。CNend + */ +typedef struct { + hi_u32 hash_alg : 16; /**< HASH algorithm:0:SHA256.CNcomment:HASH算法。CNend */ + hi_u32 sign_alg : 6; /**< Sign algorithm:0:RSA-PKCS;1:RSA-PSS;0x10:ECDSA256;0x3F:SHA256.CNcomment:签名算法。CNend */ + hi_u32 sign_param : 10; /**< Sign parameter, default '0'.CNcomment:HASH算法。CNend */ +} sign_alg_param; + +typedef struct { + hi_u8 mod_n[RSA_2048_LEN]; /**< Mod N.CNcomment:RSA参数N。CNend */ + hi_u8 exp_e[RSA_EXP_E_LEN]; /**< Exp E.CNcomment:RSA参数E。CNend */ + hi_u8 padding[28]; /**< Padding field:28.CNcomment:填充字段。CNend */ +} upg_rsa_key; + +typedef struct { + hi_u8 sign[RSA_2048_LEN]; /**< RSA signature.CNcomment:RSA签名。CNend */ +} upg_rsa_sign; + +typedef struct { + hi_u8 px[ECC_32_BYTES]; /**< Pubkey x.CNcomment:ECC密钥x。CNend */ + hi_u8 py[ECC_32_BYTES]; /**< Pubkey y.CNcomment:ECC密钥y。CNend */ + hi_u8 padding[224]; /**< Padding field:224. CNcomment:填充字段。CNend */ +} upg_ecc_key; + +typedef struct { + hi_u8 r[ECC_32_BYTES]; /**< Signature of ECC.CNcomment:ECC签名信息r。CNend */ + hi_u8 s[ECC_32_BYTES]; /**< Signature of ECC.CNcomment:ECC签名信息s。CNend */ + hi_u8 padding[192]; /**< Padding field:192.CNcomment:填充字段。CNend */ +} upg_ecc_sign; + +typedef struct { + hi_u8 padding[288]; /**< Padding field:288.CNcomment:填充字段。CNend */ +} upg_sha256_key; + +typedef struct { + hi_u8 check_sum[SHA_256_LEN]; /**< Hash value of SHA256.CNcomment:SHA256算法哈希值。CNend */ + hi_u8 padding[224]; /**< Padding field:224.CNcomment:填充字段。CNend */ +} upg_sha256_sign; + +/** + * @ingroup upg + * + * Parameters of user-defined fields.CNcomment:用户自定义字段。CNend + */ +typedef struct { + hi_u8 reserved[32]; /**< 32:Reserved for user.CNcomment:用户自定义字段。CNend */ +}hi_upg_user_info; + +typedef struct { + hi_u32 image_id; /**< Identity of upgrade file Key Area.CNcomment:升级文件魔术字。CNend */ + hi_u32 struct_version; /**< The structure of upgrade file version.CNcomment:升级文件结构体版本号。CNend */ + hi_u32 section_offset; /**< Offset of upgrade Section.CNcomment:Section段偏移。CNend */ + hi_u32 section_len; /**< Length of upgrade Section.CNcomment:Section段长度。CNend */ + hi_upg_user_info user_info; /**< Reserved for user.CNcomment:用户自定义字段。CNend */ + hi_u8 file_type; /**< Upgrade file type:0xF0: kernel file; 0xE1: boot file.CNcomment:升级文件类型。CNend */ + hi_u8 file_version; /**< File Version, for anti-rollback. [0, 16] for boot file and [0, 48] for kernel file. + CNcomment:升级文件结构体版本号。CNend */ + hi_u8 encrypt_flag; /**< 0x42: Section Area is not encrypted; other: Section Area is encrypted. + CNcomment:Section段加密标志。CNend */ + hi_u8 file_attr; /**< File Attributes.CNcomment:文件属性。CNend */ + hi_u32 file_len; /**< Entire file length.CNcomment:升级文件长度。CNend */ + hi_u32 key_len; /**< Length of Key(288Bytes).True length:RSA2048: 272 Bytes, ECDSA: 64Bytes. + CNcomment:密钥长度。CNend */ + sign_alg_param param; /**< Parma of the signature algorithm.CNcomment:签名算法参数。CNend */ + hi_u8 aes_key[IV_BYTE_LEN]; /**< Part of key factor.CNcomment:AES密钥。CNend */ + hi_u8 aes_iv[IV_BYTE_LEN]; /**< The IV (AES-256 CBC-mode) to encrypt Section.CNcomment:AES初始向量。CNend */ +} hi_upg_common_head; + +typedef struct { + hi_u32 image_id; /**< Identity of upgrade file Key Area.CNcomment:升级文件魔术字。CNend */ + hi_u32 struct_version; /**< The structure of upgrade file Section Area.CNcomment:升级文件结构体版本号。CNend */ + sign_alg_param param; /**< The signature algorithm.CNcomment:签名算法参数。CNend */ + hi_u8 section_count; /**< The number of sections.CNcomment:Section段个数。CNend */ + hi_u8 reserved[27]; /**< 27 bytes reserved.CNcomment:保留字段。CNend */ + hi_u8 section0_compress; /**< Whether section 0 is compressed.CNcomment:Section0是否压缩。CNend */ + hi_u8 pad0[3]; /**< 3 bytes padding.CNcomment:填充字段。CNend */ + hi_u32 section0_offset; /**< Offset of Section0.CNcomment:Section0段偏移。CNend */ + hi_u32 section0_len; /**< Length of Section0, aligned to 16 bytes.CNcomment:Section0段长度。CNend */ + hi_u8 section1_compress; /**< Whether section 1 is compressed.CNcomment:Section1是否压缩Nend */ + hi_u8 pad1[3]; /**< 3 bytes padding.CNcomment:填充字段。CNend */ + hi_u32 section1_offset; /**< Offset of Section1.CNcomment:Section1段偏移。CNend */ + hi_u32 section1_len; /**< Length of Section1, aligned to 16 bytes.CNcomment:Section1段长度。CNend */ +} hi_upg_section_head; + +typedef struct { + upg_rsa_key key; /**< Key of rsa.CNcomment:RSA算法密钥。CNend */ + upg_rsa_sign sign; /**< Sign of rsa.CNcomment:RSA算法签名。CNend */ +} hi_upg_rsa_alg; + +typedef struct { + upg_ecc_key key; /**< Key of ecc.CNcomment:ECC算法密钥。CNend */ + upg_ecc_sign sign; /**< Sign of ecc.CNcomment:ECC算法签名。CNend */ +} hi_upg_ecc_alg; + +typedef struct { + upg_sha256_key key; /**< Padding field.CNcomment:填充字段。CNend */ + upg_sha256_sign sign; /**< Hash of sha256.CNcomment:SHA256算法哈希值。CNend */ +} hi_upg_sha256_alg; + +typedef struct { + union { + upg_rsa_key rsa; /**< Key of rsa.CNcomment:rsa密钥。CNend */ + upg_ecc_key ecc; /**< Key of ecc.CNcomment:ecc密钥。CNend */ + upg_sha256_key sha; /**< Padding field.CNcomment:填充字段。CNend */ + } key; +}hi_upg_key; + +typedef struct { + union { + upg_rsa_sign rsa; /**< Sign of rsa.CNcomment:rsa签名。CNend */ + upg_ecc_sign ecc; /**< Sign of ecc.CNcomment:ecc签名。CNend */ + upg_sha256_sign sha; /**< Hash of sha256.CNcomment:SHA256哈希。CNend */ + } sign; +}hi_upg_sign; + +typedef struct { + hi_upg_common_head common; /**< Common head of upg file.CNcomment:公共文件头。CNend */ + union { + hi_upg_rsa_alg rsa; /**< Key and sign of RSA.CNcomment:RSA密钥及签名信息。CNend */ + hi_upg_ecc_alg ecc; /**< Key and sign of ECC.CNcomment:ECC密钥及签名信息。CNend */ + hi_upg_sha256_alg sha;/**< Key and sign of SHA256.CNcomment:SHA256密钥及签名信息。CNend */ + } sign_alg; +} hi_upg_head; + +typedef struct { + hi_upg_common_head common; /**< Common head of upg file.CNcomment:公共文件头。CNend */ + union { + hi_upg_rsa_alg rsa; /**< Key and sign of RSA.CNcomment:RSA密钥及签名信息。CNend */ + hi_upg_ecc_alg ecc; /**< Key and sign of ECC.CNcomment:ECC密钥及签名信息。CNend */ + hi_upg_sha256_alg sha; /**< Key and sign of SHA256.CNcomment:SHA256密钥及签名信息。CNend */ + } sign_alg; + hi_upg_section_head section; /**< Head of code section.CNcomment:Code段头信息。CNend */ + hi_upg_sign section_sign; /**< Sign of code section.CNcomment:Code段签名信息。CNend */ +} hi_upg_file_head; + +#endif diff --git a/sdk_liteos/include/hi_ver.h b/sdk_liteos/include/hi_ver.h new file mode 100644 index 0000000000000000000000000000000000000000..a4f528f78d55ccaf6cae57bf671bb7d861f41c31 --- /dev/null +++ b/sdk_liteos/include/hi_ver.h @@ -0,0 +1,78 @@ +/* + * @file hi_ver.h + * + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** @defgroup iot_ver Soft ver + * @ingroup system + */ + +#ifndef __HI_VER_H__ +#define __HI_VER_H__ +#include +#ifdef __cplusplus +extern "C" { +#endif + +/** +* @ingroup iot_ver +* @brief Obtains SDK version information. CNcomment:获取SDK版本信息CNend +* +* @par 描述: +* Obtains SDK version information. CNcomment:获取SDK版本信息CNend +* @attention None +* @retval #hi_char* SDK version information string. CNcomment:SDK版本信息字符串CNend +* +* @par Dependency: +* @li hi_ver.h: This file describes version information APIs.CNcomment:文件用于描述系统相关接口.CNend +* @see None +*/ +const hi_char *hi_get_sdk_version(hi_void); + +/** +* @ingroup iot_ver +* @brief Obtains boot version in secure boot mode. CNcomment:安全启动模式下,获取BOOT版本号CNend +* +* @par 描述: +* Obtains boot version in secure boot mode. CNcomment:安全启动模式下,获取BOOT版本号CNend +* @attention Ver always be 0 in non-secure boot mode. CNcomment: 非安全启动模式下,该版本号始终为0。CNend +* @retval #hi_u8 boot ver num, value from 0-16, Return 0xFF means get boot ver fail. +CNcomment:boot版本号,有效值为0-16,返回0xFF表示获取BOOT版本号失败CNend +* @par Dependency: +* @li hi_ver.h: This file describes version information APIs.CNcomment:文件用于描述系统相关接口.CNend +* @see None +*/ +hi_u8 hi_get_boot_ver(hi_void); + +/** +* @ingroup iot_ver +* @brief Obtains kernel version in secure boot mode. CNcomment:安全启动模式下,获取kernel版本号CNend +* +* @par 描述: +* Obtains kernel version in secure boot mode. CNcomment:安全启动模式下,获取kernel版本号CNend +* @attention Ver always be 0 in non-secure boot mode. CNcomment:非安全启动模式下,该版本号始终为0。CNend +* @retval #hi_u8 kernel ver num, value from 0-48, Return 0xFF means get kernel ver fail. +CNcomment:kernel版本号,有效值为0-48,返回0xFF表示获取kernel版本号失败CNend +* +* @par Dependency: +* @li hi_ver.h: This file describes version information APIs.CNcomment:文件用于描述系统相关接口.CNend +* @see None +*/ +hi_u8 hi_get_kernel_ver(hi_void); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/sdk_liteos/include/hi_watchdog.h b/sdk_liteos/include/hi_watchdog.h new file mode 100644 index 0000000000000000000000000000000000000000..9dc24bea68b9f3878d5e37688965c9d15a863a40 --- /dev/null +++ b/sdk_liteos/include/hi_watchdog.h @@ -0,0 +1,100 @@ +/** + * @file hi_watchdog.h + * + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @defgroup iot_watchdog Watchdog + * @ingroup drivers + */ +#ifndef __HI_WATCHDOG_H__ +#define __HI_WATCHDOG_H__ + +#include + +#define HI_WDG_MIN_TIMEOUT 6500 + +/** +* @ingroup iot_watchdog +* @brief Enables the watchdog.CNcomment:使能看门狗。CNend +* +* @par 描述: +* Enables the watchdog.CNcomment:使能看门狗。CNend +* +* @attention None +* @param None +* +* @retval None +* @par 依赖: +* @li hi_watchdog.h:describes the watchdog APIs.CNcomment:文件用于描述看门狗相关接口。CNend +* @see None +*/ +hi_void hi_watchdog_enable(hi_void); + +/** +* @ingroup iot_watchdog +* @brief Feeds the watchdog.CNcomment:喂狗。CNend +* +* @par 描述: Feeds the watchdog.CNcomment:喂狗。CNend +* +* @attention None +* @param None +* +* @retval None +* @par 依赖: +* @li hi_watchdog.h:describes the watchdog APIs.CNcomment:文件用于描述看门狗相关接口。CNend +* @see None +*/ +hi_void hi_watchdog_feed(hi_void); + +/** +* @ingroup iot_watchdog +* @brief Disables the watchdog.CNcomment:关闭看门狗。CNend +* +* @par 描述: +* @li Disable the clock enable control of the watchdog.CNcomment:禁止WatchDog时钟使能控制位。CNend +* @li Mask the watchdog reset function.CNcomment:屏蔽WatchDog复位功能。CNend +* +* @attention None +* @param None +* +* @retval None +* @par 依赖: +* @li hi_watchdog.h:describes the watchdog APIs.CNcomment:文件用于描述看门狗相关接口。CNend +* @see None +*/ +hi_void hi_watchdog_disable(hi_void); + +/** +* @ingroup iot_watchdog +* @brief Set watchod timeout(ms).CNcomment:设置看门狗超时时间,单位ms。CNend +* +* @par 描述: +* @li Set watchod timeout(ms).CNcomment:设置看门狗超时时间,单位ms。CNend +* +* @attention +* timeout should not smaller than 6500ms.CNcomment:看门狗超时时间不得小于6500ms。 +* system will restart count after set timeout.CNcomment:设置超时时间后,系统会重新开始计数。 +* @param timeout_ms [IN] type #hi_u32,timeout(ms). CNcomment:超时时间(单位:ms)。CNend +* +* @retval #HI_ERR_SUCCESS Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_watchdog.h:describes the watchdog APIs.CNcomment:文件用于描述看门狗相关接口。CNend +* @see None +*/ +hi_u32 hi_watchdog_set_timeout(hi_u32 timeout_ms); + +#endif diff --git a/sdk_liteos/include/hi_wifi_api.h b/sdk_liteos/include/hi_wifi_api.h new file mode 100644 index 0000000000000000000000000000000000000000..e8300e653a3a01bbe301541aadc9d0e87470a59c --- /dev/null +++ b/sdk_liteos/include/hi_wifi_api.h @@ -0,0 +1,2152 @@ +/** + * @file hi_wifi_api.h + * + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @defgroup hi_wifi_basic WiFi Basic Settings + * @ingroup hi_wifi + */ + +#ifndef __HI_WIFI_API_H__ +#define __HI_WIFI_API_H__ + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif + +/** + * mac transform string.CNcomment:地址转为字符串.CNend + */ +#ifndef MACSTR +#define MACSTR "%02x:%02x:%02x:%02x:%02x:%02x" +#endif + +#ifndef MAC2STR +#define mac2str(a) (a)[0], (a)[1], (a)[2], (a)[3], (a)[4], (a)[5] +#endif + +#ifndef bit +#define bit(x) (1U << (x)) +#endif + +/** + * @ingroup hi_wifi_basic + * + * TKIP of cipher mode.CNcomment:加密方式为TKIP.CNend + */ +#define WIFI_CIPHER_TKIP bit(3) + +/** + * @ingroup hi_wifi_basic + * + * CCMP of cipher mode.CNcomment:加密方式为CCMP.CNend + */ +#define WIFI_CIPHER_CCMP bit(4) + +/** + * @ingroup hi_wifi_basic + * + * Channel numbers of 2.4G frequency.CNcomment:2.4G频段的信道数量.CNend + */ +#define WIFI_24G_CHANNEL_NUMS 14 + +/** + * @ingroup hi_wifi_basic + * + * max interiface name length.CNcomment:网络接口名最大长度.CNend + */ +#define WIFI_IFNAME_MAX_SIZE 16 + +/** + * @ingroup hi_wifi_basic + * + * The minimum timeout of a single reconnection.CNcomment:最小单次重连超时时间.CNend + */ +#define WIFI_MIN_RECONNECT_TIMEOUT 2 + +/** + * @ingroup hi_wifi_basic + * + * The maximum timeout of a single reconnection, representing an infinite number of loop reconnections. + * CNcomment:最大单次重连超时时间,表示无限次循环重连.CNend + */ +#define WIFI_MAX_RECONNECT_TIMEOUT 65535 + +/** + * @ingroup hi_wifi_basic + * + * The minimum auto reconnect interval.CNcomment:最小自动重连间隔时间.CNend + */ +#define WIFI_MIN_RECONNECT_PERIOD 1 + +/** + * @ingroup hi_wifi_basic + * + * The maximum auto reconnect interval.CNcomment:最大自动重连间隔时间.CNend + */ +#define WIFI_MAX_RECONNECT_PERIOD 65535 + +/** + * @ingroup hi_wifi_basic + * + * The minmum times of auto reconnect.CNcomment:最小自动重连连接次数.CNend + */ +#define WIFI_MIN_RECONNECT_TIMES 1 + +/** + * @ingroup hi_wifi_basic + * + * The maximum times of auto reconnect.CNcomment:最大自动重连连接次数.CNend + */ +#define WIFI_MAX_RECONNECT_TIMES 65535 + +/** + * @ingroup hi_wifi_basic + * + * max scan number of ap.CNcomment:支持扫描ap的最多数目.CNend + */ +#define WIFI_SCAN_AP_LIMIT 32 + +/** + * @ingroup hi_wifi_basic + * + * length of status buff.CNcomment:获取连接状态字符串的长度.CNend + */ +#define WIFI_STATUS_BUF_LEN_LIMIT 512 + +/** + * @ingroup hi_wifi_basic + * + * Decimal only WPS pin code length.CNcomment:WPS中十进制pin码长度.CNend + */ +#define WIFI_WPS_PIN_LEN 8 + +/** + * @ingroup hi_wifi_basic + * + * default max num of station.CNcomment:默认支持的station最大个数.CNend + */ +#define WIFI_DEFAULT_MAX_NUM_STA 6 + +/** + * @ingroup hi_wifi_basic + * + * return success value.CNcomment:返回成功标识.CNend + */ +#define HISI_OK 0 + +/** + * @ingroup hi_wifi_basic + * + * return failed value.CNcomment:返回值错误标识.CNend + */ +#define HISI_FAIL (-1) + +/** + * @ingroup hi_wifi_basic + * + * Max length of SSID.CNcomment:SSID最大长度定义.CNend + */ +#define HI_WIFI_MAX_SSID_LEN 32 + +/** + * @ingroup hi_wifi_basic + * + * Length of MAC address.CNcomment:MAC地址长度定义.CNend + */ +#define HI_WIFI_MAC_LEN 6 + +/** + * @ingroup hi_wifi_basic + * + * String length of bssid, eg. 00:00:00:00:00:00.CNcomment:bssid字符串长度定义(00:00:00:00:00:00).CNend + */ +#define HI_WIFI_TXT_ADDR_LEN 17 + +/** + * @ingroup hi_wifi_basic + * + * Length of Key.CNcomment:KEY 密码长度定义.CNend + */ +#define HI_WIFI_AP_KEY_LEN 64 + +/** + * @ingroup hi_wifi_basic + * + * Maximum length of Key.CNcomment:KEY 最大密码长度.CNend + */ +#define HI_WIFI_MAX_KEY_LEN 64 + +/** + * @ingroup hi_wifi_basic + * + * Return value of invalid channel.CNcomment:无效信道返回值.CNend + */ +#define HI_WIFI_INVALID_CHANNEL 0xFF + +/** + * @ingroup hi_wifi_basic + * + * Index of Vendor IE.CNcomment:Vendor IE 最大索引.CNend + */ +#define HI_WIFI_VENDOR_IE_MAX_IDX 1 + +/** + * @ingroup hi_wifi_basic + * + * Max length of Vendor IE.CNcomment:Vendor IE 最大长度.CNend + */ +#define HI_WIFI_VENDOR_IE_MAX_LEN 255 + +/** + * @ingroup hi_wifi_basic + * + * Minimum length of custom's frame.CNcomment:用户定制报文最小长度值.CNend + */ +#define HI_WIFI_CUSTOM_PKT_MIN_LEN 24 + +/** + * @ingroup hi_wifi_basic + * + * Max length of custom's frame.CNcomment:用户定制报文最大长度值.CNend + */ +#define HI_WIFI_CUSTOM_PKT_MAX_LEN 1400 + +/** + * @ingroup hi_wifi_basic + * + * Length of wpa psk.CNcomment:wpa psk的长度.CNend + */ +#define HI_WIFI_STA_PSK_LEN 32 + +/** + * @ingroup hi_wifi_basic + * + * Max num of retry.CNcomment:软件重传的最大次数.CNend + */ +#define HI_WIFI_RETRY_MAX_NUM 15 + +/** + * @ingroup hi_wifi_basic + * + * Max time of retry.CNcomment:软件重传的最大时间.CNend + */ +#define HI_WIFI_RETRY_MAX_TIME 200 + +/** + * @ingroup hi_wifi_basic + * + * Minimum priority of callback task.CNcomment:事件回调task的最小优先级.CNend + */ +#define HI_WIFI_CB_MIN_PRIO 10 + +/** + * @ingroup hi_wifi_basic + * + * Max priority of callback task.CNcomment:事件回调task的最大优先级.CNend + */ +#define HI_WIFI_CB_MAX_PRIO 50 + +/** + * @ingroup hi_wifi_basic + * + * Minimum stack size of callback task.CNcomment:最小的回调线程栈大小.CNend + */ +#define HI_WIFI_CB_MIN_STACK 1024 + +/** + * @ingroup hi_wifi_basic + * + * max usr ie length.CNcomment:用户IE字段最大长度CNend + */ +#define HI_WIFI_USR_IE_MAX_SIZE 128 + +/** + * @ingroup hi_wifi_basic + * + * Reporting data type of monitor mode.CNcomment:混杂模式上报的数据类型.CNend + */ +typedef enum { + HI_WIFI_MONITOR_OFF, /**< close monitor mode. CNcomment: 关闭混杂模式.CNend */ + HI_WIFI_MONITOR_MCAST_DATA, /**< report multi-cast data frame. CNcomment: 上报组播(广播)数据包.CNend */ + HI_WIFI_MONITOR_UCAST_DATA, /**< report single-cast data frame. CNcomment: 上报单播数据包.CNend */ + HI_WIFI_MONITOR_MCAST_MANAGEMENT, /**< report multi-cast mgmt frame. CNcomment: 上报组播(广播)管理包.CNend */ + HI_WIFI_MONITOR_UCAST_MANAGEMENT, /**< report sigle-cast mgmt frame. CNcomment: 上报单播管理包.CNend */ + HI_WIFI_MONITOR_BUTT +} hi_wifi_monitor_mode; + +/** + * @ingroup hi_wifi_basic + * + * Definition of protocol frame type.CNcomment:协议报文类型定义.CNend + */ +typedef enum { + HI_WIFI_PKT_TYPE_BEACON, /**< Beacon packet. CNcomment: Beacon包.CNend */ + HI_WIFI_PKT_TYPE_PROBE_REQ, /**< Probe Request packet. CNcomment: Probe Request包.CNend */ + HI_WIFI_PKT_TYPE_PROBE_RESP, /**< Probe Response packet. CNcomment: Probe Response包.CNend */ + HI_WIFI_PKT_TYPE_ASSOC_REQ, /**< Assoc Request packet. CNcomment: Assoc Request包.CNend */ + HI_WIFI_PKT_TYPE_ASSOC_RESP, /**< Assoc Response packet. CNcomment: Assoc Response包.CNend */ + HI_WIFI_PKT_TYPE_BUTT +}hi_wifi_pkt_type; + +/** + * @ingroup hi_wifi_basic + * + * Interface type of wifi.CNcomment:wifi 接口类型.CNend + */ +typedef enum { + HI_WIFI_IFTYPE_UNSPECIFIED, + HI_WIFI_IFTYPE_ADHOC, + HI_WIFI_IFTYPE_STATION = 2, /**< Station. CNcomment: STA类型.CNend */ + HI_WIFI_IFTYPE_AP = 3, /**< SoftAp. CNcomment: SoftAp类型.CNend */ + HI_WIFI_IFTYPE_AP_VLAN, + HI_WIFI_IFTYPE_WDS, + HI_WIFI_IFTYPE_MONITOR, + HI_WIFI_IFTYPE_MESH_POINT = 7, /**< Mesh. CNcomment: Mesh类型.CNend */ + HI_WIFI_IFTYPE_P2P_CLIENT, + HI_WIFI_IFTYPE_P2P_GO, + HI_WIFI_IFTYPE_P2P_DEVICE, + + HI_WIFI_IFTYPES_BUTT +} hi_wifi_iftype; + +/** + * @ingroup hi_wifi_basic + * + * Definition of bandwith type.CNcomment:接口带宽定义.CNend + */ +typedef enum { + HI_WIFI_BW_HIEX_5M, /**< 5M bandwidth. CNcomment: 窄带5M带宽.CNend */ + HI_WIFI_BW_HIEX_10M, /**< 10M bandwidth. CNcomment: 窄带10M带宽.CNend */ + HI_WIFI_BW_LEGACY_20M, /**< 20M bandwidth. CNcomment: 20M带宽.CNend */ + HI_WIFI_BW_BUTT +} hi_wifi_bw; + +/** + * @ingroup hi_wifi_basic + * + * The protocol mode of softap and station interfaces.CNcomment:softap和station接口的protocol模式.CNend + */ +typedef enum { + HI_WIFI_PHY_MODE_11BGN, /**< 802.11BGN mode. CNcomment: 802.11BGN 模式.CNend */ + HI_WIFI_PHY_MODE_11BG, /**< 802.11BG mode. CNcomment: 802.11BG 模式.CNend */ + HI_WIFI_PHY_MODE_11B, /**< 802.11B mode. CNcomment: 802.11B 模式.CNend */ + HI_WIFI_PHY_MODE_BUTT +} hi_wifi_protocol_mode; + +/** + * @ingroup hi_wifi_basic + * + * Authentification type enum.CNcomment:认证类型(连接网络不支持HI_WIFI_SECURITY_WPAPSK).CNend + */ +typedef enum { + HI_WIFI_SECURITY_OPEN, /**< OPEN. CNcomment: 认证类型:开放.CNend */ + HI_WIFI_SECURITY_WEP, /**< WEP. CNcomment: 认证类型:WEP.CNend */ + HI_WIFI_SECURITY_WPA2PSK, /**< WPA-PSK. CNcomment: 认证类型:WPA2-PSK.CNend */ + HI_WIFI_SECURITY_WPAPSK_WPA2PSK_MIX, /**< WPA/WPA2-PSK MIX. CNcomment: 认证类型:WPA-PSK/WPA2-PSK混合.CNend */ + HI_WIFI_SECURITY_WPAPSK, /**< WPA-PSK. CNcomment: 认证类型:WPA-PSK.CNend */ + HI_WIFI_SECURITY_WPA, /**< WPA. CNcomment: 认证类型:WPA.CNend */ + HI_WIFI_SECURITY_WPA2, /**< WPA2. CNcomment: 认证类型:WPA2.CNend */ + HI_WIFI_SECURITY_SAE, /**< SAE. CNcomment: 认证类型:SAE.CNend */ + HI_WIFI_SECURITY_WPA3_WPA2_PSK_MIX, /**< WPA3/WPA2-PSK MIX. CNcomment: 认证类型:WPA3/WPA2-PSK混合.CNend */ + HI_WIFI_SECURITY_UNKNOWN /**< UNKNOWN. CNcomment: 其他认证类型:UNKNOWN.CNend */ +} hi_wifi_auth_mode; + +/** + * @ingroup hi_wifi_basic + * + * Encryption type enum.CNcoment:加密类型.CNend + * + */ +typedef enum { + HI_WIFI_PARIWISE_UNKNOWN, /**< UNKNOWN. CNcomment: 加密类型:UNKNOWN.CNend */ + HI_WIFI_PAIRWISE_AES, /**< AES. CNcomment: 加密类型:AES.CNend */ + HI_WIFI_PAIRWISE_TKIP, /**< TKIP. CNcomment: 加密类型:TKIP.CNend */ + HI_WIFI_PAIRWISE_TKIP_AES_MIX /**< TKIP/AES MIX. CNcomment: 加密类型:TKIP AES混合.CNend */ +} hi_wifi_pairwise; + +/** + * @ingroup hi_wifi_basic + * + * PMF type enum.CNcomment:PMF管理帧保护模式类型.CNend + */ +typedef enum { + HI_WIFI_MGMT_FRAME_PROTECTION_CLOSE, /**< Disable. CNcomment: 管理帧保护模式:关闭.CNend */ + HI_WIFI_MGMT_FRAME_PROTECTION_OPTIONAL, /**< Optional. CNcomment: 管理帧保护模式:可选.CNend */ + HI_WIFI_MGMT_FRAME_PROTECTION_REQUIRED /**< Required. CNcomment: 管理帧保护模式:必须.CNend */ +} hi_wifi_pmf_options; + +/** + * @ingroup hi_wifi_basic + * + * Type of connect's status.CNcomment:连接状态.CNend + */ +typedef enum { + HI_WIFI_DISCONNECTED, /**< Disconnected. CNcomment: 连接状态:未连接.CNend */ + HI_WIFI_CONNECTED, /**< Connected. CNcomment: 连接状态:已连接.CNend */ +} hi_wifi_conn_status; + +/** + * @ingroup hi_wifi_basic + * + * Frame type that usr ies will insert into.CNcomment: 待插入ie字段的帧类型.CNend + */ +typedef enum { + HI_WIFI_FRAME_TYPE_BEACON = bit(0), + HI_WIFI_FRAME_TYPE_PROBE_REQ = bit(1), + HI_WIFI_FRAME_TYPE_PROBE_RSP = bit(2), + HI_WIFI_FRAME_TYPE_BUTT +} hi_wifi_frame_type; + +/** + * @ingroup hi_wifi_basic + * + * Usr ie type to be inserted.CNcomment: 待插入ie字段类型.CNend + */ +typedef enum { + HI_WIFI_USR_IE_TYPE_DEFAULT = 0, + HI_WIFI_USR_IE_BUTT +} hi_wifi_usr_ie_type; + +/** + * @ingroup hi_wifi_basic + * + * Event type of WiFi event.CNcomment:锚点功能上报的事件类型.CNend + */ +typedef enum { + HI_WIFI_ANCHOR_UNKNOWN, /**< UNKNWON. CNcomment: UNKNOWN.CNend */ + HI_WIFI_ANCHOR_SCAN_DONE, /**< Scan finish. CNcomment: 锚点扫描完成.CNend */ + HI_WIFI_ANCHOR_SCAN_NO_BSS, /**< Scan no bss. CNcomment: 锚点未扫描到对应bss.CNend */ + HI_WIFI_ANCHOR_CONNECTED, /**< Connected. CNcomment: 锚点已连接.CNend */ + HI_WIFI_ANCHOR_DISCONNECTED, /**< Disconnected. CNcomment: 锚点断开连接.CNend */ + HI_WIFI_ANCHOR_REPORT_BCN, /**< REPORT_BCN. CNcomment: 锚点上报BEACON包.CNend */ + HI_WIFI_ANCHOR_BUTT +} hi_anchor_event_type; + +/** + * @ingroup hi_wifi_basic + * + * Event type of WiFi event.CNcomment:WiFi的事件类型.CNend + */ +typedef enum { + HI_WIFI_EVT_UNKNOWN, /**< UNKNWON. CNcomment: UNKNOWN.CNend */ + HI_WIFI_EVT_SCAN_DONE, /**< Scan finish. CNcomment: STA扫描完成.CNend */ + HI_WIFI_EVT_CONNECTED, /**< Connected. CNcomment: 已连接.CNend */ + HI_WIFI_EVT_DISCONNECTED, /**< Disconnected. CNcomment: 断开连接.CNend */ + HI_WIFI_EVT_WPS_TIMEOUT, /**< WPS timeout. CNcomment: WPS事件超时.CNend */ + HI_WIFI_EVT_MESH_CONNECTED, /**< MESH connected. CNcomment: MESH已连接.CNend */ + HI_WIFI_EVT_MESH_DISCONNECTED, /**< MESH disconnected. CNcomment: MESH断开连接.CNend */ + HI_WIFI_EVT_AP_START, /**< AP start. CNcomment: AP开启.CNend */ + HI_WIFI_EVT_STA_CONNECTED, /**< STA connected with ap. CNcomment: AP和STA已连接.CNend */ + HI_WIFI_EVT_STA_DISCONNECTED, /**< STA disconnected from ap. CNcomment: AP和STA断开连接.CNend */ + HI_WIFI_EVT_STA_FCON_NO_NETWORK, /**< STA connect, but can't find network. CNcomment: STA连接时扫描不到网络.CNend */ + HI_WIFI_EVT_MESH_CANNOT_FOUND, /**< MESH can't find network. CNcomment: MESH关联扫不到对端.CNend */ + HI_WIFI_EVT_MESH_SCAN_DONE, /**< MESH AP scan finish. CNcomment: MESH AP扫描完成.CNend */ + HI_WIFI_EVT_MESH_STA_SCAN_DONE, /**< MESH STA scan finish. CNcomment: MESH STA扫描完成.CNend */ + HI_WIFI_EVT_AP_SCAN_DONE, /**< AP scan finish. CNcomment: AP扫描完成.CNend */ + HI_WIFI_EVT_BUTT +} hi_wifi_event_type; + +/** + * @ingroup hi_wifi_basic + * + * Scan type enum.CNcomment:扫描类型.CNend + */ +typedef enum { + HI_WIFI_BASIC_SCAN, /**< Common and all channel scan. CNcomment: 普通扫描.CNend */ + HI_WIFI_CHANNEL_SCAN, /**< Specified channel scan. CNcomment: 指定信道扫描.CNend */ + HI_WIFI_SSID_SCAN, /**< Specified SSID scan. CNcomment: 指定SSID扫描.CNend */ + HI_WIFI_SSID_PREFIX_SCAN, /**< Prefix SSID scan. CNcomment: SSID前缀扫描.CNend */ + HI_WIFI_BSSID_SCAN, /**< Specified BSSID scan. CNcomment: 指定BSSID扫描.CNend */ +} hi_wifi_scan_type; + +/** + * @ingroup hi_wifi_basic + * + * WPA PSK usage type.CNcomment: WPA PSK使用策略.CNend + */ +typedef enum { + HI_WIFI_WPA_PSK_NOT_USE, /**< Not use. CNcomment: 不使用.CNend */ + HI_WIFI_WPA_PSK_USE_INNER, /**< Inner PSK. CNcomment: 使用内部PSK.CNend */ + HI_WIFI_WPA_PSK_USE_OUTER, /**< Outer PSK. CNcomment: 使用外部PSK.CNend */ +} hi_wifi_wpa_psk_usage_type; + +/** + * @ingroup hi_wifi_basic + * + * XLDO voltage.CNcomment: XLDO控制电压.CNend + */ +typedef enum { + HI_WIFI_XLDO_VOLTAGE_0 = 0x00, /**< 1.5V. CNcomment: 1.5V.CNend */ + HI_WIFI_XLDO_VOLTAGE_1 = 0x11, /**< 1.8V. CNcomment: 1.8V.CNend */ + HI_WIFI_XLDO_VOLTAGE_2 = 0x22, /**< 2.1V. CNcomment: 2.1V.CNend */ + HI_WIFI_XLDO_VOLTAGE_3 = 0x33, /**< 2.4V. CNcomment: 2.4V.CNend */ +} hi_wifi_xldo_voltage; + +/** + * @ingroup hi_wifi_basic + * + * parameters of scan.CNcomment:station和mesh接口scan参数.CNend + */ +typedef struct { + char ssid[HI_WIFI_MAX_SSID_LEN + 1]; /**< SSID. CNcomment: SSID 只支持ASCII字符.CNend */ + unsigned char bssid[HI_WIFI_MAC_LEN]; /**< BSSID. CNcomment: BSSID.CNend */ + unsigned char ssid_len; /**< SSID length. CNcomment: SSID长度.CNend */ + unsigned char channel; /**< Channel number. CNcomment: 信道号,范围1-14,不同区域有差异.CNend */ + hi_wifi_scan_type scan_type; /**< Scan type. CNcomment: 扫描类型.CNend */ +} hi_wifi_scan_params; + +/** + * @ingroup hi_wifi_basic + * + * Struct of scan result.CNcomment:扫描结果结构体.CNend + */ +typedef struct { + char ssid[HI_WIFI_MAX_SSID_LEN + 1]; /**< SSID. CNcomment: SSID 只支持ASCII字符.CNend */ + unsigned char bssid[HI_WIFI_MAC_LEN]; /**< BSSID. CNcomment: BSSID.CNend */ + unsigned int channel; /**< Channel number. CNcomment: 信道号,范围1-14,不同区域有差异.CNend */ + hi_wifi_auth_mode auth; /**< Authentication type. CNcomment: 认证类型.CNend */ + int rssi; /**< Signal Strength. CNcomment: 信号强度.CNend */ + unsigned char wps_flag : 1; /**< WPS flag. CNcomment: WPS标识.CNend */ + unsigned char wps_session : 1; /**< WPS session:PBC-0/PIN-1. CNcomment: WPS会话类型,PBC-0/PIN-1.CNend */ + unsigned char wmm : 1; /**< WMM flag. CNcomment: WMM标识.CNend */ + unsigned char resv : 1; /**< Reserved. CNcomment: 预留.CNend */ + unsigned char hisi_mesh_flag : 1; /**< MESH flag. CNcomment: MESH标识.CNend */ +} hi_wifi_ap_info; + +/** + * @ingroup hi_wifi_basic + * + * Struct of connect parameters.CNcomment:station连接结构体.CNend + */ +typedef struct { + char ssid[HI_WIFI_MAX_SSID_LEN + 1]; /**< SSID. CNcomment: SSID 只支持ASCII字符.CNend */ + hi_wifi_auth_mode auth; /**< Authentication mode. CNcomment: 认证类型.CNend */ + char key[HI_WIFI_MAX_KEY_LEN + 1]; /**< Secret key. CNcomment: 秘钥.CNend */ + unsigned char bssid[HI_WIFI_MAC_LEN]; /**< BSSID. CNcomment: BSSID.CNend */ + hi_wifi_pairwise pairwise; /**< Encryption type. CNcomment: 加密方式,不需指定时置0.CNend */ +} hi_wifi_assoc_request; + +/** + * @ingroup hi_wifi_basic + * + * Struct of fast connect parameters.CNcomment:station快速连接结构体.CNend + */ +typedef struct { + hi_wifi_assoc_request req; /**< Association request. CNcomment: 关联请求.CNend */ + unsigned char channel; /**< Channel number. CNcomment: 信道号,范围1-14,不同区域有差异.CNend */ + unsigned char psk[HI_WIFI_STA_PSK_LEN]; /**< PSK. CNcomment: PSL.CNend */ + hi_wifi_wpa_psk_usage_type psk_flag; /**< PSK TYPE. CNcomment: psk的标志,不需指定时置0.CNend */ +} hi_wifi_fast_assoc_request; + +/** + * @ingroup hi_wifi_basic + * + * Status of sta's connection.CNcomment:获取station连接状态.CNend + */ +typedef struct { + char ssid[HI_WIFI_MAX_SSID_LEN + 1]; /**< SSID. CNcomment: SSID 只支持ASCII字符.CNend */ + unsigned char bssid[HI_WIFI_MAC_LEN]; /**< BSSID. CNcomment: BSSID.CNend */ + unsigned int channel; /**< Channel number. CNcomment: 信道号,范围1-14,不同区域有差异.CNend */ + hi_wifi_conn_status status; /**< Connect status. CNcomment: 连接状态.CNend */ +} hi_wifi_status; + +/** + * @ingroup hi_wifi_basic + * + * Event type of wifi scan done.CNcomment:扫描完成事件.CNend + */ +typedef struct { + unsigned short bss_num; /**< numbers of scan result. CNcomment: 扫描到的ap数目.CNend */ +} event_wifi_scan_done; + +/** + * @ingroup hi_wifi_basic + * + * Event type of wifi connected CNcomment:wifi的connect事件信息.CNend + */ +typedef struct { + char ssid[HI_WIFI_MAX_SSID_LEN + 1]; /**< SSID. CNcomment: SSID 只支持ASCII字符.CNend */ + unsigned char bssid[HI_WIFI_MAC_LEN]; /**< BSSID. CNcomment: BSSID.CNend */ + unsigned char ssid_len; /**< SSID length. CNcomment: SSID长度.CNend */ + char ifname[WIFI_IFNAME_MAX_SIZE + 1]; /**< Iftype name. CNcomment: 接口名称.CNend */ +} event_wifi_connected; + +/** + * @ingroup hi_wifi_basic + * + * Event type of wifi disconnected.CNcomment:wifi的断开事件信息.CNend + */ +typedef struct { + unsigned char bssid[HI_WIFI_MAC_LEN]; /**< BSSID. CNcomment: BSSID.CNend */ + unsigned short reason_code; /**< reason code. CNcomment: 断开原因.CNend */ + char ifname[WIFI_IFNAME_MAX_SIZE + 1]; /**< Iftype name. CNcomment: 接口名称.CNend */ +} event_wifi_disconnected; + +/** + * @ingroup hi_wifi_basic + * + * Event type of ap connected sta.CNcomment:ap连接sta事件信息.CNend + */ +typedef struct { + char addr[HI_WIFI_MAC_LEN]; /**< user's mac address of SoftAp. CNcomment: 连接AP的sta地址.CNend */ +} event_ap_sta_connected; + +/** + * @ingroup hi_wifi_basic + * + * Event type of ap disconnected sta.CNcomment:ap断开sta事件信息.CNend + */ +typedef struct { + unsigned char addr[HI_WIFI_MAC_LEN]; /**< User's mac address of SoftAp. CNcomment: AP断开STA的MAC地址.CNend */ + unsigned short reason_code; /**< Reason code. CNcomment: AP断开连接的原因值.CNend */ +} event_ap_sta_disconnected; + +/** + * @ingroup hi_wifi_basic + * + * Event type of mesh connected.CNcomment:mesh的connect事件信息.CNend + */ +typedef struct { + unsigned char addr[HI_WIFI_MAC_LEN]; /**< User's mac address of MESH. CNcomment: MESH连接的peer MAC地址.CNend */ +} event_mesh_connected; + +/** + * @ingroup hi_wifi_basic + * + * Event type of mesh disconnected.CNcomment:mesh的disconnect事件信息.CNend + */ +typedef struct { + unsigned char addr[HI_WIFI_MAC_LEN]; /**< User's mac address of MESH. CNcomment: 断开连接的peer MAC地址.CNend */ + unsigned short reason_code; /**< Reason code. CNcomment: MESH断开连接的原因.CNend */ +} event_mesh_disconnected; + +/** + * @ingroup hi_wifi_basic + * + * Event type wifi information.CNcomment:wifi的事件信息体.CNend + */ +typedef union { + event_wifi_scan_done wifi_scan_done; /**< Scan finish event. CNcomment: WIFI扫描完成事件信息.CNend */ + event_wifi_connected wifi_connected; /**< STA's connected event. CNcomment: STA的连接事件信息.CNend */ + event_wifi_disconnected wifi_disconnected; /**< STA's dsiconnected event. CNcomment: STA的断连事件信息.CNend */ + event_ap_sta_connected ap_sta_connected; /**< AP's connected event . CNcomment: AP的连接事件信息.CNend */ + event_ap_sta_disconnected ap_sta_disconnected; /**< AP's disconnected event. CNcomment: AP的断连事件信息.CNend */ + event_mesh_connected mesh_connected; /**< MESH's connected event. CNcomment: MESH连接事件信息.CNend */ + event_mesh_disconnected mesh_disconnected; /**< MESH's disconnected event. CNcomment: MESH断连事件信息.CNend */ +} hi_wifi_event_info; + +/** + * @ingroup hi_wifi_basic + * + * Struct of WiFi event.CNcomment:WiFi事件结构体.CNend + * + */ +typedef struct { + hi_wifi_event_type event; /**< Event type. CNcomment: 事件类型.CNend */ + hi_wifi_event_info info; /**< Event information. CNcomment: 事件信息.CNend */ +} hi_wifi_event; + +/** + * @ingroup hi_wifi_basic + * + * Struct of softap's basic config.CNcomment:softap基本配置.CNend + * + */ +typedef struct { + char ssid[HI_WIFI_MAX_SSID_LEN + 1]; /**< SSID. CNcomment: SSID 只支持ASCII字符.CNend */ + char key[HI_WIFI_AP_KEY_LEN + 1]; /**< Secret key. CNcomment: 秘钥.CNend */ + unsigned char channel_num; /**< Channel number. CNcomment: 信道号,范围1-14,不同区域有差异.CNend */ + int ssid_hidden; /**< Hidden ssid. CNcomment: 是否隐藏SSID.CNend */ + hi_wifi_auth_mode authmode; /**< Authentication mode. CNcomment: 认证方式.CNend */ + hi_wifi_pairwise pairwise; /**< Encryption type. CNcomment: 加密方式,不需指定时置0.CNend */ +} hi_wifi_softap_config; + +/** + * @ingroup hi_wifi_basic + * + * mac address of softap's user.CNcomment:与softap相连的station mac地址.CNend + * + */ +typedef struct { + unsigned char mac[HI_WIFI_MAC_LEN]; /**< MAC address.CNcomment:与softap相连的station mac地址.CNend */ +} hi_wifi_ap_sta_info; + +/** + * @ingroup hi_wifi_basic + * + * Struct of frame filter config in monitor mode.CNcomment:混杂模式报文接收过滤设置.CNend + */ +typedef struct { + char mdata_en : 1; /**< get multi-cast data frame flag. CNcomment: 使能接收组播(广播)数据包.CNend */ + char udata_en : 1; /**< get single-cast data frame flag. CNcomment: 使能接收单播数据包.CNend */ + char mmngt_en : 1; /**< get multi-cast mgmt frame flag. CNcomment: 使能接收组播(广播)管理包.CNend */ + char umngt_en : 1; /**< get single-cast mgmt frame flag. CNcomment: 使能接收单播管理包.CNend */ + char custom_en : 1; /**< get beacon/probe response flag. CNcomment: 使能STA接收beacon/probe response包.CNend */ + char resvd : 3; /**< reserved bits. CNcomment: 保留字段.CNend */ +} hi_wifi_ptype_filter; + +/** + * @ingroup hi_wifi_basic + * + * Struct of WPA psk calc config.CNcomment:计算WPA psk需要设置的参数.CNend + */ +typedef struct { + unsigned char ssid[HI_WIFI_MAX_SSID_LEN + 1]; /**< SSID. CNcomment: SSID 只支持ASCII字符.CNend */ + char key[HI_WIFI_AP_KEY_LEN + 1]; /**< Secret key. CNcomment: 秘钥.CNend */ +} hi_wifi_sta_psk_config; + +/** + * @ingroup hi_wifi_basic + * + * callback function definition of monitor mode.CNcommment:混杂模式收包回调接口定义.CNend + */ +typedef int (*hi_wifi_promis_cb)(void* recv_buf, int frame_len, signed char rssi); + +/** + * @ingroup hi_wifi_basic + * + * callback function definition of wifi event.CNcommment:wifi事件回调接口定义.CNend + */ +typedef void (*hi_wifi_event_cb)(const hi_wifi_event *event); + +/** + * @ingroup hi_wifi_basic + * + * callback function definition of anchor.CNcommment:锚点功能回调接口定义.CNend + */ +typedef void (*hi_wifi_anchor_cb)(hi_anchor_event_type event, const unsigned char *info, unsigned int len); + +/** +* @ingroup hi_wifi_basic +* @brief Wifi initialize.CNcomment:wifi初始化.CNend +* +* @par Description: + Wifi driver initialize.CNcomment:wifi驱动初始化,不创建wifi设备.CNend +* +* @attention NULL +* @param vap_res_num [IN] Type #const unsigned char, vap num[rang: 1-3].CNcomment:vap资源个数,取值[1-3].CNend +* @param user_res_num [IN] Type #const unsigned char, user resource num[1-7]. +* CNcomment:用户资源个数,多vap时共享,取值[1-7].CNend +* +* @retval #HISI_OK Excute successfully +* @retval #Other Error code +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +int hi_wifi_init(const unsigned char vap_res_num, const unsigned char user_res_num); + +/** +* @ingroup hi_wifi_basic +* @brief Wifi de-initialize.CNcomment:wifi去初始化.CNend +* +* @par Description: +* Wifi driver de-initialize.CNcomment:wifi驱动去初始化.CNend +* +* @attention NULL +* @param NULL +* +* @retval #HISI_OK Excute successfully +* @retval #Other Error code +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +int hi_wifi_deinit(void); + +/** +* @ingroup hi_wifi_basic +* @brief Get wifi initialize status.CNcomment:获取wifi初始化状态.CNend +* +* @par Description: + Get wifi initialize status.CNcomment:获取wifi初始化状态.CNend +* +* @attention NULL +* @param NULL +* +* @retval #1 Wifi is initialized.CNcoment:Wifi已经初始化.CNend +* @retval #0 Wifi is not initialized.CNcoment:Wifi没有初始化.CNend +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +unsigned char hi_wifi_get_init_status(void); + +/** +* @ingroup hi_wifi_basic +* @brief Set protocol mode of sta.CNcomment:设置station接口的protocol模式.CNend +* +* @par Description: +* Set protocol mode of sta, set before calling hi_wifi_sta_start().\n +* CNcomment:配置station接口的protocol模式, 在sta start之前调用.CNend +* +* @attention Default mode 802.11BGN CNcomment:默认模式 802.11BGN.CNend +* @param mode [IN] Type #hi_wifi_protocol_mode, protocol mode. +* +* @retval #HISI_OK Execute successfully. +* @retval #HISI_FAIL Execute failed. +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +int hi_wifi_sta_set_protocol_mode(hi_wifi_protocol_mode mode); + +/** +* @ingroup hi_wifi_basic +* @brief Get protocol mode of.CNcomment:获取station接口的protocol模式.CNend +* +* @par Description: +* Get protocol mode of station.CNcomment:获取station接口的protocol模式.CNend +* +* @attention NULL +* @param NULL +* +* @retval #hi_wifi_protocol_mode protocol mode. +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +hi_wifi_protocol_mode hi_wifi_sta_get_protocol_mode(void); + +/** +* @ingroup hi_wifi_basic +* @brief Config pmf settings of sta.CNcomment:配置station的pmf.CNend +* +* @par Description: +* Config pmf settings of sta, set before sta start.CNcomment:配置station的pmf, 在sta start之前调用.CNend +* +* @attention Default pmf enum value 1. CNcomment:默认pmf枚举值1.CNend +* @param pmf [IN] Type #hi_wifi_pmf_options, pmf enum value.CNcoment:pmf枚举值.CNend +* +* @retval #HISI_OK Execute successfully. +* @retval #HISI_FAIL Execute failed. +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +int hi_wifi_set_pmf(hi_wifi_pmf_options pmf); + +/** +* @ingroup hi_wifi_basic +* @brief Get pmf settings of sta.CNcomment:获取station的pmf设置.CNend +* +* @par Description: +* Get pmf settings of sta.CNcomment:获取station的pmf设置.CNend +* +* @attention NULL +* @param NULL +* +* @retval #hi_wifi_pmf_options pmf enum value. +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +hi_wifi_pmf_options hi_wifi_get_pmf(void); + +/** +* @ingroup hi_wifi_basic +* @brief Start wifi station.CNcomment:开启STA.CNend +* +* @par Description: +* Start wifi station.CNcomment:开启STA.CNend +* +* @attention 1. Multiple interfaces of the same type are not supported.CNcomment:1. 不支持使用多个同类型接口.CNend\n +* 2. Dual interface coexistence support: STA + AP or STA + MESH. +* CNcomment:2. 双接口共存支持:STA + AP or STA + MESH.CNend\n +* 3. Start timeout 5s.CNcomment:3. 启动超时时间5s.CNend\n +* 4. The memories of and should be requested by the caller, +* the input value of len must be the same as the length of ifname(the recommended length is 17Bytes).\n +* CNcomment:4. 由调用者申请内存,用户写入len的值必须与ifname长度一致(建议长度为17Bytes).CNend \n +* 5. This is a blocking function.CNcomment:5.此函数为阻塞函数.CNend +* @param ifname [IN/OUT] Type #char *, device name.CNcomment:接口名.CNend +* @param len [IN/OUT] Type #int *, length of device name.CNcomment:接口名长度.CNend +* +* @retval #HISI_OK Execute successfully. +* @retval #HISI_FAIL Execute failed. +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +int hi_wifi_sta_start(char *ifname, int *len); + +/** +* @ingroup hi_wifi_basic +* @brief Close wifi station.CNcomment:关闭STA.CNend +* +* @par Description: +* Close wifi station.CNcomment:关闭STA.CNend +* +* @attention 1. This is a blocking function.CNcomment:1.此函数为阻塞函数.CNend +* @param NULL +* +* @retval #HISI_OK Execute successfully. +* @retval #HISI_FAIL Execute failed. +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +int hi_wifi_sta_stop(void); + +/** +* @ingroup hi_wifi_basic +* @brief Start sta basic scanning in all channels.CNcomment:station进行全信道基础扫描.CNend +* +* @par Description: +* Start sta basic scanning in all channels.CNcomment:启动station全信道基础扫描.CNend +* +* @attention NULL +* @param NULL +* +* @retval #HISI_OK Execute successfully. +* @retval #HISI_FAIL Execute failed. +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +int hi_wifi_sta_scan(void); + +/** +* @ingroup hi_wifi_basic +* @brief Start station scanning with specified parameter.CNcomment:station执行带特定参数的扫描.CNend +* +* @par Description: +* Start station scanning with specified parameter.CNcomment:station执行带特定参数的扫描.CNend +* +* @attention 1. advance scan can scan with ssid only,channel only,bssid only,prefix_ssid only, +* and the combination parameters scanning does not support.\n +* CNcomment:1. 高级扫描分别单独支持 ssid扫描,信道扫描,bssid扫描,ssid前缀扫描, 不支持组合参数扫描方式.CNend\n +* 2. Scanning mode, subject to the type set by scan_type. +* CNcomment:2 .扫描方式,以scan_type传入的类型为准。CNend \n +* 3. SSID only supports ASCII characters. +* CNcomment:3. SSID 只支持ASCII字符.CNend +* @param sp [IN] Type #hi_wifi_scan_params * parameters of scan.CNcomment:扫描网络参数设置.CNend +* +* @retval #HISI_OK Execute successfully. +* @retval #HISI_FAIL Execute failed. +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +int hi_wifi_sta_advance_scan(hi_wifi_scan_params *sp); + +/** +* @ingroup hi_wifi_basic +* @brief sta start scan.CNcomment:station进行扫描.CNend +* +* @par Description: +* Get station scan result.CNcomment:获取station扫描结果.CNend +* @attention 1. The memories of and memories are requested by the caller. \n +* The size up to : sizeof(hi_wifi_ap_info ap_list) * 32. \n +* CNcomment:1. 由调用者申请内存, +* size最大为:sizeof(hi_wifi_ap_info ap_list) * 32.CNend \n +* 2. ap_num: parameters can be passed in to specify the number of scanned results.The maximum is 32. \n +* CNcomment:2. ap_num: 可以传入参数,指定获取扫描到的结果数量,最大为32。CNend \n +* 3. If the user callback function is used, ap num refers to bss_num in event_wifi_scan_done. \n +* CNcomment:3. 如果使用上报用户的回调函数,ap_num参考event_wifi_scan_done中的bss_num。CNend \n +* 4. ap_num should be same with number of hi_wifi_ap_info structures applied, +* Otherwise, it will cause memory overflow. \n +* CNcomment:4. ap_num和申请的hi_wifi_ap_info结构体数量一致,否则可能造成内存溢出。CNend \n +* 5. SSID only supports ASCII characters. \n +* CNcomment:5. SSID 只支持ASCII字符.CNend \n +* 6. The rssi in the scan results needs to be divided by 100 to get the actual rssi.\n +* CNcomment:6. 扫描结果中的rssi需要除以100才能获得实际的rssi.CNend +* @param ap_list [IN/OUT] Type #hi_wifi_ap_info * scan result.CNcomment:扫描的结果.CNend +* @param ap_num [IN/OUT] Type #unsigned int *, number of scan result.CNcomment:扫描到的网络数目.CNend +* +* @retval #HISI_OK Execute successfully. +* @retval #HISI_FAIL Execute failed. +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +int hi_wifi_sta_scan_results(hi_wifi_ap_info *ap_list, unsigned int *ap_num); + +/** +* @ingroup hi_wifi_basic +* @brief sta start connect.CNcomment:station进行连接网络.CNend +* +* @par Description: +* sta start connect.CNcomment:station进行连接网络.CNend +* +* @attention 1. and cannot be empty at the same time. CNcomment:1. 不能同时为空.CNend\n +* 2. When is set to OPEN, the parameter is not required. +* CNcomment:2. 设置为OPEN时,无需参数.CNend\n +* 3. This function is non-blocking.CNcomment:3. 此函数为非阻塞式.CNend\n +* 4. Pairwise can be set, default is 0.CNcomment:4. pairwise 可设置, 默认为0.CNend\n +* 5. If the station is already connected to a network, disconnect the existing connection and +* then connect to the new network.\n +* CNcomment:5. 若station已接入某个网络,则先断开已有连接,然后连接新网络.CNend\n +* 6. If the wrong SSID, BSSID or key is passed in, the HISI_OK will be returned, +* but sta cannot connect the ap. +* CNcomment:6. 如果传入错误的ssid,bssid或者不正确的密码,返回成功,但连接ap失败。CNend\n +* 7. SSID only supports ASCII characters. +* CNcomment:7. SSID 只支持ASCII字符.CNend \n +* 8. Only support auth mode as bellow: +* HI_WIFI_SECURITY_SAE, +* HI_WIFI_SECURITY_WPA3_WPA2_PSK_MIX, +* HI_WIFI_SECURITY_WPAPSK_WPA2PSK_MIX, +* HI_WIFI_SECURITY_WPA2PSK, +* HI_WIFI_SECURITY_WEP, +* HI_WIFI_SECURITY_OPEN +* CNcomment:8. 只支持以下认证模式: +* HI_WIFI_SECURITY_SAE, +* HI_WIFI_SECURITY_WPA3_WPA2_PSK_MIX, +* HI_WIFI_SECURITY_WPAPSK_WPA2PSK_MIX, +* HI_WIFI_SECURITY_WPA2PSK, +* HI_WIFI_SECURITY_WEP, +* HI_WIFI_SECURITY_OPEN \n +* 9. WEP supports 64 bit and 128 bit encryption. +* for 64 bit encryption, the encryption key is 10 hexadecimal characters or 5 ASCII characters; +* for 128 bit encryption, the encryption key is 26 hexadecimal characters or 13 ASCII characters。\n +* CNcomment:9. WEP支持64位和128位加密,对于64位加密,加密密钥为10个十六进制字符或5个ASCII字符; +* 对于128位加密,加密密钥为26个十六进制字符或13个ASCII字符。CNend\n +* 10. When the key of WEP is in the form of ASCII character, +* the key in the input struct needs to be added with double quotation marks; +* when the key of WEP is in the form of hexadecimal character, +* the key in the input struct does not need to add double quotation marks.\n +* CNcomment:10. WEP的秘钥为ASCIl字符形式时,入参结构体中的key需要添加双引号; +* WEP的秘钥为为十六进制字符时,入参结构体中的key不需要添加双引号。CNend\n +* 11. If the auth type is HI_WIFI_SECURITY_SAE, PMF is temporarily enabled as required.\n +* CNcomment:11. 当使用HI_WIFI_SECURITY_SAE进行认证时,默认临时开启PMF(强制)。CNend\n +* 12. If the auth type is HI_WIFI_SECURITY_WPA3_WPA2_PSK_MIX, PMF is temporarily enabled as optional.\n +* CNcomment:12. 当使用HI_WIFI_SECURITY_WPA3_WPA2_PSK_MIX进行认证时,默认临时开启PMF(可选)。CNend\n +* +* @param req [IN] Type #hi_wifi_assoc_request * connect parameters of network.CNcomment:连接网络参数设置.CNend +* @retval #HISI_OK Execute successfully. +* @retval #HISI_FAIL Execute failed. +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +int hi_wifi_sta_connect(hi_wifi_assoc_request *req); + +/** +* @ingroup hi_wifi_basic +* @brief Start fast connect.CNcomment:station进行快速连接网络.CNend +* +* @par Description: +* Start fast connect.CNcomment:station进行快速连接网络.CNend +* +* @attention 1. and cannot be empty at the same time. CNcomment:1.不能同时为空.CNend\n +* 2. When is set to OPEN, the parameter is not required. +* CNcomment:2.设置为OPEN时,无需参数.CNend\n +* 3. There are differences in the range of values, and China is 1-13. +* CNcomment:3.取值范围不同区域有差异,中国为1-13.CNend\n +* 4. This is a blocking function.CNcomment:4.此函数为阻塞函数.CNend\n +* 5. Pairwise can be set, set to zero by default.CNcomment:5. pairwise 可设置,默认置零.CNend\n +* 6. and are optional parameters, set to zero by default. \n +* CNcomment:6. 为可选参数,无需使用时填0.CNend\n +* 7. If the wrong SSID, BSSID or key is passed in, the HISI_FAIL will be returned, +* and sta cannot connect the ap. +* CNcomment:7. 如果传入错误的ssid,bssid或者不正确的密码,返回失败并且连接ap失败。CNend\n +* 8. SSID only supports ASCII characters. +* CNcomment:8. SSID 只支持ASCII字符.CNend \n +* 9. The PSK internal cache calculated in advance will be cleared after the function execution is completed. +* CNcomment:9. 提前计算的PSK内部缓存将在函数执行完成后清除.CNend \n +* 10. The PSK calculated in advance do not support WPA3-PSK. +* CNcomment:10. PSK提前计算不支持WPA3-PSK.CNend +* 11. If the auth type is HI_WIFI_SECURITY_SAE, PMF is temporarily enabled as required.\n +* CNcomment:11. 当使用HI_WIFI_SECURITY_SAE进行认证时,默认临时开启PMF(强制)。CNend\n +* 12. If the auth type is HI_WIFI_SECURITY_WPA3_WPA2_PSK_MIX, PMF is temporarily enabled as optional.\n +* CNcomment:12. 当使用HI_WIFI_SECURITY_WPA3_WPA2_PSK_MIX进行认证时,默认临时开启PMF(可选)。CNend\n +* +* @param fast_request [IN] Type #hi_wifi_fast_assoc_request *,fast connect parameters. CNcomment:快速连接网络参数.CNend + +* @retval #HISI_OK Execute successfully. +* @retval #HISI_FAIL Execute failed. +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +int hi_wifi_sta_fast_connect(hi_wifi_fast_assoc_request *fast_request); + +/** +* @ingroup hi_wifi_basic +* @brief Disconnect from network.CNcomment:station断开相连的网络.CNend +* +* @par Description: +* Disconnect from network.CNcomment:station断开相连的网络.CNend +* +* @attention NULL +* @param NULL +* +* @retval #HISI_OK Execute successfully. +* @retval #HISI_FAIL Execute failed. +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +int hi_wifi_sta_disconnect(void); + +/** +* @ingroup hi_wifi_basic +* @brief Set reconnect policy.CNcomment:station设置重新连接网络机制.CNend +* +* @par Description: +* Set reconnect policy.CNcomment:station设置重新连接网络机制.CNend +* +* @attention 1. It is recommended called after STA start or connected successfully. +* CNcomment:1. 在STA启动后或者关联成功后调用该接口.CNend\n +* 2. The reconnection policy will be triggered when the station is disconnected from ap.\n +* CNcomment:2. 重连机制将于station下一次去关联时生效,当前已经去关联设置无效.CNend\n +* 3. The Settings will take effect on the next reconnect timer.\n +* CNcomment:3. 重关联过程中更新重关联配置将于下一次重连计时生效.CNend\n +* 4. After calling station connect/disconnect or station stop, stop reconnecting. +* CNcomment:4. 调用station connect/disconnect或station stop,停止重连.CNend\n +* 5. If the target network cannot be found by scanning, + the reconnection policy cannot trigger to take effect.\n +* CNcomment:5. 若扫描不到目标网络,重连机制无法触发生效.CNend\n +* 6. When the value is 65535, it means infinite loop reconnection. +* CNcomment:6. 取值为65535时,表示无限次循环重连.CNend\n +* 7.Enable reconnect, user and lwip will not receive disconnect event when disconnected from ap until 15 +* seconds later and still don't reconnect to ap successfully. +* CNcomment:7. 使能自动重连,wifi将在15s内尝试自动重连并在此期间不上报去关联事件到用户和lwip协议栈, +* 做到15秒内重连成功用户和上层网络不感知.CNend\n +* 8.Must call again if add/down/delete SoftAp or MESH's interface status after last call. +* CNcomment:8. 调用后如果添加/禁用/删除了SoftAp,MESH接口的状态,需要再次调用该接口.CNend\n + +* @param enable [IN] Type #int enable reconnect.0-disable/1-enable.CNcomment:使能重连网络参数.CNend +* @param seconds [IN] Type #unsigned int reconnect timeout in seconds for once, range:[2-65535]. +* CNcomment:单次重连超时时间,取值[2-65535].CNend +* @param period [IN] Type #unsigned int reconnect period in seconds, range:[1-65535]. + CNcomment:重连间隔周期,取值[1-65535].CNend +* @param max_try_count [IN] Type #unsigned int max reconnect try count number,range:[1-65535]. + CNcomment:最大重连次数,取值[1-65535].CNend +* +* @retval #HISI_OK Execute successfully. +* @retval #HISI_FAIL Execute failed. +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +int hi_wifi_sta_set_reconnect_policy(int enable, unsigned int seconds, + unsigned int period, unsigned int max_try_count); + +/** +* @ingroup hi_wifi_basic +* @brief Get status of sta.CNcomment:获取station连接的网络状态.CNend +* +* @par Description: +* Get status of sta.CNcomment:获取station连接的网络状态.CNend +* +* @attention NULL +* @param connect_status [IN/OUT] Type #hi_wifi_status *, connect status, memory is requested by the caller. +* CNcomment:连接状态, 由调用者申请内存.CNend +* +* @retval #HISI_OK Execute successfully. +* @retval #HISI_FAIL Execute failed. +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +int hi_wifi_sta_get_connect_info(hi_wifi_status *connect_status); + +/** +* @ingroup hi_wifi_basic +* @brief Start pbc connect in WPS.CNcomment:设置WPS进行pbc连接.CNend +* +* @par Description: +* Start pbc connect in WPS.CNcomment:设置WPS进行pbc连接.CNend +* +* @attention 1. bssid can be NULL or MAC. CNcomment:1. bssid 可以指定mac或者填NULL.CNend +* @param bssid [IN] Type #unsigned char * mac address +* +* @retval #HISI_OK Execute successfully. +* @retval #HISI_FAIL Execute failed. +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +int hi_wifi_sta_wps_pbc(unsigned char *bssid); + +/** +* @ingroup hi_wifi_basic +* @brief Start pin connect in WPS.CNcomment:WPS通过pin码连接网络.CNend +* +* @par Description: +* Start pin connect in WPS.CNcomment:WPS通过pin码连接网络.CNend +* +* @attention 1. Bssid can be NULL or MAC. CNcomment:1. bssid 可以指定mac或者填NULL.CNend \n +* 2. Decimal only WPS pin code length is 8 Bytes.CNcomment:2. WPS中pin码仅限十进制,长度为8 Bytes.CNend +* @param pin [IN] Type #char * pin code +* @param bssid [IN] Type #unsigned char * mac address +* +* @retval #HISI_OK Execute successfully. +* @retval #HISI_FAIL Execute failed. +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +int hi_wifi_sta_wps_pin(char *pin, unsigned char *bssid); + +/** +* @ingroup hi_wifi_basic +* @brief Get pin code.CNcomment:WPS获取pin码.CNend +* +* @par Description: +* Get pin code.CNcomment:WPS获取pin码.CNend +* +* @attention Decimal only WPS pin code length is 8 Bytes.CNcomment:WPS中pin码仅限十进制,长度为8 Bytes.CNend +* @param pin [IN/OUT] Type #char *, pin code buffer, should be obtained, length is 9 Bytes. +* The memory is requested by the caller.\n +* CNcomment:待获取pin码,长度为9 Bytes。由调用者申请内存.CNend +* @param len [IN] Type #int, length of pin code。CNcomment:pin码的长度.CNend +* +* @retval #HISI_OK Execute successfully. +* @retval #HISI_FAIL Execute failed. +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +int hi_wifi_sta_wps_pin_get(char* pin, unsigned int len); + +/** +* @ingroup hi_wifi_basic +* @brief Get rssi value.CNcomment:获取rssi值.CNend +* +* @par Description: +* Get current rssi of ap which sta connected to.CNcomment:获取sta当前关联的ap的rssi值.CNend +* +* @attention The rssi value is derived from latest data frame received.CNcomment:该值从最新收到的数据帧获取.CNend +* @param NULL +* +* @retval #0x7F Invalid value. +* @retval #Other rssi +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +int hi_wifi_sta_get_ap_rssi(void); + +/** +* @ingroup hi_wifi_basic +* @brief Set sta powersave configuration.CNcomment:设置STA的低功耗参数.CNend +* +* @par Description: +* Set sta powersave configuration.CNcomment:设置STA的低功耗参数.CNend +* +* @attention CNcomment:1.参数值越小,功耗越低但性能表现和抗干扰会越差,建议使用默认值或根据流量动态配置.CNend\n +* CNcomment:2.所有参数配置0,表示该参数使用默认值.CNend\n +* CNcomment:3.仅支持设置STA的低功耗参数.CNend\n +* CNcomment:4.需要在关联成功后配置,支持动态配置.CNend\n +* CNcomment:5.定时器首次启动不计数,故实际睡眠时间为配置的重启次数+1乘以周期.CNend\n +* @param timer [IN] Type #unsigned char CNcomment:低功耗定时器周期,默认50ms,取值[0-100]ms.CNend +* @param time_cnt [IN] Type #unsigned char CNcomment:低功耗定时器重启次数,达到该次数后wifi无数据收发则进入休眠, + 默认为4,取值[0-10].CNend +* @param bcn_timeout [IN] Type #unsigned char CNcomment:等待接收beacon的超时时间,默认10ms,取值[0-100]ms.CNend +* @param mcast_timeout [IN] Type #unsigned char CNcomment:等待接收组播/广播帧的超时时间,默认30ms,取值[0-100]ms.CNend +* +* @retval #HISI_OK Excute successfully +* @retval #Other Error code +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +int hi_wifi_sta_set_pm_param(unsigned char timer, unsigned char time_cnt, unsigned char bcn_timeout, + unsigned char mcast_timeout); + +/** +* @ingroup hi_wifi_basic +* @brief WPA PSK Calculate.CNcomment:计算WPA PSK.CNend +* +* @par Description: +* PSK Calculate.CNcomment:计算psk.CNend +* +* @attention 1. support only WPA/WPA2 PSK. CNcomment:1. 只支持WPA/WPA2 PSK计算.CNend \n +* 2. SSID only supports ASCII characters. CNcomment:2. SSID 只支持ASCII字符.CNend +* @param psk_config [IN] Type #hi_wifi_sta_psk_config +* @param get_psk [IN/OUT] Type #const unsigned char *,Psk to be obtained, length is 32 Bytes. +* The memory is requested by the caller. +* CNcomment:待获取psk,长度为32 Bytes。由调用者申请内存.CNend +* @param psk_len [IN] Type #unsigned int +* @retval #HISI_OK Execute successfully. +* @retval #HISI_FAIL Execute failed. +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +int hi_wifi_psk_calc(hi_wifi_sta_psk_config psk_config, unsigned char *get_psk, unsigned int psk_len); + +/** +* @ingroup hi_wifi_basic +* @brief WPA PSK Calculate,then keep it inside .CNcomment:计算WPA PSK, 并做内部保存.CNend +* +* @par Description: +* psk Calculate.CNcomment:计算psk.CNend +* +* @attention 1. support only WPA/WPA2 PSK. CNcomment:1. 只支持WPA/WPA2 PSK计算.CNend \n +* 2. SSID only supports ASCII characters. CNcomment:2. SSID 只支持ASCII字符.CNend \n +* 3. The cached PSK will be cleared after the first quick connection. \n +* CNcomment:3. PSK缓存将在第一次执行快速连接后清除.CNend +* @param psk_config [IN] Type #hi_wifi_sta_psk_config +* @retval #HISI_OK Execute successfully. +* @retval #HISI_FAIL Execute failed. +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +int hi_wifi_psk_calc_and_store(hi_wifi_sta_psk_config psk_config); + +/** +* @ingroup hi_wifi_basic +* @brief config calling mode of user's callback interface.CNcomment:配置用户回调接口的调用方式.CNend +* +* @par Description: +* config calling mode of user's callback interface.CNcomment:配置用户回调接口的调用方式.CNend +* +* @attention 1. Wpa's task has high priority and call wifi's api directly may be cause error. + CNcomment:1. wpa线程优先级高,直接调用方式下在该回调接口内再次调用某些api会导致线程卡死.CNend + 2. If you have create a task in your app, you should use mode:0, or mode:1 is adervised. + CNcomment:2. 上层应用已创建task来处理事件回调建议使用直接调用方式,否则建议使用线程调用方式.CNend + 3. Configuration will keep till system reboot, set again when you start a new station. + CNcomment:3. 参数会保持上一次设置值直到系统重启,重新启动station后建议再配置一次.CNend + 4. Configuration will work immediately whenever you set. + CNcomment:4. 可随时配置该参数,配置成功即生效.CNend +* @param mode [IN] Type #unsigned char , call mode, 1:direct and 0:create task[default]. + CNcomment:回调调用方式,1:wpa线程直接调用,0:新建一个低优先级线程调用,默认.CNend +* @param task_prio [IN] Type #unsigned char , task priority, range(10-50) . + CNcomment:新建线程优先级,取值范围(10-50).CNend +* @param stack_size [IN] Type #unsigned short , task stack size, more than 1K bytes, default: 2k. + CNcomment:新建线程栈空间,需大于1K,默认2k.CNend +* +* @retval #HISI_OK Execute successfully. +* @retval #HISI_FAIL Execute failed. +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +int hi_wifi_config_callback(unsigned char mode, unsigned char task_prio, unsigned short stack_size); + +/** +* @ingroup hi_wifi_basic +* @brief register user callback interface.CNcomment:注册回调函数接口.CNend +* +* @par Description: +* register user callback interface.CNcomment:注册回调函数接口.CNend +* +* @attention NULL +* @param event_cb [OUT] Type #hi_wifi_event_cb, event callback .CNcomment:回调函数.CNend +* +* @retval #HISI_OK Execute successfully. +* @retval #HISI_FAIL Execute failed. +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +int hi_wifi_register_event_callback(hi_wifi_event_cb event_cb); + +/** +* @ingroup hi_wifi_basic +* @brief Set protocol mode of softap.CNcomment:设置softap接口的protocol模式.CNend +* +* @par Description: +* Set protocol mode of softap.CNcomment:设置softap接口的protocol模式.CNend\n +* Initiallize config, set before softap start.CNcomment:初始配置,在softap start之前调用.CNend +* +* @attention Default mode(802.11BGN) CNcomment:默认模式(802.11BGN).CNend +* @param mode [IN] Type #hi_wifi_protocol_mode protocol mode. +* +* @retval #HISI_OK Execute successfully. +* @retval #HISI_FAIL Execute failed. +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +int hi_wifi_softap_set_protocol_mode(hi_wifi_protocol_mode mode); + +/** +* @ingroup hi_wifi_basic +* @brief Get protocol mode of softap.CNcomment:获取softap接口的protocol模式.CNend +* +* @par Description: +* Get protocol mode of softap.CNcomment:获取softap接口的protocol模式.CNend +* +* @attention NULL +* @param NULL +* +* @retval #hi_wifi_protocol_mode protocol mode. +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +hi_wifi_protocol_mode hi_wifi_softap_get_protocol_mode(void); + +/** +* @ingroup hi_wifi_basic +* @brief Set softap's beacon interval.CNcomment:设置softap的beacon周期.CNend +* +* @par Description: +* Set softap's beacon interval.CNcomment:设置softap的beacon周期.CNend \n +* Initialized config sets before interface starts.CNcomment:初始配置softap启动之前调用.CNend +* +* @attention NULL +* @param beacon_period [IN] Type #int beacon period in milliseconds, range(33ms~1000ms), default(100ms) +* +* @retval #HISI_OK Execute successfully. +* @retval #HISI_FAIL Execute failed. +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +int hi_wifi_softap_set_beacon_period(int beacon_period); + +/** +* @ingroup hi_wifi_basic +* @brief Set softap's dtim count.CNcomment:设置softap的dtim周期.CNend +* +* @par Description: +* Set softap's dtim count.CNcomment:设置softap的dtim周期.CNend \n +* Initialized config sets before interface starts.CNcomment:初始配置softap启动之前调用.CNend +* +* @attention NULL +* @param dtim_period [IN] Type #int, dtim period , range(1~30), default(2) +* +* @retval #HISI_OK Execute successfully. +* @retval #HISI_FAIL Execute failed. +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +int hi_wifi_softap_set_dtim_period(int dtim_period); + +/** +* @ingroup hi_wifi_basic +* @brief Set update time of softap's group key.CNcomment:配置softap组播秘钥更新时间.CNend +* +* @par Description: +* Set update time of softap's group key.CNcomment:配置softap组播秘钥更新时间.CNend\n +* Initialized config sets before interface starts.CNcomment:初始配置softap启动之前调用.CNend\n +* If you need to use the rekey function, it is recommended to use WPA+WPA2-PSK + CCMP encryption. +* CNcomment:若需要使用rekey功能,推荐使用WPA+WPA2-PSK + CCMP加密方式.CNend +* +* @attention When using wpa2psk-only + CCMP encryption, rekey is forced to 86400s by default. +* CNcomment:当使用wpa2psk-only + CCMP加密方式时 ,rekey默认强制改为 86400.CNend +* @param wpa_group_rekey [IN] Type #int, update time in seconds, range(30s-86400s), default(86400s) +* CNcomment:更新时间以秒为单位,范围(30s-86400s),默认(86400s).CNend +* +* @retval #HISI_OK Execute successfully. +* @retval #HISI_FAIL Execute failed. +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +int hi_wifi_softap_set_group_rekey(int wifi_group_rekey); + +/** +* @ingroup hi_wifi_basic +* @brief Set short-gi of softap.CNcomment:设置softap的SHORT-GI功能.CNend +* +* @par Description: +* Enable or disable short-gi of softap.CNcomment:开启或则关闭softap的SHORT-GI功能.CNend\n +* Initialized config sets before interface starts.CNcomment:初始配置softap启动之前调用.CNend +* @attention NULL +* @param flag [IN] Type #int, enable(1) or disable(0). default enable(1). + CNcomment:使能标志,默认使能(1).CNend +* +* @retval #HISI_OK Execute successfully. +* @retval #HISI_FAIL Execute failed. +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +int hi_wifi_softap_set_shortgi(int flag); + +/** +* @ingroup hi_wifi_basic +* @brief Start softap interface.CNcomment:开启SoftAP.CNend +* +* @par Description: +* Start softap interface.CNcomment:开启SoftAP.CNend +* +* @attention 1. Multiple interfaces of the same type are not supported.CNcomment:不支持使用多个同类型接口.CNend\n +* 2. Dual interface coexistence support: STA + AP. CNcomment:双接口共存支持:STA + AP.CNend \n +* 3. Start timeout 5s.CNcomment:启动超时时间5s。CNend \n +* 4. Softap key length range(8 Bytes - 64 Bytes).CNcomment:softap key长度范围(8 Bytes - 64 Bytes).CNend \n +* 5. Only support auth mode as bellow: \n +* HI_WIFI_SECURITY_WPAPSK_WPA2PSK_MIX, \n +* HI_WIFI_SECURITY_WPA2PSK, \n +* HI_WIFI_SECURITY_OPEN \n +* CNcomment:5. 只支持以下认证模式:\n +* HI_WIFI_SECURITY_WPAPSK_WPA2PSK_MIX, \n +* HI_WIFI_SECURITY_WPA2PSK, \n +* HI_WIFI_SECURITY_OPEN.CNend \n +* 6. The memories of and should be requested by the caller, +* the input value of len must be the same as the length of ifname(the recommended length is 17Bytes).\n +* CNcomment:6. 由调用者申请内存,用户写入len的值必须与ifname长度一致(建议长度为17Bytes).CNend \n +* 7. SSID only supports ASCII characters. +* CNcomment:7. SSID 只支持ASCII字符.CNend \n +* 8. This is a blocking function.CNcomment:8.此函数为阻塞函数.CNend +* @param conf [IN] Type #hi_wifi_softap_config *, softap's configuration.CNcomment:SoftAP配置.CNend +* @param ifname [IN/OUT] Type #char *, interface name.CNcomment:接口名字.CNend +* @param len [IN/OUT] Type #int *, interface name length.CNcomment:接口名字长度.CNend +* +* @retval #HISI_OK Execute successfully. +* @retval #HISI_FAIL Execute failed. +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +int hi_wifi_softap_start(hi_wifi_softap_config *conf, char *ifname, int *len); + +/** +* @ingroup hi_wifi_basic +* @brief Close softap interface.CNcomment:关闭SoftAP.CNend +* +* @par Description: +* Close softap interface.CNcomment:关闭SoftAP.CNend +* +* @attention 1. This is a blocking function.CNcomment:1.此函数为阻塞函数.CNend +* @param NULL +* +* @retval #HISI_OK Execute successfully. +* @retval #HISI_FAIL Execute failed. +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +int hi_wifi_softap_stop(void); + +/** +* @ingroup hi_wifi_basic +* @brief Get all user's information of softap.CNcomment:softap获取已连接的station的信息.CNend +* +* @par Description: +* Get all user's information of softap.CNcomment:softap获取已连接的station的信息.CNend +* +* @attention 1.sta_list: malloc by user.CNcomment:1.扫描结果参数。由用户动态申请。CNend \n +* 2.sta_list: max size is hi_wifi_ap_sta_info * 6. +* CNcomment:2.sta_list 足够的结构体大小,最大为hi_wifi_ap_sta_info * 6。CNend \n +* 3.sta_num:parameters can be passed in to specify the number of connected sta.The maximum is 6. +* CNcomment:3.可以传入参数,指定获取已接入的sta个数,最大为6。CNend \n +* 4.sta_num should be the same with number of hi_wifi_ap_sta_info structures applied, Otherwise, +* it will cause memory overflow.\n +* CNcomment:4.sta_num和申请的hi_wifi_ap_sta_info结构体数量一致,否则可能造成内存溢出。CNend +* @param sta_list [IN/OUT] Type #hi_wifi_ap_sta_info *, station information.CNcomment:STA信息.CNend +* @param sta_num [IN/OUT] Type #unsigned int *, station number.CNcomment:STA个数.CNend +* +* @retval #HISI_OK Execute successfully. +* @retval #HISI_FAIL Execute failed. +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +int hi_wifi_softap_get_connected_sta(hi_wifi_ap_sta_info *sta_list, unsigned int *sta_num); + +/** +* @ingroup hi_wifi_basic +* @brief Softap deauth user by mac address.CNcomment:softap指定断开连接的station网络.CNend +* +* @par Description: +* Softap deauth user by mac address.CNcomment:softap指定断开连接的station网络.CNend +* +* @attention NULL +* @param addr [IN] Type #const unsigned char *, station mac address.CNcomment:MAC地址.CNend +* @param addr_len [IN] Type #unsigned char, station mac address length, must be 6. +* CNcomment:MAC地址长度,必须为6.CNend +* +* @retval #HISI_OK Execute successfully. +* @retval #HISI_FAIL Execute failed. +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +int hi_wifi_softap_deauth_sta(const unsigned char *addr, unsigned char addr_len); + +/** +* @ingroup hi_wifi_basic +* @brief set mac address.CNcomment:设置MAC地址.CNend +* +* @par Description: +* Set original mac address.CNcomment:设置起始mac地址.CNend\n +* mac address will increase or recycle when adding or deleting device. +* CNcomment:添加设备mac地址递增,删除设备回收对应的mac地址.CNend +* +* @attention NULL +* @param mac_addr [IN] Type #char *, mac address.CNcomment:MAC地址.CNend +* @param mac_len [IN] Type #unsigned char, mac address length.CNcomment:MAC地址长度.CNend +* +* @retval #HISI_OK Excute successfully +* @retval #Other Error code +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +int hi_wifi_set_macaddr(const char *mac_addr, unsigned char mac_len); + +/** +* @ingroup hi_wifi_basic +* @brief get mac address.CNcomment:获取MAC地址.CNend +* +* @par Description: +* Get original mac address.CNcomment:获取mac地址.CNend\n +* mac address will increase or recycle when adding device or deleting device. +* CNcomment:添加设备mac地址递增,删除设备回收对应的mac地址.CNend +* +* @attention NULL +* @param mac_addr [OUT] Type #char *, mac address. +* @param mac_len [IN] Type #unsigned char, mac address length. +* +* @retval #HISI_OK Excute successfully +* @retval #Other Error code +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +int hi_wifi_get_macaddr(char *mac_addr, unsigned char mac_len); + +/** +* @ingroup hi_wifi_basic +* @brief Set country code.CNcomment:设置国家码.CNend +* +* @par Description: +* Set country code(two uppercases).CNcomment:设置国家码,由两个大写字符组成.CNend +* +* @attention 1.Before setting the country code, you must call hi_wifi_init to complete the initialization. +* CNcomment:设置国家码之前,必须调用hi_wifi_init初始化完成.CNend\n +* 2.cc_len should be greater than or equal to 3.CNcomment:cc_len应大于等于3.CNend +* @param cc [IN] Type #char *, country code.CNcomment:国家码.CNend +* @param cc_len [IN] Type #unsigned char, country code length.CNcomment:国家码长度.CNend +* +* @retval #HISI_OK Excute successfully +* @retval #Other Error code +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +int hi_wifi_set_country(const char *cc, unsigned char cc_len); + +/** +* @ingroup hi_wifi_basic +* @brief Get country code.CNcomment:获取国家码.CNend +* +* @par Description: +* Get country code.CNcomment:获取国家码,由两个大写字符组成.CNend +* +* @attention 1.Before getting the country code, you must call hi_wifi_init to complete the initialization. +* CNcomment:获取国家码之前,必须调用hi_wifi_init初始化完成.CNend +* @param cc [OUT] Type #char *, country code.CNcomment:国家码.CNend +* @param len [IN/OUT] Type #int *, country code length.CNcomment:国家码长度.CNend +* +* @retval #HISI_OK Excute successfully +* @retval #Other Error code +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +int hi_wifi_get_country(char *cc, int *len); + +/** +* @ingroup hi_wifi_basic +* @brief Set bandwidth.CNcomment:设置带宽.CNend +* +* @par Description: +* Set bandwidth, support 5M/10M/20M.CNcomment:设置接口的工作带宽,支持5M 10M 20M带宽的设置.CNend +* +* @attention NULL +* @param ifname [IN] Type #const char *, interface name.CNcomment:接口名.CNend +* @param ifname_len [IN] Type #unsigned char, interface name length.CNcomment:接口名长度.CNend +* @param bw [IN] Type #hi_wifi_bw, bandwidth enum.CNcomment:带宽.CNend +* +* @retval #HISI_OK Excute successfully +* @retval #Other Error code +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +int hi_wifi_set_bandwidth(const char *ifname, unsigned char ifname_len, hi_wifi_bw bw); + +/** +* @ingroup hi_wifi_basic +* @brief Get bandwidth.CNcomment:获取带宽.CNend +* +* @par Description: +* Get bandwidth.CNcomment:获取带宽.CNend +* +* @attention NULL +* @param ifname [IN] Type #const char *, interface name.CNcomment:接口名.CNend +* @param ifname_len [IN] Type #unsigned char, interface name length.CNcomment:接口名长度.CNend +* +* @retval #bandwidth enum.CNcomment:带宽的枚举值.CNend +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +hi_wifi_bw hi_wifi_get_bandwidth(const char *ifname, unsigned char ifname_len); + +/** +* @ingroup hi_wifi_basic +* @brief Set channel.CNcomment:设置信道.CNend +* +* @par Description: +* Set channel.CNcomment:设置信道.CNend +* +* @attention NULL +* @param ifname [IN] Type #const char *, interface name.CNcomment:接口名.CNend +* @param ifname_len [IN] Type #unsigned char, interface name length.CNcomment:接口名长度.CNend +* @param channel [IN] Type #int , listen channel.CNcomment:信道号.CNend +* +* @retval #HISI_OK Excute successfully +* @retval #Other Error code +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +int hi_wifi_set_channel(const char *ifname, unsigned char ifname_len, int channel); + +/** +* @ingroup hi_wifi_basic +* @brief Get channel.CNcomment:获取信道.CNend +* +* @par Description: +* Get channel.CNcomment:获取信道.CNend +* +* @attention NULL +* @param ifname [IN] Type #const char *, interface name.CNcomment:接口名.CNend +* @param ifname_len [IN] Type #unsigned char, interface name length.CNcomment:接口名长度.CNend +* +* @retval #HI_WIFI_INVALID_CHANNEL +* @retval #Other chanel value. +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +int hi_wifi_get_channel(const char *ifname, unsigned char ifname_len); + +/** +* @ingroup hi_wifi_basic +* @brief Set monitor mode.CNcomment:设置混杂模式.CNend +* +* @par Description: +* Enable/disable monitor mode of interface.CNcomment:设置指定接口的混杂模式使能.CNend +* +* @attention NULL +* @param ifname [IN] Type #const char * interface name.CNcomment:接口名.CNend +* @param enable [IN] Type #int enable(1) or disable(0).CNcomment:开启/关闭.CNend +* @param filter [IN] Type #hi_wifi_ptype_filter * filtered frame type enum.CNcomment:过滤列表.CNend +* +* @retval #HI_ERR_SUCCESS Excute successfully +* @retval #Other Error code +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +int hi_wifi_promis_enable(const char *ifname, int enable, const hi_wifi_ptype_filter *filter); + +/** +* @ingroup hi_wifi_basic +* @brief Register receive callback in monitor mode.CNcomment:注册混杂模式的收包回调函数.CNend +* +* @par Description: +* 1.Register receive callback in monitor mode.CNcomment:1.注册混杂模式的收包回调函数.CNend\n +* 2.Wifi driver will put the receive frames to this callback. +* CNcomment:2.驱动将混杂模式的收到的报文递交到注册的回调函数处理.CNend +* +* @attention NULL +* @param data_cb [IN] Type #hi_wifi_promis_cb callback function pointer.CNcomment:混杂模式回调函数.CNend +* +* @retval #HI_ERR_SUCCESS Excute successfully +* @retval #Other Error code +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +int hi_wifi_promis_set_rx_callback(hi_wifi_promis_cb data_cb); + +/** +* @ingroup hi_wifi_basic +* @brief Open/close system power save.CNcomment:开启/关闭WiFi低功耗模式并配置预期休眠时间.CNend +* +* @par Description: +* Open/close system power save.CNcomment:开启/关闭WiFi低功耗模式并配置预期休眠时间.CNend +* +* @attention NULL +* @param enable [IN] Type #unsigned char, enable(1) or disable(0).CNcomment:开启/关闭WiFi低功耗.CNend +* @param sleep_time [IN] Type #unsigned int, expected sleep time(uint: ms). CNcomment:预期休眠时间(单位: 毫秒), +* 参考有效范围33ms~4000ms, 准确的时间根据dtim*beacon和sleep_time值计算, +* 关闭低功耗或者不配置有效休眠时间时需要将sleep_time配置为0(休眠时间由关联的ap决定).CNend +* +* @retval #HI_ERR_SUCCESS Excute successfully +* @retval #Other Error code +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +int hi_wifi_set_pm_switch(unsigned char enable, unsigned int sleep_time); + +/** +* @ingroup hi_wifi_basic +* @brief Set arp offload on/off.CNcomment:设置arp offload 打开/关闭.CNend +* +* @par Description: +* Set arp offload on with ip address, or set arp offload off. +* CNcomment:设置arp offload打开、并且设置相应ip地址,或者设置arp offload关闭.CNend +* +* @attention NULL +* @param ifname [IN] Type #const char *, device name. +* @param en [IN] Type #unsigned char, arp offload type, 1-on, 0-off. +* @param ip [IN] Type #unsigned int, ip address in network byte order, eg:192.168.50.4 -> 0x0432A8C0. +* +* @retval #HISI_OK Excute successfully +* @retval #Other Error code +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +unsigned char hi_wifi_arp_offload_setting(const char *ifname, unsigned char en, unsigned int ip); + +/** +* @ingroup hi_wifi_basic +* @brief Set nd offload on/off.CNcomment:设置nd offload 打开/关闭.CNend +* +* @par Description: +* Set nd offload on with ipv6 address, or set nd offload off. +* CNcomment:设置nd offload打开、设置正确的解析后的ipv6地址,或设置nd offload关闭.CNend +* +* @attention NULL +* @param ifname [IN] Type #const char *, device name. +* @param en [IN] Type #unsigned char, nd offload type, 1-on, 0-off. +* @param ip [IN] Type #unsigned char *, ipv6 address after parsing. +* eg:FE80::F011:31FF:FEE8:DB6E -> 0xfe80000000f01131fffee8db6e +* +* @retval #HISI_OK Excute successfully +* @retval #Other Error code +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +unsigned char hi_wifi_nd_offload_setting(const char *ifname, unsigned char en, unsigned char *ip6); + +/** +* @ingroup hi_wifi_basic +* @brief Set tx power.CNcomment:设置发送功率上限.CNend +* +* @par Description: +* Set maximum tx power.CNcomment:设置指定接口的发送功率上限.CNend +* +* @attention 1/only softAP can set maximum tx power.CNcomment:只有AP可以设置最大发送功率.CNend +* 2/should start softAP before set tx power.CNcomment:只有在AP start之后才可以设置.CNend +* @param ifname [IN] Type #const char * interface name. +* @param power [IN] Type #int maximum tx power value, range (0-19]dBm. +* +* @retval #HI_ERR_SUCCESS Excute successfully +* @retval #Other Error code +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +int hi_wifi_set_txpower_up_limit(const char *ifname, int power); + +/** +* @ingroup hi_wifi_basic +* @brief Get tx power.CNcomment:获取发送功率上限.CNend +* +* @par Description: +* Get maximum tx power setting.CNcomment:获取接口的最大发送功率限制值.CNend +* +* @attention NULL +* @param ifname [IN] Type #const char * interface name. +* +* @retval #tx power value. +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +int hi_wifi_get_txpower_up_limit(const char *ifname); + +/** +* @ingroup hi_wifi_basic +* @brief Set retry params.CNcomment:设置软件重传策略.CNend +* +* @par Description: +* Set retry params.CNcomment:设置指定接口的软件重传策略.CNend +* +* @attention 1.Need call befora start sta or softap.CNcomment:1.本API需要在STA或AP start之后调用.CNend +* @param ifname [IN] Type #const char * interface name.CNcomment:接口名.CNend +* @param type [IN] Type #unsigned char retry type. +* CNcomment:0:次数重传(数据帧); 1:次数重传(管理帧); 2:时间重传.CNend +* @param limit [IN] Type #unsigned char limit value. +* CNcomment:重传次数(0~15次)/重传时间(0~200个时间粒度,时间粒度10ms).CNend +* +* @retval #HISI_OK Excute successfully +* @retval #Other Error code +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +unsigned int hi_wifi_set_retry_params(const char *ifname, unsigned char type, unsigned char limit); + +/** +* @ingroup hi_wifi_basic +* @brief Set cca threshold.CNcomment:设置CCA门限.CNend +* +* @par Description: +* Set cca threshold.CNcomment:设置CCA门限.CNend +* +* @attention CNcomment:1.threshold设置范围是-128~126时,阈值固定为设置值.CNend\n +* CNcomment:2.threshold设置值为127时,恢复默认阈值-62dBm,并使能动态调整.CNend +* @param ifname [IN] Type #char *, device name. CNcomment:接口名.CNend +* @param threshold [IN] Type #char, threshold. CNcomment:门限值.CNend +* +* @retval #HISI_OK Excute successfully +* @retval #Other Error code +* +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +unsigned int hi_wifi_set_cca_threshold(const char* ifname, signed char threshold); + +/** +* @ingroup hi_wifi_basic +* @brief Set tx power offset.CNcomment:设置发送功率偏移.CNend +* +* @par Description: +* Set tx power offset.CNcomment:设置发送功率偏移.CNend +* +* @attention CNcomment:1.offset设置范围是-150~30,单位0.1dB.参数超出范围按最接近的边界值设置CNend\n +* CNcomment:2.offset设置,可能会影响信道功率平坦度和evm.CNend +* @param ifname [IN] Type #char *, device name. CNcomment:接口名.CNend +* @param offset [IN] Type #signed short, offset. CNcomment:门限值.CNend +* +* @retval #HISI_OK Excute successfully +* @retval #Other Error code +* +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +unsigned int hi_wifi_set_tx_pwr_offset(const char* ifname, signed short offset); + +/** +* @ingroup hi_wifi_basic +* @brief Send a custom frame.CNcomment:发送用户定制报文.CNend +* +* @par Description: +* Send a custom frame.CNcomment:发送用户定制报文.CNend +* +* @attention 1.Maximum length is 1400 bytes.CNcomment:1.最大支持发送1400字节的报文.CNend\n +* 2.Require to 802.11 prcotocol.CNcomment:2.报文须按照802.11协议格式封装.CNend\n +* 3.Send by management rate.CNcomment:3.采用管理帧速率发送,发送长包效率较低.CNend\n +* 4.Return status only specify the data has injected to send queue, isn't real send status. +* CNcomment:4.返回值仅表示数据是否成功进入发送队列,不表示空口发送状态.CNend\n +* 5.The chip is in a low-power state and does not support sending. +* CNcomment:5.芯片工作在低功耗状态下,不能调用该接口发送报文.CNend\n +* @param ifname [IN] Type #char *, device name. CNcomment:接口名.CNend +* @param data [IN] Type #unsigned char *, frame. CNcomment:帧内容.CNend +* @param len [IN] Type #unsigned int, frame length. CNcomment:帧长度.CNend +* +* @retval #HISI_OK Excute successfully +* @retval #Other Error code +* +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +int hi_wifi_send_custom_pkt(const char* ifname, const unsigned char *data, unsigned int len); + +/** +* @ingroup hi_wifi_basic +* @brief Add user IEs to management frame.CNcomment:在管理帧中添加用户IE字段。CNend +* +* @par Description: +* Add user IEs to management frame.CNcomment:在管理帧中添加用户IE字段。CNend +* +* @attention NULL +* @param iftype [IN] Type #hi_wifi_iftype, interface type. CNcomment:接口类型。CNend +* fram_type [IN] Type #hi_wifi_frame_type, frame type,HI_WIFI_IFTYPE_STATION iftype only supports +* Probe Request. +* CNcomment:帧类型, HI_WIFI_IFTYPE_STATION 接口类型只支持Probe Request帧。CNend +* usr_ie_type [IN] Type #usr_ie_type, user IE type, default set zero.CNcomment:用户IE类型,默认设为0。CNend +* ie [IN] Type #const unsigned char *, user IE value.CNcomment:用户IE字段内容。CNend +* ie_len [IN] Type #unsigned short, user IE length.CNcomment:用户IE字段内容长度。CNend +* @retval #HISI_OK Execute successfully. +* @retval #HISI_FAIL Execute failed. +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +int hi_wifi_add_usr_app_ie(hi_wifi_iftype iftype, hi_wifi_frame_type fram_type, + hi_wifi_usr_ie_type usr_ie_type, const unsigned char *ie, unsigned short ie_len); + +/** +* @ingroup hi_wifi_basic +* @brief Delete user IEs from management frame.CNcomment:在管理帧中删除用户IE字段。CNend +* +* @par Description: +* Delete user IEs from management frame.CNcomment:在管理帧中删除用户IE字段。CNend +* +* @attention NULL +* @param iftype [IN] Type #hi_wifi_iftype, interface type. CNcomment:接口类型。CNend +* fram_type [IN] Type #hi_wifi_frame_type, frame type,HI_WIFI_IFTYPE_STATION iftype only supports +* Probe Request. +* CNcomment:帧类型, HI_WIFI_IFTYPE_STATION 接口类型只支持Probe Request帧。CNend +* usr_ie_type [IN] Type #usr_ie_type, user IE type, default set zero.CNcomment:用户IE类型,默认设为0。CNend +* @retval #HISI_OK Execute successfully. +* @retval #HISI_FAIL Execute failed. +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +int hi_wifi_delete_usr_app_ie(hi_wifi_iftype iftype, hi_wifi_frame_type fram_type, hi_wifi_usr_ie_type usr_ie_type); + +/** +* @ingroup hi_wifi_basic +* @brief Set tcp mode.CNcomment:设置tpc开关.CNend +* +* @par Description: +* Set tpc mode.CNcomment:设置tpc开关.CNend +* +* @attention 1.Mode set to 1, enable auto power control. set to 0, disbale it. +* CNcomment:1.mode范围是0~1,1:打开发送功率自动控制,0:关闭发送功率自动控制.CNend +* @param ifname [IN] Type #char *, device name. CNcomment:接口名.CNend +* @param ifname_len [IN] Type #unsigned char, interface name length.CNcomment:接口名长度.CNend +* @param tpc_value [IN] Type #unsigned int, tpc_value. CNcomment:tpc开关.CNend +* +* @retval #HISI_OK Excute successfully +* @retval #Other Error code +* +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +unsigned int hi_wifi_set_tpc(const char* ifname, unsigned char ifname_len, unsigned int tpc_value); + +/** +* @ingroup hi_wifi_basic +* @brief Start STA's anchor point function.CNcomment:启动STA的锚点同步功能.CNend +* +* @par Description: +* Start STA's anchor point function.CNcomment:启动STA的锚点同步功能.CNend +* +* @attention 1.Only support STATION.CNcomment:1.仅支持STA开启该功能.CNend +* 2.Channel set to 0 indicates no channel specified.CNcomment:2.不指定信道时channel参数可设置为0.CNend +* @param ssid [IN] Type #char *, ap's ssid. CNcomment:ap的ssid.CNend +* @param ssid_len [IN] Type #unsigned char, ssid length.CNcomment:ssid长度.CNend +* @param channel [IN] Type #unsigned char, ap's channel.CNcomment:ap的信道.CNend +* +* @retval #HISI_OK Excute successfully +* @retval #Other Error code +* +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +int hi_wifi_start_anchor(const unsigned char *bssid, unsigned char bssid_len, unsigned char channel, + hi_wifi_anchor_cb cb); + +/** +* @ingroup hi_wifi_basic +* @brief Stop STA's anchor point function.CNcomment:停止STA的锚点同步功能.CNend +* +* @par Description: +* Stop STA's anchor point function.CNcomment:停止STA的锚点同步功能.CNend +* +* @attention 1.After stoping need stop and start sta again to use normal sta function. +* CNcomment:1.关闭锚点后需要stop STA并重新启动STA以使用正常的wifi功能.CNend +* +* @retval #HISI_OK Excute successfully +* @retval #Other Error code +* +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +int hi_wifi_stop_anchor(void); + +/** +* @ingroup hi_wifi_basic +* @brief Set STA's anchor wake up time offset.CNcomment:配置STA的唤醒提前量.CNend +* +* @par Description: +* Set STA's anchor wake up time offset.CNcomment:配置STA的唤醒提前量.CNend +* +* @attention 1.before sta start, the function should call first. +* CNcomment:1.在STA strart之前先调用.CNend +* 2.offset_time should less than 15000us. +* CNcomment:2.偏移时间应该小于15000us.CNend +* @param offset_time [IN] Type #unsigned short, offset time(us). CNcomment:唤醒提前量.CNend +* +* @retval #HISI_OK Excute successfully +* @retval #Other Error code +* +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +int hi_wifi_anchor_wakeup_offset_time(unsigned short offset_time); + +/** +* @ingroup hi_wifi_basic +* @brief Get Status Codes for Authentication and Association Frames. +* CNcomment:查询Authentication与Association帧status code.CNend +* +* @par Description: +* Get Status Codes for Authentication and Association Frames. +* CNcomment:查询Authentication与Association帧status code.CNend +* @attention 1.the return value is Status Codes for Authentication and Association Frames in 802.11. +* 2.used when STA connect AP fail. +* 3.the -1 return value means no status code, then if you want to get the reason of connect fail, use +* event_wifi_disconnected.reason_code. +* CNcomment: +* 1.返回值为802.11协议中Authentication reponse与Association reponse帧的status code +* 2.网卡类型为STA时使用,在STA发起路由器连接并失败时调用 +* 3.如果返回值为-1,表示无status code信息,此时获取连接失败的原因请使用event_wifi_disconnected结构体中的 +* reason_code值.CNend +* @param NULL +* +* @retval #Status Codes value +* +* +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +short hi_wifi_get_mac_status_code(void); + +/** +* @ingroup hi_wifi_basic +* @brief Set evm para.CNcomment:设置evm参数.CNend +* +* @par Description: +* Set evm para.CNcomment:设置evm参数.CNend +* +* @attention 1.Should be called before hi_wifi_init(). +* CNcomment:只能在hi_wifi_init()函数前调用.CNend +* @param pa_bias [IN] Type #unsigned char, PA bias setting.0:0xfe83,default value.1:0xfcc3.Others:invalid. +* CNcomment:PA偏置,0:0xfe83,默认值;1:0xfcc3;其它值:不支持.CNend +* @param osc_drv_vals [IN] Type #hi_wifi_xldo_voltage *, OSC driver values ch1~14.CNcomment:信道1~14的OSC驱动强度值.CNend +* @param size [IN] Type #unsigned char, OSC driver values' size.Should be 14. +* CNcomment:OSC驱动强度值数组大小,只能为14.CNend +* +* @retval #HISI_OK Excute successfully +* @retval #Other Error code +* +* @par Dependency: +* @li hi_wifi_api.h: WiFi API +* @see NULL +*/ +unsigned int hi_wifi_set_evm_para(unsigned char pa_bias, hi_wifi_xldo_voltage *osc_drv_vals, unsigned char size); + +#ifdef __cplusplus +#if __cplusplus + } +#endif +#endif + +#endif /* end of hi_wifi_api.h */ diff --git a/sdk_liteos/include/hi_wifi_csi_api.h b/sdk_liteos/include/hi_wifi_csi_api.h new file mode 100644 index 0000000000000000000000000000000000000000..a11ba4a01440ba36b1db67ea0034b3a8058d31fb --- /dev/null +++ b/sdk_liteos/include/hi_wifi_csi_api.h @@ -0,0 +1,191 @@ +/** + * @file hi_wifi_csi_api.h + * + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @defgroup hi_wifi_csi CSI + * @ingroup hi_wifi + */ + +#ifndef __HI_WIFI_CSI_API_H__ +#define __HI_WIFI_CSI_API_H__ + +#include "hi_wifi_api.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif + +/** + * @ingroup hi_wifi_csi + * + * Sample period of CSI.CNcomment:CSI 上报采样周期CNend + */ +typedef enum { + CSI_REPORT_PERIOD_EVERY_FRAME = 0, + CSI_REPORT_PERIOD_256US = 1, + CSI_REPORT_PERIOD_512US = 2, + CSI_REPORT_PERIOD_1024US = 3, + CSI_REPORT_PERIOD_2048US = 4, + CSI_REPORT_PERIOD_4096US = 5, + CSI_REPORT_PERIOD_8192US = 6, + CSI_REPORT_PERIOD_16384US = 7, + CSI_REPORT_PERIOD_32768US = 8, + CSI_REPORT_PERIOD_65536US = 9, + CSI_REPORT_PERIOD_131072US = 10, + CSI_REPORT_PERIOD_262144US = 11, + CSI_REPORT_PERIOD_524288US = 12, + CSI_REPORT_PERIOD_1048576US = 13, + CSI_REPORT_PERIOD_2097152US = 14, + CSI_REPORT_PERIOD_4194304US = 15, + CSI_REPORT_PERIOD_BUTT +} hi_wifi_csi_period_enum; + +/** + * @ingroup hi_wifi_csi + * + * Frame type of CSI report.CNcomment:CSI 上报数据帧类型CNend + */ +typedef enum { + CSI_FRAME_TYPE_DATA = 1, /**< data. CNcomment: 数据帧.CNend */ + CSI_FRAME_TYPE_MGMT = 2, /**< management. CNcomment: 管理帧.CNend */ + CSI_FRAME_TYPE_MGMT_DATA = 3, /**< management and data. CNcomment: 管理帧和数据帧.CNend */ + CSI_FRAME_TYPE_CTRL = 4, /**< control. CNcomment: 控制帧.CNend */ + CSI_FRAME_TYPE_CTRL_DATA = 5, /**< control and data. CNcomment: 控制帧和数据帧.CNend */ + CSI_FRAME_TYPE_CTRL_MGMT = 6, /**< control adn management. CNcomment: 控制帧和管理帧.CNend */ + CSI_FRAME_TYPE_ALL = 7, /**< control and data and management. CNcomment: 控制帧和数据帧和管理帧.CNend */ + CSI_FRAME_TYPE_BUTT +} hi_wifi_csi_frame_type_enum; + +/** + * @ingroup hi_wifi_csi + * + * Struct of CSI reporting config.CNcomment:CSI 上报参数配置CNend + */ +typedef struct { + unsigned char mac[HI_WIFI_MAC_LEN]; /**< Mac address. CNcomment: MAC地址.CNend */ + hi_wifi_csi_frame_type_enum frame_type; /**< Report frame type. CNcomment: 上报帧类型.CNend */ + hi_wifi_csi_period_enum sample_period; /**< Sample period. CNcomment: 信道采样周期.CNend */ +} hi_wifi_csi_entry; + +/** +* @ingroup hi_wifi_csi +* @brief CSI data report callback. +* +* @par Description: +* user's callback to handle csi report data. + CNcomment:用户注册的回调函数,用于处理CSI上报的数据。CNend +* +* @attention NULL +* @param csi_data [IN] Type #unsigned char *, 4 bytes extend timestamp + 184 bytes 64bit big endian data. + CNcomment:4字节扩展时间戳+184字节64位小端存储格式的CSI数据。CNend +* @param len [IN] Type #int, data length. CNcomment:数据长度,固定为188字节。CNend +* +* @retval void +* @par Dependency: +* @li hi_wifi_csi_api.h: WiFi API +* @see NULL +*/ +typedef void (*hi_wifi_csi_data_cb)(unsigned char *csi_data, int len); + +/** +* @ingroup hi_wifi_csi +* @brief Config CSI. +* +* @par Description: +* Config CSI basic parameters, config csi will colse low power, stop csi can open low power again. + CNcomment:配置CSI数据上报功能的基本参数,配置后会关闭低功耗,暂时不启用CSI可通过stop命令开启低功耗。CNend +* +* @attention NULL +* @param ifname [IN] Type #char *,interface which enable CSI, wlan0 or ap0. +* @param report_min_interval [IN] Type #unsigned int, report period: minimum 50 ms. + CNcomment:CSI数据上报最小间隔,最小周期50ms,小于50ms默认为50ms。CNend +* @param entry_list [IN] Type #hi_wifi_csi_entry *, configuration struct. +* @param entry_num [IN] Type #int, list number.CNcomment:entry_list的数量,可添加最大白名单数量为6。CNend +* +* @retval #HI_ERR_SUCCESS Excute successfully +* @retval #Other Error code +* @par Dependency: +* @li hi_wifi_csi_api.h: WiFi API +* @see NULL +*/ +int hi_wifi_csi_set_config(const char *ifname, unsigned int report_min_interval, + const hi_wifi_csi_entry *entry_list, int entry_num); + +/** +* @ingroup hi_wifi_csi +* @brief Register report callback of CSI.CNcomment:注册CSI数据上报回调函数。CNend +* +* @par Description: +* CSI data report interface.CNcomment:由用户注册回调函数,用于上报CSI数据。CNend +* +* @attention NULL +* @param data_cb [IN] Type #hi_wifi_csi_data_cb, callback pointer. +* +* @retval #HI_ERR_SUCCESS Excute successfully +* @retval #Other Error code +* @par Dependency: +* @li hi_wifi_csi_api.h: WiFi API +* @see NULL +*/ +int hi_wifi_csi_register_data_recv_func(hi_wifi_csi_data_cb data_cb); + +/** +* @ingroup hi_wifi_csi +* @brief Start CSI. +* +* @par Description: +* Start CSI. +* +* @attention NULL +* @param NULL +* +* @retval #HI_ERR_SUCCESS Excute successfully +* @retval #Other Error code +* @par Dependency: +* @li hi_wifi_csi_api.h: WiFi API +* @see NULL +*/ +int hi_wifi_csi_start(void); + +/** +* @ingroup hi_wifi_csi +* @brief Close CSI. +* +* @par Description: +* Close CSI. +* +* @attention NULL +* @param NULL +* +* @retval #HI_ERR_SUCCESS Excute successfully +* @retval #Other Error code +* @par Dependency: +* @li hi_wifi_csi_api.h: WiFi API +* @see NULL +*/ +int hi_wifi_csi_stop(void); + +#ifdef __cplusplus +#if __cplusplus + } +#endif +#endif + +#endif /* end of hi_wifi_csi_api.h */ + diff --git a/sdk_liteos/include/hi_wifi_sdp_api.h b/sdk_liteos/include/hi_wifi_sdp_api.h new file mode 100644 index 0000000000000000000000000000000000000000..c9eb65dd58b661667c0eed5d913ec63d713ba000 --- /dev/null +++ b/sdk_liteos/include/hi_wifi_sdp_api.h @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __HI_WIFI_NAN_API_H__ +#define __HI_WIFI_NAN_API_H__ + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif + +typedef enum { + WIFI_SDP_PUBLISH = 0x01, + WIFI_SDP_SUBSCRIBE = 0x02, + WIFI_SDP_BUTT +}wifi_sdp_type_enum; + +typedef enum { + WIFI_SDP_SYNC_MODE_PRIVATE, + WIFI_SDP_SYNC_MODE_STANDARD, + WIFI_SDP_SYNC_MODE_BOTH, + WIFI_SDP_SYNC_MODE_BUTT +}wifi_sdp_sync_enum; + +typedef int (*hi_wifi_sdp_recv_cb)(unsigned char* mac, unsigned char peer_handle, unsigned char local_handle, + unsigned char* msg, unsigned char len); +int hi_wifi_sdp_init(const char* ifname); +int hi_wifi_sdp_deinit(void); +int hi_wifi_sdp_start_service(const char* service_name, unsigned char local_handle, + hi_wifi_sdp_recv_cb recv_cb, unsigned char role); +int hi_wifi_sdp_stop_service(unsigned char local_handle, unsigned char role); +int hi_wifi_sdp_send(unsigned char* mac_addr, unsigned char peer_handle, unsigned char local_handle, + unsigned char* msg, int len); +int hi_wifi_sdp_adjust_tx_power(const char *ifname, signed char power); +int hi_wifi_sdp_restore_tx_power(const char *ifname); +int hi_wifi_sdp_adjust_rx_param(const char *ifname, signed char rssi); +int hi_wifi_sdp_restore_rx_param(const char *ifname); +int hi_wifi_sdp_beacon_switch(const char *ifname, unsigned char enable); +int hi_wifi_sdp_set_retry_times(hi_u32 retries); +int hi_wifi_sdp_get_sync_mode(void); +#ifdef __cplusplus +#if __cplusplus + } +#endif +#endif + +#endif /* end __HI_WIFI_VLWIP_API_H__ */ + diff --git a/sdk_liteos/include/hi_workqueue.h b/sdk_liteos/include/hi_workqueue.h new file mode 100644 index 0000000000000000000000000000000000000000..b3be3ff73ade2cd2bdac4b48a4acc6d68c307ca3 --- /dev/null +++ b/sdk_liteos/include/hi_workqueue.h @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __HI_QUEUE_H__ +#define __HI_QUEUE_H__ +#include "hi_types.h" +#include + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif + +typedef hi_void (*work_func)(struct work_struct *); +typedef struct workqueue_struct hi_workqueue; +typedef struct work_struct hi_work; +typedef struct delayed_work hi_delayed_work; /* struct delay_work wrap struct work_struct */ + +/* create workqueue. */ +inline hi_workqueue *hi_workqueue_create(char *workqueue_name) +{ + return create_workqueue(workqueue_name); +} + +/* destroy workqueue. */ +inline hi_void hi_workqueue_destroy(hi_workqueue *workqueue) +{ + destroy_workqueue(workqueue); +} + +/* init work. */ +inline hi_void hi_workqueue_init_work(hi_work *work, work_func func) +{ + INIT_WORK(work, func); +} + +/* add work to workqueue. */ +inline hi_s32 hi_workqueue_add_work(hi_workqueue *workqueue, hi_work *work) +{ + return queue_work(workqueue, work); +} + +/* cancle work from workqueue. */ +inline hi_bool hi_workqueue_cancle_work_sync(hi_work *work) +{ + return cancel_work_sync(work); +} + +/* judge work is working. */ +inline hi_bool hi_workqueue_is_busy(hi_work *work) +{ + return work_busy(work); +} + +/* init delayed work. */ +inline hi_void hi_workqueue_init_delayed_work(hi_delayed_work *delayed_work, work_func func) +{ + init_delayed_work(delayed_work, func); +} + +/* add delay work to workqueue. */ +inline hi_s32 hi_workqueue_add_delayed_work(hi_workqueue *workqueue, hi_delayed_work *delayed_work, hi_u32 delay) +{ + return queue_delayed_work(workqueue, delayed_work, delay); +} + +/* cancle delayed work to workqueue. */ +inline hi_bool hi_workqueue_cancle_delayed_work_sync(hi_delayed_work *delayed_work) +{ + return cancel_delayed_work_sync(delayed_work); +} + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif + +#endif /* end of hi_workqueue.h */ diff --git a/sdk_liteos/include/hks_client.h b/sdk_liteos/include/hks_client.h new file mode 100644 index 0000000000000000000000000000000000000000..4b321e17a3f9cd879910bf603a006ee2930c0730 --- /dev/null +++ b/sdk_liteos/include/hks_client.h @@ -0,0 +1,764 @@ +/** + * @file hks_client.h + * + * Copyright (c) 2020 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Description: Contains key generation, signature verify, + * encryption and decryption, key derivation, key agreement, etc. \n + * Author: Huawei \n + * Create: 2019-06-19 + */ +/** + * @defgroup iot_hks + * @ingroup hks + */ + +#ifndef HKS_CLIENT_H +#define HKS_CLIENT_H + +#include "hks_types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** +* @ingroup iot_hks +* @brief Hks get sdk version.CNcomment:获取HKS sdk版本号。CNend +* +* @par 描述: +* Hks get sdk version.CNcomment:获取HKS sdk版本号。CNend +* +* @attention None +* @param sdk_version [OUT] type #struct hks_blob *,get sdk version.CNcomment:HKS sdk版本号。CNend +* +* @retval None +* @par 依赖: +* @li hks_types.h:describes hks_types SDK interfaces.CNcomment:描述hks_types SDK的接口。CNend +* @see hks_get_sdk_version +*/ +HKS_DLL_API_PUBLIC void hks_get_sdk_version(struct hks_blob *sdk_version); + +/** +* @ingroup iot_hks +* @brief Hks init.CNcomment:hks 初始化。CNend +* +* @par 描述: +* Hks init.CNcomment:hks 初始化。CNend +* +* @attention None +* @param None +* +* @retval #0 Success. +* @retval #Other Failure. +* @par 依赖: +* @li hks_types.h:describes hks_types SDK interfaces.CNcomment:描述hks_types SDK的接口。CNend +* @see hks_init +*/ +HKS_DLL_API_PUBLIC int32_t hks_init(void); + +/** +* @ingroup iot_hks +* @brief Hks destroy.CNcomment:销毁 hks。CNend +* +* @par 描述: +* Hks destroy.CNcomment:销毁 hks。CNend +* +* @attention None +* @param None +* +* @retval None +* @par 依赖: +* @li hks_types.h:describes hks_types SDK interfaces.CNcomment:描述hks_types SDK的接口。CNend +* @see hks_destroy +*/ +HKS_DLL_API_PUBLIC void hks_destroy(void); + +/** +* @ingroup iot_hks +* @brief Refresh key info and root key info.CNcomment:刷新密钥信息和根密钥信息。CNend +* +* @par 描述: +* Refresh key info and root key info.CNcomment:刷新密钥信息和根密钥信息。CNend +* +* @attention None +* @param None +* +* @retval #0 Success. +* @retval #Other Failure. +* @par 依赖: +* @li hks_types.h:describes hks_types SDK interfaces.CNcomment:描述hks_types SDK的接口。CNend +* @see hks_refresh_key_info +*/ +HKS_DLL_API_PUBLIC int32_t hks_refresh_key_info(void); + +/** +* @ingroup iot_hks +* @brief Generate key Only ED25519 algorithm key pair generation is supported The number of local storage keys. + CNcomment:生成密钥仅支持ED25519算法密钥对生成本地存储密钥。CNend +* +* @par 描述: +* Generate key Only ED25519 algorithm key pair generation is supported The number of local storage keys + (including generated ED25519 public-private key pairs imported ED25519 public keys) is limited to 16. + CNcomment:生成密钥仅支持ED25519算法密钥对生成本地存储密钥 + (包括导入的ED25519公共密钥和私有ED25519生成的ED25519公共密钥对)的数量限制为16个。CNend +* +* @attention None +* @param key_alias [IN] type #const struct hks_blob *,key alias, constraint condition:key_alias->size <= 64. + CNcomment:密钥别名,约束条件:key_alias-> size <= 64。CNend +* @param key_param [IN] type #const struct hks_key_param *,The parameter of the key which need to generate + constraint condition: key_param cannot be NULL & key_param->key_type must be HKS_KEY_TYPE_EDDSA_KEYPAIR_ED25519. + CNcomment:需要生成的密钥参数 约束条件: + key_param不能为NULL & key_param-> key_type必须为HKS_KEY_TYPE_EDDSA_KEYPAIR_ED25519。CNend +* @retval #0 Success. +* @retval #Other Failure. +* @par 依赖: +* @li hks_types.h:describes hks_types SDK interfaces.CNcomment:描述hks_types SDK的接口。CNend +* @see hks_generate_key +*/ +HKS_DLL_API_PUBLIC int32_t hks_generate_key(const struct hks_blob *key_alias, + const struct hks_key_param *key_param); + +/** +* @ingroup iot_hks +* @brief Generate the X25519 algorithm key pair and return it to the caller. The generated key pair is not saved in HKS. + CNcomment:生成X25519算法秘钥对并返回给调用者,生成的秘钥对不在hks保存。CNend +* +* @par 描述: +* Generate the X25519 algorithm key pair and return it to the caller. + The generated key pair is not saved in HKS. + CNcomment:生成X25519算法秘钥对并返回给调用者,生成的秘钥对不在hks保存。CNend +* +* @attention None +* @param key_param [IN] type #const struct hks_key_param *,Used to specify related parameters that affect + key generation, constraint condition: key_param.key_type must be HKS_KEY_TYPE_ECC_KEYPAIR_CURVE25519 + key_param.usage must be hks_alg_ecdh(HKS_ALG_SELECT_RAW). + CNcomment:用于指定影响秘钥生成的相关参数, 约束条件:key_param.key_type必须为HKS_KEY_TYPE_ECC_KEYPAIR_CURVE25519 + key_param.usage必须为hks_alg_ecdh(HKS_ALG_SELECT_RAW)。CNend +* @param pri_key [OUT] type #struct hks_blob *,Used to save the generated private key + CNcomment:用于保存生成的私钥。CNend +* @param pub_key [OUT] type #struct hks_blob *,Used to save the generated public key. + CNcomment:用于保存生成的公钥。CNend +* @param +* @retval #0 Success. +* @retval #Other Failure. +* @par 依赖: +* @li hks_types.h:describes hks_types SDK interfaces.CNcomment:描述hks_types SDK的接口。CNend +* @see hks_generate_asymmetric_key +*/ +HKS_DLL_API_PUBLIC int32_t hks_generate_asymmetric_key( + const struct hks_key_param *key_param, struct hks_blob *pri_key, + struct hks_blob *pub_key); + +/** +* @ingroup iot_hks +* @brief Associate the ED25519 algorithm public key and the parameters of the public key with the alias and + import it into HKS to save. CNcomment:将ED25519算法公钥以及公钥的参数与别名关联并导入到hks中保存。CNend +* +* @par 描述: +* Associate the ED25519 algorithm public key and the parameters of the public key with the alias and + import it into HKS to save. CNcomment:将ED25519算法公钥以及公钥的参数与别名关联并导入到hks中保存。CNend +* +* @attention None +* @param key_alias [IN] type #const struct hks_blob *,Alias to specify to save the ED25519 public key. + CNcomment:用于指定保存ED25519公钥的别名。CNend +* @param key_param [IN] type #const struct hks_key_param *,The key parameters associated with + the public key are saved to the HKS together with the public key, constraint condition: key_param.key_type must be + HKS_KEY_TYPE_EDDSA_PUBLIC_KEY_ED25519 + CNcomment:和公钥关联的秘钥参数,与公钥一起保存到hks中, 约束条件:key_param.key_type必须为 + HKS_KEY_TYPE_EDDSA_PUBLIC_KEY_ED25519。CNend +* @param key [IN] type #const struct hks_blob *,Public key to be imported into hks. + CNcomment:需要导入到hks中的公钥。CNend +* @retval #0 Success. +* @retval #Other Failure. +* @par 依赖: +* @li hks_types.h:describes hks_types SDK interfaces.CNcomment:描述hks_types SDK的接口。CNend +* @see hks_import_public_key +*/ +HKS_DLL_API_PUBLIC int32_t hks_import_public_key( + const struct hks_blob *key_alias, + const struct hks_key_param *key_param, const struct hks_blob *key); + +/** +* @ingroup iot_hks +* @brief Export the public key associated with the file name saved in the HKS system. + CNcomment:导出保存在hks系统中与文件名关联的公钥。CNend +* +* @par 描述: +* Export the public key associated with the file name saved in the HKS system. + CNcomment:导出保存在hks系统中与文件名关联的公钥。CNend +* +* @attention None +* @param key_alias [IN] type #const struct hks_blob * Alias used to associate with the exported public key, + constraint condition: key_alias->size <= 64. + CNcomment:用于与导出公钥关联的别名, 约束条件:key_alias-> size <= 64。CNend +* @param key [OUT] type #struct hks_blob * Cache of hks public key.CNcomment:存放 hks公钥的缓存。CNend +* @retval #0 Success. +* @retval #Other Failure. +* @par 依赖: +* @li hks_types.h:describes hks_types SDK interfaces.CNcomment:描述hks_types SDK的接口。CNend +* @see hks_export_public_key +*/ +HKS_DLL_API_PUBLIC int32_t hks_export_public_key( + const struct hks_blob *key_alias, struct hks_blob *key); + +/** +* @ingroup iot_hks +* @brief Delete the public key associated with the alias saved in the HKS system. + CNcomment:删除保存在hks系统中与别名关联的公钥。CNend +* +* @par 描述: +* Delete the public key associated with the alias saved in the HKS system. + CNcomment:删除保存在hks系统中与别名关联的公钥。CNend +* +* @attention None +* @param key_alias [IN] type #const struct hks_blob * The alias associated with the delete key, + constraint condition: key_alias->size <= 64. + CNcomment:与删除秘钥关联的别名, 约束条件:key_alias-> size <= 64。CNend +* @retval #0 Success. +* @retval #Other Failure. +* @par 依赖: +* @li hks_types.h:describes hks_types SDK interfaces.CNcomment:描述hks_types SDK的接口。CNend +* @see hks_delete_key +*/ +HKS_DLL_API_PUBLIC int32_t hks_delete_key(const struct hks_blob *key_alias); + +/** +* @ingroup iot_hks +* @brief Export key attributes associated with aliases stored in the HKS system. + CNcomment:导出保存在hks系统中与别名关联的秘钥属性。CNend +* +* @par 描述: +* Export key attributes associated with aliases stored in the HKS system. + CNcomment:导出保存在hks系统中与别名关联的秘钥属性。CNend +* +* @attention None +* @param key_alias [IN] type #const struct hks_blob * Alias used to associate with the exported public key, + constraint condition: key_alias->size <= 64. + CNcomment:用于与导出公钥关联的别名, 约束条件:key_alias-> size <= 64。CNend +* @param key_param [OUT] type #struct hks_key_param * Pointer to key attribute. CNcomment:存放秘钥属性的指针。CNend +* @retval #0 Success. +* @retval #Other Failure. +* @par 依赖: +* @li hks_types.h:describes hks_types SDK interfaces.CNcomment:描述hks_types SDK的接口。CNend +* @see hks_get_key_param +*/ +HKS_DLL_API_PUBLIC int32_t hks_get_key_param(const struct hks_blob *key_alias, + struct hks_key_param *key_param); + +/** +* @ingroup iot_hks +* @brief Determine if there is a public or secret key pair associated with the alias in hks. + CNcomment:判断hks中是否存在与别名关联的公钥或秘钥对。CNend +* +* @par 描述: +* Determine if there is a public or secret key pair associated with the alias in hks. + CNcomment:判断hks中是否存在与别名关联的公钥或秘钥对。CNend +* +* @attention None +* @param key_alias [IN] type #const struct hks_blob * The alias associated with the delete key, + constraint condition: key_alias->size <= 64. + CNcomment:与删除秘钥关联的别名, 约束条件:key_alias-> size <= 64。CNend +* @retval #0 Success. +* @retval #Other Failure. +* @par 依赖: +* @li hks_types.h:describes hks_types SDK interfaces.CNcomment:描述hks_types SDK的接口。CNend +* @see hks_is_key_exist +*/ +HKS_DLL_API_PUBLIC int32_t hks_is_key_exist(const struct hks_blob *key_alias); + +/** +* @ingroup iot_hks +* @brief Generate a secure random number, no longer than 1024 bytes. CNcomment:生成安全随机数,长度不超过1024字节。CNend +* +* @par 描述: +* Generate a secure random number, no longer than 1024 bytes. + CNcomment:生成安全随机数,长度不超过1024字节。CNend +* +* @attention None +* @param random [OUT] type #struct hks_blob * Used to save generated random numbers, + random->size must be specified by the caller ,constraint condition: random->size <= 1024. + CNcomment:用于保存生成的随机数, random-> size必须由调用方指定,约束条件:random-> size <= 1024。CNend +* @retval #0 Success. +* @retval #Other Failure. +* @par 依赖: +* @li hks_types.h:describes hks_types SDK interfaces.CNcomment:描述hks_types SDK的接口。CNend +* @see hks_generate_random +*/ +HKS_DLL_API_PUBLIC int32_t hks_generate_random(struct hks_blob *random); + +/** +* @ingroup iot_hks +* @brief Generate a data signature using the ED25519 private key associated with the alias in hks. + CNcomment:使用hks中与别名关联的ED25519私钥生成数据签名。CNend +* +* @par 描述: +* Generate a data signature using the ED25519 private key associated with the alias in hks. + CNcomment:使用hks中与别名关联的ED25519私钥生成数据签名。CNend +* +* @attention None +* @param key_alias [IN] type #const struct hks_blob * Sign using alias of secret key, + constraint condition: key_alias->size <= 64. + CNcomment:签名使用秘钥的别名, 约束条件:key_alias-> size <= 64。CNend +* @param key_param [IN] type #const struct hks_key_param *,Attributes of the key associated with key_alias. + CNcomment:与key_alias关联的秘钥的属性。CNend +* @param hash [IN] type #const struct hks_blob *,Data to be signed. CNcomment:待签名的数据。CNend +* @param signature [OUT] type #struct hks_blob *,Output data signature, constraint condition: + signature->size bigger & equal 64。 + CNcomment:输出的数据签名,约束条件:签名大小> = 64。CNend +* @retval #0 Success. +* @retval #Other Failure. +* @par 依赖: +* @li hks_types.h:describes hks_types SDK interfaces.CNcomment:描述hks_types SDK的接口。CNend +* @see hks_asymmetric_sign +*/ +HKS_DLL_API_PUBLIC int32_t hks_asymmetric_sign( + const struct hks_blob *key_alias, + const struct hks_key_param *key_param, const struct hks_blob *hash, + struct hks_blob *signature); + +/** +* @ingroup iot_hks +* @brief Verify data signature using ED25519 public key. CNcomment:使用ED25519公钥验证数据签名。CNend +* +* @par 描述: +* Verify data signature using ED25519 public key. CNcomment:使用ED25519公钥验证数据签名。CNend +* +* @attention None +* @param key [IN] type #const struct hks_blob * The alias or ED25519 public key associated with the ED25519 key. + CNcomment:与ED25519秘钥关联的别名或ED25519公钥。CNend +* @param key_param [IN] type #const struct hks_key_param *,The attributes of the key associated with the key. + CNcomment:与key关联的秘钥的属性。CNend +* @param hash [IN] type #const struct hks_blob *,Signed data. CNcomment:签名的数据。CNend +* @param signature [IN] type #const struct hks_blob *,Data signature,constraint condition: + signature->size bigger & equal 64。 + CNcomment:数据签名, 约束条件:签名大小> = 64。CNend +* @retval #0 Success. +* @retval #Other Failure. +* @par 依赖: +* @li hks_types.h:describes hks_types SDK interfaces.CNcomment:描述hks_types SDK的接口。CNend +* @see hks_asymmetric_verify +*/ +HKS_DLL_API_PUBLIC int32_t hks_asymmetric_verify(const struct hks_blob *key, + const struct hks_key_param *key_param, const struct hks_blob *hash, + const struct hks_blob *signature); + +/** +* @ingroup iot_hks +* @brief Data encryption using AES-128-GCM algorithm. CNcomment:使用AES-128-GCM算法对数据加密。CNend +* +* @par 描述: +* Data encryption using AES-128-GCM algorithm. CNcomment:使用AES-128-GCM算法对数据加密。CNend +* +* @attention None +* @param key [IN] type #const struct hks_blob *,The key used to encrypt the plaintext. + CNcomment:用于加密明文的秘钥。CNend +* @param key_param [IN] type #const struct hks_key_param *,The attributes of the key associated with the key. + constraint condition: key_param.key_type is HKS_KEY_TYPE_AES, key_param.key_len is 128 or 192 or 256; + key_param.key_usage is HKS_KEY_USAGE_ENCRYPT, key_param.key_mode is HKS_ALG_GCM; + key_param.key_pad is HKS_PADDING_NONE + CNcomment:与key关联的秘钥的属性,约束条件:key_param.key_type为HKS_KEY_TYPE_AES,key_param.key_len为128或192或256; + key_param.key_usage是HKS_KEY_USAGE_ENCRYPT,key_param.key_mode是HKS_ALG_GCM; + key_param.key_pad为HKS_PADDING_NONE。CNend +* @param crypt_param [IN] type #const struct hks_crypt_param *,Vectors and additional data used for encryption. + CNcomment:加密使用的向量和附加数据。CNend +* @param plain_text [IN] type #const struct hks_blob *,Data plaintext。CNcomment:数据明文。CNend +* @param cipher_text_with_tag [OUT] type #struct hks_blob *,Data ciphertext CNcomment:数据密文。CNend +* @retval #0 Success. +* @retval #Other Failure. +* @par 依赖: +* @li hks_types.h:describes hks_types SDK interfaces.CNcomment:描述hks_types SDK的接口。CNend +* @see hks_aead_encrypt +*/ +HKS_DLL_API_PUBLIC int32_t hks_aead_encrypt(const struct hks_blob *key, + const struct hks_key_param *key_param, + const struct hks_crypt_param *crypt_param, + const struct hks_blob *plain_text, + struct hks_blob *cipher_text_with_tag); + +/** +* @ingroup iot_hks +* @brief Decrypt ciphertext using AES-128-GCM algorithm. CNcomment:使用AES-128-GCM算法对密文解密。CNend +* +* @par 描述: +* Decrypt ciphertext using AES-128-GCM algorithm. CNcomment:使用AES-128-GCM算法对密文解密。CNend +* +* @attention None +* @param key [IN] type #const struct hks_blob *,Secret key for decryption. CNcomment:用于解密的秘钥。CNend +* @param key_param [IN] type #const struct hks_key_param *,The attributes of the key associated with the key. + constraint condition: key_param.key_type is HKS_KEY_TYPE_AES, key_param.key_len is 128 or 192 or 256; + key_param.key_usage is HKS_KEY_USAGE_DECRYPT, key_param.key_mode is HKS_ALG_GCM; + key_param.key_pad is HKS_PADDING_NONE; + CNcomment:与key关联的秘钥的属性,约束条件:key_param.key_type为HKS_KEY_TYPE_AES,key_param.key_len为128或192或256; + key_param.key_usage是HKS_KEY_USAGE_DECRYPT,key_param.key_mode是HKS_ALG_GCM; + key_param.key_pad为HKS_PADDING_NONE。CNend +* @param crypt_param [IN] type #const struct hks_crypt_param *,Vector and additional data used for decryption. + CNcomment:解密使用的向量和附加数据。CNend +* @param plain_text [OUT] type #struct hks_blob *,Data plaintext。CNcomment:数据明文。CNend +* @param cipher_text_with_tag [IN] type #const struct hks_blob *,Data ciphertext CNcomment:数据密文。CNend +* @retval #0 Success. +* @retval #Other Failure. +* @par 依赖: +* @li hks_types.h:describes hks_types SDK interfaces.CNcomment:描述hks_types SDK的接口。CNend +* @see hks_aead_decrypt +*/ +HKS_DLL_API_PUBLIC int32_t hks_aead_decrypt(const struct hks_blob *key, + const struct hks_key_param *key_param, + const struct hks_crypt_param *crypt_param, + struct hks_blob *plain_text, + const struct hks_blob *cipher_text_with_tag); + +/** +* @ingroup iot_hks +* @brief Key negotiation using X25519 algorithm. CNcomment:使用X25519算法进行秘钥协商。CNend +* +* @par 描述: +* Key negotiation using X25519 algorithm. CNcomment:使用X25519算法进行秘钥协商。CNend +* +* @attention None +* @param agreed_key [OUT] type #struct hks_blob *,Negotiation key calculated through X25519. + CNcomment:通过X25519计算出来的协商秘钥。CNend +* @param private_key_param [IN] type #const struct hks_key_param *,Local private key private_key attributes. + constraint condition:private_key_param.key_type is HKS_KEY_TYPE_ECC_KEYPAIR_CURVE25519 + private_key_param.key_usage is HKS_KEY_USAGE_DERIVE + private_key_param.key_mode is the same as agreement_alg + CNcomment:本端私钥private_key的属性,约束条件:private_key_param.key_type为HKS_KEY_TYPE_ECC_KEYPAIR_CURVE25519 + private_key_param.key_usage是HKS_KEY_USAGE_DERIVE + private_key_param.key_mode与Agreement_alg相同。CNend +* @param agreement_alg [IN] type #const uint32_t, + Algorithm for further deriving secret key based on negotiation secret key. + CNcomment:基于协商秘钥进一步派生秘钥的算法。CNend +* @param private_key [IN] type #const struct hks_blob *,Local X25519 private key。 + CNcomment:本端X25519私钥。CNend +* @param peer_public_key [IN] type #const struct hks_blob *,Peer X25519 public key + CNcomment:对端X25519公钥。CNend +* @retval #0 Success. +* @retval #Other Failure. +* @par 依赖: +* @li hks_types.h:describes hks_types SDK interfaces.CNcomment:描述hks_types SDK的接口。CNend +* @see hks_key_agreement +*/ +HKS_DLL_API_PUBLIC int32_t hks_key_agreement(struct hks_blob *agreed_key, + const struct hks_key_param *private_key_param, + const uint32_t agreement_alg, const struct hks_blob *private_key, + const struct hks_blob *peer_public_key); + +/** +* @ingroup iot_hks +* @brief Key derivation. CNcomment:秘钥派生。CNend +* +* @par 描述: +* Derive the key using HKD512 algorithm based on SHA512. + The currently derived key is only used for AES encryption and decryption. + CNcomment:使用基于SHA512的HKDF算法派生秘钥,当前派生的秘钥仅用于AES加解密。CNend +* +* @attention None +* @param derived_key [OUT] type #struct hks_blob *,Derived key calculated through HKDF , + derived_key and data cannot be null, and size >= 16. + CNcomment:通过HKDF计算出来的派生秘钥 named_key和data不能为null,且大小> = 16。CNend +* @param key_param [IN] type #const struct hks_key_param *,Properties for derived keys constraint condition: + key_param.key_type is HKS_KEY_TYPE_DERIVE,key_param.key_usage is HKS_KEY_USAGE_DERIVE + key_param.key_mode is hks_alg_hkdf(HKS_ALG_HASH_SHA_256) or hks_alg_hkdf(HKS_ALG_HASH_SHA_512) + key_param.key_len is 128 or 256. + CNcomment:派生秘钥对应的属性,约束条件: + key_param.key_type为HKS_KEY_TYPE_DERIVE,key_param.key_usage为HKS_KEY_USAGE_DERIVE + key_param.key_mode为hks_alg_hkdf(HKS_ALG_HASH_SHA_256)或hks_alg_hkdf(HKS_ALG_HASH_SHA_512) + key_param.key_len是128或256。。CNend +* @param kdf_key [IN] type #const struct hks_blob *,The base key used to derive the key. + CNcomment:用于派生秘钥的基础秘钥。CNend +* @param salt [IN] type #const struct hks_blob *, + Derived salt value,salt.size must be greater than or equal to 16。 + CNcomment:派生使用的盐值,salt.size必须大于或等于16。CNend +* @param label [IN] type #const struct hks_blob *,Derived label,constraint condition: + lable.size must be greater than or equal to 16 + CNcomment:派生使用的label,约束条件:lable.size必须大于或等于16。CNend +* @retval #0 Success. +* @retval #Other Failure. +* @par 依赖: +* @li hks_types.h:describes hks_types SDK interfaces.CNcomment:描述hks_types SDK的接口。CNend +* @see hks_key_derivation +*/ +HKS_DLL_API_PUBLIC int32_t hks_key_derivation(struct hks_blob *derived_key, + const struct hks_key_param *key_param, const struct hks_blob *kdf_key, + const struct hks_blob *salt, const struct hks_blob *label); + +/** +* @ingroup iot_hks +* @brief Generate message authentication code (MAC) based on SHA256 or SHA512. + CNcomment:基于SHA256或SHA512生成消息验证码(MAC)。CNend +* +* @par 描述: +* Generate message authentication code (MAC) based on SHA256 or SHA512. + CNcomment:基于SHA256或SHA512生成消息验证码(MAC)。CNend +* +* @attention None +* @param key [IN] type #const struct hks_blob *,Keys involved in calculating HMAC, + data cannot be null,and size > 0. + CNcomment:参与计算HMAC的秘钥,数据不能为null,大小> 0。CNend +* @param alg [IN] type #const uint32_t,HMAC algorithm hks_alg_hmac(HKS_ALG_HASH_SHA_256) or + (HKS_ALG_HASH_SHA_512). + CNcomment:HMAC算法, hks_alg_hmac(HKS_ALG_HASH_SHA_256)或 (HKS_ALG_HASH_SHA_512)。CNend +* @param src_data [IN] type #const struct hks_blob *,src data data cannot be null, and size > 0. + CNcomment:源数据,数据不能为null,大小> 0。CNend +* @param output [OUT] type #struct hks_blob *,Generated message verification code, + output and output->data cannot be null constraint condition: + when alg is hks_alg_hmac(HKS_ALG_HASH_SHA_256), output->size must be greater than or + equal to 32 when alg is hks_alg_hmac(HKS_ALG_HASH_SHA_512), output->size must be greater than or equal to 64 + CNcomment:生成的消息验证码,输出和输出->数据不能为空约束条件: + 当alg为hks_alg_hmac(HKS_ALG_HASH_SHA_256)时,output-> size必须大于或 + 当alg为hks_alg_hmac(HKS_ALG_HASH_SHA_512)时等于32,则output-> size必须大于或等于64。CNend +* @retval #0 Success. +* @retval #Other Failure. +* @par 依赖: +* @li hks_types.h:describes hks_types SDK interfaces.CNcomment:描述hks_types SDK的接口。CNend +* @see hks_hmac +*/ +HKS_DLL_API_PUBLIC int32_t hks_hmac(const struct hks_blob *key, + const uint32_t alg, const struct hks_blob *src_data, + struct hks_blob *output); + +/** +* @ingroup iot_hks +* @brief Calculate the hash value of the data based on SHA256 or SHA512. + CNcomment:基于SHA256或SHA512计算数据的散列值。CNend +* +* @par 描述: +* Calculate the hash value of the data based on SHA256 or SHA512. + CNcomment:基于SHA256或SHA512计算数据的散列值。CNend +* +* @attention None +* @param alg [IN] type #const uint32_t,Hash algorithm, Only spuuort SHA256/SHA512. + CNcomment:哈希算法,仅支持SHA256 / SHA512。CNend +* @param src_data [IN] type #const struct hks_blob *,src data data cannot be null, and size > 0. + CNcomment:源数据,数据不能为null,大小> 0。CNend +* @param hash [OUT] type #struct hks_blob *,Generated message verification code , + hash and hash->data cannot be null constraint condition: + when alg is HKS_ALG_HASH_SHA_256, hash->size must be greater than or equal to 32 when alg is HKS_ALG_HASH_SHA_512, + hash->size must be greater than or equal to 64. + CNcomment:生成的消息验证码,hash和hash-> data不能为null约束条件:当alg为HKS_ALG_HASH_SHA_256时, + 当alg为HKS_ALG_HASH_SHA_512时,hash-> size必须大于或等于32,hash-> size必须大于或等于64。CNend +* @retval #0 Success. +* @retval #Other Failure. +* @par 依赖: +* @li hks_types.h:describes hks_types SDK interfaces.CNcomment:描述hks_types SDK的接口。CNend +* @see hks_hash +*/ +HKS_DLL_API_PUBLIC int32_t hks_hash(const uint32_t alg, + const struct hks_blob *src_data, struct hks_blob *hash); + +/** +* @ingroup iot_hks +* @brief Unsigned large integer modulo operation. CNcomment:无符号大整数模运算。CNend +* +* @par 描述: +* Unsigned large integer modulo operation. CNcomment:无符号大整数模运算。CNend +* +* @attention None +* @param x [OUT] type #struct hks_blob *,Modular result,x and x->data cannot be null, x->size >= n.size. + CNcomment:模运算结果,x和x-> data不能为null,x-> size> = n.size。CNend +* @param a [IN] type #const struct hks_blob *,Base data data cannot be null, size > 0. + CNcomment:底数, 数据不能为null,大小> 0。CNend +* @param e [IN] type #const struct hks_blob *,data cannot be null, size > 0. + CNcomment:幂, 数据不能为null,大小> 0。CNend +* @param n [IN] type #const struct hks_blob *,Modulus, data cannot be null, size > 0. + CNcomment:模数, 数据不能为null,大小> 0。CNend +* @retval #0 Success. +* @retval #Other Failure. +* @par 依赖: +* @li hks_types.h:describes hks_types SDK interfaces.CNcomment:描述hks_types SDK的接口。CNend +* @see hks_bn_exp_mod +*/ +HKS_DLL_API_PUBLIC int32_t hks_bn_exp_mod(struct hks_blob *x, + const struct hks_blob *a, const struct hks_blob *e, + const struct hks_blob *n); + +/** +* @ingroup iot_hks +* @brief Get public key alias list Interface. CNcomment:获取公钥别名列表接口。CNend +* +* @par 描述: +* Get public key alias list Interface. CNcomment:获取公钥别名列表接口。CNend +* +* @attention None +* @param key_alias_list [OUT] type #struct hks_blob *,struct hks_blob array, alloc and free memory by the caller. + CNcomment:用于存放别名,struct hks_blob数组,调用者分配和释放内存。CNend +* @param list_count [IN] type #uint32_t *,Indicates the number of available hks_blob_t caches, + public key alias number, alloc and free memory by the caller. + CNcomment:表示可用的hks_blob_t缓存数量,调用方的公钥别名号,分配和可用内存。CNend +* @retval #0 Success. +* @retval #Other Failure. +* @par 依赖: +* @li hks_types.h:describes hks_types SDK interfaces.CNcomment:描述hks_types SDK的接口。CNend +* @see hks_get_pub_key_alias_list +*/ +HKS_DLL_API_PUBLIC int32_t hks_get_pub_key_alias_list( + struct hks_blob *key_alias_list, uint32_t *list_count); + +/** +* @ingroup iot_hks +* @brief generate symmetric key. CNcomment:生成对称密钥。CNend +* +* @par 描述: +* generate symmetric key,Only AES-128/AES-192/AES-256 key generation is supported. + CNcomment:生成对称密钥,仅支持AES-128 / AES-192 / AES-256密钥生成。CNend +* +* @attention None +* @param output_key [OUT] type #struct hks_blob *,Key obtained.CNcomment:获取的key。CNend +* @param key_param [IN] type #const struct hks_key_param *,Need to generate key parameters. + CNcomment:需要生成key的参数。CNend +* @retval #0 Success. +* @retval #Other Failure. +* @par 依赖: +* @li hks_types.h:describes hks_types SDK interfaces.CNcomment:描述hks_types SDK的接口。CNend +* @see hks_generate_symmetric_key +*/ +HKS_DLL_API_PUBLIC int32_t hks_generate_symmetric_key(struct hks_blob *output_key, + const struct hks_key_param *key_param); + +/** +* @ingroup iot_hks +* @brief AES encryption, requires the use of the AES symmetric key generated above as an input parameter, + supports GCM CCM CBC mode, key length 128/192/256. + CNcomment:AES加密,要求使用上述生成AES对称的密钥作为入参,支持GCM CCM CBC模式,key长度128/192/256。CNend +* +* @par 描述: +* AES encryption, requires the use of the AES symmetric key generated above as an input parameter, + supports GCM CCM CBC mode, key length 128/192/256. + CNcomment:AES加密,要求使用上述生成AES对称的密钥作为入参,支持GCM CCM CBC模式,key长度128/192/256。CNend +* +* @attention None +* @param key [IN] type #const struct hks_blob *,The key required for encryption, + the key to generate the AES symmetric key output as an input parameter. + CNcomment:加密所需密钥,需要为生成AES对称密钥输出的key作为入参。CNend +* @param key_param [IN] type #const struct hks_key_param *,Encryption key parameters. + CNcomment:加密密钥参数。CNend +* @param crypt_param [IN] type #const struct hks_crypt_param *,Encrypted information. CNcomment:加密信息。CNend +* @param plain_text [IN] type #const struct hks_blob *,plain_text.CNcomment:明文。CNend +* @param cipher_text_with_tag [OUT] type #struct hks_blob *,Encrypted ciphertext.CNcomment:加密后密文。CNend +* @retval #0 Success. +* @retval #Other Failure. +* @par 依赖: +* @li hks_types.h:describes hks_types SDK interfaces.CNcomment:描述hks_types SDK的接口。CNend +* @see hks_symmetric_encrypt +*/ +HKS_DLL_API_PUBLIC int32_t hks_symmetric_encrypt(const struct hks_blob *key, + const struct hks_key_param *key_param, const struct hks_crypt_param *crypt_param, + const struct hks_blob *plain_text, struct hks_blob *cipher_text_with_tag); + +/** +* @ingroup iot_hks +* @brief AES decryption, requires the use of the above generated AES symmetric key as an input parameter, + supports GCM CCM CBC mode, key length 128/192/256. + CNcomment:AES解密,要求使用上述生成AES对称的密钥作为入参,支持GCM CCM CBC模式,key长度128/192/256。CNend +* +* @par 描述: +* AES decryption, requires the use of the above generated AES symmetric key as an input parameter, + supports GCM CCM CBC mode, key length 128/192/256. + CNcomment:AES解密,要求使用上述生成AES对称的密钥作为入参,支持GCM CCM CBC模式,key长度128/192/256。CNend +* +* @attention None +* @param key [IN] type #const struct hks_blob *,The key required for decryption needs to be the + input key for generating the AES symmetric key output. + CNcomment:解密所需密钥,需要为生成AES对称密钥输出的key作为入参。CNend +* @param key_param [IN] type #const struct hks_key_param *,decrypt key parameters. + CNcomment:解密密钥参数。CNend +* @param crypt_param [IN] type #const struct hks_crypt_param *,Decrypt information. CNcomment:解密信息。CNend +* @param plain_text [OUT] type #const struct hks_blob *,Plaintext after decryption.CNcomment:解密后明文。CNend +* @param cipher_text_with_tag [IN] type #struct hks_blob *,Ciphertext.CNcomment:密文。CNend +* @retval #0 Success. +* @retval #Other Failure. +* @par 依赖: +* @li hks_types.h:describes hks_types SDK interfaces.CNcomment:描述hks_types SDK的接口。CNend +* @see hks_symmetric_encrypt +*/ +HKS_DLL_API_PUBLIC int32_t hks_symmetric_decrypt(const struct hks_blob *key, + const struct hks_key_param *key_param, const struct hks_crypt_param *crypt_param, + struct hks_blob *plain_text, const struct hks_blob *cipher_text_with_tag); + +/** +* @ingroup iot_hks +* @brief get security capabilites. CNcomment:获得安全功能。CNend +* +* @par 描述: +* Get device security attributes, output as a json string, you can get information such as the + algorithm type supported by the device certificate. + CNcomment:获取设备安全属性,输出为json串,可以获取设备证书支持的算法类型等信息。CNend +* +* @attention None +* @param flag [IN] type #uint32_t,Reserved field, no assignment is required. + CNcomment:预留字段,当前不需要赋值。CNend +* @param capabilities [OUT] type #struct hks_blob *,Information obtained.CNcomment:获取到的信息。CNend +* @retval #0 Success. +* @retval #Other Failure. +* @par 依赖: +* @li hks_types.h:describes hks_types SDK interfaces.CNcomment:描述hks_types SDK的接口。CNend +* @see hks_get_security_capabilites +*/ +HKS_DLL_API_PUBLIC int32_t hks_get_security_capabilites(uint32_t flag, struct hks_blob *capabilities); + +/** +* @ingroup iot_hks +* @brief export device certs. CNcomment:导出设备证书。CNend +* +* @par 描述: +* export device certs. CNcomment:导出设备证书。CNend +* +* @attention None +* @param key_id [IN] type #uint8_t,Array index of device_identity field obtained with + hks_get_security_capabilites. + CNcomment:使用hks_get_security_capabilites获取的device_identity字段的数组下标。CNend +* @param cert_chain [OUT] type #hks_cert_chain *,Export certificate information. + CNcomment:导出证书信息。CNend +* @retval #0 Success. +* @retval #Other Failure. +* @par 依赖: +* @li hks_types.h:describes hks_types SDK interfaces.CNcomment:描述hks_types SDK的接口。CNend +* @see hks_export_device_certs +*/ +HKS_DLL_API_PUBLIC int32_t hks_export_device_certs(uint8_t key_id, struct hks_cert_chain *cert_chain); + +/** +* @ingroup iot_hks +* @brief sign with device key. CNcomment:用设备私钥签名。CNend +* +* @par 描述: +* sign with device key. CNcomment:用设备私钥签名。CNend +* +* @attention None +* @param key_id [IN] type #uint8_t,Array index of device_identity field obtained with + hks_get_security_capabilites. + CNcomment:使用hks_get_security_capabilites获取的device_identity字段的数组下标。CNend +* @param usage [IN] type #const struct hks_usage_spec *,Signing required parameters. + CNcomment:签名所需参数。CNend +* @param challenge [IN] type #const struct hks_blob *,Data to be signed. + CNcomment:待签名的数据。CNend +* @param signature [OUT] type #struct hks_blob *,Output data signature. + CNcomment:输出的数据签名。CNend +* @retval #0 Success. +* @retval #Other Failure. +* @par 依赖: +* @li hks_types.h:describes hks_types SDK interfaces.CNcomment:描述hks_types SDK的接口。CNend +* @see hks_sign_with_device_key +*/ +HKS_DLL_API_PUBLIC int32_t hks_sign_with_device_key(uint8_t key_id, + const struct hks_usage_spec *usage, const struct hks_blob *challenge, struct hks_blob *signature); + + +#ifdef __cplusplus +} +#endif + +#endif /* HKS_CLIENT_H */ diff --git a/sdk_liteos/include/hks_device_provision.h b/sdk_liteos/include/hks_device_provision.h new file mode 100644 index 0000000000000000000000000000000000000000..a56195b9bd38db1a3ca6a7f1d38ac0e2151799a1 --- /dev/null +++ b/sdk_liteos/include/hks_device_provision.h @@ -0,0 +1,65 @@ +/** + * @file hks_device_provision.h + * + * Copyright (c) 2020 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Description: device pki provision, verify; efuse write, verify function \n + * Author: Huawei \n + * Create: 2020-03-26 + */ + + /** + * @defgroup iot_hks + * @ingroup hks + */ + +#ifndef HKS_DEVICE_PROVISION_H +#define HKS_DEVICE_PROVISION_H + +#include "hks_types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** +* @ingroup iot_hks +* @brief Production write efuse and certificate import verification function. + CNcomment:产线写入efuse和证书导入验证功能。CNend +* +* @par 描述: +* Production write efuse and certificate import verification function. + CNcomment:产线写入efuse和证书导入验证功能。CNend +* +* @attention None +* @param cmd [IN] type #uint32_t,Command word id. CNcomment: 命令字id。CNend +* @param input [IN] type #const struct hks_blob *,keybox data for pki provision function; + common name information for certificate. + CNcomment:证书导入keybox数据或者为证书common name信息。CNend +* @param output [OUT] type #struct hks_blob *,reserved parameters, not used. CNcomment:保留参数,暂不使用。CNend +* @retval #0 Success. +* @retval #Other Failure. +* @par 依赖: +* @li hks_types.h:describes hks_types SDK interfaces.CNcomment:描述hks_types SDK的接口。CNend +* @see hks_pki_provision +*/ +HKS_DLL_API_PUBLIC int32_t hks_pki_provision(uint32_t cmd, const struct hks_blob *input, struct hks_blob *output); + +#ifdef __cplusplus +} +#endif + +#endif /* HKS_DEVICE_PROVISION_H */ diff --git a/sdk_liteos/include/hks_errno.h b/sdk_liteos/include/hks_errno.h new file mode 100755 index 0000000000000000000000000000000000000000..12120eb186ccf5cb9fa61e671b50df731c9a5726 --- /dev/null +++ b/sdk_liteos/include/hks_errno.h @@ -0,0 +1,125 @@ +/** + * @file hks_errno.h + * + * Copyright (c) 2020 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @defgroup iot_hks + * @ingroup hks + */ + +#ifndef HKS_ERRNO_H +#define HKS_ERRNO_H + +#include "hks_types.h" + +/* MBEDTLS_SUCCESS */ +#define HKS_SUCCESS ((int32_t)0) +/* MBEDTLS_ERROR_UNKNOWN_ERROR */ +#define HKS_FAILURE ((int32_t)-132) +/* MBEDTLS_ERROR_NOT_PERMITTED */ +#define HKS_ERROR_NOT_PERMITTED ((int32_t)-133) +/* MBEDTLS_ERROR_NOT_SUPPORTED */ +#define HKS_ERROR_NOT_SUPPORTED ((int32_t)-134) +/* MBEDTLS_ERROR_INVALID_ARGUMENT */ +#define HKS_ERROR_INVALID_ARGUMENT ((int32_t)-135) +/* MBEDTLS_ERROR_INVALID_HANDLE */ +#define HKS_ERROR_INVALID_HANDLE ((int32_t)-136) +/* MBEDTLS_ERROR_BAD_STATE */ +#define HKS_ERROR_BAD_STATE ((int32_t)-137) +/* MBEDTLS_ERROR_BUFFER_TOO_SMALL */ +#define HKS_ERROR_BUFFER_TOO_SMALL ((int32_t)-138) +/* MBEDTLS_ERROR_OCCUPIED_SLOT */ +#define HKS_ERROR_OCCUPIED_SLOT ((int32_t)-139) +/* MBEDTLS_ERROR_EMPTY_SLOT */ +#define HKS_ERROR_EMPTY_SLOT ((int32_t)-140) +/* MBEDTLS_ERROR_INSUFFICIENT_MEMORY */ +#define HKS_ERROR_INSUFFICIENT_MEMORY ((int32_t)-141) +/* MBEDTLS_ERROR_INSUFFICIENT_STORAGE */ +#define HKS_ERROR_INSUFFICIENT_STORAGE ((int32_t)-142) +/* MBEDTLS_ERROR_INSUFFICIENT_CAPACITY */ +#define HKS_ERROR_INSUFFICIENT_CAPACITY ((int32_t)-143) +/* MBEDTLS_ERROR_COMMUNICATION_FAILURE */ +#define HKS_ERROR_COMMUNICATION_FAILURE ((int32_t)-145) +/* MBEDTLS_ERROR_STORAGE_FAILURE */ +#define HKS_ERROR_STORAGE_FAILURE ((int32_t)-146) +/* MBEDTLS_ERROR_HARDWARE_FAILURE */ +#define HKS_ERROR_HARDWARE_FAILURE ((int32_t)-147) +/* MBEDTLS_ERROR_INSUFFICIENT_ENTROPY */ +#define HKS_ERROR_INSUFFICIENT_ENTROPY ((int32_t)-148) +/* MBEDTLS_ERROR_INVALID_SIGNATURE */ +#define HKS_ERROR_INVALID_SIGNATURE ((int32_t)-149) +/* MBEDTLS_ERROR_INVALID_PADDING */ +#define HKS_ERROR_INVALID_PADDING ((int32_t)-150) +/* MBEDTLS_ERROR_TAMPERING_DETECTED */ +#define HKS_ERROR_TAMPERING_DETECTED ((int32_t)-151) +/* MBEDTLS_ERROR_DATA_CORRUPT */ +#define HKS_ERROR_DATA_CORRUPT ((int32_t)-152) +#define HKS_ERROR_MBEDTLS_RANGE_MIN ((int32_t)-153) + +/* + * Error code for hks + * Add new error code before HKS_ERROR_RANGE_MIN + * Modify the value of HKS_ERROR_RANGE_MIN when adding an error code + * The value of HKS_ERROR_RANGE_MIN = The value of new error code - 1 + * Such as add HKS_ERROR_XXX(-1015),must modify HKS_ERROR_RANGE_MIN to be -1016 + */ +#define HKS_STATUS_OK ((int32_t)0) +#define HKS_ERROR_NULL_POINTER ((int32_t)-1000) +#define HKS_ERROR_DUPLICATED_REG ((int32_t)-1001) +#define HKS_ERROR_FILE_SIZE_FAIL ((int32_t)-1002) +#define HKS_ERROR_READ_FILE_FAIL ((int32_t)-1003) +#define HKS_ERROR_INVALID_PUBLIC_KEY ((int32_t)-1004) +#define HKS_ERROR_INVALID_PRIVATE_KEY ((int32_t)-1005) +#define HKS_ERROR_INVALID_KEY_INFO ((int32_t)-1006) +#define HKS_ERROR_BUF_TOO_SMALL ((int32_t)-1007) +#define HKS_ERROR_UNKNOWN_ERROR ((int32_t)-1008) +#define HKS_ERROR_ASSERT_FAIL ((int32_t)-1009) +#define HKS_ERROR_KEY_NOT_EXIST ((int32_t)-1010) +#define HKS_ERROR_HASH_NOT_EQUAL ((int32_t)-1011) +#define HKS_ERROR_MALLOC_FAIL ((int32_t)-1012) +#define HKS_ERROR_WRITE_FILE_FAIL ((int32_t)-1013) +#define HKS_ERROR_REMOVE_FILE_FAIL ((int32_t)-1014) +#define HKS_ERROR_INVALID_KEY_FILE ((int32_t)-1015) +#define HKS_ERROR_IPC_INITIAL_FAIL ((int32_t)-1016) +#define HKS_ERROR_GET_KEY_PARAM_FAIL ((int32_t)-1017) +#define HKS_ERROR_AES_ENCRYPT_FAIL ((int32_t)-1018) +#define HKS_ERROR_AES_DECRYPT_FAIL ((int32_t)-1019) +#define HKS_ERROR_SIGN_FAIL ((int32_t)-1020) +#define HKS_ERROR_VERIFY_FAIL ((int32_t)-1021) +#define HKS_ERROR_EXPORT_FAIL ((int32_t)-1022) +#define HKS_ERROR_IMPORT_FAIL ((int32_t)-1023) +#define HKS_ERROR_WRAP_FAIL ((int32_t)-1024) +#define HKS_ERROR_UNWRAP_FAIL ((int32_t)-1025) +#define HKS_ERROR_DELETE_FAIL ((int32_t)-1026) +#define HKS_ERROR_GENERATE_ASYM_FAIL ((int32_t)-1027) +#define HKS_ERROR_GENERATE_SYM_FAIL ((int32_t)-1028) +#define HKS_ERROR_KEY_ATTEST_FAIL ((int32_t)-1029) +#define HKS_ERROR_CERT_CHAIN_FAIL ((int32_t)-1030) +#define HKS_ERROR_GET_KEY_LIST_FAIL ((int32_t)-1031) +#define HKS_ERROR_RANGE_MIN ((int32_t)-1032) +#define HKS_ERROR_CERT_NOT_EXIST ((int32_t)-1033) +#define HKS_ERROR_INVALID_PKI_FILE ((int32_t)-1034) +#define HKS_ERROR_CERT_VERIFY_FAIL ((int32_t)-1035) +#define HKS_ERROR_WB_DECRYPT_FAIL ((int32_t)-1036) +#define HKS_ERROR_EFUSE_WRITE_FAIL ((int32_t)-1037) +#define HKS_ERROR_EFUSE_READ_FAIL ((int32_t)-1038) +#define HKS_ERROR_EFUSE_LOCK_FAIL ((int32_t)-1039) +#define HKS_ERROR_INTERNAL_UNKOWN ((int32_t)-9999) +#define HKS_ERROR_IPC_RANGE_MIN ((int32_t)65536) +#define HKS_ERROR_IPC_RANGE_MAX ((int32_t)65556) +#define HKS_ERROR_PERMISSION_DENIED ((int32_t)0xFF07) + +#endif /* HKS_ERRNO_H */ diff --git a/sdk_liteos/include/hks_file_api.h b/sdk_liteos/include/hks_file_api.h new file mode 100644 index 0000000000000000000000000000000000000000..0ffe37e685dd5b3b65201da81da6cf96561a3b52 --- /dev/null +++ b/sdk_liteos/include/hks_file_api.h @@ -0,0 +1,96 @@ +/** + * @file hks_file_api.h + * + * Copyright (c) 2020 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @defgroup iot_hks + * @ingroup hks + */ + +#ifndef _HKS_FILE_API_H +#define _HKS_FILE_API_H + +#include +#include "hks_types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +struct hks_flash_operation_callbacks { + /** + * @ingroup iot_hks + * @brief Read data from flash. CNcomment:从flash读取数据。CNend + * + * @par 描述: + * Read data from flash. CNcomment:从flash读取数据。CNend + * + * @attention None + * @param buf [OUT] type #uint8_t *,The buffer used to store the content readed from flash. + CNcomment:用于存储从闪存读取的内容的缓冲区。CNend + * @param len [IN] type #uint32_t,The size count in buffer trying to read from flash. + CNcomment:尝试从闪存读取的缓冲区中的大小计数。CNend + * @retval #0 Success. + * @retval # < 0 Failure. + * @par 依赖: + * @li hks_file_api.h:describes hks_types SDK interfaces.CNcomment:描述hks_types SDK的接口。CNend + * @see read_flash + */ + int32_t (*read_flash)(uint8_t *buf, uint32_t len); + + /** + * @ingroup iot_hks + * @brief Write data into flash. CNcomment:将数据写入闪存。CNend + * + * @par 描述: + * Write data into flash. CNcomment:将数据写入闪存。CNend + * + * @attention None + * @param buf [IN] type #uint8_t *,The content which you want write into the file. + CNcomment:要写入文件的内容。CNend + * @param len [IN] type #uint32_t,The size of the content.CNcomment:要写入的内容大小。CNend + * @retval #0 Success. + * @retval # < 0 Failure. + * @par 依赖: + * @li hks_file_api.h:describes hks_types SDK interfaces.CNcomment:描述hks_types SDK的接口。CNend + * @see read_flash + */ + int32_t (*write_flash)(const uint8_t *buf, uint32_t len); +}; + +/** +* @ingroup iot_hks +* @brief register flash operation callbacks. CNcomment:注册flash操作回调函数。CNend +* +* @par 描述: +* register flash operation callbacks. CNcomment:注册flash操作回调函数。CNend +* +* @attention None +* @param callbacks [IN] type #struct hks_flash_operation_callbacks *,Registered callback function. + CNcomment:注册的回调函数。CNend +* @retval #0 Success. +* @retval #Other Failure. +* @par 依赖: +* @li hks_file_api.h:describes hks_types SDK interfaces.CNcomment:描述hks_types SDK的接口。CNend +* @see hks_register_flash_operation_callbacks +*/ +HKS_DLL_API_PUBLIC int32_t hks_register_flash_operation_callbacks(struct hks_flash_operation_callbacks *callbacks); + +#ifdef __cplusplus +} +#endif + +#endif /* _HKS_FILE_API_H */ diff --git a/sdk_liteos/include/hks_types.h b/sdk_liteos/include/hks_types.h new file mode 100644 index 0000000000000000000000000000000000000000..e997b7daf5ebce6253d8616f408dffbf585227eb --- /dev/null +++ b/sdk_liteos/include/hks_types.h @@ -0,0 +1,284 @@ +/** + * @file hks_types.h + * + * Copyright (c) 2020 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @defgroup iot_hks + * @ingroup hks + */ + +#ifndef HKS_TYPES_H +#define HKS_TYPES_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef HKS_API_PUBLIC +#if defined(WIN32) || defined(_WIN32) || defined(__CYGWIN__) +#ifdef HKS_DLL_EXPORT +#define HKS_DLL_API_PUBLIC __declspec(dllexport) +#else +#define HKS_DLL_API_PUBLIC __declspec(dllimport) +#endif +#else +#define HKS_DLL_API_PUBLIC __attribute__ ((visibility("default"))) +#endif +#else +#define HKS_DLL_API_PUBLIC __attribute__ ((visibility("default"))) +#endif + +#define HKS_SDK_VERSION "1.0.0.10" +#define HKS_BOOL_FALSE 0 +#define HKS_BOOL_TRUE 1 +#define HKS_ALIAS_MAX_SIZE 64 +#define HKS_SALT_MAX_SIZE 16 +#define HKS_NONCE_MIN_SIZE 7 +#define HKS_KEY_BYTES_CURVE25519 32 +#define HKS_RANDOM_MAX_LEN 1024 +#define HKS_MAX_KEY_LEN_128 128 +#define HKS_MAX_KEY_LEN_192 192 +#define HKS_MAX_KEY_LEN_256 256 +#define HKS_KEY_DERIVE_LEN 32 +#define HKS_BINARY_OF_DEC 10 +#define HKS_BINARY_OF_HEX 16 +#define HKS_HASH256_MIN_OUT_SIZE 32 +#define HKS_HASH512_MIN_OUT_SIZE 64 +#define HKS_DERIVED_KEY_MIN_OUT_SIZE 16 +#define HKS_BITS_PER_BYTES 8 +#define HKS_SIGNATURE_MIN_SIZE 64 +#define HKS_RSA2048_SIGNATURE_SIZE 256 +#define HKS_PUBLIC_BYTES_ED25519 32 +#define HKS_PRIVATE_BYTES_ED25519 64 +#define HKS_KEY_PAIR_CIPHER_ED25519 80 +#define HKS_HEADER_HASH_SIZE 64 +#define HKS_AUTH_ID_MAX_SIZE 64 +#define HKS_KEY_LEN_RSA_KEYPAIR 2048 +#define HKS_CHALLENGE_MIN_LEN 16 +#define HKS_CHALLENGE_MAX_LEN 128 +#define HKS_ENCRYPTED_KEY_TAG_LEN 16 +#define HKS_ENCRYPTED_KEY_NONCE_LEN 16 +#define HKS_ENCRYPTED_KEY_AAD_LEN 16 + +/* AES encrypt tag max length */ +#define HKS_ENCRYPT_MAX_TAG_SIZE ((uint8_t)32) + +/* Data blob type and related macros */ +#define HKS_BLOB_TYPE_RAW ((uint8_t)0x00) +#define HKS_BLOB_TYPE_ALIAS ((uint8_t)0x01) +#define HKS_BLOB_TYPE_KEY ((uint8_t)0x02) +#define HKS_BLOB_TYPE_ENCRYPTED_KEY ((uint8_t)0x03) +#define HKS_BLOB_TYPE_MESSAGE ((uint8_t)0x04) +#define HKS_BLOB_TYPE_HASH ((uint8_t)0x05) +#define HKS_BLOB_TYPE_MAC ((uint8_t)0x06) +#define HKS_BLOB_TYPE_LABEL ((uint8_t)0x07) +#define HKS_BLOB_TYPE_SIGNATURE ((uint8_t)0x08) +#define HKS_BLOB_TYPE_IV ((uint8_t)0x09) +#define HKS_BLOB_TYPE_AAD ((uint8_t)0x0a) +#define HKS_BLOB_TYPE_SALT ((uint8_t)0x0b) +#define HKS_BLOB_TYPE_PLAIN_TEXT ((uint8_t)0x0c) +#define HKS_BLOB_TYPE_CIPHER_TEXT ((uint8_t)0x0d) +#define HKS_BLOB_TYPE_MATERIAL ((uint8_t)0x0e) +#define HKS_BLOB_TYPE_AUTH_ID ((uint8_t)0x10) +#define HKS_BLOB_TYPE_BUFFER ((uint8_t)0x12) + +struct hks_blob { + uint8_t type; + uint8_t *data; + uint32_t size; +}; + +/* HKS_ECC_CURVE_CURVE25519 */ +#define HKS_ECC_CURVE_CURVE25519 ((uint16_t)0x001d) + +#define HKS_ECC_CURVE_ED25519 ((uint16_t)0x8001) + +#define HKS_KEY_TYPE_RSA_PUBLIC_KEY ((uint32_t)0x60010000) + +#define HKS_KEY_TYPE_RSA_KEYPAIR ((uint32_t)0x70010000) + +#define HKS_KEY_TYPE_ECC_PUBLIC_KEY_BASE ((uint32_t)0x60030000) + +#define HKS_KEY_TYPE_ECC_KEYPAIR_BASE ((uint32_t)0x70030000) + +#define HKS_KEY_TYPE_ECC_CURVE_MASK ((uint32_t)0x0000ffff) + +#define hks_key_type_ecc_public_key(curve) \ + (HKS_KEY_TYPE_ECC_PUBLIC_KEY_BASE | (curve)) + +#define hks_key_type_ecc_key_pair(curve) \ + (HKS_KEY_TYPE_ECC_KEYPAIR_BASE | (curve)) + +#define HKS_KEY_TYPE_ECC_PUBLIC_KEY_CURVE25519 \ + (hks_key_type_ecc_public_key(HKS_ECC_CURVE_CURVE25519)) + +#define HKS_KEY_TYPE_ECC_KEYPAIR_CURVE25519 \ + (hks_key_type_ecc_key_pair(HKS_ECC_CURVE_CURVE25519)) + +#define HKS_KEY_TYPE_EDDSA_PUBLIC_KEY_BASE ((uint32_t)0xe0010000) + +#define HKS_KEY_TYPE_EDDSA_KEYPAIR_BASE ((uint32_t)0xf0010000) + +#define hks_key_type_eddsa_public_key(curve) \ + (HKS_KEY_TYPE_EDDSA_PUBLIC_KEY_BASE | (curve)) + +#define hks_key_type_eddsa_key_pair(curve) \ + (HKS_KEY_TYPE_EDDSA_KEYPAIR_BASE | (curve)) + +#define HKS_KEY_TYPE_EDDSA_PUBLIC_KEY_ED25519 \ + (hks_key_type_eddsa_public_key(HKS_ECC_CURVE_CURVE25519)) + +#define HKS_KEY_TYPE_EDDSA_KEYPAIR_ED25519 \ + (hks_key_type_eddsa_key_pair(HKS_ECC_CURVE_CURVE25519)) + + +#define HKS_KEY_TYPE_AES ((uint32_t)0x40000001) + +#define HKS_KEY_TYPE_HMAC ((uint32_t)0x51000000) + +#define HKS_KEY_TYPE_DERIVE ((uint32_t)0x52000000) + +/* key usage */ +#define HKS_KEY_USAGE_EXPORT ((uint32_t)0x00000001) + +#define HKS_KEY_USAGE_ENCRYPT ((uint32_t)0x00000100) + +#define HKS_KEY_USAGE_DECRYPT ((uint32_t)0x00000200) + +#define HKS_KEY_USAGE_SIGN ((uint32_t)0x00000400) + +#define HKS_KEY_USAGE_VERIFY ((uint32_t)0x00000800) + +#define HKS_KEY_USAGE_DERIVE ((uint32_t)0x00001000) + +/* algorithm padding */ +#define HKS_PADDING_NONE ((uint32_t)0x00000000) +#define HKS_PADDING_PKCS7 ((uint32_t)0x00000001) +#define HKS_PADDING_PSS ((uint32_t)0x00000002) +#define HKS_PADDING_OAEP ((uint32_t)0x00000003) +#define HKS_PADDING_PKCS1_5 ((uint32_t)0x00000004) +#define HKS_PADDING_PKCS2_1 ((uint32_t)0x00000005) + +/* mode */ +#define HKS_MODE_CBC ((uint32_t)0x04600101) + +#define HKS_MODE_GCM ((uint32_t)0x06001002) + +/* hash algorithms */ +#define HKS_ALG_DIGEST_NONE ((uint32_t)0x00000000) + +#define HKS_ALG_HASH_MASK ((uint32_t)0x000000ff) + +#define HKS_ALG_HASH_SHA_1 ((uint32_t)0x01000005) + +#define HKS_ALG_HASH_SHA_256 ((uint32_t)0x01000009) + +#define HKS_ALG_HASH_SHA_384 ((uint32_t)0x0100000a) + +#define HKS_ALG_HASH_SHA_512 ((uint32_t)0x0100000b) + +/* mac algorithms */ +#define HKS_ALG_HMAC_BASE ((uint32_t)0x02800000) + +#define hks_alg_hmac(hash_alg) \ + (HKS_ALG_HMAC_BASE | ((hash_alg) & HKS_ALG_HASH_MASK)) + +/* AEAD algorithms */ +#define HKS_ALG_CCM ((uint32_t)0x06001001) +#define HKS_ALG_GCM ((uint32_t)0x06001002) +#define HKS_ALG_CBC ((uint32_t)0x06001003) + +/* HKDF algorithms */ +#define HKS_ALG_HKDF_BASE ((uint32_t)0x30000100) +#define hks_alg_hkdf(hash_alg) \ + (HKS_ALG_HKDF_BASE | ((hash_alg) & HKS_ALG_HASH_MASK)) + +/* Key agreement/derivation algorithm */ +#define HKS_ALG_SELECT_RAW ((uint32_t)0x31000001) +#define HKS_ALG_ECDH_BASE ((uint32_t)0x22200000) +#define HKS_ALG_KEY_DERIVATION_MASK ((uint32_t)0x010fffff) +#define hks_alg_ecdh(kdf_alg) (HKS_ALG_ECDH_BASE | ((kdf_alg) & HKS_ALG_KEY_DERIVATION_MASK)) + +struct hks_key_param { + uint32_t key_type; /* algorithm */ + uint32_t key_len; + uint32_t key_usage; /* usage */ + uint32_t key_pad; /* Fill mode */ + uint32_t key_mode; /* Group mode */ + uint32_t key_role; /* role */ + uint16_t key_domain; + struct hks_blob key_auth_id; /* auth id */ +}; + +struct hks_crypt_param { + struct hks_blob nonce; /* Nonce value or iv vector */ + struct hks_blob aad; +}; + +/* + * log interface + * tag - modle name, default "HKS" + */ +typedef void(*hks_log_func)(const char *tag, const char *func_name, + const char *format, ...); + +struct hks_log_f_group { + hks_log_func log_info; + hks_log_func log_warn; + hks_log_func log_error; + hks_log_func log_debug; +}; + +struct hks_encrypt_material { + struct hks_blob *cipher_text; + struct hks_blob *nonce_blob; /* Nonce value or iv vector */ + struct hks_blob *aad_blob; + struct hks_blob *plain_text; + struct hks_storage_key_info *key_info; + uint32_t sealing_alg; +}; + +enum hks_pki_cmd_type { + CMD_PKI_PROVISION = 1, + CMD_PKI_VERIFY, + CMD_EFUSE_ROOT_SALT_WRITE, + CMD_EFUSE_ROOT_SALT_VERIFY, +}; + +#define HKS_MAX_CERT_NUM 3 +#define HKS_MIN_SIGNATURE_SIZE 256 +#define HKS_GET_CAPABILITES_SIZE 512 + +struct hks_cert_chain { + uint32_t count; + struct hks_blob *cert; /* cert array list */ +}; + +struct hks_usage_spec { + uint32_t mode; + uint32_t padding; + uint32_t digest; + void *param; /* extended param */ +}; + +#ifdef __cplusplus +} +#endif + +#endif /* HKS_TYPES_H */ diff --git a/sdk_liteos/license/LICENSE b/sdk_liteos/license/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..0450c36f73f0a0811ad4dfdd978c18a5cc425e7e --- /dev/null +++ b/sdk_liteos/license/LICENSE @@ -0,0 +1,14 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ \ No newline at end of file diff --git a/sdk_liteos/license/apache-2.0.txt b/sdk_liteos/license/apache-2.0.txt new file mode 100644 index 0000000000000000000000000000000000000000..4947287f7b5ccb5d1e8b7b2d3aa5d89f322c160d --- /dev/null +++ b/sdk_liteos/license/apache-2.0.txt @@ -0,0 +1,177 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS \ No newline at end of file diff --git a/sdk_liteos/non_factory.mk b/sdk_liteos/non_factory.mk new file mode 100644 index 0000000000000000000000000000000000000000..04ede8be06fe45a89531d388b7c7d8b5b4b80bd4 --- /dev/null +++ b/sdk_liteos/non_factory.mk @@ -0,0 +1,168 @@ +# Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# ֱʹmakeбʹ÷ +# make make all : ɾн±ģ +# make clean : ɾpatchļɵм +# make all_clean : ɾн +# make link : +THIRD_DIR = $(MAIN_TOPDIR)/third_party +U_BOOT_DIR = $(MAIN_TOPDIR)/third_party/u-boot-v2019.07 + +include $(MAIN_TOPDIR)/build/make_scripts/config.mk +include $(MAIN_TOPDIR)/build/make_scripts/config_lib_non_factory.mk + +GCC_PATH := $(dir $(shell which $(CC))) +GCC_LIBPATH := -L$(GCC_PATH)../lib/gcc/riscv32-unknown-elf/$(GCC_VER_NUM) +LIBPATH += $(addprefix -Lbuild/build_tmp/libs/, $(foreach module, $(COMPILE_MODULE), $($(module)_dir))) +ifneq ($(USR_LIBS),) + LIBPATH := $(foreach path, $(LIBPATH), $(patsubst -L%, -L$(MAIN_TOPDIR)/%, $(path))) +endif +COMPILE_MODULE += boot loaderboot +SIGN_CFG = A B +A_SIGN = 0x0040d3c0 +B_SIGN = 0x004f13c0 +FACTORY_SIGN = 0x0054d3c0 + +FIRM_WARE_VER := $(shell if [ $(CONFIG_TARGET_KERNEL_VER) -gt -1 ] && [ $(CONFIG_TARGET_KERNEL_VER) -lt 49 ];then echo $(CONFIG_TARGET_KERNEL_VER);fi;) +ifneq ($(FIRM_WARE_VER), $(CONFIG_TARGET_KERNEL_VER)) +$(error [ERROR]:FIRM_WARE_VER=$(FIRM_WARE_VER) Ranges From 0 To 48) +endif + +BOOT_VER = $(shell if [ $(CONFIG_TARGET_BOOT_VER) -gt -1 ] && [ $(CONFIG_TARGET_BOOT_VER) -lt 17 ];then echo $(CONFIG_TARGET_BOOT_VER);fi;) +ifneq ($(BOOT_VER), $(CONFIG_TARGET_BOOT_VER)) +$(error [ERROR]:BOOT_VER Ranges From 0 To 16) +endif + +ifeq ($(CONFIG_MESH_SUPPORT),y) + LIBS += -lmeshautolink +endif +LIBS := $(filter-out -lboot -lloaderboot, $(LIBS)) +ifeq ($(CONFIG_TARGET_SIG_RSA_V15), y) + SIGN_ALG = 0x0 +else ifeq ($(CONFIG_TARGET_SIG_RSA_PSS), y) + SIGN_ALG = 0x1 +else ifeq ($(CONFIG_TARGET_SIG_ECC), y) + SIGN_ALG = 0x10 +else ifeq ($(CONFIG_TARGET_SIG_SHA256), y) + SIGN_ALG = 0x3F +endif + +OUT_DIRS = $(MAIN_TOPDIR)/$(LOG_PATH) $(MAIN_TOPDIR)/$(CACHE_PATH) $(MAIN_TOPDIR)/$(LINK_PATH) $(MAIN_TOPDIR)/$(NV_PATH) $(MAIN_TOPDIR)/$(BIN_PATH) +all: prepare build_libs nv link check ota + $(Q)echo "< ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ >" + $(Q)echo " BUILD SUCCESS " + $(Q)echo "< ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ >" + +build_libs: + $(Q)$(foreach module, $(COMPILE_MODULE), \ + $(foreach lib, $($(module)_libs), \ + $(MAKE) -C $(MAIN_TOPDIR)/$($(module)_dir) MODULE_DIR=$($(module)_dir) LIB=$(lib) all;)) + +nv: + $(NV_TOOL) $(MAIN_TOPDIR)/$(NV_PATH) $(TARGET_NAME) $(NV_CFG_NAME) + +#link: build_libs nv +link: + $(CC) $(LINK_SCRIPTS_FLAG) -E $(MAIN_TOPDIR)/build/link/system_config.ld.S -o $(MAIN_TOPDIR)/$(LINK_PATH)/system_config.ld -P + +ifeq ($(CONFIG_COMPRESSION_OTA_SUPPORT), y) + $(CC) $(LINK_SCRIPTS_FLAG) -DFLASH_FIRM_START=$(A_SIGN) -E $(MAIN_TOPDIR)/build/link/link.ld.S -o $(MAIN_TOPDIR)/$(LINK_PATH)/link.lds -P + $(LINK) $(LINKFLAGS) $(GCC_LIBPATH) $(sort $(LIBPATH)) -T$(MAIN_TOPDIR)/$(LINK_PATH)/link.lds -Map=$(MAIN_TOPDIR)/$(BIN_PATH)/$(TARGET_NAME).map -o $(MAIN_TOPDIR)/$(BIN_PATH)/$(TARGET_NAME).out --start-group $(LIBS) --end-group + $(OBJCOPY) -O binary $(MAIN_TOPDIR)/$(BIN_PATH)/$(TARGET_NAME).out $(MAIN_TOPDIR)/$(CACHE_PATH)/$(TARGET_NAME).bin + $(OBJDUMP) -d $(MAIN_TOPDIR)/$(BIN_PATH)/$(TARGET_NAME).out >$(MAIN_TOPDIR)/$(BIN_PATH)/$(TARGET_NAME).asm + dd if=$(MAIN_TOPDIR)/$(CACHE_PATH)/$(TARGET_NAME).bin of=$(MAIN_TOPDIR)/$(CACHE_PATH)/$(TARGET_NAME)_base.bin seek=0 count=278 bs=1K + dd if=$(MAIN_TOPDIR)/$(CACHE_PATH)/$(TARGET_NAME).bin of=$(MAIN_TOPDIR)/$(CACHE_PATH)/$(TARGET_NAME)_kernel.bin skip=278 bs=1K +else + $(Q)$(foreach X, $(SIGN_CFG), \ + $(CC) $(LINK_SCRIPTS_FLAG) -DFLASH_FIRM_START=$($(X)_SIGN) -E $(MAIN_TOPDIR)/build/link/link.ld.S -o $(MAIN_TOPDIR)/$(LINK_PATH)/link_$(X).lds -P; \ + $(LINK) $(LINKFLAGS) $(GCC_LIBPATH) $(sort $(LIBPATH)) -T$(MAIN_TOPDIR)/$(LINK_PATH)/link_$(X).lds -Map=$(MAIN_TOPDIR)/$(BIN_PATH)/$(TARGET_NAME)_$(X).map -o $(MAIN_TOPDIR)/$(BIN_PATH)/$(TARGET_NAME)_$(X).out --start-group $(LIBS) --end-group; \ + $(OBJCOPY) -O binary $(MAIN_TOPDIR)/$(BIN_PATH)/$(TARGET_NAME)_$(X).out $(MAIN_TOPDIR)/$(CACHE_PATH)/$(TARGET_NAME)_$(X).bin; \ + $(OBJDUMP) -d $(MAIN_TOPDIR)/$(BIN_PATH)/$(TARGET_NAME)_$(X).out >$(MAIN_TOPDIR)/$(BIN_PATH)/$(TARGET_NAME)_$(X).asm; \ + dd if=$(MAIN_TOPDIR)/$(CACHE_PATH)/$(TARGET_NAME)_$(X).bin of=$(MAIN_TOPDIR)/$(CACHE_PATH)/$(TARGET_NAME)_base_$(X).bin seek=0 count=278 bs=1K; \ + dd if=$(MAIN_TOPDIR)/$(CACHE_PATH)/$(TARGET_NAME)_$(X).bin of=$(MAIN_TOPDIR)/$(CACHE_PATH)/$(TARGET_NAME)_kernel_$(X).bin skip=278 bs=1K; ) +endif + +ota: + $(OTA_TOOL) boot_ota $(TARGET_NAME) $(SIGN_ALG) $(FIRM_WARE_VER) $(BOOT_VER) $(MAIN_TOPDIR)/$(BIN_PATH)/$(TARGET_NAME)_flash_boot_ota.bin usr_output=$(USR_OUTPUT_DIR) +ifeq ($(CONFIG_COMPRESSION_OTA_SUPPORT), y) + $(OTA_TOOL) ota $(TARGET_NAME) $(SIGN_ALG) $(FIRM_WARE_VER) $(BOOT_VER) $(MAIN_TOPDIR)/$(CACHE_PATH)/$(TARGET_NAME)_ota_temp.bin usr_output=$(USR_OUTPUT_DIR) $(MAIN_TOPDIR)/$(CACHE_PATH)/$(TARGET_NAME)_kernel.bin A; + $(OTA_TOOL) burn_bin $(TARGET_NAME) $(SIGN_ALG) $(FIRM_WARE_VER) $(BOOT_VER) $(MAIN_TOPDIR)/$(BIN_PATH)/$(TARGET_NAME)_burn.bin usr_output=$(USR_OUTPUT_DIR) $(MAIN_TOPDIR)/$(CACHE_PATH)/$(TARGET_NAME)_ota_temp.bin; + $(OTA_TOOL) ota_compress $(TARGET_NAME) $(SIGN_ALG) $(FIRM_WARE_VER) $(BOOT_VER) $(MAIN_TOPDIR)/$(BIN_PATH)/$(TARGET_NAME)_ota.bin usr_output=$(USR_OUTPUT_DIR) $(MAIN_TOPDIR)/$(CACHE_PATH)/$(TARGET_NAME)_ota_temp.bin; +else + $(Q)$(foreach X, $(SIGN_CFG), \ + $(OTA_TOOL) ota $(TARGET_NAME) $(SIGN_ALG) $(FIRM_WARE_VER) $(BOOT_VER) $(MAIN_TOPDIR)/$(BIN_PATH)/$(TARGET_NAME)_ota_$X.bin usr_output=$(USR_OUTPUT_DIR) $(MAIN_TOPDIR)/$(CACHE_PATH)/$(TARGET_NAME)_kernel_$(X).bin $X; ) + + $(OTA_TOOL) burn_bin $(TARGET_NAME) $(SIGN_ALG) $(FIRM_WARE_VER) $(BOOT_VER) $(MAIN_TOPDIR)/$(BIN_PATH)/$(TARGET_NAME)_burn.bin usr_output=$(USR_OUTPUT_DIR) $(MAIN_TOPDIR)/$(CACHE_PATH)/$(TARGET_NAME)_kernel_A.bin +endif + +check: link +ifeq ($(CONFIG_COMPRESSION_OTA_SUPPORT), y) + @TARGET_SUM=$(shell sha256sum $(MAIN_TOPDIR)/$(CACHE_PATH)/$(TARGET_NAME)_base.bin | cut -d ' ' -f1) && \ + if [ "$$TARGET_SUM" == '$(BASE_NUM)' ]; \ + then echo "#########BASE BIN IS SAME WITH FIRST COMPILE!#########"; \ + else echo "\033[32m#########BASE BIN IS DIFFERENT WITH FIRST COMPILE!#########\033[0m"; exit 1; fi; +else + $(Q)$(foreach X, $(SIGN_CFG), \ + TARGET_SUM=$(shell sha256sum $(MAIN_TOPDIR)/$(CACHE_PATH)/$(TARGET_NAME)_base_$(X).bin | cut -d ' ' -f1) && \ + if [ "$$TARGET_SUM" == '$(BASE_NUM)' ]; \ + then echo "#########BASE BIN IS SAME WITH FIRST COMPILE!#########"; \ + else echo "\033[32m#########BASE BIN IS DIFFERENT WITH FIRST COMPILE!#########\033[0m"; exit 1; fi; ) +endif + +prepare: + $(Q)$(foreach x, $(OUT_DIRS),\ + if [ ! -d $x ]; \ + then \ + mkdir -p $x; \ + echo create dir $(x) success; \ + fi;) + if [ ! -d $(MAIN_TOPDIR)/third_party/u-boot-v2019.07/u-boot-v2019.07/ ]; \ + then \ + cd $(THIRD_DIR)/u-boot-v2019.07; \ + tar -xvf u-boot-v2019.07.tar.gz; \ + cd $(U_BOOT_DIR)/u-boot-v2019.07; \ + patch -p1 < ./../patch/CVE-2019-13103.patch; \ + patch -p1 < ./../patch/CVE-2019-13104.patch; \ + patch -p1 < ./../patch/CVE-2019-13105.patch; \ + patch -p1 < ./../patch/CVE-2019-13106.patch; \ + patch -p1 < ./../patch/CVE-2019-14192-14193-14199.patch; \ + patch -p1 < ./../patch/CVE-2019-14194-14198.patch; \ + patch -p1 < ./../patch/CVE-2019-14195.patch; \ + patch -p1 < ./../patch/CVE-2019-14196.patch; \ + patch -p1 < ./../patch/CVE-2019-14197-14200-14201-14202-14203-14204.patch; \ + patch -p1 < ./../hisilicon_patch/hisilicon-u-boot-v2019.07.patch ; \ + cd $(MAIN_TOPDIR); \ + fi; + +clean: + $(Q)$(foreach x, $(OUT_DIRS),\ + if [ -d $(dir $x) ]; \ + then \ + $(RM) $(dir $x); \ + echo clean dir $(dir $x) success; \ + fi;) + $(RM) $(MAIN_TOPDIR)/build/libs/factory_bin + $(RM) $(MAIN_TOPDIR)/build/scripts/__pycache__/ + +all_clean: + $(Q)$(foreach x, $(OUT_DIRS),\ + if [ -d $(dir $x) ]; \ + then \ + $(RM) $(dir $x); \ + echo clean dir $(dir $x) success; \ + fi;) + $(RM) $(MAIN_TOPDIR)/build/libs/factory_bin + $(RM) $(MAIN_TOPDIR)/build/scripts/__pycache__/ + $(RM) $(MAIN_TOPDIR)/third_party/u-boot-v2019.07/u-boot-v2019.07 + $(RM) $(MAIN_TOPDIR)/build/config/usr_config.mk.old diff --git a/sdk_liteos/platform/drivers/Makefile b/sdk_liteos/platform/drivers/Makefile new file mode 100755 index 0000000000000000000000000000000000000000..e8dffa9b51c1d121072661effec703d019677df4 --- /dev/null +++ b/sdk_liteos/platform/drivers/Makefile @@ -0,0 +1,36 @@ +include $(MAIN_TOPDIR)/build/make_scripts/config.mk +include $(MAIN_TOPDIR)/$(MODULE_DIR)/module_config.mk +-include $(MAIN_TOPDIR)/$(MODULE_DIR)/srcs.mk + +OBJDIR = $(MAIN_TOPDIR)/$(OBJ_PATH)/$(MODULE_DIR) + +ID_CFG_FILE = $(MAIN_TOPDIR)/$(MODULE_DIR)/file_id.cfg + +LIB_NAME = lib$(LIB).a +SRCS = $($(LIB)_srcs) +LIBOUT = $(MAIN_TOPDIR)/$(LIB_PATH)/$(MODULE_DIR)/$(LIB_NAME) + +ifdef SRC_FILES +OBJ_SRCS := $(filter %.c, $(SRC_FILES)) +ASM_SRCS := $(filter %.S, $(SRC_FILES)) +else +OBJ_SRCS := $(foreach dir, $(SRCS), $(wildcard $(dir)/*.c)) +ASM_SRCS := $(foreach dir, $(SRCS), $(wildcard $(dir)/*.S )) +endif + +OBJ_SRCS := $(filter-out %/ethernetif.c, $(OBJ_SRCS)) +OBJS = $(patsubst %.c, $(OBJDIR)/%.o, $(OBJ_SRCS)) +ASM_OBJS = $(patsubst %.S, $(OBJDIR)/%.o, $(ASM_SRCS)) + +all: $(LIBOUT) +include $(MAIN_TOPDIR)/build/make_scripts/lib.mk + +clean: + $(Q)$(foreach x, $(OBJS) $(ASM_OBJS) $(LIBOUT), \ + if [ -d $(dir $x) ]; \ + then $(RM) $(dir $x); \ + echo clean dir $(dir $x) success; \ + fi;) + +.PHONY: all clean + diff --git a/sdk_liteos/platform/drivers/SConscript b/sdk_liteos/platform/drivers/SConscript new file mode 100755 index 0000000000000000000000000000000000000000..5e0495940c216fcade0b1d624489e99946246a99 --- /dev/null +++ b/sdk_liteos/platform/drivers/SConscript @@ -0,0 +1,27 @@ +#!/usr/bin/env python3 +# coding=utf-8 +import os +from scripts import common_env +Import('env') +Import('env_cfg') +Import('module') + +module_path = env_cfg.get_module_dir(module) +obj_path = env_cfg.obj_path +module_libs = env_cfg.get_module_libs(module) +libs = [] + +env = env.Clone() +env_cfg.append_environs(env, module) +common_env.print_log_env(env, env_cfg.get_module_dir(module)) + +for lib in module_libs: + print('lib_name:', lib) + src_path = module_libs[lib] + objs = [] + for src in src_path: + objs += env.SConscript(os.path.join(src, 'SConscript'), {'env':env}, variant_dir = os.path.join('#', obj_path, module_path, src), duplicate = 0) + libs += env.Library(lib, objs) +Return('libs') + + diff --git a/sdk_liteos/platform/drivers/adc/SConscript b/sdk_liteos/platform/drivers/adc/SConscript new file mode 100755 index 0000000000000000000000000000000000000000..b0e5f0e2b015ebbec8bd8a4344149640ab49ef09 --- /dev/null +++ b/sdk_liteos/platform/drivers/adc/SConscript @@ -0,0 +1,4 @@ +Import('env') + +objs = env.Object(Glob('*.c')) +Return('objs') diff --git a/sdk_liteos/platform/drivers/adc/adc_drv.h b/sdk_liteos/platform/drivers/adc/adc_drv.h new file mode 100644 index 0000000000000000000000000000000000000000..c57685bbb53ba87de59a76cd9a8c870f9ec298e7 --- /dev/null +++ b/sdk_liteos/platform/drivers/adc/adc_drv.h @@ -0,0 +1,276 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Description: ADC driver header file. + */ + +#ifndef __ADC_DRV_H__ +#define __ADC_DRV_H__ + +#include +#include +#include + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ + +#ifdef ADC_DEBUG +#define adc_print(fmt...) \ + do { \ + printf(fmt); \ + printf("\n"); \ + } while (0) +#else +#define adc_print(fmt...) +#endif + +#define LS_ADC_CLK_DIV1_REG CLDO_CTL_CLK_DIV1_REG +#define LS_ADC_CLK_DIV1_OFFSET 9 + +#define HI_LS_ADC_REG_BASE 0x40070000 /* LD ADC base address */ +#define REG_ADC_CFG (HI_LS_ADC_REG_BASE + 0x00) +#define REG_ADC_FIFO_CFG (HI_LS_ADC_REG_BASE + 0x04) +#define REG_ADC_IMSC (HI_LS_ADC_REG_BASE + 0x08) +#define REG_ADC_CR (HI_LS_ADC_REG_BASE + 0x0C) +#define REG_ADC_SR (HI_LS_ADC_REG_BASE + 0x10) +#define REG_ADC_RIS (HI_LS_ADC_REG_BASE + 0x14) +#define REG_ADC_MIS (HI_LS_ADC_REG_BASE + 0x18) +#define REG_ADC_START (HI_LS_ADC_REG_BASE + 0x1C) +#define REG_ADC_STOP (HI_LS_ADC_REG_BASE + 0x20) +#define REG_ADC_DR (HI_LS_ADC_REG_BASE + 0x24) +#define REG_ADC_CTRL (HI_LS_ADC_REG_BASE + 0x28) +#define REG_ADC_EN (HI_LS_ADC_REG_BASE + 0x2C) + +#define ADC_INT_FIFO_WATER_LINE (1 << 1) +#define ADC_INT_FIFO_OVER_FLOW (1 << 0) + +#define ADC_SR_RNE (1 << 0) /* FIFO not empty flag: 0:empty 1:not empty */ +#define ADC_SR_RFF (1 << 1) /* FIFO full flag 0:not full 1:full */ +#define ADC_SR_BSY (1 << 2) /* ADC busy flag 0:idle 1:busy */ + +#define ADC_SCAN_START 1 +#define ADC_SCAN_STOP 1 +#define ADC_POWER_ON 0 +#define ADC_POWER_OFF 1 +#define ADC_ISR_DISABLE 0 +#define ADC_DATA_BIT_WIDTH 12 + +/* + * The longest time to get 1 data is ((0xfff+(18*8)+3)*334)ns + * The unit of this cnt is about 5us + */ +#define ADC_PER_DATA_TIMEOUT_CNT 500 +#define ADC_LOOP_DELAY_US 5 + +typedef void (*adc_clken_callback)(hi_void); + +/** +* @ingroup iot_ls_adc +* @brief Callback function of ADC read data done. +CNcomment:ADC读数完成后回调函数的类型。CNend +* +* @par 描述: +* Callback function of ADC read data done. +CNcomment:ADC读数完成后回调函数的类型。CNend +* +* @attention Can NOT be called in the interruption. +CNcomment:在其它中断响应中无法被调用。CNend +* @param data_buf [IN] type #hi_u16 *,received data. +CNcomment:回调入参,读到的数据。CNend +* @param length [IN] type #hi_u32,length of the received data. +CNcomment:读取数据的长度。CNend +* +* @retval None +* @par 依赖: +* @li hi_adc.h:Describes ADC APIs. +CNcomment:文件用于描述ADC相关接口。CNend +* @see None +*/ +typedef hi_void(*adc_read_cb) (const hi_u16 *data_buf, hi_u32 length); + +typedef struct { + hi_u32 ch_vld : 8; + hi_u32 equ_model : 2; + hi_u32 reserved0 : 2; + hi_u32 delay_cnt : 12; + hi_u32 cur_bais : 2; + hi_u32 reserved1 : 6; +} adc_cfg_reg_s; + +typedef struct { + volatile hi_u32 buf_pos; /* offset of data buffer */ + hi_u32 is_init; /* init flag */ + hi_u32 buf_length; /* length of data buffer length */ + hi_u16 *data_buf; /* point of data buffer */ + adc_read_cb adc_cb; /* callback function after read data finish */ +} adc_data; + + +/** + * @ingroup iot_ls_adc + * + * Settings: ADC RX threshold. CNcomment:设置参数:ADC接收水线。CNend + */ +typedef enum { + HI_ADC_FIFO_WATER_LINE_127, + HI_ADC_FIFO_WATER_LINE_124, + HI_ADC_FIFO_WATER_LINE_64, + HI_ADC_FIFO_WATER_LINE_32, + HI_ADC_FIFO_WATER_LINE_16, + HI_ADC_FIFO_WATER_LINE_8, + HI_ADC_FIFO_WATER_LINE_4, + HI_ADC_FIFO_WATER_LINE_1, +} hi_adc_fifo_water_line; + +/** + * @ingroup iot_ls_adc + * + * ADC settings. CNcomment:ADC设置参数。CNend + */ +typedef struct { + hi_u16 delay_cnt; /**< Countings from config to start collect, [0xF, 0xFF]. + CNcomment:从配置采样到启动采样的延时时间计数,其值需在 + 0xF~0xFFF之间 CNend */ + hi_adc_equ_model_sel equ_model_sel; /**< Average algorithm mode. + CNcomment:平均算法模式 CNend */ + hi_adc_cur_bais cur_bais; /**< ADC Analog power control. + CNcomment:模拟电源控制 CNend */ + hi_adc_fifo_water_line fifo_water_line; /**< FIFO threshold interruption settings. Not use in sync rx mode. + CNcomment:FIFO水线中断设置,同步读取时无需设置 CNend */ +} hi_adc_cfg; + +/** + * @ingroup iot_ls_adc + * + * Data format in 16bit, [0:11] are data bits, [0:2] are decimal fractions, [12:24] are channel number, [15] reserved. + CNcomment:读取到的ADC数据格式,[0:11]是数据位,其中[0:1]是小数位。[12:14]是通道编号, + [15]保留。CNend + */ +typedef struct { + hi_u16 val : 12; /**< Data bit, [0:1] are decimal fractions. + CNcomment:数据位,其中[0:1]是小数位 CNend */ + hi_u16 ch_id : 3; /**< Channel number. CNcomment:通道编号 CNend */ + hi_u16 reserved : 1; +} hi_adc_data_format; + +/** +* @ingroup iot_ls_adc +* @brief Initializes the data acquisition control module. +CNcomment:ADC模块初始化。CNend +* +* @par 描述: +* Initializes the data acquisition control module, apply for interrupt, enable the module. +CNcomment:ADC模块初始化,对ADC模块初始化,申请中断,使能ADC模块。CNend +* +* @retval #HI_ERR_SUCCESS Success. +* @retval #Other Failure. See hi_errno.h for details. +* @see hi_adc_shutdown。 +*/ +hi_u32 hi_adc_init(hi_void); + +/** +* @ingroup iot_ls_adc +* @brief ADC settings. CNcomment:设置ADC参数。CNend +* +* @par 描述: +* Set ADC parameters. CNcomment:设置ADC参数。CNend +* +* @attention None +* @param adc_cfg [IN] type #hi_adc_cfg,ADC settings. CNcomment:ADC模块相关参数。CNend +* +* @retval #HI_ERR_SUCCESS Success. +* @retval #Other Failure. See hi_errno.h for details. +* @par 依赖: +* @li hi_adc.h:Describes ADC APIs. +CNcomment:文件用于描述ADC相关接口。CNend +* @see hi_adc_set_basic_info。 +*/ +hi_u32 hi_adc_set_basic_info(const hi_adc_cfg *adc_cfg); + +/** +* @ingroup iot_ls_adc +* @brief Read ADC received data synchronously. CNcomment:同步读取ADC数据。CNend +* +* @par 描述: +* Read ADC received data synchronously. CNcomment:同步读取ADC数据。CNend +* +* @attention None +* @param channel [IN] type #hi_u8 ,channel to be read. CNcomment:要使能的channel。CNend +* @param data_buf [IN] type #hi_u16 * ,data buffer to store the data. +CNcomment:读取的ADC数据保存buf地址。CNend +* @param get_len [IN] type #hi_u32 ,length to read, do NOT longer than the buffer size. +CNcomment:要读的数据长度,数据存入data_buf,不能大于data_buf长度。CNend +* +* @retval #HI_ERR_SUCCESS Success. +* @retval #Other Failure. See hi_errno.h for details. +* @par 依赖: +* @li hi_adc.h:Describes ADC APIs. +CNcomment:文件用于描述ADC相关接口。CNend +* @see hi_adc_get_data。 +*/ +hi_u32 hi_adc_read_sync(hi_u8 channel, hi_u16 *data_buf, hi_u32 get_len); + +/** +* @ingroup iot_ls_adc +* @brief Asynchronously reading ADC data. CNcomment:异步读取ADC数据。CNend +* +* @par 描述: +* Asynchronously reading ADC data. CNcomment:异步读取ADC数据。CNend +* +* @attention None +* @param channel [IN] type #hi_u8 ,channel to be read. CNcomment:要使能的channel。CNend +* @param data_buf [IN] type #hi_u16 * ,data buffer to store the data. +CNcomment:读取的ADC数据保存buf地址。CNend +* @param get_len [IN] type #hi_u32 ,length to read, do NOT longer than the buffer size. +CNcomment:要读的数据长度,数据存入data_buf,不能大于data_buf长度。CNend +* @param cb [IN] type #adc_read_cb ,Callback function when read done. +CNcomment:ADC读数完成后回调函数。CNend +* +* @retval #HI_ERR_SUCCESS Success. +* @retval #Other Failure. See hi_errno.h for details. +* @par 依赖: +* @li hi_adc.h:Describes ADC APIs. +CNcomment:文件用于描述ADC相关接口。CNend +* @see hi_adc_scan_stop。 +*/ +hi_u32 hi_adc_read_async(hi_u8 channel, hi_u16 *data_buf, hi_u32 get_len, adc_read_cb cb); + +/** +* @ingroup iot_ls_adc +* @brief Deinitialize ADC module. CNcomment:关闭ADC模块。CNend +* +* @par 描述: +* Deinitialize ADC module, clear up FIFO, disable interruption, shutdown power. +CNcomment:关闭ADC模块,清空FIFO,关闭中断,关闭电源。CNend +* +* @attention None +* @param None +* @retval None +* @par 依赖: +* @li hi_adc.h:Describes ADC APIs. +CNcomment:文件用于描述ADC相关接口。CNend +* @see hi_adc_init。 +*/ +hi_void hi_adc_deinit(hi_void); + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif diff --git a/sdk_liteos/platform/drivers/adc/hi_adc.c b/sdk_liteos/platform/drivers/adc/hi_adc.c new file mode 100644 index 0000000000000000000000000000000000000000..a01ba75eee48bc8d13543d8dc47e3f33f08c862b --- /dev/null +++ b/sdk_liteos/platform/drivers/adc/hi_adc.c @@ -0,0 +1,111 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include + +#include "adc_drv.h" + +#define CHECK_EMPTY_MAX_TIME_US 3000 /* 344ns * (0xfff + 18) * 2 = 2.8ms ,reserved 3ms */ + +HI_ALWAYS_STAIC_INLINE hi_bool check_adc_fifo_empty(hi_void) +{ + hi_u32 reg_val = hi_reg_read_val32(REG_ADC_SR); + if (reg_val & ADC_SR_RNE) { + return HI_FALSE; + } + return HI_TRUE; +} + +HI_ALWAYS_STAIC_INLINE hi_void wait_adc_fifo_empty(hi_void) +{ + hi_u32 timeout = CHECK_EMPTY_MAX_TIME_US; + while ((check_adc_fifo_empty() == HI_FALSE) && (timeout > 0)) { + (hi_void)hi_reg_read_val32(REG_ADC_DR); + hi_udelay(1); + timeout--; + } +} + +HI_ALWAYS_STAIC_INLINE hi_u32 adc_check_parameter(hi_adc_channel_index channel, hi_u16 *data, + hi_adc_equ_model_sel equ_model, hi_adc_cur_bais cur_bais, hi_u16 delay_cnt) +{ + if ((channel > HI_ADC_CHANNEL_7) || (data == HI_NULL) || (equ_model > HI_ADC_EQU_MODEL_8) || + (cur_bais > HI_ADC_CUR_BAIS_3P3V) || (delay_cnt > 0xFF0)) { + return HI_ERR_ADC_PARAMETER_WRONG; + } + return HI_ERR_SUCCESS; +} + +hi_u32 hi_adc_read(hi_adc_channel_index channel, hi_u16 *data, hi_adc_equ_model_sel equ_model, + hi_adc_cur_bais cur_bais, hi_u16 delay_cnt) +{ + hi_u16 reg_val, int_value; + hi_u32 timeout_cnt = 0; + adc_cfg_reg_s adc_ctl = {0}; + if (adc_check_parameter(channel, data, equ_model, cur_bais, delay_cnt) != HI_ERR_SUCCESS) { + return HI_ERR_ADC_PARAMETER_WRONG; + } + + hi_xtal_clock clock = hi_get_xtal_clock(); + hi_reg_read16(LS_ADC_CLK_DIV1_REG, reg_val); + reg_val &= ~(0xF << LS_ADC_CLK_DIV1_OFFSET); + if (clock == HI_XTAL_CLOCK_24M) { + reg_val |= (0x7 << LS_ADC_CLK_DIV1_OFFSET); + } else if (clock == HI_XTAL_CLOCK_40M) { + reg_val |= (0xC << LS_ADC_CLK_DIV1_OFFSET); + } + hi_reg_write16(LS_ADC_CLK_DIV1_REG, reg_val); + int_value = hi_int_lock(); + hi_reg_write32(REG_ADC_EN, ADC_POWER_ON); + + adc_ctl.ch_vld = (hi_u32)(1 << (hi_u32)channel); + adc_ctl.equ_model = equ_model; + adc_ctl.cur_bais = cur_bais; + adc_ctl.delay_cnt = delay_cnt + 0xF; + hi_reg_write32(REG_ADC_CFG, *(volatile hi_u32 *)&adc_ctl); + + hi_reg_write32(REG_ADC_START, ADC_SCAN_START); + + while (timeout_cnt < ADC_PER_DATA_TIMEOUT_CNT) { + if (!check_adc_fifo_empty()) { + *data = (hi_u16)hi_reg_read_val32(REG_ADC_DR); + if ((*data >> ADC_DATA_BIT_WIDTH) == channel) { + *data = *data & 0xFFF; + break; + } + } + hi_udelay(ADC_LOOP_DELAY_US); + timeout_cnt++; + } + if (timeout_cnt >= ADC_PER_DATA_TIMEOUT_CNT) { + hi_int_restore(int_value); + return HI_ERR_ADC_TIMEOUT; + } + hi_reg_write32(REG_ADC_STOP, ADC_SCAN_STOP); + hi_reg_write32(REG_ADC_IMSC, ADC_ISR_DISABLE); + wait_adc_fifo_empty(); + hi_reg_write32(REG_ADC_EN, ADC_POWER_OFF); + hi_int_restore(int_value); + return HI_ERR_SUCCESS; +} + +hi_float hi_adc_convert_to_voltage(hi_u16 data) +{ + float voltage = (float)data * 1.8 * 4 / 4096; /* adc code equals: voltage/4/1.8*4096 */ + return voltage; +} + diff --git a/sdk_liteos/platform/drivers/cipher/cipher.h b/sdk_liteos/platform/drivers/cipher/cipher.h new file mode 100644 index 0000000000000000000000000000000000000000..b37f1496dd68f9c93e5b194c3f927f584500a76c --- /dev/null +++ b/sdk_liteos/platform/drivers/cipher/cipher.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Description: head file of cipher + */ + +#ifndef __CIPHER_H__ +#define __CIPHER_H__ +#include +#include + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ + +hi_u32 cipher_init(hi_bool is_liteos); +hi_u32 cipher_deinit(hi_void); +hi_void cipher_clk_switch(hi_bool enable); +hi_bool cipher_get_clk_ctrl(hi_void); + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif /* __CIPHER_H__ */ + diff --git a/sdk_liteos/platform/drivers/cipher/drv_osal_lib.h b/sdk_liteos/platform/drivers/cipher/drv_osal_lib.h new file mode 100644 index 0000000000000000000000000000000000000000..ee2d8f9dd665d1caf87393924e351f3a3ede716e --- /dev/null +++ b/sdk_liteos/platform/drivers/cipher/drv_osal_lib.h @@ -0,0 +1,198 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Description: head file of osal lib define for cipher + */ + +#ifndef __DRV_OSAL_LIB_H__ +#define __DRV_OSAL_LIB_H__ + +#define __LITEOS_CRYPTO_SUPPORT__ +#ifdef __LITEOS_CRYPTO_SUPPORT__ +#include +#include +#include +#include "hi_types.h" +#include +#include +#include +#include +#include +#include +#include +#include +#else +#include +#include +#endif + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ + + +/* Turn off the interrupt switch of cipher. + * #define CRYPTO_OS_INT_SUPPORT + * + * Turn off the debug switch of cipher. + * #define CRYPTO_DEBUG_SUPPORT + */ + +#define CRYPTO_QUEUE_HEAD hi_u32 +#define crypto_queue_init(x) hi_sem_create(&(x), 0) +#define crypto_queue_wait_up(x) hi_sem_signal(x) +#define crypto_queue_wait_timeout(x, con, time) hi_sem_wait(x, time) +#define crypto_queue_delete(x) hi_sem_delete(x); + +#define crypto_irq_enable(irq) hi_irq_enable(irq) +#define crypto_irq_disable(irq) hi_irq_disable(irq) +#define crypto_request_irq(irq, func, name) hi_irq_request(irq, HI_IRQ_FLAG_PRI1, (irq_routine)(func), 0); +#define crypto_free_irq(irq, name) hi_irq_free(irq) + +#define crypto_udelay(us) hi_udelay(us) + +#define crypto_reg_read(addr) (*(volatile hi_u32 *)(uintptr_t)(addr)) +#define crypto_reg_write(addr, val) (*(volatile hi_u32 *)(uintptr_t)(addr) = (val)) + +/* crypto mutex adapt. */ +typedef struct { + hi_u32 mux_id; + hi_bool is_liteos; + hi_u8 resv[3]; /* 3 bytes reserved */ +}crypto_mutex_ctx; + +#define CRYPTO_MUX_TIME_OUT 300 +hi_u32 crypto_mutex_init(crypto_mutex_ctx *ctx); +hi_u32 crypto_mutex_lock(const crypto_mutex_ctx *ctx); +hi_u32 crypto_mutex_unlock(const crypto_mutex_ctx *ctx); +hi_u32 crypto_mutex_destroy(crypto_mutex_ctx *ctx); + +/* clock reg read or write. */ +#define REG_CRG_BASE 0x40c00000 +#define clk_read(offset) crypto_reg_read(REG_CRG_BASE + (offset)) +#define clk_write(offset, val) crypto_reg_write(REG_CRG_BASE + (offset), (val)) + +/* word index number. */ +#define WORD_INDEX_0 0 +#define WORD_INDEX_1 1 +#define WORD_INDEX_2 2 +#define WORD_INDEX_3 3 + +/* Boundary value 1. */ +#define BOUND_VALUE_1 1 + +/* multiple value */ +#define MULTIPLE_VALUE_1 1 +#define MULTIPLE_VALUE_2 2 + +#define SHIFT_4BITS 4 +#define SHIFT_8BITS 8 +#define SHIFT_16BITS 16 +#define SHIFT_24BITS 24 +#define MAX_LOW_2BITS 3 +#define MAX_LOW_3BITS 7 +#define MAX_LOW_4BITS 0xF +#define MAX_LOW_8BITS 0xFF +#define WORD_WIDTH 4 +#define BYTE_BITS 8 + +#define CRYPTO_NUM_1 1 +#define CRYPTO_NUM_2 2 +#define crypto_unused(x) ((x) = (x)) + +#ifndef max +#define max(a, b) ((a) > (b) ? (a) : (b)) +#endif +#ifndef min +#define min(a, b) ((a) < (b) ? (a) : (b)) +#endif + +hi_void *crypto_calloc(hi_u32 n, hi_u32 size, hi_bool is_liteos); +hi_u32 crypto_free(hi_void *ptr, hi_bool is_liteos); + +#define DCACHE_ENABLE 1 +#define DCACHE_EN_REG 0x7C1 /* DCACHE enable reg */ +#define DCACHE_FLUSH_REG 0x7C3 /* DCACHE fluch reg */ +#define DCACHE_CLEAN_INVALI 0x000C /* Bit[2]:invalidation ;Bit[3]:clean */ + +#define CRYPTO_CACHE_LINE_SIZE 32 +#define CRYPTO_DCACHE_BY_ADDR_MAX_SIZE 512 /* 512 bytes. */ + +hi_u32 crypto_flush_dcache_by_addr(hi_u32 src_addr, hi_u32 size); + +/* print for DFX infomation. */ +#define HI_PRINT printf +#ifdef HI_LOG_CIPHER_DEBUG_SUPPORT +#define hi_log_debug(fmt...) \ + do { \ + HI_PRINT("[HI-CIPHER-DEBUG]%s[%d]:", __FUNCTION__, __LINE__); \ + HI_PRINT(fmt); \ + } while (0); +#else +#define hi_log_debug(fmt...) +#endif + +#ifdef HI_LOG_CIPHER_INFO_SUPPORT +#define hi_log_info(fmt...) \ + do { \ + HI_PRINT("[HI-CIPHER-INFO]%s[%d]:", __FUNCTION__, __LINE__); \ + HI_PRINT(fmt); \ + } while (0); +#else +#define hi_log_info(fmt...) +#endif + +#ifdef CRYPTO_DEBUG_SUPPORT +#define hi_log_error(fmt...) \ + do { \ + HI_PRINT("[HI-CIPHER-ERROR]%s[%d]:", __FUNCTION__, __LINE__); \ + HI_PRINT(fmt); \ + } while (0); + +#define hi_log_print_func_err(_func, _err_code) \ + hi_log_error("Call %s return [0x%08x]\n", #_func, (unsigned int)(_err_code)); + +#define hi_log_print_err_code(_err_code) \ + hi_log_error("Error code: [0x%08x]\n", (unsigned int)(_err_code)); + +#define hi_log_check_param(_val) \ + do { \ + if (_val) { \ + hi_log_error("%s\n", #_val); \ + hi_log_print_err_code(HI_ERR_CIPHER_INVALID_PARAMETER); \ + return HI_ERR_CIPHER_INVALID_PARAMETER; \ + } \ + } while (0) +#else +#define hi_log_error(fmt...) +#define hi_log_print_func_err(_func, _err_code) +#define hi_log_print_err_code(_err_code) + +#define hi_log_check_param(_val) \ + do { \ + if (_val) { \ + return HI_ERR_CIPHER_INVALID_PARAMETER; \ + } \ + } while (0) +#endif + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif /* __DRV_OSAL_LIB_H__ */ diff --git a/sdk_liteos/platform/drivers/cipher/drv_pke_common.h b/sdk_liteos/platform/drivers/cipher/drv_pke_common.h new file mode 100644 index 0000000000000000000000000000000000000000..06ee32118df03958df6138040996e4a681a6c73e --- /dev/null +++ b/sdk_liteos/platform/drivers/cipher/drv_pke_common.h @@ -0,0 +1,541 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Description: head file of cipher pke common driver. + */ + +#ifndef __DRV_PKE_COMMON_H__ +#define __DRV_PKE_COMMON_H__ + +#include "hi_cipher.h" +#include "cipher.h" +#include "drv_osal_lib.h" +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ + +#define CRYPTO_PKE_ECC_SUPPORT + +/* Define the offset of reg */ +#define PKE_VERSION_DATE 0x0 +#define PKE_BUSY 0x4 +#define PKE_WORK_MODE 0x8 +#define PKE_START 0xc +#define PKE_INT_ENABLE 0x10 +#define PKE_INT_STATUS 0x14 +#define PKE_INT_NOMASK_STATUS 0x18 +#define PKE_KEY_CRC 0x20 +#define PKE_KEY_RANDOM_1 0x24 +#define PKE_KEY_RANDOM_2 0x28 +#define PKE_RESULT_FLAG 0x24 +#define PKE_FAILURE_FLAG 0x28 +#define PKE_OTP_KEY_SEL 0x38 +#define PKE_CFG_KEY_FLAG 0x3c +#define PKE_NOISE_EN 0x1C +#define PKE_MRAM 0x200 +#define PKE_PRAM 0x300 +#define PKE_NRAM 0x600 +#define PKE_KRAM 0xa00 +#define PKE_RRAM 0xe00 + +#define HISC_COM_PKE_CLK_ENABLE 0x08 + +#define PKE_LOCK_TPP 0x55 +#define PKE_LOCK_HPP 0x95 /* HSL */ +#define PKE_LOCK_TEE 0xA5 +#define PKE_LOCK_REE 0xAA + +#define PKE_INT_VALID 1 +#define PKE_INT_INVALID 0 +#define PKE_INT_NOMASK_VALID 1 +#define PKE_INT_NOMASK_INVALID 0 +#define PKE_INT_ENABLE_VALID 1 +#define PKE_INT_ENABLE_INVALID 0 + +#define PKE_RAM_SELECT_0 0 +#define PKE_RAM_SELECT_1 1 +#define PKE_RAM_SELECT_2 2 +#define PKE_RAM_SELECT_3 3 +#define PKE_RAM_SELECT_4 4 + +/* Define the pke data len */ +typedef enum { + PKE_DATA_LEN_BYTE_32 = 4, + PKE_DATA_LEN_BYTE_48 = 6, + PKE_DATA_LEN_BYTE_64 = 8, + PKE_DATA_LEN_BYTE_72 = 9, + PKE_DATA_LEN_BYTE_128 = 16, + PKE_DATA_LEN_BYTE_256 = 32, + PKE_DATA_LEN_BYTE_384 = 48, + PKE_DATA_LEN_BYTE_512 = 64, +} pke_data_len; + +/* Define the ram sel for clear */ +typedef enum { + PKE_CLR_RAM_SEL_NONE = 0x00, + PKE_CLR_RAM_SEL_MRAM = 0x01, + PKE_CLR_RAM_SEL_NRAM = 0x02, + PKE_CLR_RAM_SEL_KRAM = 0x04, + PKE_CLR_RAM_SEL_RRAM = 0x08, + PKE_CLR_RAM_SEL_RAM = 0x10, + PKE_CLR_RAM_SEL_ALL = 0x1F, +} pke_clr_ram_sel; + +/* Define the ram type */ +typedef enum { + PKE_RAM_TYPE_MRAM = 0, /* 0x0200 ~ 0x05FF */ + PKE_RAM_TYPE_NRAM, /* 0x0600 ~ 0x09FF */ + PKE_RAM_TYPE_KRAM, /* 0x0a00 ~ 0x0dFF */ + PKE_RAM_TYPE_RRAM, /* 0x0e00 ~ 0x11FF */ +} pke_ram_type; + +/* Define the operaion mode */ +typedef enum { + PKE_MODE_CLR_RAM = 0x0, + PKE_MODE_EXP_MOD = 0x1, + PKE_MODE_MUL_DOT = 0x2, + PKE_MODE_ADD_DOT = 0x3, + PKE_MODE_TIMES_DOT = 0x4, + PKE_MODE_ADD_MOD = 0x5, + PKE_MODE_SUB_MOD = 0x6, + PKE_MODE_MUL_MOD = 0x7, + PKE_MODE_MINV_MOD = 0x8, + PKE_MODE_MOD = 0x9, + PKE_MODE_MUL = 0xa, + PKE_MODE_KGEN_NO_E = 0x10, + PKE_MODE_KGEN_WITH_E = 0x11, + PKE_MODE_KTRANS = 0x12, +} pke_mode; + +/* Define the result flag */ +typedef enum { + PKE_RESULT_FLAG_FAIL = 0x00, + PKE_RESULT_FLAG_OK = 0x01, +} pke_result_code; + +typedef enum { + PKE_FAIL_FLAG_MOD_INFINITY = 0x01, + PKE_FAIL_FLAG_INPUT_POINT_INVALID = 0x02, + PKE_FAIL_FLAG_OUTPUT_POINT_INVALID = 0x04, + PKE_FAIL_FLAG_DFX = 0x08, +} pke_fail_flag; + +#define PKE_FAIL_FLAG_CNT 0x08 +#define PKE_SECURE_TRUE 0x01 +#define PKE_SECURE_FALSE 0x00 + +/* Define the union U_PKE_BUSY */ +typedef union { + /* Define the struct bits */ + struct { + unsigned int pke_busy : 1; /* [0] */ + unsigned int reserved_0 : 31; /* [31..1] */ + } bits; + + /* Define an unsigned member */ + unsigned int u32; +} pke_busy; + +/* Define the union U_PKE_WORK_MODE */ +typedef union { + /* Define the struct bits */ + struct { + unsigned int mode_sel : 4; /* [3..0] */ + unsigned int data_len : 2; /* [5..4] */ + unsigned int reserved : 26; /* [31..6] */ + } bits; + + /* Define an unsigned member */ + unsigned int u32; +} pke_work_mode; + +/* Define the union U_PKE_START */ +typedef union { + /* Define the struct bits */ + struct { + unsigned int pke_start : 1; /* [0] */ + unsigned int reserved_0 : 31; /* [31..1] */ + } bits; + + /* Define an unsigned member */ + unsigned int u32; +} pke_start; + +/* Define the union U_PKE_INT_ENABLE */ +typedef union { + /* Define the struct bits */ + struct { + unsigned int pke_int_enable : 1; /* [0] */ + unsigned int reserved_0 : 31; /* [31..1] */ + } bits; + + /* Define an unsigned member */ + unsigned int u32; +} pke_int_enable; + +/* Define the union U_PKE_INT_STATUS */ +typedef union { + /* Define the struct bits */ + struct { + unsigned int pke_int : 1; /* [0] */ + unsigned int reserved_0 : 31; /* [31..1] */ + } bits; + + /* Define an unsigned member */ + unsigned int u32; +} pke_int_status; + +/* Define the union U_PKE_INT_NOMASK_STATUS */ +typedef union { + /* Define the struct bits */ + struct { + unsigned int pke_int_nomask : 1; /* [0] */ + unsigned int reserved_0 : 31; /* [31..1] */ + } bits; + + /* Define an unsigned member */ + unsigned int u32; +} pke_int_nomask_status; + +/* Define the union U_PKE_POWER_NOISE_LOCK */ +typedef union { + /* Define the struct bits */ + struct { + unsigned int power_noise_lock : 4; /* [3..0] */ + unsigned int reserved_0 : 28; /* [31..4] */ + } bits; + + /* Define an unsigned member */ + unsigned int u32; +}pke_power_noise_lock; + +/* Define the union U_PKE_KEY_CRC */ +typedef union { + /* Define the struct bits */ + struct { + unsigned int key_crc_in : 16; /* [15..0] */ + unsigned int key_crc_out : 16; /* [31..16] */ + } bits; + + /* Define an unsigned member */ + unsigned int u32; +} pke_key_crc; + +/* Define the union U_PKE_RESULT_FLAG */ +typedef union { + /* Define the struct bits */ + struct { + unsigned int pke_result_flag : 4; /* [3..0] */ + unsigned int reserved_0 : 28; /* [31..4] */ + } bits; + + /* Define an unsigned member */ + unsigned int u32; +} pke_result_flag; + +/* Define the union U_PKE_FAILURE_FLAG */ +typedef union { + /* Define the struct bits */ + struct { + unsigned int pke_failure_flag : 8; /* [7..0] */ + unsigned int reserved_0 : 24; /* [31..8] */ + } bits; + + /* Define an unsigned member */ + unsigned int u32; +} pke_failure_flag; + +/* Define the union U_PKE_OTP_KEY_SEL */ +typedef union { + /* Define the struct bits */ + struct { + unsigned int otp_key_sel : 4; /* [3..0] */ + unsigned int reserved_0 : 28; /* [31..4] */ + } bits; + + /* Define an unsigned member */ + unsigned int u32; +} pke_otp_key_sel; + +/* Define the union U_PKE_CFG_KEY_FLAG */ +typedef union { + /* Define the struct bits */ + struct { + unsigned int key_cfg_flag : 4; /* [3..0] */ + unsigned int reserved_0 : 28; /* [31..4] */ + } bits; + + /* Define an unsigned member */ + unsigned int u32; +} pke_cfg_key_flag; + +/* Define the union U_PKE_POWER_EN */ +typedef union { + /* Define the struct bits */ + struct { + unsigned int power_en : 4; /* [3..0] */ + unsigned int reserved_0 : 28; /* [31..4] */ + } bits; + + /* Define an unsigned member */ + unsigned int u32; +} pke_power_on; + +/* Define the union U_PKE_NOISE_EN */ +typedef union { + /* Define the struct bits */ + struct { + unsigned int pke_noise_en : 1; /* [0] */ + unsigned int reserved_0 : 31; /* [31..1] */ + } bits; + + /* Define an unsigned member */ + unsigned int u32; +} pke_noise_en; + +/* Define the union U_PKE_INT_EN */ +typedef union { + /* Define the struct bits */ + struct { + unsigned int pke_lock_int_en : 1; /* [0] */ + unsigned int reserved_0 : 31; /* [31..1] */ + } bits; + + /* Define an unsigned member */ + unsigned int u32; +} pke_int_en; + +/* Define the union U_PKE_LOCK_CTRL */ +typedef union { + /* Define the struct bits */ + struct { + unsigned int pke_lock : 1; /* [0] */ + unsigned int pke_lock_type : 1; /* [1] */ + unsigned int reserved_0 : 30; /* [31..2] */ + } bits; + + /* Define an unsigned member */ + unsigned int u32; +} pke_lock_ctrl; + +/* Define the union U_PKE_LOCK_STATUS */ +typedef union { + /* Define the struct bits */ + struct { + unsigned int pke_lock_busy : 1; /* [0] */ + unsigned int pke_unlock_fail : 1; /* [1] */ + unsigned int reserved_0 : 2; /* [3..2] */ + unsigned int pke_lock_cnt : 3; /* [6..4] */ + unsigned int reserved_1 : 1; /* [7] */ + unsigned int pke_lock_stat : 8; /* [15..8] */ + unsigned int reserved_2 : 16; /* [31..16] */ + } bits; + + /* Define an unsigned member */ + unsigned int u32; +} pke_lock_status; + +/* Define the union U_PKE_ERROR */ +typedef union { + /* Define the struct bits */ + struct { + unsigned int pke_access_err : 1; /* [0] */ + unsigned int reserved_0 : 31; /* [31..1] */ + } bits; + + /* Define an unsigned member */ + unsigned int u32; +} pke_error; + +/* Define the union HISC_COM_PKE_CLK_ENABLE */ +typedef union { + /* Define the struct bits */ + struct { + unsigned int pke_clk_enable : 1; /* [0] */ + unsigned int reserved_0 : 31; /* [31..1] */ + } bits; + + /* Define an unsigned member */ + unsigned int u32; +}hisc_com_pke_clk_enable; + +/*************************** Pke Definition ****************************/ +/* Define the length of zero padding for mul-dot */ +#define PKE_LEN_BLOCK_IN_WOED 0x02 +#define PKE_LEN_BLOCK_IN_BYTE 0x08 + +#define REG_PKE_BASE 0x40c06000 + +#define PKE_CLK_DISABLE 0x0 +#define PKE_CLK_ENABLE 0x1 +#define STEP_AUTH 0x1 + +/* Define the union for pke block */ +typedef union { + hi_u8 byte[PKE_LEN_BLOCK_IN_BYTE]; + hi_u32 word[PKE_LEN_BLOCK_IN_WOED]; +}pke_block; + +#define HASH_LEN_256 32 +#define PKE_KEY_LEN_IN_BYTE 32 + +typedef enum { + ROTATE_DIABLE, + ROTATE_ENABLE +}rotate_type; + +typedef enum { + PKE_WIDTH_256BIT = 0x00, + PKE_WIDTH_2048BIT, + PKE_WIDTH_3072BIT, + PKE_WIDTH_4096BIT, +}pke_width; + +typedef struct { + const hi_u8 *a; + const hi_u8 *b; + const hi_u8 *p; + hi_u8 *c; + hi_u32 klen; +}pke_add_mod; + +typedef struct { + const hi_u8 *n; + const hi_u8 *e; + const hi_u8 *m; + hi_u8 *c; + hi_u32 klen; +}rsa_exp_mod; + +typedef struct { + const hi_u8 *a; + const hi_u8 *b; + const hi_u8 *p; + hi_u8 *c; + hi_u32 klen; +}pke_mul_mod; + +typedef struct { + const hi_u8 *k; + const hi_u8 *px; + const hi_u8 *py; + hi_u8 *rx; + hi_u8 *ry; + hi_u32 klen; +}pke_mul_dot; + +typedef struct { + const hi_u8 *sx; + const hi_u8 *sy; + const hi_u8 *rx; + const hi_u8 *ry; + hi_u8 *cx; + hi_u8 *cy; + hi_u32 klen; +}pke_add_dot; + +typedef struct { + const hi_u8 *sx; + const hi_u8 *sy; + hi_u8 *cx; + hi_u8 *cy; + hi_u32 klen; +}pke_double_dot; + +typedef struct { + hi_u32 power; + const hi_u8 *p; + hi_u8 *c; + hi_u32 klen; +}pke_mod_block; + +typedef struct { + hi_bool is_liteos; + hi_bool pke_initialize; + hi_bool clk_initialize; + hi_u8 resv; +}pke_init_ctx; + +/** +\brief Initialize the pke module. +\retval On success, HI_ERR_SUCCESS is returned. On error, HI_ERR_FAILURE is returned. +*/ +hi_u32 drv_pke_init(hi_bool is_liteos); + +/** +\brief Deinitialize the pke module. +\retval On success, HI_ERR_SUCCESS is returned. On error, HI_ERR_FAILURE is returned. +*/ +hi_u32 drv_pke_deinit(hi_void); + +hi_void pke_enable(hi_void); + +hi_void pke_disable(hi_void); + +pke_init_ctx *drv_pke_get_pke_init(hi_void); +crypto_mutex_ctx *drv_pke_get_mutex(hi_void); + +hi_u32 drv_pke_inv_mod(const hi_u8 *a, const hi_u8 *p, hi_u8 *c, hi_u32 klen, rotate_type rotate); + +/* c=m^e mod n */ +hi_u32 drv_ifep_rsa_exp_mod(const rsa_exp_mod *exp, rotate_type rotate); + +/** +\brief clean pke ram . +*/ +hi_u32 drv_pke_clean_ram(hi_void); + +hi_u32 drv_pke_rsa_check_rsa_data(const hi_u8 *n, const hi_u8 *e, const hi_u8 *mc, hi_u32 mc_len, hi_u32 keylen); + +#ifdef CRYPTO_PKE_ECC_SUPPORT +hi_bool drv_pke_ecc_is_zero(const hi_void *val, hi_u32 klen); + +/* descript: c = a mod p */ +hi_u32 drv_pke_mod(const hi_u8 *a, const hi_u8 *p, hi_u8 *c, hi_u32 klen, rotate_type rotate); + +/* descript: c = a * b */ +hi_u32 drv_pke_mul(const hi_u8 *a, const hi_u8 *b, hi_u8 *c, hi_u32 klen, rotate_type rotate); + +/* descript: c = a + b mod p */ +hi_u32 drv_pke_add_mod(const pke_add_mod *para, rotate_type rotate); + +/* descript: c = a - b mod p */ +hi_u32 drv_pke_sub_mod(const pke_add_mod *para, rotate_type rotate); + +/* descript: c = a * b mod p */ +hi_u32 drv_pke_mul_mod(const pke_mul_mod *para, rotate_type rotate); + +/* descript: R = k . P(x,y) */ +hi_u32 drv_pke_mul_dot(const pke_mul_dot *para, const hi_cipher_ecc_param *ecp_id, rotate_type rotate); + +/* descript: C = S(x,y) + R(x,y) */ +hi_u32 drv_pke_add_dot(const pke_add_dot *para, const hi_cipher_ecc_param *ecp_id, rotate_type rotate); + +/* descript: C = S(x,y) + S(x,y) */ +hi_u32 drv_pke_double_dot(const pke_double_dot *para, const hi_cipher_ecc_param *ecp_id, rotate_type rotate); + +/* descript: c = 2^power mod p */ +hi_u32 drv_pke_mod_block(const pke_block *a, const pke_mod_block *para, rotate_type rotate); +#endif + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif /* __DRV_PKE_COMMON_H__ */ + diff --git a/sdk_liteos/platform/drivers/dma/dma.h b/sdk_liteos/platform/drivers/dma/dma.h new file mode 100644 index 0000000000000000000000000000000000000000..1f44b250b1ac501b800e8463fcc4b33c7ece089a --- /dev/null +++ b/sdk_liteos/platform/drivers/dma/dma.h @@ -0,0 +1,328 @@ +/** + * @file dma.h + * + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** @defgroup hct_dma + * @ingroup drivers + */ + +#ifndef _DMA_H_ +#define _DMA_H_ + +#include +#include + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif + +#ifdef DMA_DEBUG +#define dma_print(fmt...) \ + do { \ + printf(fmt); \ + printf("\r\n"); \ + } while (0) +#else +#define dma_print(fmt...) +#endif + +/* DMA registers address */ +#define DMA_BASE_ADDR 0x40200000 +#define DMA_INT_STAT (DMA_BASE_ADDR + 0x000) +#define DMA_INT_TC_STAT (DMA_BASE_ADDR + 0x004) +#define DMA_INT_TC_CLR (DMA_BASE_ADDR + 0x008) +#define DMA_INT_ERR_STAT (DMA_BASE_ADDR + 0x00C) +#define DMA_INT_ERR_CLR (DMA_BASE_ADDR + 0x010) +#define DMA_RAW_INT_TC_STATUS (DMA_BASE_ADDR + 0x014) +#define DMA_RAW_INT_ERR_STATUS (DMA_BASE_ADDR + 0x018) +#define DMA_ENBLD_CHNS (DMA_BASE_ADDR + 0x01C) +#define DMA_SOFT_BREQ (DMA_BASE_ADDR + 0x020) +#define DMA_SOFT_SREQ (DMA_BASE_ADDR + 0x024) +#define DMA_SOFT_LBREQ (DMA_BASE_ADDR + 0x028) +#define DMA_SOFT_LSREQ (DMA_BASE_ADDR + 0x02C) +#define DMA_CFG_REG (DMA_BASE_ADDR + 0x030) +#define DMA_SYNC (DMA_BASE_ADDR + 0x034) +/* Source Address Register for Channel x */ +#define dma_sar(x) (DMA_BASE_ADDR + 0x100 + (x)*0x020) +/* Destination Address Register for Channel x */ +#define dma_dar(x) (DMA_BASE_ADDR + 0x104 + (x)*0x020) +/* Linked List Pointer Register for Channel x */ +#define dma_lli(x) (DMA_BASE_ADDR + 0x108 + (x)*0x020) +/* Control Register for Channel x */ +#define dma_ctl(x) (DMA_BASE_ADDR + 0x10C + (x)*0x020) +/* Configuration Register for Channel x */ +#define dma_cfg(x) (DMA_BASE_ADDR + 0x110 + (x)*0x020) + +#define DMA_MASK_INT 0 +#define DMA_UNMASK_INT 1 + +#define DMA_CHANNEL_0 0x01 +#define DMA_CHANNEL_1 0x02 +#define DMA_CHANNEL_2 0x04 +#define DMA_CHANNEL_3 0x08 + +#define DMA_CHANNEL_NUM_0 0 +#define DMA_CHANNEL_NUM_1 1 +#define DMA_CHANNEL_NUM_2 2 +#define DMA_CHANNEL_NUM_3 3 + +#define DMA_CHANNEL_NUM 4 + +#define DMA_DISABLE 0 +#define DMA_ENABLE 1 + +#define DMA_TR_ADDR_INCREMENT 1 +#define DMA_TR_ADDR_NOCHANGE 0 + +#define DMA_WORD_WIDTH 4 + +#define DMA_TS_MAX 4095 +#define DMA_TS_BLOCK 4092 + +#define DMA_TRANSFER_COMPLETE 0 +#define DMA_TRANSFER_INCOMPLETE 1 +#define DMA_TRANSFER_ERR 2 + +#define DMA_TIMEOUT_US 50000 + +#define dma_pkt_b_to_dma_addr(_virt_addr) ((hi_u32)(_virt_addr) + PKT_B_OFFSET) +#define dma_pkt_h_to_dma_addr(_virt_addr) ((hi_u32)(_virt_addr) + PKT_H_OFFSET) + +#define DCACHE_ENABLE 1 +#define DCACHE_EN_REG 0x7C1 + +/** + * @ingroup hct_dma + * + * DMA transfer mode. CNcomment:DMA传输模式。CNend + */ +typedef enum { + DMA_MEM_TO_MEM = 0, + DMA_MEM_TO_PHL, + DMA_PHL_TO_MEM, + DMA_PHL_TO_PHL, +} hi_dma_tr_type; + +/** + * @ingroup hct_dma + * + * Peripheral ID that supports DMA transfer. CNcomment:支持DMA传输的外设ID。CNend + */ +typedef enum { + UART0_RX = 0, + UART0_TX, + UART1_RX, + UART1_TX, + UART2_RX, + UART2_TX, + SPI0_RX, + SPI0_TX, + SPI1_RX, + SPI1_TX, + I2S0_RX, + I2S0_TX, + PHL_MAX, +} hi_dma_phl; + +/** + * @ingroup hct_dma + * + * One DMA burst transmission length. CNcomment:一次DMA burst传输长度。CNend + */ +typedef enum { + DMA_BURST_MSIZE_1 = 0, + DMA_BURST_MSIZE_4, + DMA_BURST_MSIZE_8, + DMA_BURST_MSIZE_16, + DMA_BURST_MSIZE_32, + DMA_BURST_MSIZE_64, + DMA_BURST_MSIZE_128, + DMA_BURST_MSIZE_256, +} hi_dma_burst_size; + +typedef union dma_ch_sel { + struct { + hi_u32 channel_0 : 1; + hi_u32 channel_1 : 1; + hi_u32 channel_2 : 1; + hi_u32 channel_3 : 1; + hi_u32 reserved : 28; + } ch_bit; + hi_u32 ch_set_u32; +} dma_ch_sel; + +typedef union dma_init_cfg { + struct { + hi_u32 dma_en : 1; + hi_u32 master1_endianness : 1; + hi_u32 master2_endianness : 1; + hi_u32 reserved : 29; + } dma_cfg_bit; + hi_u32 dma_cfg_u32; +} dma_init_cfg; + +typedef union dma_ch_cfg { + struct { + hi_u32 en : 1; + hi_u32 src_peripheral : 4; + hi_u32 reserved0 : 1; + hi_u32 dst_peripheral : 4; + hi_u32 reserved1 : 1; + hi_u32 flow_cntrl : 3; + hi_u32 err_int_mask : 1; + hi_u32 tc_int_mask : 1; + hi_u32 lock : 1; + hi_u32 active : 1; + hi_u32 halt : 1; + hi_u32 reserved2 : 13; + } ch_cfg_bit; + hi_u32 ch_cfg_u32; +} dma_ch_cfg; + +typedef union dma_llp { + struct { + hi_u32 lms : 1; + hi_u32 reserved : 1; + hi_u32 loc : 30; + } llp_bit; + hi_u32 llp_u32; +} dma_llp; + +typedef struct dma_channel_para dma_channel_para_t; + +/** + * @ingroup dma + * + * The channel control register structure of DMA. CNcomment:DMA 通道控制寄存器结构。CNend + */ +typedef struct dma_ch_ctl_t dma_ch_ctl; +typedef union dma_ch_ctl { + struct { + hi_u32 transfer_size : 12; + hi_u32 src_burst_size : 3; + hi_u32 dst_burst_size : 3; + hi_u32 src_width : 3; + hi_u32 dst_width : 3; + hi_u32 master_src_sel : 1; + hi_u32 master_dst_sel : 1; + hi_u32 src_inc : 1; + hi_u32 dst_inc : 1; + hi_u32 prot : 3; + hi_u32 lli_tc_int_en : 1; + } ch_ctl_bit; + hi_u32 ch_ctl_u32; +} dma_ch_ctl_t; + +/** + * @ingroup dma + * + * The link structure of DMA link list item. CNcomment:DMA link list item链表结构。CNend + */ +typedef struct dma_lli_stru dma_lli_stru_t; +typedef struct dma_lli_stru { + hi_u32 saddr; + hi_u32 daddr; + dma_lli_stru_t *llp_next; + dma_ch_ctl_t st_ctl; +} dma_lli_stru_t; + +typedef struct dma_channel_para { + dma_llp llp; + dma_ch_ctl_t ch_ctl; + dma_ch_cfg ch_cfg; + hi_void (*cb)(hi_u32); + volatile hi_u32 is_transfering; + dma_lli_stru_t *ch_lli; +} dma_channel_para; + +typedef struct dma_data { + hi_bool is_inited; + volatile hi_u32 ch_mask; + dma_channel_para ch_data[DMA_CHANNEL_NUM]; +} dma_data; + +/** + * @ingroup hct_dma + * + * The general setting structure of the user's incoming DMA. It is used for the transmission participated by IO. + CNcomment:用户传入DMA的通用设置结构,主要用于外设参与的传输。CNend + */ +typedef struct hi_dma_para { + hi_u32 tr_type; + hi_u32 src_phl; + hi_u32 dst_phl; + uintptr_t src_addr; + uintptr_t dst_addr; + hi_u32 src_burst_size; + hi_u32 dst_burst_size; + hi_u32 src_width; + hi_u32 dst_width; + hi_u32 transfer_size; + hi_void (*cb)(hi_u32); +} hi_dma_para; + +/** +* @ingroup hct_dma +* @brief Start dma transmission. CNcomment:启动dma传输。CNend +* +* @par 描述: +* Start dma transmission and channel will be released after success or failure. +CNcomment:启动dma传输,成功或失败后会释放通道。CNend +* +* @attention +* @param dma_para [IN/OUT] type #hi_dma_user_para_sSetting incoming dma transfer parameter. +CNcomment:传入DMA传输参数设置。CNend +* @param block [IN] type #hi_bool,Whether to block for waiting dma tranmission completeness +CNcomment:是否阻塞等待DMA传输完成。CNend +* +* @retval #HI_ERR_SUCCESS Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_dma.h: DMA driver implementation interface. CNcomment:DMA驱动实现接口。CNend +* @see None + */ +hi_u32 hi_dma_transfer(const hi_dma_para *dma_para, hi_bool block); +/** +* @ingroup hct_dma +* @brief Start dma transmission. CNcomment:启动dma传输。CNend +* +* @par 描述: +* Start dma transmission and channel will be released after success or failure. +CNcomment:启动dma传输,成功或失败后会释放通道。CNend +* +* @attention +* @param dma_para [IN/OUT] type #hi_dma_user_para_sSetting incoming dma transfer parameter. +CNcomment:传入DMA传输参数设置。CNend +* @param dma_ch [IN] type #hi_bool,return dma channel number +CNcomment:返回申请的通道号。CNend +* +* @retval #HI_ERR_SUCCESS Success. +* @retval #Other Failure. For details, see hi_errno.h. +* @par 依赖: +* @li hi_dma.h: DMA driver implementation interface. CNcomment:DMA驱动实现接口。CNend +* @see None + */ +hi_u32 dma_hw_request_transfer(const hi_dma_para *dma_para, hi_u32 *dma_ch); +void dma_write_data(hi_u32 ch_num, const hi_dma_para *dma_para); +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif + +#endif diff --git a/sdk_liteos/platform/drivers/flash/flash_prv.h b/sdk_liteos/platform/drivers/flash/flash_prv.h new file mode 100644 index 0000000000000000000000000000000000000000..f32ba878ae3ec486f4369542d823c19d957c2bf2 --- /dev/null +++ b/sdk_liteos/platform/drivers/flash/flash_prv.h @@ -0,0 +1,431 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __FLASH_PRV_H__ +#define __FLASH_PRV_H__ +#include +#include +#include +#define flash_info_print(fmt, ...) + +#define HI_FLASH_OPTION_READ_WAIT_READY 0x1 +#define HI_FLASH_OPTION_WRITE_WAIT_READY 0x2 +#define HI_FLASH_OPTION_ERASE_WAIT_READY 0x4 +#define HI_FLASH_OPTION_WRITE_ENABLE_WAIT_READY 0x8 + +/*****************************************************************************/ +#define SPI_QE_EN 0x02 /* QE Bit Enable */ +#define SPI_CMD_WREN 0x06 /* Write Enable */ +#define SPI_CMD_VSR_WREN 0x50 /* write volatile SR reg enable */ +/*****************************************************************************/ +#define SPI_CMD_SE_4K 0x20 /* 4KB sector Erase */ +#define SPI_CMD_SE_32K 0x52 /* 32KB sector Erase */ +#define SPI_CMD_SE 0xD8 /* 64KB Sector Erase */ +#define SPI_CMD_CE1 0xC7 /* chip erase */ +#define SPI_CMD_CE2 0x60 /* chip erase */ +/*****************************************************************************/ +#define SPI_CMD_WRSR1 0x01 /* Write Status Register */ +#define SPI_CMD_WRSR2 0x31 /* Write Status Register-2 */ +#define SPI_CMD_RDSR2 0x35 /* Read Status Register-2 */ +#define SPI_CMD_WRSR3 0x11 /* Write Status Register-3 */ +#define SPI_CMD_RDSR3 0x15 /* Read Status Register-3 */ +#define SPI_CMD_RDID 0x9F /* Read Identification */ + +/* read status register. */ +#define SPI_CMD_RDSR 0x05 + +/* write status/configuration register. */ +#define SPI_CMD_WRSRCR 0x01 + +/* read configuration register. */ +#define SPI_CMD_RDCR 0x15 + +/*****************************************************************************/ +#define SPI_CMD_PP 0x02 /* Page Programming */ +#define SPI_CMD_WRITE_DUAL 0xA2 /* fast program dual input */ +#define SPI_CMD_WRITE_QUAD 0x32 /* fast program quad input */ +#define SPI_CMD_WRITE_DUAL_ADDR 0xD2 /* Dual I/O High Performance Write */ +#define SPI_CMD_WRITE_QUAD_ADDR 0x12 /* Quad I/O High Performance Write */ +/*****************************************************************************/ +#define SPI_CMD_READ 0x03 /* Read Data bytes */ +#define SPI_CMD_FAST_READ 0x0B /* Read Data Bytes at Higher Speed */ +#define SPI_CMD_READ_DUAL 0x3B /* fast read dual output */ +#define SPI_CMD_READ_QUAD 0x6B /* fast read quad output */ +#define SPI_CMD_QUAD_IO 0xEB /* fast quad-IO */ + +#define SPI_CMD_READ_DUAL_ADDR 0xBB /* Dual I/O High Performance Read */ +#define SPI_CMD_READ_QUAD_ADDR 0xEB /* Quad I/O High Performance Read */ +/*****************************************************************************/ +#define SPI_CMD_SR_WIPN 0 /* Write in Progress */ +#define SPI_CMD_SR_WIP 1 /* Write in Progress */ +#define SPI_CMD_SR_WEL 2 /* Write Enable Latch */ +/*****************************************************************************/ +#define SPI_CMD_EN4B 0xB7 /* enter to 4 bytes mode and set 4 byte bit as '1' */ +#define SPI_CMD_EX4B 0xE9 /* exit 4 bytes mode and clear 4 byte bit as '0' */ + +#define SPI_CMD_RESET_ENABLE 0x66 /* RESET Enable */ +#define SPI_CMD_RESET 0x99 /* RESET */ + +#define SPI_SR_BIT_WIP (1<<0) /* Write in Progress */ +#define SPI_SR_BIT_WEL (1<<1) /* Write Enable Latch */ + +#define _1K 0x400 +#define _2K 0x800 +#define _4K 0x1000 +#define _8K 0x2000 +#define _16K 0x4000 +#define _32K 0x8000 +#define _64K 0x10000 +#define _128K 0x20000 +#define _256K 0x40000 +#define _512K 0x80000 +#define _1M 0x100000 +#define _2M 0x200000 +#define _4M 0x400000 +#define _8M 0x800000 +#define _16M 0x1000000 +#define _32M 0x2000000 + +#define _CHIP_SIZE 0x3ffff +#define HI_FLASH_DEFAULT_TYPE_NUM 8 + +#define HI_FLASH_SUPPORT_REF_VBAT /* VBAT can be used as ref valtage */ +/* if support flash_update:#define HI_FLASH_SUPPORT_UPDATE_SFC_FREQ */ +#define HI_FLASH_VOLTAGE_TH0 280 +#define HI_FLASH_VOLTAGE_TH1 310 +#define PLL2DBB_192M_MASK 0x3 +#define CMU_CLK_SEL_96M 96 +#define CMU_CLK_SEL_80M 80 +#define CMU_CLK_SEL_48M 48 + +typedef struct { + hi_u32 cmd : 8; + hi_u32 iftype : 3; + hi_u32 dummy : 3; + hi_u32 size : 18; +} spi_flash_operation; + +typedef enum { + HI_FLASH_SUPPORT_4K_ERASE = 0x1, + HI_FLASH_SUPPORT_32K_ERASE = 0x2, + HI_FLASH_SUPPORT_64K_ERASE = 0x4, + HI_FLASH_SUPPORT_CHIP_ERASE = 0x8, + HI_FLASH_SUPPORT_AREA_LOCK_NV = 0x10, + HI_FLASH_SUPPORT_AREA_LOCK_VOLATILE = 0x20, + HI_FLASH_SUPPORT_INDIVIDUAL_LOCK = 0x40, + HI_FLASH_SUPPORT_SUSPEND_RESUME = 0x80, + HI_FLASH_VLT_INFLUENCE_FREQ = 0x100, + HI_FLASH_SUPPORT_MASK = 0xFFFF, +} hi_spi_flash_chip_attribute; + +typedef struct { + hi_char *chip_name; + hi_u8 chip_id[HI_FLASH_CHIP_ID_NUM]; + hi_u8 freq_read; + hi_u8 freq_lowpower; + hi_u8 freq_hpm; + hi_u16 chip_attribute; + hi_u8 cmd_suspend; + hi_u8 cmd_resume; + hi_u8 cmd_readsr; + hi_u8 sus_bits; +} hi_spi_flash_basic_info; + +typedef struct { + hi_u32 flash_offset; + hi_u8 *ram_data; + hi_u32 size; +} spi_flash_prv_addr_info; + +typedef struct { + hi_u8 chip_id[HI_FLASH_CHIP_ID_NUM]; /* flash chip ID */ + hi_u8 freq_high : 2; + hi_u8 freq_midle : 2; + hi_u8 freq_low : 2; + hi_u8 voltage : 2; +} flash_vlt_sfc_info; + +#define HI_FLASH_SUPPORT_CHIPS (HI_FLASH_SUPPORT_4K_ERASE | \ + HI_FLASH_SUPPORT_64K_ERASE | \ + HI_FLASH_SUPPORT_CHIP_ERASE | \ + HI_FLASH_SUPPORT_AREA_LOCK_NV | \ + HI_FLASH_SUPPORT_AREA_LOCK_VOLATILE) +#define HI_FLASH_SUPPORT_DEFAULT (HI_FLASH_SUPPORT_4K_ERASE | \ + HI_FLASH_SUPPORT_64K_ERASE | \ + HI_FLASH_SUPPORT_CHIP_ERASE) + +#define PRODUCT_CFG_FLASH_BLOCK_SIZE 0x1000 +/*****************************************************************************/ +#define HISFC300_DMA_MAX_SIZE 2048 +#define HISFC300_DMA_MAX_MASK 0x7FF + +/*****************************************************************************/ +#define HISFC300_REG_BUF_SIZE 64 +#define HISFC300_REG_BUF_MASK 0x3F + +#define HISFC300_BUS_CONFIG2 0x0204 +#define HISFC300_BUS_BASE_ADDR_CS1 0x0218 +#define HISFC300_BUS_ALIAS_ADDR 0x021C +#define HISFC300_BUS_ALIAS_CS 0x0220 +#define HISFC300_CMD_DATABUF64 0x04FC + +/***************SFC of Hi1131HV100********************************************/ +#define SFC_REG_BASE_ADDRESS HI_SFC_REG_BASE +#define SFC_BUFFER_BASE_ADDRESS 0x400000 + +#define SFC_REG_GLOBAL_CONFIG 0x0100 +#define SFC_REG_GLOBAL_CONFIG_ADDR_MODE_4B (1 << 2) +#define SFC_REG_TIMING 0x0110 +#define SFC_REG_GLOBAL_CONFIG_WP_ENABLE (1<<1) +#define sfc_timing_tshsl(_n) ((_n) & 0xF) +#define sfc_timing_tshwl(_n) (((_n) & 0xF) << 4) +#define sfc_timing_tcss(_n) (((_n) & 0x7) << 8) +#define sfc_timing_tcsh(_n) (((_n) & 0x7) << 12) +#define sfc_timing_trpd(_n) (((_n) & 0xFFF) << 16) +#define SFC_REG_INT_RAW_STATUS 0x0120 +#define SFC_REG_INT_RAW_STATUS_DMA_DONE (1<<1) +#define SFC_REG_INT_STATUS 0x0124 +#define SFC_REG_INT_MASK 0x0128 +#define SFC_REG_INT_CLEAR 0x012C +#define SFC_REG_INT_CLEAR_DMA_DONE (1<<1) +#define SFC_REG_VERSION 0x01F8 +#define SFC_REG_VERSION_SEL 0x01FC + +#define SFC_REG_BUS_CONFIG1 0x0200 +#define SFC_REG_BUS_CONFIG1_MASK_RD 0x8000ffff +#define SFC_REG_BUS_CONFIG1_MASK_WT 0x7fff0000 + +#define sfc_bus_config1_wr_ins(_n) (((_n) & 0xFF) << 22) +#define sfc_bus_config1_rd_ins(_n) (((_n) & 0xFF) << 8) +#define sfc_bus_config1_rd_prefetch_cnt(_n) (((_n) & 0x3) << 6) +#define sfc_bus_config1_rd_dummy_bytes(_n) (((_n) & 0x7) << 3) +#define sfc_bus_config1_rd_mem_if_type(_n) ((_n) & 0x7) +#define SFC_BUS_CONFIG1_RD_ENABLE ((hi_u32)1 << 31) + +#define SFC_REG_BUS_FLASH_SIZE 0x0210 +#define SFC_REG_BUS_BASE_ADDR_CS0 0x0214 +#define SFC_REG_BUS_BASE_ADDR_CS1 0x0218 + +#define SFC_REG_BUS_DMA_CTRL 0X0240 +#define SFC_BUS_DMA_CTRL_START (1<<0) +#define sfc_bus_dma_ctrl_read(_dir) ((_dir) << 1) +#define sfc_bus_dma_ctrl_cs(_cs) (((_cs) & 0x01) << 4) +#define SFC_REG_BUS_DMA_MEM_SADDR 0X0244 /* DMA DDR start address R */ +#define SFC_REG_BUS_DMA_FLASH_SADDR 0X0248 +#define SFC_REG_BUS_DMA_LEN 0x024C +#define SFC_REG_BUS_DMA_AHB_CTRL 0X0250 +#define SFC_BUS_DMA_AHB_CTRL_INCR4_EN (1<<0) +#define SFC_BUS_DMA_AHB_CTRL_INCR8_EN (1<<1) +#define SFC_BUS_DMA_AHB_CTRL_INCR16_EN (1<<2) + +#define SFC_REG_CMD_CONFIG 0x0300 +#define sfc_cmd_config_mem_if_type(_n) (((_n) & 0x07) << 17) +#define sfc_cmd_config_data_cnt(_n) ((((_n) - 1) & HISFC300_REG_BUF_MASK) << 9) +#define SFC_CMD_CONFIG_RW (1<<8) +#define SFC_CMD_CONFIG_DATA_EN (1<<7) +#define sfc_cmd_config_dummy_byte_cnt(_n) (((_n) & 0x07) << 4) +#define SFC_CMD_CONFIG_ADDR_EN (1<<3) +#define SFC_CMD_CONFIG_SEL_CS (0x01 << 1) +#define SFC_CMD_CONFIG_START (1 << 0) +#define SFC_REG_CMD_INS 0x0308 + +#define SFC_REG_CMD_ADDR 0x030C +#define SFC_CMD_ADDR_MASK 0x3FFFFFFF +#define SFC_REG_CMD_DATABUF1 0x0400 + +#define SPI_SR3_DRV_MASK 0x3 + +#define SFC_ERASE_OPT_MAX_NUM 4 + +typedef enum { + SPI_SR3_DRV_100PCT = 0, + SPI_SR3_DRV_75PCT, + SPI_SR3_DRV_50PCT, + SPI_SR3_DRV_25PCT, + SPI_SR3_DRV_MAX, +} hi_flash_drv_strength; + +#define SFC_CMD_WRITE (0<<8) +#define SFC_CMD_READ (1<<8) + +typedef enum { + HI_FLASH_CHECK_PARAM_OPT_READ, + HI_FLASH_CHECK_PARAM_OPT_WRITE, + HI_FLASH_CHECK_PARAM_OPT_ERASE, +} hi_flash_check_param_opt; + +typedef struct spi_flash_ctrl { + hi_bool init; + hi_bool sus_enable; + hi_bool limit_0_to_1; + hi_u8 reserve; + hi_spi_flash_basic_info basic_info; + spi_flash_operation opt_read; + spi_flash_operation opt_write; + spi_flash_operation array_opt_erase[SFC_ERASE_OPT_MAX_NUM]; + hi_u32 chip_size; + hi_u32 erase_size; + hi_u32 dma_ram_size; + hi_u8 *dma_ram_buffer; + hi_u8 *back_up_buf; + hi_u32 (*read)(struct spi_flash_ctrl* spif_ctrl, hi_u32 flash_addr, hi_u32 read_size, + hi_void* ram_addr, hi_bool b_is_crash); + hi_u32 (*write)(struct spi_flash_ctrl* spif_ctrl, hi_u32 flash_addr, hi_u32 write_size, + hi_void* ram_addr, hi_bool b_is_crash); + hi_u32 (*erase)(struct spi_flash_ctrl* spif_ctrl, hi_u32 flash_addr, hi_u32 erase_size, hi_bool is_crash); + hi_bool (*is_busy)(hi_void); + hi_u32 mutex_handle; + hi_pvoid usr_data; +} hi_spi_flash_ctrl; + +/*****************************************************************************/ +#define hisfc_read(_reg) \ + reg_read_val(SFC_REG_BASE_ADDRESS +(_reg)) + +#define hisfc_write(_reg, _value) \ + reg_write32(SFC_REG_BASE_ADDRESS + (_reg), (_value)) + +HI_EXTERN hi_u32 spi_flash_read_chip_id(hi_u8 *chip_id, hi_u8 id_len); +HI_EXTERN hi_u32 spi_flash_configure_driver_strength(hi_flash_drv_strength drv_strength); + +HI_EXTERN hi_u32 spif_map_chipsize(hi_u32 chip_size); +HI_EXTERN hi_u32 spif_dma_read(hi_spi_flash_ctrl* spif_ctrl, hi_u32 flash_addr, hi_u32 read_size, + hi_void* ram_addr, hi_bool is_crash); +HI_EXTERN hi_u32 spif_reg_erase(hi_spi_flash_ctrl* spif_ctrl, hi_u32 flash_addr, hi_u32 erase_size, hi_bool is_crash); +HI_EXTERN hi_u32 spif_dma_write(hi_spi_flash_ctrl* spif_ctrl, hi_u32 flash_addr, hi_u32 write_size, + hi_void* ram_addr, hi_bool is_crash); +HI_EXTERN hi_bool spif_is_busy(hi_void); +HI_EXTERN hi_u32 spi_flash_basic_info_probe(HI_INOUT hi_spi_flash_ctrl* spif_ctrl, hi_u8 *chip_id, + hi_u8 id_len, hi_spi_flash_basic_info *spi_info_tbl, hi_u32 tbl_size); +HI_EXTERN hi_u32 flash_write_prv(hi_spi_flash_ctrl* spif_ctrl, const spi_flash_prv_addr_info *info, hi_bool do_erase, + hi_bool is_crash); +HI_EXTERN hi_u32 flash_erase_prv(hi_spi_flash_ctrl* spif_ctrl, hi_u32 flash_addr, hi_u32 size, hi_bool is_crash); +HI_EXTERN hi_u32 flash_read_prv(hi_spi_flash_ctrl* spif_ctrl, const spi_flash_prv_addr_info *info, hi_bool is_crash); +HI_EXTERN hi_u32 flash_suspend_prv_default(const hi_spi_flash_ctrl *spif_ctrl, hi_u32 timeout); +HI_EXTERN hi_void flash_resume_prv_default(const hi_spi_flash_ctrl *spif_ctrl, hi_u32 timeout); +HI_EXTERN hi_void spif_send_cmd(hi_u8 cmd); +HI_EXTERN hi_u32 spi_flash_read_reg(hi_u8 cmd, hi_u8 *data, hi_u8 data_len); +HI_EXTERN hi_u32 spi_flash_write_reg(hi_u8 cmd, const hi_u8 *data, hi_u8 data_len); +HI_EXTERN hi_u32 sfc_check_para(const hi_spi_flash_ctrl* spif_ctrl, hi_u32 addr, hi_u32 size, + hi_flash_check_param_opt opt); +HI_EXTERN hi_u32 flash_ioctl(const hi_spi_flash_ctrl* spif_ctrl, hi_u16 cmd, hi_void* data); +HI_EXTERN hi_u32 spi_flash_enable_quad_mode(hi_void); +HI_EXTERN hi_void spif_bus_config(const spi_flash_operation* spi_operation, hi_u8 cmd, hi_bool blto_read); +HI_EXTERN hi_void spif_register_irq_soft_patch(hi_void_callback prepare, hi_void_callback resume); +HI_EXTERN hi_void spif_wait_config_start(hi_void); +HI_EXTERN hi_u32 spif_write_enable(hi_bool is_crash); +HI_EXTERN hi_u32 spif_wait_ready(hi_bool is_crash, hi_u8 val, hi_u8 bit_mask); + + +HI_EXTERN HI_CONST spi_flash_operation g_spi_opt_standard_read; +HI_EXTERN HI_CONST spi_flash_operation g_spi_opt_fast_read; +HI_EXTERN HI_CONST spi_flash_operation g_spi_opt_fast_dual_out_read; +HI_EXTERN HI_CONST spi_flash_operation g_spi_opt_fast_quad_out_read; +HI_EXTERN HI_CONST spi_flash_operation g_spi_opt_fast_quad_eb_out_read; + +HI_EXTERN HI_CONST spi_flash_operation g_spi_opt_page_program_write; + +HI_EXTERN HI_CONST spi_flash_operation g_spi_opt_sector_erase; +HI_EXTERN HI_CONST spi_flash_operation g_spi_opt_32k_erase; +HI_EXTERN HI_CONST spi_flash_operation g_spi_opt_64k_erase; +HI_EXTERN HI_CONST spi_flash_operation g_spi_opt_chip_erase1; +HI_EXTERN HI_CONST spi_flash_operation g_spi_opt_chip_erase2; +HI_EXTERN HI_CONST hi_spi_flash_basic_info g_flash_default_info_tbl[HI_FLASH_DEFAULT_TYPE_NUM]; + +#ifdef HI_FLASH_SUPPORT_REF_VBAT +#ifdef HI_FLASH_SUPPORT_UPDATE_SFC_FREQ +hi_u32 sfc_config_get_update_time(hi_u32 *time_ms); +hi_u32 sfc_config_set_update_time(hi_u32 time_ms); +hi_void sfc_config_set_voltage_threshold_increment(hi_u8 voltage_increment); +hi_u32 sfc_config_get_voltage_threshold_increment(hi_u8 *voltage_increment); + +#endif +#endif + +/* flash protect */ +#define PROTECT_TIMEOUT_1 6000 +#define PROTECT_TIMEOUT_2 3600000 +#define PROTECT_TIMEOUT_AUTO 0xFFFFFFFF +#define PROTECT_FLASH_ALL 0x6 /* 0x6: 000110 */ + +#ifdef HI_BOARD_ASIC +/* if support flash protect:#define HI_FLASH_SUPPORT_FLASH_PROTECT */ +#define HI_FLASH_SUPPORT_FLASH_PROTECT +#endif + +typedef enum { + HI_FLASH_PROTECT_TYPE_1 = 0x0, + HI_FLASH_PROTECT_TYPE_2, + HI_FLASH_PROTECT_NONE, + HI_FLASH_PROTECT_TYPE_MAX, +}hi_flash_protect_type; + +typedef struct { + hi_u32 default_type : 6; + hi_u32 enable : 1; + hi_u32 is_volatile : 1; + hi_u32 init : 1; + hi_u32 current_block : 13; + hi_u32 reserve : 10; + hi_u32 timer_timeout; + hi_u32 timer_handle; +} hi_flash_protect_ctrl; + +typedef struct { + hi_u32 cmp_bp : 6; + hi_u32 block : 13; + hi_u32 reseve : 13; +} hi_flash_protect_size; + +typedef struct { + hi_u32 support_flash_protect : 1; + hi_u32 protect_all : 1; + hi_u32 reserve : 30; + hi_u32 (*protect_all_area)(hi_void); +} support_flash_protect; +support_flash_protect *flash_get_support_flash_protect_info(hi_void); +hi_spi_flash_ctrl *flash_get_spi_flash_ctrl_info(hi_void); + +#ifdef HI_FLASH_SUPPORT_FLASH_PROTECT +hi_u32 flash_protect(hi_u32 flash_offset, hi_u32 size, hi_u32 timeout, hi_bool is_volatile); +hi_u32 flash_protect_set_protect(hi_u8 cmp_bp, hi_bool is_volatile, hi_bool forced_write); +#endif +hi_u32 hi_flash_protect_init(hi_flash_protect_type type); +hi_u32 hi_flash_protect_deinit(hi_void); +hi_u32 hi_flash_protect_enable(hi_bool enable); + +hi_u32 flash_lock(hi_void); +hi_u32 flash_unlock(hi_void); +hi_u8 get_flash_op_during_flash(void); /* flash option is during crash */ + +hi_u32 hi_flash_write_fs(const hi_u32 flash_offset, hi_u32 size, const hi_u8 *ram_data, hi_bool do_erase); + +#ifdef HI_FLASH_SUPPORT_COUNT_DEBUG + +#define SECTOR_SIZE 4096 +#define SECTOR_NUM 512 +#define FLASH_OPT_RECORD_SIZE 2048 +typedef struct { + hi_u16 write_times[SECTOR_NUM]; + hi_u16 erase_times[SECTOR_NUM]; +} hi_flash_opt_record; /* 2KB */ + +hi_void hi_flash_record_opt_init(hi_void); +hi_flash_opt_record* hi_flash_get_opt_record(hi_void); +#endif + +hi_void hi_flash_record_flash_opt(hi_void); + +#endif diff --git a/sdk_liteos/platform/drivers/i2c/SConscript b/sdk_liteos/platform/drivers/i2c/SConscript new file mode 100755 index 0000000000000000000000000000000000000000..b0e5f0e2b015ebbec8bd8a4344149640ab49ef09 --- /dev/null +++ b/sdk_liteos/platform/drivers/i2c/SConscript @@ -0,0 +1,4 @@ +Import('env') + +objs = env.Object(Glob('*.c')) +Return('objs') diff --git a/sdk_liteos/platform/drivers/i2c/i2c.c b/sdk_liteos/platform/drivers/i2c/i2c.c new file mode 100644 index 0000000000000000000000000000000000000000..c080b7e7e8d6eef70696d71950a80713e1849778 --- /dev/null +++ b/sdk_liteos/platform/drivers/i2c/i2c.c @@ -0,0 +1,865 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "i2c.h" +#include +#include +#include +#include + +#define I2C0_BASE HI_I2C0_REG_BASE +#define I2C1_BASE HI_I2C1_REG_BASE +#define CLKEN_I2C0 14 +#define CLKEN_I2C1 15 + +hi_u32 g_i2c_drv_sem[2] = {0xffffffff, 0xffffffff}; // for 2 i2c + +hi_u32 g_i2c_rcv_time_out_us = 4096; + +typedef struct { + hi_u32 baudrate; + i2c_reset_func reset_bus_func; + i2c_prepare_func prepare_func; + i2c_restore_func restore_func; + hi_u16 timeout_us; + hi_u8 scl_h : 3; + hi_u8 scl_l : 3; + hi_bool init : 1; + hi_bool pad : 1; + hi_u8 err_times; +} hi_i2c_ctrl; + +/* timeout_us unused */ +hi_i2c_ctrl g_i2c_ctrl[I2C_NUM] = { + { 0, HI_NULL, HI_NULL, HI_NULL, 3000, 1, 1, HI_FALSE, 0, 0 }, + { 0, HI_NULL, HI_NULL, HI_NULL, 3000, 1, 1, HI_FALSE, 0, 0 } +}; + +hi_void i2c_read(hi_i2c_idx id); +hi_void i2c_write(hi_i2c_idx id); + +hi_u32 i2c_reset(hi_i2c_idx id) +{ + hi_u32 value; + hi_u32 ret; + + hi_reg_read32(CRG_REG_SC_PERI_SRST_REG, value); + value |= (1 << CRG_REG_I2C_SRST_REQ_OFFSET); + hi_reg_write32(CRG_REG_SC_PERI_SRST_REG, value); + value &= ~(1 << CRG_REG_I2C_SRST_REQ_OFFSET); + hi_reg_write32(CRG_REG_SC_PERI_SRST_REG, value); + + ret = hi_i2c_deinit(id); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + if (!g_i2c_ctrl[id].baudrate) { + hi_i2c_init(id, g_i2c_ctrl[id].baudrate); + } else { + hi_i2c_init(id, I2C_RATE_DEFAULT); + } + return HI_ERR_SUCCESS; +} + +static hi_u32 i2c_base(hi_i2c_idx id) +{ + if (id == HI_I2C_IDX_0) { + return I2C0_BASE; + } + return I2C1_BASE; +} + +static hi_u32 i2c_wait(hi_i2c_idx id) +{ + hi_u32 reg_val = 0; + hi_u32 time_out = 0; + + hi_reg_read32((i2c_base(id) + I2C_SR), reg_val); + while ((!(reg_val & I2C_INT_DONE)) && (time_out < g_i2c_ctrl[id].timeout_us)) { + time_out++; + hi_udelay(1); + hi_reg_read32((i2c_base(id) + I2C_SR), reg_val); + } + + if (time_out >= g_i2c_ctrl[id].timeout_us) { + i2c_error("wait-timeout >= TIMEOUT error ! \n"); + return HI_ERR_I2C_TIMEOUT_WAIT; + } + + /* ack error occur */ + if (I2C_ACK_INTR & reg_val) { + return HI_ERR_I2C_WAIT_ACK_ERR; + } + + hi_reg_read32((i2c_base(id) + I2C_ICR), reg_val); + hi_reg_write32((i2c_base(id) + I2C_ICR), (reg_val | I2C_CLEAR_OVER)); + + return HI_ERR_SUCCESS; +} + +static hi_void i2c_cfg_clk(hi_i2c_idx id, hi_u32 i2c_rate) +{ + hi_u32 reg_val = 0; + hi_u32 reg_clk_val; + + /* save i2c system control */ + hi_reg_read32((i2c_base(id) + I2C_CTRL), reg_val); + + /* mask all i2c interrupt */ + hi_reg_write32((i2c_base(id) + I2C_CTRL), (reg_val & (~I2C_UNMASK_ALL))); + reg_clk_val = (I2C_CLK / (i2c_rate * 2)) * /* 2 */ + g_i2c_ctrl[id].scl_h / (g_i2c_ctrl[id].scl_l + g_i2c_ctrl[id].scl_h) - 1; + hi_reg_write32((i2c_base(id) + I2C_SCL_H), reg_clk_val); + reg_clk_val = (I2C_CLK / (i2c_rate * 2)) * /* 2 */ + g_i2c_ctrl[id].scl_l / (g_i2c_ctrl[id].scl_l + g_i2c_ctrl[id].scl_h) - 1; + hi_reg_write32((i2c_base(id) + I2C_SCL_L), reg_clk_val); + + /* resume i2c interrupt */ + hi_reg_write32((i2c_base(id) + I2C_CTRL), reg_val); +} + +static hi_u32 i2c_start(hi_i2c_idx id) +{ + hi_u32 reg_val = 0; + hi_u32 time_out = 0; + + /* clear interrupt */ + hi_reg_write32((i2c_base(id) + I2C_ICR), I2C_CLEAR_ALL); + + /* start operation */ + hi_reg_write32((i2c_base(id) + I2C_COM), (I2C_START | I2C_WRITE)); + + hi_reg_read32((i2c_base(id) + I2C_SR), reg_val); + + while (((reg_val & I2C_INT_DONE) != I2C_INT_DONE) && (time_out < g_i2c_ctrl[id].timeout_us)) { + time_out++; + hi_reg_read32((i2c_base(id) + I2C_SR), reg_val); + hi_udelay(1); + } + + hi_reg_write32((i2c_base(id) + I2C_ICR), I2C_START_END); + + /* timeout handle */ + if (time_out >= g_i2c_ctrl[id].timeout_us) { + i2c_error("timeout >= TIMEOUT error ! \n"); + return HI_ERR_I2C_TIMEOUT_START; + } + + if (I2C_ACK_INTR & reg_val) { /* ack error occur */ + return HI_ERR_I2C_START_ACK_ERR; + } + + hi_reg_write32((i2c_base(id) + I2C_ICR), I2C_CLEAR_OVER); + + return HI_ERR_SUCCESS; +} + +static hi_u32 i2c_stop(hi_i2c_idx id) +{ + hi_u32 reg_val = 0; + hi_u32 time_out = 0; + + /* start stop operation */ + hi_reg_write32((i2c_base(id) + I2C_COM), I2C_STOP); + hi_reg_read32((i2c_base(id) + I2C_SR), reg_val); + + while (((reg_val & I2C_INT_DONE) != I2C_INT_DONE) && (time_out < g_i2c_ctrl[id].timeout_us)) { + hi_reg_read32((i2c_base(id) + I2C_SR), reg_val); + hi_udelay(1); + time_out++; + } + + hi_reg_write32((i2c_base(id) + I2C_ICR), I2C_CLEAR_ALL); + + if (time_out >= g_i2c_ctrl[id].timeout_us) { + i2c_error("timeout >= TIMEOUT in i2c_stop error ! \n"); + return HI_ERR_I2C_TIMEOUT_STOP; + } + + return HI_ERR_SUCCESS; +} + +hi_void i2c_read(hi_i2c_idx id) +{ + hi_reg_write32((i2c_base(id) + I2C_ICR), I2C_CLEAR_ALL); + hi_reg_write32((i2c_base(id) + I2C_COM), I2C_READ); +} + +hi_void i2c_write(hi_i2c_idx id) +{ + /* clear interrupt */ + hi_reg_write32((i2c_base(id) + I2C_ICR), I2C_CLEAR_ALL); + + /* write operation */ + hi_reg_write32((i2c_base(id) + I2C_COM), I2C_WRITE); +} + +/* + * sends a character over I2C bus routine. + * + * @param sendvalue: character to send + * @return value:0--success; -1--error. + * + */ +static hi_u32 i2c_send_byte(hi_i2c_idx id, hi_u8 send_val) +{ + hi_reg_write32((i2c_base(id) + I2C_TXR), send_val); + i2c_write(id); + + return i2c_wait(id); +} + +/* + * receives a character from I2C bus routine. + * + * @return value:character received + * + */ +static hi_u32 i2c_receive_byte(hi_i2c_idx id, hi_u8 *p_data) +{ + hi_u32 ret; + hi_u32 reg_val = 0; + hi_u32 time_out = 0; + + if (p_data == HI_NULL) { + i2c_error("null point.\n"); + return HI_ERR_I2C_INVALID_PARAMETER; + } + + i2c_read(id); + + hi_reg_read32((i2c_base(id) + I2C_SR), reg_val); + while ((!(reg_val & I2C_INT_DONE)) && (time_out < g_i2c_ctrl[id].timeout_us)) { + time_out++; + hi_udelay(1); + hi_reg_read32((i2c_base(id) + I2C_SR), reg_val); + } + + if (time_out >= g_i2c_ctrl[id].timeout_us) { + i2c_error("receive data error\n"); + return HI_ERR_I2C_TIMEOUT_RCV_BYTE; + } + + hi_reg_read32((i2c_base(id) + I2C_RXR), reg_val); + *p_data = (hi_u8)(reg_val); + ret = i2c_wait(id); + if (ret != HI_ERR_SUCCESS) { + i2c_error("read wait timeout.\n"); + } + + hi_reg_write32((i2c_base(id) + I2C_ICR), (I2C_RECEIVE_INTR | I2C_INT_DONE)); + + return ret; +} + +/* + * writes address of device to I2C bus routine. + * + * @param address: address of device + * + */ +static hi_void i2c_set_addr(hi_i2c_idx id, hi_u16 addr) +{ + hi_reg_write32((i2c_base(id) + I2C_TXR), addr); +} + +static hi_bool i2c_is_10bit_addr(hi_u16 uc_addr) +{ + if ((uc_addr & 0xF000) == 0xF000) { + return HI_TRUE; + } + return HI_FALSE; +} + +static hi_u32 i2c_10bit_send_addressing(hi_i2c_idx id, hi_u16 device_addr) +{ + hi_u32 ret; + /* 10bit: */ + /* Send 5 bits signaling 10 bit addressing(1111 0) + followed by the first two bits of the I2C address + and then the standard read/write bit. */ + hi_u8 addr = device_addr >> 8; /* 8 */ + + i2c_set_addr(id, addr & WRITE_OPERATION); /* R/W -> W(0) */ + ret = i2c_start(id); + if (ret != HI_ERR_SUCCESS) { + hi_reg_write32((i2c_base(id) + I2C_ICR), I2C_CLEAR_ALL); + /* for testing */ + i2c_error("10bit SEND first addressing failed!"); + return ret; + } + + addr = (hi_u8)device_addr; + i2c_set_addr(id, addr); /* second addressing */ + ret = i2c_start(id); + if (ret != HI_ERR_SUCCESS) { + hi_reg_write32((i2c_base(id) + I2C_ICR), I2C_CLEAR_ALL); + /* for testing */ + i2c_error("10bit SEND second addressing failed!"); + return ret; + } + return HI_ERR_SUCCESS; +} + +static hi_u32 i2c_10bit_receive_addressing(hi_i2c_idx id, hi_u16 device_addr) +{ + hi_u32 ret; + /* 10bit: */ + /* send the complete 10-bit address (two bytes) as for writing at first */ + /* first addressing R/W->W(0) */ + hi_u8 addr = device_addr >> 8; /* 8 */ + + i2c_set_addr(id, addr & WRITE_OPERATION); /* R/W -> W(0) */ + ret = i2c_start(id); + if (ret != HI_ERR_SUCCESS) { + hi_reg_write32((i2c_base(id) + I2C_ICR), I2C_CLEAR_ALL); + /* for testing */ + i2c_error("10bit RECEIVE first addressing failed"); + return ret; + } + + /* second addressing */ + addr = (hi_u8)device_addr; + + i2c_set_addr(id, addr); + ret = i2c_start(id); + if (ret != HI_ERR_SUCCESS) { + hi_reg_write32((i2c_base(id) + I2C_ICR), I2C_CLEAR_ALL); + /* for testing */ + i2c_error("10bit RECEIVE second addressing failed"); + return ret; + } + + /* a repeated start is sent followed by the first address byte + with read/write bit set to high to signal reading */ + /* third addressing R/W->R(1) */ + addr = device_addr >> 8; /* 8 */ + + i2c_set_addr(id, addr | READ_OPERATION); + ret = i2c_start(id); + if (ret != HI_ERR_SUCCESS) { + hi_reg_write32((i2c_base(id) + I2C_ICR), I2C_CLEAR_ALL); + /* for testing */ + i2c_error("10bit RECEIVE after SR addressing failed"); + return ret; + } + return HI_ERR_SUCCESS; +} + +static hi_u32 i2c_receive_last_byte(hi_i2c_idx id, hi_u8 *p_data) +{ + hi_u32 reg_val = 0; + hi_u32 ret; + hi_u32 time_out = 0; + + hi_reg_write32((i2c_base(id) + I2C_COM), (I2C_READ | (~I2C_SEND_ACK))); + hi_reg_read32((i2c_base(id) + I2C_SR), reg_val); + while ((!(reg_val & I2C_INT_DONE)) && (time_out < g_i2c_rcv_time_out_us)) { + time_out++; + hi_udelay(1); + hi_reg_read32((i2c_base(id) + I2C_SR), reg_val); + } + + if (time_out >= g_i2c_rcv_time_out_us) { + i2c_error("receive data error\n"); + hi_reg_write32((i2c_base(id) + I2C_ICR), I2C_CLEAR_ALL); + return HI_ERR_I2C_TIMEOUT_RCV_BYTE_PROC; + } + + hi_reg_read32((i2c_base(id) + I2C_RXR), reg_val); + if (p_data != HI_NULL) { + *p_data = (hi_u8)reg_val; + } + ret = i2c_wait(id); + if (ret != HI_ERR_SUCCESS) { + i2c_error("Receive data with no ack error!..\n"); + hi_reg_write32((i2c_base(id) + I2C_ICR), I2C_CLEAR_ALL); + return ret; + } + + return HI_ERR_SUCCESS; +} + +static hi_u32 i2c_receive_byte_proc(hi_i2c_idx id, const hi_i2c_data *i2c_data) +{ + hi_u32 ret; + hi_u32 i; + + for (i = 0; i < (i2c_data->receive_len); i++) { + if (i == (i2c_data->receive_len - 1)) { + ret = i2c_receive_last_byte(id, i2c_data->receive_buf + i); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + } else { + ret = i2c_receive_byte(id, i2c_data->receive_buf + i); + if (ret != HI_ERR_SUCCESS) { + i2c_error("i2c_receive_byte error ! \n"); + hi_reg_write32((i2c_base(id) + I2C_ICR), I2C_CLEAR_ALL); + return ret; + } + } + } + + hi_reg_write32((i2c_base(id) + I2C_ICR), I2C_CLEAR_OVER); + + ret = i2c_stop(id); + if (ret != HI_ERR_SUCCESS) { + hi_reg_write32((i2c_base(id) + I2C_ICR), I2C_CLEAR_ALL); + return ret; + } + + return HI_ERR_SUCCESS; +} + +static hi_u32 i2c_restart_receive_data(hi_i2c_idx id, hi_u8 device_addr, const hi_i2c_data *i2c_data) +{ + hi_u32 i; + hi_u32 ret; + + hi_reg_write32((i2c_base(id) + I2C_CTRL), + (I2C_IP_ENABLE | I2C_UNMASK_ALL | I2C_UNMASK_ACK | I2C_UNMASK_ARBITRATE | I2C_UNMASK_OVER)); + + hi_reg_write32((i2c_base(id) + I2C_ICR), I2C_CLEAR_ALL); + + /* write device addr */ + if (i2c_is_10bit_addr(device_addr) == HI_TRUE) { + ret = i2c_10bit_send_addressing(id, device_addr); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + } else { + /* 7bit addressing */ + i2c_set_addr(id, device_addr & WRITE_OPERATION); + ret = i2c_start(id); + if (ret != HI_ERR_SUCCESS) { + i2c_error("start error when write address.\n"); + hi_reg_write32((i2c_base(id) + I2C_ICR), I2C_CLEAR_ALL); + return ret; + } + } + + /* write register addr */ + for (i = 0; i < (i2c_data->send_len); i++) { + ret = i2c_send_byte(id, *(i2c_data->send_buf + i)); + if (ret != HI_ERR_SUCCESS) { + i2c_error("no ack.\n"); + hi_reg_write32((i2c_base(id) + I2C_ICR), I2C_CLEAR_ALL); + return ret; + } + } + + /* read device addr */ + if (i2c_is_10bit_addr(device_addr) == HI_TRUE) { + ret = i2c_10bit_receive_addressing(id, device_addr); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + } else { + /* 7bit addressing */ + i2c_set_addr(id, device_addr | READ_OPERATION); + ret = i2c_start(id); + if (ret != HI_ERR_SUCCESS) { + i2c_error("start error when write address.\n"); + hi_reg_write32((i2c_base(id) + I2C_ICR), I2C_CLEAR_ALL); + return ret; + } + } + + /* read data */ + ret = i2c_receive_byte_proc(id, i2c_data); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + return HI_ERR_SUCCESS; +} + +static hi_u32 i2c_send_data(hi_i2c_idx id, hi_u16 device_addr, const hi_i2c_data *i2c_data) +{ + hi_u32 i; + hi_u32 ret; + + hi_reg_write32((i2c_base(id) + I2C_CTRL), + (I2C_IP_ENABLE | I2C_UNMASK_ALL | I2C_UNMASK_ACK | I2C_UNMASK_ARBITRATE | I2C_UNMASK_OVER)); + + /* clear all i2c interrupt */ + hi_reg_write32((i2c_base(id) + I2C_ICR), I2C_CLEAR_ALL); + + i2c_set_addr(id, device_addr & WRITE_OPERATION); + + if (i2c_is_10bit_addr(device_addr) == HI_TRUE) { + ret = i2c_10bit_send_addressing(id, device_addr); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + } else { + /* 7bit addressing */ + i2c_set_addr(id, device_addr & WRITE_OPERATION); + ret = i2c_start(id); + if (ret != HI_ERR_SUCCESS) { + hi_reg_write32((i2c_base(id) + I2C_ICR), I2C_CLEAR_ALL); + return ret; + } + } + + for (i = 0; i < (i2c_data->send_len); i++) { + ret = i2c_send_byte(id, *(i2c_data->send_buf + i)); + if (ret != HI_ERR_SUCCESS) { + i2c_error("i2csendbyte() error ! \n"); + hi_reg_write32((i2c_base(id) + I2C_ICR), I2C_CLEAR_ALL); + return ret; + } + } + + ret = i2c_stop(id); + if (ret != HI_ERR_SUCCESS) { + hi_reg_write32((i2c_base(id) + I2C_ICR), I2C_CLEAR_ALL); + return ret; + } + + return HI_ERR_SUCCESS; +} + +static hi_u32 i2c_receive_data(hi_i2c_idx id, hi_u16 device_addr, const hi_i2c_data *i2c_data) +{ + hi_u32 ret; + + hi_reg_write32((i2c_base(id) + I2C_CTRL), + (I2C_IP_ENABLE | I2C_UNMASK_ALL | I2C_UNMASK_ACK | I2C_UNMASK_ARBITRATE | I2C_UNMASK_OVER)); + + /* clear all i2c interrupt */ + hi_reg_write32((i2c_base(id) + I2C_ICR), I2C_CLEAR_ALL); + + if (i2c_is_10bit_addr(device_addr) == HI_TRUE) { + ret = i2c_10bit_receive_addressing(id, device_addr); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + } else { + /* 7bit addressing */ + i2c_set_addr(id, device_addr | READ_OPERATION); + ret = i2c_start(id); + if (ret != HI_ERR_SUCCESS) { + i2c_error("start error when write address.\n"); + hi_reg_write32((i2c_base(id) + I2C_ICR), I2C_CLEAR_ALL); + return ret; + } + ret = i2c_receive_byte_proc(id, i2c_data); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + } + + return HI_ERR_SUCCESS; +} + +static hi_u32 i2c_read_param_check(hi_i2c_idx id, const hi_i2c_data *i2c_data) +{ + if (id > HI_I2C_IDX_1 || id < HI_I2C_IDX_0) { + return HI_ERR_I2C_INVALID_PARAMETER; + } + + if (id >= I2C_NUM) { + return HI_ERR_I2C_INVALID_PARAMETER; + } + + if (i2c_data == HI_NULL) { + return HI_ERR_I2C_INVALID_PARAMETER; + } + + if (i2c_data->receive_buf == HI_NULL) { + i2c_error("null point.\n"); + return HI_ERR_I2C_INVALID_PARAMETER; + } + + if (i2c_data->receive_len == 0) { + i2c_error("invalid receive_len. \n"); + return HI_ERR_I2C_INVALID_PARAMETER; + } + + return HI_ERR_SUCCESS; +} + +static hi_u32 i2c_writeread_param_check(hi_i2c_idx id, const hi_i2c_data *i2c_data) +{ + if (id > HI_I2C_IDX_1 || id < HI_I2C_IDX_0) { + return HI_ERR_I2C_INVALID_PARAMETER; + } + + if (id >= I2C_NUM) { + return HI_ERR_I2C_INVALID_PARAMETER; + } + + if (i2c_data == HI_NULL) { + return HI_ERR_I2C_INVALID_PARAMETER; + } + + if ((i2c_data->send_buf == HI_NULL) || (i2c_data->receive_buf == HI_NULL)) { + i2c_error("null point.\n"); + return HI_ERR_I2C_INVALID_PARAMETER; + } + + if (i2c_data->receive_len == 0 || i2c_data->send_len == 0) { + i2c_error("invalid receive_len or send_len. \n"); + return HI_ERR_I2C_INVALID_PARAMETER; + } + + return HI_ERR_SUCCESS; +} + +static hi_u32 i2c_read_data(hi_i2c_idx id, hi_u16 device_addr, const hi_i2c_data *i2c_data) +{ + hi_u32 ret; + + if (g_i2c_ctrl[id].prepare_func) { + g_i2c_ctrl[id].prepare_func(); + } + + ret = i2c_receive_data(id, device_addr, i2c_data); + if (ret) { + if (g_i2c_ctrl[id].reset_bus_func) { + g_i2c_ctrl[id].reset_bus_func(); + } + } + + if (g_i2c_ctrl[id].restore_func) { + g_i2c_ctrl[id].restore_func(); + } + + return ret; +} + +static hi_void i2c_writeread_data(hi_i2c_idx id, hi_u16 device_addr, const hi_i2c_data *i2c_data) +{ + hi_u32 ret; + + if (g_i2c_ctrl[id].prepare_func) { + g_i2c_ctrl[id].prepare_func(); + } + + ret = i2c_restart_receive_data(id, device_addr, i2c_data); + if (ret) { + if (g_i2c_ctrl[id].reset_bus_func) { + g_i2c_ctrl[id].reset_bus_func(); + } + } + if (g_i2c_ctrl[id].restore_func) { + g_i2c_ctrl[id].restore_func(); + } +} + +hi_u32 hi_i2c_writeread(hi_i2c_idx id, hi_u16 device_addr, const hi_i2c_data *i2c_data) +{ + hi_u32 ret; + + ret = i2c_writeread_param_check(id, i2c_data); + if (ret != HI_ERR_SUCCESS) { + return HI_ERR_I2C_INVALID_PARAMETER; + } + + if (g_i2c_ctrl[id].init == HI_FALSE) { + return HI_ERR_I2C_NOT_INIT; + } + + i2c_writeread_data(id, device_addr, i2c_data); + + ret = hi_sem_wait(g_i2c_drv_sem[id], HI_SYS_WAIT_FOREVER); + if (ret != HI_ERR_SUCCESS) { + return HI_ERR_I2C_WAIT_SEM_FAIL; + } + + hi_sem_signal(g_i2c_drv_sem[id]); + return ret; +} + +hi_u32 hi_i2c_write(hi_i2c_idx id, hi_u16 device_addr, const hi_i2c_data *i2c_data) +{ + hi_u32 ret; + + if (id > HI_I2C_IDX_1 || id < HI_I2C_IDX_0) { + return HI_ERR_I2C_INVALID_PARAMETER; + } + + if (id >= I2C_NUM) { + return HI_ERR_I2C_INVALID_PARAMETER; + } + + if (g_i2c_ctrl[id].init == HI_FALSE) { + return HI_ERR_I2C_NOT_INIT; + } + + if (i2c_data == HI_NULL) { + return HI_ERR_I2C_INVALID_PARAMETER; + } + + if (i2c_data->send_buf == HI_NULL) { + i2c_error("null point.\n"); + return HI_ERR_I2C_INVALID_PARAMETER; + } + + if (i2c_data->send_len == 0) { + i2c_error("invalid send_len. \n"); + return HI_ERR_I2C_INVALID_PARAMETER; + } + + ret = hi_sem_wait(g_i2c_drv_sem[id], HI_SYS_WAIT_FOREVER); + if (ret != HI_ERR_SUCCESS) { + return HI_ERR_I2C_WAIT_SEM_FAIL; + } + + if (g_i2c_ctrl[id].prepare_func) { + g_i2c_ctrl[id].prepare_func(); + } + + ret = i2c_send_data(id, device_addr, i2c_data); + if (ret) { + if (g_i2c_ctrl[id].reset_bus_func) { + g_i2c_ctrl[id].reset_bus_func(); + } + } + + if (g_i2c_ctrl[id].restore_func) { + g_i2c_ctrl[id].restore_func(); + } + + hi_sem_signal(g_i2c_drv_sem[id]); + + return ret; +} + +hi_u32 hi_i2c_read(hi_i2c_idx id, hi_u16 device_addr, const hi_i2c_data *i2c_data) +{ + hi_u32 ret, sem_ret; + + ret = i2c_read_param_check(id, i2c_data); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + if (g_i2c_ctrl[id].init == HI_FALSE) { + return HI_ERR_I2C_NOT_INIT; + } + + ret = hi_sem_wait(g_i2c_drv_sem[id], HI_SYS_WAIT_FOREVER); + if (ret != HI_ERR_SUCCESS) { + return HI_ERR_I2C_WAIT_SEM_FAIL; + } + + ret = i2c_read_data(id, device_addr, i2c_data); + + sem_ret = hi_sem_signal(g_i2c_drv_sem[id]); + if (sem_ret != HI_ERR_SUCCESS) { + return sem_ret; + } + + return ret; +} + +hi_u32 hi_i2c_init(hi_i2c_idx id, hi_u32 baudrate) +{ + hi_u32 ret; + + if (baudrate == 0 || id > HI_I2C_IDX_1 || id < HI_I2C_IDX_0) { + return HI_ERR_I2C_INVALID_PARAMETER; + } + + if (id >= I2C_NUM) { + return HI_ERR_I2C_INVALID_PARAMETER; + } + + if (g_i2c_ctrl[id].init == HI_FALSE) { + hi_u16 reg_val; + hi_reg_read16(CLDO_CTL_CLKEN_REG, reg_val); + reg_val |= (id == HI_I2C_IDX_0) ? (1 << CLKEN_I2C0) : (1 << CLKEN_I2C1); + hi_reg_write16(CLDO_CTL_CLKEN_REG, reg_val); /* enable i2cx clk bus */ + hi_reg_write32((i2c_base(id) + I2C_CTRL), (~(I2C_IP_ENABLE))); + + g_i2c_ctrl[id].baudrate = baudrate; + + i2c_cfg_clk(id, baudrate); + + hi_reg_write32((i2c_base(id) + I2C_ICR), I2C_CLEAR_ALL); + + ret = hi_sem_bcreate(&g_i2c_drv_sem[id], HI_TRUE); + if (ret) { + return ret; + } + g_i2c_ctrl[id].init = HI_TRUE; + } + + return HI_ERR_SUCCESS; +} + +hi_u32 hi_i2c_deinit(hi_i2c_idx id) +{ + hi_u32 ret; + + if (id > HI_I2C_IDX_1 || id < HI_I2C_IDX_0) { + return HI_ERR_I2C_INVALID_PARAMETER; + } + + if (id >= I2C_NUM) { + return HI_ERR_I2C_INVALID_PARAMETER; + } + + if (g_i2c_ctrl[id].init == HI_TRUE) { + ret = hi_sem_delete(g_i2c_drv_sem[id]); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + g_i2c_ctrl[id].init = HI_FALSE; + hi_u16 reg_val; + hi_reg_read16(CLDO_CTL_CLKEN_REG, reg_val); + reg_val &= (id == HI_I2C_IDX_0) ? ~(1 << CLKEN_I2C0) : ~(1 << CLKEN_I2C1); + hi_reg_write16(CLDO_CTL_CLKEN_REG, reg_val); /* disable i2cx clk bus */ + } + + return HI_ERR_SUCCESS; +} + +hi_u32 hi_i2c_set_baudrate(hi_i2c_idx id, hi_u32 baudrate) +{ + /* baudrate range */ + if (id > HI_I2C_IDX_1 || id < HI_I2C_IDX_0 || baudrate == 0) { + return HI_ERR_I2C_INVALID_PARAMETER; + } + + if (g_i2c_ctrl[id].init == HI_FALSE) { + return HI_ERR_I2C_NOT_INIT; + } + + hi_reg_write32((i2c_base(id) + I2C_CTRL), (~(I2C_IP_ENABLE))); + + g_i2c_ctrl[id].baudrate = baudrate; + + i2c_cfg_clk(id, baudrate); + + hi_reg_write32((i2c_base(id) + I2C_ICR), I2C_CLEAR_ALL); + + return HI_ERR_SUCCESS; +} + +hi_void hi_i2c_register_reset_bus_func(hi_i2c_idx id, hi_i2c_func pfn) +{ + if (id > HI_I2C_IDX_1 || id < HI_I2C_IDX_0) { + return; + } + g_i2c_ctrl[id].reset_bus_func = pfn.reset_func; + g_i2c_ctrl[id].prepare_func = pfn.prepare_func; + g_i2c_ctrl[id].restore_func = pfn.restore_func; +} + diff --git a/sdk_liteos/platform/drivers/i2c/i2c.h b/sdk_liteos/platform/drivers/i2c/i2c.h new file mode 100644 index 0000000000000000000000000000000000000000..c16e6b008e176f78ff2e4a3486d7ae8456039e47 --- /dev/null +++ b/sdk_liteos/platform/drivers/i2c/i2c.h @@ -0,0 +1,118 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __I2C_H_ +#define __I2C_H_ + +#include + +#define I2C_CLK CONFIG_WDT_CLOCK +#define I2C_NUM 2 + +#define I2C_FIFO_LINE_MIN 1 +#define I2C_FIFO_LINE_MAX 32 +#define I2C_FIFO_INIT_COUNT 1 +#define I2C_FIFO_INIT_VALUE 0x1fff +#define I2C_INIT_VALUE 0x1ff +#define READ_OPERATION (1<<0) +#define WRITE_OPERATION (~READ_OPERATION) + +#define I2C_CTRL 0x000 +#define I2C_COM 0x004 +#define I2C_ICR 0x008 +#define I2C_SR 0x00C +#define I2C_SCL_H 0x010 +#define I2C_SCL_L 0x014 +#define I2C_TXR 0x018 +#define I2C_RXR 0x01C +#define I2C_FIFOSTATUS 0x020 +#define I2C_TXCOUNT 0x024 +#define I2C_RXCOUNT 0x028 +#define I2C_RXTIDE 0x02C +#define I2C_TXTIDE 0x030 + +/* I2C_CTRL */ +#define I2C_UNMASK_FIFO_EMPTY (1<<12) +#define I2C_FIFO_ENABLE (1<<11) +#define I2C_UNMASK_FIFO_SEND_OF (1<<10) +#define I2C_UNMASK_FIFO_RECEIVE_OF (1<<9) +#define I2C_IP_ENABLE (1<<8) +#define I2C_UNMASK_ALL (1<<7) +#define I2C_UNMASK_START (1<<6) +#define I2C_UNMASK_END (1<<5) +#define I2C_UNMASK_SEND (1<<4) +#define I2C_UNMASK_RECEIVE (1<<3) +#define I2C_UNMASK_ACK (1<<2) +#define I2C_UNMASK_ARBITRATE (1<<1) +#define I2C_UNMASK_OVER (1<<0) + +/* I2C_COM */ +#define I2C_SEND_ACK (~(1<<4)) +#define I2C_START (1<<3) +#define I2C_READ (1<<2) +#define I2C_WRITE (1<<1) +#define I2C_STOP (1<<0) + +/* I2C_ICR */ +#define I2C_CLEAR_FIFO_EMPTY (1<<9) +#define I2C_CLEAR_FIFO_SEND_OF (1<<8) +#define I2C_CLEAR_FIFO_RECEIVE_OF (1<<7) +#define I2C_CLEAR_START (1<<6) +#define I2C_CLEAR_END (1<<5) +#define I2C_CLEAR_SEND (1<<4) +#define I2C_CLEAR_RECEIVE (1<<3) +#define I2C_CLEAR_ACK (1<<2) +#define I2C_CLEAR_ARBITRATE (1<<1) +#define I2C_CLEAR_OVER (1<<0) +#define I2C_CLEAR_ALL (I2C_CLEAR_FIFO_EMPTY | \ + I2C_CLEAR_FIFO_SEND_OF | I2C_CLEAR_FIFO_RECEIVE_OF | \ + I2C_CLEAR_START | I2C_CLEAR_END | \ + I2C_CLEAR_SEND | I2C_CLEAR_RECEIVE | \ + I2C_CLEAR_ACK | I2C_CLEAR_ARBITRATE | \ + I2C_CLEAR_OVER) + +/* I2C_SR */ +#define I2C_FIFO_EMPTY (1<<10) +#define I2C_FIFO_SEND_OF (1<<9) +#define I2C_FIFO_RECEIVE_OF (1<<8) +#define I2C_BUSY (1<<7) +#define I2C_START_INTR (1<<6) +#define I2C_END_INTR (1<<5) +#define I2C_SEND_INTR (1<<4) +#define I2C_RECEIVE_INTR (1<<3) +#define I2C_ACK_INTR (1<<2) +#define I2C_ARBITRATE_INTR (1<<1) +#define I2C_INT_DONE (1<<0) + +#define I2C_START_END (I2C_START_INTR | I2C_INT_DONE) +#define I2C_STOP_END (I2C_END_INTR | I2C_INT_DONE) + +#define I2C_START_EMPTY (I2C_START_INTR | I2C_FIFO_EMPTY) +#define I2C_STOP_EMPTY (I2C_END_INTR | I2C_FIFO_EMPTY) + +/* I2C_FIFOSTATUS */ +#define I2C_RECVFIFO_EMPTY (1<<3) +#define I2C_RECVFIFO_FULL (1<<2) +#define I2C_SENDFIFO_EMPTY (1<<1) +#define I2C_SENDFIFO_FULL (1<<0) + + +#define I2C_SC_SCPERCTRL0 0x1c +#define I2C_SC_SCPERCTRL2 0x34 + +#define i2c_error(_fmt, arg...) + +#endif + diff --git a/sdk_liteos/platform/drivers/module_config.mk b/sdk_liteos/platform/drivers/module_config.mk new file mode 100644 index 0000000000000000000000000000000000000000..d9c00d61595ed0ea3067500ea45e623b0843ebb9 --- /dev/null +++ b/sdk_liteos/platform/drivers/module_config.mk @@ -0,0 +1,16 @@ +uart_srcs := uart +adc_srcs := adc +tsensor_srcs := tsensor +CCFLAGS += -Werror -fsigned-char +CCFLAGS += -I$(MAIN_TOPDIR)/platform/drivers/dma \ + -I$(MAIN_TOPDIR)/platform/drivers/flash +ifeq ($(CONFIG_I2C_SUPPORT), y) + i2c_srcs += i2c +endif +ifeq ($(CONFIG_SPI_SUPPORT), y) + spi_srcs += spi +endif +ifeq ($(CONFIG_PWM_SUPPORT), y) + pwm_srcs += pwm +endif + diff --git a/sdk_liteos/platform/drivers/pwm/SConscript b/sdk_liteos/platform/drivers/pwm/SConscript new file mode 100755 index 0000000000000000000000000000000000000000..b0e5f0e2b015ebbec8bd8a4344149640ab49ef09 --- /dev/null +++ b/sdk_liteos/platform/drivers/pwm/SConscript @@ -0,0 +1,4 @@ +Import('env') + +objs = env.Object(Glob('*.c')) +Return('objs') diff --git a/sdk_liteos/platform/drivers/pwm/hi_pwm.c b/sdk_liteos/platform/drivers/pwm/hi_pwm.c new file mode 100644 index 0000000000000000000000000000000000000000..e58d45e6eca334151fc1129a68aadd95413023fe --- /dev/null +++ b/sdk_liteos/platform/drivers/pwm/hi_pwm.c @@ -0,0 +1,210 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#include "pwm_drv.h" + +#define CLKEN1_PWM5 10 +#define CLKEN1_PWM_BUS 6 +#define CLKEN1_PWM 5 +#define CLKEN1_PWM4 4 +#define CLKEN1_PWM3 3 +#define CLKEN1_PWM2 2 +#define CLKEN1_PWM1 1 +#define CLKEN1_PWM0 0 +#define CLKEN1_PWM_ALL ((1 << (CLKEN1_PWM0)) | (1 << (CLKEN1_PWM1)) | (1 << (CLKEN1_PWM2)) | (1 << (CLKEN1_PWM3)) | \ + (1 << (CLKEN1_PWM4)) | (1 << (CLKEN1_PWM5))) + +hi_u32 hi_pwm_init(hi_pwm_port port) +{ + hi_u32 ret; + pwm_ctl *ctrl = HI_NULL; + hi_u16 reg_val; + + if (pwm_check_port(port) != HI_ERR_SUCCESS) { + return HI_ERR_PWM_INVALID_PARAMETER; + } + ctrl = pwm_get_ctl(port); + if (ctrl->is_init == HI_FALSE) { + hi_reg_read16(CLDO_CTL_CLKEN1_REG, reg_val); + switch (port) { + case HI_PWM_PORT_PWM0: + ret = hi_sem_bcreate(&(ctrl->pwm_sem), HI_SEM_ONE); + reg_val |= 1 << CLKEN1_PWM0; + break; + case HI_PWM_PORT_PWM1: + ret = hi_sem_bcreate(&(ctrl->pwm_sem), HI_SEM_ONE); + reg_val |= 1 << CLKEN1_PWM1; + break; + case HI_PWM_PORT_PWM2: + ret = hi_sem_bcreate(&(ctrl->pwm_sem), HI_SEM_ONE); + reg_val |= 1 << CLKEN1_PWM2; + break; + case HI_PWM_PORT_PWM3: + ret = hi_sem_bcreate(&(ctrl->pwm_sem), HI_SEM_ONE); + reg_val |= 1 << CLKEN1_PWM3; + break; + case HI_PWM_PORT_PWM4: + ret = hi_sem_bcreate(&(ctrl->pwm_sem), HI_SEM_ONE); + reg_val |= 1 << CLKEN1_PWM4; + break; + default: + ret = hi_sem_bcreate(&(ctrl->pwm_sem), HI_SEM_ONE); + reg_val |= 1 << CLKEN1_PWM5; + break; + } + + if (ret == HI_ERR_SUCCESS) { + ctrl->is_init = HI_TRUE; + reg_val |= (1 << CLKEN1_PWM_BUS) | (1 << CLKEN1_PWM); + hi_reg_write16(CLDO_CTL_CLKEN1_REG, reg_val); /* enable pwmx clk bus */ + } + } else { + ret = HI_ERR_SUCCESS; /* HI_ERR_PWM_INITILIZATION_ALREADY return success */ + } + return ret; +} + +hi_void pwm_deinit_clken(hi_pwm_port port) +{ + hi_u16 reg_val; + if (pwm_check_port(port) != HI_ERR_SUCCESS) { + return; + } + hi_reg_read16(CLDO_CTL_CLKEN1_REG, reg_val); + if (port == HI_PWM_PORT_PWM5) { + reg_val &= ~(1 << CLKEN1_PWM5); + } else { + reg_val &= ~(1 << (hi_u16)port); + } + if ((reg_val & CLKEN1_PWM_ALL) == 0) { /* if all channels are free, then close pwm bus and clk_pwm */ + reg_val &= ~((1 << CLKEN1_PWM_BUS) | (1 << CLKEN1_PWM)); + } + hi_reg_write16(CLDO_CTL_CLKEN1_REG, reg_val); /* disable pwmx clk bus */ +} + +hi_u32 hi_pwm_deinit(hi_pwm_port port) +{ + hi_u32 ret; + pwm_ctl *ctrl = HI_NULL; + + if (pwm_check_port(port) != HI_ERR_SUCCESS) { + return HI_ERR_PWM_INVALID_PARAMETER; + } + ctrl = pwm_get_ctl(port); + if (ctrl->is_init == HI_TRUE) { + ret = hi_sem_delete(ctrl->pwm_sem); + if (ret == HI_ERR_SUCCESS) { + (hi_void)memset_s(ctrl, sizeof(pwm_ctl), 0, sizeof(pwm_ctl)); + pwm_deinit_clken(port); + } + } else { + ret = HI_ERR_SUCCESS; + } + return ret; +} + +hi_u32 hi_pwm_set_clock(hi_pwm_clk_source clk_type) +{ + if (clk_type >= PWM_CLK_MAX) { + return HI_ERR_PWM_INVALID_PARAMETER; + } + + if (clk_type == PWM_CLK_160M) { + hi_reg_clrbit(CLDO_CTL_CLK_SEL_REG, 0); + } else { + hi_reg_setbit(CLDO_CTL_CLK_SEL_REG, 0); + } + + return HI_ERR_SUCCESS; +} + +static hi_void pwm_set_enable(hi_pwm_port port, hi_bool flag) +{ + if (flag == HI_TRUE) { + /* enable */ + hi_reg_setbit(pwm_en_reg(pwm_base_addr(port)), 0); + } else { + /* disable */ + hi_reg_clrbit(pwm_en_reg(pwm_base_addr(port)), 0); + } +} + +static hi_void pwm_set_freq(hi_pwm_port port, hi_u16 freq) +{ + hi_reg_setbits(pwm_freq_reg(pwm_base_addr(port)), 0, 16, freq); /* base_addr 16 */ +} + +static hi_void pwm_set_duty(hi_pwm_port port, hi_u16 duty) +{ + hi_reg_setbits(pwm_duty_reg(pwm_base_addr(port)), 0, 16, duty); /* base_addr 16 */ +} + +static hi_void pwm_take_effect(hi_pwm_port port) +{ + hi_reg_setbit(pwm_start_reg(pwm_base_addr(port)), 0); +} + +hi_u32 hi_pwm_start(hi_pwm_port port, hi_u16 duty, hi_u16 freq) +{ + hi_u32 ret; + + if ((pwm_check_port(port) != HI_ERR_SUCCESS) || (duty == 0) || (freq == 0) + || (duty > freq)) { + return HI_ERR_PWM_INVALID_PARAMETER; + } + if (pwm_is_init(port) == HI_FALSE) { + return HI_ERR_PWM_NO_INIT; + } + ret = pwm_lock(port); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + pwm_set_enable(port, HI_TRUE); + pwm_set_freq(port, freq); + pwm_set_duty(port, duty); + pwm_take_effect(port); + return pwm_unlock(port); +} + +hi_u32 hi_pwm_stop(hi_pwm_port port) +{ + hi_u32 ret; + + if (pwm_check_port(port) != HI_ERR_SUCCESS) { + return HI_ERR_PWM_INVALID_PARAMETER; + } + if (pwm_is_init(port) == HI_FALSE) { + return HI_ERR_PWM_NO_INIT; + } + + ret = pwm_lock(port); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + pwm_set_enable(port, HI_FALSE); + pwm_take_effect(port); + return pwm_unlock(port); +} + +hi_u32 pwm_check_port(hi_pwm_port port) +{ + if (port >= HI_PWM_PORT_MAX) { + return HI_ERR_PWM_INVALID_PARAMETER; + } + return HI_ERR_SUCCESS; +} diff --git a/sdk_liteos/platform/drivers/pwm/pwm_drv.h b/sdk_liteos/platform/drivers/pwm/pwm_drv.h new file mode 100644 index 0000000000000000000000000000000000000000..8748efe946b93562eaa489259389e6e991f15576 --- /dev/null +++ b/sdk_liteos/platform/drivers/pwm/pwm_drv.h @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Description: pwm driver implementatioin. + */ + +#ifndef __PWM_DRV_H__ +#define __PWM_DRV_H__ + +#include +#include + +#define PWM_BASE_ADDR_STEP 0x100 +#define pwm_base_addr(pwm_num) (HI_PWM_REG_BASE + (pwm_num) * PWM_BASE_ADDR_STEP) + +#define pwm_en_reg(base_addr) ((base_addr)+ 0x0) +#define pwm_start_reg(base_addr) ((base_addr) + 0x4) +#define pwm_freq_reg(base_addr) ((base_addr) + 0x8) +#define pwm_duty_reg(base_addr) ((base_addr) + 0xC) + +typedef struct { + hi_bool is_init; + hi_u8 reserved[3]; /* 3bytes reserved */ + hi_u32 pwm_sem; +}pwm_ctl; + +typedef struct { + pwm_ctl pwm[HI_PWM_PORT_MAX]; +}pwm_ctx; + +hi_u32 pwm_check_port(hi_pwm_port port); +hi_bool pwm_is_init(hi_pwm_port port); +hi_u32 pwm_lock(hi_pwm_port port); +hi_u32 pwm_unlock(hi_pwm_port port); +pwm_ctl *pwm_get_ctl(hi_pwm_port port); + + +#endif + diff --git a/sdk_liteos/platform/drivers/sdio/sdio_device.h b/sdk_liteos/platform/drivers/sdio/sdio_device.h new file mode 100644 index 0000000000000000000000000000000000000000..0d5b1e0db2e94d8464bc4965123e07d5d4ba89a8 --- /dev/null +++ b/sdk_liteos/platform/drivers/sdio/sdio_device.h @@ -0,0 +1,211 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Description: sdio driver implementatioin. + */ + +#ifndef __SDIO_SLAVE_H__ +#define __SDIO_SLAVE_H__ + +#include "hi_types_base.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif + +#define HI_SDIO_BASE_ADDR 0x40340000 + +#define SDIO_ESW_CCCR 0x004 /* Card Common Control Registers */ +#define SDIO_AMDA_SYS_ADDR 0x008 +#define SDIO_ESW_CARD_RDY 0x00C +#define SDIO_ESW_FUN_RDY 0x010 +#define SDIO_INTRPT_EN 0x014 +#define SDIO_INTRPT_STA 0x018 +#define SDIO_SOFT_RST_VALID 0x01C +#define SDIO_AHB_MEM_INT_EN 0x020 +#define SDIO_AHB_MEM_INT_STA 0x024 +#define SDIO_GLOBAL_INT_EN 0x028 +#define SDIO_GLOBAL_INT_STA 0x02C +#define SDIO_CSA_PTR 0x030 +#define SDIO_IO_ACCESS_MODE 0x034 +#define SDIO_UHS_SUPPORT 0x038 +#define SDIO_CLK_DELAY_TIMER 0x03C +#define SDIO_POWER_CTRL 0x040 +#define SDIO_POWER_STA 0x044 + +/* SDIO FN1 Registers Definition */ +#define SDIO_ESW_IO_OCR 0x104 +#define SDIO_AHB_XFER_COUNT 0x10C +#define SDIO_XFER_COUNT 0x110 +#define SDIO_AHB_INT_STA 0x114 +#define SDIO_AHB_INT_EN 0x118 +#define SDIO_ESW_FBR1 0x11C +#define SDIO_ESW_IOR 0x120 +#define SDIO_HOST_MSG 0x124 +#define SDIO_ARM_HOST 0x128 +#define SDIO_FUN1_RD_DAT_RDY 0x12C +#define GPIO_FUNCTION3 3 +#define START_TYPE_EFUSE_ADDR 1072 + +#define SDIO_FUN1_CREDIT_INFO_BASE 0x13c +#define SDIO_FUN1_EXTEND_REG_BASE 0x140 +#define SDIO_FUN1_EXTEND_REG_LEN 64 + +#define SDIO_MEM_ADMA_FETCH_ADDR 0x204 + +/* SDIO MEM */ +#define SDIO_BLOCK_SIZE_REG 0x244 +#define SDIO_ARGUMENT_REG 0x248 + +/* Block Size Reg */ +#define BLK_SIZE_MSK (hi_u32)0x00000fff + +/* Argument Reg */ +#define BLKCNT_OR_BYTES_MSK (hi_u32)0x000001ff +#define CMD53_ADDR_MSK ((hi_u32)0x0000ffff << 9) +#define CMD53_OPCODE BIT26 +#define CMD53_BLK_MODE BIT27 +#define CMD53_FUN_NUM (BIT28 | BIT29 | BIT30) +#define CMD53_RW_FLAG BIT31 + +/* SDIO_INTRPT */ +#define AHBSOFT_RST_INT BIT0 +#define VOLT_SWITCH_CMD_INT BIT1 +#define CMD19_RD_STRT BIT2 +#define CMD19_RD_TRANS_OVER BIT3 +#define FN0_WR_START BIT4 +#define FN0_WR_TRN_OVER BIT5 +#define FN0_RD_START BIT6 +#define FN0_RD_TRN_OVER BIT7 +#define FN0_RD_TRN_ERR BIT8 +#define FN0_ADMA_END_INT BIT9 +#define FN0_ADMA_INT BIT10 +#define FN0_ADMA_ERR BIT11 + +/* global interrupt */ +#define INT_FRM_SOFT_RESET BIT0 +#define INT_FRM_MEM BIT1 +#define INT_FRM_FN1 BIT2 + +/* AHB Interrupt */ +#define FN1_WR_OVER BIT0 +#define FN1_RD_OVER BIT1 +#define FN1_RD_ERROR BIT2 +#define FN1_RST BIT3 +#define SD_HOST_FN1_MSG_RDY BIT4 +#define FN1_ACK_TO_ARM BIT5 +#define FN1_SDIO_RD_START BIT6 +#define FN1_SDIO_WR_START BIT7 +#define FN1_ADMA_END_INT BIT8 +#define FN1_SUSPEND BIT9 +#define FN1_RESUME BIT10 +#define FN1_ADMA_INT BIT11 +#define FN1_ADMA_ERR BIT12 +#define FN1_EN_INT BIT13 + +/* UHS Support */ +#define UHS_SUPPORT BIT0 +#define DDR_DLY_SELECT BIT1 +#define CARD_VOLT_ACCEPTED BIT2 +#define SD_CLK_LINE_SWITCHED BIT3 +#define SD_CMD_LINE_SWITCHED BIT4 + +#define CCCR_REVISION 3 /* 4Bit 0~3: 1.0, 1.1, 2.0, 3.0, */ +#define SDIO_REVISION (4 << 4) /* 4Bit 0~4: 1.0, 1.1, 1.2, 2.0, 3.0 */ +#define SD_REVISION (3 << 8) /* 4Bit 0~3: 1.0, 1.1, 2.0, 3.0, */ +#define CCCR_SCSI (0 << 12) +#define CCCR_SDC (1 << 13) +#define CCCR_SMB (1 << 14) +#define CCCR_SRW (0 << 15) +#define CCCR_SBS (1 << 16) +#define CCCR_S4MI (1 << 17) +#define CCCR_LSC (0 << 18) +#define CCCR_4BLS (0 << 19) +#define CCCR_SMPC (1 << 20) +#define CCCR_SHS (1 << 21) +#define CCCR_MEM_PRE (2 << 22) + +#define SDIO_ESW_CCCR_SET (hi_u32) \ + (CCCR_REVISION | SDIO_REVISION | SD_REVISION| CCCR_SCSI | CCCR_SDC | CCCR_SMB | CCCR_SRW| \ + CCCR_SBS | CCCR_S4MI | CCCR_LSC | CCCR_4BLS| CCCR_SMPC | CCCR_SHS | CCCR_MEM_PRE) + +#define SDIO_ESW_IO_OCR_SET (hi_u32)(0x00ff8000) /* Bit23~Bit8: 3.6~2.0 0.1/bit */ + +/* ESW FBR1 Register */ +#define IO_DEVICE_CODE1 7 /* 4Bit 7:SDIO WLAN interface + SDIO Simplified Specification Version 3.00 Chapter 6.10 */ +#define FUN_CSA_SUPPORT (0 << 4) /* 1Bit */ +#define EXT_IO_DEVICE_CODE1 (0 << 5) /* 8Bit */ +#define FBR1_SPS (0 << 13) /* 1Bit Function1 supports high power */ + +#define SDIO_ESW_FBR1_SET (hi_u32)(IO_DEVICE_CODE1 | FUN_CSA_SUPPORT | EXT_IO_DEVICE_CODE1 | FBR1_SPS) + +#define SDIO_IO_ACCESS_SET (hi_u32)0xffffffff + +#define SDIO_CLK_DELAY_SET (hi_u32)0x2f92 + +#define SDIO_ADMA_STEP 8 +#define SDIO_ADMA_VALID BIT0 +#define SDIO_ADMA_END BIT1 +#define SDIO_ADMA_INT BIT2 +#define SDIO_ADMA_NOP 0 +#define SDIO_ADMA_TRAN BIT5 +#define SDIO_ADMA_LINK (BIT5 | BIT4) +#define SDIO_ADMA_PARAM_MASK (BIT0 | BIT1 | BIT2 | BIT3 | BIT4 | BIT5) + +/* SDIO soft reset offset and bit. */ +#define SDIO_RESET_OFFSET 0x0020 +#define SDIO_SOFT_RESET BIT3 + +#define SDIO_TRANS_BLK_SIZE 512 +#define PADDING_BLK SDIO_TRANS_BLK_SIZE +#define PADDING_BYTE 4 +#define padding(x, size) (((x) + (size) - 1) & (~ ((size) - 1))) +#define hisdio_align_4_or_blk(len) ((len) < HISDIO_BLOCK_SIZE ? padding((len), 4) : \ + padding((len), HISDIO_BLOCK_SIZE)) +#define hisdio_shift_check(a, b) ((a) == (((a)<<(b))>>(b))) + +typedef enum { + MSG_FLAG_OFF = 0, + MSG_FLAG_ON = 1, +} msg_flag; + +typedef struct { + hi_u32 reg; + hi_u32 value; +} sdio_reg_store; + +enum _hcc_netbuf_queue_type_ { + HCC_NETBUF_NORMAL_QUEUE = 0, /* netbuf is shared with others */ + HCC_NETBUF_HIGH_QUEUE = 1, /* netbuf is special for high pri */ + HCC_NETBUF_QUEUE_BUTT +}; + +hi_void sdio_soft_reset_valid(hi_void); + +#ifdef HI_BOARD_ASIC +#define NON_IOT_START_TYPE 0 +#else +#define NON_IOT_START_TYPE 1 +#endif + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif + +#endif /* end of sdio_slave.h */ diff --git a/sdk_liteos/platform/drivers/spi/SConscript b/sdk_liteos/platform/drivers/spi/SConscript new file mode 100755 index 0000000000000000000000000000000000000000..b0e5f0e2b015ebbec8bd8a4344149640ab49ef09 --- /dev/null +++ b/sdk_liteos/platform/drivers/spi/SConscript @@ -0,0 +1,4 @@ +Import('env') + +objs = env.Object(Glob('*.c')) +Return('objs') diff --git a/sdk_liteos/platform/drivers/spi/hi_spi.c b/sdk_liteos/platform/drivers/spi/hi_spi.c new file mode 100644 index 0000000000000000000000000000000000000000..5e502a88c1f94d4223c93608076a54e6b6748ded --- /dev/null +++ b/sdk_liteos/platform/drivers/spi/hi_spi.c @@ -0,0 +1,607 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef CONFIG_SPI_DMA_SUPPORT +#include +#endif +#include + +#include "spi.h" + +#define SPI_HOST_OPT_BASE (SPI_OPT_ENABLE_SPI | \ + SPI_OPT_SET_CFG | \ + SPI_OPT_DISABLE_SPI | \ + SPI_OPT_WAIT_SIGNAL | \ + SPI_OPT_FREE_SIGNAL) + +#define SPI_SLAVE_OPT_READ (SPI_OPT_ENABLE_SPI | \ + SPI_OPT_SET_CFG) + +#define SPI_SLAVE_OPT_WRITE (SPI_OPT_ENABLE_SPI | \ + SPI_OPT_SET_CFG | \ + SPI_OPT_WAIT_SIGNAL | \ + SPI_OPT_FREE_SIGNAL) + +#define CLKEN_SPI0 5 +#define CLKEN_SPI1 0 + +hi_u32 g_spi_clk = SPI_DEFAULT_CLK; + +static hi_u32 spi_get_clk(hi_void) +{ + hi_reg_write16(W_CTL_W_TCXO_SEL_REG, 1); + hi_udelay(1); + return g_spi_clk; +} + +static hi_u32 spi_write_data(hi_spi_idx id, hi_u32 timeout_ms) +{ + hi_u32 event_bit; + hi_u32 ret; + spi_isr_enable(g_spi_ctrl[id]->reg_base, SPI_INT_BIT_TX_FIFO_WATER_LINE); + event_bit = 0; + ret = hi_event_wait(g_spi_ctrl[id]->event_id, HI_EVENT_BIT_TX_DATA, &event_bit, timeout_ms, + HI_EVENT_WAITMODE_OR | HI_EVENT_WAITMODE_CLR); + if (ret == HI_ERR_EVENT_WAIT_TIME_OUT) { + spi_process_printf("write time out"); + return HI_ERR_SPI_WRITE_TIMEOUT; + } else { + return HI_ERR_SUCCESS; + } +} + +static hi_u32 spi_read_data(hi_spi_idx id, hi_u32 timeout_ms) +{ + hi_u32 event_bit = 0; + hi_u32 ret; + + for (;;) { + if (g_spi_ctrl[id]->rx_buf.cur_cnt >= g_spi_ctrl[id]->trans_len) { + g_spi_ctrl[id]->rx_buf.cur_cnt = 0; + return HI_ERR_SUCCESS; + } + spi_isr_enable(g_spi_ctrl[id]->reg_base, + SPI_INT_BIT_RX_FIFO_WATER_LINE | SPI_INT_BIT_RX_FIFO_TIME_OUT | SPI_INT_BIT_RX_FIFO_OVER_FLOW); + + ret = hi_event_wait(g_spi_ctrl[id]->event_id, + HI_EVENT_BIT_RX_DATA | HI_EVENT_BIT_RX_DATA_TIME_OUT | HI_EVENT_BIT_RX_FIFO_OVER_FLOW, + &event_bit, timeout_ms, HI_EVENT_WAITMODE_OR | HI_EVENT_WAITMODE_CLR); + if (ret == HI_ERR_SUCCESS) { + continue; + } else if (ret == HI_ERR_EVENT_WAIT_TIME_OUT) { + return HI_ERR_SPI_READ_TIMEOUT; + } else { + return ret; + } + } +} +static hi_u32 spi_host_transfer(hi_spi_idx id, const spi_trans_attr *trans_attr, hi_u32 total_len, hi_u32 read_write) +{ + hi_u32 ret; + hi_u16 threshold = (id == HI_SPI_ID_0 ? SPI0_FIFO_THRESHOLD : SPI1_FIFO_THRESHOLD); + hi_u32 len = total_len; + while (len) { + if (len > threshold) { + g_spi_ctrl[id]->single_len = threshold; + g_spi_ctrl[id]->trans_len = threshold; + } else { + g_spi_ctrl[id]->single_len = len; + g_spi_ctrl[id]->trans_len = len; + } + if (read_write & SPI_WRITE_FLAG) { + ret = spi_write_data(id, trans_attr->time_out_ms); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + } + /* if too fast, there should be delay 50-100 us to wait slave */ + if (read_write & SPI_READ_FLAG) { + ret = spi_read_data(id, trans_attr->time_out_ms); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + } + if (len < g_spi_ctrl[id]->single_len) { + return HI_ERR_FAILURE; + } + len -= g_spi_ctrl[id]->single_len; + } + return HI_ERR_SUCCESS; +} + +static hi_u32 spi_slave_transfer(hi_spi_idx id, const spi_trans_attr *trans_attr, hi_u32 read_write) +{ + hi_u32 ret; + hi_u16 threshold = (id == HI_SPI_ID_0 ? SPI0_FIFO_THRESHOLD : SPI1_FIFO_THRESHOLD); + hi_u32 len = g_spi_ctrl[id]->trans_len; + if (read_write & SPI_WRITE_FLAG) { + while (len) { + if (len > threshold) { + g_spi_ctrl[id]->single_len = threshold; + } else { + g_spi_ctrl[id]->single_len = len; + } + ret = spi_write_data(id, trans_attr->time_out_ms); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + len -= g_spi_ctrl[id]->single_len; + } + } + if (read_write & SPI_READ_FLAG) { + g_spi_ctrl[id]->single_len = threshold; + ret = spi_read_data(id, trans_attr->time_out_ms); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + } + return HI_ERR_SUCCESS; +} + +#ifdef CONFIG_SPI_DMA_SUPPORT +/* slave using dma transfer data, use read or write, can't use both methods of work at the same time */ +static hi_u32 spi_slave_dma_transfer(hi_spi_idx id, const spi_trans_attr *trans_attr, hi_u32 read_write) +{ + hi_u32 ret; + if (read_write & SPI_WRITE_FLAG) { + spi_dma_enable(g_spi_ctrl[id]->reg_base, SPI_TX_DMAE); + ret = spi_hd_dma_write_fifo(g_spi_ctrl[id], trans_attr->time_out_ms); + spi_dma_disable(g_spi_ctrl[id]->reg_base, SPI_TX_DMAE); + } else { + spi_dma_enable(g_spi_ctrl[id]->reg_base, SPI_RX_DMAE); + ret = spi_hd_dma_read_fifo(g_spi_ctrl[id], trans_attr->time_out_ms); + spi_dma_disable(g_spi_ctrl[id]->reg_base, SPI_RX_DMAE); + } + return ret; +} +#endif + +static hi_u32 spi_get_data_len(hi_u32 data_width, hi_u32 byte_len) +{ + if (data_width > HI_SPI_CFG_DATA_WIDTH_E_8BIT) { + if ((byte_len % SPI_DATA_WIDTH_2BYTES) != 0) { + return 0; + } + return (byte_len / SPI_DATA_WIDTH_2BYTES); + } else { + return byte_len; + } +} + +static hi_u32 spi_host_writeread(hi_spi_idx id, hi_pvoid write_data, hi_pvoid read_data, hi_u32 byte_len, + hi_u32 options) +{ + hi_u32 data_len; + hi_u32 ret; + if ((hi_u32)id > HI_SPI_ID_1 || byte_len == 0 || + (!(options & SPI_OPT_SEND_FIX_DATA) && (write_data == HI_NULL)) || + (!(options & SPI_OPT_RCV_FIX_DATA) && (read_data == HI_NULL))) { + return HI_ERR_SPI_PARAMETER_WRONG; + } + if (g_spi_ctrl[id] == HI_NULL) { + return HI_ERR_SPI_NOT_INIT; + } + if (g_spi_ctrl[id]->spi_cfg.is_slave == SPI_CFG_ROLE_SLAVE) { + return HI_ERR_SPI_PARAMETER_WRONG; + } + if (g_spi_ctrl[id]->transferring) { + return HI_ERR_SPI_BUSY; + } + data_len = spi_get_data_len(g_spi_ctrl[id]->spi_cfg.data_width, byte_len); + if (data_len == 0) { + return HI_ERR_SPI_PARAMETER_WRONG; + } + spi_trans_attr trans_attr = { SPI_HOST_TIMEOUT_MS, options }; + g_spi_ctrl[id]->single_len = 0; + g_spi_ctrl[id]->trans_len = data_len; + g_spi_ctrl[id]->tx_buf.buf = write_data; + g_spi_ctrl[id]->tx_buf.cur_pos = 0; + g_spi_ctrl[id]->tx_buf.cur_cnt = 0; + g_spi_ctrl[id]->rx_buf.buf = read_data; + g_spi_ctrl[id]->rx_buf.cur_pos = 0; + g_spi_ctrl[id]->rx_buf.cur_cnt = 0; + ret = spi_trans_prepare(g_spi_ctrl[id], &trans_attr); + if (ret != HI_ERR_SUCCESS) { + spi_trans_restore(g_spi_ctrl[id], &trans_attr); + return ret; + } + spi_flush_fifo(g_spi_ctrl[id]->reg_base); + if (!g_spi_ctrl[id]->use_irq) { + if (g_spi_ctrl[id]->spi_cfg.data_width < HI_SPI_CFG_DATA_WIDTH_E_9BIT) { + ret = spi_transfer_8bits_block(g_spi_ctrl[id], options); + } else { + ret = spi_transfer_16bits_block(g_spi_ctrl[id], options); + } + } else { + ret = spi_host_transfer(id, &trans_attr, data_len, SPI_WRITE_FLAG | SPI_READ_FLAG); + } + + spi_trans_restore(g_spi_ctrl[id], &trans_attr); + return ret; +} + +hi_u32 hi_spi_set_loop_back_mode(hi_spi_idx id, hi_bool lb_en) +{ + hi_u16 reg_val = 0; + if (id > HI_SPI_ID_1 || id < HI_SPI_ID_0) { + return HI_ERR_SPI_PARAMETER_WRONG; + } + if (g_spi_ctrl[id] == HI_NULL) { + return HI_ERR_SPI_NOT_INIT; + } + if ((g_spi_ctrl[id]->spi_cfg.fram_mode == HI_SPI_CFG_FRAM_MODE_MICROWIRE || + g_spi_ctrl[id]->spi_cfg.is_slave == SPI_CFG_ROLE_SLAVE) && lb_en) { + return HI_ERR_SPI_PARAMETER_WRONG; + } + if (lb_en) { + hi_reg_read16(g_spi_ctrl[id]->reg_base + REG_SPI_CR1, reg_val); + reg_val |= (1 << SPI_CR1_ST_BIT_LBM); + hi_reg_write16(g_spi_ctrl[id]->reg_base + REG_SPI_CR1, reg_val); + g_spi_ctrl[id]->spi_cfg.loop_back = 1; + } else { + g_spi_ctrl[id]->spi_cfg.loop_back = 0; + } + return HI_ERR_SUCCESS; +} + +hi_u32 hi_spi_slave_write(hi_spi_idx id, hi_pvoid write_data, hi_u32 byte_len, hi_u32 time_out_ms) +{ + hi_u32 ret; + hi_u32 data_len; + if ((hi_u32)id > HI_SPI_ID_1 || write_data == HI_NULL || byte_len == 0 || id < HI_SPI_ID_0) { + return HI_ERR_SPI_PARAMETER_WRONG; + } + if (g_spi_ctrl[id] == HI_NULL) { + return HI_ERR_SPI_NOT_INIT; + } + if (g_spi_ctrl[id]->spi_cfg.is_slave != SPI_CFG_ROLE_SLAVE) { + return HI_ERR_SPI_PARAMETER_WRONG; + } + data_len = spi_get_data_len(g_spi_ctrl[id]->spi_cfg.data_width, byte_len); + if (data_len == 0) { + return HI_ERR_SPI_PARAMETER_WRONG; + } + spi_trans_attr trans_attr = { time_out_ms, SPI_SLAVE_OPT_WRITE }; + g_spi_ctrl[id]->single_len = 0; + g_spi_ctrl[id]->trans_len = data_len; + g_spi_ctrl[id]->tx_buf.buf = write_data; + g_spi_ctrl[id]->tx_buf.cur_pos = 0; + g_spi_ctrl[id]->tx_buf.cur_cnt = 0; + ret = spi_trans_prepare(g_spi_ctrl[id], &trans_attr); + if (ret != HI_ERR_SUCCESS) { + spi_trans_restore(g_spi_ctrl[id], &trans_attr); + return ret; + } +#ifdef CONFIG_SPI_DMA_SUPPORT + if (g_spi_ctrl[id]->use_dma) { /* transfer less fifo size data, use isr modle first */ + ret = spi_slave_dma_transfer(id, &trans_attr, SPI_WRITE_FLAG); + } else { + ret = spi_slave_transfer(id, &trans_attr, SPI_WRITE_FLAG); + } +#else + ret = spi_slave_transfer(id, &trans_attr, SPI_WRITE_FLAG); +#endif + + spi_trans_restore(g_spi_ctrl[id], &trans_attr); + return ret; +} + +hi_u32 hi_spi_slave_read(hi_spi_idx id, hi_pvoid read_data, hi_u32 byte_len, hi_u32 time_out_ms) +{ + hi_u32 ret; + hi_u32 data_len; + if ((hi_u32)id > HI_SPI_ID_1 || read_data == HI_NULL || byte_len == 0 || id < HI_SPI_ID_0) { + return HI_ERR_SPI_PARAMETER_WRONG; + } + if (g_spi_ctrl[id] == HI_NULL) { + return HI_ERR_SPI_NOT_INIT; + } + if (g_spi_ctrl[id]->spi_cfg.is_slave != SPI_CFG_ROLE_SLAVE) { + return HI_ERR_SPI_PARAMETER_WRONG; + } + data_len = spi_get_data_len(g_spi_ctrl[id]->spi_cfg.data_width, byte_len); + if (data_len == 0) { + return HI_ERR_SPI_PARAMETER_WRONG; + } + spi_trans_attr trans_attr = { time_out_ms, SPI_SLAVE_OPT_READ }; + g_spi_ctrl[id]->single_len = 0; + g_spi_ctrl[id]->trans_len = data_len; + g_spi_ctrl[id]->rx_buf.buf = read_data; + g_spi_ctrl[id]->rx_buf.cur_pos = 0; + g_spi_ctrl[id]->rx_buf.cur_cnt = 0; + spi_flush_fifo(g_spi_ctrl[id]->reg_base); + ret = spi_trans_prepare(g_spi_ctrl[id], &trans_attr); + if (ret != HI_ERR_SUCCESS) { + spi_trans_restore(g_spi_ctrl[id], &trans_attr); + return ret; + } +#ifdef CONFIG_SPI_DMA_SUPPORT + if (g_spi_ctrl[id]->use_dma) { + ret = spi_slave_dma_transfer(id, &trans_attr, SPI_READ_FLAG); + } else { + ret = spi_slave_transfer(id, &trans_attr, SPI_READ_FLAG); + } +#else + ret = spi_slave_transfer(id, &trans_attr, SPI_READ_FLAG); +#endif + + spi_trans_restore(g_spi_ctrl[id], &trans_attr); + return ret; +} + +hi_u32 hi_spi_host_writeread(hi_spi_idx id, hi_pvoid write_data, hi_pvoid read_data, hi_u32 byte_len) +{ + if ((id > HI_SPI_ID_1) || (id < HI_SPI_ID_0) || byte_len == 0 || + (write_data == HI_NULL) || (read_data == HI_NULL)) { + return HI_ERR_SPI_PARAMETER_WRONG; + } + return spi_host_writeread(id, write_data, read_data, byte_len, SPI_HOST_OPT_BASE); +} + +hi_u32 hi_spi_host_read(hi_spi_idx id, hi_pvoid read_data, hi_u32 byte_len) +{ + if ((id > HI_SPI_ID_1) || (id < HI_SPI_ID_0) || (byte_len == 0) || (read_data == HI_NULL)) { + return HI_ERR_SPI_PARAMETER_WRONG; + } + return spi_host_writeread(id, HI_NULL, read_data, byte_len, (SPI_HOST_OPT_BASE) | SPI_OPT_SEND_FIX_DATA); +} + +hi_u32 hi_spi_host_write(hi_spi_idx id, hi_pvoid write_data, hi_u32 byte_len) +{ + if ((id > HI_SPI_ID_1) || (id < HI_SPI_ID_0) || (byte_len == 0) || (write_data == HI_NULL)) { + return HI_ERR_SPI_PARAMETER_WRONG; + } + return spi_host_writeread(id, write_data, HI_NULL, byte_len, (SPI_HOST_OPT_BASE) | SPI_OPT_RCV_FIX_DATA); +} + +hi_u32 hi_spi_set_irq_mode(hi_spi_idx id, hi_bool irq_en) +{ + if ((id > HI_SPI_ID_1) || (id < HI_SPI_ID_0)) { + return HI_ERR_SPI_PARAMETER_WRONG; + } + if (g_spi_ctrl[id] == HI_NULL) { + return HI_ERR_SPI_NOT_INIT; + } + if (g_spi_ctrl[id]->transferring) { + return HI_ERR_SPI_BUSY; + } + g_spi_ctrl[id]->use_irq = irq_en; + if (!irq_en) { + spi_isr_disable(g_spi_ctrl[id]->reg_base, SPI_INT_BIT_TX_FIFO_WATER_LINE | + SPI_INT_BIT_RX_FIFO_WATER_LINE | + SPI_INT_BIT_RX_FIFO_TIME_OUT); + } + return HI_ERR_SUCCESS; +} + +hi_u32 hi_spi_set_dma_mode(hi_spi_idx id, hi_bool dma_en) +{ + if (id > HI_SPI_ID_1) { + return HI_ERR_SPI_PARAMETER_WRONG; + } + if (g_spi_ctrl[id] == HI_NULL) { + return HI_ERR_SPI_NOT_INIT; + } + if (g_spi_ctrl[id]->transferring) { + return HI_ERR_SPI_BUSY; + } +#ifdef CONFIG_SPI_DMA_SUPPORT + g_spi_ctrl[id]->use_dma = dma_en; +#else + hi_unref_param(dma_en); + return HI_ERR_SPI_NOT_SUPPORT_DMA; +#endif + return HI_ERR_SUCCESS; +} + +hi_u32 hi_spi_register_usr_func(hi_spi_idx id, hi_spi_usr_func prepare_func, hi_spi_usr_func restore_func) +{ + if ((id > HI_SPI_ID_1) || (id < HI_SPI_ID_0)) { + return HI_ERR_SPI_PARAMETER_WRONG; + } + if (g_spi_ctrl[id] == HI_NULL) { + return HI_ERR_SPI_NOT_INIT; + } + + if (g_spi_ctrl[id]->transferring) { + return HI_ERR_SPI_BUSY; + } + g_spi_ctrl[id]->prepare_func = prepare_func; + g_spi_ctrl[id]->restore_func = restore_func; + return HI_ERR_SUCCESS; +} + +hi_u32 hi_spi_set_basic_info(hi_spi_idx id, const hi_spi_cfg_basic_info *param) +{ + hi_u32 ret; + hi_u32 spi_clk = spi_get_clk(); + if (((hi_u32)id > HI_SPI_ID_1) || (param == HI_NULL) || (id < HI_SPI_ID_0)) { + return HI_ERR_SPI_PARAMETER_WRONG; + } + + if (g_spi_ctrl[id] == HI_NULL) { + return HI_ERR_SPI_NOT_INIT; + } + + if (g_spi_ctrl[id]->transferring) { + return HI_ERR_SPI_BUSY; + } + + if (param->fram_mode > HI_SPI_CFG_FRAM_MODE_MICROWIRE || param->data_width < HI_SPI_CFG_DATA_WIDTH_E_4BIT || + param->freq > spi_max_speed(spi_clk) || param->freq < spi_min_speed(spi_clk)) { + return HI_ERR_SPI_PARAMETER_WRONG; + } + if (g_spi_ctrl[id]->spi_cfg.loop_back == HI_TRUE && (param->fram_mode == HI_SPI_CFG_FRAM_MODE_MICROWIRE || + g_spi_ctrl[id]->spi_cfg.is_slave == SPI_CFG_ROLE_SLAVE)) { + return HI_ERR_SPI_PARAMETER_WRONG; + } + + /* compute spi speed, speed=clk/(cpsdvsr*(scr+1)) */ + hi_u32 tmp = spi_clk / param->freq; + if (tmp < CPSDVSR_MIN) { + g_spi_ctrl[id]->spi_cfg.cpsdvsr = CPSDVSR_MIN; + g_spi_ctrl[id]->spi_cfg.scr = 0; + } else if (tmp <= CPSDVSR_MAX) { + g_spi_ctrl[id]->spi_cfg.cpsdvsr = (hi_u16)(tmp & (~0x1)); + g_spi_ctrl[id]->spi_cfg.scr = (tmp / g_spi_ctrl[id]->spi_cfg.cpsdvsr) - 1; + } else { + g_spi_ctrl[id]->spi_cfg.cpsdvsr = CPSDVSR_MAX; + g_spi_ctrl[id]->spi_cfg.scr = (tmp / g_spi_ctrl[id]->spi_cfg.cpsdvsr) - 1; + } + + g_spi_ctrl[id]->spi_cfg.data_width = param->data_width; + g_spi_ctrl[id]->spi_cfg.fram_mode = param->fram_mode; + g_spi_ctrl[id]->spi_cfg.cpol = param->cpol; + g_spi_ctrl[id]->spi_cfg.cpha = param->cpha; + g_spi_ctrl[id]->spi_cfg.endian = param->endian; + /* write reg */ + ret = spi_config(g_spi_ctrl[id]); + return ret; +} + +static hi_void spi_ctrl_init(hi_spi_idx id, hi_spi_cfg_init_param init_param) +{ + g_spi_ctrl[id]->spi_cfg.loop_back = HI_FALSE; + hi_u16 reg_val; + hi_reg_read16(CLDO_CTL_CLKEN_REG, reg_val); + if (id == HI_SPI_ID_0) { + g_spi_ctrl[id]->spi_cfg.tx_fifo_line = SPI0_TX_FIFO_WATER_LINE; + g_spi_ctrl[id]->spi_cfg.rx_fifo_line = SPI0_RX_FIFO_WATER_LINE; + g_spi_ctrl[id]->spi_cfg.tx_fifo_dma_line = SPI0_TX_FIFO_DMA_WLINE_64; + g_spi_ctrl[id]->spi_cfg.rx_fifo_dma_line = SPI0_RX_FIFO_DMA_WLINE_128; + reg_val |= 1 << CLKEN_SPI0; + } else { + g_spi_ctrl[id]->spi_cfg.tx_fifo_line = SPI1_TX_FIFO_WATER_LINE; + g_spi_ctrl[id]->spi_cfg.rx_fifo_line = SPI1_RX_FIFO_WATER_LINE; + g_spi_ctrl[id]->spi_cfg.tx_fifo_dma_line = SPI1_TX_FIFO_DMA_WLINE_16; + g_spi_ctrl[id]->spi_cfg.rx_fifo_dma_line = SPI1_RX_FIFO_DMA_WLINE_32; + reg_val |= 1 << CLKEN_SPI1; + } + hi_reg_write16(CLDO_CTL_CLKEN_REG, reg_val); /* enable spix clk bus */ + g_spi_ctrl[id]->spi_cfg.is_slave = init_param.is_slave ? SPI_CFG_ROLE_SLAVE : SPI_CFG_ROLE_MASTER; + spi_reset(g_spi_ctrl[id]); + spi_set_fifo_line(g_spi_ctrl[id]); +#ifdef CONFIG_SPI_DMA_SUPPORT + spi_set_dma_fifo_line(g_spi_ctrl[id]); +#endif + spi_isr_disable(g_spi_ctrl[id]->reg_base, + SPI_INT_BIT_RX_FIFO_WATER_LINE | SPI_INT_BIT_RX_FIFO_TIME_OUT | SPI_INT_BIT_RX_FIFO_OVER_FLOW); +} + +#ifdef CONFIG_SPI_DMA_SUPPORT +static hi_u32 spi_dma_init(hi_void) +{ + hi_u32 ret = HI_ERR_SUCCESS; + if (hi_dma_is_init() == HI_FALSE) { + ret = hi_dma_init(); + } + return ret; +} +#endif + +hi_u32 hi_spi_init(hi_spi_idx id, hi_spi_cfg_init_param init_param, const hi_spi_cfg_basic_info *param) +{ + if ((id > HI_SPI_ID_1) || (param == HI_NULL) || (id < HI_SPI_ID_0)) { + return HI_ERR_SPI_PARAMETER_WRONG; + } + hi_u32 ret; + if (g_spi_ctrl[id] != HI_NULL) { + return HI_ERR_SPI_REINIT; + } + + g_spi_ctrl[id] = (spi_ctrl *)hi_malloc(HI_MOD_ID_DRV_SPI, sizeof(spi_ctrl)); + if (g_spi_ctrl[id] == HI_NULL) { + return HI_ERR_MALLOC_FAILUE; + } + memset_s(g_spi_ctrl[id], sizeof(spi_ctrl), 0x0, sizeof(spi_ctrl)); + g_spi_ctrl[id]->reg_base = (id == HI_SPI_ID_0) ? HI_SSP0_REG_BASE : HI_SSP1_REG_BASE; + + ret = hi_sem_bcreate(&g_spi_ctrl[id]->sem_id, 1); + if (ret != HI_ERR_SUCCESS) { + goto init_fail; + } + + ret = hi_event_create(&g_spi_ctrl[id]->event_id); + if (ret != HI_ERR_SUCCESS) { + goto init_fail2; + } + + g_spi_ctrl[id]->irq_num = (id == HI_SPI_ID_0) ? SSP_0_IRQ : SSP_1_IRQ; + ret = hi_irq_request(g_spi_ctrl[id]->irq_num, HI_IRQ_FLAG_PRI2, (irq_routine)spi_isr, (uintptr_t)g_spi_ctrl[id]); + if (ret != HI_ERR_SUCCESS) { + goto init_fail3; + } + spi_ctrl_init(id, init_param); + ret = (hi_u32)hi_spi_set_basic_info(id, param); + if (ret != HI_ERR_SUCCESS) { + goto init_fail4; + } + +#ifdef CONFIG_SPI_DMA_SUPPORT + return spi_dma_init(); +#endif + + return HI_ERR_SUCCESS; + +init_fail4: + (hi_void) hi_irq_free(g_spi_ctrl[id]->irq_num); +init_fail3: + (hi_void) hi_event_delete(g_spi_ctrl[id]->event_id); +init_fail2: + (hi_void) hi_sem_delete(g_spi_ctrl[id]->sem_id); +init_fail: + hi_free(HI_MOD_ID_DRV_SPI, g_spi_ctrl[id]); + g_spi_ctrl[id] = HI_NULL; + return ret; +} + +hi_u32 hi_spi_deinit(hi_spi_idx id) +{ + hi_u16 reg_val; + if ((id > HI_SPI_ID_1) || (id < HI_SPI_ID_0)) { + return HI_ERR_SPI_PARAMETER_WRONG; + } + if (g_spi_ctrl[id] == HI_NULL) { + return HI_ERR_SUCCESS; /* HI_ERR_SPI_NOT_INIT return success */ + } + if (g_spi_ctrl[id]->transferring) { + return HI_ERR_SPI_BUSY; + } + + spi_isr_disable(g_spi_ctrl[id]->reg_base, + SPI_INT_BIT_RX_FIFO_WATER_LINE | SPI_INT_BIT_RX_FIFO_TIME_OUT | SPI_INT_BIT_RX_FIFO_OVER_FLOW); + hi_irq_disable(g_spi_ctrl[id]->irq_num); + (hi_void) hi_irq_free(g_spi_ctrl[id]->irq_num); + + (hi_void) hi_sem_delete(g_spi_ctrl[id]->sem_id); + (hi_void) hi_event_delete(g_spi_ctrl[id]->event_id); + /* disable spi */ + spi_disable(g_spi_ctrl[id]); + hi_free(HI_MOD_ID_DRV_SPI, g_spi_ctrl[id]); + g_spi_ctrl[id] = HI_NULL; + hi_reg_read16(CLDO_CTL_CLKEN_REG, reg_val); + reg_val &= (id == HI_SPI_ID_0) ? ~(1 << CLKEN_SPI0) : ~(1 << CLKEN_SPI1); + hi_reg_write16(CLDO_CTL_CLKEN_REG, reg_val); /* disable spix clk bus */ + return HI_ERR_SUCCESS; +} diff --git a/sdk_liteos/platform/drivers/spi/spi.c b/sdk_liteos/platform/drivers/spi/spi.c new file mode 100644 index 0000000000000000000000000000000000000000..08322e842f596d87caef1d2fce1092035259970f --- /dev/null +++ b/sdk_liteos/platform/drivers/spi/spi.c @@ -0,0 +1,761 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "spi.h" +#include +#include +#include +#include +#ifdef CONFIG_SPI_DMA_SUPPORT +#include +#endif + +spi_ctrl *g_spi_ctrl[SPI_NUM] = { 0 }; + +HI_ALWAYS_STAIC_INLINE hi_bool spi_check_rx_fifo_empty(hi_u32 reg_base) +{ + hi_u16 reg_val = 0; + hi_reg_read16(reg_base + REG_SPI_SR, reg_val); + if (reg_val & MASK_SPI_SR_RNE) { + return HI_FALSE; + } + return HI_TRUE; +} + +HI_ALWAYS_STAIC_INLINE hi_bool spi_check_busy(hi_u32 reg_base) +{ + hi_u16 reg_val = 0; + hi_reg_read16(reg_base + REG_SPI_SR, reg_val); + if (reg_val & MASK_SPI_SR_BSY) { + return HI_TRUE; + } + return HI_FALSE; +} + +HI_ALWAYS_STAIC_INLINE hi_u32 spi_check_write_timeout(hi_u32 reg_base) +{ + hi_u16 reg_val = 0; + hi_u32 count = 0; + while (count++ < SPI_HOST_TIMEOUT_US) { + hi_reg_read16(reg_base + REG_SPI_SR, reg_val); + if ((reg_val & MASK_SPI_SR_TFE) && (!(reg_val & MASK_SPI_SR_BSY))) { + break; + } + hi_udelay(1); + } + if (count >= SPI_HOST_TIMEOUT_US) { + spi_process_printf("%s spi transfer wait timeout!", __func__); + return HI_ERR_SPI_WRITE_TIMEOUT; + } + return HI_ERR_SUCCESS; +} + +/* check tx fifo not full */ +HI_ALWAYS_STAIC_INLINE hi_u32 spi_check_tnf_timeout(hi_u32 reg_base, HI_CONST hi_u32 time_out_us) +{ + hi_u16 reg_val = 0; + hi_u32 count = 0; + while (count++ < time_out_us) { + hi_reg_read16(reg_base + REG_SPI_SR, reg_val); + if ((reg_val & MASK_SPI_SR_TNF)) { + break; + } + hi_udelay(1); + } + if (count >= time_out_us) { + if (reg_val & MASK_SPI_SR_TNF) { + spi_process_printf("MASK_SPI_SR_TNF\n"); + } + if (reg_val & MASK_SPI_SR_BSY) { + spi_process_printf("MASK_SPI_SR_BSY \n"); + } + return HI_ERR_SPI_WRITE_TIMEOUT; + } + return HI_ERR_SUCCESS; +} +/* check rx fifo not empty */ +HI_ALWAYS_STAIC_INLINE hi_u32 spi_check_rne_timeout(hi_u32 reg_base, HI_CONST hi_u32 time_out_us) +{ + hi_u16 reg_val = 0; + hi_u32 count = 0; + while (count++ < time_out_us) { + hi_reg_read16(reg_base + REG_SPI_SR, reg_val); + if (((reg_val & MASK_SPI_SR_RNE))) { + break; + } + hi_udelay(1); + } + if (count >= time_out_us) { + spi_process_printf("%s timeout!\n", __func__); + return HI_ERR_SPI_WRITE_TIMEOUT; + } + return HI_ERR_SUCCESS; +} + +/* + * spi_flush_fifo: flush spi fifo + */ +hi_void spi_flush_fifo(hi_u32 reg_base) +{ + hi_u16 reg_val = 0; + hi_u16 fifo_len = (reg_base == HI_SSP0_REG_BASE ? SPI0_FIFO_LEN : SPI1_FIFO_LEN); + for (hi_u16 i = 0; i < fifo_len; i++) { + hi_reg_read16(reg_base + REG_SPI_SR, reg_val); + if (!(reg_val & MASK_SPI_SR_RNE)) { + break; + } + hi_reg_read16(reg_base + REG_SPI_DR, reg_val); + } +} + +hi_void spi_disable(spi_ctrl *ctrl) +{ + hi_u16 reg_val = 0; + if (ctrl == NULL) { + spi_process_printf("spi_disable para is null \n"); + return; + } + if ((ctrl->spi_cfg.is_slave == 0) && spi_check_busy(ctrl->reg_base)) { + ctrl->disable_later = HI_TRUE; + return; + } + hi_reg_read16(ctrl->reg_base + REG_SPI_CR1, reg_val); + reg_val &= ~(1 << SPI_CR1_ST_BIT_SSE); + hi_reg_write16(ctrl->reg_base + REG_SPI_CR1, reg_val); +} + +static hi_void spi_enable(spi_ctrl *ctrl) +{ + hi_u16 reg_val = 0; + + hi_reg_read16(ctrl->reg_base + REG_SPI_CR1, reg_val); + reg_val |= (1 << SPI_CR1_ST_BIT_SSE); + hi_reg_write16(ctrl->reg_base + REG_SPI_CR1, reg_val); + ctrl->disable_later = HI_FALSE; +} + +hi_void spi_reset(const spi_ctrl *spi_hw_ctrl) +{ + hi_u8 reset_bit; + hi_u16 reg_val = 0; + hi_u32 int_value; + if (spi_hw_ctrl != HI_NULL && + spi_hw_ctrl->reg_base == HI_SSP0_REG_BASE) { + reset_bit = CRG_REG_SSP_SRST_REQ_OFFSET; + } else { + reset_bit = CRG_REG_SSP2_SRST_REQ_OFFSET; + } + int_value = hi_int_lock(); + hi_reg_read16(CLDO_CTL_SOFT_RESET_REG, reg_val); + reg_val &= (~((hi_u16)(1 << reset_bit))); + hi_reg_write16(CLDO_CTL_SOFT_RESET_REG, reg_val); + reg_val |= (hi_u16)(1 << reset_bit); + hi_reg_write16(CLDO_CTL_SOFT_RESET_REG, reg_val); + hi_int_restore(int_value); +} + +hi_u32 spi_config(const spi_ctrl *spi_hw_ctrl) +{ + spi_inner_cfg inner_cfg = { 0 }; + if (spi_hw_ctrl == HI_NULL) { + return HI_ERR_FAILURE; + } + if (memcpy_s(&inner_cfg, sizeof(spi_inner_cfg), &spi_hw_ctrl->spi_cfg, sizeof(spi_inner_cfg)) == EOK) { + hi_reg_write16(spi_hw_ctrl->reg_base + REG_SPI_CR0, inner_cfg.cr0); + hi_reg_write16(spi_hw_ctrl->reg_base + REG_SPI_CR1, inner_cfg.cr1); + hi_reg_write16(spi_hw_ctrl->reg_base + REG_SPI_CPSR, inner_cfg.cpsdvsr); + } else { + return HI_ERR_FAILURE; + } + return HI_ERR_SUCCESS; +} + +hi_void spi_set_fifo_line(const spi_ctrl *spi_hw_ctrl) +{ + hi_u16 reg_val; + if (spi_hw_ctrl == HI_NULL) { + return; + } + hi_reg_read16(spi_hw_ctrl->reg_base + REG_SPI_TXFIFOCR, reg_val); + reg_val &= ~(hi_u16)(SPI_FIFO_LINE_MASK << SPI_FIFO_LINE_OFFSET); + reg_val |= (hi_u16)(spi_hw_ctrl->spi_cfg.tx_fifo_line << SPI_FIFO_LINE_OFFSET); + hi_reg_write16(spi_hw_ctrl->reg_base + REG_SPI_TXFIFOCR, reg_val); + hi_reg_read16(spi_hw_ctrl->reg_base + REG_SPI_RXFIFOCR, reg_val); + reg_val &= ~(hi_u16)(SPI_FIFO_LINE_MASK << SPI_FIFO_LINE_OFFSET); + reg_val |= (hi_u16)(spi_hw_ctrl->spi_cfg.rx_fifo_line << SPI_FIFO_LINE_OFFSET); + hi_reg_write16(spi_hw_ctrl->reg_base + REG_SPI_RXFIFOCR, reg_val); +} + +#ifdef CONFIG_SPI_DMA_SUPPORT +hi_void spi_set_dma_fifo_line(const spi_ctrl *spi_hw_ctrl) +{ + hi_u16 reg_val; + if (spi_hw_ctrl == HI_NULL) { + return; + } + hi_reg_read16(spi_hw_ctrl->reg_base + REG_SPI_TXFIFOCR, reg_val); + reg_val &= ~(hi_u16)(SPI_FIFO_LINE_MASK); + reg_val |= (hi_u16)(spi_hw_ctrl->spi_cfg.tx_fifo_dma_line); + hi_reg_write16(spi_hw_ctrl->reg_base + REG_SPI_TXFIFOCR, reg_val); + hi_reg_read16(spi_hw_ctrl->reg_base + REG_SPI_RXFIFOCR, reg_val); + reg_val &= ~(hi_u16)(SPI_FIFO_LINE_MASK); + reg_val |= (hi_u16)(spi_hw_ctrl->spi_cfg.rx_fifo_dma_line); + hi_reg_write16(spi_hw_ctrl->reg_base + REG_SPI_RXFIFOCR, reg_val); +} + +hi_void dma_write_fifo_callback(hi_u32 irq_type) +{ + spi_process_printf("This is callback,irq type is %d\r\n", irq_type); + if (irq_type == DMA_INT_TC) { + hi_event_send(g_spi_ctrl[0]->event_id, HI_EVENT_BIT_DMA_TX_DATA); + } else { + hi_event_send(g_spi_ctrl[0]->event_id, HI_EVENT_BIT_DMA_TX_ERR_DATA); + } +} +hi_void dma_read_fifo_callback(hi_u32 irq_type) +{ + spi_process_printf("This is callback,irq type is %d\r\n", irq_type); + if (irq_type == DMA_INT_TC) { + hi_event_send(g_spi_ctrl[0]->event_id, HI_EVENT_BIT_DMA_RX_DATA); + } else { + hi_event_send(g_spi_ctrl[0]->event_id, HI_EVENT_BIT_DMA_RX_ERR_DATA); + } +} +hi_void dma_write_fifo_callback_spi1(hi_u32 irq_type) +{ + spi_process_printf("This is callback,irq type is %d\r\n", irq_type); + if (irq_type == DMA_INT_TC) { + hi_event_send(g_spi_ctrl[1]->event_id, HI_EVENT_BIT_DMA_TX_DATA); + } else { + hi_event_send(g_spi_ctrl[1]->event_id, HI_EVENT_BIT_DMA_TX_ERR_DATA); + } +} +hi_void dma_read_fifo_callback_spi1(hi_u32 irq_type) +{ + spi_process_printf("This is callback,irq type is %d\r\n", irq_type); + if (irq_type == DMA_INT_TC) { + hi_event_send(g_spi_ctrl[1]->event_id, HI_EVENT_BIT_DMA_RX_DATA); + } else { + hi_event_send(g_spi_ctrl[1]->event_id, HI_EVENT_BIT_DMA_RX_ERR_DATA); + } +} + +HI_ALWAYS_STAIC_INLINE hi_u32 spi_get_rx_dma_burst_size(spi_ctrl *spi_dev_ctrl) +{ + spi_hw_cfg *spi_cfg = &(spi_dev_ctrl->spi_cfg); + if (spi_dev_ctrl->reg_base == HI_SSP0_REG_BASE) { + return spi_cfg->rx_fifo_dma_line >= + SPI0_RX_FIFO_DMA_WLINE_128 ? DMA_BURST_MSIZE_128 : spi_cfg->rx_fifo_dma_line; + } else { + return spi_cfg->rx_fifo_dma_line >= SPI1_RX_FIFO_DMA_WLINE_32 ? DMA_BURST_MSIZE_32 : spi_cfg->rx_fifo_dma_line; + } +} + +HI_ALWAYS_STAIC_INLINE hi_u32 spi_get_tx_dma_burst_size(spi_ctrl *spi_dev_ctrl) +{ + spi_hw_cfg *spi_cfg = &(spi_dev_ctrl->spi_cfg); + if (spi_dev_ctrl->reg_base == HI_SSP0_REG_BASE) { + return spi_cfg->tx_fifo_dma_line >= SPI0_TX_FIFO_DMA_WLINE_64 ? DMA_BURST_MSIZE_128 : spi_cfg->tx_fifo_dma_line; + } else { + return spi_cfg->tx_fifo_dma_line >= SPI1_TX_FIFO_DMA_WLINE_16 ? DMA_BURST_MSIZE_32 : spi_cfg->tx_fifo_dma_line; + } +} + +hi_void spi_dma_enable(hi_u32 reg_base, hi_u16 enable_bits) /* 使能DMA(按bit操作) */ +{ + hi_u16 reg_val = 0; + hi_u32 int_save; + int_save = hi_int_lock(); + hi_reg_read16(reg_base + REG_SPI_DMACR, reg_val); + reg_val |= enable_bits; + hi_reg_write16(reg_base + REG_SPI_DMACR, reg_val); + hi_int_restore(int_save); + spi_process_printf("dma enable 0x%x 0x%x", reg_base, reg_val); +} + +hi_void spi_dma_disable(hi_u32 reg_base, hi_u16 disable_bits) /* 清除DMA使能位(按bit操作) */ +{ + hi_u16 reg_val = 0; + hi_u32 int_save; + int_save = hi_int_lock(); + hi_reg_read16(reg_base + REG_SPI_DMACR, reg_val); + reg_val &= (~disable_bits); + hi_reg_write16(reg_base + REG_SPI_DMACR, reg_val); + hi_int_restore(int_save); +} + +hi_u32 spi_dma_transer(hi_u32 tr_type, spi_ctrl *spi_dev_ctrl, uintptr_t addr, hi_u32 tran_len, + hi_void (*cb)(hi_u32), + hi_u32 *ch_num) +{ + hi_u32 reg_base = spi_dev_ctrl->reg_base; + hi_u32 data_width = WIDTH_BIT8; + if (hi_unlikely(spi_dev_ctrl->spi_cfg.data_width > HI_SPI_CFG_DATA_WIDTH_E_8BIT)) { + data_width = WIDTH_BIT16; + } + hi_u8 dma_burst_size; + hi_u32 dma_ts; + hi_dma_para dma_para; + dma_para.tr_type = tr_type; + dma_para.src_width = data_width; + dma_para.dst_width = data_width; + if (tr_type == MEM_TO_SPI) { + dma_para.dst_addr = reg_base + REG_SPI_DR; + dma_para.src_addr = addr; + dma_para.dst_phl = (reg_base == HI_SSP0_REG_BASE) ? SPI0_TX : SPI1_TX; + dma_para.src_phl = 0; + dma_burst_size = spi_get_tx_dma_burst_size(spi_dev_ctrl); + } else { + dma_para.dst_addr = addr; + dma_para.src_addr = reg_base + REG_SPI_DR; + dma_para.dst_phl = 0; + dma_para.src_phl = (reg_base == HI_SSP0_REG_BASE) ? SPI0_RX : SPI1_RX; + dma_burst_size = spi_get_rx_dma_burst_size(spi_dev_ctrl); + } + dma_ts = spi_get_transfer_size(dma_burst_size); + dma_para.dst_burst_size = (dma_ts > tran_len) ? DMA_BURST_MSIZE_1 : dma_burst_size; + dma_para.src_burst_size = (dma_ts > tran_len) ? DMA_BURST_MSIZE_1 : dma_burst_size; + dma_para.transfer_size = tran_len; + dma_para.cb = cb; + return dma_hw_request_transfer(&dma_para, ch_num); +} + +/* +・dma read fifo can used for slave device + */ +hi_u32 spi_hd_dma_read_fifo(spi_ctrl *spi_dev_ctrl, hi_u32 timeout_ms) +{ + if (spi_dev_ctrl == HI_NULL) { + return HI_ERR_FAILURE; + } + hi_pvoid read_buf = spi_dev_ctrl->rx_buf.buf; + hi_u32 read_pos = spi_dev_ctrl->rx_buf.cur_pos; + hi_u32 loop = spi_dev_ctrl->trans_len - spi_dev_ctrl->rx_buf.cur_cnt; + hi_u32 ret; + hi_u32 event_bit = 0; + hi_u32 ch_num = 0xff; /* set invalid value 0xff */ + if (spi_dev_ctrl->reg_base == HI_SSP0_REG_BASE) { + if (spi_dev_ctrl->spi_cfg.data_width < HI_SPI_CFG_DATA_WIDTH_E_9BIT) { + ret = spi_dma_transer(SPI_TO_MEM, spi_dev_ctrl, (uintptr_t)((hi_u8 *)read_buf + read_pos), loop, + dma_read_fifo_callback, &ch_num); + } else { + ret = spi_dma_transer(SPI_TO_MEM, spi_dev_ctrl, (uintptr_t)((hi_u16 *)read_buf + read_pos), loop, + dma_read_fifo_callback, &ch_num); + } + } else { + if (spi_dev_ctrl->spi_cfg.data_width < HI_SPI_CFG_DATA_WIDTH_E_9BIT) { + ret = spi_dma_transer(SPI_TO_MEM, spi_dev_ctrl, (uintptr_t)((hi_u8 *)read_buf + read_pos), loop, + dma_read_fifo_callback_spi1, &ch_num); + } else { + ret = spi_dma_transer(SPI_TO_MEM, spi_dev_ctrl, (uintptr_t)((hi_u16 *)read_buf + read_pos), loop, + dma_read_fifo_callback_spi1, &ch_num); + } + } + if (ret != HI_ERR_SUCCESS) { + return ret; + } + ret = hi_event_wait(spi_dev_ctrl->event_id, HI_EVENT_BIT_DMA_RX_DATA, &event_bit, timeout_ms, + HI_EVENT_WAITMODE_OR | HI_EVENT_WAITMODE_CLR); + if (event_bit & HI_EVENT_BIT_DMA_RX_ERR_DATA) { + spi_process_printf("DMA trans err\n"); + return HI_ERR_FAILURE; + } + if (ret == HI_ERR_EVENT_WAIT_TIME_OUT) { + hi_dma_ch_close(ch_num); + spi_process_printf("read time out\n"); + return HI_ERR_SPI_WRITE_TIMEOUT; + } + spi_dev_ctrl->rx_buf.cur_cnt += loop; /* update cur_cnt and read_pos/cur_pos */ + spi_dev_ctrl->rx_buf.cur_pos += loop; + return ret; +} +hi_u32 spi_hd_dma_write_fifo(spi_ctrl *spi_dev_ctrl, hi_u32 timeout_ms) +{ + if (spi_dev_ctrl == NULL) { + return HI_ERR_FAILURE; + } + hi_pvoid write_buf = spi_dev_ctrl->tx_buf.buf; + hi_u32 write_pos = spi_dev_ctrl->tx_buf.cur_pos; + hi_u32 loop = spi_dev_ctrl->trans_len - spi_dev_ctrl->tx_buf.cur_cnt; + hi_u32 ret; + hi_u32 event_bit = 0; + hi_u32 ch_num = 0xff; /* set invalid value 0xff */ + if (spi_dev_ctrl->reg_base == HI_SSP0_REG_BASE) { + if (spi_dev_ctrl->spi_cfg.data_width < HI_SPI_CFG_DATA_WIDTH_E_9BIT) { + ret = spi_dma_transer(MEM_TO_SPI, spi_dev_ctrl, (uintptr_t)((hi_u8 *)write_buf + write_pos), loop, + dma_write_fifo_callback, &ch_num); + } else { + ret = spi_dma_transer(MEM_TO_SPI, spi_dev_ctrl, (uintptr_t)((hi_u16 *)write_buf + write_pos), loop, + dma_write_fifo_callback, &ch_num); + } + } else { + if (spi_dev_ctrl->spi_cfg.data_width < HI_SPI_CFG_DATA_WIDTH_E_9BIT) { + ret = spi_dma_transer(MEM_TO_SPI, spi_dev_ctrl, (uintptr_t)((hi_u8 *)write_buf + write_pos), loop, + dma_write_fifo_callback_spi1, &ch_num); + } else { + ret = spi_dma_transer(MEM_TO_SPI, spi_dev_ctrl, (uintptr_t)((hi_u16 *)write_buf + write_pos), loop, + dma_write_fifo_callback_spi1, &ch_num); + } + } + if (ret != HI_ERR_SUCCESS) { /* dma fail */ + return ret; + } + ret = hi_event_wait(spi_dev_ctrl->event_id, HI_EVENT_BIT_DMA_TX_DATA | HI_EVENT_BIT_DMA_TX_ERR_DATA, &event_bit, + timeout_ms, HI_EVENT_WAITMODE_OR | HI_EVENT_WAITMODE_CLR); + if (event_bit & HI_EVENT_BIT_DMA_TX_ERR_DATA) { + spi_process_printf("DMA trans err\n"); + return HI_ERR_FAILURE; + } + if (ret == HI_ERR_EVENT_WAIT_TIME_OUT) { + hi_dma_ch_close(ch_num); + spi_process_printf("WRITE time out, ch_num:%d, ret:%x\n", ch_num, ret); + return HI_ERR_SPI_WRITE_TIMEOUT; + } + spi_dev_ctrl->tx_buf.cur_cnt += loop; /* update cur_cnt and read_pos/cur_pos */ + spi_dev_ctrl->tx_buf.cur_pos += loop; + return ret; +} +#endif + +hi_void spi_isr_enable(hi_u32 reg_base, hi_u16 enable_bits) +{ + hi_u16 reg_val = 0; + hi_u32 int_save; + int_save = hi_int_lock(); + hi_reg_read16(reg_base + REG_SPI_IMSC, reg_val); + reg_val |= enable_bits; + hi_reg_write16(reg_base + REG_SPI_IMSC, reg_val); + hi_int_restore(int_save); + spi_process_printf("isr enable 0x%x 0x%x", reg_base, reg_val); +} + +hi_void spi_isr_disable(hi_u32 reg_base, hi_u16 disable_bits) +{ + hi_u16 reg_val = 0; + hi_u32 int_save; + int_save = hi_int_lock(); + hi_reg_read16(reg_base + REG_SPI_IMSC, reg_val); + reg_val &= (~disable_bits); + hi_reg_write16(reg_base + REG_SPI_IMSC, reg_val); + hi_int_restore(int_save); +} +hi_void spi_isr_clear_cr(hi_u32 reg_base, hi_u16 clear_bit) +{ + hi_u16 reg_val = 0; + hi_u32 int_save; + int_save = hi_int_lock(); + hi_reg_read16(reg_base + REG_SPI_CR, reg_val); + reg_val |= clear_bit; + hi_reg_write16(reg_base + REG_SPI_CR, reg_val); + hi_int_restore(int_save); +} + +HI_ALWAYS_STAIC_INLINE hi_void spi_isr_read_16bits(spi_ctrl *spi_dev_ctrl, hi_bool fifo_irq, hi_u32 loop, + hi_pvoid read_buf, hi_u16 increase_step) +{ + hi_u32 i; + hi_u32 reg_base = spi_dev_ctrl->reg_base; + hi_u32 read_pos = spi_dev_ctrl->rx_buf.cur_pos; + if (fifo_irq) { + for (i = 0; i < loop; i++) { + *((hi_u16 *)read_buf + read_pos) = (hi_u16)hi_reg_read_val16(reg_base + REG_SPI_DR); + read_pos += increase_step; + } + spi_dev_ctrl->rx_buf.cur_cnt += loop; + } else { + for (i = 0; i < loop; i++) { + if (hi_likely(!spi_check_rx_fifo_empty(reg_base))) { + *((hi_u16 *)read_buf + read_pos) = (hi_u16)hi_reg_read_val16(reg_base + REG_SPI_DR); + read_pos += increase_step; + spi_dev_ctrl->rx_buf.cur_cnt++; + } else { + break; + } + } + } + spi_dev_ctrl->rx_buf.cur_pos = read_pos; +} + +HI_ALWAYS_STAIC_INLINE hi_void spi_isr_read_8bits(spi_ctrl *spi_dev_ctrl, hi_bool fifo_irq, hi_u32 loop, + hi_pvoid read_buf, hi_u16 increase_step) +{ + hi_u32 i; + hi_u32 reg_base = spi_dev_ctrl->reg_base; + hi_u32 read_pos = spi_dev_ctrl->rx_buf.cur_pos; + if (fifo_irq) { + for (i = 0; i < loop; i++) { + *((hi_u8 *)read_buf + read_pos) = (hi_u8)hi_reg_read_val16(reg_base + REG_SPI_DR); + read_pos += increase_step; + } + spi_dev_ctrl->rx_buf.cur_cnt += loop; + } else { + for (i = 0; i < loop; i++) { + if (hi_likely(!spi_check_rx_fifo_empty(reg_base))) { + *((hi_u8 *)read_buf + read_pos) = (hi_u8)hi_reg_read_val16(reg_base + REG_SPI_DR); + read_pos += increase_step; + spi_dev_ctrl->rx_buf.cur_cnt++; + } else { + break; + } + } + } + spi_dev_ctrl->rx_buf.cur_pos = read_pos; +} + +static hi_u16 spi_isr_read_fifo(spi_ctrl *spi_dev_ctrl, hi_bool fifo_irq) +{ + hi_pvoid read_buf = spi_dev_ctrl->rx_buf.buf; + hi_u16 fix_data = SPI_UNUSE_DATA; + hi_u16 increase_step = 1; + hi_u32 loop = hi_min(spi_dev_ctrl->single_len, (spi_dev_ctrl->trans_len - spi_dev_ctrl->rx_buf.cur_cnt)); + if (read_buf == HI_NULL) { + read_buf = &fix_data; + increase_step = 0; + } + + if (hi_likely(spi_dev_ctrl->spi_cfg.data_width < HI_SPI_CFG_DATA_WIDTH_E_9BIT)) { + spi_isr_read_8bits(spi_dev_ctrl, fifo_irq, loop, read_buf, increase_step); + } else { + spi_isr_read_16bits(spi_dev_ctrl, fifo_irq, loop, read_buf, increase_step); + } + + if (spi_dev_ctrl->rx_buf.cur_cnt >= spi_dev_ctrl->trans_len) { + return SPI_INT_BIT_RX_FIFO_WATER_LINE | SPI_INT_BIT_RX_FIFO_TIME_OUT; + } + return 0; +} + +static hi_u16 spi_isr_write_fifo(spi_ctrl *spi_dev_ctrl) +{ + hi_pvoid write_buf = spi_dev_ctrl->tx_buf.buf; + hi_u32 i; + hi_u16 fix_data = SPI_UNUSE_DATA; + hi_u16 increase_step = 1; + hi_u32 reg_base = spi_dev_ctrl->reg_base; + hi_u32 len = spi_dev_ctrl->single_len; + hi_u32 write_pos = spi_dev_ctrl->tx_buf.cur_pos; + if (write_buf == HI_NULL) { + write_buf = &fix_data; + increase_step = 0; + } + if (hi_likely(spi_dev_ctrl->spi_cfg.data_width < HI_SPI_CFG_DATA_WIDTH_E_9BIT)) { + for (i = 0; i < len; i++) { + spi_process_printf("[wreg8][0x%x]", *((hi_u8 *)write_buf + write_pos)); + hi_reg_write16(reg_base + REG_SPI_DR, *((hi_u8 *)write_buf + write_pos)); + write_pos += increase_step; + } + spi_dev_ctrl->tx_buf.cur_cnt += len; + } else { + for (i = 0; i < len; i++) { + spi_process_printf("[wreg16][0x%x]", *((hi_u16 *)write_buf + write_pos)); + hi_reg_write16(reg_base + REG_SPI_DR, *((hi_u16 *)write_buf + write_pos)); + write_pos += increase_step; + } + spi_dev_ctrl->tx_buf.cur_cnt += len; + } + spi_dev_ctrl->tx_buf.cur_pos = write_pos; + if (spi_dev_ctrl->tx_buf.cur_cnt == spi_dev_ctrl->single_len) { + spi_dev_ctrl->tx_buf.cur_cnt = 0; + return SPI_INT_BIT_TX_FIFO_WATER_LINE; + } + return 0; +} + +hi_void spi_isr(spi_ctrl *spi_dev_ctrl) +{ + if (spi_dev_ctrl == NULL) { + spi_process_printf("spi_isr para is null \n"); + return; + } + hi_u32 reg_base = spi_dev_ctrl->reg_base; + hi_u16 int_val; + hi_u32 event_bits = 0; + hi_u16 dis_int_bis = 0; + hi_u16 clear_int_bits = 0; + hi_u32 ret; + hi_reg_read16(reg_base + REG_SPI_MIS, int_val); + if (int_val & SPI_INT_BIT_TX_FIFO_WATER_LINE) { + dis_int_bis |= spi_isr_write_fifo(spi_dev_ctrl); + event_bits |= HI_EVENT_BIT_TX_DATA; + } + if (int_val & SPI_INT_BIT_RX_FIFO_WATER_LINE) { + dis_int_bis |= spi_isr_read_fifo(spi_dev_ctrl, HI_TRUE); + event_bits |= HI_EVENT_BIT_RX_DATA; + } + if (int_val & SPI_INT_BIT_RX_FIFO_TIME_OUT) { + dis_int_bis |= spi_isr_read_fifo(spi_dev_ctrl, HI_FALSE); + event_bits |= HI_EVENT_BIT_RX_DATA; + clear_int_bits |= SPI_INT_BIT_RTIC; + } + if (int_val & SPI_INT_BIT_RX_FIFO_OVER_FLOW) { + dis_int_bis |= SPI_INT_BIT_RX_FIFO_OVER_FLOW; + event_bits |= HI_EVENT_BIT_RX_FIFO_OVER_FLOW; + clear_int_bits |= SPI_INT_BIT_RORIC; + } + spi_isr_clear_cr(reg_base, clear_int_bits); + spi_isr_disable(reg_base, dis_int_bis); + if (spi_dev_ctrl->disable_later && !spi_check_busy(reg_base)) { + spi_dev_ctrl->disable_later = HI_FALSE; + } + ret = hi_event_send(spi_dev_ctrl->event_id, event_bits); + if (ret != HI_ERR_SUCCESS) { + spi_process_printf("spi_isr send sig fail \n"); + } +} + +hi_u32 spi_trans_prepare(spi_ctrl *spi_hw_ctrl, spi_trans_attr *trans_attr) +{ + hi_u32 ret = HI_ERR_SUCCESS; + if ((spi_hw_ctrl == NULL) || (trans_attr == NULL)) { + return HI_ERR_FAILURE; + } + + if (trans_attr->trans_opt & SPI_OPT_WAIT_SIGNAL) { + spi_process_printf("wait_sem\n"); + ret = hi_sem_wait(spi_hw_ctrl->sem_id, trans_attr->time_out_ms); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + trans_attr->trans_opt |= SPI_OPT_TASKED_SIGNAL; + } + spi_hw_ctrl->transferring = HI_TRUE; + if (spi_hw_ctrl->prepare_func) { + spi_hw_ctrl->prepare_func(); + } + if (trans_attr->trans_opt & SPI_OPT_ENABLE_SPI) { + spi_enable(spi_hw_ctrl); + } + return ret; +} + +hi_void spi_trans_restore(spi_ctrl *spi_hw_ctrl, const spi_trans_attr *trans_attr) +{ + if ((spi_hw_ctrl == NULL) || (trans_attr == NULL)) { + return; + } + if (spi_hw_ctrl->restore_func) { + spi_hw_ctrl->restore_func(); + } + + if ((trans_attr->trans_opt & SPI_OPT_TASKED_SIGNAL) && (trans_attr->trans_opt & SPI_OPT_FREE_SIGNAL)) { + spi_process_printf("free_sem\n"); + hi_u32 ret = hi_sem_signal(spi_hw_ctrl->sem_id); + if (ret != HI_ERR_SUCCESS) { + spi_process_printf("free_sem fail\n"); + } + } + spi_hw_ctrl->transferring = HI_FALSE; +} + +hi_u32 spi_transfer_8bits_block(const spi_ctrl *spi_hw_ctrl, hi_u32 options) +{ + if (spi_hw_ctrl == NULL) { + return HI_ERR_FAILURE; + } + hi_u32 tmp_len, count; + hi_u16 value; + hi_u8 *tx = (hi_u8 *)spi_hw_ctrl->tx_buf.buf; + hi_u8 *rx = (hi_u8 *)spi_hw_ctrl->rx_buf.buf; + hi_u32 len = spi_hw_ctrl->trans_len; + hi_u16 fifo_len = (spi_hw_ctrl->reg_base == HI_SSP0_REG_BASE ? SPI0_FIFO_LEN : SPI1_FIFO_LEN); + hi_bool write_not_fix = ((options & SPI_OPT_SEND_FIX_DATA) == 0); + hi_bool read_not_fix = ((options & SPI_OPT_RCV_FIX_DATA) == 0); + hi_u32 ret; + while (len) { + if (len > fifo_len) { + tmp_len = fifo_len; + } else { + tmp_len = len; + } + len -= tmp_len; + /* wirte fifo */ + count = tmp_len; + value = SPI_UNUSE_DATA; + while (count) { + if (write_not_fix && tx != HI_NULL) { + value = *tx++; + } + hi_reg_write16(spi_hw_ctrl->reg_base + REG_SPI_DR, value); + count -= 1; + } + ret = spi_check_write_timeout(spi_hw_ctrl->reg_base); + if (ret != HI_ERR_SUCCESS) { + return HI_ERR_SPI_WRITE_TIMEOUT; + } + /* if host device too fast, there be delay 50-100us */ + /* read fifo */ + count = tmp_len; + while (count) { + hi_reg_read16(spi_hw_ctrl->reg_base + REG_SPI_DR, value); + if (read_not_fix && rx != HI_NULL) { + *rx++ = (hi_u8)value; + } + count -= 1; + } + } + return HI_ERR_SUCCESS; +} + +/* + * spi_txrx16: send and receive 16bit data + */ +hi_u32 spi_transfer_16bits_block(const spi_ctrl *spi_hw_ctrl, hi_u32 options) +{ + if (spi_hw_ctrl == NULL) { + return HI_ERR_FAILURE; + } + hi_u32 len = spi_hw_ctrl->trans_len; + hi_u32 tmp_len; + hi_u32 count; + hi_u16 *tx = (hi_u16 *)spi_hw_ctrl->tx_buf.buf; + hi_u16 *rx = (hi_u16 *)spi_hw_ctrl->rx_buf.buf; + hi_u16 value; + hi_u16 fifo_len = (spi_hw_ctrl->reg_base == HI_SSP0_REG_BASE ? SPI0_FIFO_LEN : SPI1_FIFO_LEN); + hi_bool write_not_fix = ((options & SPI_OPT_SEND_FIX_DATA) == 0); + hi_bool read_not_fix = ((options & SPI_OPT_RCV_FIX_DATA) == 0); + hi_u32 ret; + while (len) { + if (len > fifo_len) { + tmp_len = fifo_len; + } else { + tmp_len = len; + } + len -= tmp_len; + /* wirte fifo */ + count = tmp_len; + value = SPI_UNUSE_DATA; + while (count) { + if (write_not_fix && tx != HI_NULL) { + value = *tx++; + } + hi_reg_write16(spi_hw_ctrl->reg_base + REG_SPI_DR, value); + count--; + } + ret = spi_check_write_timeout(spi_hw_ctrl->reg_base); + if (ret != HI_ERR_SUCCESS) { + return HI_ERR_SPI_WRITE_TIMEOUT; + } + /* if host device too fast, there be delay 50-100us */ + count = tmp_len; + while (count) { + hi_reg_read16(spi_hw_ctrl->reg_base + REG_SPI_DR, value); + if (read_not_fix && rx != HI_NULL) { + *rx++ = value; + } + count--; + } + } + return HI_ERR_SUCCESS; +} diff --git a/sdk_liteos/platform/drivers/spi/spi.h b/sdk_liteos/platform/drivers/spi/spi.h new file mode 100644 index 0000000000000000000000000000000000000000..b1b4fd8b12eb1c56f1433b703ec095a973a228fe --- /dev/null +++ b/sdk_liteos/platform/drivers/spi/spi.h @@ -0,0 +1,333 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __SPI_H__ +#define __SPI_H__ + +#include +#include +#include +#include +#include +#include +#include +#include + +/* if some print is needed :#define SPI_DEBUG */ +#ifdef SPI_DEBUG +#define spi_printf(fmt...) do { \ + printf("[DEBUG]"fmt); \ + printf("\n"); \ +} while (0) +#define spi_process_printf(fmt...) do { \ + printf("[PROCESS]"fmt); \ + printf("\n"); \ +} while (0) +#else +#define spi_printf(fmt, ...) +#define spi_process_printf(fmt, ...) +#endif + +#define SPI_NUM 2 + +#define REG_SPI_CR0 0x00 +#define REG_SPI_CR1 0x04 +#define REG_SPI_DR 0x08 +#define REG_SPI_SR 0x0c +#define REG_SPI_CPSR 0x10 +#define REG_SPI_IMSC 0x14 +#define REG_SPI_RIS 0x18 +#define REG_SPI_MIS 0x1c +#define REG_SPI_CR 0x20 +#define REG_SPI_DMACR 0x24 +#define REG_SPI_TXFIFOCR 0x28 +#define REG_SPI_RXFIFOCR 0x2c + +#define MASK_SPI_SR_TFE (1<<0) +#define MASK_SPI_SR_TNF (1<<1) +#define MASK_SPI_SR_RNE (1<<2) +#define MASK_SPI_SR_RFF (1<<3) +#define MASK_SPI_SR_BSY (1<<4) + +#define SPI_CR0_ST_BIT_DSS 0 +#define SPI_CR0_ST_BIT_FRF 4 +#define SPI_CR0_ST_BIT_SPO 6 +#define SPI_CR0_ST_BIT_SPH 7 +#define SPI_CR0_ST_BIT_SCR 8 + +#define SPI_CR0_BIT_WIDTH_DSS 4 +#define SPI_CR0_BIT_WIDTH_FRF 2 +#define SPI_CR0_BIT_WIDTH_SPO 1 +#define SPI_CR0_BIT_WIDTH_SPH 1 +#define SPI_CR0_BIT_WIDTH_SCR 8 + +#define SPI_CR1_ST_BIT_LBM 0 +#define SPI_CR1_ST_BIT_SSE 1 +#define SPI_CR1_ST_BIT_MS 2 +#define SPI_CR1_ST_BIT_BIGEND 4 +#define SPI_CR1_ST_BIT_WAITVAL 8 +#define SPI_CR1_ST_BIT_WAITEN 15 + +#define SPI_CR1_BIT_WIDTH_LBM 1 +#define SPI_CR1_BIT_WIDTH_SSE 1 +#define SPI_CR1_BIT_WIDTH_MS 1 +#define SPI_CR1_BIT_WIDTH_BIGEND 1 +#define SPI_CR1_BIT_WIDTH_WAITVAL 7 +#define SPI_CR1_BIT_WIDTH_WAITEN 1 + +#define SPI_INT_BIT_TX_FIFO_WATER_LINE (1<<3) +#define SPI_INT_BIT_RX_FIFO_WATER_LINE (1<<2) +#define SPI_INT_BIT_RX_FIFO_TIME_OUT (1<<1) +#define SPI_INT_BIT_RX_FIFO_OVER_FLOW (1<<0) + +#define SPI_INT_BIT_RTIC (1<<1) +#define SPI_INT_BIT_RORIC (1<<0) + +#define SPI_TX_DMAE (1<<1) +#define SPI_RX_DMAE (1<<0) + +#define SPI_FIFO_LINE_OFFSET 3 +#define SPI_FIFO_MAX_VAL 7 +#define SPI_FIFO_LINE_MASK 0x7 + +#define SPI_UNUSE_DATA 0xFFFF + +#define spi_get_transfer_size(burst) (((burst) == (DMA_BURST_MSIZE_1)) ? 1 : (1 << ((burst) + 1))) + +#define MEM_TO_SPI 1 +#define SPI_TO_MEM 2 + +#define SCR_MAX 255 +#define SCR_MIN 0 +#define CPSDVSR_MAX 254 +#define CPSDVSR_MIN 4 + +#define SPI0_FIFO_LEN 256 +#define SPI1_FIFO_LEN 64 +#define SPI0_FIFO_THRESHOLD 128 +#define SPI1_FIFO_THRESHOLD 32 + +#define SPI_HOST_TIMEOUT_US 1000000 +#define SPI_HOST_TIMEOUT_MS 1000 + +#define SPI_SLAVE_TIMEOUT_US 10000000 + +#define SPI0_TX_FIFO_WATER_LINE 6 +#define SPI0_RX_FIFO_WATER_LINE 6 +#define SPI1_TX_FIFO_WATER_LINE 4 +#define SPI1_RX_FIFO_WATER_LINE 3 + +#define SPI0_TX_FIFO_DMA_WLINE_64 7 +#define SPI0_RX_FIFO_DMA_WLINE_128 6 +#define SPI1_TX_FIFO_DMA_WLINE_16 4 +#define SPI1_RX_FIFO_DMA_WLINE_32 4 + +/* 40 or 24M */ +#define SPI_DEFAULT_CLK 160000000 +#define spi_max_speed(clk) ((clk) / (((SCR_MIN) + 1) * (CPSDVSR_MIN))) +#define spi_min_speed(clk) ((clk) / (((SCR_MAX) + 1) * (CPSDVSR_MAX))) + +#define SPI_WRITE_FLAG 0x1 /* 发送数据 */ +#define SPI_READ_FLAG 0x2 /* 接收数据 */ + +#define GPIO_00_SEL 0x604 +#define GPIO_01_SEL 0x608 +#define GPIO_02_SEL 0x60c +#define GPIO_03_SEL 0x610 + +#define GPIO_05_SEL 0x618 +#define GPIO_06_SEL 0x61c +#define GPIO_07_SEL 0x620 +#define GPIO_08_SEL 0x624 + +#define GPIO_09_SEL 0x628 +#define GPIO_10_SEL 0x62c +#define GPIO_11_SEL 0x630 +#define GPIO_12_SEL 0x634 + +/** + * SPI EVENT + */ +#define HI_EVENT_BIT_RX_DATA 0x1 +#define HI_EVENT_BIT_TX_DATA 0x2 +#define HI_EVENT_BIT_RX_DATA_TIME_OUT 0x4 +#define HI_EVENT_BIT_RX_FIFO_OVER_FLOW 0x8 + +#define HI_EVENT_BIT_DMA_RX_DATA 0x10 +#define HI_EVENT_BIT_DMA_RX_ERR_DATA 0x20 +#define HI_EVENT_BIT_DMA_TX_DATA 0x40 +#define HI_EVENT_BIT_DMA_TX_ERR_DATA 0x80 + +typedef enum { + SPI_OPT_SET_CFG = 0x1, + SPI_OPT_ENABLE_SPI = 0x2, + SPI_OPT_DISABLE_SPI = 0x4, + SPI_OPT_TASKED_SIGNAL = 0x8, + SPI_OPT_SEND_FIX_DATA = 0x10, + SPI_OPT_RCV_FIX_DATA = 0x20, + SPI_OPT_WAIT_SIGNAL = 0x40, + SPI_OPT_FREE_SIGNAL = 0x80, +} spi_opt; + +/** + * @ingroup hct_spi + */ +typedef enum { + SPI_CFG_ROLE_MASTER, + SPI_CFG_ROLE_SLAVE, +} spi_cfg_role; + +/** + * @ingroup hct_spi + */ +typedef enum { + SPI_DATA_WIDTH_1BYTES = 1, + SPI_DATA_WIDTH_2BYTES, +} spi_data_width; + +/** + * @ingroup hct_spi + */ +typedef enum { + HI_SPI0_TX_FIFO_WATER_LINE_1, + HI_SPI0_TX_FIFO_WATER_LINE_4, + HI_SPI0_TX_FIFO_WATER_LINE_8, + HI_SPI0_TX_FIFO_WATER_LINE_16, + HI_SPI0_TX_FIFO_WATER_LINE_32, + HI_SPI0_TX_FIFO_WATER_LINE_64, + HI_SPI0_TX_FIFO_WATER_LINE_128, + HI_SPI0_TX_FIFO_WATER_LINE_192, +} hi_spi0_tx_fifo_water_line; + +/** + * @ingroup hct_spi + */ +typedef enum { + HI_SPI0_RX_FIFO_WATER_LINE_255, + HI_SPI0_RX_FIFO_WATER_LINE_252, + HI_SPI0_RX_FIFO_WATER_LINE_248, + HI_SPI0_RX_FIFO_WATER_LINE_240, + HI_SPI0_RX_FIFO_WATER_LINE_224, + HI_SPI0_RX_FIFO_WATER_LINE_192, + HI_SPI0_RX_FIFO_WATER_LINE_128, + HI_SPI0_RX_FIFO_WATER_LINE_32, +} hi_spi0_rx_fifo_water_line; +/** + * @ingroup hct_spi + */ +typedef enum { + HI_SPI1_TX_FIFO_WATER_LINE_1, + HI_SPI1_TX_FIFO_WATER_LINE_4, + HI_SPI1_TX_FIFO_WATER_LINE_8, + HI_SPI1_TX_FIFO_WATER_LINE_16, + HI_SPI1_TX_FIFO_WATER_LINE_32, + HI_SPI1_TX_FIFO_WATER_LINE_48, + HI_SPI1_TX_FIFO_WATER_LINE_56, + HI_SPI1_TX_FIFO_WATER_LINE_64, +} hi_spi1_tx_fifo_water_line; +/** + * @ingroup hct_spi + */ +typedef enum { + HI_SPI1_RX_FIFO_WATER_LINE_65, + HI_SPI1_RX_FIFO_WATER_LINE_62, + HI_SPI1_RX_FIFO_WATER_LINE_48, + HI_SPI1_RX_FIFO_WATER_LINE_32, + HI_SPI1_RX_FIFO_WATER_LINE_16, + HI_SPI1_RX_FIFO_WATER_LINE_8, + HI_SPI1_RX_FIFO_WATER_LINE_4, + HI_SPI1_RX_FIFO_WATER_LINE_1, +} hi_spi1_rx_fifo_water_line; + +typedef struct { + hi_u16 cr0; + hi_u16 cr1; + hi_u16 cpsdvsr; +} spi_inner_cfg; + +typedef struct { + hi_u16 data_width : 4; + hi_u16 fram_mode : 2; + hi_u16 cpol : 1; + hi_u16 cpha : 1; + hi_u16 scr : 8; + hi_u16 loop_back : 1; + hi_u16 reserver_1 : 1; + hi_u16 is_slave : 1; + hi_u16 reserver_2 : 1; + hi_u16 endian : 1; + hi_u16 reserver_3 : 11; + hi_u16 cpsdvsr; + hi_u16 rx_fifo_line; + hi_u16 tx_fifo_line; + hi_u16 rx_fifo_dma_line; + hi_u16 tx_fifo_dma_line; + hi_u16 pad; +} spi_hw_cfg; + +typedef struct { + hi_u32 time_out_ms; + hi_u32 trans_opt; +} spi_trans_attr; + +typedef struct { + hi_pvoid buf; + volatile hi_u32 cur_pos; + volatile hi_u32 cur_cnt; +} spi_buf; + +typedef struct { + hi_u32 reg_base; + hi_u32 irq_num; + hi_u32 sem_id; + hi_u32 event_id; + hi_bool use_dma; + hi_bool use_irq; + volatile hi_bool transferring; + volatile hi_bool disable_later; + hi_spi_usr_func prepare_func; + hi_spi_usr_func restore_func; + spi_hw_cfg spi_cfg; + hi_u32 single_len; + hi_u32 trans_len; + spi_buf tx_buf; + spi_buf rx_buf; +} spi_ctrl; + +HI_EXTERN spi_ctrl *g_spi_ctrl[SPI_NUM]; + +hi_void spi_isr(spi_ctrl *spi_dev_ctrl); +hi_void spi_isr_enable(hi_u32 reg_base, hi_u16 enable_bits); +hi_void spi_isr_disable(hi_u32 reg_base, hi_u16 disable_bits); +hi_u32 spi_trans_prepare(spi_ctrl *spi_hw_ctrl, spi_trans_attr *trans_attr); +hi_void spi_trans_restore(spi_ctrl *spi_hw_ctrl, const spi_trans_attr *trans_attr); +hi_u32 spi_transfer_8bits_block(const spi_ctrl *spi_hw_ctrl, hi_u32 options); +hi_u32 spi_transfer_16bits_block(const spi_ctrl *spi_hw_ctrl, hi_u32 options); +hi_void spi_set_fifo_line(const spi_ctrl *spi_hw_ctrl); +hi_u32 spi_config(const spi_ctrl *spi_hw_ctrl); +hi_void spi_reset(const spi_ctrl *spi_hw_ctrl); +hi_void spi_disable(spi_ctrl *ctrl); +hi_void spi_flush_fifo(hi_u32 reg_base); + +hi_void spi_isr_clear_cr(hi_u32 reg_base, hi_u16 clear_bit); +#ifdef CONFIG_SPI_DMA_SUPPORT +hi_u32 spi_hd_dma_read_fifo(spi_ctrl *spi_dev_ctrl, hi_u32 timeout_ms); +hi_u32 spi_hd_dma_write_fifo(spi_ctrl *spi_dev_ctrl, hi_u32 timeout_ms); +hi_void spi_set_dma_fifo_line(const spi_ctrl *spi_hw_ctrl); +hi_void spi_dma_enable(hi_u32 reg_base, hi_u16 enable_bits); +hi_void spi_dma_disable(hi_u32 reg_base, hi_u16 disable_bits); +#endif + +#endif diff --git a/sdk_liteos/platform/drivers/tsensor/SConscript b/sdk_liteos/platform/drivers/tsensor/SConscript new file mode 100755 index 0000000000000000000000000000000000000000..b0e5f0e2b015ebbec8bd8a4344149640ab49ef09 --- /dev/null +++ b/sdk_liteos/platform/drivers/tsensor/SConscript @@ -0,0 +1,4 @@ +Import('env') + +objs = env.Object(Glob('*.c')) +Return('objs') diff --git a/sdk_liteos/platform/drivers/tsensor/hi_tsensor_pm.c b/sdk_liteos/platform/drivers/tsensor/hi_tsensor_pm.c new file mode 100644 index 0000000000000000000000000000000000000000..e503abf8bd6db2b2893b099c33bd07d2657fe42f --- /dev/null +++ b/sdk_liteos/platform/drivers/tsensor/hi_tsensor_pm.c @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#define TSENSOR_BASE_ADDRESS (W_CTL_BASE_ADDR) +#define TSENSOR_START 0x0500 /* TSENSOR start register */ +#define TSENSOR_CTRL 0x0504 /* TSENSOR control register */ +#define TSENSOR_MAN_STS 0x0508 /* TSENSOR manual control status register */ +#define TSENSOR_AUTO_STS 0x050C /* TSENSOR auto control status register */ +#define TSENSOR_TRIM_CTRL 0x0510 /* TSENSOR TRIM configuration register */ +#define TSENSOR_TEMP_HIGH_LIMIT 0x0514 /* TSENSOR high temperature threshold register */ +#define TSENSOR_TEMP_LOW_LIMIT 0x0518 /* TSENSOR low temperature threshold register */ +#define TSENSOR_TEMP_OVER_LIMIT 0x051C /* TSENSOR over temperature threshold register */ +#define TSENSOR_TEMP_INT_EN 0x0520 /* TSENSOR interrupt configuration register */ +#define TSENSOR_TEMP_INT_CLR 0x0524 /* TSENSOR interrupt clear register */ +#define TSENSOR_TEMP_INT_STATE 0x0528 /* TSENSOR interrupt state register */ +#define TSENSOR_TEMP_PD_LIMIT 0x0530 /* TSENSOR power down temperature threshold register */ +#define TSENSOR_AUTO_REFRESH_PERIOD 0x0540 /* TSENSOR auto refresh period control register */ +#define TSENSOR_AUTO_REFRESH_CFG 0x0544 /* TSENSOR auto refresh control register */ + +#define TSENSOR_CLK_GATE_BIT 3 +#define TSENSOR_CLK_SET_VALUE ((hi_u16)1 << (TSENSOR_CLK_GATE_BIT)) + +typedef struct { + hi_u16 trim_ctrl; + hi_u16 high_limit; + hi_u16 low_limit; + hi_u16 over_limit; + hi_u16 pd_limit; + hi_u16 int_en; + hi_u16 int_clr; + hi_u16 clk_en; + hi_u16 clk_div; + hi_u16 ctrl; + hi_u16 refresh_period; + hi_u16 refresh_en; + hi_u16 start; +} tsensor_lp_regs; + +tsensor_lp_regs g_lp_regs_save = {0}; + +hi_void hi_tsensor_lp_save(hi_void) +{ + g_lp_regs_save.trim_ctrl = hi_reg_read_val16(TSENSOR_BASE_ADDRESS + TSENSOR_TRIM_CTRL); + g_lp_regs_save.high_limit = hi_reg_read_val16(TSENSOR_BASE_ADDRESS + TSENSOR_TEMP_HIGH_LIMIT); + g_lp_regs_save.low_limit = hi_reg_read_val16(TSENSOR_BASE_ADDRESS + TSENSOR_TEMP_LOW_LIMIT); + g_lp_regs_save.over_limit = hi_reg_read_val16(TSENSOR_BASE_ADDRESS + TSENSOR_TEMP_OVER_LIMIT); + g_lp_regs_save.pd_limit = hi_reg_read_val16(TSENSOR_BASE_ADDRESS + TSENSOR_TEMP_PD_LIMIT); + + g_lp_regs_save.int_en = hi_reg_read_val16(TSENSOR_BASE_ADDRESS + TSENSOR_TEMP_INT_EN); + g_lp_regs_save.int_clr = hi_reg_read_val16(TSENSOR_BASE_ADDRESS + TSENSOR_TEMP_INT_CLR); + + g_lp_regs_save.clk_en = hi_reg_read_val16(W_CTL_UART_MAC80M_CLKEN_REG); + g_lp_regs_save.clk_div = hi_reg_read_val16(W_CTL_TSENSOR_DIV_REG); + g_lp_regs_save.ctrl = hi_reg_read_val16(TSENSOR_BASE_ADDRESS + TSENSOR_CTRL); + g_lp_regs_save.refresh_period = hi_reg_read_val16(TSENSOR_BASE_ADDRESS + TSENSOR_AUTO_REFRESH_PERIOD); + g_lp_regs_save.refresh_en = hi_reg_read_val16(TSENSOR_BASE_ADDRESS + TSENSOR_AUTO_REFRESH_CFG); + + g_lp_regs_save.start = hi_reg_read_val16(TSENSOR_BASE_ADDRESS + TSENSOR_START); +} + +hi_void hi_tsensor_lp_restore(hi_void) +{ + hi_reg_write16((TSENSOR_BASE_ADDRESS + TSENSOR_TRIM_CTRL), g_lp_regs_save.trim_ctrl); + hi_reg_write16((TSENSOR_BASE_ADDRESS + TSENSOR_TEMP_HIGH_LIMIT), g_lp_regs_save.high_limit); + hi_reg_write16((TSENSOR_BASE_ADDRESS + TSENSOR_TEMP_LOW_LIMIT), g_lp_regs_save.low_limit); + hi_reg_write16((TSENSOR_BASE_ADDRESS + TSENSOR_TEMP_OVER_LIMIT), g_lp_regs_save.over_limit); + hi_reg_write16((TSENSOR_BASE_ADDRESS + TSENSOR_TEMP_PD_LIMIT), g_lp_regs_save.pd_limit); + + hi_reg_write16((TSENSOR_BASE_ADDRESS + TSENSOR_TEMP_INT_EN), g_lp_regs_save.int_en); + hi_reg_write16((TSENSOR_BASE_ADDRESS + TSENSOR_TEMP_INT_CLR), g_lp_regs_save.int_clr); + + if ((g_lp_regs_save.clk_en & TSENSOR_CLK_SET_VALUE) == TSENSOR_CLK_SET_VALUE) { + hi_reg_setbit(W_CTL_UART_MAC80M_CLKEN_REG, TSENSOR_CLK_GATE_BIT); + } else { + hi_reg_clrbit(W_CTL_UART_MAC80M_CLKEN_REG, TSENSOR_CLK_GATE_BIT); + hi_reg_setbit((TSENSOR_BASE_ADDRESS + TSENSOR_MAN_STS), 0); + hi_reg_setbit((TSENSOR_BASE_ADDRESS + TSENSOR_AUTO_STS), 0); + } + + hi_reg_write16(W_CTL_TSENSOR_DIV_REG, g_lp_regs_save.clk_div); + hi_reg_write16((TSENSOR_BASE_ADDRESS + TSENSOR_CTRL), g_lp_regs_save.ctrl); + hi_reg_write16((TSENSOR_BASE_ADDRESS + TSENSOR_AUTO_REFRESH_PERIOD), g_lp_regs_save.refresh_period); + hi_reg_write16((TSENSOR_BASE_ADDRESS + TSENSOR_AUTO_REFRESH_CFG), g_lp_regs_save.refresh_en); + + hi_reg_write16(TSENSOR_BASE_ADDRESS + TSENSOR_START, g_lp_regs_save.start); +} + diff --git a/sdk_liteos/platform/drivers/uart/SConscript b/sdk_liteos/platform/drivers/uart/SConscript new file mode 100755 index 0000000000000000000000000000000000000000..b0e5f0e2b015ebbec8bd8a4344149640ab49ef09 --- /dev/null +++ b/sdk_liteos/platform/drivers/uart/SConscript @@ -0,0 +1,4 @@ +Import('env') + +objs = env.Object(Glob('*.c')) +Return('objs') diff --git a/sdk_liteos/platform/drivers/uart/hi_uart.c b/sdk_liteos/platform/drivers/uart/hi_uart.c new file mode 100644 index 0000000000000000000000000000000000000000..cab38ee1dbaa994bf37048b286f95985789bda5f --- /dev/null +++ b/sdk_liteos/platform/drivers/uart/hi_uart.c @@ -0,0 +1,500 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "hi_uart.h" + +#include +#include +#ifdef CONFIG_UART_DMA_SUPPORT +#include +#endif + +#include "hi_early_debug.h" +#include "uart.h" +#include "uart_drv.h" + +#define UART_FR_BUSY (1 << 3) +#define UART_FR_TXFE (1 << 7) +#define UART_FR_RXFE (1 << 4) +#define WAIT_TIME 10000 /* wait 10 seconds */ +#define CLKEN_UART2 6 +#define CLKEN_UART2_BUS 9 +#define OFFSET_14_BITS 14 +#define UART_DR 0x0 +#define UART_FR 0x18 +#define UART_IBRD 0x24 +#define UART_FBRD 0x28 +#define UART_LCR_H 0x2C +#define UART_CR 0x30 +#define UART_IFLS 0x34 +#define UART_IMSC 0x38 +#define UART_DMACR 0x48 +#define UART_DMA_DISABLE 0X04 +#define UARTCR_CFG 0x301 /* UART tx enable, rx enable, uart enable */ + +#ifndef UART_FR +#define UART_FR 0x18 +#endif + +typedef struct { + hi_u16 ibrd; + hi_u16 fbrd; + hi_u16 lcr_h; + hi_u16 cr; + hi_u16 ifls; +} uart_regs; + +uart_regs g_uart_regs_save[UART_NUM] = {0}; + +hi_u32 g_uart_timer_handle[UART_NUM] = {0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF}; +volatile hi_bool g_uart_timeout[UART_NUM] = {0}; + +static void init_uart_param(uart_attr_t *uart_attr, const hi_uart_attribute *attr) +{ + uart_attr->baud_rate = attr->baud_rate; + uart_attr->data_bits = attr->data_bits; + uart_attr->stop_bits = attr->stop_bits; + uart_attr->parity = attr->parity; + uart_attr->pad = attr->pad; +} + +static hi_u32 get_uart_param(const uart_driver_data_t *udd, hi_uart_attribute *attr, hi_uart_extra_attr *extra_attr) +{ + if (udd == HI_NULL) { + return HI_ERR_UART_INVALID_PARAMETER; + } + + if (udd->state != UART_STATE_USEABLE) { + uart_set_errno(UART_ERR_NOT_OPENED); + return HI_ERR_FAILURE; + } + + if (extra_attr != HI_NULL) { + extra_attr->tx_fifo_line = (hi_uart_fifo_line)(udd->attr.tx_fifo_line + 1); + extra_attr->rx_fifo_line = (hi_uart_fifo_line)(udd->attr.rx_fifo_line + 1); + extra_attr->flow_fifo_line = (hi_uart_fifo_line)(udd->attr.flow_fifo_line + 1); + + extra_attr->tx_block = (hi_uart_block_state)udd->act.tx_block; + extra_attr->rx_block = (hi_uart_block_state)udd->act.rx_block; + extra_attr->tx_buf_size = udd->act.tx_buffer_size; + extra_attr->rx_buf_size = udd->act.rx_buffer_size; + extra_attr->tx_use_dma = (hi_uart_dma_state)udd->act.tx_use_dma; + extra_attr->rx_use_dma = (hi_uart_dma_state)udd->act.rx_use_dma; + } + + attr->baud_rate = udd->attr.baud_rate; + attr->data_bits = udd->attr.data_bits; + attr->stop_bits = udd->attr.stop_bits; + attr->parity = udd->attr.parity; + attr->pad = udd->attr.pad; + + return HI_ERR_SUCCESS; +} + +BSP_RAM_TEXT_SECTION hi_u32 hi_uart_is_busy(hi_uart_idx id, hi_bool *busy) +{ + hi_u32 port_num = (hi_u32) id; + uart_driver_data_t *udd = HI_NULL; + hi_u32 val; + if (port_num >= UART_NUM || busy == HI_NULL) { + return HI_ERR_UART_INVALID_PARAMETER; + } + udd = g_udd_g[port_num]; + hi_reg_read32(udd->phys_base + UART_FR, val); + if (val & UART_FR_BUSY) { + *busy = HI_TRUE; + } else { + *busy = HI_FALSE; + } + return HI_ERR_SUCCESS; +} + +BSP_RAM_TEXT_SECTION hi_u32 hi_uart_is_buf_empty(hi_uart_idx id, hi_bool *empty) +{ + hi_u32 port_num = (hi_u32) id; + uart_driver_data_t *udd = HI_NULL; + hi_u32 val; + hi_u32 ret; + if (port_num >= UART_NUM || empty == HI_NULL) { + return HI_ERR_UART_INVALID_PARAMETER; + } + udd = g_udd_g[port_num]; + hi_reg_read32(udd->phys_base + UART_FR, val); + if (((val & UART_FR_RXFE) == 0) || ((val & UART_FR_TXFE) == 0)) { + *empty = HI_FALSE; + return HI_ERR_SUCCESS; + } + ret = uart_ioctl(udd, UART_CFG_GET_BUF_EMPTY, (hi_u32)(uintptr_t)&val); + if ((val == 0) && (ret == HI_ERR_SUCCESS)) { + *empty = HI_FALSE; + } else { + *empty = HI_TRUE; + } + return ret; +} + +hi_bool uart_check_extra_param(const hi_uart_extra_attr *extra_attr) +{ + if (extra_attr->tx_fifo_line <= HI_FIFO_LINE_SEVEN_EIGHTS && + extra_attr->rx_fifo_line <= HI_FIFO_LINE_SEVEN_EIGHTS && + extra_attr->flow_fifo_line <= HI_FIFO_LINE_SEVEN_EIGHTS && + extra_attr->tx_block <= HI_UART_BLOCK_STATE_BLOCK && + extra_attr->rx_block <= HI_UART_BLOCK_STATE_BLOCK && + extra_attr->tx_use_dma <= HI_UART_USE_DMA && + extra_attr->rx_use_dma <= HI_UART_USE_DMA) { + return HI_TRUE; + } + + return HI_FALSE; +} + +hi_u32 init_uart_extra_param(hi_u32 port_num, const hi_uart_extra_attr *extra_attr) +{ + uart_driver_data_t *udd = HI_NULL; + + udd = g_udd_g[port_num]; + + if (udd == HI_NULL || uart_check_extra_param(extra_attr) != HI_TRUE) { + return HI_ERR_UART_INVALID_PARAMETER; + } + + if (udd->state != UART_STATE_NOT_OPENED) { + uart_set_errno(UART_ERR_NOT_IDLE); + return HI_ERR_FAILURE; + } + + if (extra_attr->tx_fifo_line != 0) { + udd->attr.tx_fifo_line = (hi_u8)(extra_attr->tx_fifo_line) - 1; + } + if (extra_attr->rx_fifo_line != 0) { + udd->attr.rx_fifo_line = (hi_u8)(extra_attr->rx_fifo_line) - 1; + } + if (extra_attr->flow_fifo_line != 0) { + udd->attr.flow_fifo_line = (hi_u8)(extra_attr->flow_fifo_line) - 1; + } + if (extra_attr->tx_block != 0) { + udd->act.tx_block = extra_attr->tx_block; + } + if (extra_attr->rx_block != 0) { + udd->act.rx_block = extra_attr->rx_block; + } + if (extra_attr->tx_buf_size != 0) { + udd->act.tx_buffer_size = extra_attr->tx_buf_size; + } + if (extra_attr->rx_buf_size != 0) { + udd->act.rx_buffer_size = extra_attr->rx_buf_size; + } + if (extra_attr->tx_use_dma == UART_TX_USE_DMA) { +#ifdef CONFIG_UART_DMA_SUPPORT + udd->act.tx_use_dma = extra_attr->tx_use_dma; +#else + return HI_ERR_UART_NOT_SUPPORT_DMA; +#endif + } + if (extra_attr->rx_use_dma == UART_RX_USE_DMA) { +#ifdef CONFIG_UART_DMA_SUPPORT + udd->act.rx_use_dma = extra_attr->rx_use_dma; +#else + return HI_ERR_UART_NOT_SUPPORT_DMA; +#endif + } + return HI_ERR_SUCCESS; +} + +hi_u32 uart_attribute_ioctl(uart_driver_data_t *udd, const hi_uart_attribute *attr) +{ + if (udd == HI_NULL) { + return HI_ERR_UART_INVALID_PARAMETER; + } + uart_attr_t uart_attr = { 0 }; + + if (memcpy_s(&uart_attr, sizeof(uart_attr_t), &udd->attr, sizeof(uart_attr_t)) != EOK) { + return HI_ERR_FAILURE; + } + init_uart_param(&uart_attr, attr); + + return uart_ioctl(udd, UART_CFG_SET_ATTR, (uintptr_t)&uart_attr); +} + +hi_u32 hi_uart_init(hi_uart_idx id, const hi_uart_attribute *param, const hi_uart_extra_attr *extra_attr) +{ + hi_u32 port_num = (hi_u32) id; + uart_driver_data_t *udd = HI_NULL; + + if (port_num >= UART_NUM || param == HI_NULL) { + return HI_ERR_UART_INVALID_PARAMETER; + } + + if (extra_attr != HI_NULL) { + hi_u32 ret = init_uart_extra_param(port_num, extra_attr); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + } + if (id == HI_UART_IDX_2) { + hi_u16 reg_val; + hi_reg_read16(W_CTL_UART_MAC80M_CLKEN_REG, reg_val); + reg_val |= (1 << CLKEN_UART2) | (1 << CLKEN_UART2_BUS); + hi_reg_write16(W_CTL_UART_MAC80M_CLKEN_REG, reg_val); /* enable uart2 clk */ + } + udd = uart_open(port_num, UART_232); + if (udd == HI_NULL) { + return HI_ERR_FAILURE; + } + +#ifdef CONFIG_UART_DMA_SUPPORT + if (extra_attr != HI_NULL && (extra_attr->tx_use_dma == HI_TRUE || extra_attr->rx_use_dma == HI_TRUE)) { + if (hi_dma_is_init() == HI_FALSE) { + hi_u32 ret = hi_dma_init(); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + } + } +#endif + + if (g_uart_timer_handle[id] == 0xFFFFFFFF) { + hi_u32 ret = hi_timer_create(&(g_uart_timer_handle[id])); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + } + + return uart_attribute_ioctl(udd, param); +} + +hi_u32 hi_uart_set_flow_ctrl(hi_uart_idx id, hi_flow_ctrl flow_ctrl) +{ + hi_u32 port_num = (hi_u32) id; + uart_driver_data_t *udd = HI_NULL; + uart_attr_t uart_attr = { 0 }; + + if (port_num >= UART_NUM || flow_ctrl > HI_FLOW_CTRL_CTS_ONLY) { + return HI_ERR_UART_INVALID_PARAMETER; + } + + udd = g_udd_g[port_num]; + if (memcpy_s(&uart_attr, sizeof(uart_attr_t), &udd->attr, sizeof(uart_attr_t)) != EOK) { + return HI_ERR_FAILURE; + } + uart_attr.flow_ctrl = (hi_u8) flow_ctrl; + + return uart_ioctl(udd, UART_CFG_SET_ATTR, (uintptr_t)&uart_attr); +} + +hi_s32 hi_uart_read(hi_uart_idx id, hi_u8 *data, hi_u32 data_len) +{ + hi_u32 port_num = (hi_u32) id; + hi_s32 num; + + if (port_num >= UART_NUM) { + return (hi_s32)HI_ERR_FAILURE; + } + + num = uart_read(g_udd_g[port_num], (hi_char *) data, data_len); + return num; +} + +hi_void uart_read_timeout_func(hi_u32 uart_id) +{ + g_uart_timeout[uart_id] = HI_TRUE; + hi_u32 ret = hi_uart_quit_read(uart_id); + if (ret != HI_ERR_SUCCESS) { + printf("uart:%d quit fail:0x%x\r\n", uart_id, ret); + } +} + +hi_s32 hi_uart_read_timeout(hi_uart_idx id, hi_u8 *data, hi_u32 len, hi_u32 timeout_ms) +{ + hi_s32 need_read_len = len; + + g_uart_timeout[id] = HI_FALSE; + hi_u32 ret = hi_timer_start(g_uart_timer_handle[id], HI_TIMER_TYPE_ONCE, timeout_ms, + uart_read_timeout_func, id); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + while ((need_read_len > 0) && (g_uart_timeout[id] == HI_FALSE)) { + hi_s32 read_len = hi_uart_read(id, data, need_read_len); + if (read_len == -1) { + (hi_void)hi_timer_stop(g_uart_timer_handle[id]); + return HI_ERR_FAILURE; + } + data += read_len; + need_read_len -= read_len; + } + + if (g_uart_timeout[id] == HI_FALSE) { + (hi_void)hi_timer_stop(g_uart_timer_handle[id]); + } + + return (len - need_read_len); +} + +hi_s32 hi_uart_write(hi_uart_idx id, const hi_u8 *data, hi_u32 data_len) +{ + hi_u32 port_num = (hi_u32) id; + uart_driver_data_t *udd = HI_NULL; + + if (port_num >= UART_NUM) { + return (hi_s32)HI_ERR_FAILURE; + } + + udd = g_udd_g[port_num]; + if (udd->tx_use_int != HI_TRUE) { + udd->tx_use_int = HI_TRUE; + } + + return uart_write(udd, (hi_char *) data, data_len); +} + +hi_s32 hi_uart_write_immediately(hi_uart_idx id, const hi_u8 *data, hi_u32 data_len) +{ + hi_u32 port_num = (hi_u32) id; + uart_driver_data_t *udd = HI_NULL; + + if (port_num >= UART_NUM) { + return (hi_s32)HI_ERR_FAILURE; + } + + udd = g_udd_g[port_num]; + if (udd->tx_use_int != HI_FALSE) { + udd->tx_use_int = HI_FALSE; + } + + return uart_write_immediately(udd, (hi_char *) data, data_len); +} + +hi_u32 hi_uart_deinit(hi_uart_idx id) +{ + hi_u32 port_num = (hi_u32) id; + hi_u32 ret; + if (port_num >= UART_NUM) { + return HI_ERR_UART_INVALID_PARAMETER; + } + + ret = uart_close(g_udd_g[port_num]); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + if (id == HI_UART_IDX_2) { + hi_u16 reg_val; + hi_reg_read16(W_CTL_UART_MAC80M_CLKEN_REG, reg_val); + reg_val &= ~((1 << CLKEN_UART2) | (1 << CLKEN_UART2_BUS)); + hi_reg_write16(W_CTL_UART_MAC80M_CLKEN_REG, reg_val); /* disable uart2 clk */ + } + + if (g_uart_timer_handle[id] != 0xFFFFFFFF) { + ret = hi_timer_delete(g_uart_timer_handle[id]); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + g_uart_timer_handle[id] = 0xFFFFFFFF; + } + + return ret; +} + +hi_u32 hi_uart_get_attribute(hi_uart_idx id, hi_uart_attribute *attr, hi_uart_extra_attr *extra_attr) +{ + hi_u32 port_num = (hi_u32) id; + + if (port_num >= UART_NUM || attr == HI_NULL) { + return HI_ERR_UART_INVALID_PARAMETER; + } + + return get_uart_param(g_udd_g[port_num], attr, extra_attr); +} + +hi_u32 hi_uart_quit_read(hi_uart_idx id) +{ + hi_u32 port_num = (hi_u32) id; + if (port_num >= UART_NUM) { + return HI_ERR_UART_INVALID_PARAMETER; + } + + uart_driver_data_t *udd = (uart_driver_data_t *) g_udd_g[id]; + if (udd->act.rx_block != UART_FLG_RD_BLOCK) { + return HI_ERR_UART_NOT_BLOCK_MODE; + } + + if (hi_event_send(udd->event_id, UART_RD_QUIT_EVENT) != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + + return HI_ERR_SUCCESS; +} + +hi_u32 hi_uart_lp_save(hi_uart_idx id) +{ + hi_u32 port_num = (hi_u32) id; + if (port_num >= UART_NUM) { + return HI_ERR_UART_INVALID_PARAMETER; + } + uart_driver_data_t *udd = HI_NULL; + udd = (uart_driver_data_t *) g_udd_g[port_num]; + g_uart_regs_save[port_num].ibrd = hi_reg_read_val16(udd->phys_base + UART_IBRD); + g_uart_regs_save[port_num].fbrd = hi_reg_read_val16(udd->phys_base + UART_FBRD); + g_uart_regs_save[port_num].lcr_h = hi_reg_read_val16(udd->phys_base + UART_LCR_H); + g_uart_regs_save[port_num].cr = hi_reg_read_val16(udd->phys_base + UART_CR); + g_uart_regs_save[port_num].ifls = hi_reg_read_val16(udd->phys_base + UART_IFLS); + return HI_ERR_SUCCESS; +} + +hi_u32 hi_uart_lp_restore(hi_uart_idx id) +{ + hi_u32 port_num = (hi_u32) id; + if (port_num >= UART_NUM) { + return HI_ERR_UART_INVALID_PARAMETER; + } + hi_u32 phys_base = ((uart_driver_data_t *) g_udd_g[port_num])->phys_base; + hi_u16 temp; + if (id == HI_UART_IDX_2) { + hi_reg_read16(W_CTL_UART_MAC80M_CLKEN_REG, temp); + temp |= (1 << CLKEN_UART2) | (1 << CLKEN_UART2_BUS); + hi_reg_write16(W_CTL_UART_MAC80M_CLKEN_REG, temp); /* enable uart2 clk */ + } + /* wait until tx fifo is null, in order to let data send before reset work normal. */ + while ((hi_reg_read_val16(phys_base + UART_FR) & 0x08) == 0x08) { } + /* disable uart tx rx and uart */ + hi_reg_write16((phys_base + UART_CR), 0); + /* flush fifo */ + hi_reg_write16((phys_base + UART_LCR_H), 0); + /* set baudrate */ + hi_reg_write16((phys_base + UART_IBRD), g_uart_regs_save[port_num].ibrd); + hi_reg_write16((phys_base + UART_FBRD), g_uart_regs_save[port_num].fbrd); + /* set databit stopbit parity */ + hi_reg_write16((phys_base + UART_LCR_H), g_uart_regs_save[port_num].lcr_h); + /* set fifo line */ + hi_reg_write16(phys_base + UART_IFLS, g_uart_regs_save[port_num].ifls); /* default val: 0x10A */ + /* disable the transmit DMA */ + hi_reg_write16((phys_base + UART_DMACR), UART_DMA_DISABLE); + /* set flow ctrl */ + if (phys_base != HI_UART0_REG_BASE) { + temp = hi_reg_read_val16(phys_base + UART_CR); + temp &= ~(0x3 << OFFSET_14_BITS); + temp |= g_uart_regs_save[port_num].cr & (0x3 << OFFSET_14_BITS); + hi_reg_write16(phys_base + UART_CR, temp); /* 14 15 bit */ + } + /* enable uart tx rx and uart */ + temp = hi_reg_read_val16(phys_base + UART_CR); + temp |= UARTCR_CFG; + hi_reg_write16((phys_base + UART_CR), temp); + temp = hi_reg_read_val16(phys_base + UART_IMSC); + hi_reg_write16(phys_base + UART_IMSC, UART_RX_INT_ENABLE | temp); + return HI_ERR_SUCCESS; +} diff --git a/sdk_liteos/platform/drivers/uart/serial_dw.h b/sdk_liteos/platform/drivers/uart/serial_dw.h new file mode 100644 index 0000000000000000000000000000000000000000..2cf7c930bb5d861964f462d2d4561be8739d4a6d --- /dev/null +++ b/sdk_liteos/platform/drivers/uart/serial_dw.h @@ -0,0 +1,187 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __SERIAL_DW_H__ +#define __SERIAL_DW_H__ + +#include + +/** + * @ingroup hct_io + */ +typedef enum { + UART_0 = 0, /**< uart0 */ + UART_1 = 1, /**< uart1 */ + UART_2 = 2, /**< uart2 */ +} hi_uart; + +/** + * @ingroup hct_io + * 串口参数结构体 + */ +typedef struct { + hi_u32 baudrate; /* ex:115200 */ + hi_u8 databit; /* 5; 6; 7; 8 */ + hi_u8 stopbit; /* 1:stop_bit 1; 2: stop_bit 2. */ + hi_u8 parity; /* 0: None; 1:Odd; 2:Even */ + hi_u8 flow_ctrl; /* 0: None; 1:rts&&cts. 2:only rts; 3:only cts */ + hi_u8 fifoline_tx_int; /* 0: tx FIFO≤1/8full; 1:tx FIFO≤1/4full; 2:tx FIFO≤1/2full; + 3:tx FIFO≤3/4full; 4:tx FIFO≤7/8full */ + hi_u8 fifoline_rx_int; /* 0: rx FIFO≥1/8full; 1:rx FIFO≥1/4full; 2:rx FIFO≥1/2full; + 3:rx FIFO≥3/4full; 4:rx FIFO≥7/8full */ + hi_u8 fifoline_rts; /* 0:rx FIFO≥1/8full; 1:rx FIFO≥1/4full; 2:rx FIFO≥1/2full; + 3:rx FIFO≥3/4full; 4:rx FIFO≥7/8full */ + hi_u8 pad; +} uart_param_stru; + +typedef struct { + hi_u32 baudrate; + hi_u16 ibrd; + hi_u16 fbrd; +} hi_uart_brd; + +hi_u32 serial_init(hi_uart uart_num, uart_param_stru default_uart_param); +hi_u32 change_uart(hi_uart uart_num); +hi_void serial_putc(const hi_char c); +hi_void serial_puts(const hi_char *s); +hi_void serial_put_buf(const hi_char *buffer, hi_s32 length); +hi_void serial_puthex(hi_u32 h, hi_u8 print_all); +hi_void serial_put_msg0(const hi_char *s); +hi_void serial_put_msg1(const hi_char *s, hi_u32 h); +hi_void serial_put_msg2(const hi_char *s, hi_u32 h1, hi_u32 h2); +hi_void serial_put_msg4(const hi_char *s, hi_u32 h1, hi_u32 h2, hi_u32 h3, hi_u32 h4); +hi_void dw_putc(hi_char c); +hi_s32 serial_getc(hi_void); +hi_s32 serial_tstc(hi_void); +hi_u8 dw_getc(hi_void); +hi_s32 dw_tstc(hi_void); +hi_u32 set_uart_param(hi_u32 base_addr, uart_param_stru uart_param); + +/* UART register OFFSET */ +#define UART_DR 0x0 +#define UART_RSR_ECR 0x04 +#define UART_FR 0x18 +#define UART_ILPR 0x20 +#define UART_IBRD 0x24 +#define UART_FBRD 0x28 +#define UART_LCR_H 0x2C +#define UART_CR 0x30 +#define UART_IFLS 0x34 +#define UART_IMSC 0x38 +#define UART_RIS 0x3C +#define UART_MIS 0x40 +#define UART_ICR 0x44 +#define UART_DMACR 0x48 + +#define UARTFR_TXFE_MASK 0x80 +#define UARTFR_RXFF_MASK 0x40 +#define UARTFR_TXFF_MASK 0x20 +#define UARTFR_RXFE_MASK 0x10 +#define UARTFR_BUSY_MASK 0x04 +#define UARTDR_DATA_MASK 0xFF + +#define UARTIFS_CFG 0x10A /* FIFO water mark:Rx 16 Tx 32 RTS 56 */ +#define UART_DMA_ENABLE 0X03 +#define UART_DMA_DISABLE 0X04 +#define UARTICR_CFG 0x7FF /* Clear up all uart interrupt */ + +#define UARTIMSC_CFG 0x0 /* Disable all uart interrupt */ +#define UARTIMSC_CFG_INT 0x50 /* enable rx time out interrupt */ + +/* UART register OFFSET */ +#define UART_LCH_H 0x2C + +#define UART_INTMASK_OVERRUN (1 << 10) +#define UART_INTMASK_BREAKERR (1 << 9) +#define UART_INTMASK_PARERR (1 << 8) +#define UART_INTMASK_FRAMINGERR (1 << 7) +#define UART_INTMASK_RECTIMEOUT (1 << 6) +#define UART_INTMASK_TX (1 << 5) +#define UART_INTMASK_RX (1 << 4) + +#define UARTLCR_H_CFG 0x60 /* 8bit, no parity, FIFO disable */ +#define UARTLCR_H_CFG_ODD 0x72 /* 8bit, odd parity,FIFO enable */ +#define UARTLCR_H_CFG_FIFO 0x70 /* 8bit, no parity, FIFO enable */ +#define UARTCR_CFG 0x301 /* UART tx enable, rx enable, uart enable */ +#define UARTCR_CFG_FLOWENABLE 0xC301 /* UART tx enable, rx enable, uart enable, flow control enable */ + +#define UART_FIFO_TX_SIZE 64 + +typedef enum { + HI_UART_BRD_IDX_1200 = 0, + HI_UART_BRD_IDX_2400 = 1, + HI_UART_BRD_IDX_9600 = 2, + HI_UART_BRD_IDX_19200 = 3, + HI_UART_BRD_IDX_115200 = 4, + HI_UART_BRD_IDX_230400 = 5, + HI_UART_BRD_IDX_460800 = 6, + HI_UART_BRD_IDX_921600 = 7, + HI_UART_BRD_IDX_1000000 = 8, + HI_UART_BRD_IDX_1024000 = 9, + HI_UART_BRD_IDX_1500000 = 10, + HI_UART_BRD_IDX_1536000 = 11, + HI_UART_BRD_IDX_2000000 = 12, + HI_UART_BRD_IDX_2048000 = 13, + HI_UART_BRD_IDX_2252800 = 14, + HI_UART_BRD_IDX_2304000 = 15, + HI_UART_BRD_IDX_2500000 = 16, + HI_UART_BRD_IDX_2560000 = 17, + HI_UART_BRD_IDX_3000000 = 18, + HI_UART_BRD_IDX_3072000 = 19, + HI_UART_BRD_IDX_3500000 = 20, + HI_UART_BRD_IDX_3584000 = 21, + HI_UART_BRD_IDX_3840000 = 22, + HI_UART_BRD_IDX_4000000 = 23, + HI_UART_BRD_IDX_4096000 = 24, + HI_UART_BRD_IDX_4500000 = 25, + HI_UART_BRD_IDX_4608000 = 26, + HI_UART_BRD_IDX_5000000 = 27, + HI_UART_BRD_IDX_6000000 = 28, + HI_UART_BRD_IDX_MAX, +} hi_uart_brd_idx_e; + +typedef enum { + HI_UART_BRD_1200 = 1200, + HI_UART_BRD_2400 = 2400, + HI_UART_BRD_9600 = 9600, + HI_UART_BRD_19200 = 19200, + HI_UART_BRD_115200 = 115200, + HI_UART_BRD_230400 = 230400, + HI_UART_BRD_460800 = 460800, + HI_UART_BRD_921600 = 921600, + HI_UART_BRD_1000000 = 1000000, + HI_UART_BRD_1024000 = 1024000, + HI_UART_BRD_1500000 = 1500000, + HI_UART_BRD_1536000 = 1536000, + HI_UART_BRD_2000000 = 2000000, + HI_UART_BRD_2048000 = 2048000, + HI_UART_BRD_2252800 = 2252800, + HI_UART_BRD_2304000 = 2304000, + HI_UART_BRD_2500000 = 2500000, + HI_UART_BRD_2560000 = 2560000, + HI_UART_BRD_3000000 = 3000000, + HI_UART_BRD_3072000 = 3072000, + HI_UART_BRD_3500000 = 3500000, + HI_UART_BRD_3584000 = 3584000, + HI_UART_BRD_3840000 = 3840000, + HI_UART_BRD_4000000 = 4000000, + HI_UART_BRD_4096000 = 4096000, + HI_UART_BRD_4500000 = 4500000, + HI_UART_BRD_4608000 = 4608000, + HI_UART_BRD_5000000 = 5000000, + HI_UART_BRD_6000000 = 6000000, +} hi_uart_baudrate_e; + +#endif diff --git a/sdk_liteos/platform/drivers/uart/uart.c b/sdk_liteos/platform/drivers/uart/uart.c new file mode 100644 index 0000000000000000000000000000000000000000..7a4e970c66d42568935ee514ba95b04090572b66 --- /dev/null +++ b/sdk_liteos/platform/drivers/uart/uart.c @@ -0,0 +1,329 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "uart.h" + +static uart_driver_data_t g_uart_0 = { + .num = UART0, + .phys_base = HI_UART0_REG_BASE, + .irq_num = UART_0_IRQ, + .rx_transfer = HI_NULL, + .tx_transfer = HI_NULL, + .rx_recv = uart_write_circ_buf, + .tx_send = uart_read_circ_buf, + .count = 0, + .state = UART_STATE_NOT_OPENED, + .receive_tx_int = HI_FALSE, + .ops = &g_uart_driver_uops, + .tx_use_int = HI_FALSE, + .attr = UART_ATTR_DEFAULT, + .act = UART_ACT_DEFAULT, +}; + +static uart_driver_data_t g_uart_1 = { + .num = UART1, + .phys_base = HI_UART1_REG_BASE, + .irq_num = UART_1_IRQ, + .rx_transfer = HI_NULL, + .tx_transfer = HI_NULL, + .rx_recv = uart_write_circ_buf, + .tx_send = uart_read_circ_buf, + .count = 0, + .state = UART_STATE_NOT_OPENED, + .receive_tx_int = HI_FALSE, + .ops = &g_uart_driver_uops, + .tx_use_int = HI_FALSE, + .attr = UART_ATTR_DEFAULT, + .act = UART_ACT_DEFAULT, +}; + +static uart_driver_data_t g_uart_2 = { + .num = UART2, + .phys_base = HI_UART2_REG_BASE, + .irq_num = UART_2_IRQ, + .rx_transfer = HI_NULL, + .tx_transfer = HI_NULL, + .rx_recv = uart_write_circ_buf, + .tx_send = uart_read_circ_buf, + .count = 0, + .state = UART_STATE_NOT_OPENED, + .receive_tx_int = HI_FALSE, + .ops = &g_uart_driver_uops, + .tx_use_int = HI_FALSE, + .attr = UART_ATTR_DEFAULT, + .act = UART_ACT_DEFAULT, +}; + +uart_driver_data_t *g_udd_g[UART_NUM] = { &g_uart_0, &g_uart_1, &g_uart_2 }; + +uart_driver_data_t *uart_open(hi_u32 uart_index, uart_mode mode) +{ + hi_u32 ret; + uart_driver_data_t *udd = HI_NULL; + + if (uart_index >= UART_NUM || mode != UART_232) { + return HI_NULL; + } + + udd = (uart_driver_data_t *) g_udd_g[uart_index]; + + if (udd->state == UART_STATE_NOT_OPENED) { + ret = uart_init_circ_buf(udd, udd->act.tx_buffer_size, udd->act.rx_buffer_size); + if (ret != HI_ERR_SUCCESS) { + uart_set_errno(UART_ERR_INIT_CIRC_FAILED); + return HI_NULL; + } + ret = hi_event_create(&udd->event_id); + if (ret != HI_ERR_SUCCESS) { + uart_deinit_circ_buf(udd); + return HI_NULL; + } + udd->type = mode; + + if (!udd->ops->startup || udd->ops->startup(udd)) { + uart_deinit_circ_buf(udd); + hi_event_delete(udd->event_id); + uart_set_errno(UART_ERR_START_FAILED); + return HI_NULL; + } + udd->state = UART_STATE_USEABLE; + } else { + if (mode != udd->type) { + if (udd->ops->startup != HI_NULL) { + udd->type = mode; + udd->ops->startup(udd); + } + } + } + + return udd; +} + + +hi_s32 uart_read(uart_driver_data_t *udd, hi_char *buf, hi_u32 count) +{ + hi_s32 len; + hi_u32 event_val = 0; + + if (udd == HI_NULL) { + return (hi_s32)HI_ERR_FAILURE; + } + if ((buf == HI_NULL) || (count == 0)) { + uart_set_errno(UART_ERR_PARA_INVALID); + return (hi_s32)HI_ERR_FAILURE; + } + if (udd->state != UART_STATE_USEABLE) { + uart_set_errno(UART_ERR_NOT_OPENED); + return (hi_s32)HI_ERR_FAILURE; + } + + do { + len = uart_read_circ_buf(udd->rx_transfer, buf, count); +#ifdef UART_DEBUG_INFO + udd->uart_stat_info.read_circ_cnt += (unsigned int) len; +#endif + if ((len == 0) && (udd->act.rx_block == UART_FLG_RD_BLOCK)) { + hi_event_wait(udd->event_id, UART_RD_EVENT | UART_RD_QUIT_EVENT, &event_val, + HI_SYS_WAIT_FOREVER, HI_EVENT_WAITMODE_OR | HI_EVENT_WAITMODE_CLR); + if (event_val == UART_RD_QUIT_EVENT) { + break; + } + } else { + break; + } + } while (len == 0); + + return len; +} + +hi_s32 uart_write(uart_driver_data_t *udd, const hi_char *buf, hi_u32 send_count) +{ + hi_s32 len = 0; + hi_s32 count = (hi_s32)send_count; + hi_u32 left; + hi_u32 event_val = 0; + /* if uart is not in useable, report error */ + if (udd == HI_NULL) { + return (hi_s32)HI_ERR_FAILURE; + } + + if ((buf == HI_NULL) || (count == 0)) { + uart_set_errno(UART_ERR_PARA_INVALID); + return (hi_s32)HI_ERR_FAILURE; + } + left = (hi_u32)count; + if (udd->state != UART_STATE_USEABLE) { + uart_set_errno(UART_ERR_NOT_OPENED); + return (hi_s32)HI_ERR_FAILURE; + } + + if (udd->receive_tx_int == HI_TRUE) { + do { + len += uart_write_circ_buf(udd->tx_transfer, (hi_char *)&buf[len], left); + if (len >= count) { + break; + } + left = (hi_u32)count - (hi_u32)len; + if (udd->act.tx_block != UART_FLG_WD_BLOCK) { + break; + } + uart_tx_interrupt_enable(udd); + (void) hi_event_wait(udd->event_id, UART_WD_EVENT, &event_val, + HI_SYS_WAIT_FOREVER, HI_EVENT_WAITMODE_OR | HI_EVENT_WAITMODE_CLR); + } while (left > 0); + uart_tx_interrupt_enable(udd); + } else { + uart_tx_interrupt_enable(udd); + if (udd->ops != HI_NULL && + udd->ops->start_tx) { + len = udd->ops->start_tx(udd, buf, (hi_u32)count); + } + } + +#ifdef UART_DEBUG_INFO + udd->uart_stat_info.write_circ_cnt += (unsigned int) len; +#endif + + return len; +} + +hi_s32 uart_write_immediately(uart_driver_data_t *udd, const hi_char *buf, hi_u32 send_count) +{ + hi_s32 len = 0; + hi_s32 count = (hi_s32)send_count; + + /* if uart is not in useable, report error */ + if (udd == HI_NULL) { + return (hi_s32)HI_ERR_FAILURE; + } + + if ((buf == HI_NULL) || (count == 0)) { + uart_set_errno(UART_ERR_PARA_INVALID); + return (hi_s32)HI_ERR_FAILURE; + } + + if (udd->state != UART_STATE_USEABLE) { + uart_set_errno(UART_ERR_NOT_OPENED); + return (hi_s32)HI_ERR_FAILURE; + } + + if (udd->ops->start_tx) { + len = udd->ops->start_tx(udd, buf, (hi_u32)count); + } + +#ifdef UART_DEBUG_INFO + udd->uart_stat_info.write_circ_cnt += (unsigned int) len; +#endif + + return len; +} + +hi_bool uart_check_ioctrl_param(const uart_attr_t *attr) +{ + if (attr == HI_NULL) { + return HI_FALSE; + } + + if (attr->baud_rate > 0 + && attr->data_bits <= 8 && attr->data_bits >= 5 /* bits>=5 bits<=8 */ + && (attr->parity == 0 || attr->parity == 1 || attr->parity == 2) /* stop_bits:1 2 */ + && (attr->stop_bits == 1 || attr->stop_bits == 2) /* stop_bits:1 2 */ + && attr->tx_fifo_line <= 4 && attr->rx_fifo_line <= 4 && attr->flow_fifo_line <= 4) { /* 4 */ + return HI_TRUE; + } + + return HI_FALSE; +} + +hi_u32 uart_ioctl(uart_driver_data_t *udd, hi_u32 cmd, uintptr_t arg) +{ + hi_u32 ret = HI_ERR_SUCCESS; + uart_attr_t *attr = HI_NULL; + + if (udd == HI_NULL) { + return HI_ERR_UART_INVALID_PARAMETER; + } + + if (udd->state != UART_STATE_USEABLE) { + uart_set_errno(UART_ERR_NOT_OPENED); + return HI_ERR_FAILURE; + } + + switch (cmd) { + case UART_CFG_SET_ATTR: + attr = (uart_attr_t *) arg; + if (uart_check_ioctrl_param(attr) == HI_TRUE) { + if (memcpy_s(&udd->attr, sizeof(uart_attr_t), attr, sizeof(uart_attr_t)) != EOK) { + return HI_ERR_FAILURE; + } + if (udd->ops->ioctl && udd->ops->ioctl(udd)) { + uart_set_errno(UART_ERR_IOCTL_FAILED); + ret = HI_ERR_FAILURE; + } + } else { + uart_set_errno(UART_ERR_PARA_INVALID); + ret = HI_ERR_FAILURE; + } + break; + case UART_CFG_GET_ATTR: + attr = (uart_attr_t *) arg; + if (memcpy_s(attr, sizeof(uart_attr_t), &udd->attr, sizeof(uart_attr_t)) != EOK) { + return HI_ERR_FAILURE; + } + break; + case UART_CFG_GET_BUF_EMPTY: { + hi_u32 *is_empty = (hi_u32 *) arg; + *is_empty = uart_buf_empty(udd); + break; + } + default: + uart_set_errno(UART_ERR_PARA_INVALID); + ret = HI_ERR_FAILURE; + break; + } + + return ret; +} + +hi_u32 uart_close(uart_driver_data_t *udd) +{ + if (udd == HI_NULL) { + return HI_ERR_UART_INVALID_PARAMETER; + } + if (udd->state != UART_STATE_USEABLE) { + return HI_ERR_SUCCESS; + } + if (udd->ops != HI_NULL && udd->ops->shutdown) { + udd->ops->shutdown(udd); + } + + uart_deinit_circ_buf(udd); + udd->state = UART_STATE_NOT_OPENED; + + if (udd->receive_tx_int != HI_FALSE) { + udd->receive_tx_int = HI_FALSE; + } + if (udd->count != 0) { + udd->count = 0; + } + + udd->attr = (uart_attr_t) UART_ATTR_DEFAULT; + udd->act = (uart_act_t) UART_ACT_DEFAULT; + + if (hi_event_delete(udd->event_id) != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + return HI_ERR_SUCCESS; +} diff --git a/sdk_liteos/platform/drivers/uart/uart.h b/sdk_liteos/platform/drivers/uart/uart.h new file mode 100644 index 0000000000000000000000000000000000000000..c2eaace8b77ce724a472e05bb2d6206cced8c949 --- /dev/null +++ b/sdk_liteos/platform/drivers/uart/uart.h @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __UART_H__ +#define __UART_H__ + +#include + +#include "uart_drv.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define UART_NUM 3 +#define UART0 0 +#define UART1 1 +#define UART2 2 + +#define UART0_BASE (HI_UART0_REG_BASE) +#define UART1_BASE (HI_UART1_REG_BASE) +#define UART2_BASE (HI_UART2_REG_BASE) + +#define UART_CIRC_BUF_ENABLE +#define UART_DEFAULT_TX_FIFO_LINE 2 /* tx FIFO<=1/2full */ +#define UART_DEFAULT_RX_FIFO_LINE 1 /* rx FIFO>=1/4full */ +#define UART_DEFAULT_FLOW_FIFO_LINE 3 /* rx FIFO>=3/4full */ +#define UART_DEFAULT_TX_BUFFER_SIZE 0x0200 +#define UART_DEFAULT_RX_BUFFER_SIZE 0x0200 +#define UART_DEFAULT_TX_USE_DMA 1 /* not use dma */ +#define UART_DEFAULT_RX_USE_DMA 1 /* not use dma */ +#define UART_DEFAULT_TX_BLOCK 2 /* block */ +#define UART_DEFAULT_RX_BLOCK 2 /* block */ + +#define UART_DEFAULT_FLOW_CONTROL 0 /* 0: disable flow ctrl; 1: enable rts and cts; 2: enable rts only; + 3: enable cts only. notice: uart0 not support flow ctrl. */ + +#define UART_ATTR_DEFAULT {115200, 8, 1, 0, UART_DEFAULT_TX_FIFO_LINE, UART_DEFAULT_RX_FIFO_LINE, \ + UART_DEFAULT_FLOW_FIFO_LINE, UART_DEFAULT_FLOW_CONTROL, HI_FALSE} +#define UART_ACT_DEFAULT {UART_DEFAULT_TX_BUFFER_SIZE, UART_DEFAULT_RX_BUFFER_SIZE, UART_DEFAULT_TX_USE_DMA, \ + UART_DEFAULT_RX_USE_DMA, UART_DEFAULT_TX_BLOCK, UART_DEFAULT_RX_BLOCK} + + +uart_driver_data_t *uart_open(hi_u32 uart_index, uart_mode uart_mode); +hi_s32 uart_read(uart_driver_data_t *udd, hi_char *buf, hi_u32 count); +hi_s32 uart_write(uart_driver_data_t *udd, const hi_char *buf, hi_u32 count); +hi_s32 uart_write_immediately(uart_driver_data_t *udd, const hi_char *buf, hi_u32 count); +hi_u32 uart_ioctl(uart_driver_data_t *udd, hi_u32 cmd, uintptr_t arg); +hi_u32 uart_close(uart_driver_data_t *udd); + +extern uart_driver_data_t *g_udd_g[UART_NUM]; +extern uart_ops g_uart_driver_uops; + +#ifdef __cplusplus +} +#endif +#endif + diff --git a/sdk_liteos/platform/drivers/uart/uart_drv.c b/sdk_liteos/platform/drivers/uart/uart_drv.c new file mode 100644 index 0000000000000000000000000000000000000000..dc3baf196a3cc8398a977dc30a93fe32e41687e2 --- /dev/null +++ b/sdk_liteos/platform/drivers/uart/uart_drv.c @@ -0,0 +1,769 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "uart.h" +#include "uart_drv.h" +#include "hi_isr.h" +#include "serial_dw.h" +#include "dma.h" + +#define hi_uart_buf_lock(x) hi_int_lock() +#define hi_uart_buf_unlock(x, val) hi_int_restore(val) +hi_bool g_uart_buf_memcpy_failed = HI_FALSE; + +hi_u32 uart_circ_buf_empty(const uart_circ_buf *transfer) +{ + if (transfer->flags & BUF_CIRCLED) { + return 0; + } + + if (transfer->wp == transfer->rp) { + return 1; + } else { + return 0; + } +} + +hi_u32 uart_init_circ_buf(uart_driver_data_t *udd, unsigned int rx_buf_size, unsigned int tx_buf_size) +{ + if ((!rx_buf_size) || (!tx_buf_size)) { + return HI_ERR_UART_INVALID_PARAMETER; + } + + udd->rx_transfer = (uart_circ_buf *) hi_malloc(HI_MOD_ID_UART, sizeof(uart_circ_buf)); + if (udd->rx_transfer == NULL) { + goto end; + } + + memset_s((hi_void *) udd->rx_transfer, sizeof(uart_circ_buf), 0, sizeof(uart_circ_buf)); + udd->rx_transfer->data = (char *) hi_malloc(HI_MOD_ID_UART, rx_buf_size); + if (udd->rx_transfer->data == NULL) { + goto free_rx_transfer; + } + + udd->rx_transfer->size = rx_buf_size; + udd->tx_transfer = (uart_circ_buf *) hi_malloc(HI_MOD_ID_UART, sizeof(uart_circ_buf)); + if (udd->tx_transfer == NULL) { + goto free_rx_circ_buf; + } + + memset_s((hi_void *) udd->tx_transfer, sizeof(uart_circ_buf), 0, sizeof(uart_circ_buf)); + udd->tx_transfer->data = (char *) hi_malloc(HI_MOD_ID_UART, tx_buf_size); + if (udd->tx_transfer->data == NULL) { + goto free_tx_circ_buf; + } + + udd->tx_transfer->size = tx_buf_size; + return HI_ERR_SUCCESS; + + free_tx_circ_buf: + hi_free(HI_MOD_ID_UART, udd->tx_transfer); + udd->tx_transfer = HI_NULL; + + free_rx_circ_buf: + hi_free(HI_MOD_ID_UART, udd->rx_transfer->data); + udd->rx_transfer->data = HI_NULL; + free_rx_transfer: + hi_free(HI_MOD_ID_UART, udd->rx_transfer->data); + udd->rx_transfer = HI_NULL; + end: + return HI_ERR_FAILURE; +} + +hi_void uart_deinit_circ_buf(uart_driver_data_t *udd) +{ + if (udd->rx_transfer != HI_NULL) { + if (udd->rx_transfer->data != HI_NULL) { + hi_free(HI_MOD_ID_UART, udd->rx_transfer->data); + udd->rx_transfer->data = HI_NULL; + } + + hi_free(HI_MOD_ID_UART, udd->rx_transfer); + udd->rx_transfer = HI_NULL; + } + + if (udd->tx_transfer != HI_NULL) { + if (udd->tx_transfer->data != HI_NULL) { + hi_free(HI_MOD_ID_UART, udd->tx_transfer->data); + udd->tx_transfer->data = HI_NULL; + } + hi_free(HI_MOD_ID_UART, udd->tx_transfer); + udd->tx_transfer = HI_NULL; + } +} + +hi_s32 uart_read_circ_buf(uart_circ_buf *transfer, hi_char *buf, hi_u32 count) +{ + uintptr_t data; + + if (transfer == NULL) { + return (hi_s32) HI_ERR_FAILURE; + } + + hi_u32 last_int_val = hi_uart_buf_lock(transfer); + hi_u32 wp = transfer->wp; + hi_u32 rp = transfer->rp; + hi_u32 flags = transfer->flags; + hi_uart_buf_unlock(transfer, last_int_val); + data = (uintptr_t) transfer->data; + hi_u32 buf_size = transfer->size; + if (!(flags & BUF_CIRCLED)) { + if (count >= (wp - rp)) { + count = wp - rp; + } + + if (memcpy_s(buf, count, (hi_void *) (uintptr_t)(data + rp), count) != EOK) { + g_uart_buf_memcpy_failed = HI_TRUE; + } + transfer->rp += count; + return (hi_s32) count; + } + if (count < (buf_size - rp)) { + if (memcpy_s(buf, count, (hi_void *) (uintptr_t)(data + rp), count) != EOK) { + g_uart_buf_memcpy_failed = HI_TRUE; + } + transfer->rp += count; + return (hi_s32) count; + } + hi_u32 copy_size = buf_size - rp; + hi_u32 left_size = count - copy_size; + if (memcpy_s(buf, copy_size, (hi_void *) (uintptr_t)(data + rp), copy_size) != EOK) { + g_uart_buf_memcpy_failed = HI_TRUE; + } + rp = 0; + if (left_size > wp) { + left_size = wp; + } + + if (memcpy_s((hi_void*)(buf + copy_size), left_size, (hi_void *)(uintptr_t)(data + rp), left_size) != EOK) { + g_uart_buf_memcpy_failed = HI_TRUE; + } + last_int_val = hi_uart_buf_lock(transfer); + transfer->rp = left_size; + transfer->flags &= ~BUF_CIRCLED; + hi_uart_buf_unlock(transfer, last_int_val); + return (hi_s32) (copy_size + left_size); +} + +hi_s32 uart_write_circ_buf(uart_circ_buf *transfer, const hi_char *buf, hi_u32 count) +{ + uintptr_t data; + + if (transfer == NULL) { + return (hi_s32) HI_ERR_FAILURE; + } + + hi_u32 last_int_val = hi_uart_buf_lock(transfer); + hi_u32 wp = transfer->wp; + hi_u32 rp = transfer->rp; + hi_u32 flags = transfer->flags; + hi_uart_buf_unlock(transfer, last_int_val); + + data = (uintptr_t) transfer->data; + hi_u32 buf_size = transfer->size; + + if (!(flags & BUF_CIRCLED)) { + if (count < (buf_size - wp)) { + if (memcpy_s((hi_void *)(uintptr_t) (data + wp), count, buf, count) != EOK) { + g_uart_buf_memcpy_failed = HI_TRUE; + } + transfer->wp += count; + return (hi_s32) count; + } + hi_u32 copy_size = buf_size - wp; + hi_u32 left_size = count - copy_size; + if (memcpy_s((hi_void *)(uintptr_t) (data + wp), copy_size, buf, copy_size) != EOK) { + g_uart_buf_memcpy_failed = HI_TRUE; + } + wp = 0; + if (left_size > rp) { + /* overflowed. some new data will be discarded */ + left_size = rp; + } + + if (memcpy_s((hi_void*)(uintptr_t)(data + wp), left_size, (hi_void *)(buf + copy_size), left_size) != EOK) { + g_uart_buf_memcpy_failed = HI_TRUE; + } + last_int_val = hi_uart_buf_lock(transfer); + transfer->wp = left_size; + transfer->flags |= BUF_CIRCLED; + hi_uart_buf_unlock(transfer, last_int_val); + return (hi_s32) (copy_size + left_size); + } + if (count > (rp - wp)) { + /* overflowed. some new data will be discarded */ + count = rp - wp; + } + + if (memcpy_s((hi_void *)(uintptr_t) (data + wp), count, buf, count) != EOK) { + g_uart_buf_memcpy_failed = HI_TRUE; + } + transfer->wp += count; + return (hi_s32) count; +} + +hi_void uart_tx_interrupt_disable(uart_driver_data_t *udd) +{ + udd->receive_tx_int = HI_FALSE; /* when disable tx interrupt, set receive_tx_int false */ + hi_u32 tx_status = hi_reg_read_val32(udd->phys_base + UART_IMSC); + hi_reg_write32(udd->phys_base + UART_IMSC, (~UART_TX_INT_BIT) & tx_status); +} + +hi_void uart_tx_interrupt_enable(const uart_driver_data_t *udd) +{ + hi_u32 tx_status = hi_reg_read_val32(udd->phys_base + UART_IMSC); + hi_reg_write32(udd->phys_base + UART_IMSC, (unsigned short) (UART_TX_INT_BIT | tx_status)); +} + +hi_void uart_tx_interrupt_clear(const uart_driver_data_t *udd) +{ + hi_u32 int_clear_status = hi_reg_read_val32(udd->phys_base + UART_ICR); + hi_reg_write32(udd->phys_base + UART_ICR, (unsigned short) (UART_TX_INT_BIT | int_clear_status)); +} + +hi_void uart_rx_interrupt_disable(const uart_driver_data_t *udd) +{ + hi_u32 tx_status = hi_reg_read_val32(udd->phys_base + UART_IMSC); + hi_reg_write32(udd->phys_base + UART_IMSC, ~(UART_RX_INT_ENABLE) & tx_status); +} + +hi_void uart_rx_interrupt_enable(const uart_driver_data_t *udd) +{ + hi_u32 tx_status = hi_reg_read_val32(udd->phys_base + UART_IMSC); + hi_reg_write32(udd->phys_base + UART_IMSC, UART_RX_INT_ENABLE | tx_status); +} + +hi_void get_recv_irq_err(unsigned int int_status, uart_drv_stat_info *pst_uart_stat_info) +{ + if (int_status & UART_INTMASK_OVERRUN) { + (pst_uart_stat_info->recv_irq_err_overrun)++; + } + + if (int_status & UART_INTMASK_PARERR) { + (pst_uart_stat_info->recv_irq_err_parity)++; + } + + if (int_status & UART_INTMASK_FRAMINGERR) { + (pst_uart_stat_info->recv_irq_err_frame)++; + } + + if (int_status & UART_INTMASK_BREAKERR) { + (pst_uart_stat_info->recv_irq_err_break)++; + } +} + +HI_ALWAYS_STAIC_INLINE hi_u32 uart_get_tx_fifo_available_cnt(const uart_driver_data_t *udd) +{ + hi_u32 tx_fifo_line = udd->attr.tx_fifo_line; + hi_u32 tx_fifo_used_cnt; + switch (tx_fifo_line) { + case 0: /* 0 */ + tx_fifo_used_cnt = 8; /* algorithm: UART_FIFO_TX_SIZE / 8; */ + break; + case 1: /* 1 */ + tx_fifo_used_cnt = 16; /* algorithm: UART_FIFO_TX_SIZE / 4; 16 */ + break; + case 2: /* 2 */ + tx_fifo_used_cnt = 32; /* algorithm: UART_FIFO_TX_SIZE / 2; 32 */ + break; + case 3: /* 3 */ + tx_fifo_used_cnt = 48; /* algorithm: UART_FIFO_TX_SIZE / 4 * 3; 48 */ + break; + case 4: /* 4 */ + tx_fifo_used_cnt = 56; /* algorithm: UART_FIFO_TX_SIZE / 8 * 7; 56 */ + break; + default: + tx_fifo_used_cnt = 32; /* algorithm: UART_FIFO_TX_SIZE / 2; 32 */ + break; + } + return (UART_FIFO_TX_SIZE - tx_fifo_used_cnt); +} + +HI_ALWAYS_STAIC_INLINE hi_u32 uart_get_rx_fifo_cnt(const uart_driver_data_t *udd) +{ + hi_u32 rx_fifo_line = udd->attr.rx_fifo_line; + hi_u32 rx_fifo_cnt; + switch (rx_fifo_line) { + case 0: /* 0 */ + rx_fifo_cnt = 8; /* algorithm: UART_FIFO_TX_SIZE / 8 -> 8 */ + break; + case 1: /* 1 */ + rx_fifo_cnt = 16; /* algorithm: UART_FIFO_TX_SIZE / 4 -> 16 */ + break; + case 2: /* 2 */ + rx_fifo_cnt = 32; /* algorithm: UART_FIFO_TX_SIZE / 2 -> 32 */ + break; + case 3: /* 3 */ + rx_fifo_cnt = 48; /* algorithm: UART_FIFO_TX_SIZE / 4 * 3 -> 48 */ + break; + case 4: /* 4 */ + rx_fifo_cnt = 56; /* algorithm: UART_FIFO_TX_SIZE / 8 * 7 -> 56 */ + break; + default: + rx_fifo_cnt = 32; /* algorithm: UART_FIFO_TX_SIZE / 2 -> 32 */ + break; + } + return rx_fifo_cnt; +} + +HI_ALWAYS_STAIC_INLINE hi_u32 uart_get_tx_fifo_dma_cnt(hi_u32 tx_fifo_available_cnt) +{ + if (tx_fifo_available_cnt <= 32) { /* algorithm: UART_FIFO_TX_SIZE / 2 = 32 */ + return tx_fifo_available_cnt; + } else { + return 32; /* algorithm: UART_FIFO_TX_SIZE / 2 = 32 */ + } +} + +HI_ALWAYS_STAIC_INLINE hi_u32 uart_get_rx_fifo_dma_cnt(hi_u32 rx_fifo_cnt) +{ + if (rx_fifo_cnt <= 32) { /* algorithm: UART_FIFO_TX_SIZE / 2 = 32 */ + return rx_fifo_cnt; + } else { + return 32; /* algorithm: UART_FIFO_TX_SIZE / 2 = 32 */ + } +} + +HI_ALWAYS_STAIC_INLINE hi_dma_burst_size uart_get_burst_size_e(hi_u32 burst_size) +{ + if (burst_size == 8) { /* burst_size为8 */ + return DMA_BURST_MSIZE_8; + } else if (burst_size == 16) { /* burst_size为16 */ + return DMA_BURST_MSIZE_16; + } else if (burst_size == 32) { /* burst_size为32 */ + return DMA_BURST_MSIZE_32; + } else { + return DMA_BURST_MSIZE_1; + } +} + +#ifdef CONFIG_UART_DMA_SUPPORT +static hi_void uart_dma_para_cfg(const uart_driver_data_t *udd, hi_dma_para *dma_para, const hi_char *buf) +{ + hi_u32 rx_fifo_dma_cnt = uart_get_rx_fifo_dma_cnt(uart_get_rx_fifo_cnt(udd)); + hi_dma_burst_size burst_size_e = uart_get_burst_size_e(rx_fifo_dma_cnt); + + dma_para->tr_type = DMA_PHL_TO_MEM; + if (udd->phys_base == UART0_BASE) { + dma_para->src_phl = UART0_RX; + } else if (udd->phys_base == UART1_BASE) { + dma_para->src_phl = UART1_RX; + } else { + dma_para->src_phl = UART2_RX; + } + dma_para->dst_phl = 0; + dma_para->src_addr = udd->phys_base; + dma_para->dst_addr = (uintptr_t) buf; + dma_para->src_burst_size = burst_size_e; + dma_para->dst_burst_size = burst_size_e; + dma_para->src_width = WIDTH_BIT8; + dma_para->dst_width = WIDTH_BIT8; + dma_para->transfer_size = rx_fifo_dma_cnt; + dma_para->cb = HI_NULL; + + uart_error("rx dma start, rx_fifo_dma_cnt:%d\r\n", rx_fifo_dma_cnt); +} + +static hi_u32 uart_dma_recv_irq(uart_driver_data_t *udd, hi_u32 status, hi_char *buf) +{ + hi_u32 ret; + hi_dma_para dma_para; + hi_u32 rx_fifo_dma_cnt; + + uart_error("enter rx dma"); +#ifdef CONFIG_UART_DEBUG_INFO + uart_drv_stat_info *pst_uart_stat_info = &(udd->uart_stat_info); + get_recv_irq_err(status, pst_uart_stat_info); +#else + unused_param(status); +#endif + + /* if uart hardware rx fifo is empty, go out of circle */ + hi_u32 usr = hi_reg_read_val32(udd->phys_base + UART_FR); + if ((usr & UARTFR_RXFE_MASK) == UARTFR_RXFE_MASK) { +#ifdef CONFIG_UART_DEBUG_INFO + (udd->uart_stat_info.recv_irq_err_emptyfifo_cnt)++; +#endif + return HI_ERR_FAILURE; + } + + rx_fifo_dma_cnt = uart_get_rx_fifo_dma_cnt(uart_get_rx_fifo_cnt(udd)); + uart_dma_para_cfg(udd, &dma_para, buf); + + ret = hi_dma_transfer(&dma_para, HI_TRUE); + uart_error("rx dma end, rx_fifo_dma_cnt:%d\r\n", rx_fifo_dma_cnt); + if (ret == HI_ERR_SUCCESS) { + udd->rx_recv(udd->rx_transfer, buf, rx_fifo_dma_cnt); +#ifdef CONFIG_UART_DEBUG_INFO + for (hi_u32 i = 0; i < rx_fifo_dma_cnt; i++) { + udd->uart_stat_info.recv_last_context.data[udd->uart_stat_info.recv_last_context.num] = buf[i]; + udd->uart_stat_info.recv_last_context.num++; + udd->uart_stat_info.recv_last_context.num &= (HI_UART_LAST_RECORD_BYTE_COUNT - 1); + } +#endif + } else { +#ifdef CONFIG_UART_DEBUG_INFO + udd->uart_stat_info.recv_dma_err_cnt++; +#endif + } + if (udd->act.rx_block == UART_FLG_RD_BLOCK) { + hi_event_send(udd->event_id, UART_RD_EVENT); + } +#ifdef CONFIG_UART_DEBUG_INFO + udd->uart_stat_info.recv_irq_cnt++; + udd->uart_stat_info.recv_irq_data_cnt += rx_fifo_dma_cnt; +#endif + return HI_ERR_SUCCESS; +} +#endif + +static hi_void uart_nodma_recv_irq(uart_driver_data_t *udd, hi_u32 status, hi_char *buf) +{ + hi_u32 count = 0; + uart_error("enter rx not dma"); + +#ifdef CONFIG_UART_DEBUG_INFO + uart_drv_stat_info *pst_uart_stat_info = &(udd->uart_stat_info); + get_recv_irq_err(status, pst_uart_stat_info); +#else + unused_param(status); +#endif + do { + hi_u32 usr = hi_reg_read_val32(udd->phys_base + UART_FR); + /* if uart hardware rx fifo is empty, go out of circle */ + if ((usr & UARTFR_RXFE_MASK) == UARTFR_RXFE_MASK) { +#ifdef CONFIG_UART_DEBUG_INFO + if (!count) { + (udd->uart_stat_info.recv_irq_err_emptyfifo_cnt)++; + } +#endif + break; + } + + if (buf == HI_NULL) { + break; + } + buf[count] = (char) hi_reg_read_val32(udd->phys_base + UART_DR); +#ifdef CONFIG_UART_DEBUG_INFO + udd->uart_stat_info.recv_last_context.data[udd->uart_stat_info.recv_last_context.num] = + (unsigned char) buf[count]; + udd->uart_stat_info.recv_last_context.num++; + udd->uart_stat_info.recv_last_context.num &= (HI_UART_LAST_RECORD_BYTE_COUNT - 1); +#endif + count++; + } while (count < 64); /* 64 */ + + if (count >= 1 && udd->rx_recv != HI_NULL) { + udd->rx_recv(udd->rx_transfer, buf, count); + if (udd->act.rx_block == UART_FLG_RD_BLOCK) { + hi_event_send(udd->event_id, UART_RD_EVENT); + } + } +#ifdef CONFIG_UART_DEBUG_INFO + udd->uart_stat_info.recv_irq_cnt++; + udd->uart_stat_info.recv_irq_data_cnt += count; +#endif +} + +static hi_void uart_send_irq(uart_driver_data_t *udd, hi_char *buf) +{ +#ifdef CONFIG_UART_DEBUG_INFO + udd->uart_stat_info.send_irq_cnt++; +#endif + + if (udd->receive_tx_int == HI_FALSE) { + udd->receive_tx_int = HI_TRUE; + return; + } + + if (uart_circ_buf_empty(udd->tx_transfer)) { + uart_tx_interrupt_disable(udd); + } else { + hi_u32 count = (unsigned int) udd->tx_send(udd->tx_transfer, buf, uart_get_tx_fifo_available_cnt(udd)); + if (udd->ops->start_tx) { + (void) udd->ops->start_tx(udd, buf, count); + } + if (udd->act.tx_block == UART_FLG_WD_BLOCK) { + (void) hi_event_send(udd->event_id, UART_WD_EVENT); + } + } +} + +static hi_void uart_drv_irq(void *data) +{ + hi_u32 status; + hi_char buf[64] = { 0 }; /* size 64 */ + uart_driver_data_t *udd = (uart_driver_data_t *) data; + char *buff = buf; + if (udd == NULL) { + return; + } + status = hi_reg_read_val32(udd->phys_base + UART_MIS); +#ifdef CONFIG_UART_DMA_SUPPORT + /* recv irq */ + if ((UART_INTMASK_RX & status) && (udd->act.rx_use_dma == UART_RX_USE_DMA)) { + if (uart_dma_recv_irq(udd, status, buff) != HI_ERR_SUCCESS) { + /* send irq */ + if (UART_INTMASK_TX & status) { + uart_send_irq(udd, buff); + } + return; + } + } else if ((UART_INTMASK_RX & status) || (UART_INTMASK_RECTIMEOUT & status)) { + uart_nodma_recv_irq(udd, status, buff); + } +#else + if ((UART_INTMASK_RX & status) || (UART_INTMASK_RECTIMEOUT & status)) { + uart_nodma_recv_irq(udd, status, buff); + } +#endif + + /* send irq */ + if (UART_INTMASK_TX & status) { + uart_send_irq(udd, buff); + } +} + +hi_u32 uart_buf_empty(const uart_driver_data_t *udd) +{ + if ((uart_circ_buf_empty(udd->tx_transfer)) && + (uart_circ_buf_empty(udd->rx_transfer))) { + return 1; + } + return 0; +} + +static hi_u32 uart_drv_set_attr(uart_driver_data_t *udd) +{ + hi_u32 ret; + hi_u32 int_save; + uart_param_stru uart_param; + if (memset_s(&uart_param, sizeof(uart_param_stru), 0, sizeof(uart_param_stru)) != EOK) { + return HI_ERR_MEMSET_S; + } + uart_param.baudrate = udd->attr.baud_rate; + uart_param.databit = udd->attr.data_bits; + uart_param.stopbit = udd->attr.stop_bits; + uart_param.parity = udd->attr.parity; + uart_param.flow_ctrl = udd->attr.flow_ctrl; + uart_param.fifoline_tx_int = udd->attr.tx_fifo_line; + uart_param.fifoline_rx_int = udd->attr.rx_fifo_line; + uart_param.fifoline_rts = udd->attr.flow_fifo_line; + + int_save = hi_int_lock(); + ret = set_uart_param(udd->phys_base, uart_param); + (hi_void) hi_int_restore(int_save); + + udd->receive_tx_int = HI_FALSE; /* when reset uart module, set receive_tx_int false */ + + return ret; +} + +static hi_u32 uart_drv_startup(uart_driver_data_t *udd) +{ + hi_u32 ret; + + /* disable interrupt */ + hi_reg_write32(udd->phys_base + UART_IMSC, 0); + + /* set baudrate,data_bit,stop_bit,parity */ + if (uart_drv_set_attr(udd) != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + + /* creat interrupt function for uart */ + ret = hi_irq_request(udd->irq_num, HI_IRQ_FLAG_PRI3, (irq_routine) uart_drv_irq, (uintptr_t) udd); + if (ret == HI_ERR_SUCCESS || ret == HI_ERR_ISR_ALREADY_CREATED) { + ret = HI_ERR_SUCCESS; + uart_rx_interrupt_enable(udd); + } + + return ret; +} + +static hi_void uart_drv_shutdown(struct uart_driver_data *udd) +{ + uart_tx_interrupt_disable(udd); + uart_rx_interrupt_disable(udd); + hi_irq_disable((hi_u32) udd->irq_num); + if (hi_irq_free(udd->irq_num) != HI_ERR_SUCCESS) { + uart_error("uart irq free fail"); + } +} + +#ifdef CONFIG_UART_DMA_SUPPORT +hi_u32 uart_drv_dma_start_tx_cfg(struct uart_driver_data *udd, const hi_char *buf, hi_u32 count) +{ + hi_u32 send_cnt = 0; + hi_u32 tx_fifo_available_cnt = uart_get_tx_fifo_available_cnt(udd); + hi_u32 dma_busrt_size = uart_get_tx_fifo_dma_cnt(tx_fifo_available_cnt); + hi_dma_burst_size burst_size_e = uart_get_burst_size_e(dma_busrt_size); + hi_u32 ret; + hi_dma_para dma_para; + + dma_para.tr_type = DMA_MEM_TO_PHL; + dma_para.src_phl = 0; + if (udd->phys_base == UART0_BASE) { + dma_para.dst_phl = UART0_TX; + } else if (udd->phys_base == UART1_BASE) { + dma_para.dst_phl = UART1_TX; + } else { + dma_para.dst_phl = UART2_TX; + } + + dma_para.src_addr = (uintptr_t) buf; + dma_para.dst_addr = udd->phys_base; + dma_para.src_burst_size = burst_size_e; + dma_para.dst_burst_size = burst_size_e; + dma_para.src_width = WIDTH_BIT8; + dma_para.dst_width = WIDTH_BIT8; + dma_para.transfer_size = dma_busrt_size; + dma_para.cb = HI_NULL; + send_cnt += dma_busrt_size; + uart_error("tx dma start, dma_busrt_size:%d\r\n", dma_busrt_size); + ret = hi_dma_transfer(&dma_para, HI_TRUE); + uart_error("tx dma end, dma_busrt_size:%d\r\n", dma_busrt_size); + if (ret != HI_ERR_SUCCESS) { +#ifdef CONFIG_UART_DEBUG_INFO + udd->uart_stat_info.send_dma_err_cnt++; +#endif + return (hi_u32)ret; + } + + for (; send_cnt < count; send_cnt++) { + /* Wait until there is space in the FIFO */ + while ((hi_reg_read_val32(udd->phys_base + UART_FR) & UARTFR_TXFF_MASK) != 0) { } + hi_reg_write32(udd->phys_base + UART_DR, (unsigned) (hi_u8) buf[send_cnt]); + } + return HI_ERR_SUCCESS; +} + +hi_u32 uart_drv_dma_start_tx(struct uart_driver_data *udd, const hi_char *buf, hi_u32 count) +{ + hi_u32 tx_fifo_available_cnt = uart_get_tx_fifo_available_cnt(udd); + hi_u32 dma_busrt_size = uart_get_tx_fifo_dma_cnt(tx_fifo_available_cnt); + if (count >= dma_busrt_size) { + hi_u32 ret = uart_drv_dma_start_tx_cfg(udd, buf, count); + if (ret != HI_ERR_SUCCESS) { +#ifdef CONFIG_UART_DEBUG_INFO + udd->uart_stat_info.send_dma_err_cnt++; +#endif + return (hi_s32)ret; + } + } else { + for (hi_u32 i = 0; i < count; i++) { + /* Wait until there is space in the FIFO */ + while ((hi_reg_read_val32(udd->phys_base + UART_FR) & UARTFR_TXFF_MASK) != 0) { } + hi_reg_write32(udd->phys_base + UART_DR, (unsigned) (hi_u8) buf[i]); + } + } + +#ifdef CONFIG_UART_DEBUG_INFO + hi_u32 idx; + for (idx = 0; idx < count; idx++) { + udd->uart_stat_info.send_last_context.data[udd->uart_stat_info.send_last_context.num] = buf[idx]; + udd->uart_stat_info.send_last_context.num++; + udd->uart_stat_info.send_last_context.num &= (HI_UART_LAST_RECORD_BYTE_COUNT - 1); + } +#endif + +#ifdef CONFIG_UART_DEBUG_INFO + udd->uart_stat_info.send_irq_data_cnt += count; +#endif + return count; +} +#endif + +static hi_u32 uart_drv_irq_start_tx(struct uart_driver_data *udd, const hi_char *buf, hi_u32 count) +{ + hi_u32 tx_fifo_available_cnt = 0; + hi_u32 send_cnt = count > tx_fifo_available_cnt ? tx_fifo_available_cnt : count; + hi_u32 idx = 0; + + while (idx < send_cnt) { + hi_reg_write32(udd->phys_base + UART_DR, (unsigned) (hi_u8) buf[idx]); +#ifdef CONFIG_UART_DEBUG_INFO + udd->uart_stat_info.send_last_context.data[udd->uart_stat_info.send_last_context.num] = buf[idx]; + udd->uart_stat_info.send_last_context.num++; + udd->uart_stat_info.send_last_context.num &= (HI_UART_LAST_RECORD_BYTE_COUNT - 1); +#endif + idx++; + } + + for (; send_cnt < count; send_cnt++) { + /* Wait until there is space in the FIFO */ + while ((hi_reg_read_val32(udd->phys_base + UART_FR) & UARTFR_TXFF_MASK) != 0) { } + hi_reg_write32(udd->phys_base + UART_DR, (unsigned) (hi_u8) buf[send_cnt]); +#ifdef CONFIG_UART_DEBUG_INFO + udd->uart_stat_info.send_last_context.data[udd->uart_stat_info.send_last_context.num] = buf[send_cnt]; + udd->uart_stat_info.send_last_context.num++; + udd->uart_stat_info.send_last_context.num &= (HI_UART_LAST_RECORD_BYTE_COUNT - 1); +#endif + } + +#ifdef CONFIG_UART_DEBUG_INFO + udd->uart_stat_info.send_irq_data_cnt += count; +#endif + return count; +} + +static hi_s32 uart_drv_start_tx(struct uart_driver_data *udd, const hi_char *buf, hi_u32 count) +{ + hi_u32 idx = 0; + hi_u32 ret; + +#ifdef CONFIG_UART_DMA_SUPPORT + if (udd->tx_use_int == HI_TRUE && udd->receive_tx_int == HI_TRUE && udd->act.tx_use_dma == UART_TX_USE_DMA) { + ret = uart_drv_dma_start_tx(udd, buf, count); + return (hi_s32)ret; + } else if (udd->tx_use_int == HI_TRUE && udd->receive_tx_int == HI_TRUE) { +#else + if (udd->tx_use_int == HI_TRUE && udd->receive_tx_int == HI_TRUE) { +#endif + ret = uart_drv_irq_start_tx(udd, buf, count); + return (hi_s32)ret; + } else { + while (idx < count) { + /* Wait until there is space in the FIFO */ + while ((hi_reg_read_val32(udd->phys_base + UART_FR) & UARTFR_TXFF_MASK) != 0) { } + hi_reg_write32(udd->phys_base + UART_DR, (unsigned) (hi_u8) buf[idx]); +#ifdef CONFIG_UART_DEBUG_INFO + udd->uart_stat_info.send_last_context.data[udd->uart_stat_info.send_last_context.num] = buf[idx]; + udd->uart_stat_info.send_last_context.num++; + udd->uart_stat_info.send_last_context.num &= (HI_UART_LAST_RECORD_BYTE_COUNT - 1); +#endif + idx++; + } +#ifdef CONFIG_UART_DEBUG_INFO + udd->uart_stat_info.send_irq_data_cnt += count; +#endif + return (hi_s32) count; + } +} + +static hi_u32 uart_drv_ioctl(uart_driver_data_t *udd) +{ + hi_u32 ret; + ret = uart_drv_set_attr(udd); + uart_rx_interrupt_enable(udd); + return ret; +} + +uart_ops g_uart_driver_uops = { + .startup = uart_drv_startup, + .shutdown = uart_drv_shutdown, + .start_tx = uart_drv_start_tx, + .ioctl = uart_drv_ioctl, +}; diff --git a/sdk_liteos/platform/drivers/uart/uart_drv.h b/sdk_liteos/platform/drivers/uart/uart_drv.h new file mode 100644 index 0000000000000000000000000000000000000000..2c90c818e4a5e9eabb6651602c5cce15f3f94554 --- /dev/null +++ b/sdk_liteos/platform/drivers/uart/uart_drv.h @@ -0,0 +1,204 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __UART_DRV_H__ +#define __UART_DRV_H__ + +#include +#include +#include +#include +#ifdef __cplusplus +extern "C" { +#endif + +#define UART_RD_EVENT 0x1 +#define UART_WD_EVENT 0x2 +#define UART_RD_QUIT_EVENT (1 << 2) +#define BUF_CIRCLED (1 << 0) +#define BUF_OVERFLOWED (1 << 1) +#define BUF_EMPTIED (1 << 2) +#define UART_FLG_RD_NONBLOCK 1 +#define UART_FLG_RD_BLOCK 2 +#define UART_FLG_WD_NONBLOCK 1 +#define UART_FLG_WD_BLOCK 2 +#define UART_TX_INT_BIT (1 << 5) +#define UART_RX_INT_ENABLE 0x50 + +#define GPIO_SEL_UART 0 +#define GPIO_SEL_GPIO 1 + +#define UART_ERR_PARA_INVALID 1 +#define UART_ERR_INIT_CIRC_FAILED 2 +#define UART_ERR_START_FAILED 3 +#define UART_ERR_IOCTL_FAILED 4 +#define UART_ERR_PTR_NULL 5 +#define UART_ERR_OPEN_AGAIN 6 +#define UART_ERR_NOT_OPENED 7 +#define UART_ERR_NOT_IDLE 8 + +/* Read Block: */ +#define UART_RD_BLOCK 1 +#define UART_RD_NONBLOCK 0 + +/* Write Block: */ +#define UART_WD_BLOCK 1 +#define UART_WD_NONBLOCK 0 +#define UART_TX_USE_DMA 2 +#define UART_RX_USE_DMA 2 +#define UART_CFG_SET_ATTR 0x101 +#define UART_CFG_RD_BLOCK 0x102 +#define UART_CFG_WD_BLOCK 0x103 +#define UART_CFG_GET_ATTR 0x104 +#define UART_CFG_SET_ACT 0x105 +#define UART_CFG_GET_ACT 0x106 +#define UART_CFG_GET_BUF_EMPTY 0x107 +#define HI_UART_LAST_RECORD_BYTE_COUNT 32 +typedef struct { + hi_u32 baud_rate; + hi_u8 data_bits; + hi_u8 stop_bits; + hi_u8 parity; + hi_u8 tx_fifo_line; /**< 0: tx FIFO≤1/8full; 1:tx FIFO≤1/4full; 2:tx FIFO≤1/2full; 3:tx FIFO≤3/4full; + 4:tx FIFO≤7/8full : default: 2 */ + hi_u8 rx_fifo_line; /**< 0: rx FIFO≥1/8full; 1:rx FIFO≥1/4full; 2:rx FIFO≥1/2full; 3:rx FIFO≥3/4full; + 4:rx FIFO≥7/8full : default: 1 */ + hi_u8 flow_fifo_line; /**< 0: rx FIFO≥1/8full; 1:rx FIFO≥1/4full; 2:rx FIFO≥1/2full; 3:rx FIFO≥3/4full; + 4:rx FIFO≥7/8full : default: 3 */ + hi_u8 flow_ctrl; /**< 0: disable flow ctrl; 1: enable rts and cts; 2: enable rts only; 3: enable cts only. + notice: uart0 not support flow ctrl. */ + hi_u8 pad; /**< reserved:currently not used. */ +} uart_attr_t; + +typedef struct { + hi_u16 tx_buffer_size; + hi_u16 rx_buffer_size; + hi_u8 tx_use_dma; + hi_u8 rx_use_dma; + hi_u8 tx_block; + hi_u8 rx_block; +} uart_act_t; + +typedef struct uart_circ_buf { + hi_u32 rp; + hi_u32 wp; + hi_u32 flags; + hi_char *data; + hi_u32 size; +} uart_circ_buf; + +typedef enum uart_status { + UART_STATE_NOT_OPENED = 0, + UART_STATE_USEABLE +} uart_status; + +typedef enum uart_mode { + UART_232 = 0 +} uart_mode; + +typedef struct uart_driver_data uart_driver_data_t; + +typedef struct uart_ops { + hi_u32(*startup) (uart_driver_data_t *udd); + hi_void(*shutdown) (uart_driver_data_t *udd); + hi_s32(*start_tx) (uart_driver_data_t *udd, const hi_char *buf, hi_u32 count); + hi_u32(*ioctl) (uart_driver_data_t *udd); +} uart_ops; + +typedef hi_s32(*recv_notify) (uart_circ_buf *transfer, const hi_char *buf, hi_u32 count); +typedef hi_s32(*send_buf) (uart_circ_buf *transfer, hi_char *buf, hi_u32 count); + +#ifdef CONFIG_UART_DEBUG_INFO +#define uart_set_errno(err) ((udd->uart_stat_info.uart_errno) = (err)) +#else +#define unused_param(p) ((p) = (p)) +#define uart_set_errno(err) +#endif + +typedef struct { + hi_char data[HI_UART_LAST_RECORD_BYTE_COUNT]; + hi_u32 num; +} uart_recv_send_last_data; + +typedef struct uart_drv_stat_info { + hi_u32 uart_errno; + hi_u32 recv_irq_cnt; + hi_u32 recv_irq_data_cnt; + hi_u32 read_circ_cnt; + hi_u32 send_irq_cnt; + hi_u32 send_irq_data_cnt; + hi_u32 write_circ_cnt; + hi_u32 recv_irq_err_overrun; + hi_u32 recv_irq_err_parity; + hi_u32 recv_irq_err_frame; + hi_u32 recv_irq_err_break; + hi_u32 recv_irq_err_busy; + hi_u32 recv_irq_err_emptyfifo_cnt; + hi_u32 send_dma_err_cnt; + hi_u32 recv_dma_err_cnt; + uart_recv_send_last_data recv_last_context; + uart_recv_send_last_data send_last_context; +} uart_drv_stat_info; + +struct uart_driver_data { +#ifdef CONFIG_UART_DEBUG_INFO + uart_drv_stat_info uart_stat_info; +#endif + hi_char num; + hi_bool receive_tx_int; + hi_u16 pad; + uart_mode type; + hi_u32 phys_base; + hi_u32 irq_num; + uart_circ_buf *rx_transfer; + uart_circ_buf *tx_transfer; + hi_u32 event_id; + hi_u32 count; + hi_u32 state; + recv_notify rx_recv; + send_buf tx_send; + uart_ops *ops; + hi_bool tx_use_int; + uart_attr_t attr; + uart_act_t act; +}; + +#ifdef UART_DEBUG_PRINT +#define uart_error(msg...) do { \ + dprintf("\n"); \ + dprintf(":%s,%d: ", __func__, __LINE__); \ + dprintf(msg); \ + dprintf("\n"); \ + }while (0) +#else +#define uart_error(msg...) +#endif + +hi_void uart_tx_interrupt_enable(const uart_driver_data_t *udd); +hi_u32 uart_circ_buf_empty(const uart_circ_buf *transfer); +hi_u32 uart_init_circ_buf(uart_driver_data_t *udd, hi_u32 rx_fifo_size, hi_u32 tx_fifo_size); +hi_void uart_deinit_circ_buf(uart_driver_data_t *udd); +hi_s32 uart_read_circ_buf(uart_circ_buf *transfer, hi_char *buf, hi_u32 count); +hi_s32 uart_write_circ_buf(uart_circ_buf *transfer, const hi_char *buf, hi_u32 count); +hi_void uart_set_tx_mode(uart_driver_data_t *udd); +hi_u32 uart_buf_empty(const uart_driver_data_t *udd); +hi_void uart_tx_interrupt_disable(uart_driver_data_t *udd); +hi_void uart_tx_interrupt_clear(const uart_driver_data_t *udd); +hi_void uart_tf_interrupt_disable(uart_driver_data_t *udd); +hi_void uart_rx_interrupt_disable(const uart_driver_data_t *udd); +#ifdef __cplusplus +} +#endif +#endif /* __UART_DRV_H__ */ diff --git a/sdk_liteos/platform/include/hi_hwtimer.h b/sdk_liteos/platform/include/hi_hwtimer.h new file mode 100644 index 0000000000000000000000000000000000000000..5ce2b1926e0135a775fb3a421f5584559e250484 --- /dev/null +++ b/sdk_liteos/platform/include/hi_hwtimer.h @@ -0,0 +1,145 @@ +/* + * @file hi_hwtimer.h + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __HI_HWTIMER_H__ +#define __HI_HWTIMER_H__ + +#include + + +typedef enum { + HI_RTC_CLK_32K = 32, + HI_RTC_CLK_24M = 24, + HI_RTC_CLK_40M = 40, +} hi_rtc_clk; /**< In low-power deep sleep mode, the 24 MHz or 40 MHz clock is unavailable. */ + +typedef void (*hi_hwtimer_callback)(hi_u32 data); + +typedef void (*hi_hwrtc_callback)(hi_u32 data); + +typedef void (*hwtimer_clken_callback)(hi_void); + +/** + * @ingroup hw_timer + * + * Timer mode control. CNcomment:定时器模式控制。CNend + */ +typedef enum { + TIMER_MODE_FREE = 0, + TIMER_MODE_CYCLE = 1, +} timer_mode; + +/** + * @ingroup hw_timer + * + * Timer interrupt mask control. CNcomment:定时器中断模式控制。CNend + */ +typedef enum { + TIMER_INT_UNMASK = 0, /**< Not masked */ + TIMER_INT_MASK = 1, /**< Masked */ +} timer_int_mask; + +/** + * @ingroup hw_timer + * + * hwtimer ID. CNcomment:硬件定时器ID。CNend + */ +typedef enum { + HI_TIMER_ID_0, + HI_TIMER_ID_1, + HI_TIMER_ID_2, + HI_TIMER_ID_MAX, /* Invalid value. */ +} hi_timer_id; + +/** + * @ingroup hw_timer + * + * hwrtc ID. CNcomment:硬件RTC ID。CNend + */ +typedef enum { + HI_RTC_ID_0 = HI_TIMER_ID_MAX, + HI_RTC_ID_1, + HI_RTC_ID_2, + HI_RTC_ID_3, + HI_RTC_ID_MAX, /* Invalid value. */ +} hi_rtc_id; + +/** + * @ingroup hw_timer + * + * hwtimer working mode. CNcomment:硬件定时器工作模式。CNend + */ +typedef enum { + HI_HWTIMER_MODE_ONCE, + HI_HWTIMER_MODE_PERIOD, + HI_HWTIMER_MODE_INVALID, +} hi_hwtimer_mode; + +/** + * @ingroup hw_timer + * + * hwrtc working mode. CNcomment:硬件RTC工作模式。CNend + */ +typedef enum { + HI_HWRTC_MODE_ONCE, + HI_HWRTC_MODE_PERIOD, + HI_HWRTC_MODE_INVALID, +} hi_hwrtc_mode; + +/** + * @ingroup hw_timer + * + * hwtimer handle structure. CNcomment:硬件定时器句柄结构。CNend + */ +typedef struct { + hi_hwtimer_mode mode; + hi_u32 expire; + hi_u32 data; + hi_hwtimer_callback func; + hi_timer_id timer_id; +} hi_hwtimer_ctl; + +/** + * @ingroup hw_timer + * + * hwrtc handle structure. CNcomment:硬件RTC句柄结构。CNend + */ +typedef struct { + hi_hwrtc_mode mode; + hi_u32 expire; + hi_u32 data; + hi_hwrtc_callback func; + hi_rtc_id rtc_id; +} hi_hwrtc_ctl; + +hi_void hi_hwrtc_set_clk(hi_rtc_clk clk); + +hi_u32 hi_hwtimer_init_new(hi_timer_id timer_id); +hi_u32 hi_hwtimer_start(const hi_hwtimer_ctl *timer); +hi_u32 hi_hwtimer_stop(hi_timer_id timer_id); +hi_u32 hi_hwtimer_destroy_new(hi_timer_id timer_id); +hi_u32 hi_hwtimer_get_cur_val(hi_timer_id timer_id, hi_u32 *val); +hi_u32 hi_hwtimer_get_load(hi_timer_id timer_id, hi_u32 *load); + +hi_u32 hi_hwrtc_start(const hi_hwrtc_ctl *rtc); +hi_u32 hi_hwrtc_init(hi_rtc_id timer_id); +hi_u32 hi_hwrtc_stop(hi_rtc_id rtc_id); +hi_u32 hi_hwrtc_destroy(hi_rtc_id rtc_id); +hi_u32 hi_hwrtc_get_cur_val(hi_rtc_id rtc_id, hi_u32 *val); +hi_u32 hi_hwrtc_get_load(hi_rtc_id rtc_id, hi_u32 *load); +hi_u32 hwtimer_start(hi_u32 tick_cnt, const hi_hwtimer_ctl *timer); + +#endif diff --git a/sdk_liteos/platform/include/hi_patch.h b/sdk_liteos/platform/include/hi_patch.h new file mode 100644 index 0000000000000000000000000000000000000000..cec6717f1e438a24375bbd3b4e499dd9c2d83825 --- /dev/null +++ b/sdk_liteos/platform/include/hi_patch.h @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __HI_PATCH_H__ +#define __HI_PATCH_H__ + +#include "hi_types_base.h" + +hi_void hi_patch_init(hi_void); +hi_void hi_patch_lp_save(hi_void); +hi_void hi_patch_lp_resume(hi_void); + +#endif diff --git a/sdk_liteos/platform/include/hi_sal.h b/sdk_liteos/platform/include/hi_sal.h new file mode 100644 index 0000000000000000000000000000000000000000..8e97356bd153c74060a53b5901b3f0038f168df7 --- /dev/null +++ b/sdk_liteos/platform/include/hi_sal.h @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** +* @file hi_sal.h +* +* Copyright (c) Hisilicon Technologies Co., Ltd. 2019. All rights reserved. \n +* +* Description: sal interfaces. \n +*/ + +#ifndef __HI_SAL_H__ +#define __HI_SAL_H__ +#include +#include +#include +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define WDG_TIMEOUT 6500 +#define MS_PER_SEC 1000 +#define MS_PER_MIN (60 * 1000) + +#define HI_WDT_FLAG_REG GLB_CTL_GP_REG1_REG + +#define HI_MONITOR_INTERVAL_MS 1000 +#define HI_MONITOR_INTERVAL_SEC (HI_MONITOR_INTERVAL_MS / 1000) + +HI_EXTERN hi_u32 g_auto_wdg_rst_sys_timeout; +#define check_wd_timerout_enable() (g_auto_wdg_rst_sys_timeout > 0) +HI_EXTERN hi_u32 g_cpu_clock; +HI_EXTERN hi_u32 g_flash_prot_sem; + +hi_void watchdog_feed(hi_void); +hi_u32 hi_sal_timer_init(hi_void); +hi_u32 hi_sal_timer_suspend(hi_void); +hi_u32 hi_sal_timer_resume(hi_void); +hi_void hi_sal_init(hi_void); +hi_void hi_sal_wdg_clear(hi_void); + +hi_bool hi_diag_is_init(hi_void); +hi_bool hi_get_shell_init(hi_void); + +/** +* @ingroup hct_reset_save +* @brief save crash messsage into flash. CNcomment:存储crash信息到flash。CNend +* +* @par 描述: +* save crash messsage into flash. CNcomment:存储crash信息到flash。CNend +* +* @attention 无。 +* @param data [IN] type #hi_pvoid ,Exception information pointer.CNcomment:异常信息指针。CNend +* @param str [IN] type #hi_char * ,Exception description. CNcomment:异常描述。CNend +* +* @retval None. +* @par 依赖: +* @li hi_crash.h:文件用于描述异常存储接口。 +* @see hi_syserr_store_crash_info。 +*/ +hi_void hi_syserr_store_crash_info(hi_pvoid data); + +#ifdef __cplusplus +} +#endif + +#endif /* __HI_SAL_H__ */ diff --git a/sdk_liteos/platform/include/hi_sal_cfg.h b/sdk_liteos/platform/include/hi_sal_cfg.h new file mode 100644 index 0000000000000000000000000000000000000000..132f6defaca24645b0bf1be4211028e74eba1d71 --- /dev/null +++ b/sdk_liteos/platform/include/hi_sal_cfg.h @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __HI_SAL_CFG_H__ +#define __HI_SAL_CFG_H__ + +#include + +HI_EXTERN hi_void hi_tee_irq_handler(hi_void); + +#endif /* __HI_SAL_CFG_H__ */ diff --git a/sdk_liteos/platform/include/sal_common.h b/sdk_liteos/platform/include/sal_common.h new file mode 100644 index 0000000000000000000000000000000000000000..360ea5afd70ba4b5daf6de1c5b3fc6e6e92802a0 --- /dev/null +++ b/sdk_liteos/platform/include/sal_common.h @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __SAL_COMMON_H__ +#define __SAL_COMMON_H__ + +#include +#include "hi_crash.h" +#include + +hi_void sal_show_run_time(hi_void); + +#define ID_MSG_DIAG_BASE 0x100 + +enum { + ID_MSG_DIAG_DATA_TX = (ID_MSG_DIAG_BASE + 1), + ID_MSG_DIAG_DATA_USER_TX, + ID_MSG_DIAG_ACK_RX, + ID_MSG_DIAG_ACK_TX, + ID_MSG_DIAG_RX, + ID_MSG_DIAG_TIMER, + ID_MSG_DIAG_MSG, + ID_MSG_DIAG_ACK_MDM_RX +}; + +#define diag_msg_free(msg) hi_free(HI_MOD_ID_SAL_DIAG, (hi_pvoid)((msg)->param[0])) +#define diag_msg_free0(msg) hi_free(HI_MOD_ID_SAL_DIAG, (hi_pvoid)((msg)->param[0])) +#define diag_buffering_msg_free(msg) diag_free_buffer((diag_buffer_id)hi_lou16((msg)->param[3]), \ + (hi_pvoid)(uintptr_t)((msg)->param[0])) + +// Helper routine +#define init_exception_polling_wait() hi_sleep(HI_DMS_CHL_EXCEPTION_POLLING_WAIT) +#define uart_exception_polling_wait() hi_sleep(HI_DMS_UART_EXCEPTION_POLLING_WAIT) + +HI_EXTERN hi_void flash_set_crash_flag(hi_void); +HI_EXTERN hi_u32 flash_read_crash(HI_IN hi_u32 addr, HI_IN hi_void *data, HI_IN hi_u32 size); +HI_EXTERN hi_u32 flash_write_crash(HI_IN hi_u32 addr, HI_IN hi_void *data, HI_IN hi_u32 size); +HI_EXTERN hi_u32 flash_erase_crash(HI_IN hi_u32 addr, HI_IN hi_u32 size); +HI_EXTERN hi_u32 flash_ioctl_crash(hi_u16 cmd, hi_void *data); + +#if defined(PRODUCT_CFG_DIAG_FRM_ERR_PK_RPT) +hi_u32 diag_chl_error_report(hi_u32 ret, hi_u32 id); +#else +#define diag_chl_error_report(ret, id) \ + do { \ + } while (0) +#endif + +/* ERR REPORT ONLY for DIAG inside */ +#define diag_chl_err_rpt(id, ret) \ + do { \ + if ((ret) != HI_ERR_SUCCESS && (ret) != HI_ERR_DIAG_CONSUMED) { \ + diag_chl_error_report((ret), (id)); \ + } \ + } while (0) + +#define DIAG_ERR_RPT_LEN 48 + +HI_EXTERN hi_stat_diag g_stat_diag; + +hi_u32 hi_syserr_get_at_printf(hi_syserr_info *info); + +#define CRASH_INFO_EID_SAVE_ADDR 6 +#define CRASH_INFO_EID_SAVE_SIZE 4 +#define CRASH_INFO_RID_SAVE_ADDR 10 +#define CRASH_INFO_RID_SAVE_SIZE 6 + +#endif /* __SAL_COMMON_H__ */ + diff --git a/sdk_liteos/platform/include/sal_inf.h b/sdk_liteos/platform/include/sal_inf.h new file mode 100644 index 0000000000000000000000000000000000000000..03c340660919382ef2d8019358d2d4ddcad59ea4 --- /dev/null +++ b/sdk_liteos/platform/include/sal_inf.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __SAL_INF_H__ +#define __SAL_INF_H__ +#include +HI_START_HEADER +#include +#include +#include +#include +#include + +typedef struct { + hi_bool enable_save; + hi_bool delay_over; + hi_bool has_save; + hi_u8 rsv; + hi_u32 rst_times; + hi_u32 handle; +} sal_rst_times_ctrl; + +hi_u32 sal_rst_times_init(hi_void); +sal_rst_times_ctrl *sal_get_rst_times_ctrl(hi_void); +hi_u32 sal_uart_port_allocation(hi_uart_func_idx uart_func_id, hi_u8 *uart_id); +hi_void lp_sleep(hi_void); + +HI_END_HEADER +#endif /* __SAL_INF_H__ */ + diff --git a/sdk_liteos/platform/include/watchdog.h b/sdk_liteos/platform/include/watchdog.h new file mode 100644 index 0000000000000000000000000000000000000000..da810d5a74781cd914264cb3373e7dc35864e025 --- /dev/null +++ b/sdk_liteos/platform/include/watchdog.h @@ -0,0 +1,102 @@ +/** + * @file watchdog.h + * + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __BSP_INC_WATCHDOG_H__ +#define __BSP_INC_WATCHDOG_H__ + +#include +#include + +/** +* @ingroup hct_watchdog +* @brief Watchdog callback function. CNcomment:看门狗到期回调函数。CNend +* +* @par 描述: +* Watchdog callback function. CNcomment:看门狗到期回调函数。CNend +* +* @attention None. +* @param data [IN] type #hi_u32,Callback function parameter passing.CNcomment:回调函数参数传递。CNend +* +* @retval None. +* @par 依赖: +* @li watchdog.h:文件用于描述看门狗相关接口。 +* @see 无。 +*/ +typedef hi_void (*hi_watchdog_func)(hi_u32 data); + +/** + * @ingroup hct_watchdog + * + * Watchdog mode. CNcomment:看门狗模式。CNend + */ +typedef enum { + HI_WDG_MODE_NORMAL = 0, + HI_WDG_MODE_INTER = 1, + HI_WDG_MODE_ERR, +} hi_wdg_mode; + +/** +* @ingroup hct_watchdog +* @brief Clear the watchdog interrupt.CNcomment:清除看门狗中断。CNend +* +* @par 描述: +* Clear the watchdog interrupt.CNcomment:清除看门狗中断。CNend +* +* @attention 无。 +* @param 无。 +* +* @retval 无。 +* @par 依赖: +* @li watchdog.h:文件用于描述看门狗相关接口。 +* @see 无。 +*/ +HI_EXTERN hi_void hi_watchdog_int_clear(hi_void); + +/** +* @ingroup hct_watchdog +* @brief Configure to enable the watchdog. CNcomment:配置使能看门狗。CNend +* +* @par 描述: +* Configure to enable the watchdog. CNcomment:配置使能看门狗。CNend +* +* @attention 无。 +* @param mode [IN] type #hi_wdg_mode ,Watchdog mode. CNcomment:看门狗模式。CNend +* @param p_func [IN] type #hi_watchdog_func,Configure the watchdog to interrupt mode and the function will be +called to notify the user when the watchdog first expires. +CNcomment:配置看门狗为中断模式时,看门狗第一次到期时会调用该函数通知用户。CNend +* @param data [IN] type #hi_u32 Callback function enter parameter. CNcomment:回调函数入参。CNend +* @param over_time_ms [IN] type #hi_u32,Watchdog expiration time (unit: ms). + Expiration time calculation method: expiration time t = 2^(top+16)*1000/wd_clk, + where wd_clk is the watchdog clock frequency and top range is 0~15. + Therefore, there is a certain error between the expected expiration time and + the actual expiration time. + CNcomment:看门狗到期时间(单位:ms)。 +* 到期时间计算方法:到期时间t = 2^(top+16)*1000/wd_clk,其中wd_clk为看门狗时钟频率,top取值为0~15。 +* 因此期望的到期时间与实际到期时间有一定误差。CNend +* +* @retval #0 Sunccess. +* @retval #非0 Failure. For details, see hi_errno.h. +* @par 依赖: +* @li watchdog.h:文件用于描述看门狗相关接口。 +* @see 无。 +*/ +HI_EXTERN hi_u32 hi_watchdog_register(hi_wdg_mode mode, hi_watchdog_func p_func, hi_u32 data, hi_u32 over_time_ms); + +HI_EXTERN hi_void watchdog_irq_handler(hi_u32 data); + +#endif + diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/arch/los_atomic.h b/sdk_liteos/platform/os/Huawei_LiteOS/arch/los_atomic.h new file mode 100644 index 0000000000000000000000000000000000000000..467fec056868250121e25106f1bdb0f40434e37c --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/arch/los_atomic.h @@ -0,0 +1,291 @@ +/* ---------------------------------------------------------------------------- + * Copyright (c) Huawei Technologies Co., Ltd. 2018-2019. All rights reserved. + * Description : los atomic. + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * ---------------------------------------------------------------------------- */ + +/** + * @defgroup los_atomic Atomic + * @ingroup kernel + */ + +#ifndef _LOS_ATOMIC_H +#define _LOS_ATOMIC_H + +#include "los_hwi.h" +#include "los_typedef.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +/** +* @ingroup los_atomic +* @brief Atomic addition. +* +* @par Description: +* This API is used to implement the atomic addition and return the result value of the augend. +* @attention +*
    +*
  • The pointer val must not be NULL.
  • +*
  • If the addtion result is not in the range of representable values for 32-bit signed integer, +* an int integer overflow may occur to the return value
  • +*
+* +* @param val [IN] The augend pointer. +* @param addVal [IN] The addend. +* +* @retval #INT32 The result value of the augend. +* @par Dependency: +*
  • los_atomic.h: the header file that contains the API declaration.
+* @see +*/ +static inline INT32 LOS_AtomicAdd(volatile INT32 *val, INT32 addVal) +{ + INT32 tmp; + UINT32 intStatus; + intStatus = LOS_IntLock(); + tmp = *val; + tmp += addVal; + *val = tmp; + LOS_IntRestore(intStatus); + return tmp; +} + +/** +* @ingroup los_atomic +* @brief Atomic subtraction. +* +* @par Description: +* This API is used to implement the atomic subtraction and return the result value of the minuend. +* @attention +*
    +*
  • The pointer val must not be NULL.
  • +*
  • If the subtraction result is not in the range of representable values for 32-bit signed integer, +* an int integer overflow may occur to the return value
  • +*
+* +* @param val [IN] The minuend pointer. +* @param addVal [IN] The subtrahend. +* +* @retval #INT32 The result value of the minuend. +* @par Dependency: +*
  • los_atomic.h: the header file that contains the API declaration.
+* @see +*/ +static inline INT32 LOS_AtomicSub(volatile INT32 *val, INT32 addVal) +{ + INT32 tmp; + UINT32 intStatus; + intStatus = LOS_IntLock(); + tmp = *val; + tmp -= addVal; + *val = tmp; + LOS_IntRestore(intStatus); + return tmp; +} +/** +* @ingroup los_atomic +* @brief Atomic addSelf. +* +* @par Description: +* This API is used to implement the atomic addSelf . +* @attention +*
    +*
  • The pointer addr must not be NULL.
  • +*
  • The value which addr point to must not be INT_MAX to avoid integer overflow after adding 1.
  • +*
+* +* @param addr [IN] The addSelf variable pointer. +* +* @retval none. +* @par Dependency: +*
  • los_atomic.h: the header file that contains the API declaration.
+* @see +*/ +static inline VOID LOS_AtomicInc(volatile INT32 *addr) +{ + UINT32 intStatus; + intStatus = LOS_IntLock(); + (*addr)++; + LOS_IntRestore(intStatus); +} + +/** +* @ingroup los_atomic +* @brief Atomic addSelf. +* +* @par Description: +* This API is used to implement the atomic addSelf and return the result of addSelf. +* @attention +*
    +*
  • The pointer addr must not be NULL.
  • +*
  • The value which pswAddr point to must not be INT_MAX to avoid integer overflow after adding 1.
  • +*
+* +* @param addr [IN] The addSelf variable pointer. +* +* @retval #INT32 The return value of variable addSelf. +* @par Dependency: +*
  • los_atomic.h: the header file that contains the API declaration.
+* @see +*/ +static inline INT32 LOS_AtomicIncRet(volatile INT32 *addr) +{ + INT32 tmp; + UINT32 intStatus; + intStatus = LOS_IntLock(); + tmp = *addr; + tmp++; + *addr = tmp; + LOS_IntRestore(intStatus); + return tmp; +} + +/** +* @ingroup los_atomic +* @brief Atomic auto-decrement. +* +* @par Description: +* This API is used to implementating the atomic auto-decrement. +* @attention +*
    +*
  • The pointer addr must not be NULL.
  • +*
  • The value which pswAddr point to must not be INT_MIN to avoid overflow after reducing 1.
  • +*
+* +* @param addr [IN] The auto-decrement variable pointer. +* +* @retval none. +* @par Dependency: +*
  • los_atomic.h: the header file that contains the API declaration.
+* @see +*/ +static inline VOID LOS_AtomicDec(volatile INT32 *addr) +{ + UINT32 intStatus; + intStatus = LOS_IntLock(); + (*addr)--; + LOS_IntRestore(intStatus); +} + +/** +* @ingroup los_atomic +* @brief Atomic auto-decrement. +* +* @par Description: +* This API is used to implementating the atomic auto-decrement and return the result of auto-decrement. +* @attention +*
    +*
  • The pointer addr must not be NULL.
  • +*
  • The value which pswAddr point to must not be INT_MIN to avoid overflow after reducing 1.
  • +*
+* +* @param addr [IN] The addSelf variable pointer. +* +* @retval #INT32 The return value of variable auto-decrement. +* @par Dependency: +*
  • los_atomic.h: the header file that contains the API declaration.
+* @see +*/ +static inline INT32 LOS_AtomicDecRet(volatile INT32 *addr) +{ + INT32 tmp; + UINT32 intStatus; + intStatus = LOS_IntLock(); + tmp = *addr; + tmp--; + *addr = tmp; + LOS_IntRestore(intStatus); + return tmp; +} + +/** +* @ingroup los_atomic +* @brief Atomic exchange for 32-bit variable. +* +* @par Description: +* This API is used to implement the atomic exchange for 32-bit variable and return the previous value of +* the atomic variable. +* @attention +*
    The pointer addr must not be NULL.
+* +* @param addr [IN] The variable pointer. +* @param value [IN] The exchange value. +* +* @retval #INT32 The previous value of the atomic variable +* @par Dependency: +*
  • los_atomic.h: the header file that contains the API declaration.
+* @see +*/ +static inline INT32 LOS_AtomicXchg32bits(volatile INT32 *addr, INT32 value) +{ + INT32 prevVal; + UINT32 intStatus; + intStatus = LOS_IntLock(); + prevVal = *addr; + *addr = value; + LOS_IntRestore(intStatus); + return prevVal; +} + +/** +* @ingroup los_atomic +* @brief Atomic exchange for 32-bit variable with compare. +* +* @par Description: +* This API is used to implement the atomic exchange for 32-bit variable, if the value of variable is equal to swOldVal. +* @attention +*
    The pointer addr must not be NULL.
+* +* @param addr [IN] The variable pointer. +* @param newVal [IN] The new value. +* @param oldVal [IN] The old value. +* +* @retval TRUE The previous value of the atomic variable is not equal to swOldVal. +* @retval FALSE The previous value of the atomic variable is equal to swOldVal. +* @par Dependency: +*
  • los_atomic.h: the header file that contains the API declaration.
+* @see +*/ +static inline BOOL LOS_AtomicCmpXchg32bits(volatile INT32 *addr, INT32 newVal, INT32 oldVal) +{ + INT32 prevVal; + UINT32 intStatus = LOS_IntLock(); + prevVal = *addr; + if (*addr == oldVal) { + *addr = newVal; + } + LOS_IntRestore(intStatus); + return (prevVal != oldVal); +} + +#ifdef __cplusplus +#if __cplusplus +} +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +#endif /* _LOS_ATOMIC_H */ diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/arch/los_hwi.h b/sdk_liteos/platform/os/Huawei_LiteOS/arch/los_hwi.h new file mode 100644 index 0000000000000000000000000000000000000000..965ebc3e3a1ba90c8640d57649e147715a0d9a8e --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/arch/los_hwi.h @@ -0,0 +1,648 @@ +/* ---------------------------------------------------------------------------- + * Copyright (c) Huawei Technologies Co., Ltd. 2018-2019. All rights reserved. + * Description : LiteOS interrupt module implemention. + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * ---------------------------------------------------------------------------- */ + +/** + * @defgroup los_hwi Hardware interrupt + * @ingroup kernel + */ + +#ifndef _LOS_HWI_H +#define _LOS_HWI_H + +#include "los_typedef.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif /* __cplusplus */ +#endif /* __cplusplus */ +/** + * @ingroup los_config + * Configuration item for interrupt with argument + */ +#ifndef OS_HWI_WITH_ARG +#define OS_HWI_WITH_ARG YES +#endif +/** + * @ingroup los_hwi + * Define the type of a hardware interrupt number. + */ +typedef UINT32 HWI_HANDLE_T; + +/** + * @ingroup los_hwi + * Define the type of a hardware interrupt priority. + */ +typedef UINT16 HWI_PRIOR_T; + +/** + * @ingroup los_hwi + * Define the type of hardware interrupt mode configurations. + */ +typedef UINT16 HWI_MODE_T; + +/** + * @ingroup los_hwi + * Define the type of the parameter used for the hardware interrupt creation function. + * The function of this parameter varies among platforms. + */ +typedef UINT32 HWI_ARG_T; + +/** + * @ingroup los_hwi + * Define the type of a hardware interrupt handling function. + */ +#if (OS_HWI_WITH_ARG == YES) + +typedef VOID (* HWI_PROC_FUNC)(VOID *arg); +typedef struct { + HWI_PROC_FUNC pfnHandler; + VOID* pParm; +} HWI_SLAVE_FUNC; + +#else + +typedef VOID (* HWI_PROC_FUNC)(VOID); + +#endif + +/** + * @ingroup los_hwi + * Define the type of a hardware interrupt hook function. + */ +typedef VOID (*HWI_HOOK_FUNC)(UINT32 hwiNum); + +/** + * @ingroup los_hwi + * Define the type of a hardware interrupt vector table function. + */ +typedef VOID (**HWI_VECTOR_FUNC)(VOID); + +/** + * @ingroup los_hwi + * Count of interrupts. + */ +extern UINT32 g_vuwIntCount; + +/** + * @ingroup los_hwi + * An interrupt is active. + */ +#define OS_INT_ACTIVE (g_vuwIntCount > 0) + +/** + * @ingroup los_hwi + * An interrupt is inactive. + */ +#define OS_INT_INACTIVE (!(OS_INT_ACTIVE)) + +/** + * @ingroup los_hwi + * Count of HimiDeer system interrupt vector. + */ +#define OS_HIMIDEER_SYS_VECTOR_CNT 26 + +/** + * @ingroup los_hwi + * Count of HimiDeer local interrupt vector 0 - 5, enabled by CSR mie 26 -31 bit. + */ +#define OS_HIMIDEER_MIE_IRQ_VECTOR_CNT 6 + +/** + * @ingroup los_hwi + * Count of HimiDeer IRQ controlled by CSR mie + */ +#define OS_HIMIDEER_MIE_TOTAL_CNT (OS_HIMIDEER_SYS_VECTOR_CNT + OS_HIMIDEER_MIE_IRQ_VECTOR_CNT) + +/** + * @ingroup los_hwi + * Count of HimiDeer local interrupt vector 6 - 34, enabled by custom CSR locie0 0 - 22 bit. + */ +#ifndef LOSCFG_RAM_MONITOR +#define OS_HIMIDEER_CUSTOM_IRQ_VECTOR_CNT 29 +#else +#define OS_HIMIDEER_CUSTOM_IRQ_VECTOR_CNT (29 + 1) // add ram monitor interrupt +#endif +/** + * @ingroup los_hwi + * Count of HimiDeer local IRQ interrupt vector. + */ +#define OS_HIMIDEER_LOCAL_IRQ_VECTOR_CNT (OS_HIMIDEER_MIE_IRQ_VECTOR_CNT + OS_HIMIDEER_CUSTOM_IRQ_VECTOR_CNT) + +/** + * @ingroup los_hwi + * Count of himideer interrupt vector. + */ +#define OS_HIMIDEER_VECTOR_CNT (OS_HIMIDEER_SYS_VECTOR_CNT + OS_HIMIDEER_LOCAL_IRQ_VECTOR_CNT) + +#define OS_VECTOR_CNT OS_HIMIDEER_VECTOR_CNT + +#define OS_HWI_MAX_NUM OS_HIMIDEER_VECTOR_CNT + +/** + * @ingroup los_hwi + * Minimum interrupt number. + */ +#define OS_HWI_MIN 0 + +/** + * @ingroup los_hwi + * Maximum interrupt number. + */ +#define OS_HWI_MAX ((OS_HWI_MAX_NUM) - 1) + +/** + * @ingroup los_hwi + * Highest priority of a hardware interrupt. + */ +#ifndef OS_HWI_PRIO_HIGHEST +#define OS_HWI_PRIO_HIGHEST 7 +#endif +/** + * @ingroup los_hwi + * Lowest priority of a hardware interrupt. + */ +#ifndef OS_HWI_PRIO_LOWEST +#define OS_HWI_PRIO_LOWEST 1 +#endif + +/** + * @ingroup los_hwi + * Hardware interrupt error code: Invalid interrupt number. + * + * Value: 0x02000900 + * + * Solution: Ensure that the interrupt number is valid. The value range of the interrupt number applicable + * for a Cortex-M4 platform is [0,240]. + */ +#define OS_ERRNO_HWI_NUM_INVALID LOS_ERRNO_OS_ERROR(LOS_MOD_HWI, 0x00) + +/** + * @ingroup los_hwi + * Hardware interrupt error code: Null hardware interrupt handling function. + * + * Value: 0x02000901 + * + * Solution: Pass in a valid non-null hardware interrupt handling function. + */ +#define OS_ERRNO_HWI_PROC_FUNC_NULL LOS_ERRNO_OS_ERROR(LOS_MOD_HWI, 0x01) + +/** + * @ingroup los_hwi + * Hardware interrupt error code: Insufficient interrupt resources for hardware interrupt creation. + * + * Value: 0x02000902 + * + * Solution: Increase the configured maximum number of supported hardware interrupts. + */ +#define OS_ERRNO_HWI_CB_UNAVAILABLE LOS_ERRNO_OS_ERROR(LOS_MOD_HWI, 0x02) + +/** + * @ingroup los_hwi + * Hardware interrupt error code: Insufficient memory for hardware interrupt initialization. + * + * Value: 0x02000903 + * + * Solution: Expand the configured memory. + */ +#define OS_ERRNO_HWI_NO_MEMORY LOS_ERRNO_OS_ERROR(LOS_MOD_HWI, 0x03) + +/** + * @ingroup los_hwi + * Hardware interrupt error code: The interrupt has already been created. + * + * Value: 0x02000904 + * + * Solution: Check whether the interrupt specified by the passed-in interrupt number has already been created. + */ +#define OS_ERRNO_HWI_ALREADY_CREATED LOS_ERRNO_OS_ERROR(LOS_MOD_HWI, 0x04) + +/** + * @ingroup los_hwi + * Hardware interrupt error code: Invalid interrupt priority. + * + * Value: 0x02000905 + * + * Solution: Ensure that the interrupt priority is valid. The value range of the interrupt priority applicable + * for a Cortex-M4 platform is [OS_HWI_PRIO_HIGHEST,OS_HWI_PRIO_LOWEST]. + */ +#define OS_ERRNO_HWI_PRIO_INVALID LOS_ERRNO_OS_ERROR(LOS_MOD_HWI, 0x05) + +/** + * @ingroup los_hwi + * Hardware interrupt error code: Incorrect interrupt creation mode. + * + * Value: 0x02000906 + * + * Solution: The interrupt creation mode can be only set to OS_HWI_MODE_COMM or OS_HWI_MODE_FAST of which the + * value can be 0 or 1. + */ +#define OS_ERRNO_HWI_MODE_INVALID LOS_ERRNO_OS_ERROR(LOS_MOD_HWI, 0x06) + +/** + * @ingroup los_hwi + * Hardware interrupt error code: The interrupt has already been created as a fast interrupt. + * + * Value: 0x02000907 + * + * Solution: Check whether the interrupt specified by the passed-in interrupt number has already been created. + */ +#define OS_ERRNO_HWI_FASTMODE_ALREADY_CREATED LOS_ERRNO_OS_ERROR(LOS_MOD_HWI, 0x07) + +/** + * @ingroup los_hwi + * Hardware interrupt error code: The interrupt is not created when enable this interrupt. + * + * Value: 0x02000908 + * + * Solution: Check whether the interrupt is already been created before enable. + */ +#define OS_ERRNO_HWI_NOT_CREATED LOS_ERRNO_OS_ERROR(LOS_MOD_HWI, 0x08) + +#if (OS_HWI_WITH_ARG == YES) +/** + * @ingroup los_hwi + * hardware interrupt Slave form mapping handling function array. + */ +extern HWI_SLAVE_FUNC g_hwiSlaveForm[OS_HIMIDEER_VECTOR_CNT]; + +/** + * @ingroup los_hwi + * Set interrupt vector table. + */ +extern HWI_PROC_FUNC g_intEntry; +#define OS_SET_VECTOR(num, vector, arg) do { \ + g_hwiSlaveForm[num].pfnHandler = (vector); \ + g_hwiSlaveForm[num].pParm = (VOID*)(UINTPTR)(arg); \ +} while (0) +#else +/** + * @ingroup los_hwi + * hardware interrupt Slave form mapping handling function array. + */ +extern HWI_PROC_FUNC g_hwiSlaveForm[OS_HIMIDEER_VECTOR_CNT]; + +/** + * @ingroup los_hwi + * Set interrupt vector table. + */ +#define OS_SET_VECTOR(num, vector) do { \ + g_hwiSlaveForm[num] = (vector); \ +} while (0) +#endif + +/** + * @ingroup los_hwi + * @brief Create a hardware interrupt. + * + * @par Description: + * This API is used to configure a hardware interrupt and register a hardware interrupt handling function. + * + * @attention + *
    + *
  • The hardware interrupt module is usable only when the configuration item for hardware interrupt tailoring + * is enabled.
  • + *
  • Hardware interrupt number value range: [OS_HWI_MIN,OS_HWI_MAX]. The value range applicable for a Cortex-M4 + * platform is [0,240].
  • + *
  • OS_HWI_MAX_NUM specifies the maximum number of interrupts that can be created.
  • + *
  • Before executing an interrupt on a platform, refer to the chip manual of the platform.
  • + *
+ * + * @param hwiNum [IN] Type#HWI_HANDLE_T: hardware interrupt number. The value range applicable for a Cortex-M4 + * platform is [0,240]. + * @param hwiPrio [IN] Type#HWI_PRIOR_T: hardware interrupt priority. Ignore this parameter temporarily. + * @param mode [IN] Type#HWI_MODE_T: hardware interrupt mode. Ignore this parameter temporarily. + * @param funHandler [IN] Type#HWI_PROC_FUNC: interrupt handler used when a hardware interrupt is triggered. + * @param arg [IN] Type#HWI_ARG_T: input parameter of the interrupt handler used when a hardware interrupt + * is triggered. + * + * @retval #OS_ERRNO_HWI_PROC_FUNC_NULL 0x02000901: Null hardware interrupt handling function. + * @retval #OS_ERRNO_HWI_NUM_INVALID 0x02000900: Invalid interrupt number. + * @retval #OS_ERRNO_HWI_NO_MEMORY 0x02000903: Insufficient memory for hardware interrupt creation. + * @retval #OS_ERRNO_HWI_ALREADY_CREATED 0x02000904: The interrupt handler being created has already been created. + * @retval #LOS_OK 0, : The interrupt is successfully created. + * @par Dependency: + *
  • los_hwi.h: the header file that contains the API declaration.
+ * @see None. + */ +extern UINT32 LOS_HwiCreate(HWI_HANDLE_T hwiNum, + HWI_PRIOR_T hwiPrio, + HWI_MODE_T mode, + HWI_PROC_FUNC funHandler, + HWI_ARG_T arg); + +/** + * @ingroup los_hwi + * @brief: Hardware interrupt entry function. + * + * @par Description: + * This API is used as all hardware interrupt handling function entry. + * + * @attention: + *
  • None.
+ * + * @param: None. + * + * @retval:None. + * @par Dependency: + *
  • los_hwi.h: the header file that contains the API declaration.
+ * @see None. + */ +extern VOID OsInterrupt(VOID); + +/** + * @ingroup los_hwi + * @brief: Get a interrupt number. + * + * @par Description: + * This API is used to get the current interrupt number. + * + * @attention: + *
  • None.
+ * + * @param: None. + * + * @retval: Interrupt Indexes number. + * @par Dependency: + *
  • los_hwi.h: the header file that contains the API declaration.
+ * @see None. + */ +extern UINT32 OsIntNumGet(VOID); + +/** + * @ingroup los_hwi + * @brief: Default vector handling function. + * + * @par Description: + * This API is used to configure interrupt for null function. + * + * @attention: + *
  • None.
+ * + * @param: None. + * + * @retval:None. + * @par Dependency: + *
  • los_hwi.h: the header file that contains the API declaration.
+ * @see None. + */ +extern VOID OsHwiDefaultHandler(VOID); + +/** + * @ingroup los_config + * @brief: hardware interrupt init function. + * + * @par Description: + * This API is used to initialize hardware interrupt module. + * + * @attention: + *
  • None.
+ * + * @param: None. + * + * @retval #LOS_OK 0:Hardware interrupt initialization success. + * + * @par Dependency: + *
  • los_config.h: the header file that contains the API declaration.
+ * @see None. + */ +extern VOID OsHwiInit(VOID); + + /** + * @ingroup los_hwi + * @brief Enable all interrupts. + * + * @par Description: + *
    + *
  • This API is used to enable all IRQ and FIQ interrupts in the CPSR.
  • + *
+ * @attention + *
    + *
  • None.
  • + *
+ * + * @param None. + * + * @retval CPSR value obtained after all interrupts are enabled. + * @par Dependency: + *
  • los_hwi.h: the header file that contains the API declaration.
+ * @see LOS_IntRestore + */ +extern UINTPTR LOS_IntUnLock(VOID); + + /** + * @ingroup los_hwi + * @brief Disable all interrupts. + * + * @par Description: + *
    + *
  • This API is used to disable all IRQ and FIQ interrupts in the CPSR.
  • + *
+ * @attention + *
    + *
  • None.
  • + *
+ * + * @param None. + * + * @retval CPSR value obtained before all interrupts are disabled. + * @par Dependency: + *
  • los_hwi.h: the header file that contains the API declaration.
+ * @see LOS_IntRestore + */ +extern UINTPTR LOS_IntLock(VOID); + + /** + * @ingroup los_hwi + * @brief Restore interrupts. + * + * @par Description: + *
    + *
  • This API is used to restore the CPSR value obtained before all interrupts are disabled.
  • + *
+ * @attention + *
    + *
  • This API can be called only after all interrupts are disabled, and the input parameter value + * should be the value returned by calling the all interrupt disabling API.
  • + *
+ * + * @param intSave [IN] CPSR value obtained before all interrupts are disabled. + * + * @retval None. + * @par Dependency: + *
  • los_hwi.h: the header file that contains the API declaration.
+ * @see LOS_IntLock + */ +extern VOID LOS_IntRestore(UINTPTR intSave); + +/** + * @ingroup los_hwi + * @brief Delete hardware interrupt. + * + * @par Description: + * This API is used to delete hardware interrupt. + * + * @attention + *
    + *
  • The hardware interrupt module is usable only when the configuration item for hardware interrupt + * tailoring is enabled.
  • + *
  • Hardware interrupt number value range: [OS_HWI_MIN,OS_HWI_MAX]. The value range applicable for + * a Cortex-M4 platform is [0,240].
  • + *
  • OS_HWI_MAX_NUM specifies the maximum number of interrupts that can be created.
  • + *
  • Before executing an interrupt on a platform, refer to the chip manual of the platform.
  • + *
+ * + * @param hwiNum [IN] Type#HWI_HANDLE_T: hardware interrupt number. The value range applicable for + * a Cortex-M4 platform is [0,240]. + * + * @retval #OS_ERRNO_HWI_NUM_INVALID 0x02000900: Invalid interrupt number. + * @retval #LOS_OK 0: The interrupt is successfully delete. + * @par Dependency: + *
  • los_hwi.h: the header file that contains the API declaration.
+ * @see None. + */ +extern UINT32 LOS_HwiDelete(HWI_HANDLE_T hwiNum); + +/** + * @ingroup los_hwi + * @brief Rigister interrupt hook functions. + * + * @par Description: + *
    + *
  • This API is used to register functions which is reserved in rom code .
  • + *
+ * @attention + *
    + *
  • None .
  • + *
+ * + * @param prepareFunc [IN] Type#HWI_HOOK_FUNC: function that called before irq. + * @param resumeFunc [IN] Type#HWI_HOOK_FUNC: function that called after irq. + * + * @retval VOID. + * @par Dependency: + *
  • los_hwi.h: the header file that contains the API declaration.
+ * @see None + */ +extern VOID LOS_HwiRigister(HWI_HOOK_FUNC prepareFunc, HWI_HOOK_FUNC resumeFunc); + +/** + * @ingroup los_hwi + * @brief Get interrupt number. + * + * @par Description: + *
    + *
  • This API is used to get irq number .
  • + *
+ * @attention + *
    + *
  • This API can be called only when an irq come up .
  • + *
+ * + * @param None. + * + * @retval UINT32 irq number. + * @par Dependency: + *
  • los_hwi.h: the header file that contains the API declaration.
+ * @see None + */ +extern UINT32 LOS_IntNumGet(VOID); + +/** + * @ingroup los_hwi + * @brief Enable interrupt and set the priority. + * + * @par Description: + *
    + *
  • This API is used to set irq priority and enable it.
  • + *
+ * @attention + *
    + *
  • This API can be called only when an irq is created by LOS_HwiCreate .
  • + *
+ * + * @param irqnum [IN] The Irq num,it should in [OS_HIMIDEER_SYS_VECTOR_CNT, + * OS_HIMIDEER_LOCAL_IRQ_VECTOR_CNT] + * @param prior [IN] The Irq priority, it should in [OS_HWI_PRIO_LOWEST, OS_HWI_PRIO_HIGHEST]. + * @retval OS_ERRNO_HWI_NUM_INVALID: the input irqnum is incorrect + * @retval OS_ERRNO_HWI_NOT_CREATED: the irq is not created by LOS_HwiCreate + * @retval OS_ERRNO_HWI_PRIO_INVALID: the input the input irqnum is incorrect is incorrect + * @retval LOS_OK: success + * @par Dependency: + *
  • los_hwi.h: the header file that contains the API declaration.
+ * @see None + */ +extern UINT32 LOS_AdapIrqEnable(UINT32 irqNum, UINT16 prior); + +/** + * @ingroup los_hwi + * @brief Disable the interrupt. + * + * @par Description: + *
    + *
  • This API is used to disable irq.
  • + *
+ * @attention + *
    + *
  • None .
  • + *
+ * + * @param irqnum [IN] The Irq num,it should in [OS_HIMIDEER_SYS_VECTOR_CNT, + * OS_HIMIDEER_LOCAL_IRQ_VECTOR_CNT] + * @par Dependency: + *
  • los_hwi.h: the header file that contains the API declaration.
+ * @see None + */ +extern VOID LOS_AdapIrqDisable(UINT32 irqNum); + +/** + * @ingroup los_hwi + * @brief diable interrupts. + * + * @par Description: + *
    + *
  • This API is used to disable interrupts .
  • + *
+ * @attention + *
    + *
  • This API can be called only in OsTaskExit() .
  • + *
+ * + * @param None. + * + * @retval None. + * @par Dependency: + *
  • los_hwi.h: the header file that contains the API declaration.
+ * @see None + */ +extern VOID OsDisableIRQ(VOID); + +#ifdef __cplusplus +#if __cplusplus +} +#endif /* __cplusplus */ +#endif /* __cplusplus */ +#endif /* _LOS_HWI_H */ diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/hw/include/bits/pthread_types.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/hw/include/bits/pthread_types.h new file mode 100644 index 0000000000000000000000000000000000000000..d06d2ee8234a8cf3a1f680645a5b58126e5a65d8 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/hw/include/bits/pthread_types.h @@ -0,0 +1,48 @@ +/* ---------------------------------------------------------------------------- + * Copyright (c) Huawei Technologies Co., Ltd. 2013-2019. All rights reserved. + * Description: PTHREAD TYPE + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice,this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice,this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * --------------------------------------------------------------------------- */ + +#ifndef _BITS_PTHREAD_TYPES_H_ +#define _BITS_PTHREAD_TYPES_H_ + +#include +#include "los_config.h" + +typedef struct __pthread_attr_s { + unsigned int detachstate; + unsigned int schedpolicy; + struct sched_param schedparam; + unsigned int inheritsched; + unsigned int scope; + unsigned int stackaddr_set; + void* stackaddr; + unsigned int stacksize_set; + size_t stacksize; +} pthread_attr_t; + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/hw/include/liteos/mtd-abi.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/hw/include/liteos/mtd-abi.h new file mode 100644 index 0000000000000000000000000000000000000000..5c39b2bba45eb7479aca007d4f42907f769f7c61 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/hw/include/liteos/mtd-abi.h @@ -0,0 +1,78 @@ +/* ---------------------------------------------------------------------------- + * Copyright (c) Huawei Technologies Co., Ltd. 2013-2019. All rights reserved. + * Description: MTD ABI HEAD FILE + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice,this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice,this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * --------------------------------------------------------------------------- */ + +#ifndef _HW_MTD_ABI_H_ +#define _HW_MTD_ABI_H_ +#include +#include "linux/kernel.h" +#include "linux/ioctl.h" + +typedef __signed__ char __s8; +typedef unsigned char __u8; +typedef __signed__ short __s16; +typedef unsigned short __u16; +typedef __signed__ int __s32; +typedef unsigned int __u32; +typedef __signed__ long long __s64; +typedef unsigned long long __u64; +typedef long long __kernel_loff_t; + +struct erase_info_user { + __u32 start; + __u32 length; +}; +struct erase_info_user64 { + __u64 start; + __u64 length; +}; + +#define MTD_NORFLASH 3 +#define MTD_NANDFLASH 4 +#define MTD_WRITEABLE 0x400 +#define MTD_BIT_WRITEABLE 0x800 +#define MTD_CAP_NORFLASH (MTD_WRITEABLE | MTD_BIT_WRITEABLE) +#define MTD_CAP_NANDFLASH (MTD_WRITEABLE) + +struct mtd_info_user { + __u8 type; + __u32 flags; + __u32 size; + __u32 erasesize; + __u32 writesize; + __u32 oobsize; + __u64 padding; +}; + +#define MEMGETINFO _IOR('M', 1, struct mtd_info_user) +#define MEMERASE _IOW('M', 2, struct erase_info_user) +#define MEMGETBADBLOCK _IOW('M', 11, __kernel_loff_t) +#define MEMSETBADBLOCK _IOW('M', 12, __kernel_loff_t) +#define MEMERASE64 _IOW('M', 20, struct erase_info_user64) + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/hw/include/sys/cdefs.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/hw/include/sys/cdefs.h new file mode 100644 index 0000000000000000000000000000000000000000..e9ea2c1e51eab176b292c41720140e9ca14c02be --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/hw/include/sys/cdefs.h @@ -0,0 +1,52 @@ +/* ---------------------------------------------------------------------------- + * Copyright (c) Huawei Technologies Co., Ltd. 2013-2019. All rights reserved. + * Description: CDEFS HEAD FILE + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice,this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice,this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * --------------------------------------------------------------------------- */ + +#ifndef _HW_CDEFS_H_ +#define _HW_CDEFS_H_ + +#if defined(__cplusplus) +#define __BEGIN_DECLS extern "C" { +#define __END_DECLS } +#else +#define __BEGIN_DECLS +#define __END_DECLS +#endif + +#define __packed __attribute__((__packed__)) +#define __aligned(x) __attribute__((__aligned__(x))) + +#define __LIBC_HIDDEN__ __attribute__((visibility("hidden"))) + +#define __FBSDID(_s) + +#define __min_size(x) static (x) + +#define __unused __attribute__((__unused__)) + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/hw/include/time64.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/hw/include/time64.h new file mode 100644 index 0000000000000000000000000000000000000000..3c037f1ac2a1aa5863c36d401f5173a25974784f --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/hw/include/time64.h @@ -0,0 +1,132 @@ +/* ---------------------------------------------------------------------------- + * Copyright (c) Huawei Technologies Co., Ltd. 2013-2019. All rights reserved. + * Description: TIME64 HEAD FILE + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice,this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice,this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * --------------------------------------------------------------------------- */ + +#ifndef _HW_TIME64_H_ +#define _HW_TIME64_H_ + +#if defined(__LP64__) + +#error Your time_t is already 64-bit. + +#else +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#if defined(__LITEOS__) && !defined(__LP64___) +#define __NEED_int64_t +#include + +struct timeval64 { + int64_t tv_sec; + int64_t tv_usec; +}; + +struct timespec64 { + int64_t tv_sec; + int64_t tv_nsec; +}; + +/** + * @ingroup time + * @par Description: + * This function sets the time as well as a timezone in 32-bit system. + * + * @attention + *
    + *
  • The function is not supported to set timezone,So the second parameter is unused
  • + *
+ * + * @retval #0 The function is executed successfully. + * @retval #-1 The function failed to execute, and corresponding error code is set. + * + * @par Errors + *
    + *
  • EINVAL: An invalid Input.
  • + *
+ * + * @par Dependency: + *
  • time64.h
+ * + * @see clock_gettime | time | ctime + * + */ +int settimeofday64(const struct timeval64 *, const struct timezone *); + +/** + * @ingroup time + * @par Description: + * This function gets the time as well as a timezone in 32-bit system. + * + * @attention + *
    + *
  • The function is not supported to get timezone,So the second parameter is unused
  • + *
+ * + * @retval #0 The function is executed successfully. + * @retval #-1 The function failed to execute, and corresponding error code is set. + * + * @par Errors + *
    + *
  • EINVAL: An invalid Input.
  • + *
+ * + * @par Dependency: + *
  • time64.h
+ * + * @see clock_gettime | time | ctime + * + */ + +int gettimeofday64(struct timeval64 *, struct timezone *); +#endif + +typedef int64_t time64_t; + +char *asctime64(const struct tm *); +char *asctime64_r(const struct tm *, char *); +char *ctime64(const time64_t *); +char *ctime64_r(const time64_t *, char *); +struct tm *gmtime64(const time64_t *); +struct tm *gmtime64_r(const time64_t *, struct tm *); +struct tm *localtime64(const time64_t *); +struct tm *localtime64_r(const time64_t *, struct tm *); +time64_t mktime64(struct tm *); +time64_t timegm64(const struct tm *); +time64_t timelocal64(const struct tm *); + +#ifdef __cplusplus +} +#endif +#endif +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/dirent.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/dirent.h new file mode 100644 index 0000000000000000000000000000000000000000..c845fe82dda20257d1bae78754bb110d7f7a2aa6 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/dirent.h @@ -0,0 +1,11 @@ +#define _DIRENT_HAVE_D_RECLEN +#define _DIRENT_HAVE_D_OFF +#define _DIRENT_HAVE_D_TYPE + +struct dirent { + ino_t d_ino; + off_t d_off; + unsigned short d_reclen; + unsigned char d_type; + char d_name[256]; +}; diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/errno.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/errno.h new file mode 100644 index 0000000000000000000000000000000000000000..7ec9c79c39579528daa547fe706109a3f818a2fe --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/errno.h @@ -0,0 +1,154 @@ +#ifdef __LITEOS__ +#define ENOERR 0 +#endif +#define EPERM 1 +#define ENOENT 2 +#define ESRCH 3 +#define EINTR 4 +#define EIO 5 +#define ENXIO 6 +#define E2BIG 7 +#define ENOEXEC 8 +#define EBADF 9 +#define ECHILD 10 +#define EAGAIN 11 +#define ENOMEM 12 +#define EACCES 13 +#define EFAULT 14 +#define ENOTBLK 15 +#define EBUSY 16 +#define EEXIST 17 +#define EXDEV 18 +#define ENODEV 19 +#define ENOTDIR 20 +#define EISDIR 21 +#define EINVAL 22 +#define ENFILE 23 +#define EMFILE 24 +#define ENOTTY 25 +#define ETXTBSY 26 +#define EFBIG 27 +#define ENOSPC 28 +#define ESPIPE 29 +#define EROFS 30 +#define EMLINK 31 +#define EPIPE 32 +#define EDOM 33 +#define ERANGE 34 +#define EDEADLK 35 +#define ENAMETOOLONG 36 +#define ENOLCK 37 +#define ENOSYS 38 +#define ENOTEMPTY 39 +#define ELOOP 40 +#define EWOULDBLOCK EAGAIN +#define ENOMSG 42 +#define EIDRM 43 +#define ECHRNG 44 +#define EL2NSYNC 45 +#define EL3HLT 46 +#define EL3RST 47 +#define ELNRNG 48 +#define EUNATCH 49 +#define ENOCSI 50 +#define EL2HLT 51 +#define EBADE 52 +#define EBADR 53 +#define EXFULL 54 +#define ENOANO 55 +#define EBADRQC 56 +#define EBADSLT 57 +#define EDEADLOCK EDEADLK +#define EBFONT 59 +#define ENOSTR 60 +#define ENODATA 61 +#define ETIME 62 +#define ENOSR 63 +#define ENONET 64 +#define ENOPKG 65 +#define EREMOTE 66 +#define ENOLINK 67 +#define EADV 68 +#define ESRMNT 69 +#define ECOMM 70 +#define EPROTO 71 +#define EMULTIHOP 72 +#define EDOTDOT 73 +#define EBADMSG 74 +#define EOVERFLOW 75 +#define ENOTUNIQ 76 +#define EBADFD 77 +#define EREMCHG 78 +#define ELIBACC 79 +#define ELIBBAD 80 +#define ELIBSCN 81 +#define ELIBMAX 82 +#define ELIBEXEC 83 +#define EILSEQ 84 +#define ERESTART 85 +#define ESTRPIPE 86 +#define EUSERS 87 +#define ENOTSOCK 88 +#define EDESTADDRREQ 89 +#define EMSGSIZE 90 +#define EPROTOTYPE 91 +#define ENOPROTOOPT 92 +#define EPROTONOSUPPORT 93 +#define ESOCKTNOSUPPORT 94 +#define EOPNOTSUPP 95 +#define ENOTSUP EOPNOTSUPP +#define EPFNOSUPPORT 96 +#define EAFNOSUPPORT 97 +#define EADDRINUSE 98 +#define EADDRNOTAVAIL 99 +#define ENETDOWN 100 +#define ENETUNREACH 101 +#define ENETRESET 102 +#define ECONNABORTED 103 +#define ECONNRESET 104 +#define ENOBUFS 105 +#define EISCONN 106 +#define ENOTCONN 107 +#define ESHUTDOWN 108 +#define ETOOMANYREFS 109 +#define ETIMEDOUT 110 +#define ECONNREFUSED 111 +#define EHOSTDOWN 112 +#define EHOSTUNREACH 113 +#define EALREADY 114 +#define EINPROGRESS 115 +#define ESTALE 116 +#define EUCLEAN 117 +#define ENOTNAM 118 +#define ENAVAIL 119 +#define EISNAM 120 +#define EREMOTEIO 121 +#define EDQUOT 122 +#define ENOMEDIUM 123 +#define EMEDIUMTYPE 124 +#define ECANCELED 125 +#define ENOKEY 126 +#define EKEYEXPIRED 127 +#define EKEYREVOKED 128 +#define EKEYREJECTED 129 +#define EOWNERDEAD 130 +#define ENOTRECOVERABLE 131 +#define ERFKILL 132 +#define EHWPOISON 133 + +#ifdef __LITEOS__ +#define EEOF 200 +#define ENOSUPP 201 +#define EDEVNOSUPP 202 +#define EBADHANDLE 521 +#define ENOTSYNC 522 +#define EBADCOOKIE 523 +#define ENOTSUPP 524 +#define ETOOSMALL 525 +#define ESERVERFAULT 526 +#define EBADTYPE 527 +#define EJUKEBOX 528 +#define EIOCBQUEUED 529 +#define EIOCBRETRY 530 +#endif + diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/fcntl.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/fcntl.h new file mode 100644 index 0000000000000000000000000000000000000000..ae233cc003c2c62ccdc2e39e5f6e7678976022a3 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/fcntl.h @@ -0,0 +1,40 @@ +#define O_CREAT 0100 +#define O_EXCL 0200 +#define O_NOCTTY 0400 +#define O_TRUNC 01000 +#define O_APPEND 02000 +#define O_NONBLOCK 04000 +#define O_DSYNC 010000 +#define O_SYNC 04010000 +#define O_RSYNC 04010000 +#define O_DIRECTORY 0200000 +#define O_NOFOLLOW 0400000 +#define O_CLOEXEC 02000000 + +#define O_ASYNC 020000 +#define O_DIRECT 040000 +#define O_LARGEFILE 0100000 +#define O_NOATIME 01000000 +#define O_PATH 010000000 +#define O_TMPFILE 020200000 +#define O_NDELAY O_NONBLOCK + +#define F_DUPFD 0 +#define F_GETFD 1 +#define F_SETFD 2 +#define F_GETFL 3 +#define F_SETFL 4 + +#define F_SETOWN 8 +#define F_GETOWN 9 +#define F_SETSIG 10 +#define F_GETSIG 11 + +#define F_GETLK 12 +#define F_SETLK 13 +#define F_SETLKW 14 + +#define F_SETOWN_EX 15 +#define F_GETOWN_EX 16 + +#define F_GETOWNER_UIDS 17 diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/fenv.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/fenv.h new file mode 100644 index 0000000000000000000000000000000000000000..edbdea2a5efcda22054568550ef555acdf14cd35 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/fenv.h @@ -0,0 +1,10 @@ +#define FE_ALL_EXCEPT 0 +#define FE_TONEAREST 0 + +typedef unsigned long fexcept_t; + +typedef struct { + unsigned long __cw; +} fenv_t; + +#define FE_DFL_ENV ((const fenv_t *) -1) diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/hwcap.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/hwcap.h new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/io.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/io.h new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/ioctl.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/ioctl.h new file mode 100644 index 0000000000000000000000000000000000000000..60ae8b850b17b7ad5a658967e6d595188f63eba2 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/ioctl.h @@ -0,0 +1,115 @@ +#define _IOC(a,b,c,d) ( ((a)<<30) | ((b)<<8) | (c) | ((d)<<16) ) +#define _IOC_NONE 0U +#define _IOC_WRITE 1U +#define _IOC_READ 2U + +#define _IO(a,b) _IOC(_IOC_NONE,(a),(b),0) +#define _IOW(a,b,c) _IOC(_IOC_WRITE,(a),(b),sizeof(c)) +#define _IOR(a,b,c) _IOC(_IOC_READ,(a),(b),sizeof(c)) +#define _IOWR(a,b,c) _IOC(_IOC_READ|_IOC_WRITE,(a),(b),sizeof(c)) + +#define TCGETS 0x5401 +#define TCSETS 0x5402 +#define TCSETSW 0x5403 +#define TCSETSF 0x5404 +#define TCGETA 0x5405 +#define TCSETA 0x5406 +#define TCSETAW 0x5407 +#define TCSETAF 0x5408 +#define TCSBRK 0x5409 +#define TCXONC 0x540A +#define TCFLSH 0x540B +#define TIOCEXCL 0x540C +#define TIOCNXCL 0x540D +#define TIOCSCTTY 0x540E +#define TIOCGPGRP 0x540F +#define TIOCSPGRP 0x5410 +#define TIOCOUTQ 0x5411 +#define TIOCSTI 0x5412 +#define TIOCGWINSZ 0x5413 +#define TIOCSWINSZ 0x5414 +#define TIOCMGET 0x5415 +#define TIOCMBIS 0x5416 +#define TIOCMBIC 0x5417 +#define TIOCMSET 0x5418 +#define TIOCGSOFTCAR 0x5419 +#define TIOCSSOFTCAR 0x541A +#define FIONREAD 0x541B +#define TIOCINQ FIONREAD +#define TIOCLINUX 0x541C +#define TIOCCONS 0x541D +#define TIOCGSERIAL 0x541E +#define TIOCSSERIAL 0x541F +#define TIOCPKT 0x5420 +#define FIONBIO 0x5421 +#define TIOCNOTTY 0x5422 +#define TIOCSETD 0x5423 +#define TIOCGETD 0x5424 +#define TCSBRKP 0x5425 +#define TIOCSBRK 0x5427 +#define TIOCCBRK 0x5428 +#define TIOCGSID 0x5429 +#define TIOCGRS485 0x542E +#define TIOCSRS485 0x542F +#define TIOCGPTN 0x80045430 +#define TIOCSPTLCK 0x40045431 +#define TIOCGDEV 0x80045432 +#define TCGETX 0x5432 +#define TCSETX 0x5433 +#define TCSETXF 0x5434 +#define TCSETXW 0x5435 +#define TIOCSIG 0x40045436 +#define TIOCVHANGUP 0x5437 +#define TIOCGPKT 0x80045438 +#define TIOCGPTLCK 0x80045439 +#define TIOCGEXCL 0x80045440 +#define TIOCGPTPEER 0x5441 +#define TIOCGISO7816 0x80285442 +#define TIOCSISO7816 0xc0285443 + +#define FIONCLEX 0x5450 +#define FIOCLEX 0x5451 +#define FIOASYNC 0x5452 +#define TIOCSERCONFIG 0x5453 +#define TIOCSERGWILD 0x5454 +#define TIOCSERSWILD 0x5455 +#define TIOCGLCKTRMIOS 0x5456 +#define TIOCSLCKTRMIOS 0x5457 +#define TIOCSERGSTRUCT 0x5458 +#define TIOCSERGETLSR 0x5459 +#define TIOCSERGETMULTI 0x545A +#define TIOCSERSETMULTI 0x545B + +#define TIOCMIWAIT 0x545C +#define TIOCGICOUNT 0x545D +#define FIOQSIZE 0x5460 + +#define TIOCM_LE 0x001 +#define TIOCM_DTR 0x002 +#define TIOCM_RTS 0x004 +#define TIOCM_ST 0x008 +#define TIOCM_SR 0x010 +#define TIOCM_CTS 0x020 +#define TIOCM_CAR 0x040 +#define TIOCM_RNG 0x080 +#define TIOCM_DSR 0x100 +#define TIOCM_CD TIOCM_CAR +#define TIOCM_RI TIOCM_RNG +#define TIOCM_OUT1 0x2000 +#define TIOCM_OUT2 0x4000 +#define TIOCM_LOOP 0x8000 + +#define FIOSETOWN 0x8901 +#define SIOCSPGRP 0x8902 +#define FIOGETOWN 0x8903 +#define SIOCGPGRP 0x8904 +#define SIOCATMARK 0x8905 +#if __LONG_MAX == 0x7fffffff +#define SIOCGSTAMP _IOR(0x89, 6, char[16]) +#define SIOCGSTAMPNS _IOR(0x89, 7, char[16]) +#else +#define SIOCGSTAMP 0x8906 +#define SIOCGSTAMPNS 0x8907 +#endif + +#include diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/ioctl_fix.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/ioctl_fix.h new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/ipc.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/ipc.h new file mode 100644 index 0000000000000000000000000000000000000000..40d6f3a2587cf475469eb65b19af5a85e1a11d7f --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/ipc.h @@ -0,0 +1,11 @@ +struct ipc_perm { + key_t __ipc_perm_key; + uid_t uid; + gid_t gid; + uid_t cuid; + gid_t cgid; + mode_t mode; + int __ipc_perm_seq; + long __pad1; + long __pad2; +}; diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/ipcstat.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/ipcstat.h new file mode 100644 index 0000000000000000000000000000000000000000..0018ad1e20f62a4bb426908c9397ee1253954cd5 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/ipcstat.h @@ -0,0 +1 @@ +#define IPC_STAT 2 diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/kd.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/kd.h new file mode 100644 index 0000000000000000000000000000000000000000..33b873f49c2615e9b5dc0130b290bee2968b3cd4 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/kd.h @@ -0,0 +1 @@ +#include diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/limits.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/limits.h new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/link.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/link.h new file mode 100644 index 0000000000000000000000000000000000000000..4a94d8f895b16d645f7e7ff5cae86fb0f14b4a42 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/link.h @@ -0,0 +1 @@ +typedef uint32_t Elf_Symndx; diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/mman.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/mman.h new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/msg.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/msg.h new file mode 100644 index 0000000000000000000000000000000000000000..2e23ca27f580705efe87a0ab6e9742daaf047577 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/msg.h @@ -0,0 +1,12 @@ +struct msqid_ds { + struct ipc_perm msg_perm; + time_t msg_stime; + time_t msg_rtime; + time_t msg_ctime; + unsigned long msg_cbytes; + msgqnum_t msg_qnum; + msglen_t msg_qbytes; + pid_t msg_lspid; + pid_t msg_lrpid; + unsigned long __unused[2]; +}; diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/poll.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/poll.h new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/ptrace.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/ptrace.h new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/resource.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/resource.h new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/sem.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/sem.h new file mode 100644 index 0000000000000000000000000000000000000000..5184eb5977ece3775fe5f7a6659a83d6da24ca44 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/sem.h @@ -0,0 +1,14 @@ +struct semid_ds { + struct ipc_perm sem_perm; + time_t sem_otime; + time_t sem_ctime; +#if __BYTE_ORDER == __LITTLE_ENDIAN + unsigned short sem_nsems; + char __sem_nsems_pad[sizeof(long)-sizeof(short)]; +#else + char __sem_nsems_pad[sizeof(long)-sizeof(short)]; + unsigned short sem_nsems; +#endif + long __unused3; + long __unused4; +}; diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/shm.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/shm.h new file mode 100644 index 0000000000000000000000000000000000000000..8d19378191bacd8a43080a7f96027befcfd30e4c --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/shm.h @@ -0,0 +1,24 @@ +#define SHMLBA 4096 + +struct shmid_ds { + struct ipc_perm shm_perm; + size_t shm_segsz; + time_t shm_atime; + time_t shm_dtime; + time_t shm_ctime; + pid_t shm_cpid; + pid_t shm_lpid; + unsigned long shm_nattch; + unsigned long __pad1; + unsigned long __pad2; +}; + +struct shminfo { + unsigned long shmmax, shmmin, shmmni, shmseg, shmall, __unused[4]; +}; + +struct shm_info { + int __used_ids; + unsigned long shm_tot, shm_rss, shm_swp; + unsigned long __swap_attempts, __swap_successes; +}; diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/socket.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/socket.h new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/soundcard.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/soundcard.h new file mode 100644 index 0000000000000000000000000000000000000000..fade986fe42125d1fbe2916a9aceac4494df58ac --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/soundcard.h @@ -0,0 +1 @@ +#include diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/statfs.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/statfs.h new file mode 100644 index 0000000000000000000000000000000000000000..f103f4e4f4ef0cf545b49c192dee90f066ba3dab --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/statfs.h @@ -0,0 +1,7 @@ +struct statfs { + unsigned long f_type, f_bsize; + fsblkcnt_t f_blocks, f_bfree, f_bavail; + fsfilcnt_t f_files, f_ffree; + fsid_t f_fsid; + unsigned long f_namelen, f_frsize, f_flags, f_spare[4]; +}; diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/termios.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/termios.h new file mode 100644 index 0000000000000000000000000000000000000000..20bd6105e1d354656ca573f3c0d80884cc7e0f6c --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/termios.h @@ -0,0 +1,189 @@ +struct termios { + tcflag_t c_iflag; + tcflag_t c_oflag; + tcflag_t c_cflag; + tcflag_t c_lflag; + cc_t c_line; + cc_t c_cc[NCCS]; + speed_t __c_ispeed; + speed_t __c_ospeed; +}; + +#ifdef __LITEOS__ +struct termios2 { + tcflag_t c_iflag; + tcflag_t c_oflag; + tcflag_t c_cflag; + tcflag_t c_lflag; + cc_t c_line; + cc_t c_cc[NCCS]; + speed_t c_ispeed; + speed_t c_ospeed; +}; +struct ktermios { + tcflag_t c_iflag; + tcflag_t c_oflag; + tcflag_t c_cflag; + tcflag_t c_lflag; + cc_t c_line; + cc_t c_cc[NCCS]; + speed_t c_ispeed; + speed_t c_ospeed; +}; +#endif + +#define VINTR 0 +#define VQUIT 1 +#define VERASE 2 +#define VKILL 3 +#define VEOF 4 +#define VTIME 5 +#define VMIN 6 +#define VSWTC 7 +#define VSTART 8 +#define VSTOP 9 +#define VSUSP 10 +#define VEOL 11 +#define VREPRINT 12 +#define VDISCARD 13 +#define VWERASE 14 +#define VLNEXT 15 +#define VEOL2 16 + +#define IGNBRK 0000001 +#define BRKINT 0000002 +#define IGNPAR 0000004 +#define PARMRK 0000010 +#define INPCK 0000020 +#define ISTRIP 0000040 +#define INLCR 0000100 +#define IGNCR 0000200 +#define ICRNL 0000400 +#define IUCLC 0001000 +#define IXON 0002000 +#define IXANY 0004000 +#define IXOFF 0010000 +#define IMAXBEL 0020000 +#define IUTF8 0040000 + +#define OPOST 0000001 +#define OLCUC 0000002 +#define ONLCR 0000004 +#define OCRNL 0000010 +#define ONOCR 0000020 +#define ONLRET 0000040 +#define OFILL 0000100 +#define OFDEL 0000200 +#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE) || defined(_XOPEN_SOURCE) +#define NLDLY 0000400 +#define NL0 0000000 +#define NL1 0000400 +#define CRDLY 0003000 +#define CR0 0000000 +#define CR1 0001000 +#define CR2 0002000 +#define CR3 0003000 +#define TABDLY 0014000 +#define TAB0 0000000 +#define TAB1 0004000 +#define TAB2 0010000 +#define TAB3 0014000 +#define BSDLY 0020000 +#define BS0 0000000 +#define BS1 0020000 +#define FFDLY 0100000 +#define FF0 0000000 +#define FF1 0100000 +#endif + +#define VTDLY 0040000 +#define VT0 0000000 +#define VT1 0040000 + +#define B0 0000000 +#define B50 0000001 +#define B75 0000002 +#define B110 0000003 +#define B134 0000004 +#define B150 0000005 +#define B200 0000006 +#define B300 0000007 +#define B600 0000010 +#define B1200 0000011 +#define B1800 0000012 +#define B2400 0000013 +#define B4800 0000014 +#define B9600 0000015 +#define B19200 0000016 +#define B38400 0000017 + +#define B57600 0010001 +#define B115200 0010002 +#define B230400 0010003 +#define B460800 0010004 +#define B500000 0010005 +#define B576000 0010006 +#define B921600 0010007 +#define B1000000 0010010 +#define B1152000 0010011 +#define B1500000 0010012 +#define B2000000 0010013 +#define B2500000 0010014 +#define B3000000 0010015 +#define B3500000 0010016 +#define B4000000 0010017 + +#define CSIZE 0000060 +#define CS5 0000000 +#define CS6 0000020 +#define CS7 0000040 +#define CS8 0000060 +#define CSTOPB 0000100 +#define CREAD 0000200 +#define PARENB 0000400 +#define PARODD 0001000 +#define HUPCL 0002000 +#define CLOCAL 0004000 + +#define ISIG 0000001 +#define ICANON 0000002 +#define ECHO 0000010 +#define ECHOE 0000020 +#define ECHOK 0000040 +#define ECHONL 0000100 +#define NOFLSH 0000200 +#define TOSTOP 0000400 +#define IEXTEN 0100000 + +#define TCOOFF 0 +#define TCOON 1 +#define TCIOFF 2 +#define TCION 3 + +#define TCIFLUSH 0 +#define TCOFLUSH 1 +#define TCIOFLUSH 2 + +#define TCSANOW 0 +#define TCSADRAIN 1 +#define TCSAFLUSH 2 + +#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE) +#define EXTA 0000016 +#define EXTB 0000017 +#define CBAUD 0010017 +#define CBAUDEX 0010000 +#define CIBAUD 002003600000 +#define CMSPAR 010000000000 +#define CRTSCTS 020000000000 + +#define XCASE 0000004 +#define ECHOCTL 0001000 +#define ECHOPRT 0002000 +#define ECHOKE 0004000 +#define FLUSHO 0010000 +#define PENDIN 0040000 +#define EXTPROC 0200000 + +#define XTABS 0014000 +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/vt.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/vt.h new file mode 100644 index 0000000000000000000000000000000000000000..834abfbc8fbb42a1a08886e951095f0d763b5323 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/bits/vt.h @@ -0,0 +1 @@ +#include diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/fp_arch.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/generic/fp_arch.h new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/riscv32/atomic_arch.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/riscv32/atomic_arch.h new file mode 100644 index 0000000000000000000000000000000000000000..d19a7ca2da97d02c34d8cbad91dbb771a3e56907 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/riscv32/atomic_arch.h @@ -0,0 +1,21 @@ +#define a_barrier a_barrier +static inline void a_barrier(void) +{ + __asm__ __volatile__ ("fence rw,rw" : : : "memory"); +} + +#define a_ll a_ll +static inline int a_ll(volatile int *p) +{ + int v; + return v; +} + +#define a_sc a_sc +static inline int a_sc(volatile int *p, int v) +{ + int r = 0; + (void)p; + (void)v; + return !r; +} diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/riscv32/bits/float.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/riscv32/bits/float.h new file mode 100644 index 0000000000000000000000000000000000000000..c4a655e7b58c131274d2d558d3a85b167e14fa04 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/riscv32/bits/float.h @@ -0,0 +1,16 @@ +#define FLT_EVAL_METHOD 0 + +#define LDBL_TRUE_MIN 4.94065645841246544177e-324L +#define LDBL_MIN 2.22507385850720138309e-308L +#define LDBL_MAX 1.79769313486231570815e+308L +#define LDBL_EPSILON 2.22044604925031308085e-16L + +#define LDBL_MANT_DIG 53 +#define LDBL_MIN_EXP (-1021) +#define LDBL_MAX_EXP 1024 + +#define LDBL_DIG 15 +#define LDBL_MIN_10_EXP (-307) +#define LDBL_MAX_10_EXP 308 + +#define DECIMAL_DIG 17 diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/riscv32/bits/limits.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/riscv32/bits/limits.h new file mode 100644 index 0000000000000000000000000000000000000000..fbc6d238dc89b91dbe94af93ea60e862c67ac154 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/riscv32/bits/limits.h @@ -0,0 +1,7 @@ +#if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \ + || defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) || defined(_BSD_SOURCE) +#define LONG_BIT 32 +#endif + +#define LONG_MAX 0x7fffffffL +#define LLONG_MAX 0x7fffffffffffffffLL diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/riscv32/bits/posix.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/riscv32/bits/posix.h new file mode 100644 index 0000000000000000000000000000000000000000..7563df5d9d72b195d2669fb0e0580a2a2aaaad8f --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/riscv32/bits/posix.h @@ -0,0 +1,2 @@ +# define _POSIX_V6_ILP32_OFFBIG 1 +# define _POSIX_V7_ILP32_OFFBIG 1 diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/riscv32/bits/signal.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/riscv32/bits/signal.h new file mode 100644 index 0000000000000000000000000000000000000000..4763beeba7f9e8e9a7b45862f925e97aa8aba434 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/riscv32/bits/signal.h @@ -0,0 +1,36 @@ +#define SIGHUP 1 +#define SIGINT 2 +#define SIGQUIT 3 +#define SIGILL 4 +#define SIGTRAP 5 +#define SIGABRT 6 +#define SIGIOT SIGABRT +#define SIGBUS 7 +#define SIGFPE 8 +#define SIGKILL 9 +#define SIGUSR1 10 +#define SIGSEGV 11 +#define SIGUSR2 12 +#define SIGPIPE 13 +#define SIGALRM 14 +#define SIGTERM 15 +#define SIGSTKFLT 16 +#define SIGCHLD 17 +#define SIGCONT 18 +#define SIGSTOP 19 +#define SIGTSTP 20 +#define SIGTTIN 21 +#define SIGTTOU 22 +#define SIGURG 23 +#define SIGXCPU 24 +#define SIGXFSZ 25 +#define SIGVTALRM 26 +#define SIGPROF 27 +#define SIGWINCH 28 +#define SIGIO 29 +#define SIGPOLL SIGIO +#define SIGPWR 30 +#define SIGSYS 31 +#define SIGUNUSED SIGSYS + +#define _NSIG 65 diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/riscv32/bits/stat.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/riscv32/bits/stat.h new file mode 100644 index 0000000000000000000000000000000000000000..f09cae6313ba2450760cdadc3dbbe610d9e74c4c --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/riscv32/bits/stat.h @@ -0,0 +1,22 @@ +struct stat { + dev_t st_dev; + ino_t st_ino; + mode_t st_mode; + nlink_t st_nlink; + uid_t st_uid; + gid_t st_gid; + dev_t st_rdev; + unsigned long __pad; +#ifdef __LITEOS__ + long long st_size; +#else + off_t st_size; +#endif + blksize_t st_blksize; + int __pad2; + blkcnt_t st_blocks; + struct timespec st_atim; + struct timespec st_mtim; + struct timespec st_ctim; + unsigned __unused[2]; +}; diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/riscv32/bits/stdint.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/riscv32/bits/stdint.h new file mode 100644 index 0000000000000000000000000000000000000000..d1b2712199acabb2e597bfeb1850f3e0216705d0 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/riscv32/bits/stdint.h @@ -0,0 +1,20 @@ +typedef int32_t int_fast16_t; +typedef int32_t int_fast32_t; +typedef uint32_t uint_fast16_t; +typedef uint32_t uint_fast32_t; + +#define INT_FAST16_MIN INT32_MIN +#define INT_FAST32_MIN INT32_MIN + +#define INT_FAST16_MAX INT32_MAX +#define INT_FAST32_MAX INT32_MAX + +#define UINT_FAST16_MAX UINT32_MAX +#define UINT_FAST32_MAX UINT32_MAX + +#define INTPTR_MIN INT32_MIN +#define INTPTR_MAX INT32_MAX +#define UINTPTR_MAX UINT32_MAX +#define PTRDIFF_MIN INT32_MIN +#define PTRDIFF_MAX INT32_MAX +#define SIZE_MAX UINT32_MAX diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/riscv32/pthread_arch.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/riscv32/pthread_arch.h new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/riscv32/syscall_arch.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/riscv32/syscall_arch.h new file mode 100644 index 0000000000000000000000000000000000000000..bc60d1f6203d2de51b8d927f85c70243df2c7f0e --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/arch/riscv32/syscall_arch.h @@ -0,0 +1,78 @@ +#define __SYSCALL_LL_E(x) \ +((union { long long ll; long l[2]; }){ .ll = x }).l[0], \ +((union { long long ll; long l[2]; }){ .ll = x }).l[1] +#define __SYSCALL_LL_O(x) 0, __SYSCALL_LL_E((x)) + +#define __asm_syscall(...) \ + __asm__ __volatile__ ("scall\n\t" \ + : "+r"(a0) : __VA_ARGS__ : "memory"); \ + return a0; \ + +static inline long __syscall0(long n) +{ + register long a7 __asm__("a7") = n; + register long a0 __asm__("a0"); + __asm_syscall("r"(a7)) +} + +static inline long __syscall1(long n, long a) +{ + register long a7 __asm__("a7") = n; + register long a0 __asm__("a0") = a; + __asm_syscall("r"(a7), "0"(a0)) +} + +static inline long __syscall2(long n, long a, long b) +{ + register long a7 __asm__("a7") = n; + register long a0 __asm__("a0") = a; + register long a1 __asm__("a1") = b; + __asm_syscall("r"(a7), "0"(a0), "r"(a1)) +} + +static inline long __syscall3(long n, long a, long b, long c) +{ + register long a7 __asm__("a7") = n; + register long a0 __asm__("a0") = a; + register long a1 __asm__("a1") = b; + register long a2 __asm__("a2") = c; + __asm_syscall("r"(a7), "0"(a0), "r"(a1), "r"(a2)) +} + +static inline long __syscall4(long n, long a, long b, long c, long d) +{ + register long a7 __asm__("a7") = n; + register long a0 __asm__("a0") = a; + register long a1 __asm__("a1") = b; + register long a2 __asm__("a2") = c; + register long a3 __asm__("a3") = d; + __asm_syscall("r"(a7), "0"(a0), "r"(a1), "r"(a2), "r"(a3)) +} + +static inline long __syscall5(long n, long a, long b, long c, long d, long e) +{ + register long a7 __asm__("a7") = n; + register long a0 __asm__("a0") = a; + register long a1 __asm__("a1") = b; + register long a2 __asm__("a2") = c; + register long a3 __asm__("a3") = d; + register long a4 __asm__("a4") = e; + __asm_syscall("r"(a7), "0"(a0), "r"(a1), "r"(a2), "r"(a3), "r"(a4)) +} + +static inline long __syscall6(long n, long a, long b, long c, long d, long e, long f) +{ + register long a7 __asm__("a7") = n; + register long a0 __asm__("a0") = a; + register long a1 __asm__("a1") = b; + register long a2 __asm__("a2") = c; + register long a3 __asm__("a3") = d; + register long a4 __asm__("a4") = e; + register long a5 __asm__("a5") = f; + __asm_syscall("r"(a7), "0"(a0), "r"(a1), "r"(a2), "r"(a3), "r"(a4), "r"(a5)) +} + +#define VDSO_USEFUL +/* We don't have a clock_gettime function. +#define VDSO_CGT_SYM "__vdso_clock_gettime" +#define VDSO_CGT_VER "LINUX_2.6" */ diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/aio.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/aio.h new file mode 100644 index 0000000000000000000000000000000000000000..7fcac55c59f7f7252264757278134c6d04757d56 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/aio.h @@ -0,0 +1,80 @@ +#ifndef _AIO_H +#define _AIO_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include + +#define __NEED_ssize_t +#define __NEED_off_t +#ifdef __LITEOS__ +#define __NEED_int64_t +#endif + +#include + +struct aiocb { + int aio_fildes, aio_lio_opcode, aio_reqprio; + volatile void *aio_buf; + size_t aio_nbytes; + struct sigevent aio_sigevent; + void *__td; + int __lock[2]; + volatile int __err; + ssize_t __ret; + off_t aio_offset; + void *__next, *__prev; + char __dummy4[32-2*sizeof(void *)]; +}; + +#define AIO_CANCELED 0 +#define AIO_NOTCANCELED 1 +#define AIO_ALLDONE 2 + +#define LIO_READ 0 +#define LIO_WRITE 1 +#define LIO_NOP 2 + +#define LIO_WAIT 0 +#define LIO_NOWAIT 1 + +int aio_read(struct aiocb *); +int aio_write(struct aiocb *); +int aio_error(const struct aiocb *); +ssize_t aio_return(struct aiocb *); +int aio_cancel(int, struct aiocb *); +int aio_suspend(const struct aiocb *const [], int, const struct timespec *); +int aio_fsync(int, struct aiocb *); + +int lio_listio(int, struct aiocb *__restrict const *__restrict, int, struct sigevent *__restrict); + +#if defined(_LARGEFILE64_SOURCE) || defined(_GNU_SOURCE) +#define aiocb64 aiocb +#define aio_read64 aio_read +#define aio_write64 aio_write +#define aio_error64 aio_error +#define aio_return64 aio_return +#define aio_cancel64 aio_cancel +#define aio_suspend64 aio_suspend +#define aio_fsync64 aio_fsync +#define lio_listio64 lio_listio +#ifdef __LITEOS__ +#define off64_t int64_t +#else +#define off64_t off_t +#endif +#endif + +#if _REDIR_TIME64 +__REDIR(aio_suspend, __aio_suspend_time64); +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/alloca.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/alloca.h new file mode 100644 index 0000000000000000000000000000000000000000..b8d183d144efad9bbe6aa94516bfe6ee6c5aa098 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/alloca.h @@ -0,0 +1,19 @@ +#ifndef _ALLOCA_H +#define _ALLOCA_H + +#ifdef __cplusplus +extern "C" { +#endif + +#define __NEED_size_t +#include + +void *alloca(size_t); + +#define alloca __builtin_alloca + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/ar.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/ar.h new file mode 100644 index 0000000000000000000000000000000000000000..eafd51d0e785360ff1e3d1aec673afb19fad1b70 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/ar.h @@ -0,0 +1,25 @@ +#ifndef _AR_H +#define _AR_H + +#ifdef __cplusplus +extern "C" { +#endif + +#define ARMAG "!\n" +#define SARMAG 8 +#define ARFMAG "`\n" + +struct ar_hdr { + char ar_name[16]; + char ar_date[12]; + char ar_uid[6], ar_gid[6]; + char ar_mode[8]; + char ar_size[10]; + char ar_fmag[2]; +}; + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/arpa/ftp.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/arpa/ftp.h new file mode 100644 index 0000000000000000000000000000000000000000..fb0a46f2b879423290365cda85892a587f89929b --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/arpa/ftp.h @@ -0,0 +1,35 @@ +#ifndef _ARPA_FTP_H +#define _ARPA_FTP_H +#define PRELIM 1 +#define COMPLETE 2 +#define CONTINUE 3 +#define TRANSIENT 4 +#define ERROR 5 +#define TYPE_A 1 +#define TYPE_E 2 +#define TYPE_I 3 +#define TYPE_L 4 +#define FORM_N 1 +#define FORM_T 2 +#define FORM_C 3 +#define STRU_F 1 +#define STRU_R 2 +#define STRU_P 3 +#define MODE_S 1 +#define MODE_B 2 +#define MODE_C 3 +#define REC_ESC '\377' +#define REC_EOR '\001' +#define REC_EOF '\002' +#define BLK_EOR 0x80 +#define BLK_EOF 0x40 +#define BLK_ERRORS 0x20 +#define BLK_RESTART 0x10 +#define BLK_BYTECOUNT 2 +#ifdef FTP_NAMES +char *modenames[] = {"0", "Stream", "Block", "Compressed" }; +char *strunames[] = {"0", "File", "Record", "Page" }; +char *typenames[] = {"0", "ASCII", "EBCDIC", "Image", "Local" }; +char *formnames[] = {"0", "Nonprint", "Telnet", "Carriage-control" }; +#endif +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/arpa/inet.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/arpa/inet.h new file mode 100644 index 0000000000000000000000000000000000000000..14421c9cce87d3a7da19e08e1330518df914bb68 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/arpa/inet.h @@ -0,0 +1,180 @@ +/** + * @defgroup inet Inet + * @ingroup libc + */ + +#ifndef _ARPA_INET_H +#define _ARPA_INET_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include + +uint32_t htonl(uint32_t); +uint16_t htons(uint16_t); +uint32_t ntohl(uint32_t); +uint16_t ntohs(uint16_t); + +/** + * @ingroup inet + * + * @par Description: + * This function is used to convert the IPv4 address from string notation (number and dot format) + * to binary notation of network byte order. + * + * @param cp [IN] Pointer to IPv4 address string. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval #in_addr_t On success, in unsigned int (32bit) format. + * @retval #IPADDR_NONE On failure. + * + * @par Dependency: + *
  • inet.h
+ * + * @see inet_aton + * + */ +in_addr_t inet_addr (const char *); +in_addr_t inet_network (const char *); + +/** + * @ingroup inet + * + * @par Description: + * This function is used to convert the IPv4 address from binary notation (network byte order) + * to string notation (number and dot format). + * + * @param in [IN] Pointer to binary notation of IPv4 address. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval #char* On success, returns pointer to string notation of IPv4 address. + * @retval #NULL On failure. + * + * @par Dependency: + *
  • inet.h
+ * + * @see inet_ntop + * + */ +char *inet_ntoa (struct in_addr); + +/** + * @ingroup inet + * + * @par Description: + * This function is used to convert the character string src into a network address + * structure in the af address family, then copies the network address structure to dst. + * The af argument must be AF_INET. + * + * @param af [IN] Address family. + * @param src [IN] Pointer to IPv4 address string. + * @param dst [OUT] Result string of IPv4 address will be udpated here. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval #1 On success, network address was successfully converted. + * @retval #0 On failure, if src does not contain a character string representing a + * valid network address in the specified address family. + * @retval #-1 On failure, if af does not contain a valid address family. + * + * @par Errors + *
    + *
  • EAFNOSUPPORT: Address family not supported.
  • + *
+ * + * @par Dependency: + *
  • inet.h
+ * + * @see inet_ntop + * + */ +int inet_pton (int, const char *__restrict, void *__restrict); + +/** + * @ingroup inet + * + * @par Description: + * This function is used to convert the network address structure src in the af address family into a character string. + * The resulting string is copied to the buffer pointed to by dst, which must be a non-null pointer. + * The caller specifies the number of bytes available in this buffer in the argument size. + * + * @param af [IN] Address family. + * @param src [IN] Pointer to IPv4 address string. + * @param size [IN] Size of IPv4 address string. + * @param dst [OUT] Result string of IPv4 address will be udpated here. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval #char* On success, returns pointer to string notation of IPv4 address. + * @retval #NULL On failure. + * + * @par Errors + *
    + *
  • EAFNOSUPPORT: Address family not supported.
  • + *
+ * + * @par Dependency: + *
  • inet.h
+ * + * @see inet_pton + * + */ +const char *inet_ntop (int, const void *__restrict, char *__restrict, socklen_t); + +/** + * @ingroup inet + * + * @par Description: + * This function is used to convert the IPv4 address from string notation (number and dot format) + * to binary notation of network byte order and stores it in the structure that addr points to. + * + * @param cp [IN] Pointer to IPv4 address string. + * @param inp [OUT] Generated binary notation of IPv4 address will be udpated here. + * + * @attention + *
    + *
  • This interface is same as inet_addr(). Only difference is that the generated binary notation + * of IPv4 address is updated in the input parameter "inp", instead of returning it.
  • + *
+ * + * @retval #1 On success. + * @retval #0 On failure. + * + * @par Dependency: + *
  • inet.h
+ * + * @see inet_addr + * + */ +int inet_aton (const char *, struct in_addr *); +struct in_addr inet_makeaddr(in_addr_t, in_addr_t); +in_addr_t inet_lnaof(struct in_addr); +in_addr_t inet_netof(struct in_addr); + +#undef INET_ADDRSTRLEN +#undef INET6_ADDRSTRLEN +#define INET_ADDRSTRLEN 16 +#define INET6_ADDRSTRLEN 46 + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/arpa/nameser.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/arpa/nameser.h new file mode 100644 index 0000000000000000000000000000000000000000..581925a43367ae19bfa9cff25bcc022b098f37b6 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/arpa/nameser.h @@ -0,0 +1,455 @@ +#ifndef _ARPA_NAMESER_H +#define _ARPA_NAMESER_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include + +#define __NAMESER 19991006 +#define NS_PACKETSZ 512 +#define NS_MAXDNAME 1025 +#define NS_MAXMSG 65535 +#define NS_MAXCDNAME 255 +#define NS_MAXLABEL 63 +#define NS_HFIXEDSZ 12 +#define NS_QFIXEDSZ 4 +#define NS_RRFIXEDSZ 10 +#define NS_INT32SZ 4 +#define NS_INT16SZ 2 +#define NS_INT8SZ 1 +#define NS_INADDRSZ 4 +#define NS_IN6ADDRSZ 16 +#define NS_CMPRSFLGS 0xc0 +#define NS_DEFAULTPORT 53 + +typedef enum __ns_sect { + ns_s_qd = 0, + ns_s_zn = 0, + ns_s_an = 1, + ns_s_pr = 1, + ns_s_ns = 2, + ns_s_ud = 2, + ns_s_ar = 3, + ns_s_max = 4 +} ns_sect; + +typedef struct __ns_msg { + const unsigned char *_msg, *_eom; + uint16_t _id, _flags, _counts[ns_s_max]; + const unsigned char *_sections[ns_s_max]; + ns_sect _sect; + int _rrnum; + const unsigned char *_msg_ptr; +} ns_msg; + +struct _ns_flagdata { int mask, shift; }; +extern const struct _ns_flagdata _ns_flagdata[]; + +#define ns_msg_id(handle) ((handle)._id + 0) +#define ns_msg_base(handle) ((handle)._msg + 0) +#define ns_msg_end(handle) ((handle)._eom + 0) +#define ns_msg_size(handle) ((handle)._eom - (handle)._msg) +#define ns_msg_count(handle, section) ((handle)._counts[section] + 0) +#define ns_msg_getflag(handle, flag) \ + (((handle)._flags & _ns_flagdata[flag].mask) >> _ns_flagdata[flag].shift) + +typedef struct __ns_rr { + char name[NS_MAXDNAME]; + uint16_t type; + uint16_t rr_class; + uint32_t ttl; + uint16_t rdlength; + const unsigned char *rdata; +} ns_rr; + +#define ns_rr_name(rr) (((rr).name[0] != '\0') ? (rr).name : ".") +#define ns_rr_type(rr) ((ns_type)((rr).type + 0)) +#define ns_rr_class(rr) ((ns_class)((rr).rr_class + 0)) +#define ns_rr_ttl(rr) ((rr).ttl + 0) +#define ns_rr_rdlen(rr) ((rr).rdlength + 0) +#define ns_rr_rdata(rr) ((rr).rdata + 0) + +typedef enum __ns_flag { + ns_f_qr, + ns_f_opcode, + ns_f_aa, + ns_f_tc, + ns_f_rd, + ns_f_ra, + ns_f_z, + ns_f_ad, + ns_f_cd, + ns_f_rcode, + ns_f_max +} ns_flag; + +typedef enum __ns_opcode { + ns_o_query = 0, + ns_o_iquery = 1, + ns_o_status = 2, + ns_o_notify = 4, + ns_o_update = 5, + ns_o_max = 6 +} ns_opcode; + +typedef enum __ns_rcode { + ns_r_noerror = 0, + ns_r_formerr = 1, + ns_r_servfail = 2, + ns_r_nxdomain = 3, + ns_r_notimpl = 4, + ns_r_refused = 5, + ns_r_yxdomain = 6, + ns_r_yxrrset = 7, + ns_r_nxrrset = 8, + ns_r_notauth = 9, + ns_r_notzone = 10, + ns_r_max = 11, + ns_r_badvers = 16, + ns_r_badsig = 16, + ns_r_badkey = 17, + ns_r_badtime = 18 +} ns_rcode; + +typedef enum __ns_update_operation { + ns_uop_delete = 0, + ns_uop_add = 1, + ns_uop_max = 2 +} ns_update_operation; + +struct ns_tsig_key { + char name[NS_MAXDNAME], alg[NS_MAXDNAME]; + unsigned char *data; + int len; +}; +typedef struct ns_tsig_key ns_tsig_key; + +struct ns_tcp_tsig_state { + int counter; + struct dst_key *key; + void *ctx; + unsigned char sig[NS_PACKETSZ]; + int siglen; +}; +typedef struct ns_tcp_tsig_state ns_tcp_tsig_state; + +#define NS_TSIG_FUDGE 300 +#define NS_TSIG_TCP_COUNT 100 +#define NS_TSIG_ALG_HMAC_MD5 "HMAC-MD5.SIG-ALG.REG.INT" + +#define NS_TSIG_ERROR_NO_TSIG -10 +#define NS_TSIG_ERROR_NO_SPACE -11 +#define NS_TSIG_ERROR_FORMERR -12 + +typedef enum __ns_type { + ns_t_invalid = 0, + ns_t_a = 1, + ns_t_ns = 2, + ns_t_md = 3, + ns_t_mf = 4, + ns_t_cname = 5, + ns_t_soa = 6, + ns_t_mb = 7, + ns_t_mg = 8, + ns_t_mr = 9, + ns_t_null = 10, + ns_t_wks = 11, + ns_t_ptr = 12, + ns_t_hinfo = 13, + ns_t_minfo = 14, + ns_t_mx = 15, + ns_t_txt = 16, + ns_t_rp = 17, + ns_t_afsdb = 18, + ns_t_x25 = 19, + ns_t_isdn = 20, + ns_t_rt = 21, + ns_t_nsap = 22, + ns_t_nsap_ptr = 23, + ns_t_sig = 24, + ns_t_key = 25, + ns_t_px = 26, + ns_t_gpos = 27, + ns_t_aaaa = 28, + ns_t_loc = 29, + ns_t_nxt = 30, + ns_t_eid = 31, + ns_t_nimloc = 32, + ns_t_srv = 33, + ns_t_atma = 34, + ns_t_naptr = 35, + ns_t_kx = 36, + ns_t_cert = 37, + ns_t_a6 = 38, + ns_t_dname = 39, + ns_t_sink = 40, + ns_t_opt = 41, + ns_t_apl = 42, + ns_t_tkey = 249, + ns_t_tsig = 250, + ns_t_ixfr = 251, + ns_t_axfr = 252, + ns_t_mailb = 253, + ns_t_maila = 254, + ns_t_any = 255, + ns_t_zxfr = 256, + ns_t_max = 65536 +} ns_type; + +#define ns_t_qt_p(t) (ns_t_xfr_p(t) || (t) == ns_t_any || \ + (t) == ns_t_mailb || (t) == ns_t_maila) +#define ns_t_mrr_p(t) ((t) == ns_t_tsig || (t) == ns_t_opt) +#define ns_t_rr_p(t) (!ns_t_qt_p(t) && !ns_t_mrr_p(t)) +#define ns_t_udp_p(t) ((t) != ns_t_axfr && (t) != ns_t_zxfr) +#define ns_t_xfr_p(t) ((t) == ns_t_axfr || (t) == ns_t_ixfr || \ + (t) == ns_t_zxfr) + +typedef enum __ns_class { + ns_c_invalid = 0, + ns_c_in = 1, + ns_c_2 = 2, + ns_c_chaos = 3, + ns_c_hs = 4, + ns_c_none = 254, + ns_c_any = 255, + ns_c_max = 65536 +} ns_class; + +typedef enum __ns_key_types { + ns_kt_rsa = 1, + ns_kt_dh = 2, + ns_kt_dsa = 3, + ns_kt_private = 254 +} ns_key_types; + +typedef enum __ns_cert_types { + cert_t_pkix = 1, + cert_t_spki = 2, + cert_t_pgp = 3, + cert_t_url = 253, + cert_t_oid = 254 +} ns_cert_types; + +#define NS_KEY_TYPEMASK 0xC000 +#define NS_KEY_TYPE_AUTH_CONF 0x0000 +#define NS_KEY_TYPE_CONF_ONLY 0x8000 +#define NS_KEY_TYPE_AUTH_ONLY 0x4000 +#define NS_KEY_TYPE_NO_KEY 0xC000 +#define NS_KEY_NO_AUTH 0x8000 +#define NS_KEY_NO_CONF 0x4000 +#define NS_KEY_RESERVED2 0x2000 +#define NS_KEY_EXTENDED_FLAGS 0x1000 +#define NS_KEY_RESERVED4 0x0800 +#define NS_KEY_RESERVED5 0x0400 +#define NS_KEY_NAME_TYPE 0x0300 +#define NS_KEY_NAME_USER 0x0000 +#define NS_KEY_NAME_ENTITY 0x0200 +#define NS_KEY_NAME_ZONE 0x0100 +#define NS_KEY_NAME_RESERVED 0x0300 +#define NS_KEY_RESERVED8 0x0080 +#define NS_KEY_RESERVED9 0x0040 +#define NS_KEY_RESERVED10 0x0020 +#define NS_KEY_RESERVED11 0x0010 +#define NS_KEY_SIGNATORYMASK 0x000F +#define NS_KEY_RESERVED_BITMASK ( NS_KEY_RESERVED2 | \ + NS_KEY_RESERVED4 | \ + NS_KEY_RESERVED5 | \ + NS_KEY_RESERVED8 | \ + NS_KEY_RESERVED9 | \ + NS_KEY_RESERVED10 | \ + NS_KEY_RESERVED11 ) +#define NS_KEY_RESERVED_BITMASK2 0xFFFF +#define NS_ALG_MD5RSA 1 +#define NS_ALG_DH 2 +#define NS_ALG_DSA 3 +#define NS_ALG_DSS NS_ALG_DSA +#define NS_ALG_EXPIRE_ONLY 253 +#define NS_ALG_PRIVATE_OID 254 + +#define NS_KEY_PROT_TLS 1 +#define NS_KEY_PROT_EMAIL 2 +#define NS_KEY_PROT_DNSSEC 3 +#define NS_KEY_PROT_IPSEC 4 +#define NS_KEY_PROT_ANY 255 + +#define NS_MD5RSA_MIN_BITS 512 +#define NS_MD5RSA_MAX_BITS 4096 +#define NS_MD5RSA_MAX_BYTES ((NS_MD5RSA_MAX_BITS+7/8)*2+3) +#define NS_MD5RSA_MAX_BASE64 (((NS_MD5RSA_MAX_BYTES+2)/3)*4) +#define NS_MD5RSA_MIN_SIZE ((NS_MD5RSA_MIN_BITS+7)/8) +#define NS_MD5RSA_MAX_SIZE ((NS_MD5RSA_MAX_BITS+7)/8) + +#define NS_DSA_SIG_SIZE 41 +#define NS_DSA_MIN_SIZE 213 +#define NS_DSA_MAX_BYTES 405 + +#define NS_SIG_TYPE 0 +#define NS_SIG_ALG 2 +#define NS_SIG_LABELS 3 +#define NS_SIG_OTTL 4 +#define NS_SIG_EXPIR 8 +#define NS_SIG_SIGNED 12 +#define NS_SIG_FOOT 16 +#define NS_SIG_SIGNER 18 +#define NS_NXT_BITS 8 +#define NS_NXT_BIT_SET( n,p) (p[(n)/NS_NXT_BITS] |= (0x80>>((n)%NS_NXT_BITS))) +#define NS_NXT_BIT_CLEAR(n,p) (p[(n)/NS_NXT_BITS] &= ~(0x80>>((n)%NS_NXT_BITS))) +#define NS_NXT_BIT_ISSET(n,p) (p[(n)/NS_NXT_BITS] & (0x80>>((n)%NS_NXT_BITS))) +#define NS_NXT_MAX 127 + +#define NS_OPT_DNSSEC_OK 0x8000U +#define NS_OPT_NSID 3 + +#define NS_GET16(s, cp) (void)((s) = ns_get16(((cp)+=2)-2)) +#define NS_GET32(l, cp) (void)((l) = ns_get32(((cp)+=4)-4)) +#define NS_PUT16(s, cp) ns_put16((s), ((cp)+=2)-2) +#define NS_PUT32(l, cp) ns_put32((l), ((cp)+=4)-4) + +unsigned ns_get16(const unsigned char *); +unsigned long ns_get32(const unsigned char *); +void ns_put16(unsigned, unsigned char *); +void ns_put32(unsigned long, unsigned char *); + +int ns_initparse(const unsigned char *, int, ns_msg *); +int ns_parserr(ns_msg *, ns_sect, int, ns_rr *); +int ns_skiprr(const unsigned char *, const unsigned char *, ns_sect, int); +int ns_name_uncompress(const unsigned char *, const unsigned char *, const unsigned char *, char *, size_t); + + +#define __BIND 19950621 + +typedef struct { + unsigned id :16; +#if __BYTE_ORDER == __BIG_ENDIAN + unsigned qr: 1; + unsigned opcode: 4; + unsigned aa: 1; + unsigned tc: 1; + unsigned rd: 1; + unsigned ra: 1; + unsigned unused :1; + unsigned ad: 1; + unsigned cd: 1; + unsigned rcode :4; +#else + unsigned rd :1; + unsigned tc :1; + unsigned aa :1; + unsigned opcode :4; + unsigned qr :1; + unsigned rcode :4; + unsigned cd: 1; + unsigned ad: 1; + unsigned unused :1; + unsigned ra :1; +#endif + unsigned qdcount :16; + unsigned ancount :16; + unsigned nscount :16; + unsigned arcount :16; +} HEADER; + +#define PACKETSZ NS_PACKETSZ +#define MAXDNAME NS_MAXDNAME +#define MAXCDNAME NS_MAXCDNAME +#define MAXLABEL NS_MAXLABEL +#define HFIXEDSZ NS_HFIXEDSZ +#define QFIXEDSZ NS_QFIXEDSZ +#define RRFIXEDSZ NS_RRFIXEDSZ +#define INT32SZ NS_INT32SZ +#define INT16SZ NS_INT16SZ +#define INT8SZ NS_INT8SZ +#define INADDRSZ NS_INADDRSZ +#define IN6ADDRSZ NS_IN6ADDRSZ +#define INDIR_MASK NS_CMPRSFLGS +#define NAMESERVER_PORT NS_DEFAULTPORT + +#define S_ZONE ns_s_zn +#define S_PREREQ ns_s_pr +#define S_UPDATE ns_s_ud +#define S_ADDT ns_s_ar + +#define QUERY ns_o_query +#define IQUERY ns_o_iquery +#define STATUS ns_o_status +#define NS_NOTIFY_OP ns_o_notify +#define NS_UPDATE_OP ns_o_update + +#define NOERROR ns_r_noerror +#define FORMERR ns_r_formerr +#define SERVFAIL ns_r_servfail +#define NXDOMAIN ns_r_nxdomain +#define NOTIMP ns_r_notimpl +#define REFUSED ns_r_refused +#define YXDOMAIN ns_r_yxdomain +#define YXRRSET ns_r_yxrrset +#define NXRRSET ns_r_nxrrset +#define NOTAUTH ns_r_notauth +#define NOTZONE ns_r_notzone + +#define DELETE ns_uop_delete +#define ADD ns_uop_add + +#define T_A ns_t_a +#define T_NS ns_t_ns +#define T_MD ns_t_md +#define T_MF ns_t_mf +#define T_CNAME ns_t_cname +#define T_SOA ns_t_soa +#define T_MB ns_t_mb +#define T_MG ns_t_mg +#define T_MR ns_t_mr +#define T_NULL ns_t_null +#define T_WKS ns_t_wks +#define T_PTR ns_t_ptr +#define T_HINFO ns_t_hinfo +#define T_MINFO ns_t_minfo +#define T_MX ns_t_mx +#define T_TXT ns_t_txt +#define T_RP ns_t_rp +#define T_AFSDB ns_t_afsdb +#define T_X25 ns_t_x25 +#define T_ISDN ns_t_isdn +#define T_RT ns_t_rt +#define T_NSAP ns_t_nsap +#define T_NSAP_PTR ns_t_nsap_ptr +#define T_SIG ns_t_sig +#define T_KEY ns_t_key +#define T_PX ns_t_px +#define T_GPOS ns_t_gpos +#define T_AAAA ns_t_aaaa +#define T_LOC ns_t_loc +#define T_NXT ns_t_nxt +#define T_EID ns_t_eid +#define T_NIMLOC ns_t_nimloc +#define T_SRV ns_t_srv +#define T_ATMA ns_t_atma +#define T_NAPTR ns_t_naptr +#define T_A6 ns_t_a6 +#define T_DNAME ns_t_dname +#define T_TSIG ns_t_tsig +#define T_IXFR ns_t_ixfr +#define T_AXFR ns_t_axfr +#define T_MAILB ns_t_mailb +#define T_MAILA ns_t_maila +#define T_ANY ns_t_any + +#define C_IN ns_c_in +#define C_CHAOS ns_c_chaos +#define C_HS ns_c_hs +#define C_NONE ns_c_none +#define C_ANY ns_c_any + +#define GETSHORT NS_GET16 +#define GETLONG NS_GET32 +#define PUTSHORT NS_PUT16 +#define PUTLONG NS_PUT32 + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/arpa/nameser_compat.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/arpa/nameser_compat.h new file mode 100644 index 0000000000000000000000000000000000000000..3aac25c98b50ab58abab357b91d43e916483daf7 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/arpa/nameser_compat.h @@ -0,0 +1,2 @@ +#include + diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/arpa/telnet.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/arpa/telnet.h new file mode 100644 index 0000000000000000000000000000000000000000..e2ad97429520738e307a52bdbe90c9aaf0b1eccf --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/arpa/telnet.h @@ -0,0 +1,251 @@ +#ifndef _ARPA_TELNET_H +#define _ARPA_TELNET_H + +#define IAC 255 +#define DONT 254 +#define DO 253 +#define WONT 252 +#define WILL 251 +#define SB 250 +#define GA 249 +#define EL 248 +#define EC 247 +#define AYT 246 +#define AO 245 +#define IP 244 +#define BREAK 243 +#define DM 242 +#define NOP 241 +#define SE 240 +#define EOR 239 +#define ABORT 238 +#define SUSP 237 +#define xEOF 236 + +#define SYNCH 242 + +#define telcmds ((char [][6]){ "EOF", "SUSP", "ABORT", "EOR", "SE", "NOP", "DMARK", "BRK", "IP", "AO", "AYT", "EC", "EL", "GA", "SB", "WILL", "WONT", "DO", "DONT", "IAC", 0 }) + +#define TELCMD_FIRST xEOF +#define TELCMD_LAST IAC +#define TELCMD_OK(x) ((unsigned int)(x) <= TELCMD_LAST && \ + (unsigned int)(x) >= TELCMD_FIRST) +#define TELCMD(x) telcmds[(x)-TELCMD_FIRST] + +#define TELOPT_BINARY 0 +#define TELOPT_ECHO 1 +#define TELOPT_RCP 2 +#define TELOPT_SGA 3 +#define TELOPT_NAMS 4 +#define TELOPT_STATUS 5 +#define TELOPT_TM 6 +#define TELOPT_RCTE 7 +#define TELOPT_NAOL 8 +#define TELOPT_NAOP 9 +#define TELOPT_NAOCRD 10 +#define TELOPT_NAOHTS 11 +#define TELOPT_NAOHTD 12 +#define TELOPT_NAOFFD 13 +#define TELOPT_NAOVTS 14 +#define TELOPT_NAOVTD 15 +#define TELOPT_NAOLFD 16 +#define TELOPT_XASCII 17 +#define TELOPT_LOGOUT 18 +#define TELOPT_BM 19 +#define TELOPT_DET 20 +#define TELOPT_SUPDUP 21 +#define TELOPT_SUPDUPOUTPUT 22 +#define TELOPT_SNDLOC 23 +#define TELOPT_TTYPE 24 +#define TELOPT_EOR 25 +#define TELOPT_TUID 26 +#define TELOPT_OUTMRK 27 +#define TELOPT_TTYLOC 28 +#define TELOPT_3270REGIME 29 +#define TELOPT_X3PAD 30 +#define TELOPT_NAWS 31 +#define TELOPT_TSPEED 32 +#define TELOPT_LFLOW 33 +#define TELOPT_LINEMODE 34 +#define TELOPT_XDISPLOC 35 +#define TELOPT_OLD_ENVIRON 36 +#define TELOPT_AUTHENTICATION 37/* Authenticate */ +#define TELOPT_ENCRYPT 38 +#define TELOPT_NEW_ENVIRON 39 +#define TELOPT_EXOPL 255 + + +#define NTELOPTS (1+TELOPT_NEW_ENVIRON) +#ifdef TELOPTS +char *telopts[NTELOPTS+1] = { + "BINARY", "ECHO", "RCP", "SUPPRESS GO AHEAD", "NAME", + "STATUS", "TIMING MARK", "RCTE", "NAOL", "NAOP", + "NAOCRD", "NAOHTS", "NAOHTD", "NAOFFD", "NAOVTS", + "NAOVTD", "NAOLFD", "EXTEND ASCII", "LOGOUT", "BYTE MACRO", + "DATA ENTRY TERMINAL", "SUPDUP", "SUPDUP OUTPUT", + "SEND LOCATION", "TERMINAL TYPE", "END OF RECORD", + "TACACS UID", "OUTPUT MARKING", "TTYLOC", + "3270 REGIME", "X.3 PAD", "NAWS", "TSPEED", "LFLOW", + "LINEMODE", "XDISPLOC", "OLD-ENVIRON", "AUTHENTICATION", + "ENCRYPT", "NEW-ENVIRON", + 0, +}; +#define TELOPT_FIRST TELOPT_BINARY +#define TELOPT_LAST TELOPT_NEW_ENVIRON +#define TELOPT_OK(x) ((unsigned int)(x) <= TELOPT_LAST) +#define TELOPT(x) telopts[(x)-TELOPT_FIRST] +#endif + +#define TELQUAL_IS 0 +#define TELQUAL_SEND 1 +#define TELQUAL_INFO 2 +#define TELQUAL_REPLY 2 +#define TELQUAL_NAME 3 + +#define LFLOW_OFF 0 +#define LFLOW_ON 1 +#define LFLOW_RESTART_ANY 2 +#define LFLOW_RESTART_XON 3 + + +#define LM_MODE 1 +#define LM_FORWARDMASK 2 +#define LM_SLC 3 + +#define MODE_EDIT 0x01 +#define MODE_TRAPSIG 0x02 +#define MODE_ACK 0x04 +#define MODE_SOFT_TAB 0x08 +#define MODE_LIT_ECHO 0x10 + +#define MODE_MASK 0x1f + +#define MODE_FLOW 0x0100 +#define MODE_ECHO 0x0200 +#define MODE_INBIN 0x0400 +#define MODE_OUTBIN 0x0800 +#define MODE_FORCE 0x1000 + +#define SLC_SYNCH 1 +#define SLC_BRK 2 +#define SLC_IP 3 +#define SLC_AO 4 +#define SLC_AYT 5 +#define SLC_EOR 6 +#define SLC_ABORT 7 +#define SLC_EOF 8 +#define SLC_SUSP 9 +#define SLC_EC 10 +#define SLC_EL 11 +#define SLC_EW 12 +#define SLC_RP 13 +#define SLC_LNEXT 14 +#define SLC_XON 15 +#define SLC_XOFF 16 +#define SLC_FORW1 17 +#define SLC_FORW2 18 + +#define NSLC 18 + +#define SLC_NAMELIST "0", "SYNCH", "BRK", "IP", "AO", "AYT", "EOR", \ + "ABORT", "EOF", "SUSP", "EC", "EL", "EW", "RP", \ + "LNEXT", "XON", "XOFF", "FORW1", "FORW2", 0, +#ifdef SLC_NAMES +char *slc_names[] = { + SLC_NAMELIST +}; +#else +extern char *slc_names[]; +#define SLC_NAMES SLC_NAMELIST +#endif + +#define SLC_NAME_OK(x) ((unsigned int)(x) <= NSLC) +#define SLC_NAME(x) slc_names[x] + +#define SLC_NOSUPPORT 0 +#define SLC_CANTCHANGE 1 +#define SLC_VARIABLE 2 +#define SLC_DEFAULT 3 +#define SLC_LEVELBITS 0x03 + +#define SLC_FUNC 0 +#define SLC_FLAGS 1 +#define SLC_VALUE 2 + +#define SLC_ACK 0x80 +#define SLC_FLUSHIN 0x40 +#define SLC_FLUSHOUT 0x20 + +#define OLD_ENV_VAR 1 +#define OLD_ENV_VALUE 0 +#define NEW_ENV_VAR 0 +#define NEW_ENV_VALUE 1 +#define ENV_ESC 2 +#define ENV_USERVAR 3 + +#define AUTH_WHO_CLIENT 0 +#define AUTH_WHO_SERVER 1 +#define AUTH_WHO_MASK 1 + +#define AUTH_HOW_ONE_WAY 0 +#define AUTH_HOW_MUTUAL 2 +#define AUTH_HOW_MASK 2 + +#define AUTHTYPE_NULL 0 +#define AUTHTYPE_KERBEROS_V4 1 +#define AUTHTYPE_KERBEROS_V5 2 +#define AUTHTYPE_SPX 3 +#define AUTHTYPE_MINK 4 +#define AUTHTYPE_CNT 5 + +#define AUTHTYPE_TEST 99 + +#ifdef AUTH_NAMES +char *authtype_names[] = { + "NULL", "KERBEROS_V4", "KERBEROS_V5", "SPX", "MINK", 0, +}; +#else +extern char *authtype_names[]; +#endif + +#define AUTHTYPE_NAME_OK(x) ((unsigned int)(x) < AUTHTYPE_CNT) +#define AUTHTYPE_NAME(x) authtype_names[x] + +#define ENCRYPT_IS 0 +#define ENCRYPT_SUPPORT 1 +#define ENCRYPT_REPLY 2 +#define ENCRYPT_START 3 +#define ENCRYPT_END 4 +#define ENCRYPT_REQSTART 5 +#define ENCRYPT_REQEND 6 +#define ENCRYPT_ENC_KEYID 7 +#define ENCRYPT_DEC_KEYID 8 +#define ENCRYPT_CNT 9 + +#define ENCTYPE_ANY 0 +#define ENCTYPE_DES_CFB64 1 +#define ENCTYPE_DES_OFB64 2 +#define ENCTYPE_CNT 3 + +#ifdef ENCRYPT_NAMES +char *encrypt_names[] = { + "IS", "SUPPORT", "REPLY", "START", "END", + "REQUEST-START", "REQUEST-END", "ENC-KEYID", "DEC-KEYID", + 0, +}; +char *enctype_names[] = { + "ANY", "DES_CFB64", "DES_OFB64", 0, +}; +#else +extern char *encrypt_names[]; +extern char *enctype_names[]; +#endif + + +#define ENCRYPT_NAME_OK(x) ((unsigned int)(x) < ENCRYPT_CNT) +#define ENCRYPT_NAME(x) encrypt_names[x] + +#define ENCTYPE_NAME_OK(x) ((unsigned int)(x) < ENCTYPE_CNT) +#define ENCTYPE_NAME(x) enctype_names[x] + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/arpa/tftp.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/arpa/tftp.h new file mode 100644 index 0000000000000000000000000000000000000000..799c54f2217e0671ea1c676fbfe50ed6304d7dbb --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/arpa/tftp.h @@ -0,0 +1,31 @@ +#ifndef _ARPA_TFTP_H +#define _ARPA_TFTP_H +#define SEGSIZE 512 +#define RRQ 01 +#define WRQ 02 +#define DATA 03 +#define ACK 04 +#define ERROR 05 +struct tftphdr { + short th_opcode; + union { + unsigned short tu_block; + short tu_code; + char tu_stuff[1]; + } th_u; + char th_data[1]; +}; +#define th_block th_u.tu_block +#define th_code th_u.tu_code +#define th_stuff th_u.tu_stuff +#define th_msg th_data +#define EUNDEF 0 +#define ENOTFOUND 1 +#define EACCESS 2 +#define ENOSPACE 3 +#define EBADOP 4 +#define EBADID 5 +#define EEXISTS 6 +#define ENOUSER 7 +#endif + diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/assert.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/assert.h new file mode 100644 index 0000000000000000000000000000000000000000..4d36b1ae81abb1e9b2133cb02875f5de3cad993f --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/assert.h @@ -0,0 +1,51 @@ +#include + +#undef assert + + +/** + * @ingroup assert + * @par Description: + * This API is used to insert diagnostics into programs, if expression is false, it will output the text of the argument, + * the name of the source file, the source file line number, and the name of the enclosing function + * + * @attention + *
    + *
  • The assert() macro only prints an error message, it would not call abort,instead by locking the interrupt and entering dead cycle by doing while (1).
  • + *
+ * + * @retval None. + * + * @par Dependency: + *
  • assert.h
+ * + * @see None + * + */ +#ifdef NDEBUG +#define assert(x) (void)0 +#else +#define assert(x) ((void)((x) || (__assert_fail(#x, __FILE__, __LINE__, __func__),0))) +#endif + +#ifdef __LITEOS__ +#ifdef CONFIG_DEBUG +#define DEBUGASSERT(f) ((void)((f) || (__assert_fail(#f, __FILE__, __LINE__, __func__),0))) +#else +#define DEBUGASSERT(f) +#endif +#endif + +#if __STDC_VERSION__ >= 201112L && !defined(__cplusplus) +#define static_assert _Static_assert +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +_Noreturn void __assert_fail (const char *, const char *, int, const char *); + +#ifdef __cplusplus +} +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/bits/alltypes.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/bits/alltypes.h new file mode 100644 index 0000000000000000000000000000000000000000..7c41272901415e65ffc132d3322bb52591e91b0e --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/bits/alltypes.h @@ -0,0 +1,454 @@ +#define _REDIR_TIME64 0 +#if defined(__LP64__) +#define _Addr long +#define _Int64 long +#define _Reg long +#else +#define _Addr int +#define _Int64 long long +#define _Reg int +#endif +#define __BYTE_ORDER 1234 +#if defined(__LP64__) +#define __LONG_MAX 0x7fffffffffffffffL +#else +#define __LONG_MAX 0x7fffffffL +#endif + +#ifndef __cplusplus +#if defined(__NEED_wchar_t) && !defined(__DEFINED_wchar_t) +#ifdef __riscv +typedef int wchar_t; +#else +/* array of inappropriate type initialized from string constant in It_libwc_iswgraph_001.c */ +typedef unsigned wchar_t; +#endif +#define __DEFINED_wchar_t +#endif + +#endif +#if defined(__NEED_wint_t) && !defined(__DEFINED_wint_t) +typedef unsigned wint_t; +#define __DEFINED_wint_t +#endif + + +#if defined(__NEED_blksize_t) && !defined(__DEFINED_blksize_t) +typedef int blksize_t; +#define __DEFINED_blksize_t +#endif + +#if defined(__NEED_nlink_t) && !defined(__DEFINED_nlink_t) +typedef unsigned int nlink_t; +#define __DEFINED_nlink_t +#endif + + +#if defined(__NEED_float_t) && !defined(__DEFINED_float_t) +typedef float float_t; +#define __DEFINED_float_t +#endif + +#if defined(__NEED_double_t) && !defined(__DEFINED_double_t) +typedef double double_t; +#define __DEFINED_double_t +#endif + +/* conflict with value.h in 3rdParty/jsoncpp */ +#ifndef __LITEOS__ +#if defined(__NEED_max_align_t) && !defined(__DEFINED_max_align_t) +typedef struct { long long __ll; long double __ld; } max_align_t; +#define __DEFINED_max_align_t +#endif +#endif + +/* rom and cant be modified */ +#if defined(__NEED_suseconds_t) && !defined(__DEFINED_suseconds_t) +typedef long suseconds_t; +#define __DEFINED_suseconds_t +#endif + +#define __LITTLE_ENDIAN 1234 +#define __BIG_ENDIAN 4321 +#define __USE_TIME_BITS64 1 + +#if defined(__NEED_size_t) && !defined(__DEFINED_size_t) +typedef unsigned _Addr size_t; +#define __DEFINED_size_t +#endif + +#if defined(__NEED_uintptr_t) && !defined(__DEFINED_uintptr_t) +typedef unsigned _Addr uintptr_t; +#define __DEFINED_uintptr_t +#endif + +#if defined(__NEED_ptrdiff_t) && !defined(__DEFINED_ptrdiff_t) +typedef _Addr ptrdiff_t; +#define __DEFINED_ptrdiff_t +#endif + +#if defined(__NEED_ssize_t) && !defined(__DEFINED_ssize_t) +typedef _Addr ssize_t; +#define __DEFINED_ssize_t +#endif + +#if defined(__NEED_intptr_t) && !defined(__DEFINED_intptr_t) +typedef _Addr intptr_t; +#define __DEFINED_intptr_t +#endif + +#if defined(__NEED_regoff_t) && !defined(__DEFINED_regoff_t) +typedef _Addr regoff_t; +#define __DEFINED_regoff_t +#endif + +#if defined(__NEED_register_t) && !defined(__DEFINED_register_t) +typedef _Reg register_t; +#define __DEFINED_register_t +#endif + +#if defined(__LP64__) +#if defined(__NEED_time_t) && !defined(__DEFINED_time_t) +typedef _Int64 time_t; +#define __DEFINED_time_t +#endif +#else +#if defined(__NEED_time_t) && !defined(__DEFINED_time_t) +typedef long time_t; +#define __DEFINED_time_t +#endif +#endif + + +#if defined(__NEED_int8_t) && !defined(__DEFINED_int8_t) +typedef signed char int8_t; +#define __DEFINED_int8_t +#endif + +#if defined(__NEED_int16_t) && !defined(__DEFINED_int16_t) +typedef signed short int16_t; +#define __DEFINED_int16_t +#endif + +#if defined(__NEED_int32_t) && !defined(__DEFINED_int32_t) +typedef signed int int32_t; +#define __DEFINED_int32_t +#endif + +#if defined(__NEED_int64_t) && !defined(__DEFINED_int64_t) +typedef signed _Int64 int64_t; +#define __DEFINED_int64_t +#endif + +#if defined(__NEED_intmax_t) && !defined(__DEFINED_intmax_t) +typedef signed _Int64 intmax_t; +#define __DEFINED_intmax_t +#endif + +#if defined(__NEED_uint8_t) && !defined(__DEFINED_uint8_t) +typedef unsigned char uint8_t; +#define __DEFINED_uint8_t +#endif + +#if defined(__NEED_uint16_t) && !defined(__DEFINED_uint16_t) +typedef unsigned short uint16_t; +#define __DEFINED_uint16_t +#endif + +#if defined(__NEED_uint32_t) && !defined(__DEFINED_uint32_t) +typedef unsigned int uint32_t; +#define __DEFINED_uint32_t +#endif + +#if defined(__NEED_uint64_t) && !defined(__DEFINED_uint64_t) +typedef unsigned _Int64 uint64_t; +#define __DEFINED_uint64_t +#endif + +#if defined(__NEED_u_int64_t) && !defined(__DEFINED_u_int64_t) +typedef unsigned _Int64 u_int64_t; +#define __DEFINED_u_int64_t +#endif + +#if defined(__NEED_uintmax_t) && !defined(__DEFINED_uintmax_t) +typedef unsigned _Int64 uintmax_t; +#define __DEFINED_uintmax_t +#endif + + +#if defined(__NEED_mode_t) && !defined(__DEFINED_mode_t) +typedef unsigned mode_t; +#define __DEFINED_mode_t +#endif + +#if defined(__NEED_nlink_t) && !defined(__DEFINED_nlink_t) +typedef unsigned _Reg nlink_t; +#define __DEFINED_nlink_t +#endif + +#if defined(__NEED_off_t) && !defined(__DEFINED_off_t) +#ifdef __LITEOS__ +#if defined(__LP64__) +typedef _Int64 off_t; +#else +typedef long off_t; +#endif +#else +typedef _Int64 off_t; +#endif +#define __DEFINED_off_t +#endif + +#if defined(__NEED_ino_t) && !defined(__DEFINED_ino_t) +typedef unsigned _Int64 ino_t; +#define __DEFINED_ino_t +#endif + +#if defined(__NEED_dev_t) && !defined(__DEFINED_dev_t) +typedef unsigned _Int64 dev_t; +#define __DEFINED_dev_t +#endif + +#if defined(__NEED_blksize_t) && !defined(__DEFINED_blksize_t) +typedef long blksize_t; +#define __DEFINED_blksize_t +#endif + +#if defined(__NEED_blkcnt_t) && !defined(__DEFINED_blkcnt_t) +typedef _Int64 blkcnt_t; +#define __DEFINED_blkcnt_t +#endif + +#if defined(__NEED_fsblkcnt_t) && !defined(__DEFINED_fsblkcnt_t) +typedef unsigned _Int64 fsblkcnt_t; +#define __DEFINED_fsblkcnt_t +#endif + +#if defined(__NEED_fsfilcnt_t) && !defined(__DEFINED_fsfilcnt_t) +typedef unsigned _Int64 fsfilcnt_t; +#define __DEFINED_fsfilcnt_t +#endif + + +#if defined(__NEED_wint_t) && !defined(__DEFINED_wint_t) +typedef unsigned wint_t; +#define __DEFINED_wint_t +#endif + +#if defined(__NEED_wctype_t) && !defined(__DEFINED_wctype_t) +typedef unsigned long wctype_t; +#define __DEFINED_wctype_t +#endif + + +#if defined(__NEED_timer_t) && !defined(__DEFINED_timer_t) +typedef void * timer_t; +#define __DEFINED_timer_t +#endif + +#if defined(__NEED_clockid_t) && !defined(__DEFINED_clockid_t) +typedef int clockid_t; +#define __DEFINED_clockid_t +#endif + +#if defined(__NEED_clock_t) && !defined(__DEFINED_clock_t) +typedef long clock_t; +#define __DEFINED_clock_t +#endif + +#if defined(__NEED_struct_timeval) && !defined(__DEFINED_struct_timeval) +struct timeval { time_t tv_sec; suseconds_t tv_usec; }; +#define __DEFINED_struct_timeval +#endif + +#if defined(__NEED_struct_timespec) && !defined(__DEFINED_struct_timespec) +struct timespec { time_t tv_sec; int :8*(sizeof(time_t)-sizeof(long))*(__BYTE_ORDER==4321); long tv_nsec; int :8*(sizeof(time_t)-sizeof(long))*(__BYTE_ORDER!=4321); }; +#define __DEFINED_struct_timespec +#endif + + +#if defined(__NEED_pid_t) && !defined(__DEFINED_pid_t) +typedef int pid_t; +#define __DEFINED_pid_t +#endif + +#if defined(__NEED_id_t) && !defined(__DEFINED_id_t) +typedef unsigned id_t; +#define __DEFINED_id_t +#endif + +#if defined(__NEED_uid_t) && !defined(__DEFINED_uid_t) +typedef unsigned uid_t; +#define __DEFINED_uid_t +#endif + +#if defined(__NEED_gid_t) && !defined(__DEFINED_gid_t) +typedef unsigned gid_t; +#define __DEFINED_gid_t +#endif + +#if defined(__NEED_key_t) && !defined(__DEFINED_key_t) +typedef int key_t; +#define __DEFINED_key_t +#endif + +#if defined(__NEED_useconds_t) && !defined(__DEFINED_useconds_t) +typedef unsigned useconds_t; +#define __DEFINED_useconds_t +#endif + + +#ifdef __cplusplus +#if defined(__NEED_pthread_t) && !defined(__DEFINED_pthread_t) +typedef unsigned long pthread_t; +#define __DEFINED_pthread_t +#endif + +#else +#if defined(__NEED_pthread_t) && !defined(__DEFINED_pthread_t) +#ifndef __LITEOS__ +typedef struct __pthread * pthread_t; +#else +typedef long pthread_t; +#endif +#define __DEFINED_pthread_t +#endif + +#endif +#if defined(__NEED_pthread_once_t) && !defined(__DEFINED_pthread_once_t) +typedef int pthread_once_t; +#define __DEFINED_pthread_once_t +#endif + +#if defined(__NEED_pthread_key_t) && !defined(__DEFINED_pthread_key_t) +typedef unsigned pthread_key_t; +#define __DEFINED_pthread_key_t +#endif + +#if defined(__NEED_pthread_spinlock_t) && !defined(__DEFINED_pthread_spinlock_t) +typedef int pthread_spinlock_t; +#define __DEFINED_pthread_spinlock_t +#endif + +#ifndef __LITEOS__ +#if defined(__NEED_pthread_mutexattr_t) && !defined(__DEFINED_pthread_mutexattr_t) +typedef struct { unsigned __attr; } pthread_mutexattr_t; +#define __DEFINED_pthread_mutexattr_t +#endif + +#if defined(__NEED_pthread_condattr_t) && !defined(__DEFINED_pthread_condattr_t) +typedef struct { unsigned __attr; } pthread_condattr_t; +#define __DEFINED_pthread_condattr_t +#endif +#endif + +#if defined(__NEED_pthread_barrierattr_t) && !defined(__DEFINED_pthread_barrierattr_t) +typedef struct { unsigned __attr; } pthread_barrierattr_t; +#define __DEFINED_pthread_barrierattr_t +#endif + +#if defined(__NEED_pthread_rwlockattr_t) && !defined(__DEFINED_pthread_rwlockattr_t) +typedef struct { unsigned __attr[2]; } pthread_rwlockattr_t; +#define __DEFINED_pthread_rwlockattr_t +#endif + + +#if defined(__NEED_struct__IO_FILE) && !defined(__DEFINED_struct__IO_FILE) +struct _IO_FILE { char __x; }; +#define __DEFINED_struct__IO_FILE +#endif + +#if defined(__NEED_FILE) && !defined(__DEFINED_FILE) +typedef struct _IO_FILE FILE; +#define __DEFINED_FILE +#endif + + +#if defined(__NEED_va_list) && !defined(__DEFINED_va_list) +typedef __builtin_va_list va_list; +#define __DEFINED_va_list +#endif + +#if defined(__NEED___isoc_va_list) && !defined(__DEFINED___isoc_va_list) +typedef __builtin_va_list __isoc_va_list; +#define __DEFINED___isoc_va_list +#endif + + +#if defined(__NEED_mbstate_t) && !defined(__DEFINED_mbstate_t) +typedef struct __mbstate_t { unsigned __opaque1, __opaque2; } mbstate_t; +#define __DEFINED_mbstate_t +#endif + + +#if defined(__NEED_locale_t) && !defined(__DEFINED_locale_t) +typedef struct __locale_struct * locale_t; +#define __DEFINED_locale_t +#endif + + +#if defined(__NEED_sigset_t) && !defined(__DEFINED_sigset_t) +typedef struct __sigset_t { unsigned long __bits[128/sizeof(long)]; } sigset_t; +#define __DEFINED_sigset_t +#endif + + +#if defined(__NEED_struct_iovec) && !defined(__DEFINED_struct_iovec) +struct iovec { void *iov_base; size_t iov_len; }; +#define __DEFINED_struct_iovec +#endif + + +#if defined(__NEED_socklen_t) && !defined(__DEFINED_socklen_t) +typedef unsigned socklen_t; +#define __DEFINED_socklen_t +#endif + +#if defined(__NEED_sa_family_t) && !defined(__DEFINED_sa_family_t) +typedef unsigned short sa_family_t; +#define __DEFINED_sa_family_t +#endif + +#ifndef __LITEOS__ +#if defined(__NEED_pthread_attr_t) && !defined(__DEFINED_pthread_attr_t) +typedef struct { union { int __i[sizeof(long)==8?14:9]; volatile int __vi[sizeof(long)==8?14:9]; unsigned long __s[sizeof(long)==8?7:9]; } __u; } pthread_attr_t; +#define __DEFINED_pthread_attr_t +#endif + +#if defined(__NEED_pthread_mutex_t) && !defined(__DEFINED_pthread_mutex_t) +typedef struct { union { int __i[sizeof(long)==8?10:6]; volatile int __vi[sizeof(long)==8?10:6]; volatile void *volatile __p[sizeof(long)==8?5:6]; } __u; } pthread_mutex_t; +#define __DEFINED_pthread_mutex_t +#endif +#endif + +#if defined(__NEED_mtx_t) && !defined(__DEFINED_mtx_t) +typedef struct { union { int __i[sizeof(long)==8?10:6]; volatile int __vi[sizeof(long)==8?10:6]; volatile void *volatile __p[sizeof(long)==8?5:6]; } __u; } mtx_t; +#define __DEFINED_mtx_t +#endif + +#ifndef __LITEOS__ +#if defined(__NEED_pthread_cond_t) && !defined(__DEFINED_pthread_cond_t) +typedef struct { union { int __i[12]; volatile int __vi[12]; void *__p[12*sizeof(int)/sizeof(void*)]; } __u; } pthread_cond_t; +#define __DEFINED_pthread_cond_t +#endif +#endif + +#if defined(__NEED_cnd_t) && !defined(__DEFINED_cnd_t) +typedef struct { union { int __i[12]; volatile int __vi[12]; void *__p[12*sizeof(int)/sizeof(void*)]; } __u; } cnd_t; +#define __DEFINED_cnd_t +#endif + +#if defined(__NEED_pthread_rwlock_t) && !defined(__DEFINED_pthread_rwlock_t) +typedef struct { union { int __i[sizeof(long)==8?14:8]; volatile int __vi[sizeof(long)==8?14:8]; void *__p[sizeof(long)==8?7:8]; } __u; } pthread_rwlock_t; +#define __DEFINED_pthread_rwlock_t +#endif + +#if defined(__NEED_pthread_barrier_t) && !defined(__DEFINED_pthread_barrier_t) +typedef struct { union { int __i[sizeof(long)==8?8:5]; volatile int __vi[sizeof(long)==8?8:5]; void *__p[sizeof(long)==8?4:5]; } __u; } pthread_barrier_t; +#define __DEFINED_pthread_barrier_t +#endif + + +#undef _Addr +#undef _Int64 +#undef _Reg diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/bits/setjmp.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/bits/setjmp.h new file mode 100644 index 0000000000000000000000000000000000000000..54bc2610c95c70998159cfa5dc8aae26f9846ea8 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/bits/setjmp.h @@ -0,0 +1 @@ +typedef unsigned long __jmp_buf[22]; diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/bits/syscall.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/bits/syscall.h new file mode 100644 index 0000000000000000000000000000000000000000..2965823fa9331a953d7182e8336189325b442b70 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/bits/syscall.h @@ -0,0 +1,555 @@ +#define __NR_io_setup 0 +#define __NR_io_destroy 1 +#define __NR_io_submit 2 +#define __NR_io_cancel 3 +#define __NR_io_getevents 4 +#define __NR_setxattr 5 +#define __NR_lsetxattr 6 +#define __NR_fsetxattr 7 +#define __NR_getxattr 8 +#define __NR_lgetxattr 9 +#define __NR_fgetxattr 10 +#define __NR_listxattr 11 +#define __NR_llistxattr 12 +#define __NR_flistxattr 13 +#define __NR_removexattr 14 +#define __NR_lremovexattr 15 +#define __NR_fremovexattr 16 +#define __NR_getcwd 17 +#define __NR_lookup_dcookie 18 +#define __NR_eventfd2 19 +#define __NR_epoll_create1 20 +#define __NR_epoll_ctl 21 +#define __NR_epoll_pwait 22 +#define __NR_dup 23 +#define __NR_dup3 24 +#define __NR_fcntl 25 +#define __NR_inotify_init1 26 +#define __NR_inotify_add_watch 27 +#define __NR_inotify_rm_watch 28 +#define __NR_ioctl 29 +#define __NR_ioprio_set 30 +#define __NR_ioprio_get 31 +#define __NR_flock 32 +#define __NR_mknodat 33 +#define __NR_mkdirat 34 +#define __NR_unlinkat 35 +#define __NR_symlinkat 36 +#define __NR_linkat 37 +#define __NR_renameat 38 +#define __NR_umount2 39 +#define __NR_mount 40 +#define __NR_pivot_root 41 +#define __NR_nfsservctl 42 +#define __NR_statfs 43 +#define __NR_fstatfs 44 +#define __NR_truncate 45 +#define __NR_ftruncate 46 +#define __NR_fallocate 47 +#define __NR_faccessat 48 +#define __NR_chdir 49 +#define __NR_fchdir 50 +#define __NR_chroot 51 +#define __NR_fchmod 52 +#define __NR_fchmodat 53 +#define __NR_fchownat 54 +#define __NR_fchown 55 +#define __NR_openat 56 +#define __NR_close 57 +#define __NR_vhangup 58 +#define __NR_pipe2 59 +#define __NR_quotactl 60 +#define __NR_getdents64 61 +#define __NR_lseek 62 +#define __NR_read 63 +#define __NR_write 64 +#define __NR_readv 65 +#define __NR_writev 66 +#define __NR_pread64 67 +#define __NR_pwrite64 68 +#define __NR_preadv 69 +#define __NR_pwritev 70 +#define __NR_sendfile 71 +#define __NR_pselect6 72 +#define __NR_ppoll 73 +#define __NR_signalfd4 74 +#define __NR_vmsplice 75 +#define __NR_splice 76 +#define __NR_tee 77 +#define __NR_readlinkat 78 +#define __NR_fstatat 79 +#define __NR_fstat 80 +#define __NR_sync 81 +#define __NR_fsync 82 +#define __NR_fdatasync 83 +#define __NR_sync_file_range 84 +#define __NR_timerfd_create 85 +#define __NR_timerfd_settime 86 +#define __NR_timerfd_gettime 87 +#define __NR_utimensat 88 +#define __NR_acct 89 +#define __NR_capget 90 +#define __NR_capset 91 +#define __NR_personality 92 +#define __NR_exit 93 +#define __NR_exit_group 94 +#define __NR_waitid 95 +#define __NR_set_tid_address 96 +#define __NR_unshare 97 +#define __NR_futex 98 +#define __NR_set_robust_list 99 +#define __NR_get_robust_list 100 +#define __NR_nanosleep 101 +#define __NR_getitimer 102 +#define __NR_setitimer 103 +#define __NR_kexec_load 104 +#define __NR_init_module 105 +#define __NR_delete_module 106 +#define __NR_timer_create 107 +#define __NR_timer_gettime 108 +#define __NR_timer_getoverrun 109 +#define __NR_timer_settime 110 +#define __NR_timer_delete 111 +#define __NR_clock_settime 112 +#define __NR_clock_gettime 113 +#define __NR_clock_getres 114 +#define __NR_clock_nanosleep 115 +#define __NR_syslog 116 +#define __NR_ptrace 117 +#define __NR_sched_setparam 118 +#define __NR_sched_setscheduler 119 +#define __NR_sched_getscheduler 120 +#define __NR_sched_getparam 121 +#define __NR_sched_setaffinity 122 +#define __NR_sched_getaffinity 123 +#define __NR_sched_yield 124 +#define __NR_sched_get_priority_max 125 +#define __NR_sched_get_priority_min 126 +#define __NR_sched_rr_get_interval 127 +#define __NR_restart_syscall 128 +#define __NR_kill 129 +#define __NR_tkill 130 +#define __NR_tgkill 131 +#define __NR_sigaltstack 132 +#define __NR_rt_sigsuspend 133 +#define __NR_rt_sigaction 134 +#define __NR_rt_sigprocmask 135 +#define __NR_rt_sigpending 136 +#define __NR_rt_sigtimedwait 137 +#define __NR_rt_sigqueueinfo 138 +#define __NR_rt_sigreturn 139 +#define __NR_setpriority 140 +#define __NR_getpriority 141 +#define __NR_reboot 142 +#define __NR_setregid 143 +#define __NR_setgid 144 +#define __NR_setreuid 145 +#define __NR_setuid 146 +#define __NR_setresuid 147 +#define __NR_getresuid 148 +#define __NR_setresgid 149 +#define __NR_getresgid 150 +#define __NR_setfsuid 151 +#define __NR_setfsgid 152 +#define __NR_times 153 +#define __NR_setpgid 154 +#define __NR_getpgid 155 +#define __NR_getsid 156 +#define __NR_setsid 157 +#define __NR_getgroups 158 +#define __NR_setgroups 159 +#define __NR_uname 160 +#define __NR_sethostname 161 +#define __NR_setdomainname 162 +#define __NR_getrlimit 163 +#define __NR_setrlimit 164 +#define __NR_getrusage 165 +#define __NR_umask 166 +#define __NR_prctl 167 +#define __NR_getcpu 168 +#define __NR_gettimeofday 169 +#define __NR_settimeofday 170 +#define __NR_adjtimex 171 +#define __NR_getpid 172 +#define __NR_getppid 173 +#define __NR_getuid 174 +#define __NR_geteuid 175 +#define __NR_getgid 176 +#define __NR_getegid 177 +#define __NR_gettid 178 +#define __NR_sysinfo 179 +#define __NR_mq_open 180 +#define __NR_mq_unlink 181 +#define __NR_mq_timedsend 182 +#define __NR_mq_timedreceive 183 +#define __NR_mq_notify 184 +#define __NR_mq_getsetattr 185 +#define __NR_msgget 186 +#define __NR_msgctl 187 +#define __NR_msgrcv 188 +#define __NR_msgsnd 189 +#define __NR_semget 190 +#define __NR_semctl 191 +#define __NR_semtimedop 192 +#define __NR_semop 193 +#define __NR_shmget 194 +#define __NR_shmctl 195 +#define __NR_shmat 196 +#define __NR_shmdt 197 +#define __NR_socket 198 +#define __NR_socketpair 199 +#define __NR_bind 200 +#define __NR_listen 201 +#define __NR_accept 202 +#define __NR_connect 203 +#define __NR_getsockname 204 +#define __NR_getpeername 205 +#define __NR_sendto 206 +#define __NR_recvfrom 207 +#define __NR_setsockopt 208 +#define __NR_getsockopt 209 +#define __NR_shutdown 210 +#define __NR_sendmsg 211 +#define __NR_recvmsg 212 +#define __NR_readahead 213 +#define __NR_brk 214 +#define __NR_munmap 215 +#define __NR_mremap 216 +#define __NR_add_key 217 +#define __NR_request_key 218 +#define __NR_keyctl 219 +#define __NR_clone 220 +#define __NR_execve 221 +#define __NR_mmap 222 +#define __NR_fadvise64 223 +#define __NR_swapon 224 +#define __NR_swapoff 225 +#define __NR_mprotect 226 +#define __NR_msync 227 +#define __NR_mlock 228 +#define __NR_munlock 229 +#define __NR_mlockall 230 +#define __NR_munlockall 231 +#define __NR_mincore 232 +#define __NR_madvise 233 +#define __NR_remap_file_pages 234 +#define __NR_mbind 235 +#define __NR_get_mempolicy 236 +#define __NR_set_mempolicy 237 +#define __NR_migrate_pages 238 +#define __NR_move_pages 239 +#define __NR_rt_tgsigqueueinfo 240 +#define __NR_perf_event_open 241 +#define __NR_accept4 242 +#define __NR_recvmmsg 243 +#define __NR_arch_specific_syscall 244 +#define __NR_wait4 260 +#define __NR_prlimit64 261 +#define __NR_fanotify_init 262 +#define __NR_fanotify_mark 263 +#define __NR_name_to_handle_at 264 +#define __NR_open_by_handle_at 265 +#define __NR_clock_adjtime 266 +#define __NR_syncfs 267 +#define __NR_setns 268 +#define __NR_sendmmsg 269 +#define __NR_process_vm_readv 270 +#define __NR_process_vm_writev 271 +#define __NR_kcmp 272 +#define __NR_finit_module 273 +#define __NR_sched_setattr 274 +#define __NR_sched_getattr 275 +#define __NR_renameat2 276 +#define __NR_seccomp 277 +#define __NR_getrandom 278 +#define __NR_memfd_create 279 +#define __NR_bpf 280 +#define __NR_execveat 281 +#define __NR_userfaultfd 282 +#define __NR_membarrier 283 +#define __NR_mlock2 284 +#define __NR_copy_file_range 285 +#define __NR_preadv2 286 +#define __NR_pwritev2 287 +#define __NR_pkey_mprotect 288 +#define __NR_pkey_alloc 289 +#define __NR_pkey_free 290 +#define __NR_sysriscv __NR_arch_specific_syscall + +#define SYS_io_setup 0 +#define SYS_io_destroy 1 +#define SYS_io_submit 2 +#define SYS_io_cancel 3 +#define SYS_io_getevents 4 +#define SYS_setxattr 5 +#define SYS_lsetxattr 6 +#define SYS_fsetxattr 7 +#define SYS_getxattr 8 +#define SYS_lgetxattr 9 +#define SYS_fgetxattr 10 +#define SYS_listxattr 11 +#define SYS_llistxattr 12 +#define SYS_flistxattr 13 +#define SYS_removexattr 14 +#define SYS_lremovexattr 15 +#define SYS_fremovexattr 16 +#define SYS_getcwd 17 +#define SYS_lookup_dcookie 18 +#define SYS_eventfd2 19 +#define SYS_epoll_create1 20 +#define SYS_epoll_ctl 21 +#define SYS_epoll_pwait 22 +#define SYS_dup 23 +#define SYS_dup3 24 +#define SYS_fcntl 25 +#define SYS_inotify_init1 26 +#define SYS_inotify_add_watch 27 +#define SYS_inotify_rm_watch 28 +#define SYS_ioctl 29 +#define SYS_ioprio_set 30 +#define SYS_ioprio_get 31 +#define SYS_flock 32 +#define SYS_mknodat 33 +#define SYS_mkdirat 34 +#define SYS_unlinkat 35 +#define SYS_symlinkat 36 +#define SYS_linkat 37 +#define SYS_renameat 38 +#define SYS_umount2 39 +#define SYS_mount 40 +#define SYS_pivot_root 41 +#define SYS_nfsservctl 42 +#define SYS_statfs 43 +#define SYS_fstatfs 44 +#define SYS_truncate 45 +#define SYS_ftruncate 46 +#define SYS_fallocate 47 +#define SYS_faccessat 48 +#define SYS_chdir 49 +#define SYS_fchdir 50 +#define SYS_chroot 51 +#define SYS_fchmod 52 +#define SYS_fchmodat 53 +#define SYS_fchownat 54 +#define SYS_fchown 55 +#define SYS_openat 56 +#define SYS_close 57 +#define SYS_vhangup 58 +#define SYS_pipe2 59 +#define SYS_quotactl 60 +#define SYS_getdents64 61 +#define SYS_lseek 62 +#define SYS_read 63 +#define SYS_write 64 +#define SYS_readv 65 +#define SYS_writev 66 +#define SYS_pread64 67 +#define SYS_pwrite64 68 +#define SYS_preadv 69 +#define SYS_pwritev 70 +#define SYS_sendfile 71 +#define SYS_pselect6 72 +#define SYS_ppoll 73 +#define SYS_signalfd4 74 +#define SYS_vmsplice 75 +#define SYS_splice 76 +#define SYS_tee 77 +#define SYS_readlinkat 78 +#define SYS_fstatat 79 +#define SYS_fstat 80 +#define SYS_sync 81 +#define SYS_fsync 82 +#define SYS_fdatasync 83 +#define SYS_sync_file_range 84 +#define SYS_timerfd_create 85 +#define SYS_timerfd_settime 86 +#define SYS_timerfd_gettime 87 +#define SYS_utimensat 88 +#define SYS_acct 89 +#define SYS_capget 90 +#define SYS_capset 91 +#define SYS_personality 92 +#define SYS_exit 93 +#define SYS_exit_group 94 +#define SYS_waitid 95 +#define SYS_set_tid_address 96 +#define SYS_unshare 97 +#define SYS_futex 98 +#define SYS_set_robust_list 99 +#define SYS_get_robust_list 100 +#define SYS_nanosleep 101 +#define SYS_getitimer 102 +#define SYS_setitimer 103 +#define SYS_kexec_load 104 +#define SYS_init_module 105 +#define SYS_delete_module 106 +#define SYS_timer_create 107 +#define SYS_timer_gettime 108 +#define SYS_timer_getoverrun 109 +#define SYS_timer_settime 110 +#define SYS_timer_delete 111 +#define SYS_clock_settime 112 +#define SYS_clock_gettime 113 +#define SYS_clock_getres 114 +#define SYS_clock_nanosleep 115 +#define SYS_syslog 116 +#define SYS_ptrace 117 +#define SYS_sched_setparam 118 +#define SYS_sched_setscheduler 119 +#define SYS_sched_getscheduler 120 +#define SYS_sched_getparam 121 +#define SYS_sched_setaffinity 122 +#define SYS_sched_getaffinity 123 +#define SYS_sched_yield 124 +#define SYS_sched_get_priority_max 125 +#define SYS_sched_get_priority_min 126 +#define SYS_sched_rr_get_interval 127 +#define SYS_restart_syscall 128 +#define SYS_kill 129 +#define SYS_tkill 130 +#define SYS_tgkill 131 +#define SYS_sigaltstack 132 +#define SYS_rt_sigsuspend 133 +#define SYS_rt_sigaction 134 +#define SYS_rt_sigprocmask 135 +#define SYS_rt_sigpending 136 +#define SYS_rt_sigtimedwait 137 +#define SYS_rt_sigqueueinfo 138 +#define SYS_rt_sigreturn 139 +#define SYS_setpriority 140 +#define SYS_getpriority 141 +#define SYS_reboot 142 +#define SYS_setregid 143 +#define SYS_setgid 144 +#define SYS_setreuid 145 +#define SYS_setuid 146 +#define SYS_setresuid 147 +#define SYS_getresuid 148 +#define SYS_setresgid 149 +#define SYS_getresgid 150 +#define SYS_setfsuid 151 +#define SYS_setfsgid 152 +#define SYS_times 153 +#define SYS_setpgid 154 +#define SYS_getpgid 155 +#define SYS_getsid 156 +#define SYS_setsid 157 +#define SYS_getgroups 158 +#define SYS_setgroups 159 +#define SYS_uname 160 +#define SYS_sethostname 161 +#define SYS_setdomainname 162 +#define SYS_getrlimit 163 +#define SYS_setrlimit 164 +#define SYS_getrusage 165 +#define SYS_umask 166 +#define SYS_prctl 167 +#define SYS_getcpu 168 +#define SYS_gettimeofday 169 +#define SYS_settimeofday 170 +#define SYS_adjtimex 171 +#define SYS_getpid 172 +#define SYS_getppid 173 +#define SYS_getuid 174 +#define SYS_geteuid 175 +#define SYS_getgid 176 +#define SYS_getegid 177 +#define SYS_gettid 178 +#define SYS_sysinfo 179 +#define SYS_mq_open 180 +#define SYS_mq_unlink 181 +#define SYS_mq_timedsend 182 +#define SYS_mq_timedreceive 183 +#define SYS_mq_notify 184 +#define SYS_mq_getsetattr 185 +#define SYS_msgget 186 +#define SYS_msgctl 187 +#define SYS_msgrcv 188 +#define SYS_msgsnd 189 +#define SYS_semget 190 +#define SYS_semctl 191 +#define SYS_semtimedop 192 +#define SYS_semop 193 +#define SYS_shmget 194 +#define SYS_shmctl 195 +#define SYS_shmat 196 +#define SYS_shmdt 197 +#define SYS_socket 198 +#define SYS_socketpair 199 +#define SYS_bind 200 +#define SYS_listen 201 +#define SYS_accept 202 +#define SYS_connect 203 +#define SYS_getsockname 204 +#define SYS_getpeername 205 +#define SYS_sendto 206 +#define SYS_recvfrom 207 +#define SYS_setsockopt 208 +#define SYS_getsockopt 209 +#define SYS_shutdown 210 +#define SYS_sendmsg 211 +#define SYS_recvmsg 212 +#define SYS_readahead 213 +#define SYS_brk 214 +#define SYS_munmap 215 +#define SYS_mremap 216 +#define SYS_add_key 217 +#define SYS_request_key 218 +#define SYS_keyctl 219 +#define SYS_clone 220 +#define SYS_execve 221 +#define SYS_mmap 222 +#define SYS_fadvise64 223 +#define SYS_swapon 224 +#define SYS_swapoff 225 +#define SYS_mprotect 226 +#define SYS_msync 227 +#define SYS_mlock 228 +#define SYS_munlock 229 +#define SYS_mlockall 230 +#define SYS_munlockall 231 +#define SYS_mincore 232 +#define SYS_madvise 233 +#define SYS_remap_file_pages 234 +#define SYS_mbind 235 +#define SYS_get_mempolicy 236 +#define SYS_set_mempolicy 237 +#define SYS_migrate_pages 238 +#define SYS_move_pages 239 +#define SYS_rt_tgsigqueueinfo 240 +#define SYS_perf_event_open 241 +#define SYS_accept4 242 +#define SYS_recvmmsg 243 +#define SYS_arch_specific_syscall 244 +#define SYS_wait4 260 +#define SYS_prlimit64 261 +#define SYS_fanotify_init 262 +#define SYS_fanotify_mark 263 +#define SYS_name_to_handle_at 264 +#define SYS_open_by_handle_at 265 +#define SYS_clock_adjtime 266 +#define SYS_syncfs 267 +#define SYS_setns 268 +#define SYS_sendmmsg 269 +#define SYS_process_vm_readv 270 +#define SYS_process_vm_writev 271 +#define SYS_kcmp 272 +#define SYS_finit_module 273 +#define SYS_sched_setattr 274 +#define SYS_sched_getattr 275 +#define SYS_renameat2 276 +#define SYS_seccomp 277 +#define SYS_getrandom 278 +#define SYS_memfd_create 279 +#define SYS_bpf 280 +#define SYS_execveat 281 +#define SYS_userfaultfd 282 +#define SYS_membarrier 283 +#define SYS_mlock2 284 +#define SYS_copy_file_range 285 +#define SYS_preadv2 286 +#define SYS_pwritev2 287 +#define SYS_pkey_mprotect 288 +#define SYS_pkey_alloc 289 +#define SYS_pkey_free 290 +#define SYS_sysriscv __NR_arch_specific_syscall diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/byteswap.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/byteswap.h new file mode 100644 index 0000000000000000000000000000000000000000..00b9df3c9fa2b1511105ef60efca7650607a9f52 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/byteswap.h @@ -0,0 +1,26 @@ +#ifndef _BYTESWAP_H +#define _BYTESWAP_H + +#include +#include + +static __inline uint16_t __bswap_16(uint16_t __x) +{ + return __x<<8 | __x>>8; +} + +static __inline uint32_t __bswap_32(uint32_t __x) +{ + return __x>>24 | __x>>8&0xff00 | __x<<8&0xff0000 | __x<<24; +} + +static __inline uint64_t __bswap_64(uint64_t __x) +{ + return __bswap_32(__x)+0ULL<<32 | __bswap_32(__x>>32); +} + +#define bswap_16(x) __bswap_16(x) +#define bswap_32(x) __bswap_32(x) +#define bswap_64(x) __bswap_64(x) + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/complex.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/complex.h new file mode 100644 index 0000000000000000000000000000000000000000..008b3c7e3b7d6190cb864892aa7b2bad3f1aa2cf --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/complex.h @@ -0,0 +1,133 @@ +#ifndef _COMPLEX_H +#define _COMPLEX_H + +#ifdef __cplusplus +extern "C" { +#endif + +#define complex _Complex +#ifdef __GNUC__ +#define _Complex_I (__extension__ (0.0f+1.0fi)) +#else +#define _Complex_I (0.0f+1.0fi) +#endif +#define I _Complex_I + +double complex cacos(double complex); +float complex cacosf(float complex); +long double complex cacosl(long double complex); + +double complex casin(double complex); +float complex casinf(float complex); +long double complex casinl(long double complex); + +double complex catan(double complex); +float complex catanf(float complex); +long double complex catanl(long double complex); + +double complex ccos(double complex); +float complex ccosf(float complex); +long double complex ccosl(long double complex); + +double complex csin(double complex); +float complex csinf(float complex); +long double complex csinl(long double complex); + +double complex ctan(double complex); +float complex ctanf(float complex); +long double complex ctanl(long double complex); + +double complex cacosh(double complex); +float complex cacoshf(float complex); +long double complex cacoshl(long double complex); + +double complex casinh(double complex); +float complex casinhf(float complex); +long double complex casinhl(long double complex); + +double complex catanh(double complex); +float complex catanhf(float complex); +long double complex catanhl(long double complex); + +double complex ccosh(double complex); +float complex ccoshf(float complex); +long double complex ccoshl(long double complex); + +double complex csinh(double complex); +float complex csinhf(float complex); +long double complex csinhl(long double complex); + +double complex ctanh(double complex); +float complex ctanhf(float complex); +long double complex ctanhl(long double complex); + +double complex cexp(double complex); +float complex cexpf(float complex); +long double complex cexpl(long double complex); + +double complex clog(double complex); +float complex clogf(float complex); +long double complex clogl(long double complex); + +double cabs(double complex); +float cabsf(float complex); +long double cabsl(long double complex); + +double complex cpow(double complex, double complex); +float complex cpowf(float complex, float complex); +long double complex cpowl(long double complex, long double complex); + +double complex csqrt(double complex); +float complex csqrtf(float complex); +long double complex csqrtl(long double complex); + +double carg(double complex); +float cargf(float complex); +long double cargl(long double complex); + +double cimag(double complex); +float cimagf(float complex); +long double cimagl(long double complex); + +double complex conj(double complex); +float complex conjf(float complex); +long double complex conjl(long double complex); + +double complex cproj(double complex); +float complex cprojf(float complex); +long double complex cprojl(long double complex); + +double creal(double complex); +float crealf(float complex); +long double creall(long double complex); + +#ifndef __cplusplus +#define __CIMAG(x, t) \ + (+(union { _Complex t __z; t __xy[2]; }){(_Complex t)(x)}.__xy[1]) + +#define creal(x) ((double)(x)) +#define crealf(x) ((float)(x)) +#define creall(x) ((long double)(x)) + +#define cimag(x) __CIMAG(x, double) +#define cimagf(x) __CIMAG(x, float) +#define cimagl(x) __CIMAG(x, long double) +#endif + +#if __STDC_VERSION__ >= 201112L +#if defined(_Imaginary_I) +#define __CMPLX(x, y, t) ((t)(x) + _Imaginary_I*(t)(y)) +#elif defined(__clang__) +#define __CMPLX(x, y, t) (+(_Complex t){ (t)(x), (t)(y) }) +#else +#define __CMPLX(x, y, t) (__builtin_complex((t)(x), (t)(y))) +#endif +#define CMPLX(x, y) __CMPLX(x, y, double) +#define CMPLXF(x, y) __CMPLX(x, y, float) +#define CMPLXL(x, y) __CMPLX(x, y, long double) +#endif + +#ifdef __cplusplus +} +#endif +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/cpio.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/cpio.h new file mode 100644 index 0000000000000000000000000000000000000000..39a1f8bba53357ad5d4aee5d78c803f6799ba226 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/cpio.h @@ -0,0 +1,29 @@ +#ifndef _CPIO_H +#define _CPIO_H + +#define MAGIC "070707" + +#define C_IRUSR 000400 +#define C_IWUSR 000200 +#define C_IXUSR 000100 +#define C_IRGRP 000040 +#define C_IWGRP 000020 +#define C_IXGRP 000010 +#define C_IROTH 000004 +#define C_IWOTH 000002 +#define C_IXOTH 000001 + +#define C_ISUID 004000 +#define C_ISGID 002000 +#define C_ISVTX 001000 + +#define C_ISBLK 060000 +#define C_ISCHR 020000 +#define C_ISDIR 040000 +#define C_ISFIFO 010000 +#define C_ISSOCK 0140000 +#define C_ISLNK 0120000 +#define C_ISCTG 0110000 +#define C_ISREG 0100000 + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/crypt.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/crypt.h new file mode 100644 index 0000000000000000000000000000000000000000..07de21698c7e1918fdb520dc8e93db776ad8180e --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/crypt.h @@ -0,0 +1,20 @@ +#ifndef _CRYPT_H +#define _CRYPT_H + +#ifdef __cplusplus +extern "C" { +#endif + +struct crypt_data { + int initialized; + char __buf[256]; +}; + +char *crypt(const char *, const char *); +char *crypt_r(const char *, const char *, struct crypt_data *); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/ctype.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/ctype.h new file mode 100644 index 0000000000000000000000000000000000000000..258c90c86c0aadea2d54d72ed8a4bad880965022 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/ctype.h @@ -0,0 +1,386 @@ +/** + * @defgroup ctype Ctype + * @ingroup libc + */ + +#ifndef _CTYPE_H +#define _CTYPE_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +/** + * @ingroup ctype + * + * @par Description: + * The isalnum() function tests whether c is an alphanumeric character. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval #int The isalnum() function shall return non-zero if c is an alphanumeric character; + * otherwise, it shall return 0. + * + * @par Dependency: + *
  • ctype.h
+ * @see isspace | isalpha | isblank | iscntrl | isdigit | isgraph | islower | isprint | ispunct | isupper + */ +int isalnum(int); + +/** + * @ingroup ctype + * + * @par Description: + * The isalpha() function tests whether c is an alphabetic character. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval #int The isalpha() function shall return non-zero if c is an alphabetic character; + * otherwise, it shall return 0. + * + * @par Dependency: + *
  • ctype.h
+ * @see isspace | isalnum | isblank | iscntrl | isdigit | isgraph | islower | isprint | ispunct | isupper + */ +int isalpha(int); + +/** + * @ingroup ctype + * + * @par Description: + * The isblank() function tests whether c is a character of class blank. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval #int The value returned is nonzero if the character c falls + * into the tested class, and zero if not. + * + * @par Dependency: + *
  • ctype.h
+ * @see isalnum | isalpha | iscntrl | isdigit | isgraph | islower | isprint | ispunct | isspace | isupper | isxdigit + */ +int isblank(int); + +/** + * @ingroup ctype + * + * @par Description: + * The iscntrl() function tests whether c is a control character. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval #int The iscntrl() function shall return non-zero if c is a control character; + * otherwise, it shall return 0. + * + * @par Dependency: + *
  • ctype.h
+ * @see isspace | isalnum | isblank | isalpha | isdigit | isgraph | islower | isprint | ispunct | isupper + */ +int iscntrl(int); + +/** + * @ingroup ctype + * + * @par Description: + * The isdigit() function tests whether c is a decimal digit. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval #int The isdigit() function shall return non-zero if c is a decimal digit; + * otherwise, it shall return 0. + * + * @par Dependency: + *
  • ctype.h
+ * @see isspace | isalnum | isblank | isalpha | iscntrl | isgraph | islower | isprint | ispunct | isupper + */ +int isdigit(int); + +/** + * @ingroup ctype + * + * @par Description: + * The isgraph() function tests whether c is a visible character. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval #int The isgraph() function shall return non-zero if c is a visible character; + * otherwise, it shall return 0. + * + * @par Dependency: + *
  • ctype.h
+ * @see isspace | isalnum | isblank | isalpha | iscntrl | isdigit | islower | isprint | ispunct | isupper + */ +int isgraph(int); + +/** + * @ingroup ctype + * + * @par Description: + * The islower() function tests whether c is a lowercase letter. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval #int The islower() function shall return non-zero if c is a lowercase letter; + * otherwise, it shall return 0. + * + * @par Dependency: + *
  • ctype.h
+ * @see isspace | isalnum | isblank | isalpha | iscntrl | isdigit | isgraph | isprint | ispunct | isupper + */ +int islower(int); + +/** + * @ingroup ctype + * + * @par Description: + * The isprint() function tests whether c is a printable character. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval #int The isprint() function shall return non-zero if c is a printable character; + * otherwise, it shall return 0. + * + * @par Dependency: + *
  • ctype.h
+ * @see isspace | isalnum | isblank | isalpha | iscntrl | isdigit | isgraph | islower | ispunct | isupper + */ +int isprint(int); + +/** + * @ingroup ctype + * + * @par Description: + * The ispunct() function tests whether c is a punctuation character. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval #int The ispunct() function shall return non-zero if c is a punctuation character; + * otherwise, it shall return 0. + * + * @par Dependency: + *
  • ctype.h
+ * @see isspace | isalnum | isblank | isalpha | iscntrl | isdigit | isgraph | islower | isprint | isupper + */ +int ispunct(int); + +/** + * @ingroup ctype + * + * @par Description: + * The isspace() function tests whether c is a white-space character. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval #int The isspace() function shall return non-zero if c is a white-space character; + * otherwise, it shall return 0. + * + * @par Dependency: + *
  • ctype.h
+ * @see isalnum | isalpha | isblank | iscntrl | isdigit | isgraph | islower | isprint | ispunct | isupper + */ +int isspace(int); + +/** + * @ingroup ctype + * + * @par Description: + * The isupper() function tests whether c is an uppercase letter. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval #int The isupper() function shall return non-zero if c is an uppercase letter; + * otherwise, it shall return 0. + * + * @par Dependency: + *
  • ctype.h
+ * @see isalnum | isalpha | isblank | iscntrl | isdigit | isgraph | islower | isprint | ispunct | isspace + */ +int isupper(int); + +/** + * @ingroup ctype + * + * @par Description: + * The isxdigit() function tests whether c is a hexadecimal digit. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval #int The isxdigit() function shall return non-zero if c is a hexadecimal digit; + * otherwise, it shall return 0. + * + * @par Dependency: + *
  • ctype.h
+ * @see isalnum | isalpha | isblank | iscntrl | isdigit | isgraph | islower | isprint | ispunct | isspace | isupper + */ +int isxdigit(int); + +/** + * @ingroup ctype + * + * @par Description: + * The tolower() function converts uppercase letters to lowercase. + * If c is an uppercase letter, tolower() returns its lowercase + * equivalent. Otherwise, it returns c. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval #int The value returned is that of the converted letter, or c if the + * conversion was not possible. + * + * @par Dependency: + *
  • ctype.h
+ * @see isalpha | towlower | towupper + */ +int tolower(int); + +/** + * @ingroup ctype + * + * @par Description: + * The toupper() function converts lowercase letters to uppercase. + * If c is a lowercase letter, toupper() returns its uppercase + * equivalent. Otherwise, it returns c. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval #int The value returned is that of the converted letter, or c if the + * conversion was not possible. + * + * @par Dependency: + *
  • ctype.h
+ * @see isalpha | towlower | towupper + */ +int toupper(int); + +#ifndef __cplusplus +static __inline int __isspace(int _c) +{ + return _c == ' ' || (unsigned)_c-'\t' < 5; +} + +#define isalpha(a) (0 ? isalpha(a) : (((unsigned)(a)|32)-'a') < 26) +#define isdigit(a) (0 ? isdigit(a) : ((unsigned)(a)-'0') < 10) +#define islower(a) (0 ? islower(a) : ((unsigned)(a)-'a') < 26) +#define isupper(a) (0 ? isupper(a) : ((unsigned)(a)-'A') < 26) +#define isprint(a) (0 ? isprint(a) : ((unsigned)(a)-0x20) < 0x5f) +#define isgraph(a) (0 ? isgraph(a) : ((unsigned)(a)-0x21) < 0x5e) +#define isspace(a) __isspace(a) +#endif + + +#if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \ + || defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) \ + || defined(_BSD_SOURCE) + +#define __NEED_locale_t +#include + +int isalnum_l(int, locale_t); +int isalpha_l(int, locale_t); +int isblank_l(int, locale_t); +int iscntrl_l(int, locale_t); +int isdigit_l(int, locale_t); +int isgraph_l(int, locale_t); +int islower_l(int, locale_t); +int isprint_l(int, locale_t); +int ispunct_l(int, locale_t); +int isspace_l(int, locale_t); +int isupper_l(int, locale_t); +int isxdigit_l(int, locale_t); +int tolower_l(int, locale_t); +int toupper_l(int, locale_t); + + +/** + * @ingroup ctype + * + * @par Description: + * The isascii() function tests whether c is a 7-bit US-ASCII character code. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval #int The isascii() function shall return non-zero if c is a 7-bit US-ASCII + * character code between 0 and octal 0177 inclusive; otherwise, it shall return 0. + * + * @par Dependency: + *
  • ctype.h
+ * @see toascii + */ +int isascii(int); + +/** + * @ingroup ctype + * + * @par Description: + * The toascii() function converts its argument into a 7-bit ASCII character. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval #int The toascii() function shall return the value (c &0177). + * + * @par Dependency: + *
  • ctype.h
+ * @see isascii + */ +int toascii(int); +#define _tolower(a) ((a)|0x20) +#define _toupper(a) ((a)&0x5f) +#define isascii(a) (0 ? isascii(a) : (unsigned)(a) < 128) + +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/dirent.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/dirent.h new file mode 100644 index 0000000000000000000000000000000000000000..11d8f933d1ae53ae393bd159acc496a6b78897ff --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/dirent.h @@ -0,0 +1,342 @@ +/** + * @defgroup dirent Dirent + * @ingroup libc + */ + +#ifndef _DIRENT_H +#define _DIRENT_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#define __NEED_ino_t +#define __NEED_off_t +#if defined(_BSD_SOURCE) || defined(_GNU_SOURCE) +#define __NEED_size_t +#endif +#ifdef __LITEOS__ +#define __NEED_int64_t +#endif + +#include + +#include + +#ifndef __LITEOS__ +typedef struct __dirstream DIR; +#else +typedef struct DIR DIR; +#endif + +#define d_fileno d_ino + +/** + * @ingroup dirent + * + * @par Description: + * The closedir() function shall close the directory stream referred to by the argument dirp. + * + * @param dirp [IN] An instance of type DIR created by a previous call to opendir(). + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval #0 Close directory successful. + * @retval #-1 An error is encountered and close the directory failed. + * + * @par Errors + *
    + *
  • EBADF: The dirp argument does not refer to an open directory stream.
  • + *
  • EEXIST : The 1st member in the FIL/DIR object is invalid of fat.
  • + *
  • EIO: A hard error occurred in the low level disk I/O layer or the physical drive cannot work.
  • + *
  • ENOENT: The internal node pointed to by DIR doesn't exist in jffs2 and romfs.
  • + *
  • EPERM: Other errors.
  • + *
+ * + * @par Dependency: + *
  • dirent.h
+ * @see None + */ +int closedir(DIR *); +DIR *fdopendir(int); + +/** + * @ingroup dirent + * + * @par Description: + * The opendir() function shall open a directory stream corresponding to the directory named by the path argument. + * The directory stream is positioned at the first entry. If the type DIR is implemented using a file descriptor, + * applications shall only be able to open up to a total of {OPEN_MAX} files and directories. + * + * @param path [IN] path of the diretory which need to open. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval #DIR* Upon successful completion, these functions shall return a pointer to an object of type DIR. + * @retval #NULL An error is encountered and open the directory faild. + * + * @par Errors + *
    + *
  • EINVAL: The path is an empty string.
  • + *
  • ENAMETOOLONG: The length of a component of a pathname is longer than {NAME_MAX}.
  • + *
  • ENOENT: A component of the path does not exist.
  • + *
  • ENOMEM: Out of memory.
  • + *
  • ENOTDIR: A component of the path is not a directory.
  • + *
  • EMFILE: Too many open file.
  • + *
  • EROFS: The physical drive is write protected with fat filesystem.
  • + *
  • EIO: A hard error occurred in the low level disk I/O layer or the physical drive cannot work.
  • + *
  • ENODEV: The mount is not healthy.
  • + *
  • EPERM: Other errors.
  • + *
+ * + * @par Dependency: + *
  • dirent.h
+ * @see open | readdir | rewinddir | closedir + */ +DIR *opendir(const char *); + +/** + * @ingroup dirent + * + * @par Description: + * The readdir() function shall return a pointer to a structure representing the directory entry + * at the current position in the directory stream specified by the argument dirp, + * and position the directory stream at the next entry. + * It shall return a null pointer upon reaching the end of the directory stream. + * + * @param dirp [IN] a directory stream of current directory. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval "struct dirent*" Upon successful completion, readdir() shall return a pointer to + * an object of type struct dirent. + * @retval NULL An error is encountered or the end of the directory is encountered. + * + * @par Errors + *
    + *
  • EINVAL: dirp argument is invalid.
  • + *
  • ENAMETOOLONG: The length of the pathname of the current directory entry is longer than {NAME_MAX}.
  • + *
  • ENOENT: The current position of the directory stream is invalid.
  • + *
  • ENOMEM: Out of memory.
  • + *
  • ENOSPC: No free cluster of fat filesystem.
  • + *
  • EBADF: The dirp argument does not refer to an open directory stream.
  • + *
  • EIO: A hard error occurred in the low level disk I/O layer or the physical drive cannot work.
  • + *
  • ENODEV: The mount is not healthy.
  • + *
  • EACCES: The current file system doesn't support readdir.
  • + *
  • EPERM: Other errors.
  • + *
+ * + * @par Dependency: + *
  • dirent.h
+ * @see closedir | rewinddir + */ +struct dirent *readdir(DIR *); +int readdir_r(DIR *__restrict, struct dirent *__restrict, struct dirent **__restrict); + +/** + * @ingroup dirent + * + * @par Description: + * The rewinddir() function shall reset the position of the directory stream to + * which dirp refers to the beginning of the directory. + * + * @param dirp [IN] An instance of type DIR created by a previous call to opendir(). + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval #void None. + * + * @par Errors + *
    + *
  • EBADF: The dirp argument does not refer to an open directory stream.
  • + *
+ * + * @par Dependency: + *
  • dirent.h
+ * @see readdir | closedir + */ +void rewinddir(DIR *); +int dirfd(DIR *); + +/** + * @ingroup dirent + * + * @par Description: + * The alphasort() function can be used as the comparison function for the scandir() function + * to sort the directory entries, d1 and d2, into alphabetical order. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval #int Upon successful completion, the alphasort() function shall return an integer greater than, + * equal to, or less than 0, according to whether the name of the directory entry pointed to by d1 + * is lexically greater than, equal to, or less than the directory pointed to by d2 when both are interpreted + * as appropriate to the current locale. There is no return value reserved to indicate an error. + * + * @par Dependency: + *
  • dirent.h
+ * @see strcoll + */ +int alphasort(const struct dirent **, const struct dirent **); + +/** + * @ingroup dirent + * + * @par Description: + * The scandir() function shall scan the directory dir, calling the function referenced by filter on each directory + * entry. Entries for which the function referenced by filter returns non-zero shall be stored in strings allocated + * as if by a call to malloc(), and sorted as if by a call to qsort() with the comparison function compar, + * except that compar need not provide total ordering. The strings are collected in array namelist + * which shall be allocated as if by a call to malloc(). If filter is a null pointer, all entries shall be selected. + * If the comparison function compar does not provide total ordering, the order in which the directory entries + * are stored is unspecified. + * + * @param dir [IN] The path of the directory need to scan. + * @param namelist [OUT] Return the pointer of type struct dirent* to store the dirent scanned in the directory. + * @param filter [IN] Refer to the function to select the entries. + * @param compar [IN] The comparison function used in qsort() to sort the entries. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval #int the number of entries in the array and a pointer to the array through the parameter namelist. + * @retval #-1 An error is encountered. + * + * @par Errors + *
    + *
  • EINVAL: The path is an empty string.
  • + *
  • ENAMETOOLONG: The length of a component of a pathname is longer than {NAME_MAX}.
  • + *
  • ENOENT: A component of the path does not exist.
  • + *
  • ENOMEM: Out of memory.
  • + *
  • ENOSPC: Out of memory in ramfs filesystem.
  • + *
  • ENOTDIR: A component of the path is not a directory.
  • + *
  • EMFILE: Too many open file.
  • + *
  • EROFS: The physical drive is write protected with fat filesystem.
  • + *
  • EIO: A hard error occurred in the low level disk I/O layer or the physical drive cannot work.
  • + *
  • ENODEV: The mount is not healthy.
  • + *
  • EPERM: Other errors.
  • + *
+ * + * @par Dependency: + *
  • dirent.h
+ * @see qsort + */ +int scandir(const char *, struct dirent ***, int (*)(const struct dirent *), int (*)(const struct dirent **, const struct dirent **)); + +#if defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) || defined(_BSD_SOURCE) +/** + * @ingroup dirent + * + * @par Description: + * The seekdir() function shall set the position of the next readdir() operation on the directory stream specified + * by dirp to the position specified by offset. The value of offset should have been returned from + * an earlier call to telldir() using the same directory stream. + * + * @param dirp [IN] An instance of type DIR created by a previous call to opendir(). + * @param offset [IN] offset to seek to + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval #void None. + * + * @par Errors + *
    + *
  • EBADF: The dirp argument does not refer to an open directory stream.
  • + *
  • EINVAL: offset is less than zero.
  • + *
+ * + * @par Dependency: + *
  • dirent.h
+ * @see readdir | telldir + */ +void seekdir(DIR *, long); + +/** + * @ingroup dirent + * + * @par Description: + * The telldir() function shall obtain the current location associated with the directory stream specified by dirp. + * + * @param dirp [IN] An instance of type DIR created by a previous call to opendir(). + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval #long Upon successful completion, telldir() shall return the current location + * of the specified directory stream. + * + * @par Errors + *
    + *
  • EBADF: The dirp argument does not refer to an open directory stream.
  • + *
+ * + * @par Dependency: + *
  • dirent.h
+ * @see readdir | seekdir + */ +long telldir(DIR *); +#endif + +#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE) +#define DT_UNKNOWN 0 +#define DT_FIFO 1 +#define DT_CHR 2 +#define DT_DIR 4 +#define DT_BLK 6 +#define DT_REG 8 +#define DT_LNK 10 +#define DT_SOCK 12 +#define DT_WHT 14 +#define IFTODT(x) ((x)>>12 & 017) +#define DTTOIF(x) ((x)<<12) +int getdents(int, struct dirent *, size_t); +#endif + +#ifdef _GNU_SOURCE +int versionsort(const struct dirent **, const struct dirent **); +#endif + +#if defined(_LARGEFILE64_SOURCE) || defined(_GNU_SOURCE) +#define dirent64 dirent +#define readdir64 readdir +#define readdir64_r readdir_r +#define scandir64 scandir +#define alphasort64 alphasort +#define versionsort64 versionsort +#ifdef __LITEOS__ +#define off64_t int64_t +#else +#define off64_t off_t +#endif +#define ino64_t ino_t +#define getdents64 getdents +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/dlfcn.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/dlfcn.h new file mode 100644 index 0000000000000000000000000000000000000000..3c0b52c42ac8344583896dda975748f846f46f04 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/dlfcn.h @@ -0,0 +1,114 @@ +/** + * @defgroup dlfcn Dlfcn + * @ingroup libc + */ + +#ifndef _DLFCN_H +#define _DLFCN_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#define RTLD_LAZY 1 +#define RTLD_NOW 2 +#define RTLD_NOLOAD 4 +#define RTLD_NODELETE 4096 +#define RTLD_GLOBAL 256 +#define RTLD_LOCAL 0 + +#define RTLD_NEXT ((void *)-1) +#define RTLD_DEFAULT ((void *)0) + +#define RTLD_DI_LINKMAP 2 + + +/** + * @ingroup dlfcn + * + * @par Description: + * The function shall close the loading shared libraries. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval #int On success, this function shall return LOS_OK. + * On failure, this function shall return LOS_NOK or -1. + * + * @par Dependency: + *
  • dlfcn.h
+ * + * @see dlopen | dlsym + * + */ +int dlclose(void *); +char *dlerror(void); + +/** + * @ingroup dlfcn + * + * @par Description: + * The function shall return the pointer to the handle of loading shared libraries. + * + * @attention + *
    + *
  • The function is not supported for the second param.
  • + *
+ * + * @retval #void* On success, this function shall return the pointer to the handle of + * loading shared libraries. On failure, this function shall return NULL. + * + * @par Dependency: + *
  • dlfcn.h
+ * + * @see dlclose | dlsym + * + */ +void *dlopen(const char *, int); + +/** + * @ingroup dlfcn + * + * @par Description: + * The function shall return the second param address in memory of loading shared libraries. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval #void* On success, this function shall return the second param address in memory + * of loading shared libraries. On failure, this function shall return NULL. + * + * @par Dependency: + *
  • dlfcn.h
+ * + * @see dlopen | dlclose + * + */ +void *dlsym(void *__restrict, const char *__restrict); + +#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE) +typedef struct { + const char *dli_fname; + void *dli_fbase; + const char *dli_sname; + void *dli_saddr; +} Dl_info; +int dladdr(const void *, Dl_info *); +int dlinfo(void *, int, void *); +#endif + +#if _REDIR_TIME64 +__REDIR(dlsym, __dlsym_time64); +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/elf.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/elf.h new file mode 100644 index 0000000000000000000000000000000000000000..549f92c1aa8841b8527f5ca1153d20637132c7f7 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/elf.h @@ -0,0 +1,3292 @@ +#ifndef _ELF_H +#define _ELF_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +typedef uint16_t Elf32_Half; +typedef uint16_t Elf64_Half; + +typedef uint32_t Elf32_Word; +typedef int32_t Elf32_Sword; +typedef uint32_t Elf64_Word; +typedef int32_t Elf64_Sword; + +typedef uint64_t Elf32_Xword; +typedef int64_t Elf32_Sxword; +typedef uint64_t Elf64_Xword; +typedef int64_t Elf64_Sxword; + +typedef uint32_t Elf32_Addr; +typedef uint64_t Elf64_Addr; + +typedef uint32_t Elf32_Off; +typedef uint64_t Elf64_Off; + +typedef uint16_t Elf32_Section; +typedef uint16_t Elf64_Section; + +typedef Elf32_Half Elf32_Versym; +typedef Elf64_Half Elf64_Versym; + +#define EI_NIDENT (16) + +typedef struct { + unsigned char e_ident[EI_NIDENT]; + Elf32_Half e_type; + Elf32_Half e_machine; + Elf32_Word e_version; + Elf32_Addr e_entry; + Elf32_Off e_phoff; + Elf32_Off e_shoff; + Elf32_Word e_flags; + Elf32_Half e_ehsize; + Elf32_Half e_phentsize; + Elf32_Half e_phnum; + Elf32_Half e_shentsize; + Elf32_Half e_shnum; + Elf32_Half e_shstrndx; +} Elf32_Ehdr; + +typedef struct { + unsigned char e_ident[EI_NIDENT]; + Elf64_Half e_type; + Elf64_Half e_machine; + Elf64_Word e_version; + Elf64_Addr e_entry; + Elf64_Off e_phoff; + Elf64_Off e_shoff; + Elf64_Word e_flags; + Elf64_Half e_ehsize; + Elf64_Half e_phentsize; + Elf64_Half e_phnum; + Elf64_Half e_shentsize; + Elf64_Half e_shnum; + Elf64_Half e_shstrndx; +} Elf64_Ehdr; + +#define EI_MAG0 0 +#define ELFMAG0 0x7f + +#define EI_MAG1 1 +#define ELFMAG1 'E' + +#define EI_MAG2 2 +#define ELFMAG2 'L' + +#define EI_MAG3 3 +#define ELFMAG3 'F' + + +#define ELFMAG "\177ELF" +#define SELFMAG 4 + +#define EI_CLASS 4 +#define ELFCLASSNONE 0 +#define ELFCLASS32 1 +#define ELFCLASS64 2 +#define ELFCLASSNUM 3 + +#define EI_DATA 5 +#define ELFDATANONE 0 +#define ELFDATA2LSB 1 +#define ELFDATA2MSB 2 +#define ELFDATANUM 3 + +#define EI_VERSION 6 + + +#define EI_OSABI 7 +#define ELFOSABI_NONE 0 +#define ELFOSABI_SYSV 0 +#define ELFOSABI_HPUX 1 +#define ELFOSABI_NETBSD 2 +#define ELFOSABI_LINUX 3 +#define ELFOSABI_GNU 3 +#define ELFOSABI_SOLARIS 6 +#define ELFOSABI_AIX 7 +#define ELFOSABI_IRIX 8 +#define ELFOSABI_FREEBSD 9 +#define ELFOSABI_TRU64 10 +#define ELFOSABI_MODESTO 11 +#define ELFOSABI_OPENBSD 12 +#define ELFOSABI_ARM 97 +#define ELFOSABI_STANDALONE 255 + +#define EI_ABIVERSION 8 + +#define EI_PAD 9 + + + +#define ET_NONE 0 +#define ET_REL 1 +#define ET_EXEC 2 +#define ET_DYN 3 +#define ET_CORE 4 +#define ET_NUM 5 +#define ET_LOOS 0xfe00 +#define ET_HIOS 0xfeff +#define ET_LOPROC 0xff00 +#define ET_HIPROC 0xffff + + + +#define EM_NONE 0 +#define EM_M32 1 +#define EM_SPARC 2 +#define EM_386 3 +#define EM_68K 4 +#define EM_88K 5 +#define EM_860 7 +#define EM_MIPS 8 +#define EM_S370 9 +#define EM_MIPS_RS3_LE 10 + +#define EM_PARISC 15 +#define EM_VPP500 17 +#define EM_SPARC32PLUS 18 +#define EM_960 19 +#define EM_PPC 20 +#define EM_PPC64 21 +#define EM_S390 22 + +#define EM_V800 36 +#define EM_FR20 37 +#define EM_RH32 38 +#define EM_RCE 39 +#define EM_ARM 40 +#define EM_FAKE_ALPHA 41 +#define EM_SH 42 +#define EM_SPARCV9 43 +#define EM_TRICORE 44 +#define EM_ARC 45 +#define EM_H8_300 46 +#define EM_H8_300H 47 +#define EM_H8S 48 +#define EM_H8_500 49 +#define EM_IA_64 50 +#define EM_MIPS_X 51 +#define EM_COLDFIRE 52 +#define EM_68HC12 53 +#define EM_MMA 54 +#define EM_PCP 55 +#define EM_NCPU 56 +#define EM_NDR1 57 +#define EM_STARCORE 58 +#define EM_ME16 59 +#define EM_ST100 60 +#define EM_TINYJ 61 +#define EM_X86_64 62 +#define EM_PDSP 63 + +#define EM_FX66 66 +#define EM_ST9PLUS 67 +#define EM_ST7 68 +#define EM_68HC16 69 +#define EM_68HC11 70 +#define EM_68HC08 71 +#define EM_68HC05 72 +#define EM_SVX 73 +#define EM_ST19 74 +#define EM_VAX 75 +#define EM_CRIS 76 +#define EM_JAVELIN 77 +#define EM_FIREPATH 78 +#define EM_ZSP 79 +#define EM_MMIX 80 +#define EM_HUANY 81 +#define EM_PRISM 82 +#define EM_AVR 83 +#define EM_FR30 84 +#define EM_D10V 85 +#define EM_D30V 86 +#define EM_V850 87 +#define EM_M32R 88 +#define EM_MN10300 89 +#define EM_MN10200 90 +#define EM_PJ 91 +#define EM_OR1K 92 +#define EM_OPENRISC 92 +#define EM_ARC_A5 93 +#define EM_ARC_COMPACT 93 +#define EM_XTENSA 94 +#define EM_VIDEOCORE 95 +#define EM_TMM_GPP 96 +#define EM_NS32K 97 +#define EM_TPC 98 +#define EM_SNP1K 99 +#define EM_ST200 100 +#define EM_IP2K 101 +#define EM_MAX 102 +#define EM_CR 103 +#define EM_F2MC16 104 +#define EM_MSP430 105 +#define EM_BLACKFIN 106 +#define EM_SE_C33 107 +#define EM_SEP 108 +#define EM_ARCA 109 +#define EM_UNICORE 110 +#define EM_EXCESS 111 +#define EM_DXP 112 +#define EM_ALTERA_NIOS2 113 +#define EM_CRX 114 +#define EM_XGATE 115 +#define EM_C166 116 +#define EM_M16C 117 +#define EM_DSPIC30F 118 +#define EM_CE 119 +#define EM_M32C 120 +#define EM_TSK3000 131 +#define EM_RS08 132 +#define EM_SHARC 133 +#define EM_ECOG2 134 +#define EM_SCORE7 135 +#define EM_DSP24 136 +#define EM_VIDEOCORE3 137 +#define EM_LATTICEMICO32 138 +#define EM_SE_C17 139 +#define EM_TI_C6000 140 +#define EM_TI_C2000 141 +#define EM_TI_C5500 142 +#define EM_TI_ARP32 143 +#define EM_TI_PRU 144 +#define EM_MMDSP_PLUS 160 +#define EM_CYPRESS_M8C 161 +#define EM_R32C 162 +#define EM_TRIMEDIA 163 +#define EM_QDSP6 164 +#define EM_8051 165 +#define EM_STXP7X 166 +#define EM_NDS32 167 +#define EM_ECOG1X 168 +#define EM_MAXQ30 169 +#define EM_XIMO16 170 +#define EM_MANIK 171 +#define EM_CRAYNV2 172 +#define EM_RX 173 +#define EM_METAG 174 +#define EM_MCST_ELBRUS 175 +#define EM_ECOG16 176 +#define EM_CR16 177 +#define EM_ETPU 178 +#define EM_SLE9X 179 +#define EM_L10M 180 +#define EM_K10M 181 +#define EM_AARCH64 183 +#define EM_AVR32 185 +#define EM_STM8 186 +#define EM_TILE64 187 +#define EM_TILEPRO 188 +#define EM_MICROBLAZE 189 +#define EM_CUDA 190 +#define EM_TILEGX 191 +#define EM_CLOUDSHIELD 192 +#define EM_COREA_1ST 193 +#define EM_COREA_2ND 194 +#define EM_ARC_COMPACT2 195 +#define EM_OPEN8 196 +#define EM_RL78 197 +#define EM_VIDEOCORE5 198 +#define EM_78KOR 199 +#define EM_56800EX 200 +#define EM_BA1 201 +#define EM_BA2 202 +#define EM_XCORE 203 +#define EM_MCHP_PIC 204 +#define EM_KM32 210 +#define EM_KMX32 211 +#define EM_EMX16 212 +#define EM_EMX8 213 +#define EM_KVARC 214 +#define EM_CDP 215 +#define EM_COGE 216 +#define EM_COOL 217 +#define EM_NORC 218 +#define EM_CSR_KALIMBA 219 +#define EM_Z80 220 +#define EM_VISIUM 221 +#define EM_FT32 222 +#define EM_MOXIE 223 +#define EM_AMDGPU 224 +#define EM_RISCV 243 +#define EM_BPF 247 +#define EM_CSKY 252 +#define EM_NUM 253 + +#define EM_ALPHA 0x9026 + +#define EV_NONE 0 +#define EV_CURRENT 1 +#define EV_NUM 2 + +typedef struct { + Elf32_Word sh_name; + Elf32_Word sh_type; + Elf32_Word sh_flags; + Elf32_Addr sh_addr; + Elf32_Off sh_offset; + Elf32_Word sh_size; + Elf32_Word sh_link; + Elf32_Word sh_info; + Elf32_Word sh_addralign; + Elf32_Word sh_entsize; +} Elf32_Shdr; + +typedef struct { + Elf64_Word sh_name; + Elf64_Word sh_type; + Elf64_Xword sh_flags; + Elf64_Addr sh_addr; + Elf64_Off sh_offset; + Elf64_Xword sh_size; + Elf64_Word sh_link; + Elf64_Word sh_info; + Elf64_Xword sh_addralign; + Elf64_Xword sh_entsize; +} Elf64_Shdr; + + + +#define SHN_UNDEF 0 +#define SHN_LORESERVE 0xff00 +#define SHN_LOPROC 0xff00 +#define SHN_BEFORE 0xff00 + +#define SHN_AFTER 0xff01 + +#define SHN_HIPROC 0xff1f +#define SHN_LOOS 0xff20 +#define SHN_HIOS 0xff3f +#define SHN_ABS 0xfff1 +#define SHN_COMMON 0xfff2 +#define SHN_XINDEX 0xffff +#define SHN_HIRESERVE 0xffff + + + +#define SHT_NULL 0 +#define SHT_PROGBITS 1 +#define SHT_SYMTAB 2 +#define SHT_STRTAB 3 +#define SHT_RELA 4 +#define SHT_HASH 5 +#define SHT_DYNAMIC 6 +#define SHT_NOTE 7 +#define SHT_NOBITS 8 +#define SHT_REL 9 +#define SHT_SHLIB 10 +#define SHT_DYNSYM 11 +#define SHT_INIT_ARRAY 14 +#define SHT_FINI_ARRAY 15 +#define SHT_PREINIT_ARRAY 16 +#define SHT_GROUP 17 +#define SHT_SYMTAB_SHNDX 18 +#define SHT_NUM 19 +#define SHT_LOOS 0x60000000 +#define SHT_GNU_ATTRIBUTES 0x6ffffff5 +#define SHT_GNU_HASH 0x6ffffff6 +#define SHT_GNU_LIBLIST 0x6ffffff7 +#define SHT_CHECKSUM 0x6ffffff8 +#define SHT_LOSUNW 0x6ffffffa +#define SHT_SUNW_move 0x6ffffffa +#define SHT_SUNW_COMDAT 0x6ffffffb +#define SHT_SUNW_syminfo 0x6ffffffc +#define SHT_GNU_verdef 0x6ffffffd +#define SHT_GNU_verneed 0x6ffffffe +#define SHT_GNU_versym 0x6fffffff +#define SHT_HISUNW 0x6fffffff +#define SHT_HIOS 0x6fffffff +#define SHT_LOPROC 0x70000000 +#define SHT_HIPROC 0x7fffffff +#define SHT_LOUSER 0x80000000 +#define SHT_HIUSER 0x8fffffff + +#define SHF_WRITE (1 << 0) +#define SHF_ALLOC (1 << 1) +#define SHF_EXECINSTR (1 << 2) +#define SHF_MERGE (1 << 4) +#define SHF_STRINGS (1 << 5) +#define SHF_INFO_LINK (1 << 6) +#define SHF_LINK_ORDER (1 << 7) +#define SHF_OS_NONCONFORMING (1 << 8) + +#define SHF_GROUP (1 << 9) +#define SHF_TLS (1 << 10) +#define SHF_COMPRESSED (1 << 11) +#define SHF_MASKOS 0x0ff00000 +#define SHF_MASKPROC 0xf0000000 +#define SHF_ORDERED (1 << 30) +#define SHF_EXCLUDE (1U << 31) + +typedef struct { + Elf32_Word ch_type; + Elf32_Word ch_size; + Elf32_Word ch_addralign; +} Elf32_Chdr; + +typedef struct { + Elf64_Word ch_type; + Elf64_Word ch_reserved; + Elf64_Xword ch_size; + Elf64_Xword ch_addralign; +} Elf64_Chdr; + +#define ELFCOMPRESS_ZLIB 1 +#define ELFCOMPRESS_LOOS 0x60000000 +#define ELFCOMPRESS_HIOS 0x6fffffff +#define ELFCOMPRESS_LOPROC 0x70000000 +#define ELFCOMPRESS_HIPROC 0x7fffffff + + +#define GRP_COMDAT 0x1 + +typedef struct { + Elf32_Word st_name; + Elf32_Addr st_value; + Elf32_Word st_size; + unsigned char st_info; + unsigned char st_other; + Elf32_Section st_shndx; +} Elf32_Sym; + +typedef struct { + Elf64_Word st_name; + unsigned char st_info; + unsigned char st_other; + Elf64_Section st_shndx; + Elf64_Addr st_value; + Elf64_Xword st_size; +} Elf64_Sym; + +typedef struct { + Elf32_Half si_boundto; + Elf32_Half si_flags; +} Elf32_Syminfo; + +typedef struct { + Elf64_Half si_boundto; + Elf64_Half si_flags; +} Elf64_Syminfo; + +#define SYMINFO_BT_SELF 0xffff +#define SYMINFO_BT_PARENT 0xfffe +#define SYMINFO_BT_LOWRESERVE 0xff00 + +#define SYMINFO_FLG_DIRECT 0x0001 +#define SYMINFO_FLG_PASSTHRU 0x0002 +#define SYMINFO_FLG_COPY 0x0004 +#define SYMINFO_FLG_LAZYLOAD 0x0008 + +#define SYMINFO_NONE 0 +#define SYMINFO_CURRENT 1 +#define SYMINFO_NUM 2 + +#define ELF32_ST_BIND(val) (((unsigned char) (val)) >> 4) +#define ELF32_ST_TYPE(val) ((val) & 0xf) +#define ELF32_ST_INFO(bind, type) (((bind) << 4) + ((type) & 0xf)) + +#define ELF64_ST_BIND(val) ELF32_ST_BIND (val) +#define ELF64_ST_TYPE(val) ELF32_ST_TYPE (val) +#define ELF64_ST_INFO(bind, type) ELF32_ST_INFO ((bind), (type)) + +#define STB_LOCAL 0 +#define STB_GLOBAL 1 +#define STB_WEAK 2 +#define STB_NUM 3 +#define STB_LOOS 10 +#define STB_GNU_UNIQUE 10 +#define STB_HIOS 12 +#define STB_LOPROC 13 +#define STB_HIPROC 15 + +#define STT_NOTYPE 0 +#define STT_OBJECT 1 +#define STT_FUNC 2 +#define STT_SECTION 3 +#define STT_FILE 4 +#define STT_COMMON 5 +#define STT_TLS 6 +#define STT_NUM 7 +#define STT_LOOS 10 +#define STT_GNU_IFUNC 10 +#define STT_HIOS 12 +#define STT_LOPROC 13 +#define STT_HIPROC 15 + +#define STN_UNDEF 0 + +#define ELF32_ST_VISIBILITY(o) ((o) & 0x03) +#define ELF64_ST_VISIBILITY(o) ELF32_ST_VISIBILITY (o) + +#define STV_DEFAULT 0 +#define STV_INTERNAL 1 +#define STV_HIDDEN 2 +#define STV_PROTECTED 3 + + + + +typedef struct { + Elf32_Addr r_offset; + Elf32_Word r_info; +} Elf32_Rel; + +typedef struct { + Elf64_Addr r_offset; + Elf64_Xword r_info; +} Elf64_Rel; + + + +typedef struct { + Elf32_Addr r_offset; + Elf32_Word r_info; + Elf32_Sword r_addend; +} Elf32_Rela; + +typedef struct { + Elf64_Addr r_offset; + Elf64_Xword r_info; + Elf64_Sxword r_addend; +} Elf64_Rela; + + + +#define ELF32_R_SYM(val) ((val) >> 8) +#define ELF32_R_TYPE(val) ((val) & 0xff) +#define ELF32_R_INFO(sym, type) (((sym) << 8) + ((type) & 0xff)) + +#define ELF64_R_SYM(i) ((i) >> 32) +#define ELF64_R_TYPE(i) ((i) & 0xffffffff) +#define ELF64_R_INFO(sym,type) ((((Elf64_Xword) (sym)) << 32) + (type)) + + + +typedef struct { + Elf32_Word p_type; + Elf32_Off p_offset; + Elf32_Addr p_vaddr; + Elf32_Addr p_paddr; + Elf32_Word p_filesz; + Elf32_Word p_memsz; + Elf32_Word p_flags; + Elf32_Word p_align; +} Elf32_Phdr; + +typedef struct { + Elf64_Word p_type; + Elf64_Word p_flags; + Elf64_Off p_offset; + Elf64_Addr p_vaddr; + Elf64_Addr p_paddr; + Elf64_Xword p_filesz; + Elf64_Xword p_memsz; + Elf64_Xword p_align; +} Elf64_Phdr; + + + +#define PT_NULL 0 +#define PT_LOAD 1 +#define PT_DYNAMIC 2 +#define PT_INTERP 3 +#define PT_NOTE 4 +#define PT_SHLIB 5 +#define PT_PHDR 6 +#define PT_TLS 7 +#define PT_NUM 8 +#define PT_LOOS 0x60000000 +#define PT_GNU_EH_FRAME 0x6474e550 +#define PT_GNU_STACK 0x6474e551 +#define PT_GNU_RELRO 0x6474e552 +#define PT_LOSUNW 0x6ffffffa +#define PT_SUNWBSS 0x6ffffffa +#define PT_SUNWSTACK 0x6ffffffb +#define PT_HISUNW 0x6fffffff +#define PT_HIOS 0x6fffffff +#define PT_LOPROC 0x70000000 +#define PT_HIPROC 0x7fffffff + + +#define PN_XNUM 0xffff + + +#define PF_X (1 << 0) +#define PF_W (1 << 1) +#define PF_R (1 << 2) +#define PF_MASKOS 0x0ff00000 +#define PF_MASKPROC 0xf0000000 + + + +#define NT_PRSTATUS 1 +#define NT_PRFPREG 2 +#define NT_FPREGSET 2 +#define NT_PRPSINFO 3 +#define NT_PRXREG 4 +#define NT_TASKSTRUCT 4 +#define NT_PLATFORM 5 +#define NT_AUXV 6 +#define NT_GWINDOWS 7 +#define NT_ASRS 8 +#define NT_PSTATUS 10 +#define NT_PSINFO 13 +#define NT_PRCRED 14 +#define NT_UTSNAME 15 +#define NT_LWPSTATUS 16 +#define NT_LWPSINFO 17 +#define NT_PRFPXREG 20 +#define NT_SIGINFO 0x53494749 +#define NT_FILE 0x46494c45 +#define NT_PRXFPREG 0x46e62b7f +#define NT_PPC_VMX 0x100 +#define NT_PPC_SPE 0x101 +#define NT_PPC_VSX 0x102 +#define NT_PPC_TAR 0x103 +#define NT_PPC_PPR 0x104 +#define NT_PPC_DSCR 0x105 +#define NT_PPC_EBB 0x106 +#define NT_PPC_PMU 0x107 +#define NT_PPC_TM_CGPR 0x108 +#define NT_PPC_TM_CFPR 0x109 +#define NT_PPC_TM_CVMX 0x10a +#define NT_PPC_TM_CVSX 0x10b +#define NT_PPC_TM_SPR 0x10c +#define NT_PPC_TM_CTAR 0x10d +#define NT_PPC_TM_CPPR 0x10e +#define NT_PPC_TM_CDSCR 0x10f +#define NT_386_TLS 0x200 +#define NT_386_IOPERM 0x201 +#define NT_X86_XSTATE 0x202 +#define NT_S390_HIGH_GPRS 0x300 +#define NT_S390_TIMER 0x301 +#define NT_S390_TODCMP 0x302 +#define NT_S390_TODPREG 0x303 +#define NT_S390_CTRS 0x304 +#define NT_S390_PREFIX 0x305 +#define NT_S390_LAST_BREAK 0x306 +#define NT_S390_SYSTEM_CALL 0x307 +#define NT_S390_TDB 0x308 +#define NT_S390_VXRS_LOW 0x309 +#define NT_S390_VXRS_HIGH 0x30a +#define NT_S390_GS_CB 0x30b +#define NT_S390_GS_BC 0x30c +#define NT_S390_RI_CB 0x30d +#define NT_ARM_VFP 0x400 +#define NT_ARM_TLS 0x401 +#define NT_ARM_HW_BREAK 0x402 +#define NT_ARM_HW_WATCH 0x403 +#define NT_ARM_SYSTEM_CALL 0x404 +#define NT_ARM_SVE 0x405 +#define NT_ARM_PAC_MASK 0x406 +#define NT_ARM_PACA_KEYS 0x407 +#define NT_ARM_PACG_KEYS 0x408 +#define NT_METAG_CBUF 0x500 +#define NT_METAG_RPIPE 0x501 +#define NT_METAG_TLS 0x502 +#define NT_ARC_V2 0x600 +#define NT_VMCOREDD 0x700 +#define NT_MIPS_DSP 0x800 +#define NT_MIPS_FP_MODE 0x801 +#define NT_MIPS_MSA 0x802 +#define NT_VERSION 1 + + + + +typedef struct { + Elf32_Sword d_tag; + union { + Elf32_Word d_val; + Elf32_Addr d_ptr; + } d_un; +} Elf32_Dyn; + +typedef struct { + Elf64_Sxword d_tag; + union { + Elf64_Xword d_val; + Elf64_Addr d_ptr; + } d_un; +} Elf64_Dyn; + + + +#define DT_NULL 0 +#define DT_NEEDED 1 +#define DT_PLTRELSZ 2 +#define DT_PLTGOT 3 +#define DT_HASH 4 +#define DT_STRTAB 5 +#define DT_SYMTAB 6 +#define DT_RELA 7 +#define DT_RELASZ 8 +#define DT_RELAENT 9 +#define DT_STRSZ 10 +#define DT_SYMENT 11 +#define DT_INIT 12 +#define DT_FINI 13 +#define DT_SONAME 14 +#define DT_RPATH 15 +#define DT_SYMBOLIC 16 +#define DT_REL 17 +#define DT_RELSZ 18 +#define DT_RELENT 19 +#define DT_PLTREL 20 +#define DT_DEBUG 21 +#define DT_TEXTREL 22 +#define DT_JMPREL 23 +#define DT_BIND_NOW 24 +#define DT_INIT_ARRAY 25 +#define DT_FINI_ARRAY 26 +#define DT_INIT_ARRAYSZ 27 +#define DT_FINI_ARRAYSZ 28 +#define DT_RUNPATH 29 +#define DT_FLAGS 30 +#define DT_ENCODING 32 +#define DT_PREINIT_ARRAY 32 +#define DT_PREINIT_ARRAYSZ 33 +#define DT_SYMTAB_SHNDX 34 +#define DT_NUM 35 +#define DT_LOOS 0x6000000d +#define DT_HIOS 0x6ffff000 +#define DT_LOPROC 0x70000000 +#define DT_HIPROC 0x7fffffff +#define DT_PROCNUM DT_MIPS_NUM + +#define DT_VALRNGLO 0x6ffffd00 +#define DT_GNU_PRELINKED 0x6ffffdf5 +#define DT_GNU_CONFLICTSZ 0x6ffffdf6 +#define DT_GNU_LIBLISTSZ 0x6ffffdf7 +#define DT_CHECKSUM 0x6ffffdf8 +#define DT_PLTPADSZ 0x6ffffdf9 +#define DT_MOVEENT 0x6ffffdfa +#define DT_MOVESZ 0x6ffffdfb +#define DT_FEATURE_1 0x6ffffdfc +#define DT_POSFLAG_1 0x6ffffdfd + +#define DT_SYMINSZ 0x6ffffdfe +#define DT_SYMINENT 0x6ffffdff +#define DT_VALRNGHI 0x6ffffdff +#define DT_VALTAGIDX(tag) (DT_VALRNGHI - (tag)) +#define DT_VALNUM 12 + +#define DT_ADDRRNGLO 0x6ffffe00 +#define DT_GNU_HASH 0x6ffffef5 +#define DT_TLSDESC_PLT 0x6ffffef6 +#define DT_TLSDESC_GOT 0x6ffffef7 +#define DT_GNU_CONFLICT 0x6ffffef8 +#define DT_GNU_LIBLIST 0x6ffffef9 +#define DT_CONFIG 0x6ffffefa +#define DT_DEPAUDIT 0x6ffffefb +#define DT_AUDIT 0x6ffffefc +#define DT_PLTPAD 0x6ffffefd +#define DT_MOVETAB 0x6ffffefe +#define DT_SYMINFO 0x6ffffeff +#define DT_ADDRRNGHI 0x6ffffeff +#define DT_ADDRTAGIDX(tag) (DT_ADDRRNGHI - (tag)) +#define DT_ADDRNUM 11 + + + +#define DT_VERSYM 0x6ffffff0 + +#define DT_RELACOUNT 0x6ffffff9 +#define DT_RELCOUNT 0x6ffffffa + + +#define DT_FLAGS_1 0x6ffffffb +#define DT_VERDEF 0x6ffffffc + +#define DT_VERDEFNUM 0x6ffffffd +#define DT_VERNEED 0x6ffffffe + +#define DT_VERNEEDNUM 0x6fffffff +#define DT_VERSIONTAGIDX(tag) (DT_VERNEEDNUM - (tag)) +#define DT_VERSIONTAGNUM 16 + + + +#define DT_AUXILIARY 0x7ffffffd +#define DT_FILTER 0x7fffffff +#define DT_EXTRATAGIDX(tag) ((Elf32_Word)-((Elf32_Sword) (tag) <<1>>1)-1) +#define DT_EXTRANUM 3 + + +#define DF_ORIGIN 0x00000001 +#define DF_SYMBOLIC 0x00000002 +#define DF_TEXTREL 0x00000004 +#define DF_BIND_NOW 0x00000008 +#define DF_STATIC_TLS 0x00000010 + + + +#define DF_1_NOW 0x00000001 +#define DF_1_GLOBAL 0x00000002 +#define DF_1_GROUP 0x00000004 +#define DF_1_NODELETE 0x00000008 +#define DF_1_LOADFLTR 0x00000010 +#define DF_1_INITFIRST 0x00000020 +#define DF_1_NOOPEN 0x00000040 +#define DF_1_ORIGIN 0x00000080 +#define DF_1_DIRECT 0x00000100 +#define DF_1_TRANS 0x00000200 +#define DF_1_INTERPOSE 0x00000400 +#define DF_1_NODEFLIB 0x00000800 +#define DF_1_NODUMP 0x00001000 +#define DF_1_CONFALT 0x00002000 +#define DF_1_ENDFILTEE 0x00004000 +#define DF_1_DISPRELDNE 0x00008000 +#define DF_1_DISPRELPND 0x00010000 +#define DF_1_NODIRECT 0x00020000 +#define DF_1_IGNMULDEF 0x00040000 +#define DF_1_NOKSYMS 0x00080000 +#define DF_1_NOHDR 0x00100000 +#define DF_1_EDITED 0x00200000 +#define DF_1_NORELOC 0x00400000 +#define DF_1_SYMINTPOSE 0x00800000 +#define DF_1_GLOBAUDIT 0x01000000 +#define DF_1_SINGLETON 0x02000000 +#define DF_1_STUB 0x04000000 +#define DF_1_PIE 0x08000000 + +#define DTF_1_PARINIT 0x00000001 +#define DTF_1_CONFEXP 0x00000002 + + +#define DF_P1_LAZYLOAD 0x00000001 +#define DF_P1_GROUPPERM 0x00000002 + + + + +typedef struct { + Elf32_Half vd_version; + Elf32_Half vd_flags; + Elf32_Half vd_ndx; + Elf32_Half vd_cnt; + Elf32_Word vd_hash; + Elf32_Word vd_aux; + Elf32_Word vd_next; +} Elf32_Verdef; + +typedef struct { + Elf64_Half vd_version; + Elf64_Half vd_flags; + Elf64_Half vd_ndx; + Elf64_Half vd_cnt; + Elf64_Word vd_hash; + Elf64_Word vd_aux; + Elf64_Word vd_next; +} Elf64_Verdef; + + + +#define VER_DEF_NONE 0 +#define VER_DEF_CURRENT 1 +#define VER_DEF_NUM 2 + + +#define VER_FLG_BASE 0x1 +#define VER_FLG_WEAK 0x2 + + +#define VER_NDX_LOCAL 0 +#define VER_NDX_GLOBAL 1 +#define VER_NDX_LORESERVE 0xff00 +#define VER_NDX_ELIMINATE 0xff01 + + + +typedef struct { + Elf32_Word vda_name; + Elf32_Word vda_next; +} Elf32_Verdaux; + +typedef struct { + Elf64_Word vda_name; + Elf64_Word vda_next; +} Elf64_Verdaux; + + + + +typedef struct { + Elf32_Half vn_version; + Elf32_Half vn_cnt; + Elf32_Word vn_file; + Elf32_Word vn_aux; + Elf32_Word vn_next; +} Elf32_Verneed; + +typedef struct { + Elf64_Half vn_version; + Elf64_Half vn_cnt; + Elf64_Word vn_file; + Elf64_Word vn_aux; + Elf64_Word vn_next; +} Elf64_Verneed; + + + +#define VER_NEED_NONE 0 +#define VER_NEED_CURRENT 1 +#define VER_NEED_NUM 2 + + + +typedef struct { + Elf32_Word vna_hash; + Elf32_Half vna_flags; + Elf32_Half vna_other; + Elf32_Word vna_name; + Elf32_Word vna_next; +} Elf32_Vernaux; + +typedef struct { + Elf64_Word vna_hash; + Elf64_Half vna_flags; + Elf64_Half vna_other; + Elf64_Word vna_name; + Elf64_Word vna_next; +} Elf64_Vernaux; + + + +#define VER_FLG_WEAK 0x2 + + + +typedef struct { + uint32_t a_type; + union { + uint32_t a_val; + } a_un; +} Elf32_auxv_t; + +typedef struct { + uint64_t a_type; + union { + uint64_t a_val; + } a_un; +} Elf64_auxv_t; + + + +#define AT_NULL 0 +#define AT_IGNORE 1 +#define AT_EXECFD 2 +#define AT_PHDR 3 +#define AT_PHENT 4 +#define AT_PHNUM 5 +#define AT_PAGESZ 6 +#define AT_BASE 7 +#define AT_FLAGS 8 +#define AT_ENTRY 9 +#define AT_NOTELF 10 +#define AT_UID 11 +#define AT_EUID 12 +#define AT_GID 13 +#define AT_EGID 14 +#define AT_CLKTCK 17 + + +#define AT_PLATFORM 15 +#define AT_HWCAP 16 + + + + +#define AT_FPUCW 18 + + +#define AT_DCACHEBSIZE 19 +#define AT_ICACHEBSIZE 20 +#define AT_UCACHEBSIZE 21 + + + +#define AT_IGNOREPPC 22 + +#define AT_SECURE 23 + +#define AT_BASE_PLATFORM 24 + +#define AT_RANDOM 25 + +#define AT_HWCAP2 26 + +#define AT_EXECFN 31 + + + +#define AT_SYSINFO 32 +#define AT_SYSINFO_EHDR 33 + + + +#define AT_L1I_CACHESHAPE 34 +#define AT_L1D_CACHESHAPE 35 +#define AT_L2_CACHESHAPE 36 +#define AT_L3_CACHESHAPE 37 + +#define AT_L1I_CACHESIZE 40 +#define AT_L1I_CACHEGEOMETRY 41 +#define AT_L1D_CACHESIZE 42 +#define AT_L1D_CACHEGEOMETRY 43 +#define AT_L2_CACHESIZE 44 +#define AT_L2_CACHEGEOMETRY 45 +#define AT_L3_CACHESIZE 46 +#define AT_L3_CACHEGEOMETRY 47 + +#define AT_MINSIGSTKSZ 51 + + +typedef struct { + Elf32_Word n_namesz; + Elf32_Word n_descsz; + Elf32_Word n_type; +} Elf32_Nhdr; + +typedef struct { + Elf64_Word n_namesz; + Elf64_Word n_descsz; + Elf64_Word n_type; +} Elf64_Nhdr; + + + + +#define ELF_NOTE_SOLARIS "SUNW Solaris" + + +#define ELF_NOTE_GNU "GNU" + + + + + +#define ELF_NOTE_PAGESIZE_HINT 1 + + +#define NT_GNU_ABI_TAG 1 +#define ELF_NOTE_ABI NT_GNU_ABI_TAG + + + +#define ELF_NOTE_OS_LINUX 0 +#define ELF_NOTE_OS_GNU 1 +#define ELF_NOTE_OS_SOLARIS2 2 +#define ELF_NOTE_OS_FREEBSD 3 + +#define NT_GNU_BUILD_ID 3 +#define NT_GNU_GOLD_VERSION 4 + + + +typedef struct { + Elf32_Xword m_value; + Elf32_Word m_info; + Elf32_Word m_poffset; + Elf32_Half m_repeat; + Elf32_Half m_stride; +} Elf32_Move; + +typedef struct { + Elf64_Xword m_value; + Elf64_Xword m_info; + Elf64_Xword m_poffset; + Elf64_Half m_repeat; + Elf64_Half m_stride; +} Elf64_Move; + + +#define ELF32_M_SYM(info) ((info) >> 8) +#define ELF32_M_SIZE(info) ((unsigned char) (info)) +#define ELF32_M_INFO(sym, size) (((sym) << 8) + (unsigned char) (size)) + +#define ELF64_M_SYM(info) ELF32_M_SYM (info) +#define ELF64_M_SIZE(info) ELF32_M_SIZE (info) +#define ELF64_M_INFO(sym, size) ELF32_M_INFO (sym, size) + +#define EF_CPU32 0x00810000 + +#define R_68K_NONE 0 +#define R_68K_32 1 +#define R_68K_16 2 +#define R_68K_8 3 +#define R_68K_PC32 4 +#define R_68K_PC16 5 +#define R_68K_PC8 6 +#define R_68K_GOT32 7 +#define R_68K_GOT16 8 +#define R_68K_GOT8 9 +#define R_68K_GOT32O 10 +#define R_68K_GOT16O 11 +#define R_68K_GOT8O 12 +#define R_68K_PLT32 13 +#define R_68K_PLT16 14 +#define R_68K_PLT8 15 +#define R_68K_PLT32O 16 +#define R_68K_PLT16O 17 +#define R_68K_PLT8O 18 +#define R_68K_COPY 19 +#define R_68K_GLOB_DAT 20 +#define R_68K_JMP_SLOT 21 +#define R_68K_RELATIVE 22 +#define R_68K_TLS_GD32 25 +#define R_68K_TLS_GD16 26 +#define R_68K_TLS_GD8 27 +#define R_68K_TLS_LDM32 28 +#define R_68K_TLS_LDM16 29 +#define R_68K_TLS_LDM8 30 +#define R_68K_TLS_LDO32 31 +#define R_68K_TLS_LDO16 32 +#define R_68K_TLS_LDO8 33 +#define R_68K_TLS_IE32 34 +#define R_68K_TLS_IE16 35 +#define R_68K_TLS_IE8 36 +#define R_68K_TLS_LE32 37 +#define R_68K_TLS_LE16 38 +#define R_68K_TLS_LE8 39 +#define R_68K_TLS_DTPMOD32 40 +#define R_68K_TLS_DTPREL32 41 +#define R_68K_TLS_TPREL32 42 +#define R_68K_NUM 43 + +#define R_386_NONE 0 +#define R_386_32 1 +#define R_386_PC32 2 +#define R_386_GOT32 3 +#define R_386_PLT32 4 +#define R_386_COPY 5 +#define R_386_GLOB_DAT 6 +#define R_386_JMP_SLOT 7 +#define R_386_RELATIVE 8 +#define R_386_GOTOFF 9 +#define R_386_GOTPC 10 +#define R_386_32PLT 11 +#define R_386_TLS_TPOFF 14 +#define R_386_TLS_IE 15 +#define R_386_TLS_GOTIE 16 +#define R_386_TLS_LE 17 +#define R_386_TLS_GD 18 +#define R_386_TLS_LDM 19 +#define R_386_16 20 +#define R_386_PC16 21 +#define R_386_8 22 +#define R_386_PC8 23 +#define R_386_TLS_GD_32 24 +#define R_386_TLS_GD_PUSH 25 +#define R_386_TLS_GD_CALL 26 +#define R_386_TLS_GD_POP 27 +#define R_386_TLS_LDM_32 28 +#define R_386_TLS_LDM_PUSH 29 +#define R_386_TLS_LDM_CALL 30 +#define R_386_TLS_LDM_POP 31 +#define R_386_TLS_LDO_32 32 +#define R_386_TLS_IE_32 33 +#define R_386_TLS_LE_32 34 +#define R_386_TLS_DTPMOD32 35 +#define R_386_TLS_DTPOFF32 36 +#define R_386_TLS_TPOFF32 37 +#define R_386_SIZE32 38 +#define R_386_TLS_GOTDESC 39 +#define R_386_TLS_DESC_CALL 40 +#define R_386_TLS_DESC 41 +#define R_386_IRELATIVE 42 +#define R_386_GOT32X 43 +#define R_386_NUM 44 + + + + + +#define STT_SPARC_REGISTER 13 + + + +#define EF_SPARCV9_MM 3 +#define EF_SPARCV9_TSO 0 +#define EF_SPARCV9_PSO 1 +#define EF_SPARCV9_RMO 2 +#define EF_SPARC_LEDATA 0x800000 +#define EF_SPARC_EXT_MASK 0xFFFF00 +#define EF_SPARC_32PLUS 0x000100 +#define EF_SPARC_SUN_US1 0x000200 +#define EF_SPARC_HAL_R1 0x000400 +#define EF_SPARC_SUN_US3 0x000800 + + + +#define R_SPARC_NONE 0 +#define R_SPARC_8 1 +#define R_SPARC_16 2 +#define R_SPARC_32 3 +#define R_SPARC_DISP8 4 +#define R_SPARC_DISP16 5 +#define R_SPARC_DISP32 6 +#define R_SPARC_WDISP30 7 +#define R_SPARC_WDISP22 8 +#define R_SPARC_HI22 9 +#define R_SPARC_22 10 +#define R_SPARC_13 11 +#define R_SPARC_LO10 12 +#define R_SPARC_GOT10 13 +#define R_SPARC_GOT13 14 +#define R_SPARC_GOT22 15 +#define R_SPARC_PC10 16 +#define R_SPARC_PC22 17 +#define R_SPARC_WPLT30 18 +#define R_SPARC_COPY 19 +#define R_SPARC_GLOB_DAT 20 +#define R_SPARC_JMP_SLOT 21 +#define R_SPARC_RELATIVE 22 +#define R_SPARC_UA32 23 + + + +#define R_SPARC_PLT32 24 +#define R_SPARC_HIPLT22 25 +#define R_SPARC_LOPLT10 26 +#define R_SPARC_PCPLT32 27 +#define R_SPARC_PCPLT22 28 +#define R_SPARC_PCPLT10 29 +#define R_SPARC_10 30 +#define R_SPARC_11 31 +#define R_SPARC_64 32 +#define R_SPARC_OLO10 33 +#define R_SPARC_HH22 34 +#define R_SPARC_HM10 35 +#define R_SPARC_LM22 36 +#define R_SPARC_PC_HH22 37 +#define R_SPARC_PC_HM10 38 +#define R_SPARC_PC_LM22 39 +#define R_SPARC_WDISP16 40 +#define R_SPARC_WDISP19 41 +#define R_SPARC_GLOB_JMP 42 +#define R_SPARC_7 43 +#define R_SPARC_5 44 +#define R_SPARC_6 45 +#define R_SPARC_DISP64 46 +#define R_SPARC_PLT64 47 +#define R_SPARC_HIX22 48 +#define R_SPARC_LOX10 49 +#define R_SPARC_H44 50 +#define R_SPARC_M44 51 +#define R_SPARC_L44 52 +#define R_SPARC_REGISTER 53 +#define R_SPARC_UA64 54 +#define R_SPARC_UA16 55 +#define R_SPARC_TLS_GD_HI22 56 +#define R_SPARC_TLS_GD_LO10 57 +#define R_SPARC_TLS_GD_ADD 58 +#define R_SPARC_TLS_GD_CALL 59 +#define R_SPARC_TLS_LDM_HI22 60 +#define R_SPARC_TLS_LDM_LO10 61 +#define R_SPARC_TLS_LDM_ADD 62 +#define R_SPARC_TLS_LDM_CALL 63 +#define R_SPARC_TLS_LDO_HIX22 64 +#define R_SPARC_TLS_LDO_LOX10 65 +#define R_SPARC_TLS_LDO_ADD 66 +#define R_SPARC_TLS_IE_HI22 67 +#define R_SPARC_TLS_IE_LO10 68 +#define R_SPARC_TLS_IE_LD 69 +#define R_SPARC_TLS_IE_LDX 70 +#define R_SPARC_TLS_IE_ADD 71 +#define R_SPARC_TLS_LE_HIX22 72 +#define R_SPARC_TLS_LE_LOX10 73 +#define R_SPARC_TLS_DTPMOD32 74 +#define R_SPARC_TLS_DTPMOD64 75 +#define R_SPARC_TLS_DTPOFF32 76 +#define R_SPARC_TLS_DTPOFF64 77 +#define R_SPARC_TLS_TPOFF32 78 +#define R_SPARC_TLS_TPOFF64 79 +#define R_SPARC_GOTDATA_HIX22 80 +#define R_SPARC_GOTDATA_LOX10 81 +#define R_SPARC_GOTDATA_OP_HIX22 82 +#define R_SPARC_GOTDATA_OP_LOX10 83 +#define R_SPARC_GOTDATA_OP 84 +#define R_SPARC_H34 85 +#define R_SPARC_SIZE32 86 +#define R_SPARC_SIZE64 87 +#define R_SPARC_GNU_VTINHERIT 250 +#define R_SPARC_GNU_VTENTRY 251 +#define R_SPARC_REV32 252 + +#define R_SPARC_NUM 253 + + + +#define DT_SPARC_REGISTER 0x70000001 +#define DT_SPARC_NUM 2 + + +#define EF_MIPS_NOREORDER 1 +#define EF_MIPS_PIC 2 +#define EF_MIPS_CPIC 4 +#define EF_MIPS_XGOT 8 +#define EF_MIPS_64BIT_WHIRL 16 +#define EF_MIPS_ABI2 32 +#define EF_MIPS_ABI_ON32 64 +#define EF_MIPS_FP64 512 +#define EF_MIPS_NAN2008 1024 +#define EF_MIPS_ARCH 0xf0000000 + + + +#define EF_MIPS_ARCH_1 0x00000000 +#define EF_MIPS_ARCH_2 0x10000000 +#define EF_MIPS_ARCH_3 0x20000000 +#define EF_MIPS_ARCH_4 0x30000000 +#define EF_MIPS_ARCH_5 0x40000000 +#define EF_MIPS_ARCH_32 0x50000000 +#define EF_MIPS_ARCH_64 0x60000000 +#define EF_MIPS_ARCH_32R2 0x70000000 +#define EF_MIPS_ARCH_64R2 0x80000000 + + +#define E_MIPS_ARCH_1 0x00000000 +#define E_MIPS_ARCH_2 0x10000000 +#define E_MIPS_ARCH_3 0x20000000 +#define E_MIPS_ARCH_4 0x30000000 +#define E_MIPS_ARCH_5 0x40000000 +#define E_MIPS_ARCH_32 0x50000000 +#define E_MIPS_ARCH_64 0x60000000 + + + +#define SHN_MIPS_ACOMMON 0xff00 +#define SHN_MIPS_TEXT 0xff01 +#define SHN_MIPS_DATA 0xff02 +#define SHN_MIPS_SCOMMON 0xff03 +#define SHN_MIPS_SUNDEFINED 0xff04 + + + +#define SHT_MIPS_LIBLIST 0x70000000 +#define SHT_MIPS_MSYM 0x70000001 +#define SHT_MIPS_CONFLICT 0x70000002 +#define SHT_MIPS_GPTAB 0x70000003 +#define SHT_MIPS_UCODE 0x70000004 +#define SHT_MIPS_DEBUG 0x70000005 +#define SHT_MIPS_REGINFO 0x70000006 +#define SHT_MIPS_PACKAGE 0x70000007 +#define SHT_MIPS_PACKSYM 0x70000008 +#define SHT_MIPS_RELD 0x70000009 +#define SHT_MIPS_IFACE 0x7000000b +#define SHT_MIPS_CONTENT 0x7000000c +#define SHT_MIPS_OPTIONS 0x7000000d +#define SHT_MIPS_SHDR 0x70000010 +#define SHT_MIPS_FDESC 0x70000011 +#define SHT_MIPS_EXTSYM 0x70000012 +#define SHT_MIPS_DENSE 0x70000013 +#define SHT_MIPS_PDESC 0x70000014 +#define SHT_MIPS_LOCSYM 0x70000015 +#define SHT_MIPS_AUXSYM 0x70000016 +#define SHT_MIPS_OPTSYM 0x70000017 +#define SHT_MIPS_LOCSTR 0x70000018 +#define SHT_MIPS_LINE 0x70000019 +#define SHT_MIPS_RFDESC 0x7000001a +#define SHT_MIPS_DELTASYM 0x7000001b +#define SHT_MIPS_DELTAINST 0x7000001c +#define SHT_MIPS_DELTACLASS 0x7000001d +#define SHT_MIPS_DWARF 0x7000001e +#define SHT_MIPS_DELTADECL 0x7000001f +#define SHT_MIPS_SYMBOL_LIB 0x70000020 +#define SHT_MIPS_EVENTS 0x70000021 +#define SHT_MIPS_TRANSLATE 0x70000022 +#define SHT_MIPS_PIXIE 0x70000023 +#define SHT_MIPS_XLATE 0x70000024 +#define SHT_MIPS_XLATE_DEBUG 0x70000025 +#define SHT_MIPS_WHIRL 0x70000026 +#define SHT_MIPS_EH_REGION 0x70000027 +#define SHT_MIPS_XLATE_OLD 0x70000028 +#define SHT_MIPS_PDR_EXCEPTION 0x70000029 + + + +#define SHF_MIPS_GPREL 0x10000000 +#define SHF_MIPS_MERGE 0x20000000 +#define SHF_MIPS_ADDR 0x40000000 +#define SHF_MIPS_STRINGS 0x80000000 +#define SHF_MIPS_NOSTRIP 0x08000000 +#define SHF_MIPS_LOCAL 0x04000000 +#define SHF_MIPS_NAMES 0x02000000 +#define SHF_MIPS_NODUPE 0x01000000 + + + + + +#define STO_MIPS_DEFAULT 0x0 +#define STO_MIPS_INTERNAL 0x1 +#define STO_MIPS_HIDDEN 0x2 +#define STO_MIPS_PROTECTED 0x3 +#define STO_MIPS_PLT 0x8 +#define STO_MIPS_SC_ALIGN_UNUSED 0xff + + +#define STB_MIPS_SPLIT_COMMON 13 + + + +typedef union { + struct { + Elf32_Word gt_current_g_value; + Elf32_Word gt_unused; + } gt_header; + struct { + Elf32_Word gt_g_value; + Elf32_Word gt_bytes; + } gt_entry; +} Elf32_gptab; + + + +typedef struct { + Elf32_Word ri_gprmask; + Elf32_Word ri_cprmask[4]; + Elf32_Sword ri_gp_value; +} Elf32_RegInfo; + + + +typedef struct { + unsigned char kind; + + unsigned char size; + Elf32_Section section; + + Elf32_Word info; +} Elf_Options; + + + +#define ODK_NULL 0 +#define ODK_REGINFO 1 +#define ODK_EXCEPTIONS 2 +#define ODK_PAD 3 +#define ODK_HWPATCH 4 +#define ODK_FILL 5 +#define ODK_TAGS 6 +#define ODK_HWAND 7 +#define ODK_HWOR 8 + + + +#define OEX_FPU_MIN 0x1f +#define OEX_FPU_MAX 0x1f00 +#define OEX_PAGE0 0x10000 +#define OEX_SMM 0x20000 +#define OEX_FPDBUG 0x40000 +#define OEX_PRECISEFP OEX_FPDBUG +#define OEX_DISMISS 0x80000 + +#define OEX_FPU_INVAL 0x10 +#define OEX_FPU_DIV0 0x08 +#define OEX_FPU_OFLO 0x04 +#define OEX_FPU_UFLO 0x02 +#define OEX_FPU_INEX 0x01 + + + +#define OHW_R4KEOP 0x1 +#define OHW_R8KPFETCH 0x2 +#define OHW_R5KEOP 0x4 +#define OHW_R5KCVTL 0x8 + +#define OPAD_PREFIX 0x1 +#define OPAD_POSTFIX 0x2 +#define OPAD_SYMBOL 0x4 + + + +typedef struct { + Elf32_Word hwp_flags1; + Elf32_Word hwp_flags2; +} Elf_Options_Hw; + + + +#define OHWA0_R4KEOP_CHECKED 0x00000001 +#define OHWA1_R4KEOP_CLEAN 0x00000002 + + + +#define R_MIPS_NONE 0 +#define R_MIPS_16 1 +#define R_MIPS_32 2 +#define R_MIPS_REL32 3 +#define R_MIPS_26 4 +#define R_MIPS_HI16 5 +#define R_MIPS_LO16 6 +#define R_MIPS_GPREL16 7 +#define R_MIPS_LITERAL 8 +#define R_MIPS_GOT16 9 +#define R_MIPS_PC16 10 +#define R_MIPS_CALL16 11 +#define R_MIPS_GPREL32 12 + +#define R_MIPS_SHIFT5 16 +#define R_MIPS_SHIFT6 17 +#define R_MIPS_64 18 +#define R_MIPS_GOT_DISP 19 +#define R_MIPS_GOT_PAGE 20 +#define R_MIPS_GOT_OFST 21 +#define R_MIPS_GOT_HI16 22 +#define R_MIPS_GOT_LO16 23 +#define R_MIPS_SUB 24 +#define R_MIPS_INSERT_A 25 +#define R_MIPS_INSERT_B 26 +#define R_MIPS_DELETE 27 +#define R_MIPS_HIGHER 28 +#define R_MIPS_HIGHEST 29 +#define R_MIPS_CALL_HI16 30 +#define R_MIPS_CALL_LO16 31 +#define R_MIPS_SCN_DISP 32 +#define R_MIPS_REL16 33 +#define R_MIPS_ADD_IMMEDIATE 34 +#define R_MIPS_PJUMP 35 +#define R_MIPS_RELGOT 36 +#define R_MIPS_JALR 37 +#define R_MIPS_TLS_DTPMOD32 38 +#define R_MIPS_TLS_DTPREL32 39 +#define R_MIPS_TLS_DTPMOD64 40 +#define R_MIPS_TLS_DTPREL64 41 +#define R_MIPS_TLS_GD 42 +#define R_MIPS_TLS_LDM 43 +#define R_MIPS_TLS_DTPREL_HI16 44 +#define R_MIPS_TLS_DTPREL_LO16 45 +#define R_MIPS_TLS_GOTTPREL 46 +#define R_MIPS_TLS_TPREL32 47 +#define R_MIPS_TLS_TPREL64 48 +#define R_MIPS_TLS_TPREL_HI16 49 +#define R_MIPS_TLS_TPREL_LO16 50 +#define R_MIPS_GLOB_DAT 51 +#define R_MIPS_COPY 126 +#define R_MIPS_JUMP_SLOT 127 + +#define R_MIPS_NUM 128 + + + +#define PT_MIPS_REGINFO 0x70000000 +#define PT_MIPS_RTPROC 0x70000001 +#define PT_MIPS_OPTIONS 0x70000002 +#define PT_MIPS_ABIFLAGS 0x70000003 + + + +#define PF_MIPS_LOCAL 0x10000000 + + + +#define DT_MIPS_RLD_VERSION 0x70000001 +#define DT_MIPS_TIME_STAMP 0x70000002 +#define DT_MIPS_ICHECKSUM 0x70000003 +#define DT_MIPS_IVERSION 0x70000004 +#define DT_MIPS_FLAGS 0x70000005 +#define DT_MIPS_BASE_ADDRESS 0x70000006 +#define DT_MIPS_MSYM 0x70000007 +#define DT_MIPS_CONFLICT 0x70000008 +#define DT_MIPS_LIBLIST 0x70000009 +#define DT_MIPS_LOCAL_GOTNO 0x7000000a +#define DT_MIPS_CONFLICTNO 0x7000000b +#define DT_MIPS_LIBLISTNO 0x70000010 +#define DT_MIPS_SYMTABNO 0x70000011 +#define DT_MIPS_UNREFEXTNO 0x70000012 +#define DT_MIPS_GOTSYM 0x70000013 +#define DT_MIPS_HIPAGENO 0x70000014 +#define DT_MIPS_RLD_MAP 0x70000016 +#define DT_MIPS_DELTA_CLASS 0x70000017 +#define DT_MIPS_DELTA_CLASS_NO 0x70000018 + +#define DT_MIPS_DELTA_INSTANCE 0x70000019 +#define DT_MIPS_DELTA_INSTANCE_NO 0x7000001a + +#define DT_MIPS_DELTA_RELOC 0x7000001b +#define DT_MIPS_DELTA_RELOC_NO 0x7000001c + +#define DT_MIPS_DELTA_SYM 0x7000001d + +#define DT_MIPS_DELTA_SYM_NO 0x7000001e + +#define DT_MIPS_DELTA_CLASSSYM 0x70000020 + +#define DT_MIPS_DELTA_CLASSSYM_NO 0x70000021 + +#define DT_MIPS_CXX_FLAGS 0x70000022 +#define DT_MIPS_PIXIE_INIT 0x70000023 +#define DT_MIPS_SYMBOL_LIB 0x70000024 +#define DT_MIPS_LOCALPAGE_GOTIDX 0x70000025 +#define DT_MIPS_LOCAL_GOTIDX 0x70000026 +#define DT_MIPS_HIDDEN_GOTIDX 0x70000027 +#define DT_MIPS_PROTECTED_GOTIDX 0x70000028 +#define DT_MIPS_OPTIONS 0x70000029 +#define DT_MIPS_INTERFACE 0x7000002a +#define DT_MIPS_DYNSTR_ALIGN 0x7000002b +#define DT_MIPS_INTERFACE_SIZE 0x7000002c +#define DT_MIPS_RLD_TEXT_RESOLVE_ADDR 0x7000002d + +#define DT_MIPS_PERF_SUFFIX 0x7000002e + +#define DT_MIPS_COMPACT_SIZE 0x7000002f +#define DT_MIPS_GP_VALUE 0x70000030 +#define DT_MIPS_AUX_DYNAMIC 0x70000031 + +#define DT_MIPS_PLTGOT 0x70000032 + +#define DT_MIPS_RWPLT 0x70000034 +#define DT_MIPS_RLD_MAP_REL 0x70000035 +#define DT_MIPS_NUM 0x36 + + + +#define RHF_NONE 0 +#define RHF_QUICKSTART (1 << 0) +#define RHF_NOTPOT (1 << 1) +#define RHF_NO_LIBRARY_REPLACEMENT (1 << 2) +#define RHF_NO_MOVE (1 << 3) +#define RHF_SGI_ONLY (1 << 4) +#define RHF_GUARANTEE_INIT (1 << 5) +#define RHF_DELTA_C_PLUS_PLUS (1 << 6) +#define RHF_GUARANTEE_START_INIT (1 << 7) +#define RHF_PIXIE (1 << 8) +#define RHF_DEFAULT_DELAY_LOAD (1 << 9) +#define RHF_REQUICKSTART (1 << 10) +#define RHF_REQUICKSTARTED (1 << 11) +#define RHF_CORD (1 << 12) +#define RHF_NO_UNRES_UNDEF (1 << 13) +#define RHF_RLD_ORDER_SAFE (1 << 14) + + + +typedef struct { + Elf32_Word l_name; + Elf32_Word l_time_stamp; + Elf32_Word l_checksum; + Elf32_Word l_version; + Elf32_Word l_flags; +} Elf32_Lib; + +typedef struct { + Elf64_Word l_name; + Elf64_Word l_time_stamp; + Elf64_Word l_checksum; + Elf64_Word l_version; + Elf64_Word l_flags; +} Elf64_Lib; + + + + +#define LL_NONE 0 +#define LL_EXACT_MATCH (1 << 0) +#define LL_IGNORE_INT_VER (1 << 1) +#define LL_REQUIRE_MINOR (1 << 2) +#define LL_EXPORTS (1 << 3) +#define LL_DELAY_LOAD (1 << 4) +#define LL_DELTA (1 << 5) + + + +typedef Elf32_Addr Elf32_Conflict; + +typedef struct { + Elf32_Half version; + unsigned char isa_level; + unsigned char isa_rev; + unsigned char gpr_size; + unsigned char cpr1_size; + unsigned char cpr2_size; + unsigned char fp_abi; + Elf32_Word isa_ext; + Elf32_Word ases; + Elf32_Word flags1; + Elf32_Word flags2; +} Elf_MIPS_ABIFlags_v0; + +#define MIPS_AFL_REG_NONE 0x00 +#define MIPS_AFL_REG_32 0x01 +#define MIPS_AFL_REG_64 0x02 +#define MIPS_AFL_REG_128 0x03 + +#define MIPS_AFL_ASE_DSP 0x00000001 +#define MIPS_AFL_ASE_DSPR2 0x00000002 +#define MIPS_AFL_ASE_EVA 0x00000004 +#define MIPS_AFL_ASE_MCU 0x00000008 +#define MIPS_AFL_ASE_MDMX 0x00000010 +#define MIPS_AFL_ASE_MIPS3D 0x00000020 +#define MIPS_AFL_ASE_MT 0x00000040 +#define MIPS_AFL_ASE_SMARTMIPS 0x00000080 +#define MIPS_AFL_ASE_VIRT 0x00000100 +#define MIPS_AFL_ASE_MSA 0x00000200 +#define MIPS_AFL_ASE_MIPS16 0x00000400 +#define MIPS_AFL_ASE_MICROMIPS 0x00000800 +#define MIPS_AFL_ASE_XPA 0x00001000 +#define MIPS_AFL_ASE_MASK 0x00001fff + +#define MIPS_AFL_EXT_XLR 1 +#define MIPS_AFL_EXT_OCTEON2 2 +#define MIPS_AFL_EXT_OCTEONP 3 +#define MIPS_AFL_EXT_LOONGSON_3A 4 +#define MIPS_AFL_EXT_OCTEON 5 +#define MIPS_AFL_EXT_5900 6 +#define MIPS_AFL_EXT_4650 7 +#define MIPS_AFL_EXT_4010 8 +#define MIPS_AFL_EXT_4100 9 +#define MIPS_AFL_EXT_3900 10 +#define MIPS_AFL_EXT_10000 11 +#define MIPS_AFL_EXT_SB1 12 +#define MIPS_AFL_EXT_4111 13 +#define MIPS_AFL_EXT_4120 14 +#define MIPS_AFL_EXT_5400 15 +#define MIPS_AFL_EXT_5500 16 +#define MIPS_AFL_EXT_LOONGSON_2E 17 +#define MIPS_AFL_EXT_LOONGSON_2F 18 + +#define MIPS_AFL_FLAGS1_ODDSPREG 1 + +enum +{ + Val_GNU_MIPS_ABI_FP_ANY = 0, + Val_GNU_MIPS_ABI_FP_DOUBLE = 1, + Val_GNU_MIPS_ABI_FP_SINGLE = 2, + Val_GNU_MIPS_ABI_FP_SOFT = 3, + Val_GNU_MIPS_ABI_FP_OLD_64 = 4, + Val_GNU_MIPS_ABI_FP_XX = 5, + Val_GNU_MIPS_ABI_FP_64 = 6, + Val_GNU_MIPS_ABI_FP_64A = 7, + Val_GNU_MIPS_ABI_FP_MAX = 7 +}; + + + + +#define EF_PARISC_TRAPNIL 0x00010000 +#define EF_PARISC_EXT 0x00020000 +#define EF_PARISC_LSB 0x00040000 +#define EF_PARISC_WIDE 0x00080000 +#define EF_PARISC_NO_KABP 0x00100000 + +#define EF_PARISC_LAZYSWAP 0x00400000 +#define EF_PARISC_ARCH 0x0000ffff + + + +#define EFA_PARISC_1_0 0x020b +#define EFA_PARISC_1_1 0x0210 +#define EFA_PARISC_2_0 0x0214 + + + +#define SHN_PARISC_ANSI_COMMON 0xff00 + +#define SHN_PARISC_HUGE_COMMON 0xff01 + + + +#define SHT_PARISC_EXT 0x70000000 +#define SHT_PARISC_UNWIND 0x70000001 +#define SHT_PARISC_DOC 0x70000002 + + + +#define SHF_PARISC_SHORT 0x20000000 +#define SHF_PARISC_HUGE 0x40000000 +#define SHF_PARISC_SBP 0x80000000 + + + +#define STT_PARISC_MILLICODE 13 + +#define STT_HP_OPAQUE (STT_LOOS + 0x1) +#define STT_HP_STUB (STT_LOOS + 0x2) + + + +#define R_PARISC_NONE 0 +#define R_PARISC_DIR32 1 +#define R_PARISC_DIR21L 2 +#define R_PARISC_DIR17R 3 +#define R_PARISC_DIR17F 4 +#define R_PARISC_DIR14R 6 +#define R_PARISC_PCREL32 9 +#define R_PARISC_PCREL21L 10 +#define R_PARISC_PCREL17R 11 +#define R_PARISC_PCREL17F 12 +#define R_PARISC_PCREL14R 14 +#define R_PARISC_DPREL21L 18 +#define R_PARISC_DPREL14R 22 +#define R_PARISC_GPREL21L 26 +#define R_PARISC_GPREL14R 30 +#define R_PARISC_LTOFF21L 34 +#define R_PARISC_LTOFF14R 38 +#define R_PARISC_SECREL32 41 +#define R_PARISC_SEGBASE 48 +#define R_PARISC_SEGREL32 49 +#define R_PARISC_PLTOFF21L 50 +#define R_PARISC_PLTOFF14R 54 +#define R_PARISC_LTOFF_FPTR32 57 +#define R_PARISC_LTOFF_FPTR21L 58 +#define R_PARISC_LTOFF_FPTR14R 62 +#define R_PARISC_FPTR64 64 +#define R_PARISC_PLABEL32 65 +#define R_PARISC_PLABEL21L 66 +#define R_PARISC_PLABEL14R 70 +#define R_PARISC_PCREL64 72 +#define R_PARISC_PCREL22F 74 +#define R_PARISC_PCREL14WR 75 +#define R_PARISC_PCREL14DR 76 +#define R_PARISC_PCREL16F 77 +#define R_PARISC_PCREL16WF 78 +#define R_PARISC_PCREL16DF 79 +#define R_PARISC_DIR64 80 +#define R_PARISC_DIR14WR 83 +#define R_PARISC_DIR14DR 84 +#define R_PARISC_DIR16F 85 +#define R_PARISC_DIR16WF 86 +#define R_PARISC_DIR16DF 87 +#define R_PARISC_GPREL64 88 +#define R_PARISC_GPREL14WR 91 +#define R_PARISC_GPREL14DR 92 +#define R_PARISC_GPREL16F 93 +#define R_PARISC_GPREL16WF 94 +#define R_PARISC_GPREL16DF 95 +#define R_PARISC_LTOFF64 96 +#define R_PARISC_LTOFF14WR 99 +#define R_PARISC_LTOFF14DR 100 +#define R_PARISC_LTOFF16F 101 +#define R_PARISC_LTOFF16WF 102 +#define R_PARISC_LTOFF16DF 103 +#define R_PARISC_SECREL64 104 +#define R_PARISC_SEGREL64 112 +#define R_PARISC_PLTOFF14WR 115 +#define R_PARISC_PLTOFF14DR 116 +#define R_PARISC_PLTOFF16F 117 +#define R_PARISC_PLTOFF16WF 118 +#define R_PARISC_PLTOFF16DF 119 +#define R_PARISC_LTOFF_FPTR64 120 +#define R_PARISC_LTOFF_FPTR14WR 123 +#define R_PARISC_LTOFF_FPTR14DR 124 +#define R_PARISC_LTOFF_FPTR16F 125 +#define R_PARISC_LTOFF_FPTR16WF 126 +#define R_PARISC_LTOFF_FPTR16DF 127 +#define R_PARISC_LORESERVE 128 +#define R_PARISC_COPY 128 +#define R_PARISC_IPLT 129 +#define R_PARISC_EPLT 130 +#define R_PARISC_TPREL32 153 +#define R_PARISC_TPREL21L 154 +#define R_PARISC_TPREL14R 158 +#define R_PARISC_LTOFF_TP21L 162 +#define R_PARISC_LTOFF_TP14R 166 +#define R_PARISC_LTOFF_TP14F 167 +#define R_PARISC_TPREL64 216 +#define R_PARISC_TPREL14WR 219 +#define R_PARISC_TPREL14DR 220 +#define R_PARISC_TPREL16F 221 +#define R_PARISC_TPREL16WF 222 +#define R_PARISC_TPREL16DF 223 +#define R_PARISC_LTOFF_TP64 224 +#define R_PARISC_LTOFF_TP14WR 227 +#define R_PARISC_LTOFF_TP14DR 228 +#define R_PARISC_LTOFF_TP16F 229 +#define R_PARISC_LTOFF_TP16WF 230 +#define R_PARISC_LTOFF_TP16DF 231 +#define R_PARISC_GNU_VTENTRY 232 +#define R_PARISC_GNU_VTINHERIT 233 +#define R_PARISC_TLS_GD21L 234 +#define R_PARISC_TLS_GD14R 235 +#define R_PARISC_TLS_GDCALL 236 +#define R_PARISC_TLS_LDM21L 237 +#define R_PARISC_TLS_LDM14R 238 +#define R_PARISC_TLS_LDMCALL 239 +#define R_PARISC_TLS_LDO21L 240 +#define R_PARISC_TLS_LDO14R 241 +#define R_PARISC_TLS_DTPMOD32 242 +#define R_PARISC_TLS_DTPMOD64 243 +#define R_PARISC_TLS_DTPOFF32 244 +#define R_PARISC_TLS_DTPOFF64 245 +#define R_PARISC_TLS_LE21L R_PARISC_TPREL21L +#define R_PARISC_TLS_LE14R R_PARISC_TPREL14R +#define R_PARISC_TLS_IE21L R_PARISC_LTOFF_TP21L +#define R_PARISC_TLS_IE14R R_PARISC_LTOFF_TP14R +#define R_PARISC_TLS_TPREL32 R_PARISC_TPREL32 +#define R_PARISC_TLS_TPREL64 R_PARISC_TPREL64 +#define R_PARISC_HIRESERVE 255 + + + +#define PT_HP_TLS (PT_LOOS + 0x0) +#define PT_HP_CORE_NONE (PT_LOOS + 0x1) +#define PT_HP_CORE_VERSION (PT_LOOS + 0x2) +#define PT_HP_CORE_KERNEL (PT_LOOS + 0x3) +#define PT_HP_CORE_COMM (PT_LOOS + 0x4) +#define PT_HP_CORE_PROC (PT_LOOS + 0x5) +#define PT_HP_CORE_LOADABLE (PT_LOOS + 0x6) +#define PT_HP_CORE_STACK (PT_LOOS + 0x7) +#define PT_HP_CORE_SHM (PT_LOOS + 0x8) +#define PT_HP_CORE_MMF (PT_LOOS + 0x9) +#define PT_HP_PARALLEL (PT_LOOS + 0x10) +#define PT_HP_FASTBIND (PT_LOOS + 0x11) +#define PT_HP_OPT_ANNOT (PT_LOOS + 0x12) +#define PT_HP_HSL_ANNOT (PT_LOOS + 0x13) +#define PT_HP_STACK (PT_LOOS + 0x14) + +#define PT_PARISC_ARCHEXT 0x70000000 +#define PT_PARISC_UNWIND 0x70000001 + + + +#define PF_PARISC_SBP 0x08000000 + +#define PF_HP_PAGE_SIZE 0x00100000 +#define PF_HP_FAR_SHARED 0x00200000 +#define PF_HP_NEAR_SHARED 0x00400000 +#define PF_HP_CODE 0x01000000 +#define PF_HP_MODIFY 0x02000000 +#define PF_HP_LAZYSWAP 0x04000000 +#define PF_HP_SBP 0x08000000 + + + + + + +#define EF_ALPHA_32BIT 1 +#define EF_ALPHA_CANRELAX 2 + + + + +#define SHT_ALPHA_DEBUG 0x70000001 +#define SHT_ALPHA_REGINFO 0x70000002 + + + +#define SHF_ALPHA_GPREL 0x10000000 + + +#define STO_ALPHA_NOPV 0x80 +#define STO_ALPHA_STD_GPLOAD 0x88 + + + +#define R_ALPHA_NONE 0 +#define R_ALPHA_REFLONG 1 +#define R_ALPHA_REFQUAD 2 +#define R_ALPHA_GPREL32 3 +#define R_ALPHA_LITERAL 4 +#define R_ALPHA_LITUSE 5 +#define R_ALPHA_GPDISP 6 +#define R_ALPHA_BRADDR 7 +#define R_ALPHA_HINT 8 +#define R_ALPHA_SREL16 9 +#define R_ALPHA_SREL32 10 +#define R_ALPHA_SREL64 11 +#define R_ALPHA_GPRELHIGH 17 +#define R_ALPHA_GPRELLOW 18 +#define R_ALPHA_GPREL16 19 +#define R_ALPHA_COPY 24 +#define R_ALPHA_GLOB_DAT 25 +#define R_ALPHA_JMP_SLOT 26 +#define R_ALPHA_RELATIVE 27 +#define R_ALPHA_TLS_GD_HI 28 +#define R_ALPHA_TLSGD 29 +#define R_ALPHA_TLS_LDM 30 +#define R_ALPHA_DTPMOD64 31 +#define R_ALPHA_GOTDTPREL 32 +#define R_ALPHA_DTPREL64 33 +#define R_ALPHA_DTPRELHI 34 +#define R_ALPHA_DTPRELLO 35 +#define R_ALPHA_DTPREL16 36 +#define R_ALPHA_GOTTPREL 37 +#define R_ALPHA_TPREL64 38 +#define R_ALPHA_TPRELHI 39 +#define R_ALPHA_TPRELLO 40 +#define R_ALPHA_TPREL16 41 + +#define R_ALPHA_NUM 46 + + +#define LITUSE_ALPHA_ADDR 0 +#define LITUSE_ALPHA_BASE 1 +#define LITUSE_ALPHA_BYTOFF 2 +#define LITUSE_ALPHA_JSR 3 +#define LITUSE_ALPHA_TLS_GD 4 +#define LITUSE_ALPHA_TLS_LDM 5 + + +#define DT_ALPHA_PLTRO (DT_LOPROC + 0) +#define DT_ALPHA_NUM 1 + + + + +#define EF_PPC_EMB 0x80000000 + + +#define EF_PPC_RELOCATABLE 0x00010000 +#define EF_PPC_RELOCATABLE_LIB 0x00008000 + + + +#define R_PPC_NONE 0 +#define R_PPC_ADDR32 1 +#define R_PPC_ADDR24 2 +#define R_PPC_ADDR16 3 +#define R_PPC_ADDR16_LO 4 +#define R_PPC_ADDR16_HI 5 +#define R_PPC_ADDR16_HA 6 +#define R_PPC_ADDR14 7 +#define R_PPC_ADDR14_BRTAKEN 8 +#define R_PPC_ADDR14_BRNTAKEN 9 +#define R_PPC_REL24 10 +#define R_PPC_REL14 11 +#define R_PPC_REL14_BRTAKEN 12 +#define R_PPC_REL14_BRNTAKEN 13 +#define R_PPC_GOT16 14 +#define R_PPC_GOT16_LO 15 +#define R_PPC_GOT16_HI 16 +#define R_PPC_GOT16_HA 17 +#define R_PPC_PLTREL24 18 +#define R_PPC_COPY 19 +#define R_PPC_GLOB_DAT 20 +#define R_PPC_JMP_SLOT 21 +#define R_PPC_RELATIVE 22 +#define R_PPC_LOCAL24PC 23 +#define R_PPC_UADDR32 24 +#define R_PPC_UADDR16 25 +#define R_PPC_REL32 26 +#define R_PPC_PLT32 27 +#define R_PPC_PLTREL32 28 +#define R_PPC_PLT16_LO 29 +#define R_PPC_PLT16_HI 30 +#define R_PPC_PLT16_HA 31 +#define R_PPC_SDAREL16 32 +#define R_PPC_SECTOFF 33 +#define R_PPC_SECTOFF_LO 34 +#define R_PPC_SECTOFF_HI 35 +#define R_PPC_SECTOFF_HA 36 + + +#define R_PPC_TLS 67 +#define R_PPC_DTPMOD32 68 +#define R_PPC_TPREL16 69 +#define R_PPC_TPREL16_LO 70 +#define R_PPC_TPREL16_HI 71 +#define R_PPC_TPREL16_HA 72 +#define R_PPC_TPREL32 73 +#define R_PPC_DTPREL16 74 +#define R_PPC_DTPREL16_LO 75 +#define R_PPC_DTPREL16_HI 76 +#define R_PPC_DTPREL16_HA 77 +#define R_PPC_DTPREL32 78 +#define R_PPC_GOT_TLSGD16 79 +#define R_PPC_GOT_TLSGD16_LO 80 +#define R_PPC_GOT_TLSGD16_HI 81 +#define R_PPC_GOT_TLSGD16_HA 82 +#define R_PPC_GOT_TLSLD16 83 +#define R_PPC_GOT_TLSLD16_LO 84 +#define R_PPC_GOT_TLSLD16_HI 85 +#define R_PPC_GOT_TLSLD16_HA 86 +#define R_PPC_GOT_TPREL16 87 +#define R_PPC_GOT_TPREL16_LO 88 +#define R_PPC_GOT_TPREL16_HI 89 +#define R_PPC_GOT_TPREL16_HA 90 +#define R_PPC_GOT_DTPREL16 91 +#define R_PPC_GOT_DTPREL16_LO 92 +#define R_PPC_GOT_DTPREL16_HI 93 +#define R_PPC_GOT_DTPREL16_HA 94 +#define R_PPC_TLSGD 95 +#define R_PPC_TLSLD 96 + + +#define R_PPC_EMB_NADDR32 101 +#define R_PPC_EMB_NADDR16 102 +#define R_PPC_EMB_NADDR16_LO 103 +#define R_PPC_EMB_NADDR16_HI 104 +#define R_PPC_EMB_NADDR16_HA 105 +#define R_PPC_EMB_SDAI16 106 +#define R_PPC_EMB_SDA2I16 107 +#define R_PPC_EMB_SDA2REL 108 +#define R_PPC_EMB_SDA21 109 +#define R_PPC_EMB_MRKREF 110 +#define R_PPC_EMB_RELSEC16 111 +#define R_PPC_EMB_RELST_LO 112 +#define R_PPC_EMB_RELST_HI 113 +#define R_PPC_EMB_RELST_HA 114 +#define R_PPC_EMB_BIT_FLD 115 +#define R_PPC_EMB_RELSDA 116 + + +#define R_PPC_DIAB_SDA21_LO 180 +#define R_PPC_DIAB_SDA21_HI 181 +#define R_PPC_DIAB_SDA21_HA 182 +#define R_PPC_DIAB_RELSDA_LO 183 +#define R_PPC_DIAB_RELSDA_HI 184 +#define R_PPC_DIAB_RELSDA_HA 185 + + +#define R_PPC_IRELATIVE 248 + + +#define R_PPC_REL16 249 +#define R_PPC_REL16_LO 250 +#define R_PPC_REL16_HI 251 +#define R_PPC_REL16_HA 252 + + + +#define R_PPC_TOC16 255 + + +#define DT_PPC_GOT (DT_LOPROC + 0) +#define DT_PPC_OPT (DT_LOPROC + 1) +#define DT_PPC_NUM 2 + +#define PPC_OPT_TLS 1 + + +#define R_PPC64_NONE R_PPC_NONE +#define R_PPC64_ADDR32 R_PPC_ADDR32 +#define R_PPC64_ADDR24 R_PPC_ADDR24 +#define R_PPC64_ADDR16 R_PPC_ADDR16 +#define R_PPC64_ADDR16_LO R_PPC_ADDR16_LO +#define R_PPC64_ADDR16_HI R_PPC_ADDR16_HI +#define R_PPC64_ADDR16_HA R_PPC_ADDR16_HA +#define R_PPC64_ADDR14 R_PPC_ADDR14 +#define R_PPC64_ADDR14_BRTAKEN R_PPC_ADDR14_BRTAKEN +#define R_PPC64_ADDR14_BRNTAKEN R_PPC_ADDR14_BRNTAKEN +#define R_PPC64_REL24 R_PPC_REL24 +#define R_PPC64_REL14 R_PPC_REL14 +#define R_PPC64_REL14_BRTAKEN R_PPC_REL14_BRTAKEN +#define R_PPC64_REL14_BRNTAKEN R_PPC_REL14_BRNTAKEN +#define R_PPC64_GOT16 R_PPC_GOT16 +#define R_PPC64_GOT16_LO R_PPC_GOT16_LO +#define R_PPC64_GOT16_HI R_PPC_GOT16_HI +#define R_PPC64_GOT16_HA R_PPC_GOT16_HA + +#define R_PPC64_COPY R_PPC_COPY +#define R_PPC64_GLOB_DAT R_PPC_GLOB_DAT +#define R_PPC64_JMP_SLOT R_PPC_JMP_SLOT +#define R_PPC64_RELATIVE R_PPC_RELATIVE + +#define R_PPC64_UADDR32 R_PPC_UADDR32 +#define R_PPC64_UADDR16 R_PPC_UADDR16 +#define R_PPC64_REL32 R_PPC_REL32 +#define R_PPC64_PLT32 R_PPC_PLT32 +#define R_PPC64_PLTREL32 R_PPC_PLTREL32 +#define R_PPC64_PLT16_LO R_PPC_PLT16_LO +#define R_PPC64_PLT16_HI R_PPC_PLT16_HI +#define R_PPC64_PLT16_HA R_PPC_PLT16_HA + +#define R_PPC64_SECTOFF R_PPC_SECTOFF +#define R_PPC64_SECTOFF_LO R_PPC_SECTOFF_LO +#define R_PPC64_SECTOFF_HI R_PPC_SECTOFF_HI +#define R_PPC64_SECTOFF_HA R_PPC_SECTOFF_HA +#define R_PPC64_ADDR30 37 +#define R_PPC64_ADDR64 38 +#define R_PPC64_ADDR16_HIGHER 39 +#define R_PPC64_ADDR16_HIGHERA 40 +#define R_PPC64_ADDR16_HIGHEST 41 +#define R_PPC64_ADDR16_HIGHESTA 42 +#define R_PPC64_UADDR64 43 +#define R_PPC64_REL64 44 +#define R_PPC64_PLT64 45 +#define R_PPC64_PLTREL64 46 +#define R_PPC64_TOC16 47 +#define R_PPC64_TOC16_LO 48 +#define R_PPC64_TOC16_HI 49 +#define R_PPC64_TOC16_HA 50 +#define R_PPC64_TOC 51 +#define R_PPC64_PLTGOT16 52 +#define R_PPC64_PLTGOT16_LO 53 +#define R_PPC64_PLTGOT16_HI 54 +#define R_PPC64_PLTGOT16_HA 55 + +#define R_PPC64_ADDR16_DS 56 +#define R_PPC64_ADDR16_LO_DS 57 +#define R_PPC64_GOT16_DS 58 +#define R_PPC64_GOT16_LO_DS 59 +#define R_PPC64_PLT16_LO_DS 60 +#define R_PPC64_SECTOFF_DS 61 +#define R_PPC64_SECTOFF_LO_DS 62 +#define R_PPC64_TOC16_DS 63 +#define R_PPC64_TOC16_LO_DS 64 +#define R_PPC64_PLTGOT16_DS 65 +#define R_PPC64_PLTGOT16_LO_DS 66 + + +#define R_PPC64_TLS 67 +#define R_PPC64_DTPMOD64 68 +#define R_PPC64_TPREL16 69 +#define R_PPC64_TPREL16_LO 70 +#define R_PPC64_TPREL16_HI 71 +#define R_PPC64_TPREL16_HA 72 +#define R_PPC64_TPREL64 73 +#define R_PPC64_DTPREL16 74 +#define R_PPC64_DTPREL16_LO 75 +#define R_PPC64_DTPREL16_HI 76 +#define R_PPC64_DTPREL16_HA 77 +#define R_PPC64_DTPREL64 78 +#define R_PPC64_GOT_TLSGD16 79 +#define R_PPC64_GOT_TLSGD16_LO 80 +#define R_PPC64_GOT_TLSGD16_HI 81 +#define R_PPC64_GOT_TLSGD16_HA 82 +#define R_PPC64_GOT_TLSLD16 83 +#define R_PPC64_GOT_TLSLD16_LO 84 +#define R_PPC64_GOT_TLSLD16_HI 85 +#define R_PPC64_GOT_TLSLD16_HA 86 +#define R_PPC64_GOT_TPREL16_DS 87 +#define R_PPC64_GOT_TPREL16_LO_DS 88 +#define R_PPC64_GOT_TPREL16_HI 89 +#define R_PPC64_GOT_TPREL16_HA 90 +#define R_PPC64_GOT_DTPREL16_DS 91 +#define R_PPC64_GOT_DTPREL16_LO_DS 92 +#define R_PPC64_GOT_DTPREL16_HI 93 +#define R_PPC64_GOT_DTPREL16_HA 94 +#define R_PPC64_TPREL16_DS 95 +#define R_PPC64_TPREL16_LO_DS 96 +#define R_PPC64_TPREL16_HIGHER 97 +#define R_PPC64_TPREL16_HIGHERA 98 +#define R_PPC64_TPREL16_HIGHEST 99 +#define R_PPC64_TPREL16_HIGHESTA 100 +#define R_PPC64_DTPREL16_DS 101 +#define R_PPC64_DTPREL16_LO_DS 102 +#define R_PPC64_DTPREL16_HIGHER 103 +#define R_PPC64_DTPREL16_HIGHERA 104 +#define R_PPC64_DTPREL16_HIGHEST 105 +#define R_PPC64_DTPREL16_HIGHESTA 106 +#define R_PPC64_TLSGD 107 +#define R_PPC64_TLSLD 108 +#define R_PPC64_TOCSAVE 109 +#define R_PPC64_ADDR16_HIGH 110 +#define R_PPC64_ADDR16_HIGHA 111 +#define R_PPC64_TPREL16_HIGH 112 +#define R_PPC64_TPREL16_HIGHA 113 +#define R_PPC64_DTPREL16_HIGH 114 +#define R_PPC64_DTPREL16_HIGHA 115 + + +#define R_PPC64_JMP_IREL 247 +#define R_PPC64_IRELATIVE 248 +#define R_PPC64_REL16 249 +#define R_PPC64_REL16_LO 250 +#define R_PPC64_REL16_HI 251 +#define R_PPC64_REL16_HA 252 + +#define EF_PPC64_ABI 3 + +#define DT_PPC64_GLINK (DT_LOPROC + 0) +#define DT_PPC64_OPD (DT_LOPROC + 1) +#define DT_PPC64_OPDSZ (DT_LOPROC + 2) +#define DT_PPC64_OPT (DT_LOPROC + 3) +#define DT_PPC64_NUM 4 + +#define PPC64_OPT_TLS 1 +#define PPC64_OPT_MULTI_TOC 2 +#define PPC64_OPT_LOCALENTRY 4 + +#define STO_PPC64_LOCAL_BIT 5 +#define STO_PPC64_LOCAL_MASK 0xe0 +#define PPC64_LOCAL_ENTRY_OFFSET(x) (1 << (((x)&0xe0)>>5) & 0xfc) + + +#define EF_ARM_RELEXEC 0x01 +#define EF_ARM_HASENTRY 0x02 +#define EF_ARM_INTERWORK 0x04 +#define EF_ARM_APCS_26 0x08 +#define EF_ARM_APCS_FLOAT 0x10 +#define EF_ARM_PIC 0x20 +#define EF_ARM_ALIGN8 0x40 +#define EF_ARM_NEW_ABI 0x80 +#define EF_ARM_OLD_ABI 0x100 +#define EF_ARM_SOFT_FLOAT 0x200 +#define EF_ARM_VFP_FLOAT 0x400 +#define EF_ARM_MAVERICK_FLOAT 0x800 + +#define EF_ARM_ABI_FLOAT_SOFT 0x200 +#define EF_ARM_ABI_FLOAT_HARD 0x400 + + +#define EF_ARM_SYMSARESORTED 0x04 +#define EF_ARM_DYNSYMSUSESEGIDX 0x08 +#define EF_ARM_MAPSYMSFIRST 0x10 +#define EF_ARM_EABIMASK 0XFF000000 + + +#define EF_ARM_BE8 0x00800000 +#define EF_ARM_LE8 0x00400000 + +#define EF_ARM_EABI_VERSION(flags) ((flags) & EF_ARM_EABIMASK) +#define EF_ARM_EABI_UNKNOWN 0x00000000 +#define EF_ARM_EABI_VER1 0x01000000 +#define EF_ARM_EABI_VER2 0x02000000 +#define EF_ARM_EABI_VER3 0x03000000 +#define EF_ARM_EABI_VER4 0x04000000 +#define EF_ARM_EABI_VER5 0x05000000 + + +#define STT_ARM_TFUNC STT_LOPROC +#define STT_ARM_16BIT STT_HIPROC + + +#define SHF_ARM_ENTRYSECT 0x10000000 +#define SHF_ARM_COMDEF 0x80000000 + + + +#define PF_ARM_SB 0x10000000 + +#define PF_ARM_PI 0x20000000 +#define PF_ARM_ABS 0x40000000 + + +#define PT_ARM_EXIDX (PT_LOPROC + 1) + + +#define SHT_ARM_EXIDX (SHT_LOPROC + 1) +#define SHT_ARM_PREEMPTMAP (SHT_LOPROC + 2) +#define SHT_ARM_ATTRIBUTES (SHT_LOPROC + 3) + +#define R_AARCH64_NONE 0 +#define R_AARCH64_P32_ABS32 1 +#define R_AARCH64_P32_COPY 180 +#define R_AARCH64_P32_GLOB_DAT 181 +#define R_AARCH64_P32_JUMP_SLOT 182 +#define R_AARCH64_P32_RELATIVE 183 +#define R_AARCH64_P32_TLS_DTPMOD 184 +#define R_AARCH64_P32_TLS_DTPREL 185 +#define R_AARCH64_P32_TLS_TPREL 186 +#define R_AARCH64_P32_TLSDESC 187 +#define R_AARCH64_P32_IRELATIVE 188 +#define R_AARCH64_ABS64 257 +#define R_AARCH64_ABS32 258 +#define R_AARCH64_ABS16 259 +#define R_AARCH64_PREL64 260 +#define R_AARCH64_PREL32 261 +#define R_AARCH64_PREL16 262 +#define R_AARCH64_MOVW_UABS_G0 263 +#define R_AARCH64_MOVW_UABS_G0_NC 264 +#define R_AARCH64_MOVW_UABS_G1 265 +#define R_AARCH64_MOVW_UABS_G1_NC 266 +#define R_AARCH64_MOVW_UABS_G2 267 +#define R_AARCH64_MOVW_UABS_G2_NC 268 +#define R_AARCH64_MOVW_UABS_G3 269 +#define R_AARCH64_MOVW_SABS_G0 270 +#define R_AARCH64_MOVW_SABS_G1 271 +#define R_AARCH64_MOVW_SABS_G2 272 +#define R_AARCH64_LD_PREL_LO19 273 +#define R_AARCH64_ADR_PREL_LO21 274 +#define R_AARCH64_ADR_PREL_PG_HI21 275 +#define R_AARCH64_ADR_PREL_PG_HI21_NC 276 +#define R_AARCH64_ADD_ABS_LO12_NC 277 +#define R_AARCH64_LDST8_ABS_LO12_NC 278 +#define R_AARCH64_TSTBR14 279 +#define R_AARCH64_CONDBR19 280 +#define R_AARCH64_JUMP26 282 +#define R_AARCH64_CALL26 283 +#define R_AARCH64_LDST16_ABS_LO12_NC 284 +#define R_AARCH64_LDST32_ABS_LO12_NC 285 +#define R_AARCH64_LDST64_ABS_LO12_NC 286 +#define R_AARCH64_MOVW_PREL_G0 287 +#define R_AARCH64_MOVW_PREL_G0_NC 288 +#define R_AARCH64_MOVW_PREL_G1 289 +#define R_AARCH64_MOVW_PREL_G1_NC 290 +#define R_AARCH64_MOVW_PREL_G2 291 +#define R_AARCH64_MOVW_PREL_G2_NC 292 +#define R_AARCH64_MOVW_PREL_G3 293 +#define R_AARCH64_LDST128_ABS_LO12_NC 299 +#define R_AARCH64_MOVW_GOTOFF_G0 300 +#define R_AARCH64_MOVW_GOTOFF_G0_NC 301 +#define R_AARCH64_MOVW_GOTOFF_G1 302 +#define R_AARCH64_MOVW_GOTOFF_G1_NC 303 +#define R_AARCH64_MOVW_GOTOFF_G2 304 +#define R_AARCH64_MOVW_GOTOFF_G2_NC 305 +#define R_AARCH64_MOVW_GOTOFF_G3 306 +#define R_AARCH64_GOTREL64 307 +#define R_AARCH64_GOTREL32 308 +#define R_AARCH64_GOT_LD_PREL19 309 +#define R_AARCH64_LD64_GOTOFF_LO15 310 +#define R_AARCH64_ADR_GOT_PAGE 311 +#define R_AARCH64_LD64_GOT_LO12_NC 312 +#define R_AARCH64_LD64_GOTPAGE_LO15 313 +#define R_AARCH64_TLSGD_ADR_PREL21 512 +#define R_AARCH64_TLSGD_ADR_PAGE21 513 +#define R_AARCH64_TLSGD_ADD_LO12_NC 514 +#define R_AARCH64_TLSGD_MOVW_G1 515 +#define R_AARCH64_TLSGD_MOVW_G0_NC 516 +#define R_AARCH64_TLSLD_ADR_PREL21 517 +#define R_AARCH64_TLSLD_ADR_PAGE21 518 +#define R_AARCH64_TLSLD_ADD_LO12_NC 519 +#define R_AARCH64_TLSLD_MOVW_G1 520 +#define R_AARCH64_TLSLD_MOVW_G0_NC 521 +#define R_AARCH64_TLSLD_LD_PREL19 522 +#define R_AARCH64_TLSLD_MOVW_DTPREL_G2 523 +#define R_AARCH64_TLSLD_MOVW_DTPREL_G1 524 +#define R_AARCH64_TLSLD_MOVW_DTPREL_G1_NC 525 +#define R_AARCH64_TLSLD_MOVW_DTPREL_G0 526 +#define R_AARCH64_TLSLD_MOVW_DTPREL_G0_NC 527 +#define R_AARCH64_TLSLD_ADD_DTPREL_HI12 528 +#define R_AARCH64_TLSLD_ADD_DTPREL_LO12 529 +#define R_AARCH64_TLSLD_ADD_DTPREL_LO12_NC 530 +#define R_AARCH64_TLSLD_LDST8_DTPREL_LO12 531 +#define R_AARCH64_TLSLD_LDST8_DTPREL_LO12_NC 532 +#define R_AARCH64_TLSLD_LDST16_DTPREL_LO12 533 +#define R_AARCH64_TLSLD_LDST16_DTPREL_LO12_NC 534 +#define R_AARCH64_TLSLD_LDST32_DTPREL_LO12 535 +#define R_AARCH64_TLSLD_LDST32_DTPREL_LO12_NC 536 +#define R_AARCH64_TLSLD_LDST64_DTPREL_LO12 537 +#define R_AARCH64_TLSLD_LDST64_DTPREL_LO12_NC 538 +#define R_AARCH64_TLSIE_MOVW_GOTTPREL_G1 539 +#define R_AARCH64_TLSIE_MOVW_GOTTPREL_G0_NC 540 +#define R_AARCH64_TLSIE_ADR_GOTTPREL_PAGE21 541 +#define R_AARCH64_TLSIE_LD64_GOTTPREL_LO12_NC 542 +#define R_AARCH64_TLSIE_LD_GOTTPREL_PREL19 543 +#define R_AARCH64_TLSLE_MOVW_TPREL_G2 544 +#define R_AARCH64_TLSLE_MOVW_TPREL_G1 545 +#define R_AARCH64_TLSLE_MOVW_TPREL_G1_NC 546 +#define R_AARCH64_TLSLE_MOVW_TPREL_G0 547 +#define R_AARCH64_TLSLE_MOVW_TPREL_G0_NC 548 +#define R_AARCH64_TLSLE_ADD_TPREL_HI12 549 +#define R_AARCH64_TLSLE_ADD_TPREL_LO12 550 +#define R_AARCH64_TLSLE_ADD_TPREL_LO12_NC 551 +#define R_AARCH64_TLSLE_LDST8_TPREL_LO12 552 +#define R_AARCH64_TLSLE_LDST8_TPREL_LO12_NC 553 +#define R_AARCH64_TLSLE_LDST16_TPREL_LO12 554 +#define R_AARCH64_TLSLE_LDST16_TPREL_LO12_NC 555 +#define R_AARCH64_TLSLE_LDST32_TPREL_LO12 556 +#define R_AARCH64_TLSLE_LDST32_TPREL_LO12_NC 557 +#define R_AARCH64_TLSLE_LDST64_TPREL_LO12 558 +#define R_AARCH64_TLSLE_LDST64_TPREL_LO12_NC 559 +#define R_AARCH64_TLSDESC_LD_PREL19 560 +#define R_AARCH64_TLSDESC_ADR_PREL21 561 +#define R_AARCH64_TLSDESC_ADR_PAGE21 562 +#define R_AARCH64_TLSDESC_LD64_LO12 563 +#define R_AARCH64_TLSDESC_ADD_LO12 564 +#define R_AARCH64_TLSDESC_OFF_G1 565 +#define R_AARCH64_TLSDESC_OFF_G0_NC 566 +#define R_AARCH64_TLSDESC_LDR 567 +#define R_AARCH64_TLSDESC_ADD 568 +#define R_AARCH64_TLSDESC_CALL 569 +#define R_AARCH64_TLSLE_LDST128_TPREL_LO12 570 +#define R_AARCH64_TLSLE_LDST128_TPREL_LO12_NC 571 +#define R_AARCH64_TLSLD_LDST128_DTPREL_LO12 572 +#define R_AARCH64_TLSLD_LDST128_DTPREL_LO12_NC 573 +#define R_AARCH64_COPY 1024 +#define R_AARCH64_GLOB_DAT 1025 +#define R_AARCH64_JUMP_SLOT 1026 +#define R_AARCH64_RELATIVE 1027 +#define R_AARCH64_TLS_DTPMOD 1028 +#define R_AARCH64_TLS_DTPMOD64 1028 +#define R_AARCH64_TLS_DTPREL 1029 +#define R_AARCH64_TLS_DTPREL64 1029 +#define R_AARCH64_TLS_TPREL 1030 +#define R_AARCH64_TLS_TPREL64 1030 +#define R_AARCH64_TLSDESC 1031 + + +#define R_ARM_NONE 0 +#define R_ARM_PC24 1 +#define R_ARM_ABS32 2 +#define R_ARM_REL32 3 +#define R_ARM_PC13 4 +#define R_ARM_ABS16 5 +#define R_ARM_ABS12 6 +#define R_ARM_THM_ABS5 7 +#define R_ARM_ABS8 8 +#define R_ARM_SBREL32 9 +#define R_ARM_THM_PC22 10 +#define R_ARM_THM_PC8 11 +#define R_ARM_AMP_VCALL9 12 +#define R_ARM_TLS_DESC 13 +#define R_ARM_THM_SWI8 14 +#define R_ARM_XPC25 15 +#define R_ARM_THM_XPC22 16 +#define R_ARM_TLS_DTPMOD32 17 +#define R_ARM_TLS_DTPOFF32 18 +#define R_ARM_TLS_TPOFF32 19 +#define R_ARM_COPY 20 +#define R_ARM_GLOB_DAT 21 +#define R_ARM_JUMP_SLOT 22 +#define R_ARM_RELATIVE 23 +#define R_ARM_GOTOFF 24 +#define R_ARM_GOTPC 25 +#define R_ARM_GOT32 26 +#define R_ARM_PLT32 27 +#define R_ARM_CALL 28 +#define R_ARM_JUMP24 29 +#define R_ARM_THM_JUMP24 30 +#define R_ARM_BASE_ABS 31 +#define R_ARM_ALU_PCREL_7_0 32 +#define R_ARM_ALU_PCREL_15_8 33 +#define R_ARM_ALU_PCREL_23_15 34 +#define R_ARM_LDR_SBREL_11_0 35 +#define R_ARM_ALU_SBREL_19_12 36 +#define R_ARM_ALU_SBREL_27_20 37 +#define R_ARM_TARGET1 38 +#define R_ARM_SBREL31 39 +#define R_ARM_V4BX 40 +#define R_ARM_TARGET2 41 +#define R_ARM_PREL31 42 +#define R_ARM_MOVW_ABS_NC 43 +#define R_ARM_MOVT_ABS 44 +#define R_ARM_MOVW_PREL_NC 45 +#define R_ARM_MOVT_PREL 46 +#define R_ARM_THM_MOVW_ABS_NC 47 +#define R_ARM_THM_MOVT_ABS 48 +#define R_ARM_THM_MOVW_PREL_NC 49 +#define R_ARM_THM_MOVT_PREL 50 +#define R_ARM_THM_JUMP19 51 +#define R_ARM_THM_JUMP6 52 +#define R_ARM_THM_ALU_PREL_11_0 53 +#define R_ARM_THM_PC12 54 +#define R_ARM_ABS32_NOI 55 +#define R_ARM_REL32_NOI 56 +#define R_ARM_ALU_PC_G0_NC 57 +#define R_ARM_ALU_PC_G0 58 +#define R_ARM_ALU_PC_G1_NC 59 +#define R_ARM_ALU_PC_G1 60 +#define R_ARM_ALU_PC_G2 61 +#define R_ARM_LDR_PC_G1 62 +#define R_ARM_LDR_PC_G2 63 +#define R_ARM_LDRS_PC_G0 64 +#define R_ARM_LDRS_PC_G1 65 +#define R_ARM_LDRS_PC_G2 66 +#define R_ARM_LDC_PC_G0 67 +#define R_ARM_LDC_PC_G1 68 +#define R_ARM_LDC_PC_G2 69 +#define R_ARM_ALU_SB_G0_NC 70 +#define R_ARM_ALU_SB_G0 71 +#define R_ARM_ALU_SB_G1_NC 72 +#define R_ARM_ALU_SB_G1 73 +#define R_ARM_ALU_SB_G2 74 +#define R_ARM_LDR_SB_G0 75 +#define R_ARM_LDR_SB_G1 76 +#define R_ARM_LDR_SB_G2 77 +#define R_ARM_LDRS_SB_G0 78 +#define R_ARM_LDRS_SB_G1 79 +#define R_ARM_LDRS_SB_G2 80 +#define R_ARM_LDC_SB_G0 81 +#define R_ARM_LDC_SB_G1 82 +#define R_ARM_LDC_SB_G2 83 +#define R_ARM_MOVW_BREL_NC 84 +#define R_ARM_MOVT_BREL 85 +#define R_ARM_MOVW_BREL 86 +#define R_ARM_THM_MOVW_BREL_NC 87 +#define R_ARM_THM_MOVT_BREL 88 +#define R_ARM_THM_MOVW_BREL 89 +#define R_ARM_TLS_GOTDESC 90 +#define R_ARM_TLS_CALL 91 +#define R_ARM_TLS_DESCSEQ 92 +#define R_ARM_THM_TLS_CALL 93 +#define R_ARM_PLT32_ABS 94 +#define R_ARM_GOT_ABS 95 +#define R_ARM_GOT_PREL 96 +#define R_ARM_GOT_BREL12 97 +#define R_ARM_GOTOFF12 98 +#define R_ARM_GOTRELAX 99 +#define R_ARM_GNU_VTENTRY 100 +#define R_ARM_GNU_VTINHERIT 101 +#define R_ARM_THM_PC11 102 +#define R_ARM_THM_PC9 103 +#define R_ARM_TLS_GD32 104 + +#define R_ARM_TLS_LDM32 105 + +#define R_ARM_TLS_LDO32 106 + +#define R_ARM_TLS_IE32 107 + +#define R_ARM_TLS_LE32 108 +#define R_ARM_TLS_LDO12 109 +#define R_ARM_TLS_LE12 110 +#define R_ARM_TLS_IE12GP 111 +#define R_ARM_ME_TOO 128 +#define R_ARM_THM_TLS_DESCSEQ 129 +#define R_ARM_THM_TLS_DESCSEQ16 129 +#define R_ARM_THM_TLS_DESCSEQ32 130 +#define R_ARM_THM_GOT_BREL12 131 +#define R_ARM_IRELATIVE 160 +#define R_ARM_RXPC25 249 +#define R_ARM_RSBREL32 250 +#define R_ARM_THM_RPC22 251 +#define R_ARM_RREL32 252 +#define R_ARM_RABS22 253 +#define R_ARM_RPC24 254 +#define R_ARM_RBASE 255 + +#define R_ARM_NUM 256 + + +#define R_CKCORE_NONE 0 +#define R_CKCORE_ADDR32 1 +#define R_CKCORE_PCRELIMM8BY4 2 +#define R_CKCORE_PCRELIMM11BY2 3 +#define R_CKCORE_PCREL32 5 +#define R_CKCORE_PCRELJSR_IMM11BY2 6 +#define R_CKCORE_RELATIVE 9 +#define R_CKCORE_COPY 10 +#define R_CKCORE_GLOB_DAT 11 +#define R_CKCORE_JUMP_SLOT 12 +#define R_CKCORE_GOTOFF 13 +#define R_CKCORE_GOTPC 14 +#define R_CKCORE_GOT32 15 +#define R_CKCORE_PLT32 16 +#define R_CKCORE_ADDRGOT 17 +#define R_CKCORE_ADDRPLT 18 +#define R_CKCORE_PCREL_IMM26BY2 19 +#define R_CKCORE_PCREL_IMM16BY2 20 +#define R_CKCORE_PCREL_IMM16BY4 21 +#define R_CKCORE_PCREL_IMM10BY2 22 +#define R_CKCORE_PCREL_IMM10BY4 23 +#define R_CKCORE_ADDR_HI16 24 +#define R_CKCORE_ADDR_LO16 25 +#define R_CKCORE_GOTPC_HI16 26 +#define R_CKCORE_GOTPC_LO16 27 +#define R_CKCORE_GOTOFF_HI16 28 +#define R_CKCORE_GOTOFF_LO16 29 +#define R_CKCORE_GOT12 30 +#define R_CKCORE_GOT_HI16 31 +#define R_CKCORE_GOT_LO16 32 +#define R_CKCORE_PLT12 33 +#define R_CKCORE_PLT_HI16 34 +#define R_CKCORE_PLT_LO16 35 +#define R_CKCORE_ADDRGOT_HI16 36 +#define R_CKCORE_ADDRGOT_LO16 37 +#define R_CKCORE_ADDRPLT_HI16 38 +#define R_CKCORE_ADDRPLT_LO16 39 +#define R_CKCORE_PCREL_JSR_IMM26BY2 40 +#define R_CKCORE_TOFFSET_LO16 41 +#define R_CKCORE_DOFFSET_LO16 42 +#define R_CKCORE_PCREL_IMM18BY2 43 +#define R_CKCORE_DOFFSET_IMM18 44 +#define R_CKCORE_DOFFSET_IMM18BY2 45 +#define R_CKCORE_DOFFSET_IMM18BY4 46 +#define R_CKCORE_GOT_IMM18BY4 48 +#define R_CKCORE_PLT_IMM18BY4 49 +#define R_CKCORE_PCREL_IMM7BY4 50 +#define R_CKCORE_TLS_LE32 51 +#define R_CKCORE_TLS_IE32 52 +#define R_CKCORE_TLS_GD32 53 +#define R_CKCORE_TLS_LDM32 54 +#define R_CKCORE_TLS_LDO32 55 +#define R_CKCORE_TLS_DTPMOD32 56 +#define R_CKCORE_TLS_DTPOFF32 57 +#define R_CKCORE_TLS_TPOFF32 58 + + +#define EF_IA_64_MASKOS 0x0000000f +#define EF_IA_64_ABI64 0x00000010 +#define EF_IA_64_ARCH 0xff000000 + + +#define PT_IA_64_ARCHEXT (PT_LOPROC + 0) +#define PT_IA_64_UNWIND (PT_LOPROC + 1) +#define PT_IA_64_HP_OPT_ANOT (PT_LOOS + 0x12) +#define PT_IA_64_HP_HSL_ANOT (PT_LOOS + 0x13) +#define PT_IA_64_HP_STACK (PT_LOOS + 0x14) + + +#define PF_IA_64_NORECOV 0x80000000 + + +#define SHT_IA_64_EXT (SHT_LOPROC + 0) +#define SHT_IA_64_UNWIND (SHT_LOPROC + 1) + + +#define SHF_IA_64_SHORT 0x10000000 +#define SHF_IA_64_NORECOV 0x20000000 + + +#define DT_IA_64_PLT_RESERVE (DT_LOPROC + 0) +#define DT_IA_64_NUM 1 + + +#define R_IA64_NONE 0x00 +#define R_IA64_IMM14 0x21 +#define R_IA64_IMM22 0x22 +#define R_IA64_IMM64 0x23 +#define R_IA64_DIR32MSB 0x24 +#define R_IA64_DIR32LSB 0x25 +#define R_IA64_DIR64MSB 0x26 +#define R_IA64_DIR64LSB 0x27 +#define R_IA64_GPREL22 0x2a +#define R_IA64_GPREL64I 0x2b +#define R_IA64_GPREL32MSB 0x2c +#define R_IA64_GPREL32LSB 0x2d +#define R_IA64_GPREL64MSB 0x2e +#define R_IA64_GPREL64LSB 0x2f +#define R_IA64_LTOFF22 0x32 +#define R_IA64_LTOFF64I 0x33 +#define R_IA64_PLTOFF22 0x3a +#define R_IA64_PLTOFF64I 0x3b +#define R_IA64_PLTOFF64MSB 0x3e +#define R_IA64_PLTOFF64LSB 0x3f +#define R_IA64_FPTR64I 0x43 +#define R_IA64_FPTR32MSB 0x44 +#define R_IA64_FPTR32LSB 0x45 +#define R_IA64_FPTR64MSB 0x46 +#define R_IA64_FPTR64LSB 0x47 +#define R_IA64_PCREL60B 0x48 +#define R_IA64_PCREL21B 0x49 +#define R_IA64_PCREL21M 0x4a +#define R_IA64_PCREL21F 0x4b +#define R_IA64_PCREL32MSB 0x4c +#define R_IA64_PCREL32LSB 0x4d +#define R_IA64_PCREL64MSB 0x4e +#define R_IA64_PCREL64LSB 0x4f +#define R_IA64_LTOFF_FPTR22 0x52 +#define R_IA64_LTOFF_FPTR64I 0x53 +#define R_IA64_LTOFF_FPTR32MSB 0x54 +#define R_IA64_LTOFF_FPTR32LSB 0x55 +#define R_IA64_LTOFF_FPTR64MSB 0x56 +#define R_IA64_LTOFF_FPTR64LSB 0x57 +#define R_IA64_SEGREL32MSB 0x5c +#define R_IA64_SEGREL32LSB 0x5d +#define R_IA64_SEGREL64MSB 0x5e +#define R_IA64_SEGREL64LSB 0x5f +#define R_IA64_SECREL32MSB 0x64 +#define R_IA64_SECREL32LSB 0x65 +#define R_IA64_SECREL64MSB 0x66 +#define R_IA64_SECREL64LSB 0x67 +#define R_IA64_REL32MSB 0x6c +#define R_IA64_REL32LSB 0x6d +#define R_IA64_REL64MSB 0x6e +#define R_IA64_REL64LSB 0x6f +#define R_IA64_LTV32MSB 0x74 +#define R_IA64_LTV32LSB 0x75 +#define R_IA64_LTV64MSB 0x76 +#define R_IA64_LTV64LSB 0x77 +#define R_IA64_PCREL21BI 0x79 +#define R_IA64_PCREL22 0x7a +#define R_IA64_PCREL64I 0x7b +#define R_IA64_IPLTMSB 0x80 +#define R_IA64_IPLTLSB 0x81 +#define R_IA64_COPY 0x84 +#define R_IA64_SUB 0x85 +#define R_IA64_LTOFF22X 0x86 +#define R_IA64_LDXMOV 0x87 +#define R_IA64_TPREL14 0x91 +#define R_IA64_TPREL22 0x92 +#define R_IA64_TPREL64I 0x93 +#define R_IA64_TPREL64MSB 0x96 +#define R_IA64_TPREL64LSB 0x97 +#define R_IA64_LTOFF_TPREL22 0x9a +#define R_IA64_DTPMOD64MSB 0xa6 +#define R_IA64_DTPMOD64LSB 0xa7 +#define R_IA64_LTOFF_DTPMOD22 0xaa +#define R_IA64_DTPREL14 0xb1 +#define R_IA64_DTPREL22 0xb2 +#define R_IA64_DTPREL64I 0xb3 +#define R_IA64_DTPREL32MSB 0xb4 +#define R_IA64_DTPREL32LSB 0xb5 +#define R_IA64_DTPREL64MSB 0xb6 +#define R_IA64_DTPREL64LSB 0xb7 +#define R_IA64_LTOFF_DTPREL22 0xba + + +#define EF_SH_MACH_MASK 0x1f +#define EF_SH_UNKNOWN 0x0 +#define EF_SH1 0x1 +#define EF_SH2 0x2 +#define EF_SH3 0x3 +#define EF_SH_DSP 0x4 +#define EF_SH3_DSP 0x5 +#define EF_SH4AL_DSP 0x6 +#define EF_SH3E 0x8 +#define EF_SH4 0x9 +#define EF_SH2E 0xb +#define EF_SH4A 0xc +#define EF_SH2A 0xd +#define EF_SH4_NOFPU 0x10 +#define EF_SH4A_NOFPU 0x11 +#define EF_SH4_NOMMU_NOFPU 0x12 +#define EF_SH2A_NOFPU 0x13 +#define EF_SH3_NOMMU 0x14 +#define EF_SH2A_SH4_NOFPU 0x15 +#define EF_SH2A_SH3_NOFPU 0x16 +#define EF_SH2A_SH4 0x17 +#define EF_SH2A_SH3E 0x18 + +#define R_SH_NONE 0 +#define R_SH_DIR32 1 +#define R_SH_REL32 2 +#define R_SH_DIR8WPN 3 +#define R_SH_IND12W 4 +#define R_SH_DIR8WPL 5 +#define R_SH_DIR8WPZ 6 +#define R_SH_DIR8BP 7 +#define R_SH_DIR8W 8 +#define R_SH_DIR8L 9 +#define R_SH_SWITCH16 25 +#define R_SH_SWITCH32 26 +#define R_SH_USES 27 +#define R_SH_COUNT 28 +#define R_SH_ALIGN 29 +#define R_SH_CODE 30 +#define R_SH_DATA 31 +#define R_SH_LABEL 32 +#define R_SH_SWITCH8 33 +#define R_SH_GNU_VTINHERIT 34 +#define R_SH_GNU_VTENTRY 35 +#define R_SH_TLS_GD_32 144 +#define R_SH_TLS_LD_32 145 +#define R_SH_TLS_LDO_32 146 +#define R_SH_TLS_IE_32 147 +#define R_SH_TLS_LE_32 148 +#define R_SH_TLS_DTPMOD32 149 +#define R_SH_TLS_DTPOFF32 150 +#define R_SH_TLS_TPOFF32 151 +#define R_SH_GOT32 160 +#define R_SH_PLT32 161 +#define R_SH_COPY 162 +#define R_SH_GLOB_DAT 163 +#define R_SH_JMP_SLOT 164 +#define R_SH_RELATIVE 165 +#define R_SH_GOTOFF 166 +#define R_SH_GOTPC 167 +#define R_SH_GOT20 201 +#define R_SH_GOTOFF20 202 +#define R_SH_GOTFUNCDESC 203 +#define R_SH_GOTFUNCDEST20 204 +#define R_SH_GOTOFFFUNCDESC 205 +#define R_SH_GOTOFFFUNCDEST20 206 +#define R_SH_FUNCDESC 207 +#define R_SH_FUNCDESC_VALUE 208 + +#define R_SH_NUM 256 + + + +#define R_390_NONE 0 +#define R_390_8 1 +#define R_390_12 2 +#define R_390_16 3 +#define R_390_32 4 +#define R_390_PC32 5 +#define R_390_GOT12 6 +#define R_390_GOT32 7 +#define R_390_PLT32 8 +#define R_390_COPY 9 +#define R_390_GLOB_DAT 10 +#define R_390_JMP_SLOT 11 +#define R_390_RELATIVE 12 +#define R_390_GOTOFF32 13 +#define R_390_GOTPC 14 +#define R_390_GOT16 15 +#define R_390_PC16 16 +#define R_390_PC16DBL 17 +#define R_390_PLT16DBL 18 +#define R_390_PC32DBL 19 +#define R_390_PLT32DBL 20 +#define R_390_GOTPCDBL 21 +#define R_390_64 22 +#define R_390_PC64 23 +#define R_390_GOT64 24 +#define R_390_PLT64 25 +#define R_390_GOTENT 26 +#define R_390_GOTOFF16 27 +#define R_390_GOTOFF64 28 +#define R_390_GOTPLT12 29 +#define R_390_GOTPLT16 30 +#define R_390_GOTPLT32 31 +#define R_390_GOTPLT64 32 +#define R_390_GOTPLTENT 33 +#define R_390_PLTOFF16 34 +#define R_390_PLTOFF32 35 +#define R_390_PLTOFF64 36 +#define R_390_TLS_LOAD 37 +#define R_390_TLS_GDCALL 38 + +#define R_390_TLS_LDCALL 39 + +#define R_390_TLS_GD32 40 + +#define R_390_TLS_GD64 41 + +#define R_390_TLS_GOTIE12 42 + +#define R_390_TLS_GOTIE32 43 + +#define R_390_TLS_GOTIE64 44 + +#define R_390_TLS_LDM32 45 + +#define R_390_TLS_LDM64 46 + +#define R_390_TLS_IE32 47 + +#define R_390_TLS_IE64 48 + +#define R_390_TLS_IEENT 49 + +#define R_390_TLS_LE32 50 + +#define R_390_TLS_LE64 51 + +#define R_390_TLS_LDO32 52 + +#define R_390_TLS_LDO64 53 + +#define R_390_TLS_DTPMOD 54 +#define R_390_TLS_DTPOFF 55 +#define R_390_TLS_TPOFF 56 + +#define R_390_20 57 +#define R_390_GOT20 58 +#define R_390_GOTPLT20 59 +#define R_390_TLS_GOTIE20 60 + + +#define R_390_NUM 61 + + + +#define R_CRIS_NONE 0 +#define R_CRIS_8 1 +#define R_CRIS_16 2 +#define R_CRIS_32 3 +#define R_CRIS_8_PCREL 4 +#define R_CRIS_16_PCREL 5 +#define R_CRIS_32_PCREL 6 +#define R_CRIS_GNU_VTINHERIT 7 +#define R_CRIS_GNU_VTENTRY 8 +#define R_CRIS_COPY 9 +#define R_CRIS_GLOB_DAT 10 +#define R_CRIS_JUMP_SLOT 11 +#define R_CRIS_RELATIVE 12 +#define R_CRIS_16_GOT 13 +#define R_CRIS_32_GOT 14 +#define R_CRIS_16_GOTPLT 15 +#define R_CRIS_32_GOTPLT 16 +#define R_CRIS_32_GOTREL 17 +#define R_CRIS_32_PLT_GOTREL 18 +#define R_CRIS_32_PLT_PCREL 19 + +#define R_CRIS_NUM 20 + + + +#define R_X86_64_NONE 0 +#define R_X86_64_64 1 +#define R_X86_64_PC32 2 +#define R_X86_64_GOT32 3 +#define R_X86_64_PLT32 4 +#define R_X86_64_COPY 5 +#define R_X86_64_GLOB_DAT 6 +#define R_X86_64_JUMP_SLOT 7 +#define R_X86_64_RELATIVE 8 +#define R_X86_64_GOTPCREL 9 + +#define R_X86_64_32 10 +#define R_X86_64_32S 11 +#define R_X86_64_16 12 +#define R_X86_64_PC16 13 +#define R_X86_64_8 14 +#define R_X86_64_PC8 15 +#define R_X86_64_DTPMOD64 16 +#define R_X86_64_DTPOFF64 17 +#define R_X86_64_TPOFF64 18 +#define R_X86_64_TLSGD 19 + +#define R_X86_64_TLSLD 20 + +#define R_X86_64_DTPOFF32 21 +#define R_X86_64_GOTTPOFF 22 + +#define R_X86_64_TPOFF32 23 +#define R_X86_64_PC64 24 +#define R_X86_64_GOTOFF64 25 +#define R_X86_64_GOTPC32 26 +#define R_X86_64_GOT64 27 +#define R_X86_64_GOTPCREL64 28 +#define R_X86_64_GOTPC64 29 +#define R_X86_64_GOTPLT64 30 +#define R_X86_64_PLTOFF64 31 +#define R_X86_64_SIZE32 32 +#define R_X86_64_SIZE64 33 + +#define R_X86_64_GOTPC32_TLSDESC 34 +#define R_X86_64_TLSDESC_CALL 35 + +#define R_X86_64_TLSDESC 36 +#define R_X86_64_IRELATIVE 37 +#define R_X86_64_RELATIVE64 38 +#define R_X86_64_GOTPCRELX 41 +#define R_X86_64_REX_GOTPCRELX 42 +#define R_X86_64_NUM 43 + + + +#define R_MN10300_NONE 0 +#define R_MN10300_32 1 +#define R_MN10300_16 2 +#define R_MN10300_8 3 +#define R_MN10300_PCREL32 4 +#define R_MN10300_PCREL16 5 +#define R_MN10300_PCREL8 6 +#define R_MN10300_GNU_VTINHERIT 7 +#define R_MN10300_GNU_VTENTRY 8 +#define R_MN10300_24 9 +#define R_MN10300_GOTPC32 10 +#define R_MN10300_GOTPC16 11 +#define R_MN10300_GOTOFF32 12 +#define R_MN10300_GOTOFF24 13 +#define R_MN10300_GOTOFF16 14 +#define R_MN10300_PLT32 15 +#define R_MN10300_PLT16 16 +#define R_MN10300_GOT32 17 +#define R_MN10300_GOT24 18 +#define R_MN10300_GOT16 19 +#define R_MN10300_COPY 20 +#define R_MN10300_GLOB_DAT 21 +#define R_MN10300_JMP_SLOT 22 +#define R_MN10300_RELATIVE 23 + +#define R_MN10300_NUM 24 + + + +#define R_M32R_NONE 0 +#define R_M32R_16 1 +#define R_M32R_32 2 +#define R_M32R_24 3 +#define R_M32R_10_PCREL 4 +#define R_M32R_18_PCREL 5 +#define R_M32R_26_PCREL 6 +#define R_M32R_HI16_ULO 7 +#define R_M32R_HI16_SLO 8 +#define R_M32R_LO16 9 +#define R_M32R_SDA16 10 +#define R_M32R_GNU_VTINHERIT 11 +#define R_M32R_GNU_VTENTRY 12 + +#define R_M32R_16_RELA 33 +#define R_M32R_32_RELA 34 +#define R_M32R_24_RELA 35 +#define R_M32R_10_PCREL_RELA 36 +#define R_M32R_18_PCREL_RELA 37 +#define R_M32R_26_PCREL_RELA 38 +#define R_M32R_HI16_ULO_RELA 39 +#define R_M32R_HI16_SLO_RELA 40 +#define R_M32R_LO16_RELA 41 +#define R_M32R_SDA16_RELA 42 +#define R_M32R_RELA_GNU_VTINHERIT 43 +#define R_M32R_RELA_GNU_VTENTRY 44 +#define R_M32R_REL32 45 + +#define R_M32R_GOT24 48 +#define R_M32R_26_PLTREL 49 +#define R_M32R_COPY 50 +#define R_M32R_GLOB_DAT 51 +#define R_M32R_JMP_SLOT 52 +#define R_M32R_RELATIVE 53 +#define R_M32R_GOTOFF 54 +#define R_M32R_GOTPC24 55 +#define R_M32R_GOT16_HI_ULO 56 + +#define R_M32R_GOT16_HI_SLO 57 + +#define R_M32R_GOT16_LO 58 +#define R_M32R_GOTPC_HI_ULO 59 + +#define R_M32R_GOTPC_HI_SLO 60 + +#define R_M32R_GOTPC_LO 61 + +#define R_M32R_GOTOFF_HI_ULO 62 + +#define R_M32R_GOTOFF_HI_SLO 63 + +#define R_M32R_GOTOFF_LO 64 +#define R_M32R_NUM 256 + +#define R_MICROBLAZE_NONE 0 +#define R_MICROBLAZE_32 1 +#define R_MICROBLAZE_32_PCREL 2 +#define R_MICROBLAZE_64_PCREL 3 +#define R_MICROBLAZE_32_PCREL_LO 4 +#define R_MICROBLAZE_64 5 +#define R_MICROBLAZE_32_LO 6 +#define R_MICROBLAZE_SRO32 7 +#define R_MICROBLAZE_SRW32 8 +#define R_MICROBLAZE_64_NONE 9 +#define R_MICROBLAZE_32_SYM_OP_SYM 10 +#define R_MICROBLAZE_GNU_VTINHERIT 11 +#define R_MICROBLAZE_GNU_VTENTRY 12 +#define R_MICROBLAZE_GOTPC_64 13 +#define R_MICROBLAZE_GOT_64 14 +#define R_MICROBLAZE_PLT_64 15 +#define R_MICROBLAZE_REL 16 +#define R_MICROBLAZE_JUMP_SLOT 17 +#define R_MICROBLAZE_GLOB_DAT 18 +#define R_MICROBLAZE_GOTOFF_64 19 +#define R_MICROBLAZE_GOTOFF_32 20 +#define R_MICROBLAZE_COPY 21 +#define R_MICROBLAZE_TLS 22 +#define R_MICROBLAZE_TLSGD 23 +#define R_MICROBLAZE_TLSLD 24 +#define R_MICROBLAZE_TLSDTPMOD32 25 +#define R_MICROBLAZE_TLSDTPREL32 26 +#define R_MICROBLAZE_TLSDTPREL64 27 +#define R_MICROBLAZE_TLSGOTTPREL32 28 +#define R_MICROBLAZE_TLSTPREL32 29 + +#define DT_NIOS2_GP 0x70000002 + +#define R_NIOS2_NONE 0 +#define R_NIOS2_S16 1 +#define R_NIOS2_U16 2 +#define R_NIOS2_PCREL16 3 +#define R_NIOS2_CALL26 4 +#define R_NIOS2_IMM5 5 +#define R_NIOS2_CACHE_OPX 6 +#define R_NIOS2_IMM6 7 +#define R_NIOS2_IMM8 8 +#define R_NIOS2_HI16 9 +#define R_NIOS2_LO16 10 +#define R_NIOS2_HIADJ16 11 +#define R_NIOS2_BFD_RELOC_32 12 +#define R_NIOS2_BFD_RELOC_16 13 +#define R_NIOS2_BFD_RELOC_8 14 +#define R_NIOS2_GPREL 15 +#define R_NIOS2_GNU_VTINHERIT 16 +#define R_NIOS2_GNU_VTENTRY 17 +#define R_NIOS2_UJMP 18 +#define R_NIOS2_CJMP 19 +#define R_NIOS2_CALLR 20 +#define R_NIOS2_ALIGN 21 +#define R_NIOS2_GOT16 22 +#define R_NIOS2_CALL16 23 +#define R_NIOS2_GOTOFF_LO 24 +#define R_NIOS2_GOTOFF_HA 25 +#define R_NIOS2_PCREL_LO 26 +#define R_NIOS2_PCREL_HA 27 +#define R_NIOS2_TLS_GD16 28 +#define R_NIOS2_TLS_LDM16 29 +#define R_NIOS2_TLS_LDO16 30 +#define R_NIOS2_TLS_IE16 31 +#define R_NIOS2_TLS_LE16 32 +#define R_NIOS2_TLS_DTPMOD 33 +#define R_NIOS2_TLS_DTPREL 34 +#define R_NIOS2_TLS_TPREL 35 +#define R_NIOS2_COPY 36 +#define R_NIOS2_GLOB_DAT 37 +#define R_NIOS2_JUMP_SLOT 38 +#define R_NIOS2_RELATIVE 39 +#define R_NIOS2_GOTOFF 40 +#define R_NIOS2_CALL26_NOAT 41 +#define R_NIOS2_GOT_LO 42 +#define R_NIOS2_GOT_HA 43 +#define R_NIOS2_CALL_LO 44 +#define R_NIOS2_CALL_HA 45 + +#define R_OR1K_NONE 0 +#define R_OR1K_32 1 +#define R_OR1K_16 2 +#define R_OR1K_8 3 +#define R_OR1K_LO_16_IN_INSN 4 +#define R_OR1K_HI_16_IN_INSN 5 +#define R_OR1K_INSN_REL_26 6 +#define R_OR1K_GNU_VTENTRY 7 +#define R_OR1K_GNU_VTINHERIT 8 +#define R_OR1K_32_PCREL 9 +#define R_OR1K_16_PCREL 10 +#define R_OR1K_8_PCREL 11 +#define R_OR1K_GOTPC_HI16 12 +#define R_OR1K_GOTPC_LO16 13 +#define R_OR1K_GOT16 14 +#define R_OR1K_PLT26 15 +#define R_OR1K_GOTOFF_HI16 16 +#define R_OR1K_GOTOFF_LO16 17 +#define R_OR1K_COPY 18 +#define R_OR1K_GLOB_DAT 19 +#define R_OR1K_JMP_SLOT 20 +#define R_OR1K_RELATIVE 21 +#define R_OR1K_TLS_GD_HI16 22 +#define R_OR1K_TLS_GD_LO16 23 +#define R_OR1K_TLS_LDM_HI16 24 +#define R_OR1K_TLS_LDM_LO16 25 +#define R_OR1K_TLS_LDO_HI16 26 +#define R_OR1K_TLS_LDO_LO16 27 +#define R_OR1K_TLS_IE_HI16 28 +#define R_OR1K_TLS_IE_LO16 29 +#define R_OR1K_TLS_LE_HI16 30 +#define R_OR1K_TLS_LE_LO16 31 +#define R_OR1K_TLS_TPOFF 32 +#define R_OR1K_TLS_DTPOFF 33 +#define R_OR1K_TLS_DTPMOD 34 + +#define R_BPF_NONE 0 +#define R_BPF_MAP_FD 1 + +#define R_RISCV_NONE 0 +#define R_RISCV_32 1 +#define R_RISCV_64 2 +#define R_RISCV_RELATIVE 3 +#define R_RISCV_COPY 4 +#define R_RISCV_JUMP_SLOT 5 +#define R_RISCV_TLS_DTPMOD32 6 +#define R_RISCV_TLS_DTPMOD64 7 +#define R_RISCV_TLS_DTPREL32 8 +#define R_RISCV_TLS_DTPREL64 9 +#define R_RISCV_TLS_TPREL32 10 +#define R_RISCV_TLS_TPREL64 11 + +#define R_RISCV_BRANCH 16 +#define R_RISCV_JAL 17 +#define R_RISCV_CALL 18 +#define R_RISCV_CALL_PLT 19 +#define R_RISCV_GOT_HI20 20 +#define R_RISCV_TLS_GOT_HI20 21 +#define R_RISCV_TLS_GD_HI20 22 +#define R_RISCV_PCREL_HI20 23 +#define R_RISCV_PCREL_LO12_I 24 +#define R_RISCV_PCREL_LO12_S 25 +#define R_RISCV_HI20 26 +#define R_RISCV_LO12_I 27 +#define R_RISCV_LO12_S 28 +#define R_RISCV_TPREL_HI20 29 +#define R_RISCV_TPREL_LO12_I 30 +#define R_RISCV_TPREL_LO12_S 31 +#define R_RISCV_TPREL_ADD 32 +#define R_RISCV_ADD8 33 +#define R_RISCV_ADD16 34 +#define R_RISCV_ADD32 35 +#define R_RISCV_ADD64 36 +#define R_RISCV_SUB8 37 +#define R_RISCV_SUB16 38 +#define R_RISCV_SUB32 39 +#define R_RISCV_SUB64 40 +#define R_RISCV_GNU_VTINHERIT 41 +#define R_RISCV_GNU_VTENTRY 42 +#define R_RISCV_ALIGN 43 +#define R_RISCV_RVC_BRANCH 44 +#define R_RISCV_RVC_JUMP 45 +#define R_RISCV_RVC_LUI 46 +#define R_RISCV_GPREL_I 47 +#define R_RISCV_GPREL_S 48 +#define R_RISCV_TPREL_I 49 +#define R_RISCV_TPREL_S 50 +#define R_RISCV_RELAX 51 +#define R_RISCV_SUB6 52 +#define R_RISCV_SET6 53 +#define R_RISCV_SET8 54 +#define R_RISCV_SET16 55 +#define R_RISCV_SET32 56 +#define R_RISCV_32_PCREL 57 + +#ifdef __cplusplus +} +#endif + + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/endian.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/endian.h new file mode 100644 index 0000000000000000000000000000000000000000..3e8f0ba987bb72b71a36c65ab71299b4dfe05f6d --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/endian.h @@ -0,0 +1,88 @@ +#ifndef _ENDIAN_H +#define _ENDIAN_H + +#include + +#define __NEED_uint16_t +#define __NEED_uint32_t +#define __NEED_uint64_t + +#include + +#define __PDP_ENDIAN 3412 + +#define BIG_ENDIAN __BIG_ENDIAN +#define LITTLE_ENDIAN __LITTLE_ENDIAN +#define PDP_ENDIAN __PDP_ENDIAN +#define BYTE_ORDER __BYTE_ORDER + +static __inline uint16_t __bswap16(uint16_t __x) +{ + return __x<<8 | __x>>8; +} + +static __inline uint32_t __bswap32(uint32_t __x) +{ + return __x>>24 | ((__x>>8)&0xff00) | ((__x<<8)&0xff0000) | __x<<24; +} + +static __inline uint64_t __bswap64(uint64_t __x) +{ + return (__bswap32(__x)+0ULL)<<32 | __bswap32(__x>>32); +} + +#if __BYTE_ORDER == __LITTLE_ENDIAN +#define htobe16(x) __bswap16(x) +#define be16toh(x) __bswap16(x) +#define htobe32(x) __bswap32(x) +#define be32toh(x) __bswap32(x) +#define htobe64(x) __bswap64(x) +#define be64toh(x) __bswap64(x) +#define htole16(x) (uint16_t)(x) +#define le16toh(x) (uint16_t)(x) +#define htole32(x) (uint32_t)(x) +#define le32toh(x) (uint32_t)(x) +#define htole64(x) (uint64_t)(x) +#define le64toh(x) (uint64_t)(x) +#else +#define htobe16(x) (uint16_t)(x) +#define be16toh(x) (uint16_t)(x) +#define htobe32(x) (uint32_t)(x) +#define be32toh(x) (uint32_t)(x) +#define htobe64(x) (uint64_t)(x) +#define be64toh(x) (uint64_t)(x) +#define htole16(x) __bswap16(x) +#define le16toh(x) __bswap16(x) +#define htole32(x) __bswap32(x) +#define le32toh(x) __bswap32(x) +#define htole64(x) __bswap64(x) +#define le64toh(x) __bswap64(x) +#endif + +#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE) +#if __BYTE_ORDER == __LITTLE_ENDIAN +#define betoh16(x) __bswap16(x) +#define betoh32(x) __bswap32(x) +#define betoh64(x) __bswap64(x) +#define letoh16(x) (uint16_t)(x) +#define letoh32(x) (uint32_t)(x) +#define letoh64(x) (uint64_t)(x) +#else +#define betoh16(x) (uint16_t)(x) +#define betoh32(x) (uint32_t)(x) +#define betoh64(x) (uint64_t)(x) +#define letoh16(x) __bswap16(x) +#define letoh32(x) __bswap32(x) +#define letoh64(x) __bswap64(x) +#endif +#endif + +#ifdef __LITEOS__ +#define htonl(x) __bswap32(x) +#define htons(x) __bswap16(x) +#define ntohl(x) __bswap32(x) +#define ntohs(x) __bswap16(x) +#endif + + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/err.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/err.h new file mode 100644 index 0000000000000000000000000000000000000000..9f5cb6b9e9fad0ff255f2dd1b505cfcec4658d26 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/err.h @@ -0,0 +1,25 @@ +#ifndef _ERR_H +#define _ERR_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +void warn(const char *, ...); +void vwarn(const char *, va_list); +void warnx(const char *, ...); +void vwarnx(const char *, va_list); + +_Noreturn void err(int, const char *, ...); +_Noreturn void verr(int, const char *, va_list); +_Noreturn void errx(int, const char *, ...); +_Noreturn void verrx(int, const char *, va_list); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/errno.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/errno.h new file mode 100644 index 0000000000000000000000000000000000000000..3c0a68fd83042f541674296f4c19a303c02be48e --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/errno.h @@ -0,0 +1,77 @@ +/** + * @defgroup errno Errno + * @ingroup libc + */ + +#ifndef _ERRNO_H +#define _ERRNO_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#include + +#ifdef __GNUC__ +__attribute__((const)) +#endif + +#ifdef __LITEOS__ +/** + * @ingroup errno + * + * @par Description: + * The set_errno() function sets the error code. + * + * @attention + *
    + *
  • The set_errno() function is not a standard C Library Function.
  • + *
+ * + * @retval #void None. + * + * @par Dependency: + *
  • errno.h
+ * @see get_errno + */ +void set_errno(int errcode); + +/** + * @ingroup errno + * + * @par Description: + * The get_errno() function gets the error code. + * + * @attention + *
    + *
  • The get_errno() function is not a standard C Library Function.
  • + *
+ * + * @retval #int The get_errno() returns the error code. + * + * @par Dependency: + *
  • errno.h
+ * @see set_errno + */ +int get_errno(void); +extern volatile int* __errno(void); +#endif +int *__errno_location(void); +#ifndef __LITEOS__ +#define errno (*__errno_location()) +#else +#define errno (*__errno()) +#endif + +#ifdef _GNU_SOURCE +extern char *program_invocation_short_name, *program_invocation_name; +#endif + +#ifdef __cplusplus +} +#endif + +#endif + diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/fcntl.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/fcntl.h new file mode 100644 index 0000000000000000000000000000000000000000..8b9a059657b35a7fa9544e90e3f7f2810174d4a3 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/fcntl.h @@ -0,0 +1,412 @@ +/** + * @defgroup fcntl Fcntl + * @ingroup libc + */ + +#ifndef _FCNTL_H +#define _FCNTL_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#define __NEED_off_t +#define __NEED_pid_t +#define __NEED_mode_t + +#ifdef _GNU_SOURCE +#define __NEED_size_t +#define __NEED_ssize_t +#define __NEED_struct_iovec +#endif +#ifdef __LITEOS__ +#define __NEED_int64_t +#endif + +#include + +#include + +struct flock { + short l_type; + short l_whence; + off_t l_start; + off_t l_len; + pid_t l_pid; +}; + + +/** + * @ingroup fcntl + * + * @par Description: + * Create a new file or rewrite an existing one. + * @param path [IN] Path of the file which need to be created. + * @param mode [IN] Describes the permissions of the file, should be an integer type. + * (For example: 0666, 0777) + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval #0 Upon successful completion. + * @retval #-1 Failed and set errno to indicate the error. + * + * @par Errors + *
    + *
  • Refer to open.
  • + *
+ * + * @par Dependency: + *
  • fcntl.h
+ * @see None + */ +int creat(const char *, mode_t); +/* func realization is used lwip_ioctl, func declaration conflict hear*/ +#ifndef __LITEOS__ +int fcntl(int, int, ...); +#endif +/** + * @ingroup fcntl + * + * @par Description: + * The open() function shall establish the connection between a file and a file descriptor. + * It shall create an open file description that refers to a file and a file descriptor that refers to that open file + * description. The file descriptor is used by other I/O functions to refer to that file. The file status flags + * The file offset used to mark the current position within the file shall be set to the beginning of the file. + * and file access modes of the open file description shall be set according to the value of oflags. + * @param path [IN] Points to a pathname naming the file. + * @param oflags [IN] Values for oflags are constructed by a bitwise-inclusive OR of flags from the following list, + * defined in . Applications should specify one of the median values + * (file access patterns) in the value of oflags in the attention description. + * @param "..." [IN] If the file is opened for creation, description file mode_t mode. + * @attention + *
    + *
  • O_RDONLY: Open for reading only.
  • + *
  • O_RDWR: Open for reading and writing. The result is undefined if this flag is applied to a FIFO.
  • + *
  • O_WRONLY: Open for writing only.
  • + *
  • O_CREAT: If the file exists, this flag has no effect except as noted under O_EXCL below. Otherwise, + * if O_DIRECTORY is not set the file shall be created as a regular file; the access permission bits of the file mode + * shall be set to the value of the argument following the oflag argument taken as type mode_t.
  • + *
  • O_EXCL: If O_CREAT and O_EXCL are set, open() shall fail if the file exists. + * The check for the existence of the file and the creation of the file if it does not exist shall be atomic with + * respect to other threads executing open() naming the same filename in the same directory with O_EXCL and O_CREAT set. + * If O_EXCL and O_CREAT are set, and path names a symbolic link, open() shall fail and set errno to [EEXIST], + * regardless of the contents of the symbolic link. If O_EXCL is set and O_CREAT is not set, the result is undefined + * .
  • + *
  • O_NOCTTY: Not support.
  • + *
  • O_APPEND: If set, the file offset shall be set to the end of the file prior to each write.
  • + *
  • O_NONBLOCK: When opening a FIFO with O_RDONLY or O_WRONLY set: + * If O_NONBLOCK is set, an open() for reading-only shall return without delay. + * An open() for writing-only shall return an error if no process currently has the file open for reading. + * If O_NONBLOCK is clear, an open() for reading-only shall block the calling thread until a thread opens the file + * for writing. An open() for writing-only shall block the calling thread until a thread opens the file for reading.
  • + *
  • O_TRUNC: If the file exists and is a regular file, and the file is successfully opened O_RDWR or O_WRONLY, + * its length shall be truncated to 0, and the mode and owner shall be unchanged. It shall have no effect on FIFO special + * files or terminal device files. Its effect on other file types is implementation-defined. + * The result of using O_TRUNC without either O_RDWR or O_WRONLY is undefined.
  • + *
  • O_DIRECTORY: No support, if set this mode returns error code [EACCES].
  • + *
  • O_NOFOLLOW: Not support.
  • + *
  • O_DIRECT: Not support.
  • + *
+ * + * @retval #0 Upon successful completion. + * @retval #-1 Failed and set errno to indicate the error. + * + * @par Errors + *
    + *
  • EACCES: Permission bits of the file mode do not permit the requested access, + * or search permission is denied on a component of the path prefix, or set oflags with O_DIRECTORY shall return it.
  • + *
  • EINVAL: The path name format is invalid.
  • + *
  • ENAMETOOLONG: The length of a component of a pathname is longer than {NAME_MAX}.
  • + *
  • ENOENT: O_CREAT is not set and the named file does not exist. Or a directory component in pathname does not + * exist or is a dangling symbolic link. This error code is also returned in the fat file system: no valid FAT volume, + * not find the file, not find the path
  • + *
  • ENOMEM: Out of memory.
  • + *
  • ENXIO: Inode is invalid or not a "normal" character driver or not a mountpoint.
  • + *
  • EMFILE: All file descriptors available to the process are currently open.
  • + *
  • EPERM: Get the file structure corresponding to the file descriptor failed. + * In fat file system: This error code is also returned when operation not permitted or access denied due to prohibited + * access or directory full.
  • + *
  • EEXIST: O_CREAT and O_EXCL are set, and the named file exists. + *
  • EIO: A hard error occurred in the low level disk I/O layer ro the physical drive cannot work or Assertion + * failed.
  • + *
  • EROFS: The named file resides on a read-only file system and either O_WRONLY, O_RDWR, O_CREAT + * (if the file does not exist), or O_TRUNC is set in the oflags argument.
  • + *
  • ENOSPC: The directory or file system that would contain the new file cannot be expanded, + * the file does not exist, and O_CREAT is specified.
  • + *
  • ENFILE: The maximum allowable number of files is currently open in the system.
  • + *
  • EISDIR: The named file is a directory and oflag includes O_WRONLY or O_RDWR, or includes O_CREAT without + * O_DIRECTORY.
  • + *
  • ENOTDIR: A component of the path prefix names an existing file that is neither a directory nor a symbolic + * link to a directory; or O_CREAT and O_EXCL are not specified, the path argument contains at least one non- + * character and ends with one or more trailing characters, and the last pathname component names an existing + * file that is neither a directory nor a symbolic link to a directory; or the path + * argument resolves to a non-directory file.
  • + *
  • EBUSY: The operation is rejected according to the file sharing policy.
  • + *
  • ENODEV: No such device.
  • + *
  • ENOTEMPTY: Directory not empty.
  • + *
  • ELOOP: Too many symbolic links encountered.
  • + *
  • EFAULT: Bad address.
  • + *
+ * + * @par Dependency: + *
  • fcntl.h
+ * @see None + */ +int open(const char *, int, ...); +int openat(int, const char *, int, ...); +int posix_fadvise(int, off_t, off_t, int); +int posix_fallocate(int, off_t, off_t); + +#define O_SEARCH O_PATH +#define O_EXEC O_PATH +#define O_TTY_INIT 0 + +#define O_ACCMODE (03|O_SEARCH) +#define O_RDONLY 00 +#define O_WRONLY 01 +#define O_RDWR 02 + +#define F_OFD_GETLK 36 +#define F_OFD_SETLK 37 +#define F_OFD_SETLKW 38 + +#define F_DUPFD_CLOEXEC 1030 + +#define F_RDLCK 0 +#define F_WRLCK 1 +#define F_UNLCK 2 + +#define FD_CLOEXEC 1 + +#define AT_FDCWD (-100) +#define AT_SYMLINK_NOFOLLOW 0x100 +#define AT_REMOVEDIR 0x200 +#define AT_SYMLINK_FOLLOW 0x400 +#define AT_EACCESS 0x200 + +#define POSIX_FADV_NORMAL 0 +#define POSIX_FADV_RANDOM 1 +#define POSIX_FADV_SEQUENTIAL 2 +#define POSIX_FADV_WILLNEED 3 +#ifndef POSIX_FADV_DONTNEED +#define POSIX_FADV_DONTNEED 4 +#define POSIX_FADV_NOREUSE 5 +#endif + +#undef SEEK_SET +#undef SEEK_CUR +#undef SEEK_END +#define SEEK_SET 0 +#define SEEK_CUR 1 +#define SEEK_END 2 + +#ifndef S_IRUSR +#define S_ISUID 04000 +#define S_ISGID 02000 +#define S_ISVTX 01000 +#define S_IRUSR 0400 +#define S_IWUSR 0200 +#define S_IXUSR 0100 +#define S_IRWXU 0700 +#define S_IRGRP 0040 +#define S_IWGRP 0020 +#define S_IXGRP 0010 +#define S_IRWXG 0070 +#define S_IROTH 0004 +#define S_IWOTH 0002 +#define S_IXOTH 0001 +#define S_IRWXO 0007 +#endif + +#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE) +#define AT_NO_AUTOMOUNT 0x800 +#define AT_EMPTY_PATH 0x1000 +#define AT_STATX_SYNC_TYPE 0x6000 +#define AT_STATX_SYNC_AS_STAT 0x0000 +#define AT_STATX_FORCE_SYNC 0x2000 +#define AT_STATX_DONT_SYNC 0x4000 +#define AT_RECURSIVE 0x8000 + +#define FAPPEND O_APPEND +#define FFSYNC O_SYNC +#define FASYNC O_ASYNC +#define FNONBLOCK O_NONBLOCK +#define FNDELAY O_NDELAY + +#define F_OK 0 +#define R_OK 4 +#define W_OK 2 +#define X_OK 1 +#define F_ULOCK 0 +#define F_LOCK 1 +#define F_TLOCK 2 +#define F_TEST 3 + +#define F_SETLEASE 1024 +#define F_GETLEASE 1025 +#define F_NOTIFY 1026 +#define F_CANCELLK 1029 +#define F_SETPIPE_SZ 1031 +#define F_GETPIPE_SZ 1032 +#define F_ADD_SEALS 1033 +#define F_GET_SEALS 1034 + +#define F_SEAL_SEAL 0x0001 +#define F_SEAL_SHRINK 0x0002 +#define F_SEAL_GROW 0x0004 +#define F_SEAL_WRITE 0x0008 +#define F_SEAL_FUTURE_WRITE 0x0010 + +#define F_GET_RW_HINT 1035 +#define F_SET_RW_HINT 1036 +#define F_GET_FILE_RW_HINT 1037 +#define F_SET_FILE_RW_HINT 1038 + +#define RWF_WRITE_LIFE_NOT_SET 0 +#define RWH_WRITE_LIFE_NONE 1 +#define RWH_WRITE_LIFE_SHORT 2 +#define RWH_WRITE_LIFE_MEDIUM 3 +#define RWH_WRITE_LIFE_LONG 4 +#define RWH_WRITE_LIFE_EXTREME 5 + +#define DN_ACCESS 0x00000001 +#define DN_MODIFY 0x00000002 +#define DN_CREATE 0x00000004 +#define DN_DELETE 0x00000008 +#define DN_RENAME 0x00000010 +#define DN_ATTRIB 0x00000020 +#define DN_MULTISHOT 0x80000000 + +int lockf(int, int, off_t); +#endif + +#if defined(_GNU_SOURCE) +#define F_OWNER_TID 0 +#define F_OWNER_PID 1 +#define F_OWNER_PGRP 2 +#define F_OWNER_GID 2 +#ifndef __LITEOS__ +struct file_handle { + unsigned handle_bytes; + int handle_type; + unsigned char f_handle[]; +}; +#endif +struct f_owner_ex { + int type; + pid_t pid; +}; +#define FALLOC_FL_KEEP_SIZE 1 +#define FALLOC_FL_PUNCH_HOLE 2 +#define MAX_HANDLE_SZ 128 +#define SYNC_FILE_RANGE_WAIT_BEFORE 1 +#define SYNC_FILE_RANGE_WRITE 2 +#define SYNC_FILE_RANGE_WAIT_AFTER 4 +#define SPLICE_F_MOVE 1 +#define SPLICE_F_NONBLOCK 2 +#define SPLICE_F_MORE 4 +#define SPLICE_F_GIFT 8 + +/** + * @ingroup fcntl + * + * @par Description: + * The fallocate() function shall ensure that any required storage for regular file data starting at offset and + * continuing for len bytes is allocated on the file system storage media. + * @param fd [IN] File descriptor. + * @param mode [IN] Operation mode. Only support FALLOC_FL_KEEP_SIZE. + * @param offset [IN] Offset of the file to allocated. + * @param len [IN] The size to allocate for the file. + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval #0 Upon successful completion. + * @retval #-1 Failed and set errno to indicate the error. + * + * @par Errors + *
    + *
  • EINVAL: The len argument or the offset argument is less than zero or greater than INT_MAX, + * or operation mode is not equal to FALLOC_FL_KEEP_SIZE.
  • + *
  • EBADF: The fd argument is not a valid file descriptor or or the underlying file system does not support + * this operation.
  • + *
  • EAGAIN: The file list is NULL.
  • + *
  • EACCES: Permission bits of the file mode do not permit the requested access, + * or search permission is denied on a component of the path prefix.
  • + *
  • ENOENT: A directory component in pathname does not exist or is a dangling symbolic link.
  • + *
  • EEXIST: The file/directory object is already exist.
  • + *
  • EIO: An I/O error occurred while reading from or writing to a file system.
  • + *
  • EROFS: The physical drive is write protected.
  • + *
  • ENOSPC: The directory or file system that would contain the new file cannot be expanded, + * the file does not exist, and O_CREAT is specified.
  • + *
  • ENFILE: The maximum allowable number of files is currently open in the system.
  • + *
  • ENOTEMPTY: Directory not empty.
  • + *
  • EISDIR: The named file is a directory.
  • + *
  • ENOTDIR: A component of the path prefix names an existing file that is neither a directory nor a symbolic + * link to a directory; or the path argument resolves to a non-directory file.
  • + *
  • EPERM: Operation not permitted or access denied due to prohibited access or directory full.
  • + *
  • EBUSY: The operation is rejected according to the file sharing policy.
  • + *
+ * + * @par Dependency: + *
  • fcntl.h
+ * @see None + */ +int fallocate(int, int, off_t, off_t); +#ifndef __LITEOS__ +#define fallocate64 fallocate +int name_to_handle_at(int, const char *, struct file_handle *, int *, int); +int open_by_handle_at(int, struct file_handle *, int); +#endif +ssize_t readahead(int, off_t, size_t); +int sync_file_range(int, off_t, off_t, unsigned); +ssize_t vmsplice(int, const struct iovec *, size_t, unsigned); +ssize_t splice(int, off_t *, int, off_t *, size_t, unsigned); +ssize_t tee(int, int, size_t, unsigned); +#if defined(__LITEOS__) && !defined(__LP64__) +typedef long long _loff_t; +#define loff_t _loff_t +#else +#define loff_t off_t +#endif +#endif + +#if defined(_LARGEFILE64_SOURCE) || defined(_GNU_SOURCE) +#ifdef __LITEOS__ +#define F_GETLK64 F_GETLK +#define F_SETLK64 F_SETLK +#define F_SETLKW64 F_SETLKW +#define flock64 flock +#define off64_t int64_t +int open64 (const char *, int, ...); +int openat64(int, const char *, int, ...); +int creat64(const char *, mode_t); +int lockf64(int, int, off64_t); +int posix_fadvise64(int, off64_t, off64_t, int); +int posix_fallocate64(int, off64_t, off64_t); +int fallocate64(int, int, off64_t, off64_t); +#else +#define F_GETLK64 F_GETLK +#define F_SETLK64 F_SETLK +#define F_SETLKW64 F_SETLKW +#define flock64 flock +#define open64 open +#define openat64 openat +#define creat64 creat +#define lockf64 lockf +#define posix_fadvise64 posix_fadvise +#define posix_fallocate64 posix_fallocate +#define off64_t off_t +#endif +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/features.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/features.h new file mode 100644 index 0000000000000000000000000000000000000000..c2d659c5aff79063726e9e857915d8bd131354ee --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/features.h @@ -0,0 +1,43 @@ +#ifndef _FEATURES_H +#define _FEATURES_H + +#ifdef __LITEOS__ +#define _ALL_SOURCE +#endif +#if defined(_ALL_SOURCE) && !defined(_GNU_SOURCE) +#define _GNU_SOURCE 1 +#endif + +#if defined(_DEFAULT_SOURCE) && !defined(_BSD_SOURCE) +#define _BSD_SOURCE 1 +#endif + +#if !defined(_POSIX_SOURCE) && !defined(_POSIX_C_SOURCE) \ + && !defined(_XOPEN_SOURCE) && !defined(_GNU_SOURCE) \ + && !defined(_BSD_SOURCE) && !defined(__STRICT_ANSI__) +#define _BSD_SOURCE 1 +#define _XOPEN_SOURCE 700 +#endif + +#if __STDC_VERSION__ >= 199901L +#define __restrict restrict +#elif !defined(__GNUC__) +#define __restrict +#endif + +#if __STDC_VERSION__ >= 199901L || defined(__cplusplus) +#define __inline inline +#elif !defined(__GNUC__) +#define __inline +#endif + +#if __STDC_VERSION__ >= 201112L +#elif defined(__GNUC__) +#define _Noreturn __attribute__((__noreturn__)) +#else +#define _Noreturn +#endif + +#define __REDIR(x,y) __typeof__(x) x __asm__(#y) + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/fenv.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/fenv.h new file mode 100644 index 0000000000000000000000000000000000000000..05de990c0bad27ae63af84199caf3ef549249886 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/fenv.h @@ -0,0 +1,28 @@ +#ifndef _FENV_H +#define _FENV_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +int feclearexcept(int); +int fegetexceptflag(fexcept_t *, int); +int feraiseexcept(int); +int fesetexceptflag(const fexcept_t *, int); +int fetestexcept(int); + +int fegetround(void); +int fesetround(int); + +int fegetenv(fenv_t *); +int feholdexcept(fenv_t *); +int fesetenv(const fenv_t *); +int feupdateenv(const fenv_t *); + +#ifdef __cplusplus +} +#endif +#endif + diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/float.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/float.h new file mode 100644 index 0000000000000000000000000000000000000000..713aadb906d9565f9a9d6bb408dd506b8a98e74c --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/float.h @@ -0,0 +1,52 @@ +#ifndef _FLOAT_H +#define _FLOAT_H + +#ifdef __cplusplus +extern "C" { +#endif + +int __flt_rounds(void); +#define FLT_ROUNDS (__flt_rounds()) + +#define FLT_RADIX 2 + +#define FLT_TRUE_MIN 1.40129846432481707092e-45F +#define FLT_MIN 1.17549435082228750797e-38F +#define FLT_MAX 3.40282346638528859812e+38F +#define FLT_EPSILON 1.1920928955078125e-07F + +#define FLT_MANT_DIG 24 +#define FLT_MIN_EXP (-125) +#define FLT_MAX_EXP 128 +#define FLT_HAS_SUBNORM 1 + +#define FLT_DIG 6 +#define FLT_DECIMAL_DIG 9 +#define FLT_MIN_10_EXP (-37) +#define FLT_MAX_10_EXP 38 + +#define DBL_TRUE_MIN 4.94065645841246544177e-324 +#define DBL_MIN 2.22507385850720138309e-308 +#define DBL_MAX 1.79769313486231570815e+308 +#define DBL_EPSILON 2.22044604925031308085e-16 + +#define DBL_MANT_DIG 53 +#define DBL_MIN_EXP (-1021) +#define DBL_MAX_EXP 1024 +#define DBL_HAS_SUBNORM 1 + +#define DBL_DIG 15 +#define DBL_DECIMAL_DIG 17 +#define DBL_MIN_10_EXP (-307) +#define DBL_MAX_10_EXP 308 + +#define LDBL_HAS_SUBNORM 1 +#define LDBL_DECIMAL_DIG DECIMAL_DIG + +#include + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/fmtmsg.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/fmtmsg.h new file mode 100644 index 0000000000000000000000000000000000000000..d944b06f8d2db9882c6820ae7419e09ecb8d55a8 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/fmtmsg.h @@ -0,0 +1,47 @@ +#ifndef _FMTMSG_H +#define _FMTMSG_H + +#ifdef __cplusplus +extern "C" { +#endif + +#define MM_HARD 1 +#define MM_SOFT 2 +#define MM_FIRM 4 + +#define MM_APPL 8 +#define MM_UTIL 16 +#define MM_OPSYS 32 + +#define MM_RECOVER 64 +#define MM_NRECOV 128 + +#define MM_PRINT 256 +#define MM_CONSOLE 512 + +#define MM_NULLMC 0L + +#define MM_HALT 1 +#define MM_ERROR 2 +#define MM_WARNING 3 +#define MM_INFO 4 +#define MM_NOSEV 0 + +#define MM_OK 0 +#define MM_NOTOK (-1) +#define MM_NOMSG 1 +#define MM_NOCON 4 + +#define MM_NULLLBL ((char*)0) +#define MM_NULLTXT ((char*)0) +#define MM_NULLACT ((char*)0) +#define MM_NULLTAG ((char*)0) +#define MM_NULLSEV 0 + +int fmtmsg(long, const char *, int, const char *, const char *, const char *); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/fnmatch.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/fnmatch.h new file mode 100644 index 0000000000000000000000000000000000000000..f9593217ffca540867a92f855e3d61366e1c3809 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/fnmatch.h @@ -0,0 +1,24 @@ +#ifndef _FNMATCH_H +#define _FNMATCH_H + +#ifdef __cplusplus +extern "C" { +#endif + +#define FNM_PATHNAME 0x1 +#define FNM_NOESCAPE 0x2 +#define FNM_PERIOD 0x4 +#define FNM_LEADING_DIR 0x8 +#define FNM_CASEFOLD 0x10 +#define FNM_FILE_NAME FNM_PATHNAME + +#define FNM_NOMATCH 1 +#define FNM_NOSYS (-1) + +int fnmatch(const char *, const char *, int); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/ftw.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/ftw.h new file mode 100644 index 0000000000000000000000000000000000000000..b15c062a8389e3ea62d151ef417f9ad90945660e --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/ftw.h @@ -0,0 +1,41 @@ +#ifndef _FTW_H +#define _FTW_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include + +#define FTW_F 1 +#define FTW_D 2 +#define FTW_DNR 3 +#define FTW_NS 4 +#define FTW_SL 5 +#define FTW_DP 6 +#define FTW_SLN 7 + +#define FTW_PHYS 1 +#define FTW_MOUNT 2 +#define FTW_CHDIR 4 +#define FTW_DEPTH 8 + +struct FTW { + int base; + int level; +}; + +int ftw(const char *, int (*)(const char *, const struct stat *, int), int); +int nftw(const char *, int (*)(const char *, const struct stat *, int, struct FTW *), int, int); + +#if defined(_LARGEFILE64_SOURCE) || defined(_GNU_SOURCE) +#define ftw64 ftw +#define nftw64 nftw +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/getopt.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/getopt.h new file mode 100644 index 0000000000000000000000000000000000000000..35cbd358b52855fb1596da7970c84c18dd0f1cdb --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/getopt.h @@ -0,0 +1,30 @@ +#ifndef _GETOPT_H +#define _GETOPT_H + +#ifdef __cplusplus +extern "C" { +#endif + +int getopt(int, char * const [], const char *); +extern char *optarg; +extern int optind, opterr, optopt, optreset; + +struct option { + const char *name; + int has_arg; + int *flag; + int val; +}; + +int getopt_long(int, char *const *, const char *, const struct option *, int *); +int getopt_long_only(int, char *const *, const char *, const struct option *, int *); + +#define no_argument 0 +#define required_argument 1 +#define optional_argument 2 + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/glob.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/glob.h new file mode 100644 index 0000000000000000000000000000000000000000..4a562a206d5202397ca989ff373bdf18bf6f4f4f --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/glob.h @@ -0,0 +1,52 @@ +#ifndef _GLOB_H +#define _GLOB_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#define __NEED_size_t + +#include + +typedef struct { + size_t gl_pathc; + char **gl_pathv; + size_t gl_offs; + int __dummy1; + void *__dummy2[5]; +} glob_t; + +int glob(const char *__restrict, int, int (*)(const char *, int), glob_t *__restrict); +void globfree(glob_t *); + +#define GLOB_ERR 0x01 +#define GLOB_MARK 0x02 +#define GLOB_NOSORT 0x04 +#define GLOB_DOOFFS 0x08 +#define GLOB_NOCHECK 0x10 +#define GLOB_APPEND 0x20 +#define GLOB_NOESCAPE 0x40 +#define GLOB_PERIOD 0x80 + +#define GLOB_TILDE 0x1000 +#define GLOB_TILDE_CHECK 0x4000 + +#define GLOB_NOSPACE 1 +#define GLOB_ABORTED 2 +#define GLOB_NOMATCH 3 +#define GLOB_NOSYS 4 + +#if defined(_LARGEFILE64_SOURCE) || defined(_GNU_SOURCE) +#define glob64 glob +#define globfree64 globfree +#define glob64_t glob_t +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/grp.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/grp.h new file mode 100644 index 0000000000000000000000000000000000000000..27e8c5e6c67260deaed574cd91e5c865ef82320f --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/grp.h @@ -0,0 +1,53 @@ +#ifndef _GRP_H +#define _GRP_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#define __NEED_size_t +#define __NEED_gid_t + +#ifdef _GNU_SOURCE +#define __NEED_FILE +#endif + +#include + +struct group { + char *gr_name; + char *gr_passwd; + gid_t gr_gid; + char **gr_mem; +}; + +struct group *getgrgid(gid_t); +struct group *getgrnam(const char *); + +int getgrgid_r(gid_t, struct group *, char *, size_t, struct group **); +int getgrnam_r(const char *, struct group *, char *, size_t, struct group **); + +#if defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) || defined(_BSD_SOURCE) +struct group *getgrent(void); +void endgrent(void); +void setgrent(void); +#endif + +#ifdef _GNU_SOURCE +struct group *fgetgrent(FILE *); +int putgrent(const struct group *, FILE *); +#endif + +#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE) +int getgrouplist(const char *, gid_t, gid_t *, int *); +int setgroups(size_t, const gid_t *); +int initgroups(const char *, gid_t); +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/iconv.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/iconv.h new file mode 100644 index 0000000000000000000000000000000000000000..ebe9bfda3926a6a532b4aefc1db8e06a16ec0cdf --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/iconv.h @@ -0,0 +1,24 @@ +#ifndef _ICONV_H +#define _ICONV_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#define __NEED_size_t + +#include + +typedef void *iconv_t; + +iconv_t iconv_open(const char *, const char *); +size_t iconv(iconv_t, char **__restrict, size_t *__restrict, char **__restrict, size_t *__restrict); +int iconv_close(iconv_t); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/ifaddrs.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/ifaddrs.h new file mode 100644 index 0000000000000000000000000000000000000000..737199a41443567edb84d4fa4ac2dc63538e4edc --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/ifaddrs.h @@ -0,0 +1,123 @@ +#ifndef _IFADDRS_H +#define _IFADDRS_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include + +struct ifaddrs { + struct ifaddrs *ifa_next; + char *ifa_name; + unsigned ifa_flags; + struct sockaddr *ifa_addr; + struct sockaddr *ifa_netmask; + union { + struct sockaddr *ifu_broadaddr; + struct sockaddr *ifu_dstaddr; + } ifa_ifu; + void *ifa_data; +}; +#define ifa_broadaddr ifa_ifu.ifu_broadaddr +#define ifa_dstaddr ifa_ifu.ifu_dstaddr + +/** + * @defgroup Network_Interfaces_Info Network Interfaces Info + * This section contains the interfaces to get information about Network interfaces in LwIP. + * @ingroup User_interfaces + */ + +/* + * Func Name: freeifaddrs + */ + +/** + * @ingroup Network_Interfaces_Info + * @par Prototype + * @code + * void freeifaddrs(struct ifaddrs *ifa); + * @endcode + * + * @par Purpose + * This function is to free the memory of struct ifaddrs * provided by getifaddrs. + * + * @par Description + * The function getifaddrs, provides the list of network interfaces in struct ifaddrs*. + * The application has to free the memory of struct ifaddrs * by using this function. + * + * @param[in] ifap Pointer to struct ifaddrs [N/A] + * + * @par Return values + * None + * + * @par Required Header File + * ifaddrs.h.h + * + * @par Note + * \n + * N/A + * + * @par Related Topics + * \n + * N/A + */ +void freeifaddrs(struct ifaddrs *); + +/* + * Func Name: getifaddrs + */ + +/** + * @ingroup Network_Interfaces_Info + * @par Prototype + * @code + * int getifaddrs(struct ifaddrs **ifap); + * @endcode + * + * @par Purpose + * This function creates a linked list of structures describing the network + * interfaces of the local system, and stores the address of the first item + * of the list in *ifap. + * + * @par Description + * This function creates a linked list of struct ifaddrs, which holds the information + * about the network interfaces of the local system. The ifa_next field contains a + * pointer to the next structure on the list, or NULL if this is the last item of the list. + * The ifa_name points to the null-terminated interface name. The ifa_flags field + * contains the interface flags. The ifa_addr field points to a structure containing + * the interface address. The ifa_netmask field points to a structure containing + * the netmask associated with ifa_addr, if applicable for the address family. + * Depending on whether the bit IFF_brcast or IFF_POINTOPOINT is set + * in ifa_flags (only one can be set at a time), either ifa_broadaddr will contain + * the brcast address associated with ifa_addr (if applicable for the address + * family) or ifa_dstaddr will contain the destination address of the point-to-point + * interface. + * + * @param[in] ifap Double Pointer to struct ifaddrs [N/A] + * + * @par Return values + * ERR_OK : on success + * Non zero value : on failure + * + * @par Required Header File + * ifaddrs.h.h + * + * @par Note + * The data returned by getifaddrs() is dynamically allocated and should be freed + * using freeifaddrs() when no longer needed.\n + * + * @par Related Topics + * \n + * N/A + */ +int getifaddrs(struct ifaddrs **); + +#ifdef __cplusplus +} +#endif + +#endif + diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/inttypes.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/inttypes.h new file mode 100644 index 0000000000000000000000000000000000000000..f9e7c5082e4f65797e46ef24d9279ac5528a6bad --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/inttypes.h @@ -0,0 +1,280 @@ +#ifndef _INTTYPES_H +#define _INTTYPES_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include + +#define __NEED_wchar_t +#include + +typedef struct { intmax_t quot, rem; } imaxdiv_t; + +intmax_t imaxabs(intmax_t); +imaxdiv_t imaxdiv(intmax_t, intmax_t); + +/** + * @ingroup string + * @par Description: + * The function shall be equivalent to the strtol(), strtoll(), strtoul(), and strtoull() functions, + * except that the initial portion of the string shall be converted to intmax_t representation. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval + * #intmax_t The function shall return the converted value, if any. + * + * @par Errors + *
    + *
  • ERANGE: The value to be returned is not representable.
  • + *
+ * + * @par Dependency: + *
  • inttypes.h
+ * + * @see strtol | strtoul + * + */ +intmax_t strtoimax(const char *__restrict, char **__restrict, int); + +/** + * @ingroup string + * @par Description: + * The function shall be equivalent to the strtol(), strtoll(), strtoul(), and strtoull() functions, + * except that the initial portion of the string shall be converted to uintmax_t representation. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval + * #uintmax_t The function shall return the converted value, if any. + * + * @par Errors + *
    + *
  • ERANGE: The value to be returned is not representable.
  • + *
+ * + * @par Dependency: + *
  • inttypes.h
+ * + * @see strtol | strtoul + * + */ +uintmax_t strtoumax(const char *__restrict, char **__restrict, int); + +intmax_t wcstoimax(const wchar_t *__restrict, wchar_t **__restrict, int); +uintmax_t wcstoumax(const wchar_t *__restrict, wchar_t **__restrict, int); + +#if UINTPTR_MAX == UINT64_MAX +#define __PRI64 "l" +#define __PRIPTR "l" +#else +#define __PRI64 "ll" +#define __PRIPTR "" +#endif + +#define PRId8 "d" +#define PRId16 "d" +#define PRId32 "d" +#define PRId64 __PRI64 "d" + +#define PRIdLEAST8 "d" +#define PRIdLEAST16 "d" +#define PRIdLEAST32 "d" +#define PRIdLEAST64 __PRI64 "d" + +#define PRIdFAST8 "d" +#define PRIdFAST16 "d" +#define PRIdFAST32 "d" +#define PRIdFAST64 __PRI64 "d" + +#define PRIi8 "i" +#define PRIi16 "i" +#define PRIi32 "i" +#define PRIi64 __PRI64 "i" + +#define PRIiLEAST8 "i" +#define PRIiLEAST16 "i" +#define PRIiLEAST32 "i" +#define PRIiLEAST64 __PRI64 "i" + +#define PRIiFAST8 "i" +#define PRIiFAST16 "i" +#define PRIiFAST32 "i" +#define PRIiFAST64 __PRI64 "i" + +#define PRIo8 "o" +#define PRIo16 "o" +#define PRIo32 "o" +#define PRIo64 __PRI64 "o" + +#define PRIoLEAST8 "o" +#define PRIoLEAST16 "o" +#define PRIoLEAST32 "o" +#define PRIoLEAST64 __PRI64 "o" + +#define PRIoFAST8 "o" +#define PRIoFAST16 "o" +#define PRIoFAST32 "o" +#define PRIoFAST64 __PRI64 "o" + +#define PRIu8 "u" +#define PRIu16 "u" +#define PRIu32 "u" +#define PRIu64 __PRI64 "u" + +#define PRIuLEAST8 "u" +#define PRIuLEAST16 "u" +#define PRIuLEAST32 "u" +#define PRIuLEAST64 __PRI64 "u" + +#define PRIuFAST8 "u" +#define PRIuFAST16 "u" +#define PRIuFAST32 "u" +#define PRIuFAST64 __PRI64 "u" + +#define PRIx8 "x" +#define PRIx16 "x" +#define PRIx32 "x" +#define PRIx64 __PRI64 "x" + +#define PRIxLEAST8 "x" +#define PRIxLEAST16 "x" +#define PRIxLEAST32 "x" +#define PRIxLEAST64 __PRI64 "x" + +#define PRIxFAST8 "x" +#define PRIxFAST16 "x" +#define PRIxFAST32 "x" +#define PRIxFAST64 __PRI64 "x" + +#define PRIX8 "X" +#define PRIX16 "X" +#define PRIX32 "X" +#define PRIX64 __PRI64 "X" + +#define PRIXLEAST8 "X" +#define PRIXLEAST16 "X" +#define PRIXLEAST32 "X" +#define PRIXLEAST64 __PRI64 "X" + +#define PRIXFAST8 "X" +#define PRIXFAST16 "X" +#define PRIXFAST32 "X" +#define PRIXFAST64 __PRI64 "X" + +#define PRIdMAX __PRI64 "d" +#define PRIiMAX __PRI64 "i" +#define PRIoMAX __PRI64 "o" +#define PRIuMAX __PRI64 "u" +#define PRIxMAX __PRI64 "x" +#define PRIXMAX __PRI64 "X" + +#define PRIdPTR __PRIPTR "d" +#define PRIiPTR __PRIPTR "i" +#define PRIoPTR __PRIPTR "o" +#define PRIuPTR __PRIPTR "u" +#define PRIxPTR __PRIPTR "x" +#define PRIXPTR __PRIPTR "X" + +#define SCNd8 "hhd" +#define SCNd16 "hd" +#define SCNd32 "d" +#define SCNd64 __PRI64 "d" + +#define SCNdLEAST8 "hhd" +#define SCNdLEAST16 "hd" +#define SCNdLEAST32 "d" +#define SCNdLEAST64 __PRI64 "d" + +#define SCNdFAST8 "hhd" +#define SCNdFAST16 "d" +#define SCNdFAST32 "d" +#define SCNdFAST64 __PRI64 "d" + +#define SCNi8 "hhi" +#define SCNi16 "hi" +#define SCNi32 "i" +#define SCNi64 __PRI64 "i" + +#define SCNiLEAST8 "hhi" +#define SCNiLEAST16 "hi" +#define SCNiLEAST32 "i" +#define SCNiLEAST64 __PRI64 "i" + +#define SCNiFAST8 "hhi" +#define SCNiFAST16 "i" +#define SCNiFAST32 "i" +#define SCNiFAST64 __PRI64 "i" + +#define SCNu8 "hhu" +#define SCNu16 "hu" +#define SCNu32 "u" +#define SCNu64 __PRI64 "u" + +#define SCNuLEAST8 "hhu" +#define SCNuLEAST16 "hu" +#define SCNuLEAST32 "u" +#define SCNuLEAST64 __PRI64 "u" + +#define SCNuFAST8 "hhu" +#define SCNuFAST16 "u" +#define SCNuFAST32 "u" +#define SCNuFAST64 __PRI64 "u" + +#define SCNo8 "hho" +#define SCNo16 "ho" +#define SCNo32 "o" +#define SCNo64 __PRI64 "o" + +#define SCNoLEAST8 "hho" +#define SCNoLEAST16 "ho" +#define SCNoLEAST32 "o" +#define SCNoLEAST64 __PRI64 "o" + +#define SCNoFAST8 "hho" +#define SCNoFAST16 "o" +#define SCNoFAST32 "o" +#define SCNoFAST64 __PRI64 "o" + +#define SCNx8 "hhx" +#define SCNx16 "hx" +#define SCNx32 "x" +#define SCNx64 __PRI64 "x" + +#define SCNxLEAST8 "hhx" +#define SCNxLEAST16 "hx" +#define SCNxLEAST32 "x" +#define SCNxLEAST64 __PRI64 "x" + +#define SCNxFAST8 "hhx" +#define SCNxFAST16 "x" +#define SCNxFAST32 "x" +#define SCNxFAST64 __PRI64 "x" + +#define SCNdMAX __PRI64 "d" +#define SCNiMAX __PRI64 "i" +#define SCNoMAX __PRI64 "o" +#define SCNuMAX __PRI64 "u" +#define SCNxMAX __PRI64 "x" + +#define SCNdPTR __PRIPTR "d" +#define SCNiPTR __PRIPTR "i" +#define SCNoPTR __PRIPTR "o" +#define SCNuPTR __PRIPTR "u" +#define SCNxPTR __PRIPTR "x" + +#ifdef __cplusplus +} +#endif + +#endif + diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/iso646.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/iso646.h new file mode 100644 index 0000000000000000000000000000000000000000..88ff53d7b8130e40666acba0b6fa42d9ecb41108 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/iso646.h @@ -0,0 +1,20 @@ +#ifndef _ISO646_H +#define _ISO646_H + +#ifndef __cplusplus + +#define and && +#define and_eq &= +#define bitand & +#define bitor | +#define compl ~ +#define not ! +#define not_eq != +#define or || +#define or_eq |= +#define xor ^ +#define xor_eq ^= + +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/langinfo.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/langinfo.h new file mode 100644 index 0000000000000000000000000000000000000000..519c061294c0f96fa3bffa40ec9ec3f1da8bd02c --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/langinfo.h @@ -0,0 +1,98 @@ +#ifndef _LANGINFO_H +#define _LANGINFO_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include + +#define __NEED_locale_t + +#include + +#define ABDAY_1 0x20000 +#define ABDAY_2 0x20001 +#define ABDAY_3 0x20002 +#define ABDAY_4 0x20003 +#define ABDAY_5 0x20004 +#define ABDAY_6 0x20005 +#define ABDAY_7 0x20006 + +#define DAY_1 0x20007 +#define DAY_2 0x20008 +#define DAY_3 0x20009 +#define DAY_4 0x2000A +#define DAY_5 0x2000B +#define DAY_6 0x2000C +#define DAY_7 0x2000D + +#define ABMON_1 0x2000E +#define ABMON_2 0x2000F +#define ABMON_3 0x20010 +#define ABMON_4 0x20011 +#define ABMON_5 0x20012 +#define ABMON_6 0x20013 +#define ABMON_7 0x20014 +#define ABMON_8 0x20015 +#define ABMON_9 0x20016 +#define ABMON_10 0x20017 +#define ABMON_11 0x20018 +#define ABMON_12 0x20019 + +#define MON_1 0x2001A +#define MON_2 0x2001B +#define MON_3 0x2001C +#define MON_4 0x2001D +#define MON_5 0x2001E +#define MON_6 0x2001F +#define MON_7 0x20020 +#define MON_8 0x20021 +#define MON_9 0x20022 +#define MON_10 0x20023 +#define MON_11 0x20024 +#define MON_12 0x20025 + +#define AM_STR 0x20026 +#define PM_STR 0x20027 + +#define D_T_FMT 0x20028 +#define D_FMT 0x20029 +#define T_FMT 0x2002A +#define T_FMT_AMPM 0x2002B + +#define ERA 0x2002C +#define ERA_D_FMT 0x2002E +#define ALT_DIGITS 0x2002F +#define ERA_D_T_FMT 0x20030 +#define ERA_T_FMT 0x20031 + +#define CODESET 14 + +#define CRNCYSTR 0x4000F + +#define RADIXCHAR 0x10000 +#define THOUSEP 0x10001 +#define YESEXPR 0x50000 +#define NOEXPR 0x50001 + +#define _NL_LOCALE_NAME(cat) (((cat)<<16) | 0xffff) + +#if defined(_GNU_SOURCE) +#define NL_LOCALE_NAME(cat) _NL_LOCALE_NAME(cat) +#endif + +#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE) +#define YESSTR 0x50002 +#define NOSTR 0x50003 +#endif + +char *nl_langinfo(nl_item); +char *nl_langinfo_l(nl_item, locale_t); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/lastlog.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/lastlog.h new file mode 100644 index 0000000000000000000000000000000000000000..5fa45ee47780fa6c68c3ab216ed715aef5d5d243 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/lastlog.h @@ -0,0 +1 @@ +#include diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/libgen.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/libgen.h new file mode 100644 index 0000000000000000000000000000000000000000..7c7fd9c6d2b3005a692faaf4fb00afc66c4a7f51 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/libgen.h @@ -0,0 +1,15 @@ +#ifndef _LIBGEN_H +#define _LIBGEN_H + +#ifdef __cplusplus +extern "C" { +#endif + +char *dirname(char *); +char *basename(char *); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/libintl.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/libintl.h new file mode 100644 index 0000000000000000000000000000000000000000..6a707bf0f0011b1de8ab0c81ff885b6c188deff5 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/libintl.h @@ -0,0 +1,33 @@ +#ifndef _LIBINTL_H +#define _LIBINTL_H + +#ifdef __cplusplus +extern "C" { +#endif + +#define __USE_GNU_GETTEXT 1 +#define __GNU_GETTEXT_SUPPORTED_REVISION(major) ((major) == 0 ? 1 : -1) + +#if __GNUC__ >= 3 +#define __fa(n) __attribute__ ((__format_arg__ (n))) +#else +#define __fa(n) +#endif + +char *gettext(const char *) __fa(1); +char *dgettext(const char *, const char *) __fa(2); +char *dcgettext(const char *, const char *, int) __fa(2); +char *ngettext(const char *, const char *, unsigned long) __fa(1) __fa(2); +char *dngettext(const char *, const char *, const char *, unsigned long) __fa(2) __fa(3); +char *dcngettext(const char *, const char *, const char *, unsigned long, int) __fa(2) __fa(3); +char *textdomain(const char *); +char *bindtextdomain (const char *, const char *); +char *bind_textdomain_codeset(const char *, const char *); + +#undef __fa + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/limits.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/limits.h new file mode 100644 index 0000000000000000000000000000000000000000..0fb64f8a6047ad50d08422983352aaba8776630f --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/limits.h @@ -0,0 +1,241 @@ +#ifndef _LIMITS_H +#define _LIMITS_H + +#include + +#include /* __LONG_MAX */ +#ifdef __LITEOS__ +#include "los_config.h" +#include "los_sem_pri.h" +#endif + +/* Support signed or unsigned plain-char */ + +#if '\xff' > 0 +#define CHAR_MIN 0 +#define CHAR_MAX 255 +#else +#define CHAR_MIN (-128) +#define CHAR_MAX 127 +#endif + +#define CHAR_BIT 8 +#define SCHAR_MIN (-128) +#define SCHAR_MAX 127 +#define UCHAR_MAX 255 +#define SHRT_MIN (-1-0x7fff) +#define SHRT_MAX 0x7fff +#define USHRT_MAX 0xffff +#define INT_MIN (-1-0x7fffffff) +#define INT_MAX 0x7fffffff +#define UINT_MAX 0xffffffffU +#define LONG_MIN (-LONG_MAX-1) +#define LONG_MAX __LONG_MAX +#define ULONG_MAX (2UL*LONG_MAX+1) +#define LLONG_MIN (-LLONG_MAX-1) +#define LLONG_MAX 0x7fffffffffffffffLL +#define ULLONG_MAX (2ULL*LLONG_MAX+1) + +#define MB_LEN_MAX 4 + +#if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \ + || defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) || defined(_BSD_SOURCE) + +#include + +#ifndef __LITEOS__ +#define PIPE_BUF 4096 +#else +#define PIPE_BUF 512 +#endif +#define FILESIZEBITS 64 +#ifndef NAME_MAX +#define NAME_MAX 255 +#endif +#ifndef __LITEOS__ +#define PATH_MAX 4096 +#else +#define PATH_MAX 260 +#define CONFIG_NAME_MAX NAME_MAX +#define CONFIG_PATH_MAX PATH_MAX +#endif + +#ifdef __LITEOS__ +#define NGROUPS_MAX 0 +#define ARG_MAX 4096 +#else +#define NGROUPS_MAX 32 +#define ARG_MAX 131072 +#endif +#define IOV_MAX 1024 +#define SYMLOOP_MAX 40 +#define WORD_BIT 32 +#define SSIZE_MAX LONG_MAX +#define TZNAME_MAX 6 +#define TTY_NAME_MAX 32 +#define HOST_NAME_MAX 255 + +#if LONG_MAX == 0x7fffffffL +#define LONG_BIT 32 +#else +#define LONG_BIT 64 +#endif + +/* Implementation choices... */ + +#define PTHREAD_KEYS_MAX 128 +#ifndef __LITEOS__ +#define PTHREAD_STACK_MIN 2048 +#endif +#define PTHREAD_DESTRUCTOR_ITERATIONS 4 +#ifndef __LITEOS__ +#define SEM_VALUE_MAX 0x7fffffff +#define SEM_NSEMS_MAX 256 +#else +/** + * @ingroup semaphore + * Maximum semaphore value. + */ +#define SEM_VALUE_MAX OS_SEM_COUNT_MAX +/** + * @ingroup semaphore + * Maximum number of supported semaphores. + */ +#define SEM_NSEMS_MAX LOSCFG_BASE_IPC_SEM_LIMIT +#define OS_SEM_COUNT_MAX SEM_NSEMS_MAX +#endif +#define DELAYTIMER_MAX 0x7fffffff +#ifdef __LITEOS__ +#define MQ_PRIO_MAX 1 +#else +#define MQ_PRIO_MAX 32768 +#endif +#define LOGIN_NAME_MAX 256 + +/* Arbitrary numbers... */ + +#define BC_BASE_MAX 99 +#define BC_DIM_MAX 2048 +#define BC_SCALE_MAX 99 +#define BC_STRING_MAX 1000 +#define CHARCLASS_NAME_MAX 14 +#define COLL_WEIGHTS_MAX 2 +#define EXPR_NEST_MAX 32 +#define LINE_MAX 4096 +#define RE_DUP_MAX 255 + +#define NL_ARGMAX 9 +#define NL_MSGMAX 32767 +#define NL_SETMAX 255 +#define NL_TEXTMAX 2048 + +#endif + +#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE) || defined(_XOPEN_SOURCE) + +#ifdef PAGESIZE +#define PAGE_SIZE PAGESIZE +#endif +#define NZERO 20 +#define NL_LANGMAX 32 + +#endif + +#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE) \ + || (defined(_XOPEN_SOURCE) && _XOPEN_SOURCE+0 < 700) + +#define NL_NMAX 16 + +#endif + +/* POSIX/SUS requirements follow. These numbers come directly + * from SUS and have nothing to do with the host system. */ + +#define _POSIX_AIO_LISTIO_MAX 2 +#define _POSIX_AIO_MAX 1 +#define _POSIX_ARG_MAX 4096 +#define _POSIX_CHILD_MAX 25 +#define _POSIX_CLOCKRES_MIN 20000000 +#define _POSIX_DELAYTIMER_MAX 32 +#define _POSIX_HOST_NAME_MAX 255 +#define _POSIX_LINK_MAX 8 +#define _POSIX_LOGIN_NAME_MAX 9 +#define _POSIX_MAX_CANON 255 +#define _POSIX_MAX_INPUT 255 +#define _POSIX_MQ_OPEN_MAX 8 +#define _POSIX_MQ_PRIO_MAX 32 +#define _POSIX_NAME_MAX 14 +#define _POSIX_NGROUPS_MAX 8 +#define _POSIX_OPEN_MAX 20 +#define _POSIX_PATH_MAX 256 +#define _POSIX_PIPE_BUF 512 +#define _POSIX_RE_DUP_MAX 255 +#define _POSIX_RTSIG_MAX 8 +#define _POSIX_SEM_NSEMS_MAX 256 +#define _POSIX_SEM_VALUE_MAX 32767 +#define _POSIX_SIGQUEUE_MAX 32 +#define _POSIX_SSIZE_MAX 32767 +#define _POSIX_STREAM_MAX 8 +#define _POSIX_SS_REPL_MAX 4 +#define _POSIX_SYMLINK_MAX 255 +#define _POSIX_SYMLOOP_MAX 8 +#define _POSIX_THREAD_DESTRUCTOR_ITERATIONS 4 +#define _POSIX_THREAD_KEYS_MAX 128 +#define _POSIX_THREAD_THREADS_MAX 64 +#define _POSIX_TIMER_MAX 32 +#define _POSIX_TRACE_EVENT_NAME_MAX 30 +#define _POSIX_TRACE_NAME_MAX 8 +#define _POSIX_TRACE_SYS_MAX 8 +#define _POSIX_TRACE_USER_EVENT_MAX 32 +#define _POSIX_TTY_NAME_MAX 9 +#define _POSIX_TZNAME_MAX 6 +#define _POSIX2_BC_BASE_MAX 99 +#define _POSIX2_BC_DIM_MAX 2048 +#define _POSIX2_BC_SCALE_MAX 99 +#define _POSIX2_BC_STRING_MAX 1000 +#define _POSIX2_CHARCLASS_NAME_MAX 14 +#define _POSIX2_COLL_WEIGHTS_MAX 2 +#define _POSIX2_EXPR_NEST_MAX 32 +#define _POSIX2_LINE_MAX 2048 +#define _POSIX2_RE_DUP_MAX 255 + +#define _XOPEN_IOV_MAX 16 +#define _XOPEN_NAME_MAX 255 +#define _XOPEN_PATH_MAX 1024 + +#ifdef __LITEOS__ +#include "los_config.h" +#ifdef LOSCFG_FS_VFS +#include "vfs_config.h" +#endif + +#define CHILD_MAX 6 +#define _POSIX_CLK_TICK time((time_t *)NULL) +#define _POSIX_GETGR_R_SIZE_MAX 0 +#define _POSIX_GETPW_R_SIZE_MAX 0 +#define _LITEOS_MQ_OPEN_MAX LOSCFG_BASE_IPC_QUEUE_LIMIT +#define GETGR_R_SIZE_MAX _POSIX_GETGR_R_SIZE_MAX +#define GETPW_R_SIZE_MAX _POSIX_GETPW_R_SIZE_MAX + +#ifdef LOSCFG_FS_VFS +#define OPEN_MAX CONFIG_NFILE_DESCRIPTORS +#else +#define OPEN_MAX 255 +#endif +#define RTSIG_MAX 8 +#define PTHREAD_ATTR_STACKSIZE LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE +#define PTHREAD_PRIORITY_SCHEDULING SCHED_OTHER +#define PTHREAD_THREADS_MAX (LOSCFG_BASE_CORE_TSK_LIMIT + 1) +#define TIMERS LOSCFG_BASE_CORE_SWTMR +#define TIMER_MAX _POSIX_TIMER_MAX +#define _POSIX_VERSION 200809L +#define POSIX_VERSION _POSIX_VERSION +#define SIGQUEUE_MAX 32 +#define STREAM_MAX 8 +#define MQ_OPEN_MAX _LITEOS_MQ_OPEN_MAX +#define SYS_CLK_TCK _POSIX_CLK_TICK +#define CONFIG_PATH_MAX PATH_MAX +#define LINK_MAX 8 +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/link.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/link.h new file mode 100644 index 0000000000000000000000000000000000000000..815018594c777b1513911cc04157e71fb7572015 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/link.h @@ -0,0 +1,53 @@ +#ifndef _LINK_H +#define _LINK_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#define __NEED_size_t +#define __NEED_uint32_t +#include + +#if UINTPTR_MAX > 0xffffffff +#define ElfW(type) Elf64_ ## type +#else +#define ElfW(type) Elf32_ ## type +#endif + +#include + +struct dl_phdr_info { + ElfW(Addr) dlpi_addr; + const char *dlpi_name; + const ElfW(Phdr) *dlpi_phdr; + ElfW(Half) dlpi_phnum; + unsigned long long int dlpi_adds; + unsigned long long int dlpi_subs; + size_t dlpi_tls_modid; + void *dlpi_tls_data; +}; + +struct link_map { + ElfW(Addr) l_addr; + char *l_name; + ElfW(Dyn) *l_ld; + struct link_map *l_next, *l_prev; +}; + +struct r_debug { + int r_version; + struct link_map *r_map; + ElfW(Addr) r_brk; + enum { RT_CONSISTENT, RT_ADD, RT_DELETE } r_state; + ElfW(Addr) r_ldbase; +}; + +int dl_iterate_phdr(int (*)(struct dl_phdr_info *, size_t, void *), void *); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/locale.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/locale.h new file mode 100644 index 0000000000000000000000000000000000000000..bd487f4dfff65f230b329567ce90712ecafafeb5 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/locale.h @@ -0,0 +1,106 @@ +#ifndef _LOCALE_H +#define _LOCALE_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#ifdef __cplusplus +#define NULL 0L +#else +#define NULL ((void*)0) +#endif + +#define LC_CTYPE 0 +#define LC_NUMERIC 1 +#define LC_TIME 2 +#define LC_COLLATE 3 +#define LC_MONETARY 4 +#define LC_MESSAGES 5 +#define LC_ALL 6 + +struct lconv { + char *decimal_point; + char *thousands_sep; + char *grouping; + + char *int_curr_symbol; + char *currency_symbol; + char *mon_decimal_point; + char *mon_thousands_sep; + char *mon_grouping; + char *positive_sign; + char *negative_sign; + char int_frac_digits; + char frac_digits; + char p_cs_precedes; + char p_sep_by_space; + char n_cs_precedes; + char n_sep_by_space; + char p_sign_posn; + char n_sign_posn; + char int_p_cs_precedes; + char int_p_sep_by_space; + char int_n_cs_precedes; + char int_n_sep_by_space; + char int_p_sign_posn; + char int_n_sign_posn; +}; + + +/** + * @ingroup locale + * @par Description: + * This API is used to selects the appropriate piece of the global locale, as specified by the category and locale arguments, + * and can be used to change or query the entire global locale or portions thereof. + * + * @attention + *
    + *
  • Not support.
  • + *
+ * + * @retval #NULL Failed to set, the input param invalid or the locale name not supported. + * @retval #char* The string associated with the specified category for the new locale if successful. + * + * @par Dependency: + *
  • locale.h
+ * + * @see None + * + */ +char *setlocale (int, const char *); +struct lconv *localeconv(void); + + +#if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \ + || defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) || defined(_BSD_SOURCE) + +#define __NEED_locale_t + +#include + +#define LC_GLOBAL_LOCALE ((locale_t)-1) + +#define LC_CTYPE_MASK (1< + +/** + * @ingroup malloc + * + * @par Description: + * The malloc() function shall allocate unused space for an object whose size in bytes is specified by byte_count + * and whose value is unspecified. If byte_count is 0, then malloc() returns NULL. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval #void* Upon successful completion with byte_count not equal to 0, malloc() shall return a pointer to the allocated space. + * If byte_count is 0, it shall return a null pointer. + * + * @par Dependency: + *
  • malloc.h
+ * @see calloc | free | posix_memalign | realloc + */ +void *malloc (size_t); +void *calloc (size_t, size_t); +void *realloc (void *, size_t); +void free (void *); +void *valloc (size_t); +void *memalign(size_t, size_t); + +size_t malloc_usable_size(void *); + +#ifdef __LITEOS__ +void *zalloc(size_t); +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/math.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/math.h new file mode 100644 index 0000000000000000000000000000000000000000..523facc7f27d8bf73e7af7d743593a51831b6be3 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/math.h @@ -0,0 +1,3187 @@ +/** + * @defgroup math Math + * @ingroup libm + */ + +#ifndef _MATH_H +#define _MATH_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#define __NEED_float_t +#define __NEED_double_t +#include + +#if 100*__GNUC__+__GNUC_MINOR__ >= 303 +#define NAN __builtin_nanf("") +#define INFINITY __builtin_inff() +#else +#define NAN (0.0f/0.0f) +#define INFINITY 1e5000f +#endif + +#define HUGE_VALF INFINITY +#define HUGE_VAL ((double)INFINITY) +#define HUGE_VALL ((long double)INFINITY) + +#define MATH_ERRNO 1 +#define MATH_ERREXCEPT 2 +#define math_errhandling 2 + +#define FP_ILOGBNAN (-1-0x7fffffff) +#define FP_ILOGB0 FP_ILOGBNAN + +#define FP_NAN 0 +#define FP_INFINITE 1 +#define FP_ZERO 2 +#define FP_SUBNORMAL 3 +#define FP_NORMAL 4 + +#ifdef __FP_FAST_FMA +#define FP_FAST_FMA 1 +#endif + +#ifdef __FP_FAST_FMAF +#define FP_FAST_FMAF 1 +#endif + +#ifdef __FP_FAST_FMAL +#define FP_FAST_FMAL 1 +#endif + +int __fpclassify(double); +int __fpclassifyf(float); +int __fpclassifyl(long double); + +static __inline unsigned __FLOAT_BITS(float __f) +{ + union {float __f; unsigned __i;} __u; + __u.__f = __f; + return __u.__i; +} +static __inline unsigned long long __DOUBLE_BITS(double __f) +{ + union {double __f; unsigned long long __i;} __u; + __u.__f = __f; + return __u.__i; +} + +#define fpclassify(x) ( \ + sizeof(x) == sizeof(float) ? __fpclassifyf(x) : \ + sizeof(x) == sizeof(double) ? __fpclassify(x) : \ + __fpclassifyl(x) ) + +#define isinf(x) ( \ + sizeof(x) == sizeof(float) ? (__FLOAT_BITS(x) & 0x7fffffff) == 0x7f800000 : \ + sizeof(x) == sizeof(double) ? (__DOUBLE_BITS(x) & -1ULL>>1) == 0x7ffULL<<52 : \ + __fpclassifyl(x) == FP_INFINITE) + +#define isnan(x) ( \ + sizeof(x) == sizeof(float) ? (__FLOAT_BITS(x) & 0x7fffffff) > 0x7f800000 : \ + sizeof(x) == sizeof(double) ? (__DOUBLE_BITS(x) & -1ULL>>1) > 0x7ffULL<<52 : \ + __fpclassifyl(x) == FP_NAN) + +#define isnormal(x) ( \ + sizeof(x) == sizeof(float) ? ((__FLOAT_BITS(x)+0x00800000) & 0x7fffffff) >= 0x01000000 : \ + sizeof(x) == sizeof(double) ? ((__DOUBLE_BITS(x)+(1ULL<<52)) & -1ULL>>1) >= 1ULL<<53 : \ + __fpclassifyl(x) == FP_NORMAL) + +#define isfinite(x) ( \ + sizeof(x) == sizeof(float) ? (__FLOAT_BITS(x) & 0x7fffffff) < 0x7f800000 : \ + sizeof(x) == sizeof(double) ? (__DOUBLE_BITS(x) & -1ULL>>1) < 0x7ffULL<<52 : \ + __fpclassifyl(x) > FP_INFINITE) + +/* cmath use using ::isnan, need isnan deferance. */ +#ifdef __LITEOS__ +int (isnan)(double); +#endif + +int __signbit(double); +int __signbitf(float); +int __signbitl(long double); + +#define signbit(x) ( \ + sizeof(x) == sizeof(float) ? (int)(__FLOAT_BITS(x)>>31) : \ + sizeof(x) == sizeof(double) ? (int)(__DOUBLE_BITS(x)>>63) : \ + __signbitl(x) ) + +#define isunordered(x,y) (isnan((x)) ? ((void)(y),1) : isnan((y))) + +#define __ISREL_DEF(rel, op, type) \ +static __inline int __is##rel(type __x, type __y) \ +{ return !isunordered(__x,__y) && __x op __y; } + +__ISREL_DEF(lessf, <, float_t) +__ISREL_DEF(less, <, double_t) +__ISREL_DEF(lessl, <, long double) +__ISREL_DEF(lessequalf, <=, float_t) +__ISREL_DEF(lessequal, <=, double_t) +__ISREL_DEF(lessequall, <=, long double) +__ISREL_DEF(lessgreaterf, !=, float_t) +__ISREL_DEF(lessgreater, !=, double_t) +__ISREL_DEF(lessgreaterl, !=, long double) +__ISREL_DEF(greaterf, >, float_t) +__ISREL_DEF(greater, >, double_t) +__ISREL_DEF(greaterl, >, long double) +__ISREL_DEF(greaterequalf, >=, float_t) +__ISREL_DEF(greaterequal, >=, double_t) +__ISREL_DEF(greaterequall, >=, long double) + +#define __tg_pred_2(x, y, p) ( \ + sizeof((x)+(y)) == sizeof(float) ? p##f(x, y) : \ + sizeof((x)+(y)) == sizeof(double) ? p(x, y) : \ + p##l(x, y) ) + +#define isless(x, y) __tg_pred_2(x, y, __isless) +#define islessequal(x, y) __tg_pred_2(x, y, __islessequal) +#define islessgreater(x, y) __tg_pred_2(x, y, __islessgreater) +#define isgreater(x, y) __tg_pred_2(x, y, __isgreater) +#define isgreaterequal(x, y) __tg_pred_2(x, y, __isgreaterequal) + +/** + * @ingroup math + * @par Description: + * This function calculates the arc cosine of x; that is the value whose cosine is x. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval + * #double On success, this function returns the arc cosine of x in radians; + * the return value is in the range [0, pi].\n + * If x is a NaN, a NaN is returned.\n + * If x is +1, +0 is returned.\n + * If x is positive infinity or negative infinity, a domain error occurs, and a NaN is returned.\n + * If x is outside the range [-1, 1], a domain error occurs, and a NaN is returned. + * + * @par Dependency: + *
  • math.h
+ * + * @see asin | atan | atan2 | cos | sin | tan + * + */ +double acos(double); + +/** + * @ingroup math + * @par Description: + * The function calculates the arc cosine of x; that is the value whose cosine is x. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval + * #float On success, the function returns the arc cosine of x in radians; + * the return value is in the range [0, pi].\n + * If x is a NaN, a NaN is returned.\n + * If x is +1, +0 is returned.\n + * If x is positive infinity or negative infinity, a domain error occurs, and a NaN is returned.\n + * If x is outside the range [-1, 1], a domain error occurs, and a NaN is returned.\n + * + * @par Dependency: + *
  • math.h
+ * + * @see asin | atan | atan2 | cos | sin | tan + * + */ +float acosf(float); + +/** + * @ingroup math + * @par Description: + * This function calculates the arc cosine of x; that is the value whose cosine is x. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval "long double" On success, this function returns the arc cosine of x in radians; + * the return value is in the range [0, pi].\n + * If x is a NaN, a NaN is returned.\n + * If x is +1, +0 is returned.\n + * If x is positive infinity or negative infinity, a domain error occurs, and a NaN is returned.\n + * If x is outside the range [-1, 1], a domain error occurs, and a NaN is returned.\n + * + * @par Dependency: + *
  • math.h
+ * + * @see asin | atan | atan2 | cos | sin | tan + * + */ +long double acosl(long double); +/** + * @ingroup math + * @par Description: + * This function calculates the inverse hyperbolic cosine of x; that is the value whose hyperbolic cosine is x. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval + * #double On success, this function returns the inverse hyperbolic cosine of x.\n + * If x is a NaN, a NaN is returned.\n + * If x is +1, +0 is returned.\n + * If x is positive infinity, positive infinity is returned.\n + * If x is less than 1, a domain error occurs, and the functions return a NaN.\n + * + * @par Dependency: + *
  • math.h
+ * + * @see asinh | atanh | cosh | sinh | tanh + * + */ +double acosh(double); + +/** + * @ingroup math + * @par Description: + * This function calculates the inverse hyperbolic cosine of x; that is the value whose hyperbolic cosine is x. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval + * #float On success, this function calculates the inverse hyperbolic cosine of x; that is the value + * whose hyperbolic cosine is x.\n + * If x is a NaN, a NaN is returned.\n + * If x is +1, +0 is returned.\n + * If x is positive infinity or negative infinity, a domain error occurs, and a NaN is returned.\n + * If x is less than 1, a domain error occurs, and the functions return a NaN.\n + * @par Dependency: + *
  • math.h
+ * + * @see asinh | atanh | cosh | sinh | tanh + * + */ +float acoshf(float); + +/** + * @ingroup math + * @par Description: + * This function calculates the inverse hyperbolic cosine of x; that is the value whose hyperbolic cosine is x. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval "long double" On success, this function returns the inverse hyperbolic cosine of x.\n + * If x is a NaN, a NaN is returned.\n + * If x is +1, +0 is returned.\n + * If x is positive infinity, positive infinity is returned.\n + * If x is less than 1, a domain error occurs, and the functions return a NaN.\n + * + * @par Dependency: + *
  • math.h
+ * + * @see asinh | atanh | cosh | sinh | tanh + * + */ +long double acoshl(long double); + +/** + * @ingroup math + * @par Description: + * This function calculates the arc sine of x; that is the value whose sine is x. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval + * #double On success, the function returns the principal value of the arc sine of x in radians; + * the return value is in the range [-pi/2, pi/2].\n + * If x is a NaN, a NaN is returned.\n + * If x is +0 (-0), +0 (-0) is returned.\n + * If x is outside the range [-1, 1], a domain error occurs, and a NaN is returned. + * + * @par Dependency: + *
  • math.h
+ * + * @see acos | atan | atan2 | cos | sin | tan + * + */ +double asin(double); + +/** + * @ingroup math + * @par Description: + * This function calculates the arc sine of x; that is the value whose sine is x. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval + * #float On success, the function returns the principal value of the arc sine of x in radians; + * the return value is in the range [-pi/2, pi/2].\n + * If x is a NaN, a NaN is returned.\n + * If x is +0 (-0), +0 (-0) is returned.\n + * If x is outside the range [-1, 1], a domain error occurs, and a NaN is returned.\n + * + * @par Dependency: + *
  • math.h
+ * + * @see acos | atan | atan2 | cos | sin | tan + * + */ +float asinf(float); + +/** + * @ingroup math + * @par Description: + * This function calculates the arc sine of x; that is the value whose sine is x. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval "long double" On success, the function returns the principal value of the arc sine of x in radians; + * the return value is in the range [-pi/2, pi/2].\n + * If x is a NaN, a NaN is returned.\n + * If x is +0 (-0), +0 (-0) is returned.\n + * If x is outside the range [-1, 1], a domain error occurs, and a NaN is returned.\n + * + * @par Dependency: + *
  • math.h
+ * + * @see acos | atan | atan2 | cos | sin | tan + * + */ +long double asinl(long double); + +/** + * @ingroup math + * @par Description: + * This function calculates the inverse hyperbolic sine of x; that is the value whose hyperbolic sine is x. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval + * #double On success, the function returns the inverse hyperbolic sine of x.\n + * If x is a NaN, a NaN is returned.\n + * If x is +0 (-0), +0 (-0) is returned.\n + * If x is positive infinity (negative infinity), positive infinity (negative infinity) is returned.\n + * + * @par Dependency: + *
  • math.h
+ * + * @see acosh | atanh | cosh | sinh | tanh + * + */ +double asinh(double); + +/** + * @ingroup math + * @par Description: + * This function calculates the inverse hyperbolic sine of x; that is the value whose hyperbolic sine is x. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval + * #float On success, these functions return the inverse hyperbolic sine of x.\n + * If x is a NaN, a NaN is returned.\n + * If x is +0 (-0), +0 (-0) is returned.\n + * If x is positive infinity (negative infinity), positive infinity (negative infinity) is returned.\n + * + * @par Dependency: + *
  • math.h
+ * + * @see acosh | atanh | cosh | sinh | tanh + * + */ +float asinhf(float); + +/** + * @ingroup math + * @par Description: + * This function calculates the inverse hyperbolic sine of x; that is the value whose hyperbolic sine is x. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval "long double" On success, the function returns the inverse hyperbolic sine of x.\n + * If x is a NaN, a NaN is returned.\n + * If x is +0 (-0), +0 (-0) is returned.\n + * If x is positive infinity (negative infinity), positive infinity (negative infinity) is returned.\n + * + * @par Dependency: + *
  • math.h
+ * + * @see acosh | atanh | cosh | sinh | tanh + * + */ +long double asinhl(long double); + +/** + * @ingroup math + * @par Description: + * This function calculates the principal value of the arc tangent of x; that is the value whose tangent is x. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval + * #double On success, the function returns the principal value of the arc tangent of x in radians; + *the return value is in the range [-pi/2, pi/2].\n + * If x is a NaN, a NaN is returned.\n + * If x is +0 (-0), +0 (-0) is returned.\n + * If x is positive infinity (negative infinity), +pi/2 (-pi/2) is returned. + * + * @par Dependency: + *
  • math.h
+ * + * @see acos | asin | atan2 | cos | sin | tan + * + */ +double atan(double); + +/** + * @ingroup math + * @par Description: + * This function calculates the principal value of the arc tangent of x; that is the value whose tangent is x. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval + * #float On success, the function returns the principal value of the arc tangent of x in radians; + * the return value is in the range [-pi/2, pi/2].\n + * If x is a NaN, a NaN is returned.\n + * If x is +0 (-0), +0 (-0) is returned.\n + * If x is positive infinity (negative infinity), +pi/2 (-pi/2) is returned.\n + * + * @par Dependency: + *
  • math.h
+ * + * @see acos | asin | atan2 | cos | sin | tan + * + */ +float atanf(float); + +/** + * @ingroup math + * @par Description: + * This function calculates the principal value of the arc tangent of x; that is the value whose tangent is x. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval "long double" On success, the function returns the principal value of the arc tangent of x in radians; the return value is in the range [-pi/2, pi/2].\n + * If x is a NaN, a NaN is returned.\n + * If x is +0 (-0), +0 (-0) is returned.\n + * If x is positive infinity (negative infinity), +pi/2 (-pi/2) is returned.\n + * + * @par Dependency: + *
  • math.h
+ * + * @see acos | asin | atan2 | cos | sin | tan + * + */ +long double atanl(long double); + +/** + * @ingroup math + * @par Description: + * This function calculates the principal value of the arc tangent of y/x, + * using the signs of the two arguments to determine the quadrant of the result. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval + * #double On success, these functions return the principal value of the arc tangent + * of y/x in radians; the return value is in the range [-pi, pi].\n + * If y is +0 (-0) and x is less than 0, +pi (-pi) is returned.\n + * If y is +0 (-0) and x is greater than 0, +0 (-0) is returned.\n + * If y is less than 0 and x is +0 or -0, -pi/2 is returned.\n + * If y is greater than 0 and x is +0 or -0, pi/2 is returned.\n + * If either x or y is NaN, a NaN is returned.\n + * If y is +0 (-0) and x is -0, +pi (-pi) is returned.\n + * If y is +0 (-0) and x is +0, +0 (-0) is returned.\n + * If y is a finite value greater (less) than 0, and x is negative infinity, +pi (-pi) is returned.\n + * If y is a finite value greater (less) than 0, and x is positive infinity, +0 (-0) is returned.\n + * If y is positive infinity (negative infinity), and x is finite, pi/2 (-pi/2) is returned.\n + * If y is positive infinity (negative infinity) and x is negative infinity, +3 *pi/4 (-3 *pi/4) is returned.\n + * If y is positive infinity (negative infinity) and x is positive infinity, +pi/4 (-pi/4) is returned. + * + * @par Dependency: + *
  • math.h
+ * + * @see acos | asin | atan | cos | sin | tan + * + */ +double atan2(double, double); + +/** + * @ingroup math + * @par Description: + * This function calculates the principal value of the arc tangent of y/x, + * using the signs of the two arguments to determine the quadrant of the result. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval + * #float On success, the function returns the principal value of the arc tangent of y/x in radians; + * the return value is in the range [-pi, pi].\n + * If y is +0 (-0) and x is less than 0, +pi (-pi) is returned.\n + * If y is +0 (-0) and x is greater than 0, +0 (-0) is returned.\n + * If y is less than 0 and x is +0 or -0, -pi/2 is returned.\n + * If y is greater than 0 and x is +0 or -0, pi/2 is returned.\n + * If either x or y is NaN, a NaN is returned.\n + * If y is +0 (-0) and x is -0, +pi (-pi) is returned.\n + * If y is +0 (-0) and x is +0, +0 (-0) is returned.\n + * If y is a finite value greater (less) than 0, and x is negative infinity, +pi (-pi) is returned.\n + * If y is a finite value greater (less) than 0, and x is positive infinity, +0 (-0) is returned.\n + * If y is positive infinity (negative infinity), and x is finite, pi/2 (-pi/2) is returned.\n + * If y is positive infinity (negative infinity) and x is negative infinity, +3 *pi/4 (-3 *pi/4) is returned.\n + * If y is positive infinity (negative infinity) and x is positive infinity, +pi/4 (-pi/4) is returned.\n + * + * @par Dependency: + *
  • math.h
+ * + * @see acos | asin | atan | cos | sin | tan + * + */ +float atan2f(float, float); + +/** + * @ingroup math + * @par Description: + * This function calculates the principal value of the arc tangent of y/x, + * using the signs of the two arguments to determine the quadrant of the result. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval "long double" On success, these functions return the principal value of the arc tangent of y/x in radians; + * the return value is in the range [-pi, pi].\n + * If y is +0 (-0) and x is less than 0, +pi (-pi) is returned.\n + * If y is +0 (-0) and x is greater than 0, +0 (-0) is returned.\n + * If y is less than 0 and x is +0 or -0, -pi/2 is returned.\n + * If y is greater than 0 and x is +0 or -0, pi/2 is returned.\n + * If either x or y is NaN, a NaN is returned.\n + * If y is +0 (-0) and x is -0, +pi (-pi) is returned.\n + * If y is +0 (-0) and x is +0, +0 (-0) is returned.\n + * If y is a finite value greater (less) than 0, and x is negative infinity, +pi (-pi) is returned.\n + * If y is a finite value greater (less) than 0, and x is positive infinity, +0 (-0) is returned.\n + * If y is positive infinity (negative infinity), and x is finite, pi/2 (-pi/2) is returned.\n + * If y is positive infinity (negative infinity) and x is negative infinity, +3 *pi/4 (-3 *pi/4) is returned.\n + * If y is positive infinity (negative infinity) and x is positive infinity, +pi/4 (-pi/4) is returned.\n + * + * @par Dependency: + *
  • math.h
+ * + * @see acos | asin | atan | cos | sin | tan + * + */ +long double atan2l(long double, long double); + +/** + * @ingroup math + * @par Description: + * This function calculates the inverse hyperbolic tangent of x; that is the value whose hyperbolic tangent is x. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval + * #double On success, this function returns the inverse hyperbolic tangent of x.\n + * If x is a NaN, a NaN is returned.\n + * If x is +0 (-0), +0 (-0) is returned.\n + * If x is +1 or -1, a pole error occurs, and the functions return HUGE_VAL, HUGE_VALF, or HUGE_VALL, + * respectively, with the mathematically correct sign.\n + * If the absolute value of x is greater than 1, a domain error occurs, and a NaN is returned.\n + * + * @par Dependency: + *
  • math.h
+ * @see acosh | asinh | cosh | sinh | tanh + * + */ +double atanh(double); + +/** + * @ingroup math + * @par Description: + * This function calculates the inverse hyperbolic tangent of x; that is the value whose hyperbolic tangent is x. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval + * #float On success, this function returns the inverse hyperbolic tangent of x.\n + * If x is a NaN, a NaN is returned.\n + * If x is +0 (-0), +0 (-0) is returned.\n + * If x is +1 or -1, a pole error occurs, and the functions return HUGE_VAL, + * HUGE_VALF, or HUGE_VALL, respectively, with the mathematically correct sign.\n + * If the absolute value of x is greater than 1, a domain error occurs, and a NaN is returned.\n + * + * @par Dependency: + *
  • math.h
+ * @see acosh | asinh | cosh | sinh | tanh + * + */ +float atanhf(float); + +/** + * @ingroup math + * @par Description: + * This function calculates the inverse hyperbolic tangent of x; that is the value whose hyperbolic tangent is x. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval "long double" On success, this function returns the inverse hyperbolic tangent of x.\n + * If x is a NaN, a NaN is returned.\n + * If x is +0 (-0), +0 (-0) is returned.\n + * If x is +1 or -1, a pole error occurs, and the functions return HUGE_VAL, HUGE_VALF, or HUGE_VALL, respectively, with the mathematically correct sign.\n + * If the absolute value of x is greater than 1, a domain error occurs, and a NaN is returned.\n + * + * @par Dependency: + *
  • math.h
+ * @see acosh | asinh | cosh | sinh | tanh + * + */ +long double atanhl(long double); + +/** + * @ingroup math + * @par Description: + * This function returns the (real) cube root of x. This function cannot fail; every representable + * real value has a representable real cube root. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval + * #double On success, this function returns the cube root of x.\n + * If x is +0, -0, positive infinity, negative infinity, or NaN, x is returned.\n + * + * @par Dependency: + *
  • math.h
+ * + * @see pow | sqrt + * + */ +double cbrt(double); + +/** + * @ingroup math + * @par Description: + * This function returns the (real) cube root of x. This function cannot fail; every + * representable real value has a representable real cube root. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval + * #float On success, this function returns the cube root of x.\n + * If x is +0, -0, positive infinity, negative infinity, or NaN, x is returned.\n + * + * @par Dependency: + *
  • math.h
+ * @see pow | sqrt + * + */ +float cbrtf(float); + +/** + * @ingroup math + * @par Description: + * This function returns the (real) cube root of x. This function cannot fail; every representable real value has a representable real cube root. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval "long double" On success, this function returns the cube root of x.\n + * If x is +0, -0, positive infinity, negative infinity, or NaN, x is returned.\n + * + * @par Dependency: + *
  • math.h
+ * + * @see pow | sqrt + * + */ +long double cbrtl(long double); + +/** + * @ingroup math + * @par Description: + * This function returns the smallest integral value that is not less than x. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval + * #double This function returns the ceiling of x.\n + * If x is integral, +0, -0, NaN, or infinite, x itself is returned.\n + * + * @par Dependency: + *
  • math.h
+ * @see floor | lrint | nearbyint | rint | round | trunc + * + */ +double ceil(double); + +/** + * @ingroup math + * @par Description: + * This function returns the smallest integral value that is not less than x. + * + * @retval + * #float This function returns the ceiling of x.\n + * If x is integral, +0, -0, NaN, or infinite, x itself is returned.\n + * + * @par Dependency: + *
  • math.h
+ * @see floor | lrint | nearbyint | rint | round | trunc + * + */ +float ceilf(float); + +/** + * @ingroup math + * @par Description: + * This function returns the smallest integral value that is not less than x. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval "long double" This function returns the ceiling of x.\n + * If x is integral, +0, -0, NaN, or infinite, x itself is returned.\n + * + * @par Dependency: + *
  • math.h
+ * @see floor | lrint | nearbyint | rint | round | trunc + * + */ +long double ceill(long double); + +/** + * @ingroup math + * @par Description: + * This function returns a value whose absolute value matches that of x, + * but whose sign bit matches that of y. + * For example, copysign(42.0, -1.0) and copysign(-42.0, -1.0) both return -42.0. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval + * #double On success, this function returns a value whose magnitude is taken from x + * and whose sign is taken from y.\n + * If x is a NaN, a NaN with the sign bit of y is returned.\n + * + * @par Dependency: + *
  • math.h
+ * + * @see signbit + * + */ +double copysign(double, double); + +/** + * @ingroup math + * @par Description: + * This function returns a value whose absolute value matches that of x, + * but whose sign bit matches that of y. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval + * #float On success, this function returns a value whose magnitude is taken from x + * and whose sign is taken from y.\n + * If x is a NaN, a NaN with the sign bit of y is returned.\n + * + * @par Dependency: + *
  • math.h
+ * + * @see signbit + * + */ +float copysignf(float, float); + +/** + * @ingroup math + * @par Description: + * This function returns a value whose absolute value matches that of x, + * but whose sign bit matches that of y. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval "long double" On success, this function returns a value whose magnitude is taken from x + * and whose sign is taken from y.\n + * If x is a NaN, a NaN with the sign bit of y is returned.\n + * + * @par Dependency: + *
  • math.h
+ * + * @see signbit + * + */ +long double copysignl(long double, long double); + +/** + * @ingroup math + * @par Description: + * This function returns the cosine of x, where x is given in radians. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval + * #double On success, this function returns the cosine of x.\n + * If x is a NaN, a NaN is returned.\n + * If x is positive infinity or negative infinity, a domain error occurs, and a NaN is returned. + * + * @par Dependency: + *
  • math.h
+ * + * @see acos | asin | atan | atan2 | sin | sincos | tan + * + */ +double cos(double); + +/** + * @ingroup math + * @par Description: + * This function returns the cosine of x, where x is given in radians. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval + * #float On success, this function return the cosine of x.\n + * If x is a NaN, a NaN is returned.\n + * If x is positive infinity or negative infinity, a domain error occurs, and a NaN is returned.\n + * + * @par Dependency: + *
  • math.h
+ * + * @see acos | asin | atan | atan2 | sin | sincos | tan + * + */ +float cosf(float); + +/** + * @ingroup math + * @par Description: + * This function returns the cosine of x, where x is given in radians. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval "long double" On success, this function returns the cosine of x.\n + * If x is a NaN, a NaN is returned.\n + * If x is positive infinity or negative infinity, a domain error occurs, and a NaN is returned.\n + * + * @par Dependency: + *
  • math.h
+ * + * @see acos | asin | atan | atan2 | sin | sincos | tan + * + */ +long double cosl(long double); + +/** + * @ingroup math + * @par Description: + * This function returns the hyperbolic cosine of x, which is defined mathematically as: + * cosh(x) = (exp(x) + exp(-x)) / 2 + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval + * #double On success, this function return the hyperbolic cosine of x.\n + * If x is a NaN, a NaN is returned.\n + * If x is +0 or -0, 1 is returned.\n + * If x is positive infinity or negative infinity, positive infinity is returned.\n + * If the result overflows, a range error occurs, and the functions return +HUGE_VAL, + * +HUGE_VALF, or +HUGE_VALL, respectively.\n + * + * @par Dependency: + *
  • math.h
+ * + * @see acosh | asinh | atanh | sinh | tanh + * + */ +double cosh(double); + +/** + * @ingroup math + * @par Description: + * This function returns the hyperbolic cosine of x, which is defined mathematically as: + * cosh(x) = (exp(x) + exp(-x)) / 2 + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval + * #float On success, this function return the hyperbolic cosine of x.\n + * If x is a NaN, a NaN is returned.\n + * If x is +0 or -0, 1 is returned.\n + * If x is positive infinity or negative infinity, positive infinity is returned.\n + * If the result overflows, a range error occurs, and the functions return +HUGE_VAL, + * +HUGE_VALF, or +HUGE_VALL, respectively.\n + * + * @par Dependency: + *
  • math.h
+ * + * @see acosh | asinh | atanh | sinh | tanh + * + */ +float coshf(float); + +/** + * @ingroup math + * @par Description: + * This function returns the hyperbolic cosine of x, which is defined mathematically as: + * cosh(x) = (exp(x) + exp(-x)) / 2 + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval "long double" On success, this function return the hyperbolic cosine of x.\n + * If x is a NaN, a NaN is returned.\n + * If x is +0 or -0, 1 is returned.\n + * If x is positive infinity or negative infinity, positive infinity is returned.\n + * If the result overflows, a range error occurs, and the functions return +HUGE_VAL, +HUGE_VALF, or +HUGE_VALL, respectively.\n + * + * @par Dependency: + *
  • math.h
+ * + * @see acosh | asinh | atanh | sinh | tanh + * + */ +long double coshl(long double); + +/** + * @ingroup math + * @par Description: + * This function returns the error function of x, defined as erf(x) = 2/sqrt(pi) * integral + * from 0 to x of exp(-t *t) dt. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval + * #double On success, this function returns the error function of x, a value in the range [-1, 1].\n + * If x is a NaN, a NaN is returned.\n + * If x is +0 (-0), +0 (-0) is returned.\n + * If x is positive infinity (negative infinity), +1 (-1) is returned.\n + * If x is subnormal, a range error occurs, and the return value is 2 *x/sqrt(pi).\n + * + * @par Dependency: + *
  • math.h
+ * + * @see erfc | exp + * + */ +double erf(double); + +/** + * @ingroup math + * @par Description: + * This function returns the error function of x. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval + * #float On success, this function returns the error function of x, a value in the range [-1, 1].\n + * If x is a NaN, a NaN is returned.\n + * If x is +0 (-0), +0 (-0) is returned.\n + * If x is positive infinity (negative infinity), +1 (-1) is returned.\n + * If x is subnormal, a range error occurs, and the return value is 2 *x/sqrt(pi).\n + * + * @par Dependency: + *
  • math.h
+ * + * @see erfc | exp + * + */ +float erff(float); + +/** + * @ingroup math + * @par Description: + * This function returns the error function of x, defined as erf(x) = 2/sqrt(pi) * integral from 0 to x of exp(-t *t) dt. + * + * @attention + *
    + *
  • The erfc(), erfcf(), and erfcl() functions are provided to avoid the loss accuracy that would occur for the calculation 1-erf(x) for large values of x + * (for which the value of erf(x) approaches 1).
  • + *
+ * + * @retval "long double" On success, this function returns the error function of x, a value in the range [-1, 1].\n + * If x is a NaN, a NaN is returned.\n + * If x is +0 (-0), +0 (-0) is returned.\n + * If x is positive infinity (negative infinity), +1 (-1) is returned.\n + * If x is subnormal, a range error occurs, and the return value is 2 *x/sqrt(pi).\n + * + * @par Dependency: + *
  • math.h
+ * + * @see erfc | exp + * + */ +long double erfl(long double); + +/** + * @ingroup math + * @par Description: + * This function returns the complementary error function of x, that is, 1.0 - erf(x). + * + * @attention + *
    + *
  • The erfc(), erfcf(), and erfcl() functions are provided to avoid the loss accuracy + * that would occur for the calculation 1-erf(x) for large values of x + * (for which the value of erf(x) approaches 1).
  • + *
+ * + * @retval + * #double On success, this function returns the complementary error function of x, a value in the range [0,2].\n + * If x is a NaN, a NaN is returned.\n + * If x is +0 or -0, 1 is returned.\n + * If x is positive infinity, +0 is returned.\n + * If x is negative infinity, +2 is returned.\n + * If the function result underflows and produces an unrepresentable value, the return value is 0.0.\n + * If the function result underflows but produces a representable (i.e., subnormal) value, + * that value is returned, and a range error occurs.\n + * + * @par Dependency: + *
  • math.h
+ * + * @see erf | exp + * + */ +double erfc(double); + +/** + * @ingroup math + * @par Description: + * This function returns the complementary error function of x, that is, 1.0 - erf(x). + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval + * #float On success, this function returns the complementary error function of x, a value in the range [0,2].\n + * If x is a NaN, a NaN is returned.\n + * If x is +0 or -0, 1 is returned.\n + * If x is positive infinity, +0 is returned.\n + * If x is negative infinity, +2 is returned.\n + * If the function result underflows and produces an unrepresentable value, the return value is 0.0.\n + * If the function result underflows but produces a representable (i.e., subnormal) value, + * that value is returned, and a range error occurs.\n + * + * @par Dependency: + *
  • math.h
+ * + * @see erf | exp + * + */ +float erfcf(float); + +/** + * @ingroup math + * @par Description: + * This function returns the complementary error function of x, that is, 1.0 - erf(x). + * + * @attention + *
    + *
  • The erfc(), erfcf(), and erfcl() functions are provided to avoid the loss accuracy that would occur for the calculation 1-erf(x) for large values of x + * (for which the value of erf(x) approaches 1).
  • + *
+ * + * @retval "long double" On success, this function returns the complementary error function of x, a value in the range [0,2].\n + * If x is a NaN, a NaN is returned.\n + * If x is +0 or -0, 1 is returned.\n + * If x is positive infinity, +0 is returned.\n + * If x is negative infinity, +2 is returned.\n + * If the function result underflows and produces an unrepresentable value, the return value is 0.0.\n + * If the function result underflows but produces a representable (i.e., subnormal) value, that value is returned, and a range error occurs.\n + * + * @par Dependency: + *
  • math.h
+ * + * @see erf | exp + * + */ +long double erfcl(long double); + +/** + * @ingroup math + * @par Description: + * This function returns the value of e (the base of natural logarithms) raised to the power of x. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval + * #double On success, this function returns the exponential value of x.\n + * If x is a NaN, a NaN is returned.\n + * If x is positive infinity, positive infinity is returned.\n + * If x is negative infinity, +0 is returned.\n + * If the result underflows, a range error occurs, and zero is returned.\n + * If the result overflows, a range error occurs, and the functions return +HUGE_VAL, +HUGE_VALF, + * or +HUGE_VALL, respectively.\n + * + * @par Dependency: + *
  • math.h
+ * + * @see cbrt | exp2 | sqrt + * + */ +double exp(double); + +/** + * @ingroup math + * @par Description: + * This function returns the value of e (the base of natural logarithms) raised to the power of x. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval + * #float On success, this function returns the exponential value of x.\n + * If x is a NaN, a NaN is returned.\n + * If x is positive infinity, positive infinity is returned.\n + * If x is negative infinity, +0 is returned.\n + * If the result underflows, a range error occurs, and zero is returned.\n + * If the result overflows, a range error occurs, and the functions return +HUGE_VAL, + * +HUGE_VALF, or +HUGE_VALL, respectively.\n + * + * @par Dependency: + *
  • math.h
+ * + * @see cbrt | exp | exp2 | sqrt + * + */ +float expf(float); + +/** + * @ingroup math + * @par Description: + * This function returns the value of e (the base of natural logarithms) raised to the power of x. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval "long double" On success, this function returns the exponential value of x.\n + * If x is a NaN, a NaN is returned.\n + * If x is positive infinity, positive infinity is returned.\n + * If x is negative infinity, +0 is returned.\n + * If the result underflows, a range error occurs, and zero is returned.\n + * If the result overflows, a range error occurs, and the functions return +HUGE_VAL, +HUGE_VALF, or +HUGE_VALL, respectively.\n + * + * @par Dependency: + *
  • math.h
+ * + * @see cbrt | exp | exp2 | sqrt + * + */ +long double expl(long double); + +/** + * @ingroup math + * @par Description: + * This function returns the value of 2 raised to the power of x. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval + * #double On success, the function returns the base-2 exponential value of x.\n + * For various special cases, including the handling of infinity and NaN, as well as + * overflows and underflows, see exp().\n + * + * @par Dependency: + *
  • math.h
+ * + * @see cbrt | exp | sqrt + * + */ +double exp2(double); +float exp2f(float); +long double exp2l(long double); + +/** + * @ingroup math + * @par Description: + * The function returns a value equivalent to + * exp(x) - 1 + * The result is computed in a way that is accurate even if the value of x is near zero. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval + * #double On success, this function returns exp(x) - 1.\n + * If x is a NaN, a NaN is returned.\n + * If x is +0 (-0), +0 (-0) is returned.\n + * If x is positive infinity, positive infinity is returned.\n + * If x is negative infinity, -1 is returned.\n + * If the result overflows, a range error occurs, and the function returns -HUGE_VAL, + * -HUGE_VALF, or -HUGE_VALL, respectively.\n + * + * @par Dependency: + *
  • math.h
+ * + * @see exp | log | log1p + * + */ +double expm1(double); + +/** + * @ingroup math + * @par Description: + * The function returns a value equivalent to + * exp(x) - 1 + * The result is computed in a way that is accurate even if the value of x is near zero-a case where exp(x)-1 would + * be inaccurate due to subtraction of two numbers that are nearly equal. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval + * #float On success, this function returns exp(x) - 1.\n + * If x is a NaN, a NaN is returned.\n + * If x is +0 (-0), +0 (-0) is returned.\n + * If x is positive infinity, positive infinity is returned.\n + * If x is negative infinity, -1 is returned.\n + * If the result overflows, a range error occurs, and the function returns -HUGE_VAL, + * -HUGE_VALF, or -HUGE_VALL, respectively.\n + * + * @par Dependency: + *
  • math.h
+ * + * @see exp | log | log1p + * + */ +float expm1f(float); +long double expm1l(long double); + +/** + * @ingroup math + * @par Description: + * This function returns the absolute value of the floating-point number x. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval + * #double This function returns the absolute value of x.\n + * If x is a NaN, a NaN is returned.\n + * If x is -0, +0 is returned.\n + * If x is negative infinity or positive infinity, positive infinity is returned.\n + * + * @par Dependency: + *
  • math.h
+ * + * @see ceil | floor | rint + * + */ +double fabs(double); + +/** + * @ingroup math + * @par Description: + * This function returns the absolute value of the floating-point number x. + * + * @retval + * #float This function returns the absolute value of x.\n + * If x is a NaN, a NaN is returned.\n + * If x is -0, +0 is returned.\n + * If x is negative infinity or positive infinity, positive infinity is returned.\n + * + * @par Dependency: + *
  • math.h
+ * @see ceil | floor | rint + * + */ +float fabsf(float); + +/** + * @ingroup math + * @par Description: + * This function returns the absolute value of the floating-point number x. + * + * @retval "long double" This function returns the absolute value of x.\n + * If x is a NaN, a NaN is returned.\n + * If x is -0, +0 is returned.\n + * If x is negative infinity or positive infinity, positive infinity is returned.\n + * + * @par Dependency: + *
  • math.h
+ * @see ceil | floor | rint + * + */ +long double fabsl(long double); + +double fdim(double, double); +float fdimf(float, float); +long double fdiml(long double, long double); + +/** + * @ingroup math + * @par Description: + * This function returns the largest integral value that is not greater than x. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval + * #double This function returns the floor of x.\n + * If x is integral, +0, -0, NaN, or an infinity, x itself is returned.\n + * + * @par Dependency: + *
  • math.h
+ * + * @see ceil | lrint | nearbyint | rint | round | trunc + * + */ +double floor(double); + +/** + * @ingroup math + * @par Description: + * This function returns the largest integral value that is not greater than x. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval + * #float This function returns the floor of x.\n + * If x is integral, +0, -0, NaN, or an infinity, x itself is returned.\n + * + * @par Dependency: + *
  • math.h
+ * + * @see ceil | lrint | nearbyint | rint | round | trunc + * + */ +float floorf(float); + +/** + * @ingroup math + * @par Description: + * This function returns the largest integral value that is not greater than x. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval "long double" this function returns the floor of x. If x is integral, +0, -0, NaN, or an infinity, x itself is returned. + * + * @par Dependency: + *
  • math.h
+ * + * @see ceil | lrint | nearbyint | rint | round | trunc + * + */ +long double floorl(long double); + +double fma(double, double, double); +float fmaf(float, float, float); +long double fmal(long double, long double, long double); + +double fmax(double, double); +float fmaxf(float, float); +long double fmaxl(long double, long double); + +double fmin(double, double); +float fminf(float, float); +long double fminl(long double, long double); + +/** + * @ingroup math + * @par Description: + * The function computes the floating-point remainder of dividing x by div. The return value is x - n * div, + * where n is the quotient of x / div, rounded toward zero to an integer. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval + * #double On success, the function returns the value x - n *div, for some integer n, + * such that the returned value has the same sign as x and a magnitude less than + * the magnitude of div.\n + * If x or div is a NaN, a NaN is returned.\n + * If x is an infinity, a domain error occurs, and a NaN is returne.\n + * If div is zero, a domain error occurs, and a NaN is returned.\n + * If x is +0 (-0), and div is not zero, +0 (-0) is returned.\n + * + * @par Dependency: + *
  • math.h
+ * + * @see remainder + * + */ +double fmod(double, double); + +/** + * @ingroup math + * @par Description: + * The function computes the floating-point remainder of dividing x by div. The return value is x - n * div, + * where n is the quotient of x / div, rounded toward zero to an integer. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval + * #float On success, these functions return the value x - n *div, for some integer n, + * such that the returned value has the same sign as x and a magnitude less than + * the magnitude of div.\n + * If x is a NaN, a NaN with the sign bit of div is returned.\n + * If x is an infinity, a domain error occurs, and a NaN is returned.\n + * If y is zero, a domain error occurs, and a NaN is returned.\n + * If x is +0 (-0), and div is not zero, +0 (-0) is returned.\n + * + * @par Dependency: + *
  • math.h
+ * + * @see remainder + * + */ +float fmodf(float, float); + +/** + * @ingroup math + * @par Description: + * The function computes the floating-point remainder of dividing x by div. The return value is x - n * div, + * where n is the quotient of x / div, rounded toward zero to an integer. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval "long double" On success, these functions return the value x - n*div, for some integer n, + * such that the returned value has the same sign as x and a magnitude less than + * the magnitude of div.\n + * If x is a NaN, a NaN with the sign bit of div is returned.\n + * If x is an infinity, a domain error occurs, and a NaN is returned.\n + * If y is zero, a domain error occurs, and a NaN is returned.\n + * If x is +0 (-0), and div is not zero, +0 (-0) is returned.\n + * + * @par Dependency: + *
  • math.h
+ * + * @see remainder + * + */ +long double fmodl(long double, long double); + +/** + * @ingroup math + * @par Description: + * This function is used to split the number x into a normalized fraction and an exponent which is stored in eptr. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval + * #double This function returns the normalized fraction. If the argument x is not zero, the normalized + * fraction is x times a power of two, and its absolute + * value is always in the range 1/2 (inclusive) to 1(exclusive), that is, [0.5,1).\n + * If x is zero, then the normalized fraction is zero and zero is stored in eptr.\n + * If x is a NaN, a NaN is returned, and the value of *eptr is unspecified.\n + * If x is positive infinity (negative infinity), positive infinity (negative infinity) is returned, + * and the value of *eptr is unspecified.\n + * + * @par Dependency: + *
  • math.h
+ * + * @see ldexp | modf + * + */ +double frexp(double, int *); + +/** + * @ingroup math + * @par Description: + * This function is used to split the number x into a normalized fraction and an exponent which is stored in eptr. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval + * #float This function returns the normalized fraction. If the argument x is not zero, + * the normalized fraction is x times a power of two, and its absolute + * value is always in the range 1/2 (inclusive) to 1(exclusive), that is, [0.5,1).\n + * If x is zero, then the normalized fraction is zero and zero is stored in eptr.\n + * If x is a NaN, a NaN is returned, and the value of *eptr is unspecified.\n + * If x is positive infinity (negative infinity), positive infinity (negative infinity) is returned, + * and the value of *eptr is unspecified.\n + * + * @par Dependency: + *
  • math.h
+ * + * @see ldexp | modf + * + */ +float frexpf(float, int *); + +/** + * @ingroup math + * @par Description: + * This function is used to split the number x into a normalized fraction and an exponent which is stored in eptr. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval "long double" This function returns the normalized fraction. If the argument x is not zero, the normalized fraction is x times a power of two, and its absolute + * value is always in the range 1/2 (inclusive) to 1(exclusive), that is, [0.5,1).\n + * If x is zero, then the normalized fraction is zero and zero is stored in eptr.\n + * If x is a NaN, a NaN is returned, and the value of *eptr is unspecified.\n + * If x is positive infinity (negative infinity), positive infinity (negative infinity) is returned, and the value of *eptr is unspecified.\n + * + * @par Dependency: + *
  • math.h
+ * + * @see ldexp | modf + * + */ +long double frexpl(long double, int *); + +/** + * @ingroup math + * @par Description: + * The function returns sqrt(x *x+y *y). This is the length of the hypotenuse of a right-angled triangle + * with sides of length x and y. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval + * #double On success, this function returns the length of a right-angled triangle with sides of length x and y.\n + * If x or y is an infinity, positive infinity is returned.\n + * If x or y is a NaN, and the other argument is not an infinity, a NaN is returned.\n + * If the result overflows, a range error occurs, and the functions return HUGE_VAL, HUGE_VALF, + * or HUGE_VALL, respectively.\n + * If both arguments are subnormal, and the result is subnormal, a range error occurs, + * and the correct result is returned.\n + * + * @par Dependency: + *
  • math.h
+ * + * @see sqrt + * + */ +double hypot(double, double); +float hypotf(float, float); + +/** + * @ingroup math + * @par Description: + * The function returns sqrt(x*x+y*y). This is the length of the hypotenuse of a right-angled triangle + * with sides of length x and y. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval "long double" On success, this function returns the length of a right-angled triangle with sides of length x and y.\n + * If x or y is an infinity, positive infinity is returned.\n + * If x or y is a NaN, and the other argument is not an infinity, a NaN is returned.\n + * If the result overflows, a range error occurs, and the functions return HUGE_VAL, HUGE_VALF, + * or HUGE_VALL, respectively.\n + * If both arguments are subnormal, and the result is subnormal, a range error occurs, + * and the correct result is returned.\n + * + * @par Dependency: + *
  • math.h
+ * + * @see sqrt + * + */ +long double hypotl(long double, long double); + +int ilogb(double); +int ilogbf(float); +int ilogbl(long double); + +/** + * @ingroup math + * @par Description: + * This function returns the result of multiplying the floating-point number x by 2 raised to the power n. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval + * #double On success, this function return x * (2^n).\n + * If n is zero, then x is returned.\n + * If x is a NaN, a NaN is returned.\n + * If x is positive infinity (negative infinity), positive infinity (negative infinity) is returned.\n + * If the result underflows, a range error occurs, and zero is returned.\n + * If the result overflows, a range error occurs, and the functions return HUGE_VAL, HUGE_VALF, or HUGE_VALL, + * respectively, with a sign the same as x.\n + * + * @par Dependency: + *
  • math.h
+ * + * @see frexp | modf | scalbln + * + */ +double ldexp(double, int); + +/** + * @ingroup math + * @par Description: + * This function returns the result of multiplying the floating-point number x by 2 raised to the power exp. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval + * #float On success, this function return x * (2^exp).\n + * If exp is zero, then x is returned.\n + * If x is a NaN, a NaN is returned.\n + * If x is positive infinity (negative infinity), positive infinity (negative infinity) is returned.\n + * If the result underflows, a range error occurs, and zero is returned.\n + * If the result overflows, a range error occurs, and the functions return + * HUGE_VAL, HUGE_VALF, or HUGE_VALL, respectively, with a sign the same as x.\n + * + * @par Dependency: + *
  • math.h
+ * + * @see frexp | modf | scalbln + * + */ +float ldexpf(float, int); + +/** + * @ingroup math + * @par Description: + * This function returns the result of multiplying the floating-point number x by 2 raised to the power n. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval "long double" On success, this function return x * (2^n).\n + * If n is zero, then x is returned.\n + * If x is a NaN, a NaN is returned.\n + * If x is positive infinity (negative infinity), positive infinity (negative infinity) is returned.\n + * If the result underflows, a range error occurs, and zero is returned.\n + * If the result overflows, a range error occurs, and the functions return HUGE_VAL, HUGE_VALF, or HUGE_VALL, respectively, with a sign the same as x.\n + * + * @par Dependency: + *
  • math.h
+ * + * @see frexp | modf | scalbln + * + */ +long double ldexpl(long double, int); + +double lgamma(double); +float lgammaf(float); +long double lgammal(long double); + +/** + * @ingroup math + * @par Description: + * The function rounds its argument to the nearest integer value, using the current rounding direction. + * Note that unlike the rint() family of functions, the return type of the function differs from that + * of their arguments. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval "long long" The function returns the rounded integer value. If x is a NaN or an infinity, + * or the rounded value is too large to be stored in a long + * (long long in the case of the ll * functions), then a domain error occurs, + * and the return value is unspecified. + * + * @par Dependency: + *
  • math.h
+ * + * @see ceil | floor | lround | nearbyint | rint | round + * + */ +long long llrint(double); +long long llrintf(float); +long long llrintl(long double); + +long long llround(double); +long long llroundf(float); +long long llroundl(long double); + +/** + * @ingroup math + * @par Description: + * This function returns the natural logarithm of x. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval + * #double On success, this function returns the natural logarithm of x.\n + * If x is a NaN, a NaN is returned.\n + * If x is 1, the result is +0.\n + * If x is positive infinity, positive infinity is returned.\n + * If x is zero, then a pole error occurs, and the functions return -HUGE_VAL, + * -HUGE_VALF, or -HUGE_VALL, respectively.\n + * If x is negative (including negative infinity), then a domain error occurs, + * and a NaN (not a number) is returned.\n + * + * + * @par Dependency: + *
  • math.h
+ * + * @see cbrt | log10 | log1p | log2 | sqrt + * + */ +double log(double); + +/** + * @ingroup math + * @par Description: + * This function returns the natural logarithm of x. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval + * #float On success, this function returns the natural logarithm of x.\n + * If x is a NaN, a NaN is returned.\n + * If x is 1, the result is +0.\n + * If x is positive infinity, positive infinity is returned.\n + * If x is zero, then a pole error occurs, and the functions return + * -HUGE_VAL, -HUGE_VALF, or -HUGE_VALL, respectively.\n + * If x is negative (including negative infinity), then a domain error occurs, + * and a NaN (not a number) is returned.\n + * + * @par Dependency: + *
  • math.h
+ * + * @see cbrt | log10 | log1p | log2 | sqrt + * + */ +float logf(float); + +/** + * @ingroup math + * @par Description: + * This function returns the natural logarithm of x. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval "long double" On success, this function returns the natural logarithm of x.\n + * If x is a NaN, a NaN is returned.\n + * If x is 1, the result is +0.\n + * If x is positive infinity, positive infinity is returned.\n + * If x is zero, then a pole error occurs, and the functions return -HUGE_VAL, -HUGE_VALF, or -HUGE_VALL, respectively.\n + * If x is negative (including negative infinity), then a domain error occurs, and a NaN (not a number) is returned.\n + * + * @par Dependency: + *
  • math.h
+ * + * @see cbrt | log10 | log1p | log2 | sqrt + * + */ +long double logl(long double); + +/** + * @ingroup math + * @par Description: + * This function returns the base 10 logarithm of x. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval + * #double On success, this function returns the base 10 logarithm of x.\n + * For special cases, including where x is 0, 1, negative, infinity, or NaN, see log.\n + * + * @par Dependency: + *
  • math.h
+ * + * @see cbrt | log | log2 | sqrt + * + */ +double log10(double); + +/** + * @ingroup math + * @par Description: + * This function returns the base 10 logarithm of x. + * + * @attention + *
    + *
  • None.
  • + *
+ * + * @retval + * #float On success, this function returns the base 10 logarithm of x.\n + *
    For special cases, including where x is 0, 1, negative, infinity, or NaN, see log.\n + * + * @par Dependency: + *
    • math.h
    + * + * @see cbrt | log | log2 | sqrt + * + */ +float log10f(float); + +/** + * @ingroup math + * @par Description: + * This function returns the base 10 logarithm of x. + * + * @attention + *
      + *
    • None.
    • + *
    + * + * @retval "long double" On success, this function returns the base 10 logarithm of x.\n + *
      For special cases, including where x is 0, 1, negative, infinity, or NaN, see log.\n + * + * @par Dependency: + *
      • math.h
      + * + * @see cbrt | log | log2 | sqrt + * + */ +long double log10l(long double); + +/** + * @ingroup math + * @par Description: + * This function returns a value equivalent to log (1 + x). + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval + * #double On success, this function returns the natural logarithm of (1 + x).\n + * If x is a NaN, a NaN is returned.\n + * If x is positive infinity, positive infinity is returned.\n + * If x is -1, a pole error occurs, and the functions return -HUGE_VAL, + * -HUGE_VALF, or -HUGE_VALL, respectively.\n + * If x is less than -1 (including negative infinity), a domain error occurs, + * and a NaN (not a number) is returned.\n + * + * @par Dependency: + *
      • math.h
      + * + * @see exp | expm1 | log + * + */ +double log1p(double); + +/** + * @ingroup math + * @par Description: + * The function return a value equivalent to + * log (1 + x) + * The result is computed in a way that is accurate even if the value of x is near zero. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval + * #float On success, the function returns the natural logarithm of (1 + x).\n + * If x is a NaN, a NaN is returned.\n + * If x is positive infinity, positive infinity is returned.\n + * If x is -1, a pole error occurs, and the functions return -HUGE_VAL, -HUGE_VALF, or -HUGE_VALL, respectivel.\n + * If x is less than -1 (including negative infinity), a domain error occurs, and a NaN (not a number) is returned.\n + * + * + * @par Dependency: + *
      • math.h
      + * + * @see exp | expm1 | log + * + */ +float log1pf(float); +long double log1pl(long double); + +/** + * @ingroup math + * @par Description: + * This function returns the base 2 logarithm of x. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval + * #double On success, the function returns the base 2 logarithm of x. + * For special cases, including where x is 0, 1, negative, infinity, or NaN, see log(). + * + * @par Dependency: + *
      • math.h
      + * + * @see cbrt | log | log10 | sqrt + * + */ +double log2(double); + +/** + * @ingroup math + * @par Description: + * This function returns the base 2 logarithm of x. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval + * #float On success, this function returns the base 2 logarithm of x.\n + * For special cases, including where x is 0, 1, negative, infinity, or NaN, see log. + * + * @par Dependency: + *
      • math.h
      + * + * @see cbrt | log | log10 | sqrt + * + */ +float log2f(float); + +/** + * @ingroup math + * @par Description: + * This function returns the base 2 logarithm of x. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval "long double" On success, the function returns the base 2 logarithm of x. For special cases, including where x is 0, 1, negative, infinity, or NaN, see log(). + * + * @par Dependency: + *
      • math.h
      + * + * @see cbrt | log | log10 | sqrt + * + */ +long double log2l(long double); + +double logb(double); +float logbf(float); +long double logbl(long double); + +long lrint(double); +long lrintf(float); +long lrintl(long double); + +long lround(double); +long lroundf(float); +long lroundl(long double); + +/** + * @ingroup math + * @par Description: + * This function breaks the argument x into an integral part and a fractional part, + * each of which has the same sign as x. + * The integral part is stored in the location pointed to by iptr. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval + * #double This function returns the fractional part of x.\n + * If x is a NaN, a NaN is returned, and *iptr is set to a NaN.\n + * If x is positive infinity (negative infinity), +0 (-0) is returned, + * and *iptr is set to positive infinity (negative infinity).\n + * + * @par Dependency: + *
      • math.h
      + * + * @see frexp | ldexp + * + */ +double modf(double, double *); + +/** + * @ingroup math + * @par Description: + * This function breaks the argument x into an integral part and a fractional part, + * each of which has the same sign as x. + * The integral part is stored in the location pointed to by iptr. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval + * #float This function returns the fractional part of x.\n + * If x is a NaN, a NaN is returned, and *iptr is set to a NaN.\n + * If x is positive infinity (negative infinity), +0 (-0) is returned, and *iptr + * is set to positive infinity (negative infinity).\n + * + * @par Dependency: + *
      • math.h
      + * + * @see frexp | ldexp + * + */ +float modff(float, float *); + +/** + * @ingroup math + * @par Description: + * This function breaks the argument x into an integral part and a fractional part, each of which has the same sign as x. + * The integral part is stored in the location pointed to by iptr. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval "long double" This function returns the fractional part of x.\n + * If x is a NaN, a NaN is returned, and *iptr is set to a NaN.\n + * If x is positive infinity (negative infinity), +0 (-0) is returned, and *iptr is set to positive infinity (negative infinity).\n + * + * @par Dependency: + *
      • math.h
      + * + * @see frexp | ldexp + * + */ +long double modfl(long double, long double *); + +/** + * @ingroup math + * @par Description: + * The function returns a representation (determined by __kind) of a quiet NaN. If the implementation does not support + * quiet NaNs, the function returns zero. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval + * #double It returns a representation (determined by __kind) of a quiet NaN. If the implementation does not support + * quiet NaNs, the function returns zero. + * + * @par Dependency: + *
      • math.h
      + * + * @see signbit + * + */ +double nan(const char *); + +/** + * @ingroup math + * @par Description: + * The function returns a representation (determined by __kind) of a quiet NaN. If the implementation does not support + * quiet NaNs, the function returns zero. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval + * #float It returns a representation (determined by __kind) of a quiet NaN. If the implementation does not support + * quiet NaNs, the function returns zero. + * + * @par Dependency: + *
      • math.h
      + * + * @see signbit + * + */ +float nanf(const char *); + +/** + * @ingroup math + * @par Description: + * The function returns a representation (determined by __kind) of a quiet NaN. If the implementation does not support + * quiet NaNs, the function returns zero. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval "long double" It returns a representation (determined by __kind) of a quiet NaN. If the implementation does not support + * quiet NaNs, the function returns zero. + * + * @par Dependency: + *
      • math.h
      + * + * @see signbit + * + */ +long double nanl(const char *); + +double nearbyint(double); +float nearbyintf(float); +long double nearbyintl(long double); + +/** + * @ingroup math + * @par Description: + * The nextafter() functions return the next representable floating-point value following x in + * the direction of y. If y is less than x, these functions will return the largest representable + * number less than x. If x equals y, the functions return y. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval + * #double On success, these functions return the next representable floating-point value after x + * in the direction of y.\n + * If x equals y, then y (cast to the same type as x) is returned.\n + * If x or y is a NaN, a NaN is returned.\n + * If x is finite, and the result would overflow, a range error occurs, and the functions return + * HUGE_VAL, HUGE_VALF, or HUGE_VALL, respectively, with the + * correct mathematical sign.\n + * If x is not equal to y, and the correct function result would be subnormal, zero, or underflow, + * a range error occurs, and either the correct value (if it + * can be represented), or 0.0, is returned.\n + * + * @par Dependency: + *
      • math.h
      + * + * @see nearbyint + * + */ +double nextafter(double, double); + +/** + * @ingroup math + * @par Description: + * The nextafterf() function returns the next representable floating-point value + * following x in the direction of y. If y is less than x, the function will return + * the largest representable number less than x. If x equals y, the functions return y. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval + * #float On success, the function returns the next representable floating-point value after x + * in the direction of y.\n + * If x equals y, then y (cast to the same type as x) is returned.\n + * If x or y is a NaN, a NaN is returned.\n + * If x is finite, and the result would overflow, a range error occurs, + * and the functions return HUGE_VAL, HUGE_VALF, or HUGE_VALL, respectively, with the correct mathematical sign.\n + * If x is not equal to y, and the correct function result would be subnormal, zero, or underflow, + * a range error occurs, and either the correct value (if it can be represented), or 0.0, is returned.\n + * + * @par Dependency: + *
      • math.h
      + * @see nearbyint + * + */ +float nextafterf(float, float); +long double nextafterl(long double, long double); + +double nexttoward(double, long double); +float nexttowardf(float, long double); +long double nexttowardl(long double, long double); + +/** + * @ingroup math + * @par Description: + * The pow() function returns the value of x raised to the power of y. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval + * #double On success, this function returns the value of x to the power of y.\n + * If x is a finite value less than 0, and y is a finite noninteger, a domain error occurs, + * and a NaN is returned.\n + * If the result overflows, a range error occurs, and the functions return HUGE_VAL, HUGE_VALF, + * or HUGE_VALL, respectively, with the mathematically correct + * sign.\n + * If result underflows, and is not representable, a range error occurs, and 0.0 is returned.\n + * Except as specified below, if x or y is a NaN, the result is a NaN.\n + * If x is +1, the result is 1.0 (even if y is a NaN).\n + * If y is 0, the result is 1.0 (even if x is a NaN).\n + * If x is +0 (-0), and y is an odd integer greater than 0, the result is +0 (-0).\n + * If x is 0, and y greater than 0 and not an odd integer, the result is +0.\n + * If x is -1, and y is positive infinity or negative infinity, the result is 1.0.\n + * If the absolute value of x is less than 1, and y is negative infinity, the result is positive infinity.\n + * If the absolute value of x is greater than 1, and y is negative infinity, the result is +0.\n + * If the absolute value of x is less than 1, and y is positive infinity, the result is +0.\n + * If the absolute value of x is greater than 1, and y is positive infinity, the result is positive infinity.\n + * If x is negative infinity, and y is an odd integer less than 0, the result is -0.\n + * If x is negative infinity, and y less than 0 and not an odd integer, the result is +0.\n + * If x is negative infinity, and y is an odd integer greater than 0, the result is negative infinity.\n + * If x is negative infinity, and y greater than 0 and not an odd integer, the result is positive infinity.\n + * If x is positive infinity, and y less than 0, the result is +0.\n + * If x is positive infinity, and y greater than 0, the result is positive infinity.\n + * If x is +0 or -0, and y is an odd integer less than 0, a pole error occurs and HUGE_VAL, HUGE_VALF, + * or HUGE_VALL, is returned, with the same sign as x.\n + * If x is +0 or -0, and y is less than 0 and not an odd integer, a pole error occurs and +HUGE_VAL, + * +HUGE_VALF, or +HUGE_VALL, is returned.\n + * + * @par Dependency: + *
      • math.h
      + * + * @see cbrt | sqrt + * + */ +double pow(double, double); + +/** + * @ingroup math + * @par Description: + * This function returns the value of x raised to the power of y. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval + * #float On success, this function returns the value of x to the power of y.\n + * If x is a finite value less than 0, and y is a finite noninteger, a domain error occurs, and a NaN is returned.\n + * If the result overflows, a range error occurs, and the functions return + * HUGE_VAL, HUGE_VALF, or HUGE_VALL, respectively, with the mathematically correct sign.\n + * If result underflows, and is not representable, a range error occurs, and 0.0 is returned.\n + * Except as specified below, if x or y is a NaN, the result is a NaN.\n + * If x is +1, the result is 1.0 (even if y is a NaN).\n + * If y is 0, the result is 1.0 (even if x is a NaN).\n + * If x is +0 (-0), and y is an odd integer greater than 0, the result is +0 (-0).\n + * If x is 0, and y greater than 0 and not an odd integer, the result is +0.\n + * If x is -1, and y is positive infinity or negative infinity, the result is 1.0.\n + * If the absolute value of x is less than 1, and y is negative infinity, the result is positive infinity.\n + * If the absolute value of x is greater than 1, and y is negative infinity, the result is +0.\n + * If the absolute value of x is less than 1, and y is positive infinity, the result is +0.\n + * If the absolute value of x is greater than 1, and y is positive infinity, the result is positive infinity.\n + * If x is negative infinity, and y is an odd integer less than 0, the result is -0.\n + * If x is negative infinity, and y less than 0 and not an odd integer, the result is +0.\n + * If x is negative infinity, and y is an odd integer greater than 0, the result is negative infinity.\n + * If x is negative infinity, and y greater than 0 and not an odd integer, the result is positive infinity.\n + * If x is positive infinity, and y less than 0, the result is +0.\n + * If x is positive infinity, and y greater than 0, the result is positive infinity.\n + * If x is +0 or -0, and y is an odd integer less than 0, a pole error occurs and + * HUGE_VAL, HUGE_VALF, or HUGE_VALL, is returned, with the same sign as x.\n + * If x is +0 or -0, and y is less than 0 and not an odd integer, a pole error occurs + * and +HUGE_VAL, +HUGE_VALF, or +HUGE_VALL, is returned.\n + * + * @par Dependency: + *
      • math.h
      + * + * @see cbrt | sqrt + * + */ +float powf(float, float); + +/** + * @ingroup math + * @par Description: + * The powl() function returns the value of x raised to the power of y. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval "long double" On success, this function returns the value of x to the power of y.\n + * If x is a finite value less than 0, and y is a finite noninteger, a domain error occurs, and a NaN is returned.\n + * If the result overflows, a range error occurs, and the functions return HUGE_VAL, HUGE_VALF, or HUGE_VALL, respectively, with the mathematically correct + * sign.\n + * If result underflows, and is not representable, a range error occurs, and 0.0 is returned.\n + * Except as specified below, if x or y is a NaN, the result is a NaN.\n + * If x is +1, the result is 1.0 (even if y is a NaN).\n + * If y is 0, the result is 1.0 (even if x is a NaN).\n + * If x is +0 (-0), and y is an odd integer greater than 0, the result is +0 (-0).\n + * If x is 0, and y greater than 0 and not an odd integer, the result is +0.\n + * If x is -1, and y is positive infinity or negative infinity, the result is 1.0.\n + * If the absolute value of x is less than 1, and y is negative infinity, the result is positive infinity.\n + * If the absolute value of x is greater than 1, and y is negative infinity, the result is +0.\n + * If the absolute value of x is less than 1, and y is positive infinity, the result is +0.\n + * If the absolute value of x is greater than 1, and y is positive infinity, the result is positive infinity.\n + * If x is negative infinity, and y is an odd integer less than 0, the result is -0.\n + * If x is negative infinity, and y less than 0 and not an odd integer, the result is +0.\n + * If x is negative infinity, and y is an odd integer greater than 0, the result is negative infinity.\n + * If x is negative infinity, and y greater than 0 and not an odd integer, the result is positive infinity.\n + * If x is positive infinity, and y less than 0, the result is +0.\n + * If x is positive infinity, and y greater than 0, the result is positive infinity.\n + * If x is +0 or -0, and y is an odd integer less than 0, a pole error occurs and HUGE_VAL, HUGE_VALF, or HUGE_VALL, is returned, with the same sign as x.\n + * If x is +0 or -0, and y is less than 0 and not an odd integer, a pole error occurs and +HUGE_VAL, +HUGE_VALF, or +HUGE_VALL, is returned.\n + * + * @par Dependency: + *
      • math.h
      + * + * @see cbrt | sqrt + * + */ +long double powl(long double, long double); + +double remainder(double, double); +float remainderf(float, float); +long double remainderl(long double, long double); + +double remquo(double, double, int *); +float remquof(float, float, int *); +long double remquol(long double, long double, int *); + +/** + * @ingroup math + * @par Description: + * The rint() function rounds itsargument to an integer value in floating-point format, + * using the current rounding direction and + * will raise the inexact exception when the result differs in value from the argument. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval + * #double The function returns the rounded integer value. If x is integral, +0, -0, NaN, or + * infinite, x itself is returned. + * + * @par Dependency: + *
      • math.h
      + * + * @see ceil | floor | lrint | round | trunc + * + */ +double rint(double); + +/** + * @ingroup math + * @par Description: + * The rintf() function rounds itsargument to an integer value in floating-point format, + * using the current rounding direction and + * will raise the inexact exception when the result differs in value from the argument. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval + * #float The function returns the rounded integer value. If x is integral, +0, -0, + * NaN, or infinite, x itself is returned. + * + * @par Dependency: + *
      • math.h
      + * + * @see ceil | floor | lrint | round | trunc + * + */ +float rintf(float); + +/** + * @ingroup math + * @par Description: + * The rintl() function rounds itsargument to an integer value in floating-point format, using the current rounding direction and + * will raise the inexact exception when the result differs in value from the argument. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval "long double" The function returns the rounded integer value. If x is integral, +0, -0, NaN, or infinite, x itself is returned. + * + * @par Dependency: + *
      • math.h
      + * + * @see ceil | floor | lrint | round | trunc + * + */ +long double rintl(long double); + +/** + * @ingroup math + * @par Description: + * The function rounds x to the nearest integer, but round halfway cases away from zero, + * instead of to the nearest even integer + * like rint(). For example, round(0.5) is 1.0, and round(-0.5) is -1.0. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval + * #double This function returns the rounded integer value.\n + * If x is integral, +0, -0, NaN, or infinite, x itself is returned.\n + * + * @par Dependency: + *
      • math.h
      + * + * @see ceil | floor | lround | nearbyint | rint | trunc + * + */ +double round(double); + +/** + * @ingroup math + * @par Description: + * The function rounds x to the nearest integer, but round halfway cases away from zero, + * instead of to the nearest even integer + * like rint(). + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval + * #float This function returns the rounded integer value.\n + * If x is integral, +0, -0, NaN, or infinite, x itself is returned.\n + * + * @par Dependency: + *
      • math.h
      + * + * @see ceil | floor | lround | nearbyint | rint | trunc + * + */ +float roundf(float); + +/** + * @ingroup math + * @par Description: + * The function rounds x to the nearest integer, but round halfway cases away from zero, instead of to the nearest even integer + * like rint(). + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval "long double" This function returns the rounded integer value.\n + * If x is integral, +0, -0, NaN, or infinite, x itself is returned.\n + * + * @par Dependency: + *
      • math.h
      + * + * @see ceil | floor | lround | nearbyint | rint | trunc + * + */ +long double roundl(long double); + +double scalbln(double, long); +float scalblnf(float, long); +long double scalblnl(long double, long); + +double scalbn(double, int); + +/** + * @ingroup math + * @par Description: + * The function multiplies its first argument x by FLT_RADIX (probably 2) to the power of n, that is: + * x * FLT_RADIX * * exp + *The definition of FLT_RADIX can be obtained by including + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval + * #float On success, the function returns x * FLT_RADIX * * exp. + *
        If x is a NaN, a NaN is returned.
      + *
        If x is positive infinity (negative infinity), positive infinity (negative infinity) is returned.
      + *
        If the result overflows, a range error occurs, and the functions return HUGE_VAL, HUGE_VALF, + * or HUGE_VALL, respectively, with a sign the same as x.
      + *
        If x is less than -1 (including negative infinity), a domain error occurs, + * and a NaN (not a number) is returned.
      + *
        If the result underflows, a range error occurs, and the functions return zero, + * with a sign the same as x.
      + * + * @par Dependency: + *
      • math.h
      + * + * @see ldexp + * + */ +float scalbnf(float, int); + +/** + * @ingroup math + * @par Description: + * The function multiplies its first argument x by FLT_RADIX (probably 2) to the power of n, that is: + * x * FLT_RADIX ** exp + * The definition of FLT_RADIX can be obtained by including + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval "long double" On success, the function returns x * FLT_RADIX ** exp. + *
        If x is a NaN, a NaN is returned.
      + *
        If x is positive infinity (negative infinity), positive infinity (negative infinity) is returned.
      + *
        If the result overflows, a range error occurs, and the functions return HUGE_VAL, HUGE_VALF, + * or HUGE_VALL, respectively, with a sign the same as x.
      + *
        If x is less than -1 (including negative infinity), a domain error occurs, + * and a NaN (not a number) is returned.
      + *
        If the result underflows, a range error occurs, and the functions return zero, + * with a sign the same as x.
      + * + * @par Dependency: + *
      • math.h
      + * + * @see ldexp + * + */ +long double scalbnl(long double, int); +/** + * @ingroup math + * @par Description: + * This function returns the sine of x, where x is given in radians. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval + * #double On success, this function returns the sine of x.\n + * If x is a NaN, a NaN is returned.\n + * If x is positive infinity or negative infinity, a domain error occurs, and a NaN is returned.\n + * + * @par Dependency: + *
      • math.h
      + * + * @see acos | asin | atan | atan2 | sincos | tan | cos + * + */ +double sin(double); + +/** + * @ingroup math + * @par Description: + * This function returns the sine of x, where x is given in radians. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval + * #float On success, this function returns the sine of x.\n + * If x is a NaN, a NaN is returned.\n + * If x is positive infinity or negative infinity, a domain error occurs, and a NaN is returned.\n + * + * @par Dependency: + *
      • math.h
      + * + * @see acos | asin | atan | atan2 | sin | sincos | tan + * + */ +float sinf(float); + +/** + * @ingroup math + * @par Description: + * This function returns the sine of x, where x is given in radians. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval "long double" On success, this function returns the sine of x.\n + * If x is a NaN, a NaN is returned.\n + * If x is positive infinity or negative infinity, a domain error occurs, and a NaN is returned.\n + * + * @par Dependency: + *
      • math.h
      + * + * @see acos | asin | atan | atan2 | sincos | tan | cos + * + */ +long double sinl(long double); + +/** + * @ingroup math + * @par Description: + * This function returns the hyperbolic sine of x, which is defined mathematically as: + * sinh(x) = (exp(x) - exp(-x)) / 2 + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval + * #double On success, this function return the hyperbolic sine of x.\n + * If x is a NaN, a NaN is returned.\n + * If x is +0 (-0), +0 (-0) is returned.\n + * If x is positive infinity (negative infinity), positive infinity (negative infinity) is returned.\n + * If the result overflows, a range error occurs, and the functions return +HUGE_VAL, + * +HUGE_VALF, or +HUGE_VALL, respectively.\n + * + * @par Dependency: + *
      • math.h
      + * + * @see acosh | asinh | atanh | cosh | tanh + * + */ +double sinh(double); + +/** + * @ingroup math + * @par Description: + * This function returns the hyperbolic sine of x, which is defined mathematically as: + * sinh(x) = (exp(x) - exp(-x)) / 2 + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval + * #float On success, this function return the hyperbolic sine of x.\n + * If x is a NaN, a NaN is returned.\n + * If x is +0 (-0), +0 (-0) is returned.\n + * If x is positive infinity (negative infinity), positive infinity (negative infinity) is returned.\n + * If the result overflows, a range error occurs, and the functions return +HUGE_VAL, + * +HUGE_VALF, or +HUGE_VALL, respectively.\n + * + * @par Dependency: + *
      • math.h
      + * + * @see acosh | asinh | atanh | cosh | tanh + * + */ +float sinhf(float); + +/** + * @ingroup math + * @par Description: + * This function returns the hyperbolic sine of x. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval "long double" On success, this function return the hyperbolic sine of x.\n + * If x is a NaN, a NaN is returned.\n + * If x is +0 (-0), +0 (-0) is returned.\n + * If x is positive infinity (negative infinity), positive infinity (negative infinity) is returned.\n + * If the result overflows, a range error occurs, and the functions return +HUGE_VAL, +HUGE_VALF, or +HUGE_VALL, respectively.\n + * + * @par Dependency: + *
      • math.h
      + * + * @see acosh | asinh | atanh | cosh | tanh + * + */ +long double sinhl(long double); + +/** + * @ingroup math + * @par Description: + * The sqrt() function returns the nonnegative square root of x. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval + * #double On success, this function returns the square root of x.\n + * If x is a NaN, a NaN is returned.\n + * If x is +0 (-0), +0 (-0) is returned.\n + * If x is positive infinity, positive infinity is returned.\n + * If x is less than -0, a domain error occurs, and a NaN is returned.\n + * + * @par Dependency: + *
      • math.h
      + * + * @see cbrt | hypot + * + */ +double sqrt(double); + +/** + * @ingroup math + * @par Description: + * This function returns the nonnegative square root of x. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval + * #float On success, this function returns the square root of x.\n + * If x is a NaN, a NaN is returned.\n + * If x is +0 (-0), +0 (-0) is returned.\n + * If x is positive infinity, positive infinity is returned.\n + * If x is less than -0, a domain error occurs, and a NaN is returned.\n + * + * @par Dependency: + *
      • math.h
      + * + * @see cbrt | hypot + * + */ +float sqrtf(float); + +/** + * @ingroup math + * @par Description: + * The sqrtl() function returns the nonnegative square root of x. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval "long double" On success, this function returns the square root of x.\n + * If x is a NaN, a NaN is returned.\n + * If x is +0 (-0), +0 (-0) is returned.\n + * If x is positive infinity, positive infinity is returned.\n + * If x is less than -0, a domain error occurs, and a NaN is returned.\n + * + * @par Dependency: + *
      • math.h
      + * + * @see cbrt | hypot + * + */ +long double sqrtl(long double); + +/** + * @ingroup math + * @par Description: + * This function returns the tangent of x, where x is given in radians. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval + * #double On success, this function returns the tangent of x.\n + * If x is a NaN, a NaN is returned.\n + * If x is positive infinity or negative infinity, a domain error occurs, and a NaN is returned.\n + * If the correct result would overflow, a range error occurs, and the functions + * return HUGE_VAL, HUGE_VALF, or HUGE_VALL, respectively, with the + * mathematically correct sign.\n + * + * @par Dependency: + *
      • math.h
      + * + * @see acos | asin | atan | atan2 | cos | sin + * + */ +double tan(double); + +/** + * @ingroup math + * @par Description: + * This function returns the tangent of x, where x is given in radians. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval + * #float On success, this function returns the tangent of x.\n + * If x is a NaN, a NaN is returned.\n + * If x is positive infinity or negative infinity, a domain error occurs, and a NaN is returned.\n + * If the correct result would overflow, a range error occurs, and the functions return + * HUGE_VAL, HUGE_VALF, or HUGE_VALL, respectively, with the + * mathematically correct sign.\n + * + * @par Dependency: + *
      • math.h
      + * + * @see acos | asin | atan | atan2 | cos | sin + * + */ +float tanf(float); + +/** + * @ingroup math + * @par Description: + * This function returns the tangent of x, where x is given in radians. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval "long double" On success, this function returns the tangent of x.\n + * If x is a NaN, a NaN is returned.\n + * If x is positive infinity or negative infinity, a domain error occurs, and a NaN is returned.\n + * If the correct result would overflow, a range error occurs, and the functions return HUGE_VAL, HUGE_VALF, or HUGE_VALL, respectively, with the + * mathematically correct sign.\n + * + * @par Dependency: + *
      • math.h
      + * + * @see acos | asin | atan | atan2 | cos | sin + * + */ +long double tanl(long double); + +/** + * @ingroup math + * @par Description: + * This function returns the hyperbolic tangent of x, which is defined mathematically as: + * tanh(x) = sinh(x) / cosh(x) + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval + * #double On success, this function returns the hyperbolic tangent of x.\n + * If x is a NaN, a NaN is returned.\n + * If x is +0 (-0), +0 (-0) is returned.\n + * If x is positive infinity (negative infinity), +1 (-1) is returned.\n + * + * @par Dependency: + *
      • math.h
      + * + * @see acosh | asinh | atanh | cosh | sinh + * + */ +double tanh(double); + +/** + * @ingroup math + * @par Description: + * This function returns the hyperbolic tangent of x, which is defined mathematically as: + * tanh(x) = sinh(x) / cosh(x) + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval + * #float On success, this function returns the hyperbolic tangent of x.\n + * If x is a NaN, a NaN is returned.\n + * If x is +0 (-0), +0 (-0) is returned.\n + * If x is positive infinity (negative infinity), +1 (-1) is returned.\n + * + * @par Dependency: + *
      • math.h
      + * + * @see acosh | asinh | atanh | cosh | sinh + * + */ +float tanhf(float); + +/** + * @ingroup math + * @par Description: + * This function returns the hyperbolic tangent of x, which is defined mathematically as: + * tanh(x) = sinh(x) / cosh(x) + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval "long double" On success, this function returns the hyperbolic tangent of x.\n + * If x is a NaN, a NaN is returned.\n + * If x is +0 (-0), +0 (-0) is returned.\n + * If x is positive infinity (negative infinity), +1 (-1) is returned.\n + * + * @par Dependency: + *
      • math.h
      + * + * @see acosh | asinh | atanh | cosh | sinh + * + */ +long double tanhl(long double); + +double tgamma(double); +float tgammaf(float); +long double tgammal(long double); + +/** + * @ingroup math + * @par Description: + * The function rounds x to the nearest integer not larger in absolute value. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval + * #double This function returns the rounded integer value.\n + * If x is integral, infinite, or NaN, x itself is returned.\n + * + * @par Dependency: + *
      • math.h
      + * + * @see ceil | floor | lrint | nearbyint | rint | round + * + */ +double trunc(double); + +/** + * @ingroup math + * @par Description: + * The truncf() function round x to the nearest integer not larger in absolute value. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval + * #float The function returns the rounded integer value. If x is integral, infinite, or NaN, x itself is returned. + * + * @par Dependency: + *
      • math.h
      + * + * @see ceil | floor | lrint | nearbyint | rint | round + * + */ +float truncf(float); + +/** + * @ingroup math + * @par Description: + * The function rounds x to the nearest integer not larger in absolute value. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval "long double" This function returns the rounded integer value.\n + * If x is integral, infinite, or NaN, x itself is returned.\n + * + * @par Dependency: + *
      • math.h
      + * + * @see ceil | floor | lrint | nearbyint | rint | round + * + */ +long double truncl(long double); + + +#if defined(_XOPEN_SOURCE) || defined(_BSD_SOURCE) +#undef MAXFLOAT +#define MAXFLOAT 3.40282346638528859812e+38F +#endif + +#if defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) || defined(_BSD_SOURCE) +#define M_E 2.7182818284590452354 /* e */ +#define M_LOG2E 1.4426950408889634074 /* log_2 e */ +#define M_LOG10E 0.43429448190325182765 /* log_10 e */ +#define M_LN2 0.69314718055994530942 /* log_e 2 */ +#define M_LN10 2.30258509299404568402 /* log_e 10 */ +#define M_PI 3.14159265358979323846 /* pi */ +#define M_PI_2 1.57079632679489661923 /* pi/2 */ +#define M_PI_4 0.78539816339744830962 /* pi/4 */ +#define M_1_PI 0.31830988618379067154 /* 1/pi */ +#define M_2_PI 0.63661977236758134308 /* 2/pi */ +#define M_2_SQRTPI 1.12837916709551257390 /* 2/sqrt(pi) */ +#define M_SQRT2 1.41421356237309504880 /* sqrt(2) */ +#define M_SQRT1_2 0.70710678118654752440 /* 1/sqrt(2) */ + +extern int signgam; + +double j0(double); +double j1(double); +double jn(int, double); + +double y0(double); +double y1(double); +double yn(int, double); +#endif + +#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE) +#define HUGE 3.40282346638528859812e+38F + +double drem(double, double); +float dremf(float, float); + +int finite(double); +int finitef(float); + +double scalb(double, double); +float scalbf(float, float); + +double significand(double); +float significandf(float); + +double lgamma_r(double, int*); +float lgammaf_r(float, int*); + +float j0f(float); +float j1f(float); +float jnf(int, float); + +float y0f(float); +float y1f(float); +float ynf(int, float); +#endif + +#ifdef _GNU_SOURCE +long double lgammal_r(long double, int*); + +void sincos(double, double*, double*); +void sincosf(float, float*, float*); +void sincosl(long double, long double*, long double*); + +double exp10(double); +float exp10f(float); +long double exp10l(long double); + +double pow10(double); +float pow10f(float); +long double pow10l(long double); +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/memory.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/memory.h new file mode 100644 index 0000000000000000000000000000000000000000..3b2f5900276f0ef72b52e5a9c5c5f3d8a3176612 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/memory.h @@ -0,0 +1 @@ +#include diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/mntent.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/mntent.h new file mode 100644 index 0000000000000000000000000000000000000000..3492a1d6daa25ad9f061ab67f5b5938603ea7c40 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/mntent.h @@ -0,0 +1,43 @@ +#ifndef _MNTENT_H +#define _MNTENT_H + +#ifdef __cplusplus +extern "C" { +#endif + +#define __NEED_FILE +#include + +#define MOUNTED "/etc/mtab" + +#define MNTTYPE_IGNORE "ignore" +#define MNTTYPE_NFS "nfs" +#define MNTTYPE_SWAP "swap" +#define MNTOPT_DEFAULTS "defaults" +#define MNTOPT_RO "ro" +#define MNTOPT_RW "rw" +#define MNTOPT_SUID "suid" +#define MNTOPT_NOSUID "nosuid" +#define MNTOPT_NOAUTO "noauto" + +struct mntent { + char *mnt_fsname; + char *mnt_dir; + char *mnt_type; + char *mnt_opts; + int mnt_freq; + int mnt_passno; +}; + +FILE *setmntent(const char *, const char *); +int endmntent(FILE *); +struct mntent *getmntent(FILE *); +struct mntent *getmntent_r(FILE *, struct mntent *, char *, int); +int addmntent(FILE *, const struct mntent *); +char *hasmntopt(const struct mntent *, const char *); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/monetary.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/monetary.h new file mode 100644 index 0000000000000000000000000000000000000000..a91fa565574758726977376659b9890a2380087d --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/monetary.h @@ -0,0 +1,23 @@ +#ifndef _MONETARY_H +#define _MONETARY_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#define __NEED_ssize_t +#define __NEED_size_t +#define __NEED_locale_t + +#include + +ssize_t strfmon(char *__restrict, size_t, const char *__restrict, ...); +ssize_t strfmon_l(char *__restrict, size_t, locale_t, const char *__restrict, ...); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/mqueue.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/mqueue.h new file mode 100644 index 0000000000000000000000000000000000000000..0c807ea0cbb26e6a5d46df5cdb0be6bb8c84ba42 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/mqueue.h @@ -0,0 +1,41 @@ +#ifndef _MQUEUE_H +#define _MQUEUE_H +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#define __NEED_size_t +#define __NEED_ssize_t +#define __NEED_pthread_attr_t +#define __NEED_time_t +#define __NEED_struct_timespec +#include + +typedef int mqd_t; +struct mq_attr { + long mq_flags, mq_maxmsg, mq_msgsize, mq_curmsgs, __unused[4]; +}; +struct sigevent; + +int mq_close(mqd_t); +int mq_getattr(mqd_t, struct mq_attr *); +int mq_notify(mqd_t, const struct sigevent *); +mqd_t mq_open(const char *, int, ...); +ssize_t mq_receive(mqd_t, char *, size_t, unsigned *); +int mq_send(mqd_t, const char *, size_t, unsigned); +int mq_setattr(mqd_t, const struct mq_attr *__restrict, struct mq_attr *__restrict); +ssize_t mq_timedreceive(mqd_t, char *__restrict, size_t, unsigned *__restrict, const struct timespec *__restrict); +int mq_timedsend(mqd_t, const char *, size_t, unsigned, const struct timespec *); +int mq_unlink(const char *); + +#if _REDIR_TIME64 +__REDIR(mq_timedreceive, __mq_timedreceive_time64); +__REDIR(mq_timedsend, __mq_timedsend_time64); +#endif + +#ifdef __cplusplus +} +#endif +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/net/ethernet.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/net/ethernet.h new file mode 100644 index 0000000000000000000000000000000000000000..d4984803dc2ac801e4aa1d9328ed246d6785b9c9 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/net/ethernet.h @@ -0,0 +1,58 @@ +#ifndef _NET_ETHERNET_H +#define _NET_ETHERNET_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include + +struct ether_addr { + uint8_t ether_addr_octet[ETH_ALEN]; +}; + +struct ether_header { + uint8_t ether_dhost[ETH_ALEN]; + uint8_t ether_shost[ETH_ALEN]; + uint16_t ether_type; +}; + +#define ETHERTYPE_PUP 0x0200 +#define ETHERTYPE_SPRITE 0x0500 +#define ETHERTYPE_IP 0x0800 +#define ETHERTYPE_ARP 0x0806 +#define ETHERTYPE_REVARP 0x8035 +#define ETHERTYPE_AT 0x809B +#define ETHERTYPE_AARP 0x80F3 +#define ETHERTYPE_VLAN 0x8100 +#define ETHERTYPE_IPX 0x8137 +#define ETHERTYPE_IPV6 0x86dd +#define ETHERTYPE_LOOPBACK 0x9000 + +#ifdef __LITEOS__ +#ifndef ETHER_ADDR_LEN +#define ETHER_ADDR_LEN ETH_ALEN +#endif +#endif +#define ETHER_TYPE_LEN 2 +#define ETHER_CRC_LEN 4 +#define ETHER_HDR_LEN ETH_HLEN +#define ETHER_MIN_LEN (ETH_ZLEN + ETHER_CRC_LEN) +#define ETHER_MAX_LEN (ETH_FRAME_LEN + ETHER_CRC_LEN) + +#define ETHER_IS_VALID_LEN(foo) \ + ((foo) >= ETHER_MIN_LEN && (foo) <= ETHER_MAX_LEN) + +#define ETHERTYPE_TRAIL 0x1000 +#define ETHERTYPE_NTRAILER 16 + +#define ETHERMTU ETH_DATA_LEN +#define ETHERMIN (ETHER_MIN_LEN - ETHER_HDR_LEN - ETHER_CRC_LEN) + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/net/if.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/net/if.h new file mode 100644 index 0000000000000000000000000000000000000000..7c16ff94dd5f1158394a5cdf4f40d669c97c1689 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/net/if.h @@ -0,0 +1,268 @@ + +/** + * @defgroup if If + * @ingroup libc + */ + +#ifndef _NET_IF_H +#define _NET_IF_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#define IF_NAMESIZE 16 + +struct if_nameindex { + unsigned int if_index; + char *if_name; +}; + +/** + * @ingroup if + * + * @par Description: + * This function is used to convert the index of the network interface corresponding to the name ifname. + * + * @param ifname [IN] The name of the network interface. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #>0 On success, the index number of the network interface was successfully converted + * @retval #0 On failure, 0 is returned and errno is set appropriately + * + * @par Errors + *
        + *
      • ENXIO: Could not find the index corresponding to the interface name.
      • + *
      + * + * @par Dependency: + *
      • if.h
      + * + * @see if_indextoname + * + */ +unsigned int if_nametoindex (const char *); + +/** + * @ingroup if + * + * @par Description: + * This function is used to convert the name of the network interface corresponding + * to the interface index ifindex. The name is placed in the buffer pointed to by ifname. + * The buffer must allow for the storage of at least IF_NAMESIZE bytes. + * + * @param #ifindex [IN] The index of the network interface. + * @param #ifname [OUT] The name of the network interface. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval ifname On success, the ifname was successfully converted + * @retval NULL On failure, NULL is returned and errno is set appropriately + * + * @par Errors + *
        + *
      • ENXIO: There is no name as per the index specified.
      • + *
      • EINVAL: The ifname is a null pointer.
      • + *
      + * + * @par Dependency: + *
      • if.h
      + * + * @see if_nametoindex + * + */ +char *if_indextoname (unsigned int, char *); + +/** + * @ingroup if + * + * @par Description: + * This function returns an array of if_nameindex structures, one structure per interface. + * The if_nameindex structure holds the information about a single interface and is defined as a result of including the header. + * The end of the array of structures is indicated by a structure with an if_index of 0 and an if_name of NULL. + * The function returns a NULL pointer upon an error, and would set errno to the appropriate value. + * The memory used for this array of structures along with the interface names pointed to by the if_name members is obtained dynamically. + * + * @param void [IN] The function does not take any input instead returns all the interfaces in format if_nameindex structures. + * + * @attention + *
        + *
      • This API is only supported since lwip 2.0.
      • + *
      • The end of the array of structures is indicated by a structure with an if_index of 0 and an if_name of NULL. + * The function returns a NULL pointer upon an error, and would set errno to the appropriate value.
      • + *
      + * + * @retval #if_nameindex* On success, the function returns an array of if_nameindex structures, one structure per interface. On failure, NULL shall be returned. + * + * @par Errors + *
        + *
      • ENOBUFS: Insufficient resources available.
      • + *
      + * + * @par Dependency: + *
      • if.h
      + * + * @see if_freenameindex + * + */ +struct if_nameindex *if_nameindex (void); + +/** + * @ingroup if + * + * @par Description: + * This function frees the dynamic memory that was allocated by if_nameindex(). + * The argument to this function must be a pointer that was returned by if_nameindex(). + * + * @param ptr [IN] The argument to this function must be a pointer that was returned by if_nameindex(). + * + * @attention + *
        + *
      • This API is only supported since lwip 2.0.
      • + *
      + * + * @retval #void None. + * + * @par Dependency: + *
      • if.h
      + * + * @see if_nameindex + * + */ +void if_freenameindex (struct if_nameindex *); + + + + +#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE) + +#include + +#define IFF_UP 0x1 +#define IFF_BROADCAST 0x2 +#define IFF_DEBUG 0x4 +#define IFF_LOOPBACK 0x8 +#define IFF_POINTOPOINT 0x10 +#define IFF_NOTRAILERS 0x20 +#define IFF_RUNNING 0x40 +#define IFF_NOARP 0x80 +#define IFF_PROMISC 0x100 +#define IFF_ALLMULTI 0x200 +#define IFF_MASTER 0x400 +#define IFF_SLAVE 0x800 +#define IFF_MULTICAST 0x1000 +#define IFF_PORTSEL 0x2000 +#define IFF_AUTOMEDIA 0x4000 +#define IFF_DYNAMIC 0x8000 +#define IFF_LOWER_UP 0x10000 +#define IFF_DORMANT 0x20000 +#define IFF_ECHO 0x40000 +#define IFF_VOLATILE (IFF_LOOPBACK|IFF_POINTOPOINT|IFF_BROADCAST| \ + IFF_ECHO|IFF_MASTER|IFF_SLAVE|IFF_RUNNING|IFF_LOWER_UP|IFF_DORMANT) + +struct ifaddr { + struct sockaddr ifa_addr; + union { + struct sockaddr ifu_broadaddr; + struct sockaddr ifu_dstaddr; + } ifa_ifu; + struct iface *ifa_ifp; + struct ifaddr *ifa_next; +}; + +#define ifa_broadaddr ifa_ifu.ifu_broadaddr +#define ifa_dstaddr ifa_ifu.ifu_dstaddr + +struct ifmap { + unsigned long int mem_start; + unsigned long int mem_end; + unsigned short int base_addr; + unsigned char irq; + unsigned char dma; + unsigned char port; +}; + +#define IFHWADDRLEN 6 +#ifdef __LITEOS__ +#ifndef IFNAMSIZ +#define IFNAMSIZ IF_NAMESIZE +#endif +#endif + +struct ifreq { + union { + char ifrn_name[IFNAMSIZ]; + } ifr_ifrn; + union { + struct sockaddr ifru_addr; + struct sockaddr ifru_dstaddr; + struct sockaddr ifru_broadaddr; + struct sockaddr ifru_netmask; + struct sockaddr ifru_hwaddr; + short int ifru_flags; + int ifru_ivalue; + int ifru_mtu; + struct ifmap ifru_map; + char ifru_slave[IFNAMSIZ]; + char ifru_newname[IFNAMSIZ]; + char *ifru_data; + } ifr_ifru; +}; + +#define ifr_name ifr_ifrn.ifrn_name +#define ifr_hwaddr ifr_ifru.ifru_hwaddr +#define ifr_addr ifr_ifru.ifru_addr +#define ifr_dstaddr ifr_ifru.ifru_dstaddr +#define ifr_broadaddr ifr_ifru.ifru_broadaddr +#define ifr_netmask ifr_ifru.ifru_netmask +#define ifr_flags ifr_ifru.ifru_flags +#define ifr_metric ifr_ifru.ifru_ivalue +#define ifr_mtu ifr_ifru.ifru_mtu +#define ifr_map ifr_ifru.ifru_map +#define ifr_slave ifr_ifru.ifru_slave +#ifndef __LITEOS__ +#define ifr_data ifr_ifru.ifru_data +#endif +#define ifr_ifindex ifr_ifru.ifru_ivalue +#define ifr_bandwidth ifr_ifru.ifru_ivalue +#define ifr_qlen ifr_ifru.ifru_ivalue +#define ifr_newname ifr_ifru.ifru_newname +#define _IOT_ifreq _IOT(_IOTS(char),IFNAMSIZ,_IOTS(char),16,0,0) +#define _IOT_ifreq_short _IOT(_IOTS(char),IFNAMSIZ,_IOTS(short),1,0,0) +#define _IOT_ifreq_int _IOT(_IOTS(char),IFNAMSIZ,_IOTS(int),1,0,0) + +struct ifconf { + int ifc_len; + union { + char *ifcu_buf; + struct ifreq *ifcu_req; + } ifc_ifcu; +}; + +#define ifc_buf ifc_ifcu.ifcu_buf +#define ifc_req ifc_ifcu.ifcu_req +#define _IOT_ifconf _IOT(_IOTS(struct ifconf),1,0,0,0,0) + +#define __UAPI_DEF_IF_IFCONF 0 +#define __UAPI_DEF_IF_IFMAP 0 +#define __UAPI_DEF_IF_IFNAMSIZ 0 +#define __UAPI_DEF_IF_IFREQ 0 +#define __UAPI_DEF_IF_NET_DEVICE_FLAGS 0 +#define __UAPI_DEF_IF_NET_DEVICE_FLAGS_LOWER_UP_DORMANT_ECHO 0 + +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/net/if_arp.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/net/if_arp.h new file mode 100644 index 0000000000000000000000000000000000000000..27becc835eeb458830f990fbb29621a8229e694d --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/net/if_arp.h @@ -0,0 +1,142 @@ +/* Nonstandard header */ +#ifndef _NET_IF_ARP_H +#define _NET_IF_ARP_H +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include + +#define MAX_ADDR_LEN 7 + +#define ARPOP_REQUEST 1 +#define ARPOP_REPLY 2 +#define ARPOP_RREQUEST 3 +#define ARPOP_RREPLY 4 +#define ARPOP_InREQUEST 8 +#define ARPOP_InREPLY 9 +#define ARPOP_NAK 10 + +struct arphdr { + uint16_t ar_hrd; + uint16_t ar_pro; + uint8_t ar_hln; + uint8_t ar_pln; + uint16_t ar_op; +}; + + +#define ARPHRD_NETROM 0 +#define ARPHRD_ETHER 1 +#define ARPHRD_EETHER 2 +#define ARPHRD_AX25 3 +#define ARPHRD_PRONET 4 +#define ARPHRD_CHAOS 5 +#define ARPHRD_IEEE802 6 +#define ARPHRD_ARCNET 7 +#define ARPHRD_APPLETLK 8 +#define ARPHRD_DLCI 15 +#define ARPHRD_ATM 19 +#define ARPHRD_METRICOM 23 +#define ARPHRD_IEEE1394 24 +#define ARPHRD_EUI64 27 +#define ARPHRD_INFINIBAND 32 +#define ARPHRD_SLIP 256 +#define ARPHRD_CSLIP 257 +#define ARPHRD_SLIP6 258 +#define ARPHRD_CSLIP6 259 +#define ARPHRD_RSRVD 260 +#define ARPHRD_ADAPT 264 +#define ARPHRD_ROSE 270 +#define ARPHRD_X25 271 +#define ARPHRD_HWX25 272 +#define ARPHRD_CAN 280 +#define ARPHRD_PPP 512 +#define ARPHRD_CISCO 513 +#define ARPHRD_HDLC ARPHRD_CISCO +#define ARPHRD_LAPB 516 +#define ARPHRD_DDCMP 517 +#define ARPHRD_RAWHDLC 518 +#define ARPHRD_RAWIP 519 + +#define ARPHRD_TUNNEL 768 +#define ARPHRD_TUNNEL6 769 +#define ARPHRD_FRAD 770 +#define ARPHRD_SKIP 771 +#define ARPHRD_LOOPBACK 772 +#define ARPHRD_LOCALTLK 773 +#define ARPHRD_FDDI 774 +#define ARPHRD_BIF 775 +#define ARPHRD_SIT 776 +#define ARPHRD_IPDDP 777 +#define ARPHRD_IPGRE 778 +#define ARPHRD_PIMREG 779 +#define ARPHRD_HIPPI 780 +#define ARPHRD_ASH 781 +#define ARPHRD_ECONET 782 +#define ARPHRD_IRDA 783 +#define ARPHRD_FCPP 784 +#define ARPHRD_FCAL 785 +#define ARPHRD_FCPL 786 +#define ARPHRD_FCFABRIC 787 +#define ARPHRD_IEEE802_TR 800 +#define ARPHRD_IEEE80211 801 +#define ARPHRD_IEEE80211_PRISM 802 +#define ARPHRD_IEEE80211_RADIOTAP 803 +#define ARPHRD_IEEE802154 804 +#define ARPHRD_IEEE802154_MONITOR 805 +#define ARPHRD_PHONET 820 +#define ARPHRD_PHONET_PIPE 821 +#define ARPHRD_CAIF 822 +#define ARPHRD_IP6GRE 823 +#define ARPHRD_NETLINK 824 +#define ARPHRD_6LOWPAN 825 +#define ARPHRD_VSOCKMON 826 + +#define ARPHRD_VOID 0xFFFF +#define ARPHRD_NONE 0xFFFE + +struct arpreq { + struct sockaddr arp_pa; + struct sockaddr arp_ha; + int arp_flags; + struct sockaddr arp_netmask; + char arp_dev[16]; +}; + +struct arpreq_old { + struct sockaddr arp_pa; + struct sockaddr arp_ha; + int arp_flags; + struct sockaddr arp_netmask; +}; + +#define ATF_COM 0x02 +#define ATF_PERM 0x04 +#define ATF_PUBL 0x08 +#define ATF_USETRAILERS 0x10 +#define ATF_NETMASK 0x20 +#define ATF_DONTPUB 0x40 +#define ATF_MAGIC 0x80 + +#define ARPD_UPDATE 0x01 +#define ARPD_LOOKUP 0x02 +#define ARPD_FLUSH 0x03 + +struct arpd_request { + unsigned short req; + uint32_t ip; + unsigned long dev; + unsigned long stamp; + unsigned long updated; + unsigned char ha[MAX_ADDR_LEN]; +}; + + + +#ifdef __cplusplus +} +#endif +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/net/route.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/net/route.h new file mode 100644 index 0000000000000000000000000000000000000000..96ff48e014ce6ee08270b0497ed2d662c09e01e7 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/net/route.h @@ -0,0 +1,124 @@ +#ifndef _NET_ROUTE_H +#define _NET_ROUTE_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include +#include + + +struct rtentry { + unsigned long int rt_pad1; + struct sockaddr rt_dst; + struct sockaddr rt_gateway; + struct sockaddr rt_genmask; + unsigned short int rt_flags; + short int rt_pad2; + unsigned long int rt_pad3; + unsigned char rt_tos; + unsigned char rt_class; + short int rt_pad4[sizeof(long)/2-1]; + short int rt_metric; + char *rt_dev; + unsigned long int rt_mtu; + unsigned long int rt_window; + unsigned short int rt_irtt; +}; + +#define rt_mss rt_mtu + + +struct in6_rtmsg { + struct in6_addr rtmsg_dst; + struct in6_addr rtmsg_src; + struct in6_addr rtmsg_gateway; + uint32_t rtmsg_type; + uint16_t rtmsg_dst_len; + uint16_t rtmsg_src_len; + uint32_t rtmsg_metric; + unsigned long int rtmsg_info; + uint32_t rtmsg_flags; + int rtmsg_ifindex; +}; + + +#define RTF_UP 0x0001 +#define RTF_GATEWAY 0x0002 + +#define RTF_HOST 0x0004 +#define RTF_REINSTATE 0x0008 +#define RTF_DYNAMIC 0x0010 +#define RTF_MODIFIED 0x0020 +#define RTF_MTU 0x0040 +#define RTF_MSS RTF_MTU +#define RTF_WINDOW 0x0080 +#define RTF_IRTT 0x0100 +#define RTF_REJECT 0x0200 +#define RTF_STATIC 0x0400 +#define RTF_XRESOLVE 0x0800 +#define RTF_NOFORWARD 0x1000 +#define RTF_THROW 0x2000 +#define RTF_NOPMTUDISC 0x4000 + +#define RTF_DEFAULT 0x00010000 +#define RTF_ALLONLINK 0x00020000 +#define RTF_ADDRCONF 0x00040000 + +#define RTF_LINKRT 0x00100000 +#define RTF_NONEXTHOP 0x00200000 + +#define RTF_CACHE 0x01000000 +#define RTF_FLOW 0x02000000 +#define RTF_POLICY 0x04000000 + +#define RTCF_VALVE 0x00200000 +#define RTCF_MASQ 0x00400000 +#define RTCF_NAT 0x00800000 +#define RTCF_DOREDIRECT 0x01000000 +#define RTCF_LOG 0x02000000 +#define RTCF_DIRECTSRC 0x04000000 + +#define RTF_LOCAL 0x80000000 +#define RTF_INTERFACE 0x40000000 +#define RTF_MULTICAST 0x20000000 +#define RTF_BROADCAST 0x10000000 +#define RTF_NAT 0x08000000 + +#define RTF_ADDRCLASSMASK 0xF8000000 +#define RT_ADDRCLASS(flags) ((uint32_t) flags >> 23) + +#define RT_TOS(tos) ((tos) & IPTOS_TOS_MASK) + +#define RT_LOCALADDR(flags) ((flags & RTF_ADDRCLASSMASK) \ + == (RTF_LOCAL|RTF_INTERFACE)) + +#define RT_CLASS_UNSPEC 0 +#define RT_CLASS_DEFAULT 253 + +#define RT_CLASS_MAIN 254 +#define RT_CLASS_LOCAL 255 +#define RT_CLASS_MAX 255 + + +#define RTMSG_ACK NLMSG_ACK +#define RTMSG_OVERRUN NLMSG_OVERRUN + +#define RTMSG_NEWDEVICE 0x11 +#define RTMSG_DELDEVICE 0x12 +#define RTMSG_NEWROUTE 0x21 +#define RTMSG_DELROUTE 0x22 +#define RTMSG_NEWRULE 0x31 +#define RTMSG_DELRULE 0x32 +#define RTMSG_CONTROL 0x40 + +#define RTMSG_AR_FAILED 0x51 + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/netdb.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/netdb.h new file mode 100755 index 0000000000000000000000000000000000000000..d096c78183b5609c4e5932adbd8d6ed8e75f168e --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/netdb.h @@ -0,0 +1,156 @@ +#ifndef _NETDB_H +#define _NETDB_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include + +#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE) +#define __NEED_size_t +#include +#endif + +struct addrinfo { + int ai_flags; + int ai_family; + int ai_socktype; + int ai_protocol; + socklen_t ai_addrlen; + struct sockaddr *ai_addr; + char *ai_canonname; + struct addrinfo *ai_next; +}; + +#define AI_PASSIVE 0x01 +#define AI_CANONNAME 0x02 +#define AI_NUMERICHOST 0x04 +#define AI_V4MAPPED 0x08 +#define AI_ALL 0x10 +#define AI_ADDRCONFIG 0x20 +#define AI_NUMERICSERV 0x400 + + +#define NI_NUMERICHOST 0x01 +#define NI_NUMERICSERV 0x02 +#define NI_NOFQDN 0x04 +#define NI_NAMEREQD 0x08 +#define NI_DGRAM 0x10 +#define NI_NUMERICSCOPE 0x100 + +#define EAI_BADFLAGS -1 +#define EAI_NONAME -2 +#define EAI_AGAIN -3 +#define EAI_FAIL -4 +#define EAI_FAMILY -6 +#define EAI_SOCKTYPE -7 +#define EAI_SERVICE -8 +#define EAI_MEMORY -10 +#define EAI_SYSTEM -11 +#define EAI_OVERFLOW -12 + +int getaddrinfo (const char *__restrict, const char *__restrict, const struct addrinfo *__restrict, struct addrinfo **__restrict); +void freeaddrinfo (struct addrinfo *); +int getnameinfo (const struct sockaddr *__restrict, socklen_t, char *__restrict, socklen_t, char *__restrict, socklen_t, int); +const char *gai_strerror(int); + + +/* Legacy functions follow (marked OBsolete in SUS) */ + +struct netent { + char *n_name; + char **n_aliases; + int n_addrtype; + uint32_t n_net; +}; + +struct hostent { + char *h_name; + char **h_aliases; + int h_addrtype; + int h_length; + char **h_addr_list; +}; +#define h_addr h_addr_list[0] + +struct servent { + char *s_name; + char **s_aliases; + int s_port; + char *s_proto; +}; + +struct protoent { + char *p_name; + char **p_aliases; + int p_proto; +}; + +void sethostent (int); +void endhostent (void); +struct hostent *gethostent (void); + +void setnetent (int); +void endnetent (void); +struct netent *getnetent (void); +struct netent *getnetbyaddr (uint32_t, int); +struct netent *getnetbyname (const char *); + +void setservent (int); +void endservent (void); +struct servent *getservent (void); +struct servent *getservbyname (const char *, const char *); +struct servent *getservbyport (int, const char *); + +void setprotoent (int); +void endprotoent (void); +struct protoent *getprotoent (void); +struct protoent *getprotobyname (const char *); +struct protoent *getprotobynumber (int); + +#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE) || defined(_POSIX_SOURCE) \ + || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE+0 < 200809L) \ + || (defined(_XOPEN_SOURCE) && _XOPEN_SOURCE+0 < 700) +struct hostent *gethostbyname (const char *); +struct hostent *gethostbyaddr (const void *, socklen_t, int); +#ifdef __GNUC__ +__attribute__((const)) +#endif +int *__h_errno_location(void); +#define h_errno (*__h_errno_location()) +#define HOST_NOT_FOUND 1 +#define TRY_AGAIN 2 +#define NO_RECOVERY 3 +#define NO_DATA 4 +#define NO_ADDRESS NO_DATA +#endif + +#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE) +void herror(const char *); +const char *hstrerror(int); +int gethostbyname_r(const char *, struct hostent *, char *, size_t, struct hostent **, int *); +int gethostbyname2_r(const char *, int, struct hostent *, char *, size_t, struct hostent **, int *); +struct hostent *gethostbyname2(const char *, int); +int gethostbyaddr_r(const void *, socklen_t, int, struct hostent *, char *, size_t, struct hostent **, int *); +int getservbyport_r(int, const char *, struct servent *, char *, size_t, struct servent **); +int getservbyname_r(const char *, const char *, struct servent *, char *, size_t, struct servent **); +#define EAI_NODATA -5 +#define EAI_ADDRFAMILY -9 +#define EAI_INPROGRESS -100 +#define EAI_CANCELED -101 +#define EAI_NOTCANCELED -102 +#define EAI_ALLDONE -103 +#define EAI_INTR -104 +#define EAI_IDN_ENCODE -105 +#define NI_MAXHOST 255 +#define NI_MAXSERV 32 +#endif + + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/netinet/ether.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/netinet/ether.h new file mode 100644 index 0000000000000000000000000000000000000000..eec7e53ca497a4ec1041e7c29a8b5a41a801b182 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/netinet/ether.h @@ -0,0 +1,22 @@ +#ifndef _NETINET_ETHER_H +#define _NETINET_ETHER_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +char *ether_ntoa (const struct ether_addr *); +struct ether_addr *ether_aton (const char *); +char *ether_ntoa_r (const struct ether_addr *, char *); +struct ether_addr *ether_aton_r (const char *, struct ether_addr *); +int ether_line(const char *, struct ether_addr *, char *); +int ether_ntohost(char *, const struct ether_addr *); +int ether_hostton(const char *, struct ether_addr *); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/netinet/icmp6.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/netinet/icmp6.h new file mode 100644 index 0000000000000000000000000000000000000000..01269e7d4adc44e3f301fe48310066dba5fca478 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/netinet/icmp6.h @@ -0,0 +1,305 @@ +#ifndef _NETINET_ICMP6_H +#define _NETINET_ICMP6_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include +#include + +#define ICMP6_FILTER 1 + +#define ICMP6_FILTER_BLOCK 1 +#define ICMP6_FILTER_PASS 2 +#define ICMP6_FILTER_BLOCKOTHERS 3 +#define ICMP6_FILTER_PASSONLY 4 + +struct icmp6_filter { + uint32_t icmp6_filt[8]; +}; + +struct icmp6_hdr { + uint8_t icmp6_type; + uint8_t icmp6_code; + uint16_t icmp6_cksum; + union { + uint32_t icmp6_un_data32[1]; + uint16_t icmp6_un_data16[2]; + uint8_t icmp6_un_data8[4]; + } icmp6_dataun; +}; + +#define icmp6_data32 icmp6_dataun.icmp6_un_data32 +#define icmp6_data16 icmp6_dataun.icmp6_un_data16 +#define icmp6_data8 icmp6_dataun.icmp6_un_data8 +#define icmp6_pptr icmp6_data32[0] +#define icmp6_mtu icmp6_data32[0] +#define icmp6_id icmp6_data16[0] +#define icmp6_seq icmp6_data16[1] +#define icmp6_maxdelay icmp6_data16[0] + +#define ICMP6_DST_UNREACH 1 +#define ICMP6_PACKET_TOO_BIG 2 +#define ICMP6_TIME_EXCEEDED 3 +#define ICMP6_PARAM_PROB 4 + +#define ICMP6_INFOMSG_MASK 0x80 + +#define ICMP6_ECHO_REQUEST 128 +#define ICMP6_ECHO_REPLY 129 +#define MLD_LISTENER_QUERY 130 +#define MLD_LISTENER_REPORT 131 +#define MLD_LISTENER_REDUCTION 132 + +#define ICMP6_DST_UNREACH_NOROUTE 0 +#define ICMP6_DST_UNREACH_ADMIN 1 +#define ICMP6_DST_UNREACH_BEYONDSCOPE 2 +#define ICMP6_DST_UNREACH_ADDR 3 +#define ICMP6_DST_UNREACH_NOPORT 4 + +#define ICMP6_TIME_EXCEED_TRANSIT 0 +#define ICMP6_TIME_EXCEED_REASSEMBLY 1 + +#define ICMP6_PARAMPROB_HEADER 0 +#define ICMP6_PARAMPROB_NEXTHEADER 1 +#define ICMP6_PARAMPROB_OPTION 2 + +#define ICMP6_FILTER_WILLPASS(type, filterp) \ + ((((filterp)->icmp6_filt[(type) >> 5]) & (1 << ((type) & 31))) == 0) + +#define ICMP6_FILTER_WILLBLOCK(type, filterp) \ + ((((filterp)->icmp6_filt[(type) >> 5]) & (1 << ((type) & 31))) != 0) + +#define ICMP6_FILTER_SETPASS(type, filterp) \ + ((((filterp)->icmp6_filt[(type) >> 5]) &= ~(1 << ((type) & 31)))) + +#define ICMP6_FILTER_SETBLOCK(type, filterp) \ + ((((filterp)->icmp6_filt[(type) >> 5]) |= (1 << ((type) & 31)))) + +#define ICMP6_FILTER_SETPASSALL(filterp) \ + memset (filterp, 0, sizeof (struct icmp6_filter)); + +#define ICMP6_FILTER_SETBLOCKALL(filterp) \ + memset (filterp, 0xFF, sizeof (struct icmp6_filter)); + +#define ND_ROUTER_SOLICIT 133 +#define ND_ROUTER_ADVERT 134 +#define ND_NEIGHBOR_SOLICIT 135 +#define ND_NEIGHBOR_ADVERT 136 +#define ND_REDIRECT 137 + +struct nd_router_solicit { + struct icmp6_hdr nd_rs_hdr; +}; + +#define nd_rs_type nd_rs_hdr.icmp6_type +#define nd_rs_code nd_rs_hdr.icmp6_code +#define nd_rs_cksum nd_rs_hdr.icmp6_cksum +#define nd_rs_reserved nd_rs_hdr.icmp6_data32[0] + +struct nd_router_advert { + struct icmp6_hdr nd_ra_hdr; + uint32_t nd_ra_reachable; + uint32_t nd_ra_retransmit; +}; + +#define nd_ra_type nd_ra_hdr.icmp6_type +#define nd_ra_code nd_ra_hdr.icmp6_code +#define nd_ra_cksum nd_ra_hdr.icmp6_cksum +#define nd_ra_curhoplimit nd_ra_hdr.icmp6_data8[0] +#define nd_ra_flags_reserved nd_ra_hdr.icmp6_data8[1] +#define ND_RA_FLAG_MANAGED 0x80 +#define ND_RA_FLAG_OTHER 0x40 +#define ND_RA_FLAG_HOME_AGENT 0x20 +#define nd_ra_router_lifetime nd_ra_hdr.icmp6_data16[1] + +struct nd_neighbor_solicit { + struct icmp6_hdr nd_ns_hdr; + struct in6_addr nd_ns_target; +}; + +#define nd_ns_type nd_ns_hdr.icmp6_type +#define nd_ns_code nd_ns_hdr.icmp6_code +#define nd_ns_cksum nd_ns_hdr.icmp6_cksum +#define nd_ns_reserved nd_ns_hdr.icmp6_data32[0] + +struct nd_neighbor_advert { + struct icmp6_hdr nd_na_hdr; + struct in6_addr nd_na_target; +}; + +#define nd_na_type nd_na_hdr.icmp6_type +#define nd_na_code nd_na_hdr.icmp6_code +#define nd_na_cksum nd_na_hdr.icmp6_cksum +#define nd_na_flags_reserved nd_na_hdr.icmp6_data32[0] +#if __BYTE_ORDER == __BIG_ENDIAN +#define ND_NA_FLAG_ROUTER 0x80000000 +#define ND_NA_FLAG_SOLICITED 0x40000000 +#define ND_NA_FLAG_OVERRIDE 0x20000000 +#else +#define ND_NA_FLAG_ROUTER 0x00000080 +#define ND_NA_FLAG_SOLICITED 0x00000040 +#define ND_NA_FLAG_OVERRIDE 0x00000020 +#endif + +struct nd_redirect { + struct icmp6_hdr nd_rd_hdr; + struct in6_addr nd_rd_target; + struct in6_addr nd_rd_dst; +}; + +#define nd_rd_type nd_rd_hdr.icmp6_type +#define nd_rd_code nd_rd_hdr.icmp6_code +#define nd_rd_cksum nd_rd_hdr.icmp6_cksum +#define nd_rd_reserved nd_rd_hdr.icmp6_data32[0] + +struct nd_opt_hdr { + uint8_t nd_opt_type; + uint8_t nd_opt_len; +}; + +#define ND_OPT_SOURCE_LINKADDR 1 +#define ND_OPT_TARGET_LINKADDR 2 +#define ND_OPT_PREFIX_INFORMATION 3 +#define ND_OPT_REDIRECTED_HEADER 4 +#define ND_OPT_MTU 5 +#define ND_OPT_RTR_ADV_INTERVAL 7 +#define ND_OPT_HOME_AGENT_INFO 8 + +struct nd_opt_prefix_info { + uint8_t nd_opt_pi_type; + uint8_t nd_opt_pi_len; + uint8_t nd_opt_pi_prefix_len; + uint8_t nd_opt_pi_flags_reserved; + uint32_t nd_opt_pi_valid_time; + uint32_t nd_opt_pi_preferred_time; + uint32_t nd_opt_pi_reserved2; + struct in6_addr nd_opt_pi_prefix; +}; + +#define ND_OPT_PI_FLAG_ONLINK 0x80 +#define ND_OPT_PI_FLAG_AUTO 0x40 +#define ND_OPT_PI_FLAG_RADDR 0x20 + +struct nd_opt_rd_hdr { + uint8_t nd_opt_rh_type; + uint8_t nd_opt_rh_len; + uint16_t nd_opt_rh_reserved1; + uint32_t nd_opt_rh_reserved2; +}; + +struct nd_opt_mtu { + uint8_t nd_opt_mtu_type; + uint8_t nd_opt_mtu_len; + uint16_t nd_opt_mtu_reserved; + uint32_t nd_opt_mtu_mtu; +}; + +struct mld_hdr { + struct icmp6_hdr mld_icmp6_hdr; + struct in6_addr mld_addr; +}; + +#define mld_type mld_icmp6_hdr.icmp6_type +#define mld_code mld_icmp6_hdr.icmp6_code +#define mld_cksum mld_icmp6_hdr.icmp6_cksum +#define mld_maxdelay mld_icmp6_hdr.icmp6_data16[0] +#define mld_reserved mld_icmp6_hdr.icmp6_data16[1] + +#define ICMP6_ROUTER_RENUMBERING 138 + +struct icmp6_router_renum { + struct icmp6_hdr rr_hdr; + uint8_t rr_segnum; + uint8_t rr_flags; + uint16_t rr_maxdelay; + uint32_t rr_reserved; +}; + +#define rr_type rr_hdr.icmp6_type +#define rr_code rr_hdr.icmp6_code +#define rr_cksum rr_hdr.icmp6_cksum +#define rr_seqnum rr_hdr.icmp6_data32[0] + +#define ICMP6_RR_FLAGS_TEST 0x80 +#define ICMP6_RR_FLAGS_REQRESULT 0x40 +#define ICMP6_RR_FLAGS_FORCEAPPLY 0x20 +#define ICMP6_RR_FLAGS_SPECSITE 0x10 +#define ICMP6_RR_FLAGS_PREVDONE 0x08 + +struct rr_pco_match { + uint8_t rpm_code; + uint8_t rpm_len; + uint8_t rpm_ordinal; + uint8_t rpm_matchlen; + uint8_t rpm_minlen; + uint8_t rpm_maxlen; + uint16_t rpm_reserved; + struct in6_addr rpm_prefix; +}; + +#define RPM_PCO_ADD 1 +#define RPM_PCO_CHANGE 2 +#define RPM_PCO_SETGLOBAL 3 + +struct rr_pco_use { + uint8_t rpu_uselen; + uint8_t rpu_keeplen; + uint8_t rpu_ramask; + uint8_t rpu_raflags; + uint32_t rpu_vltime; + uint32_t rpu_pltime; + uint32_t rpu_flags; + struct in6_addr rpu_prefix; +}; + +#define ICMP6_RR_PCOUSE_RAFLAGS_ONLINK 0x20 +#define ICMP6_RR_PCOUSE_RAFLAGS_AUTO 0x10 + +#if __BYTE_ORDER == __BIG_ENDIAN +#define ICMP6_RR_PCOUSE_FLAGS_DECRVLTIME 0x80000000 +#define ICMP6_RR_PCOUSE_FLAGS_DECRPLTIME 0x40000000 +#else +#define ICMP6_RR_PCOUSE_FLAGS_DECRVLTIME 0x80 +#define ICMP6_RR_PCOUSE_FLAGS_DECRPLTIME 0x40 +#endif + +struct rr_result { + uint16_t rrr_flags; + uint8_t rrr_ordinal; + uint8_t rrr_matchedlen; + uint32_t rrr_ifid; + struct in6_addr rrr_prefix; +}; + +#if __BYTE_ORDER == __BIG_ENDIAN +#define ICMP6_RR_RESULT_FLAGS_OOB 0x0002 +#define ICMP6_RR_RESULT_FLAGS_FORBIDDEN 0x0001 +#else +#define ICMP6_RR_RESULT_FLAGS_OOB 0x0200 +#define ICMP6_RR_RESULT_FLAGS_FORBIDDEN 0x0100 +#endif + +struct nd_opt_adv_interval { + uint8_t nd_opt_adv_interval_type; + uint8_t nd_opt_adv_interval_len; + uint16_t nd_opt_adv_interval_reserved; + uint32_t nd_opt_adv_interval_ival; +}; + +struct nd_opt_home_agent_info { + uint8_t nd_opt_home_agent_info_type; + uint8_t nd_opt_home_agent_info_len; + uint16_t nd_opt_home_agent_info_reserved; + uint16_t nd_opt_home_agent_info_preference; + uint16_t nd_opt_home_agent_info_lifetime; +}; + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/netinet/if_ether.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/netinet/if_ether.h new file mode 100644 index 0000000000000000000000000000000000000000..a08485e7f7cd2ef6da6b184d7d290e42a30f1da9 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/netinet/if_ether.h @@ -0,0 +1,147 @@ +#ifndef _NETINET_IF_ETHER_H +#define _NETINET_IF_ETHER_H + +#include +#include + +#define ETH_ALEN 6 +#define ETH_TLEN 2 +#define ETH_HLEN 14 +#define ETH_ZLEN 60 +#define ETH_DATA_LEN 1500 +#define ETH_FRAME_LEN 1514 +#define ETH_FCS_LEN 4 +#define ETH_MIN_MTU 68 +#define ETH_MAX_MTU 0xFFFFU + +#define ETH_P_LOOP 0x0060 +#define ETH_P_PUP 0x0200 +#define ETH_P_PUPAT 0x0201 +#define ETH_P_TSN 0x22F0 +#define ETH_P_ERSPAN2 0x22EB +#define ETH_P_IP 0x0800 +#define ETH_P_X25 0x0805 +#define ETH_P_ARP 0x0806 +#define ETH_P_BPQ 0x08FF +#define ETH_P_IEEEPUP 0x0a00 +#define ETH_P_IEEEPUPAT 0x0a01 +#define ETH_P_BATMAN 0x4305 +#define ETH_P_DEC 0x6000 +#define ETH_P_DNA_DL 0x6001 +#define ETH_P_DNA_RC 0x6002 +#define ETH_P_DNA_RT 0x6003 +#define ETH_P_LAT 0x6004 +#define ETH_P_DIAG 0x6005 +#define ETH_P_CUST 0x6006 +#define ETH_P_SCA 0x6007 +#define ETH_P_TEB 0x6558 +#define ETH_P_RARP 0x8035 +#define ETH_P_ATALK 0x809B +#define ETH_P_AARP 0x80F3 +#define ETH_P_8021Q 0x8100 +#define ETH_P_IPX 0x8137 +#define ETH_P_IPV6 0x86DD +#define ETH_P_PAUSE 0x8808 +#define ETH_P_SLOW 0x8809 +#define ETH_P_WCCP 0x883E +#define ETH_P_MPLS_UC 0x8847 +#define ETH_P_MPLS_MC 0x8848 +#define ETH_P_ATMMPOA 0x884c +#define ETH_P_PPP_DISC 0x8863 +#define ETH_P_PPP_SES 0x8864 +#define ETH_P_LINK_CTL 0x886c +#define ETH_P_ATMFATE 0x8884 +#define ETH_P_PAE 0x888E +#define ETH_P_AOE 0x88A2 +#define ETH_P_8021AD 0x88A8 +#define ETH_P_802_EX1 0x88B5 +#define ETH_P_ERSPAN 0x88BE +#define ETH_P_PREAUTH 0x88C7 +#define ETH_P_TIPC 0x88CA +#define ETH_P_LLDP 0x88CC +#define ETH_P_MACSEC 0x88E5 +#define ETH_P_8021AH 0x88E7 +#define ETH_P_MVRP 0x88F5 +#define ETH_P_1588 0x88F7 +#define ETH_P_NCSI 0x88F8 +#define ETH_P_PRP 0x88FB +#define ETH_P_FCOE 0x8906 +#define ETH_P_TDLS 0x890D +#define ETH_P_FIP 0x8914 +#define ETH_P_IBOE 0x8915 +#define ETH_P_80221 0x8917 +#define ETH_P_HSR 0x892F +#define ETH_P_NSH 0x894F +#define ETH_P_LOOPBACK 0x9000 +#define ETH_P_QINQ1 0x9100 +#define ETH_P_QINQ2 0x9200 +#define ETH_P_QINQ3 0x9300 +#define ETH_P_EDSA 0xDADA +#define ETH_P_DSA_8021Q 0xDADB +#define ETH_P_IFE 0xED3E +#define ETH_P_AF_IUCV 0xFBFB + +#define ETH_P_802_3_MIN 0x0600 + +#define ETH_P_802_3 0x0001 +#define ETH_P_AX25 0x0002 +#define ETH_P_ALL 0x0003 +#define ETH_P_802_2 0x0004 +#define ETH_P_SNAP 0x0005 +#define ETH_P_DDCMP 0x0006 +#define ETH_P_WAN_PPP 0x0007 +#define ETH_P_PPP_MP 0x0008 +#define ETH_P_LOCALTALK 0x0009 +#define ETH_P_CAN 0x000C +#define ETH_P_CANFD 0x000D +#define ETH_P_PPPTALK 0x0010 +#define ETH_P_TR_802_2 0x0011 +#define ETH_P_MOBITEX 0x0015 +#define ETH_P_CONTROL 0x0016 +#define ETH_P_IRDA 0x0017 +#define ETH_P_ECONET 0x0018 +#define ETH_P_HDLC 0x0019 +#define ETH_P_ARCNET 0x001A +#define ETH_P_DSA 0x001B +#define ETH_P_TRAILER 0x001C +#define ETH_P_PHONET 0x00F5 +#define ETH_P_IEEE802154 0x00F6 +#define ETH_P_CAIF 0x00F7 +#define ETH_P_XDSA 0x00F8 +#define ETH_P_MAP 0x00F9 + +struct ethhdr { + uint8_t h_dest[ETH_ALEN]; + uint8_t h_source[ETH_ALEN]; + uint16_t h_proto; +}; + +#include +#include + +struct ether_arp { + struct arphdr ea_hdr; + uint8_t arp_sha[ETH_ALEN]; + uint8_t arp_spa[4]; + uint8_t arp_tha[ETH_ALEN]; + uint8_t arp_tpa[4]; +}; +#define arp_hrd ea_hdr.ar_hrd +#define arp_pro ea_hdr.ar_pro +#define arp_hln ea_hdr.ar_hln +#define arp_pln ea_hdr.ar_pln +#define arp_op ea_hdr.ar_op + +#define ETHER_MAP_IP_MULTICAST(ipaddr, enaddr) \ +do { \ + (enaddr)[0] = 0x01; \ + (enaddr)[1] = 0x00; \ + (enaddr)[2] = 0x5e; \ + (enaddr)[3] = ((uint8_t *)ipaddr)[1] & 0x7f; \ + (enaddr)[4] = ((uint8_t *)ipaddr)[2]; \ + (enaddr)[5] = ((uint8_t *)ipaddr)[3]; \ +} while(0) + +#define __UAPI_DEF_ETHHDR 0 + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/netinet/igmp.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/netinet/igmp.h new file mode 100644 index 0000000000000000000000000000000000000000..bbe8206a1015828e2143533dd35ae4de235b9bb6 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/netinet/igmp.h @@ -0,0 +1,45 @@ +#ifndef _NETINET_IGMP_H +#define _NETINET_IGMP_H + +#include +#include + +struct igmp { + uint8_t igmp_type; + uint8_t igmp_code; + uint16_t igmp_cksum; + struct in_addr igmp_group; +}; + +#define IGMP_MINLEN 8 + +#define IGMP_MEMBERSHIP_QUERY 0x11 +#define IGMP_V1_MEMBERSHIP_REPORT 0x12 +#define IGMP_V2_MEMBERSHIP_REPORT 0x16 +#define IGMP_V2_LEAVE_GROUP 0x17 + +#define IGMP_DVMRP 0x13 +#define IGMP_PIM 0x14 +#define IGMP_TRACE 0x15 + +#define IGMP_MTRACE_RESP 0x1e +#define IGMP_MTRACE 0x1f + +#define IGMP_MAX_HOST_REPORT_DELAY 10 +#define IGMP_TIMER_SCALE 10 + +#define IGMP_DELAYING_MEMBER 1 +#define IGMP_IDLE_MEMBER 2 +#define IGMP_LAZY_MEMBER 3 +#define IGMP_SLEEPING_MEMBER 4 +#define IGMP_AWAKENING_MEMBER 5 + +#define IGMP_v1_ROUTER 1 +#define IGMP_v2_ROUTER 2 + +#define IGMP_HOST_MEMBERSHIP_QUERY IGMP_MEMBERSHIP_QUERY +#define IGMP_HOST_MEMBERSHIP_REPORT IGMP_V1_MEMBERSHIP_REPORT +#define IGMP_HOST_NEW_MEMBERSHIP_REPORT IGMP_V2_MEMBERSHIP_REPORT +#define IGMP_HOST_LEAVE_MESSAGE IGMP_V2_LEAVE_GROUP + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/netinet/in.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/netinet/in.h new file mode 100644 index 0000000000000000000000000000000000000000..b996cf135f9bc846d674e325bd3b0754c12625df --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/netinet/in.h @@ -0,0 +1,423 @@ +#ifndef _NETINET_IN_H +#define _NETINET_IN_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include + +typedef uint16_t in_port_t; +typedef uint32_t in_addr_t; +struct in_addr { in_addr_t s_addr; }; + +struct sockaddr_in { + sa_family_t sin_family; + in_port_t sin_port; + struct in_addr sin_addr; + uint8_t sin_zero[8]; +}; + +struct in6_addr { + union { + uint8_t u6_addr8[16]; + uint16_t u6_addr16[8]; + uint32_t u6_addr32[4]; + } in6_u; +}; +#define s6_addr in6_u.u6_addr8 +#define s6_addr16 in6_u.u6_addr16 +#define s6_addr32 in6_u.u6_addr32 + +struct sockaddr_in6 { + sa_family_t sin6_family; + in_port_t sin6_port; + uint32_t sin6_flowinfo; + struct in6_addr sin6_addr; + uint32_t sin6_scope_id; +}; + +#ifdef __LITEOS__ +struct in6_ifreq { + struct in6_addr ifr6_addr; + uint32_t ifr6_prefixlen; + int32_t ifr6_ifindex; +}; +#endif + +struct ipv6_mreq { + struct in6_addr ipv6mr_multiaddr; + unsigned ipv6mr_interface; +}; + +#define INADDR_ANY ((in_addr_t) 0x00000000) +#define INADDR_BROADCAST ((in_addr_t) 0xffffffff) +#define INADDR_NONE ((in_addr_t) 0xffffffff) +#define INADDR_LOOPBACK ((in_addr_t) 0x7f000001) + +#define INADDR_UNSPEC_GROUP ((in_addr_t) 0xe0000000) +#define INADDR_ALLHOSTS_GROUP ((in_addr_t) 0xe0000001) +#define INADDR_ALLRTRS_GROUP ((in_addr_t) 0xe0000002) +#define INADDR_ALLSNOOPERS_GROUP ((in_addr_t) 0xe000006a) +#define INADDR_MAX_LOCAL_GROUP ((in_addr_t) 0xe00000ff) + +#define IN6ADDR_ANY_INIT { { { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } } } +#define IN6ADDR_LOOPBACK_INIT { { { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1 } } } + +extern const struct in6_addr in6addr_any, in6addr_loopback; + +#undef INET_ADDRSTRLEN +#undef INET6_ADDRSTRLEN +#define INET_ADDRSTRLEN 16 +#define INET6_ADDRSTRLEN 46 + +uint32_t htonl(uint32_t); +uint16_t htons(uint16_t); +uint32_t ntohl(uint32_t); +uint16_t ntohs(uint16_t); + +#define IPPORT_RESERVED 1024 + +#define IPPROTO_IP 0 +#define IPPROTO_HOPOPTS 0 +#define IPPROTO_ICMP 1 +#define IPPROTO_IGMP 2 +#define IPPROTO_IPIP 4 +#define IPPROTO_TCP 6 +#define IPPROTO_EGP 8 +#define IPPROTO_PUP 12 +#define IPPROTO_UDP 17 +#define IPPROTO_IDP 22 +#define IPPROTO_TP 29 +#define IPPROTO_DCCP 33 +#define IPPROTO_IPV6 41 +#define IPPROTO_ROUTING 43 +#define IPPROTO_FRAGMENT 44 +#define IPPROTO_RSVP 46 +#define IPPROTO_GRE 47 +#define IPPROTO_ESP 50 +#define IPPROTO_AH 51 +#define IPPROTO_ICMPV6 58 +#define IPPROTO_NONE 59 +#define IPPROTO_DSTOPTS 60 +#define IPPROTO_MTP 92 +#define IPPROTO_BEETPH 94 +#define IPPROTO_ENCAP 98 +#define IPPROTO_PIM 103 +#define IPPROTO_COMP 108 +#define IPPROTO_SCTP 132 +#define IPPROTO_MH 135 +#define IPPROTO_UDPLITE 136 +#define IPPROTO_MPLS 137 +#define IPPROTO_RAW 255 +#define IPPROTO_MAX 256 + +#define IN6_IS_ADDR_UNSPECIFIED(a) \ + (((uint32_t *) (a))[0] == 0 && ((uint32_t *) (a))[1] == 0 && \ + ((uint32_t *) (a))[2] == 0 && ((uint32_t *) (a))[3] == 0) + +#define IN6_IS_ADDR_LOOPBACK(a) \ + (((uint32_t *) (a))[0] == 0 && ((uint32_t *) (a))[1] == 0 && \ + ((uint32_t *) (a))[2] == 0 && \ + ((uint8_t *) (a))[12] == 0 && ((uint8_t *) (a))[13] == 0 && \ + ((uint8_t *) (a))[14] == 0 && ((uint8_t *) (a))[15] == 1 ) + +#define IN6_IS_ADDR_MULTICAST(a) (((uint8_t *) (a))[0] == 0xff) + +#define IN6_IS_ADDR_LINKLOCAL(a) \ + ((((uint8_t *) (a))[0]) == 0xfe && (((uint8_t *) (a))[1] & 0xc0) == 0x80) + +#define IN6_IS_ADDR_SITELOCAL(a) \ + ((((uint8_t *) (a))[0]) == 0xfe && (((uint8_t *) (a))[1] & 0xc0) == 0xc0) + +#define IN6_IS_ADDR_V4MAPPED(a) \ + (((uint32_t *) (a))[0] == 0 && ((uint32_t *) (a))[1] == 0 && \ + ((uint8_t *) (a))[8] == 0 && ((uint8_t *) (a))[9] == 0 && \ + ((uint8_t *) (a))[10] == 0xff && ((uint8_t *) (a))[11] == 0xff) + +#define IN6_IS_ADDR_V4COMPAT(a) \ + (((uint32_t *) (a))[0] == 0 && ((uint32_t *) (a))[1] == 0 && \ + ((uint32_t *) (a))[2] == 0 && ((uint8_t *) (a))[15] > 1) + +#define IN6_IS_ADDR_MC_NODELOCAL(a) \ + (IN6_IS_ADDR_MULTICAST(a) && ((((uint8_t *) (a))[1] & 0xf) == 0x1)) + +#define IN6_IS_ADDR_MC_LINKLOCAL(a) \ + (IN6_IS_ADDR_MULTICAST(a) && ((((uint8_t *) (a))[1] & 0xf) == 0x2)) + +#define IN6_IS_ADDR_MC_SITELOCAL(a) \ + (IN6_IS_ADDR_MULTICAST(a) && ((((uint8_t *) (a))[1] & 0xf) == 0x5)) + +#define IN6_IS_ADDR_MC_ORGLOCAL(a) \ + (IN6_IS_ADDR_MULTICAST(a) && ((((uint8_t *) (a))[1] & 0xf) == 0x8)) + +#define IN6_IS_ADDR_MC_GLOBAL(a) \ + (IN6_IS_ADDR_MULTICAST(a) && ((((uint8_t *) (a))[1] & 0xf) == 0xe)) + +#define __ARE_4_EQUAL(a,b) \ + (!( (0[a]-0[b]) | (1[a]-1[b]) | (2[a]-2[b]) | (3[a]-3[b]) )) +#define IN6_ARE_ADDR_EQUAL(a,b) \ + __ARE_4_EQUAL((const uint32_t *)(a), (const uint32_t *)(b)) + +#define IN_CLASSA(a) ((((in_addr_t)(a)) & 0x80000000) == 0) +#define IN_CLASSA_NET 0xff000000 +#define IN_CLASSA_NSHIFT 24 +#define IN_CLASSA_HOST (0xffffffff & ~IN_CLASSA_NET) +#define IN_CLASSA_MAX 128 +#define IN_CLASSB(a) ((((in_addr_t)(a)) & 0xc0000000) == 0x80000000) +#define IN_CLASSB_NET 0xffff0000 +#define IN_CLASSB_NSHIFT 16 +#define IN_CLASSB_HOST (0xffffffff & ~IN_CLASSB_NET) +#define IN_CLASSB_MAX 65536 +#define IN_CLASSC(a) ((((in_addr_t)(a)) & 0xe0000000) == 0xc0000000) +#define IN_CLASSC_NET 0xffffff00 +#define IN_CLASSC_NSHIFT 8 +#define IN_CLASSC_HOST (0xffffffff & ~IN_CLASSC_NET) +#define IN_CLASSD(a) ((((in_addr_t)(a)) & 0xf0000000) == 0xe0000000) +#define IN_MULTICAST(a) IN_CLASSD(a) +#define IN_EXPERIMENTAL(a) ((((in_addr_t)(a)) & 0xe0000000) == 0xe0000000) +#define IN_BADCLASS(a) ((((in_addr_t)(a)) & 0xf0000000) == 0xf0000000) + +#define IN_LOOPBACKNET 127 + + +#define IP_TOS 1 +#define IP_TTL 2 +#define IP_HDRINCL 3 +#define IP_OPTIONS 4 +#define IP_ROUTER_ALERT 5 +#define IP_RECVOPTS 6 +#define IP_RETOPTS 7 +#define IP_PKTINFO 8 +#define IP_PKTOPTIONS 9 +#define IP_PMTUDISC 10 +#define IP_MTU_DISCOVER 10 +#define IP_RECVERR 11 +#define IP_RECVTTL 12 +#define IP_RECVTOS 13 +#define IP_MTU 14 +#define IP_FREEBIND 15 +#define IP_IPSEC_POLICY 16 +#define IP_XFRM_POLICY 17 +#define IP_PASSSEC 18 +#define IP_TRANSPARENT 19 +#define IP_ORIGDSTADDR 20 +#define IP_RECVORIGDSTADDR IP_ORIGDSTADDR +#define IP_MINTTL 21 +#define IP_NODEFRAG 22 +#define IP_CHECKSUM 23 +#define IP_BIND_ADDRESS_NO_PORT 24 +#define IP_RECVFRAGSIZE 25 +#define IP_MULTICAST_IF 32 +#define IP_MULTICAST_TTL 33 +#define IP_MULTICAST_LOOP 34 +#define IP_ADD_MEMBERSHIP 35 +#define IP_DROP_MEMBERSHIP 36 +#define IP_UNBLOCK_SOURCE 37 +#define IP_BLOCK_SOURCE 38 +#define IP_ADD_SOURCE_MEMBERSHIP 39 +#define IP_DROP_SOURCE_MEMBERSHIP 40 +#define IP_MSFILTER 41 +#define IP_MULTICAST_ALL 49 +#define IP_UNICAST_IF 50 + +#define IP_RECVRETOPTS IP_RETOPTS + +#define IP_PMTUDISC_DONT 0 +#define IP_PMTUDISC_WANT 1 +#define IP_PMTUDISC_DO 2 +#define IP_PMTUDISC_PROBE 3 +#define IP_PMTUDISC_INTERFACE 4 +#define IP_PMTUDISC_OMIT 5 + +#define IP_DEFAULT_MULTICAST_TTL 1 +#define IP_DEFAULT_MULTICAST_LOOP 1 +#define IP_MAX_MEMBERSHIPS 20 + +struct ip_opts { + struct in_addr ip_dst; + char ip_opts[40]; +}; + +#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE) + +#define MCAST_JOIN_GROUP 42 +#define MCAST_BLOCK_SOURCE 43 +#define MCAST_UNBLOCK_SOURCE 44 +#define MCAST_LEAVE_GROUP 45 +#define MCAST_JOIN_SOURCE_GROUP 46 +#define MCAST_LEAVE_SOURCE_GROUP 47 +#define MCAST_MSFILTER 48 + +#define MCAST_EXCLUDE 0 +#define MCAST_INCLUDE 1 + +struct ip_mreq { + struct in_addr imr_multiaddr; + struct in_addr imr_interface; +}; + +struct ip_mreqn { + struct in_addr imr_multiaddr; + struct in_addr imr_address; + int imr_ifindex; +}; + +struct ip_mreq_source { + struct in_addr imr_multiaddr; + struct in_addr imr_interface; + struct in_addr imr_sourceaddr; +}; + +struct ip_msfilter { + struct in_addr imsf_multiaddr; + struct in_addr imsf_interface; + uint32_t imsf_fmode; + uint32_t imsf_numsrc; + struct in_addr imsf_slist[1]; +}; +#define IP_MSFILTER_SIZE(numsrc) \ + (sizeof(struct ip_msfilter) - sizeof(struct in_addr) \ + + (numsrc) * sizeof(struct in_addr)) + +struct group_req { + uint32_t gr_interface; + struct sockaddr_storage gr_group; +}; + +struct group_source_req { + uint32_t gsr_interface; + struct sockaddr_storage gsr_group; + struct sockaddr_storage gsr_source; +}; + +struct group_filter { + uint32_t gf_interface; + struct sockaddr_storage gf_group; + uint32_t gf_fmode; + uint32_t gf_numsrc; + struct sockaddr_storage gf_slist[1]; +}; +#define GROUP_FILTER_SIZE(numsrc) \ + (sizeof(struct group_filter) - sizeof(struct sockaddr_storage) \ + + (numsrc) * sizeof(struct sockaddr_storage)) + +struct in_pktinfo { + int ipi_ifindex; + struct in_addr ipi_spec_dst; + struct in_addr ipi_addr; +}; + +struct in6_pktinfo { + struct in6_addr ipi6_addr; + unsigned ipi6_ifindex; +}; + +struct ip6_mtuinfo { + struct sockaddr_in6 ip6m_addr; + uint32_t ip6m_mtu; +}; +#endif + +#define IPV6_ADDRFORM 1 +#define IPV6_2292PKTINFO 2 +#define IPV6_2292HOPOPTS 3 +#define IPV6_2292DSTOPTS 4 +#define IPV6_2292RTHDR 5 +#define IPV6_2292PKTOPTIONS 6 +#define IPV6_CHECKSUM 7 +#define IPV6_2292HOPLIMIT 8 +#define IPV6_NEXTHOP 9 +#define IPV6_AUTHHDR 10 +#define IPV6_UNICAST_HOPS 16 +#define IPV6_MULTICAST_IF 17 +#define IPV6_MULTICAST_HOPS 18 +#define IPV6_MULTICAST_LOOP 19 +#define IPV6_JOIN_GROUP 20 +#define IPV6_LEAVE_GROUP 21 +#define IPV6_ROUTER_ALERT 22 +#define IPV6_MTU_DISCOVER 23 +#define IPV6_MTU 24 +#define IPV6_RECVERR 25 +#define IPV6_V6ONLY 26 +#define IPV6_JOIN_ANYCAST 27 +#define IPV6_LEAVE_ANYCAST 28 +#define IPV6_MULTICAST_ALL 29 +#define IPV6_ROUTER_ALERT_ISOLATE 30 +#define IPV6_IPSEC_POLICY 34 +#define IPV6_XFRM_POLICY 35 +#define IPV6_HDRINCL 36 + +#define IPV6_RECVPKTINFO 49 +#define IPV6_PKTINFO 50 +#define IPV6_RECVHOPLIMIT 51 +#define IPV6_HOPLIMIT 52 +#define IPV6_RECVHOPOPTS 53 +#define IPV6_HOPOPTS 54 +#define IPV6_RTHDRDSTOPTS 55 +#define IPV6_RECVRTHDR 56 +#define IPV6_RTHDR 57 +#define IPV6_RECVDSTOPTS 58 +#define IPV6_DSTOPTS 59 +#define IPV6_RECVPATHMTU 60 +#define IPV6_PATHMTU 61 +#define IPV6_DONTFRAG 62 +#define IPV6_RECVTCLASS 66 +#define IPV6_TCLASS 67 +#define IPV6_AUTOFLOWLABEL 70 +#define IPV6_ADDR_PREFERENCES 72 +#define IPV6_MINHOPCOUNT 73 +#define IPV6_ORIGDSTADDR 74 +#define IPV6_RECVORIGDSTADDR IPV6_ORIGDSTADDR +#define IPV6_TRANSPARENT 75 +#define IPV6_UNICAST_IF 76 +#define IPV6_RECVFRAGSIZE 77 +#define IPV6_FREEBIND 78 + +#define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP +#define IPV6_DROP_MEMBERSHIP IPV6_LEAVE_GROUP +#define IPV6_RXHOPOPTS IPV6_HOPOPTS +#define IPV6_RXDSTOPTS IPV6_DSTOPTS + +#define IPV6_PMTUDISC_DONT 0 +#define IPV6_PMTUDISC_WANT 1 +#define IPV6_PMTUDISC_DO 2 +#define IPV6_PMTUDISC_PROBE 3 +#define IPV6_PMTUDISC_INTERFACE 4 +#define IPV6_PMTUDISC_OMIT 5 + +#define IPV6_PREFER_SRC_TMP 0x0001 +#define IPV6_PREFER_SRC_PUBLIC 0x0002 +#define IPV6_PREFER_SRC_PUBTMP_DEFAULT 0x0100 +#define IPV6_PREFER_SRC_COA 0x0004 +#define IPV6_PREFER_SRC_HOME 0x0400 +#define IPV6_PREFER_SRC_CGA 0x0008 +#define IPV6_PREFER_SRC_NONCGA 0x0800 + +#define IPV6_RTHDR_LOOSE 0 +#define IPV6_RTHDR_STRICT 1 + +#define IPV6_RTHDR_TYPE_0 0 + +#define __UAPI_DEF_IN_ADDR 0 +#define __UAPI_DEF_IN_IPPROTO 0 +#define __UAPI_DEF_IN_PKTINFO 0 +#define __UAPI_DEF_IP_MREQ 0 +#define __UAPI_DEF_SOCKADDR_IN 0 +#define __UAPI_DEF_IN_CLASS 0 +#define __UAPI_DEF_IN6_ADDR 0 +#define __UAPI_DEF_IN6_ADDR_ALT 0 +#define __UAPI_DEF_SOCKADDR_IN6 0 +#define __UAPI_DEF_IPV6_MREQ 0 +#define __UAPI_DEF_IPPROTO_V6 0 +#define __UAPI_DEF_IPV6_OPTIONS 0 +#define __UAPI_DEF_IN6_PKTINFO 0 +#define __UAPI_DEF_IP6_MTUINFO 0 + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/netinet/in_systm.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/netinet/in_systm.h new file mode 100644 index 0000000000000000000000000000000000000000..a7b417722c3eb9034383b5aa14c3b80d0e4ed651 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/netinet/in_systm.h @@ -0,0 +1,9 @@ +#ifndef _NETINET_IN_SYSTM_H +#define _NETINET_IN_SYSTM_H + +#include + +typedef uint16_t n_short; +typedef uint32_t n_long, n_time; + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/netinet/ip.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/netinet/ip.h new file mode 100644 index 0000000000000000000000000000000000000000..0ae132a58584b6916e13c9c72015def387c35442 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/netinet/ip.h @@ -0,0 +1,199 @@ +#ifndef _NETINET_IP_H +#define _NETINET_IP_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include + +struct timestamp { + uint8_t len; + uint8_t ptr; +#if __BYTE_ORDER == __LITTLE_ENDIAN + unsigned int flags:4; + unsigned int overflow:4; +#else + unsigned int overflow:4; + unsigned int flags:4; +#endif + uint32_t data[9]; + }; + +struct iphdr { +#if __BYTE_ORDER == __LITTLE_ENDIAN + unsigned int ihl:4; + unsigned int version:4; +#else + unsigned int version:4; + unsigned int ihl:4; +#endif + uint8_t tos; + uint16_t tot_len; + uint16_t id; + uint16_t frag_off; + uint8_t ttl; + uint8_t protocol; + uint16_t check; + uint32_t saddr; + uint32_t daddr; +}; + +struct ip { +#if __BYTE_ORDER == __LITTLE_ENDIAN + unsigned int ip_hl:4; + unsigned int ip_v:4; +#else + unsigned int ip_v:4; + unsigned int ip_hl:4; +#endif + uint8_t ip_tos; + uint16_t ip_len; + uint16_t ip_id; + uint16_t ip_off; + uint8_t ip_ttl; + uint8_t ip_p; + uint16_t ip_sum; + struct in_addr ip_src, ip_dst; +}; + +#define IP_RF 0x8000 +#define IP_DF 0x4000 +#define IP_MF 0x2000 +#define IP_OFFMASK 0x1fff + +struct ip_timestamp { + uint8_t ipt_code; + uint8_t ipt_len; + uint8_t ipt_ptr; +#if __BYTE_ORDER == __LITTLE_ENDIAN + unsigned int ipt_flg:4; + unsigned int ipt_oflw:4; +#else + unsigned int ipt_oflw:4; + unsigned int ipt_flg:4; +#endif + uint32_t data[9]; +}; + +#define IPVERSION 4 +#define IP_MAXPACKET 65535 + +#define IPTOS_ECN_MASK 0x03 +#define IPTOS_ECN(x) ((x) & IPTOS_ECN_MASK) +#define IPTOS_ECN_NOT_ECT 0x00 +#define IPTOS_ECN_ECT1 0x01 +#define IPTOS_ECN_ECT0 0x02 +#define IPTOS_ECN_CE 0x03 + +#define IPTOS_DSCP_MASK 0xfc +#define IPTOS_DSCP(x) ((x) & IPTOS_DSCP_MASK) +#define IPTOS_DSCP_AF11 0x28 +#define IPTOS_DSCP_AF12 0x30 +#define IPTOS_DSCP_AF13 0x38 +#define IPTOS_DSCP_AF21 0x48 +#define IPTOS_DSCP_AF22 0x50 +#define IPTOS_DSCP_AF23 0x58 +#define IPTOS_DSCP_AF31 0x68 +#define IPTOS_DSCP_AF32 0x70 +#define IPTOS_DSCP_AF33 0x78 +#define IPTOS_DSCP_AF41 0x88 +#define IPTOS_DSCP_AF42 0x90 +#define IPTOS_DSCP_AF43 0x98 +#define IPTOS_DSCP_EF 0xb8 + +#define IPTOS_CLASS_MASK 0xe0 +#define IPTOS_CLASS(x) ((x) & IPTOS_CLASS_MASK) +#define IPTOS_CLASS_CS0 0x00 +#define IPTOS_CLASS_CS1 0x20 +#define IPTOS_CLASS_CS2 0x40 +#define IPTOS_CLASS_CS3 0x60 +#define IPTOS_CLASS_CS4 0x80 +#define IPTOS_CLASS_CS5 0xa0 +#define IPTOS_CLASS_CS6 0xc0 +#define IPTOS_CLASS_CS7 0xe0 +#define IPTOS_CLASS_DEFAULT IPTOS_CLASS_CS0 + +#define IPTOS_TOS_MASK 0x1E +#define IPTOS_TOS(tos) ((tos) & IPTOS_TOS_MASK) +#define IPTOS_LOWDELAY 0x10 +#define IPTOS_THROUGHPUT 0x08 +#define IPTOS_RELIABILITY 0x04 +#define IPTOS_LOWCOST 0x02 +#define IPTOS_MINCOST IPTOS_LOWCOST + +#define IPTOS_PREC_MASK 0xe0 +#define IPTOS_PREC(tos) ((tos) & IPTOS_PREC_MASK) +#define IPTOS_PREC_NETCONTROL 0xe0 +#define IPTOS_PREC_INTERNETCONTROL 0xc0 +#define IPTOS_PREC_CRITIC_ECP 0xa0 +#define IPTOS_PREC_FLASHOVERRIDE 0x80 +#define IPTOS_PREC_FLASH 0x60 +#define IPTOS_PREC_IMMEDIATE 0x40 +#define IPTOS_PREC_PRIORITY 0x20 +#define IPTOS_PREC_ROUTINE 0x00 + +#define IPOPT_COPY 0x80 +#define IPOPT_CLASS_MASK 0x60 +#define IPOPT_NUMBER_MASK 0x1f + +#define IPOPT_COPIED(o) ((o) & IPOPT_COPY) +#define IPOPT_CLASS(o) ((o) & IPOPT_CLASS_MASK) +#define IPOPT_NUMBER(o) ((o) & IPOPT_NUMBER_MASK) + +#define IPOPT_CONTROL 0x00 +#define IPOPT_RESERVED1 0x20 +#define IPOPT_DEBMEAS 0x40 +#define IPOPT_MEASUREMENT IPOPT_DEBMEAS +#define IPOPT_RESERVED2 0x60 + +#define IPOPT_EOL 0 +#define IPOPT_END IPOPT_EOL +#define IPOPT_NOP 1 +#define IPOPT_NOOP IPOPT_NOP + +#define IPOPT_RR 7 +#define IPOPT_TS 68 +#define IPOPT_TIMESTAMP IPOPT_TS +#define IPOPT_SECURITY 130 +#define IPOPT_SEC IPOPT_SECURITY +#define IPOPT_LSRR 131 +#define IPOPT_SATID 136 +#define IPOPT_SID IPOPT_SATID +#define IPOPT_SSRR 137 +#define IPOPT_RA 148 + +#define IPOPT_OPTVAL 0 +#define IPOPT_OLEN 1 +#define IPOPT_OFFSET 2 +#define IPOPT_MINOFF 4 + +#define MAX_IPOPTLEN 40 + +#define IPOPT_TS_TSONLY 0 +#define IPOPT_TS_TSANDADDR 1 +#define IPOPT_TS_PRESPEC 3 + +#define IPOPT_SECUR_UNCLASS 0x0000 +#define IPOPT_SECUR_CONFID 0xf135 +#define IPOPT_SECUR_EFTO 0x789a +#define IPOPT_SECUR_MMMM 0xbc4d +#define IPOPT_SECUR_RESTR 0xaf13 +#define IPOPT_SECUR_SECRET 0xd788 +#define IPOPT_SECUR_TOPSECRET 0x6bc5 + +#define MAXTTL 255 +#define IPDEFTTL 64 +#define IPFRAGTTL 60 +#define IPTTLDEC 1 + +#define IP_MSS 576 + +#define __UAPI_DEF_IPHDR 0 + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/netinet/ip6.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/netinet/ip6.h new file mode 100644 index 0000000000000000000000000000000000000000..50c626a69c646639cf7313ef138bc38c3e82e999 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/netinet/ip6.h @@ -0,0 +1,141 @@ +#ifndef _NETINET_IP6_H +#define _NETINET_IP6_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include + +struct ip6_hdr { + union { + struct ip6_hdrctl { + uint32_t ip6_un1_flow; + uint16_t ip6_un1_plen; + uint8_t ip6_un1_nxt; + uint8_t ip6_un1_hlim; + } ip6_un1; + uint8_t ip6_un2_vfc; + } ip6_ctlun; + struct in6_addr ip6_src; + struct in6_addr ip6_dst; +}; + +#define ip6_vfc ip6_ctlun.ip6_un2_vfc +#define ip6_flow ip6_ctlun.ip6_un1.ip6_un1_flow +#define ip6_plen ip6_ctlun.ip6_un1.ip6_un1_plen +#define ip6_nxt ip6_ctlun.ip6_un1.ip6_un1_nxt +#define ip6_hlim ip6_ctlun.ip6_un1.ip6_un1_hlim +#define ip6_hops ip6_ctlun.ip6_un1.ip6_un1_hlim + +struct ip6_ext { + uint8_t ip6e_nxt; + uint8_t ip6e_len; +}; + +struct ip6_hbh { + uint8_t ip6h_nxt; + uint8_t ip6h_len; +}; + +struct ip6_dest { + uint8_t ip6d_nxt; + uint8_t ip6d_len; +}; + +struct ip6_rthdr { + uint8_t ip6r_nxt; + uint8_t ip6r_len; + uint8_t ip6r_type; + uint8_t ip6r_segleft; +}; + +struct ip6_rthdr0 { + uint8_t ip6r0_nxt; + uint8_t ip6r0_len; + uint8_t ip6r0_type; + uint8_t ip6r0_segleft; + uint8_t ip6r0_reserved; + uint8_t ip6r0_slmap[3]; + struct in6_addr ip6r0_addr[]; +}; + +struct ip6_frag { + uint8_t ip6f_nxt; + uint8_t ip6f_reserved; + uint16_t ip6f_offlg; + uint32_t ip6f_ident; +}; + +#if __BYTE_ORDER == __BIG_ENDIAN +#define IP6F_OFF_MASK 0xfff8 +#define IP6F_RESERVED_MASK 0x0006 +#define IP6F_MORE_FRAG 0x0001 +#else +#define IP6F_OFF_MASK 0xf8ff +#define IP6F_RESERVED_MASK 0x0600 +#define IP6F_MORE_FRAG 0x0100 +#endif + +struct ip6_opt { + uint8_t ip6o_type; + uint8_t ip6o_len; +}; + +#define IP6OPT_TYPE(o) ((o) & 0xc0) +#define IP6OPT_TYPE_SKIP 0x00 +#define IP6OPT_TYPE_DISCARD 0x40 +#define IP6OPT_TYPE_FORCEICMP 0x80 +#define IP6OPT_TYPE_ICMP 0xc0 +#define IP6OPT_TYPE_MUTABLE 0x20 + +#define IP6OPT_PAD1 0 +#define IP6OPT_PADN 1 + +#define IP6OPT_JUMBO 0xc2 +#define IP6OPT_NSAP_ADDR 0xc3 +#define IP6OPT_TUNNEL_LIMIT 0x04 +#define IP6OPT_ROUTER_ALERT 0x05 + +struct ip6_opt_jumbo { + uint8_t ip6oj_type; + uint8_t ip6oj_len; + uint8_t ip6oj_jumbo_len[4]; +}; +#define IP6OPT_JUMBO_LEN 6 + +struct ip6_opt_nsap { + uint8_t ip6on_type; + uint8_t ip6on_len; + uint8_t ip6on_src_nsap_len; + uint8_t ip6on_dst_nsap_len; +}; + +struct ip6_opt_tunnel { + uint8_t ip6ot_type; + uint8_t ip6ot_len; + uint8_t ip6ot_encap_limit; +}; + +struct ip6_opt_router { + uint8_t ip6or_type; + uint8_t ip6or_len; + uint8_t ip6or_value[2]; +}; + +#if __BYTE_ORDER == __BIG_ENDIAN +#define IP6_ALERT_MLD 0x0000 +#define IP6_ALERT_RSVP 0x0001 +#define IP6_ALERT_AN 0x0002 +#else +#define IP6_ALERT_MLD 0x0000 +#define IP6_ALERT_RSVP 0x0100 +#define IP6_ALERT_AN 0x0200 +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/netinet/ip_icmp.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/netinet/ip_icmp.h new file mode 100644 index 0000000000000000000000000000000000000000..b9e0df8997e145726e1c0eef5768c52c5c69fb97 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/netinet/ip_icmp.h @@ -0,0 +1,193 @@ +#ifndef _NETINET_IP_ICMP_H +#define _NETINET_IP_ICMP_H + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +struct icmphdr { + uint8_t type; + uint8_t code; + uint16_t checksum; + union { + struct { + uint16_t id; + uint16_t sequence; + } echo; + uint32_t gateway; + struct { + uint16_t __unused; + uint16_t mtu; + } frag; + uint8_t reserved[4]; + } un; +}; + +#define ICMP_ECHOREPLY 0 +#define ICMP_DEST_UNREACH 3 +#define ICMP_SOURCE_QUENCH 4 +#define ICMP_REDIRECT 5 +#define ICMP_ECHO 8 +#define ICMP_TIME_EXCEEDED 11 +#define ICMP_PARAMETERPROB 12 +#define ICMP_TIMESTAMP 13 +#define ICMP_TIMESTAMPREPLY 14 +#define ICMP_INFO_REQUEST 15 +#define ICMP_INFO_REPLY 16 +#define ICMP_ADDRESS 17 +#define ICMP_ADDRESSREPLY 18 +#define NR_ICMP_TYPES 18 + + +#define ICMP_NET_UNREACH 0 +#define ICMP_HOST_UNREACH 1 +#define ICMP_PROT_UNREACH 2 +#define ICMP_PORT_UNREACH 3 +#define ICMP_FRAG_NEEDED 4 +#define ICMP_SR_FAILED 5 +#define ICMP_NET_UNKNOWN 6 +#define ICMP_HOST_UNKNOWN 7 +#define ICMP_HOST_ISOLATED 8 +#define ICMP_NET_ANO 9 +#define ICMP_HOST_ANO 10 +#define ICMP_NET_UNR_TOS 11 +#define ICMP_HOST_UNR_TOS 12 +#define ICMP_PKT_FILTERED 13 +#define ICMP_PREC_VIOLATION 14 +#define ICMP_PREC_CUTOFF 15 +#define NR_ICMP_UNREACH 15 + +#define ICMP_REDIR_NET 0 +#define ICMP_REDIR_HOST 1 +#define ICMP_REDIR_NETTOS 2 +#define ICMP_REDIR_HOSTTOS 3 + +#define ICMP_EXC_TTL 0 +#define ICMP_EXC_FRAGTIME 1 + + +struct icmp_ra_addr { + uint32_t ira_addr; + uint32_t ira_preference; +}; + +struct icmp { + uint8_t icmp_type; + uint8_t icmp_code; + uint16_t icmp_cksum; + union { + uint8_t ih_pptr; + struct in_addr ih_gwaddr; + struct ih_idseq { + uint16_t icd_id; + uint16_t icd_seq; + } ih_idseq; + uint32_t ih_void; + + struct ih_pmtu { + uint16_t ipm_void; + uint16_t ipm_nextmtu; + } ih_pmtu; + + struct ih_rtradv { + uint8_t irt_num_addrs; + uint8_t irt_wpa; + uint16_t irt_lifetime; + } ih_rtradv; + } icmp_hun; + union { + struct { + uint32_t its_otime; + uint32_t its_rtime; + uint32_t its_ttime; + } id_ts; + struct { + struct ip idi_ip; + } id_ip; + struct icmp_ra_addr id_radv; + uint32_t id_mask; + uint8_t id_data[1]; + } icmp_dun; +}; + +#define icmp_pptr icmp_hun.ih_pptr +#define icmp_gwaddr icmp_hun.ih_gwaddr +#define icmp_id icmp_hun.ih_idseq.icd_id +#define icmp_seq icmp_hun.ih_idseq.icd_seq +#define icmp_void icmp_hun.ih_void +#define icmp_pmvoid icmp_hun.ih_pmtu.ipm_void +#define icmp_nextmtu icmp_hun.ih_pmtu.ipm_nextmtu +#define icmp_num_addrs icmp_hun.ih_rtradv.irt_num_addrs +#define icmp_wpa icmp_hun.ih_rtradv.irt_wpa +#define icmp_lifetime icmp_hun.ih_rtradv.irt_lifetime +#define icmp_otime icmp_dun.id_ts.its_otime +#define icmp_rtime icmp_dun.id_ts.its_rtime +#define icmp_ttime icmp_dun.id_ts.its_ttime +#define icmp_ip icmp_dun.id_ip.idi_ip +#define icmp_radv icmp_dun.id_radv +#define icmp_mask icmp_dun.id_mask +#define icmp_data icmp_dun.id_data + +#define ICMP_MINLEN 8 +#define ICMP_TSLEN (8 + 3 * sizeof (n_time)) +#define ICMP_MASKLEN 12 +#define ICMP_ADVLENMIN (8 + sizeof (struct ip) + 8) +#define ICMP_ADVLEN(p) (8 + ((p)->icmp_ip.ip_hl << 2) + 8) + +#define ICMP_UNREACH 3 +#define ICMP_SOURCEQUENCH 4 +#define ICMP_ROUTERADVERT 9 +#define ICMP_ROUTERSOLICIT 10 +#define ICMP_TIMXCEED 11 +#define ICMP_PARAMPROB 12 +#define ICMP_TSTAMP 13 +#define ICMP_TSTAMPREPLY 14 +#define ICMP_IREQ 15 +#define ICMP_IREQREPLY 16 +#define ICMP_MASKREQ 17 +#define ICMP_MASKREPLY 18 +#define ICMP_MAXTYPE 18 + +#define ICMP_UNREACH_NET 0 +#define ICMP_UNREACH_HOST 1 +#define ICMP_UNREACH_PROTOCOL 2 +#define ICMP_UNREACH_PORT 3 +#define ICMP_UNREACH_NEEDFRAG 4 +#define ICMP_UNREACH_SRCFAIL 5 +#define ICMP_UNREACH_NET_UNKNOWN 6 +#define ICMP_UNREACH_HOST_UNKNOWN 7 +#define ICMP_UNREACH_ISOLATED 8 +#define ICMP_UNREACH_NET_PROHIB 9 +#define ICMP_UNREACH_HOST_PROHIB 10 +#define ICMP_UNREACH_TOSNET 11 +#define ICMP_UNREACH_TOSHOST 12 +#define ICMP_UNREACH_FILTER_PROHIB 13 +#define ICMP_UNREACH_HOST_PRECEDENCE 14 +#define ICMP_UNREACH_PRECEDENCE_CUTOFF 15 + +#define ICMP_REDIRECT_NET 0 +#define ICMP_REDIRECT_HOST 1 +#define ICMP_REDIRECT_TOSNET 2 +#define ICMP_REDIRECT_TOSHOST 3 + +#define ICMP_TIMXCEED_INTRANS 0 +#define ICMP_TIMXCEED_REASS 1 + +#define ICMP_PARAMPROB_OPTABSENT 1 + +#define ICMP_INFOTYPE(type) \ + ((type) == ICMP_ECHOREPLY || (type) == ICMP_ECHO || \ + (type) == ICMP_ROUTERADVERT || (type) == ICMP_ROUTERSOLICIT || \ + (type) == ICMP_TSTAMP || (type) == ICMP_TSTAMPREPLY || \ + (type) == ICMP_IREQ || (type) == ICMP_IREQREPLY || \ + (type) == ICMP_MASKREQ || (type) == ICMP_MASKREPLY) + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/netinet/tcp.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/netinet/tcp.h new file mode 100644 index 0000000000000000000000000000000000000000..44a007aaf5a252f21f5e5c76ec5fafd69267cf69 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/netinet/tcp.h @@ -0,0 +1,282 @@ +#ifndef _NETINET_TCP_H +#define _NETINET_TCP_H + +#include + +#define TCP_NODELAY 1 +#define TCP_MAXSEG 2 +#define TCP_CORK 3 +#define TCP_KEEPIDLE 4 +#define TCP_KEEPINTVL 5 +#define TCP_KEEPCNT 6 +#define TCP_SYNCNT 7 +#define TCP_LINGER2 8 +#define TCP_DEFER_ACCEPT 9 +#define TCP_WINDOW_CLAMP 10 +#define TCP_INFO 11 +#define TCP_QUICKACK 12 +#define TCP_CONGESTION 13 +#define TCP_MD5SIG 14 +#define TCP_THIN_LINEAR_TIMEOUTS 16 +#define TCP_THIN_DUPACK 17 +#define TCP_USER_TIMEOUT 18 +#define TCP_REPAIR 19 +#define TCP_REPAIR_QUEUE 20 +#define TCP_QUEUE_SEQ 21 +#define TCP_REPAIR_OPTIONS 22 +#define TCP_FASTOPEN 23 +#define TCP_TIMESTAMP 24 +#define TCP_NOTSENT_LOWAT 25 +#define TCP_CC_INFO 26 +#define TCP_SAVE_SYN 27 +#define TCP_SAVED_SYN 28 +#define TCP_REPAIR_WINDOW 29 +#define TCP_FASTOPEN_CONNECT 30 +#define TCP_ULP 31 +#define TCP_MD5SIG_EXT 32 +#define TCP_FASTOPEN_KEY 33 +#define TCP_FASTOPEN_NO_COOKIE 34 +#define TCP_ZEROCOPY_RECEIVE 35 +#define TCP_INQ 36 +#define TCP_TX_DELAY 37 + +#define TCP_CM_INQ TCP_INQ + +#define TCP_ESTABLISHED 1 +#define TCP_SYN_SENT 2 +#define TCP_SYN_RECV 3 +#define TCP_FIN_WAIT1 4 +#define TCP_FIN_WAIT2 5 +#define TCP_TIME_WAIT 6 +#define TCP_CLOSE 7 +#define TCP_CLOSE_WAIT 8 +#define TCP_LAST_ACK 9 +#define TCP_LISTEN 10 +#define TCP_CLOSING 11 + +enum { + TCP_NLA_PAD, + TCP_NLA_BUSY, + TCP_NLA_RWND_LIMITED, + TCP_NLA_SNDBUF_LIMITED, + TCP_NLA_DATA_SEGS_OUT, + TCP_NLA_TOTAL_RETRANS, + TCP_NLA_PACING_RATE, + TCP_NLA_DELIVERY_RATE, + TCP_NLA_SND_CWND, + TCP_NLA_REORDERING, + TCP_NLA_MIN_RTT, + TCP_NLA_RECUR_RETRANS, + TCP_NLA_DELIVERY_RATE_APP_LMT, + TCP_NLA_SNDQ_SIZE, + TCP_NLA_CA_STATE, + TCP_NLA_SND_SSTHRESH, + TCP_NLA_DELIVERED, + TCP_NLA_DELIVERED_CE, + TCP_NLA_BYTES_SENT, + TCP_NLA_BYTES_RETRANS, + TCP_NLA_DSACK_DUPS, + TCP_NLA_REORD_SEEN, + TCP_NLA_SRTT, +}; + +#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE) +#define TCPOPT_EOL 0 +#define TCPOPT_NOP 1 +#define TCPOPT_MAXSEG 2 +#define TCPOPT_WINDOW 3 +#define TCPOPT_SACK_PERMITTED 4 +#define TCPOPT_SACK 5 +#define TCPOPT_TIMESTAMP 8 +#define TCPOLEN_SACK_PERMITTED 2 +#define TCPOLEN_WINDOW 3 +#define TCPOLEN_MAXSEG 4 +#define TCPOLEN_TIMESTAMP 10 + +#define SOL_TCP 6 + +#include +#include +#include + +typedef uint32_t tcp_seq; + +#define TH_FIN 0x01 +#define TH_SYN 0x02 +#define TH_RST 0x04 +#define TH_PUSH 0x08 +#define TH_ACK 0x10 +#define TH_URG 0x20 + +struct tcphdr { +#ifdef _GNU_SOURCE +#ifdef __GNUC__ + __extension__ +#endif + union { struct { + + uint16_t source; + uint16_t dest; + uint32_t seq; + uint32_t ack_seq; +#if __BYTE_ORDER == __LITTLE_ENDIAN + uint16_t res1:4; + uint16_t doff:4; + uint16_t fin:1; + uint16_t syn:1; + uint16_t rst:1; + uint16_t psh:1; + uint16_t ack:1; + uint16_t urg:1; + uint16_t res2:2; +#else + uint16_t doff:4; + uint16_t res1:4; + uint16_t res2:2; + uint16_t urg:1; + uint16_t ack:1; + uint16_t psh:1; + uint16_t rst:1; + uint16_t syn:1; + uint16_t fin:1; +#endif + uint16_t window; + uint16_t check; + uint16_t urg_ptr; + + }; struct { +#endif + + uint16_t th_sport; + uint16_t th_dport; + uint32_t th_seq; + uint32_t th_ack; +#if __BYTE_ORDER == __LITTLE_ENDIAN + uint8_t th_x2:4; + uint8_t th_off:4; +#else + uint8_t th_off:4; + uint8_t th_x2:4; +#endif + uint8_t th_flags; + uint16_t th_win; + uint16_t th_sum; + uint16_t th_urp; + +#ifdef _GNU_SOURCE + }; }; +#endif +}; +#endif + +#ifdef _GNU_SOURCE +#define TCPI_OPT_TIMESTAMPS 1 +#define TCPI_OPT_SACK 2 +#define TCPI_OPT_WSCALE 4 +#define TCPI_OPT_ECN 8 + +#define TCP_CA_Open 0 +#define TCP_CA_Disorder 1 +#define TCP_CA_CWR 2 +#define TCP_CA_Recovery 3 +#define TCP_CA_Loss 4 + +struct tcp_info { + uint8_t tcpi_state; + uint8_t tcpi_ca_state; + uint8_t tcpi_retransmits; + uint8_t tcpi_probes; + uint8_t tcpi_backoff; + uint8_t tcpi_options; + uint8_t tcpi_snd_wscale : 4, tcpi_rcv_wscale : 4; + uint8_t tcpi_delivery_rate_app_limited : 1; + uint32_t tcpi_rto; + uint32_t tcpi_ato; + uint32_t tcpi_snd_mss; + uint32_t tcpi_rcv_mss; + uint32_t tcpi_unacked; + uint32_t tcpi_sacked; + uint32_t tcpi_lost; + uint32_t tcpi_retrans; + uint32_t tcpi_fackets; + uint32_t tcpi_last_data_sent; + uint32_t tcpi_last_ack_sent; + uint32_t tcpi_last_data_recv; + uint32_t tcpi_last_ack_recv; + uint32_t tcpi_pmtu; + uint32_t tcpi_rcv_ssthresh; + uint32_t tcpi_rtt; + uint32_t tcpi_rttvar; + uint32_t tcpi_snd_ssthresh; + uint32_t tcpi_snd_cwnd; + uint32_t tcpi_advmss; + uint32_t tcpi_reordering; + uint32_t tcpi_rcv_rtt; + uint32_t tcpi_rcv_space; + uint32_t tcpi_total_retrans; + uint64_t tcpi_pacing_rate; + uint64_t tcpi_max_pacing_rate; + uint64_t tcpi_bytes_acked; + uint64_t tcpi_bytes_received; + uint32_t tcpi_segs_out; + uint32_t tcpi_segs_in; + uint32_t tcpi_notsent_bytes; + uint32_t tcpi_min_rtt; + uint32_t tcpi_data_segs_in; + uint32_t tcpi_data_segs_out; + uint64_t tcpi_delivery_rate; + uint64_t tcpi_busy_time; + uint64_t tcpi_rwnd_limited; + uint64_t tcpi_sndbuf_limited; + uint32_t tcpi_delivered; + uint32_t tcpi_delivered_ce; + uint64_t tcpi_bytes_sent; + uint64_t tcpi_bytes_retrans; + uint32_t tcpi_dsack_dups; + uint32_t tcpi_reord_seen; + uint32_t tcpi_rcv_ooopack; + uint32_t tcpi_snd_wnd; +}; + +#define TCP_MD5SIG_MAXKEYLEN 80 + +#define TCP_MD5SIG_FLAG_PREFIX 1 + +struct tcp_md5sig { + struct sockaddr_storage tcpm_addr; + uint8_t tcpm_flags; + uint8_t tcpm_prefixlen; + uint16_t tcpm_keylen; + uint32_t __tcpm_pad; + uint8_t tcpm_key[TCP_MD5SIG_MAXKEYLEN]; +}; + +struct tcp_diag_md5sig { + uint8_t tcpm_family; + uint8_t tcpm_prefixlen; + uint16_t tcpm_keylen; + uint32_t tcpm_addr[4]; + uint8_t tcpm_key[TCP_MD5SIG_MAXKEYLEN]; +}; + +#define TCP_REPAIR_ON 1 +#define TCP_REPAIR_OFF 0 +#define TCP_REPAIR_OFF_NO_WP -1 + +struct tcp_repair_window { + uint32_t snd_wl1; + uint32_t snd_wnd; + uint32_t max_window; + uint32_t rcv_wnd; + uint32_t rcv_wup; +}; + +struct tcp_zerocopy_receive { + uint64_t address; + uint32_t length; + uint32_t recv_skip_hint; +}; + +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/netinet/udp.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/netinet/udp.h new file mode 100644 index 0000000000000000000000000000000000000000..ffd8907962eb24708cc089d9ba7b6fb544cba521 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/netinet/udp.h @@ -0,0 +1,45 @@ +#ifndef _NETINET_UDP_H +#define _NETINET_UDP_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include + +#ifdef _GNU_SOURCE +#define uh_sport source +#define uh_dport dest +#define uh_ulen len +#define uh_sum check +#endif + +struct udphdr { + uint16_t uh_sport; + uint16_t uh_dport; + uint16_t uh_ulen; + uint16_t uh_sum; +}; + +#define UDP_CORK 1 +#define UDP_ENCAP 100 +#define UDP_NO_CHECK6_TX 101 +#define UDP_NO_CHECK6_RX 102 +#define UDP_SEGMENT 103 +#define UDP_GRO 104 + +#define UDP_ENCAP_ESPINUDP_NON_IKE 1 +#define UDP_ENCAP_ESPINUDP 2 +#define UDP_ENCAP_L2TPINUDP 3 +#define UDP_ENCAP_GTP0 4 +#define UDP_ENCAP_GTP1U 5 +#define UDP_ENCAP_RXRPC 6 + +#define SOL_UDP 17 + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/netpacket/packet.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/netpacket/packet.h new file mode 100644 index 0000000000000000000000000000000000000000..b36e092ad4fb6dc5aba83d86a826f261dc79dfb1 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/netpacket/packet.h @@ -0,0 +1,62 @@ +#ifndef _NETPACKET_PACKET_H +#define _NETPACKET_PACKET_H + +#ifdef __cplusplus +extern "C" { +#endif + +struct sockaddr_ll { + unsigned short sll_family, sll_protocol; + int sll_ifindex; + unsigned short sll_hatype; + unsigned char sll_pkttype, sll_halen; + unsigned char sll_addr[8]; +}; + +struct packet_mreq { + int mr_ifindex; + unsigned short int mr_type, mr_alen; + unsigned char mr_address[8]; +}; + +#define PACKET_HOST 0 +#define PACKET_BROADCAST 1 +#define PACKET_MULTICAST 2 +#define PACKET_OTHERHOST 3 +#define PACKET_OUTGOING 4 +#define PACKET_LOOPBACK 5 +#define PACKET_FASTROUTE 6 + +#define PACKET_ADD_MEMBERSHIP 1 +#define PACKET_DROP_MEMBERSHIP 2 +#define PACKET_RECV_OUTPUT 3 +#define PACKET_RX_RING 5 +#define PACKET_STATISTICS 6 +#define PACKET_COPY_THRESH 7 +#define PACKET_AUXDATA 8 +#define PACKET_ORIGDEV 9 +#define PACKET_VERSION 10 +#define PACKET_HDRLEN 11 +#define PACKET_RESERVE 12 +#define PACKET_TX_RING 13 +#define PACKET_LOSS 14 +#define PACKET_VNET_HDR 15 +#define PACKET_TX_TIMESTAMP 16 +#define PACKET_TIMESTAMP 17 +#define PACKET_FANOUT 18 +#define PACKET_TX_HAS_OFF 19 +#define PACKET_QDISC_BYPASS 20 +#define PACKET_ROLLOVER_STATS 21 +#define PACKET_FANOUT_DATA 22 +#define PACKET_IGNORE_OUTGOING 23 + +#define PACKET_MR_MULTICAST 0 +#define PACKET_MR_PROMISC 1 +#define PACKET_MR_ALLMULTI 2 +#define PACKET_MR_UNICAST 3 + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/nl_types.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/nl_types.h new file mode 100644 index 0000000000000000000000000000000000000000..7c2d48e0f145411c1ef1966cffe787a603894524 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/nl_types.h @@ -0,0 +1,22 @@ +#ifndef _NL_TYPES_H +#define _NL_TYPES_H + +#ifdef __cplusplus +extern "C" { +#endif + +#define NL_SETD 1 +#define NL_CAT_LOCALE 1 + +typedef int nl_item; +typedef void *nl_catd; + +nl_catd catopen (const char *, int); +char *catgets (nl_catd, int, int, const char *); +int catclose (nl_catd); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/paths.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/paths.h new file mode 100644 index 0000000000000000000000000000000000000000..67de6b3c3263eb50076ce1170fe7b2dd3084fa27 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/paths.h @@ -0,0 +1,31 @@ +#ifndef _PATHS_H +#define _PATHS_H + +#define _PATH_DEFPATH "/usr/local/bin:/bin:/usr/bin" +#define _PATH_STDPATH "/bin:/usr/bin:/sbin:/usr/sbin" + +#define _PATH_BSHELL "/bin/sh" +#define _PATH_CONSOLE "/dev/console" +#define _PATH_DEVNULL "/dev/null" +#define _PATH_KLOG "/proc/kmsg" +#define _PATH_LASTLOG "/var/log/lastlog" +#define _PATH_MAILDIR "/var/mail" +#define _PATH_MAN "/usr/share/man" +#define _PATH_MNTTAB "/etc/fstab" +#define _PATH_MOUNTED "/etc/mtab" +#define _PATH_NOLOGIN "/etc/nologin" +#define _PATH_SENDMAIL "/usr/sbin/sendmail" +#define _PATH_SHADOW "/etc/shadow" +#define _PATH_SHELLS "/etc/shells" +#define _PATH_TTY "/dev/tty" +#define _PATH_UTMP "/dev/null/utmp" +#define _PATH_VI "/usr/bin/vi" +#define _PATH_WTMP "/dev/null/wtmp" + +#define _PATH_DEV "/dev/" +#define _PATH_TMP "/tmp/" +#define _PATH_VARDB "/var/lib/misc/" +#define _PATH_VARRUN "/var/run/" +#define _PATH_VARTMP "/var/tmp/" + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/poll.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/poll.h new file mode 100644 index 0000000000000000000000000000000000000000..daf6b6f5784ef2c3c603385a5eb1f46c25e653c6 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/poll.h @@ -0,0 +1,60 @@ +#ifndef _POLL_H +#define _POLL_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#include + +#define POLLIN 0x001 +#define POLLPRI 0x002 +#define POLLOUT 0x004 +#define POLLERR 0x008 +#define POLLHUP 0x010 +#define POLLNVAL 0x020 +#define POLLRDNORM 0x040 +#define POLLRDBAND 0x080 +#ifndef POLLWRNORM +#define POLLWRNORM 0x100 +#define POLLWRBAND 0x200 +#endif +#ifndef POLLMSG +#define POLLMSG 0x400 +#define POLLRDHUP 0x2000 +#endif + +#ifdef __LITEOS__ +typedef unsigned int pollevent_t; +#endif +typedef unsigned long nfds_t; + +struct pollfd { + int fd; + short events; + short revents; +}; + +int poll (struct pollfd *, nfds_t, int); + +#ifdef _GNU_SOURCE +#define __NEED_time_t +#define __NEED_struct_timespec +#define __NEED_sigset_t +#include +int ppoll(struct pollfd *, nfds_t, const struct timespec *, const sigset_t *); +#endif + +#if _REDIR_TIME64 +#ifdef _GNU_SOURCE +__REDIR(ppoll, __ppoll_time64); +#endif +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/pthread.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/pthread.h new file mode 100644 index 0000000000000000000000000000000000000000..04e144aa5bbca8434ffe550a41fe6546235a8753 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/pthread.h @@ -0,0 +1,1281 @@ +/** + * @defgroup posix POSIX + * @defgroup pthread Thread + * @ingroup posix + */ + +#ifndef _PTHREAD_H +#define _PTHREAD_H +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef __LITEOS__ +#include "bits/pthread_types.h" +#include "los_list.h" +#include "los_task_pri.h" +#endif + +#include + +#ifdef __LITEOS__ +typedef struct { + LOS_DL_LIST stMuxList; /**< Mutex blocking linked list*/ + LosTaskCB* pstOwner; /**< Task that involves the mutex*/ + UINT16 usMuxCount; /**< Mutex counter value*/ +} MUX_CB_P; +#endif + +#define __NEED_time_t +#define __NEED_clockid_t +#define __NEED_struct_timespec +#define __NEED_sigset_t +#define __NEED_pthread_t +#define __NEED_pthread_attr_t +#define __NEED_pthread_mutexattr_t +#define __NEED_pthread_condattr_t +#define __NEED_pthread_rwlockattr_t +#define __NEED_pthread_barrierattr_t +#define __NEED_pthread_mutex_t +#define __NEED_pthread_cond_t +#define __NEED_pthread_rwlock_t +#define __NEED_pthread_barrier_t +#define __NEED_pthread_spinlock_t +#define __NEED_pthread_key_t +#define __NEED_pthread_once_t +#define __NEED_size_t + + +#include + +#include +#include + +#ifdef __LITEOS__ +typedef struct pthread_mutexattr { + UINT8 protocol; /**< Mutex protocol. The value range is [0, 2].*/ + UINT8 prioceiling; /**< Upper priority limit of a mutex. The value range is [0, 31].*/ + UINT8 type; /**< Mutex type. The value range is [0, 2].*/ + UINT8 reserved; /**< Reserved.*/ +} pthread_mutexattr_t; + +typedef struct pthread_mutex { + pthread_mutexattr_t stAttr; /**< Mutex attributes object*/ + MUX_CB_P stLock; /**< Mutex operation object*/ +} pthread_mutex_t; + +typedef struct { + clockid_t clock; +} pthread_condattr_t; + +typedef struct pthread_cond { + volatile int count; /**< The number of tasks blocked by condition */ + EVENT_CB_S event; /**< Event object*/ + pthread_mutex_t* mutex; /**< Mutex locker for condition variable protection */ + volatile int value; /**< Condition variable state value*/ +} pthread_cond_t; +#endif + +#define PTHREAD_CREATE_JOINABLE 0 +#define PTHREAD_CREATE_DETACHED 1 + +#define PTHREAD_MUTEX_NORMAL 0 +#define PTHREAD_MUTEX_DEFAULT 0 +#define PTHREAD_MUTEX_RECURSIVE 1 +#define PTHREAD_MUTEX_ERRORCHECK 2 +#ifdef __LITEOS__ +#define PTHREAD_MUTEX_RECURSIVE_NP 1 +#define PTHREAD_MUTEX_ERRORCHECK_NP 2 +#endif + +#define PTHREAD_MUTEX_STALLED 0 +#define PTHREAD_MUTEX_ROBUST 1 + +#define PTHREAD_PRIO_NONE 0 +#define PTHREAD_PRIO_INHERIT 1 +#define PTHREAD_PRIO_PROTECT 2 + +#define PTHREAD_INHERIT_SCHED 0 +#define PTHREAD_EXPLICIT_SCHED 1 + +#define PTHREAD_SCOPE_SYSTEM 0 +#define PTHREAD_SCOPE_PROCESS 1 + +/** + * @ingroup pthread + * Define a condition variable to be shared between threads within the same process. + */ +#define PTHREAD_PROCESS_PRIVATE 0 + +/** + * @ingroup pthread + * Define a condition variable to be shared among multiple processes. + */ +#define PTHREAD_PROCESS_SHARED 1 + +#ifdef __LITEOS__ +#define PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP \ + { { PTHREAD_PRIO_INHERIT, OS_TASK_PRIORITY_LOWEST, PTHREAD_MUTEX_RECURSIVE_NP, 0 }, \ + { { (struct LOS_DL_LIST *)NULL, (struct LOS_DL_LIST *)NULL }, \ + (LosTaskCB *)NULL, 0 } } + +#define PTHREAD_MUTEX_INITIALIZER \ + { { PTHREAD_PRIO_INHERIT, OS_TASK_PRIORITY_LOWEST, 0, 0 }, \ + { { (struct LOS_DL_LIST *)NULL, (struct LOS_DL_LIST *)NULL }, \ + (LosTaskCB *)NULL, 0 } } + +#define PTHREAD_COND_INITIALIZER { -1, { 0, { NULL, NULL } }, NULL, -1 } +#endif + +#define PTHREAD_RWLOCK_INITIALIZER {{{0}}} +#define PTHREAD_ONCE_INIT 0 + + +#define PTHREAD_CANCEL_ENABLE 0 +#define PTHREAD_CANCEL_DISABLE 1 +#define PTHREAD_CANCEL_MASKED 2 + +#define PTHREAD_CANCEL_DEFERRED 0 +#define PTHREAD_CANCEL_ASYNCHRONOUS 1 + +#define PTHREAD_CANCELED ((void *)-1) + + +#define PTHREAD_BARRIER_SERIAL_THREAD (-1) + + +int pthread_create(pthread_t *__restrict, const pthread_attr_t *__restrict, void *(*)(void *), void *__restrict); + +/** + * @ingroup pthread + * + * @par Description: + * This API is used to mark a thread as detached. When a detached thread terminates, its resources are automatically released back to Huawei LiteOS without the need for another thread to join with the terminated thread. + * + * @param pthread [IN] ID of the thread to be marked as detached. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #int If the call succeeds, pthread_detach() shall return 0; otherwise, an error number shall be returned to indicate the error. + * + * @retval #ESRCH The target thread cannot be marked (the thread does not exist or has exited). + * @retval #EINVAL The target thread is already marked as detached. + * @retval #ENOERR The thread is successfully marked. + * + * @par Dependency: + *
      • pthread.h
      + * @see pthread_join + */ +int pthread_detach(pthread_t); +#ifndef __LITEOS__ +_Noreturn void pthread_exit(void *); +#else +/** + * @ingroup pthread + * + * @par Description: + * This API is used to terminate the current thread, and the return value contains only one parameter. + * + * @param retval [OUT] Pointer to the thread return value. + * + * @attention + *
        + *
      • Thread termination does not release any application visible process resources, including, but not limited to, + * mutexes and file descriptors.
      • + *
      + * + * @retval #void None. + * + * @par Dependency: + *
      • pthread.h
      + * @see pthread_create | pthread_join + */ +void pthread_exit(void *); +#endif + +/* Wait for the thread to terminate. If thread_return is not NULL then + * the retval from the thread's call to pthread_exit() is stored at thread_return. + */ +/** + * @ingroup pthread + * + * @par Description: + * This API is used to wait for a thread to terminate and reclaim its resources. + * + * @param pthread [IN] ID of the target thread (the waited thread). + * @param thread_return [OUT] Return value sent to the waiting thread. + * + * @attention + *
        + *
      • A thread cannot be waited for by multiple threads. If a thread is waited for by multiple threads, ESRCH will be returned.
      • + *
      + * + * @retval #int If successful, the pthread_join() function shall return zero; otherwise, an error number shall be returned to indicate the error. + * + * @retval #ESRCH The target thread is not joinable (the thread does not exist, or has exited, or is waited for by another thread). + * @retval #EDEADLK A deadlock results because a thread is waiting for itself to terminate. + * @retval #EINVAL The target thread is not joinable. + * @retval #ENOERR The target thread is successfully joined with. + * + * @par Dependency: + *
      • pthread.h
      + * @see pthread_detach + */ +int pthread_join(pthread_t, void **); + +#ifdef __GNUC__ +__attribute__((const)) +#endif + +/** + * @ingroup pthread + * + * @par Description: + * This API is used to acquire the thread identifier of the calling thread. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval pthread_t Thread ID [0,LOSCFG_BASE_CORE_TSK_LIMIT]. + * + * @par Dependency: + *
      • pthread.h
      + * @see None + */ +pthread_t pthread_self(void); + +/* Compare two thread identifiers. */ +/** + * @ingroup pthread + * + * @par Description: + * This API is used to compare whether two thread IDs belong to the same thread. + * + * @param thread1 [IN] ID of the thread 1 being compared. + * @param thread2 [IN] ID of the thread 2 being compared. + * + * @attention + *
        + *
      • Just compare the thread ID, not judge the validity of the thread ID.
      • + *
      + * + * @retval #int Any value other than 0 mean that two threads are equal. + * @retval #0 The two threads are unequal. + * + * @par Dependency: + *
      • pthread.h
      + * @see None + */ +int pthread_equal(pthread_t, pthread_t); +#ifndef __cplusplus +#define pthread_equal(x,y) ((x)==(y)) +#endif + +int pthread_setcancelstate(int, int *); +int pthread_setcanceltype(int, int *); +void pthread_testcancel(void); +int pthread_cancel(pthread_t); + +/* Get scheduling policy and parameters for the thread */ +/** + * @ingroup pthread + * + * @par Description: + * This API is used to acquire the scheduling policy and priority of a thread. + * + * @param pthread [IN] ID of the thread whose scheduling policy is to be read. + * @param policy [OUT] Acquired scheduling policy. + * @param param [OUT] Acquired scheduling priority. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #int If successful, the pthread_getschedparam() function shall return zero; otherwise, an error number shall be returned to indicate the error. + * + * @retval #EINVAL invalid parameter. + * @retval #ENOERR The scheduling policy and priority of the thread is successfully acquired. + * + * @par Dependency: + *
      • pthread.h
      + * @see pthread_setschedparam + */ +int pthread_getschedparam(pthread_t, int *__restrict, struct sched_param *__restrict); + +/* Set scheduling policy and parameters for the thread */ +/** + * @ingroup pthread + * + * @par Description: + * This API is used to set the scheduling policy and priority of a thread. + * + * @param pthread [IN] ID of the thread whose scheduling policy is to be set. + * @param policy [IN] Specified scheduling policy. + * @param param [IN] Pointer to the scheduling priority. + * + * @attention + *
        + *
      • The scheduling policy must be SCHED_OTHER, SCHED_FIFO, or SCHED_RR.
      • + *
      • Only SCHED_RR is supported now. An error code will be returned if the value is set to the other two scheduling policies.
      • + *
      • The content priority specified by the param parameter must fall within the OS priority range[0,31].
      • + *
      • A smaller priority value indicates a higher priority.
      • + *
      + * + * @retval #int If successful, the pthread_setschedparam() function shall return zero; otherwise, an error number shall be returned to indicate the error. + * + * @retval #EINVAL invalid parameter. + * @retval #ENOERR The scheduling policy and priority of the thread is successfully set. + * + * @par Dependency: + *
      • pthread.h
      + * @see pthread_getschedparam + */ +int pthread_setschedparam(pthread_t, int, const struct sched_param *); +int pthread_setschedprio(pthread_t, int); + +/* Call init_routine just the once per control variable. */ +/** + * @ingroup pthread + * + * @par Decription: + * This API is used to call the initialization routine at most once. + * + * @param once_control [IN/OUT] Once-control parameter. + * @param init_routine [IN] Initialization routine function. + * + * @attention + *
        + *
      • The control variable once_control must be statically initialized using PTHREAD_ONCE_INIT. Otherwise, this API will not work as expected.
      • + *
      + * + * @retval #int Upon successful completion, pthread_once() shall return zero; otherwise, an error number shall be returned to indicate the error. + * @retval #EINVAL One or more parameters are invalid. + * + * @par Dependency: + *
      • pthread.h
      + * @see None + */ +int pthread_once(pthread_once_t *, void (*)(void)); + +int pthread_mutex_init(pthread_mutex_t *__restrict, const pthread_mutexattr_t *__restrict); +int pthread_mutex_lock(pthread_mutex_t *); +int pthread_mutex_unlock(pthread_mutex_t *); +int pthread_mutex_trylock(pthread_mutex_t *); +int pthread_mutex_timedlock(pthread_mutex_t *__restrict, const struct timespec *__restrict); +int pthread_mutex_destroy(pthread_mutex_t *); +int pthread_mutex_consistent(pthread_mutex_t *); + +int pthread_mutex_getprioceiling(const pthread_mutex_t *__restrict, int *__restrict); +int pthread_mutex_setprioceiling(pthread_mutex_t *__restrict, int, int *__restrict); + +/** + * @ingroup pthread + * @par Description: + * This API is used to initialize a condition variable. + * + * @param cond [OUT] Condition variable object. + * @param attr [IN] Condition variable attribute. The passed value and the default value of this parameter can be only set to PTHREAD_PROCESS_PRIVATE. + * + * @attention + *
        + *
      • A condition variable cannot be initialized by multiple threads. When a condition variable needs to be reinitialized, it must not have been used.
      • + *
      + * + * @retval #EINVAL One or more parameters are invalid. + * @retval #ENOERR The condition variable is successfully initialized. + * @retval #ENOMEM Failed to allocate in-memory resources for the operation. + * + * @par Dependency: + *
      • pthread.h
      + * + * @see pthread_cond_destroy + * + */ +int pthread_cond_init(pthread_cond_t *__restrict, const pthread_condattr_t *__restrict); + +/** + * @ingroup pthread + * @par Description: + * This API is used to destroy a condition variable. + * + * @param cond [IN] Condition variable object. + * + * @attention + *
        + *
      • The condition variable is using memory and not destroyed.
      • + *
      + * + * @retval #ENVAIL The parameter is invalid. + * @retval #EBUSY The condition variable is being in use. + * @retval #ENOERR The condition variable is successfully destroyed. + * + * @par Dependency: + *
      • pthread.h
      + * + * @see pthread_cond_init + * + */ +int pthread_cond_destroy(pthread_cond_t *); + +/** + * @ingroup pthread + * @par Description: + * A thread has been being blocked on a condition variable and waits to be awoken by the condition variable. + * + * @param cond [IN] Condition variable object. + * @param mutex [IN] Mutex object. + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #ENVAIL One or more parameters are invalid. + * @retval #ENOERR The thread is successfully awoken. + * + * @par Dependency: + *
      • pthread.h
      + * + * @see pthread_cond_signal | pthread_cond_broadcast + * + */ +int pthread_cond_wait(pthread_cond_t *__restrict, pthread_mutex_t *__restrict); + +/** + * @ingroup pthread + * @par Description: + * A thread has been being blocked on a condition variable and is awoken until the set relative time has passed or the thread obtains a condition variable. + * + * @param cond [IN] Condition variable object. + * @param mutex [IN] Mutex object. + * @param abstime [IN] Time object. + * + * @attention + *
        + *
      • The waiting time is a relative time.
      • + *
      • Setting the timeout interval to a past time period is not supported.
      • + *
      + * + * @retval #ENOERR The thread receives a signal and is successfully awoken. + * @retval #ENVAIL One or more parameters are invalid. + * @retval #ETIMEDOUT The waiting time has passed. + * @retval #ENOMEM Failed to allocate in-memory resources for the operation. + * + * @par Dependency: + *
      • pthread.h
      + * + * @see pthread_cond_wait + * + */ +int pthread_cond_timedwait(pthread_cond_t *__restrict, pthread_mutex_t *__restrict, const struct timespec *__restrict); + +/** + * @ingroup pthread + * @par Description: + * This API is used to unblock all threads blocked on a condition variable and wake all these threads. + * + * @param cond [IN] Condition variable object. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #ENVAIL The parameter is invalid. + * @retval #ENOERR All threads blocked on this condition variable are successfully unblocked. + * + * @par Dependency: + *
      • pthread.h
      + * + * @see pthread_cond_wait + * + */ +int pthread_cond_broadcast(pthread_cond_t *); + +/** + * @ingroup pthread + * @par Description: + * This API is used to unblock a thread blocked on a condition variable and wakes this thread. + * + * @param cond [IN] Condition variable object. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #ENVAIL The parameter is invalid. + * @retval #ENOERR The thread is successfully unlocked. + * + * @par Dependency: + *
      • pthread.h
      + * + * @see pthread_cond_wait + * + */ +int pthread_cond_signal(pthread_cond_t *); + +int pthread_rwlock_init(pthread_rwlock_t *__restrict, const pthread_rwlockattr_t *__restrict); +int pthread_rwlock_destroy(pthread_rwlock_t *); +int pthread_rwlock_rdlock(pthread_rwlock_t *); +int pthread_rwlock_tryrdlock(pthread_rwlock_t *); +int pthread_rwlock_timedrdlock(pthread_rwlock_t *__restrict, const struct timespec *__restrict); +int pthread_rwlock_wrlock(pthread_rwlock_t *); +int pthread_rwlock_trywrlock(pthread_rwlock_t *); +int pthread_rwlock_timedwrlock(pthread_rwlock_t *__restrict, const struct timespec *__restrict); +int pthread_rwlock_unlock(pthread_rwlock_t *); + +int pthread_spin_init(pthread_spinlock_t *, int); +int pthread_spin_destroy(pthread_spinlock_t *); +int pthread_spin_lock(pthread_spinlock_t *); +int pthread_spin_trylock(pthread_spinlock_t *); +int pthread_spin_unlock(pthread_spinlock_t *); + +int pthread_barrier_init(pthread_barrier_t *__restrict, const pthread_barrierattr_t *__restrict, unsigned); +int pthread_barrier_destroy(pthread_barrier_t *); +int pthread_barrier_wait(pthread_barrier_t *); +int pthread_key_create(pthread_key_t *, void (*)(void *)); +int pthread_key_delete(pthread_key_t); +void *pthread_getspecific(pthread_key_t); +int pthread_setspecific(pthread_key_t, const void *); + +/* Thread attribute handling. */ + +/** + * @ingroup pthread + * + * @par Description: + * This API is used to initialize a thread attributes object into default attributes. + * + * @param attr [IN] Pointer to the thread attributes object to be initialized. + * + * @attention + *
        + *
      • Default thread attributes
      • + *
      • detachstate = PTHREAD_CREATE_JOINABLE
      • + *
      • schedpolicy = SCHED_RR
      • + *
      • schedparam.sched_priority = LOSCFG_BASE_CORE_TSK_DEFAULT_PRIO
      • + *
      • inheritsched = PTHREAD_INHERIT_SCHED
      • + *
      • scope = PTHREAD_SCOPE_SYSTEM
      • + *
      • stackaddr_set = 0
      • + *
      • stackaddr = NULL
      • + *
      • stacksize_set = 1
      • + *
      • stacksize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE
      • + *
      + * + * @retval #int Upon successful completion, pthread_attr_init() shall return a value of 0; otherwise, an error number shall be returned to indicate the error. + * + * @retval #EINVAL The input parameter is NULL. + * @retval #ENOERR The thread attributes object is successfully initialized. + * + * @par Dependency: + *
      • pthread.h
      + * @see pthread_attr_destroy + */ +int pthread_attr_init(pthread_attr_t *); + +/* Destroy thread attributes object */ +/** + * @ingroup pthread + * + * @par Dependency: + * This API is used to destroy a thread attributes object. + * + * @param attr [IN] Pointer to the thread attributes object to be destroyed. + * + * @attention + *
        + *
      • This API does not take effect on Huawei LiteOS. In fact, nothing has been done in this API.
      • + *
      + * + * @retval #int Upon successful completion, pthread_attr_destroy() shall return a value of 0; otherwise, an error number shall be returned to indicate the error. + * + * @retval #EINVAL The input parameter is NULL. + * @retval #ENOERR The thread attributes object is successfully destroyed. + * + * @par Dependency: + *
      • pthread.h
      + * @see pthread_attr_init + */ +int pthread_attr_destroy(pthread_attr_t *); + +int pthread_attr_getguardsize(const pthread_attr_t *__restrict, size_t *__restrict); +int pthread_attr_setguardsize(pthread_attr_t *, size_t); + +/* Get current minimal stack size. */ +/** + * @ingroup pthread + * + * @par Description: + * This API is used to acquire the stack size attribute of a thread attribute object. + * + * @param attr [IN] Pointer to the thread attributes object to be read. + * @param stacksize [OUT] Pointer to the acquired stack size. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #int Upon successful completion, pthread_attr_getstacksize() shall return a value of 0; otherwise, an error number shall be returned to indicate the error. + * The pthread_attr_getstacksize() function stores the stacksize attribute value in stacksize if successful. + * + * @retval #EINVAL invalid parameter, or the stack size left unspecified. + * @retval #ENOERR The stack size attribute is successfully acquired. + * + * @par Dependency: + *
      • pthread.h
      + * @see pthread_attr_setstacksize + */ +int pthread_attr_getstacksize(const pthread_attr_t *__restrict, size_t *__restrict); + +/* Set minimum creation stack size. */ +/** + * @ingroup pthread + * + * @par Description: + * This API is used to set the stack size attribute of a thread attribute object. + * + * @param attr [OUT] Pointer to the thread attributes object to be set. + * @param stacksize [IN] Specified stack size. + * + * @attention + *
        + *
      • The stack size must fall within an appropriate range and be greater than PTHREAD_STACK_MIN. + * If the stack size attribute is left unspecified, the default stack size will be used.
      • + *
      + * + * @retval #int Upon successful completion, pthread_attr_setstacksize() shall return a value of 0; otherwise, an error number shall be returned to indicate the error. + * + * @retval #EINVAL invalid parameter. + * @retval #ENOERR The stack size attribute is successfully set. + * + * @par Dependency: + *
      • pthread.h
      + * @see pthread_attr_getstacksize + */ +int pthread_attr_setstacksize(pthread_attr_t *, size_t); + +/* Get the detachstate attribute */ +/** + * @ingroup pthread + * + * @par Description: + * This API is used to acquire the detach state attribute of a thread attributes object. + * + * @param attr [IN] Pointer to the thread attributes object to be read. + * @param detachstate [OUT] Pointer to the acquired detach state attribute. + * + * @attention + *
        + *
      • Detachstate shall be set to either PTHREAD_CREATE_DETACHED or PTHREAD_CREATE_JOINABLE.
      • + *
      + * + * @retval int Upon successful completion, pthread_attr_getdetachstate() shall return a value of 0; otherwise, an error number shall be returned to indicate the error. + * The pthread_attr_getdetachstate() function stores the value of the detachstate attribute in detachstate if successful. + * + * @retval #EINVAL invalid parameter. + * @retval #ENOERR The detach state attribute is successfully acquired. + * + * @par Dependency: + *
      • pthread.h
      + * @see pthread_attr_setdetachstate + */ +int pthread_attr_getdetachstate(const pthread_attr_t *, int *); + +/* Set the detachstate attribute */ +/** + * @ingroup pthread + * + * @par Description: + * This API is used to set the detach state attribute of a thread attributes object. + * + * @param attr [OUT] Pointer to the thread attributes object to be set. + * @param detachstate [IN] Detach state attribute. + * + * @attention + *
        + *
      • The detach state attribute must be either PTHREAD_CREATE_JOINABLE or PTHREAD_CREATE_DETACHED. Otherwise, the attempt to set the detach state attribute will fail.
      • + *
      + * + * @retval #int Upon successful completion, pthread_attr_setdetachstate() shall return a value of 0; otherwise, an error number shall be returned to indicate the error. + * + * @retval #EINVAL invalid parameter. + * @retval #ENOERR The detach state attribute is successfully set. + * + * @par Dependency: + *
      • pthread.h
      + * @see pthread_attr_getdetachstate + */ +int pthread_attr_setdetachstate(pthread_attr_t *, int); +int pthread_attr_getstack(const pthread_attr_t *__restrict, void **__restrict, size_t *__restrict); +int pthread_attr_setstack(pthread_attr_t *, void *, size_t); + +#ifdef __LITEOS__ +/* Set starting address of stack. Whether this is at the start or end of + * the memory block allocated for the stack depends on whether the stack + * grows up or down. + */ +/** + * @ingroup pthread + * + * @par Description: + * This API is used to set the stack address attribute of a thread attributes object. This attribute specifies the start address of a stack. + * + * @param attr [OUT] Pointer to the thread attributes object to be set. + * @param stackaddr [IN] Specified stack address. + * + * @attention + *
        + *
      • This API does not take effect on Huawei LiteOS Kernel.
      • + *
      + * + * @retval #int Upon successful completion, pthread_attr_setstackaddr() shall return a value of 0; otherwise, an error number shall be returned to indicate the error. + * + * @retval #EINVAL invalid parameter. + * @retval #ENOERR The stack address attribute is successfully set. + * + * @par Dependency: + *
      • pthread.h
      + * @see pthread_attr_getstackaddr + */ +int pthread_attr_setstackaddr(pthread_attr_t *, void *); + +/* Get any previously set stack address. */ +/** + * @ingroup pthread + * + * @par Description: + * This API is used to acquire the stack address attribute of a thread attributes object. This attribute specifies the starting address of a stack. + * + * @param attr [IN] Pointer to the thread attributes object to be read. + * @param stackaddr [OUT] Pointer to the acquired starting address of stack. + * + * @attention + *
        + *
      • This API does not take effect on Huawei LiteOS Kernel.
      • + *
      + * + * @retval #int Upon successful completion, pthread_attr_getstackaddr() shall return a value of 0; otherwise, an error number shall be returned to indicate the error. + * + * @retval #EINVAL invalid parameter. + * @retval #ENOERR The stack address attribute is successfully acquired. + * + * @par Dependency: + *
      • pthread.h
      + * @see pthread_attr_setstackaddr + */ +int pthread_attr_getstackaddr(const pthread_attr_t *, void **); +#endif + +/* Get scheduling contention scope */ +/** + * @ingroup pthread + * + * @par Description: + * This API is used to acquire the contention scope attribute of a thread attributes object. + * + * @param attr [IN] Pointer to the thread attributes object to be read. + * @param scope [OUT] Pointer to the acquired contention scope attribute. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #int If successful, the pthread_attr_getscope() function shall return zero; otherwise, an error number shall be returned to indicate the error. + * + * @retval #EINVAL invalid parameter. + * @retval #ENOERR The contention scope attribute is successfully acquired. + * + * @par Dependency: + *
      • pthread.h
      + * @see pthread_attr_setscope + */ +int pthread_attr_getscope(const pthread_attr_t *__restrict, int *__restrict); + +/* Set scheduling contention scope */ +/** + * @ingroup pthread + * + * @par Description: + * This API is used to set the contention scope attribute of a thread attributes object. + * + * @param attr [OUT] Pointer to the thread attributes object to be set. + * @param scope [IN] Contention scope attribute. + * + * @attention + *
        + *
      • The contention scope attribute can only be PTHREAD_SCOPE_SYSTEM. PTHREAD_SCOPE_PROCES is not supported.
      • + *
      + * + * @retval #int If successful, the pthread_attr_setscope() function shall return zero; otherwise, an error number shall be returned to indicate the error. + * + * @retval #EINVAL invalid parameter. + * @retval #ENOTSUP The specified contention scope attribute value is not supported. + * @retval #ENOERR The contention scope attribute is successfully set. + * + * @par Dependency: + *
      • pthread.h
      + * @see pthread_attr_getscope + */ +int pthread_attr_setscope(pthread_attr_t *, int); + +/* Get scheduling policy */ +/** + * @ingroup pthread + * + * @par Description: + * This API is used to acquire the scheduling policy attribute of a thread attributes object. + * + * @param attr [IN] Pointer to the thread attributes object to be read. + * @param policy [OUT] Pointer to the acquired scheduling policy attribute. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #int If successful, the pthread_attr_getschedpolicy() function shall return zero; otherwise, an error number shall be returned to indicate the error. + * + * @retval #EINVAL invalid parameter. + * @retval #ENOERR The scheduling policy attribute is successfully obtained. + * + * @par Dependency: + *
      • pthread.h
      + * @see pthread_attr_setschedpolicy + */ +int pthread_attr_getschedpolicy(const pthread_attr_t *__restrict, int *__restrict); + +/* Set scheduling policy */ +/** + * @ingroup pthread + * + * @par Description: + * This API is used to set the scheduling policy attribute of a thread attributes object. + * + * @param attr [OUT] Pointer to the thread attributes object to be set. + * @param policy [IN] Scheduling policy attribute. + * + * @attention + *
        + *
      • The scheduling policy attribute is SCHED_OTHER, SCHED_FIFO, or SCHED_RR.
      • + *
      • Only SCHED_RR is supported now. An error code will be returned if the value is set to the other two scheduling policies.
      • + *
      + * + * @retval #int If successful, the pthread_attr_setschedpolicy() function shall return zero; otherwise, an error number shall be returned to indicate the error. + * + * @retval #EINVAL invalid parameter. + * @retval #ENOERR The scheduling policy attribute is successfully set. + * + * @par Dependency: + *
      • pthread.h
      + * @see pthread_attr_getschedpolicy + */ +int pthread_attr_setschedpolicy(pthread_attr_t *, int); + +/* Get scheduling parameters */ +/** + * @ingroup pthread + * + * @par Description: + * This API is used to acquire the scheduling parameter attributes of a thread attributes object. The scheduling parameter attributes indicate the thread priorities. + * + * @param attr [IN] Pointer to the thread attributes object to be read. + * @param param [OUT] Pointer to the acquired scheduling parameter attributes object. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #int If successful, the pthread_attr_getschedparam() function shall return zero; otherwise, an error number shall be returned to indicate the error. + * + * @retval #EINVAL invalid parameter. + * @retval #ENOERR The scheduling parameter attributes are successfully acquired. + * + * @par Dependency: + *
      • pthread.h
      + * @see pthread_attr_setschedparam + */ +int pthread_attr_getschedparam(const pthread_attr_t *__restrict, struct sched_param *__restrict); + +/* Set scheduling parameters */ +/** + * @ingroup pthread + * + * @par Description: + * This API is used to set the scheduling parameter attributes of a thread attributes object. The scheduling parameter attributes indicate thread priorities. + * + * @param attr [OUT] Pointer to the thread attributes object to be set. + * @param param [IN] Pointer to the scheduling parameter attributes object. + * + *@attention + *
        + *
      • The priority of the scheduling parameter attributes must be in the range of [0, 31].
      • + *
      + * + * @retval #int If successful, the pthread_attr_setschedparam() function shall return zero; otherwise, an error number shall be returned to indicate the error. + * + * @retval #EINVAL invalid parameter. + * @retval #ENOTSUP made to set the attribute to an unsupported value. + * @retval #ENOERR The scheduling parameter attributes are successfully set. + * + * @par Dependency: + *
      • pthread.h
      + * @see pthread_attr_getschedparam + */ +int pthread_attr_setschedparam(pthread_attr_t *__restrict, const struct sched_param *__restrict); + +/* Get scheduling inheritance attribute */ +/** + * @ingroup pthread + * + * @par Description: + * This API is used to acquire the inherit scheduler attribute of a thread attributes object. + * + * @param attr [IN] Pointer to the thread attributes object to be read. + * @param inherit [OUT] Pointer to the acquired inherit scheduler attribute. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #int If successful, the pthread_attr_getinheritsched() function shall return zero; otherwise, an error number shall be returned to indicate the error. + * + * @retval #EINVAL invalid parameter. + * @retval #ENOERR The inherit scheduler attribute is successfully acquired. + * + * @par Dependency: + *
      • pthread.h
      + * @see pthread_attr_setinheritsched + */ +int pthread_attr_getinheritsched(const pthread_attr_t *__restrict, int *__restrict); + +/* Set scheduling inheritance attribute */ +/** + * @ingroup pthread + * + * @par Description: + * This API is used to set the inherit scheduler attribute of a thread attributes object. + * + * @param attr [OUT] Pointer to the thread attributes object to be set. + * @param inherit [IN] Inherit scheduler attribute. + * + * @attention + *
        + *
      • The inherit scheduler attribute must be either PTHREAD_INHERIT_SCHED or PTHREAD_EXPLICIT_SCHED.
      • + *
      + * + * @retval #int If successful, the pthread_attr_setinheritsched() function shall return zero; otherwise, an error number shall be returned to indicate the error. + * @retval #EINVAL invalid parameter. + * @retval #ENOERR The inherit scheduler attribute is successfully set. + * + * @par Dependency: + *
      • pthread.h
      + * @see pthread_attr_getinheritsched + */ +int pthread_attr_setinheritsched(pthread_attr_t *, int); + +int pthread_mutexattr_destroy(pthread_mutexattr_t *); +int pthread_mutexattr_getprioceiling(const pthread_mutexattr_t *__restrict, int *__restrict); +int pthread_mutexattr_getprotocol(const pthread_mutexattr_t *__restrict, int *__restrict); +int pthread_mutexattr_getpshared(const pthread_mutexattr_t *__restrict, int *__restrict); +int pthread_mutexattr_getrobust(const pthread_mutexattr_t *__restrict, int *__restrict); +int pthread_mutexattr_gettype(const pthread_mutexattr_t *__restrict, int *__restrict); +int pthread_mutexattr_init(pthread_mutexattr_t *); +int pthread_mutexattr_setprioceiling(pthread_mutexattr_t *, int); +int pthread_mutexattr_setprotocol(pthread_mutexattr_t *, int); +int pthread_mutexattr_setpshared(pthread_mutexattr_t *, int); +int pthread_mutexattr_setrobust(pthread_mutexattr_t *, int); +int pthread_mutexattr_settype(pthread_mutexattr_t *, int); + +/** + * @ingroup pthread + * @par Description: + * This API is used to initialize the condition variable attribute. + * This API does not task effect on Huawei LiteOS Kernel. + * + * @param attr [OUT] Condition variable attribute. + * + * @attention + *
        + *
      • The condition variable attribute can be only set to PTHREAD_PROCESS_PRIVATE.
      • + *
      + * + * @retval #ENVAIL The parameter is invalid. + * @retval #ENOERR The condition variable attribute is successfully initialized. + * + * @par Dependency: + *
      • pthread.h
      + * + * @see pthread_condattr_setpshared | pthread_condattr_getpshared + * + */ +int pthread_condattr_init(pthread_condattr_t *); + +/** + * @ingroup pthread + * @par Description: + * This API is used to destroy the condition variable attribute. + * + * @param attr [IN] Condition variable attribute. + * + * @attention + *
        + *
      • The condition variable attribute can be only set to PTHREAD_PROCESS_PRIVATE.
      • + *
      • This API does not task effect on Huawei LiteOS Kernel.
      • + *
      + * + * @retval #ENVAIL The parameter is invalid. + * @retval #ENOERR The condition variable attribute is successfully destroied. + * + * @par Dependency: + *
      • pthread.h
      + * + * @see pthread_condattr_init + * + */ +int pthread_condattr_destroy(pthread_condattr_t *); +int pthread_condattr_setclock(pthread_condattr_t *, clockid_t); + +/** + * @ingroup pthread + * @par Description: + * This API is used to set the condition variable attribute. + * + * @param attr [IN] Condition variable attribute. + * @param pshared [OUT] Condition variable attribute, which is always PTHREAD_PROCESS_PRIVATE. + * + * @attention + *
        + *
      • The condition variable attribute can be only set to PTHREAD_PROCESS_PRIVATE.
      • + *
      • This API does not task effect on Huawei LiteOS Kernel.
      • + *
      + * + * @retval #ENVAIL One or more parameters are invalid. + * @retval #ENOERR The condition variable attribute is successfully set. + * + * @par Dependency: + *
      • pthread.h
      + * + * @see pthread_condattr_getpshared + * + */ +int pthread_condattr_setpshared(pthread_condattr_t *, int); +int pthread_condattr_getclock(const pthread_condattr_t *__restrict, clockid_t *__restrict); + +/** + * @ingroup pthread + * @par Description: + * This API is used to obtain the condition variable attribute. + * + * @param attr [IN] Condition variable attribute. + * @param pshared [OUT] Obtained condition variable attribute, which is always PTHREAD_PROCESS_PRIVATE. + * + * @attention + *
        + *
      • The condition variable attribute can be only set to PTHREAD_PROCESS_PRIVATE.
      • + *
      • This API does not task effect on Huawei LiteOS Kernel.
      • + *
      + * + * @retval #ENVAIL One or more parameters are invalid. + * @retval #ENOERR The condition variable attribute is successfully obtained. + * + * @par Dependency: + *
      • pthread.h
      + * + * @see pthread_condattr_setpshared + * + */ +int pthread_condattr_getpshared(const pthread_condattr_t *__restrict, int *__restrict); + +int pthread_rwlockattr_init(pthread_rwlockattr_t *); +int pthread_rwlockattr_destroy(pthread_rwlockattr_t *); +int pthread_rwlockattr_setpshared(pthread_rwlockattr_t *, int); +int pthread_rwlockattr_getpshared(const pthread_rwlockattr_t *__restrict, int *__restrict); + +int pthread_barrierattr_destroy(pthread_barrierattr_t *); +int pthread_barrierattr_getpshared(const pthread_barrierattr_t *__restrict, int *__restrict); +int pthread_barrierattr_init(pthread_barrierattr_t *); +int pthread_barrierattr_setpshared(pthread_barrierattr_t *, int); + +/** + * @ingroup pthread + * @par Description: + * The function is not supported. + * + * @attention + *
        + *
      • The function is not supported.
      • + *
      + * + * @retval #int zero. + * + * @par Dependency: + *
      • pthread.h
      + * + * @see None + * + */ +int pthread_atfork(void (*)(void), void (*)(void), void (*)(void)); + +int pthread_getconcurrency(void); +int pthread_setconcurrency(int); + +int pthread_getcpuclockid(pthread_t, clockid_t *); + +#ifndef __LITEOS__ +struct __ptcb { + void (*__f)(void *); + void *__x; + struct __ptcb *__next; +}; + +void _pthread_cleanup_push(struct __ptcb *, void (*)(void *), void *); +void _pthread_cleanup_pop(struct __ptcb *, int); +#endif + +struct pthread_cleanup_buffer { + void (*routine)(void *); + void *arg; + struct pthread_cleanup_buffer *next; +}; +#define pthread_cleanup_push(routine, arg) do { struct pthread_cleanup_buffer cb; pthread_cleanup_push_inner(&cb, routine, arg); +#define pthread_cleanup_pop(arg) pthread_cleanup_pop_inner(&cb, (arg)); } while(0) + +#ifdef _GNU_SOURCE +struct cpu_set_t; + +/** + * @ingroup pthread + * + * @par Description: + * This API is used to get the cpu affinity mask from the thread. + * + * @param pthread [IN] ID of the thread whose affinity mask is to be read. + * @param cpusetsize [IN] Size of cpuset in bytes. + * @param cpuset [OUT] Pointer to the cpu affinity mask. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #EINVAL Invalid parameter. + * @retval #ENOERR The cpu affinity mask of the thread is successfully acquired. + * + * @par Dependency: + *
      • pthread.h
      + * + * @see pthread_setaffinity_np + * + */ +int pthread_getaffinity_np(pthread_t, size_t, struct cpu_set_t *); + +/** + * @ingroup pthread + * + * @par Description: + * This API is used to set the cpu affinity mask for the thread. + * + * @param pthread [IN] ID of the thread whose affinity mask is to be set. + * @param cpusetsize [IN] Size of cpuset in bytes. + * @param cpuset [IN] Pointer to the cpu affinity mask. + * + * @attention + *
        + *
      • The cpu affinity mask attributes must be in the range of [1, LOSCFG_KERNEL_CPU_MASK].
      • + *
      + * + * @retval #EINVAL Invalid parameter. + * @retval #ENOERR The cpu affinity mask of the thread is successfully set. + * + * @par Dependency: + *
      • pthread.h
      + * + * @see pthread_getaffinity_np + * + */ +int pthread_setaffinity_np(pthread_t, size_t, const struct cpu_set_t *); +#ifdef __LITEOS__ +/** + * @ingroup pthread + * + * @par Description: + * This API is used to set the cpu affinity mask attributes of a thread attributes object. + * + * @param attr [OUT] Pointer to the thread attributes object to be set. + * @param cpusetsize [IN] Size of cpuset in bytes. + * @param cpuset [IN] Pointer to the cpu affinity mask. + * + * @attention + *
        + *
      • The cpu affinity mask attributes must be in the range of [1, LOSCFG_KERNEL_CPU_MASK].
      • + *
      + * + * @retval #EINVAL Invalid parameter. + * @retval #ENOERR The cpu affinity mask attributes are successfully set. + * + * @par Dependency: + *
      • pthread.h
      + * + * @see pthread_attr_getaffinity_np + * + */ +int pthread_attr_setaffinity_np(pthread_attr_t *attr, size_t cpusetsize, const cpu_set_t *cpuset); + +/** + * @ingroup pthread + * + * @par Description: + * This API is used to get the cpu affinity mask attributes of a thread attributes object. + * + * @param attr [IN] Pointer to the thread attributes object to be read. + * @param cpusetsize [IN] Size of cpuset in bytes. + * @param cpuset [OUT] Pointer to the cpu affinity mask. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #EINVAL Invalid parameter. + * @retval #ENOERR The cpu affinity mask attributes are successfully acquired. + * + * @par Dependency: + *
      • pthread.h
      + * + * @see pthread_attr_setaffinity_np + * + */ +int pthread_attr_getaffinity_np(const pthread_attr_t *attr, size_t cpusetsize, cpu_set_t *cpuset); +#endif +int pthread_getattr_np(pthread_t, pthread_attr_t *); +int pthread_setname_np(pthread_t, const char *); +int pthread_getattr_default_np(pthread_attr_t *); +int pthread_setattr_default_np(const pthread_attr_t *); +int pthread_tryjoin_np(pthread_t, void **); +int pthread_timedjoin_np(pthread_t, void **, const struct timespec *); +#endif + +#if _REDIR_TIME64 +__REDIR(pthread_mutex_timedlock, __pthread_mutex_timedlock_time64); +__REDIR(pthread_cond_timedwait, __pthread_cond_timedwait_time64); +__REDIR(pthread_rwlock_timedrdlock, __pthread_rwlock_timedrdlock_time64); +__REDIR(pthread_rwlock_timedwrlock, __pthread_rwlock_timedwrlock_time64); +#ifdef _GNU_SOURCE +__REDIR(pthread_timedjoin_np, __pthread_timedjoin_np_time64); +#endif +#endif + +#ifdef __cplusplus +} +#endif +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/pty.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/pty.h new file mode 100644 index 0000000000000000000000000000000000000000..db63853411879851f0cb04ad562e73a7e7634aad --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/pty.h @@ -0,0 +1,18 @@ +#ifndef _PTY_H +#define _PTY_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include + +int openpty(int *, int *, char *, const struct termios *, const struct winsize *); +int forkpty(int *, char *, const struct termios *, const struct winsize *); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/pwd.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/pwd.h new file mode 100644 index 0000000000000000000000000000000000000000..4f470b558b15f950e2ae4152c15dea08495b3127 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/pwd.h @@ -0,0 +1,50 @@ +#ifndef _PWD_H +#define _PWD_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#define __NEED_size_t +#define __NEED_uid_t +#define __NEED_gid_t + +#ifdef _GNU_SOURCE +#define __NEED_FILE +#endif + +#include + +struct passwd { + char *pw_name; + char *pw_passwd; + uid_t pw_uid; + gid_t pw_gid; + char *pw_gecos; + char *pw_dir; + char *pw_shell; +}; + +#if defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) || defined(_BSD_SOURCE) +void setpwent (void); +void endpwent (void); +struct passwd *getpwent (void); +#endif + +struct passwd *getpwuid (uid_t); +struct passwd *getpwnam (const char *); +int getpwuid_r (uid_t, struct passwd *, char *, size_t, struct passwd **); +int getpwnam_r (const char *, struct passwd *, char *, size_t, struct passwd **); + +#ifdef _GNU_SOURCE +struct passwd *fgetpwent(FILE *); +int putpwent(const struct passwd *, FILE *); +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/regex.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/regex.h new file mode 100644 index 0000000000000000000000000000000000000000..dce217718f8c825acec8d7dad38806db2064b4ec --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/regex.h @@ -0,0 +1,62 @@ +#ifndef _REGEX_H +#define _REGEX_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#define __NEED_regoff_t +#define __NEED_size_t + +#include + +typedef struct re_pattern_buffer { + size_t re_nsub; + void *__opaque, *__padding[4]; + size_t __nsub2; + char __padding2; +} regex_t; + +typedef struct { + regoff_t rm_so; + regoff_t rm_eo; +} regmatch_t; + +#define REG_EXTENDED 1 +#define REG_ICASE 2 +#define REG_NEWLINE 4 +#define REG_NOSUB 8 + +#define REG_NOTBOL 1 +#define REG_NOTEOL 2 + +#define REG_OK 0 +#define REG_NOMATCH 1 +#define REG_BADPAT 2 +#define REG_ECOLLATE 3 +#define REG_ECTYPE 4 +#define REG_EESCAPE 5 +#define REG_ESUBREG 6 +#define REG_EBRACK 7 +#define REG_EPAREN 8 +#define REG_EBRACE 9 +#define REG_BADBR 10 +#define REG_ERANGE 11 +#define REG_ESPACE 12 +#define REG_BADRPT 13 + +#define REG_ENOSYS -1 + +int regcomp(regex_t *__restrict, const char *__restrict, int); +int regexec(const regex_t *__restrict, const char *__restrict, size_t, regmatch_t *__restrict, int); +void regfree(regex_t *); + +size_t regerror(int, const regex_t *__restrict, char *__restrict, size_t); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/resolv.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/resolv.h new file mode 100644 index 0000000000000000000000000000000000000000..8b23ad66cc7613a68e670c95c2b409273fdc05a5 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/resolv.h @@ -0,0 +1,142 @@ +#ifndef _RESOLV_H +#define _RESOLV_H + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define MAXNS 3 +#define MAXDFLSRCH 3 +#define MAXDNSRCH 6 +#define LOCALDOMAINPARTS 2 + +#define RES_TIMEOUT 5 +#define MAXRESOLVSORT 10 +#define RES_MAXNDOTS 15 +#define RES_MAXRETRANS 30 +#define RES_MAXRETRY 5 +#define RES_DFLRETRY 2 +#define RES_MAXTIME 65535 + +/* unused; purely for broken apps */ +typedef struct __res_state { + int retrans; + int retry; + unsigned long options; + int nscount; + struct sockaddr_in nsaddr_list[MAXNS]; +# define nsaddr nsaddr_list[0] + unsigned short id; + char *dnsrch[MAXDNSRCH+1]; + char defdname[256]; + unsigned long pfcode; + unsigned ndots:4; + unsigned nsort:4; + unsigned ipv6_unavail:1; + unsigned unused:23; + struct { + struct in_addr addr; + uint32_t mask; + } sort_list[MAXRESOLVSORT]; + void *qhook; + void *rhook; + int res_h_errno; + int _vcsock; + unsigned _flags; + union { + char pad[52]; + struct { + uint16_t nscount; + uint16_t nsmap[MAXNS]; + int nssocks[MAXNS]; + uint16_t nscount6; + uint16_t nsinit; + struct sockaddr_in6 *nsaddrs[MAXNS]; + unsigned int _initstamp[2]; + } _ext; + } _u; +} *res_state; + +#define __RES 19960801 + +#ifndef _PATH_RESCONF +#define _PATH_RESCONF "/etc/resolv.conf" +#endif + +struct res_sym { + int number; + char *name; + char *humanname; +}; + +#define RES_F_VC 0x00000001 +#define RES_F_CONN 0x00000002 +#define RES_F_EDNS0ERR 0x00000004 + +#define RES_EXHAUSTIVE 0x00000001 + +#define RES_INIT 0x00000001 +#define RES_DEBUG 0x00000002 +#define RES_AAONLY 0x00000004 +#define RES_USEVC 0x00000008 +#define RES_PRIMARY 0x00000010 +#define RES_IGNTC 0x00000020 +#define RES_RECURSE 0x00000040 +#define RES_DEFNAMES 0x00000080 +#define RES_STAYOPEN 0x00000100 +#define RES_DNSRCH 0x00000200 +#define RES_INSECURE1 0x00000400 +#define RES_INSECURE2 0x00000800 +#define RES_NOALIASES 0x00001000 +#define RES_USE_INET6 0x00002000 +#define RES_ROTATE 0x00004000 +#define RES_NOCHECKNAME 0x00008000 +#define RES_KEEPTSIG 0x00010000 +#define RES_BLAST 0x00020000 +#define RES_USEBSTRING 0x00040000 +#define RES_NOIP6DOTINT 0x00080000 +#define RES_USE_EDNS0 0x00100000 +#define RES_SNGLKUP 0x00200000 +#define RES_SNGLKUPREOP 0x00400000 +#define RES_USE_DNSSEC 0x00800000 + +#define RES_DEFAULT (RES_RECURSE|RES_DEFNAMES|RES_DNSRCH|RES_NOIP6DOTINT) + +#define RES_PRF_STATS 0x00000001 +#define RES_PRF_UPDATE 0x00000002 +#define RES_PRF_CLASS 0x00000004 +#define RES_PRF_CMD 0x00000008 +#define RES_PRF_QUES 0x00000010 +#define RES_PRF_ANS 0x00000020 +#define RES_PRF_AUTH 0x00000040 +#define RES_PRF_ADD 0x00000080 +#define RES_PRF_HEAD1 0x00000100 +#define RES_PRF_HEAD2 0x00000200 +#define RES_PRF_TTLID 0x00000400 +#define RES_PRF_HEADX 0x00000800 +#define RES_PRF_QUERY 0x00001000 +#define RES_PRF_REPLY 0x00002000 +#define RES_PRF_INIT 0x00004000 + +struct __res_state *__res_state(void); +#define _res (*__res_state()) + +int res_init(void); +int res_query(const char *, int, int, unsigned char *, int); +int res_querydomain(const char *, const char *, int, int, unsigned char *, int); +int res_search(const char *, int, int, unsigned char *, int); +int res_mkquery(int, const char *, int, int, const unsigned char *, int, const unsigned char*, unsigned char *, int); +int res_send(const unsigned char *, int, unsigned char *, int); +int dn_comp(const char *, unsigned char *, int, unsigned char **, unsigned char **); +int dn_expand(const unsigned char *, const unsigned char *, const unsigned char *, char *, int); +int dn_skipname(const unsigned char *, const unsigned char *); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sched.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sched.h new file mode 100644 index 0000000000000000000000000000000000000000..c278240a594969c95a63d7c0bca47062d56a3c55 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sched.h @@ -0,0 +1,221 @@ +/** + * @defgroup sched Sched + * @ingroup libc + */ + +#ifndef _SCHED_H +#define _SCHED_H +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#define __NEED_struct_timespec +#define __NEED_pid_t +#define __NEED_time_t + +#ifdef _GNU_SOURCE +#define __NEED_size_t +#endif + +#include + +struct sched_param { + int sched_priority; + int __reserved1; +#if _REDIR_TIME64 + long __reserved2[4]; +#else + struct { + time_t __reserved1; + long __reserved2; + } __reserved2[2]; +#endif + int __reserved3; +}; + +/** + * @ingroup sched + * + * @par Description: + * The sched_get_priority_max() function shall return the appropriate maximum for the scheduling policy. + * + * @attention + *
        + *
      • LiteOS only support the scheduling policy is SCHED_RR.
      • + *
      + * + * @retval #int The sched_get_priority_max() function shall return the appropriate maximum values;\n + * otherwise, it shall return -1 and set errno to indicate the error. + * + * @par Errors + *
        + *
      • EINVAL: The value of the policy parameter does not represent a defined scheduling policy.
      • + *
      + * + * @par Dependency: + *
      • sched.h
      + * @see sched_get_priority_min + */ +int sched_get_priority_max(int); + +/** + * @ingroup sched + * + * @par Description: + * The sched_get_priority_min() function shall return the appropriate minimum for the scheduling policy. + * + * @attention + *
        + *
      • LiteOS only support the scheduling policy is SCHED_RR.
      • + *
      + * + * @retval #int The sched_get_priority_min() function shall return the appropriate minimum values;\n + * otherwise, it shall return -1 and set errno to indicate the error. + * + * @par Errors + *
        + *
      • EINVAL: The value of the policy parameter does not represent a defined scheduling policy.
      • + *
      + * + * @par Dependency: + *
      • sched.h
      + * @see sched_get_priority_max + */ +int sched_get_priority_min(int); +int sched_getparam(pid_t, struct sched_param *); +int sched_getscheduler(pid_t); +int sched_rr_get_interval(pid_t, struct timespec *); +int sched_setparam(pid_t, const struct sched_param *); +int sched_setscheduler(pid_t, int, const struct sched_param *); + +/** + * @ingroup sched + * + * @par Description: + * The sched_yield() function force the running thread to relinquish the processor. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #int The sched_yield() function shall return 0 if it completes successfully;\n + * otherwise, it shall return -1. + * @par Dependency: + *
      • sched.h
      + * @see None + */ +int sched_yield(void); + +#define SCHED_OTHER 0 +#define SCHED_FIFO 1 +#define SCHED_RR 2 +#define SCHED_BATCH 3 +#define SCHED_IDLE 5 +#define SCHED_DEADLINE 6 +#define SCHED_RESET_ON_FORK 0x40000000 + +#ifdef __LITEOS__ +#define __CPU_BITTYPE unsigned long +#endif + +#ifdef _GNU_SOURCE +#define CSIGNAL 0x000000ff +#define CLONE_VM 0x00000100 +#define CLONE_FS 0x00000200 +#define CLONE_FILES 0x00000400 +#define CLONE_SIGHAND 0x00000800 +#define CLONE_PIDFD 0x00001000 +#define CLONE_PTRACE 0x00002000 +#define CLONE_VFORK 0x00004000 +#define CLONE_PARENT 0x00008000 +#define CLONE_THREAD 0x00010000 +#define CLONE_NEWNS 0x00020000 +#define CLONE_SYSVSEM 0x00040000 +#define CLONE_SETTLS 0x00080000 +#define CLONE_PARENT_SETTID 0x00100000 +#define CLONE_CHILD_CLEARTID 0x00200000 +#define CLONE_DETACHED 0x00400000 +#define CLONE_UNTRACED 0x00800000 +#define CLONE_CHILD_SETTID 0x01000000 +#define CLONE_NEWCGROUP 0x02000000 +#define CLONE_NEWUTS 0x04000000 +#define CLONE_NEWIPC 0x08000000 +#define CLONE_NEWUSER 0x10000000 +#define CLONE_NEWPID 0x20000000 +#define CLONE_NEWNET 0x40000000 +#define CLONE_IO 0x80000000 +int clone (int (*)(void *), void *, int, void *, ...); +int unshare(int); +int setns(int, int); + +void *memcpy(void *__restrict, const void *__restrict, size_t); +int memcmp(const void *, const void *, size_t); +void *memset (void *, int, size_t); +void *calloc(size_t, size_t); +void free(void *); + +typedef struct cpu_set_t { unsigned long __bits[128/sizeof(long)]; } cpu_set_t; +int __sched_cpucount(size_t, const cpu_set_t *); +int sched_getcpu(void); +int sched_getaffinity(pid_t, size_t, cpu_set_t *); +int sched_setaffinity(pid_t, size_t, const cpu_set_t *); + +#define __CPU_op_S(i, size, set, op) ( (i)/8U >= (size) ? 0 : \ + (((unsigned long *)(set))[(i)/8/sizeof(long)] op (1UL<<((i)%(8*sizeof(long))))) ) + +#define CPU_SET_S(i, size, set) __CPU_op_S(i, size, set, |=) +#define CPU_CLR_S(i, size, set) __CPU_op_S(i, size, set, &=~) +#define CPU_ISSET_S(i, size, set) __CPU_op_S(i, size, set, &) + +#define __CPU_op_func_S(func, op) \ +static __inline void __CPU_##func##_S(size_t __size, cpu_set_t *__dest, \ + const cpu_set_t *__src1, const cpu_set_t *__src2) \ +{ \ + size_t __i; \ + for (__i=0; __i<__size/sizeof(long); __i++) \ + ((unsigned long *)__dest)[__i] = ((unsigned long *)__src1)[__i] \ + op ((unsigned long *)__src2)[__i] ; \ +} + +__CPU_op_func_S(AND, &) +__CPU_op_func_S(OR, |) +__CPU_op_func_S(XOR, ^) + +#define CPU_AND_S(a,b,c,d) __CPU_AND_S(a,b,c,d) +#define CPU_OR_S(a,b,c,d) __CPU_OR_S(a,b,c,d) +#define CPU_XOR_S(a,b,c,d) __CPU_XOR_S(a,b,c,d) + +#define CPU_COUNT_S(size,set) __sched_cpucount(size,set) +#define CPU_ZERO_S(size,set) memset(set,0,size) +#define CPU_EQUAL_S(size,set1,set2) (!memcmp(set1,set2,size)) + +#define CPU_ALLOC_SIZE(n) (sizeof(long) * ( (n)/(8*sizeof(long)) \ + + ((n)%(8*sizeof(long)) + 8*sizeof(long)-1)/(8*sizeof(long)) ) ) +#define CPU_ALLOC(n) ((cpu_set_t *)calloc(1,CPU_ALLOC_SIZE(n))) +#define CPU_FREE(set) free(set) + +#define CPU_SETSIZE 128 + +#define CPU_SET(i, set) CPU_SET_S(i,sizeof(cpu_set_t),set) +#define CPU_CLR(i, set) CPU_CLR_S(i,sizeof(cpu_set_t),set) +#define CPU_ISSET(i, set) CPU_ISSET_S(i,sizeof(cpu_set_t),set) +#define CPU_AND(d,s1,s2) CPU_AND_S(sizeof(cpu_set_t),d,s1,s2) +#define CPU_OR(d,s1,s2) CPU_OR_S(sizeof(cpu_set_t),d,s1,s2) +#define CPU_XOR(d,s1,s2) CPU_XOR_S(sizeof(cpu_set_t),d,s1,s2) +#define CPU_COUNT(set) CPU_COUNT_S(sizeof(cpu_set_t),set) +#define CPU_ZERO(set) CPU_ZERO_S(sizeof(cpu_set_t),set) +#define CPU_EQUAL(s1,s2) CPU_EQUAL_S(sizeof(cpu_set_t),s1,s2) + +#endif + +#if _REDIR_TIME64 +__REDIR(sched_rr_get_interval, __sched_rr_get_interval_time64); +#endif + +#ifdef __cplusplus +} +#endif +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/scsi/scsi.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/scsi/scsi.h new file mode 100644 index 0000000000000000000000000000000000000000..8837f5875656bf26927d0e78ab486debe3fa780d --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/scsi/scsi.h @@ -0,0 +1,150 @@ +#ifndef _SCSI_SCSI_H +#define _SCSI_SCSI_H + +#define TEST_UNIT_READY 0x00 +#define REZERO_UNIT 0x01 +#define REQUEST_SENSE 0x03 +#define FORMAT_UNIT 0x04 +#define READ_BLOCK_LIMITS 0x05 +#define REASSIGN_BLOCKS 0x07 +#define READ_6 0x08 +#define WRITE_6 0x0a +#define SEEK_6 0x0b +#define READ_REVERSE 0x0f +#define WRITE_FILEMARKS 0x10 +#define SPACE 0x11 +#define INQUIRY 0x12 +#define RECOVER_BUFFERED_DATA 0x14 +#define MODE_SELECT 0x15 +#define RESERVE 0x16 +#define RELEASE 0x17 +#define COPY 0x18 +#define ERASE 0x19 +#define MODE_SENSE 0x1a +#define START_STOP 0x1b +#define RECEIVE_DIAGNOSTIC 0x1c +#define SEND_DIAGNOSTIC 0x1d +#define ALLOW_MEDIUM_REMOVAL 0x1e +#define SET_WINDOW 0x24 +#define READ_CAPACITY 0x25 +#define READ_10 0x28 +#define WRITE_10 0x2a +#define SEEK_10 0x2b +#define WRITE_VERIFY 0x2e +#define VERIFY 0x2f +#define SEARCH_HIGH 0x30 +#define SEARCH_EQUAL 0x31 +#define SEARCH_LOW 0x32 +#define SET_LIMITS 0x33 +#define PRE_FETCH 0x34 +#define READ_POSITION 0x34 +#define SYNCHRONIZE_CACHE 0x35 +#define LOCK_UNLOCK_CACHE 0x36 +#define READ_DEFECT_DATA 0x37 +#define MEDIUM_SCAN 0x38 +#define COMPARE 0x39 +#define COPY_VERIFY 0x3a +#define WRITE_BUFFER 0x3b +#define READ_BUFFER 0x3c +#define UPDATE_BLOCK 0x3d +#define READ_LONG 0x3e +#define WRITE_LONG 0x3f +#define CHANGE_DEFINITION 0x40 +#define WRITE_SAME 0x41 +#define READ_TOC 0x43 +#define LOG_SELECT 0x4c +#define LOG_SENSE 0x4d +#define MODE_SELECT_10 0x55 +#define RESERVE_10 0x56 +#define RELEASE_10 0x57 +#define MODE_SENSE_10 0x5a +#define PERSISTENT_RESERVE_IN 0x5e +#define PERSISTENT_RESERVE_OUT 0x5f +#define MOVE_MEDIUM 0xa5 +#define READ_12 0xa8 +#define WRITE_12 0xaa +#define WRITE_VERIFY_12 0xae +#define SEARCH_HIGH_12 0xb0 +#define SEARCH_EQUAL_12 0xb1 +#define SEARCH_LOW_12 0xb2 +#define READ_ELEMENT_STATUS 0xb8 +#define SEND_VOLUME_TAG 0xb6 +#define WRITE_LONG_2 0xea +#define GOOD 0x00 +#define CHECK_CONDITION 0x01 +#define CONDITION_GOOD 0x02 +#define BUSY 0x04 +#define INTERMEDIATE_GOOD 0x08 +#define INTERMEDIATE_C_GOOD 0x0a +#define RESERVATION_CONFLICT 0x0c +#define COMMAND_TERMINATED 0x11 +#define QUEUE_FULL 0x14 +#define STATUS_MASK 0x3e +#define NO_SENSE 0x00 +#define RECOVERED_ERROR 0x01 +#define NOT_READY 0x02 +#define MEDIUM_ERROR 0x03 +#define HARDWARE_ERROR 0x04 +#define ILLEGAL_REQUEST 0x05 +#define UNIT_ATTENTION 0x06 +#define DATA_PROTECT 0x07 +#define BLANK_CHECK 0x08 +#define COPY_ABORTED 0x0a +#define ABORTED_COMMAND 0x0b +#define VOLUME_OVERFLOW 0x0d +#define MISCOMPARE 0x0e +#define TYPE_DISK 0x00 +#define TYPE_TAPE 0x01 +#define TYPE_PROCESSOR 0x03 +#define TYPE_WORM 0x04 +#define TYPE_ROM 0x05 +#define TYPE_SCANNER 0x06 +#define TYPE_MOD 0x07 +#define TYPE_MEDIUM_CHANGER 0x08 +#define TYPE_ENCLOSURE 0x0d +#define TYPE_NO_LUN 0x7f +#define COMMAND_COMPLETE 0x00 +#define EXTENDED_MESSAGE 0x01 +#define EXTENDED_MODIFY_DATA_POINTER 0x00 +#define EXTENDED_SDTR 0x01 +#define EXTENDED_EXTENDED_IDENTIFY 0x02 +#define EXTENDED_WDTR 0x03 +#define SAVE_POINTERS 0x02 +#define RESTORE_POINTERS 0x03 +#define DISCONNECT 0x04 +#define INITIATOR_ERROR 0x05 +#define ABORT 0x06 +#define MESSAGE_REJECT 0x07 +#define NOP 0x08 +#define MSG_PARITY_ERROR 0x09 +#define LINKED_CMD_COMPLETE 0x0a +#define LINKED_FLG_CMD_COMPLETE 0x0b +#define BUS_DEVICE_RESET 0x0c +#define INITIATE_RECOVERY 0x0f +#define RELEASE_RECOVERY 0x10 +#define SIMPLE_QUEUE_TAG 0x20 +#define HEAD_OF_QUEUE_TAG 0x21 +#define ORDERED_QUEUE_TAG 0x22 +#define SCSI_IOCTL_GET_IDLUN 0x5382 +#define SCSI_IOCTL_TAGGED_ENABLE 0x5383 +#define SCSI_IOCTL_TAGGED_DISABLE 0x5384 +#define SCSI_IOCTL_PROBE_HOST 0x5385 +#define SCSI_IOCTL_GET_BUS_NUMBER 0x5386 + +struct ccs_modesel_head { + unsigned char _r1; + unsigned char medium; + unsigned char _r2; + unsigned char block_desc_length; + unsigned char density; + unsigned char number_blocks_hi; + unsigned char number_blocks_med; + unsigned char number_blocks_lo; + unsigned char _r3; + unsigned char block_length_hi; + unsigned char block_length_med; + unsigned char block_length_lo; +}; + +#endif + diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/scsi/scsi_ioctl.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/scsi/scsi_ioctl.h new file mode 100644 index 0000000000000000000000000000000000000000..22df7feffaedd660325e5183783b286d410e12db --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/scsi/scsi_ioctl.h @@ -0,0 +1,11 @@ +#ifndef _SCSI_IOCTL_H +#define _SCSI_IOCTL_H +#define SCSI_IOCTL_SEND_COMMAND 1 +#define SCSI_IOCTL_TEST_UNIT_READY 2 +#define SCSI_IOCTL_BENCHMARK_COMMAND 3 +#define SCSI_IOCTL_SYNC 4 +#define SCSI_IOCTL_START_UNIT 5 +#define SCSI_IOCTL_STOP_UNIT 6 +#define SCSI_IOCTL_DOORLOCK 0x5380 +#define SCSI_IOCTL_DOORUNLOCK 0x5381 +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/scsi/sg.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/scsi/sg.h new file mode 100644 index 0000000000000000000000000000000000000000..a7ac247e3ffade1a20770e2bc90119c7756eaf83 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/scsi/sg.h @@ -0,0 +1,129 @@ +#ifndef _SCSI_SG_H +#define _SCSI_SG_H + +#define SG_DXFER_NONE -1 +#define SG_DXFER_TO_DEV -2 +#define SG_DXFER_FROM_DEV -3 +#define SG_DXFER_TO_FROM_DEV -4 +#define SG_FLAG_DIRECT_IO 1 +#define SG_FLAG_LUN_INHIBIT 2 +#define SG_FLAG_NO_DXFER 0x10000 +#define SG_INFO_OK_MASK 0x1 +#define SG_INFO_OK 0x0 +#define SG_INFO_CHECK 0x1 +#define SG_INFO_DIRECT_IO_MASK 0x6 +#define SG_INFO_INDIRECT_IO 0x0 +#define SG_INFO_DIRECT_IO 0x2 +#define SG_INFO_MIXED_IO 0x4 +#define SG_EMULATED_HOST 0x2203 +#define SG_SET_TRANSFORM 0x2204 +#define SG_GET_TRANSFORM 0x2205 +#define SG_SET_RESERVED_SIZE 0x2275 +#define SG_GET_RESERVED_SIZE 0x2272 +#define SG_GET_SCSI_ID 0x2276 +#define SG_SET_FORCE_LOW_DMA 0x2279 +#define SG_GET_LOW_DMA 0x227a +#define SG_SET_FORCE_PACK_ID 0x227b +#define SG_GET_PACK_ID 0x227c +#define SG_GET_NUM_WAITING 0x227d +#define SG_GET_SG_TABLESIZE 0x227F +#define SG_GET_VERSION_NUM 0x2282 +#define SG_SCSI_RESET 0x2284 +#define SG_SCSI_RESET_NOTHING 0 +#define SG_SCSI_RESET_DEVICE 1 +#define SG_SCSI_RESET_BUS 2 +#define SG_SCSI_RESET_HOST 3 +#define SG_IO 0x2285 +#define SG_GET_REQUEST_TABLE 0x2286 +#define SG_SET_KEEP_ORPHAN 0x2287 +#define SG_GET_KEEP_ORPHAN 0x2288 +#define SG_SCATTER_SZ (8 * 4096) +#define SG_DEFAULT_RETRIES 1 +#define SG_DEF_FORCE_LOW_DMA 0 +#define SG_DEF_FORCE_PACK_ID 0 +#define SG_DEF_KEEP_ORPHAN 0 +#define SG_DEF_RESERVED_SIZE SG_SCATTER_SZ +#define SG_MAX_QUEUE 16 +#define SG_BIG_BUFF SG_DEF_RESERVED_SIZE +#define SG_MAX_SENSE 16 +#define SG_SET_TIMEOUT 0x2201 +#define SG_GET_TIMEOUT 0x2202 +#define SG_GET_COMMAND_Q 0x2270 +#define SG_SET_COMMAND_Q 0x2271 +#define SG_SET_DEBUG 0x227e +#define SG_NEXT_CMD_LEN 0x2283 +#define SG_DEFAULT_TIMEOUT (60*100) /* 60*HZ */ +#define SG_DEF_COMMAND_Q 0 +#define SG_DEF_UNDERRUN_FLAG 0 + +typedef struct sg_iovec { + void *iov_base; + unsigned long iov_len; +} sg_iovec_t; + +typedef struct sg_io_hdr { + int interface_id; + int dxfer_direction; + unsigned char cmd_len; + unsigned char mx_sb_len; + unsigned short iovec_count; + unsigned dxfer_len; + void *dxferp; + unsigned char *cmdp; + unsigned char *sbp; + unsigned timeout; + unsigned flags; + int pack_id; + void *usr_ptr; + unsigned char status; + unsigned char masked_status; + unsigned char msg_status; + unsigned char sb_len_wr; + unsigned short host_status; + unsigned short driver_status; + int resid; + unsigned int duration; + unsigned int info; +} sg_io_hdr_t; + +struct sg_scsi_id { + int host_no; + int channel; + int scsi_id; + int lun; + int scsi_type; + short h_cmd_per_lun; + short d_queue_depth; + int unused[2]; +}; + +typedef struct sg_req_info { + char req_state; + char orphan; + char sg_io_owned; + char problem; + int pack_id; + void *usr_ptr; + unsigned duration; + int unused; +} sg_req_info_t; + +typedef struct sg_io_hdr Sg_io_hdr; +typedef struct sg_io_vec Sg_io_vec; +typedef struct sg_scsi_id Sg_scsi_id; +typedef struct sg_req_info Sg_req_info; + +struct sg_header { + int pack_len; + int reply_len; + int pack_id; + int result; + unsigned twelve_byte:1; + unsigned target_status:5; + unsigned host_status:8; + unsigned driver_status:8; + unsigned other_flags:10; + unsigned char sense_buffer[SG_MAX_SENSE]; +}; + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/search.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/search.h new file mode 100644 index 0000000000000000000000000000000000000000..02e407e3c2aba21b6fe4d015c6430c3155c3db69 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/search.h @@ -0,0 +1,63 @@ +#ifndef _SEARCH_H +#define _SEARCH_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#define __NEED_size_t +#include + +typedef enum { FIND, ENTER } ACTION; +typedef enum { preorder, postorder, endorder, leaf } VISIT; + +typedef struct entry { + char *key; + void *data; +} ENTRY; + +int hcreate(size_t); +void hdestroy(void); +ENTRY *hsearch(ENTRY, ACTION); + +#ifdef _GNU_SOURCE +struct hsearch_data { + struct __tab *__tab; + unsigned int __unused1; + unsigned int __unused2; +}; + +int hcreate_r(size_t, struct hsearch_data *); +void hdestroy_r(struct hsearch_data *); +int hsearch_r(ENTRY, ACTION, ENTRY **, struct hsearch_data *); +#endif + +void insque(void *, void *); +void remque(void *); + +void *lsearch(const void *, void *, size_t *, size_t, + int (*)(const void *, const void *)); +void *lfind(const void *, const void *, size_t *, size_t, + int (*)(const void *, const void *)); + +void *tdelete(const void *__restrict, void **__restrict, int(*)(const void *, const void *)); +void *tfind(const void *, void *const *, int(*)(const void *, const void *)); +void *tsearch(const void *, void **, int (*)(const void *, const void *)); +void twalk(const void *, void (*)(const void *, VISIT, int)); + +#ifdef _GNU_SOURCE +struct qelem { + struct qelem *q_forw, *q_back; + char q_data[1]; +}; + +void tdestroy(void *, void (*)(void *)); +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/semaphore.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/semaphore.h new file mode 100644 index 0000000000000000000000000000000000000000..a9d8d0af729f707db65e9aecacf40f5329a2a526 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/semaphore.h @@ -0,0 +1,51 @@ +#ifndef _SEMAPHORE_H +#define _SEMAPHORE_H +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#define __NEED_time_t +#define __NEED_struct_timespec +#include + +#include + +#define SEM_FAILED ((sem_t *)0) + +#ifndef __LITEOS__ +typedef struct { + volatile int __val[4*sizeof(long)/sizeof(int)]; +} sem_t; +#else +#include "los_sem_pri.h" + +/** + * @ingroup semaphore + * API parameter sructure + */ +typedef struct posix_sem { + LosSemCB *sem; +} sem_t; +#endif + +int sem_close(sem_t *); +int sem_destroy(sem_t *); +int sem_getvalue(sem_t *__restrict, int *__restrict); +int sem_init(sem_t *, int, unsigned); +sem_t *sem_open(const char *, int, ...); +int sem_post(sem_t *); +int sem_timedwait(sem_t *__restrict, const struct timespec *__restrict); +int sem_trywait(sem_t *); +int sem_unlink(const char *); +int sem_wait(sem_t *); + +#if _REDIR_TIME64 +__REDIR(sem_timedwait, __sem_timedwait_time64); +#endif + +#ifdef __cplusplus +} +#endif +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/setjmp.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/setjmp.h new file mode 100644 index 0000000000000000000000000000000000000000..2d43abf84f54ad9fc9501e0204816579c9b0de99 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/setjmp.h @@ -0,0 +1,41 @@ +#ifndef _SETJMP_H +#define _SETJMP_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#include + +typedef struct __jmp_buf_tag { + __jmp_buf __jb; + unsigned long __fl; + unsigned long __ss[128/sizeof(long)]; +} jmp_buf[1]; + +#if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \ + || defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) \ + || defined(_BSD_SOURCE) +typedef jmp_buf sigjmp_buf; +int sigsetjmp (sigjmp_buf, int); +_Noreturn void siglongjmp (sigjmp_buf, int); +#endif + +#if defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) \ + || defined(_BSD_SOURCE) +int _setjmp (jmp_buf); +_Noreturn void _longjmp (jmp_buf, int); +#endif + +int setjmp (jmp_buf); +_Noreturn void longjmp (jmp_buf, int); + +#define setjmp setjmp + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/shadow.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/shadow.h new file mode 100644 index 0000000000000000000000000000000000000000..2b1be413f3643f2724646f2c9f7b01cf2eace559 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/shadow.h @@ -0,0 +1,44 @@ +#ifndef _SHADOW_H +#define _SHADOW_H + +#ifdef __cplusplus +extern "C" { +#endif + +#define __NEED_FILE +#define __NEED_size_t + +#include + +#define SHADOW "/etc/shadow" + +struct spwd { + char *sp_namp; + char *sp_pwdp; + long sp_lstchg; + long sp_min; + long sp_max; + long sp_warn; + long sp_inact; + long sp_expire; + unsigned long sp_flag; +}; + +void setspent(void); +void endspent(void); +struct spwd *getspent(void); +struct spwd *fgetspent(FILE *); +struct spwd *sgetspent(const char *); +int putspent(const struct spwd *, FILE *); + +struct spwd *getspnam(const char *); +int getspnam_r(const char *, struct spwd *, char *, size_t, struct spwd **); + +int lckpwdf(void); +int ulckpwdf(void); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/signal.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/signal.h new file mode 100644 index 0000000000000000000000000000000000000000..26c14cf701a7e5e13ede783ab0a0d16f2fd4855a --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/signal.h @@ -0,0 +1,298 @@ +/** + * @defgroup signal Signal + * @ingroup posix + */ + +#ifndef _SIGNAL_H +#define _SIGNAL_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include "bits/pthread_types.h" + +#if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \ + || defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) \ + || defined(_BSD_SOURCE) + +#ifdef _GNU_SOURCE +#define __ucontext ucontext +#endif + +#define __NEED_size_t +#define __NEED_pid_t +#define __NEED_uid_t +#define __NEED_struct_timespec +#define __NEED_pthread_t +#define __NEED_pthread_attr_t +#define __NEED_time_t +#define __NEED_clock_t +#define __NEED_sigset_t + +#include + +#define SIG_BLOCK 0 +#define SIG_UNBLOCK 1 +#define SIG_SETMASK 2 + +#define SI_ASYNCNL (-60) +#define SI_TKILL (-6) +#define SI_SIGIO (-5) +#define SI_ASYNCIO (-4) +#define SI_MESGQ (-3) +#define SI_TIMER (-2) +#define SI_QUEUE (-1) +#define SI_USER 0 +#define SI_KERNEL 128 + +typedef struct sigaltstack stack_t; + +#endif + +#include + +#if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \ + || defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) \ + || defined(_BSD_SOURCE) + +#define SIG_HOLD ((void (*)(int)) 2) + +#define FPE_INTDIV 1 +#define FPE_INTOVF 2 +#define FPE_FLTDIV 3 +#define FPE_FLTOVF 4 +#define FPE_FLTUND 5 +#define FPE_FLTRES 6 +#define FPE_FLTINV 7 +#define FPE_FLTSUB 8 + +#define ILL_ILLOPC 1 +#define ILL_ILLOPN 2 +#define ILL_ILLADR 3 +#define ILL_ILLTRP 4 +#define ILL_PRVOPC 5 +#define ILL_PRVREG 6 +#define ILL_COPROC 7 +#define ILL_BADSTK 8 + +#define SEGV_MAPERR 1 +#define SEGV_ACCERR 2 +#define SEGV_BNDERR 3 +#define SEGV_PKUERR 4 + +#define BUS_ADRALN 1 +#define BUS_ADRERR 2 +#define BUS_OBJERR 3 +#define BUS_MCEERR_AR 4 +#define BUS_MCEERR_AO 5 + +#define CLD_EXITED 1 +#define CLD_KILLED 2 +#define CLD_DUMPED 3 +#define CLD_TRAPPED 4 +#define CLD_STOPPED 5 +#define CLD_CONTINUED 6 + +union sigval { + int sival_int; + void *sival_ptr; +}; + +typedef struct { +#ifdef __SI_SWAP_ERRNO_CODE + int si_signo, si_code, si_errno; +#else + int si_signo, si_errno, si_code; +#endif + union { + char __pad[128 - 2*sizeof(int) - sizeof(long)]; + struct { + union { + struct { + pid_t si_pid; + uid_t si_uid; + } __piduid; + struct { + int si_timerid; + int si_overrun; + } __timer; + } __first; + union { + union sigval si_value; + struct { + int si_status; + clock_t si_utime, si_stime; + } __sigchld; + } __second; + } __si_common; + struct { + void *si_addr; + short si_addr_lsb; + union { + struct { + void *si_lower; + void *si_upper; + } __addr_bnd; + unsigned si_pkey; + } __first; + } __sigfault; + struct { + long si_band; + int si_fd; + } __sigpoll; + struct { + void *si_call_addr; + int si_syscall; + unsigned si_arch; + } __sigsys; + } __si_fields; +} siginfo_t; +#define si_pid __si_fields.__si_common.__first.__piduid.si_pid +#define si_uid __si_fields.__si_common.__first.__piduid.si_uid +#define si_status __si_fields.__si_common.__second.__sigchld.si_status +#define si_utime __si_fields.__si_common.__second.__sigchld.si_utime +#define si_stime __si_fields.__si_common.__second.__sigchld.si_stime +#define si_value __si_fields.__si_common.__second.si_value +#define si_addr __si_fields.__sigfault.si_addr +#define si_addr_lsb __si_fields.__sigfault.si_addr_lsb +#define si_lower __si_fields.__sigfault.__first.__addr_bnd.si_lower +#define si_upper __si_fields.__sigfault.__first.__addr_bnd.si_upper +#define si_pkey __si_fields.__sigfault.__first.si_pkey +#define si_band __si_fields.__sigpoll.si_band +#define si_fd __si_fields.__sigpoll.si_fd +#define si_timerid __si_fields.__si_common.__first.__timer.si_timerid +#define si_overrun __si_fields.__si_common.__first.__timer.si_overrun +#define si_ptr si_value.sival_ptr +#define si_int si_value.sival_int +#define si_call_addr __si_fields.__sigsys.si_call_addr +#define si_syscall __si_fields.__sigsys.si_syscall +#define si_arch __si_fields.__sigsys.si_arch + +struct sigaction { + union { + void (*sa_handler)(int); + void (*sa_sigaction)(int, siginfo_t *, void *); + } __sa_handler; + sigset_t sa_mask; + int sa_flags; + void (*sa_restorer)(void); +}; +#define sa_handler __sa_handler.sa_handler +#define sa_sigaction __sa_handler.sa_sigaction + +#ifdef __LITEOS__ +typedef void (*sa_sighandler_t)(int); + +typedef void (*sa_siginfoaction_t)(int, siginfo_t *, void *); +#endif + +struct sigevent { + union sigval sigev_value; + int sigev_signo; + int sigev_notify; + void (*sigev_notify_function)(union sigval); + pthread_attr_t *sigev_notify_attributes; + char __pad[56-3*sizeof(long)]; +}; + +#define SIGEV_SIGNAL 0 +#define SIGEV_NONE 1 +#define SIGEV_THREAD 2 + +int __libc_current_sigrtmin(void); +int __libc_current_sigrtmax(void); + +#define SIGRTMIN (__libc_current_sigrtmin()) +#define SIGRTMAX (__libc_current_sigrtmax()) + +int kill(pid_t, int); + +int sigemptyset(sigset_t *); +int sigfillset(sigset_t *); +int sigaddset(sigset_t *, int); +int sigdelset(sigset_t *, int); +int sigismember(const sigset_t *, int); + +int sigprocmask(int, const sigset_t *__restrict, sigset_t *__restrict); +int sigsuspend(const sigset_t *); +int sigaction(int, const struct sigaction *__restrict, struct sigaction *__restrict); +int sigpending(sigset_t *); +int sigwait(const sigset_t *__restrict, int *__restrict); +int sigwaitinfo(const sigset_t *__restrict, siginfo_t *__restrict); +int sigtimedwait(const sigset_t *__restrict, siginfo_t *__restrict, const struct timespec *__restrict); +int sigqueue(pid_t, int, union sigval); + +int pthread_sigmask(int, const sigset_t *__restrict, sigset_t *__restrict); +int pthread_kill(pthread_t, int); + +void psiginfo(const siginfo_t *, const char *); +void psignal(int, const char *); + +#endif + +#if defined(_XOPEN_SOURCE) || defined(_BSD_SOURCE) || defined(_GNU_SOURCE) +int killpg(pid_t, int); +int sigaltstack(const stack_t *__restrict, stack_t *__restrict); +int sighold(int); +int sigignore(int); +int siginterrupt(int, int); +int sigpause(int); +int sigrelse(int); +void (*sigset(int, void (*)(int)))(int); +#define TRAP_BRKPT 1 +#define TRAP_TRACE 2 +#define TRAP_BRANCH 3 +#define TRAP_HWBKPT 4 +#define TRAP_UNK 5 +#define POLL_IN 1 +#define POLL_OUT 2 +#define POLL_MSG 3 +#define POLL_ERR 4 +#define POLL_PRI 5 +#define POLL_HUP 6 +#define SS_ONSTACK 1 +#define SS_DISABLE 2 +#define SS_AUTODISARM (1U << 31) +#define SS_FLAG_BITS SS_AUTODISARM +#endif + +#if defined(_BSD_SOURCE) || defined(_GNU_SOURCE) +#define NSIG _NSIG +typedef void (*sig_t)(int); +#endif + +#ifdef _GNU_SOURCE +typedef void (*sighandler_t)(int); +void (*bsd_signal(int, void (*)(int)))(int); +int sigisemptyset(const sigset_t *); +int sigorset (sigset_t *, const sigset_t *, const sigset_t *); +int sigandset(sigset_t *, const sigset_t *, const sigset_t *); + +#define SA_NOMASK SA_NODEFER +#define SA_ONESHOT SA_RESETHAND +#endif + +#define SIG_ERR ((void (*)(int))-1) +#define SIG_DFL ((void (*)(int)) 0) +#define SIG_IGN ((void (*)(int)) 1) + +typedef int sig_atomic_t; + +void (*signal(int, void (*)(int)))(int); +int raise(int); + +#if _REDIR_TIME64 +#if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \ + || defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) \ + || defined(_BSD_SOURCE) +__REDIR(sigtimedwait, __sigtimedwait_time64); +#endif +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/spawn.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/spawn.h new file mode 100644 index 0000000000000000000000000000000000000000..8eb73e003a65e3cb40abdc3c47371084522b9864 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/spawn.h @@ -0,0 +1,83 @@ +#ifndef _SPAWN_H +#define _SPAWN_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#define __NEED_mode_t +#define __NEED_pid_t +#define __NEED_sigset_t + +#include + +struct sched_param; + +#define POSIX_SPAWN_RESETIDS 1 +#define POSIX_SPAWN_SETPGROUP 2 +#define POSIX_SPAWN_SETSIGDEF 4 +#define POSIX_SPAWN_SETSIGMASK 8 +#define POSIX_SPAWN_SETSCHEDPARAM 16 +#define POSIX_SPAWN_SETSCHEDULER 32 +#define POSIX_SPAWN_USEVFORK 64 +#define POSIX_SPAWN_SETSID 128 + +typedef struct { + int __flags; + pid_t __pgrp; + sigset_t __def, __mask; + int __prio, __pol; + void *__fn; + char __pad[64-sizeof(void *)]; +} posix_spawnattr_t; + +typedef struct { + int __pad0[2]; + void *__actions; + int __pad[16]; +} posix_spawn_file_actions_t; + +int posix_spawn(pid_t *__restrict, const char *__restrict, const posix_spawn_file_actions_t *, + const posix_spawnattr_t *__restrict, char *const *__restrict, char *const *__restrict); +int posix_spawnp(pid_t *__restrict, const char *__restrict, const posix_spawn_file_actions_t *, + const posix_spawnattr_t *__restrict, char *const *__restrict, char *const *__restrict); + +int posix_spawnattr_init(posix_spawnattr_t *); +int posix_spawnattr_destroy(posix_spawnattr_t *); + +int posix_spawnattr_setflags(posix_spawnattr_t *, short); +int posix_spawnattr_getflags(const posix_spawnattr_t *__restrict, short *__restrict); + +int posix_spawnattr_setpgroup(posix_spawnattr_t *, pid_t); +int posix_spawnattr_getpgroup(const posix_spawnattr_t *__restrict, pid_t *__restrict); + +int posix_spawnattr_setsigmask(posix_spawnattr_t *__restrict, const sigset_t *__restrict); +int posix_spawnattr_getsigmask(const posix_spawnattr_t *__restrict, sigset_t *__restrict); + +int posix_spawnattr_setsigdefault(posix_spawnattr_t *__restrict, const sigset_t *__restrict); +int posix_spawnattr_getsigdefault(const posix_spawnattr_t *__restrict, sigset_t *__restrict); + +int posix_spawnattr_setschedparam(posix_spawnattr_t *__restrict, const struct sched_param *__restrict); +int posix_spawnattr_getschedparam(const posix_spawnattr_t *__restrict, struct sched_param *__restrict); +int posix_spawnattr_setschedpolicy(posix_spawnattr_t *, int); +int posix_spawnattr_getschedpolicy(const posix_spawnattr_t *__restrict, int *__restrict); + +int posix_spawn_file_actions_init(posix_spawn_file_actions_t *); +int posix_spawn_file_actions_destroy(posix_spawn_file_actions_t *); + +int posix_spawn_file_actions_addopen(posix_spawn_file_actions_t *__restrict, int, const char *__restrict, int, mode_t); +int posix_spawn_file_actions_addclose(posix_spawn_file_actions_t *, int); +int posix_spawn_file_actions_adddup2(posix_spawn_file_actions_t *, int, int); + +#if defined(_BSD_SOURCE) || defined(_GNU_SOURCE) +int posix_spawn_file_actions_addchdir_np(posix_spawn_file_actions_t *__restrict, const char *__restrict); +int posix_spawn_file_actions_addfchdir_np(posix_spawn_file_actions_t *, int); +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/stdalign.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/stdalign.h new file mode 100644 index 0000000000000000000000000000000000000000..2cc94be3f6d7e4b65839cbcd35a1e5286139e4c8 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/stdalign.h @@ -0,0 +1,20 @@ +#ifndef _STDALIGN_H +#define _STDALIGN_H + +#ifndef __cplusplus + +/* this whole header only works in C11 or with compiler extensions */ +#if __STDC_VERSION__ < 201112L && defined( __GNUC__) +#define _Alignas(t) __attribute__((__aligned__(t))) +#define _Alignof(t) __alignof__(t) +#endif + +#define alignas _Alignas +#define alignof _Alignof + +#endif + +#define __alignas_is_defined 1 +#define __alignof_is_defined 1 + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/stdarg.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/stdarg.h new file mode 100644 index 0000000000000000000000000000000000000000..3256f805001912e46a0cfdc23a8513bc6388de01 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/stdarg.h @@ -0,0 +1,21 @@ +#ifndef _STDARG_H +#define _STDARG_H + +#ifdef __cplusplus +extern "C" { +#endif + +#define __NEED_va_list + +#include + +#define va_start(v,l) __builtin_va_start(v,l) +#define va_end(v) __builtin_va_end(v) +#define va_arg(v,l) __builtin_va_arg(v,l) +#define va_copy(d,s) __builtin_va_copy(d,s) + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/stdbool.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/stdbool.h new file mode 100644 index 0000000000000000000000000000000000000000..a9d7ab787839727b5fada461710a265afd1dff27 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/stdbool.h @@ -0,0 +1,14 @@ +#ifndef _STDBOOL_H +#define _STDBOOL_H + +#ifndef __cplusplus + +#define true 1 +#define false 0 +#define bool _Bool + +#endif + +#define __bool_true_false_are_defined 1 + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/stdc-predef.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/stdc-predef.h new file mode 100644 index 0000000000000000000000000000000000000000..f8cd4b8911366530ab3231f25dbd93826f769add --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/stdc-predef.h @@ -0,0 +1,10 @@ +#ifndef _STDC_PREDEF_H +#define _STDC_PREDEF_H + +#define __STDC_ISO_10646__ 201206L + +#if !defined(__GCC_IEC_559) || __GCC_IEC_559 > 0 +#define __STDC_IEC_559__ 1 +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/stddef.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/stddef.h new file mode 100644 index 0000000000000000000000000000000000000000..d4f4478ac6958b9ffb96469ae793d8885c2ad801 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/stddef.h @@ -0,0 +1,29 @@ +#ifndef _STDDEF_H +#define _STDDEF_H + +#ifdef __cplusplus +#define NULL 0L +#else +#ifndef NULL +#define NULL ((void*)0) +#endif +#endif + +#define __NEED_ptrdiff_t +#define __NEED_size_t +#define __NEED_wchar_t +#ifndef __LITEOS__ +#if __STDC_VERSION__ >= 201112L || __cplusplus >= 201103L +#define __NEED_max_align_t +#endif +#endif + +#include + +#if __GNUC__ > 3 +#define offsetof(type, member) __builtin_offsetof(type, member) +#else +#define offsetof(type, member) ((size_t)( (char *)&(((type *)0)->member) - (char *)0 )) +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/stdint.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/stdint.h new file mode 100644 index 0000000000000000000000000000000000000000..a2968197dbe2312c46de0d41f09675b56846984c --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/stdint.h @@ -0,0 +1,117 @@ +#ifndef _STDINT_H +#define _STDINT_H + +#define __NEED_int8_t +#define __NEED_int16_t +#define __NEED_int32_t +#define __NEED_int64_t + +#define __NEED_uint8_t +#define __NEED_uint16_t +#define __NEED_uint32_t +#define __NEED_uint64_t + +#define __NEED_intptr_t +#define __NEED_uintptr_t + +#define __NEED_intmax_t +#define __NEED_uintmax_t + +#include + +typedef int8_t int_fast8_t; +typedef int64_t int_fast64_t; + +typedef int8_t int_least8_t; +typedef int16_t int_least16_t; +typedef int32_t int_least32_t; +typedef int64_t int_least64_t; + +typedef uint8_t uint_fast8_t; +typedef uint64_t uint_fast64_t; + +typedef uint8_t uint_least8_t; +typedef uint16_t uint_least16_t; +typedef uint32_t uint_least32_t; +typedef uint64_t uint_least64_t; + +#define INT8_MIN (-1-0x7f) +#define INT16_MIN (-1-0x7fff) +#define INT32_MIN (-1-0x7fffffff) +#define INT64_MIN (-1-0x7fffffffffffffff) + +#define INT8_MAX (0x7f) +#define INT16_MAX (0x7fff) +#define INT32_MAX (0x7fffffff) +#define INT64_MAX (0x7fffffffffffffff) + +#define UINT8_MAX (0xff) +#define UINT16_MAX (0xffff) +#define UINT32_MAX (0xffffffffu) +#define UINT64_MAX (0xffffffffffffffffu) + +#define INT_FAST8_MIN INT8_MIN +#define INT_FAST64_MIN INT64_MIN + +#define INT_LEAST8_MIN INT8_MIN +#define INT_LEAST16_MIN INT16_MIN +#define INT_LEAST32_MIN INT32_MIN +#define INT_LEAST64_MIN INT64_MIN + +#define INT_FAST8_MAX INT8_MAX +#define INT_FAST64_MAX INT64_MAX + +#define INT_LEAST8_MAX INT8_MAX +#define INT_LEAST16_MAX INT16_MAX +#define INT_LEAST32_MAX INT32_MAX +#define INT_LEAST64_MAX INT64_MAX + +#define UINT_FAST8_MAX UINT8_MAX +#define UINT_FAST64_MAX UINT64_MAX + +#define UINT_LEAST8_MAX UINT8_MAX +#define UINT_LEAST16_MAX UINT16_MAX +#define UINT_LEAST32_MAX UINT32_MAX +#define UINT_LEAST64_MAX UINT64_MAX + +#define INTMAX_MIN INT64_MIN +#define INTMAX_MAX INT64_MAX +#define UINTMAX_MAX UINT64_MAX + +#define WINT_MIN 0U +#define WINT_MAX UINT32_MAX + +#if L'\0'-1 > 0 +#define WCHAR_MAX (0xffffffffu+L'\0') +#define WCHAR_MIN (0+L'\0') +#else +#define WCHAR_MAX (0x7fffffff+L'\0') +#define WCHAR_MIN (-1-0x7fffffff+L'\0') +#endif + +#define SIG_ATOMIC_MIN INT32_MIN +#define SIG_ATOMIC_MAX INT32_MAX + +#include + +#define INT8_C(c) c +#define INT16_C(c) c +#define INT32_C(c) c + +#define UINT8_C(c) c +#define UINT16_C(c) c +#define UINT32_C(c) c ## U + +#if UINTPTR_MAX == UINT64_MAX +#define INT64_C(c) c ## L +#define UINT64_C(c) c ## UL +#define INTMAX_C(c) c ## L +#define UINTMAX_C(c) c ## UL +#else +#define INT64_C(c) c ## LL +#define UINT64_C(c) c ## ULL +#define INTMAX_C(c) c ## LL +#define UINTMAX_C(c) c ## ULL +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/stdio.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/stdio.h new file mode 100644 index 0000000000000000000000000000000000000000..d6490547119e4cbda8fa745a1c67deef43e18f0b --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/stdio.h @@ -0,0 +1,1415 @@ +/** + * @defgroup stdio Stdio + * @ingroup libc + */ + +#ifndef _STDIO_H +#define _STDIO_H + +#ifdef __LITEOS__ +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#define __NEED_FILE +#define __NEED___isoc_va_list +#define __NEED_size_t + +#if __STDC_VERSION__ < 201112L +#define __NEED_struct__IO_FILE +#endif + +#if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \ + || defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) \ + || defined(_BSD_SOURCE) +#define __NEED_ssize_t +#define __NEED_off_t +#define __NEED_va_list +#endif + +#ifdef __LITEOS__ +#define __NEED_int64_t +#endif + +#include + +#ifdef __cplusplus +#define NULL 0L +#else +#ifndef NULL +#define NULL ((void*)0) +#endif +#endif + +#undef EOF +#define EOF (-1) + +#undef SEEK_SET +#undef SEEK_CUR +#undef SEEK_END +#define SEEK_SET 0 +#define SEEK_CUR 1 +#define SEEK_END 2 + +#define _IOFBF 0 +#define _IOLBF 1 +#define _IONBF 2 + +#ifdef __LITEOS__ +#define BUFSIZ (8 * 1024) +#else +#define BUFSIZ 1024 +#endif +#define FILENAME_MAX 4096 +#define FOPEN_MAX 1000 +#define TMP_MAX 10000 +#define L_tmpnam 20 + +#ifndef __LITEOS__ +typedef union _G_fpos64_t { + char __opaque[16]; + long long __lldata; + double __align; +} fpos_t; +#else +typedef off_t fpos_t; +#endif + +extern FILE *const stdin; +extern FILE *const stdout; +extern FILE *const stderr; + +#define stdin (stdin) +#define stdout (stdout) +#define stderr (stderr) + +/** + * @ingroup stdio + * + * @par Description: + * The fopen() function shall open the file whose pathname is the string pointed to by pathname, and associates a stream + * with it. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #FILE* Upon successful completion, fopen() shall return a pointer to the object controlling the stream.\n + * Otherwise, a null pointer shall be returned, and errno shall be set to indicate the error. + * + * @par Errors + *
        + *
      • EINVAL: The mode argument is not a valid mode.
      • + *
      • EMFILE: The file descriptor is greater than SHRT_MAX
      • + *
      + * + * @par Dependency: + *
      • stdio.h
      + * @see open | fdopen | fclose + */ +FILE *fopen(const char *__restrict, const char *__restrict); + +/** + * @ingroup stdio + * + * @par Description: + * The freopen() function opens the file whose name is the string pointed to by path and associates the stream pointed + * to by stream with it. The original stream (if it exists) is closed. + * + * @attention + *
        + *
      • when the file where is in the target directory mounted by the file system, the func returns NULL.
      • + *
      + * + * @retval #FILE* The freopen() function shall return a pointer to a stream, if it completes successfully;\n + * otherwise, a null pointer shall be returned and errno set to indicate the error. + * + * @par Dependency: + *
      • stdio.h
      + * @see open | fopen | fclose + */ +FILE *freopen(const char *__restrict, const char *__restrict, FILE *__restrict); + +/** + * @ingroup stdio + * + * @par Description: + * The fclose() function shall clear the end-of-file and error indicators for the stream to which stream points. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #int The fclose() shall return 0, if it completes successfully;\n + * otherwise, it shall return EOF. + * + * @par Errors + *
        + *
      • EBADF: The file descriptor underlying stream is not valid.
      • + *
      + * + * @par Dependency: + *
      • stdio.h
      + * @see fopen | fflush + */ +int fclose(FILE *); + +/** + * @ingroup stdio + * + * @par Description: + * The remove() function shell remove a file or directory. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #int The remove() function shall return 0, if it completes successfully;\n + * otherwise, it shall return -1 and set errno to indicate the error. + * + * @par Dependency: + *
      • stdio.h
      + * @see unlink | rmdir + */ +int remove(const char *); + +/** + * @ingroup stdio + * + * @par Description: + * The rename() function shall change the name of a file. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #int Upon successful completion, the rename() function shall return 0.\n + * Otherwise, it shall return -1 and errno shall be set to indicate the error. + * + * @par Errors + *
        + *
      • EINVAL: Invalid argument.
      • + *
      • ENOENT: No such file or directory./li> + *
      • EXDEV: Cross-device link.
      • + *
      • ENOSYS: Rename function not implemented.
      • + *
      • EBUSY: Device or resource busy.
      • + *
      • EEXIST: File exists.
      • + *
      • ENXIO: No such device or address.
      • + *
      + * + * @par Dependency: + *
      • stdio.h
      + * @see rmdir | unlink + */ +int rename(const char *, const char *); + +/** + * @ingroup stdio + * + * @par Description: + * The feof() function shall test the end-of-file indicator for the stream pointed to by stream. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #int The feof() shall return non-zero if and only if the end-of-file indicator is set for stream. + * @par Dependency: + *
      • stdio.h
      + * @see clearerr | ferror | fopen + */ +int feof(FILE *); + +/** + * @ingroup stdio + * + * @par Description: + * The ferror() function shall test the error indicator for the stream pointed to by stream. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #int The ferror() function shall return non-zero if and only if the error indicator is set for stream. + * @par Dependency: + *
      • stdio.h
      + * @see clearerr | feof | fopen + */ +int ferror(FILE *); + +/** + * @ingroup stdio + * + * @par Description: + * If stream points to an output stream or an update stream in which the most recent operation was not input, fflush() + * shall cause any unwritten data for that stream to be written to the file, [CX] [Option Start] and the last data + * modification and last file status change timestamps of the underlying file shall be marked for update. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #int The fflush() function shall return 0, if it completes successfully;\n + * otherwise, it shall set the error indicator for the stream, return EOF and set errno to + * indicate the error. + * + * @par Errors + *
        + *
      • EBADF: The file descriptor underlying stream is not valid.
      • + *
      • ENOBUFS: No buffer space available.
      • + *
      + * + * @par Dependency: + *
      • stdio.h
      + * @see sync | write | fclose | fopen + */ +int fflush(FILE *); + +/** + * @ingroup stdio + * + * @par Description: + * The clearerr() function shall clear the end-of-file and error indicators for the stream to which stream points. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #void None. + * @par Dependency: + *
      • stdio.h
      + * @see None + */ +void clearerr(FILE *); + +/** + * @ingroup stdio + * + * @par Description: + * The fseek() function shall set the file-position indicator for the stream pointed to by stream. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #int The fseek() function shall return 0, if it completes successfully;\n + * otherwise, it shall return -1 and set errno to indicate the error. + * + * @par Errors + *
        + *
      • ESPIPE: Illegal seek.
      • + *
      • EINVAL: The whence argument to fseek() was not SEEK_SET, SEEK_END, or SEEK_CUR.
      • + *
      • EBADF: The stream specified is not a seekable stream.
      • + *
      + * + * @par Dependency: + *
      • stdio.h
      + * @see fopen | fgetpos | fseeko + */ +int fseek(FILE *, long, int); + +/** + * @ingroup stdio + * + * @par Description: + * The ftell() function shall obtain the current value of the file-position indicator for the stream pointed to by stream. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #long The ftell() function shall return the current offset, if it completes successfully;\n + * otherwise, it shall return -1 and set errno to indicate the error. + * + * @par Errors + *
        + *
      • ESPIPE: Illegal seek.
      • + *
      + * + * @par Dependency: + *
      • stdio.h
      + * @see fseek | ftello + */ +long ftell(FILE *); + +/** + * @ingroup stdio + * + * @par Description: + * The rewind() function sets the file position indicator for the stream pointed to by stream + * to the beginning of the file. It is equivalent to:\n + * (void) fseek(stream, 0L, SEEK_SET) + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #void None. + * + * @par Dependency: + *
      • stdio.h
      + * @see fseek | fseeko + */ +void rewind(FILE *); + +/** + * @ingroup stdio + * + * @par Description: + * The fgetpos() function shall store the current values of the parse state (if any) and file position indicator for the + * stream pointed to by stream in the object pointed to by pos. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #int The fgetpos() function shall return 0, if it completes successfully;\n + * otherwise, it shall return 1 and set errno to indicate the error. + * + * @par Errors + *
        + *
      • ESPIPE: Illegal seek.
      • + *
      + * + * @par Dependency: + *
      • stdio.h
      + * @see fopen | fsetpos + */ +int fgetpos(FILE *__restrict, fpos_t *__restrict); + +/** + * @ingroup stdio + * + * @par Description: + * The fsetpos() function shall set the file position and state indicators for the stream. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #int The fsetpos() function shall return 0, if it completes successfully;\n + * otherwise, it shall return -1 and set errno to indicate the error. + * + * @par Errors + *
        + *
      • ESPIPE: Illegal seek.
      • + *
      • EINVAL: The whence argument to fseek() was not SEEK_SET, SEEK_END, or SEEK_CUR.
      • + *
      • EBADF: The stream specified is not a seekable stream.
      • + *
      + * + * @par Dependency: + *
      • stdio.h
      + * @see fseeko | fgetpos + */ +int fsetpos(FILE *, const fpos_t *); + +/** + * @ingroup stdio + * + * @par Description: + * The fread() function shall read into the array pointed to by ptr up to nitems elements whose size is specified by + * size in bytes, from the stream pointed to by stream. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #size_t Upon successful completion, fread() shall return the number of elements successfully read + * which is less than nitems only if a read error or end-of-file is encountered. \n + * If size or nitems is 0, fread() shall return 0 and the contents of the array + * and the state of the stream remain unchanged.\n + * Otherwise, if a read error occurs, the error indicator for the stream shall be set, + * and errno shall be set to indicate the error. + * + * @par Errors + *
        + *
      • EEOF: The end of file has been reached
      • + *
      • EBADF: Bad file number.
      • + *
      + * + * @par Dependency: + *
      • stdio.h
      + * @see read | write | feof + */ +size_t fread(void *__restrict, size_t, size_t, FILE *__restrict); + +/** + * @ingroup stdio + * + * @par Description: + * The fwrite() function shall write, from the array pointed to by ptr, up to nitems elements whose size is specified by + * size, to the stream pointed to by stream. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #size_t The fwrite() function shall return the number of elements successfully written, + * which may be less than nitems if a write error is encountered. + * If size or nitems is 0, fwrite() shall return 0 and the state of the stream remains unchanged. + * Otherwise, if a write error occurs, the error indicator for the stream shall be set, + * and errno shall be set to indicate the error. + * + * @par Errors + *
        + *
      • EINVAL: Invalid argument.
      • + *
      • EBADF: Bad file number.
      • + *
      + * + * @par Dependency: + *
      • stdio.h
      + * @see puts | fwrite | ferror | fopen + */ +size_t fwrite(const void *__restrict, size_t, size_t, FILE *__restrict); + +/** + * @ingroup stdio + * + * @par Description: + * the fgetc() function shall obtain the next byte as an unsigned char converted to an int, from the input stream. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #int The fgetc() shall return the next byte from the input stream pointed to by stream + * @par Dependency: + *
      • stdio.h
      + * @see feof | ferror | fgets | fread | fscanf | getchar | getc | gets + */ +int fgetc(FILE *); + +/** + * @ingroup stdio + * + * @par Description: + * The getc() function shell get a byte from a stream. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #int The getc() function return the character read as an unsigned char + * cast to an int or EOF on end of file or error. + * + * @par Dependency: + *
      • stdio.h
      + * @see putc | getchar + */ +int getc(FILE *); + +/** + * @ingroup stdio + * + * @par Description: + * The getchar() function shell get a byte from a stdin stream. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #int The getchar() function return the character read as an unsigned char + * cast to an int or EOF on end of file or error. + * + * @par Dependency: + *
      • stdio.h
      + * @see putchar | getc + */ +int getchar(void); + +/** + * @ingroup stdio + * + * @par Description: + * The ungetc() function shall push the byte specified by c (converted to an unsigned char) + * back onto the input stream pointed to by stream. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #int Upon successful completion, ungetc() shall return the byte pushed back after conversion.\n + * Otherwise, it shall return EOF. + * + * @par Dependency: + *
      • stdio.h
      + * @see fseek | getc | fsetpos + */ +int ungetc(int, FILE *); + +/** + * @ingroup stdio + * + * @par Description: + * The fputc() function shall write the byte (converted to an unsigned char) to the output stream. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #int The fputc() shall return the value it has written. Otherwise, it shall return EOF. + * @par Dependency: + *
      • stdio.h
      + * @see fprintf | fscanf | fputs + */ +int fputc(int, FILE *); + +/** + * @ingroup stdio + * + * @par Description: + * The putc() function shell put a byte from a stream. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #int The putc() function return the character written as an unsigned char + * cast to an int or EOF on end of file or error. + * + * @par Dependency: + *
      • stdio.h
      + * @see putchar | getc + */ +int putc(int, FILE *); + +/** + * @ingroup stdio + * + * @par Description: + * The putchar() function shell put a byte from a stdin stream. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #int The putchar() function return the character written as an unsigned char + * cast to an int or EOF on end of file or error. + * + * @par Dependency: + *
      • stdio.h
      + * @see getchar | putc + */ +int putchar(int); + +/** + * @ingroup stdio + * + * @par Description: + * The fgets() function shall read bytes from stream into the array pointed to by s until n-1 bytes are read, or a < + * newline> is read and transferred to s, or an end-of-file condition is encountered. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #char* Upon successful completion, fgets() shall return s. If the stream is at end-of-file, + * the end-of-file indicator for the stream shall be set and fgets() shall return a null pointer. + * If a read error occurs, the error indicator for the stream shall be set, + * fgets() shall return a null pointer, and shall set errno to indicate the error. + * + * @par Errors + *
        + *
      • EINVAL: Invalid argument.
      • + *
      + * + * @par Dependency: + *
      • stdio.h
      + * @see fgetc | fopen | fread | fscanf | getc + */ +char *fgets(char *__restrict, int, FILE *__restrict); +#if __STDC_VERSION__ < 201112L +/** + * @ingroup stdio + * + * @par Description: + * The gets() function shall get a string from a stdin stream. + * + * @attention + *
        + *
      • gets is unsafe, use fgets instead.
      • + *
      + * + * @retval #char* Upon successful completion, gets() shall return s; otherwise, it shall return NULL; + * + * @par Dependency: + *
      • stdio.h
      + * @see printf | dprintf | fprintf + */ +char *gets(char *); +#endif + +/** + * @ingroup stdio + * + * @par Description: + * The fputs() function shall writes the string s to stream. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #int The fputs() shall return the 0, if it completes successfully;\n + * Otherwise, it shall return EOF. + * + * @par Dependency: + *
      • stdio.h
      + * @see fopen | fputc | puts + */ +int fputs(const char *__restrict, FILE *__restrict); + +/** + * @ingroup stdio + * + * @par Description: + * The puts() function shell put a string on standard output. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #int Upon successful completion, puts() shall return 0. Otherwise, it shall return EOF, shall set an + * error indicator for the stream, and errno shall be set to indicate the error. + * + * @par Errors + *
        + *
      • EBADF: Bad file number.
      • + *
      + * + * @par Dependency: + *
      • stdio.h
      + * @see fputs | putc + */ +int puts(const char *); + +/** + * @ingroup stdio + * + * @par Description: + * The printf() function shall place output on the stdout stream. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #int The printf() function shall return the number of characters printed. + * + * @par Dependency: + *
      • stdio.h
      + * @see snprintf | dprintf | fprintf + */ +int printf(const char *__restrict, ...); + +/** + * @ingroup stdio + * + * @par Description: + * The fprintf() function shall place output on the named output stream. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #int The fprintf() functions shall return the number of bytes transmitted. + * @par Dependency: + *
      • stdio.h
      + * @see fputc | fscanf + */ +int fprintf(FILE *__restrict, const char *__restrict, ...); + +/** + * @ingroup stdio + * + * @par Description: + * The sprintf() function shall write to the string according to the format. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #int The sprintf() function shall return the number of characters printed. + * + * @par Dependency: + *
      • stdio.h
      + * @see printf | dprintf | fprintf + */ +int sprintf(char *__restrict, const char *__restrict, ...); + +/** + * @ingroup stdio + * + * @par Description: + * The snprintf() function shall write at most size bytes to the string. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #int The snprintf() function shall return the number of characters printed. + * + * @par Dependency: + *
      • stdio.h
      + * @see printf | dprintf | fprintf + */ +int snprintf(char *__restrict, size_t, const char *__restrict, ...); + +/** + * @ingroup stdio + * + * @par Description: + * The vprintf() function shall format output of a stdarg argument list to the stdout. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #int The vprintf() function shall return the number of characters printed. + * + * @par Dependency: + *
      • stdio.h
      + * @see printf | dprintf | fprintf + */ +int vprintf(const char *__restrict, __isoc_va_list); + +/** + * @ingroup stdio + * + * @par Description: + * The vfprintf() function shall format output of a stdarg argument list to the named file descriptor. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #int The vfprintf() function shall return the number of characters printed. + * + * @par Dependency: + *
      • stdio.h
      + * @see printf | dprintf | fprintf + */ +int vfprintf(FILE *__restrict, const char *__restrict, __isoc_va_list); + +/** + * @ingroup stdio + * + * @par Description: + * The vsprintf() function shall format output of a stdarg argument list to the string. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #int The vsprintf() function shall return the number of characters printed. + * + * @par Dependency: + *
      • stdio.h
      + * @see printf | dprintf | fprintf + */ +int vsprintf(char *__restrict, const char *__restrict, __isoc_va_list); + +/** + * @ingroup stdio + * + * @par Description: + * The vsnprintf() function shall format output of a stdarg argument list to the string at most size bytes. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #int The vsnprintf() function shall return the number of characters printed. + * + * @par Dependency: + *
      • stdio.h
      + * @see printf | dprintf | fprintf + */ +int vsnprintf(char *__restrict, size_t, const char *__restrict, __isoc_va_list); + +/** + * @ingroup stdio + * + * @par Description: + * The scanf() function scans shall read from the stdin stream + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #int On success, these functions return the number of input items successfully matched and assigned;\n + * this can be fewer than provided for, or even zero, in the event of an early matching failure.\n + * The value EOF is returned if the end of input is reached + * before either the first successful conversion or a matching failure occurs. + * + * @par Dependency: + *
      • stdio.h
      + * @see fprintf | getc | scanf + */ +int scanf(const char *__restrict, ...); + +/** + * @ingroup stdio + * + * @par Description: + * The fscanf() function scans shall read from the named input stream. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #int On success, these functions return the number of input items successfully matched and assigned;\n + * this can be fewer than provided for, or even zero, in the event of an early matching failure.\n + * The value EOF is returned if the end of input is reached + * before either the first successful conversion or a matching failure occurs. + * + * @par Dependency: + *
      • stdio.h
      + * @see fprintf | getc | scanf + */ +int fscanf(FILE *__restrict, const char *__restrict, ...); + +/** + * @ingroup stdio + * + * @par Description: + * The scanf() function scans shall read from the named string. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #int On success, these functions return the number of input items successfully matched and assigned;\n + * this can be fewer than provided for, or even zero, in the event of an early matching failure.\n + * The value EOF is returned if the end of input is reached + * before either the first successful conversion or a matching failure occurs. + * + * @par Dependency: + *
      • stdio.h
      + * @see fprintf | getc | scanf + */ +int sscanf(const char *__restrict, const char *__restrict, ...); + +/** + * @ingroup stdio + * + * @par Description: + * The vscanf() function scans a variable argument list from the standard input. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #int On success, the vscanf() function return the number of input items successfully matched and assigned;\n + * this can be fewer than provided for, or even zero, in the event of an early matching failure. + * + * @par Dependency: + *
      • stdio.h
      + * @see vfscanf | getc | fprintf + */ +int vscanf(const char *__restrict, __isoc_va_list); + +/** + * @ingroup stdio + * + * @par Description: + * The vfscanf() function scans a variable argument list from the named input stream. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #int On success, these functions return the number of input items successfully matched and assigned;\n + * this can be fewer than provided for, or even zero, in the event of an early matching failure.\n + * The value EOF is returned if the end of input is reached + * before either the first successful conversion or a matching failure occurs. + * + * @par Dependency: + *
      • stdio.h
      + * @see vscanf | getc | fprintf + */ +int vfscanf(FILE *__restrict, const char *__restrict, __isoc_va_list); +int vsscanf(const char *__restrict, const char *__restrict, __isoc_va_list); + +/** + * @ingroup stdio + * + * @par Description: + * The perror() function shell write error messages to standard error. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #void None. + * + * @par Dependency: + *
      • stdio.h
      + * @see fprintf | fputc + */ +void perror(const char *); + +/** + * @ingroup stdio + * + * @par Description: + * The setvbuf() function may be used after the stream pointed to by stream + * is associated with an open file but before any other operation + * (other than an unsuccessful call to setvbuf()) is performed on the stream. + * + * @attention + *
        + *
      • when buf is NULL, the default requested memory size is BUFSIZ.
      • + *
      + * + * @retval #int Upon successful completion, setvbuf() shall return 0.\n + * Otherwise, it shall return EOF if an invalid value + * is given for type or if the request cannot be honored, + * and may set errno to indicate the error. + * + * @par Errors + *
        + *
      • EINVAL: Invalid argument.
      • + *
      • ENOBUFS: No buffer space available.
      • + *
      + * + * @par Dependency: + *
      • stdio.h
      + * @see setbuf | fopen + */ +int setvbuf(FILE *__restrict, char *__restrict, int, size_t); + +/** + * @ingroup stdio + * + * @par Description: + * The setvbuf() function assign buffering to a stream, and is exactly equivalent to the call\n + * setvbuf(stream, buf, buf ? _IOFBF : _IONBF, BUFSIZ); + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #void None. + * + * @par Errors + *
        + *
      • EINVAL: Invalid argument.
      • + *
      • ENOBUFS: No buffer space available.
      • + *
      + * + * @par Dependency: + *
      • stdio.h
      + * @see setvbuf | fopen + */ +void setbuf(FILE *__restrict, char *__restrict); + +/** + * @ingroup stdio + * + * @par Description: + * The tmpnam() function shall generate a string that is a valid pathname that does not name an existing file. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #char* Upon successful completion, tmpnam() shall return a pointer to a string. If no suitable string can be generated, the + * tmpnam() function shall return a null pointer. + * + * @par Dependency: + *
      • stdio.h
      + * @see fopen | mkstemp + */ +char *tmpnam(char *); +FILE *tmpfile(void); + +#if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \ + || defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) \ + || defined(_BSD_SOURCE) +FILE *fmemopen(void *__restrict, size_t, const char *__restrict); +FILE *open_memstream(char **, size_t *); + +/** + * @ingroup stdio + * + * @par Description: + * The fdopen() function shall associate a stream with a file descriptor. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #FILE* The fdopen() function shall return a pointer to a stream, if it completes successfully;\n + * otherwise, a null pointer shall be returned and errno set to indicate the error. + * + * @par Errors + *
        + *
      • EMFILE: The file descriptor is greater than SHRT_MAX
      • + *
      • EINVAL: The mode argument is not a valid mode.
      • + *
      + * + * @par Dependency: + *
      • stdio.h
      + * @see fclose | fopen | open + */ +FILE *fdopen(int, const char *); +FILE *popen(const char *, const char *); +int pclose(FILE *); + +/** + * @ingroup stdio + * + * @par Description: + * The fileno() function shall return the integer file descriptor associated with the stream. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #int The fileno() function return the integer value of the file descriptor associated with stream.\n + * Otherwise, the value -1 shall be returned and errno set to indicate the error. + * + * @par Errors + *
        + *
      • EBADF: The stream is not associated with a file.
      • + *
      + * + * @par Dependency: + *
      • stdio.h
      + * @see fdopen | fopen + */ +int fileno(FILE *); + +/** + * @ingroup stdio + * + * @par Description: + * The fseeko() function shall set the file-position indicator for the stream pointed to by stream. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #int The fseeko() function shall return 0, if it completes successfully;\n + * otherwise, it shall return -1 and set errno to indicate the error. + * + * @par Errors + *
        + *
      • ESPIPE: Illegal seek.
      • + *
      • EINVAL: The whence argument to fseek() was not SEEK_SET, SEEK_END, or SEEK_CUR.
      • + *
      • EBADF: The stream specified is not a seekable stream.
      • + *
      + * + * @par Dependency: + *
      • stdio.h
      + * @see fopen | fgetpos | fseek + */ +int fseeko(FILE *, off_t, int); + +/** + * @ingroup stdio + * + * @par Description: + * The ftello() function shall obtain the current value of the file-position indicator for the stream pointed to by stream. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #off_t The ftello() function shall return the current offset, if it completes successfully;\n + * otherwise, it shall return -1 and set errno to indicate the error. + * + * @par Errors + *
        + *
      • ESPIPE: Illegal seek.
      • + *
      + * + * @par Dependency: + *
      • stdio.h
      + * @see fseeko | ftell + */ +off_t ftello(FILE *); +/* func realization is used dprintf in printf.c, func declaration conflict hear*/ +#ifndef __LITEOS__ +int dprintf(int, const char *__restrict, ...); +#else +int dprintf(const char *fmt, ...); +#endif +int vdprintf(int, const char *__restrict, __isoc_va_list); + +/** + * @ingroup stdio + * + * @par Description: + * The flockfile() function shall acquire for a thread ownership of a (FILE *) object. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #void None. + * + * @par Dependency: + *
      • stdio.h
      + * @see ftrylockfile | funlockfile + */ +void flockfile(FILE *); + +/** + * @ingroup stdio + * + * @par Description: + * The ftrylockfile() function shall acquire for a thread ownership of a (FILE *) object if the object is available; + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #int The ftrylockfile() function shall return zero for success and non-zero to indicate that the lock cannot be acquired. + * + * @par Dependency: + *
      • stdio.h
      + * @see flockfile | funlockfile + */ +int ftrylockfile(FILE *); + +/** + * @ingroup stdio + * + * @par Description: + * The funlockfile() function shall relinquish the ownership granted to the thread. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #void None. + * + * @par Dependency: + *
      • stdio.h
      + * @see flockfile | ftrylockfile + */ +void funlockfile(FILE *); + +/** + * @ingroup stdio + * + * @par Description: + * The getc_unlocked() function shell get a byte from a stream without the thread-safe. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #int The getc_unlocked() function return the character read as an unsigned char cast to an int or EOF on end of file or error. + * + * @par Dependency: + *
      • stdio.h
      + * @see putc_unlocked | getc + */ +int getc_unlocked(FILE *); + +/** + * @ingroup stdio + * + * @par Description: + * The getchar_unlocked() function shell get a byte from a stdin stream without the thread-safe. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #int The getchar_unlocked() function return the character read as an unsigned char cast to an int or EOF on end of file or error. + * + * @par Dependency: + *
      • stdio.h
      + * @see putchar_unlocked | getchar + */ +int getchar_unlocked(void); +int putc_unlocked(int, FILE *); +int putchar_unlocked(int); +ssize_t getdelim(char **__restrict, size_t *__restrict, int, FILE *__restrict); +ssize_t getline(char **__restrict, size_t *__restrict, FILE *__restrict); +int renameat(int, const char *, int, const char *); +char *ctermid(char *); +#define L_ctermid 20 +#endif + + +#if defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) \ + || defined(_BSD_SOURCE) +#define P_tmpdir "/tmp" +char *tempnam(const char *, const char *); +#endif + +#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE) +#define L_cuserid 20 +char *cuserid(char *); +void setlinebuf(FILE *); +void setbuffer(FILE *, char *, size_t); +int fgetc_unlocked(FILE *); +int fputc_unlocked(int, FILE *); +int fflush_unlocked(FILE *); +size_t fread_unlocked(void *, size_t, size_t, FILE *); +size_t fwrite_unlocked(const void *, size_t, size_t, FILE *); +void clearerr_unlocked(FILE *); +int feof_unlocked(FILE *); +int ferror_unlocked(FILE *); +int fileno_unlocked(FILE *); +int getw(FILE *); +int putw(int, FILE *); +char *fgetln(FILE *, size_t *); + +/** + * @ingroup stdio + * + * @par Description: + * The asprintf() function shell allocate a string large enough to hold the output. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #int The asprintf() function return the number of bytes printed, if it completes successfully;\n + * otherwise, it shall return -1. + * + * @par Errors + *
        + *
      • ENOMEM: Insufficient storage space is available.
      • + *
      + * + * @par Dependency: + *
      • stdio.h
      + * @see malloc | free | printf + */ +int asprintf(char **, const char *, ...); + +/** + * @ingroup stdio + * + * @par Description: + * The vasprintf() function shell allocate a string large enough to hold the output. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #int The vasprintf() function return the number of bytes printed, if it completes successfully;\n + * otherwise, it shall return -1. + * + * @par Errors + *
        + *
      • ENOMEM: Insufficient storage space is available.
      • + *
      + * + * @par Dependency: + *
      • stdio.h
      + * @see malloc | free | printf + */ +int vasprintf(char **, const char *, __isoc_va_list); +#endif + +#ifdef _GNU_SOURCE +char *fgets_unlocked(char *, int, FILE *); +int fputs_unlocked(const char *, FILE *); + +typedef ssize_t (cookie_read_function_t)(void *, char *, size_t); +typedef ssize_t (cookie_write_function_t)(void *, const char *, size_t); +typedef int (cookie_seek_function_t)(void *, off_t *, int); +typedef int (cookie_close_function_t)(void *); + +typedef struct _IO_cookie_io_functions_t { + cookie_read_function_t *read; + cookie_write_function_t *write; + cookie_seek_function_t *seek; + cookie_close_function_t *close; +} cookie_io_functions_t; + +FILE *fopencookie(void *, const char *, cookie_io_functions_t); +#endif + +#if defined(_LARGEFILE64_SOURCE) || defined(_GNU_SOURCE) +#ifdef __LITEOS__ +#define off64_t int64_t +#define fpos64_t fpos_t +FILE *tmpfile64(void); +FILE *fopen64(const char *, const char *); +FILE *freopen64(const char *, const char *, FILE *); +int fseeko64(FILE *, off64_t, int); +off64_t ftello64(FILE *); +int fsetpos64(FILE *, const fpos64_t *); +int fsetpos64(FILE *, const fpos64_t *); +#else +#define tmpfile64 tmpfile +#define fopen64 fopen +#define freopen64 freopen +#define fseeko64 fseeko +#define ftello64 ftello +#define fgetpos64 fgetpos +#define fsetpos64 fsetpos +#define fpos64_t fpos_t +#define off64_t off_t +#endif +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/stdio_ext.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/stdio_ext.h new file mode 100644 index 0000000000000000000000000000000000000000..e3ab7fd4f9c6b1bb90af537dcb19d7ede9491309 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/stdio_ext.h @@ -0,0 +1,34 @@ +#ifndef _STDIO_EXT_H +#define _STDIO_EXT_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#define FSETLOCKING_QUERY 0 +#define FSETLOCKING_INTERNAL 1 +#define FSETLOCKING_BYCALLER 2 + +void _flushlbf(void); +int __fsetlocking(FILE *, int); +int __fwriting(FILE *); +int __freading(FILE *); +int __freadable(FILE *); +int __fwritable(FILE *); +int __flbf(FILE *); +size_t __fbufsize(FILE *); +size_t __fpending(FILE *); +int __fpurge(FILE *); + +size_t __freadahead(FILE *); +const char *__freadptr(FILE *, size_t *); +void __freadptrinc(FILE *, size_t); +void __fseterr(FILE *); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/stdlib.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/stdlib.h new file mode 100644 index 0000000000000000000000000000000000000000..1342c4ebf7c7a025fd55c7ee2ac00bd446fc551d --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/stdlib.h @@ -0,0 +1,741 @@ +/** + * @defgroup stdlib Stdlib + * @ingroup libc + */ + +#ifndef _STDLIB_H +#define _STDLIB_H + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef __LITEOS__ +#include +#endif + +#include + +#ifdef __cplusplus +#define NULL 0L +#else +#ifndef NULL +#define NULL ((void*)0) +#endif +#endif + +#define __NEED_size_t +#define __NEED_wchar_t + +#include + +/** + *@ingroup stdlib + * + *@par Description: + *This API is used to convert a string to an integer. + * The call is equivalent to strtol(str, (char **)NULL, 10). + * If the value cannot be represented, the behavior is undefined. + *@attention + *
        + *
      • None.
      • + *
      + * + *@retval int converted value if the value can be represented. + * + *@par Dependency: + *
      • stdlib.h
      + *@see strtol + */ +int atoi (const char *); + +/** + *@ingroup stdlib + * + *@par Description: + *This API is used to convert a string to a long integer. + * The call is equivalent to strtol(str, (char **)NULL, 10). + * If the value cannot be represented, the behavior is undefined. + *@attention + *
        + *
      • None.
      • + *
      + * + *@retval long converted value if the value can be represented. + * + *@par Dependency: + *
      • stdlib.h
      + *@see strtol + */ +long atol (const char *); + +/** + *@ingroup stdlib + * + *@par Description: + *This API is used to convert a string to a long long integer. + * The call is equivalent to strtol(str, (char **)NULL, 10). + * If the value cannot be represented, the behavior is undefined. + *@attention + *
        + *
      • None.
      • + *
      + * + *@retval long-long converted value if the value can be represented. + * + *@par Dependency: + *
      • stdlib.h
      + *@see strtol + */ +long long atoll (const char *); + +/** + *@ingroup stdlib + * + *@par Description: + *This API is used to convert a string to a double-precision number. + * The call is equivalent to strtod(str, (char **)NULL). + * If the value cannot be represented, the behavior is undefined. + *@attention + *
        + *
      • None.
      • + *
      + * + *@retval double converted value if the value can be represented. + * + *@par Errors + *
        + *
      • ERANGE: The value to be returned would cause overflow or underflow.
      • + *
      + * + *@par Dependency: + *
      • stdlib.h
      + *@see strtod + */ +double atof (const char *); + +/** + *@ingroup stdlib + * + *@par Description: + *This API is used to convert a string to a float-precision number. + * If the value cannot be represented, the behavior is undefined. + *@attention + *
        + *
      • None.
      • + *
      + * + *@retval float converted value if the value can be represented. + * + *@par Errors + *
        + *
      • ERANGE: The value to be returned would cause overflow or underflow.
      • + *
      + * + *@par Dependency: + *
      • stdlib.h
      + *@see strtod | strtold + */ +float strtof (const char *__restrict, char **__restrict); + +/** + *@ingroup stdlib + * + *@par Description: + *This API is used to convert a string to a double-precision number. + * If the value cannot be represented, the behavior is undefined. + *@attention + *
        + *
      • None.
      • + *
      + * + *@retval double converted value if the value can be represented. + * + *@par Errors + *
        + *
      • ERANGE: The value to be returned would cause overflow or underflow.
      • + *
      + * + *@par Dependency: + *
      • stdlib.h
      + *@see strtof | strtold + */ +double strtod (const char *__restrict, char **__restrict); + +/** + *@ingroup stdlib + * + *@par Description: + *This API is used to convert a string to a long-double-precision number. + * If the value cannot be represented, the behavior is undefined. + *@attention + *
        + *
      • None.
      • + *
      + * + *@retval long-double converted value if the value can be represented. + * + *@par Errors + *
        + *
      • ERANGE: The value to be returned would cause overflow or underflow.
      • + *
      + * + *@par Dependency: + *
      • stdlib.h
      + *@see strtod | strtof + */ +long double strtold (const char *__restrict, char **__restrict); + +/** + *@ingroup stdlib + * + *@par Description: + *This API is used to convert a string to a long integer. + * Ensure that "base" is between 2 and 36 inclusive, or the special value of 0. + *@attention + *
        + *
      • None.
      • + *
      + * + *@retval non-zero The converted value, successful completion. + *@retval 0 Fails to convert, with any of the following error codes in errno. + * + *@par Errors + *
        + *
      • ERANGE: The converted value is out of range {LONG_MIN, LONG_MAX}.
      • + *
      • EINVAL: The value of "base" is not supported.
      • + *
      + * + *@par Dependency: + *
      • stdlib.h
      + *@see strtoll | strtoul | strtoull + */ +long strtol (const char *__restrict, char **__restrict, int); + +/** + *@ingroup stdlib + * + *@par Description: + *This API is used to convert a string to a unsigned long integer. + * Ensure that "base" is between 2 and 36 inclusive, or the special value of 0. + *@attention + *
        + *
      • None.
      • + *
      + * + *@retval non-zero The converted value, successful completion. + *@retval 0 Fails to convert, with any of the following error codes in errno. + * + *@par Errors + *
        + *
      • ERANGE: The converted value is out of range ULONG_MAX.
      • + *
      • EINVAL: The value of "base" is not supported.
      • + *
      + * + *@par Dependency: + *
      • stdlib.h
      + *@see strtoll | strtoul | strtoull + */ +unsigned long strtoul (const char *__restrict, char **__restrict, int); + + +/** + *@ingroup stdlib + * + *@par Description: + *This API is used to convert a string to a long long integer. + * Ensure that "base" is between 2 and 36 inclusive, or the special value of 0. + *@attention + *
        + *
      • None.
      • + *
      + * + *@retval non-zero The converted value, successful completion. + *@retval 0 Fails to convert, with any of the following error codes in errno. + * + *@par Errors + *
        + *
      • ERANGE: The converted value is out of range {LLONG_MIN, LLONG_MAX}.
      • + *
      • EINVAL: The value of "base" is not supported.
      • + *
      + * + *@par Dependency: + *
      • stdlib.h
      + *@see strtoll | strtoul | strtoull + */ +long long strtoll (const char *__restrict, char **__restrict, int); + + +/** + *@ingroup stdlib + * + *@par Description: + *This API is used to convert a string to a unsigned long long integer. + * Ensure that "base" is between 2 and 36 inclusive, or the special value of 0. + *@attention + *
        + *
      • None.
      • + *
      + * + *@retval non-zero The converted value, successful completion. + *@retval 0 Fails to convert, with any of the following error codes in errno. + * + *@par Errors + *
        + *
      • ERANGE: The converted value is out of range ULLONG_MAX.
      • + *
      • EINVAL: The value of "base" is not supported.
      • + *
      + * + *@par Dependency: + *
      • stdlib.h
      + *@see strtoll | strtoul | strtoull + */ +unsigned long long strtoull (const char *__restrict, char **__restrict, int); + +/** + *@ingroup stdlib + * + *@par Description: + *This API is used to compute a sequence of pseudo-random integers in the range [0, RAND_MAX]. + *@attention + *
        + *
      • None.
      • + *
      + * + *@par Dependency: + *
      • stdlib.h
      + *@see random + */ +int rand (void); + +/** + *@ingroup stdlib + * + *@par Description: + *This API is used to set the argument as a seed for a new sequence of pseudo-random + * numbers to be returned by subsequent calls to rand(). + *@attention + *
        + *
      • None.
      • + *
      + * + *@par Dependency: + *
      • stdlib.h
      + *@see srandom + */ +void srand (unsigned); + +void *malloc (size_t); +void *calloc (size_t, size_t); +void *realloc (void *, size_t); +void free (void *); +void *aligned_alloc(size_t, size_t); + +/** + *@ingroup stdlib + * + *@par Description: + *This API is used to abort the system, the system enters swi exception, print backtrace and then + * Entering an infinite loop. + *@attention + *
        + *
      • Normal interrupts will not be responded, only NMI exception can be triggered.
      • + *
      + * + *@par Dependency: + *
      • stdlib.h
      + *@see exit + */ +_Noreturn void abort (void); + +/** + *@ingroup stdlib + * + *@par Description: + *This API is defined, but just return 0. + *@attention + *
        + *
      • None.
      • + *
      + * + *@par Dependency: + *
      • stdlib.h
      + *@see abort | exit + */ +int atexit (void (*) (void)); + +/** + *@ingroup stdlib + * + *@par Description: + *This API is used to terminate a thread, the current thread enters an infinite loop. + *@attention + *
        + *
      • The current thread enters an infinite loop, the thread with a lower priority than + the current thread can not obtain cpu resources.
      • + *
      • CPU occupancy rate will up to 100%.
      • + *
      + * + *@par Dependency: + *
      • stdlib.h
      + *@see abort + */ +_Noreturn void exit (int); +_Noreturn void _Exit (int); +int at_quick_exit (void (*) (void)); +_Noreturn void quick_exit (int); + +/** + *@ingroup stdlib + * + *@par Description: + *This API is defined, but just return NULL. + *@attention + *
        + *
      • None.
      • + *
      + * + *@par Dependency: + *
      • stdlib.h
      + *@see putenv | setenv | unsetenv + */ +char *getenv (const char *); + +/** + *@ingroup stdlib + * + *@par Description: + *This API is defined, but just return 0. + *@attention + *
        + *
      • None.
      • + *
      + * + *@par Dependency: + *
      • stdlib.h
      + *@see None. + */ +int system (const char *); + +/** + *@ingroup stdlib + * + *@par Description: + *This API is used to search an array of "nmemb" objects, the initial element of which + * is pointed to by base0", for an element that matches the object pointed to by "key". + * The size of each element in the array is specified by "size". + *@attention + *
        + *
      • None.
      • + *
      + * + *@retval NULL No match is found. + *@retval void* A pointer to a matching member of the array. + * + *@par Dependency: + *
      • stdlib.h
      + *@see None. + */ +void *bsearch (const void *, const void *, size_t, size_t, int (*)(const void *, const void *)); + +/** + *@ingroup stdlib + * + *@par Description: + *This API is used to sort an array of "nmemb", the initial element of which + * is pointed to by base", The size of each object, in bytes, is specified by the "size". + * If the "nmemb" has the value zero, the comparison function pointed to by "compar" + * would not be called and no rearrangement will take place. + *@attention + *
        + *
      • None.
      • + *
      + * + *@par Dependency: + *
      • stdlib.h
      + *@see None. + */ +void qsort (void *, size_t, size_t, int (*)(const void *, const void *)); + +/** + *@ingroup stdlib + * + *@par Description: + *This API is used to compute the absolute value of its integer operand "j". + * If the value cannot be represented, the behavior is undefined. + *@attention + *
        + *
      • None.
      • + *
      + * + *@retval int The absolute value of its integer operand. + * + *@par Dependency: + *
      • stdlib.h
      + *@see labs | llabs + */ +int abs (int); + +/** + *@ingroup stdlib + * + *@par Description: + *This API is used to compute the absolute value of the long integer operand "j". + * If the value cannot be represented, the behavior is undefined. + *@attention + *
        + *
      • None.
      • + *
      + * + *@retval long The absolute value of its integer operand. + * + *@par Dependency: + *
      • stdlib.h
      + *@see abs | llabs + */ +long labs (long); + +/** + *@ingroup stdlib + * + *@par Description: + *This API is used to compute the absolute value of the long long integer operand "j". + * If the value cannot be represented, the behavior is undefined. + *@attention + *
        + *
      • None.
      • + *
      + * + *@retval long-long The absolute value of its integer operand. + * + *@par Dependency: + *
      • stdlib.h
      + *@see labs | abs + */ +long long llabs (long long); + +typedef struct { int quot, rem; } div_t; +typedef struct { long quot, rem; } ldiv_t; +typedef struct { long long quot, rem; } lldiv_t; + +div_t div (int, int); +ldiv_t ldiv (long, long); +lldiv_t lldiv (long long, long long); + +int mblen (const char *, size_t); +int mbtowc (wchar_t *__restrict, const char *__restrict, size_t); +int wctomb (char *, wchar_t); +size_t mbstowcs (wchar_t *__restrict, const char *__restrict, size_t); +size_t wcstombs (char *__restrict, const wchar_t *__restrict, size_t); + +/** + * @ingroup stdlib + * Define unsuccessful termination to 1. + */ +#define EXIT_FAILURE 1 + +/** + * @ingroup stdlib + * Define successful termination to 0. + */ +#define EXIT_SUCCESS 0 + +size_t __ctype_get_mb_cur_max(void); +#define MB_CUR_MAX (__ctype_get_mb_cur_max()) + +/** + * @ingroup stdlib + * Define Maximum value returned by rand() to 0x7fffffff. + */ +#define RAND_MAX (0x7fffffff) + + +#if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \ + || defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) \ + || defined(_BSD_SOURCE) + +#define WNOHANG 1 +#define WUNTRACED 2 + +#define WEXITSTATUS(s) (((s) & 0xff00) >> 8) +#define WTERMSIG(s) ((s) & 0x7f) +#define WSTOPSIG(s) WEXITSTATUS(s) +#define WIFEXITED(s) (!WTERMSIG(s)) +#define WIFSTOPPED(s) ((short)((((s)&0xffff)*0x10001)>>8) > 0x7f00) +#define WIFSIGNALED(s) (((s)&0xffff)-1U < 0xffu) + +/** + *@ingroup stdlib + * + *@par Description: + *This API is used to allocate "size" bytes memory aligned on a boundary specified by "alignment". + *The value of "alignment" shall be a power of two and multiple of sizeof(void *). + *The value of errno would not be modified. + *@attention + *
        + *
      • None.
      • + *
      + * + *@retval 0 Success to allocate memory. + *@retval EINVAL The value of "alignment" shall be a power of two and multiple of sizeof(void *). + *@retval ENOMEM There is no enough memory. + * + *@par Dependency: + *
      • stdlib.h
      + *@see malloc | free + */ +int posix_memalign (void **, size_t, size_t); +int setenv (const char *, const char *, int); +int unsetenv (const char *); + +/** + *@ingroup stdlib + * + *@par Description: + *This API is defined, but just return -1. + *@attention + *
        + *
      • None.
      • + *
      + * + *@par Dependency: + *
      • stdlib.h
      + *@see mktemp | mkstemps + */ +int mkstemp (char *); +int mkostemp (char *, int); +char *mkdtemp (char *); +int getsubopt (char **, char *const *, char **); +int rand_r (unsigned *); + +#endif + + +#if defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) \ + || defined(_BSD_SOURCE) +char *realpath (const char *__restrict, char *__restrict); + +/** + *@ingroup stdlib + * + *@par Description: + *This API is used to generate a pseudo-random integer in the range [0, RAND_MAX]. + *@attention + *
        + *
      • None.
      • + *
      + * + *@par Dependency: + *
      • stdlib.h
      + *@see srandom + */ +long int random (void); + +/** + *@ingroup stdlib + * + *@par Description: + *This API is used to set the argument as a seed for a new sequence of pseudo-random + * numbers to be returned by subsequent calls to random(). + *@attention + *
        + *
      • None.
      • + *
      + * + *@par Dependency: + *
      • stdlib.h
      + *@see srandom + */ +void srandom (unsigned int); +char *initstate (unsigned int, char *, size_t); +char *setstate (char *); +int putenv (char *); +int posix_openpt (int); +int grantpt (int); +int unlockpt (int); +char *ptsname (int); +char *l64a (long); +long a64l (const char *); +void setkey (const char *); +double drand48 (void); +double erand48 (unsigned short [3]); +long int lrand48 (void); +long int nrand48 (unsigned short [3]); +long mrand48 (void); +long jrand48 (unsigned short [3]); +void srand48 (long); +unsigned short *seed48 (unsigned short [3]); +void lcong48 (unsigned short [7]); +#endif + +#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE) +#include + +/** + *@ingroup stdlib + * + *@par Description: + *This API is defined, but just return NULL. + *@attention + *
        + *
      • None.
      • + *
      + * + *@par Dependency: + *
      • stdlib.h
      + *@see mkstemp + */ +char *mktemp (char *); + +/** + *@ingroup stdlib + * + *@par Description: + *This API is defined, but just return -1. + *@attention + *
        + *
      • None.
      • + *
      + * + *@par Dependency: + *
      • stdlib.h
      + *@see mkstemp | mkstemps + */ +int mkstemps (char *, int); +int mkostemps (char *, int, int); +void *valloc (size_t); +void *memalign(size_t, size_t); +int getloadavg(double *, int); +int clearenv(void); +#define WCOREDUMP(s) ((s) & 0x80) +#define WIFCONTINUED(s) ((s) == 0xffff) +#endif + +#ifdef _GNU_SOURCE +int ptsname_r(int, char *, size_t); +char *ecvt(double, int, int *, int *); +char *fcvt(double, int, int *, int *); +char *gcvt(double, int, char *); +char *secure_getenv(const char *); +struct __locale_struct; +#ifndef __LITEOS__ +float strtof_l(const char *__restrict, char **__restrict, struct __locale_struct *); +double strtod_l(const char *__restrict, char **__restrict, struct __locale_struct *); +long double strtold_l(const char *__restrict, char **__restrict, struct __locale_struct *); +#endif +#endif + +#if defined(_LARGEFILE64_SOURCE) || defined(_GNU_SOURCE) +#define mkstemp64 mkstemp +#define mkostemp64 mkostemp +#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE) +#define mkstemps64 mkstemps +#define mkostemps64 mkostemps +#endif +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/stdnoreturn.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/stdnoreturn.h new file mode 100644 index 0000000000000000000000000000000000000000..5c6aeeb008cd8150dda6bd2421b85627ee6014dd --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/stdnoreturn.h @@ -0,0 +1,7 @@ +#ifndef _STDNORETURN_H +#define _STDNORETURN_H +#ifndef __cplusplus +#include +#define noreturn _Noreturn +#endif +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/string.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/string.h new file mode 100644 index 0000000000000000000000000000000000000000..ee08facd32c8bfcd0b62f1ab5fa3f80f3a39d826 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/string.h @@ -0,0 +1,799 @@ +/** + * @defgroup libc Libc + * @defgroup string String + * @ingroup libc + */ + +#ifndef _STRING_H +#define _STRING_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#ifdef __cplusplus +#define NULL 0L +#else +#ifndef NULL +#define NULL ((void*)0) +#endif +#endif + +#define __NEED_size_t +#if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \ + || defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) \ + || defined(_BSD_SOURCE) +#define __NEED_locale_t +#endif + +#include + +/** + * @ingroup string + * + * @par Description: + * The memcpy() function copies n bytes from memory area src to memory area dest. + * The memory areas must not overlap. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #void* The memcpy() function returns a pointer to dest. + * + * @par Dependency: + *
      • string.h
      + * @see memmove | strcpy | strncpy | wmemcpy + */ +void *memcpy (void *__restrict, const void *__restrict, size_t); + +/** + * @ingroup string + * + * @par Description: + * The memmove() function copies n bytes from memory area src to memory area dest. + * The memory areas may overlap: copying takes place as though the bytes in src are + * first copied into a temporary array that does not overlap src or dest, and + * the bytes are then copied from the temporary array to dest. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #void* The memmove() function returns a pointer to dest. + * + * @par Dependency: + *
      • string.h
      + * @see strcpy | strncpy | wmemcpy + */ +void *memmove (void *, const void *, size_t); + +/** + * @ingroup string + * + * @par Description: + * The memset() function fills the first n bytes of the memory area + * pointed to by s with the constant byte c. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #void* The memset() function returns a pointer to the memory area s. + * + * @par Dependency: + *
      • string.h
      + * @see wmemset + */ +void *memset (void *, int, size_t); + +/** + * @ingroup string + * + * @par Description: + * The memcmp() function compares the first n bytes (each interpreted as unsigned char) + * of the memory areas s1 and s2. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #int The memcmp() function returns 0 if the parameters s1 and s2 are identical. + * If s1 is greater than s2, a value greater than 0 is returned. + * If s1 is less than s2, a value less than 0 is returned. + * + * @par Dependency: + *
      • string.h
      + * @see strcasecmp | strcmp | strcoll | strncasecmp | strncmp | wmemcmp + */ +int memcmp (const void *, const void *, size_t); + +/** + * @ingroup string + * + * @par Description: + * The memchr() function scans the initial n bytes of the memory area + * pointed to by src for the first instance of c. Both c and the bytes of + * the memory area pointed to by src are interpreted as unsigned char. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #void* The memchr() function returns a pointer to the matching + * byte or NULL if the character does not occur in the given memory + * area. + * + * @par Dependency: + *
      • string.h
      + * @see strchr | strpbrk | strrchr | strsep | strspn | strstr | wmemchr + */ +void *memchr (const void *, int, size_t); + +/** + * @ingroup string + * + * @par Description: + * The strcpy() function copies the string pointed to by from, including + * the terminating null byte ("\0"), to the buffer pointed to by to. + * The strings may not overlap, and the destination string to must be + * large enough to receive the copy. Beware of buffer overruns! + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #char* The function returns a pointer to the resulting string to. + * + * @par Dependency: + *
      • string.h
      + * @see memcpy | stpcpy | strdup + */ +char *strcpy (char *__restrict, const char *__restrict); + +/** + * @ingroup string + * + * @par Description: + * The strncpy() function shall copy not more than n + * bytes (bytes that follow a NUL character are not copied) from the + * array pointed to by src to the array pointed to by dst. + * If the array pointed to by src is a string that is shorter than n + * bytes, NUL characters shall be appended to the copy in the array + * pointed to by dst, until n bytes in all are written. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #char* The strncpy() function shall return dst. + * + * @par Dependency: + *
      • string.h
      + * @see strcpy | wcsncpy + */ +char *strncpy (char *__restrict, const char *__restrict, size_t); + +/** + * @ingroup string + * + * @par Description: + * The strcat() function appends the src string to the dst string, + * overwriting the terminating null byte ("\0") at the end of dst, and + * then adds a terminating null byte. The strings may not overlap, and + * the dst string must have enough space for the result. If dst is + * not large enough, program behavior is unpredictable. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #char* The function returns a pointer to the resulting string dst. + * + * @par Dependency: + *
      • string.h
      + * @see memcpy | strcpy | strncpy + */ +char *strcat (char *__restrict, const char *__restrict); + +/** + * @ingroup string + * + * @par Description: + * The strncat() function will use at most n bytes from src and src does not + * need to be null-terminated if it contains n or more bytes. As with strcat(), + * the resulting string in dst is always null-terminated. If src contains n or more bytes, + * strncat() writes n+1 bytes to dst(n from src plus the terminating null byte). + * Therefore, the size of dst must be at least strlen(dst)+n+1. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #char* The strncat() function returns pointer to the + * resulting string dst. + * + * @par Dependency: + *
      • string.h
      + * @see memcpy | strcpy | strncpy + */ +char *strncat (char *__restrict, const char *__restrict, size_t); + +/** + * @ingroup string + * + * @par Description: + * The strcmp() function shall compare the string pointed to by s1 to the + * string pointed to by s2. The sign of a non-zero return value shall be + * determined by the sign of the difference between the values of the first + * pair of bytes (both interpreted as type unsigned char) that differ in the + * strings being compared. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #int Upon completion, strcmp() shall return an integer greater than, + * equal to, or less than 0, if the string pointed to by s1 is greater than, equal to, + * or less than the string pointed to by s2, respectively. + * + * @par Dependency: + *
      • string.h
      + * @see strncmp + */ +int strcmp (const char *, const char *); + +/** + * @ingroup string + * + * @par Description: + * The strncmp() function compares only the first (at most) n bytes of s1 and s2. + * It returns an integer less than, equal to, or greater than zero if s1 is found, + * respectively, to be less than, to match, or be greater than s2. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #int The strncmp() function returns an integer less than, + * equal to, or greater than zero if s1 (or the first n bytes thereof) + * is found, respectively, to be less than, to match, or be greater than + * s2. + * + * @par Dependency: + *
      • string.h
      + * @see memcmp | strcasecmp | strcoll | strncasecmp | wcscmp | wcsncmp + */ +int strncmp (const char *, const char *, size_t); + +/** + * @ingroup string + * + * @par Description: + * The strcoll() function compares the two strings s1 and s2. It + * returns an integer less than, equal to, or greater than zero if s1 is + * found, respectively, to be less than, to match, or be greater than s2. + * + * @attention + *
        + *
      • Liteos does not compare strings according to the order in which + * text is specified by LC_COLLATE.
      • + *
      + * + * @retval #int The strcoll() function returns an integer less than, equal to, or + * greater than zero if s1 is found, respectively, to be less than, to + * match, or be greater than s2, when both are interpreted as + * appropriate for the current locale. + * + * @par Dependency: + *
      • string.h
      + * @see memcmp | setlocale | strcasecmp | strcmp | strxfrm + */ +int strcoll (const char *, const char *); + +/** + * @ingroup string + * + * @par Description: + * + * The strxfrm() function Transforms the string src and places the result into dst. It copies at most + * n characters into dst including the null terminating character. The + * transformation occurs such that strcmp applied to two separate converted + * strings returns the same value as strcoll applied to the same two strings. If + * overlapping occurs, the result is undefined. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #size_t The strxfrm() function returns the number of bytes required to store + * the transformed string in dst excluding the terminating null byte + * ("\0"). If the value returned is n or more, the contents of dst are + * indeterminate. + * + * @par Dependency: + *
      • string.h
      + * @see memcmp | setlocale | strcasecmp | strcmp | strcoll + */ +size_t strxfrm (char *__restrict, const char *__restrict, size_t); + +/** + * @ingroup string + * + * @par Description: + * The strchr() function returns a pointer to the first occurrence of the character c in the string s. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #char* Upon completion, strchr() shall return a pointer to the byte, or a null pointer + * if the byte was not found. + * + * @par Dependency: + *
      • string.h
      + * @see memcpy | memmove | stpcpy | strdup | wcsncpy + */ +char *strchr (const char *, int); + +/** + * @ingroup string + * + * @par Description: + * The strrchr() function returns a pointer to the last occurrence of + * the character c in the string s. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #char* The strrchr() function returns a pointer to the matched + * character or NULL if the character is not found. The terminating + * null byte is considered part of the string, so that if c is specified + * as "\0", the function returns a pointer to the terminator. + * + * + * @par Dependency: + *
      • string.h
      + * @see memchr | strlen | strpbrk | strsep | strspn | strstr | strtok | wcschr + */ +char *strrchr (const char *, int); + +/** + * @ingroup string + * + * @par Description: + * The strcspn() function calculates the length of the initial segment + * of s1 which consists entirely of bytes not in s2. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #size_t The strcspn() function returns the number of bytes in the initial + * segment of s1 which are not in the string s2. + * + * @par Dependency: + *
      • string.h
      + * @see memchr | strchr | strpbrk | strsep | strstr | strtok + */ +size_t strcspn (const char *, const char *); + +/** + * @ingroup string + * + * @par Description: + * The strspn() function calculates the length (in bytes) of the initial + * segment of s1 which consists entirely of bytes in s2. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #size_t The strspn() function returns the number of bytes in the initial + * segment of s1 which consist only of bytes from s2. + * + * @par Dependency: + *
      • string.h
      + * @see memchr | strchr | strpbrk | strsep | strstr | strtok + */ +size_t strspn (const char *, const char *); + +/** + * @ingroup string + * + * @par Description: + * The strpbrk() function shall locate the first occurrence in the + * string pointed to by s1 of any byte from the string pointed to by s2. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #char* Upon successful completion, strpbrk() shall return a pointer to the + * byte or a null pointer if no byte from s2 occurs in s1. + * + * @par Dependency: + *
      • string.h
      + * @see strchr | strrchr + */ +char *strpbrk (const char *, const char *); + +/** + * @ingroup string + * + * @par Description: + * The strstr() function finds the first occurrence of the substring + * find in the string s. The terminating null bytes ("\0") are + * not compared. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #char* The function returns a pointer to the beginning of the located + * substring, or NULL if the substring is not found. + * + * @par Dependency: + *
      • string.h
      + * @see memchr | strcasecmp | strchr | strpbrk | strsep | strspn | strtok + */ +char *strstr (const char *, const char *); + +/** + * @ingroup string + * + * @par Description: + * The strtok() function breaks a string into a sequence of zero or more + * nonempty tokens. On the first call to strtok(), the string to be + * parsed should be specified in str. In each subsequent call that + * should parse the same string, str must be NULL. + * The delim argument specifies a set of bytes that delimit the tokens + * in the parsed string. The caller may specify different strings in + * delim in successive calls that parse the same string. + * Each call to strtok() returns a pointer to a null-terminated string + * containing the next token. This string does not include the + * delimiting byte. If no more tokens are found, strtok() returns NULL. + * A sequence of calls to strtok() that operate on the same string + * maintains a pointer that determines the point from which to start + * searching for the next token. The first call to strtok() sets this + * pointer to point to the first byte of the string. The start of the + * next token is determined by scanning forward for the next + * nondelimiter byte in str. If such a byte is found, it is taken as + * the start of the next token. If no such byte is found, then there + * are no more tokens, and strtok() returns NULL. (A string that is + * empty or that contains only delimiters will thus cause strtok() to + * return NULL on the first call.) + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #char* The strtok() function returns a pointer to the next + * token, or NULL if there are no more tokens. + * + * @par Dependency: + *
      • string.h
      + * @see memchr | strchr | strpbrk | strsep | strspn | strstr + */ +char *strtok (char *__restrict, const char *__restrict); + +/** + * @ingroup string + * + * @par Description: + * The strlen() function calculates the length of the string s, + * excluding the terminating null byte ("\0"). + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #size_t The strlen() function returns the number of bytes in the string s. + * + * + * @par Dependency: + *
      • string.h
      + * @see strnlen | wcslen + * + */ +size_t strlen (const char *); + +/** + * @ingroup string + * + * @par Description: + * The strerror() function returns a pointer to a string that describes + * the error code passed in the argument error_number. (For example, if error_number is EINVAL, + * the returned description will be "Invalid argument".) This string must not be + * modified by the application, but may be modified by a subsequent call + * to strerror(). No other library function, including + * perror(), will modify this string. + * + * @attention + *
        + *
      • The errno is not to be set in Liteos.
      • + *
      + * + * @retval #char* The strerror() function returns the appropriate error description string, + * or return NULL if can not find error description string. + * + * @par Dependency: + *
      • string.h
      + * @see perror + */ +char *strerror (int); + +#if defined(_BSD_SOURCE) || defined(_GNU_SOURCE) +#include +#endif + +#if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \ + || defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) \ + || defined(_BSD_SOURCE) + +/** + * @ingroup string + * + * @par Description: + * The strtok_r() function is a reentrant version strtok(). The saveptr + * argument is a pointer to a char* variable that is used internally by + * strtok_r() in order to maintain context between successive calls that + * parse the same string. + * On the first call to strtok_r(), str should point to the string to be + * parsed, and the value of saveptr is ignored. In subsequent calls, + * str should be NULL, and saveptr should be unchanged since the + * previous call. + * Different strings may be parsed concurrently using sequences of calls + * to strtok_r() that specify different saveptr arguments. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #char* The strtok_r() function returns a pointer to the next + * token, or NULL if there are no more tokens. + * + * @par Dependency: + *
      • string.h
      + * @see memchr | strchr | strpbrk | strsep | strspn | strstr + */ +char *strtok_r (char *__restrict, const char *__restrict, char **__restrict); + +/** + * @ingroup string + * + * @par Description: + * The strerror_r() function shall map the error number in error_number + * to a locale-dependent error message string and shall return the string + * in the buffer pointed to by buf, with length buf_len. If the value of + * error_number is a valid error number, the message string shall indicate + * what error occurred; if the value of error_number is zero, the message + * string shall either be an empty string or indicate that no error occurred; + * otherwise, if these functions complete successfully, the message string + * shall indicate that an unknown error occurred. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #int Upon successful completion, strerror_l() shall return a pointer + * to the generated message string. If error_number is not a valid error number, + * errno may be set to [EINVAL], but a pointer to a message string shall still + * be returned. If any other error occurs, errno shall be set to indicate the + * error and a null pointer shall be returned. + * + * @par Dependency: + *
      • string.h
      + * @see perror + */ +int strerror_r (int, char *, size_t); + +/** + * @ingroup string + * + * @par Description: + * The stpcpy() function copies the string pointed to by src + * (including the terminating null byte ("\0")) to the array pointed to by dest. + * The strings may not overlap, and the destination string dest must be large + * enough to receive the copy. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #char* stpcpy() returns a pointer to the end of the string dest + * (that is, the address of the terminating null byte) rather than the beginning. + * + * @par Dependency: + *
      • string.h
      + * @see memcpy | memmove | strcpy + */ +char *stpcpy(char *__restrict, const char *__restrict); +char *stpncpy(char *__restrict, const char *__restrict, size_t); + +/** + * @ingroup string + * + * @par Description: + * The strnlen() function returns the number of characters in the string + * pointed to by str, excluding the terminating null byte ("\0"), but at + * most maxlen. In doing this, strnlen() looks only at the first maxlen + * characters in the string pointed to by str and never beyond str+maxlen. + * + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #size_t The strnlen() function returns the number of characters in the string + * pointed to by str, if that is less than maxlen, or maxlen if there is no null + * terminating ("\0") among the first maxlen characters pointed to by str. + * + * @par Dependency: + *
      • string.h
      + * @see strlen + */ +size_t strnlen (const char *, size_t); + +/** + * @ingroup string + * + * @par Description: + * The strdup() function returns a pointer to a new string which is a + * duplicate of the string str. Memory for the new string is obtained + * with malloc(), and can be freed with free(). + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #char* On success, the strdup() function returns a pointer to the duplicated + * string. It returns NULL if insufficient memory was available. + * + * @par Dependency: + *
      • string.h
      + * @see calloc | free | malloc | realloc + */ +char *strdup (const char *); +char *strndup (const char *, size_t); +char *strsignal(int); +char *strerror_l (int, locale_t); +int strcoll_l (const char *, const char *, locale_t); +size_t strxfrm_l (char *__restrict, const char *__restrict, size_t, locale_t); +#endif + +#if defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) \ + || defined(_BSD_SOURCE) +void *memccpy (void *__restrict, const void *__restrict, int, size_t); +#endif + +#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE) + +/** + * @ingroup string + * + * @par Description: + * Decompose a string into a set of strings. Scan backwards from the position pointed + * to by stringp. After encountering the character in the string pointed to by delim, + * replace this character with NULL and return the address pointed to by stringp. + * + * @attention + *
        + *
      • + * The strsep() function is not a standard C Library Function. + *
      • + *
      + * + * @retval #char* Returns a substring starting at the beginning of stringp, and returns + * NULL when there is no substring that is split. + * + * @par Dependency: + *
      • string.h
      + * @see memchr | strchr | strspn | strstr | strtok + */ +char *strsep(char **, const char *); +size_t strlcat (char *, const char *, size_t); + +/** + * @ingroup string + * + * @par Description: + * The strlcpy() function copies and concatenate strings. It is + * designed to be safer, more consistent, and less error prone replacements + * for the easily misused functions strncpy() and. + * strlcpy() takes the full size of the destination buffer and + * guarantee NUL-termination if there is room. Note that room for the NUL + * should be included in siz. strlcpy() copies up to siz - 1 characters from + * the string src to dst, NUL-terminating the result if siz is not 0. + * + * @attention + *
        + *
      • + * The strlcpy() function is not a standard C Library Function. + *
      • + *
      + * + * @retval #size_t the strlcpy() function returns the total + * length of the string they tried to create. For strlcpy() that means the + * length of src. If the return value is >= siz, the output string has been truncated. + * + * @par Dependency: + *
      • string.h
      + * @see snprintf | strncat | strncpy | wcslcpy + */ +size_t strlcpy (char *, const char *, size_t); +void explicit_bzero (void *, size_t); +#endif + +#ifdef _GNU_SOURCE +#define strdupa(x) strcpy(alloca(strlen(x)+1),x) +int strverscmp (const char *, const char *); +char *strchrnul(const char *, int); + +/** + * @ingroup string + * + * @par Description: + * The strcasestr() function finds the first occurrence of the substring + * find in the string s. The terminating null bytes ("\0") are not compared. + * + * @attention + *
        + *
      • + * The strcasestr() function is not a standard C Library Function. + *
      • + *
      + * + * @retval #char* The function returns a pointer to the beginning of the substring, + * or NULL if the substring is not found. + * + * @par Dependency: + *
      • string.h
      + * @see memchr | strcasecmp | strchr | strpbrk | strsep | strspn | strtok + */ +char *strcasestr(const char *, const char *); +void *memmem(const void *, size_t, const void *, size_t); +void *memrchr(const void *, int, size_t); +void *mempcpy(void *, const void *, size_t); +#ifndef __cplusplus +#ifndef __LITEOS__ +char *basename(); +#else +char *basename(char *); +#endif +#endif +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/strings.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/strings.h new file mode 100644 index 0000000000000000000000000000000000000000..db0960b4eb87a5d5883d7c94ad6d9e5dca9d9633 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/strings.h @@ -0,0 +1,39 @@ +#ifndef _STRINGS_H +#define _STRINGS_H + +#ifdef __cplusplus +extern "C" { +#endif + + +#define __NEED_size_t +#define __NEED_locale_t +#include + +#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE) || defined(_POSIX_SOURCE) \ + || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE+0 < 200809L) \ + || (defined(_XOPEN_SOURCE) && _XOPEN_SOURCE+0 < 700) +int bcmp (const void *, const void *, size_t); +void bcopy (const void *, void *, size_t); +void bzero (void *, size_t); +char *index (const char *, int); +char *rindex (const char *, int); +#endif + +#if defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) || defined(_BSD_SOURCE) +int ffs (int); +int ffsl (long); +int ffsll (long long); +#endif + +int strcasecmp (const char *, const char *); +int strncasecmp (const char *, const char *, size_t); + +int strcasecmp_l (const char *, const char *, locale_t); +int strncasecmp_l (const char *, const char *, size_t, locale_t); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/stropts.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/stropts.h new file mode 100644 index 0000000000000000000000000000000000000000..c99c922e3411bab394e5fce78a3dca98977fc94b --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/stropts.h @@ -0,0 +1,139 @@ +#ifndef _STROPTS_H +#define _STROPTS_H + +#ifdef __cplusplus +extern "C" { +#endif + +#define __SID ('S' << 8) + +#define I_NREAD (__SID | 1) +#define I_PUSH (__SID | 2) +#define I_POP (__SID | 3) +#define I_LOOK (__SID | 4) +#define I_FLUSH (__SID | 5) +#define I_SRDOPT (__SID | 6) +#define I_GRDOPT (__SID | 7) +#define I_STR (__SID | 8) +#define I_SETSIG (__SID | 9) +#define I_GETSIG (__SID |10) +#define I_FIND (__SID |11) +#define I_LINK (__SID |12) +#define I_UNLINK (__SID |13) +#define I_PEEK (__SID |15) +#define I_FDINSERT (__SID |16) +#define I_SENDFD (__SID |17) +#define I_RECVFD (__SID |14) +#define I_SWROPT (__SID |19) +#define I_GWROPT (__SID |20) +#define I_LIST (__SID |21) +#define I_PLINK (__SID |22) +#define I_PUNLINK (__SID |23) +#define I_FLUSHBAND (__SID |28) +#define I_CKBAND (__SID |29) +#define I_GETBAND (__SID |30) +#define I_ATMARK (__SID |31) +#define I_SETCLTIME (__SID |32) +#define I_GETCLTIME (__SID |33) +#define I_CANPUT (__SID |34) + +#define FMNAMESZ 8 + +#define FLUSHR 0x01 +#define FLUSHW 0x02 +#define FLUSHRW 0x03 +#define FLUSHBAND 0x04 + +#define S_INPUT 0x0001 +#define S_HIPRI 0x0002 +#define S_OUTPUT 0x0004 +#define S_MSG 0x0008 +#define S_ERROR 0x0010 +#define S_HANGUP 0x0020 +#define S_RDNORM 0x0040 +#define S_WRNORM S_OUTPUT +#define S_RDBAND 0x0080 +#define S_WRBAND 0x0100 +#define S_BANDURG 0x0200 + +#define RS_HIPRI 0x01 + +#define RNORM 0x0000 +#define RMSGD 0x0001 +#define RMSGN 0x0002 +#define RPROTDAT 0x0004 +#define RPROTDIS 0x0008 +#define RPROTNORM 0x0010 +#define RPROTMASK 0x001C + +#define SNDZERO 0x001 +#define SNDPIPE 0x002 + +#define ANYMARK 0x01 +#define LASTMARK 0x02 + +#define MUXID_ALL (-1) + +#define MSG_HIPRI 0x01 +#define MSG_ANY 0x02 +#define MSG_BAND 0x04 + +#define MORECTL 1 +#define MOREDATA 2 + +struct bandinfo { + unsigned char bi_pri; + int bi_flag; +}; + +struct strbuf { + int maxlen; + int len; + char *buf; +}; + +struct strpeek { + struct strbuf ctlbuf; + struct strbuf databuf; + unsigned flags; +}; + +struct strfdinsert { + struct strbuf ctlbuf; + struct strbuf databuf; + unsigned flags; + int fildes; + int offset; +}; + +struct strioctl { + int ic_cmd; + int ic_timout; + int ic_len; + char *ic_dp; +}; + +struct strrecvfd { + int fd; + int uid; + int gid; + char __fill[8]; +}; + +struct str_mlist { + char l_name[FMNAMESZ + 1]; +}; + +struct str_list { + int sl_nmods; + struct str_mlist *sl_modlist; +}; + +int isastream(int); +int ioctl(int, int, ...); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/acct.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/acct.h new file mode 100644 index 0000000000000000000000000000000000000000..fae9d0508f9c839d149ed80cba9f89e12013c7c7 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/acct.h @@ -0,0 +1,72 @@ +#ifndef _SYS_ACCT_H +#define _SYS_ACCT_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include + +#define ACCT_COMM 16 + +typedef uint16_t comp_t; + +struct acct { + char ac_flag; + uint16_t ac_uid; + uint16_t ac_gid; + uint16_t ac_tty; + uint32_t ac_btime; + comp_t ac_utime; + comp_t ac_stime; + comp_t ac_etime; + comp_t ac_mem; + comp_t ac_io; + comp_t ac_rw; + comp_t ac_minflt; + comp_t ac_majflt; + comp_t ac_swaps; + uint32_t ac_exitcode; + char ac_comm[ACCT_COMM+1]; + char ac_pad[10]; +}; + + +struct acct_v3 { + char ac_flag; + char ac_version; + uint16_t ac_tty; + uint32_t ac_exitcode; + uint32_t ac_uid; + uint32_t ac_gid; + uint32_t ac_pid; + uint32_t ac_ppid; + uint32_t ac_btime; + float ac_etime; + comp_t ac_utime; + comp_t ac_stime; + comp_t ac_mem; + comp_t ac_io; + comp_t ac_rw; + comp_t ac_minflt; + comp_t ac_majflt; + comp_t ac_swaps; + char ac_comm[ACCT_COMM]; +}; + +#define AFORK 1 +#define ASU 2 +#define ACORE 8 +#define AXSIG 16 +#define ACCT_BYTEORDER (128*(__BYTE_ORDER==__BIG_ENDIAN)) +#define AHZ 100 + +int acct(const char *); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/auxv.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/auxv.h new file mode 100644 index 0000000000000000000000000000000000000000..ddccf57ff6f3851c5bf59555ad81e8d540da5417 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/auxv.h @@ -0,0 +1,17 @@ +#ifndef _SYS_AUXV_H +#define _SYS_AUXV_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include + +unsigned long getauxval(unsigned long); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/cachectl.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/cachectl.h new file mode 100644 index 0000000000000000000000000000000000000000..f3b896a8e059ebfef2b3709d375c59cd74e3ffef --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/cachectl.h @@ -0,0 +1,22 @@ +#ifndef _SYS_CACHECTL_H +#define _SYS_CACHECTL_H + +#ifdef __cplusplus +extern "C" { +#endif + +#define ICACHE (1<<0) +#define DCACHE (1<<1) +#define BCACHE (ICACHE|DCACHE) +#define CACHEABLE 0 +#define UNCACHEABLE 1 + +int cachectl(void *, int, int); +int cacheflush(void *, int, int); +int _flush_cache(void *, int, int); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/dir.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/dir.h new file mode 100644 index 0000000000000000000000000000000000000000..9ba1c79e2a322571db3a5307f8fe4dc0550781fd --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/dir.h @@ -0,0 +1,2 @@ +#include +#define direct dirent diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/epoll.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/epoll.h new file mode 100644 index 0000000000000000000000000000000000000000..ac81a8418a0cc66b065cbb6d57ec3af0d6b4cc60 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/epoll.h @@ -0,0 +1,69 @@ +#ifndef _SYS_EPOLL_H +#define _SYS_EPOLL_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include + +#define __NEED_sigset_t + +#include + +#define EPOLL_CLOEXEC O_CLOEXEC +#define EPOLL_NONBLOCK O_NONBLOCK + +enum EPOLL_EVENTS { __EPOLL_DUMMY }; +#define EPOLLIN 0x001 +#define EPOLLPRI 0x002 +#define EPOLLOUT 0x004 +#define EPOLLRDNORM 0x040 +#define EPOLLNVAL 0x020 +#define EPOLLRDBAND 0x080 +#define EPOLLWRNORM 0x100 +#define EPOLLWRBAND 0x200 +#define EPOLLMSG 0x400 +#define EPOLLERR 0x008 +#define EPOLLHUP 0x010 +#define EPOLLRDHUP 0x2000 +#define EPOLLEXCLUSIVE (1U<<28) +#define EPOLLWAKEUP (1U<<29) +#define EPOLLONESHOT (1U<<30) +#define EPOLLET (1U<<31) + +#define EPOLL_CTL_ADD 1 +#define EPOLL_CTL_DEL 2 +#define EPOLL_CTL_MOD 3 + +typedef union epoll_data { + void *ptr; + int fd; + uint32_t u32; + uint64_t u64; +} epoll_data_t; + +struct epoll_event { + uint32_t events; + epoll_data_t data; +} +#ifdef __x86_64__ +__attribute__ ((__packed__)) +#endif +; + + +int epoll_create(int); +int epoll_create1(int); +int epoll_ctl(int, int, int, struct epoll_event *); +int epoll_wait(int, struct epoll_event *, int, int); +int epoll_pwait(int, struct epoll_event *, int, int, const sigset_t *); + + +#ifdef __cplusplus +} +#endif + +#endif /* sys/epoll.h */ diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/errno.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/errno.h new file mode 100644 index 0000000000000000000000000000000000000000..35a3e5a2a20d97f45fc29cfd45ee289a383961d8 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/errno.h @@ -0,0 +1,2 @@ +#warning redirecting incorrect #include to +#include diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/eventfd.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/eventfd.h new file mode 100644 index 0000000000000000000000000000000000000000..dc5c88f041fb5084a4d1ebea2d8e540292ea4a88 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/eventfd.h @@ -0,0 +1,26 @@ +#ifndef _SYS_EVENTFD_H +#define _SYS_EVENTFD_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include + +typedef uint64_t eventfd_t; + +#define EFD_SEMAPHORE 1 +#define EFD_CLOEXEC O_CLOEXEC +#define EFD_NONBLOCK O_NONBLOCK + +int eventfd(unsigned int, int); +int eventfd_read(int, eventfd_t *); +int eventfd_write(int, eventfd_t); + + +#ifdef __cplusplus +} +#endif + +#endif /* sys/eventfd.h */ diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/fanotify.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/fanotify.h new file mode 100644 index 0000000000000000000000000000000000000000..b637c8f58a18318f4f0beae3011fb000d653b14f --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/fanotify.h @@ -0,0 +1,105 @@ +#ifndef _FANOTIFY_H +#define _FANOTIFY_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +struct fanotify_event_metadata { + unsigned event_len; + unsigned char vers; + unsigned char reserved; + unsigned short metadata_len; + unsigned long long mask +#ifdef __GNUC__ + __attribute__((__aligned__(8))) +#endif + ; + int fd; + int pid; +}; + +struct fanotify_event_info_header { + unsigned char info_type; + unsigned char pad; + unsigned short len; +}; + +struct fanotify_event_info_fid { + struct fanotify_event_info_header hdr; + fsid_t fsid; + unsigned char handle[]; +}; + +struct fanotify_response { + int fd; + unsigned response; +}; + +#define FAN_ACCESS 0x01 +#define FAN_MODIFY 0x02 +#define FAN_ATTRIB 0x04 +#define FAN_CLOSE_WRITE 0x08 +#define FAN_CLOSE_NOWRITE 0x10 +#define FAN_OPEN 0x20 +#define FAN_MOVED_FROM 0x40 +#define FAN_MOVED_TO 0x80 +#define FAN_CREATE 0x100 +#define FAN_DELETE 0x200 +#define FAN_DELETE_SELF 0x400 +#define FAN_MOVE_SELF 0x800 +#define FAN_OPEN_EXEC 0x1000 +#define FAN_Q_OVERFLOW 0x4000 +#define FAN_OPEN_PERM 0x10000 +#define FAN_ACCESS_PERM 0x20000 +#define FAN_OPEN_EXEC_PERM 0x40000 +#define FAN_ONDIR 0x40000000 +#define FAN_EVENT_ON_CHILD 0x08000000 +#define FAN_CLOSE (FAN_CLOSE_WRITE | FAN_CLOSE_NOWRITE) +#define FAN_MOVE (FAN_MOVED_FROM | FAN_MOVED_TO) +#define FAN_CLOEXEC 0x01 +#define FAN_NONBLOCK 0x02 +#define FAN_CLASS_NOTIF 0 +#define FAN_CLASS_CONTENT 0x04 +#define FAN_CLASS_PRE_CONTENT 0x08 +#define FAN_ALL_CLASS_BITS (FAN_CLASS_NOTIF | FAN_CLASS_CONTENT | FAN_CLASS_PRE_CONTENT) +#define FAN_UNLIMITED_QUEUE 0x10 +#define FAN_UNLIMITED_MARKS 0x20 +#define FAN_ENABLE_AUDIT 0x40 +#define FAN_REPORT_TID 0x100 +#define FAN_REPORT_FID 0x200 +#define FAN_ALL_INIT_FLAGS (FAN_CLOEXEC | FAN_NONBLOCK | FAN_ALL_CLASS_BITS | FAN_UNLIMITED_QUEUE | FAN_UNLIMITED_MARKS) +#define FAN_MARK_ADD 0x01 +#define FAN_MARK_REMOVE 0x02 +#define FAN_MARK_DONT_FOLLOW 0x04 +#define FAN_MARK_ONLYDIR 0x08 +#define FAN_MARK_IGNORED_MASK 0x20 +#define FAN_MARK_IGNORED_SURV_MODIFY 0x40 +#define FAN_MARK_FLUSH 0x80 +#define FAN_MARK_INODE 0x00 +#define FAN_MARK_MOUNT 0x10 +#define FAN_MARK_FILESYSTEM 0x100 +#define FAN_MARK_TYPE_MASK (FAN_MARK_INODE | FAN_MARK_MOUNT | FAN_MARK_FILESYSTEM) +#define FAN_ALL_MARK_FLAGS (FAN_MARK_ADD | FAN_MARK_REMOVE | FAN_MARK_DONT_FOLLOW | FAN_MARK_ONLYDIR | FAN_MARK_MOUNT | FAN_MARK_IGNORED_MASK | FAN_MARK_IGNORED_SURV_MODIFY | FAN_MARK_FLUSH) +#define FAN_ALL_EVENTS (FAN_ACCESS | FAN_MODIFY | FAN_CLOSE | FAN_OPEN) +#define FAN_ALL_PERM_EVENTS (FAN_OPEN_PERM | FAN_ACCESS_PERM) +#define FAN_ALL_OUTGOING_EVENTS (FAN_ALL_EVENTS | FAN_ALL_PERM_EVENTS | FAN_Q_OVERFLOW) +#define FANOTIFY_METADATA_VERSION 3 +#define FAN_EVENT_INFO_TYPE_FID 1 +#define FAN_ALLOW 0x01 +#define FAN_DENY 0x02 +#define FAN_AUDIT 0x10 +#define FAN_NOFD -1 +#define FAN_EVENT_METADATA_LEN (sizeof(struct fanotify_event_metadata)) +#define FAN_EVENT_NEXT(meta, len) ((len) -= (meta)->event_len, (struct fanotify_event_metadata*)(((char *)(meta)) + (meta)->event_len)) +#define FAN_EVENT_OK(meta, len) ((long)(len) >= (long)FAN_EVENT_METADATA_LEN && (long)(meta)->event_len >= (long)FAN_EVENT_METADATA_LEN && (long)(meta)->event_len <= (long)(len)) + +int fanotify_init(unsigned, unsigned); +int fanotify_mark(int, unsigned, unsigned long long, int, const char *); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/fcntl.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/fcntl.h new file mode 100644 index 0000000000000000000000000000000000000000..3dd928ef69a976a083f3da234e3ecb0f9a400a2b --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/fcntl.h @@ -0,0 +1,2 @@ +#warning redirecting incorrect #include to +#include diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/file.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/file.h new file mode 100644 index 0000000000000000000000000000000000000000..4fc83b981874c059ae82aa6e41cbd5b6f0bde1d7 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/file.h @@ -0,0 +1,21 @@ +#ifndef _SYS_FILE_H +#define _SYS_FILE_H +#ifdef __cplusplus +extern "C" { +#endif + +#define LOCK_SH 1 +#define LOCK_EX 2 +#define LOCK_NB 4 +#define LOCK_UN 8 + +#define L_SET 0 +#define L_INCR 1 +#define L_XTND 2 + +int flock(int, int); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/fsuid.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/fsuid.h new file mode 100644 index 0000000000000000000000000000000000000000..c7a9b8faa7954dd0c06b4851c644375001990246 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/fsuid.h @@ -0,0 +1,20 @@ +#ifndef _SYS_FSUID_H +#define _SYS_FSUID_H + +#ifdef __cplusplus +extern "C" { +#endif + +#define __NEED_uid_t +#define __NEED_gid_t + +#include + +int setfsuid(uid_t); +int setfsgid(gid_t); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/inotify.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/inotify.h new file mode 100644 index 0000000000000000000000000000000000000000..69b5863199228bb8d2a14cbf0a73dd2181fbeba7 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/inotify.h @@ -0,0 +1,58 @@ +#ifndef _SYS_INOTIFY_H +#define _SYS_INOTIFY_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include + +struct inotify_event { + int wd; + uint32_t mask, cookie, len; + char name[]; +}; + +#define IN_CLOEXEC O_CLOEXEC +#define IN_NONBLOCK O_NONBLOCK + +#define IN_ACCESS 0x00000001 +#define IN_MODIFY 0x00000002 +#define IN_ATTRIB 0x00000004 +#define IN_CLOSE_WRITE 0x00000008 +#define IN_CLOSE_NOWRITE 0x00000010 +#define IN_CLOSE (IN_CLOSE_WRITE | IN_CLOSE_NOWRITE) +#define IN_OPEN 0x00000020 +#define IN_MOVED_FROM 0x00000040 +#define IN_MOVED_TO 0x00000080 +#define IN_MOVE (IN_MOVED_FROM | IN_MOVED_TO) +#define IN_CREATE 0x00000100 +#define IN_DELETE 0x00000200 +#define IN_DELETE_SELF 0x00000400 +#define IN_MOVE_SELF 0x00000800 +#define IN_ALL_EVENTS 0x00000fff + +#define IN_UNMOUNT 0x00002000 +#define IN_Q_OVERFLOW 0x00004000 +#define IN_IGNORED 0x00008000 + +#define IN_ONLYDIR 0x01000000 +#define IN_DONT_FOLLOW 0x02000000 +#define IN_EXCL_UNLINK 0x04000000 +#define IN_MASK_CREATE 0x10000000 +#define IN_MASK_ADD 0x20000000 + +#define IN_ISDIR 0x40000000 +#define IN_ONESHOT 0x80000000 + +int inotify_init(void); +int inotify_init1(int); +int inotify_add_watch(int, const char *, uint32_t); +int inotify_rm_watch(int, int); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/io.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/io.h new file mode 100644 index 0000000000000000000000000000000000000000..16658cecae9b29707fb247210abcabcfd2ef8bfa --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/io.h @@ -0,0 +1,17 @@ +#ifndef _SYS_IO_H +#define _SYS_IO_H +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#include + +int iopl(int); +int ioperm(unsigned long, unsigned long, int); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/ioctl.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/ioctl.h new file mode 100644 index 0000000000000000000000000000000000000000..01f8de19e64d9172b527120e9f61eeb841ae80b0 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/ioctl.h @@ -0,0 +1,129 @@ +#ifndef _SYS_IOCTL_H +#define _SYS_IOCTL_H +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include + +#define N_TTY 0 +#define N_SLIP 1 +#define N_MOUSE 2 +#define N_PPP 3 +#define N_STRIP 4 +#define N_AX25 5 +#define N_X25 6 +#define N_6PACK 7 +#define N_MASC 8 +#define N_R3964 9 +#define N_PROFIBUS_FDL 10 +#define N_IRDA 11 +#define N_SMSBLOCK 12 +#define N_HDLC 13 +#define N_SYNC_PPP 14 +#define N_HCI 15 +#define N_GIGASET_M101 16 +#define N_SLCAN 17 +#define N_PPS 18 +#define N_V253 19 +#define N_CAIF 20 +#define N_GSM0710 21 +#define N_TI_WL 22 +#define N_TRACESINK 23 +#define N_TRACEROUTER 24 +#define N_NCI 25 +#define N_SPEAKUP 26 +#define N_NULL 27 + +#define TIOCPKT_DATA 0 +#define TIOCPKT_FLUSHREAD 1 +#define TIOCPKT_FLUSHWRITE 2 +#define TIOCPKT_STOP 4 +#define TIOCPKT_START 8 +#define TIOCPKT_NOSTOP 16 +#define TIOCPKT_DOSTOP 32 +#define TIOCPKT_IOCTL 64 + +#define TIOCSER_TEMT 1 + +struct winsize { + unsigned short ws_row; + unsigned short ws_col; + unsigned short ws_xpixel; + unsigned short ws_ypixel; +}; + +#define SIOCADDRT 0x890B +#define SIOCDELRT 0x890C +#define SIOCRTMSG 0x890D + +#define SIOCGIFNAME 0x8910 +#define SIOCSIFLINK 0x8911 +#define SIOCGIFCONF 0x8912 +#define SIOCGIFFLAGS 0x8913 +#define SIOCSIFFLAGS 0x8914 +#define SIOCGIFADDR 0x8915 +#define SIOCSIFADDR 0x8916 +#define SIOCGIFDSTADDR 0x8917 +#define SIOCSIFDSTADDR 0x8918 +#define SIOCGIFBRDADDR 0x8919 +#define SIOCSIFBRDADDR 0x891a +#define SIOCGIFNETMASK 0x891b +#define SIOCSIFNETMASK 0x891c +#define SIOCGIFMETRIC 0x891d +#define SIOCSIFMETRIC 0x891e +#define SIOCGIFMEM 0x891f +#define SIOCSIFMEM 0x8920 +#define SIOCGIFMTU 0x8921 +#define SIOCSIFMTU 0x8922 +#define SIOCSIFNAME 0x8923 +#define SIOCSIFHWADDR 0x8924 +#define SIOCGIFENCAP 0x8925 +#define SIOCSIFENCAP 0x8926 +#define SIOCGIFHWADDR 0x8927 +#define SIOCGIFSLAVE 0x8929 +#define SIOCSIFSLAVE 0x8930 +#define SIOCADDMULTI 0x8931 +#define SIOCDELMULTI 0x8932 +#define SIOCGIFINDEX 0x8933 +#define SIOGIFINDEX SIOCGIFINDEX +#define SIOCSIFPFLAGS 0x8934 +#define SIOCGIFPFLAGS 0x8935 +#define SIOCDIFADDR 0x8936 +#define SIOCSIFHWBROADCAST 0x8937 +#define SIOCGIFCOUNT 0x8938 + +#define SIOCGIFBR 0x8940 +#define SIOCSIFBR 0x8941 + +#define SIOCGIFTXQLEN 0x8942 +#define SIOCSIFTXQLEN 0x8943 + +#ifdef __LITEOS__ +#define SIOCETHTOOL 0x8946 +#endif + +#define SIOCDARP 0x8953 +#define SIOCGARP 0x8954 +#define SIOCSARP 0x8955 + +#define SIOCDRARP 0x8960 +#define SIOCGRARP 0x8961 +#define SIOCSRARP 0x8962 + +#define SIOCGIFMAP 0x8970 +#define SIOCSIFMAP 0x8971 + +#define SIOCADDDLCI 0x8980 +#define SIOCDELDLCI 0x8981 + +#define SIOCDEVPRIVATE 0x89F0 +#define SIOCPROTOPRIVATE 0x89E0 + +int ioctl (int, int, ...); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/ipc.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/ipc.h new file mode 100644 index 0000000000000000000000000000000000000000..9e366b7bed0499abed8cacb13a4e64faedad79d1 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/ipc.h @@ -0,0 +1,42 @@ +#ifndef _SYS_IPC_H +#define _SYS_IPC_H +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#define __NEED_uid_t +#define __NEED_gid_t +#define __NEED_mode_t +#define __NEED_key_t + +#include + +#define __ipc_perm_key __key +#define __ipc_perm_seq __seq + +#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE) +#define __key key +#define __seq seq +#endif + +#include +#include + +#define IPC_CREAT 01000 +#define IPC_EXCL 02000 +#define IPC_NOWAIT 04000 + +#define IPC_RMID 0 +#define IPC_SET 1 +#define IPC_INFO 3 + +#define IPC_PRIVATE ((key_t) 0) + +key_t ftok (const char *, int); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/kd.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/kd.h new file mode 100644 index 0000000000000000000000000000000000000000..42122b9c3a4c4ce4ca6831bb053a4e986a8ce730 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/kd.h @@ -0,0 +1 @@ +#include diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/klog.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/klog.h new file mode 100644 index 0000000000000000000000000000000000000000..aa66684e3fd8e9d2dcc8bc382b2c970600171306 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/klog.h @@ -0,0 +1,14 @@ +#ifndef _SYS_KLOG_H +#define _SYS_KLOG_H + +#ifdef __cplusplus +extern "C" { +#endif + +int klogctl (int, char *, int); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/membarrier.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/membarrier.h new file mode 100644 index 0000000000000000000000000000000000000000..10cb31083c0b2902668e0423f75401269c591980 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/membarrier.h @@ -0,0 +1,17 @@ +#ifndef _SYS_MEMBARRIER_H +#define _SYS_MEMBARRIER_H + +#define MEMBARRIER_CMD_QUERY 0 +#define MEMBARRIER_CMD_GLOBAL 1 +#define MEMBARRIER_CMD_GLOBAL_EXPEDITED 2 +#define MEMBARRIER_CMD_REGISTER_GLOBAL_EXPEDITED 4 +#define MEMBARRIER_CMD_PRIVATE_EXPEDITED 8 +#define MEMBARRIER_CMD_REGISTER_PRIVATE_EXPEDITED 16 +#define MEMBARRIER_CMD_PRIVATE_EXPEDITED_SYNC_CORE 32 +#define MEMBARRIER_CMD_REGISTER_PRIVATE_EXPEDITED_SYNC_CORE 64 + +#define MEMBARRIER_CMD_SHARED MEMBARRIER_CMD_GLOBAL + +int membarrier(int, int); + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/mman.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/mman.h new file mode 100644 index 0000000000000000000000000000000000000000..e0ae3e789be30744b7674d53f507b54e7b060725 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/mman.h @@ -0,0 +1,182 @@ +/** + * @defgroup mman Mman + * @ingroup libc + */ + +#ifndef _SYS_MMAN_H +#define _SYS_MMAN_H +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#define __NEED_mode_t +#define __NEED_size_t +#define __NEED_off_t + +#if defined(_GNU_SOURCE) +#define __NEED_ssize_t +#endif +#ifdef __LITEOS__ +#define __NEED_int64_t +#endif + +#include + +#define MAP_FAILED ((void *) -1) + +#define MAP_SHARED 0x01 +#define MAP_PRIVATE 0x02 +#define MAP_SHARED_VALIDATE 0x03 +#define MAP_TYPE 0x0f +#define MAP_FIXED 0x10 +#define MAP_ANON 0x20 +#define MAP_ANONYMOUS MAP_ANON +#define MAP_NORESERVE 0x4000 +#define MAP_GROWSDOWN 0x0100 +#define MAP_DENYWRITE 0x0800 +#define MAP_EXECUTABLE 0x1000 +#define MAP_LOCKED 0x2000 +#define MAP_POPULATE 0x8000 +#define MAP_NONBLOCK 0x10000 +#define MAP_STACK 0x20000 +#define MAP_HUGETLB 0x40000 +#define MAP_SYNC 0x80000 +#define MAP_FIXED_NOREPLACE 0x100000 +#define MAP_FILE 0 + +#define MAP_HUGE_SHIFT 26 +#define MAP_HUGE_MASK 0x3f +#define MAP_HUGE_64KB (16 << 26) +#define MAP_HUGE_512KB (19 << 26) +#define MAP_HUGE_1MB (20 << 26) +#define MAP_HUGE_2MB (21 << 26) +#define MAP_HUGE_8MB (23 << 26) +#define MAP_HUGE_16MB (24 << 26) +#define MAP_HUGE_32MB (25 << 26) +#define MAP_HUGE_256MB (28 << 26) +#define MAP_HUGE_512MB (29 << 26) +#define MAP_HUGE_1GB (30 << 26) +#define MAP_HUGE_2GB (31 << 26) +#define MAP_HUGE_16GB (34U << 26) + +#define PROT_NONE 0 +#define PROT_READ 1 +#define PROT_WRITE 2 +#define PROT_EXEC 4 +#define PROT_GROWSDOWN 0x01000000 +#define PROT_GROWSUP 0x02000000 + +#define MS_ASYNC 1 +#define MS_INVALIDATE 2 +#define MS_SYNC 4 + +#define MCL_CURRENT 1 +#define MCL_FUTURE 2 +#define MCL_ONFAULT 4 + +#define POSIX_MADV_NORMAL 0 +#define POSIX_MADV_RANDOM 1 +#define POSIX_MADV_SEQUENTIAL 2 +#define POSIX_MADV_WILLNEED 3 +#define POSIX_MADV_DONTNEED 4 + +#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE) +#define MADV_NORMAL 0 +#define MADV_RANDOM 1 +#define MADV_SEQUENTIAL 2 +#define MADV_WILLNEED 3 +#define MADV_DONTNEED 4 +#define MADV_FREE 8 +#define MADV_REMOVE 9 +#define MADV_DONTFORK 10 +#define MADV_DOFORK 11 +#define MADV_MERGEABLE 12 +#define MADV_UNMERGEABLE 13 +#define MADV_HUGEPAGE 14 +#define MADV_NOHUGEPAGE 15 +#define MADV_DONTDUMP 16 +#define MADV_DODUMP 17 +#define MADV_WIPEONFORK 18 +#define MADV_KEEPONFORK 19 +#define MADV_COLD 20 +#define MADV_PAGEOUT 21 +#define MADV_HWPOISON 100 +#define MADV_SOFT_OFFLINE 101 +#endif + +#ifdef _GNU_SOURCE +#define MREMAP_MAYMOVE 1 +#define MREMAP_FIXED 2 + +#define MLOCK_ONFAULT 0x01 + +#define MFD_CLOEXEC 0x0001U +#define MFD_ALLOW_SEALING 0x0002U +#define MFD_HUGETLB 0x0004U +#endif + +#include + +/** + * @ingroup mman + * + * @par Description: + * This function shall establish a mapping between an address space and a memory object. + * + * @attention + *
        + *
      • This API just returns the pointer to the offset parameter on LiteOS.
      • + *
      • The macro __USE_FILE_OFFSET64 should have been defined for this api.
      • + *
      + * + * @retval #void* pointer to the offset parameter is returned. + * + * @par Dependency: + *
      • mman.h
      + * + * @see None + * + */ +void *mmap (void *, size_t, int, int, int, off_t); +int munmap (void *, size_t); + +int mprotect (void *, size_t, int); +int msync (void *, size_t, int); + +int posix_madvise (void *, size_t, int); + +int mlock (const void *, size_t); +int munlock (const void *, size_t); +int mlockall (int); +int munlockall (void); + +#ifdef _GNU_SOURCE +void *mremap (void *, size_t, size_t, int, ...); +int remap_file_pages (void *, size_t, int, size_t, int); +int memfd_create (const char *, unsigned); +int mlock2 (const void *, size_t, unsigned); +#endif + +#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE) +int madvise (void *, size_t, int); +int mincore (void *, size_t, unsigned char *); +#endif + +int shm_open (const char *, int, mode_t); +int shm_unlink (const char *); + +#if defined(_LARGEFILE64_SOURCE) || defined(_GNU_SOURCE) +#define mmap64 mmap +#ifdef __LITEOS__ +#define off64_t int64_t +#else +#define off64_t off_t +#endif +#endif + +#ifdef __cplusplus +} +#endif +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/mount.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/mount.h new file mode 100644 index 0000000000000000000000000000000000000000..57a89c09ecb1ff8dc6448b6fd6a1405851768028 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/mount.h @@ -0,0 +1,74 @@ +#ifndef _SYS_MOUNT_H +#define _SYS_MOUNT_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#define BLKROSET _IO(0x12, 93) +#define BLKROGET _IO(0x12, 94) +#define BLKRRPART _IO(0x12, 95) +#define BLKGETSIZE _IO(0x12, 96) +#define BLKFLSBUF _IO(0x12, 97) +#define BLKRASET _IO(0x12, 98) +#define BLKRAGET _IO(0x12, 99) +#define BLKFRASET _IO(0x12,100) +#define BLKFRAGET _IO(0x12,101) +#define BLKSECTSET _IO(0x12,102) +#define BLKSECTGET _IO(0x12,103) +#define BLKSSZGET _IO(0x12,104) +#define BLKBSZGET _IOR(0x12,112,size_t) +#define BLKBSZSET _IOW(0x12,113,size_t) +#define BLKGETSIZE64 _IOR(0x12,114,size_t) + +#define MS_RDONLY 1 +#define MS_NOSUID 2 +#define MS_NODEV 4 +#define MS_NOEXEC 8 +#define MS_SYNCHRONOUS 16 +#define MS_REMOUNT 32 +#define MS_MANDLOCK 64 +#define MS_DIRSYNC 128 +#define MS_NOATIME 1024 +#define MS_NODIRATIME 2048 +#define MS_BIND 4096 +#define MS_MOVE 8192 +#define MS_REC 16384 +#define MS_SILENT 32768 +#define MS_POSIXACL (1<<16) +#define MS_UNBINDABLE (1<<17) +#define MS_PRIVATE (1<<18) +#define MS_SLAVE (1<<19) +#define MS_SHARED (1<<20) +#define MS_RELATIME (1<<21) +#define MS_KERNMOUNT (1<<22) +#define MS_I_VERSION (1<<23) +#define MS_STRICTATIME (1<<24) +#define MS_LAZYTIME (1<<25) +#define MS_NOREMOTELOCK (1<<27) +#define MS_NOSEC (1<<28) +#define MS_BORN (1<<29) +#define MS_ACTIVE (1<<30) +#define MS_NOUSER (1U<<31) + +#define MS_RMT_MASK (MS_RDONLY|MS_SYNCHRONOUS|MS_MANDLOCK|MS_I_VERSION|MS_LAZYTIME) + +#define MS_MGC_VAL 0xc0ed0000 +#define MS_MGC_MSK 0xffff0000 + +#define MNT_FORCE 1 +#define MNT_DETACH 2 +#define MNT_EXPIRE 4 +#define UMOUNT_NOFOLLOW 8 + +int mount(const char *, const char *, const char *, unsigned long, const void *); +int umount(const char *); +int umount2(const char *, int); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/msg.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/msg.h new file mode 100644 index 0000000000000000000000000000000000000000..db5c62a42f5934170e8ee6a1c188473a6f5ec2ba --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/msg.h @@ -0,0 +1,53 @@ +#ifndef _SYS_MSG_H +#define _SYS_MSG_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#define __NEED_pid_t +#define __NEED_key_t +#define __NEED_time_t +#define __NEED_size_t +#define __NEED_ssize_t + +#include + +typedef unsigned long msgqnum_t; +typedef unsigned long msglen_t; + +#include + +#define __msg_cbytes msg_cbytes + +#define MSG_NOERROR 010000 +#define MSG_EXCEPT 020000 + +#define MSG_STAT (11 | (IPC_STAT & 0x100)) +#define MSG_INFO 12 +#define MSG_STAT_ANY (13 | (IPC_STAT & 0x100)) + +struct msginfo { + int msgpool, msgmap, msgmax, msgmnb, msgmni, msgssz, msgtql; + unsigned short msgseg; +}; + +int msgctl (int, int, struct msqid_ds *); +int msgget (key_t, int); +ssize_t msgrcv (int, void *, size_t, long, int); +int msgsnd (int, const void *, size_t, int); + +#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE) +struct msgbuf { + long mtype; + char mtext[1]; +}; +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/mtio.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/mtio.h new file mode 100644 index 0000000000000000000000000000000000000000..f16a529bb4091950860ed2e9afa3be8e5a752c0a --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/mtio.h @@ -0,0 +1,188 @@ +#ifndef _SYS_MTIO_H +#define _SYS_MTIO_H + +#include +#include + +struct mtop { + short mt_op; + int mt_count; +}; + +#define _IOT_mtop _IOT (_IOTS (short), 1, _IOTS (int), 1, 0, 0) +#define _IOT_mtget _IOT (_IOTS (long), 7, 0, 0, 0, 0) +#define _IOT_mtpos _IOT_SIMPLE (long) +#define _IOT_mtconfiginfo _IOT (_IOTS (long), 2, _IOTS (short), 3, _IOTS (long), 1) + + +#define MTRESET 0 +#define MTFSF 1 +#define MTBSF 2 +#define MTFSR 3 +#define MTBSR 4 +#define MTWEOF 5 +#define MTREW 6 +#define MTOFFL 7 +#define MTNOP 8 +#define MTRETEN 9 +#define MTBSFM 10 +#define MTFSFM 11 +#define MTEOM 12 +#define MTERASE 13 +#define MTRAS1 14 +#define MTRAS2 15 +#define MTRAS3 16 +#define MTSETBLK 20 +#define MTSETDENSITY 21 +#define MTSEEK 22 +#define MTTELL 23 +#define MTSETDRVBUFFER 24 +#define MTFSS 25 +#define MTBSS 26 +#define MTWSM 27 +#define MTLOCK 28 +#define MTUNLOCK 29 +#define MTLOAD 30 +#define MTUNLOAD 31 +#define MTCOMPRESSION 32 +#define MTSETPART 33 +#define MTMKPART 34 + +struct mtget { + long mt_type; + long mt_resid; + long mt_dsreg; + long mt_gstat; + long mt_erreg; + int mt_fileno; + int mt_blkno; +}; + +#define MT_ISUNKNOWN 0x01 +#define MT_ISQIC02 0x02 +#define MT_ISWT5150 0x03 +#define MT_ISARCHIVE_5945L2 0x04 +#define MT_ISCMSJ500 0x05 +#define MT_ISTDC3610 0x06 +#define MT_ISARCHIVE_VP60I 0x07 +#define MT_ISARCHIVE_2150L 0x08 +#define MT_ISARCHIVE_2060L 0x09 +#define MT_ISARCHIVESC499 0x0A +#define MT_ISQIC02_ALL_FEATURES 0x0F +#define MT_ISWT5099EEN24 0x11 +#define MT_ISTEAC_MT2ST 0x12 +#define MT_ISEVEREX_FT40A 0x32 +#define MT_ISDDS1 0x51 +#define MT_ISDDS2 0x52 +#define MT_ISSCSI1 0x71 +#define MT_ISSCSI2 0x72 +#define MT_ISFTAPE_UNKNOWN 0x800000 +#define MT_ISFTAPE_FLAG 0x800000 + +struct mt_tape_info { + long t_type; + char *t_name; +}; + +#define MT_TAPE_INFO \ +{ \ + {MT_ISUNKNOWN, "Unknown type of tape device"}, \ + {MT_ISQIC02, "Generic QIC-02 tape streamer"}, \ + {MT_ISWT5150, "Wangtek 5150, QIC-150"}, \ + {MT_ISARCHIVE_5945L2, "Archive 5945L-2"}, \ + {MT_ISCMSJ500, "CMS Jumbo 500"}, \ + {MT_ISTDC3610, "Tandberg TDC 3610, QIC-24"}, \ + {MT_ISARCHIVE_VP60I, "Archive VP60i, QIC-02"}, \ + {MT_ISARCHIVE_2150L, "Archive Viper 2150L"}, \ + {MT_ISARCHIVE_2060L, "Archive Viper 2060L"}, \ + {MT_ISARCHIVESC499, "Archive SC-499 QIC-36 controller"}, \ + {MT_ISQIC02_ALL_FEATURES, "Generic QIC-02 tape, all features"}, \ + {MT_ISWT5099EEN24, "Wangtek 5099-een24, 60MB"}, \ + {MT_ISTEAC_MT2ST, "Teac MT-2ST 155mb data cassette drive"}, \ + {MT_ISEVEREX_FT40A, "Everex FT40A, QIC-40"}, \ + {MT_ISSCSI1, "Generic SCSI-1 tape"}, \ + {MT_ISSCSI2, "Generic SCSI-2 tape"}, \ + {0, 0} \ +} + +struct mtpos { + long mt_blkno; +}; + +struct mtconfiginfo { + long mt_type; + long ifc_type; + unsigned short irqnr; + unsigned short dmanr; + unsigned short port; + unsigned long debug; + unsigned have_dens:1; + unsigned have_bsf:1; + unsigned have_fsr:1; + unsigned have_bsr:1; + unsigned have_eod:1; + unsigned have_seek:1; + unsigned have_tell:1; + unsigned have_ras1:1; + unsigned have_ras2:1; + unsigned have_ras3:1; + unsigned have_qfa:1; + unsigned pad1:5; + char reserved[10]; +}; + +#define MTIOCTOP _IOW('m', 1, struct mtop) +#define MTIOCGET _IOR('m', 2, struct mtget) +#define MTIOCPOS _IOR('m', 3, struct mtpos) + +#define MTIOCGETCONFIG _IOR('m', 4, struct mtconfiginfo) +#define MTIOCSETCONFIG _IOW('m', 5, struct mtconfiginfo) + +#define GMT_EOF(x) ((x) & 0x80000000) +#define GMT_BOT(x) ((x) & 0x40000000) +#define GMT_EOT(x) ((x) & 0x20000000) +#define GMT_SM(x) ((x) & 0x10000000) +#define GMT_EOD(x) ((x) & 0x08000000) +#define GMT_WR_PROT(x) ((x) & 0x04000000) +#define GMT_ONLINE(x) ((x) & 0x01000000) +#define GMT_D_6250(x) ((x) & 0x00800000) +#define GMT_D_1600(x) ((x) & 0x00400000) +#define GMT_D_800(x) ((x) & 0x00200000) +#define GMT_DR_OPEN(x) ((x) & 0x00040000) +#define GMT_IM_REP_EN(x) ((x) & 0x00010000) + +#define MT_ST_BLKSIZE_SHIFT 0 +#define MT_ST_BLKSIZE_MASK 0xffffff +#define MT_ST_DENSITY_SHIFT 24 +#define MT_ST_DENSITY_MASK 0xff000000 +#define MT_ST_SOFTERR_SHIFT 0 +#define MT_ST_SOFTERR_MASK 0xffff +#define MT_ST_OPTIONS 0xf0000000 +#define MT_ST_BOOLEANS 0x10000000 +#define MT_ST_SETBOOLEANS 0x30000000 +#define MT_ST_CLEARBOOLEANS 0x40000000 +#define MT_ST_WRITE_THRESHOLD 0x20000000 +#define MT_ST_DEF_BLKSIZE 0x50000000 +#define MT_ST_DEF_OPTIONS 0x60000000 +#define MT_ST_BUFFER_WRITES 0x1 +#define MT_ST_ASYNC_WRITES 0x2 +#define MT_ST_READ_AHEAD 0x4 +#define MT_ST_DEBUGGING 0x8 +#define MT_ST_TWO_FM 0x10 +#define MT_ST_FAST_MTEOM 0x20 +#define MT_ST_AUTO_LOCK 0x40 +#define MT_ST_DEF_WRITES 0x80 +#define MT_ST_CAN_BSR 0x100 +#define MT_ST_NO_BLKLIMS 0x200 +#define MT_ST_CAN_PARTITIONS 0x400 +#define MT_ST_SCSI2LOGICAL 0x800 +#define MT_ST_CLEAR_DEFAULT 0xfffff +#define MT_ST_DEF_DENSITY (MT_ST_DEF_OPTIONS | 0x100000) +#define MT_ST_DEF_COMPRESSION (MT_ST_DEF_OPTIONS | 0x200000) +#define MT_ST_DEF_DRVBUFFER (MT_ST_DEF_OPTIONS | 0x300000) +#define MT_ST_HPLOADER_OFFSET 10000 +#ifndef DEFTAPE +# define DEFTAPE "/dev/tape" +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/param.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/param.h new file mode 100644 index 0000000000000000000000000000000000000000..ce6b801980c10bdd1a104a7250d13e59d809942d --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/param.h @@ -0,0 +1,35 @@ +#ifndef _SYS_PARAM_H +#define _SYS_PARAM_H + +#define MAXSYMLINKS 20 +#define MAXHOSTNAMELEN 64 +#define MAXNAMLEN 255 +#define MAXPATHLEN 4096 +#define NBBY 8 +#define NGROUPS 32 +#define CANBSIZ 255 +#define NOFILE 256 +#define NCARGS 131072 +#define DEV_BSIZE 512 +#define NOGROUP (-1) + +#undef MIN +#undef MAX +#define MIN(a,b) (((a)<(b))?(a):(b)) +#define MAX(a,b) (((a)>(b))?(a):(b)) + +#define __bitop(x,i,o) ((x)[(i)/8] o (1<<(i)%8)) +#define setbit(x,i) __bitop(x,i,|=) +#define clrbit(x,i) __bitop(x,i,&=~) +#define isset(x,i) __bitop(x,i,&) +#define isclr(x,i) !isset(x,i) + +#define howmany(n,d) (((n)+((d)-1))/(d)) +#define roundup(n,d) (howmany(n,d)*(d)) +#define powerof2(n) !(((n)-1) & (n)) + +#include +#include +#include + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/personality.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/personality.h new file mode 100644 index 0000000000000000000000000000000000000000..31d43dfe13ea428a97709470832e06d5c10dacf1 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/personality.h @@ -0,0 +1,46 @@ +#ifndef _PERSONALITY_H +#define _PERSONALITY_H + +#ifdef __cplusplus +extern "C" { +#endif + +#define ADDR_NO_RANDOMIZE 0x0040000 +#define MMAP_PAGE_ZERO 0x0100000 +#define ADDR_COMPAT_LAYOUT 0x0200000 +#define READ_IMPLIES_EXEC 0x0400000 +#define ADDR_LIMIT_32BIT 0x0800000 +#define SHORT_INODE 0x1000000 +#define WHOLE_SECONDS 0x2000000 +#define STICKY_TIMEOUTS 0x4000000 +#define ADDR_LIMIT_3GB 0x8000000 + +#define PER_LINUX 0 +#define PER_LINUX_32BIT ADDR_LIMIT_32BIT +#define PER_SVR4 (1 | STICKY_TIMEOUTS | MMAP_PAGE_ZERO) +#define PER_SVR3 (2 | STICKY_TIMEOUTS | SHORT_INODE) +#define PER_SCOSVR3 (3 | STICKY_TIMEOUTS | WHOLE_SECONDS | SHORT_INODE) +#define PER_OSR5 (3 | STICKY_TIMEOUTS | WHOLE_SECONDS) +#define PER_WYSEV386 (4 | STICKY_TIMEOUTS | SHORT_INODE) +#define PER_ISCR4 (5 | STICKY_TIMEOUTS) +#define PER_BSD 6 +#define PER_SUNOS (6 | STICKY_TIMEOUTS) +#define PER_XENIX (7 | STICKY_TIMEOUTS | SHORT_INODE) +#define PER_LINUX32 8 +#define PER_LINUX32_3GB (8 | ADDR_LIMIT_3GB) +#define PER_IRIX32 (9 | STICKY_TIMEOUTS) +#define PER_IRIXN32 (0xa | STICKY_TIMEOUTS) +#define PER_IRIX64 (0x0b | STICKY_TIMEOUTS) +#define PER_RISCOS 0xc +#define PER_SOLARIS (0xd | STICKY_TIMEOUTS) +#define PER_UW7 (0xe | STICKY_TIMEOUTS | MMAP_PAGE_ZERO) +#define PER_OSF4 0xf +#define PER_HPUX 0x10 +#define PER_MASK 0xff + +int personality(unsigned long); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/poll.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/poll.h new file mode 100644 index 0000000000000000000000000000000000000000..99170401d0ce3858d1c8b32662fe9bd5c7f9d8e0 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/poll.h @@ -0,0 +1,2 @@ +#warning redirecting incorrect #include to +#include diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/prctl.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/prctl.h new file mode 100644 index 0000000000000000000000000000000000000000..d9c846e9c2eaec7103f71b9894d76a0b0345c1e2 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/prctl.h @@ -0,0 +1,167 @@ +#ifndef _SYS_PRCTL_H +#define _SYS_PRCTL_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#define PR_SET_PDEATHSIG 1 +#define PR_GET_PDEATHSIG 2 +#define PR_GET_DUMPABLE 3 +#define PR_SET_DUMPABLE 4 +#define PR_GET_UNALIGN 5 +#define PR_SET_UNALIGN 6 +#define PR_UNALIGN_NOPRINT 1 +#define PR_UNALIGN_SIGBUS 2 +#define PR_GET_KEEPCAPS 7 +#define PR_SET_KEEPCAPS 8 +#define PR_GET_FPEMU 9 +#define PR_SET_FPEMU 10 +#define PR_FPEMU_NOPRINT 1 +#define PR_FPEMU_SIGFPE 2 +#define PR_GET_FPEXC 11 +#define PR_SET_FPEXC 12 +#define PR_FP_EXC_SW_ENABLE 0x80 +#define PR_FP_EXC_DIV 0x010000 +#define PR_FP_EXC_OVF 0x020000 +#define PR_FP_EXC_UND 0x040000 +#define PR_FP_EXC_RES 0x080000 +#define PR_FP_EXC_INV 0x100000 +#define PR_FP_EXC_DISABLED 0 +#define PR_FP_EXC_NONRECOV 1 +#define PR_FP_EXC_ASYNC 2 +#define PR_FP_EXC_PRECISE 3 +#define PR_GET_TIMING 13 +#define PR_SET_TIMING 14 +#define PR_TIMING_STATISTICAL 0 +#define PR_TIMING_TIMESTAMP 1 +#define PR_SET_NAME 15 +#define PR_GET_NAME 16 +#define PR_GET_ENDIAN 19 +#define PR_SET_ENDIAN 20 +#define PR_ENDIAN_BIG 0 +#define PR_ENDIAN_LITTLE 1 +#define PR_ENDIAN_PPC_LITTLE 2 +#define PR_GET_SECCOMP 21 +#define PR_SET_SECCOMP 22 +#define PR_CAPBSET_READ 23 +#define PR_CAPBSET_DROP 24 +#define PR_GET_TSC 25 +#define PR_SET_TSC 26 +#define PR_TSC_ENABLE 1 +#define PR_TSC_SIGSEGV 2 +#define PR_GET_SECUREBITS 27 +#define PR_SET_SECUREBITS 28 +#define PR_SET_TIMERSLACK 29 +#define PR_GET_TIMERSLACK 30 + +#define PR_TASK_PERF_EVENTS_DISABLE 31 +#define PR_TASK_PERF_EVENTS_ENABLE 32 + +#define PR_MCE_KILL 33 +#define PR_MCE_KILL_CLEAR 0 +#define PR_MCE_KILL_SET 1 +#define PR_MCE_KILL_LATE 0 +#define PR_MCE_KILL_EARLY 1 +#define PR_MCE_KILL_DEFAULT 2 +#define PR_MCE_KILL_GET 34 + +#define PR_SET_MM 35 +#define PR_SET_MM_START_CODE 1 +#define PR_SET_MM_END_CODE 2 +#define PR_SET_MM_START_DATA 3 +#define PR_SET_MM_END_DATA 4 +#define PR_SET_MM_START_STACK 5 +#define PR_SET_MM_START_BRK 6 +#define PR_SET_MM_BRK 7 +#define PR_SET_MM_ARG_START 8 +#define PR_SET_MM_ARG_END 9 +#define PR_SET_MM_ENV_START 10 +#define PR_SET_MM_ENV_END 11 +#define PR_SET_MM_AUXV 12 +#define PR_SET_MM_EXE_FILE 13 +#define PR_SET_MM_MAP 14 +#define PR_SET_MM_MAP_SIZE 15 + +struct prctl_mm_map { + uint64_t start_code; + uint64_t end_code; + uint64_t start_data; + uint64_t end_data; + uint64_t start_brk; + uint64_t brk; + uint64_t start_stack; + uint64_t arg_start; + uint64_t arg_end; + uint64_t env_start; + uint64_t env_end; + uint64_t *auxv; + uint32_t auxv_size; + uint32_t exe_fd; +}; + +#define PR_SET_PTRACER 0x59616d61 +#define PR_SET_PTRACER_ANY (-1UL) + +#define PR_SET_CHILD_SUBREAPER 36 +#define PR_GET_CHILD_SUBREAPER 37 + +#define PR_SET_NO_NEW_PRIVS 38 +#define PR_GET_NO_NEW_PRIVS 39 + +#define PR_GET_TID_ADDRESS 40 + +#define PR_SET_THP_DISABLE 41 +#define PR_GET_THP_DISABLE 42 + +#define PR_MPX_ENABLE_MANAGEMENT 43 +#define PR_MPX_DISABLE_MANAGEMENT 44 + +#define PR_SET_FP_MODE 45 +#define PR_GET_FP_MODE 46 +#define PR_FP_MODE_FR (1 << 0) +#define PR_FP_MODE_FRE (1 << 1) + +#define PR_CAP_AMBIENT 47 +#define PR_CAP_AMBIENT_IS_SET 1 +#define PR_CAP_AMBIENT_RAISE 2 +#define PR_CAP_AMBIENT_LOWER 3 +#define PR_CAP_AMBIENT_CLEAR_ALL 4 + +#define PR_SVE_SET_VL 50 +#define PR_SVE_SET_VL_ONEXEC (1 << 18) +#define PR_SVE_GET_VL 51 +#define PR_SVE_VL_LEN_MASK 0xffff +#define PR_SVE_VL_INHERIT (1 << 17) + +#define PR_GET_SPECULATION_CTRL 52 +#define PR_SET_SPECULATION_CTRL 53 +#define PR_SPEC_STORE_BYPASS 0 +#define PR_SPEC_INDIRECT_BRANCH 1 +#define PR_SPEC_NOT_AFFECTED 0 +#define PR_SPEC_PRCTL (1UL << 0) +#define PR_SPEC_ENABLE (1UL << 1) +#define PR_SPEC_DISABLE (1UL << 2) +#define PR_SPEC_FORCE_DISABLE (1UL << 3) +#define PR_SPEC_DISABLE_NOEXEC (1UL << 4) + +#define PR_PAC_RESET_KEYS 54 +#define PR_PAC_APIAKEY (1UL << 0) +#define PR_PAC_APIBKEY (1UL << 1) +#define PR_PAC_APDAKEY (1UL << 2) +#define PR_PAC_APDBKEY (1UL << 3) +#define PR_PAC_APGAKEY (1UL << 4) + +#define PR_SET_TAGGED_ADDR_CTRL 55 +#define PR_GET_TAGGED_ADDR_CTRL 56 +#define PR_TAGGED_ADDR_ENABLE (1UL << 0) + +int prctl (int, ...); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/procfs.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/procfs.h new file mode 100644 index 0000000000000000000000000000000000000000..38e58c168b416a2e2452b06f9196e748f3e8a46a --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/procfs.h @@ -0,0 +1,63 @@ +#ifndef _SYS_PROCFS_H +#define _SYS_PROCFS_H +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include + +struct elf_siginfo { + int si_signo; + int si_code; + int si_errno; +}; + +struct elf_prstatus { + struct elf_siginfo pr_info; + short int pr_cursig; + unsigned long int pr_sigpend; + unsigned long int pr_sighold; + pid_t pr_pid; + pid_t pr_ppid; + pid_t pr_pgrp; + pid_t pr_sid; + struct { + long tv_sec, tv_usec; + } pr_utime, pr_stime, pr_cutime, pr_cstime; + elf_gregset_t pr_reg; + int pr_fpvalid; +}; + +#define ELF_PRARGSZ 80 + +struct elf_prpsinfo { + char pr_state; + char pr_sname; + char pr_zomb; + char pr_nice; + unsigned long int pr_flag; +#if UINTPTR_MAX == 0xffffffff + unsigned short int pr_uid; + unsigned short int pr_gid; +#else + unsigned int pr_uid; + unsigned int pr_gid; +#endif + int pr_pid, pr_ppid, pr_pgrp, pr_sid; + char pr_fname[16]; + char pr_psargs[ELF_PRARGSZ]; +}; + +typedef void *psaddr_t; +typedef elf_gregset_t prgregset_t; +typedef elf_fpregset_t prfpregset_t; +typedef pid_t lwpid_t; +typedef struct elf_prstatus prstatus_t; +typedef struct elf_prpsinfo prpsinfo_t; + +#ifdef __cplusplus +} +#endif +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/ptrace.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/ptrace.h new file mode 100644 index 0000000000000000000000000000000000000000..5d62a9859aac6016e89e0134bce25ec270673da3 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/ptrace.h @@ -0,0 +1,138 @@ +#ifndef _SYS_PTRACE_H +#define _SYS_PTRACE_H +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#define PTRACE_TRACEME 0 +#define PT_TRACE_ME PTRACE_TRACEME + +#define PTRACE_PEEKTEXT 1 +#define PTRACE_PEEKDATA 2 +#define PTRACE_PEEKUSER 3 +#define PTRACE_POKETEXT 4 +#define PTRACE_POKEDATA 5 +#define PTRACE_POKEUSER 6 +#define PTRACE_CONT 7 +#define PTRACE_KILL 8 +#define PTRACE_SINGLESTEP 9 +#define PTRACE_GETREGS 12 +#define PTRACE_SETREGS 13 +#define PTRACE_GETFPREGS 14 +#define PTRACE_SETFPREGS 15 +#define PTRACE_ATTACH 16 +#define PTRACE_DETACH 17 +#define PTRACE_GETFPXREGS 18 +#define PTRACE_SETFPXREGS 19 +#define PTRACE_SYSCALL 24 +#define PTRACE_SETOPTIONS 0x4200 +#define PTRACE_GETEVENTMSG 0x4201 +#define PTRACE_GETSIGINFO 0x4202 +#define PTRACE_SETSIGINFO 0x4203 +#define PTRACE_GETREGSET 0x4204 +#define PTRACE_SETREGSET 0x4205 +#define PTRACE_SEIZE 0x4206 +#define PTRACE_INTERRUPT 0x4207 +#define PTRACE_LISTEN 0x4208 +#define PTRACE_PEEKSIGINFO 0x4209 +#define PTRACE_GETSIGMASK 0x420a +#define PTRACE_SETSIGMASK 0x420b +#define PTRACE_SECCOMP_GET_FILTER 0x420c +#define PTRACE_SECCOMP_GET_METADATA 0x420d +#define PTRACE_GET_SYSCALL_INFO 0x420e + +#define PT_READ_I PTRACE_PEEKTEXT +#define PT_READ_D PTRACE_PEEKDATA +#define PT_READ_U PTRACE_PEEKUSER +#define PT_WRITE_I PTRACE_POKETEXT +#define PT_WRITE_D PTRACE_POKEDATA +#define PT_WRITE_U PTRACE_POKEUSER +#define PT_CONTINUE PTRACE_CONT +#define PT_KILL PTRACE_KILL +#define PT_STEP PTRACE_SINGLESTEP +#define PT_GETREGS PTRACE_GETREGS +#define PT_SETREGS PTRACE_SETREGS +#define PT_GETFPREGS PTRACE_GETFPREGS +#define PT_SETFPREGS PTRACE_SETFPREGS +#define PT_ATTACH PTRACE_ATTACH +#define PT_DETACH PTRACE_DETACH +#define PT_GETFPXREGS PTRACE_GETFPXREGS +#define PT_SETFPXREGS PTRACE_SETFPXREGS +#define PT_SYSCALL PTRACE_SYSCALL +#define PT_SETOPTIONS PTRACE_SETOPTIONS +#define PT_GETEVENTMSG PTRACE_GETEVENTMSG +#define PT_GETSIGINFO PTRACE_GETSIGINFO +#define PT_SETSIGINFO PTRACE_SETSIGINFO + +#define PTRACE_O_TRACESYSGOOD 0x00000001 +#define PTRACE_O_TRACEFORK 0x00000002 +#define PTRACE_O_TRACEVFORK 0x00000004 +#define PTRACE_O_TRACECLONE 0x00000008 +#define PTRACE_O_TRACEEXEC 0x00000010 +#define PTRACE_O_TRACEVFORKDONE 0x00000020 +#define PTRACE_O_TRACEEXIT 0x00000040 +#define PTRACE_O_TRACESECCOMP 0x00000080 +#define PTRACE_O_EXITKILL 0x00100000 +#define PTRACE_O_SUSPEND_SECCOMP 0x00200000 +#define PTRACE_O_MASK 0x003000ff + +#define PTRACE_EVENT_FORK 1 +#define PTRACE_EVENT_VFORK 2 +#define PTRACE_EVENT_CLONE 3 +#define PTRACE_EVENT_EXEC 4 +#define PTRACE_EVENT_VFORK_DONE 5 +#define PTRACE_EVENT_EXIT 6 +#define PTRACE_EVENT_SECCOMP 7 +#define PTRACE_EVENT_STOP 128 + +#define PTRACE_PEEKSIGINFO_SHARED 1 + +#define PTRACE_SYSCALL_INFO_NONE 0 +#define PTRACE_SYSCALL_INFO_ENTRY 1 +#define PTRACE_SYSCALL_INFO_EXIT 2 +#define PTRACE_SYSCALL_INFO_SECCOMP 3 + +#include + +struct __ptrace_peeksiginfo_args { + uint64_t off; + uint32_t flags; + int32_t nr; +}; + +struct __ptrace_seccomp_metadata { + uint64_t filter_off; + uint64_t flags; +}; + +struct __ptrace_syscall_info { + uint8_t op; + uint8_t __pad[3]; + uint32_t arch; + uint64_t instruction_pointer; + uint64_t stack_pointer; + union { + struct { + uint64_t nr; + uint64_t args[6]; + } entry; + struct { + int64_t rval; + uint8_t is_error; + } exit; + struct { + uint64_t nr; + uint64_t args[6]; + uint32_t ret_data; + } seccomp; + }; +}; + +long ptrace(int, ...); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/quota.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/quota.h new file mode 100644 index 0000000000000000000000000000000000000000..3ed73785df4c6fb9267110cd38a7c191308bf420 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/quota.h @@ -0,0 +1,102 @@ +#ifndef _SYS_QUOTA_H +#define _SYS_QUOTA_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#define _LINUX_QUOTA_VERSION 2 + +#define dbtob(num) ((num) << 10) +#define btodb(num) ((num) >> 10) +#define fs_to_dq_blocks(num, blksize) (((num) * (blksize)) / 1024) + +#define MAX_IQ_TIME 604800 +#define MAX_DQ_TIME 604800 + +#define MAXQUOTAS 2 +#define USRQUOTA 0 +#define GRPQUOTA 1 + +#define INITQFNAMES { "user", "group", "undefined" }; + +#define QUOTAFILENAME "quota" +#define QUOTAGROUP "staff" + +#define NR_DQHASH 43 +#define NR_DQUOTS 256 + +#define SUBCMDMASK 0x00ff +#define SUBCMDSHIFT 8 +#define QCMD(cmd, type) (((cmd) << SUBCMDSHIFT) | ((type) & SUBCMDMASK)) + +#define Q_SYNC 0x800001 +#define Q_QUOTAON 0x800002 +#define Q_QUOTAOFF 0x800003 +#define Q_GETFMT 0x800004 +#define Q_GETINFO 0x800005 +#define Q_SETINFO 0x800006 +#define Q_GETQUOTA 0x800007 +#define Q_SETQUOTA 0x800008 + +#define QFMT_VFS_OLD 1 +#define QFMT_VFS_V0 2 +#define QFMT_OCFS2 3 +#define QFMT_VFS_V1 4 + +#define QIF_BLIMITS 1 +#define QIF_SPACE 2 +#define QIF_ILIMITS 4 +#define QIF_INODES 8 +#define QIF_BTIME 16 +#define QIF_ITIME 32 +#define QIF_LIMITS (QIF_BLIMITS | QIF_ILIMITS) +#define QIF_USAGE (QIF_SPACE | QIF_INODES) +#define QIF_TIMES (QIF_BTIME | QIF_ITIME) +#define QIF_ALL (QIF_LIMITS | QIF_USAGE | QIF_TIMES) + +struct dqblk { + uint64_t dqb_bhardlimit; + uint64_t dqb_bsoftlimit; + uint64_t dqb_curspace; + uint64_t dqb_ihardlimit; + uint64_t dqb_isoftlimit; + uint64_t dqb_curinodes; + uint64_t dqb_btime; + uint64_t dqb_itime; + uint32_t dqb_valid; +}; + +#define dq_bhardlimit dq_dqb.dqb_bhardlimit +#define dq_bsoftlimit dq_dqb.dqb_bsoftlimit +#define dq_curspace dq_dqb.dqb_curspace +#define dq_valid dq_dqb.dqb_valid +#define dq_ihardlimit dq_dqb.dqb_ihardlimit +#define dq_isoftlimit dq_dqb.dqb_isoftlimit +#define dq_curinodes dq_dqb.dqb_curinodes +#define dq_btime dq_dqb.dqb_btime +#define dq_itime dq_dqb.dqb_itime + +#define dqoff(UID) ((long long)(UID) * sizeof (struct dqblk)) + +#define IIF_BGRACE 1 +#define IIF_IGRACE 2 +#define IIF_FLAGS 4 +#define IIF_ALL (IIF_BGRACE | IIF_IGRACE | IIF_FLAGS) + +struct dqinfo { + uint64_t dqi_bgrace; + uint64_t dqi_igrace; + uint32_t dqi_flags; + uint32_t dqi_valid; +}; + +int quotactl(int, const char *, int, char *); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/random.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/random.h new file mode 100644 index 0000000000000000000000000000000000000000..4ee7bf2cc4f2311742fa717ab08c8ee5ca466360 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/random.h @@ -0,0 +1,19 @@ +#ifndef _SYS_RANDOM_H +#define _SYS_RANDOM_H +#ifdef __cplusplus +extern "C" { +#endif + +#define __NEED_size_t +#define __NEED_ssize_t +#include + +#define GRND_NONBLOCK 0x0001 +#define GRND_RANDOM 0x0002 + +ssize_t getrandom(void *, size_t, unsigned); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/reboot.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/reboot.h new file mode 100644 index 0000000000000000000000000000000000000000..9702eddba4ba24accb231b81d9e7ed0f79d37656 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/reboot.h @@ -0,0 +1,20 @@ +#ifndef _SYS_REBOOT_H +#define _SYS_REBOOT_H +#ifdef __cplusplus +extern "C" { +#endif + +#define RB_AUTOBOOT 0x01234567 +#define RB_HALT_SYSTEM 0xcdef0123 +#define RB_ENABLE_CAD 0x89abcdef +#define RB_DISABLE_CAD 0 +#define RB_POWER_OFF 0x4321fedc +#define RB_SW_SUSPEND 0xd000fce2 +#define RB_KEXEC 0x45584543 + +int reboot(int); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/reg.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/reg.h new file mode 100644 index 0000000000000000000000000000000000000000..b47452d003ec6b227e34804d7622215d4cf27466 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/reg.h @@ -0,0 +1,9 @@ +#ifndef _SYS_REG_H +#define _SYS_REG_H + +#include +#include + +#include + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/resource.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/resource.h new file mode 100644 index 0000000000000000000000000000000000000000..3068328d09612b8b9d58f2874ea17b0afeef0fef --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/resource.h @@ -0,0 +1,116 @@ +#ifndef _SYS_RESOURCE_H +#define _SYS_RESOURCE_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include + +#define __NEED_id_t + +#ifdef _GNU_SOURCE +#define __NEED_pid_t +#endif + +#include +#include + +typedef unsigned long long rlim_t; + +struct rlimit { + rlim_t rlim_cur; + rlim_t rlim_max; +}; + +struct rusage { + struct timeval ru_utime; + struct timeval ru_stime; + /* linux extentions, but useful */ + long ru_maxrss; + long ru_ixrss; + long ru_idrss; + long ru_isrss; + long ru_minflt; + long ru_majflt; + long ru_nswap; + long ru_inblock; + long ru_oublock; + long ru_msgsnd; + long ru_msgrcv; + long ru_nsignals; + long ru_nvcsw; + long ru_nivcsw; + /* room for more... */ + long __reserved[16]; +}; + +int getrlimit (int, struct rlimit *); +int setrlimit (int, const struct rlimit *); +int getrusage (int, struct rusage *); + +int getpriority (int, id_t); +int setpriority (int, id_t, int); + +#ifdef _GNU_SOURCE +int prlimit(pid_t, int, const struct rlimit *, struct rlimit *); +#define prlimit64 prlimit +#endif + +#define PRIO_MIN (-20) +#define PRIO_MAX 20 + +#define PRIO_PROCESS 0 +#define PRIO_PGRP 1 +#define PRIO_USER 2 + +#define RUSAGE_SELF 0 +#define RUSAGE_CHILDREN (-1) +#define RUSAGE_THREAD 1 + +#define RLIM_INFINITY (~0ULL) +#define RLIM_SAVED_CUR RLIM_INFINITY +#define RLIM_SAVED_MAX RLIM_INFINITY + +#define RLIMIT_CPU 0 +#define RLIMIT_FSIZE 1 +#define RLIMIT_DATA 2 +#define RLIMIT_STACK 3 +#define RLIMIT_CORE 4 +#ifndef RLIMIT_RSS +#define RLIMIT_RSS 5 +#define RLIMIT_NPROC 6 +#define RLIMIT_NOFILE 7 +#define RLIMIT_MEMLOCK 8 +#define RLIMIT_AS 9 +#endif +#define RLIMIT_LOCKS 10 +#define RLIMIT_SIGPENDING 11 +#define RLIMIT_MSGQUEUE 12 +#define RLIMIT_NICE 13 +#define RLIMIT_RTPRIO 14 +#define RLIMIT_RTTIME 15 +#define RLIMIT_NLIMITS 16 + +#define RLIM_NLIMITS RLIMIT_NLIMITS + +#if defined(_LARGEFILE64_SOURCE) || defined(_GNU_SOURCE) +#define RLIM64_INFINITY RLIM_INFINITY +#define RLIM64_SAVED_CUR RLIM_SAVED_CUR +#define RLIM64_SAVED_MAX RLIM_SAVED_MAX +#define getrlimit64 getrlimit +#define setrlimit64 setrlimit +#define rlimit64 rlimit +#define rlim64_t rlim_t +#endif + +#if _REDIR_TIME64 +__REDIR(getrusage, __getrusage_time64); +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/select.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/select.h new file mode 100644 index 0000000000000000000000000000000000000000..a69320c640f213806b100e16b4ebd96c23f50c6b --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/select.h @@ -0,0 +1,155 @@ +/** + * @defgroup select Select + * @ingroup libc + */ + +#ifndef _SYS_SELECT_H +#define _SYS_SELECT_H +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#define __NEED_size_t +#define __NEED_time_t +#define __NEED_suseconds_t +#define __NEED_struct_timeval +#define __NEED_struct_timespec +#define __NEED_sigset_t + +#include + +#include "los_config.h" +#if defined(__LITEOS__) && defined(LOSCFG_FS_VFS) +#include "vfs_config.h" +#else +#ifndef FD_SETSIZE +#define FD_SETSIZE 1024 +#endif +#endif + +typedef unsigned long fd_mask; + +typedef struct { + unsigned long fds_bits[FD_SETSIZE / 8 / sizeof(long)]; +} fd_set; + +#define FD_ZERO(s) do { int __i; unsigned long *__b=(s)->fds_bits; for(__i=sizeof (fd_set)/sizeof (long); __i; __i--) *__b++=0; } while(0) +#define FD_SET(d, s) ((s)->fds_bits[(d)/(8*sizeof(long))] |= (1UL<<((d)%(8*sizeof(long))))) +#define FD_CLR(d, s) ((s)->fds_bits[(d)/(8*sizeof(long))] &= ~(1UL<<((d)%(8*sizeof(long))))) +#define FD_ISSET(d, s) !!((s)->fds_bits[(d)/(8*sizeof(long))] & (1UL<<((d)%(8*sizeof(long))))) + +/** + * @ingroup select + * @par Description: + * + * The select function examines the file descriptor sets whose addresses are passed in the readfds, writefds, and errorfds parameters to see whether + * some of their descriptors are ready for reading, are ready for writing, or have an exceptional condition pending, respectively. \n\n + * + * Upon successful completion, the select function would modify the objects pointed to by the readfds, writefds, and errorfds arguments to indicate + * which file descriptors are ready for reading, ready for writing, or have an error condition pending, respectively, and the total number of ready descriptors + * in all the output sets would be returned. For each file descriptor less than nfds, the corresponding bit shall be set upon successful completion if it was + * set on input and the associated condition is true for that file descriptor. If none of the selected descriptors are ready for the requested operation, the + * select function shall block until at least one of the requested operations becomes ready, until the timeout occurs. The timeout parameter controls how + * long the select function shall take before timing out. If the timeout parameter is not a null pointer, it specifies a maximum interval to wait for the selection + * to complete. If the specified time interval expires without any requested operationbecoming ready, the function would return. If the timeout parameter is + * a null pointer, then the call to select would block indefinitely until at least one descriptor meets the specified criteria.\n\n + * + * A descriptor shall be considered ready for reading when a call to an input function with O_NONBLOCK clear would not block, whether or not the function + * would transfer data successfully. (The function might return data, an end-of-file indication, or an error other than one indicating that it is blocked, and + * in each of these cases the descriptor shall be considered ready for reading). If the descriptor refers to a socket, the implied input function is the recvmsg + * function with parameters requesting normal and ancillary data, such that the presence of either type shall cause the socket to be marked as readable. + * The presence of out-of-band data shall be checked if the socket option SO_OOBINLINE has been enabled, as out-of-band data is enqueued with normal data. + * If the socket is currently listening, then it shall be marked as readable if an incoming connection request has been received, and a call to the accept function + * shall complete without blocking.\n\n + * + * A descriptor shall be considered ready for writing when a call to an output function with O_NONBLOCK clear would not block, whether or not the function + * would transfer data successfully. If the descriptor refers to a socket, the implied output function is the sendmsg function supplying an amount of normal + * data equal to the current value of the SO_SNDLOWAT option for the socket. If a non-blocking call to the connect function has been made for a socket, and + * the connection attempt has either succeeded or failed leaving a pending error, the socket shall be marked as writable.\n\n + * + * If a socket has a pending error, it shall be considered to have an exceptional condition pending. Otherwise, what constitutes an exceptional condition is file + * type-specific. For a file descriptor for use with a socket, it is protocol-specific except as noted below. For other file types it is implementation-defined. If the + * operation is meaningless for a particular file type, the select shall indicate that the descriptor is ready for read or write operations, and shall indicate that the + * descriptor has no exceptional condition pending. A socket shall be considered to have an exceptional condition pending if a receive operation with O_NONBLOCK + * clear for the open file description and with the MSG_OOB flag set would return out-of-band data without blocking. (It is protocol-specific whether the MSG_OOB + * flag would be used to read out-of-band data.) A socket shall also be considered to have an exceptional condition pending if an out-of-band data mark is present + * in the receive queue. Other circumstances under which a socket may be considered to have an exceptional condition pending are implementation-defined. \n\n + * + * File descriptors associated with regular files shall always select true for ready to read, ready to write, and error conditions.\n\n + * + * If the readfds, writefds, and errorfds arguments are all null pointers and the timeout argument is not a null pointer, the select() function would block for the + * time specified. If the readfds, writefds, and errorfds arguments are all null pointers and the timeout argument is a null pointer, the select() function returns + * failure immediately.\n\n + * + * File descriptor masks of type fd_set can be initialized and tested with FD_CLR, FD_ISSET, FD_SET, and FD_ZERO. It is unspecified whether each of these + * is a macro or a function. If a macro definition is suppressed in order to access an actual function, or a program defines an external identifier with any of these + * names, the behavior is undefined.\n\n + * + * FD_CLR(fd, set) shall remove the file descriptor fd from the set pointed to by set. If fd is not a member of this set, there is no effect on the set. + * FD_ISSET(fd, set) shall evaluate to non-zero if the file descriptor fd is a member of the set pointed to by set, and shall evaluate to zero otherwise. + * FD_SET(fd, set) shall add the file descriptor fd to the set pointed to by set. If the file descriptor fd is already in this set, there is no effect on the set. + * FD_ZERO(set) shall initialize the descriptor set pointed to by set to the null set. No error is returned if the set is not empty at the time FD_ZERO() is invoked.\n\n + * + * The behavior of these macros is undefined if the fd argument is less than 0 or greater than or equal to FD_SETSIZE, or if fd is not a valid file descriptor, + * or if any of the arguments are expressions with side-effects.\n\n + * + * @param nfds [IN] the range of descriptors to be tested, all descriptors from zero to nfds-1 in the descriptor sets shall be examined. + * @param readfds [IN/OUT] on input specifies the file descriptors to be checked for being ready to read, and on output indicates which file descriptors are ready to read. + * @param writefds [IN/OUT] on input specifies the file descriptors to be checked for being ready to write, and on output indicates which file descriptors are ready to write. + * @param errorfds [IN/OUT] on input specifies the file descriptors to be checked for error conditions pending, and on output indicates which file descriptors have error conditions pending. + * @param timeout [IN] a maximum interval to wait for the selection to complete. + * + * @attention + *
        + *
      • Unlike Linux or other operation system, LiteOS does not support signal mechanism, so the select function can't be interrupted by signal.
      • + *
      • Unlike Linux, LiteOS does not modify the timeout argument to reflect the amount of time not slept on successful completion.
      • + *
      • The select functions support regular files, terminal, device files and sockets. The behavior of select on file descriptors that refer to other types of file is unspecified.
      • + *
      • If the readfds, writefds, errorfds and timeout are all null, the select function returns immediately. But in Linux or other system, the select function + * would block until interrupted by a signal.
      • + *
      • LiteOS don't support TCP urgent data(also used as the out-of-band data), so the caller can not use the select function with errorfds to examine the TCP urgent data.
      • + *
      • It is recommended that the poll function is perferred than the select as the impelmentation of select is based on the pool, so the poll function is more efficient.
      • + *
      • If a file descriptor being monitored by select is closed in another thread, the result is unspecified. On some UNIX systems, select unblocks and returns + * with an indication that the file descriptor is ready. On LiteOS, closing the file descriptor in another thread has no effect on select. In summary, + * any application that relies on a particular behavior in this scenario must be considered buggy.
      • + *
      • The timeout will be rounded up to the system clock granularity, on LiteOS, it's the system scheduling tick. So the minimal poll timeout is one + * scheduling tick on LiteOS.
      • + *
      + * + * @retval #>=0 On success, the total number of bits set in the bit masks is retuened. If timeout expires before anything interesting happens, 0 is returned. + * @retval #-1 On failure, -1 is returned, and errno is set to indicate the error, the file descriptor sets and timeout are unmodified. + * FD_CLR, FD_SET, and FD_ZERO do not return a value. FD_ISSET returns a non-zero value if the bit for the file descriptor fd is set in the file descriptor + * set pointed to by fdset, and 0 otherwise.\n\n + * + * @par Errors + *
        + *
      • EBADF: One or more of the file descriptor sets specified a file descriptor that is not a valid open file descriptor.
      • + *
      • EINVAL: The nfds argument is less than 0 or greater than FD_SETSIZE.
      • + *
      • EINVAL: The readfds, writefds, errorfds and timeout are all null.
      • + *
      • ENOMEM: Unable to allocate memory for internal tables.
      • + *
      • ENOSYS: One or more of the file descriptor sets specified a file descriptor don't support poll operation
      • + *
      + * + * @par Dependency: + *
      • sys/select.h
      + * + * @see accept | connect | poll | read | recv | send | write + * + */ +int select (int, fd_set *__restrict, fd_set *__restrict, fd_set *__restrict, struct timeval *__restrict); +int pselect (int, fd_set *__restrict, fd_set *__restrict, fd_set *__restrict, const struct timespec *__restrict, const sigset_t *__restrict); + +#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE) +#define NFDBITS (8*(int)sizeof(long)) +#endif + +#if _REDIR_TIME64 +__REDIR(select, __select_time64); +__REDIR(pselect, __pselect_time64); +#endif + +#ifdef __cplusplus +} +#endif +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/sem.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/sem.h new file mode 100644 index 0000000000000000000000000000000000000000..a747784ede9e0d0a04d96b80c29bc8f847e3b3c7 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/sem.h @@ -0,0 +1,72 @@ +#ifndef _SYS_SEM_H +#define _SYS_SEM_H +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#define __NEED_size_t +#define __NEED_pid_t +#define __NEED_time_t +#ifdef _GNU_SOURCE +#define __NEED_struct_timespec +#endif +#include + +#include + +#define SEM_UNDO 0x1000 +#define GETPID 11 +#define GETVAL 12 +#define GETALL 13 +#define GETNCNT 14 +#define GETZCNT 15 +#define SETVAL 16 +#define SETALL 17 + +#include + +#define _SEM_SEMUN_UNDEFINED 1 + +#define SEM_STAT (18 | (IPC_STAT & 0x100)) +#define SEM_INFO 19 +#define SEM_STAT_ANY (20 | (IPC_STAT & 0x100)) + +struct seminfo { + int semmap; + int semmni; + int semmns; + int semmnu; + int semmsl; + int semopm; + int semume; + int semusz; + int semvmx; + int semaem; +}; + +struct sembuf { + unsigned short sem_num; + short sem_op; + short sem_flg; +}; + +int semctl(int, int, int, ...); +int semget(key_t, int, int); +int semop(int, struct sembuf *, size_t); + +#ifdef _GNU_SOURCE +int semtimedop(int, struct sembuf *, size_t, const struct timespec *); +#endif + +#if _REDIR_TIME64 +#ifdef _GNU_SOURCE +__REDIR(semtimedop, __semtimedop_time64); +#endif +#endif + +#ifdef __cplusplus +} +#endif +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/sendfile.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/sendfile.h new file mode 100644 index 0000000000000000000000000000000000000000..bcd8709708c5ca5234658e062a064d3e5d177054 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/sendfile.h @@ -0,0 +1,32 @@ +#ifndef _SYS_SENDFILE_H +#define _SYS_SENDFILE_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include + +#ifdef __LITEOS__ +#define __NEED_off_t +#define __NEED_int64_t +#include +#endif + +ssize_t sendfile(int, int, off_t *, size_t); + +#if defined(_LARGEFILE64_SOURCE) || defined(_GNU_SOURCE) +#define sendfile64 sendfile +#ifdef __LITEOS__ +#define off64_t int64_t +#else +#define off64_t off_t +#endif +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/shm.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/shm.h new file mode 100644 index 0000000000000000000000000000000000000000..fd708cab1eb8c2e22eaf6bf300d8234e5002d770 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/shm.h @@ -0,0 +1,70 @@ +#ifndef _SYS_SHM_H +#define _SYS_SHM_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#define __NEED_time_t +#define __NEED_size_t +#define __NEED_pid_t + +#include + +#include + +#ifdef _GNU_SOURCE +#define __used_ids used_ids +#define __swap_attempts swap_attempts +#define __swap_successes swap_successes +#endif + +#include + +#define SHM_R 0400 +#define SHM_W 0200 + +#define SHM_RDONLY 010000 +#define SHM_RND 020000 +#define SHM_REMAP 040000 +#define SHM_EXEC 0100000 + +#define SHM_LOCK 11 +#define SHM_UNLOCK 12 +#define SHM_STAT (13 | (IPC_STAT & 0x100)) +#define SHM_INFO 14 +#define SHM_STAT_ANY (15 | (IPC_STAT & 0x100)) +#define SHM_DEST 01000 +#define SHM_LOCKED 02000 +#define SHM_HUGETLB 04000 +#define SHM_NORESERVE 010000 + +#define SHM_HUGE_SHIFT 26 +#define SHM_HUGE_MASK 0x3f +#define SHM_HUGE_64KB (16 << 26) +#define SHM_HUGE_512KB (19 << 26) +#define SHM_HUGE_1MB (20 << 26) +#define SHM_HUGE_2MB (21 << 26) +#define SHM_HUGE_8MB (23 << 26) +#define SHM_HUGE_16MB (24 << 26) +#define SHM_HUGE_32MB (25 << 26) +#define SHM_HUGE_256MB (28 << 26) +#define SHM_HUGE_512MB (29 << 26) +#define SHM_HUGE_1GB (30 << 26) +#define SHM_HUGE_2GB (31 << 26) +#define SHM_HUGE_16GB (34U << 26) + +typedef unsigned long shmatt_t; + +void *shmat(int, const void *, int); +int shmctl(int, int, struct shmid_ds *); +int shmdt(const void *); +int shmget(key_t, size_t, int); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/signal.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/signal.h new file mode 100644 index 0000000000000000000000000000000000000000..45bdcc648e7b07771533c1cb59cecd643fb95dab --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/signal.h @@ -0,0 +1,2 @@ +#warning redirecting incorrect #include to +#include diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/signalfd.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/signalfd.h new file mode 100644 index 0000000000000000000000000000000000000000..e881e2cfddcc7708c8c332ae5d844ec96d85944d --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/signalfd.h @@ -0,0 +1,49 @@ +#ifndef _SYS_SIGNALFD_H +#define _SYS_SIGNALFD_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include + +#define __NEED_sigset_t + +#include + +#define SFD_CLOEXEC O_CLOEXEC +#define SFD_NONBLOCK O_NONBLOCK + +int signalfd(int, const sigset_t *, int); + +struct signalfd_siginfo { + uint32_t ssi_signo; + int32_t ssi_errno; + int32_t ssi_code; + uint32_t ssi_pid; + uint32_t ssi_uid; + int32_t ssi_fd; + uint32_t ssi_tid; + uint32_t ssi_band; + uint32_t ssi_overrun; + uint32_t ssi_trapno; + int32_t ssi_status; + int32_t ssi_int; + uint64_t ssi_ptr; + uint64_t ssi_utime; + uint64_t ssi_stime; + uint64_t ssi_addr; + uint16_t ssi_addr_lsb; + uint16_t __pad2; + int32_t ssi_syscall; + uint64_t ssi_call_addr; + uint32_t ssi_arch; + uint8_t __pad[128-14*4-5*8-2*2]; +}; + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/socket.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/socket.h new file mode 100644 index 0000000000000000000000000000000000000000..049fcdac48d8e33240c65b73108724ebcedf9308 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/socket.h @@ -0,0 +1,1148 @@ +/** + * @defgroup socket Socket + * @ingroup libc + */ + +#ifndef _SYS_SOCKET_H +#define _SYS_SOCKET_H +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#define __NEED_socklen_t +#define __NEED_sa_family_t +#define __NEED_size_t +#define __NEED_ssize_t +#define __NEED_uid_t +#define __NEED_pid_t +#define __NEED_gid_t +#define __NEED_struct_iovec + +#include + +#include + +struct msghdr { + void *msg_name; + socklen_t msg_namelen; + struct iovec *msg_iov; +#if __LONG_MAX > 0x7fffffff && __BYTE_ORDER == __BIG_ENDIAN + int __pad1; +#endif + int msg_iovlen; +#if __LONG_MAX > 0x7fffffff && __BYTE_ORDER == __LITTLE_ENDIAN + int __pad1; +#endif + void *msg_control; +#if __LONG_MAX > 0x7fffffff && __BYTE_ORDER == __BIG_ENDIAN + int __pad2; +#endif + socklen_t msg_controllen; +#if __LONG_MAX > 0x7fffffff && __BYTE_ORDER == __LITTLE_ENDIAN + int __pad2; +#endif + int msg_flags; +}; + +struct cmsghdr { +#if __LONG_MAX > 0x7fffffff && __BYTE_ORDER == __BIG_ENDIAN + int __pad1; +#endif + socklen_t cmsg_len; +#if __LONG_MAX > 0x7fffffff && __BYTE_ORDER == __LITTLE_ENDIAN + int __pad1; +#endif + int cmsg_level; + int cmsg_type; +}; + +#ifdef _GNU_SOURCE +struct ucred { + pid_t pid; + uid_t uid; + gid_t gid; +}; + +struct mmsghdr { + struct msghdr msg_hdr; + unsigned int msg_len; +}; + +struct timespec; + +int sendmmsg (int, struct mmsghdr *, unsigned int, unsigned int); +int recvmmsg (int, struct mmsghdr *, unsigned int, unsigned int, struct timespec *); +#endif + +struct linger { + int l_onoff; + int l_linger; +}; + +#define SHUT_RD 0 +#define SHUT_WR 1 +#define SHUT_RDWR 2 + +#ifndef SOCK_STREAM +#define SOCK_STREAM 1 +#define SOCK_DGRAM 2 +#endif + +#define SOCK_RAW 3 +#define SOCK_RDM 4 +#define SOCK_SEQPACKET 5 +#define SOCK_DCCP 6 +#define SOCK_PACKET 10 + +#ifndef SOCK_CLOEXEC +#define SOCK_CLOEXEC 02000000 +#define SOCK_NONBLOCK 04000 +#endif + +#define PF_UNSPEC 0 +#define PF_LOCAL 1 +#define PF_UNIX PF_LOCAL +#define PF_FILE PF_LOCAL +#define PF_INET 2 +#define PF_AX25 3 +#define PF_IPX 4 +#define PF_APPLETALK 5 +#define PF_NETROM 6 +#define PF_BRIDGE 7 +#define PF_ATMPVC 8 +#define PF_X25 9 +#define PF_INET6 10 +#define PF_ROSE 11 +#define PF_DECnet 12 +#define PF_NETBEUI 13 +#define PF_SECURITY 14 +#define PF_KEY 15 +#define PF_NETLINK 16 +#define PF_ROUTE PF_NETLINK +#define PF_PACKET 17 +#define PF_ASH 18 +#define PF_ECONET 19 +#define PF_ATMSVC 20 +#define PF_RDS 21 +#define PF_SNA 22 +#define PF_IRDA 23 +#define PF_PPPOX 24 +#define PF_WANPIPE 25 +#define PF_LLC 26 +#define PF_IB 27 +#define PF_MPLS 28 +#define PF_CAN 29 +#define PF_TIPC 30 +#define PF_BLUETOOTH 31 +#define PF_IUCV 32 +#define PF_RXRPC 33 +#define PF_ISDN 34 +#define PF_PHONET 35 +#define PF_IEEE802154 36 +#define PF_CAIF 37 +#define PF_ALG 38 +#define PF_NFC 39 +#define PF_VSOCK 40 +#define PF_KCM 41 +#define PF_QIPCRTR 42 +#define PF_SMC 43 +#define PF_XDP 44 +#define PF_MAX 45 + +#define AF_UNSPEC PF_UNSPEC +#define AF_LOCAL PF_LOCAL +#define AF_UNIX AF_LOCAL +#define AF_FILE AF_LOCAL +#define AF_INET PF_INET +#define AF_AX25 PF_AX25 +#define AF_IPX PF_IPX +#define AF_APPLETALK PF_APPLETALK +#define AF_NETROM PF_NETROM +#define AF_BRIDGE PF_BRIDGE +#define AF_ATMPVC PF_ATMPVC +#define AF_X25 PF_X25 +#define AF_INET6 PF_INET6 +#define AF_ROSE PF_ROSE +#define AF_DECnet PF_DECnet +#define AF_NETBEUI PF_NETBEUI +#define AF_SECURITY PF_SECURITY +#define AF_KEY PF_KEY +#define AF_NETLINK PF_NETLINK +#define AF_ROUTE PF_ROUTE +#define AF_PACKET PF_PACKET +#define AF_ASH PF_ASH +#define AF_ECONET PF_ECONET +#define AF_ATMSVC PF_ATMSVC +#define AF_RDS PF_RDS +#define AF_SNA PF_SNA +#define AF_IRDA PF_IRDA +#define AF_PPPOX PF_PPPOX +#define AF_WANPIPE PF_WANPIPE +#define AF_LLC PF_LLC +#define AF_IB PF_IB +#define AF_MPLS PF_MPLS +#define AF_CAN PF_CAN +#define AF_TIPC PF_TIPC +#define AF_BLUETOOTH PF_BLUETOOTH +#define AF_IUCV PF_IUCV +#define AF_RXRPC PF_RXRPC +#define AF_ISDN PF_ISDN +#define AF_PHONET PF_PHONET +#define AF_IEEE802154 PF_IEEE802154 +#define AF_CAIF PF_CAIF +#define AF_ALG PF_ALG +#define AF_NFC PF_NFC +#define AF_VSOCK PF_VSOCK +#define AF_KCM PF_KCM +#define AF_QIPCRTR PF_QIPCRTR +#define AF_SMC PF_SMC +#define AF_XDP PF_XDP +#define AF_MAX PF_MAX + +#ifndef SO_DEBUG +#define SO_DEBUG 1 +#define SO_REUSEADDR 2 +#define SO_TYPE 3 +#define SO_ERROR 4 +#define SO_DONTROUTE 5 +#define SO_BROADCAST 6 +#define SO_SNDBUF 7 +#define SO_RCVBUF 8 +#define SO_KEEPALIVE 9 +#define SO_OOBINLINE 10 +#define SO_NO_CHECK 11 +#define SO_PRIORITY 12 +#define SO_LINGER 13 +#define SO_BSDCOMPAT 14 +#define SO_REUSEPORT 15 +#define SO_PASSCRED 16 +#define SO_PEERCRED 17 +#define SO_RCVLOWAT 18 +#define SO_SNDLOWAT 19 +#define SO_ACCEPTCONN 30 +#define SO_PEERSEC 31 +#define SO_SNDBUFFORCE 32 +#define SO_RCVBUFFORCE 33 +#define SO_PROTOCOL 38 +#define SO_DOMAIN 39 +#endif + +#ifndef SO_RCVTIMEO +#if __LONG_MAX == 0x7fffffff +#define SO_RCVTIMEO 66 +#define SO_SNDTIMEO 67 +#else +#define SO_RCVTIMEO 20 +#define SO_SNDTIMEO 21 +#endif +#endif + +#ifndef SO_TIMESTAMP +#if __LONG_MAX == 0x7fffffff +#define SO_TIMESTAMP 63 +#define SO_TIMESTAMPNS 64 +#define SO_TIMESTAMPING 65 +#else +#define SO_TIMESTAMP 29 +#define SO_TIMESTAMPNS 35 +#define SO_TIMESTAMPING 37 +#endif +#endif + +#define SO_SECURITY_AUTHENTICATION 22 +#define SO_SECURITY_ENCRYPTION_TRANSPORT 23 +#define SO_SECURITY_ENCRYPTION_NETWORK 24 + +#define SO_BINDTODEVICE 25 + +#define SO_ATTACH_FILTER 26 +#define SO_DETACH_FILTER 27 +#define SO_GET_FILTER SO_ATTACH_FILTER + +#define SO_PEERNAME 28 +#define SCM_TIMESTAMP SO_TIMESTAMP +#define SO_PASSSEC 34 +#define SCM_TIMESTAMPNS SO_TIMESTAMPNS +#define SO_MARK 36 +#define SCM_TIMESTAMPING SO_TIMESTAMPING +#define SO_RXQ_OVFL 40 +#define SO_WIFI_STATUS 41 +#define SCM_WIFI_STATUS SO_WIFI_STATUS +#define SO_PEEK_OFF 42 +#define SO_NOFCS 43 +#define SO_LOCK_FILTER 44 +#define SO_SELECT_ERR_QUEUE 45 +#define SO_BUSY_POLL 46 +#define SO_MAX_PACING_RATE 47 +#define SO_BPF_EXTENSIONS 48 +#define SO_INCOMING_CPU 49 +#define SO_ATTACH_BPF 50 +#define SO_DETACH_BPF SO_DETACH_FILTER +#define SO_ATTACH_REUSEPORT_CBPF 51 +#define SO_ATTACH_REUSEPORT_EBPF 52 +#define SO_CNX_ADVICE 53 +#define SCM_TIMESTAMPING_OPT_STATS 54 +#define SO_MEMINFO 55 +#define SO_INCOMING_NAPI_ID 56 +#define SO_COOKIE 57 +#define SCM_TIMESTAMPING_PKTINFO 58 +#define SO_PEERGROUPS 59 +#define SO_ZEROCOPY 60 +#define SO_TXTIME 61 +#define SCM_TXTIME SO_TXTIME +#define SO_BINDTOIFINDEX 62 +#define SO_DETACH_REUSEPORT_BPF 68 + +#ifndef SOL_SOCKET +#define SOL_SOCKET 1 +#endif + +#define SOL_IP 0 +#define SOL_IPV6 41 +#define SOL_ICMPV6 58 + +#define SOL_RAW 255 +#define SOL_DECNET 261 +#define SOL_X25 262 +#define SOL_PACKET 263 +#define SOL_ATM 264 +#define SOL_AAL 265 +#define SOL_IRDA 266 +#define SOL_NETBEUI 267 +#define SOL_LLC 268 +#define SOL_DCCP 269 +#define SOL_NETLINK 270 +#define SOL_TIPC 271 +#define SOL_RXRPC 272 +#define SOL_PPPOL2TP 273 +#define SOL_BLUETOOTH 274 +#define SOL_PNPIPE 275 +#define SOL_RDS 276 +#define SOL_IUCV 277 +#define SOL_CAIF 278 +#define SOL_ALG 279 +#define SOL_NFC 280 +#define SOL_KCM 281 +#define SOL_TLS 282 +#define SOL_XDP 283 + +#define SOMAXCONN 128 + +#define MSG_OOB 0x0001 +#define MSG_PEEK 0x0002 +#define MSG_DONTROUTE 0x0004 +#define MSG_CTRUNC 0x0008 +#define MSG_PROXY 0x0010 +#define MSG_TRUNC 0x0020 +#define MSG_DONTWAIT 0x0040 +#define MSG_EOR 0x0080 +#define MSG_WAITALL 0x0100 +#define MSG_FIN 0x0200 +#define MSG_SYN 0x0400 +#define MSG_CONFIRM 0x0800 +#define MSG_RST 0x1000 +#define MSG_ERRQUEUE 0x2000 +#define MSG_NOSIGNAL 0x4000 +#define MSG_MORE 0x8000 +#define MSG_WAITFORONE 0x10000 +#define MSG_BATCH 0x40000 +#define MSG_ZEROCOPY 0x4000000 +#define MSG_FASTOPEN 0x20000000 +#define MSG_CMSG_CLOEXEC 0x40000000 + +#define __CMSG_LEN(cmsg) (((cmsg)->cmsg_len + sizeof(long) - 1) & ~(long)(sizeof(long) - 1)) +#define __CMSG_NEXT(cmsg) ((unsigned char *)(cmsg) + __CMSG_LEN(cmsg)) +#define __MHDR_END(mhdr) ((unsigned char *)(mhdr)->msg_control + (mhdr)->msg_controllen) + +#define CMSG_DATA(cmsg) ((unsigned char *) (((struct cmsghdr *)(cmsg)) + 1)) +#define CMSG_NXTHDR(mhdr, cmsg) ((cmsg)->cmsg_len < sizeof (struct cmsghdr) || \ + __CMSG_LEN(cmsg) + sizeof(struct cmsghdr) >= __MHDR_END(mhdr) - (unsigned char *)(cmsg) \ + ? 0 : (struct cmsghdr *)__CMSG_NEXT(cmsg)) +#define CMSG_FIRSTHDR(mhdr) ((size_t) (mhdr)->msg_controllen >= sizeof (struct cmsghdr) ? (struct cmsghdr *) (mhdr)->msg_control : (struct cmsghdr *) 0) + +#define CMSG_ALIGN(len) (((len) + sizeof (size_t) - 1) & (size_t) ~(sizeof (size_t) - 1)) +#define CMSG_SPACE(len) (CMSG_ALIGN (len) + CMSG_ALIGN (sizeof (struct cmsghdr))) +#define CMSG_LEN(len) (CMSG_ALIGN (sizeof (struct cmsghdr)) + (len)) + +#define SCM_RIGHTS 0x01 +#define SCM_CREDENTIALS 0x02 + +struct sockaddr { + sa_family_t sa_family; + char sa_data[14]; +}; + +struct sockaddr_storage { + sa_family_t ss_family; + char __ss_padding[128-sizeof(long)-sizeof(sa_family_t)]; + unsigned long __ss_align; +}; + +/** + * @ingroup socket + * + * @par Description: + * This API is used to create an endpoint for communication and returns a file descriptor. + * + * @param domain [IN] Specifies a protocol family. + * @param type [IN] Specifies the socket type. [SOCK_RAW|SOCK_DGRAM|SOCK_STREAM] + * @param protocol [IN] Specifies the protocol to be used with the socket. + * + * @attention + *
        + *
      • Only domain AF_INET and AF_PACKET are supported. For AF_INET, type SOCK_RAW|SOCK_DGRAM|SOCK_STREAM is supported. + * For AF_PACKET, only type SOCK_RAW is supported.
      • + *
      • The type argument can only be used to specify the socket type, no flags is supported, such as SOCK_NONBLOCK and SOCK_CLOEXEC.
      • + *
      + * + * @retval #int On success, socket() shall return a non-negative integer, the socket file descriptor. On failure, -1 shall be returned. + * + * @par Errors + *
        + *
      • EAFNOSUPPORT: The implementation does not support the specified address family.
      • + *
      • EINVAL: Invalid type or invalid flags in type.
      • + *
      • ENFILE: The maximum number of sockets in the system are already open.
      • + *
      • ENOBUFS: Insufficient resources were available in the system to perform the operation.
      • + *
      • EPROTONOSUPPORT: The specified protocol is not supported within this domain & type.
      • + *
      • ESOCKTNOSUPPORT: The socket type is not supported within this domain.
      • + *
      + * + * @par Dependency: + *
      • socket.h
      + * + * @see None + * + */ +int socket (int, int, int); +int socketpair (int, int, int, int [2]); + +/** + * @ingroup socket + * + * @par Description: + * This API is used to shut down socket send and receive operations. + * + * @param s [IN] Specifies a file descriptor referring to the socket. + * @param how [IN] Specifies the type of shutdown. The values are as follows: \n SHUT_RD Disables further receive operations. SHUT_WR: Disables further send operations. SHUT_RDWR: Disables further send and receive operations. + * + * @attention + *
        + *
      • Only "SHUT_RDWR" is supported for the "how" parameter in this API. lwIP does not support closing one end of the full-duplex connection.
      • + *
      • This API does not support the PF_PACKET option.
      • + *
      • The listen socket does not support half shutdown.
      • + *
      + * + * @retval #0 On success. + * @retval #-1 On failure. + * + * @par Errors + *
        + *
      • EBADF: The socket argument is not a valid file descriptor.
      • + *
      • EINVAL: The how argument is invalid.
      • + *
      • ENOTCONN: lwIP does not support half close, ENOTCONN is returned.
      • + *
      • EINPROGRESS: If WRITE/CONNECTING/CLOSE is in progress, lwip may fail.
      • + *
      • EINVAL: If socket is not connected, lwIP shall fail with EINVAL.
      • + *
      • ENOMEM: There was insufficient memory available to complete the operation.
      • + *
      • EOPNOTSUPP: Socket is not TCP, lwIP shall fail.
      • + *
      + * + * @par Dependency: + *
      • socket.h
      + * + * @see None + * + */ +int shutdown (int, int); + +/** + * @ingroup socket + * + * @par Description: + * This API assigns the address specified by name to the socket referred to + * by the file descriptor 's'. namelen specifies the size, in bytes, of the address + * structure pointed to by name. + * + * @param s [IN] Specifies the file descriptor of the socket to be bound. + * @param name [IN] Points to a sockaddr structure containing the address to be bound to the socket. The length and format of the address depend on the address family of the socket. + * @param namelen [IN] Specifies the length of the sockaddr structure pointed to by the address argument. + * + * @attention + *
        + *
      • Bind must not be called multiple times.
      • + *
      + * + * @retval #0 On success. + * @retval #-1 On failure. + * + * @par Errors + *
        + *
      • EADDRINUSE: The specified address is already in use.
      • + *
      • EADDRINUSE: For AF_INET socket, the port number was specified as zero in the socket address structure, but, upon attempting to bind to an ephemeral port, it was determined that all port numbers in the ephemeral port range are currently in use.
      • + *
      • EADDRNOTAVAIL: The specified address is not available from the local machine.
      • + *
      • EAFNOSUPPORT: The specified address is not a valid address for the address family of the specified socket.
      • + *
      • EBADF: The socket argument is not a valid file descriptor.
      • + *
      • EINVAL: The socket is already bound to an address, and the protocol does not support binding to a new address.
      • + *
      • EINVAL: The namelen argument is not a valid length for the address family.
      • + *
      • EINVAL: For AF_PACKET socket, the ifindex is out of system netif index range.
      • + *
      • EISCONN: The specified socket is already connected.
      • + *
      • ENOBUFS: Insufficient resources were available to complete the call.
      • + *
      • ENODEV: For AF_PACKET socket, the netif can not be determined by the ifindex.
      • + *
      • ENETDOWN: For AF_PACKET socket, the netif determined by the ifindex was down.
      • + *
      • EOPNOTSUPP: The socket type of the specified socket does not support binding to an address.
      • + *
      + * + * @par Dependency: + *
      • socket.h
      + * + * @see connect | listen | socket + * + */ +int bind (int, const struct sockaddr *, socklen_t); + +/** + * @ingroup socket + * + * @par Description: + * This API connects the socket referred to by the file descriptor 's' to the address specified by name. + * + * @param s [IN] Specifies a socket file descriptor. + * @param name [IN] Specifies a pointer to the sockaddr structure which identifies the connection. + * @param namelen [IN] Specifies size of name. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #0 On success. + * @retval #-1 On failure. + * + * @par Errors + *
        + *
      • EACCES: The user tried to connect to a broadcast address without having the socket broadcast flag enabled.
      • + *
      • EADDRNOTAVAIL: For AF_IENT socket, the socket had not previously been bound to an address and, upon attempting to bind it to an ephemeral port, it was determined that all port numbers in the ephemeral port range are currently in use.
      • + *
      • EAFNOSUPPORT: The specified address is not a valid address for the address family of the specified socket.
      • + *
      • EALREADY: The socket is nonblocking and a previous connection attempt has not yet been completed.
      • + *
      • EBADF: The socket argument is not a valid file descriptor.
      • + *
      • ECONNREFUSED: The target address was not listening for connections or refused the connection request.
      • + *
      • ECONNRESET: Remote host reset the connection request.
      • + *
      • EINPROGRESS: O_NONBLOCK is set for the file descriptor for the socket and the connection cannot be immediately established; the connection shall be established asynchronously.
      • + *
      • EINVAL: The address_len argument is not a valid length for the address family.
      • + *
      • EISCONN: The specified socket is connection-mode and is already connected.
      • + *
      • ENETUNREACH: No route to the network is present.
      • + *
      • ENOBUFS: No buffer space is available.
      • + *
      • EOPNOTSUPP: The referenced socket is not of domain AF_INET.
      • + *
      • EOPNOTSUPP: The socket is listening and cannot be connected.
      • + *
      • ETIMEDOUT: The attempt to connect timed out before a connection was made.
      • + *
      + * + * @par Dependency: + *
      • socket.h
      + * + * @see bind | listen | socket + * + */ +int connect (int, const struct sockaddr *, socklen_t); + +/** + * @ingroup socket + * + * @par Description: + * This API marks the socket referred to by 's' as a passive socket, that is, as a socket that will be used + * to accept incoming connection requests using accept(). + * + * @param s [IN] Specifies a file descriptor that refers to a socket of type SOCK_STREAM. + * @param backlog [IN] Defines the maximum length to which the queue of pending connections for 's' may grow. If a connection request arrives when the queue is full, the client may receive an error with + * an indication of ECONNREFUSED or, if the underlying protocol supports retransmission, the request may be ignored so that a later reattempt at connection succeeds. + * + * @attention + *
        + *
      • Max value of backlog is 0xFF, and min value of backlog is 0.
      • + *
      • If backlog value is 0 or less than zero, backlog value of 1 is used.
      • + *
      • This API does not support the PF_PACKET socket.
      • + *
      • lwIP do not support auto binding in listen operation, so bind must be called before listen.
      • + *
      • Listen can only be called once, and the backlog value can not be changed by later calling.
      • + *
      + * + * @retval #0 On success. + * @retval #-1 On failure. + * + * @par Errors + *
        + *
      • EBADF: The socket argument is not a valid file descriptor.
      • + *
      • EDESTADDRREQ: The socket is not bound to a local address, and the protocol does not support listening on an unbound socket.
      • + *
      • EINVAL: The socket is in state which is not acceptable for listen.
      • + *
      • ENOBUFS: Insufficient resources are available in the system to complete the call.
      • + *
      • EOPNOTSUPP: The socket protocol does not support listen().
      • + *
      + * + * @par Dependency: + *
      • socket.h
      + * + * @see bind | connect | socket + * + */ +int listen (int, int); + +/** + * @ingroup socket + * + * @par Description: + * This API extracts the first connection request on the queue of pending connections + * for the listening socket 's', creates a new connected socket, and returns a new + * file descriptor referring to that socket. The newly created socket is not in the + * the listening state. The original socket 's' is unaffected by this call. + * + * @param s [IN] Specifies a socket that was created with socket(), has been bound to an address with bind(), and has issued a successful call to listen(). + * @param addr [OUT] Either a null pointer, or a pointer to a sockaddr structure where the address of the connecting socket shall be returned. + * @param addrlen [IN/OUT] Either a null pointer, if address is a null pointer, or a pointer to a socklen_t object which on input specifies the length of the supplied sockaddr structure, and on output specifies the length of the stored address. + * + * @attention + *
        + *
      • This API does not support the PF_PACKET option.
      • + *
      + * + * @retval #int On success, accept() shall return the non-negative file descriptor of the accepted socket. On failure, -1 shall be returned. + * + * @par Errors + *
        + *
      • EWOULDBLOCK: O_NONBLOCK is set for the socket file descriptor and no connections are present to be accepted.
      • + *
      • EWOULDBLOCK: O_NONBLOCK is not set but SO_RCVTIMEO is set, and no connections are present within acception timeout.
      • + *
      • EBADF: The socket argument is not a valid file descriptor.
      • + *
      • ECONNABORTED: A connection has been aborted.
      • + *
      • EINVAL: The socket is not accepting connections.
      • + *
      • ENFILE: The maximum number of sockets in the system are already open.
      • + *
      • ENOBUFS: No buffer space is available.
      • + *
      • ENOMEM: There was insufficient memory available to complete the operation.
      • + *
      • EOPNOTSUPP: The referenced socket is not of type SOCK_STREAM.
      • + *
      • EIO: Internal errors.
      • + *
      + * + * @par Dependency: + *
      • socket.h
      + * + * @see bind | connect | listen | socket + * + */ +int accept (int, struct sockaddr *__restrict, socklen_t *__restrict); +int accept4(int, struct sockaddr *__restrict, socklen_t *__restrict, int); + +/** + * @ingroup socket + * + * @par Description: + * This API returns the current address to which the socket 's' is bound, in the buffer pointed to by name. + * The namelen argument should be initialized to indicate the amount of space(in bytes) pointed to by + * name.The returned address is truncated if the buffer provided is too small; in this case, namelen will + * return a value greater than was supplied to the call. + * + * @param s [IN] Specifies the file descriptor referring to connected socket. + * @param name [OUT] Pointer to sockaddr structure of local peer. + * @param namelen [IN/OUT] Size of name structure. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #0 On success. + * @retval #-1 On failure. + * + * @par Errors + *
        + *
      • EBADF: The socket argument is not a valid file descriptor.
      • + *
      • EOPNOTSUPP: The operation is not supported for this socket's protocol.For PF_RAW sockets, this error is returned.
      • + *
      • EINVAL: The Name or Namelen are NULL, then EINVAL is returned.
      • + *
      + * + * @par Dependency: + *
      • socket.h
      + * + * @see getpeername + * + */ +int getsockname (int, struct sockaddr *__restrict, socklen_t *__restrict); + +/** + * @ingroup socket + * + * @par Description: + * This API returns the address of the peer connected to the socket 's', in the buffer pointed to by name. + * The namelen argument should be initialized to indicate the amount of space pointed to by name. + * On return it contains the actual size of the name returned (in bytes). The name is truncated if the + * buffer provided is too small. + * + * @param s [IN] Specifies the file descriptor referring to the connected socket. + * @param name [OUT] Pointer to sockaddr structure of remote peer + * @param namelen [IN/OUT] Size of name structure. + * + * @attention + *
        + *
      • This API does not support the PF_PACKET option.
      • + *
      + * + * @retval #0 On success. + * @retval #-1 On failure. + * + * @par Errors + *
        + *
      • EBADF: The socket argument is not a valid file descriptor.
      • + *
      • ENOTCONN: The socket is not connected or otherwise has not had the peer pre-specified.
      • + *
      • EOPNOTSUPP: The operation is not supported for the socket protocol.
      • + *
      • EINVAL: The Name or Namelen are NULL, then EINVAL is returned.
      • + *
      + * + * @par Dependency: + *
      • socket.h
      + * + * @see getsockname + * + */ +int getpeername (int, struct sockaddr *__restrict, socklen_t *__restrict); + +/** + * @ingroup socket + * + * @par Description: + * This API initiate transmission of a message from the specified socket to its peer. + * This API will send a message only when the socket is connected. + * + * @param s [IN] Specifies the socket file descriptor. + * @param dataptr [IN] Specifies a buffer containing message to send. + * @param size [IN] Specifies the length of the message to send. + * @param flags [IN] Indicates the flags of message transmission. + * + * @attention + *
        + *
      • UDP & RAW connection can send only a maximum data of length 65000. Sending more data would + * return -1 and errno set to EMSGSIZE.
      • + *
      • Only flag MSG_MORE, MSG_DONTWAIT and MSG_NOSIGNAL are supported, other flags, such as MSG_OOB/MSG_EOR is not supported.
      • + *
      + * + * @retval #ssize_t On success, send() shall return the number of bytes sent. On failure, -1 shall be returned. + * + * @par Errors + *
        + *
      • EWOULDBLOCK: The socket's file descriptor is marked O_NONBLOCK or MSG_DONWAIT flag is set and the requested operation would block.
      • + *
      • EWOULDBLOCK: The socket was not marked with O_NONBLOCK, but set with option SO_SNDTIMEO, and elapsed time is more than timeout value.
      • + *
      • EADDINUSE: For PF_INET/SOCK_DGRAM socket without local port bond, when attempting to bind to an ephemeral port, it was determined that all port numbers in the ephemeral port range are currently in use.
      • + *
      • EBADF: The socket argument is not a valid file descriptor.
      • + *
      • ECONNRESET: A connection was forcibly closed by a peer.
      • + *
      • EDESTADDRREQ: The socket is not connection-mode and does not have its peer address set.
      • + *
      • EINPROGRESS: For PF_INET/SOCK_STREAM, there was one send operation in progress, and concurrent sending was not supported.
      • + *
      • EINVAL: Invalid argument passed, e.g. dataptr is NULL, size is zero.
      • + *
      • EMSGSIZE: The socket type requires that message be sent atomically, and the size of the message to be sent made this impossible. For PF_PACKET/SOCK_RAW socket, it means the packet is larger than the MTU of out network interface. For PF_INET/(SOCK_RAW,SOCK_DGRAM) socket, it means the packet is larger than 65000 bytes.
      • + *
      • ENETDOWN: For PF_PACKET/SOCK_RAW socket, the binding network interface was down.
      • + *
      • ENOBUFS: Insufficient resources were available in the system to perform the operation.
      • + *
      • ENOMEM: Insufficient memory was available to fulfill the request.
      • + *
      • ENODEVADDR: For PF_PACKET/SOCK_RAW socket, the binding network interface does not exist.
      • + *
      • ENOTCONN: The socket is not connected.
      • + *
      • EOPNOTSUPP: Some bit in the flags argument is unsupported for the socket type.
      • + *
      • EIO: Internal errors.
      • + *
      + * + * @par Dependency: + *
      • socket.h
      + * + * @see sendto + * + */ +ssize_t send (int, const void *, size_t, int); + +/** + * @ingroup socket + * + * @par Description: + * This API can be used to receive messages from a connection-oriented sockets only + * because it doesnot permits the application to retrieve the source address of received data. + * + * @param s [IN] Specifies the socket file descriptor. + * @param mem [IN] Points to a buffer where the message should be stored. + * @param len [IN] Specifies the length in bytes of the buffer pointed to by the 'mem' argument. + * @param flags [IN] Specifies the type of message reception. Values of this argument are formed by logically OR'ing zero or more of the following values: MSG_PEEK + * Peeks at an incoming message. The data is treated as unread and the next recv() or similar function shall still return this data. + * + * @attention + *
        + *
      • LwIP updates this receive buffer list, once it gets the next expected segment. + * If there is any out of order segment which is next to the received segment, means + * it merges and puts that as one segemnt into receive buffer list.
      • + *
      • If the apps don't read the packet from the socket and the recv buffered + * packets up to MAX_MBOX_SIZE, the incoming packet may be discard by lwIP and cause + * retransmission for tcp connection.
      • + *
      • Only flag MSG_PEEK and MSG_DONTWAIT are supported, other flags, such as MSG_TRUNC/MSG_WAITALL/MSG_OOB is not supported.
      • + *
      • When RST is received after FIN, this API will return 0 to indicate FIN, then + * return -1 and set errno to ECONNRESET for RST if called again.
      • + *
      • This API is not thread-safe.
      • + *
      + * + * @retval #ssize_t On success, recv() shall return the length of the message in bytes. On failure, -1 shall be returned. + * + * @par Errors + *
        + *
      • EWOULDBLOCK: The socket's file descriptor is marked O_NONBLOCK or MSG_DONTWAIT flag is set and no data is waiting to be received.
      • + *
      • EWOULDBLOCK: The socket was not marked with O_NONBLOCK, but set with option SO_RCVTIMEO, and elapsed time is more than timeout value.
      • + *
      • EBADF: The socket argument is not a valid file descriptor.
      • + *
      • ECONNRESET: A connection was forcibly closed by a peer.
      • + *
      • EINVAL: Invalid input parameters. If mem, len is null or flags is less than zero, lwip return failure.
      • + *
      • ENOBUFS: Insufficient resources were available in the system to perform the operation.
      • + *
      • ENOMEM: Insufficient memory was available to fulfill the request.
      • + *
      • ENOTCONN: A receive is attempted on a connection-mode socket that is not connected.
      • + *
      • EOPNOTSUPP: Some bit in the flags argument is unsupported for the socket type.
      • + *
      • EIO: Internal errors.
      • + *
      + * + * @par Dependency: + *
      • socket.h
      + * + * @see recvfrom + * + */ +ssize_t recv (int, void *, size_t, int); + +/** + * @ingroup socket + * + * @par Description: + * This API can be used to send messages to a connection-oriented or connectionless socket. + * If the socket is connectionless-mode, the message shall be sent to the address specified by 'to'. + * If the socket is connection-mode, destination address in 'to' shall be ignored. + * + * @param s [IN] Specifies a socket file descriptor. + * @param dataptr [IN] Specifies a buffer containing the message to send. + * @param size [IN] Specifies the length of the message to send. + * @param flags [IN] Indicates the flags of message transmission. + * @param to [IN] Specifies a pointer to the sockaddr structure that contains the destination address. + * @param tolen [IN] Specifies the size of the 'to' structure. + * + * @attention + *
        + *
      • UDP & RAW connection can send only a maximum data of length 65000. Sending more data would + * return -1 and errno set to EMSGSIZE.
      • + *
      • Only flag MSG_MORE, MSG_DONTWAIT and MSG_NOSIGNAL are supported, other flags, such as MSG_OOB/MSG_EOR is not supported.
      • + *
      + * + * @retval #ssize_t On success, sendto() shall return the number of bytes sent. On failure, -1 shall be returned. + * + * @par Errors + *
        + *
      • EWOULDBLOCK: The socket's file descriptor is marked O_NONBLOCK or MSG_DONTWAIT flag is set and the requested operation would block.
      • + *
      • EWOULDBLOCK: The socket was not marked with O_NONBLOCK, but set with option SO_SNDTIMEO, and elapsed time is more than timeout value.
      • + *
      • EACCES: For PF_INET/(SOCK_RAW,SOCK_DGRAM) socket, the destination address is broadcast but SO_BROADCAST option was not enabled.
      • + *
      • EADDINUSE: For PF_INET/SOCK_DGRAM socket without local port bond, when attempting to bind to an ephemeral port, it was determined that all port numbers in the ephemeral port range are currently in use.
      • + *
      • EAFNOSUPPORT: Addresses in the specified address family cannot be used with this socket.
      • + *
      • EBADF: The socket argument is not a valid file descriptor.
      • + *
      • ECONNRESET: A connection was forcibly closed by a peer.
      • + *
      • EDESTADDRREQ: The socket is not connection-mode and does not have its peer address set, and no destination address was specified.
      • + *
      • EINPROGRESS: For PF_INET/SOCK_STREAM, there was one send operation in progress, and concurrent sending was not supported.
      • + *
      • EINVAL: Invalid argument passed, e.g. dataptr is NULL, size is zero.
      • + *
      • EMSGSIZE: The socket type requires that message be sent atomically, and the size of the message to be sent made this impossible. For PF_PACKET/SOCK_RAW socket, it means the packet is larger than the MTU of out network interface. For PF_INET/(SOCK_RAW,SOCK_DGRAM) socket, it means the packet is larger than 65000 bytes.
      • + *
      • ENETDOWN: For PF_PACKET/SOCK_RAW socket, the out network interface was down.
      • + *
      • ENETUNREACH: No route to the destination is present.
      • + *
      • ENOBUFS: Insufficient resources were available in the system to perform the operation.
      • + *
      • ENXIO: For PF_PACKET/SOCK_RAW socket, the given network interface does not exist.
      • + *
      • ENOMEM: Insufficient memory was available to fulfill the request.
      • + *
      • ENOTCONN: The socket is not connected.
      • + *
      • EOPNOTSUPP: Some bit in the flags argument is unsupported for the socket type.
      • + *
      • EIO: Internal error.
      • + *
      + * + * @par Dependency: + *
      • socket.h
      + * + * @see send + * + */ +ssize_t sendto (int, const void *, size_t, int, const struct sockaddr *, socklen_t); + +/** + * @ingroup socket + * + * @par Description: + * This API can be used to receive messages from a connection-oriented and connectionless sockets + * because it permits the application to retrieve the source address of received data. + * + * @param s [IN] Specifies the socket file descriptor. + * @param mem [IN] Points to the buffer where the message should be stored. + * @param len [IN] Specifies the length in bytes of the buffer pointed to by the buffer argument. + * @param flags [IN] Specifies the type of message reception. Values of this argument are formed by logically OR'ing zero or more of the following values: MSG_PEEK Peeks at an incoming message. The data is treated as unread and the next recvfrom() or similar function shall still return this data. + * @param from [OUT] A null pointer, or points to a sockaddr structure in which the sending address is to be stored. The length and format of the address depend on the address family of the socket. + * @param fromlen [OUT] Either a null pointer, if address is a null pointer, or a pointer to a socklen_t object which on input specifies the length of the supplied sockaddr structure, and on output specifies the length of the stored address. + * + * @attention + *
        + *
      • If the apps don't read the packet from the socket and the recv buffered + * packets up to MAX_MBOX_SIZE, the incoming packet may be discard by lwIP.
      • + *
      • For TCP connection, when RST is received after FIN, this API will return + * 0 to indicate FIN, then return -1 and set errno to ECONNRESET for RST if + * called again.
      • + *
      • Only flag MSG_PEEK and MSG_DONTWAIT are supported, other flags, such as MSG_TRUNC/MSG_WAITALL/MSG_OOB is not supported.
      • + *
      • This API is not thread-safe.
      • + *
      + * + * @retval #ssize_t On success, recvfrom() shall return the length of the message in bytes. On failure, the function shall return -1. + * + * @par Errors + *
        + *
      • EWOULDBLOCK: The socket's file descriptor is marked O_NONBLOCK or MSG_DONTWAIT flag is set and no data is waiting to be received.
      • + *
      • EWOULDBLOCK: The socket was not marked with O_NONBLOCK, but set with option SO_RCVTIMEO, and elapsed time is more than timeout value.
      • + *
      • EBADF: The socket argument is not a valid file descriptor.
      • + *
      • ECONNRESET: A connection was forcibly closed by a peer.
      • + *
      • EINVAL: Invalid input parameters. If mem, len is null or flags is less than zero, lwip return failure.
      • + *
      • ENOBUFS: Insufficient resources were available in the system to perform the operation.
      • + *
      • ENOMEM: Insufficient memory was available to fulfill the request.
      • + *
      • ENOTCONN: A receive is attempted on a connection-mode socket that is not connected.
      • + *
      • EOPNOTSUPP: Some bit in the flags argument is unsupported for the socket type.
      • + *
      • EIO: Internal errors.
      • + *
      + * + * @par Dependency: + *
      • socket.h
      + * + * @see recv + * + */ +ssize_t recvfrom (int, void *__restrict, size_t, int, struct sockaddr *__restrict, socklen_t *__restrict); + +/** + * @ingroup socket + * + * @par Description: + * This API initiates transmission of a message from the specified socket to its peer. + * It sends a message only when the socket is connected. The sendmsg() call also allows + * sending ancillary data (also known as control information). + * + * @param s [IN] Specifies the socket file descriptor. + * @param message [IN] Specifies a buffer containing message to send. + * @param flags [IN] Indicates the flags of message transmission. + * + * @attention + *
        + *
      • This API is only supported since lwip 2.0.
      • + *
      • UDP and RAW connection can send only data of maximum length 65332. Sending more than data + * will return -1 and errno set to EMSGSIZE
      • + *
      • Only flag MSG_MORE and MSG_DONTWAIT is supported. Other flags, such as + * MSG_OOB/MSG_NOSIGNAL/MSG_EOR are not supported.
      • + *
      + * + * @retval #ssize_t On success, sendmsg() shall return the number of bytes sent. On failure, -1 shall be returned. + * + * @par Errors + *
        + *
      • EADDINUSE: For PF_INET/SOCK_DGRAM socket without local port bond, when attempting to + * bind to an ephemeral port, it was determined that all port numbers in the ephemeral port range are currently in use.
      • + *
      • EBADF: The socket argument is not a valid file descriptor.
      • + *
      • ECONNRESET: A connection was forcibly closed by a peer.
      • + *
      • EDESTADDRREQ: The socket is not connection-mode and does not have its peer address set.
      • + *
      • EINPROGRESS: For PF_INET/SOCK_STREAM, there was one send operation in progress, + * and concurrent sending was not supported.
      • + *
      • EINVAL: Invalid argument passed, e.g. dataptr is NULL, size is zero.
      • + *
      • EMSGSIZE: The socket type requires that message be sent atomically, and the size of the message + * to be sent made this impossible. For PF_PACKET/SOCK_RAW socket, it means the packet is larger than the MTU of out network interface. For PF_INET/(SOCK_RAW,SOCK_DGRAM) socket, it means the packet is larger than 65000 bytes.
      • + *
      • ENETDOWN: For PF_PACKET/SOCK_RAW socket, the binding network interface was down.
      • + *
      • ENOBUFS: The socket type requires that message be sent atomically, and the size of the message to be sent made this impossible. For PF_PACKET/SOCK_RAW socket, it means the packet is larger than the MTU of out network interface. For PF_INET/(SOCK_RAW,SOCK_DGRAM) socket, it means the packet is larger than 65000 bytes.
      • + *
      • ENETDOWN: For PF_PACKET/SOCK_RAW socket, the binding network interface was down.
      • + *
      • ENOBUFS: Insufficient resources were available in the system to perform the operation.
      • + *
      • ENODEVADDR: For PF_PACKET/SOCK_RAW socket, the binding network interface does not exist.
      • + *
      • ENOMEM: Insufficient memory was available to fulfill the request.
      • + *
      • ENOTCONN: The socket is not connected.
      • + *
      • EOPNOTSUPP: Some bit in the flags argument is unsupported for the socket type.
      • + *
      • EPIPE: The socket is shut down for writing, or the socket is connection-mode + * and is no longer connected. In the latter case, and if the socket is of type SOCK_STREAM.
      • + *
      • EWOULDBLOCK: The socket's file descriptor is marked O_NONBLOCK or MSG_DONWAIT flag is set and the requested operation would block.
      • + *
      • EWOULDBLOCK: The socket was not marked with O_NONBLOCK, but set with option SO_SNDTIMEO, and elapsed time is more than timeout value.
      • + *
      • EIO: Internal errors.
      • + *
      + * + * @par Dependency: + *
      • socket.h
      + * + * @see sendto + * + */ +ssize_t sendmsg (int, const struct msghdr *, int); +ssize_t recvmsg (int, struct msghdr *, int); + +/** + * @ingroup socket + * + * @par Description: + * This API retrieves the value for the option specified by the optname argument for the socket + * specified by 's'. If the size of the optval is greater than optlen, the value stored in the object + * pointed to by the optval argument shall be silently truncated. + * + * @param s [IN] Specifies a socket file descriptor. + * @param level [IN] Specifies the protocol level at which the option resides. + * @param optname [IN] Specifies a single option to be retrieved. + * @param optval [OUT] Indicates an address to store option value. + * @param optlen [IN/OUT] Specifies the size of the option value. + * + * @attention + *
        + *
      • Supported protocol levels are: SOL_SOCKET, IPPROTO_IP, IPPROTO_TCP,IPPROTO_UDPLITE.
      • + *
      • Under SOL_SOCKET the options supported are: + * SO_ACCEPTCONN + * SO_BROADCAST + * SO_ERROR + * SO_KEEPALIVE + * SO_SNDTIMEO + * SO_RCVTIMEO + * SO_RCVBUF + * SO_SNDBUF + * SO_REUSEADDR + * SO_TYPE + * SO_NO_CHECK + * SO_DONTROUTE + * SO_BINDTODEVICE + * For SO_SNDTIMEO, SO_RCVTIMEO, SO_RCVBUF, the macros LWIP_SO_SNDTIMEO, LWIP_SO_RCVTIMEO and LWIP_SO_RCVBUF should have been defined at compile time. + * For SO_REUSEADDR, the macro SO_REUSE should have been defined at compile time. + * For SO_BINDTODEVICE, the macro LWIP_SO_BINDTODEVICE should have been defined at compile time. + * For SO_SNDBUF, the macro LWIP_SO_SNDBUF should have been defined at compile time. + *
      • + *
      • Under IPPROTO_IP the options supported are: + * IP_MULTICAST_TTL + * IP_MULTICAST_LOOP + * IP_MULTICAST_IF + * IP_HDRINCL + * IP_TTL + * IP_TOS + * Only UDP socket supports IP_MULTICAST_TTL, IP_MULTICAST_LOOP, IP_MULTICAST_IF. + *
      • + *
      • Under IPPROTO_TCP the options supported are: + * TCP_NODELAY + * TCP_KEEPIDLE + * TCP_KEEPINTVL + * TCP_KEEPCNT + * TCP_INFO + * TCP_QUEUE_SEQ. + * For TCP_KEEPIDLE, TCP_KEEPINTVL, TCP_KEEPCNT, the macro LWIP_TCP_KEEPALIVE should have been defined at compile time.\n + * For TCP_INFO, Only tcpi_state, tcpi_retransmits, tcpi_probes, tcpi_backoff, tcpi_options, tcpi_rto, tcpi_snd_mss, tcpi_rcv_mss, tcpi_unacked, + * tcpi_rtt, tcpi_rttvar, tcpi_snd_ssthresh, tcpi_snd_cwnd, tcpi_reordering in + * struct tcp_info are supported, other fields are keep 0. + *
      • + *
      • Under IPPROTO_UDPLITE the options supported are: + * UDPLITE_SEND_CSCOV + * UDPLITE_RECV_CSCOV + *
      • + *
      + * + * @retval #0 On success. + * @retval #-1 On failure. + * + * @par Errors + *
        + *
      • EBADF: The socket argument is not a valid file descriptor.
      • + *
      • EINVAL: The specified option is invalid at the specified socket level.
      • + *
      • EINVAL: If opt or optlen are NULL,option or option length is incorrect.
      • + *
      • ENOPROTOOPT: The option is not supported by the protocol.
      • + *
      • ENOMEM: There was insufficient memory available to complete the operation.
      • + *
      + * + * @par Dependency: + *
      • socket.h
      + * + * @see setsockopt + * + */ +int getsockopt (int, int, int, void *__restrict, socklen_t *__restrict); + +/** + * @ingroup socket + * + * @par Description: + * This API sets the option specified by the optname, at the protocol level specified by the level, + * to the value pointed to by the optval for the socket associated with the file descriptor specified by 's'. + * + * @param s [IN] Specifies a socket file descriptor. + * @param level [IN] Specifies the protocol level at which the option resides. + * @param optname [IN] Specifies a single option to set. + * @param optval [IN] Indicates the address to store the option value. + * @param optlen [IN] Specifies the size of option value. + * + * @attention + *
        + *
      • Supported protocol levels are: SOL_SOCKET, IPPROTO_IP, IPPROTO_TCP,IPPROTO_UDPLITE.
      • + *
      • Under SOL_SOCKET the options supported are: + * SO_BROADCAST + * SO_KEEPALIVE + * SO_SNDTIMEO + * SO_RCVTIMEO + * SO_RCVBUF + * SO_SNDBUF + * SO_REUSEADDR + * SO_REUSEPORT + * SO_NO_CHECK. + * SO_ATTACH_FILTER + * SO_DETACH_FILTER + * SO_DONTROUTE + * SO_BINDTODEVICE + * For SO_SNDTIMEO, SO_RCVTIMEO, SO_RCVBUF, the macros LWIP_SO_SNDTIMEO, LWIP_SO_RCVTIMEO and LWIP_SO_RCVBUF should have been defined at compile time. + * For SO_REUSEADDR, the macro SO_REUSE should have been defined at compile time. + * For SO_BINDTODEVICE, the macro LWIP_SO_BINDTODEVICE should have been defined at compile time. + * For SO_ATTACH_FILTER, SO_DETACH_FILTER, the macro LWIP_SOCKET_FILTER should have been defined at compile time. + * Only PF_PACKET RAW socket supports SO_ATTACH_FILTER and SO_DETACH_FILTER now. + * For SO_SNDBUF, the macro LWIP_SO_SNDBUF should have been defined at compile time. + * Only TCP socket in listen or closed stated supports SO_SNDBUF. + *
      • + *
      • Under IPPROTO_IP the options supported are: + * IP_ADD_MEMBERSHIP + * IP_DROP_MEMBERSHIP + * IP_MULTICAST_TTL + * IP_MULTICAST_LOOP + * IP_MULTICAST_IF + * IP_HDRINCL + * IP_TTL + * IP_TOS + * Only UDP socket supports IP_ADD_MEMBERSHIP, IP_DROP_MEMBERSHIP, IP_MULTICAST_TTL, IP_MULTICAST_LOOP, IP_MULTICAST_IF. + *
      • + *
      • Under IPPROTO_TCP the options supported are: + * TCP_NODELAY + * TCP_KEEPIDLE + * TCP_KEEPINTVL + * TCP_KEEPCNT. + * For TCP_KEEPIDLE, TCP_KEEPINTVL, TCP_KEEPCNT, the macro LWIP_TCP_KEEPALIVE should have been defined at compile time. + *
      • + *
      • Under IPPROTO_UDPLITE the options supported are: + * UDPLITE_SEND_CSCOV + * UDPLITE_RECV_CSCOV + *
      • + *
      + * + * @retval #0 On success. + * @retval #-1 On failure. + * + * @par Errors + *
        + *
      • EBADF: The socket argument is not a valid file descriptor.
      • + *
      • EDOM: The send and receive timeout values are too big to fit into the timeout fields in the socket structure.
      • + *
      • ENOENT: the option is SO_DETACH_FILTER while no previous socket filter was attached.
      • + *
      • ENOMEM: There was insufficient memory available for the operation to complete.
      • + *
      • ENOPROTOOPT: The option is not supported by the protocol.
      • + *
      • EINVAL: If optval is NULL pointer, lwIP shall fail.
      • + *
      • EINVAL: If for PF_PACKET socket type, level is neither SOL_PACKET nor SOL_SOCKET, lwIP shall fail.
      • + *
      • EINVAL: If optlen does not match optval for corresponding optname, lwIP shall fail.
      • + *
      • EINVAL: If the send and receive timeout values are smaller than 10000 microseconds, lwIP shall fail.
      • + *
      + * + * @par Dependency: + *
      • socket.h
      + * + * @see getsockopt + * + */ +int setsockopt (int, int, int, const void *, socklen_t); + +int sockatmark (int); + +#if _REDIR_TIME64 +#ifdef _GNU_SOURCE +__REDIR(recvmmsg, __recvmmsg_time64); +#endif +#endif + +#ifdef __cplusplus +} +#endif +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/soundcard.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/soundcard.h new file mode 100644 index 0000000000000000000000000000000000000000..5ca776461e084b24860ba1d547f4c8053b4c228d --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/soundcard.h @@ -0,0 +1 @@ +#include diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/stat.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/stat.h new file mode 100644 index 0000000000000000000000000000000000000000..cb1424b474ca978f119505bace33b3891209d481 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/stat.h @@ -0,0 +1,349 @@ +/** + * @defgroup stat Stat + * @ingroup libc + */ + +#ifndef _SYS_STAT_H +#define _SYS_STAT_H +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#define __NEED_dev_t +#define __NEED_ino_t +#define __NEED_mode_t +#define __NEED_nlink_t +#define __NEED_uid_t +#define __NEED_gid_t +#define __NEED_off_t +#define __NEED_time_t +#define __NEED_blksize_t +#define __NEED_blkcnt_t +#define __NEED_struct_timespec +#ifdef __LITEOS__ +#define __NEED_int64_t +#endif + +#include + +#include + +#define st_atime st_atim.tv_sec +#define st_mtime st_mtim.tv_sec +#define st_ctime st_ctim.tv_sec + +#define S_IFMT 0170000 + +#define S_IFDIR 0040000 +#define S_IFCHR 0020000 +#define S_IFBLK 0060000 +#define S_IFREG 0100000 +#define S_IFIFO 0010000 +#define S_IFLNK 0120000 +#define S_IFSOCK 0140000 + +#define S_TYPEISMQ(buf) 0 +#define S_TYPEISSEM(buf) 0 +#define S_TYPEISSHM(buf) 0 +#define S_TYPEISTMO(buf) 0 + +#define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR) +#define S_ISCHR(mode) (((mode) & S_IFMT) == S_IFCHR) +#define S_ISBLK(mode) (((mode) & S_IFMT) == S_IFBLK) +#define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG) +#define S_ISFIFO(mode) (((mode) & S_IFMT) == S_IFIFO) +#define S_ISLNK(mode) (((mode) & S_IFMT) == S_IFLNK) +#define S_ISSOCK(mode) (((mode) & S_IFMT) == S_IFSOCK) + +#ifndef S_IRUSR +#define S_ISUID 04000 +#define S_ISGID 02000 +#define S_ISVTX 01000 +#define S_IRUSR 0400 +#define S_IWUSR 0200 +#define S_IXUSR 0100 +#define S_IRWXU 0700 +#define S_IRGRP 0040 +#define S_IWGRP 0020 +#define S_IXGRP 0010 +#define S_IRWXG 0070 +#define S_IROTH 0004 +#define S_IWOTH 0002 +#define S_IXOTH 0001 +#define S_IRWXO 0007 +#endif + +#ifdef __LITEOS__ +#define DEFFILEMODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH) +#endif + +#define UTIME_NOW 0x3fffffff +#define UTIME_OMIT 0x3ffffffe + +/** + * @ingroup stat + * + * @par Description: + * The stat() function shall obtain information about the named file and write it to the area pointed to by the buf + * argument. + * @param path [IN] Points to a pathname naming a file. + * @param buf [IN] A pointer to a stat structure, defined in the header, + * which stores information related to files. + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #0 Upon successful completion. + * @retval #-1 Failed and set errno to indicate the error. + * + * @par Errors + *
        + *
      • EINVAL: Invalid argument.
      • + *
      • ENOENT: A directory component in pathname does not exist or path is an empty string.
      • + *
      • ENAMETOOLONG: The length of a component of a pathname is longer than {NAME_MAX}.
      • + *
      • ENOMEM: Out of memory.
      • + *
      • ENOSYS: No support.
      • + *
      • EBADF: The fd argument is not a valid file descriptor or or the underlying file system does not support + * this operation.
      • + *
      • EAGAIN: The file list is NULL.
      • + *
      • EACCES: Permission bits of the file mode do not permit the requested access, + * or search permission is denied on a component of the path prefix.
      • + *
      • EEXIST: The file/directory object is already exist.
      • + *
      • EIO: An I/O error occurred while reading from or writing to a file system.
      • + *
      • EROFS: The physical drive is write protected.
      • + *
      • ENOSPC: No space left on device.
      • + *
      • ENFILE: The maximum allowable number of files is currently open in the system.
      • + *
      • ENOTEMPTY: directory not empty.
      • + *
      • EISDIR: The named file is a directory.
      • + *
      • ENOTDIR: A component of the path prefix names an existing file that is neither a directory nor a symbolic + * link to a directory; or the path argument resolves to a non-directory file.
      • + *
      • EPERM: Operation not permitted or access denied due to prohibited access or directory full.
      • + *
      • EBUSY: The operation is rejected according to the file sharing policy.
      • + *
      • ENOSYS: Not support.
      • + *
      • EPROTO: Protocol error in nfs.
      • + *
      • ENODEV: No such device.
      • + *
      • EFAULT: Bad address.
      • + *
      + * + * @par Dependency: + *
      • stat.h
      + * @see None + */ +int stat(const char *__restrict, struct stat *__restrict); + +/** + * @ingroup stat + * + * @par Description: + * The fstat() function shall obtain information about an open file associated with the file descriptor fildes, and shall + * write it to the area pointed to by buf. + * @param fildes [IN] File descriptor fildes. + * @param buf [IN] A pointer to a stat structure, defined in the header, + * which stores information related to files. + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #0 Upon successful completion. + * @retval #-1 Failed and set errno to indicate the error. + * + * @par Errors + *
        + *
      • EBADF: The fd argument is not a valid file descriptor.
      • + *
      • EAGAIN: The file list is NULL.
      • + *
      • EINVAL: Invalid argument.
      • + *
      • ENOENT: a directory component in pathname does not exist or path is an empty string.
      • + *
      • ENAMETOOLONG: The length of a component of a pathname is longer than {NAME_MAX}.
      • + *
      • ENOMEM: Out of memory.
      • + *
      • ENOSYS: no support.
      • + *
      • EBADF: The fd argument is not a valid file descriptor or or the underlying file system does not support + * this operation.
      • + *
      • EAGAIN: The file list is NULL.
      • + *
      • EACCES: Permission bits of the file mode do not permit the requested access, + * or search permission is denied on a component of the path prefix.
      • + *
      • EEXIST: The file/directory object is already exist.
      • + *
      • EIO: An I/O error occurred while reading from or writing to a file system.
      • + *
      • EROFS: The physical drive is write protected.
      • + *
      • ENOSPC: No space left on device.
      • + *
      • ENFILE: The maximum allowable number of files is currently open in the system.
      • + *
      • ENOTEMPTY: directory not empty.
      • + *
      • EISDIR: The named file is a directory.
      • + *
      • ENOTDIR: A component of the path prefix names an existing file that is neither a directory nor a symbolic + * link to a directory; or the path argument resolves to a non-directory file.
      • + *
      • EPERM: operation not permitted or access denied due to prohibited access or directory full.
      • + *
      • EBUSY: The operation is rejected according to the file sharing policy.
      • + *
      • ENOSYS: not support.
      • + *
      • EPROTO: Protocol error in nfs.
      • + *
      • ENODEV: No such device.
      • + *
      • EFAULT: Bad address.
      • + *
      + * + * @par Dependency: + *
      • stat.h
      + * @see None + */ +int fstat(int, struct stat *); + +/** + * @ingroup stat + * + * @par Description: + * The lstat() function shall be equivalent to stat(), function shall obtain information about the named file and write + * it to the area pointed to by the buf. + * argument. + * @param path [IN] Points to a pathname naming a file. + * @param buffer [IN] A pointer to a stat structure, defined in the header, + * which stores information related to files. + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #0 Upon successful completion. + * @retval #-1 Failed and set errno to indicate the error. + * + * @par Errors + *
        + *
      • EINVAL: Invalid argument.
      • + *
      • ENOENT: A directory component in pathname does not exist or path is an empty string.
      • + *
      • ENAMETOOLONG: The length of a component of a pathname is longer than {NAME_MAX}.
      • + *
      • ENOMEM: Out of memory.
      • + *
      • ENOSYS: No support.
      • + *
      • EBADF: The fd argument is not a valid file descriptor or or the underlying file system does not support + * this operation.
      • + *
      • EAGAIN: The file list is NULL.
      • + *
      • EACCES: Permission bits of the file mode do not permit the requested access, + * or search permission is denied on a component of the path prefix.
      • + *
      • EEXIST: The file/directory object is already exist.
      • + *
      • EIO: An I/O error occurred while reading from or writing to a file system.
      • + *
      • EROFS: The physical drive is write protected.
      • + *
      • ENOSPC: No space left on device.
      • + *
      • ENFILE: The maximum allowable number of files is currently open in the system.
      • + *
      • ENOTEMPTY: directory not empty.
      • + *
      • EISDIR: The named file is a directory.
      • + *
      • ENOTDIR: A component of the path prefix names an existing file that is neither a directory nor a symbolic + * link to a directory; or the path argument resolves to a non-directory file.
      • + *
      • EPERM: Operation not permitted or access denied due to prohibited access or directory full.
      • + *
      • EBUSY: The operation is rejected according to the file sharing policy.
      • + *
      • ENOSYS: Not support.
      • + *
      • EPROTO: Protocol error in nfs.
      • + *
      • ENODEV: No such device.
      • + *
      • EFAULT: Bad address.
      • + *
      + * + * @par Dependency: + *
      • stat.h
      + * @see None + */ +int lstat(const char *__restrict, struct stat *__restrict); +int fstatat(int, const char *__restrict, struct stat *__restrict, int); +int chmod(const char *, mode_t); +int fchmod(int, mode_t); +int fchmodat(int, const char *, mode_t, int); +mode_t umask(mode_t); + +/** + * @ingroup stat + * + * @par Description: + * The mkdir() function shall create a new directory with name path. The file permission bits of the new directory shall + * be initialized from mode. These file permission bits of the mode argument shall be modified by the process' file + * creation mask. + * @param pathname [IN] Directory with name path. + * @param mode [IN] File permission bits. + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #0 Upon successful completion. + * @retval #-1 Failed and set errno to indicate the error. + * + * @par Errors + *
        + *
      • EINVAL: The path is a null pointer or an empty string.
      • + *
      • EACCES: Permission bits of the file mode do not permit the requested access, + * or search permission is denied on a component of the path prefix.
      • + *
      • ENAMETOOLONG: The length of a component of a pathname is longer than {NAME_MAX}.
      • + *
      • ENOENT: A directory component in pathname does not exist.
      • + *
      • EEXIST: The file/directory object is already exist.
      • + *
      • EIO: An I/O error occurred while reading from or writing to a file system.
      • + *
      • EROFS: The physical drive is write protected.
      • + *
      • ENOSPC: No space left on device.
      • + *
      • ENFILE: The maximum allowable number of files is currently open in the system.
      • + *
      • ENOTDIR: A component of the path prefix names an existing file that is neither a directory nor a symbolic + * link to a directory; or the path argument resolves to a non-directory file.
      • + *
      • EPERM: Operation not permitted or access denied due to prohibited access or directory full.
      • + *
      • EBUSY: The operation is rejected according to the file sharing policy.
      • + *
      • ENOSYS: Not support.
      • + *
      • EPROTO: Protocol error in nfs.
      • + *
      • EFAULT: Bad address.
      • + *
      + * + * @par Dependency: + *
      • stat.h
      + * @see None + */ +int mkdir(const char *, mode_t); +int mkfifo(const char *, mode_t); +int mkdirat(int, const char *, mode_t); +int mkfifoat(int, const char *, mode_t); + +#if defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) || defined(_BSD_SOURCE) +int mknod(const char *, mode_t, dev_t); +int mknodat(int, const char *, mode_t, dev_t); +#endif + +int futimens(int, const struct timespec [2]); +int utimensat(int, const char *, const struct timespec [2], int); + +#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE) +int lchmod(const char *, mode_t); +#define S_IREAD S_IRUSR +#define S_IWRITE S_IWUSR +#define S_IEXEC S_IXUSR +#endif + +#if defined(_LARGEFILE64_SOURCE) || defined(_GNU_SOURCE) +#ifdef __LITEOS__ +#define stat64 stat +int fstat64(int, struct stat64 *); +int lstat64(const char *, struct stat64 *); +int fstatat64(int, const char *, struct stat64 *, int); +#define blkcnt64_t blkcnt_t +#define fsblkcnt64_t fsblkcnt_t +#define fsfilcnt64_t fsfilcnt_t +#define ino64_t ino_t +#define off64_t int64_t +#else +#define stat64 stat +#define fstat64 fstat +#define lstat64 lstat +#define fstatat64 fstatat +#define blkcnt64_t blkcnt_t +#define fsblkcnt64_t fsblkcnt_t +#define fsfilcnt64_t fsfilcnt_t +#define ino64_t ino_t +#define off64_t off_t +#endif +#endif + +#if _REDIR_TIME64 +__REDIR(stat, __stat_time64); +__REDIR(fstat, __fstat_time64); +__REDIR(lstat, __lstat_time64); +__REDIR(fstatat, __fstatat_time64); +__REDIR(futimens, __futimens_time64); +__REDIR(utimensat, __utimensat_time64); +#endif + +#ifdef __cplusplus +} +#endif +#endif + + diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/statfs.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/statfs.h new file mode 100644 index 0000000000000000000000000000000000000000..e689984271b43f246e1a4e7c897ddac320f9149e --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/statfs.h @@ -0,0 +1,74 @@ +/** + * @defgroup statfs Statfs + * @ingroup libc + */ + +#ifndef _SYS_STATFS_H +#define _SYS_STATFS_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#include + +#ifdef __LITEOS__ +#define ROMFS_MAGIC 0x7275 +#define MSDOS_SUPER_MAGIC 0x4d44 +#define RAMFS_MAGIC 0x858458f6 +#define YAFFS_MAGIC 0x5941ff53 +#define NFS_SUPER_MAGIC 0x6969 +#define PROCFS_MAGIC 0x434f5250 +#define JFFS2_SUPER_MAGIC 0x72b6 +#endif + +typedef struct __fsid_t { + int __val[2]; +} fsid_t; + +#include + +/** + * @ingroup vfs + * + * @par Description: + * The statfs() function shall get the information of the file system pointed to by the path and return the + * information in buf. + * + * @attention + *
        + *
      • Now only fat filesystem support this function.
      • + *
      + * + * @retval #0 On success. + * @retval #-1 On failure with errno set. + * + * @par Errors + *
        + *
      • EFAULT: The path is a null pointer or the buf is a null pointer.
      • + *
      • ENAMETOOLONG: The length of a component of a pathname is longer than {NAME_MAX}.
      • + *
      • ENOENT: A component of the path does not exist.
      • + *
      • ENODEV: The mount is not healthy.
      • + *
      + * + * @par Dependency: + *
      • statfs.h
      + * @see None + */ +int statfs (const char *, struct statfs *); +int fstatfs (int, struct statfs *); + +#if defined(_LARGEFILE64_SOURCE) || defined(_GNU_SOURCE) +#define statfs64 statfs +#define fstatfs64 fstatfs +#define fsblkcnt64_t fsblkcnt_t +#define fsfilcnt64_t fsfilcnt_t +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/statvfs.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/statvfs.h new file mode 100644 index 0000000000000000000000000000000000000000..793490b6dc8c171f00809bbf0412bb48e7e220fa --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/statvfs.h @@ -0,0 +1,56 @@ +#ifndef _SYS_STATVFS_H +#define _SYS_STATVFS_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#define __NEED_fsblkcnt_t +#define __NEED_fsfilcnt_t +#include + +struct statvfs { + unsigned long f_bsize, f_frsize; + fsblkcnt_t f_blocks, f_bfree, f_bavail; + fsfilcnt_t f_files, f_ffree, f_favail; +#if __BYTE_ORDER == __LITTLE_ENDIAN + unsigned long f_fsid; + unsigned :8*(2*sizeof(int)-sizeof(long)); +#else + unsigned :8*(2*sizeof(int)-sizeof(long)); + unsigned long f_fsid; +#endif + unsigned long f_flag, f_namemax; + int __reserved[6]; +}; + +int statvfs (const char *__restrict, struct statvfs *__restrict); +int fstatvfs (int, struct statvfs *); + +#define ST_RDONLY 1 +#define ST_NOSUID 2 +#define ST_NODEV 4 +#define ST_NOEXEC 8 +#define ST_SYNCHRONOUS 16 +#define ST_MANDLOCK 64 +#define ST_WRITE 128 +#define ST_APPEND 256 +#define ST_IMMUTABLE 512 +#define ST_NOATIME 1024 +#define ST_NODIRATIME 2048 +#define ST_RELATIME 4096 + +#if defined(_LARGEFILE64_SOURCE) || defined(_GNU_SOURCE) +#define statvfs64 statvfs +#define fstatvfs64 fstatvfs +#define fsblkcnt64_t fsblkcnt_t +#define fsfilcnt64_t fsfilcnt_t +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/stropts.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/stropts.h new file mode 100644 index 0000000000000000000000000000000000000000..5b5bc02f40489403c3e1a57790728751b1a6cfe0 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/stropts.h @@ -0,0 +1 @@ +#include diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/swap.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/swap.h new file mode 100644 index 0000000000000000000000000000000000000000..11c0f9296179d328e6e74fabc7f4cf1b47ea4355 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/swap.h @@ -0,0 +1,21 @@ +#ifndef _SYS_SWAP_H +#define _SYS_SWAP_H + +#ifdef __cplusplus +extern "C" { +#endif + + +#define SWAP_FLAG_PREFER 0x8000 +#define SWAP_FLAG_PRIO_MASK 0x7fff +#define SWAP_FLAG_PRIO_SHIFT 0 +#define SWAP_FLAG_DISCARD 0x10000 + +int swapon (const char *, int); +int swapoff (const char *); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/syscall.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/syscall.h new file mode 100644 index 0000000000000000000000000000000000000000..24987ddf25bc90995dceeb345d18dc8b4b8f0bbc --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/syscall.h @@ -0,0 +1,6 @@ +#ifndef _SYS_SYSCALL_H +#define _SYS_SYSCALL_H + +#include + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/sysinfo.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/sysinfo.h new file mode 100644 index 0000000000000000000000000000000000000000..6a3931e52010de051f66e0dd8249590baf117eb7 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/sysinfo.h @@ -0,0 +1,36 @@ +#ifndef _SYS_SYSINFO_H +#define _SYS_SYSINFO_H + +#ifdef __cplusplus +extern "C" { +#endif + +#define SI_LOAD_SHIFT 16 + +struct sysinfo { + unsigned long uptime; + unsigned long loads[3]; + unsigned long totalram; + unsigned long freeram; + unsigned long sharedram; + unsigned long bufferram; + unsigned long totalswap; + unsigned long freeswap; + unsigned short procs, pad; + unsigned long totalhigh; + unsigned long freehigh; + unsigned mem_unit; + char __reserved[256]; +}; + +int sysinfo (struct sysinfo *); +int get_nprocs_conf (void); +int get_nprocs (void); +long get_phys_pages (void); +long get_avphys_pages (void); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/syslog.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/syslog.h new file mode 100644 index 0000000000000000000000000000000000000000..7761eceebbebcd9df273a2208dc29f430dc7da38 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/syslog.h @@ -0,0 +1 @@ +#include diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/sysmacros.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/sysmacros.h new file mode 100644 index 0000000000000000000000000000000000000000..07a3ef183cb63eaa3b4bd62671a8a0e010ca89da --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/sysmacros.h @@ -0,0 +1,15 @@ +#ifndef _SYS_SYSMACROS_H +#define _SYS_SYSMACROS_H + +#define major(x) \ + ((unsigned)( (((x)>>31>>1) & 0xfffff000) | (((x)>>8) & 0x00000fff) )) +#define minor(x) \ + ((unsigned)( (((x)>>12) & 0xffffff00) | ((x) & 0x000000ff) )) + +#define makedev(x,y) ( \ + (((x)&0xfffff000ULL) << 32) | \ + (((x)&0x00000fffULL) << 8) | \ + (((y)&0xffffff00ULL) << 12) | \ + (((y)&0x000000ffULL)) ) + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/termios.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/termios.h new file mode 100644 index 0000000000000000000000000000000000000000..f5f751f04336055dc30793b9db19968cc4fbe936 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/termios.h @@ -0,0 +1,2 @@ +#warning redirecting incorrect #include to +#include diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/time.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/time.h new file mode 100644 index 0000000000000000000000000000000000000000..dccebfdafb88e57dc0640a06084d14256d56bbd4 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/time.h @@ -0,0 +1,134 @@ +/** + * @defgroup time Time + * @ingroup libc + */ + +#ifndef _SYS_TIME_H +#define _SYS_TIME_H +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#include + +#define ITIMER_REAL 0 +#define ITIMER_VIRTUAL 1 +#define ITIMER_PROF 2 + +struct itimerval { + struct timeval it_interval; + struct timeval it_value; +}; + +int getitimer (int, struct itimerval *); +int setitimer (int, const struct itimerval *__restrict, struct itimerval *__restrict); +int utimes (const char *, const struct timeval [2]); + +#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE) +struct timezone { + int tz_minuteswest; + int tz_dsttime; +}; + +/* gettimeofday() defination in posix and statement is not same with musl */ +int gettimeofday(struct timeval* tv, struct timezone* tz); + +int futimes(int, const struct timeval [2]); +int futimesat(int, const char *, const struct timeval [2]); +int lutimes(const char *, const struct timeval [2]); + +/** + * @ingroup time + * @par Description: + * This function sets the time as well as a timezone. + * + * @attention + *
        + *
      • The function is not supported to set timezone,So the second parameter is unused
      • + *
      + * + * @retval #0 The function is executed successfully. + * @retval #-1 The function failed to execute, and corresponding error code is set. + * + * @par Errors + *
        + *
      • EINVAL: An invalid Input.
      • + *
      + * + * @par Dependency: + *
      • time.h
      + * + * @see clock_gettime | time | ctime + * + */ +int settimeofday(const struct timeval *, const struct timezone *); + +/** + * @ingroup time + * @par Description: + * This function gradually adjusts the system clock (as returned by gettimeofday). + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #0 The function is executed successfully. + * @retval #-1 The function failed to execute, and corresponding error code is set. + * + * @par Errors + *
        + *
      • EINVAL: An invalid input.
      • + *
      + * + * @par Dependency: + *
      • time.h
      + * + * @see gettimeofday | time + * + */ +int adjtime (const struct timeval *, struct timeval *); +#define timerisset(t) ((t)->tv_sec || (t)->tv_usec) +#define timerclear(t) ((t)->tv_sec = (t)->tv_usec = 0) +#define timercmp(s,t,op) ((s)->tv_sec == (t)->tv_sec ? \ + (s)->tv_usec op (t)->tv_usec : (s)->tv_sec op (t)->tv_sec) +#define timeradd(s,t,a) (void) ( (a)->tv_sec = (s)->tv_sec + (t)->tv_sec, \ + ((a)->tv_usec = (s)->tv_usec + (t)->tv_usec) >= 1000000 && \ + ((a)->tv_usec -= 1000000, (a)->tv_sec++) ) +#define timersub(s,t,a) (void) ( (a)->tv_sec = (s)->tv_sec - (t)->tv_sec, \ + ((a)->tv_usec = (s)->tv_usec - (t)->tv_usec) < 0 && \ + ((a)->tv_usec += 1000000, (a)->tv_sec--) ) +#endif + +#if defined(_GNU_SOURCE) +#define TIMEVAL_TO_TIMESPEC(tv, ts) ( \ + (ts)->tv_sec = (tv)->tv_sec, \ + (ts)->tv_nsec = (tv)->tv_usec * 1000, \ + (void)0 ) +#define TIMESPEC_TO_TIMEVAL(tv, ts) ( \ + (tv)->tv_sec = (ts)->tv_sec, \ + (tv)->tv_usec = (ts)->tv_nsec / 1000, \ + (void)0 ) +#endif + +/* gettimeofday has been defined in time.c*/ +#if _REDIR_TIME64 +__REDIR(gettimeofday, __gettimeofday_time64); +__REDIR(getitimer, __getitimer_time64); +__REDIR(setitimer, __setitimer_time64); +__REDIR(utimes, __utimes_time64); +#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE) +__REDIR(futimes, __futimes_time64); +__REDIR(futimesat, __futimesat_time64); +__REDIR(lutimes, __lutimes_time64); +__REDIR(settimeofday, __settimeofday_time64); +__REDIR(adjtime, __adjtime64); +#endif +#endif + +#ifdef __cplusplus +} +#endif +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/timeb.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/timeb.h new file mode 100644 index 0000000000000000000000000000000000000000..628239b7ed9342ad8f19a655c290b4be2c6ba213 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/timeb.h @@ -0,0 +1,28 @@ +#ifndef _SYS_TIMEB_H +#define _SYS_TIMEB_H +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#define __NEED_time_t + +#include + +struct timeb { + time_t time; + unsigned short millitm; + short timezone, dstflag; +}; + +int ftime(struct timeb *); + +#if _REDIR_TIME64 +__REDIR(ftime, __ftime64); +#endif + +#ifdef __cplusplus +} +#endif +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/timerfd.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/timerfd.h new file mode 100644 index 0000000000000000000000000000000000000000..1b832cdd8f8faed5423cdc7d33060ed1f1cd73e3 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/timerfd.h @@ -0,0 +1,32 @@ +#ifndef _SYS_TIMERFD_H +#define _SYS_TIMERFD_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include + +#define TFD_NONBLOCK O_NONBLOCK +#define TFD_CLOEXEC O_CLOEXEC + +#define TFD_TIMER_ABSTIME 1 +#define TFD_TIMER_CANCEL_ON_SET (1 << 1) + +struct itimerspec; + +int timerfd_create(int, int); +int timerfd_settime(int, int, const struct itimerspec *, struct itimerspec *); +int timerfd_gettime(int, struct itimerspec *); + +#if _REDIR_TIME64 +__REDIR(timerfd_settime, __timerfd_settime64); +__REDIR(timerfd_gettime, __timerfd_gettime64); +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/times.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/times.h new file mode 100644 index 0000000000000000000000000000000000000000..80a50522d75d9705972b4a4b5898fee51edc30ae --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/times.h @@ -0,0 +1,25 @@ +#ifndef _SYS_TIMES_H +#define _SYS_TIMES_H + +#ifdef __cplusplus +extern "C" { +#endif + +#define __NEED_clock_t +#include + +struct tms { + clock_t tms_utime; + clock_t tms_stime; + clock_t tms_cutime; + clock_t tms_cstime; +}; + +clock_t times (struct tms *); + +#ifdef __cplusplus +} +#endif + +#endif + diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/timex.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/timex.h new file mode 100644 index 0000000000000000000000000000000000000000..8b417e1be258c3a342646c3ba4528c1b6f8a7e10 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/timex.h @@ -0,0 +1,103 @@ +#ifndef _SYS_TIMEX_H +#define _SYS_TIMEX_H + +#ifdef __cplusplus +extern "C" { +#endif + +#define __NEED_clockid_t + +#include + +#include + +struct ntptimeval { + struct timeval time; + long maxerror, esterror; +}; + +struct timex { + unsigned modes; + long offset, freq, maxerror, esterror; + int status; + long constant, precision, tolerance; + struct timeval time; + long tick, ppsfreq, jitter; + int shift; + long stabil, jitcnt, calcnt, errcnt, stbcnt; + int tai; + int __padding[11]; +}; + +#define ADJ_OFFSET 0x0001 +#define ADJ_FREQUENCY 0x0002 +#define ADJ_MAXERROR 0x0004 +#define ADJ_ESTERROR 0x0008 +#define ADJ_STATUS 0x0010 +#define ADJ_TIMECONST 0x0020 +#define ADJ_TAI 0x0080 +#define ADJ_SETOFFSET 0x0100 +#define ADJ_MICRO 0x1000 +#define ADJ_NANO 0x2000 +#define ADJ_TICK 0x4000 +#define ADJ_OFFSET_SINGLESHOT 0x8001 +#define ADJ_OFFSET_SS_READ 0xa001 + +#define MOD_OFFSET ADJ_OFFSET +#define MOD_FREQUENCY ADJ_FREQUENCY +#define MOD_MAXERROR ADJ_MAXERROR +#define MOD_ESTERROR ADJ_ESTERROR +#define MOD_STATUS ADJ_STATUS +#define MOD_TIMECONST ADJ_TIMECONST +#define MOD_CLKB ADJ_TICK +#define MOD_CLKA ADJ_OFFSET_SINGLESHOT +#define MOD_TAI ADJ_TAI +#define MOD_MICRO ADJ_MICRO +#define MOD_NANO ADJ_NANO + +#define STA_PLL 0x0001 +#define STA_PPSFREQ 0x0002 +#define STA_PPSTIME 0x0004 +#define STA_FLL 0x0008 + +#define STA_INS 0x0010 +#define STA_DEL 0x0020 +#define STA_UNSYNC 0x0040 +#define STA_FREQHOLD 0x0080 + +#define STA_PPSSIGNAL 0x0100 +#define STA_PPSJITTER 0x0200 +#define STA_PPSWANDER 0x0400 +#define STA_PPSERROR 0x0800 + +#define STA_CLOCKERR 0x1000 +#define STA_NANO 0x2000 +#define STA_MODE 0x4000 +#define STA_CLK 0x8000 + +#define STA_RONLY (STA_PPSSIGNAL | STA_PPSJITTER | STA_PPSWANDER | \ + STA_PPSERROR | STA_CLOCKERR | STA_NANO | STA_MODE | STA_CLK) + +#define TIME_OK 0 +#define TIME_INS 1 +#define TIME_DEL 2 +#define TIME_OOP 3 +#define TIME_WAIT 4 +#define TIME_ERROR 5 +#define TIME_BAD TIME_ERROR + +#define MAXTC 6 + +int adjtimex(struct timex *); +int clock_adjtime(clockid_t, struct timex *); + +#if _REDIR_TIME64 +__REDIR(adjtimex, __adjtimex_time64); +__REDIR(clock_adjtime, __clock_adjtime64); +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/ttydefaults.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/ttydefaults.h new file mode 100644 index 0000000000000000000000000000000000000000..edb55bc4d68a5229bb23996c30a10878d0d430fd --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/ttydefaults.h @@ -0,0 +1,34 @@ +#ifndef _SYS_TTYDEFAULTS_H +#define _SYS_TTYDEFAULTS_H + +#define TTYDEF_IFLAG (BRKINT | ISTRIP | ICRNL | IMAXBEL | IXON | IXANY) +#define TTYDEF_OFLAG (OPOST | ONLCR | XTABS) +#define TTYDEF_LFLAG (ECHO | ICANON | ISIG | IEXTEN | ECHOE|ECHOKE|ECHOCTL) +#define TTYDEF_CFLAG (CREAD | CS7 | PARENB | HUPCL) +#define TTYDEF_SPEED (B9600) +#define CTRL(x) ((x)&037) +#define CEOF CTRL('d') + +#define CEOL '\0' +#define CSTATUS '\0' + +#define CERASE 0177 +#define CINTR CTRL('c') +#define CKILL CTRL('u') +#define CMIN 1 +#define CQUIT 034 +#define CSUSP CTRL('z') +#define CTIME 0 +#define CDSUSP CTRL('y') +#define CSTART CTRL('q') +#define CSTOP CTRL('s') +#define CLNEXT CTRL('v') +#define CDISCARD CTRL('o') +#define CWERASE CTRL('w') +#define CREPRINT CTRL('r') +#define CEOT CEOF +#define CBRK CEOL +#define CRPRNT CREPRINT +#define CFLUSH CDISCARD + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/types.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/types.h new file mode 100644 index 0000000000000000000000000000000000000000..ff6f38296190a2addbe7e117a8e1e9b19c8087cd --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/types.h @@ -0,0 +1,92 @@ +#ifndef _SYS_TYPES_H +#define _SYS_TYPES_H +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#define __NEED_ino_t +#define __NEED_dev_t +#define __NEED_uid_t +#define __NEED_gid_t +#define __NEED_mode_t +#define __NEED_nlink_t +#define __NEED_off_t +#define __NEED_pid_t +#define __NEED_size_t +#define __NEED_ssize_t +#define __NEED_time_t +#define __NEED_timer_t +#define __NEED_clockid_t + +#define __NEED_blkcnt_t +#define __NEED_fsblkcnt_t +#define __NEED_fsfilcnt_t + +#define __NEED_id_t +#define __NEED_key_t +#define __NEED_clock_t +#define __NEED_suseconds_t +#define __NEED_blksize_t + +#define __NEED_pthread_t +#define __NEED_pthread_attr_t +#define __NEED_pthread_mutexattr_t +#define __NEED_pthread_condattr_t +#define __NEED_pthread_rwlockattr_t +#define __NEED_pthread_barrierattr_t +#define __NEED_pthread_mutex_t +#define __NEED_pthread_cond_t +#define __NEED_pthread_rwlock_t +#define __NEED_pthread_barrier_t +#define __NEED_pthread_spinlock_t +#define __NEED_pthread_key_t +#define __NEED_pthread_once_t +#define __NEED_useconds_t + +#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE) +#define __NEED_int8_t +#define __NEED_int16_t +#define __NEED_int32_t +#define __NEED_int64_t +#define __NEED_u_int64_t +#define __NEED_register_t +#endif +#ifdef __LITEOS__ +#define __NEED_int64_t +#endif + +#include + +#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE) +typedef unsigned char u_int8_t; +typedef unsigned short u_int16_t; +typedef unsigned u_int32_t; +typedef char *caddr_t; +typedef unsigned char u_char; +typedef unsigned short u_short, ushort; +typedef unsigned u_int, uint; +typedef unsigned long u_long, ulong; +typedef long long quad_t; +typedef unsigned long long u_quad_t; +#include +#include +#endif + +#if defined(_LARGEFILE64_SOURCE) || defined(_GNU_SOURCE) +#define blkcnt64_t blkcnt_t +#define fsblkcnt64_t fsblkcnt_t +#define fsfilcnt64_t fsfilcnt_t +#define ino64_t ino_t +#ifdef __LITEOS__ +#define off64_t int64_t +#else +#define off64_t off_t +#endif +#endif + +#ifdef __cplusplus +} +#endif +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/ucontext.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/ucontext.h new file mode 100644 index 0000000000000000000000000000000000000000..5fdbd63dbb26c4af8200ad5c7c09cc61fa3c174a --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/ucontext.h @@ -0,0 +1 @@ +#include diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/uio.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/uio.h new file mode 100644 index 0000000000000000000000000000000000000000..6700a2d71494012876719c443c2deb7ed01d5e3b --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/uio.h @@ -0,0 +1,143 @@ +/** + * @defgroup uio Uio + * @ingroup libc + */ + +#ifndef _SYS_UIO_H +#define _SYS_UIO_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#define __NEED_size_t +#define __NEED_ssize_t +#define __NEED_struct_iovec + +#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE) +#define __NEED_off_t +#endif + +#ifdef _GNU_SOURCE +#define __NEED_pid_t +#endif +#ifdef __LITEOS__ +#define __NEED_int64_t +#endif + +#include + +#define UIO_MAXIOV 1024 + +/** + * @ingroup uio + * + * @par Description: + * The readv() function shall be equivalent to read(), except as described below. + * The readv() function shall place the input data into the iovcnt buffers specified by the members + * of the iov array: iov[0], iov[1], ..., iov[iovcnt-1]. + * Each iovec entry specifies the base address and length of an area in memory where data should be placed. + * The readv() function shall always fill an area completely before proceeding to the next. + * + * @param fd [IN] File descriptor (or socket descriptor) to read from + * @param iov [OUT] The array that user-provided to save the data + * @param iovcnt [IN] The number of members in the array + * + * @attention + *
        + *
      • If the sum of the iov_len values is greater than {SSIZE_MAX}, + * the operation shall fail and no data shall be transferred.
      • + *
      + * + * @retval #ssize_t A positive non-zero number of bytes read on suceess. + * @retval #0 End-of-file or failed in read(). + * @retval #-1 The iov is a null pointer or out of memory. + * + * @par Errors + *
        + *
      • EBADF: fd is not a valid open file descriptor, or the file system doesn't support read().
      • + *
      • EACCES: The file is a write-only file.
      • + *
      • EIO: A hard error occurred in the low level disk I/O layer or the physical drive cannot work.
      • + *
      • ENOMEM: Out of memory.
      • + *
      • EINVAL: The sum of the iov_len values is greater than {SSIZE_MAX}
      • + *
      • ENODEV: The mount is not healthy.
      • + *
      + * + * @par Dependency: + *
      • uio.h
      + * @see writev + */ +ssize_t readv (int, const struct iovec *, int); + +/** + * @ingroup uio + * + * @par Description: + * The writev() function shall be equivalent to write(), except as described below. + * The writev() function shall gather output data from the iovcnt buffers specified by the members + * of the iov array: iov[0], iov[1], ..., iov[iovcnt-1]. + * Each iovec entry specifies the base address and length of an area in memory from which data should be written. + * The writev() function shall always write a complete area before proceeding to the next. + * + * @param fd [IN] File descriptor (or socket descriptor) to read from + * @param iov [IN] The array of data that user-provided to write + * @param iovcnt [IN] The number of members in the array + * + * @attention + *
        + *
      • If all of the iov_len members in the array pointed to by iov are 0, it shall return -1.
      • + *
      • If the sum of the iov_len values is greater than {SSIZE_MAX}, + * the operation shall fail and no data shall be transferred.
      • + *
      + * + * @retval #ssize_t On success, the number of bytes written are returned (zero indicates nothing was written). + * @retval #-1 On error, -1 is returned, and errno is set appropriately. + * + * @par Errors + *
        + *
      • EBADF: fd is not a valid open file descriptor, or the file system doesn't support write().
      • + *
      • EACCES/EROFS: The file is a read-only file or the file system is read-only.
      • + *
      • EIO: A physical I/O error has occurred.
      • + *
      • ENOMEM: Out of memory.
      • + *
      • EINTR: The write operation was terminated due to the receipt of a signal, no data was transferred.
      • + *
      • ENOSPC: There was no free space remaining on the device containing the file.
      • + *
      • EAGAIN: Non-blocking I/O has been selected using O_NONBLOCK and the write would block.
      • + *
      • EFBIG: An attempt was made to write a file that exceeds the implementation defined maximum file + * size or the process' file size limit, or to write at a position past the maximum allowed offset.
      • + *
      • EINVAL: The current position of file is less than zero, + * or the sum of the iov_len values is greater than {SSIZE_MAX}.
      • + *
      • ENODEV: The mount is not healthy.
      • + *
      + * + * @par Dependency: + *
      • uio.h
      + * @see readv + */ +ssize_t writev (int, const struct iovec *, int); + +#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE) +ssize_t preadv (int, const struct iovec *, int, off_t); +ssize_t pwritev (int, const struct iovec *, int, off_t); +#if defined(_LARGEFILE64_SOURCE) || defined(_GNU_SOURCE) +#define preadv64 preadv +#define pwritev64 pwritev +#ifdef __LITEOS__ +#define off64_t int64_t +#else +#define off64_t off_t +#endif +#endif +#endif + +#ifdef _GNU_SOURCE +ssize_t process_vm_writev(pid_t, const struct iovec *, unsigned long, const struct iovec *, unsigned long, unsigned long); +ssize_t process_vm_readv(pid_t, const struct iovec *, unsigned long, const struct iovec *, unsigned long, unsigned long); +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/un.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/un.h new file mode 100644 index 0000000000000000000000000000000000000000..1a3193ad208de81969695bc4cda1a3015ecff3e6 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/un.h @@ -0,0 +1,31 @@ +#ifndef _SYS_UN_H +#define _SYS_UN_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#define __NEED_sa_family_t +#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE) +#define __NEED_size_t +#endif + +#include + +struct sockaddr_un { + sa_family_t sun_family; + char sun_path[108]; +}; + +#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE) +size_t strlen(const char *); +#define SUN_LEN(s) (2+strlen((s)->sun_path)) +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/user.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/user.h new file mode 100644 index 0000000000000000000000000000000000000000..96a03400900b6e39c5e7d1012059438955da3745 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/user.h @@ -0,0 +1,16 @@ +#ifndef _SYS_USER_H +#define _SYS_USER_H +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include + +#include + +#ifdef __cplusplus +} +#endif +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/utsname.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/utsname.h new file mode 100644 index 0000000000000000000000000000000000000000..1b2ca61be114116dedce1b1a79dd3d5b1600605d --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/utsname.h @@ -0,0 +1,53 @@ +/** + * @defgroup utsname Utsname + * @ingroup libc + */ + +#ifndef _SYS_UTSNAME_H +#define _SYS_UTSNAME_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include +/** + * @ingroup utsname + * The defination of structure utsname. + */ +struct utsname { + char sysname[65]; + char nodename[65]; + char release[65]; + char version[65]; + char machine[65]; +#ifdef _GNU_SOURCE + char domainname[65]; +#else + char __domainname[65]; +#endif +}; + +/** + *@ingroup utsname + * + *@par Description: + *This API is used to get the name of current system. + *@attention + *
        + *
      • The members "machine" and "domainname" is not supported.
      • + *
      + * + *@retval 0 Get the name of current system successfully. + *@retval -1 Fails to get the name of current system. + * + *@par Dependency: + *
      • utsname.h
      + */ +int uname (struct utsname *); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/vfs.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/vfs.h new file mode 100644 index 0000000000000000000000000000000000000000..a899db276342327aa41c34c81629e85dffcd1f7c --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/vfs.h @@ -0,0 +1 @@ +#include diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/vt.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/vt.h new file mode 100644 index 0000000000000000000000000000000000000000..5000de499fa27bbe7854ea05ca36fb069eaa7b05 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/vt.h @@ -0,0 +1 @@ +#include diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/wait.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/wait.h new file mode 100644 index 0000000000000000000000000000000000000000..d4b1f2e185c66384e7901e4ca4370f7768eb3bb7 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/wait.h @@ -0,0 +1,67 @@ +#ifndef _SYS_WAIT_H +#define _SYS_WAIT_H +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#define __NEED_pid_t +#define __NEED_id_t +#include + +typedef enum { + P_ALL = 0, + P_PID = 1, + P_PGID = 2, + P_PIDFD = 3 +} idtype_t; + +pid_t wait (int *); +pid_t waitpid (pid_t, int *, int ); + +#if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \ + || defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) \ + || defined(_BSD_SOURCE) +#include +int waitid (idtype_t, id_t, siginfo_t *, int); +#endif + +#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE) +#include +pid_t wait3 (int *, int, struct rusage *); +pid_t wait4 (pid_t, int *, int, struct rusage *); +#endif + +#define WNOHANG 1 +#define WUNTRACED 2 + +#define WSTOPPED 2 +#define WEXITED 4 +#define WCONTINUED 8 +#define WNOWAIT 0x1000000 + +#define __WNOTHREAD 0x20000000 +#define __WALL 0x40000000 +#define __WCLONE 0x80000000 + +#define WEXITSTATUS(s) (((s) & 0xff00) >> 8) +#define WTERMSIG(s) ((s) & 0x7f) +#define WSTOPSIG(s) WEXITSTATUS(s) +#define WCOREDUMP(s) ((s) & 0x80) +#define WIFEXITED(s) (!WTERMSIG(s)) +#define WIFSTOPPED(s) ((short)((((s)&0xffff)*0x10001)>>8) > 0x7f00) +#define WIFSIGNALED(s) (((s)&0xffff)-1U < 0xffu) +#define WIFCONTINUED(s) ((s) == 0xffff) + +#if _REDIR_TIME64 +#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE) +__REDIR(wait3, __wait3_time64); +__REDIR(wait4, __wait4_time64); +#endif +#endif + +#ifdef __cplusplus +} +#endif +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/xattr.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/xattr.h new file mode 100644 index 0000000000000000000000000000000000000000..eeeaafc44f09ff74e87f89e75648a3ea8ed02ec3 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sys/xattr.h @@ -0,0 +1,32 @@ +#ifndef _SYS_XATTR_H +#define _SYS_XATTR_H +#ifdef __cplusplus +extern "C" { +#endif + +#define __NEED_ssize_t +#define __NEED_size_t +#include + +#define XATTR_CREATE 1 +#define XATTR_REPLACE 2 + +ssize_t getxattr(const char *, const char *, void *, size_t); +ssize_t lgetxattr(const char *, const char *, void *, size_t); +ssize_t fgetxattr(int, const char *, void *, size_t); +ssize_t listxattr(const char *, char *, size_t); +ssize_t llistxattr(const char *, char *, size_t); +ssize_t flistxattr(int, char *, size_t); +int setxattr(const char *, const char *, const void *, size_t, int); +int lsetxattr(const char *, const char *, const void *, size_t, int); +int fsetxattr(int, const char *, const void *, size_t, int); +int removexattr(const char *, const char *); +int lremovexattr(const char *, const char *); +int fremovexattr(int, const char *); + +#define __UAPI_DEF_XATTR 0 + +#ifdef __cplusplus +} +#endif +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/syscall.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/syscall.h new file mode 100644 index 0000000000000000000000000000000000000000..4c305784472f8bbcd05f4952dd01934d8d7c2175 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/syscall.h @@ -0,0 +1 @@ +#include diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sysexits.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sysexits.h new file mode 100644 index 0000000000000000000000000000000000000000..16eeb41935eede6c384f5fd631836d7723c41fa0 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/sysexits.h @@ -0,0 +1,21 @@ +#ifndef _SYSEXITS_H +#define _SYSEXITS_H +#define EX_OK 0 +#define EX__BASE 64 +#define EX_USAGE 64 +#define EX_DATAERR 65 +#define EX_NOINPUT 66 +#define EX_NOUSER 67 +#define EX_NOHOST 68 +#define EX_UNAVAILABLE 69 +#define EX_SOFTWARE 70 +#define EX_OSERR 71 +#define EX_OSFILE 72 +#define EX_CANTCREAT 73 +#define EX_IOERR 74 +#define EX_TEMPFAIL 75 +#define EX_PROTOCOL 76 +#define EX_NOPERM 77 +#define EX_CONFIG 78 +#define EX__MAX 78 +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/syslog.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/syslog.h new file mode 100644 index 0000000000000000000000000000000000000000..5b4d2964e780e6cc7c300756ebc4c7b0447887f6 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/syslog.h @@ -0,0 +1,100 @@ +#ifndef _SYSLOG_H +#define _SYSLOG_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#define LOG_EMERG 0 +#define LOG_ALERT 1 +#define LOG_CRIT 2 +#define LOG_ERR 3 +#define LOG_WARNING 4 +#define LOG_NOTICE 5 +#define LOG_INFO 6 +#define LOG_DEBUG 7 + +#define LOG_PRIMASK 7 +#define LOG_PRI(p) ((p)&LOG_PRIMASK) +#define LOG_MAKEPRI(f, p) (((f)<<3)|(p)) + +#define LOG_MASK(p) (1<<(p)) +#define LOG_UPTO(p) ((1<<((p)+1))-1) + +#define LOG_KERN (0<<3) +#define LOG_USER (1<<3) +#define LOG_MAIL (2<<3) +#define LOG_DAEMON (3<<3) +#define LOG_AUTH (4<<3) +#define LOG_SYSLOG (5<<3) +#define LOG_LPR (6<<3) +#define LOG_NEWS (7<<3) +#define LOG_UUCP (8<<3) +#define LOG_CRON (9<<3) +#define LOG_AUTHPRIV (10<<3) +#define LOG_FTP (11<<3) + +#define LOG_LOCAL0 (16<<3) +#define LOG_LOCAL1 (17<<3) +#define LOG_LOCAL2 (18<<3) +#define LOG_LOCAL3 (19<<3) +#define LOG_LOCAL4 (20<<3) +#define LOG_LOCAL5 (21<<3) +#define LOG_LOCAL6 (22<<3) +#define LOG_LOCAL7 (23<<3) + +#define LOG_NFACILITIES 24 +#define LOG_FACMASK 0x3f8 +#define LOG_FAC(p) (((p)&LOG_FACMASK)>>3) + +#define LOG_PID 0x01 +#define LOG_CONS 0x02 +#define LOG_ODELAY 0x04 +#define LOG_NDELAY 0x08 +#define LOG_NOWAIT 0x10 +#define LOG_PERROR 0x20 + +void closelog (void); +void openlog (const char *, int, int); +int setlogmask (int); +void syslog (int, const char *, ...); + +#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE) +#define _PATH_LOG "/dev/log" +#define __NEED_va_list +#include +void vsyslog (int, const char *, va_list); +#if defined(SYSLOG_NAMES) +#define INTERNAL_NOPRI 0x10 +#define INTERNAL_MARK (LOG_NFACILITIES<<3) +typedef struct { + char *c_name; + int c_val; +} CODE; +#define prioritynames ((CODE *)(const CODE []){ \ + { "alert", LOG_ALERT }, { "crit", LOG_CRIT }, { "debug", LOG_DEBUG }, \ + { "emerg", LOG_EMERG }, { "err", LOG_ERR }, { "error", LOG_ERR }, \ + { "info", LOG_INFO }, { "none", INTERNAL_NOPRI }, \ + { "notice", LOG_NOTICE }, { "panic", LOG_EMERG }, \ + { "warn", LOG_WARNING }, { "warning", LOG_WARNING }, { 0, -1 } }) +#define facilitynames ((CODE *)(const CODE []){ \ + { "auth", LOG_AUTH }, { "authpriv", LOG_AUTHPRIV }, \ + { "cron", LOG_CRON }, { "daemon", LOG_DAEMON }, { "ftp", LOG_FTP }, \ + { "kern", LOG_KERN }, { "lpr", LOG_LPR }, { "mail", LOG_MAIL }, \ + { "mark", INTERNAL_MARK }, { "news", LOG_NEWS }, \ + { "security", LOG_AUTH }, { "syslog", LOG_SYSLOG }, \ + { "user", LOG_USER }, { "uucp", LOG_UUCP }, \ + { "local0", LOG_LOCAL0 }, { "local1", LOG_LOCAL1 }, \ + { "local2", LOG_LOCAL2 }, { "local3", LOG_LOCAL3 }, \ + { "local4", LOG_LOCAL4 }, { "local5", LOG_LOCAL5 }, \ + { "local6", LOG_LOCAL6 }, { "local7", LOG_LOCAL7 }, { 0, -1 } }) +#endif +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/tar.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/tar.h new file mode 100644 index 0000000000000000000000000000000000000000..be589842a8f756e1258e28d7fa726afc4a1f549e --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/tar.h @@ -0,0 +1,33 @@ +#ifndef _TAR_H +#define _TAR_H + +#define TSUID 04000 +#define TSGID 02000 +#define TSVTX 01000 +#define TUREAD 00400 +#define TUWRITE 00200 +#define TUEXEC 00100 +#define TGREAD 00040 +#define TGWRITE 00020 +#define TGEXEC 00010 +#define TOREAD 00004 +#define TOWRITE 00002 +#define TOEXEC 00001 + +#define REGTYPE '0' +#define AREGTYPE '\0' +#define LNKTYPE '1' +#define SYMTYPE '2' +#define CHRTYPE '3' +#define BLKTYPE '4' +#define DIRTYPE '5' +#define FIFOTYPE '6' +#define CONTTYPE '7' + +#define TMAGIC "ustar" +#define TMAGLEN 6 + +#define TVERSION "00" +#define TVERSLEN 2 + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/termios.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/termios.h new file mode 100644 index 0000000000000000000000000000000000000000..28685498008cc54b71c75b5c5afc8c3e719795e4 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/termios.h @@ -0,0 +1,322 @@ +/** + * @defgroup termios Termios + * @ingroup libc + */ + +#ifndef _TERMIOS_H +#define _TERMIOS_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#define __NEED_pid_t + +#include + +typedef unsigned char cc_t; +typedef unsigned int speed_t; +typedef unsigned int tcflag_t; + +#define NCCS 32 + +#include + +/** + *@ingroup termios + * + *@par Description: + *The cfgetospeed() function shall extract the output baud rate from the + *termios structure to which the s argument points. This function + *shall return exactly the value in the termios data structure, without interpretation. + * + *@attention + *
        + *
      • None.
      • + *
      + * + *@retval #speed_t Upon successful completion, cfgetospeed() shall return a value + *of type speed_t representing the output baud rate. + * + *@par Dependency: + *
      • termios.h
      + *@see cfgetispeed | cfsetispeed | cfsetospeed | tcgetattr + */ +speed_t cfgetospeed (const struct termios *); + +/** + *@ingroup termios + * + *@par Description: + *The cfgetispeed() function shall extract the input baud rate from the termios + *structure to which the s argument points. This function shall return + *exactly the value in the termios data structure, without interpretation. + * + *@attention + *
        + *
      • None.
      • + *
      + * + *@retval #speed_t Upon successful completion, cfgetispeed() shall return a value of + *type speed_t representing the input baud rate. + * + *@par Dependency: + *
      • termios.h
      + *@see cfgetospeed | cfsetispeed | cfsetospeed | tcgetattr + */ +speed_t cfgetispeed (const struct termios *); + +/** + *@ingroup termios + * + *@par Description: + *The cfsetospeed() function shall set the output baud rate stored in + *the structure pointed to by s to speed. + * + *@attention + *
        + *
      • None.
      • + *
      + * + *@retval #0 cfsetospeed() shall return 0. + * + *@par Dependency: + *
      • termios.h
      + *@see cfgetispeed | cfgetospeed | cfsetispeed | tcsetattr + */ +int cfsetospeed (struct termios *, speed_t); + +/** + *@ingroup termios + * + *@par Description: + *The cfsetispeed() function shall set the input baud rate stored in + *the structure pointed to by s to speed. + * + *@attention + *
        + *
      • None.
      • + *
      + * + *@retval #0 cfsetispeed() shall return 0. + * + *@par Dependency: + *
      • termios.h
      + *@see cfgetispeed | cfgetospeed | cfsetospeed | tcsetattr + */ +int cfsetispeed (struct termios *, speed_t); + +/** + *@ingroup termios + * + *@par Description: + *The tcgetattr() function shall get the parameters associated with the terminal referred + *to by fd and store them in the termios structure referenced by s. + *The fd argument is an open file descriptor associated with a terminal. + * + *@attention + *
        + *
      • The API is not supported.
      • + *
      + * + *@retval #0 Upon successful completion, 0 shall be returned. + *@retval #-1 If it fails, -1 shall be returned and errno set to indicate the error. + * + *@par Errors + *
        + *
      • EBADF:The fd argument is not a valid open file descriptor.
      • + *
      • EINVAL:The request or arg argument is not valid for this device.
      • + *
      • ENOMEM:If any resource allocation fails, ENOMEM is set as errno.
      • + *
      • EAFNOSUPPORT:If socket created with PF_PACKET, SOCK_RAW is called with SIOCADDRT.
      • + *
      + * + *@par Dependency: + *
      • termios.h
      + *@see tcsetattr + */ +int tcgetattr (int, struct termios *); + +/** + *@ingroup termios + * + *@par Description: + *The tcsetattr() function shall set the parameters associated with the terminal + *referred to by the open file descriptor fd (an open file descriptor associated with a terminal) + *from the termios structure referenced by s. + * + *@attention + *
        + *
      • The API is not supported.
      • + *
      + * + *@retval #0 Upon successful completion, 0 shall be returned. + *@retval #-1 If it fails, -1 shall be returned and errno set to indicate the error. + * + *@par Errors + *
        + *
      • EBADF:The fd argument is not a valid open file descriptor.
      • + *
      • EINVAL:The request or arg argument is not valid for this device.
      • + *
      • ENOMEM:If any resource allocation fails, ENOMEM is set as errno.
      • + *
      • EAFNOSUPPORT:If socket created with PF_PACKET, SOCK_RAW is called with SIOCADDRT.
      • + *
      + * + *@par Dependency: + *
      • termios.h
      + *@see cfgetispeed | tcgetattr + */ +int tcsetattr (int, int, const struct termios *); + +/** + *@ingroup termios + * + *@par Description: + *The tcsendbreak() function sends a break for a specific duration. + * + *@attention + *
        + *
      • None.
      • + *
      + * + *@retval #0 Upon successful completion, 0 shall be returned. + *@retval #-1 If it fails, -1 shall be returned and errno set to indicate the error. + * + *@par Errors + *
        + *
      • EBADF:The fd argument is not a valid open file descriptor.
      • + *
      • EINVAL:The request or arg argument is not valid for this device.
      • + *
      • ENOMEM:If any resource allocation fails, ENOMEM is set as errno.
      • + *
      • EAFNOSUPPORT:If socket created with PF_PACKET, SOCK_RAW is called with SIOCADDRT.
      • + *
      + * + *@par Dependency: + *
      • termios.h
      + *@see None + */ +int tcsendbreak (int, int); +int tcdrain (int); + +/** + *@ingroup termios + * + *@par Description: + *Upon successful completion, tcflush() shall discard data written to the object + *referred to by fd (an open file descriptor associated with a terminal) but not transmitted, + *or data received but not read, depending on the value of __queue. + * + *@attention + *
        + *
      • None.
      • + *
      + * + *@retval #0 Upon successful completion, 0 shall be returned. + *@retval #-1 If it fails, -1 shall be returned and errno set to indicate the error. + * + *@par Errors + *
        + *
      • EBADF:The fd argument is not a valid open file descriptor.
      • + *
      • EINVAL:The request or arg argument is not valid for this device.
      • + *
      • ENOMEM:If any resource allocation fails, ENOMEM is set as errno.
      • + *
      • EAFNOSUPPORT:If socket created with PF_PACKET, SOCK_RAW is called with SIOCADDRT.
      • + *
      + * + *@par Dependency: + *
      • termios.h
      + *@see None + */ +int tcflush (int, int); + +/** + *@ingroup termios + * + *@par Description: + *The tcflow() function shall suspend or restart transmission or reception of + *data on the object referred to by fd, depending on the value of action. + * + *@attention + *
        + *
      • None.
      • + *
      + * + *@retval #0 Upon successful completion, 0 shall be returned. + *@retval #-1 If it fails, -1 shall be returned and errno set to indicate the error. + * + *@par Errors + *
        + *
      • EBADF:The fd argument is not a valid open file descriptor.
      • + *
      • EINVAL:The request or arg argument is not valid for this device.
      • + *
      • ENOMEM:If any resource allocation fails, ENOMEM is set as errno.
      • + *
      • EAFNOSUPPORT:If socket created with PF_PACKET, SOCK_RAW is called with SIOCADDRT.
      • + *
      + * + *@par Dependency: + *
      • termios.h
      + *@see tcsendbreak + */ +int tcflow (int, int); + +/** + *@ingroup termios + * + *@par Description: + *The tcgetsid() function shall obtain the process group ID of the session for which the terminal + *specified by fildes is the controlling terminal. + * + *@attention + *
        + *
      • None.
      • + *
      + * + *@retval #pid_t Upon successful completion, tcgetsid() shall return the process group ID of + *the session associated with the terminal. Otherwise, a value of -1 shall be returned + *and errno set to indicate the error. + * + *@par Errors + *
        + *
      • EBADF:The fd argument is not a valid open file descriptor.
      • + *
      • EINVAL:The request or arg argument is not valid for this device.
      • + *
      • ENOMEM:If any resource allocation fails, ENOMEM is set as errno.
      • + *
      • EAFNOSUPPORT:If socket created with PF_PACKET, SOCK_RAW is called with SIOCADDRT.
      • + *
      + * + *@par Dependency: + *
      • termios.h
      + *@see None + */ +pid_t tcgetsid (int); + +#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE) + +/** + *@ingroup termios + * + *@par Description: + *The cfmakeraw() sets the terminal to something like the "raw" mode of terminal driver: + *input is available character by character, echoing is disabled, and all special processing + *of terminal input and output characters is disabled. + * + *@attention + *
        + *
      • + *The cfmakeraw() function is not a standard C Library Function. + *
      • + *
      + * + *@retval #void None. + * + *@par Dependency: + *
      • termios.h
      + * + *@see cfgetispeed | cfsetispeed | cfsetospeed | tcgetattr + * + */ +void cfmakeraw(struct termios *); +int cfsetspeed(struct termios *, speed_t); +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/tgmath.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/tgmath.h new file mode 100644 index 0000000000000000000000000000000000000000..e41ccac9ec54cc038ed4b4b33bc64544cb396606 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/tgmath.h @@ -0,0 +1,270 @@ +#ifndef _TGMATH_H +#define _TGMATH_H + +/* +the return types are only correct with gcc (__GNUC__) +otherwise they are long double or long double complex + +the long double version of a function is never chosen when +sizeof(double) == sizeof(long double) +(but the return type is set correctly with gcc) +*/ + +#include +#include + +#define __IS_FP(x) (sizeof((x)+1ULL) == sizeof((x)+1.0f)) +#define __IS_CX(x) (__IS_FP(x) && sizeof(x) == sizeof((x)+I)) +#define __IS_REAL(x) (__IS_FP(x) && 2*sizeof(x) == sizeof((x)+I)) + +#define __FLT(x) (__IS_REAL(x) && sizeof(x) == sizeof(float)) +#define __LDBL(x) (__IS_REAL(x) && sizeof(x) == sizeof(long double) && sizeof(long double) != sizeof(double)) + +#define __FLTCX(x) (__IS_CX(x) && sizeof(x) == sizeof(float complex)) +#define __DBLCX(x) (__IS_CX(x) && sizeof(x) == sizeof(double complex)) +#define __LDBLCX(x) (__IS_CX(x) && sizeof(x) == sizeof(long double complex) && sizeof(long double) != sizeof(double)) + +/* return type */ + +#ifdef __GNUC__ +/* +the result must be casted to the right type +(otherwise the result type is determined by the conversion +rules applied to all the function return types so it is long +double or long double complex except for integral functions) + +this cannot be done in c99, so the typeof gcc extension is +used and that the type of ?: depends on wether an operand is +a null pointer constant or not +(in c11 _Generic can be used) + +the c arguments below must be integer constant expressions +so they can be in null pointer constants +(__IS_FP above was carefully chosen this way) +*/ +/* if c then t else void */ +#define __type1(c,t) __typeof__(*(0?(t*)0:(void*)!(c))) +/* if c then t1 else t2 */ +#define __type2(c,t1,t2) __typeof__(*(0?(__type1(c,t1)*)0:(__type1(!(c),t2)*)0)) +/* cast to double when x is integral, otherwise use typeof(x) */ +#define __RETCAST(x) ( \ + __type2(__IS_FP(x), __typeof__(x), double)) +/* 2 args case, should work for complex types (cpow) */ +#define __RETCAST_2(x, y) ( \ + __type2(__IS_FP(x) && __IS_FP(y), \ + __typeof__((x)+(y)), \ + __typeof__((x)+(y)+1.0))) +/* 3 args case (fma only) */ +#define __RETCAST_3(x, y, z) ( \ + __type2(__IS_FP(x) && __IS_FP(y) && __IS_FP(z), \ + __typeof__((x)+(y)+(z)), \ + __typeof__((x)+(y)+(z)+1.0))) +/* drop complex from the type of x */ +/* TODO: wrong when sizeof(long double)==sizeof(double) */ +#define __RETCAST_REAL(x) ( \ + __type2(__IS_FP(x) && sizeof((x)+I) == sizeof(float complex), float, \ + __type2(sizeof((x)+1.0+I) == sizeof(double complex), double, \ + long double))) +/* add complex to the type of x */ +#define __RETCAST_CX(x) (__typeof__(__RETCAST(x)0+I)) +#else +#define __RETCAST(x) +#define __RETCAST_2(x, y) +#define __RETCAST_3(x, y, z) +#define __RETCAST_REAL(x) +#define __RETCAST_CX(x) +#endif + +/* function selection */ + +#define __tg_real_nocast(fun, x) ( \ + __FLT(x) ? fun ## f (x) : \ + __LDBL(x) ? fun ## l (x) : \ + fun(x) ) + +#define __tg_real(fun, x) (__RETCAST(x)__tg_real_nocast(fun, x)) + +#define __tg_real_2_1(fun, x, y) (__RETCAST(x)( \ + __FLT(x) ? fun ## f (x, y) : \ + __LDBL(x) ? fun ## l (x, y) : \ + fun(x, y) )) + +#define __tg_real_2(fun, x, y) (__RETCAST_2(x, y)( \ + __FLT(x) && __FLT(y) ? fun ## f (x, y) : \ + __LDBL((x)+(y)) ? fun ## l (x, y) : \ + fun(x, y) )) + +#define __tg_complex(fun, x) (__RETCAST_CX(x)( \ + __FLTCX((x)+I) && __IS_FP(x) ? fun ## f (x) : \ + __LDBLCX((x)+I) ? fun ## l (x) : \ + fun(x) )) + +#define __tg_complex_retreal(fun, x) (__RETCAST_REAL(x)( \ + __FLTCX((x)+I) && __IS_FP(x) ? fun ## f (x) : \ + __LDBLCX((x)+I) ? fun ## l (x) : \ + fun(x) )) + +#define __tg_real_complex(fun, x) (__RETCAST(x)( \ + __FLTCX(x) ? c ## fun ## f (x) : \ + __DBLCX(x) ? c ## fun (x) : \ + __LDBLCX(x) ? c ## fun ## l (x) : \ + __FLT(x) ? fun ## f (x) : \ + __LDBL(x) ? fun ## l (x) : \ + fun(x) )) + +/* special cases */ + +#define __tg_real_remquo(x, y, z) (__RETCAST_2(x, y)( \ + __FLT(x) && __FLT(y) ? remquof(x, y, z) : \ + __LDBL((x)+(y)) ? remquol(x, y, z) : \ + remquo(x, y, z) )) + +#define __tg_real_fma(x, y, z) (__RETCAST_3(x, y, z)( \ + __FLT(x) && __FLT(y) && __FLT(z) ? fmaf(x, y, z) : \ + __LDBL((x)+(y)+(z)) ? fmal(x, y, z) : \ + fma(x, y, z) )) + +#define __tg_real_complex_pow(x, y) (__RETCAST_2(x, y)( \ + __FLTCX((x)+(y)) && __IS_FP(x) && __IS_FP(y) ? cpowf(x, y) : \ + __FLTCX((x)+(y)) ? cpow(x, y) : \ + __DBLCX((x)+(y)) ? cpow(x, y) : \ + __LDBLCX((x)+(y)) ? cpowl(x, y) : \ + __FLT(x) && __FLT(y) ? powf(x, y) : \ + __LDBL((x)+(y)) ? powl(x, y) : \ + pow(x, y) )) + +#define __tg_real_complex_fabs(x) (__RETCAST_REAL(x)( \ + __FLTCX(x) ? cabsf(x) : \ + __DBLCX(x) ? cabs(x) : \ + __LDBLCX(x) ? cabsl(x) : \ + __FLT(x) ? fabsf(x) : \ + __LDBL(x) ? fabsl(x) : \ + fabs(x) )) + +/* suppress any macros in math.h or complex.h */ + +#undef acos +#undef acosh +#undef asin +#undef asinh +#undef atan +#undef atan2 +#undef atanh +#undef carg +#undef cbrt +#undef ceil +#undef cimag +#undef conj +#undef copysign +#undef cos +#undef cosh +#undef cproj +#undef creal +#undef erf +#undef erfc +#undef exp +#undef exp2 +#undef expm1 +#undef fabs +#undef fdim +#undef floor +#undef fma +#undef fmax +#undef fmin +#undef fmod +#undef frexp +#undef hypot +#undef ilogb +#undef ldexp +#undef lgamma +#undef llrint +#undef llround +#undef log +#undef log10 +#undef log1p +#undef log2 +#undef logb +#undef lrint +#undef lround +#undef nearbyint +#undef nextafter +#undef nexttoward +#undef pow +#undef remainder +#undef remquo +#undef rint +#undef round +#undef scalbln +#undef scalbn +#undef sin +#undef sinh +#undef sqrt +#undef tan +#undef tanh +#undef tgamma +#undef trunc + +/* tg functions */ + +#define acos(x) __tg_real_complex(acos, (x)) +#define acosh(x) __tg_real_complex(acosh, (x)) +#define asin(x) __tg_real_complex(asin, (x)) +#define asinh(x) __tg_real_complex(asinh, (x)) +#define atan(x) __tg_real_complex(atan, (x)) +#define atan2(x,y) __tg_real_2(atan2, (x), (y)) +#define atanh(x) __tg_real_complex(atanh, (x)) +#define carg(x) __tg_complex_retreal(carg, (x)) +#define cbrt(x) __tg_real(cbrt, (x)) +#define ceil(x) __tg_real(ceil, (x)) +#define cimag(x) __tg_complex_retreal(cimag, (x)) +#define conj(x) __tg_complex(conj, (x)) +#define copysign(x,y) __tg_real_2(copysign, (x), (y)) +#define cos(x) __tg_real_complex(cos, (x)) +#define cosh(x) __tg_real_complex(cosh, (x)) +#define cproj(x) __tg_complex(cproj, (x)) +#define creal(x) __tg_complex_retreal(creal, (x)) +#define erf(x) __tg_real(erf, (x)) +#define erfc(x) __tg_real(erfc, (x)) +#define exp(x) __tg_real_complex(exp, (x)) +#define exp2(x) __tg_real(exp2, (x)) +#define expm1(x) __tg_real(expm1, (x)) +#define fabs(x) __tg_real_complex_fabs(x) +#define fdim(x,y) __tg_real_2(fdim, (x), (y)) +#define floor(x) __tg_real(floor, (x)) +#define fma(x,y,z) __tg_real_fma((x), (y), (z)) +#define fmax(x,y) __tg_real_2(fmax, (x), (y)) +#define fmin(x,y) __tg_real_2(fmin, (x), (y)) +#define fmod(x,y) __tg_real_2(fmod, (x), (y)) +#define frexp(x,y) __tg_real_2_1(frexp, (x), (y)) +#define hypot(x,y) __tg_real_2(hypot, (x), (y)) +#define ilogb(x) __tg_real_nocast(ilogb, (x)) +#define ldexp(x,y) __tg_real_2_1(ldexp, (x), (y)) +#define lgamma(x) __tg_real(lgamma, (x)) +#define llrint(x) __tg_real_nocast(llrint, (x)) +#define llround(x) __tg_real_nocast(llround, (x)) +#define log(x) __tg_real_complex(log, (x)) +#define log10(x) __tg_real(log10, (x)) +#define log1p(x) __tg_real(log1p, (x)) +#define log2(x) __tg_real(log2, (x)) +#define logb(x) __tg_real(logb, (x)) +#define lrint(x) __tg_real_nocast(lrint, (x)) +#define lround(x) __tg_real_nocast(lround, (x)) +#define nearbyint(x) __tg_real(nearbyint, (x)) +#define nextafter(x,y) __tg_real_2(nextafter, (x), (y)) +#define nexttoward(x,y) __tg_real_2(nexttoward, (x), (y)) +#define pow(x,y) __tg_real_complex_pow((x), (y)) +#define remainder(x,y) __tg_real_2(remainder, (x), (y)) +#define remquo(x,y,z) __tg_real_remquo((x), (y), (z)) +#define rint(x) __tg_real(rint, (x)) +#define round(x) __tg_real(round, (x)) +#define scalbln(x,y) __tg_real_2_1(scalbln, (x), (y)) +#define scalbn(x,y) __tg_real_2_1(scalbn, (x), (y)) +#define sin(x) __tg_real_complex(sin, (x)) +#define sinh(x) __tg_real_complex(sinh, (x)) +#define sqrt(x) __tg_real_complex(sqrt, (x)) +#define tan(x) __tg_real_complex(tan, (x)) +#define tanh(x) __tg_real_complex(tanh, (x)) +#define tgamma(x) __tg_real(tgamma, (x)) +#define trunc(x) __tg_real(trunc, (x)) + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/threads.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/threads.h new file mode 100644 index 0000000000000000000000000000000000000000..52ec3100eb9e2ebf3523123ba51021582361b855 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/threads.h @@ -0,0 +1,93 @@ +#ifndef _THREADS_H +#define _THREADS_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +typedef unsigned long thrd_t; +#else +typedef struct __pthread *thrd_t; +#define thread_local _Thread_local +#endif + +typedef int once_flag; +typedef unsigned tss_t; +typedef int (*thrd_start_t)(void *); +typedef void (*tss_dtor_t)(void *); + +#define __NEED_cnd_t +#define __NEED_mtx_t + +#include + +#define TSS_DTOR_ITERATIONS 4 + +enum { + thrd_success = 0, + thrd_busy = 1, + thrd_error = 2, + thrd_nomem = 3, + thrd_timedout = 4, +}; + +enum { + mtx_plain = 0, + mtx_recursive = 1, + mtx_timed = 2, +}; + +#define ONCE_FLAG_INIT 0 + +int thrd_create(thrd_t *, thrd_start_t, void *); +_Noreturn void thrd_exit(int); + +int thrd_detach(thrd_t); +int thrd_join(thrd_t, int *); + +int thrd_sleep(const struct timespec *, struct timespec *); +void thrd_yield(void); + +thrd_t thrd_current(void); +int thrd_equal(thrd_t, thrd_t); +#ifndef __cplusplus +#define thrd_equal(A, B) ((A) == (B)) +#endif + +void call_once(once_flag *, void (*)(void)); + +int mtx_init(mtx_t *, int); +void mtx_destroy(mtx_t *); + +int mtx_lock(mtx_t *); +int mtx_timedlock(mtx_t *__restrict, const struct timespec *__restrict); +int mtx_trylock(mtx_t *); +int mtx_unlock(mtx_t *); + +int cnd_init(cnd_t *); +void cnd_destroy(cnd_t *); + +int cnd_broadcast(cnd_t *); +int cnd_signal(cnd_t *); + +int cnd_timedwait(cnd_t *__restrict, mtx_t *__restrict, const struct timespec *__restrict); +int cnd_wait(cnd_t *, mtx_t *); + +int tss_create(tss_t *, tss_dtor_t); +void tss_delete(tss_t); + +int tss_set(tss_t, void *); +void *tss_get(tss_t); + +#if _REDIR_TIME64 +__REDIR(thrd_sleep, __thrd_sleep_time64); +__REDIR(mtx_timedlock, __mtx_timedlock_time64); +__REDIR(cnd_timedwait, __cnd_timedwait_time64); +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/time.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/time.h new file mode 100644 index 0000000000000000000000000000000000000000..a288de9e1865b97fcfad089a6644e4b76dac66c2 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/time.h @@ -0,0 +1,854 @@ +/** + * @defgroup time Time + * @ingroup libc + */ + +#ifndef _TIME_H +#define _TIME_H + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef __LITEOS__ +#include "sys/time.h" +#endif + +#include + +#ifdef __cplusplus +#define NULL 0L +#else +#ifndef NULL +#define NULL ((void*)0) +#endif +#endif + + +#define __NEED_size_t +#define __NEED_time_t +#define __NEED_clock_t +#define __NEED_struct_timespec +#ifdef __LITEOS__ +#define __NEED_suseconds_t +#define __NEED_struct_timeval +#endif + +#if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \ + || defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) \ + || defined(_BSD_SOURCE) +#define __NEED_clockid_t +#define __NEED_timer_t +#define __NEED_pid_t +#define __NEED_locale_t +#endif + +#include + +#if defined(_BSD_SOURCE) || defined(_GNU_SOURCE) +#define __tm_gmtoff tm_gmtoff +#define __tm_zone tm_zone +#endif + +struct tm { + int tm_sec; + int tm_min; + int tm_hour; + int tm_mday; + int tm_mon; + int tm_year; + int tm_wday; + int tm_yday; + int tm_isdst; + long __tm_gmtoff; + const char *__tm_zone; +}; + +/** + * @ingroup time + * @par Description: + * This function gets the current time as an integer number of microseconds. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval + * #clock_t This function returns the current time as an integer number of microseconds. + * + * @par Dependency: + *
      • time.h
      + * + * @see asctime | clock_getres | ctime | difftime | gmtime | localtime | mktime | strftime | + * strptime | time | times | utime + * + */ +clock_t clock (void); + +/** + * @ingroup time + * @par Description: + * This function gets the value of time in seconds since the Epoch(1970-01-01 00:00:00 UTC). + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval + * #time_t On success, this function shall return the value of time in seconds since the Epoch. + * the argument points to an area where the return value is also stored. If the argument is a null pointer, + * no value is stored.On failure, this function shall return (time_t)-1. + * + * @par Dependency: + *
      • time.h
      + * + * @see asctime | clock | clock_getres | ctime | difftime | gettimeofday | gmtime | localtime | mktime | strftime | strptime | times | utime + * + */ +time_t time (time_t *); + +/** + * @ingroup time + * @par Description: + * This function shall compute the difference between two calendar times (as returned by time()). + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval + * #double This function return the difference expressed in seconds as a type double. + * + * @par Dependency: + *
      • time.h
      + * + * @see clock | ctime | asctime | gmtime | localtime | mktime | strftime | strptime | times | utime + * + */ +double difftime (time_t, time_t); + +/** + * @ingroup time + * @par Description: + * This function shall convert the broken-down time, expressed as local time, in the structure pointed + * to by the argument,into a time since the Epoch value with the same encoding as that of the values + * returned by time(). The original values of the tm_wday and tm_yday components of the structure shall + * be ignored, and the original values of the other components shall not be restricted to the ranges + * described in . + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval + * #time_t On success, shall return the specified time since the Epoch encoded as a value of type time_t. + * On failure, If the time since the Epoch cannot be represented, the function shall return the value (time_t)-1. + * + * @par Errors + *
        + *
      • EINVAL: An invalid input.
      • + *
      + * + * @par Dependency: + *
      • time.h
      + * + * @see asctime | clock | ctime | difftime | gmtime | localtime | strftime | strptime | time | tzset | utime + * + */ +time_t mktime (struct tm *); + +/** + * @ingroup time + * @par Description: + * This function formats the broken-down time tm according to the format specification format and places the result in the character + * array s of size the second. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval + * #size_t Provided that the result string, including the terminating null byte, does not exceed max bytes, + * it returns the number of bytes (excluding the terminating null byte) placed in the array s. + * If the length of the result string (including the terminating null byte) would exceed max bytes, + * then it returns 0, and the contents of the array are undefined. + * + * @par Dependency: + *
      • time.h
      + * + * @see asctime | clock | clock_getres | ctime | difftime | gettimeofday | gmtime | localtime | mktime | strptime | times | utime | tzset + * + */ +size_t strftime (char *__restrict, size_t, const char *__restrict, const struct tm *__restrict); + +/** + * @ingroup time + * @par Description: + * This function convert the time in seconds since the Epoch pointed to by the argument into + * a broken-down time, expressed as Coordinated Universal Time (UTC). + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval + * "struct tm*" On success, this function returns a pointer to a struct tm. + * On failure, it shall return a null pointer. + * + * @par Dependency: + *
      • time.h
      + * + * @see asctime | clock | ctime | difftime | localtime | mktime | strftime | strptime | time | utime + * + */ +struct tm *gmtime (const time_t *); + +/** + * @ingroup time + * @par Description: + * This function shall convert the time in seconds since the Epoch pointed to by the argument + * into a broken-down time, expressed as a local time. + * + * @attention + *
        + *
      • Failure compared with standard, the error code is not seted.
      • + *
      + * + * @retval + * "struct tm*" On success, the function shall return a pointer to the broken-down time structure. + * On failure, this shall return a null pointer. + * + * @par Dependency: + *
      • time.h
      + * + * @see asctime | clock | ctime | difftime | gmtime | mktime | strftime | strptime | time | tzset | utime + * + */ +struct tm *localtime (const time_t *); + +/** + * @ingroup time + * @par Description: + * This function shall convert the broken-down time in the structure pointed to by the argument into a string in the form:\n + * Sun Sep 16 01:03:52 1973\n\0. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval + * #char* On success, this function shall return a pointer to the string. On failure, it shall return NULL. + * + * @par Dependency: + *
      • time.h
      + * + * @see clock | ctime | difftime | gmtime | localtime | mktime | strftime | strptime | times | utime + * + */ +char *asctime (const struct tm *); + +/** + * @ingroup time + * @par Description: + * This function shall convert the time pointed to by the first argument, representing time in seconds since the Epoch, + * to local time in the form of a string. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval + * #char* The function returns the pointer returned by asctime() with that broken-down time as an argument. + * + * @par Dependency: + *
      • time.h
      + * + * @see asctime | clock | difftime | gmtime | localtime | mktime | strftime | strptime | time | utime + * + */ +char *ctime (const time_t *); +int timespec_get(struct timespec *, int); + +/** + * @ingroup localtime + * @brief Set Time Zone. + * + * @par Description: + * This API is used to set the time zone. + * + * @attention + *
        + *
      • When setting time zones, format is required to be "tzn[+/-]hh[:mm[:ss]][dzn]" .
      • + *
      + * + * @param buff The string point to the time zone going to be setting. + * + * @retval None + */ +void settimezone(const char *); + +/** + * @ingroup localtime + * @brief Disable daylight saving time. + * + * @par Description: + * This API is used to make daylight saving time useless. + * + * @param None. + * + * @retval None + */ +int dst_disable(VOID); + +/** + * @ingroup localtime + * @brief Enable daylight saving time.. + * + * @par Description: + * This API is used to configure daylight saving time. + * + * @attention + *
        + *
      • When config dst, The configuration format has strict requirements.
      • + *
      • The first configuration format for example "Feb-03 03:00:00"
      • + *
      • The second configuration format for example "Oct-1st-Fri 03:00:00"
      • + *
      • The abbreviations for the months are "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", + * "Sep", "Oct", "Nov", and "Dec".
      • + *
      • The abbreviations for the days of the week are "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", and "Sat".
      • + *
      • The abbreviations for the weeks of the month are "1st", "2nd", "3rd", "4th", "5th"
      • + *
      • When it's only four weekdays this month, the effect of "5th" is the same as "Last"
      • + *
      + * + * @param dstStartTime The string point to the DST start going to be setting. + * @param dstEndTime The string point to the DST end going to be setting. + * @param forwardSeconds Indicates the number of seconds that time is allocated when entering DST interval. + * + * @retval 0 Succeed. + * @retval -1 Failed. + */ +int dst_enable(const char *dstStartTime, const char *dstEndTime, int forwardSeconds); + +/** + * @ingroup localtime + * @brief Inquire daylight saving time. + * + * @par Description: + * This API is used to inquire daylight saving time. + * + * @param year Represents the year to query start from 1900. + * @param dstStart Used to store daylight savings time start time + * @param dstEnd Used to store daylight savings time end time + * + * @retval 0 Succeed. + * @retval -1 Failed. + */ +int dst_inquire(int year, struct tm *dstStart, struct tm *dstEnd); + + +#define CLOCKS_PER_SEC 1000000L + +#define TIME_UTC 1 + +#if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \ + || defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) \ + || defined(_BSD_SOURCE) + +size_t strftime_l (char * __restrict, size_t, const char * __restrict, const struct tm * __restrict, locale_t); + +/** + * @ingroup time + * @par Description: + * This function convert the time in seconds since the Epoch pointed to by the first argument into + * a broken-down time expressed as Coordinated Universal Time (UTC). The broken-down time is stored + * in the structure referred to by the second argument. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval + * "struct tm*" On success, this function returns the address of the structure pointed to by the second argument. + * On failure, it shall return a null pointer. + * + * @par Dependency: + *
      • time.h
      + * + * @see asctime | clock | ctime | difftime | localtime | mktime | strftime | strptime | time | utime + * + */ +struct tm *gmtime_r (const time_t *__restrict, struct tm *__restrict); + +/** + * @ingroup time + * @par Description: + * This function shall convert the time in seconds since the Epoch pointed to by timer into + * a broken-down time stored in the structure to which the second argument points. + * + * @attention + *
        + *
      • Failure compared with standard, the error code is not seted.
      • + *
      + * + * @retval + * "struct tm*" On success, the function shall return a pointer to the structure pointed to by the second argument. + * On failure, this shall return a null pointer. + * + * @par Dependency: + *
      • time.h
      + * + * @see asctime | clock | ctime | difftime | gmtime | mktime | strftime | strptime | time | tzset | utime + * + */ +struct tm *localtime_r (const time_t *__restrict, struct tm *__restrict); + +/** + * @ingroup time + * @par Description: + * This function shall convert the broken-down time in the structure pointed to by first argument into a string. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval + * #char* On success, this function shall return a pointer to a character string containing the date and time. + * This string is pointed to by the second argument. On failure, it shall return NULL. + * + * @par Dependency: + *
      • time.h
      + * + * @see clock | ctime | difftime | gmtime | localtime | mktime | strftime | strptime | times | utime + * + */ +char *asctime_r (const struct tm *__restrict, char *__restrict); + +/** + * @ingroup time + * @par Description: + * This function shall convert the calendar time pointed to by the first argument to local time in + * exactly the same form as ctime() and put the string into the array pointed to by the second argument + * (which shall be at least 26 bytes in size). + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval + * #char* On success, the function returns a pointer to the string pointed to by second argument. + * On failure, a null pointer shall be returned. + * + * @par Dependency: + *
      • time.h
      + * + * @see asctime | clock | difftime | gmtime | localtime | mktime | strftime | strptime | time | utime + * + */ +char *ctime_r (const time_t *, char *); + +/** + * @ingroup time + * @par Description: + * This function uses the value of the environment variable TZ to set time conversion information used + * by ctime, localtime, mktime, and strftime. If TZ is absent from the environment, implementation-defined default + * timezone information shall be used.. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval + * None + * + * @par Dependency: + *
      • time.h
      + * + * @see ctime | localtime | mktime | strftime + * + */ +void tzset (void); + +struct itimerspec { + struct timespec it_interval; + struct timespec it_value; +}; + +#ifdef __LITEOS__ +#define MAX_CLOCKS 16 +#endif +#define CLOCK_REALTIME 0 +#define CLOCK_MONOTONIC 1 +#define CLOCK_PROCESS_CPUTIME_ID 2 +#define CLOCK_THREAD_CPUTIME_ID 3 +#define CLOCK_MONOTONIC_RAW 4 +#define CLOCK_REALTIME_COARSE 5 +#define CLOCK_MONOTONIC_COARSE 6 +#define CLOCK_BOOTTIME 7 +#define CLOCK_REALTIME_ALARM 8 +#define CLOCK_BOOTTIME_ALARM 9 +#define CLOCK_SGI_CYCLE 10 +#define CLOCK_TAI 11 + +#define TIMER_ABSTIME 1 + +/** + * @ingroup time + * @par Description: + * This function shall cause the current thread to be suspended from execution + * until either the time interval specified by the first argument has elapsed. + * + * @attention + *
        + *
      • The second argument is unused.
      • + *
      • Tasks will not be awakened, if the requested time does not has elapsed
      • + *
      + * + * @retval #0 The function is executed successfully. + * @retval #-1 The function failed to execute, and corresponding error code is set. + * + * @par Errors + *
        + *
      • EINVAL: An invalid input.
      • + *
      + * + * @par Dependency: + *
      • time.h
      + * + * @see sleep + * + */ +int nanosleep (const struct timespec *, struct timespec *); + +/** + * @ingroup time + * @par Description: + * This function finds the resolution (precision) of the specified clock, and, if the second argument is non-NULL, stores it in the + * struct timespec pointed to by the second argument. + * + * @attention + *
        + *
      • The first argument of value only supports CLOCK_REALTIME.
      • + *
      + * + * @retval #0 The function is executed successfully. + * @retval #-1 The function failed to execute, and corresponding error code is set. + * + * @par Errors + *
        + *
      • EINVAL: An invalid input.
      • + *
      + * + * @par Dependency: + *
      • time.h
      + * + * @see gettimeofday | settimeofday | time | adjtime | ctime + * + */ +int clock_getres (clockid_t, struct timespec *); + +/** + * @ingroup time + * @par Description: + * This function retrieves the time of the specified clock. + * + * @attention + *
        + *
      • The first argument of value only supports CLOCK_REALTIME.
      • + *
      + * + * @retval #0 The function is executed successfully. + * @retval #-1 The function failed to execute, and corresponding error code is set. + * + * @par Errors + *
        + *
      • EINVAL: An invalid input.
      • + *
      + * + * @par Dependency: + *
      • time.h
      + * + * @see gettimeofday | settimeofday | time | adjtime | ctime + * + */ +int clock_gettime (clockid_t, struct timespec *); + +/** + * @ingroup time + * @par Description: + * This function sets the time of the specified clock clk_id. + * + * @attention + *
        + *
      • The first argument of value only supports CLOCK_REALTIME.
      • + *
      + * + * @retval #0 The function is executed successfully. + * @retval #-1 The function failed to execute, and corresponding error code is set. + * + * @par Errors + *
        + *
      • EINVAL: An invalid input.
      • + *
      + * + * @par Dependency: + *
      • time.h
      + * + * @see gettimeofday | settimeofday | time | adjtime | ctime + * + */ +int clock_settime (clockid_t, const struct timespec *); +int clock_nanosleep (clockid_t, int, const struct timespec *, struct timespec *); +int clock_getcpuclockid (pid_t, clockid_t *); + +struct sigevent; + + +/** + * @ingroup time + * @par Description: + * This function creates a per-process timer using the specified clock, as the timing base. + * The function shall return, in the location referenced by the third argument, a timer ID + * of type timer_t used to identify the timer in timer requests. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #0 The function is executed successfully. + * @retval #-1 The function failed to execute, and corresponding error code is set. + * + * @par Errors + *
        + *
      • EINVAL: An invalid input.
      • + *
      • EAGAIN: Duplicate creation.
      • + *
      + * + * @par Dependency: + *
      • time.h
      + * + * @see clock_getres | timer_delete | timer_getoverrun + * + */ +int timer_create (clockid_t, struct sigevent *__restrict, timer_t *__restrict); + +/** + * @ingroup time + * @par Description: + * This function deletes the specified timer,previously created by the timer_create() function. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #0 The function is executed successfully. + * @retval #-1 The function failed to execute, and corresponding error code is set. + * + * @par Errors + *
        + *
      • EINVAL: An invalid input.
      • + *
      + * + * @par Dependency: + *
      • time.h
      + * + * @see timer_create + * + */ +int timer_delete (timer_t); + +/** + * @ingroup time + * @par Description: + * This function set the time until the next expiration of the timer specified by timerid from + * the it_value member of the third argument and arm the timer if the it_value member of value is non-zero. + * + * @attention + *
        + *
      • the second parameter is unused
      • + *
      + * + * @retval #0 The function is executed successfully. + * @retval #-1 The function failed to execute, and corresponding error code is set. + * + * @par Errors + *
        + *
      • EINVAL: An invalid input.
      • + *
      + * + * @par Dependency: + *
      • time.h
      + * + * @see clock_getres | timer_create + * + */ +int timer_settime (timer_t, int, const struct itimerspec *__restrict, struct itimerspec *__restrict); + +/** + * @ingroup time + * @par Description: + * This function shall store the amount of time until the specified timer, + * expires and the reload value of the timer into the space pointed to by the second argument. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #0 The function is executed successfully. + * @retval #-1 The function failed to execute, and corresponding error code is set. + * + * @par Errors + *
        + *
      • EINVAL: An invalid input.
      • + *
      + * + * @par Dependency: + *
      • time.h
      + * + * @see clock_getres | timer_create + * + */ +int timer_gettime (timer_t, struct itimerspec *); + +/** + * @ingroup time + * @par Description: + * This function shall get the timer expiration overrun count for the specified timer. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval + * #int On success, this function returns the timer expiration overrun count as explained above. + * On failure, -1 is returned. + * + * @par Errors + *
        + *
      • EINVAL: An invalid input.
      • + *
      + * + * @par Dependency: + *
      • time.h
      + * + * @see clock_getres | timer_create + * + */ +int timer_getoverrun (timer_t); + +extern char *tzname[2]; + +#endif + + +#if defined(_XOPEN_SOURCE) || defined(_BSD_SOURCE) || defined(_GNU_SOURCE) + +/** + * @ingroup time + * @par Description: + * This function converts the character string pointed to by the first argument to values which are stored in + * the tm structure pointed to by the third argument, using the format specified by the second argument. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval + * #char* On success, this function returns a pointer to the character following the last character parsed. + * On failure, a null pointer shall be returned. + * + * @par Dependency: + *
      • time.h
      + * + * @see fprintf | fscanf | strftime | time + * + */ +char *strptime (const char *__restrict, const char *__restrict, struct tm *__restrict); +extern int daylight; +extern long timezone; +extern int getdate_err; +struct tm *getdate (const char *); +#endif + + +#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE) + +/** + * @ingroup time + * @par Description: + * This function sets the system's idea of the time and date. The time, pointed to by t, is measured in seconds since the Epoch. + * + * @attention + *
        + *
      • There are no restrictions on the use of superusers.
      • + *
      + * + * @retval #0 The function is executed successfully. + * @retval #-1 The function failed to execute, and corresponding error code is set. + * + * @par Errors + *
        + *
      • EINVAL: An invalid input.
      • + *
      + * + * @par Dependency: + *
      • time.h
      + * + * @see settimeofday + * + */ +int stime(const time_t *); +time_t timegm(struct tm *); +#endif + +#ifndef __LITEOS__ +#if _REDIR_TIME64 +__REDIR(time, __time64); +__REDIR(difftime, __difftime64); +__REDIR(mktime, __mktime64); +__REDIR(gmtime, __gmtime64); +__REDIR(localtime, __localtime64); +__REDIR(ctime, __ctime64); +__REDIR(timespec_get, __timespec_get_time64); +#if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \ + || defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) \ + || defined(_BSD_SOURCE) +__REDIR(gmtime_r, __gmtime64_r); +__REDIR(localtime_r, __localtime64_r); +__REDIR(ctime_r, __ctime64_r); +__REDIR(nanosleep, __nanosleep_time64); +__REDIR(clock_getres, __clock_getres_time64); +__REDIR(clock_gettime, __clock_gettime64); +__REDIR(clock_settime, __clock_settime64); +__REDIR(clock_nanosleep, __clock_nanosleep_time64); +__REDIR(timer_settime, __timer_settime64); +__REDIR(timer_gettime, __timer_gettime64); +#endif +#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE) +__REDIR(stime, __stime64); +__REDIR(timegm, __timegm_time64); +#endif +#endif +#endif + +#ifdef __cplusplus +} +#endif + + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/uchar.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/uchar.h new file mode 100644 index 0000000000000000000000000000000000000000..7e5c4d4068949258ccede5c4911a3e816a2fc006 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/uchar.h @@ -0,0 +1,29 @@ +#ifndef _UCHAR_H +#define _UCHAR_H + +#ifdef __cplusplus +extern "C" { +#endif + +#if __cplusplus < 201103L +typedef unsigned short char16_t; +typedef unsigned char32_t; +#endif + +#define __NEED_mbstate_t +#define __NEED_size_t + +#include +#include + +size_t c16rtomb(char *__restrict, char16_t, mbstate_t *__restrict); +size_t mbrtoc16(char16_t *__restrict, const char *__restrict, size_t, mbstate_t *__restrict); + +size_t c32rtomb(char *__restrict, char32_t, mbstate_t *__restrict); +size_t mbrtoc32(char32_t *__restrict, const char *__restrict, size_t, mbstate_t *__restrict); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/ucontext.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/ucontext.h new file mode 100644 index 0000000000000000000000000000000000000000..0f75712548c3492f3257f661c973856bfe59dde4 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/ucontext.h @@ -0,0 +1,25 @@ +#ifndef _UCONTEXT_H +#define _UCONTEXT_H +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#include + +#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE) +#define NGREG (sizeof(gregset_t)/sizeof(greg_t)) +#endif + +struct __ucontext; + +int getcontext(struct __ucontext *); +void makecontext(struct __ucontext *, void (*)(), int, ...); +int setcontext(const struct __ucontext *); +int swapcontext(struct __ucontext *, const struct __ucontext *); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/ulimit.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/ulimit.h new file mode 100644 index 0000000000000000000000000000000000000000..efdcd311e5c74dffd2c6f4e809fd7c2e932bf754 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/ulimit.h @@ -0,0 +1,17 @@ +#ifndef _ULIMIT_H +#define _ULIMIT_H + +#ifdef __cplusplus +extern "C" { +#endif + +#define UL_GETFSIZE 1 +#define UL_SETFSIZE 2 + +long ulimit (int, ...); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/unistd.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/unistd.h new file mode 100644 index 0000000000000000000000000000000000000000..385f5116bebfc1f468cdeb4c114afcf858685aec --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/unistd.h @@ -0,0 +1,1087 @@ +/** + * @defgroup unistd Unistd + * @ingroup libc + */ + +#ifndef _UNISTD_H +#define _UNISTD_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#define STDIN_FILENO 0 +#define STDOUT_FILENO 1 +#define STDERR_FILENO 2 + +#define SEEK_SET 0 +#define SEEK_CUR 1 +#define SEEK_END 2 + +#ifdef __cplusplus +#define NULL 0L +#else +#ifndef NULL +#define NULL ((void*)0) +#endif +#endif + +#define __NEED_size_t +#define __NEED_ssize_t +#define __NEED_uid_t +#define __NEED_gid_t +#define __NEED_off_t +#define __NEED_pid_t +#define __NEED_intptr_t +#define __NEED_useconds_t +#ifdef __LITEOS__ +#define __NEED_int64_t +#endif + +#include + +int pipe(int [2]); +int pipe2(int [2], int); + +/** + * @ingroup unistd + * + * @par Description: + * The close() function shall close a file descriptor, so that it no longer refers to any file and may be reused. + * Any record locks held on the file it was associated with, and owned by the process, are removed. + * If fd is the last copy of a particular file descriptor the resources associated with it are freed; + * if the descriptor was the last reference to a file which has been removed using unlink() the file is deleted. + * + * @param __fd [IN] file descriptor to close. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #0 close file successful. + * @retval #-1 An error is encountered and close file failed. + * + * @par Errors + *
        + *
      • EBADF: The __fd argument is not a open file descriptor, or value is not within valid range.
      • + *
      • ENOENT: Can't find volume in fat or can't find internal node in jffs.
      • + *
      • EIO: A hard error occurred in the low level disk I/O layer or the physical drive cannot work.
      • + *
      • ENODEV: The partition of disk can't find.
      • + *
      • EPERM: Other errors.
      • + *
      + * + * @par Dependency: + *
      • unistd.h
      + * @see dup | fclose | fopen | ioctl | open | unlink + */ +int close(int); +int posix_close(int, int); + +/** + * @ingroup unistd + * + * @par Description: + * The dup() function shall duplicate an open file descriptor. It provides an alternative interface + * to the service provided by fcntl() using the F_DUPFD command. The call dup(fildes) shall be equivalent to: + * fcntl(fildes, F_DUPFD, 0); + * + * @param __oldfd [IN] file descriptor to duplicate. + * + * @attention + *
        + *
      • The dup() function doesn't support to duplicate a socket descriptor.
      • + *
      + * + * @retval #int A non-negative integer namely the file descriptor shall be returned upon successful completion. + * @retval #-1 An error is encountered and duplicate file descriptor failed. + * + * @par Errors + *
        + *
      • EBADF: __oldfd is not a valid open file descriptor, or it is a socket descriptor.
      • + *
      • ENOMEM: Out of memory.
      • + *
      • EMFILE: Too many open files and allocate a file descriptor failed.
      • + *
      • ENOENT: Can't find the inode by the pathname associated with __oldfd.
      • + *
      • ENOSYS: The current file system doesn't support the dup() function.
      • + *
      • ENODEV: The mount is not healthy.
      • + *
      + * + * @par Dependency: + *
      • unistd.h
      + * @see close | fcntl | open + */ +int dup(int); + +/** + * @ingroup unistd + * + * @par Description: + * The dup2() function shall cause the file descriptor __newfd to refer to the same open file description + * as the file descriptor __oldfd and to share any locks, and shall return __newfd. + * If __newfd is already a valid open file descriptor, it shall be closed first, unless __oldfd is equal to __newfd + * in which case dup2() shall return __newfd without closing it. + * + * @attention + *
        + *
      • The dup2() function doesn't support to clone a socket descriptor.
      • + *
      • If __newfd is already a valid opend descriptor, it shall be closed first, even if the file system doesn't + * support dup2().
      • + *
      + * + * @retval #int A non-negative integer namely the file descriptor shall be returned upon successful completion. + * @retval #-1 An error is encountered and duplicate file descriptor failed. + * + * @par Errors + *
        + *
      • EBADF: __oldfd is not a valid open file descriptor, or it is a socket descriptor.
      • + *
      • ENOMEM: Out of memory.
      • + *
      • ENOENT: Can't find the inode by the pathname associated with __oldfd.
      • + *
      • EINTR: The dup2() function was interrupted by a signal.
      • + *
      • ENOSYS: The current file system doesn't support the dup() function.
      • + *
      • ENODEV: The mount is not healthy or no such device.
      • + *
      • EIO: A hard error occurred in the low level disk I/O layer or the physical drive cannot work.
      • + *
      + * + * @par Dependency: + *
      • unistd.h
      + * @see close | fcntl | open + */ +int dup2(int, int); +int dup3(int, int, int); +off_t lseek(int, off_t, int); + +/** + * @ingroup unistd + * + * @par Description: + * The fsync() function shall request that all data for the open file descriptor named by fildes is to + * be transferred to the storage device associated with the file described by fildes. + * The nature of the transfer is implementation-defined. The fsync() function shall not return until + * the system has completed that action or until an error is detected. + * + * @param __fd [IN] An open file descriptor that refers to a device. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #int The fsync() function shall return 0 upon successful completion. + * Otherwise, the function shall return -1 and set errno. + * + * @par Errors + *
        + *
      • EBADF: The __fd argument is not a valid open file descriptor.
      • + *
      • ENOSYS: The function is not supported.
      • + *
      • EINVAL: The __fd argument is not valid for this device.
      • + *
      • ENOENT: The file can't found.
      • + *
      • ENODEV: The device is not existed.
      • + *
      • EACCES: The file permission is denied.
      • + *
      + * + * @par Dependency: + *
      • unistd.h
      + * @see sync + */ +int fsync(int); +int fdatasync(int); + +/** + * @ingroup unistd + * + * @par Description: + * The read() function shall attempt to read __count bytes from the file associated with the open file descriptor, + * __fd, into the buffer pointed to by __buf. + * + * @param __fd [IN] file descriptor (or socket descriptor) to read from + * @param __buf [IN/OUT] user-provided to save the data + * @param __count [IN] The maximum size of the user-provided buffer + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #ssize_t A positive non-zero number of bytes read on suceess. + * @retval #0 End-of-file. + * @retval #-1 On failure with errno set appropriately. + * + * @par Errors + *
        + *
      • EBADF: __fd is not a valid open file descriptor, or the file system doesn't support read().
      • + *
      • EFAULT: __buf is outside your accessible address space.
      • + *
      • EACCES: The file is a write-only file.
      • + *
      • EIO: A hard error occurred in the low level disk I/O layer or the physical drive cannot work.
      • + *
      • ENOMEM: Out of memory.
      • + *
      • EINVAL: __count is greater than {YAFFS_MAX_FILE_SIZE} in yaffs filesystem.
      • + *
      • ENODEV: The mount is not healthy.
      • + *
      + * + * @par Dependency: + *
      • unistd.h
      + * @see fcntl | ioctl | lseek | open | readv + */ +ssize_t read(int, void *, size_t); + +/** + * @ingroup unistd + * + * @par Description: + * The write() function shall attempt to write __count bytes from the buffer pointed to by __buf to the file + * associated with the open file descriptor, __fd. + * + * @param __fd [IN] file descriptor (or socket descriptor) to write to + * @param __buf [IN] Data to write + * @param __count [IN] Length of data to write + * + * @attention + *
        + *
      • On a regular file or other file capable of seeking, the actual writing of data shall proceed from the position + * in the file indicated by the file offset associated with fildes. Before successful return from write(), the file + * offset shall be incremented by the number of bytes actually written. On a regular file, if the position + * of the last byte written is greater than or equal to the length of the file, the length of the file shall be + * set to this position plus one.
      • + *
      • If the O_APPEND flag of the file status flags is set, the file offset shall be set to the end of the file + * prior to each write and no intervening file modification operation shall occur between changing the file offset + * and the write operation.
      • + *
      + * + * @retval #ssize_t On success, the number of bytes written are returned (zero indicates nothing was written). + * @retval #-1 On error, -1 is returned, and errno is set appropriately. + * + * @par Errors + *
        + *
      • EBADF: __fd is not a valid open file descriptor, or the file system doesn't support write().
      • + *
      • EFAULT: __buf is outside your accessible address space.
      • + *
      • EACCES/EROFS: The file is a read-only file or the file system is read-only.
      • + *
      • EIO: A physical I/O error has occurred.
      • + *
      • ENOMEM: Out of memory.
      • + *
      • EINTR: The write operation was terminated due to the receipt of a signal, no data was transferred.
      • + *
      • ENOSPC: There was no free space remaining on the device containing the file.
      • + *
      • EAGAIN: Non-blocking I/O has been selected using O_NONBLOCK and the write would block.
      • + *
      • EFBIG: An attempt was made to write a file that exceeds the implementation defined maximum file + * size or the process' file size limit, or to write at a position past the maximum allowed offset.
      • + *
      • EINVAL: The current position of file is less than zero.
      • + *
      • ENODEV: The mount is not healthy.
      • + *
      + * + * @par Dependency: + *
      • unistd.h
      + * @see fcntl | ioctl | lseek | open | readv + */ +ssize_t write(int, const void *, size_t); + +/** + * @ingroup unistd + * + * @par Description: + * The pread() function shall be equivalent to read(), except that it shall read from a given position in the file + * without changing the file offset. The first three arguments to pread() are the same as read() with the addition + * of a fourth argument __offset for the desired position inside the file. An attempt to perform a pread() on a file + * that is incapable of seeking shall result in an error. + * + * @param __fd [IN] file descriptor (or socket descriptor) to read from + * @param __buf [IN/OUT] user-provided to save the data + * @param __count [IN] The maximum size of the user-provided buffer + * @param __offset [IN] The file offset + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #ssize_t A positive non-zero number of bytes read on suceess. + * @retval #0 End-of-file. + * @retval #-1 On failure with errno set appropriately. + * + * @par Errors + *
        + *
      • EBADF: __fd is not a valid open file descriptor, or the file system doesn't support read().
      • + *
      • EFAULT: __buf is outside your accessible address space.
      • + *
      • EACCES: The file is a write-only file.
      • + *
      • EIO: A hard error occurred in the low level disk I/O layer or the physical drive cannot work.
      • + *
      • ENOMEM: Out of memory.
      • + *
      • EINVAL: __count is greater than {YAFFS_MAX_FILE_SIZE} in yaffs filesystem.
      • + *
      • ENODEV: The mount is not healthy.
      • + *
      + * + * @par Dependency: + *
      • unistd.h
      + * @see fcntl | ioctl | lseek | open | readv + */ +ssize_t pread(int, void *, size_t, off_t); + +/** + * @ingroup unistd + * + * @par Description: + * The pwrite() function shall be equivalent to write(), except that it writes into a given position + * and does not change the file offset (regardless of whether O_APPEND is set). The first three arguments to pwrite() + * are the same as write() with the addition of a fourth argument __offset for the desired position inside the file. + * An attempt to perform a pwrite() on a file that is incapable of seeking shall result in an error. + * + * @param __fd [IN] file descriptor (or socket descriptor) to write to + * @param __buf [IN] Data to write + * @param __count [IN] Length of data to write + * @param __offset [IN] The file offset to write from + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #ssize_t On success, the number of bytes written are returned (zero indicates nothing was written). + * @retval #-1 On error, -1 is returned, and errno is set appropriately. + * + * @par Errors + *
        + *
      • EBADF: __fd is not a valid open file descriptor, or the file system doesn't support write().
      • + *
      • EFAULT: __buf is outside your accessible address space.
      • + *
      • EACCES/EROFS: The file is a read-only file or the file system is read-only.
      • + *
      • EIO: A physical I/O error has occurred.
      • + *
      • ENOMEM: Out of memory.
      • + *
      • EINTR: The write operation was terminated due to the receipt of a signal, no data was transferred.
      • + *
      • ENOSPC: There was no free space remaining on the device containing the file.
      • + *
      • EAGAIN: Non-blocking I/O has been selected using O_NONBLOCK and the write would block.
      • + *
      • EFBIG: An attempt was made to write a file that exceeds the implementation defined maximum file + * size or the process' file size limit, or to write at a position past the maximum allowed offset.
      • + *
      • EINVAL: The current position of file is less than zero.
      • + *
      • ENODEV: The mount is not healthy.
      • + *
      + * + * @par Dependency: + *
      • unistd.h
      + * @see fcntl | ioctl | lseek | open | readv + */ +ssize_t pwrite(int, const void *, size_t, off_t); + +int chown(const char *, uid_t, gid_t); +int fchown(int, uid_t, gid_t); +int lchown(const char *, uid_t, gid_t); +int fchownat(int, const char *, uid_t, gid_t, int); + +int link(const char *, const char *); +int linkat(int, const char *, int, const char *, int); +int symlink(const char *, const char *); +int symlinkat(const char *, int, const char *); +ssize_t readlink(const char *__restrict, char *__restrict, size_t); +ssize_t readlinkat(int, const char *__restrict, char *__restrict, size_t); + +/** + * @ingroup unistd + * + * @par Description: + * The unlink() function shall remove a link to file. When the file's link count becomes 0 and no process + * has the file open, the space occupied by the file shall be freed and the file shall no longer be accessible. + * If one or more processes have the file open when the last link is removed, the link shall be removed before unlink() returns, + * but the removal of the file contents shall be postponed until all references to the file are closed. + * + * @param __path [IN] path of the file which need to be removed, shall not name a directory. + * + * @attention + *
        + *
      • If the unlink() function is called to remove a file in /dev, it shall just call the registered unlink hook function + * the file will still alive and won't be removed.
      • + *
      + * + * @retval #int Upon successful completion, these functions shall return 0. + * Otherwise, these functions shall return -1 and set errno to indicate the error. + * If -1 is returned, the named file shall not be changed. + * + * + * @par Errors + *
        + *
      • EACCES: Search permission is denied for a component of the path prefix, + * or write permission is denied on the directory containing the directory entry to be removed, + * or remove a file in /dev which doesn't register the unlink function.
      • + *
      • ENAMETOOLONG: The length of a component of a pathname is longer than {NAME_MAX}.
      • + *
      • ENOTEMPTY: unlink a pseudo-file which is functioning as a directory and the directory is not empty.
      • + *
      • ENOENT: A component of path does not name an existing file.
      • + *
      • EINVAL: The path is not valid.
      • + *
      • ENOMEM: Out of memory.
      • + *
      • EISDIR: The path is a directory.
      • + *
      + * + * @par Dependency: + *
      • unistd.h
      + * @see close | remove | rename | rmdir + */ +int unlink(const char *); +int unlinkat(int, const char *, int); + +/** + * @ingroup unistd + * + * @par Description: + * The rmdir() function shall remove a directory whose name is given by __path. + * The directory shall be removed only if it is an empty directory. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #0 Remove directory successful. + * @retval #-1 An error is encountered and remove the directory failed. + * + * @par Errors + *
        + *
      • EINVAL: The path is a null pointer or an empty string.
      • + *
      • ENAMETOOLONG: The length of a component of a pathname is longer than {NAME_MAX}.
      • + *
      • ENOENT: A component of the path does not exist.
      • + *
      • EPERM: The path represent a mount point, or the path is neither a directory nor a file.
      • + *
      • ENOTEMPTY: The path argument names a directory that is not an empty directory.
      • + *
      • ENOTDIR: A component of path names an existing file instead of a directory.
      • + *
      • ENODEV: The mount is not healthy.
      • + *
      • ENOMEM: Out of memory.
      • + *
      • EIO: A hard error occurred in the low level disk I/O layer or the physical drive cannot work.
      • + *
      • EROFS: The physical drive is write protected with fat filesystem.
      • + *
      • EACCES: The directory entry to be removed resides on a read-only file system, or remove a directory + * in proc.
      • + *
      • EBUSY: Remove a root of file system, or the directory is not empty of ramfs.
      • + *
      • ENOSYS +: The file system doesn't support to rmdir.
      • + *
      + * + * @par Dependency: + *
      • unistd.h
      + * @see mkdir | remove | rename | unlink + */ +int rmdir(const char *); +int truncate(const char *, off_t); + +/** + * @ingroup unistd + * + * @par Description: + * The ftruncate() function truncates the file size to the length bytes. + * If the file previously was larger than this size, the extra data is lost. + * If the file previously was shorter, it is extended, and the extended part reads as disk data. + * @attention + *
        + *
      • Now only FAT32 support this function.
      • + *
      + * + * @retval #int The ftruncate() function shall return 0 upon successful completion. + * Otherwise, the function shall return -1 and set errno. + * + * @par Errors + *
        + *
      • EBADF: The __fd argument is not a valid open file descriptor.
      • + *
      • ENOSYS: The function is not supported.
      • + *
      • EINVAL: The length argument was less than 0 or + * The length argument was greater than the maximum file size.
      • + *
      • EIO: A hard error occurred in the low level disk I/O layer or the physical drive cannot work.
      • + *
      • EACCES: The file permission is denied.
      • + *
      • ENODEV: The device is not existed.
      • + *
      + * + * @par Dependency: + *
      • unistd.h
      + * @see fallocate + */ +int ftruncate(int, off_t); + +#define F_OK 0 +#define R_OK 4 +#define W_OK 2 +#define X_OK 1 + +/** + * @ingroup unistd + * + * @par Description: + * The access() function shall check the file named by the pathname pointed to by the __path argument + * for accessibility according to the bit pattern contained in __mode. + * + * @param __path [IN] path of the file which need to be checked. + * @param __mode [IN] The value of __mode is either the bitwise-inclusive OR of the access permissions to be checked + * (R_OK, W_OK, X_OK) or the existence test (F_OK). + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #int The access() function shall return 0 upon successful completion. + * Otherwise, the function shall return -1 and set errno. + * + * @par Errors + *
        + *
      • EACCES: Permission bits of the file mode do not permit the requested access, + * or search permission is denied on a component of the path prefix.
      • + *
      • ENAMETOOLONG: The length of a component of a pathname is longer than {NAME_MAX}.
      • + *
      • EFAULT: Bad address.
      • + *
      • ENOENT: A component of the path does not exist, or the path is an empty string.
      • + *
      • ENOMEM: Out of memory.
      • + *
      • ENOTDIR: A component of the path is not a directory.
      • + *
      + * + * @par Dependency: + *
      • unistd.h
      + * @see None + */ +int access(const char *, int); +int faccessat(int, const char *, int, int); + +/** + * @ingroup unistd + * + * @par Description: + * The chdir() function shall cause the directory named by the pathname pointed to by the __path argument to become + * the current working directory; that is, the starting point for path searches for pathnames not beginning with '/'. + * + * @param __path [IN] path of the file which need to be set as the current working directory. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #int Upon successful completion, 0 shall be returned. + * Otherwise, -1 shall be returned, the current working directory shall remain unchanged, + * and errno shall be set to indicate the error. + * + * @par Errors + *
        + *
      • EINVAL: The path is an empty string.
      • + *
      • ENAMETOOLONG: The length of a component of a pathname is longer than {NAME_MAX}.
      • + *
      • ENOENT: A component of the path does not exist, + * or length of __path is longer than {PATH_MAX}.
      • + *
      • ENOMEM: Out of memory.
      • + *
      • ENOSPC: Out of memory in ramfs filesystem.
      • + *
      • ENOTDIR: A component of the path is not a directory.
      • + *
      • EMFILE: Too many open file.
      • + *
      • EROFS: The physical drive is write protected with fat filesystem.
      • + *
      • EIO: A hard error occurred in the low level disk I/O layer or the physical drive cannot work.
      • + *
      • ENODEV: The mount is not healthy.
      • + *
      • EPERM: Other errors.
      • + *
      + * + * @par Dependency: + *
      • unistd.h
      + * @see getcwd + */ +int chdir(const char *); +int fchdir(int); + +/** + * @ingroup unistd + * + * @par Description: + * The getcwd() function shall place an absolute pathname of the current working directory + * in the array pointed to by __buf, and return __buf. + * + * @param __buf [IN/OUT] Point to an array which place an absolute pathname of the current working directory and return. + * @param __size [IN] The size in bytes of the character array pointed to by the __buf argument. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #char* Return the __buf argument if upon successful completion. + * @retval #NULL An error is encountered and the contents of the array pointed to by __buf are undefined. + * + * @par Errors + *
        + *
      • EINVAL: The __buf is a NULL pointer.
      • + *
      • ERANGE: The size argument is smaller than the length of the current working directory name + 1.
      • + *
      • ENAMETOOLONG: Use memcpy_s to copy the current working directory name to __buf failed.
      • + *
      + * + * @par Dependency: + *
      • unistd.h
      + * @see malloc + */ +char *getcwd(char *, size_t); + +unsigned alarm(unsigned); + +/** + * @ingroup unistd + * + * @par Description: + * The sleep() function shall cause the calling thread to be suspended from execution until either the number of + * realtime seconds specified by the argument __seconds has elapsed or a signal is delivered to the calling thread + * and its action is to invoke a signal-catching function or to terminate the process. + * The suspension time may be longer than requested due to the scheduling of other activity by the system. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #0 The requested time has elapsed. + * @retval #unsigned int An error is encountered in LOS_TaskDelay() and the __seconds shall be returned. + * + * @par Dependency: + *
      • unistd.h
      + * @see nanosleep + */ +unsigned sleep(unsigned); +int pause(void); + +pid_t fork(void); +int execve(const char *, char *const [], char *const []); +int execv(const char *, char *const []); +int execle(const char *, const char *, ...); +int execl(const char *, const char *, ...); +int execvp(const char *, char *const []); +int execlp(const char *, const char *, ...); +int fexecve(int, char *const [], char *const []); +_Noreturn void _exit(int); + +/** + * @ingroup unistd + * + * @par Description: + * The getpid() function get the process ID of the calling process. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #int The getpid() function shall return the process ID of the calling process. + * @par Dependency: + *
      • unistd.h
      + * @see None + */ +pid_t getpid(void); +pid_t getppid(void); +pid_t getpgrp(void); +pid_t getpgid(pid_t); +int setpgid(pid_t, pid_t); +pid_t setsid(void); +pid_t getsid(pid_t); +char *ttyname(int); +int ttyname_r(int, char *, size_t); +int isatty(int); +pid_t tcgetpgrp(int); +int tcsetpgrp(int, pid_t); + +uid_t getuid(void); +uid_t geteuid(void); +gid_t getgid(void); +gid_t getegid(void); +int getgroups(int, gid_t []); +int setuid(uid_t); +int seteuid(uid_t); +int setgid(gid_t); +int setegid(gid_t); + +char *getlogin(void); +int getlogin_r(char *, size_t); +int gethostname(char *, size_t); +char *ctermid(char *); + +int getopt(int, char * const [], const char *); +extern char *optarg; +extern int optind, opterr, optopt; + +long pathconf(const char *, int); +long fpathconf(int, int); +long sysconf(int); +size_t confstr(int, char *, size_t); + +#if defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) || defined(_BSD_SOURCE) +#define F_ULOCK 0 +#define F_LOCK 1 +#define F_TLOCK 2 +#define F_TEST 3 +int setreuid(uid_t, uid_t); +int setregid(gid_t, gid_t); +int lockf(int, int, off_t); +long gethostid(void); +int nice(int); + +/** + * @ingroup unistd + * + * @par Description: + * The sync() function shall request that all data in bcache to be transferred to the storage device for disk 0 and 1. + * + * @attention + *
        + *
      • The sync() function in liteos can only flush all data in bcache into storage device, but can't flush + * the data in memory, and it shall not return until the system completed that action or until an error is detected. + * But in POSIX, The sync() function shall cause all information in memory that updates file systems to be scheduled + * for writing out to all file systems, and the writing, although scheduled, is not necessarily complete + * upon return from sync().
      • + *
      • The sync() function is only useful for fat filesystem and the bcache shall be enabled, + * other filesystems don't need to sync.
      • + *
      • The sync() function + *
      + * + * @retval #void None. + * + * @par Dependency: + *
      • unistd.h
      + * @see fsync + */ +void sync(void); +pid_t setpgrp(void); +char *crypt(const char *, const char *); +void encrypt(char *, int); +void swab(const void *__restrict, void *__restrict, ssize_t); +#endif + +#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE) \ + || (defined(_XOPEN_SOURCE) && _XOPEN_SOURCE+0 < 700) + +/** + * @ingroup unistd + * + * @par Description: + * The usleep() function shall cause the calling thread to be suspended from execution until either the number of + * microsecond specified by the argument __usec has elapsed or a signal is delivered to the calling thread + * and its action is to invoke a signal-catching function or to terminate the process. + * The suspension time may be longer than requested due to the scheduling of other activity by the system. + * + * @attention + *
        + *
      • If __usec is less than per Millisecond and is not equal to zero, + * the suspended time shall be set to 1 millisecond.
      • + *
      • The realtime to sleep is __usec/1000 millisecond.
      • + *
      + * + * @retval #0 The requested time has elapsed. + * @retval #-1 An error is encountered in LOS_TaskDelay(). + * + * @par Dependency: + *
      • unistd.h
      + * @see sleep + */ +int usleep(unsigned); +unsigned ualarm(unsigned, unsigned); +#endif + +#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE) +#define L_SET 0 +#define L_INCR 1 +#define L_XTND 2 +int brk(void *); +void *sbrk(intptr_t); +pid_t vfork(void); +int vhangup(void); +int chroot(const char *); +int getpagesize(void); +int getdtablesize(void); +int sethostname(const char *, size_t); +int getdomainname(char *, size_t); +int setdomainname(const char *, size_t); +int setgroups(size_t, const gid_t *); +char *getpass(const char *); +int daemon(int, int); +void setusershell(void); +void endusershell(void); +char *getusershell(void); +int acct(const char *); +long syscall(long, ...); +int execvpe(const char *, char *const [], char *const []); +int issetugid(void); +int getentropy(void *, size_t); +extern int optreset; +#endif + +#ifdef _GNU_SOURCE +extern char **environ; +int setresuid(uid_t, uid_t, uid_t); +int setresgid(gid_t, gid_t, gid_t); +int getresuid(uid_t *, uid_t *, uid_t *); +int getresgid(gid_t *, gid_t *, gid_t *); +char *get_current_dir_name(void); +int syncfs(int); +int euidaccess(const char *, int); +int eaccess(const char *, int); +ssize_t copy_file_range(int, off_t *, int, off_t *, size_t, unsigned); +#endif + +#if defined(_LARGEFILE64_SOURCE) || defined(_GNU_SOURCE) +#ifdef __LITEOS__ +#define off64_t int64_t +off64_t lseek64(int, off64_t, int); +ssize_t pread64(int, void *, size_t, off64_t); +ssize_t pwrite64(int, const void *, size_t, off64_t); +int truncate64(const char *, off64_t); +int ftruncate64(int, off64_t); +int lockf64(int, int, off64_t); +#else +#define lseek64 lseek +#define pread64 pread +#define pwrite64 pwrite +#define truncate64 truncate +#define ftruncate64 ftruncate +#define lockf64 lockf +#define off64_t off_t +#endif +#endif + +#define POSIX_CLOSE_RESTART 0 + +#define _XOPEN_VERSION 700 +#define _XOPEN_UNIX 1 +#define _XOPEN_ENH_I18N 1 + +#define _POSIX_VERSION 200809L +#define _POSIX2_VERSION _POSIX_VERSION + +#define _POSIX_ADVISORY_INFO _POSIX_VERSION +#define _POSIX_CHOWN_RESTRICTED 1 +#define _POSIX_IPV6 _POSIX_VERSION +#define _POSIX_JOB_CONTROL 1 +#define _POSIX_MAPPED_FILES _POSIX_VERSION +#define _POSIX_MEMLOCK _POSIX_VERSION +#define _POSIX_MEMLOCK_RANGE _POSIX_VERSION +#define _POSIX_MEMORY_PROTECTION _POSIX_VERSION +#define _POSIX_MESSAGE_PASSING _POSIX_VERSION +#define _POSIX_FSYNC _POSIX_VERSION +#define _POSIX_NO_TRUNC 1 +#define _POSIX_RAW_SOCKETS _POSIX_VERSION +#define _POSIX_REALTIME_SIGNALS _POSIX_VERSION +#define _POSIX_REGEXP 1 +#define _POSIX_SAVED_IDS 1 +#define _POSIX_SHELL 1 +#define _POSIX_SPAWN _POSIX_VERSION +#define _POSIX_VDISABLE 0 + +#define _POSIX_THREADS _POSIX_VERSION +#define _POSIX_THREAD_PROCESS_SHARED _POSIX_VERSION +#define _POSIX_THREAD_SAFE_FUNCTIONS _POSIX_VERSION +#define _POSIX_THREAD_ATTR_STACKADDR _POSIX_VERSION +#define _POSIX_THREAD_ATTR_STACKSIZE _POSIX_VERSION +#define _POSIX_THREAD_PRIORITY_SCHEDULING _POSIX_VERSION +#define _POSIX_THREAD_CPUTIME _POSIX_VERSION +#define _POSIX_TIMERS _POSIX_VERSION +#define _POSIX_TIMEOUTS _POSIX_VERSION +#define _POSIX_MONOTONIC_CLOCK _POSIX_VERSION +#define _POSIX_CPUTIME _POSIX_VERSION +#define _POSIX_CLOCK_SELECTION _POSIX_VERSION +#define _POSIX_BARRIERS _POSIX_VERSION +#define _POSIX_SPIN_LOCKS _POSIX_VERSION +#define _POSIX_READER_WRITER_LOCKS _POSIX_VERSION +#define _POSIX_ASYNCHRONOUS_IO _POSIX_VERSION +#define _POSIX_SEMAPHORES _POSIX_VERSION +#define _POSIX_SHARED_MEMORY_OBJECTS _POSIX_VERSION + +#define _POSIX2_C_BIND _POSIX_VERSION + +#include + + + +#define _PC_LINK_MAX 0 +#define _PC_MAX_CANON 1 +#define _PC_MAX_INPUT 2 +#define _PC_NAME_MAX 3 +#define _PC_PATH_MAX 4 +#define _PC_PIPE_BUF 5 +#define _PC_CHOWN_RESTRICTED 6 +#define _PC_NO_TRUNC 7 +#define _PC_VDISABLE 8 +#define _PC_SYNC_IO 9 +#define _PC_ASYNC_IO 10 +#define _PC_PRIO_IO 11 +#define _PC_SOCK_MAXBUF 12 +#define _PC_FILESIZEBITS 13 +#define _PC_REC_INCR_XFER_SIZE 14 +#define _PC_REC_MAX_XFER_SIZE 15 +#define _PC_REC_MIN_XFER_SIZE 16 +#define _PC_REC_XFER_ALIGN 17 +#define _PC_ALLOC_SIZE_MIN 18 +#define _PC_SYMLINK_MAX 19 +#define _PC_2_SYMLINKS 20 + +#define _SC_ARG_MAX 0 +#define _SC_CHILD_MAX 1 +#define _SC_CLK_TCK 2 +#define _SC_NGROUPS_MAX 3 +#define _SC_OPEN_MAX 4 +#define _SC_STREAM_MAX 5 +#define _SC_TZNAME_MAX 6 +#define _SC_JOB_CONTROL 7 +#define _SC_SAVED_IDS 8 +#define _SC_REALTIME_SIGNALS 9 +#define _SC_PRIORITY_SCHEDULING 10 +#define _SC_TIMERS 11 +#define _SC_ASYNCHRONOUS_IO 12 +#define _SC_PRIORITIZED_IO 13 +#define _SC_SYNCHRONIZED_IO 14 +#define _SC_FSYNC 15 +#define _SC_MAPPED_FILES 16 +#define _SC_MEMLOCK 17 +#define _SC_MEMLOCK_RANGE 18 +#define _SC_MEMORY_PROTECTION 19 +#define _SC_MESSAGE_PASSING 20 +#define _SC_SEMAPHORES 21 +#define _SC_SHARED_MEMORY_OBJECTS 22 +#define _SC_AIO_LISTIO_MAX 23 +#define _SC_AIO_MAX 24 +#define _SC_AIO_PRIO_DELTA_MAX 25 +#define _SC_DELAYTIMER_MAX 26 +#define _SC_MQ_OPEN_MAX 27 +#define _SC_MQ_PRIO_MAX 28 +#define _SC_VERSION 29 +#define _SC_PAGE_SIZE 30 +#define _SC_PAGESIZE 30 /* !! */ +#define _SC_RTSIG_MAX 31 +#define _SC_SEM_NSEMS_MAX 32 +#define _SC_SEM_VALUE_MAX 33 +#define _SC_SIGQUEUE_MAX 34 +#define _SC_TIMER_MAX 35 +#define _SC_BC_BASE_MAX 36 +#define _SC_BC_DIM_MAX 37 +#define _SC_BC_SCALE_MAX 38 +#define _SC_BC_STRING_MAX 39 +#define _SC_COLL_WEIGHTS_MAX 40 +#define _SC_EXPR_NEST_MAX 42 +#define _SC_LINE_MAX 43 +#define _SC_RE_DUP_MAX 44 +#define _SC_2_VERSION 46 +#define _SC_2_C_BIND 47 +#define _SC_2_C_DEV 48 +#define _SC_2_FORT_DEV 49 +#define _SC_2_FORT_RUN 50 +#define _SC_2_SW_DEV 51 +#define _SC_2_LOCALEDEF 52 +#define _SC_UIO_MAXIOV 60 /* !! */ +#define _SC_IOV_MAX 60 +#define _SC_THREADS 67 +#define _SC_THREAD_SAFE_FUNCTIONS 68 +#define _SC_GETGR_R_SIZE_MAX 69 +#define _SC_GETPW_R_SIZE_MAX 70 +#define _SC_LOGIN_NAME_MAX 71 +#define _SC_TTY_NAME_MAX 72 +#define _SC_THREAD_DESTRUCTOR_ITERATIONS 73 +#define _SC_THREAD_KEYS_MAX 74 +#define _SC_THREAD_STACK_MIN 75 +#define _SC_THREAD_THREADS_MAX 76 +#define _SC_THREAD_ATTR_STACKADDR 77 +#define _SC_THREAD_ATTR_STACKSIZE 78 +#define _SC_THREAD_PRIORITY_SCHEDULING 79 +#define _SC_THREAD_PRIO_INHERIT 80 +#define _SC_THREAD_PRIO_PROTECT 81 +#define _SC_THREAD_PROCESS_SHARED 82 +#define _SC_NPROCESSORS_CONF 83 +#define _SC_NPROCESSORS_ONLN 84 +#define _SC_PHYS_PAGES 85 +#define _SC_AVPHYS_PAGES 86 +#define _SC_ATEXIT_MAX 87 +#define _SC_PASS_MAX 88 +#define _SC_XOPEN_VERSION 89 +#define _SC_XOPEN_XCU_VERSION 90 +#define _SC_XOPEN_UNIX 91 +#define _SC_XOPEN_CRYPT 92 +#define _SC_XOPEN_ENH_I18N 93 +#define _SC_XOPEN_SHM 94 +#define _SC_2_CHAR_TERM 95 +#define _SC_2_UPE 97 +#define _SC_XOPEN_XPG2 98 +#define _SC_XOPEN_XPG3 99 +#define _SC_XOPEN_XPG4 100 +#define _SC_NZERO 109 +#define _SC_XBS5_ILP32_OFF32 125 +#define _SC_XBS5_ILP32_OFFBIG 126 +#define _SC_XBS5_LP64_OFF64 127 +#define _SC_XBS5_LPBIG_OFFBIG 128 +#define _SC_XOPEN_LEGACY 129 +#define _SC_XOPEN_REALTIME 130 +#define _SC_XOPEN_REALTIME_THREADS 131 +#define _SC_ADVISORY_INFO 132 +#define _SC_BARRIERS 133 +#define _SC_CLOCK_SELECTION 137 +#define _SC_CPUTIME 138 +#define _SC_THREAD_CPUTIME 139 +#define _SC_MONOTONIC_CLOCK 149 +#define _SC_READER_WRITER_LOCKS 153 +#define _SC_SPIN_LOCKS 154 +#define _SC_REGEXP 155 +#define _SC_SHELL 157 +#define _SC_SPAWN 159 +#define _SC_SPORADIC_SERVER 160 +#define _SC_THREAD_SPORADIC_SERVER 161 +#define _SC_TIMEOUTS 164 +#define _SC_TYPED_MEMORY_OBJECTS 165 +#define _SC_2_PBS 168 +#define _SC_2_PBS_ACCOUNTING 169 +#define _SC_2_PBS_LOCATE 170 +#define _SC_2_PBS_MESSAGE 171 +#define _SC_2_PBS_TRACK 172 +#define _SC_SYMLOOP_MAX 173 +#define _SC_STREAMS 174 +#define _SC_2_PBS_CHECKPOINT 175 +#define _SC_V6_ILP32_OFF32 176 +#define _SC_V6_ILP32_OFFBIG 177 +#define _SC_V6_LP64_OFF64 178 +#define _SC_V6_LPBIG_OFFBIG 179 +#define _SC_HOST_NAME_MAX 180 +#define _SC_TRACE 181 +#define _SC_TRACE_EVENT_FILTER 182 +#define _SC_TRACE_INHERIT 183 +#define _SC_TRACE_LOG 184 + +#define _SC_IPV6 235 +#define _SC_RAW_SOCKETS 236 +#define _SC_V7_ILP32_OFF32 237 +#define _SC_V7_ILP32_OFFBIG 238 +#define _SC_V7_LP64_OFF64 239 +#define _SC_V7_LPBIG_OFFBIG 240 +#define _SC_SS_REPL_MAX 241 +#define _SC_TRACE_EVENT_NAME_MAX 242 +#define _SC_TRACE_NAME_MAX 243 +#define _SC_TRACE_SYS_MAX 244 +#define _SC_TRACE_USER_EVENT_MAX 245 +#define _SC_XOPEN_STREAMS 246 +#define _SC_THREAD_ROBUST_PRIO_INHERIT 247 +#define _SC_THREAD_ROBUST_PRIO_PROTECT 248 + +#define _CS_PATH 0 +#define _CS_POSIX_V6_WIDTH_RESTRICTED_ENVS 1 +#define _CS_GNU_LIBC_VERSION 2 +#define _CS_GNU_LIBPTHREAD_VERSION 3 +#define _CS_POSIX_V5_WIDTH_RESTRICTED_ENVS 4 +#define _CS_POSIX_V7_WIDTH_RESTRICTED_ENVS 5 + +#define _CS_POSIX_V6_ILP32_OFF32_CFLAGS 1116 +#define _CS_POSIX_V6_ILP32_OFF32_LDFLAGS 1117 +#define _CS_POSIX_V6_ILP32_OFF32_LIBS 1118 +#define _CS_POSIX_V6_ILP32_OFF32_LINTFLAGS 1119 +#define _CS_POSIX_V6_ILP32_OFFBIG_CFLAGS 1120 +#define _CS_POSIX_V6_ILP32_OFFBIG_LDFLAGS 1121 +#define _CS_POSIX_V6_ILP32_OFFBIG_LIBS 1122 +#define _CS_POSIX_V6_ILP32_OFFBIG_LINTFLAGS 1123 +#define _CS_POSIX_V6_LP64_OFF64_CFLAGS 1124 +#define _CS_POSIX_V6_LP64_OFF64_LDFLAGS 1125 +#define _CS_POSIX_V6_LP64_OFF64_LIBS 1126 +#define _CS_POSIX_V6_LP64_OFF64_LINTFLAGS 1127 +#define _CS_POSIX_V6_LPBIG_OFFBIG_CFLAGS 1128 +#define _CS_POSIX_V6_LPBIG_OFFBIG_LDFLAGS 1129 +#define _CS_POSIX_V6_LPBIG_OFFBIG_LIBS 1130 +#define _CS_POSIX_V6_LPBIG_OFFBIG_LINTFLAGS 1131 +#define _CS_POSIX_V7_ILP32_OFF32_CFLAGS 1132 +#define _CS_POSIX_V7_ILP32_OFF32_LDFLAGS 1133 +#define _CS_POSIX_V7_ILP32_OFF32_LIBS 1134 +#define _CS_POSIX_V7_ILP32_OFF32_LINTFLAGS 1135 +#define _CS_POSIX_V7_ILP32_OFFBIG_CFLAGS 1136 +#define _CS_POSIX_V7_ILP32_OFFBIG_LDFLAGS 1137 +#define _CS_POSIX_V7_ILP32_OFFBIG_LIBS 1138 +#define _CS_POSIX_V7_ILP32_OFFBIG_LINTFLAGS 1139 +#define _CS_POSIX_V7_LP64_OFF64_CFLAGS 1140 +#define _CS_POSIX_V7_LP64_OFF64_LDFLAGS 1141 +#define _CS_POSIX_V7_LP64_OFF64_LIBS 1142 +#define _CS_POSIX_V7_LP64_OFF64_LINTFLAGS 1143 +#define _CS_POSIX_V7_LPBIG_OFFBIG_CFLAGS 1144 +#define _CS_POSIX_V7_LPBIG_OFFBIG_LDFLAGS 1145 +#define _CS_POSIX_V7_LPBIG_OFFBIG_LIBS 1146 +#define _CS_POSIX_V7_LPBIG_OFFBIG_LINTFLAGS 1147 +#define _CS_V6_ENV 1148 +#define _CS_V7_ENV 1149 + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/utime.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/utime.h new file mode 100644 index 0000000000000000000000000000000000000000..f368c3ee9302327af511f5f1d7170f9b31d5ef9b --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/utime.h @@ -0,0 +1,67 @@ +/** + * @defgroup utime Utime + * @ingroup libc + */ + +#ifndef _UTIME_H +#define _UTIME_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#define __NEED_time_t + +#include + +struct utimbuf { + time_t actime; + time_t modtime; +}; + +/** + * @ingroup utime + * + * @par Description: + * The utime() function shall set the modification times of the file named by the path argument. + * If ptimes is a null pointer, the modification times of the file shall be set to the current time. + * If ptimes is not a null pointer, times shall be interpreted as a pointer to a utimbuf structure and + * modification times shall be set to the values contained in the designated structure. + * + * @attention + *
        + *
      • The utime() doesn't support to set access time.
      • + *
      • Now only fat filesystem support this function.
      • + *
      + * + * @retval #0 On success. + * @retval #-1 On failure with errno set. + * + * @par Errors + *
        + *
      • EINVAL: The path is a null pointer or the ptimes is a invalid value.
      • + *
      • ENAMETOOLONG: The length of a component of a pathname is longer than {NAME_MAX}.
      • + *
      • ENOENT: A component of the path does not exist.
      • + *
      • ENOSYS: The file system doesn't support this function.
      • + *
      • EACCES: It is a read-only file system.
      • + *
      • ENOMEM: Out of memory.
      • + *
      • EIO: A hard error occurred in the low level disk I/O layer or the physical drive cannot work.
      • + *
      + * + * @par Dependency: + *
      • utime.h
      + * @see fstat + */ +int utime (const char *, const struct utimbuf *); + +#if _REDIR_TIME64 +__REDIR(utime, __utime64); +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/utmp.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/utmp.h new file mode 100644 index 0000000000000000000000000000000000000000..48a400d84dec3d17db76831b2036ba41cfe2ab2b --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/utmp.h @@ -0,0 +1,52 @@ +#ifndef _UTMP_H +#define _UTMP_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#define ACCOUNTING 9 +#define UT_NAMESIZE 32 +#define UT_HOSTSIZE 256 +#define UT_LINESIZE 32 + +struct lastlog { + time_t ll_time; + char ll_line[UT_LINESIZE]; + char ll_host[UT_HOSTSIZE]; +}; + +#define ut_time ut_tv.tv_sec +#define ut_name ut_user +#define ut_addr ut_addr_v6[0] +#define utmp utmpx +#define e_exit __e_exit +#define e_termination __e_termination + +void endutent(void); +struct utmp *getutent(void); +struct utmp *getutid(const struct utmp *); +struct utmp *getutline(const struct utmp *); +struct utmp *pututline(const struct utmp *); +void setutent(void); + +void updwtmp(const char *, const struct utmp *); +int utmpname(const char *); + +int login_tty(int); + +#define _PATH_UTMP "/dev/null/utmp" +#define _PATH_WTMP "/dev/null/wtmp" + +#define UTMP_FILE _PATH_UTMP +#define WTMP_FILE _PATH_WTMP +#define UTMP_FILENAME _PATH_UTMP +#define WTMP_FILENAME _PATH_WTMP + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/utmpx.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/utmpx.h new file mode 100644 index 0000000000000000000000000000000000000000..b293f427e6b0d5acbf0f870110e326b2f7ff8d2f --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/utmpx.h @@ -0,0 +1,67 @@ +#ifndef _UTMPX_H +#define _UTMPX_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#define __NEED_pid_t +#define __NEED_time_t +#define __NEED_suseconds_t +#define __NEED_struct_timeval + +#include + +struct utmpx { + short ut_type; + short __ut_pad1; + pid_t ut_pid; + char ut_line[32]; + char ut_id[4]; + char ut_user[32]; + char ut_host[256]; + struct { + short __e_termination; + short __e_exit; + } ut_exit; +#if __BYTE_ORDER == 1234 + int ut_session, __ut_pad2; +#else + int __ut_pad2, ut_session; +#endif + struct timeval ut_tv; + unsigned ut_addr_v6[4]; + char __unused[20]; +}; + +void endutxent(void); +struct utmpx *getutxent(void); +struct utmpx *getutxid(const struct utmpx *); +struct utmpx *getutxline(const struct utmpx *); +struct utmpx *pututxline(const struct utmpx *); +void setutxent(void); + +#if defined(_BSD_SOURCE) || defined(_GNU_SOURCE) +#define e_exit __e_exit +#define e_termination __e_termination +void updwtmpx(const char *, const struct utmpx *); +int utmpxname(const char *); +#endif + +#define EMPTY 0 +#define RUN_LVL 1 +#define BOOT_TIME 2 +#define NEW_TIME 3 +#define OLD_TIME 4 +#define INIT_PROCESS 5 +#define LOGIN_PROCESS 6 +#define USER_PROCESS 7 +#define DEAD_PROCESS 8 + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/values.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/values.h new file mode 100644 index 0000000000000000000000000000000000000000..fe4949f85ea7f8c7df426c4d1da2a2ded68434c9 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/values.h @@ -0,0 +1,39 @@ +#ifndef _VALUES_H +#define _VALUES_H + +#include + +#define CHARBITS (sizeof(char) * 8) +#define SHORTBITS (sizeof(short) * 8) +#define INTBITS (sizeof(int) * 8) +#define LONGBITS (sizeof(long) * 8) +#define PTRBITS (sizeof(char *) * 8) +#define DOUBLEBITS (sizeof(double) * 8) +#define FLOATBITS (sizeof(float) * 8) + +#define MINSHORT SHRT_MIN +#define MININT INT_MIN +#define MINLONG LONG_MIN + +#define MAXSHORT SHRT_MAX +#define MAXINT INT_MAX +#define MAXLONG LONG_MAX + +#define HIBITS MINSHORT +#define HIBITL MINLONG + +#include + +#define MAXDOUBLE DBL_MAX +#undef MAXFLOAT +#define MAXFLOAT FLT_MAX +#define MINDOUBLE DBL_MIN +#define MINFLOAT FLT_MIN +#define DMINEXP DBL_MIN_EXP +#define FMINEXP FLT_MIN_EXP +#define DMAXEXP DBL_MAX_EXP +#define FMAXEXP FLT_MAX_EXP + +#define BITSPERBYTE CHAR_BIT + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/wait.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/wait.h new file mode 100644 index 0000000000000000000000000000000000000000..98396e2d20bafada0bf4b0f102c300fd6fa62874 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/wait.h @@ -0,0 +1,2 @@ +#warning redirecting incorrect #include to +#include diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/wchar.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/wchar.h new file mode 100644 index 0000000000000000000000000000000000000000..7444064036a4a8facea0f914065a31e1af95df75 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/wchar.h @@ -0,0 +1,956 @@ +/** + * @defgroup wchar Wchar + * @ingroup libc + */ + +#ifndef _WCHAR_H +#define _WCHAR_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#define __NEED_FILE +#define __NEED___isoc_va_list +#define __NEED_size_t +#define __NEED_wchar_t +#define __NEED_wint_t +#define __NEED_mbstate_t + +#if __STDC_VERSION__ < 201112L +#define __NEED_struct__IO_FILE +#endif + +#if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \ + || defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) || defined(_BSD_SOURCE) +#define __NEED_locale_t +#define __NEED_va_list +#endif + +#if defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) || defined(_BSD_SOURCE) +#define __NEED_wctype_t +#endif + +#include + +#if L'\0'-1 > 0 +#define WCHAR_MAX (0xffffffffu+L'\0') +#define WCHAR_MIN (0+L'\0') +#else +#define WCHAR_MAX (0x7fffffff+L'\0') +#define WCHAR_MIN (-1-0x7fffffff+L'\0') +#endif + +#ifdef __cplusplus +#define NULL 0L +#else +#define NULL ((void*)0) +#endif + +#undef WEOF +#define WEOF 0xffffffffU + +/** + * @ingroup wchar + * + * @par Description: + * The wcscpy() function is the wide-character equivalent of the strcpy() function. + * It copies the wide-character string pointed to by src, + * including the terminating null wide character (L'\0'), to the array pointed to by dest. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #wchar_t* wcscpy() returns dest. + * + * @par Dependency: + *
      • wchar.h
      + * @see strcpy | wmemcpy + */ +wchar_t *wcscpy (wchar_t *__restrict, const wchar_t *__restrict); + +/** + * @ingroup wchar + * + * @par Description: + * The wcsncpy() function copies at most n wide characters from the wide-character + * string pointed to by src, including the terminating null wide character (L"\0"), + * to the array pointed to by dest. Exactly n wide characters are written at dst. + * If the length wcslen(src) is smaller than n, the remaining wide characters in the + * array pointed to by dst are filled with null wide characters. If the length + * wcslen(src) is greater than or equal to n, the string pointed to by dest will + * not be terminated by a null wide character. The strings may not overlap.The programmer + * must ensure that there is room for at least n wide characters at dst. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #wchar_t* wcsncpy() returns the address of dst. + * + * @par Dependency: + *
      • wchar.h
      + * @see strncpy + */ +wchar_t *wcsncpy (wchar_t *__restrict, const wchar_t *__restrict, size_t); + +wchar_t *wcscat (wchar_t *__restrict, const wchar_t *__restrict); +wchar_t *wcsncat (wchar_t *__restrict, const wchar_t *__restrict, size_t); + +/** + * @ingroup wchar + * + * @par Description: + * The wcscmp() function compares the wide-character string pointed to by s1 + * and the wide-character string pointed to by s2. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #int The wcscmp() function returns zero if the wide-character strings + * at s1 and s2 are equal. It returns an integer greater than zero if at the first + * differing position i, the corresponding wide-character s1[i] is greater than s2[i]. + * It returns an integer less than zero if at the first differing position i, + * the corresponding wide-character s1[i] is less than s2[i]. + * + * @par Dependency: + *
      • wchar.h
      + * @see strcmp | wmemcmp + */ +int wcscmp (const wchar_t *, const wchar_t *); + +/** + * @ingroup wchar + * + * @par Description: + * The wcsncmp() function compares the wide-character string pointed to by s1 + * and the wide-character string pointed to by s2, but at most n wide characters + * from each string. In each string, the comparison extends only up to the first + * occurrence of a null wide character (L"\0"), if any. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #int The wcsncmp() function returns zero if the wide-character + * strings at s1 and s2, truncated to at most length n, + * are equal. It returns an integer greater than zero if at the first differing + * position i (i < n), the corresponding wide-character + * s1[i] is greater than s2[i]. It returns an integer less than zero if at the + * first differing position i (i < n), the corresponding + * wide-character s1[i] is less than s2[i]. + * + * @par Dependency: + *
      • wchar.h
      + * @see strncmp + */ +int wcsncmp (const wchar_t *, const wchar_t *, size_t); + +/** + * @ingroup wchar + * + * @par Description: + * The wcscoll() function shall compare the wide-character string pointed to by + * s1 to the wide-character string pointed to by s2. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #int Upon successful completion, wcscoll() shall return an integer + * greater than, equal to, or less than 0, according to whether the wide-character + * string pointed to by s1 is greater than, equal to, or less than the wide-character + * string pointed to by s2. + * + * @par Dependency: + *
      • wchar.h
      + * @see wcscmp | wcsxfrm + */ +int wcscoll(const wchar_t *, const wchar_t *); + +/** + * @ingroup wchar + * + * @par Description: + * The wcsxfrm() function transforms wide-character string. + * + * @attention + *
        + *
      • On error, it don't set errno in Liteos.
      • + *
      + * + * @retval #size_t The wcsxfrm() shall return the length of the transformed + * wide-character string (not including the terminating null wide-character code). + * + * @par Dependency: + *
      • wchar.h
      + * @see wcscmp | wcscoll + */ +size_t wcsxfrm (wchar_t *__restrict, const wchar_t *__restrict, size_t); + +/** + * @ingroup wchar + * + * @par Description: + * The wcschr() function searches the first occurrence of c in the + * wide-character string pointed to by s. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #wchar_t* The wcschr() function returns a pointer to the first occurrence of c in + * the wide-character string pointed to by s, or NULL if wc does not occur in the string. + * + * @par Dependency: + *
      • wchar.h
      + * @see strchr | wmemchr + */ +wchar_t *wcschr (const wchar_t *, wchar_t); +wchar_t *wcsrchr (const wchar_t *, wchar_t); + +size_t wcscspn (const wchar_t *, const wchar_t *); +size_t wcsspn (const wchar_t *, const wchar_t *); +wchar_t *wcspbrk (const wchar_t *, const wchar_t *); + +wchar_t *wcstok (wchar_t *__restrict, const wchar_t *__restrict, wchar_t **__restrict); + +/** + * @ingroup wchar + * + * @par Description: + * The wcslen() function shall compute the number of wide-character + * codes in the wide-character string to which s points, + * not including the terminating null wide-character code. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #size_t The wcslen() function shall return the length of s. + * + * @par Dependency: + *
      • wchar.h
      + * @see strlen + */ +size_t wcslen (const wchar_t *); + +/** + * @ingroup wchar + * + * @par Description: + * The wcsstr() function is the wide-character equivalent of the strstr() function. It searches for the first occurrence of + * the wide-character string __needle (without its terminating null wide character (L'\0')) as a substring in + * the wide-character string __haystack. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #wchar_t* The wcsstr() function returns a pointer to the first occurrence of __needle in __haystack. + * It returns NULL if needle does not occur as a substring in __haystack. + * + * @par Dependency: + *
      • wchar.h
      + * @see mbsinit | wcrtomb | wcsnrtombs | wcstombs + */ +wchar_t *wcsstr (const wchar_t *__restrict, const wchar_t *__restrict); +wchar_t *wcswcs (const wchar_t *, const wchar_t *); + +/** + * @ingroup wchar + * + * @par Description: + * The wmemchr() searches the n wide characters starting at s for the + * first occurrence of the wide character c. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #wchar_t* The wmemchr() function returns a pointer to the first occurrence of c among + * the n wide characters starting at s, or NULL if c does not occur among these. + * + * @par Dependency: + *
      • wchar.h
      + * @see memchr | wcschr + */ +wchar_t *wmemchr (const wchar_t *, wchar_t, size_t); + +/** + * @ingroup wchar + * + * @par Description: + * The wmemcmp() function compares the n wide-characters starting at s1 + * and the n wide-characters starting at s2. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #int The wmemcmp() function returns zero if the wide-character arrays + * of size n at s1 and s2 are equal. It returns an integer greater than zero if + * at the first differing position i (i < n), the corresponding wide-character + * s1[i] is greater than s2[i]. It returns an integer less than zero if at the first + * differing position i (i < n), the corresponding wide-character s1[i] is less than s2[i]. + * + * @par Dependency: + *
      • wchar.h
      + * @see memcmp | wcscmp + */ +int wmemcmp (const wchar_t *, const wchar_t *, size_t); + +/** + * @ingroup wchar + * + * @par Description: + * The wmemcpy() function copies n wide characters from the array starting at + * s to the array starting at d. The programmer must ensure that there is room + * for at least n wide characters at d. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #wchar_t* wmemcpy() returns the address of d. + * + * @par Dependency: + *
      • wchar.h
      + * @see memcpy | wmemmove + */ +wchar_t *wmemcpy (wchar_t *__restrict, const wchar_t *__restrict, size_t); + +/** + * @ingroup wchar + * + * @par Description: + * The wmemmove() function is the wide-character equivalent of the memmove() function. + * It copies n wide characters from the array starting at src to the array starting at dest. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #wchar_t* wmemmove() returns dest. + * + * @par Dependency: + *
      • wchar.h
      + * @see memmove | wmemcpy + */ +wchar_t *wmemmove (wchar_t *, const wchar_t *, size_t); + +/** + * @ingroup wchar + * + * @par Description: + * The wmemset() function fills the array of n wide-characters + * starting at s with n copies of the wide character c. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #wchar_t* wmemset() returns the address of s. + * + * @par Dependency: + *
      • wchar.h
      + * @see memset + */ +wchar_t *wmemset (wchar_t *, wchar_t, size_t); + +/** + * @ingroup wchar + * + * @par Description: + * The btowc() function converts single byte to wide character. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #wint_t The btowc() function shall return WEOF if c has the value EOF or if c + * does not constitute a valid character in the initial shift state. Otherwise, it shall + * return the wide-character representation of that character. + * + * @par Dependency: + *
      • wchar.h
      + * @see wctob + */ +wint_t btowc (int); + +/** + * @ingroup wchar + * + * @par Description: + * The wctob() function tests whether the multibyte representation of + * the wide character wc, starting in the initial state, consists of a + * single byte. If so, it is returned as an unsigned char. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #int The wctob() function returns the single-byte representation of wc, + * if it exists, of EOF otherwise. + * + * @par Dependency: + *
      • wchar.h
      + * @see btowc | wcrtomb | wctomb + */ +int wctob (wint_t); + +/** + * @ingroup wchar + * + * @par Description: + * The mbsinit() function determines conversion object status. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #int The mbsinit() returns nonzero if *ps is an initial state, or if ps is NULL. + * Otherwise, it returns 0. + * + * @par Dependency: + *
      • wchar.h
      + * @see mbrlen | mbrtowc | wcrtomb | mbsrtowcs | wcsrtombs + */ +int mbsinit (const mbstate_t *); + +/** + * @ingroup wchar + * + * @par Description: + * The mbrtowc() function converts a character to a wide-character code. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #size_t The mbrtowc() function returns the number of bytes parsed + * from the multibyte sequence starting at s, if a non-L'\0' wide character + * was recognized. It returns 0, if a L'\0' wide character was recognized. + * It returns (size_t) -1 and sets errno to EILSEQ, if an invalid multibyte + * sequence was encountered. It returns (size_t) -2 if it couldn't parse a + * complete multibyte character, meaning that n should be increased. + * + * @par Errors + *
        + *
      • EILSEQ: An invalid character sequence is detected.
      • + *
      • EINVAL: ps points to an object that contains an invalid conversion state.
      • + *
      + * + * @par Dependency: + *
      • wchar.h
      + * @see mbsinit | mbsrtowcs + */ +size_t mbrtowc (wchar_t *__restrict, const char *__restrict, size_t, mbstate_t *__restrict); + +/** + * @ingroup wchar + * + * @par Description: + * The wcrtomb() function converts a wide-character code to a character. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #size_t The wcrtomb() function returns the number of bytes that have been or + * would have been written to the byte array at s. If wc can not be represented as a multibyte + * sequence (according to the current locale), (size_t) -1 is returned, and errno set to EILSEQ. + * + * @par Dependency: + *
      • wchar.h
      + * @see mbsinit | wcsrtombs + */ +size_t wcrtomb (char *__restrict, wchar_t, mbstate_t *__restrict); + +/** + * @ingroup wchar + * + * @par Description: + * If s is not a null pointer, mbrlen() shall determine the number of bytes constituting + * the character pointed to by s. It shall be equivalent:\n + * mbstate_t internal;\n + * mbrtowc(NULL, s, n, ps != NULL ? ps : &internal);\n + * If ps is a null pointer, the mbrlen() function shall use its own + * internal mbstate_t object, which is initialized at program start-up to the initial + * conversion state. Otherwise, the mbstate_t object pointed to by ps shall be used to + * completely describe the current conversion state of the associated character sequence. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #size_t The mbrlen() function returns the number of bytes parsed + * from the multibyte sequence starting at s, if a non-null wide character was + * recognized. It returns 0, if a null wide character was recognized. It returns (size_t) -1 + * and sets errno to EILSEQ, if an invalid multibyte sequence was encountered. + * It returns (size_t) -2 if it couldn't parse a complete multibyte character, + * meaning that n should be increased. + * + * @par Dependency: + *
      • wchar.h
      + * @see mbrtowc + */ +size_t mbrlen (const char *__restrict, size_t, mbstate_t *__restrict); + +/** + * @ingroup wchar + * + * @par Description: + * The mbsrtowcs() function converts a character string to a wide-character string. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #size_t The mbsrtowcs() function returns the number of wide characters that + * make up the converted part of the wide-character string, not including the terminating null + * wide character. If an invalid multibyte sequence was encountered, (size_t)-1 is returned, + * and errno set to EILSEQ. + * + * @par Errors + *
        + *
      • EILSEQ: An invalid character sequence is detected.
      • + *
      • EINVAL: ps points to an object that contains an invalid conversion state.
      • + *
      + * + * @par Dependency: + *
      • wchar.h
      + * @see mbrtowc | mbsinit | mbsnrtowcs + */ +size_t mbsrtowcs (wchar_t *__restrict, const char **__restrict, size_t, mbstate_t *__restrict); + +/** + * @ingroup wchar + * + * @par Description: + * The wcsrtombs() function convert a wide-character string to a multibyte string. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #size_t The wcsrtombs() function returns the number of bytes that make up + * the converted part of multibyte sequence, not including the terminating null byte. + * If a wide character was encountered which could not be converted, (size_t) -1 + * is returned, and errno set to EILSEQ. + * + * @par Dependency: + *
      • wchar.h
      + * @see mbsinit | wcrtomb | wcsnrtombs | wcstombs + */ +size_t wcsrtombs (char *__restrict, const wchar_t **__restrict, size_t, mbstate_t *__restrict); + +float wcstof (const wchar_t *__restrict, wchar_t **__restrict); +double wcstod (const wchar_t *__restrict, wchar_t **__restrict); +long double wcstold (const wchar_t *__restrict, wchar_t **__restrict); + +long wcstol (const wchar_t *__restrict, wchar_t **__restrict, int); +unsigned long wcstoul (const wchar_t *__restrict, wchar_t **__restrict, int); + +long long wcstoll (const wchar_t *__restrict, wchar_t **__restrict, int); +unsigned long long wcstoull (const wchar_t *__restrict, wchar_t **__restrict, int); + + + +int fwide (FILE *, int); + + +int wprintf (const wchar_t *__restrict, ...); +int fwprintf (FILE *__restrict, const wchar_t *__restrict, ...); + +/** + * @ingroup wchar + * + * @par Description: + * The swprintf() functione prints formatted wide-character output. + * + * @attention + *
        + *
      • Liteos do not support the function.
      • + *
      + * + * @retval #int The swprintf() function returns the number of wide characters written, + * excluding the terminating null wide character. + * + * @par Dependency: + *
      • wchar.h
      + * @see printf + */ +int swprintf (wchar_t *__restrict, size_t, const wchar_t *__restrict, ...); + +int vwprintf (const wchar_t *__restrict, __isoc_va_list); + +/** + * @ingroup wchar + * + * @par Description: + * The vfwprintf() function performs wide-character output to stream. + * stream must not be byte oriented. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #int The vfwprintf() function returns the number of wide characters written, + * excluding the terminating null wide character. It returns -1 when an error occurs. + * + * @par Dependency: + *
      • wchar.h
      + * @see fprintf | fputwc | printf | snprintf + */ +int vfwprintf (FILE *__restrict, const wchar_t *__restrict, __isoc_va_list); + +/** + * @ingroup wchar + * + * @par Description: + * The vswprintf() function performs wide-character output to an array of wide characters. + * The programmer must ensure that there is room for at least n wide characters at s. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #int The vswprintf() function returns the number of wide characters written, + * excluding the terminating null wide character. It returns -1 when an error occurs. + * + * @par Dependency: + *
      • wchar.h
      + * @see fprintf | fputwc | | printf | snprintf + */ +int vswprintf (wchar_t *__restrict, size_t, const wchar_t *__restrict, __isoc_va_list); + +int wscanf (const wchar_t *__restrict, ...); +int fwscanf (FILE *__restrict, const wchar_t *__restrict, ...); +int swscanf (const wchar_t *__restrict, const wchar_t *__restrict, ...); + +int vwscanf (const wchar_t *__restrict, __isoc_va_list); +int vfwscanf (FILE *__restrict, const wchar_t *__restrict, __isoc_va_list); +int vswscanf (const wchar_t *__restrict, const wchar_t *__restrict, __isoc_va_list); + +/** + * @ingroup wchar + * + * @par Description: + * The fgetwc() function reads a wide character from stream and returns it. + * If the end of stream is reached, it returns WEOF. If a wide-character + * conversion error occurs, it sets errno to EILSEQ and returns WEOF. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #wint_t The fgetwc() function returns the next wide-character from the stream, + * or WEOF. In the event of an error, errno is set to indicate the cause. + * + * @par Errors + *
        + *
      • ENOMEM: Insufficient storage space is available.
      • + *
      • EILSEQ: The data obtained from the input stream does not form a valid character.
      • + *
      + * + * @par Dependency: + *
      • wchar.h
      + * @see fputwc | ungetwc + */ +wint_t fgetwc (FILE *); + +/** + * @ingroup wchar + * + * @par Description: + * The getwc() function identically to fgetwc(). + * + * @attention + *
        + *
      • Refer to fgetwc().
      • + *
      + * + * @retval #wint_t The getwc() function returns the next wide-character from the + * stream, or WEOF. In the event of an error, errno is set to indicate the cause. + * + * @par Errors + *
        + *
      • ENOMEM: Insufficient storage space is available.
      • + *
      • EILSEQ: The data obtained from the input stream does not form a valid character.
      • + *
      + * + * @par Dependency: + *
      • wchar.h
      + * @see fputwc | ungetwc + */ +wint_t getwc (FILE *); +wint_t getwchar (void); + +/** + * @ingroup wchar + * + * @par Description: + * The fputwc() function writes the wide character wc to stream. If a wide-character + * conversion error occurs, it sets errno to EILSEQ and returns WEOF. + * Otherwise, it returns wc. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #wint_t The fputwc() function returns wc if no error occurred, or WEOF + * to indicate an error. In the event of an error, errno is set to indicate the cause. + * + * @par Errors + *
        + *
      • ENOMEM: Insufficient storage space is available.
      • + *
      • EILSEQ: Conversion of wc to the stream's encoding fails.
      • + *
      + * + * @par Dependency: + *
      • wchar.h
      + * @see fgetwc + */ +wint_t fputwc (wchar_t, FILE *); + +/** + * @ingroup wchar + * + * @par Description: + * The putwc() function identically to fputwc(). + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #wint_t The putwc() function returns wc if no error occurred, + * or WEOF to indicate an error. In the event of an error, errno is set + * to indicate the cause. + * + * @par Errors + *
        + *
      • ENOMEM: Insufficient storage space is available.
      • + *
      • EILSEQ: Conversion of wc to the stream's encoding fails.
      • + *
      + * + * @par Dependency: + *
      • wchar.h
      + * @see fgetwc + */ +wint_t putwc (wchar_t, FILE *); +wint_t putwchar (wchar_t); + +wchar_t *fgetws (wchar_t *__restrict, int, FILE *__restrict); +int fputws (const wchar_t *__restrict, FILE *__restrict); + +/** + * @ingroup wchar + * + * @par Description: + * The ungetwc() function is the wide-character equivalent of the ungetc() function. + * It pushes back a wide character onto stream and returns it. If wc is WEOF, it returns WEOF. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #wint_t The ungetwc() function returns wc when successful, or WEOF upon failure. + * + * @par Dependency: + *
      • wchar.h
      + * @see fgetwc + */ +wint_t ungetwc (wint_t, FILE *); + +struct tm; + +/** + * @ingroup wchar + * + * @par Description: + * The wcsftime() function converts date and time to a wide-character string. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #size_t If the total number of resulting wide-character codes + * including the terminating null wide-character code is no more than maxsize, + * wcsftime() shall return the number of wide-character codes placed into the + * array pointed to by s, not including the terminating null wide-character code. + * Otherwise, zero is returned and the contents of the array are unspecified. + * + * @par Dependency: + *
      • wchar.h
      + * @see strftime + */ +size_t wcsftime (wchar_t *__restrict, size_t, const wchar_t *__restrict, const struct tm *__restrict); + +#undef iswdigit + +#if defined(_GNU_SOURCE) +wint_t fgetwc_unlocked (FILE *); +wint_t getwc_unlocked (FILE *); +wint_t getwchar_unlocked (void); +wint_t fputwc_unlocked (wchar_t, FILE *); +wint_t putwc_unlocked (wchar_t, FILE *); +wint_t putwchar_unlocked (wchar_t); +wchar_t *fgetws_unlocked (wchar_t *__restrict, int, FILE *__restrict); +int fputws_unlocked (const wchar_t *__restrict, FILE *__restrict); +#endif + +#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE) +size_t wcsftime_l (wchar_t *__restrict, size_t, const wchar_t *__restrict, const struct tm *__restrict, locale_t); +#endif + +#if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \ + || defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) || defined(_BSD_SOURCE) +FILE *open_wmemstream(wchar_t **, size_t *); + +/** + * @ingroup wchar + * + * @par Description: + * The mbsnrtowcs() function converts a character string to a wide-character string. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #size_t The mbsnrtowcs() function returns the number of wide characters that + * make up the converted part of the wide-character string, not including the terminating null + * wide character. If an invalid multibyte sequence was encountered, (size_t)-1 is returned, + * and errno set to EILSEQ. + * + * @par Errors + *
        + *
      • EILSEQ: An invalid character sequence is detected.
      • + *
      • EINVAL: ps points to an object that contains an invalid conversion state.
      • + *
      + * + * @par Dependency: + *
      • wchar.h
      + * @see mbrtowc | mbsinit | mbsrtowcs + */ +size_t mbsnrtowcs(wchar_t *__restrict, const char **__restrict, size_t, size_t, mbstate_t *__restrict); + +/** + * @ingroup wchar + * + * @par Description: + * The wcsnrtombs() function converts a wide-character string to a multibyte string. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #size_t The wcsnrtombs() function returns the number of bytes that make up + * the converted part of multibyte sequence, not including the terminating null byte. + * If a wide character was encountered which could not be converted, (size_t) -1 + * is returned, and errno set to EILSEQ. + * + * @par Dependency: + *
      • wchar.h
      + * @see mbsinit | wcsrtombs + */ +size_t wcsnrtombs(char *__restrict, const wchar_t **__restrict, size_t, size_t, mbstate_t *__restrict); +wchar_t *wcsdup(const wchar_t *); + +/** + * @ingroup wchar + * + * @par Description: + * The wcsnlen() function is the wide-character equivalent of the strnlen() function. It returns the number of wide- + * characters in the string pointed to by s, not including the terminating null wide character (L'\0'), but at most + * maxlen wide characters (note: this parameter is not a byte count). In doing this, wcsnlen() looks at only the first + * maxlen wide characters at s and never beyond s+maxlen. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @retval #size_t The wcsnlen() function returns wcslen(s), if that is less than maxlen, or maxlen if there is no null wide character + * among the first maxlen wide characters pointed to by s. + * + * @par Dependency: + *
      • wchar.h
      + * @see strnlen | wcslen + */ +size_t wcsnlen (const wchar_t *, size_t); +wchar_t *wcpcpy (wchar_t *__restrict, const wchar_t *__restrict); +wchar_t *wcpncpy (wchar_t *__restrict, const wchar_t *__restrict, size_t); +int wcscasecmp(const wchar_t *, const wchar_t *); +int wcscasecmp_l(const wchar_t *, const wchar_t *, locale_t); +int wcsncasecmp(const wchar_t *, const wchar_t *, size_t); +int wcsncasecmp_l(const wchar_t *, const wchar_t *, size_t, locale_t); +int wcscoll_l(const wchar_t *, const wchar_t *, locale_t); +size_t wcsxfrm_l(wchar_t *__restrict, const wchar_t *__restrict, size_t, locale_t); +#endif + +#if defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) || defined(_BSD_SOURCE) +int wcwidth (wchar_t); +int wcswidth (const wchar_t *, size_t); +int iswalnum(wint_t); +int iswalpha(wint_t); +int iswblank(wint_t); +int iswcntrl(wint_t); +int iswdigit(wint_t); +int iswgraph(wint_t); +int iswlower(wint_t); +int iswprint(wint_t); +int iswpunct(wint_t); +int iswspace(wint_t); +int iswupper(wint_t); +int iswxdigit(wint_t); +int iswctype(wint_t, wctype_t); +wint_t towlower(wint_t); +wint_t towupper(wint_t); +wctype_t wctype(const char *); + +#ifndef __cplusplus +#undef iswdigit +#define iswdigit(a) (0 ? iswdigit(a) : ((unsigned)(a)-'0') < 10) +#endif +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/wctype.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/wctype.h new file mode 100644 index 0000000000000000000000000000000000000000..bc2420d3fd84756c11bc575b41224266baf18925 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/wctype.h @@ -0,0 +1,79 @@ +#ifndef _WCTYPE_H +#define _WCTYPE_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#define __NEED_wint_t +#define __NEED_wctype_t + +#if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \ + || defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) || defined(_BSD_SOURCE) +#define __NEED_locale_t +#endif + +#include + +typedef const int * wctrans_t; + +#undef WEOF +#define WEOF 0xffffffffU + +#undef iswdigit + +int iswalnum(wint_t); +int iswalpha(wint_t); +int iswblank(wint_t); +int iswcntrl(wint_t); +int iswdigit(wint_t); +int iswgraph(wint_t); +int iswlower(wint_t); +int iswprint(wint_t); +int iswpunct(wint_t); +int iswspace(wint_t); +int iswupper(wint_t); +int iswxdigit(wint_t); +int iswctype(wint_t, wctype_t); +wint_t towctrans(wint_t, wctrans_t); +wint_t towlower(wint_t); +wint_t towupper(wint_t); +wctrans_t wctrans(const char *); +wctype_t wctype(const char *); + +#ifndef __cplusplus +#undef iswdigit +#define iswdigit(a) (0 ? iswdigit(a) : ((unsigned)(a)-'0') < 10) +#endif + +#if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \ + || defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) || defined(_BSD_SOURCE) + +int iswalnum_l(wint_t, locale_t); +int iswalpha_l(wint_t, locale_t); +int iswblank_l(wint_t, locale_t); +int iswcntrl_l(wint_t, locale_t); +int iswdigit_l(wint_t, locale_t); +int iswgraph_l(wint_t, locale_t); +int iswlower_l(wint_t, locale_t); +int iswprint_l(wint_t, locale_t); +int iswpunct_l(wint_t, locale_t); +int iswspace_l(wint_t, locale_t); +int iswupper_l(wint_t, locale_t); +int iswxdigit_l(wint_t, locale_t); +int iswctype_l(wint_t, wctype_t, locale_t); +wint_t towlower_l(wint_t, locale_t); +wint_t towupper_l(wint_t, locale_t); +wint_t towctrans_l(wint_t, wctrans_t, locale_t); +wctrans_t wctrans_l(const char *, locale_t); +wctype_t wctype_l(const char *, locale_t); + +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/wordexp.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/wordexp.h new file mode 100644 index 0000000000000000000000000000000000000000..5460002deec7462e42a5bdf8cd5f49d7d3040e29 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/wordexp.h @@ -0,0 +1,41 @@ +#ifndef _WORDEXP_H +#define _WORDEXP_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#define __NEED_size_t + +#include + +#define WRDE_DOOFFS 1 +#define WRDE_APPEND 2 +#define WRDE_NOCMD 4 +#define WRDE_REUSE 8 +#define WRDE_SHOWERR 16 +#define WRDE_UNDEF 32 + +typedef struct { + size_t we_wordc; + char **we_wordv; + size_t we_offs; +} wordexp_t; + +#define WRDE_NOSYS -1 +#define WRDE_NOSPACE 1 +#define WRDE_BADCHAR 2 +#define WRDE_BADVAL 3 +#define WRDE_CMDSUB 4 +#define WRDE_SYNTAX 5 + +int wordexp (const char *__restrict, wordexp_t *__restrict, int); +void wordfree (wordexp_t *); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/nuttx/include/nuttx/config.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/nuttx/include/nuttx/config.h new file mode 100644 index 0000000000000000000000000000000000000000..95a76719c24e7a2df848ca26588c983e404fde24 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/nuttx/include/nuttx/config.h @@ -0,0 +1,24 @@ +#ifndef __INCLUDE_NUTTX_CONFIG_H +#define __INCLUDE_NUTTX_CONFIG_H + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +#ifndef FAR +#define FAR +#endif + +#ifdef __cplusplus +#if __cplusplus +} +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +#endif /* __INCLUDE_NUTTX_CONFIG_H */ diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/nuttx/include/stdarg.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/nuttx/include/stdarg.h new file mode 100644 index 0000000000000000000000000000000000000000..a49e29d9051f69fed3eb924012784723b131d05b --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/nuttx/include/stdarg.h @@ -0,0 +1,74 @@ +/**************************************************************************** + * arch/arm/include/stdarg.h + * + * Copyright (C) 2012 Gregory Nutt. All rights reserved. + * Copyright (c) <2013-2018>, + * Author: Gregory Nutt + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * 3. Neither the name NuttX nor the names of its contributors may be + * used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED + * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************/ + +#ifndef LIBC_STDARG_H +#define LIBC_STDARG_H + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +/**************************************************************************** + * Pre-processor Definitions + ****************************************************************************/ +/* This should work with any modern gcc (newer than 3.4 or so) */ + +#define va_start(v,l) __builtin_va_start(v,l) +#define va_end(v) __builtin_va_end(v) +#define va_arg(v,l) __builtin_va_arg(v,l) +#define va_copy(d,s) __builtin_va_copy(d,s) + +/**************************************************************************** + * Public Types + ****************************************************************************/ +#ifndef __va_list__ +#define __va_list__ +typedef __builtin_va_list va_list; +#endif + +#ifdef __cplusplus +#if __cplusplus +} +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +#endif /* LIBC_STDARG_H */ diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/nuttx/include/stdbool.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/nuttx/include/stdbool.h new file mode 100644 index 0000000000000000000000000000000000000000..e06109da26a0f771bc43698389b4e65f93a2f9be --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/nuttx/include/stdbool.h @@ -0,0 +1,53 @@ +/**************************************************************************** + * include/stdbool.h + * + * Copyright (C) 2009, 2011 Gregory Nutt. All rights reserved. + * Copyright (c) <2013-2018>, + * Author: Gregory Nutt + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * 3. Neither the name NuttX nor the names of its contributors may be + * used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED + * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************/ + +#ifndef _STDBOOL_H +#define _STDBOOL_H + +#ifndef __cplusplus +#define true 1 +#ifndef false //new_add +#define false 0 +#endif +#define bool _Bool +#else /* __cplusplus */ +#define false false +#define true true +#define _Bool bool +#define bool bool +#endif /* __cplusplus */ + +#endif /* stdbool.h */ diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/nuttx/include/stddef.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/nuttx/include/stddef.h new file mode 100644 index 0000000000000000000000000000000000000000..7c7e488323ad8d4bc77ef08d102a9862324701d5 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/nuttx/include/stddef.h @@ -0,0 +1,126 @@ +/**************************************************************************** + * include/stddef.h + * + * Copyright (C) 2007-2009 Gregory Nutt. All rights reserved. + * Author: Gregory Nutt + * Copyright (c) <2014-2018>, + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * 3. Neither the name NuttX nor the names of its contributors may be + * used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED + * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************/ +#ifndef __INCLUDE_STDDEF_H +#define __INCLUDE_STDDEF_H + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include +#include "los_typedef.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif /* __cplusplus */ +#endif /* __cplusplus */ +/**************************************************************************** + * Pre-processor Definitions + ****************************************************************************/ + +/* The header shall define the following macros: + * + * NULL + * The null pointer constant. + * + * NOTE: Currently the definition of NULL is in sys/types.h but should + * be moved here sometime. + * + * offsetof(type, member-designator) + * Integer constant expression of type size_t, the value of which is the + * offset in bytes to the structure member (member-designator), from the + * beginning of its structure (type). + * + * NOTE: This version of offsetof() depends on behaviors that could be + * undefined for some compilers. It would be better to use a builtin + * function if one exists. + * + * Reference: Opengroup.org + */ + +#define offsetof(a, b) ((size_t)(&(((a *)(0))->b))) + +/**************************************************************************** + * Type Definitions + ****************************************************************************/ + +/* The header shall define the following types: + * + * ptrdiff_t + * Signed integer type of the result of subtracting two pointers. + * + * wchar_t + * Integer type whose range of values can represent distinct wide-character + * codes for all members of the largest character set specified among the + * locales supported by the compilation environment: the null character has + * the code value 0 and each member of the portable character set has a + * code value equal to its value when used as the lone character in an + * integer character constant. + * + * size_t + * Unsigned integer type of the result of the sizeof operator. + * + * NOTE: Currently the type definitions of ptrdiff_t, wchar_t, and size_t are + * in sys/types.h but should be moved here sometime. + * + * The implementation shall support one or more programming environments in + * which the widths of ptrdiff_t, size_t, and wchar_t are no greater than the + * width of type long. The names of these programming environments can be + * obtained using the confstr() function or the getconf utility. + * + * Reference: Opengroup.org + */ +#ifdef __LP64__ +typedef long int ptrdiff_t; +#else +typedef int ptrdiff_t; +#endif +typedef unsigned long u_long; +typedef unsigned char u_char; +typedef unsigned short u_short; +typedef unsigned int u_int; +#ifndef __cplusplus +typedef int wchar_t; +#endif +#ifdef __cplusplus +#if __cplusplus +} +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +#endif /* __INCLUDE_STDDEF_H */ diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libsec/include/securec.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libsec/include/securec.h new file mode 100644 index 0000000000000000000000000000000000000000..ee70267bcc65113103ca520475d1f22cd99d2c7a --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libsec/include/securec.h @@ -0,0 +1,631 @@ +/* + * Copyright (c) Huawei Technologies Co., Ltd. 2014-2018. All rights reserved. + * Description: The user of this secure c library should include this header file in you source code. + * This header file declare all supported API prototype of the library, + * such as memcpy_s, strcpy_s, wcscpy_s,strcat_s, strncat_s, sprintf_s, scanf_s, and so on. + * Author: lishunda + * Create: 2014-02-25 + * Notes: Do not modify this file by yourself. + * History: 2018-09-27 zhaozhijian Code base quality improvement + */ + +#ifndef __SECUREC_H__5D13A042_DC3F_4ED9_A8D1_882811274C27 +#define __SECUREC_H__5D13A042_DC3F_4ED9_A8D1_882811274C27 + +#include "securectype.h" +#ifndef SECUREC_HAVE_STDARG_H +#define SECUREC_HAVE_STDARG_H 1 +#endif + +#if SECUREC_HAVE_STDARG_H +#include +#endif + +#ifndef SECUREC_HAVE_ERRNO_H +#if SECUREC_IN_KERNEL +#define SECUREC_HAVE_ERRNO_H 0 +#else +#define SECUREC_HAVE_ERRNO_H 1 +#endif +#endif + +/* EINVAL ERANGE may defined in errno.h */ +#if SECUREC_HAVE_ERRNO_H +#include +#endif + +/* Define error code */ +#if defined(SECUREC_NEED_ERRNO_TYPE) || !defined(__STDC_WANT_LIB_EXT1__) || \ + (defined(__STDC_WANT_LIB_EXT1__) && (__STDC_WANT_LIB_EXT1__ == 0)) +#ifndef SECUREC_DEFINED_ERRNO_TYPE +#define SECUREC_DEFINED_ERRNO_TYPE +/* Just check whether macrodefinition exists. */ +#ifndef errno_t +typedef int errno_t; +#endif +#endif +#endif + +/* Success */ +#ifndef EOK +#define EOK 0 +#endif + +#ifndef EINVAL +/* The src buffer is not correct and destination buffer cant not be reset */ +#define EINVAL 22 +#endif + +#ifndef EINVAL_AND_RESET +/* Once the error is detected, the dest buffer must be reseted! */ +#define EINVAL_AND_RESET (22 | 128) +#endif + +#ifndef ERANGE +/* The destination buffer is not long enough and destination buffer can not be reset */ +#define ERANGE 34 +#endif + +#ifndef ERANGE_AND_RESET +/* Once the error is detected, the dest buffer must be reseted! */ +#define ERANGE_AND_RESET (34 | 128) +#endif + +#ifndef EOVERLAP_AND_RESET +/* Once the buffer overlap is detected, the dest buffer must be reseted! */ +#define EOVERLAP_AND_RESET (54 | 128) +#endif + +/* If you need export the function of this library in Win32 dll, use __declspec(dllexport) */ +#ifndef SECUREC_API +#if defined(SECUREC_DLL_EXPORT) +#define SECUREC_API __declspec(dllexport) +#elif defined(SECUREC_DLL_IMPORT) +#define SECUREC_API __declspec(dllimport) +#else +/* + * Standardized function declaration. If a security function is declared in the your code, + * it may cause a compilation alarm,Please delete the security function you declared. + * Adding extern under windows will cause the system to have inline functions to expand, + * so do not add the extern in default + */ +#if defined(_MSC_VER) +#define SECUREC_API +#else +#define SECUREC_API extern +#endif +#endif +#endif + +#ifdef __cplusplus +extern "C" { +#endif + /* + * Description: The GetHwSecureCVersion function get SecureC Version string and version number. + * Parameter: verNumber - to store version number + * Return: version string + */ + SECUREC_API const char *GetHwSecureCVersion(unsigned short *verNumber); + +#if SECUREC_ENABLE_MEMSET + /* + * Description: The memset_s function copies the value of c (converted to an unsigned char) into each of + * the first count characters of the object pointed to by dest. + * Parameter: dest - destination address + * Parameter: destMax - The maximum length of destination buffer + * Parameter: c - the value to be copied + * Parameter: count - copies count bytes of value to dest + * Return: EOK if there was no runtime-constraint violation + */ + SECUREC_API errno_t memset_s(void *dest, size_t destMax, int c, size_t count); +#endif + +#ifndef SECUREC_ONLY_DECLARE_MEMSET +#define SECUREC_ONLY_DECLARE_MEMSET 0 +#endif + +#if SECUREC_ONLY_DECLARE_MEMSET == 0 + +#if SECUREC_ENABLE_MEMMOVE + /* + * Description: The memmove_s function copies n characters from the object pointed to by src + * into the object pointed to by dest. + * Parameter: dest - destination address + * Parameter: destMax - The maximum length of destination buffer + * Parameter: src - source address + * Parameter: count - copies count bytes from the src + * Return: EOK if there was no runtime-constraint violation + */ + SECUREC_API errno_t memmove_s(void *dest, size_t destMax, const void *src, size_t count); +#endif + +#if SECUREC_ENABLE_MEMCPY + /* + * Description: The memcpy_s function copies n characters from the object pointed to + * by src into the object pointed to by dest. + * Parameter: dest - destination address + * Parameter: destMax - The maximum length of destination buffer + * Parameter: src - source address + * Parameter: count - copies count bytes from the src + * Return: EOK if there was no runtime-constraint violation + */ + SECUREC_API errno_t memcpy_s(void *dest, size_t destMax, const void *src, size_t count); +#endif + +#if SECUREC_ENABLE_STRCPY + /* + * Description: The strcpy_s function copies the string pointed to by strSrc (including + * the terminating null character) into the array pointed to by strDest + * Parameter: strDest - destination address + * Parameter: destMax - The maximum length of destination buffer(including the terminating null character) + * Parameter: strSrc - source address + * Return: EOK if there was no runtime-constraint violation + */ + SECUREC_API errno_t strcpy_s(char *strDest, size_t destMax, const char *strSrc); +#endif + +#if SECUREC_ENABLE_STRNCPY + /* + * Description: The strncpy_s function copies not more than n successive characters (not including + * the terminating null character) from the array pointed to by strSrc to the array pointed to by strDest. + * Parameter: strDest - destination address + * Parameter: destMax - The maximum length of destination buffer(including the terminating null character) + * Parameter: strSrc - source address + * Parameter: count - copies count characters from the src + * Return: EOK if there was no runtime-constraint violation + */ + SECUREC_API errno_t strncpy_s(char *strDest, size_t destMax, const char *strSrc, size_t count); +#endif + +#if SECUREC_ENABLE_STRCAT + /* + * Description: The strcat_s function appends a copy of the string pointed to by strSrc (including + * the terminating null character) to the end of the string pointed to by strDest. + * Parameter: strDest - destination address + * Parameter: destMax - The maximum length of destination buffer(including the terminating null wide character) + * Parameter: strSrc - source address + * Return: EOK if there was no runtime-constraint violation + */ + SECUREC_API errno_t strcat_s(char *strDest, size_t destMax, const char *strSrc); +#endif + +#if SECUREC_ENABLE_STRNCAT + /* + * Description: The strncat_s function appends not more than n successive characters (not including + * the terminating null character) + * from the array pointed to by strSrc to the end of the string pointed to by strDest. + * Parameter: strDest - destination address + * Parameter: destMax - The maximum length of destination buffer(including the terminating null character) + * Parameter: strSrc - source address + * Parameter: count - copies count characters from the src + * Return: EOK if there was no runtime-constraint violation + */ + SECUREC_API errno_t strncat_s(char *strDest, size_t destMax, const char *strSrc, size_t count); +#endif + +#if SECUREC_ENABLE_VSPRINTF + /* + * Description: The vsprintf_s function is equivalent to the vsprintf function except for the parameter destMax + * and the explicit runtime-constraints violation + * Parameter: strDest - produce output according to a format ,write to the character string strDest. + * Parameter: destMax - The maximum length of destination buffer(including the terminating null wide characte) + * Parameter: format - fromat string + * Parameter: argList - instead of a variable number of arguments + * Return: the number of characters printed(not including the terminating null byte '\0'), + * If an error occurred Return: -1. + */ + SECUREC_API int vsprintf_s(char *strDest, size_t destMax, const char *format, + va_list argList) SECUREC_ATTRIBUTE(3, 0); +#endif + +#if SECUREC_ENABLE_SPRINTF + /* + * Description: The sprintf_s function is equivalent to the sprintf function except for the parameter destMax + * and the explicit runtime-constraints violation + * Parameter: strDest - produce output according to a format ,write to the character string strDest. + * Parameter: destMax - The maximum length of destination buffer(including the terminating null byte '\0') + * Parameter: format - fromat string + * Return: the number of characters printed(not including the terminating null byte '\0'), + * If an error occurred Return: -1. + */ + SECUREC_API int sprintf_s(char *strDest, size_t destMax, const char *format, ...) SECUREC_ATTRIBUTE(3, 4); +#endif + +#if SECUREC_ENABLE_VSNPRINTF + /* + * Description: The vsnprintf_s function is equivalent to the vsnprintf function except for + * the parameter destMax/count and the explicit runtime-constraints violation + * Parameter: strDest - produce output according to a format ,write to the character string strDest. + * Parameter: destMax - The maximum length of destination buffer(including the terminating null byte '\0') + * Parameter: count - do not write more than count bytes to strDest(not including the terminating null byte '\0') + * Parameter: format - fromat string + * Parameter: argList - instead of a variable number of arguments + * Return: the number of characters printed(not including the terminating null byte '\0'), + * If an error occurred Return: -1.Pay special attention to returning -1 when truncation occurs + */ + SECUREC_API int vsnprintf_s(char *strDest, size_t destMax, size_t count, const char *format, + va_list argList) SECUREC_ATTRIBUTE(4, 0); +#endif + +#if SECUREC_ENABLE_SNPRINTF + /* + * Description: The snprintf_s function is equivalent to the snprintf function except for + * the parameter destMax/count and the explicit runtime-constraints violation + * Parameter: strDest - produce output according to a format ,write to the character string strDest. + * Parameter: destMax - The maximum length of destination buffer(including the terminating null byte '\0') + * Parameter: count - do not write more than count bytes to strDest(not including the terminating null byte '\0') + * Parameter: format - fromat string + * Return: the number of characters printed(not including the terminating null byte '\0'), + * If an error occurred Return: -1.Pay special attention to returning -1 when truncation occurs + */ + SECUREC_API int snprintf_s(char *strDest, size_t destMax, size_t count, const char *format, + ...) SECUREC_ATTRIBUTE(4, 5); +#endif + +#if SECUREC_SNPRINTF_TRUNCATED + /* + * Description: The vsnprintf_truncated_s function is equivalent to the vsnprintf_s function except + * no count parameter and return value + * Parameter: strDest - produce output according to a format ,write to the character string strDest + * Parameter: destMax - The maximum length of destination buffer(including the terminating null byte '\0') + * Parameter: format - fromat string + * Parameter: argList - instead of a variable number of arguments + * Return: the number of characters printed(not including the terminating null byte '\0'), + * If an error occurred Return: -1.Pay special attention to returning destMax - 1 when truncation occurs + */ + SECUREC_API int vsnprintf_truncated_s(char *strDest, size_t destMax, const char *format, + va_list argList) SECUREC_ATTRIBUTE(3, 0); + + /* + * Description: The snprintf_truncated_s function is equivalent to the snprintf_2 function except + * no count parameter and return value + * Parameter: strDest - produce output according to a format ,write to the character string strDest. + * Parameter: destMax - The maximum length of destination buffer(including the terminating null byte '\0') + * Parameter: format - fromat string + * Return: the number of characters printed(not including the terminating null byte '\0'), + * If an error occurred Return: -1.Pay special attention to returning destMax - 1 when truncation occurs + */ + SECUREC_API int snprintf_truncated_s(char *strDest, size_t destMax, + const char *format, ...) SECUREC_ATTRIBUTE(3, 4); +#endif + +#if SECUREC_ENABLE_SCANF + /* + * Description: The scanf_s function is equivalent to fscanf_s with the argument stdin + * interposed before the arguments to scanf_s + * Parameter: format - fromat string + * Return: the number of input items assigned, If an error occurred Return: -1. + */ + SECUREC_API int scanf_s(const char *format, ...); +#endif + +#if SECUREC_ENABLE_VSCANF + /* + * Description: The vscanf_s function is equivalent to scanf_s, with the variable argument list replaced by argList + * Parameter: format - fromat string + * Parameter: argList - instead of a variable number of arguments + * Return: the number of input items assigned, If an error occurred Return: -1. + */ + SECUREC_API int vscanf_s(const char *format, va_list argList); +#endif + +#if SECUREC_ENABLE_SSCANF + /* + * Description: The sscanf_s function is equivalent to fscanf_s, except that input is obtained from a + * string (specified by the argument buffer) rather than from a stream + * Parameter: buffer - read character from buffer + * Parameter: format - fromat string + * Return: the number of input items assigned, If an error occurred Return: -1. + */ + SECUREC_API int sscanf_s(const char *buffer, const char *format, ...); +#endif + +#if SECUREC_ENABLE_VSSCANF + /* + * Description: The vsscanf_s function is equivalent to sscanf_s, with the variable argument list + * replaced by argList + * Parameter: buffer - read character from buffer + * Parameter: format - fromat string + * Parameter: argList - instead of a variable number of arguments + * Return: the number of input items assigned, If an error occurred Return: -1. + */ + SECUREC_API int vsscanf_s(const char *buffer, const char *format, va_list argList); +#endif + +#if SECUREC_ENABLE_FSCANF + /* + * Description: The fscanf_s function is equivalent to fscanf except that the c, s, and [ conversion specifiers + * apply to a pair of arguments (unless assignment suppression is indicated by a*) + * Parameter: stream - stdio file stream + * Parameter: format - fromat string + * Return: the number of input items assigned, If an error occurred Return: -1. + */ + SECUREC_API int fscanf_s(FILE *stream, const char *format, ...); +#endif + +#if SECUREC_ENABLE_VFSCANF + /* + * Description: The vfscanf_s function is equivalent to fscanf_s, with the variable argument list + * replaced by argList + * Parameter: stream - stdio file stream + * Parameter: format - fromat string + * Parameter: argList - instead of a variable number of arguments + * Return: the number of input items assigned, If an error occurred Return: -1. + */ + SECUREC_API int vfscanf_s(FILE *stream, const char *format, va_list argList); +#endif + +#if SECUREC_ENABLE_STRTOK + /* + * Description: The strtok_s function parses a string into a sequence of strToken, + * replace all characters in strToken string that match to strDelimit set with 0. + * On the first call to strtok_s the string to be parsed should be specified in strToken. + * In each subsequent call that should parse the same string, strToken should be NULL + * Parameter: strToken - the string to be delimited + * Parameter: strDelimit - specifies a set of characters that delimit the tokens in the parsed string + * Parameter: context - is a pointer to a char * variable that is used internally by strtok_s function + * Return: On the first call returns the address of the first non \0 character, otherwise NULL is returned. + * In subsequent calls, the strtoken is set to NULL, and the context set is the same as the previous call, + * return NULL if the *context string length is equal 0, otherwise return *context. + */ + SECUREC_API char *strtok_s(char *strToken, const char *strDelimit, char **context); +#endif + +#if SECUREC_ENABLE_GETS && SECUREC_IN_KERNEL == 0 + /* + * Description: The gets_s function reads at most one less than the number of characters specified + * by destMax from the stream pointed to by stdin, into the array pointed to by buffer + * Parameter: buffer - destination address + * Parameter: destMax - The maximum length of destination buffer(including the terminating null character) + * Return: buffer if there was no runtime-constraint violation,If an error occurred Return: NULL. + */ + SECUREC_API char *gets_s(char *buffer, size_t destMax); +#endif + + +#if SECUREC_ENABLE_WCHAR_FUNC +#if SECUREC_ENABLE_MEMCPY + /* + * Description: The wmemcpy_s function copies n successive wide characters from the object pointed to + * by src into the object pointed to by dest. + * Parameter: dest - destination address + * Parameter: destMax - The maximum length of destination buffer + * Parameter: src - source address + * Parameter: count - copies count wide characters from the src + * Return: EOK if there was no runtime-constraint violation + */ + SECUREC_API errno_t wmemcpy_s(wchar_t *dest, size_t destMax, const wchar_t *src, size_t count); +#endif + +#if SECUREC_ENABLE_MEMMOVE + /* + * Description: The wmemmove_s function copies n successive wide characters from the object + * pointed to by src into the object pointed to by dest. + * Parameter: dest - destination address + * Parameter: destMax - The maximum length of destination buffer + * Parameter: src - source address + * Parameter: count - copies count wide characters from the src + * Return: EOK if there was no runtime-constraint violation + */ + SECUREC_API errno_t wmemmove_s(wchar_t *dest, size_t destMax, const wchar_t *src, size_t count); +#endif + +#if SECUREC_ENABLE_STRCPY + /* + * Description: The wcscpy_s function copies the wide string pointed to by strSrc (including theterminating + * null wide character) into the array pointed to by strDest + * Parameter: strDest - destination address + * Parameter: destMax - The maximum length of destination buffer + * Parameter: strSrc - source address + * Return: EOK if there was no runtime-constraint violation + */ + SECUREC_API errno_t wcscpy_s(wchar_t *strDest, size_t destMax, const wchar_t *strSrc); +#endif + +#if SECUREC_ENABLE_STRNCPY + /* + * Description: The wcsncpy_s function copies not more than n successive wide characters (not including the + * terminating null wide character) from the array pointed to by strSrc to the array pointed to by strDest + * Parameter: strDest - destination address + * Parameter: destMax - The maximum length of destination buffer(including the terminating wide character) + * Parameter: strSrc - source address + * Parameter: count - copies count wide characters from the src + * Return: EOK if there was no runtime-constraint violation + */ + SECUREC_API errno_t wcsncpy_s(wchar_t *strDest, size_t destMax, const wchar_t *strSrc, size_t count); +#endif + +#if SECUREC_ENABLE_STRCAT + /* + * Description: The wcscat_s function appends a copy of the wide string pointed to by strSrc (including the + * terminating null wide character) to the end of the wide string pointed to by strDest + * Parameter: strDest - destination address + * Parameter: destMax - The maximum length of destination buffer(including the terminating wide character) + * Parameter: strSrc - source address + * Return: EOK if there was no runtime-constraint violation + */ + SECUREC_API errno_t wcscat_s(wchar_t *strDest, size_t destMax, const wchar_t *strSrc); +#endif + +#if SECUREC_ENABLE_STRNCAT + /* + * Description: The wcsncat_s function appends not more than n successive wide characters (not including the + * terminating null wide character) from the array pointed to by strSrc to the end of the wide string pointed to + * by strDest. + * Parameter: strDest - destination address + * Parameter: destMax - The maximum length of destination buffer(including the terminating wide character) + * Parameter: strSrc - source address + * Parameter: count - copies count wide characters from the src + * Return: EOK if there was no runtime-constraint violation + */ + SECUREC_API errno_t wcsncat_s(wchar_t *strDest, size_t destMax, const wchar_t *strSrc, size_t count); +#endif + +#if SECUREC_ENABLE_STRTOK + /* + * Description: The wcstok_s function is the wide-character equivalent of the strtok_s function + * Parameter: strToken - the string to be delimited + * Parameter: strDelimit - specifies a set of characters that delimit the tokens in the parsed string + * Parameter: context - is a pointer to a char * variable that is used internally by strtok_s function + * Return: a pointer to the first character of a token, or a null pointer if there is no token + * or there is a runtime-constraint violation. + */ + SECUREC_API wchar_t *wcstok_s(wchar_t *strToken, const wchar_t *strDelimit, wchar_t **context); +#endif + +#if SECUREC_ENABLE_VSPRINTF + /* + * Description: The vswprintf_s function is the wide-character equivalent of the vsprintf_s function + * Parameter: strDest - produce output according to a format ,write to the character string strDest + * Parameter: destMax - The maximum length of destination buffer(including the terminating null ) + * Parameter: format - fromat string + * Parameter: argList - instead of a variable number of arguments + * Return: the number of characters printed(not including the terminating null wide characte), + * If an error occurred Return: -1. + */ + SECUREC_API int vswprintf_s(wchar_t *strDest, size_t destMax, const wchar_t *format, va_list argList); +#endif + +#if SECUREC_ENABLE_SPRINTF + + /* + * Description: The swprintf_s function is the wide-character equivalent of the sprintf_s function + * Parameter: strDest - produce output according to a format ,write to the character string strDest + * Parameter: destMax - The maximum length of destination buffer(including the terminating null ) + * Parameter: format - fromat string + * Return: the number of characters printed(not including the terminating null wide characte), + * If an error occurred Return: -1. + */ + SECUREC_API int swprintf_s(wchar_t *strDest, size_t destMax, const wchar_t *format, ...); +#endif + +#if SECUREC_ENABLE_FSCANF + /* + * Description: The fwscanf_s function is the wide-character equivalent of the fscanf_s function + * Parameter: stream - stdio file stream + * Parameter: format - fromat string + * Return: the number of input items assigned, If an error occurred Return: -1. + */ + SECUREC_API int fwscanf_s(FILE *stream, const wchar_t *format, ...); +#endif + +#if SECUREC_ENABLE_VFSCANF + /* + * Description: The vfwscanf_s function is the wide-character equivalent of the vfscanf_s function + * Parameter: stream - stdio file stream + * Parameter: format - fromat string + * Parameter: argList - instead of a variable number of arguments + * Return: the number of input items assigned, If an error occurred Return: -1. + */ + SECUREC_API int vfwscanf_s(FILE *stream, const wchar_t *format, va_list argList); +#endif + +#if SECUREC_ENABLE_SCANF + /* + * Description: The wscanf_s function is the wide-character equivalent of the scanf_s function + * Parameter: format - fromat string + * Return: the number of input items assigned, If an error occurred Return: -1. + */ + SECUREC_API int wscanf_s(const wchar_t *format, ...); +#endif + +#if SECUREC_ENABLE_VSCANF + /* + * Description: The vwscanf_s function is the wide-character equivalent of the vscanf_s function + * Parameter: format - fromat string + * Parameter: argList - instead of a variable number of arguments + * Return: the number of input items assigned, If an error occurred Return: -1. + */ + SECUREC_API int vwscanf_s(const wchar_t *format, va_list argList); +#endif + +#if SECUREC_ENABLE_SSCANF + /* + * Description: The swscanf_s function is the wide-character equivalent of the sscanf_s function + * Parameter: buffer - read character from buffer + * Parameter: format - fromat string + * Return: the number of input items assigned, If an error occurred Return: -1. + */ + SECUREC_API int swscanf_s(const wchar_t *buffer, const wchar_t *format, ...); +#endif + +#if SECUREC_ENABLE_VSSCANF + /* + * Description: The vswscanf_s function is the wide-character equivalent of the vsscanf_s function + * Parameter: buffer - read character from buffer + * Parameter: format - fromat string + * Parameter: argList - instead of a variable number of arguments + * Return: the number of input items assigned, If an error occurred Return: -1. + */ + SECUREC_API int vswscanf_s(const wchar_t *buffer, const wchar_t *format, va_list argList); +#endif +#endif /* SECUREC_ENABLE_WCHAR_FUNC */ +#endif + + /* Those functions are used by macro ,must declare hare , also for without function declaration warning */ + extern errno_t strncpy_error(char *strDest, size_t destMax, const char *strSrc, size_t count); + extern errno_t strcpy_error(char *strDest, size_t destMax, const char *strSrc); + +#if SECUREC_WITH_PERFORMANCE_ADDONS + /* Those functions are used by macro */ + extern errno_t memset_sOptAsm(void *dest, size_t destMax, int c, size_t count); + extern errno_t memset_sOptTc(void *dest, size_t destMax, int c, size_t count); + extern errno_t memcpy_sOptAsm(void *dest, size_t destMax, const void *src, size_t count); + extern errno_t memcpy_sOptTc(void *dest, size_t destMax, const void *src, size_t count); + +/* The strcpy_sp is a macro, not a function in performance optimization mode. */ +#define strcpy_sp(dest, destMax, src) ((__builtin_constant_p((destMax)) && \ + __builtin_constant_p((src))) ? \ + SECUREC_STRCPY_SM((dest), (destMax), (src)) : \ + strcpy_s((dest), (destMax), (src))) + +/* The strncpy_sp is a macro, not a function in performance optimization mode. */ +#define strncpy_sp(dest, destMax, src, count) ((__builtin_constant_p((count)) && \ + __builtin_constant_p((destMax)) && \ + __builtin_constant_p((src))) ? \ + SECUREC_STRNCPY_SM((dest), (destMax), (src), (count)) : \ + strncpy_s((dest), (destMax), (src), (count))) + +/* The strcat_sp is a macro, not a function in performance optimization mode. */ +#define strcat_sp(dest, destMax, src) ((__builtin_constant_p((destMax)) && \ + __builtin_constant_p((src))) ? \ + SECUREC_STRCAT_SM((dest), (destMax), (src)) : \ + strcat_s((dest), (destMax), (src))) + +/* The strncat_sp is a macro, not a function in performance optimization mode. */ +#define strncat_sp(dest, destMax, src, count) ((__builtin_constant_p((count)) && \ + __builtin_constant_p((destMax)) && \ + __builtin_constant_p((src))) ? \ + SECUREC_STRNCAT_SM((dest), (destMax), (src), (count)) : \ + strncat_s((dest), (destMax), (src), (count))) + +/* The memcpy_sp is a macro, not a function in performance optimization mode. */ +#define memcpy_sp(dest, destMax, src, count) (__builtin_constant_p((count)) ? \ + (SECUREC_MEMCPY_SM((dest), (destMax), (src), (count))) : \ + (__builtin_constant_p((destMax)) ? \ + (((size_t)(destMax) > 0 && \ + (((unsigned long long)(destMax) & (unsigned long long)(-2)) < SECUREC_MEM_MAX_LEN)) ? \ + memcpy_sOptTc((dest), (destMax), (src), (count)) : ERANGE) : \ + memcpy_sOptAsm((dest), (destMax), (src), (count)))) + +/* The memset_sp is a macro, not a function in performance optimization mode. */ +#define memset_sp(dest, destMax, c, count) (__builtin_constant_p((count)) ? \ + (SECUREC_MEMSET_SM((dest), (destMax), (c), (count))) : \ + (__builtin_constant_p((destMax)) ? \ + (((((unsigned long long)(destMax) & (unsigned long long)(-2)) < SECUREC_MEM_MAX_LEN)) ? \ + memset_sOptTc((dest), (destMax), (c), (count)) : ERANGE) : \ + memset_sOptAsm((dest), (destMax), (c), (count)))) +#else +#define strcpy_sp strcpy_s +#define strncpy_sp strncpy_s +#define strcat_sp strcat_s +#define strncat_sp strncat_s +#define memcpy_sp memcpy_s +#define memset_sp memset_s +#endif + +#ifdef __cplusplus +} +#endif /* __cplusplus */ +#endif /* __SECUREC_H__5D13A042_DC3F_4ED9_A8D1_882811274C27 */ + diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libsec/include/securectype.h b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libsec/include/securectype.h new file mode 100644 index 0000000000000000000000000000000000000000..ce848b4bd1769a75a2ee79938016560118bb1087 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libsec/include/securectype.h @@ -0,0 +1,566 @@ +/* + * Copyright (c) Huawei Technologies Co., Ltd. 2014-2018. All rights reserved. + * Description: Define internal used macro and data type. The marco of SECUREC_ON_64BITS + * will be determined in this header file, which is a switch for part + * of code. Some macro are used to supress warning by MS compiler. + * Author: lishunda + * Create: 2014-02-25 + * Notes: User can change the value of SECUREC_STRING_MAX_LEN and SECUREC_MEM_MAX_LEN + * macro to meet their special need, but The maximum value should not exceed 2G. + * History: 2018-09-27 zhaozhijian Code base quality improvement + */ +/* + * [Standardize-exceptions]: Performance-sensitive + * [reason]: Strict parameter verification has been done before use + */ + +#ifndef __SECURECTYPE_H__A7BBB686_AADA_451B_B9F9_44DACDAE18A7 +#define __SECURECTYPE_H__A7BBB686_AADA_451B_B9F9_44DACDAE18A7 + +#ifndef SECUREC_USING_STD_SECURE_LIB +#if defined(_MSC_VER) && _MSC_VER >= 1400 +#if defined(__STDC_WANT_SECURE_LIB__) && __STDC_WANT_SECURE_LIB__ == 0 +/* Security functions have been provided since vs2005, default use of system library functions */ +#define SECUREC_USING_STD_SECURE_LIB 0 +#else +#define SECUREC_USING_STD_SECURE_LIB 1 +#endif +#else +#define SECUREC_USING_STD_SECURE_LIB 0 +#endif +#endif + + +/* Compatibility with older Secure C versions, shielding VC symbol redefinition warning */ +#if defined(_MSC_VER) && _MSC_VER >= 1400 && SECUREC_USING_STD_SECURE_LIB == 0 +#ifndef SECUREC_DISABLE_CRT_FUNC +#define SECUREC_DISABLE_CRT_FUNC 1 +#endif +#ifndef SECUREC_DISABLE_CRT_IMP +#define SECUREC_DISABLE_CRT_IMP 1 +#endif +#else /* MSC VER */ +#ifndef SECUREC_DISABLE_CRT_FUNC +#define SECUREC_DISABLE_CRT_FUNC 0 +#endif +#ifndef SECUREC_DISABLE_CRT_IMP +#define SECUREC_DISABLE_CRT_IMP 0 +#endif +#endif + +#if SECUREC_DISABLE_CRT_FUNC +#ifdef __STDC_WANT_SECURE_LIB__ +#undef __STDC_WANT_SECURE_LIB__ +#endif +#define __STDC_WANT_SECURE_LIB__ 0 +#endif + +#if SECUREC_DISABLE_CRT_IMP +#ifdef _CRTIMP_ALTERNATIVE +#undef _CRTIMP_ALTERNATIVE +#endif +#define _CRTIMP_ALTERNATIVE /* Comment microsoft *_s function */ +#endif + +/* Compile in kernel under macro control */ +#ifndef SECUREC_IN_KERNEL +#ifdef __KERNEL__ +#define SECUREC_IN_KERNEL 1 +#else +#define SECUREC_IN_KERNEL 0 +#endif +#endif + +#if SECUREC_IN_KERNEL +#ifndef SECUREC_ENABLE_SCANF_FILE +#define SECUREC_ENABLE_SCANF_FILE 0 +#endif +#ifndef SECUREC_ENABLE_WCHAR_FUNC +#define SECUREC_ENABLE_WCHAR_FUNC 0 +#endif +#else /* SECUREC_IN_KERNEL */ +#ifndef SECUREC_ENABLE_SCANF_FILE +#define SECUREC_ENABLE_SCANF_FILE 1 +#endif +#ifndef SECUREC_ENABLE_WCHAR_FUNC +#define SECUREC_ENABLE_WCHAR_FUNC 1 +#endif +#endif + + +/* Default secure function declaration, default declarations for non-standard functions */ +#ifndef SECUREC_SNPRINTF_TRUNCATED +#define SECUREC_SNPRINTF_TRUNCATED 1 +#endif + +#if SECUREC_USING_STD_SECURE_LIB +#if defined(_MSC_VER) && _MSC_VER >= 1400 +/* Declare secure functions that are not available in the VS compiler */ +#ifndef SECUREC_ENABLE_MEMSET +#define SECUREC_ENABLE_MEMSET 1 +#endif +/* VS 2005 have vsnprintf_s function */ +#ifndef SECUREC_ENABLE_VSNPRINTF +#define SECUREC_ENABLE_VSNPRINTF 0 +#endif +#ifndef SECUREC_ENABLE_SNPRINTF +/* VS 2005 have vsnprintf_s function Adapt the snprintf_s of the security function */ +#define snprintf_s _snprintf_s +#define SECUREC_ENABLE_SNPRINTF 0 +#endif +/* Before VS 2010 do not have v functions */ +#if _MSC_VER <= 1600 || defined(SECUREC_FOR_V_SCANFS) +#ifndef SECUREC_ENABLE_VFSCANF +#define SECUREC_ENABLE_VFSCANF 1 +#endif +#ifndef SECUREC_ENABLE_VSCANF +#define SECUREC_ENABLE_VSCANF 1 +#endif +#ifndef SECUREC_ENABLE_VSSCANF +#define SECUREC_ENABLE_VSSCANF 1 +#endif +#endif + +#else /* MSC VER */ +#ifndef SECUREC_ENABLE_MEMSET +#define SECUREC_ENABLE_MEMSET 0 +#endif +#ifndef SECUREC_ENABLE_SNPRINTF +#define SECUREC_ENABLE_SNPRINTF 0 +#endif +#ifndef SECUREC_ENABLE_VSNPRINTF +#define SECUREC_ENABLE_VSNPRINTF 0 +#endif +#endif + +#ifndef SECUREC_ENABLE_MEMMOVE +#define SECUREC_ENABLE_MEMMOVE 0 +#endif +#ifndef SECUREC_ENABLE_MEMCPY +#define SECUREC_ENABLE_MEMCPY 0 +#endif +#ifndef SECUREC_ENABLE_STRCPY +#define SECUREC_ENABLE_STRCPY 0 +#endif +#ifndef SECUREC_ENABLE_STRNCPY +#define SECUREC_ENABLE_STRNCPY 0 +#endif +#ifndef SECUREC_ENABLE_STRCAT +#define SECUREC_ENABLE_STRCAT 0 +#endif +#ifndef SECUREC_ENABLE_STRNCAT +#define SECUREC_ENABLE_STRNCAT 0 +#endif +#ifndef SECUREC_ENABLE_SPRINTF +#define SECUREC_ENABLE_SPRINTF 0 +#endif +#ifndef SECUREC_ENABLE_VSPRINTF +#define SECUREC_ENABLE_VSPRINTF 0 +#endif +#ifndef SECUREC_ENABLE_SSCANF +#define SECUREC_ENABLE_SSCANF 0 +#endif +#ifndef SECUREC_ENABLE_VSSCANF +#define SECUREC_ENABLE_VSSCANF 0 +#endif +#ifndef SECUREC_ENABLE_SCANF +#define SECUREC_ENABLE_SCANF 0 +#endif +#ifndef SECUREC_ENABLE_VSCANF +#define SECUREC_ENABLE_VSCANF 0 +#endif + +#ifndef SECUREC_ENABLE_FSCANF +#define SECUREC_ENABLE_FSCANF 0 +#endif +#ifndef SECUREC_ENABLE_VFSCANF +#define SECUREC_ENABLE_VFSCANF 0 +#endif +#ifndef SECUREC_ENABLE_STRTOK +#define SECUREC_ENABLE_STRTOK 0 +#endif +#ifndef SECUREC_ENABLE_GETS +#define SECUREC_ENABLE_GETS 0 +#endif + +#else /* SECUREC USE STD SECURE LIB */ + +#ifndef SECUREC_ENABLE_MEMSET +#define SECUREC_ENABLE_MEMSET 1 +#endif +#ifndef SECUREC_ENABLE_MEMMOVE +#define SECUREC_ENABLE_MEMMOVE 1 +#endif +#ifndef SECUREC_ENABLE_MEMCPY +#define SECUREC_ENABLE_MEMCPY 1 +#endif +#ifndef SECUREC_ENABLE_STRCPY +#define SECUREC_ENABLE_STRCPY 1 +#endif +#ifndef SECUREC_ENABLE_STRNCPY +#define SECUREC_ENABLE_STRNCPY 1 +#endif +#ifndef SECUREC_ENABLE_STRCAT +#define SECUREC_ENABLE_STRCAT 1 +#endif +#ifndef SECUREC_ENABLE_STRNCAT +#define SECUREC_ENABLE_STRNCAT 1 +#endif +#ifndef SECUREC_ENABLE_SPRINTF +#define SECUREC_ENABLE_SPRINTF 1 +#endif +#ifndef SECUREC_ENABLE_VSPRINTF +#define SECUREC_ENABLE_VSPRINTF 1 +#endif +#ifndef SECUREC_ENABLE_SNPRINTF +#define SECUREC_ENABLE_SNPRINTF 1 +#endif +#ifndef SECUREC_ENABLE_VSNPRINTF +#define SECUREC_ENABLE_VSNPRINTF 1 +#endif +#ifndef SECUREC_ENABLE_SSCANF +#define SECUREC_ENABLE_SSCANF 1 +#endif +#ifndef SECUREC_ENABLE_VSSCANF +#define SECUREC_ENABLE_VSSCANF 1 +#endif +#ifndef SECUREC_ENABLE_SCANF +#if SECUREC_ENABLE_SCANF_FILE +#define SECUREC_ENABLE_SCANF 1 +#else +#define SECUREC_ENABLE_SCANF 0 +#endif +#endif +#ifndef SECUREC_ENABLE_VSCANF +#if SECUREC_ENABLE_SCANF_FILE +#define SECUREC_ENABLE_VSCANF 1 +#else +#define SECUREC_ENABLE_VSCANF 0 +#endif +#endif + +#ifndef SECUREC_ENABLE_FSCANF +#if SECUREC_ENABLE_SCANF_FILE +#define SECUREC_ENABLE_FSCANF 1 +#else +#define SECUREC_ENABLE_FSCANF 0 +#endif +#endif +#ifndef SECUREC_ENABLE_VFSCANF +#if SECUREC_ENABLE_SCANF_FILE +#define SECUREC_ENABLE_VFSCANF 1 +#else +#define SECUREC_ENABLE_VFSCANF 0 +#endif +#endif + +#ifndef SECUREC_ENABLE_STRTOK +#define SECUREC_ENABLE_STRTOK 1 +#endif +#ifndef SECUREC_ENABLE_GETS +#define SECUREC_ENABLE_GETS 1 +#endif +#endif /* SECUREC_USE_STD_SECURE_LIB */ + +#if SECUREC_ENABLE_SCANF_FILE == 0 +#if SECUREC_ENABLE_FSCANF +#undef SECUREC_ENABLE_FSCANF +#define SECUREC_ENABLE_FSCANF 0 +#endif +#if SECUREC_ENABLE_VFSCANF +#undef SECUREC_ENABLE_VFSCANF +#define SECUREC_ENABLE_VFSCANF 0 +#endif +#if SECUREC_ENABLE_SCANF +#undef SECUREC_ENABLE_SCANF +#define SECUREC_ENABLE_SCANF 0 +#endif +#if SECUREC_ENABLE_FSCANF +#undef SECUREC_ENABLE_FSCANF +#define SECUREC_ENABLE_FSCANF 0 +#endif + +#endif + +#if SECUREC_IN_KERNEL +#include +#include +#else +#ifndef SECUREC_HAVE_STDIO_H +#define SECUREC_HAVE_STDIO_H 1 +#endif +#ifndef SECUREC_HAVE_STRING_H +#define SECUREC_HAVE_STRING_H 1 +#endif +#ifndef SECUREC_HAVE_STDLIB_H +#define SECUREC_HAVE_STDLIB_H 1 +#endif +#if SECUREC_HAVE_STDIO_H +#include +#endif +#if SECUREC_HAVE_STRING_H +#include +#endif +#if SECUREC_HAVE_STDLIB_H +#include +#endif +#endif + +/* + * If you need high performance, enable the SECUREC_WITH_PERFORMANCE_ADDONS macro, default is enable. + * The macro is automatically closed on the windows platform and linux kernel + */ +#ifndef SECUREC_WITH_PERFORMANCE_ADDONS +#if SECUREC_IN_KERNEL +#define SECUREC_WITH_PERFORMANCE_ADDONS 0 +#else +#define SECUREC_WITH_PERFORMANCE_ADDONS 0 +#endif +#endif + +/* If enable SECUREC_COMPATIBLE_WIN_FORMAT, the output format will be compatible to Windows. */ +#if (defined(_WIN32) || defined(_WIN64) || defined(_MSC_VER)) && !defined(SECUREC_COMPATIBLE_LINUX_FORMAT) +#ifndef SECUREC_COMPATIBLE_WIN_FORMAT +#define SECUREC_COMPATIBLE_WIN_FORMAT +#endif +#endif + +#if defined(SECUREC_COMPATIBLE_WIN_FORMAT) +/* On windows platform, can't use optimized function for there is no __builtin_constant_p like function */ +/* If need optimized macro, can define this: define __builtin_constant_p(x) 0 */ +#ifdef SECUREC_WITH_PERFORMANCE_ADDONS +#undef SECUREC_WITH_PERFORMANCE_ADDONS +#define SECUREC_WITH_PERFORMANCE_ADDONS 0 +#endif +#endif + +#if defined(__VXWORKS__) || defined(__vxworks) || defined(__VXWORKS) || defined(_VXWORKS_PLATFORM_) || \ + defined(SECUREC_VXWORKS_VERSION_5_4) +#ifndef SECUREC_VXWORKS_PLATFORM +#define SECUREC_VXWORKS_PLATFORM +#endif +#endif + +/* If enable SECUREC_COMPATIBLE_LINUX_FORMAT, the output format will be compatible to Linux. */ +#if !defined(SECUREC_COMPATIBLE_WIN_FORMAT) && !defined(SECUREC_VXWORKS_PLATFORM) +#ifndef SECUREC_COMPATIBLE_LINUX_FORMAT +#define SECUREC_COMPATIBLE_LINUX_FORMAT +#endif +#endif + +#ifdef SECUREC_COMPATIBLE_LINUX_FORMAT +#ifndef SECUREC_HAVE_STDDEF_H +#define SECUREC_HAVE_STDDEF_H 1 +#endif +/* Some system may no stddef.h */ +#if SECUREC_HAVE_STDDEF_H +#include +#endif +#endif + +/* + * Add the -DSECUREC_SUPPORT_FORMAT_WARNING compiler option to supoort -Wformat. + * Default does not check the format is that the same data type in the actual code. + * In the product is different in the original data type definition of VxWorks and Linux. + */ +#ifndef SECUREC_SUPPORT_FORMAT_WARNING +#define SECUREC_SUPPORT_FORMAT_WARNING 0 +#endif + +/* SECUREC_PCLINT for tool do not recognize __attribute__ just for pclint */ +#if SECUREC_SUPPORT_FORMAT_WARNING && !defined(SECUREC_PCLINT) +#define SECUREC_ATTRIBUTE(x, y) __attribute__((format(printf, (x), (y)))) +#else +#define SECUREC_ATTRIBUTE(x, y) +#endif + +/* SECUREC_PCLINT for tool do not recognize __builtin_expect, just for pclint */ +#if defined(__GNUC__) && \ + ((__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ > 3))) && \ + !defined(SECUREC_PCLINT) +/* + * This is a built-in function that can be used without a declaration, if you encounter an undeclared compilation alarm, + * you can add -DSECUREC_NEED_BUILTIN_EXPECT_DECLARE to complier options + */ +#ifdef SECUREC_NEED_BUILTIN_EXPECT_DECLARE +long __builtin_expect(long exp, long c); +#endif +#define SECUREC_LIKELY(x) __builtin_expect(!!(x), 1) +#define SECUREC_UNLIKELY(x) __builtin_expect(!!(x), 0) +#else +#define SECUREC_LIKELY(x) (x) +#define SECUREC_UNLIKELY(x) (x) +#endif + +/* Define the max length of the string */ +#ifndef SECUREC_STRING_MAX_LEN +#define SECUREC_STRING_MAX_LEN 0x7fffffffUL +#endif +#define SECUREC_WCHAR_STRING_MAX_LEN (SECUREC_STRING_MAX_LEN / sizeof(wchar_t)) + +/* Add SECUREC_MEM_MAX_LEN for memcpy and memmove */ +#ifndef SECUREC_MEM_MAX_LEN +#define SECUREC_MEM_MAX_LEN 0x7fffffffUL +#endif +#define SECUREC_WCHAR_MEM_MAX_LEN (SECUREC_MEM_MAX_LEN / sizeof(wchar_t)) + +#if SECUREC_STRING_MAX_LEN > 0x7fffffff +#error "max string is 2G" +#endif + +#if (defined(__GNUC__) && defined(__SIZEOF_POINTER__)) +#if (__SIZEOF_POINTER__ != 4) && (__SIZEOF_POINTER__ != 8) +#error "unsupported system" +#endif +#endif + +#if defined(_WIN64) || defined(WIN64) || defined(__LP64__) || defined(_LP64) +#define SECUREC_ON_64BITS +#endif + +#if (!defined(SECUREC_ON_64BITS) && defined(__GNUC__) && defined(__SIZEOF_POINTER__)) +#if __SIZEOF_POINTER__ == 8 +#define SECUREC_ON_64BITS +#endif +#endif + +#if defined(__SVR4) || defined(__svr4__) +#define SECUREC_ON_SOLARIS +#endif + +#if (defined(__hpux) || defined(_AIX) || defined(SECUREC_ON_SOLARIS)) +#define SECUREC_ON_UNIX +#endif + +/* + * Codes should run under the macro SECUREC_COMPATIBLE_LINUX_FORMAT in unknow system on default, + * and strtold. + * The function strtold is referenced first at ISO9899:1999(C99), and some old compilers can + * not support these functions. Here provides a macro to open these functions: + * SECUREC_SUPPORT_STRTOLD -- If defined, strtold will be used + */ +#ifndef SECUREC_SUPPORT_STRTOLD +#define SECUREC_SUPPORT_STRTOLD 0 +#if (defined(SECUREC_COMPATIBLE_LINUX_FORMAT)) +#if defined(__USE_ISOC99) || \ + (defined(_AIX) && defined(_ISOC99_SOURCE)) || \ + (defined(__hpux) && defined(__ia64)) || \ + (defined(SECUREC_ON_SOLARIS) && (!defined(_STRICT_STDC) && !defined(__XOPEN_OR_POSIX)) || \ + defined(_STDC_C99) || defined(__EXTENSIONS__)) +#undef SECUREC_SUPPORT_STRTOLD +#define SECUREC_SUPPORT_STRTOLD 1 +#endif +#endif +#if ((defined(SECUREC_WRLINUX_BELOW4) || defined(_WRLINUX_BELOW4_))) +#undef SECUREC_SUPPORT_STRTOLD +#define SECUREC_SUPPORT_STRTOLD 0 +#endif +#endif + + +#if SECUREC_WITH_PERFORMANCE_ADDONS + +#ifndef SECUREC_TWO_MIN +#define SECUREC_TWO_MIN(a, b) ((a) < (b) ? (a) : (b)) +#endif + +/* For strncpy_s performance optimization */ +#define SECUREC_STRNCPY_SM(dest, destMax, src, count) \ + (((void *)(dest) != NULL && (void *)(src) != NULL && (size_t)(destMax) > 0 && \ + (((unsigned long long)(destMax) & (unsigned long long)(-2)) < SECUREC_STRING_MAX_LEN) && \ + (SECUREC_TWO_MIN((size_t)(count), strlen(src)) + 1) <= (size_t)(destMax)) ? \ + (((size_t)(count) < strlen(src)) ? (memcpy((dest), (src), (count)), *((char *)(dest) + (count)) = '\0', EOK) : \ + (memcpy((dest), (src), strlen(src) + 1), EOK)) : (strncpy_error((dest), (destMax), (src), (count)))) + +#define SECUREC_STRCPY_SM(dest, destMax, src) \ + (((void *)(dest) != NULL && (void *)(src) != NULL && (size_t)(destMax) > 0 && \ + (((unsigned long long)(destMax) & (unsigned long long)(-2)) < SECUREC_STRING_MAX_LEN) && \ + (strlen(src) + 1) <= (size_t)(destMax)) ? (memcpy((dest), (src), strlen(src) + 1), EOK) : \ + (strcpy_error((dest), (destMax), (src)))) + +/* For strcat_s performance optimization */ +#if defined(__GNUC__) +#define SECUREC_STRCAT_SM(dest, destMax, src) ({ \ + int catRet = EOK; \ + if ((void *)(dest) != NULL && (void *)(src) != NULL && (size_t)(destMax) > 0 && \ + (((unsigned long long)(destMax) & (unsigned long long)(-2)) < SECUREC_STRING_MAX_LEN)) { \ + char *catTmpDst = (char *)(dest); \ + size_t catRestSize = (destMax); \ + while (catRestSize > 0 && *catTmpDst != '\0') { \ + ++catTmpDst; \ + --catRestSize; \ + } \ + if (catRestSize == 0) { \ + catRet = EINVAL; \ + } else if ((strlen(src) + 1) <= catRestSize) { \ + memcpy(catTmpDst, (src), strlen(src) + 1); \ + catRet = EOK; \ + } else { \ + catRet = ERANGE; \ + } \ + if (catRet != EOK) { \ + catRet = strcat_s((dest), (destMax), (src)); \ + } \ + } else { \ + catRet = strcat_s((dest), (destMax), (src)); \ + } \ + catRet; \ +}) +#else +#define SECUREC_STRCAT_SM(dest, destMax, src) strcat_s((dest), (destMax), (src)) +#endif + +/* For strncat_s performance optimization */ +#if defined(__GNUC__) +#define SECUREC_STRNCAT_SM(dest, destMax, src, count) ({ \ + int ncatRet = EOK; \ + if ((void *)(dest) != NULL && (void *)(src) != NULL && (size_t)(destMax) > 0 && \ + (((unsigned long long)(destMax) & (unsigned long long)(-2)) < SECUREC_STRING_MAX_LEN) && \ + (((unsigned long long)(count) & (unsigned long long)(-2)) < SECUREC_STRING_MAX_LEN)) { \ + char *ncatTmpDest = (char *)(dest); \ + size_t ncatRestSize = (size_t)(destMax); \ + while (ncatRestSize > 0 && *ncatTmpDest != '\0') { \ + ++ncatTmpDest; \ + --ncatRestSize; \ + } \ + if (ncatRestSize == 0) { \ + ncatRet = EINVAL; \ + } else if ((SECUREC_TWO_MIN((count), strlen(src)) + 1) <= ncatRestSize) { \ + if ((size_t)(count) < strlen(src)) { \ + memcpy(ncatTmpDest, (src), (count)); \ + *(ncatTmpDest + (count)) = '\0'; \ + } else { \ + memcpy(ncatTmpDest, (src), strlen(src) + 1); \ + } \ + } else { \ + ncatRet = ERANGE; \ + } \ + if (ncatRet != EOK) { \ + ncatRet = strncat_s((dest), (destMax), (src), (count)); \ + } \ + } else { \ + ncatRet = strncat_s((dest), (destMax), (src), (count)); \ + } \ + ncatRet; \ +}) +#else +#define SECUREC_STRNCAT_SM(dest, destMax, src, count) strncat_s((dest), (destMax), (src), (count)) +#endif + +/* This macro do not check buffer overlap by default */ +#define SECUREC_MEMCPY_SM(dest, destMax, src, count) \ + (!(((size_t)(destMax) == 0) || \ + (((unsigned long long)(destMax) & (unsigned long long)(-2)) > SECUREC_MEM_MAX_LEN) || \ + ((size_t)(count) > (size_t)(destMax)) || ((void *)(dest)) == NULL || ((void *)(src) == NULL)) ? \ + (memcpy((dest), (src), (count)), EOK) : \ + (memcpy_s((dest), (destMax), (src), (count)))) + +#define SECUREC_MEMSET_SM(dest, destMax, c, count) \ + (!((((unsigned long long)(destMax) & (unsigned long long)(-2)) > SECUREC_MEM_MAX_LEN) || \ + ((void *)(dest) == NULL) || ((size_t)(count) > (size_t)(destMax))) ? \ + (memset((dest), (c), (count)), EOK) : \ + (memset_s((dest), (destMax), (c), (count)))) + +#endif +#endif /* __SECURECTYPE_H__A7BBB686_AADA_451B_B9F9_44DACDAE18A7 */ + diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/kernel/base/include/los_base_pri.h b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/base/include/los_base_pri.h new file mode 100644 index 0000000000000000000000000000000000000000..ef14b7008b892fa05d68e3d783cc6bd0359f3e73 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/base/include/los_base_pri.h @@ -0,0 +1,58 @@ +/* ---------------------------------------------------------------------------- + * Copyright (c) Huawei Technologies Co., Ltd. 2013-2018. All rights reserved. + * Description: Basic definitions + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * --------------------------------------------------------------------------- */ + +#ifndef _LOS_BASE_PRI_H +#define _LOS_BASE_PRI_H + +#include "los_base.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +/** + * @ingroup los_base + * Define the CPU Tick structure. + */ +typedef struct tagCpuTick { + UINT32 cntHi; /* < Upper 32 bits of the tick value */ + UINT32 cntLo; /* < Lower 32 bits of the tick value */ +} CpuTick; + +#define OS_GOTO_ERREND() \ + do { \ + goto LOS_ERREND; \ + } while (0) + +#ifdef __cplusplus +#if __cplusplus +} +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +#endif /* _LOS_BASE_PRI_H */ diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/kernel/base/include/los_memory_pri.h b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/base/include/los_memory_pri.h new file mode 100644 index 0000000000000000000000000000000000000000..698c08feab7a30abec487508be5e1eef1e56b08e --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/base/include/los_memory_pri.h @@ -0,0 +1,230 @@ +/* ---------------------------------------------------------------------------- + * Copyright (c) Huawei Technologies Co., Ltd. 2013-2015. All rights reserved. + * Description: LiteOS memory Module Implementation + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * --------------------------------------------------------------------------- */ + +#ifndef _LOS_MEMORY_PRI_H +#define _LOS_MEMORY_PRI_H + +#include "los_memory.h" +#include "los_memstat_pri.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +#define OS_MEM_ENABLE_MEM_STATISTICS + +#ifdef OS_MEM_ENABLE_MEM_STATISTICS +#define OS_MEM_ADD_USED(size, taskID) OsTaskMemUsedInc(size, taskID) +#define OS_MEM_REDUCE_USED(size, taskID) OsTaskMemUsedDec(size, taskID) +#else +#define OS_MEM_ADD_USED(size, taskID) +#define OS_MEM_REDUCE_USED(size, taskID) +#endif + +/** + * @ingroup los_memory + * Memory linked list node structure + */ +typedef struct tagLosMemDynNode { + LOS_DL_LIST freeNodeInfo; /**< Free memory node */ + struct tagLosMemDynNode *preNode; /**< Pointer to the previous memory node */ + UINT32 sizeAndFlag; /**< Size and flag of the current node(the highest bit + represents a flag, and the rest bits specify the size) */ +} LosMemDynNode; + +typedef VOID (*MemNodeHook)(LosMemDynNode *tmpNode); +extern MemNodeHook g_memAllocFinishHook; +extern MemNodeHook g_memFreeHook; + +#ifdef LOSCFG_DEBUG_KASAN +extern LITE_OS_RAM_SECTION void Asan_malloc_set(LosMemDynNode *allocNode); +extern LITE_OS_RAM_SECTION void Asan_free_set(LosMemDynNode *node); +#endif + +#define IS_ALIGNED(value, alignSize) ((((UINT32)(value)) & ((UINT32)((alignSize) - 1))) == 0) +#define OS_MEM_TASKID_SET(node, ID) \ + do { \ + UINTPTR tmp = (UINTPTR)(((LosMemDynNode *)(node))->freeNodeInfo.pstNext); \ + tmp = tmp & 0xffff0000; \ + tmp |= (ID); \ + ((LosMemDynNode *)(node))->freeNodeInfo.pstNext = (LOS_DL_LIST *)(tmp); \ + } while (0) + +#define OS_MEM_TASKID_GET(node) ((UINT32)(UINTPTR)(((LosMemDynNode *)(node))->freeNodeInfo.pstNext) & 0xffff) +#define OS_MEM_ALIGN(p, alignSize) (((unsigned int)(p) + (alignSize) - 1) & ~((alignSize) - 1)) +#define OS_MEM_NODE_HEAD_SIZE sizeof(LosMemDynNode) +#define OS_MEM_MIN_POOL_SIZE (OS_DLNK_HEAD_SIZE + (2 * OS_MEM_NODE_HEAD_SIZE) + sizeof(LosMemPoolInfo)) +#define OS_MEM_ALIGN_SIZE 4 +#define OS_MEM_NODE_USED_FLAG 0x80000000 +#define OS_MEM_NODE_ALIGNED_FLAG 0x40000000 +#define OS_EXC_ERR_NODE_RANGE 0x40 +#define OS_MEM_NODE_ALIGN_SIZE 64 +#define OS_MEM_NODE_DATA_SIZE 4 + +#define OS_MEM_NODE_GET_ALIGNED_FLAG(sizeAndFlag) ((sizeAndFlag) & OS_MEM_NODE_ALIGNED_FLAG) +#define OS_MEM_NODE_SET_ALIGNED_FLAG(sizeAndFlag) ((sizeAndFlag) = ((sizeAndFlag) | OS_MEM_NODE_ALIGNED_FLAG)) +#define OS_MEM_NODE_GET_ALIGNED_GAPSIZE(sizeAndFlag) ((sizeAndFlag) & (~OS_MEM_NODE_ALIGNED_FLAG)) +#define OS_MEM_NODE_GET_USED_FLAG(sizeAndFlag) ((sizeAndFlag) & OS_MEM_NODE_USED_FLAG) +#define OS_MEM_NODE_SET_USED_FLAG(sizeAndFlag) ((sizeAndFlag) = ((sizeAndFlag) | OS_MEM_NODE_USED_FLAG)) +#define OS_MEM_NODE_GET_SIZE(sizeAndFlag) ((sizeAndFlag) & (~OS_MEM_NODE_USED_FLAG)) +#define OS_MEM_IS_NODE_NEXT_EXIST(node, poolInfo) (((UINT32)(node) + (node)->sizeAndFlag) < \ + ((UINT32)(poolInfo) + (poolInfo)->uwPoolSize)) +#define OS_MEM_HEAD(pool, size) OS_DLNK_HEAD(OS_MEM_HEAD_ADDR(pool), size) +#define OS_MEM_HEAD_ADDR(pool) ((VOID *)((UINT32)(UINTPTR)(pool) + sizeof(LosMemPoolInfo))) +#define OS_MEM_NEXT_NODE(node) ((LosMemDynNode *)((UINT8 *)(node) + OS_MEM_NODE_GET_SIZE((node)->sizeAndFlag))) +#define OS_MEM_FIRST_NODE(pool) ((LosMemDynNode *)((UINT8 *)OS_MEM_HEAD_ADDR(pool) + OS_DLNK_HEAD_SIZE)) +#define OS_MEM_END_NODE(pool, size) ((LosMemDynNode *)(((UINT8 *)(pool) + (size)) - OS_MEM_NODE_HEAD_SIZE)) +#define OS_MEM_MIDDLE_ADDR_OPEN_END(startAddr, middleAddr, endAddr) \ + (((UINT8 *)(startAddr) <= (UINT8 *)(middleAddr)) && ((UINT8 *)(middleAddr) < (UINT8 *)(endAddr))) +#define OS_MEM_MIDDLE_ADDR(startAddr, middleAddr, endAddr) (((UINT8 *)(startAddr) <= (UINT8 *)(middleAddr)) && \ + ((UINT8 *)(middleAddr) <= (UINT8 *)(endAddr))) +#define OS_MEM_SET_MAGIC(value) (value) = (LOS_DL_LIST *)(UINTPTR)((UINT32)(UINTPTR)(&(value)) ^ 0xffffffff) +#define OS_MEM_MAGIC_VALID(value) ((((UINT32)(UINTPTR)(value)) ^ ((UINT32)(UINTPTR)(&(value)))) == 0xffffffff) + +/** + * @ingroup los_memory + * Memory pool information structure + */ +typedef struct tagLosMemPoolInfo { + VOID *poolAddr; /**< Starting address of a memory pool */ + UINT32 poolSize; /**< Memory pool size */ + UINT32 poolFailCount; /**< Memory pool malloc failed times */ +#if defined(LOSCFG_MEM_WATERLINE) && (LOSCFG_MEM_WATERLINE == YES) + UINT32 poolWaterLine; /**< Maximum usage size in a memory pool */ + UINT32 poolCurUsedSize; /**< Current usage size in a memory pool */ +#endif +} LosMemPoolInfo; + +/* + * memcheck error code: the stack have not inited + * Value: 0x02000100 + * Solution: do memcheck must after stack mem init + */ +#define OS_ERRNO_MEMCHECK_NOT_INIT LOS_ERRNO_OS_ERROR(LOS_MOD_MEM, 0x0) + +/* + * memcheck error code: the pPtr is NULL + * Value: 0x02000101 + * Solution: don't give a NULL parameter + */ +#define OS_ERRNO_MEMCHECK_PARA_NULL LOS_ERRNO_OS_ERROR(LOS_MOD_MEM, 0x1) + +/* + * memcheck error code: the pPtr addr not in the suit range + * Value: 0x02000102 + * Solution: check pPtr and comfirm it included by stack + */ +#define OS_ERRNO_MEMCHECK_OUTSIDE LOS_ERRNO_OS_ERROR(LOS_MOD_MEM, 0x2) + +/* + * memcheck error code: can't find the ctrl node + * Value: 0x02000103 + * Solution: confirm the pPtr if this node has been freed or has not been alloced + */ +#define OS_ERRNO_MEMCHECK_NO_HEAD LOS_ERRNO_OS_ERROR(LOS_MOD_MEM, 0x3) + +/* + * memcheck error code: the para level is wrong + * Value: 0x02000104 + * Solution: checkout the memcheck level by the func "OS_GetMemCheck_Level" + */ +#define OS_ERRNO_MEMCHECK_WRONG_LEVEL LOS_ERRNO_OS_ERROR(LOS_MOD_MEM, 0x4) + +/* + * memcheck error code: memcheck func not open + * Value: 0x02000105 + * Solution: enable memcheck by the func "OS_SetMemCheck_Level" + */ +#define OS_ERRNO_MEMCHECK_DISABLED LOS_ERRNO_OS_ERROR(LOS_MOD_MEM, 0x5) + +/* + * memcheck error code: memcheck err in LOS_MemIntegrityCheck + * Value: 0x02000106 + * Solution: memcheck error number used for err handle + */ +#define OS_ERRNO_MEMCHECK_ERR LOS_ERRNO_OS_ERROR(LOS_MOD_MEM, 0x6) + +typedef UINT32 (*OsMemAllocCheckFunc)(VOID *pool); +extern OsMemAllocCheckFunc g_memAllocCheckHook; + +typedef VOID (*OsMemFreeCheckFunc)(const VOID *pool, const LosMemDynNode *node); +extern OsMemFreeCheckFunc g_memFreeCheckHook; + +/** + * @ingroup los_memory + * @brief Initialization the memory system. + * + * @par Description: + *
        + *
      • This API is used to initialization the memory system.
      • + *
      + * @attention + *
        + *
      • None.
      • + *
      + * + * @param None. + * + * @retval UINT32 Initialization result. + * @par Dependency: + *
      • los_memory_pri.h: the header file that contains the API declaration.
      + * @see None. + */ +extern UINT32 OsMemSystemInit(VOID); + +/** + * @ingroup los_memory + * @brief Check memory when free node. + * + * @par Description: + *
        + *
      • This API is used to check memory when free node.
      • + *
      + * @attention + *
        + *
      • None.
      • + *
      + * + * @param pool [IN] A pointer pointed to the memory pool. + * @param node [IN] A pointer pointed to the free node. + * + * @retval None. + * @par Dependency: + *
      • los_memory_pri.h: the header file that contains the API declaration.
      + * @see None. + */ +extern VOID OsMemFreeNodeCheck(const VOID *pool, const LosMemDynNode *node); +extern UINT32 OsMemPoolInit(VOID); + +#ifdef __cplusplus +#if __cplusplus +} +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +#endif /* _LOS_MEMORY_PRI_H */ diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/kernel/base/include/los_memstat_pri.h b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/base/include/los_memstat_pri.h new file mode 100644 index 0000000000000000000000000000000000000000..3176393583c5ff302ac39e4284e5896cc8adebe2 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/base/include/los_memstat_pri.h @@ -0,0 +1,54 @@ +/* ---------------------------------------------------------------------------- + * Copyright (c) Huawei Technologies Co., Ltd. 2013-2015. All rights reserved. + * Description: LiteOS memory Module Implementation + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * --------------------------------------------------------------------------- */ + +#ifndef _LOS_MEMSTAT_PRI_H +#define _LOS_MEMSTAT_PRI_H + +#include "los_typedef.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +typedef struct { + UINT32 memUsed; +} TskMemUsedInfo; + +extern TskMemUsedInfo *g_tskMemUsedInfo; + +extern VOID OsTaskMemUsedInc(UINT32 usedSize, UINT32 taskID); +extern VOID OsTaskMemUsedDec(UINT32 usedSize, UINT32 taskID); +extern UINT32 OsTaskMemUsage(UINT32 taskID); + +#ifdef __cplusplus +#if __cplusplus +} +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +#endif /* _LOS_MEMSTAT_PRI_H */ diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/kernel/base/include/los_mux_pri.h b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/base/include/los_mux_pri.h new file mode 100644 index 0000000000000000000000000000000000000000..3ea24965a808480124fbe5dc9ad5084b75b1bfcf --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/base/include/los_mux_pri.h @@ -0,0 +1,104 @@ +/* ---------------------------------------------------------------------------- + * Copyright (c) Huawei Technologies Co., Ltd. 2013-2018. All rights reserved. + * Description: mutex + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * --------------------------------------------------------------------------- */ + +#ifndef _LOS_MUX_PRI_H +#define _LOS_MUX_PRI_H + +#include "los_task_pri.h" +#include "los_mux.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +/** + * @ingroup los_mux + * Mutex object. + */ +typedef struct { + UINT8 muxStat; /**< State OS_MUX_UNUSED,OS_MUX_USED */ + UINT16 muxCount; /**< Times of locking a mutex */ + UINT32 muxID; /**< Handle ID */ + LOS_DL_LIST muxList; /**< Mutex linked list */ + LosTaskCB *owner; /**< The current thread that is locking a mutex */ + UINT16 priority; /**< Priority of the thread that is locking a mutex */ +} LosMuxCB; + +/** + * @ingroup los_mux + * Mutex state: not in use. + */ +#define OS_MUX_UNUSED 0 + +/** + * @ingroup los_mux + * Mutex state: in use. + */ +#define OS_MUX_USED 1 + +extern LosMuxCB *g_allMux; + +/** + * @ingroup los_mux + * Obtain the pointer to a mutex object of the mutex that has a specified handle. + */ +#define GET_MUX(muxid) (((LosMuxCB *)g_allMux) + (muxid)) + +/** + * @ingroup los_mux + * @brief Initializes the mutex. + * + * @par Description: + * This API is used to initializes the mutex. + * @attention + *
        + *
      • None.
      • + *
      + * + * @param None. + * + * @retval UINT32 Initialization result. + * @par Dependency: + *
      • los_mux_pri.h: the header file that contains the API declaration.
      + * @see LOS_MuxDelete + */ +extern UINT32 OsMuxInit(VOID *muxArray); + +/** + * @ingroup los_mux + * Obtain the pointer to the linked list in the mutex pointed to by a specified pointer. + */ +#define GET_MUX_LIST(ptr) LOS_DL_LIST_ENTRY(ptr, LosMuxCB, muxList) + +#ifdef __cplusplus +#if __cplusplus +} +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +#endif /* _LOS_MUX_PRI_H */ diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/kernel/base/include/los_queue_pri.h b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/base/include/los_queue_pri.h new file mode 100644 index 0000000000000000000000000000000000000000..8484116c39160246fd977a97bdbac990334f5e31 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/base/include/los_queue_pri.h @@ -0,0 +1,224 @@ +/* ---------------------------------------------------------------------------- + * Copyright (c) Huawei Technologies Co., Ltd. 2013-2018. All rights reserved. + * Description: queue + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * --------------------------------------------------------------------------- */ + +#ifndef _LOS_QUEUE_PRI_H +#define _LOS_QUEUE_PRI_H + +#include "los_queue.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +typedef enum { + OS_QUEUE_READ, + OS_QUEUE_WRITE +} QueueReadWrite; + +typedef enum { + OS_QUEUE_HEAD, + OS_QUEUE_TAIL +} QueueHeadTail; + +#define OS_QUEUE_OPERATE_TYPE(ReadOrWrite, HeadOrTail) (((UINT32)(HeadOrTail) << 1) | (ReadOrWrite)) +#define OS_QUEUE_READ_WRITE_GET(type) ((type) & (0x01)) +#define OS_QUEUE_READ_HEAD ((UINT32)OS_QUEUE_READ | ((UINT32)OS_QUEUE_HEAD << 1)) +#define OS_QUEUE_READ_TAIL ((UINT32)OS_QUEUE_READ | ((UINT32)OS_QUEUE_TAIL << 1)) +#define OS_QUEUE_WRITE_HEAD ((UINT32)OS_QUEUE_WRITE | ((UINT32)OS_QUEUE_HEAD << 1)) +#define OS_QUEUE_WRITE_TAIL ((UINT32)OS_QUEUE_WRITE | ((UINT32)OS_QUEUE_TAIL << 1)) +#define OS_QUEUE_OPERATE_GET(type) ((type) & (0x03)) +#define OS_QUEUE_IS_READ(type) (OS_QUEUE_READ_WRITE_GET(type) == (UINT32)OS_QUEUE_READ) +#define OS_QUEUE_IS_WRITE(type) (OS_QUEUE_READ_WRITE_GET(type) == (UINT32)OS_QUEUE_WRITE) +#define OS_READWRITE_LEN 2 + +/** + * @ingroup los_queue + * Queue information block structure + */ +typedef struct { + UINT8 *queue; /**< Pointer to a queue handle */ + UINT16 queueState; /**< Queue state */ + UINT16 queueLen; /**< Queue length */ + UINT16 queueSize; /**< Node size */ + UINT16 queueID; /**< queueID */ + UINT16 queueHead; /**< Node head */ + UINT16 queueTail; /**< Node tail */ + UINT16 readWriteableCnt[OS_READWRITE_LEN]; /**< Count of readable or writable resources, 0:readable, 1:writable */ + LOS_DL_LIST readWriteList[OS_READWRITE_LEN]; /**< Pointer to the linked list to be read or written, + 0:readlist, 1:writelist */ + LOS_DL_LIST memList; /**< Pointer to the memory linked list */ +} LosQueueCB; + +/* queue state */ +/** + * @ingroup los_queue + * Message queue state: not in use. + */ +#define OS_QUEUE_UNUSED 0 + +/** + * @ingroup los_queue + * Message queue state: used. + */ +#define OS_QUEUE_INUSED 1 + +/** + * @ingroup los_queue + * Not in use. + */ +#define OS_QUEUE_WAIT_FOR_POOL 1 + +/** + * @ingroup los_queue + * Normal message queue. + */ +#define OS_QUEUE_NORMAL 0 + +/** + * @ingroup los_queue + * Queue information control block + */ +extern LosQueueCB *g_allQueue; + +/** + * @ingroup los_queue + * Obtain a handle of the queue that has a specified ID. + */ +#define GET_QUEUE_HANDLE(QueueID) (((LosQueueCB *)g_allQueue) + (QueueID)) + +/** + * @ingroup los_queue + * Obtain the head node in a queue doubly linked list. + */ +#define GET_QUEUE_LIST(ptr) LOS_DL_LIST_ENTRY(ptr, LosQueueCB, readWriteList[OS_QUEUE_WRITE]) +#if (LOSCFG_MEMBOX == YES) + +/** + * @ingroup los_queue + * @brief Alloc a stationary memory for a mail. + * + * @par Description: + * This API is used to alloc a stationary memory for a mail according to queueID. + * @attention + *
        + *
      • Do not alloc memory in unblocking modes such as interrupt.
      • + *
      • This API cannot be called before the Huawei LiteOS is initialized.
      • + *
      • The argument timeOut is a relative time.
      • + *
      + * + * @param queueID [IN] Queue ID. The value range is [1,LOSCFG_BASE_IPC_QUEUE_LIMIT]. + * @param mailPool [IN] The memory poll that stores the mail. + * @param timeOut [IN] Expiry time. The value range is [0,LOS_WAIT_FOREVER]. + * + * @retval #NULL The memory allocation is failed. + * @retval #mem The address of alloc memory. + * @par Dependency: + *
      • los_queue_pri.h: the header file that contains the API declaration.
      + * @see OsQueueMailFree + */ +extern VOID *OsQueueMailAlloc(UINT32 queueID, VOID *mailPool, UINT32 timeOut); + +/** + * @ingroup los_queue + * @brief Free a stationary memory of a mail. + * + * @par Description: + * This API is used to free a stationary memory for a mail according to queueID. + * @attention + *
        + *
      • This API cannot be called before the Huawei LiteOS is initialized.
      • + *
      + * + * @param queueID [IN] Queue ID. The value range is [1,LOSCFG_BASE_IPC_QUEUE_LIMIT]. + * @param mailPool [IN] The mail memory poll address. + * @param mailMem [IN] The mail memory block address. + * + * @retval #LOS_OK 0x00000000: The memory free successfully. + * @retval #OS_ERRNO_QUEUE_MAIL_HANDLE_INVALID 0x02000619: The handle of the queue passed-in when the memory for + the queue is being freed is invalid. + * @retval #OS_ERRNO_QUEUE_MAIL_PTR_INVALID 0x0200061a: The pointer to the memory to be freed is null. + * @retval #OS_ERRNO_QUEUE_MAIL_FREE_ERROR 0x0200061b: The memory for the queue fails to be freed. + * @par Dependency: + *
      • los_queue_pri.h: the header file that contains the API declaration.
      + * @see OsQueueMailAlloc + */ +extern UINT32 OsQueueMailFree(UINT32 queueID, VOID *mailPool, VOID *mailMem); +#endif + +/** + * @ingroup los_queue + * @brief Initialization queue. + * + * @par Description: + * This API is used to initialization queue. + * @attention + *
        + *
      • None.
      • + *
      + * + * @param None. + * + * @retval UINT32 Initialization result. + * @par Dependency: + *
      • los_queue_pri.h: the header file that contains the API declaration.
      + * @see None. + */ +extern UINT32 OsQueueInit(VOID *queueArray); + +/** + * @ingroup los_queue + * @brief Handle when read or write queue. + * + * @par Description: + * This API is used to handle when read or write queue. + * @attention + *
        + *
      • None.
      • + *
      + * + * @param queueID [IN] Queue id. + * @param operateType [IN] Operate type + * @param bufferAddr [IN] Buffer address. + * @param bufferSize [IN] Buffer size. + * @param timeOut [IN] Timeout. + * + * @retval UINT32 Handle result. + * @par Dependency: + *
      • los_queue_pri.h: the header file that contains the API declaration.
      + * @see None. + */ +extern UINT32 OsQueueOperate(UINT32 queueID, UINT32 operateType, VOID *bufferAddr, UINT32 *bufferSize, + UINT32 timeOut); + +#ifdef __cplusplus +#if __cplusplus +} +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +#endif /* _LOS_QUEUE_PRI_H */ diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/kernel/base/include/los_sem_pri.h b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/base/include/los_sem_pri.h new file mode 100644 index 0000000000000000000000000000000000000000..d11105287fae4b623ce770b30a9b362750b25f2b --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/base/include/los_sem_pri.h @@ -0,0 +1,129 @@ +/* ---------------------------------------------------------------------------- + * Copyright (c) Huawei Technologies Co., Ltd. 2013-2018. All rights reserved. + * Description: semaphore + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * --------------------------------------------------------------------------- */ + +#ifndef _LOS_SEM_PRI_H +#define _LOS_SEM_PRI_H + +#include "los_sem.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +enum LosSemMaxCount { + OS_SEM_COUNTING_MAX_COUNT = 0xFFFF, /**< Max count of counting semaphores */ + OS_SEM_BINARY_MAX_COUNT = 1 /**< Max count of binary semaphores */ +}; + +/** + * @ingroup los_sem + * Semaphore control structure. + */ +typedef struct { + UINT16 semStat; /**< Semaphore state */ + UINT16 semCount; /**< Number of available semaphores */ + UINT16 maxSemCount; /**< Max number of available semaphores */ + UINT16 semID; /**< Semaphore control structure ID */ + LOS_DL_LIST semList; /**< Queue of tasks that are waiting on a semaphore */ +} LosSemCB; + +/** + * @ingroup los_sem + * The semaphore is not in use. + * + */ +#define OS_SEM_UNUSED 0 +/** + * @ingroup los_sem + * The semaphore is used. + * + */ +#define OS_SEM_USED 1 +/** + * @ingroup los_sem + * Obtain the head node in a semaphore doubly linked list. + * + */ +#define GET_SEM_LIST(ptr) LOS_DL_LIST_ENTRY(ptr, LosSemCB, semList) +extern LosSemCB *g_allSem; +/** + * @ingroup los_sem + * Obtain a semaphore ID. + * + */ +#define GET_SEM(semid) (((LosSemCB *)g_allSem) + (semid)) + +/** + * @ingroup los_sem + * @brief Initialize the Semaphore doubly linked list. + * + * @par Description: + * This API is used to initialize the Semaphore doubly linked list. + * @attention + *
        + *
      • None.
      • + *
      + * + * @param None. + * + * @retval UINT32 Initialization result. + * @par Dependency: + *
      • los_sem_pri.h: the header file that contains the API declaration.
      + * @see None. + */ +extern UINT32 OsSemInit(VOID *semArray); + +/** + * @ingroup los_sem + * @brief Create Semaphore. + * + * @par Description: + * This API is used to create Semaphore. + * @attention + *
        + *
      • None.
      • + *
      + * + * @param count [IN]Type #UINT16 Semaphore count. + * @param maxCount [IN]Type #UINT16 Max semaphore count. + * @param semHandle [OUT]Type #UINT32 * Index of semaphore. + * + * @retval UINT32 Create result. + * @par Dependency: + *
      • los_sem_pri.h: the header file that contains the API declaration.
      + * @see None. + */ +UINT32 OsSemCreate(UINT16 count, UINT16 maxCount, UINT32 *semHandle); + +#ifdef __cplusplus +#if __cplusplus +} +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +#endif /* _LOS_SEM_PRI_H */ diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/kernel/base/include/los_swtmr_pri.h b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/base/include/los_swtmr_pri.h new file mode 100644 index 0000000000000000000000000000000000000000..5bb6529b23b1169817b930a76c87260229862917 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/base/include/los_swtmr_pri.h @@ -0,0 +1,225 @@ +/* ---------------------------------------------------------------------------- + * Copyright (c) Huawei Technologies Co., Ltd. 2013-2018. All rights reserved. + * Description: Software Timer Manager + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * --------------------------------------------------------------------------- */ + +#ifndef _LOS_SWTMR_PRI_H +#define _LOS_SWTMR_PRI_H + +#include "los_swtmr.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +/** + * @ingroup los_swtmr + * Software timer state + */ +enum SwtmrState { + OS_SWTMR_STATUS_UNUSED, /**< The software timer is not used. */ + OS_SWTMR_STATUS_CREATED, /**< The software timer is created. */ + OS_SWTMR_STATUS_TICKING /**< The software timer is timing. */ +}; + +/** + * @ingroup los_swtmr + * Structure of the callback function that handles software timer timeout + */ +typedef struct { + SWTMR_PROC_FUNC handler; /**< Callback function that handles software timer timeout */ + UINT32 arg; /**< Parameter passed in when the callback function + that handles software timer timeout is called */ +} SwtmrHandlerItem; + +extern SWTMR_CTRL_S *g_swtmrCBArray; + +#define OS_SWT_FROM_SID(swtmrId) ((SWTMR_CTRL_S *)g_swtmrCBArray + ((swtmrId) % LOSCFG_BASE_CORE_SWTMR_LIMIT)) + +/** + * @ingroup los_swtmr + * @brief Scan a software timer. + * + * @par Description: + *
        + *
      • This API is used to scan a software timer when a Tick interrupt occurs and determine whether the software timer + expires.
      • + *
      + * @attention + *
        + *
      • None.
      • + *
      + * + * @param None. + * + * @retval None. + * @par Dependency: + *
      • los_swtmr_pri.h: the header file that contains the API declaration.
      + * @see LOS_SwtmrStop + */ +extern UINT32 OsSwtmrScan(VOID); + +/** + * @ingroup los_swtmr + * @brief Initialization software timer. + * + * @par Description: + *
        + *
      • This API is used to initialization software.
      • + *
      + * @attention + *
        + *
      • None.
      • + *
      + * + * @param None. + * + * @retval None. + * @par Dependency: + *
      • los_swtmr_pri.h: the header file that contains the API declaration.
      + * @see None. + */ +extern UINT32 OsSwtmrInit(VOID *swtmrArray); + +/** + * @ingroup los_swtmr + * @brief Initialization software timer save array. + * + * @par Description: + *
        + *
      • This API is used to initialization software timer save array.
      • + *
      + * @attention + *
        + *
      • None.
      • + *
      + * + * @param None. + * + * @retval LOS_OK or LOS_ERRNO_SWTMR_NO_MEMORY. + * @par Dependency: + *
      • los_swtmr_pri.h: the header file that contains the API declaration.
      + * @see None. + */ +extern UINT32 OsSwtmrSaveInit(VOID); + +/** + * @ingroup los_swtmr + * @brief Get next timeout. + * + * @par Description: + *
        + *
      • This API is used to get next timeout.
      • + *
      + * @attention + *
        + *
      • None.
      • + *
      + * + * @param None. + * + * @retval None. + * @par Dependency: + *
      • los_swtmr_pri.h: the header file that contains the API declaration.
      + * @see None. + */ +extern UINT32 OsSwtmrGetNextTimeout(VOID); + +/** + * @ingroup los_swtmr + * @brief Adjust software timer list. + * + * @par Description: + *
        + *
      • This API is used to adjust software timer list.
      • + *
      + * @attention + *
        + *
      • None.
      • + *
      + * + * @param sleepTime [IN] UINT32 Sleep time. + * + * @retval UINT32 Sleep time. + * @par Dependency: + *
      • los_swtmr_pri.h: the header file that contains the API declaration.
      + * @see None. + */ +extern VOID OsSwtmrAdjust_Patch(UINT32 sleepTime); + +/** + * @ingroup los_swtmr + * Handle function of software timer task . + * + * @par Description: + *
        + *
      • This API is used to handle the overtime software timer.
      • + *
      + * @attention + *
        + *
      • None.
      • + *
      + * + * @param None. + * + * @retval None. + * @par Dependency: + *
      • los_swtmr.inc: the header file that contains the API declaration.
      + * @see None. + */ +extern VOID OsSwtmrTask(VOID); + +/** + * @ingroup los_swtmr + * Save enable timer id when start sleep. + * + * @par Description: + *
        + *
      • This API is used to save enable timer id when start sleep.
      • + *
      + * @attention + *
        + *
      • None.
      • + *
      + * + * @param None. + * + * @retval None. + * @par Dependency: + *
      • los_swtmr.inc: the header file that contains the API declaration.
      + * @see None. + */ +extern VOID OsSwtmrSave(VOID); + +extern SWTMR_CTRL_S *g_swtmrSortList; + +#ifdef __cplusplus +#if __cplusplus +} +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +#endif /* _LOS_SWTMR_PRI_H */ diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/kernel/base/include/los_sys_pri.h b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/base/include/los_sys_pri.h new file mode 100644 index 0000000000000000000000000000000000000000..18d7b776a029aeee22a30945128883a010d13cca --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/base/include/los_sys_pri.h @@ -0,0 +1,82 @@ +/* ---------------------------------------------------------------------------- + * Copyright (c) Huawei Technologies Co., Ltd. 2015-2018. All rights reserved. + * Description: System time + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * --------------------------------------------------------------------------- */ + +#ifndef _LOS_SYS_PRI_H +#define _LOS_SYS_PRI_H + +#include "los_base_pri.h" +#include "los_sys.h" +#include "los_tick_pri.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +/** + * @ingroup los_sys + * Number of operable bits of a 32-bit operand + */ +#define OS_SYS_MV_32_BIT 32 + +/** + * @ingroup los_sys + * Number of milliseconds in one second. + */ +#define OS_SYS_MS_PER_SECOND 1000 + +/** + * @ingroup los_sys + * Number of microseconds in one second. + */ +#define OS_SYS_US_PER_SECOND 1000000 + +/** + * @ingroup los_sys + * The maximum length of name. + */ +#define OS_SYS_APPVER_NAME_MAX 64 + +/** + * @ingroup los_sys + * The magic word. + */ +#define OS_SYS_MAGIC_WORD 0xAAAAAAAA + +/** + * @ingroup los_sys + * The initialization value of stack space. + */ +#define OS_SYS_EMPTY_STACK 0xCACACACA + +#ifdef __cplusplus +#if __cplusplus +} +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +#endif /* _LOS_SYS_PRI_H */ diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/kernel/base/include/los_task_pri.h b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/base/include/los_task_pri.h new file mode 100644 index 0000000000000000000000000000000000000000..9ef5e58c4a7cd0eb0b68003ab2f07f47c51345b4 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/base/include/los_task_pri.h @@ -0,0 +1,703 @@ +/* ---------------------------------------------------------------------------- + * Copyright (c) Huawei Technologies Co., Ltd. 2013-2015. All rights reserved. + * Description: LiteOS Task Module Implementation + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * --------------------------------------------------------------------------- */ + +#ifndef _LOS_TASK_PRI_H +#define _LOS_TASK_PRI_H + +#include "los_task.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +/** + * @ingroup los_task + * Null task ID + * + */ +#define OS_TASK_ERRORID 0xFFFFFFFF + +/** + * @ingroup los_task + * Define a usable task priority. + * + * Highest task priority. + */ +#define OS_TASK_PRIORITY_HIGHEST 0 + +/** + * @ingroup los_task + * Define a usable task priority. + * + * Lowest task priority. + */ +#define OS_TASK_PRIORITY_LOWEST 31 + +/** + * @ingroup los_task + * Flag that indicates the task or task control block status. + * + * The task control block is unused. + */ +#define OS_TASK_STATUS_UNUSED 0x0001 + +/** + * @ingroup los_task + * Flag that indicates the task or task control block status. + * + * The task is suspended. + */ +#define OS_TASK_STATUS_SUSPEND 0x0002 + +/** + * @ingroup los_task + * Flag that indicates the task or task control block status. + * + * The task is ready. + */ +#define OS_TASK_STATUS_READY 0x0004 + +/** + * @ingroup los_task + * Flag that indicates the task or task control block status. + * + * The task is blocked. + */ +#define OS_TASK_STATUS_PEND 0x0008 + +/** + * @ingroup los_task + * Flag that indicates the task or task control block status. + * + * The task is running. + */ +#define OS_TASK_STATUS_RUNNING 0x0010 + +/** + * @ingroup los_task + * Flag that indicates the task or task control block status. + * + * The task is delayed. + */ +#define OS_TASK_STATUS_DELAY 0x0020 + +/** + * @ingroup los_task + * Flag that indicates the task or task control block status. + * + * The time for waiting for an event to occur expires. + */ +#define OS_TASK_STATUS_TIMEOUT 0x0040 + +/** + * @ingroup los_task + * Flag that indicates the task or task control block status. + * + * The task is waiting for an event to occur. + */ +#define OS_TASK_STATUS_EVENT 0x0400 + +/** + * @ingroup los_task + * Flag that indicates the task or task control block status. + * + * The task is reading an event. + */ +#define OS_TASK_STATUS_EVENT_READ 0x0800 + +/** + * @ingroup los_task + * Flag that indicates the task or task control block status. + * + * A software timer is waiting for an event to occur. + */ +#define OS_TASK_STATUS_SWTMR_WAIT 0x1000 + +/** + * @ingroup los_task + * Flag that indicates the task or task control block status. + * + * The task is blocked on a queue. + */ +#define OS_TASK_STATUS_PEND_QUEUE 0x2000 + +/** + * @ingroup los_task + * Flag that indicates the task or task control block status. + * + * The task is blocked on a mutex. + */ +#define OS_TASK_STATUS_PEND_MUT 0x4000 + +/** + * @ingroup los_task + * Flag that indicates the task or task control block status. + * + * The task is blocked on a semaphore. + */ +#define OS_TASK_STATUS_PEND_SEM 0x8000 + +/** + * @ingroup los_task + * Boundary on which the stack size is aligned. + * + */ +#define OS_TASK_STACK_SIZE_ALIGN 16 + +/** + * @ingroup los_task + * Boundary on which the stack address is aligned. + * + */ +#define OS_TASK_STACK_ADDR_ALIGN 8 + +/** + * @ingroup los_task + * Task stack top magic number. + * + */ +#define OS_TASK_MAGIC_WORD 0xCCCCCCCC + +/** + * @ingroup los_task + * Initial task stack value. + * + */ +#define OS_TASK_STACK_INIT 0xCACACACA + +/** + * @ingroup los_task + * Number of usable task priorities. + */ +#define OS_TSK_PRINUM ((OS_TASK_PRIORITY_LOWEST - OS_TASK_PRIORITY_HIGHEST) + 1) + +/** + * @ingroup los_task + * @brief the num of delayed tasks bucket + */ +#define OS_TSK_SORTLINK_LEN 32 + +/** + * @ingroup los_task + * @brief the bit width occupied by the delayed ticks of task + */ +#define OS_TSK_SORTLINK_LOGLEN 5 + +/** + * @ingroup los_task + * @brief the mask of delayed tasks bucket id. + */ +#define OS_TSK_SORTLINK_MASK (OS_TSK_SORTLINK_LEN - 1) + +/** + * @ingroup los_task + * @brief the max task count for switch. + */ +#define OS_TASK_SWITCH_INFO_COUNT 0xA + +/** + * @ingroup los_task + * @brief Check whether a task ID is valid. + * + * @par Description: + * This API is used to check whether a task ID, excluding the idle task ID, is valid. + * @attention None. + * + * @param taskID [IN] Task ID. + * + * @retval 0 or 1. One indicates that the task ID is invalid, whereas zero indicates that the task ID is valid. + * @par Dependency: + *
      • los_task_pri.h: the header file that contains the API declaration.
      + * @see + */ +#define OS_TSK_GET_INDEX(taskID) (taskID) + +/** + * @ingroup los_task + * @brief Obtain the pointer to a task control block. + * + * @par Description: + * This API is used to obtain the pointer to a task control block using a corresponding parameter. + * @attention None. + * + * @param ptr [IN] Parameter used for obtaining the task control block. + * + * @retval Pointer to the task control block. + * @par Dependency: + *
      • los_task_pri.h: the header file that contains the API declaration.
      + * @see + */ +#define OS_TCB_FROM_PENDLIST(ptr) LOS_DL_LIST_ENTRY(ptr, LosTaskCB, pendList) + +/** + * @ingroup los_task + * @brief Obtain the pointer to a task control block. + * + * @par Description: + * This API is used to obtain the pointer to a task control block that has a specified task ID. + * @attention None. + * + * @param taskID [IN] task ID. + * + * @retval Pointer to the task control block. + * @par Dependency: + *
      • los_task_pri.h: the header file that contains the API declaration.
      + * @see + */ +#define OS_TCB_FROM_TID(taskID) (((LosTaskCB *)g_taskCBArray) + (taskID)) +#define OS_IDLE_TASK_ENTRY ((TSK_ENTRY_FUNC)OsIdleTask) + +/** + * @ingroup los_task + * Define the task control block structure. + */ +typedef struct { + VOID *stackPointer; /**< Task stack pointer */ + UINT16 taskStatus; + UINT16 priority; + UINT32 stackSize; /**< Task stack size */ + UINT32 topOfStack; /**< Task stack top */ + UINT32 taskID; /**< Task ID */ + TSK_ENTRY_FUNC taskEntry; /**< Task entrance function */ + VOID *taskSem; /**< Task-held semaphore */ + VOID *taskMux; /**< Task-held mutex */ + UINT32 args[LOS_TASK_ARG_NUM]; /**< Parameter */ + CHAR *taskName; /**< Task name */ + LOS_DL_LIST pendList; + LOS_DL_LIST timerList; + UINT32 idxRollNum; + EVENT_CB_S event; + UINT32 eventMask; /**< Event mask */ + UINT32 eventMode; /**< Event mode */ + VOID *msg; /**< Memory allocated to queues */ + UINT32 priBitMap; /**< BitMap for recording the change of task priority, */ + /**< the priority can not be greater than 31 */ +} LosTaskCB; + +typedef struct { + LosTaskCB *runTask; + LosTaskCB *newTask; +} LosTask; + +typedef struct { + LOS_DL_LIST *sortLink; + UINT16 cursor; + UINT16 unused; +} TaskSortLinkAttr; + +/** + * @ingroup los_task + * Time slice structure. + */ +typedef struct TaskTimeSlice { + LosTaskCB *task; /**< Current running task */ + UINT16 time; /**< Expiration time point */ + UINT16 tout; /**< Expiration duration */ +} OsTaskRobin; + +typedef struct { + UINT8 maxCnt : 7; // bits [6:0] store count of task switch info + UINT8 isFull : 1; // bit [7] store isfull status +} TaskCountInfo; + +/** + * @ingroup los_task + * Task switch information structure. + * + */ +typedef struct { + UINT8 idx; + TaskCountInfo cntInfo; + UINT16 pid[OS_TASK_SWITCH_INFO_COUNT]; + CHAR name[OS_TASK_SWITCH_INFO_COUNT][LOS_TASK_NAMELEN]; +} TaskSwitchInfo; + +extern LosTask g_losTask; + +/** + * @ingroup los_task + * Task lock flag. + * + */ +extern UINT16 g_losTaskLock; + +/** + * @ingroup los_task + * Maximum number of tasks. + * + */ +extern UINT32 g_taskMaxNum; + +/** + * @ingroup los_task + * Idle task ID. + * + */ +extern UINT32 g_idleTaskID; + +/** + * @ingroup los_task + * Software timer task ID. + * + */ +extern UINT32 g_swtmrTaskID; + +/** + * @ingroup los_task + * Starting address of a task. + * + */ +extern LosTaskCB *g_taskCBArray; + +/** + * @ingroup los_task + * Delayed task linked list. + * + */ +extern LOS_DL_LIST g_taskTimerList; + +/** + * @ingroup los_task + * Free task linked list. + * + */ +extern LOS_DL_LIST g_losFreeTask; + +/** + * @ingroup los_task + * Circular linked list that stores tasks that are deleted automatically. + * + */ +extern LOS_DL_LIST g_taskRecyleList; + +/** + * @ingroup los_task + * task Sort linked list. + * + */ +extern TaskSortLinkAttr g_taskSortLink; + +extern BOOL g_taskScheduled; + +extern UINT32 g_taskUsedCount; + +/** + * @ingroup los_task + * @brief the block status of task + */ +extern VOID OsTaskSchedule(VOID); + +/** + * @ingroup los_task + * @brief Modify the priority of task. + * + * @par Description: + * This API is used to modify the priority of task. + * + * @attention + *
        + *
      • The taskCB should be a correct pointer to task control block structure.
      • + *
      • the priority should be in [0, OS_TASK_PRIORITY_LOWEST].
      • + *
      + * + * @param taskCB [IN] Type #LosTaskCB * pointer to task control block structure. + * @param priority [IN] Type #UINT16 the priority of task. + * + * @retval None. + * @par Dependency: + *
      • los_task_pri.h: the header file that contains the API declaration.
      + * @see + */ +extern VOID OsTaskPriModify(LosTaskCB *taskCB, UINT16 priority); + +/** + * @ingroup los_task + * @brief Scan a task. + * + * @par Description: + * This API is used to scan a task. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @param None. + * + * @retval None. + * @par Dependency: + *
      • los_task_pri.h: the header file that contains the API declaration.
      + * @see + */ +extern VOID OsTaskScan(VOID); + +/** + * @ingroup los_task + * @brief Initialization a task. + * + * @par Description: + * This API is used to initialization a task. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @param None. + * + * @retval UINT32 Initialization result. + * @par Dependency: + *
      • los_task_pri.h: the header file that contains the API declaration.
      + * @see + */ +extern UINT32 OsTaskInit(VOID *taskArray); + +/** + * @ingroup los_task + * @brief Create idle task. + * + * @par Description: + * This API is used to create idle task. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @param None. + * + * @retval UINT32 Create result. + * @par Dependency: + *
      • los_task_pri.h: the header file that contains the API declaration.
      + * @see + */ +extern UINT32 OsIdleTaskCreate(VOID); + +/** + * @ingroup los_task + * @brief Check task switch. + * + * @par Description: + * This API is used to check task switch. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @param None. + * + * @retval None. + * @par Dependency: + *
      • los_task_pri.h: the header file that contains the API declaration.
      + * @see + */ +extern VOID OsTaskSwitchCheck(VOID); + +/** + * @ingroup los_task + * @brief TaskMonInit. + * + * @par Description: + * This API is used to taskMonInit. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @param None. + * + * @retval None. + * @par Dependency: + *
      • los_task_pri.h: the header file that contains the API declaration.
      + * @see + */ +extern VOID OsTaskMonInit(VOID); + +/** + * @ingroup los_task + * @brief Task entry. + * + * @par Description: + * This API is used to task entry. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @param taskID [IN] Type #UINT32 task id. + * + * @retval None. + * @par Dependency: + *
      • los_task_pri.h: the header file that contains the API declaration.
      + * @see + */ +extern VOID OsTaskEntry(UINT32 taskID); + +/** + * @ingroup los_task + * @brief pend running task to pendlist + * + * @par Description: + * This API is used to pend task to pendlist and add to sorted delay list. + * + * @attention + *
        + *
      • The pstList should be a vaild pointer to pendlist.
      • + *
      + * + * @param list [IN] Type #LOS_DL_LIST * pointer to list which running task will be pended. + * @param taskStatus [IN] Type #UINT32 Task Status. + * @param timeOut [IN] Type #UINT32 Expiry time. The value range is [0,LOS_WAIT_FOREVER]. + * + * @retval LOS_OK wait success + * @retval LOS_NOK pend out + * @par Dependency: + *
      • los_task_pri.h: the header file that contains the API declaration.
      + * @see OsTaskWake + */ +extern VOID OsTaskWait(LOS_DL_LIST *list, UINT32 taskStatus, UINT32 timeOut); + +/** + * @ingroup los_task + * @brief delete task from pendlist. + * + * @par Description: + * This API is used to delete task from pendlist and also add to the priqueue. + * + * @attention + *
        + *
      • The pstList should be a vaild pointer to pend list.
      • + *
      + * + * @param resumedTask [IN] Type #LosTaskCB * pointer to the task which will be add to priqueue. + * @param taskStatus [IN] Type #UINT32 Task Status. + * + * @retval None. + * @par Dependency: + *
      • los_task_pri.h: the header file that contains the API declaration.
      + * @see OsTaskWait + */ +extern VOID OsTaskWake(LosTaskCB *resumedTask, UINT32 taskStatus); + +/** + * @ingroup los_task + * @brief Get the task water line. + * + * @par Description: + * This API is used to get the task water line. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @param taskID [IN] Type #UINT32 task id. + * + * @retval UINT32 Task water line. + * @par Dependency: + *
      • los_task_pri.h: the header file that contains the API declaration.
      + * @see None. + */ +extern UINT32 OsGetTaskWaterLine(UINT32 taskID); + +/** + * @ingroup los_task + * @brief Convert task status to string. + * + * @par Description: + * This API is used to convert task status to string. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @param taskStatus [IN] Type #UINT16 task status. + * + * @retval UINT8 * String. + * @par Dependency: + *
      • los_task_pri.h: the header file that contains the API declaration.
      + * @see None. + */ +extern UINT8 *OsConvertTskStatus(UINT16 taskStatus); + +/** + * @ingroup los_task + * @brief Add task to sorted delay list. + * + * @par Description: + * This API is used to add task to sorted delay list. + * + * @attention + *
        + *
      • The taskCB should be a correct pointer to task control block structure.
      • + *
      + * + * @param taskCB [IN] Type #LosTaskCB * pointer to task control block structure. + * @param timeout [IN] Type #UINT32 wait time, ticks. + * + * @retval None. + * @par Dependency: + *
      • los_task_pri.h: the header file that contains the API declaration.
      + * @see OsTimerListDelete + */ +extern VOID OsTaskAdd2TimerList(LosTaskCB *taskCB, UINT32 timeout); + +/** + * @ingroup los_task + * @brief delete task from sorted delay list. + * + * @par Description: + * This API is used to delete task from sorted delay list. + * + * @attention + *
        + *
      • The taskCB should be a correct pointer to task control block structure.
      • + *
      + * + * @param taskCB [IN] Type #LosTaskCB * pointer to task control block structure. + * + * @retval None. + * @par Dependency: + *
      • los_task_pri.h: the header file that contains the API declaration.
      + * @see OsTaskAdd2TimerList + */ +extern VOID OsTimerListDelete(LosTaskCB *taskCB); + +extern BOOL OsRunningTaskIsSwtmr(VOID); + +#ifdef __cplusplus +#if __cplusplus +} +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +#endif /* _LOS_TASK_PRI_H */ diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/kernel/base/include/los_tick_pri.h b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/base/include/los_tick_pri.h new file mode 100644 index 0000000000000000000000000000000000000000..11b29e4179d4bcf91b28793d10898a69382d54bf --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/base/include/los_tick_pri.h @@ -0,0 +1,94 @@ +/* ---------------------------------------------------------------------------- + * Copyright (c) Huawei Technologies Co., Ltd. 2013-2018. All rights reserved. + * Description: Tick + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * --------------------------------------------------------------------------- */ + +#ifndef _LOS_TICK_PRI_H +#define _LOS_TICK_PRI_H + +#include "los_tick.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +#define SYSTEM_CLOCK_FREQ_24M 24 +#define SYSTEM_CLOCK_FREQ_40M 40 + +/** + * @ingroup los_tick + * Count of Ticks + */ +extern UINT64 g_tickCount; + +/** + * @ingroup los_tick + * Ticks per second + */ +extern UINT32 g_ticksPerSec; + +/** + * @ingroup los_tick + * Cycles per Tick + */ +extern UINT32 g_cyclesPerTick; + +extern UINT32 g_sysClock; +/** + * @ingroup los_tick + * @brief Handle the system tick timeout. + * + * @par Description: + * This API is called when the system tick timeout and triggers the interrupt. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @param none. + * + * @retval None. + * @par Dependency: + *
      • los_tick_pri.h: the header file that contains the API declaration.
      + * @see None. + */ +extern VOID OsTickHandler(VOID); +extern UINT32 OsTimerInit(VOID); +extern VOID OsTimerDisable(VOID); +extern VOID OsTimerStop(VOID); +extern VOID OsTimerStart(VOID); +extern LITE_OS_RAM_SECTION VOID OsPlatformTickHandler(VOID); +extern VOID OsPlatformGetCycle(UINT32 *cntHigh, UINT32 *cntLow); +extern UINT32* OsTimerGetFirstTick(VOID); +extern UINT32 OsTimerGetReloadValue(VOID); +#ifdef __cplusplus +#if __cplusplus +} +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +#endif /* _LOS_TICK_PRI_H */ diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/kernel/base/include/los_timeslice_pri.h b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/base/include/los_timeslice_pri.h new file mode 100644 index 0000000000000000000000000000000000000000..0f0540d080fc9f23065f8cb5d30463799148360a --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/base/include/los_timeslice_pri.h @@ -0,0 +1,93 @@ +/* ---------------------------------------------------------------------------- + * Copyright (c) Huawei Technologies Co., Ltd. 2013-2018. All rights reserved. + * Description: Timeslice + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * --------------------------------------------------------------------------- */ + +/** + * @defgroup los_timeslice Timeslice + * @ingroup kernel + */ + +#ifndef _LOS_TIMESLICE_PRI_H +#define _LOS_TIMESLICE_PRI_H + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +/** + * @ingroup los_timeslice + * @brief Initialize time slices. + * + * @par Description: + *
        + *
      • This API is used to initialize time slices that defines the cycle of time slices according to + LOSCFG_BASE_CORE_TIMESLICE_TIMEOUT.
      • + *
      + * @attention + *
        + *
      • None.
      • + *
      + * + * @param None. + * + * @retval None. + * @par Dependency: + *
      • los_timeslice_pri.h: the header file that contains the API declaration.
      + * @see None. + */ +extern VOID OsTimesliceInit(VOID); + +/** + * @ingroup los_timeslice + * @brief Check time slices. + * + * @par Description: + *
        + *
      • This API is used to check time slices. If the number of Ticks equals to the time for task switch, + * tasks are switched. Otherwise, the Tick counting continues.
      • + *
      + * @attention + *
        + *
      • None.
      • + *
      + * + * @param None. + * + * @retval None. + * @par Dependency: + *
      • los_timeslice_pri.h: the header file that contains the API declaration.
      + * @see None. + */ +extern VOID OsTimesliceCheck(VOID); + +#ifdef __cplusplus +#if __cplusplus +} +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +#endif /* _LOS_TIMESLICE_PRI_H */ diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/kernel/extended/include/los_cpup_pri.h b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/extended/include/los_cpup_pri.h new file mode 100644 index 0000000000000000000000000000000000000000..b32dd2c2423245df9d1b409a37a57f6291437677 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/extended/include/los_cpup_pri.h @@ -0,0 +1,164 @@ +/* ---------------------------------------------------------------------------- + * Copyright (c) Huawei Technologies Co., Ltd. 2013-2015. All rights reserved. + * Description : LiteOS Cpu Usage Calculation Module Headfile For User + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * --------------------------------------------------------------------------- */ + + +#ifndef _LOS_CPUP_PRI_H +#define _LOS_CPUP_PRI_H + +#include "los_cpup.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +/** + * @ingroup los_cpup + * Count the CPU usage structures of a task. + */ +typedef struct { + UINT32 cpupID; /**< Task ID */ + UINT16 status; /**< Task status */ + UINT64 allTime; /**< Total running time */ + UINT64 startTime; /**< Time before a task is invoked */ +} OsCpupCB; + +extern OsCpupCB *g_cpup; +extern UINT16 g_cpupInitFlg; + +#if (LOSCFG_BASE_CORE_CPUP_HWI == YES) +extern UINT32 g_timeInIrqPerTskSwitch; +#endif + +/** + * @ingroup los_cpup + * @brief Initialization cpup. + * + * @par Description: + * This API is used to initialization cpup. + * @attention + *
        + *
      • None.
      • + *
      + * + * @param None. + * + * @retval UINT32 Initialization result. + * @par Dependency: + *
      • los_cpup.h: the header file that contains the API declaration.
      + * @see None. + */ +extern UINT32 OsCpupInit(VOID *cpupArray); + +/** + * @ingroup los_cpup + * @brief Start task to get cycles count in current task ending. + * + * @par Description: + * This API is used to start task to get cycles count in current task ending. + * @attention + *
        + *
      • None.
      • + *
      + * + * @param None. + * + * @retval None. + * @par Dependency: + *
      • los_cpup.h: the header file that contains the API declaration.
      + * @see None. + */ +extern VOID OsTskCycleEndStart(VOID); + +/** + * @ingroup los_cpup + * @brief Get CPU cycle. + * + * @par Description: + * This API is used to get CPU cycle. + * @attention + *
        + *
      • None.
      • + *
      + * + * @param None. + * + * @retval UINT64 CPU cycle. + * @par Dependency: + *
      • los_cpup.h: the header file that contains the API declaration.
      + * @see None. + */ +extern UINT64 OsGetCpuCycle(VOID); + +/** + * @ingroup los_cpup + * @brief Task cycle start. + * + * @par Description: + * This API is used to task cycle start. + * @attention + *
        + *
      • None.
      • + *
      + * + * @param None. + * + * @retval None. + * @par Dependency: + *
      • los_cpup.h: the header file that contains the API declaration.
      + * @see OsTskCycleEnd + */ +extern VOID OsTskCycleStart(VOID); + +/** + * @ingroup los_cpup + * @brief Quit task cycle. + * + * @par Description: + * This API is used to quit task cycle. + * @attention + *
        + *
      • None.
      • + *
      + * + * @param None. + * + * @retval None. + * @par Dependency: + *
      • los_cpup.h: the header file that contains the API declaration.
      + * @see OsTskCycleStart + */ +extern VOID OsTskCycleEnd(VOID); + + +#ifdef __cplusplus +#if __cplusplus +} +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +#endif /* _LOS_CPUP_PRI_H */ diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_base.h b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_base.h new file mode 100644 index 0000000000000000000000000000000000000000..272512efccc78a45966c80d8ff90c6df4f3e4888 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_base.h @@ -0,0 +1,251 @@ +/* ---------------------------------------------------------------------------- + * Copyright (c) Huawei Technologies Co., Ltd. 2013-2018. All rights reserved. + * Description: Basic definitions + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * --------------------------------------------------------------------------- */ + +/** + * @defgroup kernel Kernel + * @defgroup los_base Basic definitions + * @ingroup kernel + */ + +#ifndef _LOS_BASE_H +#define _LOS_BASE_H + +#include "los_printf.h" +#include "los_list.h" +#include "los_errno.h" +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +#define SIZE(a) (a) + +#define LOS_ASSERT_COND(expression) + +/** + * @ingroup los_base + * Define the timeout interval as LOS_NO_WAIT. + */ +#define LOS_NO_WAIT 0 + +/** + * @ingroup los_base + * Define the timeout interval as LOS_WAIT_FOREVER. + */ +#define LOS_WAIT_FOREVER 0xFFFFFFFF + +/** + * @ingroup los_base + * Align the beginning of the object with the base address addr, + * with boundary bytes being the smallest unit of alignment. + */ +#ifndef ALIGN +#define ALIGN(addr, boundary) LOS_Align(addr, boundary) +#endif +/** + * @ingroup los_base + * Align the tail of the object with the base address addr, with size bytes being the smallest unit of alignment. + */ +#define TRUNCATE(addr, size) ((addr) & ~((size)-1)) + +/** + * @ingroup los_base + * Read a UINT8 value from addr and stroed in value. + */ +#define READ_UINT8(value, addr) ((value) = *((volatile UINT8 *)(addr))) +/** + * @ingroup los_base + * Read a UINT16 value from addr and stroed in addr. + */ +#define READ_UINT16(value, addr) ((value) = *((volatile UINT16 *)(addr))) +/** + * @ingroup los_base + * Read a UINT32 value from addr and stroed in value. + */ +#define READ_UINT32(value, addr) ((value) = *((volatile UINT32 *)(addr))) +/** + * @ingroup los_base + * Read a UINT64 value from addr and stroed in value. + */ +#define READ_UINT64(value, addr) ((value) = *((volatile UINT64 *)(addr))) + +/** + * @ingroup los_base + * Get a UINT8 value from addr. + */ +#define GET_UINT8(addr) (*((volatile UINT8 *)(addr))) +/** + * @ingroup los_base + * Get a UINT16 value from addr. + */ +#define GET_UINT16(addr) (*((volatile UINT16 *)(addr))) +/** + * @ingroup los_base + * Get a UINT32 value from addr. + */ +#define GET_UINT32(addr) (*((volatile UINT32 *)(addr))) +/** + * @ingroup los_base + * Get a UINT64 value from addr. + */ +#define GET_UINT64(addr) (*((volatile UINT64 *)(addr))) + +/** + * @ingroup los_base + * Write a UINT8 value to addr. + */ +#define WRITE_UINT8(value, addr) (*((volatile UINT8 *)(addr)) = (value)) +/** + * @ingroup los_base + * Write a UINT16 value to addr. + */ +#define WRITE_UINT16(value, addr) (*((volatile UINT16 *)(addr)) = (value)) +/** + * @ingroup los_base + * Write a UINT32 value to addr. + */ +#define WRITE_UINT32(value, addr) (*((volatile UINT32 *)(addr)) = (value)) +/** + * @ingroup los_base + * Write a UINT64 addr to addr. + */ +#define WRITE_UINT64(value, addr) (*((volatile UINT64 *)(addr)) = (value)) + +#if PRINT_LEVEL < LOS_ERR_LEVEL +#define LOS_ASSERT(judge) +#else +#define LOS_ASSERT(judge) \ + do { \ + if ((judge) == 0) { \ + (VOID)LOS_IntLock(); \ + PRINT_ERR("ASSERT ERROR! %s, %d\n", __FUNCTION__, __LINE__); \ + while (1) { } \ + } \ + } while (0) +#endif + +/** + * @ingroup los_base + * @brief Align the value (addr) by some bytes (boundary) you specify. + * + * @par Description: + * This API is used to align the value (addr) by some bytes (boundary) you specify. + * + * @attention + *
        + *
      • the value of boundary usually is 4,8,16,32.
      • + *
      + * + * @param addr [IN] The variable what you want to align. + * @param boundary [IN] The align size what you want to align. + * + * @retval #UINT32 The variable what have been aligned. + * @par Dependency: + *
      • los_base.h: the header file that contains the API declaration.
      + * @see + */ +extern UINT32 LOS_Align(UINT32 addr, UINT32 boundary); + +/** + * @ingroup los_base + * @brief Sleep the current task. + * + * @par Description: + * This API is used to delay the execution of the current task. The task is able to be scheduled + * after it is delayed for a specified number of Ticks. + * + * @attention + *
        + *
      • The task fails to be delayed if it is being delayed during interrupt processing or it is locked.
      • + *
      • If 0 is passed in and the task scheduling is not locked, + * execute the next task in the queue of tasks with the priority of the current task. + * If no ready task with the priority of the current task is available, + * the task scheduling will not occur, and the current task continues to be executed.
      • + *
      • The parameter passed in can not be equal to LOS_WAIT_FOREVER(0xFFFFFFFF). + * If that happens, the task will not sleep 0xFFFFFFFF milliseconds or sleep forever but sleep 0xFFFFFFFF Ticks.
      • + *
      + * + * @param mSecs [IN] Type #UINT32 Number of MS for which the task is delayed. + * + * @retval None + * @par Dependency: + *
      • los_base.h: the header file that contains the API declaration.
      + * @see None + */ +extern VOID LOS_Msleep(UINT32 mSecs); + +/** + * @ingroup los_base + * @brief System kernel initialization function. + * + * @par Description: + * This API is used to start liteOS . + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @param: None. + * + * @retval #LOS_OK 0:LiteOS start success. + * + * @par Dependency: + *
      • los_config.h: the header file that contains the API declaration.
      + * @see + */ +extern UINT32 LOS_Start(VOID); + +/** + * @ingroup los_base + * @brief System kernel initialization function. + * + * @par Description: + * This API is used to Initialize kernel ,configure all system modules. + * + * @attention + *
        + *
      • None.
      • + *
      + * + * @param: None. + * + * @retval #LOS_OK 0:System kernel initialization success. + * + * @par Dependency: + *
      • los_config.h: the header file that contains the API declaration.
      + * @see + */ +extern UINT32 LOS_KernelInit(VOID); + +#ifdef __cplusplus +#if __cplusplus +} +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +#endif /* _LOS_BASE_H */ diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_build.h b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_build.h new file mode 100644 index 0000000000000000000000000000000000000000..2435ac76f14e7749003221a4bc31f4af1eab0986 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_build.h @@ -0,0 +1,47 @@ +/* ---------------------------------------------------------------------------- + * Copyright (c) Huawei Technologies Co., Ltd. 2013-2015. All rights reserved. + * Description : build + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * --------------------------------------------------------------------------- */ + +#ifndef _LOS_BUILD_H +#define _LOS_BUILD_H + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +#define LOS_CB_START(module) __##module##_start +#define LOS_CB_END(module) __##module##_end +#define LOS_BLOCK_START(module) __block_##module##_start +#define LOS_BLOCK_END(module) __block_##module##_end + +#ifdef __cplusplus +#if __cplusplus +} +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +#endif /* _LOS_BUILD_H */ \ No newline at end of file diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_compiler.h b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_compiler.h new file mode 100644 index 0000000000000000000000000000000000000000..1221d1d65a57295aae2caa97341c583ee68d6c36 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_compiler.h @@ -0,0 +1,141 @@ +/* ---------------------------------------------------------------------------- + * Copyright (c) Huawei Technologies Co., Ltd. 2013-2018. All rights reserved. + * Description: compiler related definitions + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * --------------------------------------------------------------------------- */ + +#ifndef _LOS_COMPILER_H +#define _LOS_COMPILER_H + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +/* for IAR Compiler */ +#ifdef __ICCARM__ + +#ifndef ASM +#define ASM __asm +#endif + +#ifndef asm +#define asm __asm +#endif + +#ifndef INLINE +#define INLINE inline +#endif + +#ifndef STATIC_INLINE +#define STATIC_INLINE static inline +#endif + +#ifndef USED +#define USED __root +#endif + +#ifndef WEAK +#define WEAK __weak +#endif + +/* for ARM Compiler */ +#elif defined(__CC_ARM) + +#ifndef ASM +#define ASM __asm +#endif + +#ifndef asm +#define asm __asm +#endif + +#ifndef INLINE +#define INLINE __inline +#endif + +#ifndef STATIC_INLINE +#define STATIC_INLINE static __inline +#endif + +#ifndef USED +#define USED __attribute__((used)) +#endif + +#ifndef WEAK +#define WEAK __attribute__((weak)) +#endif + +#ifndef CLZ +#define CLZ __clz +#endif + +#pragma anon_unions + +/* for GNU Compiler */ +#elif defined(__GNUC__) + +#ifndef ASM +#define ASM __asm +#endif + +#ifndef asm +#define asm __asm +#endif + +#ifndef INLINE +#define INLINE inline +#endif + +#ifndef STATIC_INLINE +#define STATIC_INLINE static inline +#endif + +#ifndef USED +#define USED __attribute__((used)) +#endif + +#ifndef WEAK +#define WEAK __attribute__((__weak__)) +#endif + +#ifndef CLZ +#define CLZ __builtin_clz +#endif + +#ifdef typeof +#undef typeof +#endif +#define typeof __typeof__ +#else +#error Unknown compiler. +#endif + +#ifdef __cplusplus +#if __cplusplus +} +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +#endif /* _LOS_COMPILER_H */ diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_config.h b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_config.h new file mode 100644 index 0000000000000000000000000000000000000000..e8a379ece77479c647509a1d29a9a019b4791d29 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_config.h @@ -0,0 +1,673 @@ +/* ---------------------------------------------------------------------------- + * Copyright (c) Huawei Technologies Co., Ltd. 2013-2015. All rights reserved. + * Description: los_config system configuration items + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * --------------------------------------------------------------------------- */ + +/** + * @defgroup los_config System configuration items + * @ingroup kernel + */ + +#ifndef _LOS_CONFIG_H +#define _LOS_CONFIG_H + +#include "target_config.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +/* ============================================================================= + System clock module configuration +============================================================================= */ +/** + * @ingroup los_config + * System clock (unit: HZ) + */ +#ifndef OS_SYS_CLOCK +#define OS_SYS_CLOCK 100000000UL +#endif + +/** + * @ingroup los_config + * timer1 clock (unit: HZ) + */ +#ifndef OS_TIME_TIMER_CLOCK +#define OS_TIME_TIMER_CLOCK OS_SYS_CLOCK +#endif + +/** + * @ingroup los_config + * Number of Ticks in one second + */ +#ifndef LOSCFG_BASE_CORE_TICK_PER_SECOND +#define LOSCFG_BASE_CORE_TICK_PER_SECOND 1000UL +#endif + +/** + * @ingroup los_config + * External configuration item for timer tailoring + */ +#ifndef LOSCFG_BASE_CORE_TICK_HW_TIME1 +#define LOSCFG_BASE_CORE_TICK_HW_TIME1 YES +#endif + +#ifndef LOSCFG_BASE_CORE_TICK_HW_TIME +#define LOSCFG_BASE_CORE_TICK_HW_TIME NO +#endif + +/* ============================================================================= + Hardware interrupt module configuration +============================================================================= */ +/** + * @ingroup los_config + * Configuration item for hardware interrupt tailoring + */ +#ifndef LOSCFG_PLATFORM_HWI +#define LOSCFG_PLATFORM_HWI YES +#endif + +/** + * @ingroup los_config + * Maximum number of used hardware interrupts, including Tick timer interrupts. + */ +#ifndef LOSCFG_PLATFORM_HWI_LIMIT +#define LOSCFG_PLATFORM_HWI_LIMIT 32 +#endif + + +/* ============================================================================= + Task module configuration +============================================================================= */ +/** + * @ingroup los_config + * Minimum stack size. + * + * 0x80 bytes, aligned on a boundary of 8. + */ +#ifndef LOSCFG_BASE_CORE_TSK_MIN_STACK_SIZE +#define LOSCFG_BASE_CORE_TSK_MIN_STACK_SIZE (ALIGN(0x80, 4)) +#endif + +/** + * @ingroup los_config + * Default task priority + */ +#ifndef LOSCFG_BASE_CORE_TSK_DEFAULT_PRIO +#define LOSCFG_BASE_CORE_TSK_DEFAULT_PRIO 10 +#endif + +/** + * @ingroup los_config + * Maximum supported number of tasks except the idle task rather than the number of usable tasks + */ +#ifndef LOSCFG_BASE_CORE_TSK_LIMIT +#define LOSCFG_BASE_CORE_TSK_LIMIT 5 +#endif + +/** + * @ingroup los_config + * Size of the idle task stack + */ +#ifndef LOSCFG_BASE_CORE_TSK_IDLE_STACK_SIZE +#define LOSCFG_BASE_CORE_TSK_IDLE_STACK_SIZE 0x180UL +#endif + +/** + * @ingroup los_config + * Default task stack size + */ +#ifndef LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE +#define LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE 0x400UL +#endif + +/** + * @ingroup los_config + * Configuration item for task Robin tailoring + */ +#ifndef LOSCFG_BASE_CORE_TIMESLICE +#define LOSCFG_BASE_CORE_TIMESLICE YES +#endif + +/** + * @ingroup los_config + * Longest execution time of tasks with the same priorities + */ +#ifndef LOSCFG_BASE_CORE_TIMESLICE_TIMEOUT +#define LOSCFG_BASE_CORE_TIMESLICE_TIMEOUT 10 +#endif + +/** + * @ingroup los_config + * Configuration item for task (stack) monitoring module tailoring + */ +#ifndef LOSCFG_BASE_CORE_TSK_MONITOR +#define LOSCFG_BASE_CORE_TSK_MONITOR NO +#endif + +/** + * @ingroup los_config + * Configuration item for task perf task filter hook + */ +#ifndef LOSCFG_BASE_CORE_EXC_TSK_SWITCH +#define LOSCFG_BASE_CORE_EXC_TSK_SWITCH NO +#endif + +/** + * @ingroup los_config + * Define a usable task priority.Highest task priority. + */ +#ifndef LOS_TASK_PRIORITY_HIGHEST +#define LOS_TASK_PRIORITY_HIGHEST 0 +#endif + +/** + * @ingroup los_config + * Define a usable task priority.Lowest task priority. + */ +#ifndef LOS_TASK_PRIORITY_LOWEST +#define LOS_TASK_PRIORITY_LOWEST 31 +#endif + +/** + * @ingroup los_config + * SP align size + */ +#ifndef LOSCFG_STACK_POINT_ALIGN_SIZE +#define LOSCFG_STACK_POINT_ALIGN_SIZE 8 +#endif + +/* ============================================================================= + Semaphore module configuration +============================================================================= */ +/** + * @ingroup los_config + * Configuration item for semaphore module tailoring + */ +#ifndef LOSCFG_BASE_IPC_SEM +#define LOSCFG_BASE_IPC_SEM YES +#endif + +/** + * @ingroup los_config + * Maximum supported number of semaphores + */ +#ifndef LOSCFG_BASE_IPC_SEM_LIMIT +#define LOSCFG_BASE_IPC_SEM_LIMIT 6 +#endif + +/* ============================================================================= + Mutex module configuration +============================================================================= */ +/** + * @ingroup los_config + * Configuration item for mutex module tailoring + */ +#ifndef LOSCFG_BASE_IPC_MUX +#define LOSCFG_BASE_IPC_MUX YES +#endif + +/** + * @ingroup los_config + * Maximum supported number of mutexes + */ +#ifndef LOSCFG_BASE_IPC_MUX_LIMIT +#define LOSCFG_BASE_IPC_MUX_LIMIT 6 +#endif + +/* ============================================================================= + Queue module configuration +============================================================================= */ +/** + * @ingroup los_config + * Configuration item for queue module tailoring + */ +#ifndef LOSCFG_BASE_IPC_QUEUE +#define LOSCFG_BASE_IPC_QUEUE YES +#endif + +/** + * @ingroup los_config + * Maximum supported number of queues rather than the number of usable queues + */ +#ifndef LOSCFG_BASE_IPC_QUEUE_LIMIT +#define LOSCFG_BASE_IPC_QUEUE_LIMIT 6 +#endif + + +/* ============================================================================= + Software timer module configuration +============================================================================= */ +/** + * @ingroup los_config + * Configuration item for software timer module tailoring + */ +#ifndef LOSCFG_BASE_CORE_SWTMR +#define LOSCFG_BASE_CORE_SWTMR YES +#endif + +/** + * @ingroup los_config + * Maximum supported number of software timers rather than the number of usable software timers + */ +#ifndef LOSCFG_BASE_CORE_SWTMR_LIMIT +#define LOSCFG_BASE_CORE_SWTMR_LIMIT 5 +#endif + +/** + * @ingroup los_config + * Software timer task stack size + */ +#ifndef LOSCFG_BASE_CORE_TSK_SWTMR_STACK_SIZE +#define LOSCFG_BASE_CORE_TSK_SWTMR_STACK_SIZE LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE +#endif + +/** + * @ingroup los_config + * Configurate item for handling software timer interrupt in task tailoring + */ +#ifndef LOSCFG_BASE_CORE_SWTMR_TASK +#define LOSCFG_BASE_CORE_SWTMR_TASK YES +#endif + +/** + * @ingroup los_config + * Configurate item for software timer align tailoring + */ +#ifndef LOSCFG_BASE_CORE_SWTMR_ALIGN +#define LOSCFG_BASE_CORE_SWTMR_ALIGN NO +#endif + +#if((LOSCFG_BASE_CORE_SWTMR == NO) && (LOSCFG_BASE_CORE_SWTMR_ALIGN == YES)) + #error "swtmr align first need support swmtr, should make LOSCFG_BASE_CORE_SWTMR = YES" +#endif + +/** + * @ingroup los_config + * Max number of software timers ID + */ +#ifndef OS_SWTMR_MAX_TIMERID +#define OS_SWTMR_MAX_TIMERID ((65535 / LOSCFG_BASE_CORE_SWTMR_LIMIT) * LOSCFG_BASE_CORE_SWTMR_LIMIT) +#endif + +/** + * @ingroup los_config + * Maximum size of a software timer queue + */ +#ifndef OS_SWTMR_HANDLE_QUEUE_SIZE +#define OS_SWTMR_HANDLE_QUEUE_SIZE (LOSCFG_BASE_CORE_SWTMR_LIMIT) +#endif + +/** + * @ingroup los_config + * Minimum divisor of software timer multiple alignment + */ +#ifndef LOS_COMMON_DIVISOR +#define LOS_COMMON_DIVISOR 10 +#endif + +/* ============================================================================= + Memory module configuration +============================================================================= */ +extern UINT8 *m_aucSysMem0; + +/** + * @ingroup los_config + * Starting address of the memory + */ +#ifndef OS_SYS_MEM_ADDR +#define OS_SYS_MEM_ADDR (&m_aucSysMem0[0]) +#endif + +/** + * @ingroup los_config + * Ending address of the memory + */ +extern UINT32 g_sysMemAddrEnd; + +/** + * @ingroup los_config + * Memory size + */ +#ifndef OS_SYS_MEM_SIZE +#define OS_SYS_MEM_SIZE 0x10000UL +#endif + +#ifndef LOSCFG_MEMORY_BESTFIT +#define LOSCFG_MEMORY_BESTFIT YES +#endif + +/** + * @ingroup los_config + * Configuration module tailoring of more mempry pool checking + */ +#ifndef LOSCFG_MEM_MUL_POOL +#define LOSCFG_MEM_MUL_POOL NO +#endif + +/** + * @ingroup los_config + * Configuration module tailoring of slab memory + */ +#ifndef LOSCFG_KERNEL_MEM_SLAB +#define LOSCFG_KERNEL_MEM_SLAB YES +#endif + +/** + * @ingroup los_config + * Configuration module tailoring of mem node integrity checking + */ +#ifndef LOSCFG_BASE_MEM_NODE_INTEGRITY_CHECK +#define LOSCFG_BASE_MEM_NODE_INTEGRITY_CHECK NO +#endif + +/** + * @ingroup los_config + * Configuration module tailoring of mem node size checking + */ +#ifndef LOSCFG_BASE_MEM_NODE_SIZE_CHECK +#define LOSCFG_BASE_MEM_NODE_SIZE_CHECK YES +#endif + +/** + * @ingroup los_config + * Configuration module momery alloc and free check + */ +#ifndef LOSCFG_MEM_ENABLE_ALLOC_CHECK +#define LOSCFG_MEM_ENABLE_ALLOC_CHECK YES +#endif + +/** + * @ingroup los_config + * Number of memory checking blocks + */ +#ifndef OS_SYS_MEM_NUM +#define OS_SYS_MEM_NUM 20 +#endif + +/** + * @ingroup los_config + * Configuration heap memory peak statistics + */ +#ifndef LOSCFG_HEAP_MEMORY_PEAK_STATISTICS +#define LOSCFG_HEAP_MEMORY_PEAK_STATISTICS YES +#endif + +/** + * @ingroup los_config + * Size of unaligned memory + */ +#ifndef OS_SYS_NOCACHEMEM_SIZE +#define OS_SYS_NOCACHEMEM_SIZE 0x0UL +#endif + +/** + * @ingroup los_config + * Starting address of the unaligned memory + */ +#if (OS_SYS_NOCACHEMEM_SIZE > 0) +extern UINT8 *g_sysNoCacheMem0; +#define OS_SYS_NOCACHEMEM_ADDR (&g_sysNoCacheMem0[0]) +#endif + + +/* ============================================================================= + Exception module configuration +============================================================================= */ +/** + * @ingroup los_config + * Configuration item for exception tailoring + */ +#ifndef LOSCFG_PLATFORM_EXC +#define LOSCFG_PLATFORM_EXC NO +#endif + +/** + * @ingroup los_config + * Configuration item for saveing exception info tailoring + */ +#ifndef LOSCFG_SAVE_EXC_INFO +#define LOSCFG_SAVE_EXC_INFO NO +#endif + +#if(LOSCFG_PLATFORM_EXC == NO && LOSCFG_SAVE_EXC_INFO == YES) + #error "save exception info need support platform exception, should make LOSCFG_PLATFORM_EXC = YES" +#endif + +/* ============================================================================= + MPU module configuration +============================================================================= */ +/** + * @ingroup los_config + * Configuration item for MPU + */ +#ifndef LOSCFG_BASE_CORE_MPU +#define LOSCFG_BASE_CORE_MPU NO +#endif + +/** + * @ingroup los_config + * MPU support number : MPU maximum number of region support(According to the cotex-m4 authority Guide) + */ +#ifndef LOSCFG_MPU_MAX_SUPPORT +#define LOSCFG_MPU_MAX_SUPPORT 8 +#endif + +/** + * @ingroup los_config + * MPU support address range : from LOSCFG_MPU_MIN_ADDRESS to LOSCFG_MPU_MAX_ADDRESS + */ +#ifndef LOSCFG_MPU_MIN_ADDRESS +#define LOSCFG_MPU_MIN_ADDRESS 0x0UL // Minimum protected address +#endif + +#ifndef LOSCFG_MPU_MAX_ADDRESS +#define LOSCFG_MPU_MAX_ADDRESS 0xFFFFFFFFUL // Maximum protected address +#endif + +/* ============================================================================= + Runstop module configuration +============================================================================= */ +/** + * @ingroup los_config + * Configuration item for runstop module tailoring + */ +#ifndef LOSCFG_KERNEL_RUNSTOP +#define LOSCFG_KERNEL_RUNSTOP YES +#endif + +#ifndef LOSCFG_RUNSTOP_THRESHOLD +#define LOSCFG_RUNSTOP_THRESHOLD 2 +#endif + +/* ============================================================================= + Perf module configuration +============================================================================= */ +/** + * @ingroup los_config + * Configuration item for performance moniter unit + */ +#ifndef OS_INCLUDE_PERF +#define OS_INCLUDE_PERF NO +#endif + + +/* ============================================================================= + CPUP configuration +============================================================================= */ +/** + * @ingroup los_config + * Configuration item for CPU usage tailoring + */ +#ifndef LOSCFG_BASE_CORE_CPUP +#define LOSCFG_BASE_CORE_CPUP NO +#endif + +#ifndef LOSCFG_BASE_CORE_CPUP_HWI +#define LOSCFG_BASE_CORE_CPUP_HWI NO +#endif + +#if(LOSCFG_BASE_CORE_TSK_MONITOR == NO && LOSCFG_BASE_CORE_CPUP == YES) + #error "cpup need support task monitor, should make LOSCFG_BASE_CORE_TSK_MONITOR = YES" +#endif + +/*============================================================================= + FPB configuration +=============================================================================*/ +#ifndef LOSCFG_BASE_CORE_FPB +#define LOSCFG_BASE_CORE_FPB NO +#endif + + +#ifndef LOSCFG_FPB_CONFIG_PCO +#define LOSCFG_FPB_CONFIG_PCO 1 +#endif + +#if (LOSCFG_FPB_CONFIG_PCO > 1) + #error "LOSCFG_FPB_CONFIG_PCO can only set 0 or 1!" +#endif + + +/* ============================================================================= + fw Interface configuration +============================================================================= */ +/** + * @ingroup los_config + * Configuration item for the monitoring of task communication + */ +#ifndef LOSCFG_COMPAT_CMSIS_FW +#define LOSCFG_COMPAT_CMSIS_FW NO +#endif + + +/* ============================================================================= + Shell module configuration +============================================================================= */ +/** + * @ingroup los_config + * Configuration item for shell module tailoring + */ +#ifndef OS_INCLUDE_SHELL +#define OS_INCLUDE_SHELL NO +#endif + +/* ============================================================================= + Lib configurable feature configuration +============================================================================= */ +/** + * @ingroup los_config + * Configuration lib configurable feature to open + */ +#ifndef LOSCFG_LIB_CONFIGURABLE +#define LOSCFG_LIB_CONFIGURABLE NO +#endif + +/* ============================================================================= + Test module configuration +============================================================================= */ +/** + * @ingroup los_config + * Configuration test case to open + */ +#ifndef LOSCFG_TEST +#define LOSCFG_TEST NO +#endif + +/* ============================================================================= + LIBC module configuration +============================================================================= */ +/** + * @ingroup los_config + * Configuration to support libc + */ +#ifndef LOSCFG_LIB_LIBC +#define LOSCFG_LIB_LIBC NO +#endif + +/* ============================================================================= + LiteOS kernel version configuration +============================================================================= */ +/** + * @ingroup los_config + * Version number + */ +#ifndef LITEOS_VER +#endif + +/** + * @ingroup los_config + * Configuration CMSIS_OS_VER + */ +#ifndef CMSIS_OS_VER +#define CMSIS_OS_VER 0 +#endif + +/** + * @ingroup los_config + * @brief: Task start running function. + * + * @par Description: + * This API is used to start a task. + * + * @attention: + *
      • None.
      + * + * @param: None. + * + * @retval None. + * + * @par Dependency: + *
      • los_config.h: the header file that contains the API declaration.
      + * @see None. + */ +extern VOID LOS_StartToRun(VOID); + +/** + * @ingroup los_config + * @brief: Test Task init function. + * + * @par Description: + * This API is used to initialize Test Task. + * + * @attention: + *
      • None.
      + * + * @param: None. + * + * @retval #LOS_OK 0:App_Task initialization success. + * + * @par Dependency: + *
      • los_config.h: the header file that contains the API declaration.
      + * @see None. + */ +extern UINT32 LOS_TestInit(VOID); +#ifdef __cplusplus +#if __cplusplus +} +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +#endif /* _LOS_CONFIG_H */ diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_cpup.h b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_cpup.h new file mode 100644 index 0000000000000000000000000000000000000000..546a99304daea5ef13412f68f5fb24243cbb02c3 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_cpup.h @@ -0,0 +1,113 @@ +/* ---------------------------------------------------------------------------- + * Copyright (c) Huawei Technologies Co., Ltd. 2013-2015. All rights reserved. + * Description : LiteOS Cpu Usage Calculation Module Headfile For User + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * --------------------------------------------------------------------------- */ + +/** + * @defgroup los_cpup CPU usage + * @ingroup kernel + */ + +#ifndef _LOS_CPUP_H +#define _LOS_CPUP_H + +#include "los_sys.h" +#include "los_task.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif /* __cplusplus */ +#endif /* __cplusplus */ + + +/** +* @ingroup los_cpup +* CPU usage error code: The request for memory fails. +* +* Value: 0x02001e00 +* +* Solution: Decrease the maximum number of tasks. +*/ +#define LOS_ERRNO_CPUP_NO_MEMORY LOS_ERRNO_OS_ERROR(LOS_MOD_CPUP, 0x00) + +/** +* @ingroup los_cpup +* CPU usage error code: The pointer to an input parameter is NULL. +* +* Value: 0x02001e01 +* +* Solution: Check whether the pointer to the input parameter is usable. +*/ +#define LOS_ERRNO_CPUP_TASK_PTR_NULL LOS_ERRNO_OS_ERROR(LOS_MOD_CPUP, 0x01) + +/** +* @ingroup los_cpup +* CPU usage error code: The CPU usage is not initialized. +* +* Value: 0x02001e02 +* +* Solution: Check whether the CPU usage is initialized. +*/ +#define LOS_ERRNO_CPUP_NO_INIT LOS_ERRNO_OS_ERROR(LOS_MOD_CPUP, 0x02) + +/** +* @ingroup los_cpup +* CPU usage error code: The number of threads is invalid. +* +* Value: 0x02001e03 +* +* Solution: Check whether the number of threads is applicable for the current operation. +*/ +#define LOS_ERRNO_CPUP_MAXNUM_INVALID LOS_ERRNO_OS_ERROR(LOS_MOD_CPUP, 0x03) + +/** +* @ingroup los_cpup +* Sum of cpup with all tasks. It means the value of cpup is a permillage. +*/ +#define LOS_CPUP_PRECISION 1000 + +/** +* @ingroup los_cpup +* Multiple of current cpup precision change to percent. +*/ +#define LOS_CPUP_PRECISION_MULT (LOS_CPUP_PRECISION / 100) + +/** + * @ingroup los_cpup + * Count the CPU usage structures of all tasks. + */ +typedef struct tagCpupInfo { + UINT16 usStatus; /**< save the cur task status */ + UINT32 uwUsage; /**< Usage. The value range is [0,1000]. */ + UINT64 ullAllTime; /**< Time before a task is invoked */ +} CPUP_INFO_S; + +#ifdef __cplusplus +#if __cplusplus +} +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +#endif /* _LOS_CPUP_H */ diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_cpup_hwi.h b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_cpup_hwi.h new file mode 100644 index 0000000000000000000000000000000000000000..4e09929579e63f6c3998f06a9bf2b9f6eb381ec2 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_cpup_hwi.h @@ -0,0 +1,100 @@ +/* ---------------------------------------------------------------------------- + * Copyright (c) Huawei Technologies Co., Ltd. 2013-2015. All rights reserved. + * Description : LiteOS Cpu Usage Hwi Headfile For User + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * --------------------------------------------------------------------------- */ + +/** + * @defgroup los_cpup CPU usage hwi + * @ingroup kernel + */ + +#ifndef _LOS_CPUP_HWI_H +#define _LOS_CPUP_HWI_H + +#include "los_cpup.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +/** + * @ingroup los_cpup + * @brief Obtain the CPU usage of all tasks. + * + * @par Description: + * This API is used to obtain the CPU usage of all tasks according to the passed-in maximum number of threads. + * @attention + *
        + *
      • This API can be called only after the CPU usage is initialized. + * Otherwise, the CPU usage fails to be obtained.
      • + *
      • The input parameter pointer must not be NULL, and the maximum number of threads must be usable. + * Otherwise, the CPU usage fails to be obtained.
      • + *
      • The input parameter pointer should point to the structure array who's size be greater than + * (maxNum * sizeof (CPUP_INFO_S)).
      • + *
      + * + * @param maxNum [IN] UINT16. The Maximum number of threads. + * @param cpupInfo [OUT]Type. CPUP_INFO_S* Pointer to the task CPUP information structure to be obtained. + * + * @retval #LOS_ERRNO_CPUP_NO_INIT The CPU usage is not initialized. + * @retval #LOS_ERRNO_CPUP_TASK_PTR_NULL The input parameter pointer is NULL. + * @retval #LOS_ERRNO_CPUP_MAXNUM_INVALID The maximum number of threads is invalid. + * @retval #LOS_OK The CPU usage of all tasks is successfully obtained. + * @par Dependency: + *
      • los_cpup.h: the header file that contains the API declaration.
      + * @see + */ +extern UINT32 LOS_AllTaskCpuUsage(UINT16 maxNum, CPUP_INFO_S *cpupInfo); + +/** + * @ingroup los_cpup + * @brief Reset the data of CPU usage. + * + * @par Description: + * This API is used to reset the data of CPU usage. + * @attention + *
        + *
      • None.
      • + *
      + * + * @param None. + * + * @retval #None. + * + * @par Dependency: + *
      • los_cpup.h: the header file that contains the API declaration.
      + * @see + */ +extern VOID LOS_CpupReset(VOID); + +#ifdef __cplusplus +#if __cplusplus +} +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +#endif /* _LOS_CPUP_HWI_H */ + diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_err.h b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_err.h new file mode 100644 index 0000000000000000000000000000000000000000..1b677c924505af8967fd781e97f8bf8e6cddba7a --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_err.h @@ -0,0 +1,158 @@ +/* ---------------------------------------------------------------------------- + * Copyright (c) Huawei Technologies Co., Ltd. 2013-2015. All rights reserved. + * Description: los_err error handling + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * --------------------------------------------------------------------------- */ + +/** + * @defgroup los_err Error handling + * @ingroup kernel + */ + +#ifndef _LOS_ERR_H +#define _LOS_ERR_H + +#include "los_typedef.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif /* __cplusplus */ +#endif /* __cplusplus */ + + +/** + * @ingroup los_err + * @brief Define the pointer to the error handling function. + * + * @par Description: + * This API is used to define the pointer to the error handling function. + * @attention + *
        + *
      • None.
      • + *
      + * + * @param fileName [IN] Log file that stores error information. + * @param lineNo [IN] Line number of the erroneous line. + * @param errorNo [IN] Error code. + * @param paraLen [IN] Length of the input parameter pPara. + * @param para [IN] User label of the error. + * + * @retval None. + * @par Dependency: + *
      • los_err.h: the header file that contains the API declaration.
      + * @see None. + */ +typedef VOID (*LOS_ERRORHANDLE_FUNC)(const CHAR *fileName, + UINT32 lineNo, /**< Line number of the erroneous line. */ + UINT32 errorNo, /**< Error code. */ + UINT32 paraLen, /**< Length of the input parameter pPara. */ + VOID *para); + +/** + * @ingroup los_err + * @brief Error handling function. + * + * @par Description: + * This API is used to perform different operations according to error types. + * @attention + *
        + *
      • None
      • + *
      + * + * @param fileName [IN] Log file that stores error information. + * @param lineNo [IN] Line number of the erroneous line which should not be OS_ERR_MAGIC_WORD. + * @param errorNo [IN] Error code. + * @param paraLen [IN] Length of the input parameter pPara. + * @param para [IN] User label of the error. + * + * @retval LOS_OK The error is successfully processed. + * @par Dependency: + *
      • los_err.h: the header file that contains the API declaration.
      + * @see None + */ +extern UINT32 LOS_ErrHandle(const CHAR *fileName, UINT32 lineNo, + UINT32 errorNo, UINT32 paraLen, + VOID *para); + +/** + * @ingroup los_err + * Error handling function structure. + */ +typedef struct tagUserErrFunc { + LOS_ERRORHANDLE_FUNC pfnHook; /**< Hook function for error handling. */ +} UserErrFunc; + +/** + * @ingroup los_err + * Error handling function. + */ +extern UserErrFunc g_userErrFunc; + +enum LOS_MOUDLE_ID { + LOS_MOD_SYS = 0x0, + LOS_MOD_MEM = 0x1, + LOS_MOD_TSK = 0x2, + LOS_MOD_SWTMR = 0x3, + LOS_MOD_TICK = 0x4, + LOS_MOD_MSG = 0x5, + LOS_MOD_QUE = 0x6, + LOS_MOD_SEM = 0x7, + LOS_MOD_MBOX = 0x8, + LOS_MOD_HWI = 0x9, + LOS_MOD_HWWDG = 0xa, + LOS_MOD_CACHE = 0xb, + LOS_MOD_HWTMR = 0xc, + LOS_MOD_MMU = 0xd, + + LOS_MOD_LOG = 0xe, + LOS_MOD_ERR = 0xf, + + LOS_MOD_EXC = 0x10, + LOS_MOD_CSTK = 0x11, + + LOS_MOD_MPU = 0x12, + LOS_MOD_NMHWI = 0x13, + LOS_MOD_TRACK = 0x14, + LOS_MOD_KNLSTAT = 0x15, + LOS_MOD_EVTTIME = 0x16, + LOS_MOD_THRDCPUP = 0x17, + LOS_MOD_IPC = 0x18, + LOS_MOD_STKMON = 0x19, + LOS_MOD_TIMER = 0x1a, + LOS_MOD_RESLEAKMON = 0x1b, + LOS_MOD_EVENT = 0x1c, + LOS_MOD_MUX = 0X1d, + LOS_MOD_CPUP = 0x1e, + LOS_MOD_SHELL = 0x31, + LOS_MOD_BUTT +}; + + +#ifdef __cplusplus +#if __cplusplus +} +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +#endif /* _LOS_ERR_H */ diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_errno.h b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_errno.h new file mode 100644 index 0000000000000000000000000000000000000000..c9117e4e8f10c30489e17b243f00d823f7d47e91 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_errno.h @@ -0,0 +1,164 @@ +/* ---------------------------------------------------------------------------- + * Copyright (c) Huawei Technologies Co., Ltd. 2013-2015. All rights reserved. + * Description: los_errno error code + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * --------------------------------------------------------------------------- */ + +/** + * @defgroup los_errno Error code + * @ingroup kernel + */ + +#ifndef _LOS_ERRNO_H +#define _LOS_ERRNO_H + +#include "los_err.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +#ifdef LOS_SHORT_ERRNO +#define LOS_ERRNO_OS_ID ((UINT32)0x00 << 16) + +/** + * @ingroup los_errno + * Define the error level as informative. + */ +#define LOS_ERRTYPE_NORMAL ((UINT32)0x00 << 0) + +/** + * @ingroup los_errno + * Define the error level as warning. + */ +#define LOS_ERRTYPE_WARN ((UINT32)0x01 << 0) + +/** + * @ingroup los_errno + * Define the error level as critical. + */ +#define LOS_ERRTYPE_ERROR ((UINT32)0x02 << 0) + +/** + * @ingroup los_errno + * Define the error level as fatal. + */ +#define LOS_ERRTYPE_FATAL ((UINT32)0x03 << 0) + +/** + * @ingroup los_errno + * Define fatal OS errors. + */ +#define LOS_ERRNO_OS_FATAL(moduleID, errno) \ + (LOS_ERRTYPE_FATAL | LOS_ERRNO_OS_ID | ((UINT32)(moduleID) << 2) | (errno << 7)) + +/** + * @ingroup los_errno + * Define critical OS errors. + */ +#define LOS_ERRNO_OS_ERROR(moduleID, errno) \ + (LOS_ERRTYPE_ERROR | LOS_ERRNO_OS_ID | ((UINT32)(moduleID) << 2) | (errno << 7)) + +/** + * @ingroup los_errno + * Define warning OS errors. + */ +#define LOS_ERRNO_OS_WARN(moduleID, errno) \ + (LOS_ERRTYPE_WARN | LOS_ERRNO_OS_ID | ((UINT32)(moduleID) << 2) | (errno << 7)) + +/** + * @ingroup los_errno + * Define informative OS errors. + */ +#define LOS_ERRNO_OS_NORMAL(moduleID, errno) \ + (LOS_ERRTYPE_NORMAL | LOS_ERRNO_OS_ID | ((UINT32)(moduleID) << 2) | (errno << 7)) + +#else +/** + * @ingroup los_errno + * OS error code flag. + */ +#define LOS_ERRNO_OS_ID ((UINT32)0x00 << 16) + +/** + * @ingroup los_errno + * Define the error level as informative. + */ +#define LOS_ERRTYPE_NORMAL ((UINT32)0x00 << 24) + +/** + * @ingroup los_errno + * Define the error level as warning. + */ +#define LOS_ERRTYPE_WARN ((UINT32)0x01 << 24) + +/** + * @ingroup los_errno + * Define the error level as critical. + */ +#define LOS_ERRTYPE_ERROR ((UINT32)0x02 << 24) + +/** + * @ingroup los_errno + * Define the error level as fatal. + */ +#define LOS_ERRTYPE_FATAL ((UINT32)0x03 << 24) + +/** + * @ingroup los_errno + * Define fatal OS errors. + */ +#define LOS_ERRNO_OS_FATAL(moduleID, errno) \ + (LOS_ERRTYPE_FATAL | LOS_ERRNO_OS_ID | ((UINT32)(moduleID) << 8) | (errno)) + +/** + * @ingroup los_errno + * Define critical OS errors. + */ +#define LOS_ERRNO_OS_ERROR(moduleID, errno) \ + (LOS_ERRTYPE_ERROR | LOS_ERRNO_OS_ID | ((UINT32)(moduleID) << 8) | (errno)) + +/** + * @ingroup los_errno + * Define warning OS errors. + */ +#define LOS_ERRNO_OS_WARN(moduleID, errno) \ + (LOS_ERRTYPE_WARN | LOS_ERRNO_OS_ID | ((UINT32)(moduleID) << 8) | (errno)) + +/** + * @ingroup los_errno + * Define informative OS errors. + */ +#define LOS_ERRNO_OS_NORMAL(moduleID, errno) \ + (LOS_ERRTYPE_NORMAL | LOS_ERRNO_OS_ID | ((UINT32)(moduleID) << 8) | (errno)) +#endif + +#ifdef __cplusplus +#if __cplusplus +} +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +#endif /* _LOS_ERRNO_H */ diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_event.h b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_event.h new file mode 100644 index 0000000000000000000000000000000000000000..09a7d29bca3f90fa9f3fd7e6fece16d2d91c6f16 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_event.h @@ -0,0 +1,328 @@ +/* ---------------------------------------------------------------------------- + * Copyright (c) Huawei Technologies Co., Ltd. 2013-2018. All rights reserved. + * Description: Queue Manager + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * --------------------------------------------------------------------------- */ + +/** + * @defgroup los_event Event + * @ingroup kernel + */ + +#ifndef _LOS_EVENT_H +#define _LOS_EVENT_H + +#include "los_base.h" +#include "los_list.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +/** + * @ingroup los_event + * Event reading mode: The task waits for all its expected events to occur. + */ +#define LOS_WAITMODE_AND (4) /* all bits must be set */ + +/** + * @ingroup los_event + * Event reading mode: The task waits for any of its expected events to occur. + */ +#define LOS_WAITMODE_OR (2) /* any bit must be set */ + +/** + * @ingroup los_event + * Event reading mode: The event flag is immediately cleared after the event is read. + */ +#define LOS_WAITMODE_CLR (1) /* clear when satisfied */ + +/** + * @ingroup los_event + * Bit 25 of the event mask cannot be set to an event because it is set to an error code. + * + * Value: 0x02001c00 + * + * Solution: Set bits excluding bit 25 of the event mask to events. + */ +#define LOS_ERRNO_EVENT_SETBIT_INVALID LOS_ERRNO_OS_ERROR(LOS_MOD_EVENT, 0x00) +/** + * @ingroup los_event + * Event reading error code: Event reading times out. + * + * Value: 0x02001c01 + * + * Solution: Increase the waiting time for event reading, or make another task write a mask for the event. + */ +#define LOS_ERRNO_EVENT_READ_TIMEOUT LOS_ERRNO_OS_ERROR(LOS_MOD_EVENT, 0x01) + +/** + * @ingroup los_event + * Event reading error code: The EVENTMASK input parameter value is valid. The input parameter value must not be 0. + * + * Value: 0x02001c02 + * + * Solution: Pass in a valid EVENTMASK value. + */ +#define LOS_ERRNO_EVENT_EVENTMASK_INVALID LOS_ERRNO_OS_ERROR(LOS_MOD_EVENT, 0x02) + +/** + * @ingroup los_event + * Event reading error code: The event is being read during an interrupt. + * + * Value: 0x02001c03 + * + * Solution: Read the event in a task. + */ +#define LOS_ERRNO_EVENT_READ_IN_INTERRUPT LOS_ERRNO_OS_ERROR(LOS_MOD_EVENT, 0x03) + +/** + * @ingroup los_event + * Event reading error code: The uwFlags input parameter value used in the event reading API is invalid. + * This input parameter value is obtained by performing an OR operation on corresponding bits of either OS_EVENT_ANY or + * OS_EVENT_ANY and corresponding bits of either OS_EVENT_WAIT or OS_EVENT_NOWAIT. The waiting time must be set to + * a nonzero value when an event is read in the mode of OS_EVENT_WAIT. + * + * Value: 0x02001c04 + * + * Solution: Pass in a valid uwFlags value. + */ +#define LOS_ERRNO_EVENT_FLAGS_INVALID LOS_ERRNO_OS_ERROR(LOS_MOD_EVENT, 0x04) + +/** + * @ingroup los_event + * Event reading error code: The task is locked and is unable to read the event. + * + * Value: 0x02001c05 + * + * Solution: Unlock the task and read the event. + */ +#define LOS_ERRNO_EVENT_READ_IN_LOCK LOS_ERRNO_OS_ERROR(LOS_MOD_EVENT, 0x05) + +/** + * @ingroup los_event + * Event reading error code: Null pointer. + * + * Value: 0x02001c06 + * + * Solution: Check whether the input parameter is null. + */ +#define LOS_ERRNO_EVENT_PTR_NULL LOS_ERRNO_OS_ERROR(LOS_MOD_EVENT, 0x06) + +/** + * @ingroup los_event + * Event reading error code: no initialized. + * + * Value: 0x02001c07 + * + * Solution: Check whether the event is initialized. + */ +#define LOS_ERRNO_EVENT_NOT_INITIALIZED LOS_ERRNO_OS_ERROR(LOS_MOD_EVENT, 0x07) + +/** + * @ingroup los_event + * Event reading error code: should not be distory. + * + * Value: 0x02001c08 + * + * Solution: Check whether the event list is not empty. + */ +#define LOS_ERRNO_EVENT_SHOULD_NOT_DESTORY LOS_ERRNO_OS_ERROR(LOS_MOD_EVENT, 0x08) + +/** + * @ingroup los_event + * Event control structure + */ +typedef struct tagEvent { + UINT32 uwEventID; /**< Event mask in the event control block, + indicating the event that has been logically processed. */ + LOS_DL_LIST stEventList; /**< Event control block linked list */ +} EVENT_CB_S, *PEVENT_CB_S; +/** + * @ingroup los_event + * @brief Initialize an event control block. + * + * @par Description: + * This API is used to initialize the event control block pointed to by eventCB. + * @attention + *
        + *
      • None.
      • + *
      + * + * @param eventCB [IN/OUT] Pointer to the event control block to be initialized. + * + * @retval #LOS_ERRNO_EVENT_PTR_NULL Null pointer. + * @retval #LOS_OK The event control block is successfully initialized. + * @par Dependency: + *
      • los_event.h: the header file that contains the API declaration.
      + * @see LOS_EventClear + */ +extern UINT32 LOS_EventInit(PEVENT_CB_S eventCB); + +/** + * @ingroup los_event + * @brief Obtain an event specified by the event ID. + * + * @par Description: + * This API is used to check whether an event expected by the user occurs according to the event ID, event mask, + * and event reading mode, and process the event based on the event reading mode. + * The event ID must point to valid memory. + * @attention + *
        + *
      • When the mode is LOS_WAITMODE_CLR, the eventID is passed-out.
      • + *
      • Otherwise the eventID is passed-in.
      • + *
      + * + * @param eventID [IN/OUT] Pointer to the ID of the event to be checked. + * @param eventMask [IN] Mask of the event expected to occur by the user, indicating the event obtained after + * it is logically processed that matches the ID pointed to by mode. + * @param mode [IN] Event reading mode. The modes include LOS_WAITMODE_AND, LOS_WAITMODE_OR, LOS_WAITMODE_CLR. + * + * @retval 0 The event expected by the user does not occur. + * @retval #UINT32 The event expected by the user occurs. + * @par Dependency: + *
      • los_event.h: the header file that contains the API declaration.
      + * @see LOS_EventRead | LOS_EventWrite + */ +extern UINT32 LOS_EventPoll(UINT32 *eventID, UINT32 eventMask, UINT32 mode); + +/** + * @ingroup los_event + * @brief Read an event. + * + * @par Description: + * This API is used to block or schedule a task that reads an event of which the event control block, event mask, + * reading mode, and timeout information are specified. + *
    + * @attention + *
      + *
    • An error code and an event return value can be same. To differentiate the error code and return value, bit 25 of + * the event mask is forbidden to be used.
    • + *
    + * + * @param eventCB [IN/OUT] Pointer to the event control block to be checked. + This parameter must point to valid memory. + * @param eventMask [IN] Mask of the event expected to occur by the user, indicating the event obtained after + * it is logically processed that matches the ID pointed to by eventID. + * @param mode [IN] Event reading mode. + * @param timeOut [IN] Timeout interval of event reading (unit: Tick). + * + * @retval #LOS_ERRNO_EVENT_SETBIT_INVALID Bit 25 of the event mask cannot be set because + it is set to an error number. + * @retval #LOS_ERRNO_EVENT_EVENTMASK_INVALID The passed-in event reading mode is incorrect. + * @retval #LOS_ERRNO_EVENT_READ_IN_INTERRUPT The event is being read during an interrupt. + * @retval #LOS_ERRNO_EVENT_FLAGS_INVALID The event mode is invalid. + * @retval #LOS_ERRNO_EVENT_READ_IN_LOCK The event reading task is locked. + * @retval #LOS_ERRNO_EVENT_PTR_NULL The passed-in pointer is null. + * @retval 0 The event expected by the user does not occur. + * @retval #UINT32 The event expected by the user occurs. + * @par Dependency: + *
    • los_event.h: the header file that contains the API declaration.
    + * @see LOS_EventPoll | LOS_EventWrite + */ +extern UINT32 LOS_EventRead(PEVENT_CB_S eventCB, UINT32 eventMask, UINT32 mode, UINT32 timeOut); + +/** + * @ingroup los_event + * @brief Write an event. + * + * @par Description: + * This API is used to write an event specified by the passed-in event mask into an event control block + * pointed to by eventCB. + * @attention + *
      + *
    • To determine whether the LOS_EventRead API returns an event or an error code, bit 25 of the event mask + * is forbidden to be used.
    • + *
    + * + * @param eventCB [IN/OUT] Pointer to the event control block into which an event is to be written. + * This parameter must point to valid memory. + * @param events [IN] Event mask to be written. + * + * @retval #LOS_ERRNO_EVENT_SETBIT_INVALID Bit 25 of the event mask cannot be set to an event + * because it is set to an error code. + * @retval #LOS_ERRNO_EVENT_PTR_NULL Null pointer. + * @retval #LOS_OK The event is successfully written. + * @par Dependency: + *
    • los_event.h: the header file that contains the API declaration.
    + * @see LOS_EventPoll | LOS_EventRead + */ +extern UINT32 LOS_EventWrite(PEVENT_CB_S eventCB, UINT32 events); + +/** + * @ingroup los_event + * @brief Clear the event occurring in a specified task. + * + * @par Description: + *
      + *
    • This API is used to set the ID of an event that has a specified mask and of which the information is stored in + * an event control block pointed to by eventCB to 0. eventCB must point to valid memory.
    • + *
    + * @attention + *
      + *
    • The value of events needs to be reversed when it is passed-in.
    • + *
    + * + * @param eventCB [IN/OUT] Pointer to the event control block to be cleared. + * @param events [IN] Mask of the event to be cleared. + * + * @retval #LOS_ERRNO_EVENT_PTR_NULL Null pointer. + * @retval #LOS_OK The event is successfully cleared. + * @par Dependency: + *
    • los_event.h: the header file that contains the API declaration.
    + * @see LOS_EventPoll | LOS_EventRead | LOS_EventWrite + */ +extern UINT32 LOS_EventClear(PEVENT_CB_S eventCB, UINT32 events); + +/** + * @ingroup los_event + * @brief Destroy a event. + * + * @par Description: + *
      + *
    • This API is used to Destroy a event.
    • + *
    + * @attention + *
      + *
    • The specific event should be a valid one.
    • + *
    + * + * @param eventCB [IN/OUT] Pointer to the event control block to be Destroyed. + * + * @retval #LOS_ERRNO_EVENT_PTR_NULL Null pointer. + * @retval #LOS_OK The event is successfully cleared. + * @par Dependency: + *
    • los_event.h: the header file that contains the API declaration.
    + * @see LOS_EventPoll | LOS_EventRead | LOS_EventWrite + */ +extern UINT32 LOS_EventDestroy(PEVENT_CB_S eventCB); + +#ifdef __cplusplus +#if __cplusplus +} +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +#endif /* _LOS_EVENT_H */ diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_list.h b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_list.h new file mode 100644 index 0000000000000000000000000000000000000000..40887d0e6050806ab545e532b76071b729303e95 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_list.h @@ -0,0 +1,473 @@ +/* ---------------------------------------------------------------------------- + * Copyright (c) Huawei Technologies Co., Ltd. 2013-2019. All rights reserved. + * Description: Doubly linked list + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * --------------------------------------------------------------------------- */ + +/** + * @defgroup los_list Doubly linked list + * @ingroup kernel + */ + +#ifndef _LOS_LIST_H +#define _LOS_LIST_H + +#include "los_typedef.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +/** + * @ingroup los_list + * Structure of a node in a doubly linked list. + */ +typedef struct LOS_DL_LIST { + struct LOS_DL_LIST *pstPrev; /**< Current node's pointer to the previous node */ + struct LOS_DL_LIST *pstNext; /**< Current node's pointer to the next node */ +} LOS_DL_LIST; + +/** + * @ingroup los_list + * @brief Initialize a doubly linked list. + * + * @par Description: + * This API is used to initialize a doubly linked list. + * @attention + *
      + *
    • The parameter passed in should be ensured to be a legal pointer.
    • + *
    + * + * @param list [IN] Node in a doubly linked list. + * + * @retval None. + * @par Dependency: + *
    • los_list.h: the header file that contains the API declaration.
    + * @see + */ +LITE_OS_SEC_ALW_INLINE STATIC_INLINE VOID LOS_ListInit(LOS_DL_LIST *list) +{ + list->pstNext = list; + list->pstPrev = list; +} + +/** + * @ingroup los_list + * @brief Point to the next node pointed to by the current node. + * + * @par Description: + *
      + *
    • This API is used to point to the next node pointed to by the current node.
    • + *
    + * @attention + *
      + *
    • None.
    • + *
    + * + * @param object [IN] Node in the doubly linked list. + * + * @retval None. + * @par Dependency: + *
    • los_list.h: the header file that contains the API declaration.
    + * @see + */ +#define LOS_DL_LIST_FIRST(object) ((object)->pstNext) + +/** + * @ingroup los_list + * @brief Point to the previous node pointed to by the current node. + * + * @par Description: + *
      + *
    • This API is used to point to the previous node pointed to by the current node.
    • + *
    + * @attention + *
      + *
    • None.
    • + *
    + * + * @param object [IN] Node in the doubly linked list. + * + * @retval None. + * @par Dependency: + *
    • los_list.h: the header file that contains the API declaration.
    + * @see + */ +#define LOS_DL_LIST_LAST(object) ((object)->pstPrev) + +/** + * @ingroup los_list + * @brief Insert a new node to a doubly linked list. + * + * @par Description: + * This API is used to insert a new node to a doubly linked list. + * @attention + *
      + *
    • The parameters passed in should be ensured to be legal pointers.
    • + *
    + * + * @param list [IN] Doubly linked list where the new node is inserted. + * @param node [IN] New node to be inserted. + * + * @retval None + * @par Dependency: + *
    • los_list.h: the header file that contains the API declaration.
    + * @see LOS_ListDelete + */ +LITE_OS_SEC_ALW_INLINE STATIC_INLINE VOID LOS_ListAdd(LOS_DL_LIST *list, LOS_DL_LIST *node) +{ + node->pstNext = list->pstNext; + node->pstPrev = list; + list->pstNext->pstPrev = node; + list->pstNext = node; +} + +/** + * @ingroup los_list + * @brief Insert a node to the tail of a doubly linked list. + * + * @par Description: + * This API is used to insert a new node to the tail of a doubly linked list. + * @attention + *
      + *
    • The parameters passed in should be ensured to be legal pointers.
    • + *
    + * + * @param list [IN] Doubly linked list where the new node is inserted. + * @param node [IN] New node to be inserted. + * + * @retval None. + * @par Dependency: + *
    • los_list.h: the header file that contains the API declaration.
    + * @see LOS_ListAdd | LOS_ListHeadInsert + */ +LITE_OS_SEC_ALW_INLINE STATIC_INLINE VOID LOS_ListTailInsert(LOS_DL_LIST *list, LOS_DL_LIST *node) +{ + LOS_ListAdd(list->pstPrev, node); +} + +/** + * @ingroup los_list + * @brief Insert a node to the head of a doubly linked list. + * + * @par Description: + * This API is used to insert a new node to the head of a doubly linked list. + * @attention + *
      + *
    • The parameters passed in should be ensured to be legal pointers.
    • + *
    + * + * @param list [IN] Doubly linked list where the new node is inserted. + * @param node [IN] New node to be inserted. + * + * @retval None. + * @par Dependency: + *
    • los_list.h: the header file that contains the API declaration.
    + * @see LOS_ListAdd | LOS_ListTailInsert + */ +LITE_OS_SEC_ALW_INLINE STATIC_INLINE VOID LOS_ListHeadInsert(LOS_DL_LIST *list, LOS_DL_LIST *node) +{ + LOS_ListAdd(list, node); +} +/** + * @ingroup los_list + * @brief Delete a specified node from a doubly linked list. + * + * @par Description: + *
      + *
    • This API is used to delete a specified node from a doubly linked list.
    • + *
    + * @attention + *
      + *
    • The parameter passed in should be ensured to be a legal pointer.
    • + *
    + * + * @param node [IN] Node to be deleted. + * + * @retval None. + * @par Dependency: + *
    • los_list.h: the header file that contains the API declaration.
    + * @see LOS_ListAdd + */ +LITE_OS_SEC_ALW_INLINE STATIC_INLINE VOID LOS_ListDelete(LOS_DL_LIST *node) +{ + node->pstNext->pstPrev = node->pstPrev; + node->pstPrev->pstNext = node->pstNext; + node->pstNext = (LOS_DL_LIST *)NULL; + node->pstPrev = (LOS_DL_LIST *)NULL; +} + +/** + * @ingroup los_list + * @brief Identify whether a specified doubly linked list is empty. + * + * @par Description: + *
      + *
    • This API is used to return whether a doubly linked list is empty.
    • + *
    + * @attention + *
      + *
    • The parameter passed in should be ensured to be a legal pointer.
    • + *
    + * + * @param list [IN] Doubly linked node. + * + * @retval TRUE The doubly linked list is empty. + * @retval FALSE The doubly linked list is not empty. + * @par Dependency: + *
    • los_list.h: the header file that contains the API declaration.
    + * @see + */ +LITE_OS_SEC_ALW_INLINE STATIC_INLINE BOOL LOS_ListEmpty(const LOS_DL_LIST *node) +{ + return (BOOL)(node->pstNext == node); +} + +/** + * @ingroup los_list + * @brief Obtain the offset of a field to a structure address. + * + * @par Description: + * This API is used to obtain the offset of a field to a structure address. + * @attention + *
      + *
    • None.
    • + *
    + * + * @param type [IN] Structure name. + * @param field [IN] Name of the field of which the offset is to be measured. + * + * @retval Offset of the field to the structure address. + * @par Dependency: + *
    • los_list.h: the header file that contains the API declaration.
    + * @see + */ +#define OFFSET_OF_FIELD(type, field) ((UINT32)&(((type *)0)->field)) + +/** + * @ingroup los_list + * @brief Obtain the pointer to a doubly linked list in a structure. + * + * @par Description: + * This API is used to obtain the pointer to a doubly linked list in a structure. + * @attention + *
      + *
    • None.
    • + *
    + * + * @param type [IN] Structure name. + * @param member [IN] Member name of the doubly linked list in the structure. + * + * @retval Pointer to the doubly linked list in the structure. + * @par Dependency: + *
    • los_list.h: the header file that contains the API declaration.
    + * @see + */ +#define LOS_OFF_SET_OF(type, member) ((UINT32)&(((type *)0)->member)) + +/** + * @ingroup los_list + * @brief Obtain the pointer to a structure that contains a doubly linked list. + * + * @par Description: + * This API is used to obtain the pointer to a structure that contains a doubly linked list. + *
      + *
    • None.
    • + *
    + * @attention + *
      + *
    • None.
    • + *
    + * + * @param item [IN] Current node's pointer to the next node. + * @param type [IN] Structure name. + * @param member [IN] Member name of the doubly linked list in the structure. + * + * @retval Pointer to the structure that contains the doubly linked list. + * @par Dependency: + *
    • los_list.h: the header file that contains the API declaration.
    + * @see + */ +#define LOS_DL_LIST_ENTRY(item, type, member) \ + ((type *)(VOID *)((CHAR *)(item) - LOS_OFF_SET_OF(type, member))) \ + +/** + * @ingroup los_list + * @brief Iterate over a doubly linked list of given type. + * + * @par Description: + * This API is used to iterate over a doubly linked list of given type. + * @attention + *
      + *
    • None.
    • + *
    + * + * @param item [IN] Pointer to the structure that contains the doubly linked list that is to be traversed. + * @param list [IN] Pointer to the doubly linked list to be traversed. + * @param type [IN] Structure name. + * @param member [IN] Member name of the doubly linked list in the structure. + * + * @retval None. + * @par Dependency: + *
    • los_list.h: the header file that contains the API declaration.
    + * @see + */ +#define LOS_DL_LIST_FOR_EACH_ENTRY(item, list, type, member) \ + for ((item) = LOS_DL_LIST_ENTRY((list)->pstNext, type, member); \ + &(item)->member != (list); \ + (item) = LOS_DL_LIST_ENTRY((item)->member.pstNext, type, member)) + +/** + * @ingroup los_list + * @brief iterate over a doubly linked list safe against removal of list entry. + * + * @par Description: + * This API is used to iterate over a doubly linked list safe against removal of list entry. + * @attention + *
      + *
    • None.
    • + *
    + * + * @param item [IN] Pointer to the structure that contains the doubly linked list that is to be traversed. + * @param next [IN] Save the next node. + * @param list [IN] Pointer to the doubly linked list to be traversed. + * @param type [IN] Structure name. + * @param member [IN] Member name of the doubly linked list in the structure. + * + * @retval None. + * @par Dependency: + *
    • los_list.h: the header file that contains the API declaration.
    + * @see + */ +#define LOS_DL_LIST_FOR_EACH_ENTRY_SAFE(item, next, list, type, member) \ + for ((item) = LOS_DL_LIST_ENTRY((list)->pstNext, type, member), \ + (next) = LOS_DL_LIST_ENTRY((item)->member.pstNext, type, member); \ + &((item)->member) != (list); \ + (item) = (next), (next) = LOS_DL_LIST_ENTRY((item)->member.pstNext, type, member)) + +LITE_OS_SEC_ALW_INLINE STATIC_INLINE VOID osListDel(LOS_DL_LIST *prevNode, LOS_DL_LIST *nextNode) +{ + nextNode->pstPrev = prevNode; + prevNode->pstNext = nextNode; +} + +/** + * @ingroup los_list + * @brief Delete initialize a doubly linked list. + * + * @par Description: + * This API is used to delete initialize a doubly linked list. + * @attention + *
      + *
    • The parameter passed in should be ensured to be s legal pointer.
    • + *
    + * + * @param list [IN] Doubly linked list. + * + * @retval None. + * @par Dependency: + *
    • los_list.h: the header file that contains the API declaration.
    + * @see + */ +LITE_OS_SEC_ALW_INLINE STATIC_INLINE VOID LOS_ListDelInit(LOS_DL_LIST *list) +{ + osListDel(list->pstPrev, list->pstNext); + LOS_ListInit(list); +} + +/** + * @ingroup los_list + * @brief iterate over a doubly linked list. + * + * @par Description: + * This API is used to iterate over a doubly linked list. + * @attention + *
      + *
    • None.
    • + *
    + * + * @param item [IN] Pointer to the structure that contains the doubly linked list that is to be traversed. + * @param list [IN] Pointer to the doubly linked list to be traversed. + * + * @retval None. + * @par Dependency: + *
    • los_list.h: the header file that contains the API declaration.
    + * @see + */ +#define LOS_DL_LIST_FOR_EACH(item, list) \ + for ((item) = (list)->pstNext; (item) != (list); (item) = (item)->pstNext) + +/** + * @ingroup los_list + * @brief Iterate over a doubly linked list safe against removal of list entry. + * + * @par Description: + * This API is used to iterate over a doubly linked list safe against removal of list entry. + * @attention + *
      + *
    • None.
    • + *
    + * + * @param item [IN] Pointer to the structure that contains the doubly linked list that is to be traversed. + * @param next [IN] Save the next node. + * @param list [IN] Pointer to the doubly linked list to be traversed. + * + * @retval None. + * @par Dependency: + *
    • los_list.h: the header file that contains the API declaration.
    + * @see + */ +#define LOS_DL_LIST_FOR_EACH_SAFE(item, next, list) \ + for ((item) = (list)->pstNext, (next) = (item)->pstNext; (item) != (list); \ + (item) = (next), (next) = (item)->pstNext) + +/** + * @ingroup los_list + * @brief Initialize a double linked list. + * + * @par Description: + * This API is used to initialize a double linked list. + * @attention + *
      + *
    • None.
    • + *
    + * + * @param list [IN] Pointer to the doubly linked list to be traversed. + * + * @retval None. + * @par Dependency: + *
    • los_list.h: the header file that contains the API declaration.
    + * @see + */ +#define LOS_DL_LIST_HEAD(list) \ + LOS_DL_LIST list = { &(list), &(list) } + +#ifdef __cplusplus +#if __cplusplus +} +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +#endif /* _LOS_LIST_H */ diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_membox.h b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_membox.h new file mode 100644 index 0000000000000000000000000000000000000000..8e1ab69d605bdf2eb07b99aa15f7270185563ef1 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_membox.h @@ -0,0 +1,198 @@ +/* ---------------------------------------------------------------------------- + * Copyright (c) Huawei Technologies Co., Ltd. 2013-2015. All rights reserved. + * Description: LiteOS memory Module Implementation + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * --------------------------------------------------------------------------- */ + +#ifndef _LOS_MEMBOX_H +#define _LOS_MEMBOX_H + +#include "los_config.h" +#if (LOSCFG_PLATFORM_EXC == YES) +#include "los_memcheck.h" +#endif + +#if (LOSCFG_MEMBOX == YES) + +#define BOX_ALIGN_8 0x80000000 +/* ---------------------------------------------------------------------------- + * Global Functions + * --------------------------------------------------------------------------- */ +/** + * @ingroup los_membox + * Define whether to check the address validity + */ +#if (LOSCFG_PLATFORM_EXC == YES) +#define LOS_MEMBOX_CHECK +extern UINT8 g_memMang[]; +#endif + +typedef struct tagMemBoxCB { + UINT32 uwMaxBlk; + UINT32 uwBlkCnt; + UINT32 uwBlkSize; /* Memory block size */ +}OS_MEMBOX_S; + +typedef OS_MEMBOX_S *OS_MEMBOX_S_P; + +#ifdef LOS_MEMBOX_CHECK +#define LOS_MEMBOX_MAGIC_SIZE 4 +#else +#define LOS_MEMBOX_MAGIC_SIZE 0 +#endif + +/** + * @ingroup los_membox + * @brief Initialize a memory pool. + * + * @par Description: + *
      + *
    • This API is used to initialize a memory pool.
    • + *
    + * @attention + *
      + *
    • The boxSize parameter value should match the following two conditions :
    • + *
    • 1) Be less than or equal to the Memory pool size; 2) Be greater than the size of LOS_MEMBOX_INFO.
    • + *
    + * + * @param boxMem [IN] Memory pool address. + * @param boxSize [IN] Memory pool size. + * @param blkSize [IN] Memory block size. + * + * @retval #LOS_NOK The memory pool fails to be initialized. + * @retval #LOS_OK The memory pool is successfully initialized. + * @par Dependency: + *
      + *
    • los_membox.h: the header file that contains the API declaration.
    • + *
    + * @see None. + */ +extern UINT32 LOS_MemboxInit(VOID *boxMem, UINT32 boxSize, UINT32 blkSize); + +/** + * @ingroup los_membox + * @brief Request a memory block. + * + * @par Description: + *
      + *
    • This API is used to request a memory block.
    • + *
    + * @attention + *
      + *
    • The input pool parameter must be initialized via func LOS_MemboxInit.
    • + *
    + * + * @param boxMem [IN] Memory pool address. + * + * @retval #VOID* The request is accepted, and return a memory block address. + * @retval #NULL The request fails. + * @par Dependency: + *
      + *
    • los_membox.h: the header file that contains the API declaration.
    • + *
    + * @see LOS_MemboxFree + */ +extern VOID *LOS_MemboxAlloc(VOID *boxMem); + +/** + * @ingroup los_membox + * @brief Free a memory block. + * + * @par Description: + *
      + *
    • This API is used to free a memory block.
    • + *
    + * @attention + *
      + *
    • The input pool parameter must be initialized via func LOS_MemboxInit.
    • + *
    • The input pBox parameter must be allocated by LOS_MemboxAlloc.
    • + *
    + * + * @param boxMem [IN] Memory pool address. + * @param box [IN] Memory block address. + * + * @retval #LOS_NOK This memory block fails to be freed. + * @retval #LOS_OK This memory block is successfully freed. + * @par Dependency: + *
      + *
    • los_membox.h: the header file that contains the API declaration.
    • + *
    + * @see LOS_MemboxAlloc + */ +extern UINT32 LOS_MemboxFree(const VOID *boxMem, VOID *box); + +/** + * @ingroup los_membox + * @brief Clear a memory block. + * + * @par Description: + *
      + *
    • This API is used to set the memory block value to be 0.
    • + *
    + * @attention + *
      + *
    • The input pool parameter must be initialized via func LOS_MemboxInit.
    • + *
    • The input pBox parameter must be allocated by LOS_MemboxAlloc.
    • + *
    + * + * @param boxMem [IN] Memory pool address. + * @param box [IN] Memory block address. + * + * @retval VOID + * @par Dependency: + *
      + *
    • los_membox.h: the header file that contains the API declaration.
    • + *
    + * @see None. + */ +extern VOID LOS_MemboxClr(const VOID *boxMem, VOID *box); + + +/** + * @ingroup los_membox + * @brief calculate membox information. + * + * @par Description: + *
      + *
    • This API is used to calculate membox information.
    • + *
    + * @attention + *
      + *
    • One parameter of this interface is a pointer, it should be a correct value, otherwise, the system may be + * abnormal.
    • + *
    + * + * @param boxMem [IN] Type #VOID* Pointer to the calculate membox. + * @param maxBlk [OUT] Type #UINT32* Record membox max block. + * @param blkCnt [OUT] Type #UINT32* Record membox block count alreay allocated. + * @param blkSize [OUT] Type #UINT32* Record membox block size. + * + * @retval #LOS_OK The heap status calculate success. + * @retval #LOS_NOK The membox status calculate with some error. + * @par Dependency: + *
    • los_memory.h: the header file that contains the API declaration.
    + * @see LOS_MemAlloc | LOS_MemRealloc | LOS_MemFree + */ +extern UINT32 LOS_MemboxStatisticsGet(const VOID *boxMem, UINT32 *maxBlk, UINT32 *blkCnt, UINT32 *blkSize); +#endif +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_memcheck.h b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_memcheck.h new file mode 100644 index 0000000000000000000000000000000000000000..7b7158db474af707412286fafae33f15ff9ab81a --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_memcheck.h @@ -0,0 +1,110 @@ +/* ---------------------------------------------------------------------------- + * Copyright (c) Huawei Technologies Co., Ltd. 2013-2015. All rights reserved. + * Description: LiteOS memory Module Implementation + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * --------------------------------------------------------------------------- */ + +#ifndef _LOS_MEMCHECK_H +#define _LOS_MEMCHECK_H + +#include "los_base.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif /* __cpluscplus */ +#endif /* __cpluscplus */ + +#define MEM_INFO_SIZE ((sizeof(MEM_INFO) * OS_SYS_MEM_NUM) + 4) +extern UINT8 g_memMang[]; + +enum _MEM_MANG_TYPE { + MEM_MANG_MEMBOX, + MEM_MANG_MEMORY, + MEM_MANG_EMPTY, +}; + +enum _MEM_MANG_SOUCE { + MEM_MANG_UNUSED, + MEM_MANG_INIT, + MEM_MANG_INT, + MEM_MANG_TASK, +}; + +typedef struct _MEM_INFO { + UINT32 uwType; + UINT32 uwStartAddr; + UINT32 uwSize; +}MEM_INFO; + +typedef struct _SLAB_INFO { + UINT32 item_sz; + UINT32 item_cnt; + UINT32 cur_usage; +}SLAB_INFO; + +#define SLAB_CLASS_NUM (4U) +typedef struct _MEM_INFO_S { + UINT32 uwType; + UINT32 uwStartAddr; + UINT32 uwSize; + UINT32 uwFree; + UINT32 uwBlockSize; + UINT32 uwErrorAddr; + UINT32 uwErrorLen; + UINT32 uwErrorOwner; + SLAB_INFO stSlabInfo[SLAB_CLASS_NUM]; +}MEM_INFO_S; + +/** + * @ingroup los_memboxcheck + * @brief Get the information of the exc memory. + * + * @par Description: + *
      + *
    • This API is used to get the information of the exc memory.
    • + *
    + * @attention + *
      + *
    • None.
    • + *
    + * + * @param memNum [IN] Type #UINT32 Memory pool number. + * @param memExcInfo [IN/OUT] Type #MEM_INFO_S * information of the exc memory. + * + * @retval UINT32 Get information result. + * @par Dependency: + *
      + *
    • los_memboxcheck.h: the header file that contains the API declaration.
    • + *
    + * @see None. + */ +UINT32 LOS_MemExcInfoGet(UINT32 memNum, MEM_INFO_S *memExcInfo); + +#ifdef __cplusplus +#if __cplusplus +} +#endif /* __cpluscplus */ +#endif /* __cpluscplus */ + +#endif /* _LOS_MEMCHECK_H */ diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_memory.h b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_memory.h new file mode 100644 index 0000000000000000000000000000000000000000..7c2f8e214d407ead85508e2d7e32e8ee3c35e5b3 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_memory.h @@ -0,0 +1,666 @@ +/* ---------------------------------------------------------------------------- + * Copyright (c) Huawei Technologies Co., Ltd. 2013-2018. All rights reserved. + * Description: LiteOS Mem Module Implementation + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * --------------------------------------------------------------------------- */ + +#ifndef _LOS_MEMORY_H +#define _LOS_MEMORY_H +#include "los_base.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +/** + * @ingroup los_memory + * Memory information structure + */ +typedef struct { + UINT32 usedSize; + UINT32 freeSize; + UINT32 totalSize; + UINT32 allocCount; + UINT32 freeCount; + UINT32 mallocFailCount; +#if defined(LOSCFG_MEM_WATERLINE) && (LOSCFG_MEM_WATERLINE == YES) + UINT32 usageWaterLine; +#endif +} LOS_MEM_STATUS; + +#if (LOSCFG_MEMORY_BESTFIT == YES) + +#if (LOSCFG_BASE_MEM_NODE_SIZE_CHECK == YES) +#define OS_MEM_CHECK_DEBUG +#endif + +typedef VOID (*MALLOC_HOOK)(VOID); + +extern MALLOC_HOOK g_mallocHook; + +typedef VOID (*MEM_CHECK_ERR_FUNC)(VOID *tmpNode); + +/** + * @ingroup los_memory + * @brief Get the pointer to the little memory pool. + * + * @par Description: + *
      + *
    • This API is used to get the pointer to the little memory pool.
    • + *
    + * @attention + *
      + *
    • None.
    • + *
    + * + * @param None. + * + * @retval #VOID* return the pointer to the little memory pool. + * @par Dependency: + *
    • los_memory.h: the header file that contains the API declaration.
    + */ +extern VOID *LOS_MemGetLmp(VOID); + +/** + * @ingroup los_memory + * @brief Get the size of memory totally used. + * + * @par Description: + *
      + *
    • This API is used to get the size of memory totally used in memory pool.
    • + *
    + * @attention + *
      + *
    • The input pool parameter must be initialized via func LOS_MemInit.
    • + *
    + * + * @param pool [IN] A pointer pointed to the memory pool. + * + * @retval #LOS_NOK The incoming parameter pool is NULL. + * @retval #UINT32 The size of the memory pool used. + * @par Dependency: + *
    • los_memory.h: the header file that contains the API declaration.
    + * @see None. + */ +extern UINT32 LOS_MemTotalUsedGet(VOID *pool); + +/** + * @ingroup los_memory + * @brief Get the number of free memory nodes. + * + * @par Description: + *
      + *
    • This API is used to get the number of free memory nodes in memory pool.
    • + *
    + * @attention + *
      + *
    • The input pool parameter must be initialized via func LOS_MemInit.
    • + *
    + * + * @param pool [IN] A pointer pointed to the memory pool. + * + * @retval #LOS_NOK The incoming parameter pool is NULL. + * @retval #UINT32 The number of free memory nodes. + * @par Dependency: + *
    • los_memory.h: the header file that contains the API declaration.
    + * @see None. + */ +extern UINT32 LOS_MemFreeBlksGet(VOID *pool); + +/** + * @ingroup los_memory + * @brief Get the number of used memory nodes. + * + * @par Description: + *
      + *
    • This API is used to get the number of used memory nodes in memory pool.
    • + *
    + * @attention + *
      + *
    • The input pool parameter must be initialized via func LOS_MemInit.
    • + *
    + * + * @param pool [IN] A pointer pointed to the memory pool. + * + * @retval #LOS_NOK The incoming parameter pool is NULL. + * @retval #UINT32 The number of used memory nodes. + * @par Dependency: + *
    • los_memory.h: the header file that contains the API declaration.
    + * @see None. + */ +extern UINT32 LOS_MemUsedBlksGet(VOID *pool); + +/** + * @ingroup los_memory + * @brief Get the task ID of a used memory node. + * + * @par Description: + *
      + *
    • This API is used to get the task ID of a used memory node.
    • + *
    + * @attention + *
      + *
    • The input ptr parameter must be allocated by LOS_MemAlloc or LOS_MemAllocAlign.
    • + *
    • This interface only support obtain the task ID of a used memory node which is allocated from + * the system memory pool (OS_SYS_MEM_ADDR) at present.
    • + *
    + * + * @param pool [IN] A used memory node. + * + * @retval #OS_INVALID The incoming parameter ptr is illegal. + * @retval #UINT32 The task ID of used memory node ptr. + * @par Dependency: + *
    • los_memory.h: the header file that contains the API declaration.
    + * @see None. + */ +extern UINT32 LOS_MemTaskIdGet(const VOID *pool); + +/** + * @ingroup los_memory + * @brief Get the address of last node. + * + * @par Description: + *
      + *
    • This API is used to get the address of last node.
    • + *
    + * @attention + *
      + *
    • The input pool parameter must be initialized via func LOS_MemInit.
    • + *
    • The last node of memory pool is not the end node.
    • + *
    + * + * @param pool [IN] A pointer pointed to the memory pool. + * + * @retval #LOS_NOK The incoming parameter pool is NULL. + * @retval #UINT32 The address of the last used node that casts to UINT32. + * @par Dependency: + *
    • los_memory.h: the header file that contains the API declaration.
    + * @see None. + */ +extern UINT32 LOS_MemLastUsedGet(VOID *pool); + +/** + * @ingroup los_memory + * @brief Check the memory pool Integrity. + * + * @par Description: + *
      + *
    • This API is used to check the memory pool Integrity.
    • + *
    + * @attention + *
      + *
    • The input pool parameter must be initialized via func LOS_MemInit.
    • + *
    • LOS_MemIntegrityCheck will be called by malloc function when the macro of LOSCFG_BASE_MEM_NODE_INTEGRITY_CHECK + * is defined in LiteOS.
    • + *
    • LOS_MemIntegrityCheck function can be called by user anytime.
    • + *
    + * + * @param pool [IN] A pointer pointed to the memory pool. + * + * @retval #LOS_NOK The memory pool (pool) is impaired. + * @retval #LOS_OK The memory pool (pool) is integrated. + * @par Dependency: + *
    • los_memory.h: the header file that contains the API declaration.
    + * @see None. + */ +extern UINT32 LOS_MemIntegrityCheck(VOID *pool); + +/** + * @ingroup los_memory + * @brief Figure the system memory pool for it's total mem used. + * + * @par Description: + *
      + *
    • This API is used to figure the system memory pool for it's total mem used.
    • + *
    + * + * @retval #UINT32 The mem used. + * @par Dependency: + *
      + *
    • los_memory.h: the header file that contains the API declaration.
    • + *
    + * @see None. + */ +extern UINT32 LOS_MemGetUsed(VOID); + +/** + * @ingroup los_memory + * @brief Get the system memory pool's size. + * + * @par Description: + *
      + *
    • This API is used to get the system memory pool's size.
    • + *
    + * + * @retval #UINT32 The poll size. + * @par Dependency: + *
      + *
    • los_memory.h: the header file that contains the API declaration.
    • + *
    + * @see None. + */ +extern UINT32 LOS_MemGetTotal(VOID); + +/** + * @ingroup los_memory + * @brief Get the memory pool's size. + * + * @par Description: + *
      + *
    • This API is used to get the memory pool's size.
    • + *
    + * + * @retval #UINT32 The memory poll size. + * @par Dependency: + *
      + *
    • los_memory.h: the header file that contains the API declaration.
    • + *
    + * @see None. + */ +extern UINT32 LOS_MemPoolSizeGet(const VOID *pool); + +/** + * @ingroup los_memory + * Define a mem size check intensity + * + * Lowest mem check. + */ +#define LOS_MEM_CHECK_LEVEL_LOW 0 + +/** + * @ingroup los_memory + * Define a mem size check intensity + * + * Highest mem check. + */ +#define LOS_MEM_CHECK_LEVEL_HIGH 1 + +/** + * @ingroup los_memory + * Define a mem size check intensity + * + * disable mem check. + */ +#define LOS_MEM_CHECK_LEVEL_DISABLE 0xff + +/** + * @ingroup los_memory + * Define a mem size check intensity + * + * default intensity set mem check. + */ +#define LOS_MEM_CHECK_LEVEL_DEFAULT LOS_MEM_CHECK_LEVEL_DISABLE + +/** + * @ingroup los_memory + * @brief Check the size of memory node specified. + * + * @par Description: + *
      + *
    • This API is used to check the size of memory node.
    • + *
    + * @attention + *
      + *
    • The input pool parameter must be initialized via func LOS_MemInit.
    • + *
    • The input ptr parameter must be allocated by LOS_MemAlloc or LOS_MemAllocAlign.
    • + *
    • The function will be called by function specified, such as memset or memcpy.
    • + *
    • The feature can be enabled when you set the macro value of LOSCFG_BASE_MEM_NODE_SIZE_CHECK as YES.
    • + *
    • You had better set memory check level as LOS_MEM_CHECK_LEVEL_DISABLE when copy bin file.
    • + *
    + * + * @param pool [IN] A pointer pointed to the memory pool. + * @param ptr [IN] A pointer pointed to the source node. + * @param totalSize [OUT] A pointer to save total size, must point to valid memory. + * @param availSize [OUT] A pointer to save available size, must point to valid memory. + * + * @retval #OS_ERRNO_MEMCHECK_DISABLED Memcheck function does not open. + * @retval #OS_ERRNO_MEMCHECK_NOT_INIT Memcheck function does not init. + * @retval #OS_ERRNO_MEMCHECK_PARA_NULL The pool or ptr is NULL. + * @retval #OS_ERRNO_MEMCHECK_OUTSIDE The ptr address is not in the reasonable range. + * @retval #OS_ERRNO_MEMCHECK_NO_HEAD Can't find the control head node from ptr. + * @retval #OS_ERRNO_MEMCHECK_WRONG_LEVEL The memory check level is illegal. + * @retval #LOS_OK Success to get total size and available + * size of the memory node (ptr). + * @par Dependency: + *
    • los_memory.h: the header file that contains the API declaration.
    + * @see LOS_MemCheckLevelSet | LOS_MemCheckLevelGet + */ +extern UINT32 LOS_MemNodeSizeCheck(VOID *pool, const VOID *ptr, UINT32 *totalSize, UINT32 *availSize); + +/** + * @ingroup los_memory + * @brief Set the memory check level. + * + * @par Description: + *
      + *
    • This API is used to set the memory check level.
    • + *
    + * @attention + *
      + *
    • There are three level you can set.
    • + *
    • The legal level are LOS_MEM_CHECK_LEVEL_LOW, LOS_MEM_CHECK_LEVEL_HIGH, LOS_MEM_CHECK_LEVEL_DISABLE.
    • + *
    + * + * @param level [IN] The level what you want to set. + * + * @retval #LOS_ERRNO_MEMCHECK_WRONG_LEVEL The memory check level what you want to set is illegal. + * @retval #LOS_OK Success to set the memory check level. + * @par Dependency: + *
    • los_memory.h: the header file that contains the API declaration.
    + * @see LOS_MemNodeSizeCheck | LOS_MemCheckLevelGet + */ +extern UINT32 LOS_MemCheckLevelSet(UINT8 level); + +/** + * @ingroup los_memory + * @brief Get the memory check level. + * + * @par Description: + *
      + *
    • This API is used to get the current memory check level.
    • + *
    + * @attention + *
      + *
    • None.
    • + *
    + * + * @param None + * + * @retval #UINT8 The current memory check level. + * @par Dependency: + *
    • los_memory.h: the header file that contains the API declaration.
    + * @see LOS_MemNodeSizeCheck | LOS_MemCheckLevelSet + */ +extern UINT8 LOS_MemCheckLevelGet(VOID); + +/** + * @ingroup los_memory + * @brief Get the memory pool information. + * + * @par Description: + *
      + *
    • This API is used to get the current memory pool used information.
    • + *
    + * @attention + *
      + *
    • The input pool parameter must be initialized via func LOS_MemInit.
    • + *
    • The size of the input parameter size can not be greater than the memory pool size that + * specified at the second input parameter of LOS_MemInit.
    • + *
    • The size of the input parameter size must be four byte-aligned.
    • + *
    + * + * @param pool [IN] Pointer to the memory pool that contains the memory block to be allocated. + * @param status [OUT] Structure contains the mem info. + * + * @retval #LOS_NOK . + * @retval #LOS_OK . + + * @par Dependency: + *
    • los_memory.h: the header file that contains the API declaration.
    + */ +extern UINT32 LOS_MemInfoGet(VOID *pool, LOS_MEM_STATUS *status); +#else + +/** + * @ingroup los_memory + * @brief calculate heap max free block size. + * + * @par Description: + *
      + *
    • This API is used to calculate heap max free block size.
    • + *
    + * @attention + *
      + *
    • None.
    • + *
    + * + * @param pool [IN] Pointer to memory pool. + * + * @retval #UINT32 The max free block size. + * @par Dependency: + *
    • los_memory.h: the header file that contains the API declaration.
    + * @see LOS_MemAlloc | LOS_MemRealloc | LOS_MemFree + */ +extern UINT32 LOS_MemGetMaxFreeBlkSize(VOID *pool); +#endif + +/** + * @ingroup los_memory + * @brief Initialize dynamic memory. + * + * @par Description: + *
      + *
    • This API is used to initialize the dynamic memory of a doubly linked list.
    • + *
    + * @attention + *
      + *
    • The size parameter value should match the following two conditions : 1) Be less than or equal to + * the Memory pool size; 2) Be greater than the size of OS_MEM_MIN_POOL_SIZE.
    • + *
    • Call this API when dynamic memory needs to be initialized during the startup of Huawei LiteOS.
    • + *
    • The parameter input must be four byte-aligned.
    • + *
    • The init area [pool, pool + size] should not conflict with other pools.
    • + *
    + * + * @param pool [IN] Starting address of memory. + * @param size [IN] Memory size. + * + * @retval #LOS_NOK The dynamic memory fails to be initialized. + * @retval #LOS_OK The dynamic memory is successfully initialized. + * @par Dependency: + *
      + *
    • los_memory.h: the header file that contains the API declaration.
    • + *
    + * @see None. + */ +extern UINT32 LOS_MemInit(VOID *pool, UINT32 size); + +/** + * @ingroup los_memory + * @brief Allocate dynamic memory. + * + * @par Description: + *
      + *
    • This API is used to allocate a memory block of which the size is specified.
    • + *
    + * @attention + *
      + *
    • The input pool parameter must be initialized via func LOS_MemInit.
    • + *
    • The size of the input parameter size can not be greater than the memory pool size + * that specified at the second input parameter of LOS_MemInit.
    • + *
    • The size of the input parameter size must be four byte-aligned.
    • + *
    + * + * @param pool [IN] Pointer to the memory pool that contains the memory block to be allocated. + * @param size [IN] Size of the memory block to be allocated (unit: byte). + * + * @retval #NULL The memory fails to be allocated. + * @retval #VOID* The memory is successfully allocated with the starting address of + * the allocated memory block returned. + * @par Dependency: + *
    • los_memory.h: the header file that contains the API declaration.
    + * @see LOS_MemRealloc | LOS_MemAllocAlign | LOS_MemFree + */ +extern VOID *LOS_MemAlloc(VOID *pool, UINT32 size); + +/** + * @ingroup los_memory + * @brief Free dynamic memory. + * + * @par Description: + *
  • This API is used to free specified dynamic memory that has been allocated.
  • + * @attention + *
      + *
    • The input pool parameter must be initialized via func LOS_MemInit.
    • + *
    • The input mem parameter must be allocated by LOS_MemAlloc or LOS_MemAllocAlign or LOS_MemRealloc.
    • + *
    + * + * @param pool [IN] Pointer to the memory pool that contains the dynamic memory block to be freed. + * @param mem [IN] Starting address of the memory block to be freed. + * + * @retval #LOS_NOK The memory block fails to be freed + * @retval #LOS_OK The memory block is successfully freed. + * @par Dependency: + *
    • los_memory.h: the header file that contains the API declaration.
    + * @see LOS_MemAlloc | LOS_MemRealloc | LOS_MemAllocAlign + */ +extern UINT32 LOS_MemFree(VOID *pool, const VOID *mem); + +/** + * @ingroup los_memory + * @brief Re-allocate a memory block. + * + * @par Description: + *
      + *
    • This API is used to allocate a new memory block of which the size is specified by size if the original + * memory block size is insufficient. The new memory block will copy the data in the original memory block of + * which the address is specified by ptr. The size of the new memory block determines the maximum size of data + * to be copied. After the new memory block is created, the original one is freed.
    • + *
    + * @attention + *
      + *
    • The input pool parameter must be initialized via func LOS_MemInit.
    • + *
    • The input ptr parameter must be allocated by LOS_MemAlloc.
    • + *
    • The size of the input parameter size can not be greater than the memory pool size that specified at the + * second input parameter of LOS_MemInit.
    • + *
    • The size of the input parameter size must be aligned as follows: 1) if the ptr is allocated by LOS_MemAlloc, + * it must be four byte-aligned; 2) if the ptr is allocated by LOS_MemAllocAlign, it must be aligned with the size + * of the input parameter uwBoundary of LOS_MemAllocAlign.
    • + *
    + * + * @param pool [IN] Pointer to the memory pool that contains the original and new memory blocks. + * @param ptr [IN] Address of the original memory block. + * @param size [IN] Size of the new memory block. + * + * @retval #NULL The memory fails to be re-allocated. + * @retval #VOID* The memory is successfully re-allocated with the starting address of the new memory block + * returned. + * @par Dependency: + *
    • los_memory.h: the header file that contains the API declaration.
    + * @see LOS_MemAlloc | LOS_MemAllocAlign | LOS_MemFree + */ +extern VOID *LOS_MemRealloc(VOID *pool, const VOID *ptr, UINT32 size); + +/** + * @ingroup los_memory + * @brief Allocate aligned memory. + * + * @par Description: + *
      + *
    • This API is used to allocate memory blocks of specified size and of which the starting addresses are aligned + * on a specified boundary.
    • + *
    + * @attention + *
      + *
    • The input pool parameter must be initialized via func LOS_MemInit.
    • + *
    • The size of the input parameter size can not be greater than the memory pool size that specified at the second + * input parameter of LOS_MemInit.
    • + *
    • The alignment parameter value must be a power of 2 with the minimum value being 4.
    • + *
    + * + * @param pool [IN] Pointer to the memory pool that contains the memory blocks to be allocated. + * @param size [IN] Size of the memory to be allocated. + * @param boundary [IN] Boundary on which the memory is aligned. + * + * @retval #NULL The memory fails to be allocated. + * @retval #VOID* The memory is successfully allocated with the starting address of the allocated memory + * returned. + * @par Dependency: + *
    • los_memory.h: the header file that contains the API declaration.
    + * @see LOS_MemAlloc | LOS_MemRealloc | LOS_MemFree + */ +extern VOID *LOS_MemAllocAlign(VOID *pool, UINT32 size, UINT32 boundary); + +/** + * @ingroup los_memory + * @brief Enable the Intergrity check when alloc and free memory. + * + * @par Description: + *
      + *
    • This API is used to enable the Intergrity check when alloc and free memory.
    • + *
    + * @attention + *
      + *
    • None.
    • + *
    + * + * @param None + * + * @retval None. + * @par Dependency: + *
    • los_memory.h: the header file that contains the API declaration.
    + * @see LOS_MemNodeSizeCheck | LOS_MemCheckLevelSet + */ +extern VOID LOS_MemEnableIntegrityCheck(VOID); + +/** + * @ingroup los_memory + * @brief Disable the intergrity check when alloc and free memory. + * + * @par Description: + *
      + *
    • This API is used to disable the intergrity check when alloc and free memory.
    • + *
    + * @attention + *
      + *
    • None.
    • + *
    + * + * @param None + * + * @retval None. + * @par Dependency: + *
    • los_memory.h: the header file that contains the API declaration.
    + * @see LOS_MemNodeSizeCheck | LOS_MemCheckLevelSet + */ +extern VOID LOS_MemDisableIntegrityCheck(VOID); + +/** + * @ingroup los_memory + * @brief Set lr address saved in memory node info. + * + * @par Description: + *
      + *
    • This API is used to Set lr address saved in memory node info.
    • + *
    + * @attention + *
      + *
    • None.
    • + *
    + * + * @param lr [IN] The lr value need to be saved in memory node info. + * + * @retval None. + * @par Dependency: + *
    • los_memory.h: the header file that contains the API declaration.
    + */ +extern VOID LOS_MemSetLr(UINT32 lr); + +#ifdef __cplusplus +#if __cplusplus +} +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +#endif /* _LOS_MEMORY_H */ diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_mux.h b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_mux.h new file mode 100644 index 0000000000000000000000000000000000000000..0a1f0e76e15012fc7f18a6630cdee96c9f277a8c --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_mux.h @@ -0,0 +1,288 @@ +/* ---------------------------------------------------------------------------- + * Copyright (c) Huawei Technologies Co., Ltd. 2013-2018. All rights reserved. + * Description: mutex + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * --------------------------------------------------------------------------- */ + +/** + * @defgroup los_mux Mutex + * @ingroup kernel + */ + +#ifndef _LOS_MUX_H +#define _LOS_MUX_H + +#include "los_sys.h" +#include "los_list.h" +#include "los_task.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +/** + * @ingroup los_mux + * Mutex error code: The memory request fails. + * + * Value: 0x02001d00 + * + * Solution: Decrease the number of mutexes defined by LOSCFG_BASE_IPC_MUX_LIMIT. + */ +#define LOS_ERRNO_MUX_NO_MEMORY LOS_ERRNO_OS_ERROR(LOS_MOD_MUX, 0x00) + +/** + * @ingroup los_mux + * Mutex error code: The mutex is not usable. + * + * Value: 0x02001d01 + * + * Solution: Check whether the mutex ID and the mutex state are applicable for the current operation. + */ +#define LOS_ERRNO_MUX_INVALID LOS_ERRNO_OS_ERROR(LOS_MOD_MUX, 0x01) + +/** +* @ingroup los_mux +* Mutex error code: Null pointer. +* +* Value: 0x02001d02 +* +* Solution: Check whether the input parameter is usable. +*/ +#define LOS_ERRNO_MUX_PTR_NULL LOS_ERRNO_OS_ERROR(LOS_MOD_MUX, 0x02) + +/** +* @ingroup los_mux +* Mutex error code: No mutex is available and the mutex request fails. +* +* Value: 0x02001d03 +* +* Solution: Increase the number of mutexes defined by LOSCFG_BASE_IPC_MUX_LIMIT. +*/ +#define LOS_ERRNO_MUX_ALL_BUSY LOS_ERRNO_OS_ERROR(LOS_MOD_MUX, 0x03) + +/** +* @ingroup los_mux +* Mutex error code: The mutex fails to be locked in non-blocking mode because it is locked by another thread. +* +* Value: 0x02001d04 +* +* Solution: Lock the mutex after it is unlocked by the thread that owns it, or set a waiting time. +*/ +#define LOS_ERRNO_MUX_UNAVAILABLE LOS_ERRNO_OS_ERROR(LOS_MOD_MUX, 0x04) + +/** +* @ingroup los_mux +* Mutex error code: The mutex is being locked during an interrupt. +* +* Value: 0x02001d05 +* +* Solution: Check whether the mutex is being locked during an interrupt. +*/ +#define LOS_ERRNO_MUX_PEND_INTERR LOS_ERRNO_OS_ERROR(LOS_MOD_MUX, 0x05) + +/** +* @ingroup los_mux +* Mutex error code: A thread locks a mutex after waiting for the mutex to be unlocked by another thread +* when the task scheduling is disabled. +* +* Value: 0x02001d06 +* +* Solution: Check whether the task scheduling is disabled, or set uwtimeout to 0, which means that the +* thread will not wait for the mutex to become available. +*/ +#define LOS_ERRNO_MUX_PEND_IN_LOCK LOS_ERRNO_OS_ERROR(LOS_MOD_MUX, 0x06) + +/** +* @ingroup los_mux +* Mutex error code: The mutex locking times out. +* +* Value: 0x02001d07 +* +* Solution: Increase the waiting time or set the waiting time to LOS_WAIT_FOREVER (forever-blocking mode). +*/ +#define LOS_ERRNO_MUX_TIMEOUT LOS_ERRNO_OS_ERROR(LOS_MOD_MUX, 0x07) + +/** + * @ingroup los_mux + * + * Value: 0x02001d08 + * Not in use temporarily. + */ +#define LOS_ERRNO_MUX_OVERFLOW LOS_ERRNO_OS_ERROR(LOS_MOD_MUX, 0x08) + +/** +* @ingroup los_mux +* Mutex error code: The mutex to be deleted is being locked. +* +* Value: 0x02001d09 +* +* Solution: Delete the mutex after it is unlocked. +*/ +#define LOS_ERRNO_MUX_PENDED LOS_ERRNO_OS_ERROR(LOS_MOD_MUX, 0x09) + +/** + * @ingroup los_mux + * + * Value: 0x02001d0A + * Not in use temporarily. + */ +#define LOS_ERRNO_MUX_GET_COUNT_ERR LOS_ERRNO_OS_ERROR(LOS_MOD_MUX, 0x0A) + +/** + * @ingroup los_mux + * + * Value: 0x02001d0B + * Not in use temporarily. + */ +#define LOS_ERRNO_MUX_REG_ERROR LOS_ERRNO_OS_ERROR(LOS_MOD_MUX, 0x0B) + +/** + * @ingroup los_mux + * + * Mutex error code: LOS_ERRNO_MUX_MAXNUM_ZERO is zero. + * Value: 0x02001d0C + * + * Solution: LOS_ERRNO_MUX_MAXNUM_ZERO should not be zero. + */ +#define LOS_ERRNO_MUX_MAXNUM_ZERO LOS_ERRNO_OS_ERROR(LOS_MOD_MUX, 0x0C) + +/** + * @ingroup los_mux + * @brief Create a mutex. + * + * @par Description: + * This API is used to create a mutex. A mutex handle is assigned to muxHandle when the mutex is created successfully. + * Return LOS_OK on creating successful, return specific error code otherwise. + * @attention + *
      + *
    • The total number of mutexes is pre-configured. If there are no available mutexes, the mutex creation fails.
    • + *
    + * + * @param muxHandle [OUT] Handle pointer of the successfully created mutex. The value of handle should be in + * [0, LOSCFG_BASE_IPC_MUX_LIMIT - 1]. + * + * @retval #LOS_ERRNO_MUX_PTR_NULL The muxHandle pointer is NULL. + * @retval #LOS_ERRNO_MUX_ALL_BUSY No available mutex. + * @retval #LOS_OK The mutex is successfully created. + * @par Dependency: + *
    • los_mux.h: the header file that contains the API declaration.
    + * @see LOS_MuxDelete + */ +extern UINT32 LOS_MuxCreate(UINT32 *muxHandle); + +/** + * @ingroup los_mux + * @brief Delete a mutex. + * + * @par Description: + * This API is used to delete a specified mutex. Return LOS_OK on deleting successfully, return specific error code + * otherwise. + * @attention + *
      + *
    • The specific mutex should be created firstly.
    • + *
    • The mutex can be deleted successfully only if no other tasks pend on it.
    • + *
    + * + * @param muxHandle [IN] Handle of the mutex to be deleted. The value of handle should be in + * [0, LOSCFG_BASE_IPC_MUX_LIMIT - 1]. + * + * @retval #LOS_ERRNO_MUX_INVALID Invalid handle or mutex in use. + * @retval #LOS_ERRNO_MUX_PENDED Tasks pended on this mutex. + * @retval #LOS_OK The mutex is successfully deleted. + * @par Dependency: + *
    • los_mux.h: the header file that contains the API declaration.
    + * @see LOS_MuxCreate + */ +extern UINT32 LOS_MuxDelete(UINT32 muxHandle); + +/** + * @ingroup los_mux + * @brief Wait to lock a mutex. + * + * @par Description: + * This API is used to wait for a specified period of time to lock a mutex. + * @attention + *
      + *
    • The specific mutex should be created firstly.
    • + *
    • The function fails if the mutex that is waited on is already locked by another thread when the task scheduling + * is disabled.
    • + *
    • Do not wait on a mutex during an interrupt.
    • + *
    • The priority inheritance protocol is supported. If a higher-priority thread is waiting on a mutex, it changes + * the priority of the thread that owns the mutex to avoid priority inversion.
    • + *
    • A recursive mutex can be locked more than once by the same thread.
    • + *
    + * + * @param muxHandle [IN] Handle of the mutex to be waited on. The value of handle should be + * in [0, LOSCFG_BASE_IPC_MUX_LIMIT - 1]. + * @param timeout [IN] Waiting time. The value range is [0, LOS_WAIT_FOREVER](unit: Tick). + * + * @retval #LOS_ERRNO_MUX_INVALID The mutex state (for example, the mutex does not exist or is not in use) + * is not applicable for the current operation. + * @retval #LOS_ERRNO_MUX_UNAVAILABLE The mutex fails to be locked because it is locked by another thread and + * a period of time is not set for waiting for the mutex to become available. + * @retval #LOS_ERRNO_MUX_PEND_INTERR The mutex is being locked during an interrupt. + * @retval #LOS_ERRNO_MUX_PEND_IN_LOCK The mutex is waited on when the task scheduling is disabled. + * @retval #LOS_ERRNO_MUX_TIMEOUT The mutex waiting times out. + * @retval #LOS_OK The mutex is successfully locked. + * @par Dependency: + *
    • los_mux.h: the header file that contains the API declaration.
    + * @see LOS_MuxCreate | LOS_MuxPost + */ +extern UINT32 LOS_MuxPend(UINT32 muxHandle, UINT32 timeout); + +/** + * @ingroup los_mux + * @brief Release a mutex. + * + * @par Description: + * This API is used to release a specified mutex. + * @attention + *
      + *
    • The specific mutex should be created firstly.
    • + *
    • Do not release a mutex during an interrupt.
    • + *
    • If a recursive mutex is locked for many times, it must be unlocked for the same times to be released.
    • + *
    + * + * @param muxHandle [IN] Handle of the mutex to be released. The value of handle should be in + * [0, LOSCFG_BASE_IPC_MUX_LIMIT - 1]. + * + * @retval #LOS_ERRNO_MUX_INVALID The mutex state (for example, the mutex does not exist or is not in use + * or owned by other thread) is not applicable for the current operation. + * @retval #LOS_ERRNO_MUX_PEND_INTERR The mutex is being released during an interrupt. + * @retval #LOS_OK The mutex is successfully released. + * @par Dependency: + *
    • los_mux.h: the header file that contains the API declaration.
    + * @see LOS_MuxCreate | LOS_MuxPend + */ +extern UINT32 LOS_MuxPost(UINT32 muxHandle); +extern UINT32 LOS_MuxUsage(VOID); + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif /* _LOS_MUX_H */ diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_queue.h b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_queue.h new file mode 100644 index 0000000000000000000000000000000000000000..de8c9a537e8cbe5ead9572af9e979673f8f2451a --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_queue.h @@ -0,0 +1,734 @@ +/* ---------------------------------------------------------------------------- + * Copyright (c) Huawei Technologies Co., Ltd. 2013-2018. All rights reserved. + * Description: queue + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * --------------------------------------------------------------------------- */ + +/** + * @defgroup los_queue Queue + * @ingroup kernel + */ + +#ifndef _LOS_QUEUE_H +#define _LOS_QUEUE_H + +#include "los_base.h" +#include "los_list.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +/** + * @ingroup los_queue + * Queue error code: The maximum number of queue resources is configured to 0. + * + * Value: 0x02000600 + * + * Solution: Configure the maximum number of queue resources to be greater than 0. If queue modules are not used, + * set the configuration item for the tailoring of the maximum number of queue resources to NO. + */ +#define LOS_ERRNO_QUEUE_MAXNUM_ZERO LOS_ERRNO_OS_ERROR(LOS_MOD_QUE, 0x00) + +/** + * @ingroup los_queue + * Queue error code: The queue block memory fails to be initialized. + * + * Value: 0x02000601 + * + * Solution: Allocate the queue block bigger memory partition, or decrease the maximum number of queue resources. + */ +#define LOS_ERRNO_QUEUE_NO_MEMORY LOS_ERRNO_OS_ERROR(LOS_MOD_QUE, 0x01) + +/** + * @ingroup los_queue + * Queue error code: The memory for queue creation fails to be requested. + * + * Value: 0x02000602 + * + * Solution: Allocate more memory for queue creation, or decrease the queue length and the number of nodes + * in the queue to be created. + */ +#define LOS_ERRNO_QUEUE_CREATE_NO_MEMORY LOS_ERRNO_OS_ERROR(LOS_MOD_QUE, 0x02) + +/** + * @ingroup los_queue + * Queue error code: The size of the biggest message in the created queue is too big. + * + * Value: 0x02000603 + * + * Solution: Change the size of the biggest message in the created queue. + */ +#define LOS_ERRNO_QUEUE_SIZE_TOO_BIG LOS_ERRNO_OS_ERROR(LOS_MOD_QUE, 0x03) + +/** + * @ingroup los_queue + * Queue error code: The upper limit of the number of created queues is exceeded. + * + * Value: 0x02000604 + * + * Solution: Increase the configured number of resources for queues. + */ +#define LOS_ERRNO_QUEUE_CB_UNAVAILABLE LOS_ERRNO_OS_ERROR(LOS_MOD_QUE, 0x04) + +/** + * @ingroup los_queue + * Queue error code: Invalid queue. + * + * Value: 0x02000605 + * + * Solution: Ensure that the passed-in queue ID is valid. + */ +#define LOS_ERRNO_QUEUE_NOT_FOUND LOS_ERRNO_OS_ERROR(LOS_MOD_QUE, 0x05) + +/** + * @ingroup los_queue + * Queue error code: The task is forbidden to be blocked on a queue when the task is locked. + * + * Value: 0x02000606 + * + * Solution: Unlock the task before using a queue. + */ +#define LOS_ERRNO_QUEUE_PEND_IN_LOCK LOS_ERRNO_OS_ERROR(LOS_MOD_QUE, 0x06) + +/** + * @ingroup los_queue + * Queue error code: The time set for waiting to processing the queue expires. + * + * Value: 0x02000607 + * + * Solution: Check whether the expiry time setting is appropriate. + */ +#define LOS_ERRNO_QUEUE_TIMEOUT LOS_ERRNO_OS_ERROR(LOS_MOD_QUE, 0x07) + +/** + * @ingroup los_queue + * Queue error code: The queue that blocks a task cannot be deleted. + * + * Value: 0x02000608 + * + * Solution: Enable the task to obtain resources rather than be blocked on the queue. + */ +#define LOS_ERRNO_QUEUE_IN_TSKUSE LOS_ERRNO_OS_ERROR(LOS_MOD_QUE, 0x08) + +/** + * @ingroup los_queue + * Queue error code: The queue cannot be written during an interrupt when the time for waiting to + * processing the queue expires. + * + * Value: 0x02000609 + * + * Solution: Set the expiry time to the never-waiting mode, or use asynchronous queues. + */ +#define LOS_ERRNO_QUEUE_WRITE_IN_INTERRUPT LOS_ERRNO_OS_ERROR(LOS_MOD_QUE, 0x09) + +/** + * @ingroup los_queue + * Queue error code: The queue is not created. + * + * Value: 0x0200060a + * + * Solution: Check whether the passed-in queue handle value is valid. + */ +#define LOS_ERRNO_QUEUE_NOT_CREATE LOS_ERRNO_OS_ERROR(LOS_MOD_QUE, 0x0a) + +/** + * @ingroup los_queue + * Queue error code: Queue reading and writing are not synchronous. + * + * Value: 0x0200060b + * + * Solution: Synchronize queue reading with queue writing. + */ +#define LOS_ERRNO_QUEUE_IN_TSKWRITE LOS_ERRNO_OS_ERROR(LOS_MOD_QUE, 0x0b) + +/** + * @ingroup los_queue + * Queue error code: Parameters passed in during queue creation are null pointers. + * + * Value: 0x0200060c + * + * Solution: Ensure the passed-in parameters are not null pointers. + */ +#define LOS_ERRNO_QUEUE_CREAT_PTR_NULL LOS_ERRNO_OS_ERROR(LOS_MOD_QUE, 0x0c) + +/** + * @ingroup los_queue + * Queue error code: The queue length or message node size passed in during queue creation is 0. + * + * Value: 0x0200060d + * + * Solution: Pass in correct queue length and message node size. + */ +#define LOS_ERRNO_QUEUE_PARA_ISZERO LOS_ERRNO_OS_ERROR(LOS_MOD_QUE, 0x0d) + +/** + * @ingroup los_queue + * Queue error code: The handle of the queue is invalid. + * + * Value: 0x0200060e + * + * Solution: Check whether the passed-in queue handle value is valid. + */ +#define LOS_ERRNO_QUEUE_INVALID LOS_ERRNO_OS_ERROR(LOS_MOD_QUE, 0x0e) + +/** + * @ingroup los_queue + * Queue error code: The pointer passed in during queue reading is null. + * + * Value: 0x0200060f + * + * Solution: Check whether the passed-in pointer is null. + */ +#define LOS_ERRNO_QUEUE_READ_PTR_NULL LOS_ERRNO_OS_ERROR(LOS_MOD_QUE, 0x0f) + +/** + * @ingroup los_queue + * Queue error code: The buffer size passed in during queue reading is 0. + * + * Value: 0x02000610 + * + * Solution: Pass in a correct buffer size. + */ +#define LOS_ERRNO_QUEUE_READSIZE_ISZERO LOS_ERRNO_OS_ERROR(LOS_MOD_QUE, 0x10) + +/** + * @ingroup los_queue + * Queue error code: The queue handle passed in during queue writing is invalid. + * + * Value: 0x02000611 + * + * Solution: Check whether the passed-in queue handle value is valid. + */ +#define LOS_ERRNO_QUEUE_WRITE_INVALID LOS_ERRNO_OS_ERROR(LOS_MOD_QUE, 0x11) + +/** + * @ingroup los_queue + * Queue error code: The pointer passed in during queue writing is null. + * + * Value: 0x02000612 + * + * Solution: Check whether the passed-in pointer is null. + */ +#define LOS_ERRNO_QUEUE_WRITE_PTR_NULL LOS_ERRNO_OS_ERROR(LOS_MOD_QUE, 0x12) + +/** + * @ingroup los_queue + * Queue error code: The buffer size passed in during queue writing is 0. + * + * Value: 0x02000613 + * + * Solution: Pass in a correct buffer size. + */ +#define LOS_ERRNO_QUEUE_WRITESIZE_ISZERO LOS_ERRNO_OS_ERROR(LOS_MOD_QUE, 0x13) + +/** + * @ingroup los_queue + * Queue error code: The buffer size passed in during queue writing is bigger than the queue size. + * + * Value: 0x02000615 + * + * Solution: Decrease the buffer size, or use a queue in which nodes are bigger. + */ +#define LOS_ERRNO_QUEUE_WRITE_SIZE_TOO_BIG LOS_ERRNO_OS_ERROR(LOS_MOD_QUE, 0x15) + +/** + * @ingroup los_queue + * Queue error code: No free node is available during queue writing. + * + * Value: 0x02000616 + * + * Solution: Ensure that free nodes are available before queue writing. + */ +#define LOS_ERRNO_QUEUE_ISFULL LOS_ERRNO_OS_ERROR(LOS_MOD_QUE, 0x16) + +/** + * @ingroup los_queue + * Queue error code: The pointer passed in when the queue information is being obtained is null. + * + * Value: 0x02000617 + * + * Solution: Check whether the passed-in pointer is null. + */ +#define LOS_ERRNO_QUEUE_PTR_NULL LOS_ERRNO_OS_ERROR(LOS_MOD_QUE, 0x17) + +/** + * @ingroup los_queue + * Queue error code: The queue cannot be read during an interrupt + * when the time for waiting to processing the queue expires. + * + * Value: 0x02000618 + * + * Solution: Set the expiry time to the never-waiting mode, or use asynchronous queues. + */ +#define LOS_ERRNO_QUEUE_READ_IN_INTERRUPT LOS_ERRNO_OS_ERROR(LOS_MOD_QUE, 0x18) + +/** + * @ingroup los_queue + * Queue error code: The handle of the queue passed-in when the memory for the queue is being freed is invalid. + * + * Value: 0x02000619 + * + * Solution: Check whether the passed-in queue handle value is valid. + */ +#define LOS_ERRNO_QUEUE_MAIL_HANDLE_INVALID LOS_ERRNO_OS_ERROR(LOS_MOD_QUE, 0x19) + +/** + * @ingroup los_queue + * Queue error code: The pointer to the memory to be freed is null. + * + * Value: 0x0200061a + * + * Solution: Check whether the passed-in pointer is null. + */ +#define LOS_ERRNO_QUEUE_MAIL_PTR_INVALID LOS_ERRNO_OS_ERROR(LOS_MOD_QUE, 0x1a) + +/** + * @ingroup los_queue + * Queue error code: The memory for the queue fails to be freed. + * + * Value: 0x0200061b + * + * Solution: Pass in correct input parameters. + */ +#define LOS_ERRNO_QUEUE_MAIL_FREE_ERROR LOS_ERRNO_OS_ERROR(LOS_MOD_QUE, 0x1b) + +/** + * @ingroup los_queue + * Queue error code: No resource is in the queue that is being read when the + * time for waiting to processing the queue expires. + * + * Value: 0x0200061d + * + * Solution: Ensure that the queue contains messages when it is being read. + */ +#define LOS_ERRNO_QUEUE_ISEMPTY LOS_ERRNO_OS_ERROR(LOS_MOD_QUE, 0x1d) + +/** + * @ingroup los_queue + * Queue error code: The buffer size passed in during queue readding is smaller than the queue size. + * + * Value: 0x0200061f + * + * Solution: Increase the buffer size, or use a queue in which nodes are smaller. + */ +#define LOS_ERRNO_QUEUE_READ_SIZE_TOO_SMALL LOS_ERRNO_OS_ERROR(LOS_MOD_QUE, 0x1f) + +/** + * @ingroup los_queue + * Structure of the block for queue information query + */ +typedef struct tagQueueInfo { + UINT32 queueID; /**< Queue ID */ + UINT16 queueLen; /**< Queue length */ + UINT16 queueSize; /**< Node size */ + UINT16 queueHead; /**< Node head */ + UINT16 queueTail; /**< Node tail */ + UINT16 writableCnt; /**< Count of writable resources */ + UINT16 readableCnt; /**< Count of readable resources */ + UINT32 waitReadTask; /**< Resource reading task */ + UINT32 waitWriteTask; /**< Resource writing task */ + UINT32 waitMemTask; /**< Memory task */ +} QUEUE_INFO_S; + +/** + * @ingroup los_queue + * @brief Create a message queue. + * + * @par Description: + * This API is used to create a message queue. + * @attention + *
      + *
    • Threre are LOSCFG_BASE_IPC_QUEUE_LIMIT queues available, change it's value when necessory.
    • + *
    + * @param queueName [IN] Message queue name. Reserved parameter, not used for now. + * @param len [IN] Queue length. The value range is [1,0xffff]. + * @param queueID [OUT] ID of the queue control structure that is successfully created. + * @param flags [IN] Queue mode. Reserved parameter, not used for now. + * @param maxMsgSize [IN] Node size. The value range is [1,0xffff-4]. + * + * @retval #LOS_OK The message queue is successfully created. + * @retval #LOS_ERRNO_QUEUE_CB_UNAVAILABLE The upper limit of the number of created queues is exceeded. + * @retval #LOS_ERRNO_QUEUE_CREATE_NO_MEMORY Insufficient memory for queue creation. + * @retval #LOS_ERRNO_QUEUE_CREAT_PTR_NULL Null pointer, queueID is NULL. + * @retval #LOS_ERRNO_QUEUE_PARA_ISZERO The queue length or message node size passed in during queue + * creation is 0. + * @retval #LOS_ERRNO_QUEUE_SIZE_TOO_BIG The parameter maxMsgSize is larger than 0xffff - 4. + * @par Dependency: + *
    • los_queue.h: the header file that contains the API declaration.
    + * @see LOS_QueueDelete + */ +extern UINT32 LOS_QueueCreate(const CHAR *queueName, + UINT16 len, + UINT32 *queueID, + UINT32 flags, + UINT16 maxMsgSize); + +/** + * @ingroup los_queue + * @brief Read a queue. + * + * @par Description: + * This API is used to read data in a specified queue, and store the obtained data to the address specified + * by bufferAddr. The address and the size of the data to be read are defined by users. + * @attention + *
      + *
    • The specific queue should be created firstly.
    • + *
    • Queue reading adopts the fist in first out (FIFO) mode. The data that is first stored in the queue is read + * first.
    • + *
    • bufferAddr stores the obtained data.
    • + *
    • Do not read or write a queue in unblocking modes such as an interrupt.
    • + *
    • This API cannot be called before the Huawei LiteOS is initialized.
    • + *
    • The argument timeOut is a relative time.
    • + *
    + * + * @param queueID [IN] Queue ID created by LOS_QueueCreate. The value range is + * [1,LOSCFG_BASE_IPC_QUEUE_LIMIT]. + * @param bufferAddr [OUT] Starting address that stores the obtained data. The starting address must not be + * null. + * @param bufferSize [IN/OUT] Where to maintain the buffer wantted-size before read, and the real-size after read. + * @param timeOut [IN] Expiry time. The value range is [0,LOS_WAIT_FOREVER](unit: Tick). + * + * @retval #LOS_OK The queue is successfully read. + * @retval #LOS_ERRNO_QUEUE_INVALID The handle of the queue that is being read is invalid. + * @retval #LOS_ERRNO_QUEUE_READ_PTR_NULL The pointer passed in during queue reading is null. + * @retval #LOS_ERRNO_QUEUE_READSIZE_ISZERO The buffer size passed in during queue reading is 0. + * @retval #LOS_ERRNO_QUEUE_READ_IN_INTERRUPT The queue cannot be read during an interrupt when the time for + * waiting to processing the queue expires. + * @retval #LOS_ERRNO_QUEUE_NOT_CREATE The queue to be read is not created. + * @retval #LOS_ERRNO_QUEUE_ISEMPTY No resource is in the queue that is being read when the time for + * waiting to processing the queue expires. + * @retval #LOS_ERRNO_QUEUE_PEND_IN_LOCK The task is forbidden to be blocked on a queue when the task is + * locked. + * @retval #LOS_ERRNO_QUEUE_TIMEOUT The time set for waiting to processing the queue expires. + * @retval #LOS_ERRNO_QUEUE_READ_SIZE_TOO_SMALL The buffer size passed in during queue reading is less than + * the queue size. + * @par Dependency: + *
    • los_queue.h: the header file that contains the API declaration.
    + * @see LOS_QueueWriteCopy | LOS_QueueCreate + */ +extern UINT32 LOS_QueueReadCopy(UINT32 queueID, + VOID *bufferAddr, + UINT32 *bufferSize, + UINT32 timeOut); + +/** + * @ingroup los_queue + * @brief Write data into a queue. + * + * @par Description: + * This API is used to write the data of the size specified by bufferSize and stored at the address specified by + * bufferAddr into a queue. + * @attention + *
      + *
    • The specific queue should be created firstly.
    • + *
    • Do not read or write a queue in unblocking modes such as interrupt.
    • + *
    • This API cannot be called before the Huawei LiteOS is initialized.
    • + *
    • The data to be written is of the size specified by bufferSize and is stored at the address specified by + * BufferAddr.
    • + *
    • The argument timeOut is a relative time.
    • + *
    + * + * @param queueID [IN] Queue ID created by LOS_QueueCreate. The value range is + * [1,LOSCFG_BASE_IPC_QUEUE_LIMIT]. + * @param bufferAddr [IN] Starting address that stores the data to be written.The starting address must + * not be null. + * @param bufferSize [IN] Passed-in buffer size. The value range is [1,USHRT_MAX - sizeof(UINT32)]. + * @param timeOut [IN] Expiry time. The value range is [0,LOS_WAIT_FOREVER](unit: Tick). + * + * @retval #LOS_OK The data is successfully written into the queue. + * @retval #LOS_ERRNO_QUEUE_INVALID The queue handle passed in during queue writing is invalid. + * @retval #LOS_ERRNO_QUEUE_WRITE_PTR_NULL The pointer passed in during queue writing is null. + * @retval #LOS_ERRNO_QUEUE_WRITESIZE_ISZERO The buffer size passed in during queue writing is 0. + * @retval #LOS_ERRNO_QUEUE_WRITE_IN_INTERRUPT The queue cannot be written during an interrupt when the time + * for waiting to processing the queue expires. + * @retval #LOS_ERRNO_QUEUE_NOT_CREATE The queue into which the data is written is not created. + * @retval #LOS_ERRNO_QUEUE_WRITE_SIZE_TOO_BIG The buffer size passed in during queue writing is bigger than + * the queue size. + * @retval #LOS_ERRNO_QUEUE_ISFULL No free node is available during queue writing. + * @retval #LOS_ERRNO_QUEUE_PEND_IN_LOCK The task is forbidden to be blocked on a queue when + * the task is locked. + * @retval #LOS_ERRNO_QUEUE_TIMEOUT The time set for waiting to processing the queue expires. + * @par Dependency: + *
    • los_queue.h: the header file that contains the API declaration.
    + * @see LOS_QueueReadCopy | LOS_QueueCreate + */ +extern UINT32 LOS_QueueWriteCopy(UINT32 queueID, + VOID *bufferAddr, + UINT32 bufferSize, + UINT32 timeOut); + +/** + * @ingroup los_queue + * @brief Read a queue. + * + * @par Description: + * This API is used to read the address of data in a specified queue, and store it to the address specified by + * bufferAddr. + * @attention + *
      + *
    • The specific queue should be created firstly.
    • + *
    • Queue reading adopts the fist in first out (FIFO) mode. The data that is first stored in the queue is + * read first.
    • + *
    • bufferAddr stores the obtained data address.
    • + *
    • Do not read or write a queue in unblocking modes such as an interrupt.
    • + *
    • This API cannot be called before the Huawei LiteOS is initialized.
    • + *
    • The argument timeOut is a relative time.
    • + *
    • The bufferSize is not really used in LOS_QueueRead, because the interface is only used to + * obtain the address of data.
    • + *
    • The buffer which the bufferAddr pointing to must be greater than or equal to 4 bytes.
    • + *
    + * + * @param queueID [IN] Queue ID created by LOS_QueueCreate. The value range is + * [1,LOSCFG_BASE_IPC_QUEUE_LIMIT]. + * @param bufferAddr [OUT] Starting address that stores the obtained data. The starting address must + * not be null. + * @param bufferSize [IN] Passed-in buffer size, which must not be 0. The value range is [1,0xffffffff]. + * @param timeOut [IN] Expiry time. The value range is [0,LOS_WAIT_FOREVER](unit: Tick). + * + * @retval #LOS_OK The queue is successfully read. + * @retval #LOS_ERRNO_QUEUE_INVALID The handle of the queue that is being read is invalid. + * @retval #LOS_ERRNO_QUEUE_READ_PTR_NULL The pointer passed in during queue reading is null. + * @retval #LOS_ERRNO_QUEUE_READSIZE_ISZERO The buffer size passed in during queue reading is 0. + * @retval #LOS_ERRNO_QUEUE_READ_IN_INTERRUPT The queue cannot be read during an interrupt when the time for + * waiting to processing the queue expires. + * @retval #LOS_ERRNO_QUEUE_NOT_CREATE The queue to be read is not created. + * @retval #LOS_ERRNO_QUEUE_ISEMPTY No resource is in the queue that is being read when the time for + * waiting to processing the queue expires. + * @retval #LOS_ERRNO_QUEUE_PEND_IN_LOCK The task is forbidden to be blocked on a queue when the task is + * locked. + * @retval #LOS_ERRNO_QUEUE_TIMEOUT The time set for waiting to processing the queue expires. + * @par Dependency: + *
    • los_queue.h: The header file that contains the API declaration.
    + * @see LOS_QueueWrite | LOS_QueueCreate + */ +extern UINT32 LOS_QueueRead(UINT32 queueID, + VOID *bufferAddr, + UINT32 bufferSize, + UINT32 timeOut); + +/** + * @ingroup los_queue + * @brief Write data into a queue. + * + * @par Description: + * This API is used to write the address of data specified by bufferAddr into a queue. + * @attention + *
      + *
    • The specific queue should be created firstly.
    • + *
    • Do not read or write a queue in unblocking modes such as an interrupt.
    • + *
    • This API cannot be called before the Huawei LiteOS is initialized.
    • + *
    • The address of the data of the size specified by bufferSize and stored at the address specified by + * BufferAddr is to be written.
    • + *
    • The argument timeOut is a relative time.
    • + *
    • The bufferSize is not really used in LOS_QueueWrite, because the interface is only used to write the address + * of data specified by bufferAddr into a queue.
    • + *
    + * + * @param queueID [IN] Queue ID created by LOS_QueueCreate. The value range is + * [1,LOSCFG_BASE_IPC_QUEUE_LIMIT]. + * @param bufferAddr [IN] Starting address that stores the data to be written. The starting address + * must not be null. + * @param bufferSize [IN] Passed-in buffer size, which must not be 0. The value range is [1,0xffffffff]. + * @param timeOut [IN] Expiry time. The value range is [0,LOS_WAIT_FOREVER](unit: Tick). + * + * @retval #LOS_OK The data is successfully written into the queue. + * @retval #LOS_ERRNO_QUEUE_INVALID The queue handle passed in during queue writing is invalid. + * @retval #LOS_ERRNO_QUEUE_WRITE_PTR_NULL The pointer passed in during queue writing is null. + * @retval #LOS_ERRNO_QUEUE_WRITESIZE_ISZERO The buffer size passed in during queue writing is 0. + * @retval #LOS_ERRNO_QUEUE_WRITE_IN_INTERRUPT The queue cannot be written during an interrupt when the time for + * waiting to processing the queue expires. + * @retval #LOS_ERRNO_QUEUE_NOT_CREATE The queue into which the data is written is not created. + * @retval #LOS_ERRNO_QUEUE_WRITE_SIZE_TOO_BIG The buffer size passed in during queue writing is bigger than + * the queue size. + * @retval #LOS_ERRNO_QUEUE_ISFULL No free node is available during queue writing. + * @retval #LOS_ERRNO_QUEUE_PEND_IN_LOCK The task is forbidden to be blocked on a queue when the task is + * locked. + * @retval #LOS_ERRNO_QUEUE_TIMEOUT The time set for waiting to processing the queue expires. + * @par Dependency: + *
    • los_queue.h: The header file that contains the API declaration.
    + * @see LOS_QueueRead | LOS_QueueCreate + */ +extern UINT32 LOS_QueueWrite(UINT32 queueID, + VOID *bufferAddr, + UINT32 bufferSize, + UINT32 timeOut); + +/** + * @ingroup los_queue + * @brief Write data into a queue header. + * + * @par Description: + * This API is used to write the data of the size specified by bufferSize and stored at the address specified by + * bufferAddr into a queue header. + * @attention + *
      + *
    • Do not read or write a queue in unblocking modes such as an interrupt.
    • + *
    • This API cannot be called before the Huawei LiteOS is initialized.
    • + *
    • The address of the data of the size specified by bufferSize and stored at the address specified by + * BufferAddr is to be written.
    • + *
    • The argument timeOut is a relative time.
    • + *
    • LOS_QueueRead and LOS_QueueWriteHead are a set of interfaces, and the two groups of interfaces need to be used. + *
    • + *
    + * + * @param queueID [IN] Queue ID created by LOS_QueueCreate. The value range is + * [1,LOSCFG_BASE_IPC_QUEUE_LIMIT]. + * @param bufferAddr [OUT] Starting address that stores the data to be written. The starting address + * must not be null. + * @param bufferSize [IN] Passed-in buffer size, which must not be 0. The value range is [1,0xffffffff]. + * @param timeOut [IN] Expiry time. The value range is [0,LOS_WAIT_FOREVER](unit: Tick). + * + * @retval #LOS_OK The data is successfully written into the queue. + * @retval #LOS_ERRNO_QUEUE_INVALID The queue handle passed in during queue writing is invalid. + * @retval #LOS_ERRNO_QUEUE_WRITE_PTR_NULL The pointer passed in during queue writing is null. + * @retval #LOS_ERRNO_QUEUE_WRITESIZE_ISZERO The buffer size passed in during queue writing is 0. + * @retval #LOS_ERRNO_QUEUE_WRITE_IN_INTERRUPT The queue cannot be written during an interrupt when the time for + * waiting to processing the queue expires. + * @retval #LOS_ERRNO_QUEUE_NOT_CREATE The queue into which the data is written is not created. + * @retval #LOS_ERRNO_QUEUE_WRITE_SIZE_TOO_BIG The buffer size passed in during queue writing is bigger than + * the queue size. + * @retval #LOS_ERRNO_QUEUE_ISFULL No free node is available during queue writing. + * @retval #LOS_ERRNO_QUEUE_PEND_IN_LOCK The task is forbidden to be blocked on a queue when the task is + * locked. + * @retval #LOS_ERRNO_QUEUE_TIMEOUT The time set for waiting to processing the queue expires. + * @par Dependency: + *
    • los_queue.h: The header file that contains the API declaration.
    + * @see LOS_QueueRead | LOS_QueueCreate + */ +extern UINT32 LOS_QueueWriteHead(UINT32 queueID, + VOID *bufferAddr, + UINT32 bufferSize, + UINT32 timeOut); + +/** + * @ingroup los_queue + * @brief Write data into a queue header. + * + * @par Description: + * This API is used to write the data of the size specified by bufferSize and stored at the address specified by + * bufferAddr into a queue header. + * @attention + *
      + *
    • Do not read or write a queue in unblocking modes such as an interrupt.
    • + *
    • This API cannot be called before the Huawei LiteOS is initialized.
    • + *
    • The address of the data of the size specified by bufferSize and stored at the address specified by + * BufferAddr is to be written.
    • + *
    • The argument timeOut is a relative time.
    • + *
    • LOS_QueueRead and LOS_QueueWriteHead are a set of interfaces, and the two groups of interfaces need to be + * used.
    • + *
    + * + * @param queueID [IN] Queue ID created by LOS_QueueCreate. The value range is + * [1,LOSCFG_BASE_IPC_QUEUE_LIMIT]. + * @param bufferAddr [OUT] Starting address that stores the data to be written. + * The starting address must not be null. + * @param bufferSize [IN] Passed-in buffer size, which must not be 0. The value range is [1,0xffffffff]. + * @param timeOut [IN] Expiry time. The value range is [0,LOS_WAIT_FOREVER](unit: Tick). + * + * @retval #LOS_OK The data is successfully written into the queue. + * @retval #LOS_ERRNO_QUEUE_INVALID The queue handle passed in during queue writing is invalid. + * @retval #LOS_ERRNO_QUEUE_WRITE_PTR_NULL The pointer passed in during queue writing is null. + * @retval #LOS_ERRNO_QUEUE_WRITESIZE_ISZERO The buffer size passed in during queue writing is 0. + * @retval #LOS_ERRNO_QUEUE_WRITE_IN_INTERRUPT The queue cannot be written during an interrupt when the time for + * waiting to processing the queue expires. + * @retval #LOS_ERRNO_QUEUE_NOT_CREATE The queue into which the data is written is not created. + * @retval #LOS_ERRNO_QUEUE_WRITE_SIZE_TOO_BIG The buffer size passed in during queue writing is bigger than + * the queue size. + * @retval #LOS_ERRNO_QUEUE_ISFULL No free node is available during queue writing. + * @retval #LOS_ERRNO_QUEUE_PEND_IN_LOCK The task is forbidden to be blocked on a queue when the task is + * locked. + * @retval #LOS_ERRNO_QUEUE_TIMEOUT The time set for waiting to processing the queue expires. + * @par Dependency: + *
    • los_queue.h: The header file that contains the API declaration.
    + * @see LOS_QueueWrite | LOS_QueueWriteHead + */ +extern UINT32 LOS_QueueWriteHeadCopy(UINT32 queueID, + VOID *bufferAddr, + UINT32 bufferSize, + UINT32 timeOut); + +/** + * @ingroup los_queue + * @brief Delete a queue. + * + * @par Description: + * This API is used to delete a queue. + * @attention + *
      + *
    • This API cannot be used to delete a queue that is not created.
    • + *
    • A synchronous queue fails to be deleted if any tasks are blocked on it, or some queues are being read or + * written.
    • + *
    + * + * @param queueID [IN] Queue ID created by LOS_QueueCreate. The value range is + * [1,LOSCFG_BASE_IPC_QUEUE_LIMIT]. + * + * @retval #LOS_OK The queue is successfully deleted. + * @retval #LOS_ERRNO_QUEUE_NOT_FOUND The queue cannot be found. + * @retval #LOS_ERRNO_QUEUE_NOT_CREATE The queue handle passed in when the queue is being deleted is + * incorrect. + * @retval #LOS_ERRNO_QUEUE_IN_TSKUSE The queue that blocks a task cannot be deleted. + * @retval #LOS_ERRNO_QUEUE_IN_TSKWRITE Queue reading and writing are not synchronous. + * @par Dependency: + *
    • los_queue.h: the header file that contains the API declaration.
    + * @see LOS_QueueCreate | LOS_QueueCreate + */ +extern UINT32 LOS_QueueDelete(UINT32 queueID); + +/** + * @ingroup los_queue + * @brief Obtain queue information. + * + * @par Description: + * This API is used to obtain queue information. + * @attention + *
      + *
    • The specific queue should be created firstly.
    • + *
    + * @param queueID [IN] Queue ID created by LOS_QueueCreate. The value range is + * [1,LOSCFG_BASE_IPC_QUEUE_LIMIT]. + * @param queueInfo [OUT] The queue information to be read must not be null. + * + * @retval #LOS_OK The queue information is successfully obtained. + * @retval #LOS_ERRNO_QUEUE_PTR_NULL The pointer to the queue information to be obtained is null. + * @retval #LOS_ERRNO_QUEUE_INVALID The handle of the queue that is being read is invalid. + * @retval #LOS_ERRNO_QUEUE_NOT_CREATE The queue in which the information to be obtained is stored is + * not created. + * + * @par Dependency: + *
    • los_queue.h: the header file that contains the API declaration.
    + * @see LOS_QueueCreate + */ +extern UINT32 LOS_QueueInfoGet(UINT32 queueID, QUEUE_INFO_S *queueInfo); +extern UINT32 LOS_QueueUsage(VOID); + +#ifdef __cplusplus +#if __cplusplus +} +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +#endif /* _LOS_QUEUE_H */ diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_runstop.h b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_runstop.h new file mode 100644 index 0000000000000000000000000000000000000000..412b4f3e342a3e7c40c5c767e44474789ab1351d --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_runstop.h @@ -0,0 +1,124 @@ +/* ---------------------------------------------------------------------------- + * Copyright (c) Huawei Technologies Co., Ltd. 2018-2019. All rights reserved. + * Description : LiteOS interrupt module implemention. + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * ---------------------------------------------------------------------------- */ + +#ifndef _LOS_RUNSTOP_H +#define _LOS_RUNSTOP_H + +#include "los_config.h" + +#define WAKEUP_BIT_GPIO 0x0001 +#define WAKEUP_BIT_RTC 0x0002 +#define WAKEUP_BIT_SDIO 0x0004 +#define WAKEUP_BIT_STA0 0x0010 +#define WAKEUP_BIT_STA1 0x0020 +#define WAKEUP_BIT_AP0 0x0040 +#define WAKEUP_BIT_ALL 0x0077 + +typedef VOID (*RunstopFn)(VOID); +extern RunstopFn g_runStopHook; +typedef UINT32 (*GetSuspendState)(VOID); +typedef UINT32 (*RunStopDisableWDG)(VOID); +typedef UINT32 (*RunStopResumeWDG)(VOID); +typedef UINT32 (*RunStopSavePeripheral)(VOID); +typedef UINT32 (*RunStopResumePeripheral)(VOID); +typedef UINT32 (*RunStopHwSaveHandler)(VOID); +typedef UINT32 (*RunStopHwResumeHandler)(VOID); +typedef UINT32 (*RunStopSwSaveHandler)(VOID); +typedef UINT32 (*RunStopSwResumeHandler)(VOID); + +typedef VOID (*RunStopSleep)(VOID); + +typedef struct RunStopHandler { + GetSuspendState getState; // get if func can sleep + struct RunStopHandler *next; +} RunStopHandler; + +/* if debug information is used, debug macros need to be defined here */ +#ifdef DEBUG_RUNSTOP_PHASE +typedef struct ThresholdDebugInfo { + UINT32 timerTick; + UINT32 taskTick; + UINT32 taskID; +} ThresholdInfo; +#endif + +typedef struct RunStopInfo { + UINT32 tickThreshold; + UINT32 thresholdFailCnt; + UINT32 voteFailCnt; + UINT32 sleepCnt; + UINT32 timerTick; + UINT32 timerPfnHandler; + UINT32 timerArg; + UINT32 taskTick; + UINT32 taskID; + UINT32 sleepTicks; + UINT32 refuseVoteHandle; + UINT8 voteState; +#ifdef DEBUG_RUNSTOP_PHASE + UINT64 wakeupTick; + UINT64 exitIdleTick; +#endif +} RunStopInfo; + +VOID LOS_RunStopRegisterDisWDG(RunStopDisableWDG disableWDG); +VOID LOS_RunStopRegisterResWDG(RunStopDisableWDG resumeWDG); +VOID LOS_RunStopRegisterSavePeripheral(RunStopSavePeripheral savePeripheral); +VOID LOS_RunStopRegisterResumePeripheral(RunStopResumePeripheral resumePeripheral); +RunStopHandler* LOS_RunStopRegisterVote (GetSuspendState getState); +UINT32 LOS_RunStopUnregisterHandler(RunStopHandler *handler); +VOID LOS_RunStopRegisterDeepSleepFunc(RunStopSleep deepSleepFunc); +VOID LOS_RunStopRegisterLightSleepFunc(RunStopSleep deepSleepFunc); +VOID LOS_RunStopSleep(VOID); +VOID LOS_RunStopRegisterHwHandler(RunStopHwSaveHandler saveHandler, + RunStopHwResumeHandler resumeHandler); +VOID LOS_RunStopRegisterSwHandler(RunStopSwSaveHandler saveHandler, + RunStopSwResumeHandler resumeHandler); +VOID LOS_RunStopSetDeepSleepMaxTime(UINT32 timeMs); +RunStopInfo *LOS_RunStopInfo(VOID); +UINT8 *getRunStopSleepMode(VOID); +VOID setRunStopSleepMode(UINT8 sleepMode); + +/** + * @ingroup los_runstop + * @brief Register the runstop callback. + * + * @par Description: + * This API is used to register the runstop callback. + * @attention + *
      + *
    • None
    • + *
    + * + * @param None + * @retval #los_runstop_fn The runstop callback. + * @par Dependency: + *
    • los_runstop.h: the header file that contains the API declaration.
    + * @see None + */ +extern VOID LOS_RunStopCallBackRegister(RunstopFn cb); + +#endif diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_sem.h b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_sem.h new file mode 100644 index 0000000000000000000000000000000000000000..745b4151699368ef0e61f1444c0a8000d776edc7 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_sem.h @@ -0,0 +1,292 @@ +/* ---------------------------------------------------------------------------- + * Copyright (c) Huawei Technologies Co., Ltd. 2013-2018. All rights reserved. + * Description: semaphore + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * --------------------------------------------------------------------------- */ + +/** + * @defgroup los_sem Semaphore + * @ingroup kernel + */ + +#ifndef _LOS_SEM_H +#define _LOS_SEM_H + +#include "los_err.h" +#include "los_list.h" +#include "los_task.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +/** + * @ingroup los_sem + * Semaphore error code: The memory is insufficient. + * + * Value: 0x02000700 + * + * Solution: Allocate more memory. + */ +#define LOS_ERRNO_SEM_NO_MEMORY LOS_ERRNO_OS_ERROR(LOS_MOD_SEM, 0x00) + +/** + * @ingroup los_sem + * Semaphore error code: Invalid parameter. + * + * Value: 0x02000701 + * + * Solution: Change the passed-in invalid parameter value to a valid value. + */ +#define LOS_ERRNO_SEM_INVALID LOS_ERRNO_OS_ERROR(LOS_MOD_SEM, 0x01) + +/** + * @ingroup los_sem + * Semaphore error code: Null pointer. + * + * Value: 0x02000702 + * + * Solution: Change the passed-in null pointer to a valid non-null pointer. + */ +#define LOS_ERRNO_SEM_PTR_NULL LOS_ERRNO_OS_ERROR(LOS_MOD_SEM, 0x02) + +/** + * @ingroup los_sem + * Semaphore error code: No semaphore control structure is available. + * + * Value: 0x02000703 + * + * Solution: Perform corresponding operations based on the requirements in the code context. + */ +#define LOS_ERRNO_SEM_ALL_BUSY LOS_ERRNO_OS_ERROR(LOS_MOD_SEM, 0x03) + +/** +* @ingroup los_sem +* Semaphore error code: Invalid parameter that specifies the timeout interval. +* +* Value: 0x02000704 +* +* +* Solution: Change the passed-in parameter value to a valid nonzero value. +*/ +#define LOS_ERRNO_SEM_UNAVAILABLE LOS_ERRNO_OS_ERROR(LOS_MOD_SEM, 0x04) + +/** +* @ingroup los_sem +* Semaphore error code: The API is called during an interrupt, which is forbidden. +* +* Value: 0x02000705 +* +* Solution: Do not call the API during an interrupt. +*/ +#define LOS_ERRNO_SEM_PEND_INTERR LOS_ERRNO_OS_ERROR(LOS_MOD_SEM, 0x05) + +/** +* @ingroup los_sem +* Semaphore error code: The task is unable to request a semaphore because task scheduling is locked. +* +* Value: 0x02000706 +* +* Solution: Do not call LOS_SemPend when task scheduling is locked. +*/ +#define LOS_ERRNO_SEM_PEND_IN_LOCK LOS_ERRNO_OS_ERROR(LOS_MOD_SEM, 0x06) + +/** + * @ingroup los_sem + * Semaphore error code: The request for a semaphore times out. + * + * Value: 0x02000707 + * + * Solution: Change the passed-in parameter value to the value within the valid range. + */ +#define LOS_ERRNO_SEM_TIMEOUT LOS_ERRNO_OS_ERROR(LOS_MOD_SEM, 0x07) + +/** + * @ingroup los_sem + * Semaphore error code: The times of semaphore release exceed the maximum times permitted. + * + * Value: 0x02000708 + * + * Solution: Perform corresponding operations based on the requirements in the code context. + */ +#define LOS_ERRNO_SEM_OVERFLOW LOS_ERRNO_OS_ERROR(LOS_MOD_SEM, 0x08) + +/** + * @ingroup los_sem + * Semaphore error code: The queue of the tasks that are waiting on the semaphore control structure is not null. + * + * Value: 0x02000709 + * + * Solution: Delete the semaphore after awaking all tasks that are waiting on the semaphore. + */ +#define LOS_ERRNO_SEM_PENDED LOS_ERRNO_OS_ERROR(LOS_MOD_SEM, 0x09) + +/** + * @ingroup los_sem + * Semaphore error code: LOS_ERRNO_SEM_MAXNUM_ZERO is error. + * + * Value: 0x0200070A + * + * Solution: LOS_ERRNO_SEM_MAXNUM_ZERO should not be error. + */ +#define LOS_ERRNO_SEM_MAXNUM_ZERO LOS_ERRNO_OS_ERROR(LOS_MOD_SEM, 0x0A) + +/** + * @ingroup los_sem + * @brief Create a Counting semaphore. + * + * @par Description: + * This API is used to create a semaphore control structure according to the initial number of available semaphores + * specified by count and return the ID of this semaphore control structure. + * @attention + *
      + *
    • None.
    • + *
    + * + * @param count [IN] Initial number of available semaphores. The value range is [0, OS_SEM_COUNTING_MAX_COUNT]. + * @param semHandle [OUT] ID of the semaphore control structure that is initialized. + * + * @retval #LOS_ERRNO_SEM_PTR_NULL The passed-in semHandle value is NULL. + * @retval #LOS_ERRNO_SEM_OVERFLOW The passed-in count value is greater than the maximum number of available + * semaphores. + * @retval #LOS_ERRNO_SEM_ALL_BUSY No semaphore control structure is available. + * @retval #LOS_OK The semaphore is successfully created. + * @par Dependency: + *
    • los_sem.h: the header file that contains the API declaration.
    + * @see LOS_SemDelete + */ +extern UINT32 LOS_SemCreate(UINT16 count, UINT32 *semHandle); + +/** + * @ingroup los_sem + * @brief Create a binary semaphore. + * + * @par Description: + * This API is used to create a binary semaphore control structure according to the initial number of available + * semaphores specified by count and return the ID of this semaphore control structure. + * @attention + *
      + *
    • None.
    • + *
    + * + * @param count [IN] Initial number of available semaphores. The value range is [0, 1]. + * @param semHandle [OUT] ID of the semaphore control structure that is initialized. + * + * @retval #LOS_ERRNO_SEM_PTR_NULL The passed-in semHandle value is NULL. + * @retval #LOS_ERRNO_SEM_OVERFLOW The passed-in count value is greater than the maximum number of available + * semaphores. + * @retval #LOS_ERRNO_SEM_ALL_BUSY No semaphore control structure is available. + * @retval #LOS_OK The semaphore is successfully created. + * @par Dependency: + *
    • los_sem.h: the header file that contains the API declaration.
    + * @see LOS_SemDelete + */ +extern UINT32 LOS_BinarySemCreate(UINT16 count, UINT32 *semHandle); + +/** + * @ingroup los_sem + * @brief Delete a semaphore. + * + * @par Description: + * This API is used to delete a semaphore control structure that has an ID specified by semHandle. + * @attention + *
      + *
    • The specified sem id must be created first.
    • + *
    + * + * @param semHandle [IN] ID of the semaphore control structure to be deleted. The ID of the semaphore + * control structure is obtained from semaphore creation. + * + * @retval #LOS_ERRNO_SEM_INVALID The passed-in semHandle value is invalid. + * @retval #LOS_ERRNO_SEM_PENDED The queue of the tasks that are waiting on the semaphore control structure is + * not null. + * @retval #LOS_OK The semaphore control structure is successfully deleted. + * @par Dependency: + *
    • los_sem.h: the header file that contains the API declaration.
    + * @see LOS_SemCreate + */ +extern UINT32 LOS_SemDelete(UINT32 semHandle); + +/** + * @ingroup los_sem + * @brief Request a semaphore. + * + * @par Description: + * This API is used to request a semaphore based on the semaphore control structure ID specified by semHandle and the + * parameter that specifies the timeout period. + * @attention + *
      + *
    • The specified sem id must be created first.
    • + *
    + * + * @param semHandle [IN] ID of the semaphore control structure to be requested. The ID of the semaphore control + * structure is obtained from semaphore creation. + * @param timeout [IN] Timeout interval for waiting on the semaphore. The value range is [0, 0xFFFFFFFF]. + * If the value is set to 0, the semaphore is not waited on. If the value is set to 0xFFFFFFFF, + * the semaphore is waited on forever(unit: Tick). + * + * @retval #LOS_ERRNO_SEM_INVALID The passed-in semHandle value is invalid. + * @retval #LOS_ERRNO_SEM_UNAVAILABLE There is no available semaphore resource. + * @retval #LOS_ERRNO_SEM_PEND_INTERR The API is called during an interrupt, which is forbidden. + * @retval #LOS_ERRNO_SEM_PEND_IN_LOCK The task is unable to request a semaphore because task scheduling is locked. + * @retval #LOS_ERRNO_SEM_TIMEOUT The request for the semaphore times out. + * @retval #LOS_OK The semaphore request succeeds. + * @par Dependency: + *
    • los_sem.h: the header file that contains the API declaration.
    + * @see LOS_SemPost | LOS_SemCreate + */ +extern UINT32 LOS_SemPend(UINT32 semHandle, UINT32 timeout); + +/** + * @ingroup los_sem + * @brief Release a semaphore. + * + * @par Description: + * This API is used to release a semaphore that has a semaphore control structure ID specified by semHandle. + * @attention + *
      + *
    • The specified sem id must be created first.
    • + *
    + * + * @param semHandle [IN] ID of the semaphore control structure to be released.The ID of the semaphore control + * structure is obtained from semaphore creation. + * + * @retval #LOS_ERRNO_SEM_INVALID The passed-in semHandle value is invalid. + * @retval #LOS_ERRNO_SEM_OVERFLOW The times of semaphore release exceed the maximum times permitted. + * @retval #LOS_OK The semaphore is successfully released. + * @par Dependency: + *
    • los_sem.h: the header file that contains the API declaration.
    + * @see LOS_SemPend | LOS_SemCreate + */ +extern UINT32 LOS_SemPost(UINT32 semHandle); +extern UINT32 LOS_SemUsage(VOID); + +#ifdef __cplusplus +#if __cplusplus +} +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +#endif /* _LOS_SEM_H */ diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_swtmr.h b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_swtmr.h new file mode 100644 index 0000000000000000000000000000000000000000..947d90d8ce12aba33b6051b83220f4e4bbe04278 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_swtmr.h @@ -0,0 +1,435 @@ +/* --------------------------------------------------------------------------- + * Copyright (c) Huawei Technologies Co., Ltd. 2013-2018. All rights reserved. + * Description: Software Timer Manager + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * --------------------------------------------------------------------------- */ + +/** + * @defgroup los_swtmr Software timer + * @ingroup kernel + */ + +#ifndef _LOS_SWTMR_H +#define _LOS_SWTMR_H + +#include "los_task.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif /* __cplusplus */ +#endif /* __cplusplus */ + + +/** + * @ingroup los_swtmr + * Software timer error code: The timeout handling function is NULL. + * + * Value: 0x02000300 + * + * Solution: Define the timeout handling function. + */ +#define LOS_ERRNO_SWTMR_PTR_NULL LOS_ERRNO_OS_ERROR(LOS_MOD_SWTMR, 0x00) + +/** + * @ingroup los_swtmr + * Software timer error code: The expiration time is 0. + * + * Value: 0x02000301 + * + * Solution: Re-define the expiration time. + */ +#define LOS_ERRNO_SWTMR_INTERVAL_NOT_SUITED LOS_ERRNO_OS_ERROR(LOS_MOD_SWTMR, 0x01) + +/** + * @ingroup los_swtmr + * Software timer error code: Invalid software timer mode. + * + * Value: 0x02000302 + * + * Solution: Check the mode value. The value range is [0,3]. + */ +#define LOS_ERRNO_SWTMR_MODE_INVALID LOS_ERRNO_OS_ERROR(LOS_MOD_SWTMR, 0x02) + +/** + * @ingroup los_swtmr + * Software timer error code: The passed-in software timer ID is NULL. + * + * Value: 0x02000303 + * + * Solution: Define the software timer ID before passing it in. + */ +#define LOS_ERRNO_SWTMR_RET_PTR_NULL LOS_ERRNO_OS_ERROR(LOS_MOD_SWTMR, 0x03) + +/** + * @ingroup los_swtmr + * Software timer error code: The number of software timers exceeds the configured permitted maximum number. + * + * Value: 0x02000304 + * + * Solution: Re-configure the permitted maximum number of software timers, or wait for a software timer to become + * available. + */ +#define LOS_ERRNO_SWTMR_MAXSIZE LOS_ERRNO_OS_ERROR(LOS_MOD_SWTMR, 0x04) + +/** + * @ingroup los_swtmr + * Software timer error code: Invalid software timer ID. + * + * Value: 0x02000305 + * + * Solution: Pass in a valid software timer ID. + */ +#define LOS_ERRNO_SWTMR_ID_INVALID LOS_ERRNO_OS_ERROR(LOS_MOD_SWTMR, 0x05) + +/** + * @ingroup los_swtmr + * Software timer error code: The software timer is not created. + * + * Value: 0x02000306 + * + * Solution: Create a software timer. + */ +#define LOS_ERRNO_SWTMR_NOT_CREATED LOS_ERRNO_OS_ERROR(LOS_MOD_SWTMR, 0x06) + +/** + * @ingroup los_swtmr + * Software timer error code: Insufficient memory for software timer linked list creation. + * + * Value: 0x02000307 + * + * Solution: Allocate bigger memory partition to software timer linked list creation. + */ +#define LOS_ERRNO_SWTMR_NO_MEMORY LOS_ERRNO_OS_ERROR(LOS_MOD_SWTMR, 0x07) + +/** + * @ingroup los_swtmr + * Software timer error code: Invalid configured number of software timers. + * + * Value: 0x02000308 + * + * Solution: Re-configure the number of software timers. + */ +#define LOS_ERRNO_SWTMR_MAXSIZE_INVALID LOS_ERRNO_OS_ERROR(LOS_MOD_SWTMR, 0x08) + +/** + * @ingroup los_swtmr + * Software timer error code: The software timer is being used during an interrupt. + * + * Value: 0x02000309 + * + * Solution: Change the source code and do not use the software timer during an interrupt. + */ +#define LOS_ERRNO_SWTMR_HWI_ACTIVE LOS_ERRNO_OS_ERROR(LOS_MOD_SWTMR, 0x09) + +/** + * @ingroup los_swtmr + * Software timer error code: Insufficient memory allocated by membox. + * + * Value: 0x0200030a + * + * Solution: Expand the memory allocated by membox. + */ +#define LOS_ERRNO_SWTMR_HANDLER_POOL_NO_MEM LOS_ERRNO_OS_ERROR(LOS_MOD_SWTMR, 0x0a) + +/** + * @ingroup los_swtmr + * Software timer error code: The software timer queue fails to be created. + * + * Value: 0x0200030b + * + * Solution: Check whether more memory can be allocated to the queue to be created. + */ +#define LOS_ERRNO_SWTMR_QUEUE_CREATE_FAILED LOS_ERRNO_OS_ERROR(LOS_MOD_SWTMR, 0x0b) + +/** + * @ingroup los_swtmr + * Software timer error code: The software timer task fails to be created. + * + * Value: 0x0200030c + * + * Solution: Check whether the memory is sufficient and re-create the task. + */ +#define LOS_ERRNO_SWTMR_TASK_CREATE_FAILED LOS_ERRNO_OS_ERROR(LOS_MOD_SWTMR, 0x0c) + +/** + * @ingroup los_swtmr + * Software timer error code: The software timer is not started. + * + * Value: 0x0200030d + * + * Solution: Start the software timer. + */ +#define LOS_ERRNO_SWTMR_NOT_STARTED LOS_ERRNO_OS_ERROR(LOS_MOD_SWTMR, 0x0d) + +/** + * @ingroup los_swtmr + * Software timer error code: Invalid software timer state. + * + * Value: 0x0200030e + * + * Solution: Check the software timer state. + */ +#define LOS_ERRNO_SWTMR_STATUS_INVALID LOS_ERRNO_OS_ERROR(LOS_MOD_SWTMR, 0x0e) + +/** + * @ingroup los_swtmr + * This error code is not in use temporarily. + */ +#define LOS_ERRNO_SWTMR_SORTLIST_NULL LOS_ERRNO_OS_ERROR(LOS_MOD_SWTMR, 0x0f) + +/** + * @ingroup los_swtmr + * Software timer error code: The passed-in number of remaining Ticks configured on the software timer is NULL. + * + * Value: 0x02000310 + * + * Solution: Define a variable of the number of remaining Ticks before passing in the number of remaining Ticks. + */ +#define LOS_ERRNO_SWTMR_TICK_PTR_NULL LOS_ERRNO_OS_ERROR(LOS_MOD_SWTMR, 0x10) + +/** + * @ingroup los_swtmr + * Software timer mode + */ +enum EnSwTmrType { + LOS_SWTMR_MODE_ONCE, /* One-off software timer */ + LOS_SWTMR_MODE_PERIOD, /* Periodic software timer */ + LOS_SWTMR_MODE_NO_SELFDELETE, /* One-off software timer, but not self-delete */ + LOS_SWTMR_MODE_OPP, /* After the one-off timer finishes timing, + the periodic software timer is enabled. + This mode is not supported temporarily. */ +}; + +/** +* @ingroup los_swtmr +* @brief Define the type of a callback function that handles software timer timeout. +* +* @par Description: +* This API is used to define the type of a callback function that handles software timer timeout, so that it can be +* called when software timer timeout. +* +* @attention +*
      +*
    • None.
    • +*
    +* +* @param para [IN] the parameter of the callback function that handles software timer timeout. +* +* @retval None. +* @par Dependency: +*
    • los_swtmr.h: the header file that contains the API declaration.
    +* @see None. +*/ +typedef VOID (*SWTMR_PROC_FUNC)(UINT32 para); + +/** + * @ingroup los_swtmr + * Software timer control structure + */ +typedef struct tagSwTmrCtrl { + struct tagSwTmrCtrl *pstNext; /* Pointer to the next software timer */ + UINT8 ucState; /* Software timer state */ + UINT8 ucMode; /* Software timer mode */ + UINT16 usTimerID; /* Software timer ID */ + UINT32 uwCount; /* Times that a software timer works */ + UINT32 uwInterval; /* Timeout interval of a periodic software timer */ + UINT32 uwArg; /* Parameter passed in when the callback function + that handles software timer timeout is called */ + SWTMR_PROC_FUNC pfnHandler; /* Callback function that handles software timer timeout */ +} SWTMR_CTRL_S; + + +/** + * @ingroup los_swtmr + * @brief Start a software timer. + * + * @par Description: + * This API is used to start a software timer that has a specified ID. + * @attention + *
      + *
    • The specific timer must be created first
    • + *
    + * + * @param swtmrID [IN] Software timer ID created by LOS_SwtmrCreate. The value of ID should be in + * [0, LOSCFG_BASE_CORE_SWTMR_LIMIT - 1]. + * + * @retval #LOS_ERRNO_SWTMR_ID_INVALID Invalid software timer ID. + * @retval #LOS_ERRNO_SWTMR_NOT_CREATED The software timer is not created. + * @retval #LOS_ERRNO_SWTMR_STATUS_INVALID Invalid software timer state. + * @retval #LOS_OK The software timer is successfully started. + * @par Dependency: + *
    • los_swtmr.h: the header file that contains the API declaration.
    + * @see LOS_SwtmrStop | LOS_SwtmrCreate + */ +extern UINT32 LOS_SwtmrStart(UINT16 swtmrID); + +/** + * @ingroup los_swtmr + * @brief Stop a software timer. + * + * @par Description: + * This API is used to stop a software timer that has a specified ID. + * @attention + *
      + *
    • The specific timer should be created and started firstly.
    • + *
    + * + * @param swtmrID [IN] Software timer ID created by LOS_SwtmrCreate. The value of ID should be in + * [0, LOSCFG_BASE_CORE_SWTMR_LIMIT - 1]. + * + * @retval #LOS_ERRNO_SWTMR_ID_INVALID Invalid software timer ID. + * @retval #LOS_ERRNO_SWTMR_NOT_CREATED The software timer is not created. + * @retval #LOS_ERRNO_SWTMR_NOT_STARTED The software timer is not started. + * @retval #LOS_ERRNO_SWTMR_STATUS_INVALID Invalid software timer state. + * @retval #LOS_OK The software timer is successfully stopped. + * @par Dependency: + *
    • los_swtmr.h: the header file that contains the API declaration.
    + * @see LOS_SwtmrStart | LOS_SwtmrCreate + */ +extern UINT32 LOS_SwtmrStop(UINT16 swtmrID); + +/** + * @ingroup los_swtmr + * @brief Obtain the number of remaining Ticks configured on a software timer. + * + * @par Description: + * This API is used to obtain the number of remaining Ticks configured on the software timer of which the ID is + * specified by usSwTmrID. + * @attention + *
      + *
    • The specific timer should be created and started successfully, error happends otherwise.
    • + *
    + * + * @param swtmrID [IN] Software timer ID created by LOS_SwtmrCreate. The value of ID should be in + * [0, LOSCFG_BASE_CORE_SWTMR_LIMIT - 1]. + * @param tick [OUT] Number of remaining Ticks configured on the software timer. + * + * @retval #LOS_ERRNO_SWTMR_ID_INVALID Invalid software timer ID. + * @retval #LOS_ERRNO_SWTMR_NOT_CREATED The software timer is not created. + * @retval #LOS_ERRNO_SWTMR_NOT_STARTED The software timer is not started. + * @retval #LOS_ERRNO_SWTMR_STATUS_INVALID Invalid software timer state. + * @retval #LOS_OK The number of remaining Ticks is successfully obtained. + * @par Dependency: + *
    • los_swtmr.h: the header file that contains the API declaration.
    + * @see LOS_SwtmrCreate + */ +extern UINT32 LOS_SwtmrTimeGet(UINT16 swtmrID, UINT32 *tick); + +/** + * @ingroup los_swtmr + * @brief Create a software timer. + * + * @par Description: + * This API is used to create a software timer that has specified timing duration, timeout handling function, + * and trigger mode, and to return a handle by which the software timer can be referenced. + * @attention + *
      + *
    • Do not use the delay interface in the callback function that handles software timer timeout.
    • + *
    • Threre are LOSCFG_BASE_CORE_SWTMR_LIMIT timers available, change it's value when necessory.
    • + *
    + * + * @param interval [IN] Timing duration of the software timer to be created (unit: ms). + * @param mode [IN] Software timer mode. Pass in one of the modes specified by EnSwTmrType. There are three + * types of modes, one-off, periodic, and continuously periodic after one-off, of which the + * third mode is not supported temporarily. + * @param handler [IN] Callback function that handles software timer timeout. + * @param swtmrID [OUT] Software timer ID created by LOS_SwtmrCreate. + * @param arg [IN] Parameter passed in when the callback function that handles software timer timeout is + * called. + * + * @retval #LOS_ERRNO_SWTMR_INTERVAL_NOT_SUITED The software timer timeout interval is 0. + * @retval #LOS_ERRNO_SWTMR_MODE_INVALID Invalid software timer mode. + * @retval #LOS_ERRNO_SWTMR_PTR_NULL The callback function that handles software timer timeout is NULL. + * @retval #LOS_ERRNO_SWTMR_RET_PTR_NULL The passed-in software timer ID is NULL. + * @retval #LOS_ERRNO_SWTMR_MAXSIZE The number of software timers exceeds the configured permitted + * maximum number. + * @retval #LOS_OK The software timer is successfully created. + * @par Dependency: + *
    • los_swtmr.h: the header file that contains the API declaration.
    + * @see LOS_SwtmrDelete + */ +extern UINT32 LOS_SwtmrCreate(UINT32 interval, UINT8 mode, SWTMR_PROC_FUNC handler, UINT16 *swtmrID, UINT32 arg); +/** + * @ingroup los_swtmr + * @brief Modify a software timer. + * + * @par Description: + * This API is used to Modify the timing duration, timeout handling function, and trigger mode of a created timer. + * @attention + *
      + *
    • Do not use the delay interface in the callback function that handles software timer timeout.
    • + *
    + * + * @param swtmrID [IN] Software timer ID created by LOS_SwtmrCreate. + * @param interval [IN] Timing duration of the software timer to be created (unit: ms). + * @param mode [IN] Software timer mode. Pass in one of the modes specified by EnSwTmrType. + There are three types of modes, one-off, periodic, and continuously periodic after one-off, + of which the third mode is not supported temporarily. + * @param handler [IN] Callback function that handles software timer timeout. + * @param arg [IN] Parameter passed in when the callback function that handles software timer timeout is called. + * + * @retval #LOS_ERRNO_SWTMR_INTERVAL_NOT_SUITED The software timer timeout interval is 0. + * @retval #LOS_ERRNO_SWTMR_MODE_INVALID Invalid software timer mode. + * @retval #LOS_ERRNO_SWTMR_ID_INVALID Invalid software timer ID. + * @retval #LOS_ERRNO_SWTMR_NOT_CREATED The software timer is not created. + * @retval #LOS_ERRNO_SWTMR_STATUS_INVALID Invalid software timer state. + * @retval #LOS_OK The software timer is successfully created. + * @par Dependency: + *
    • los_swtmr.h: the header file that contains the API declaration.
    + * @see LOS_SwtmrDelete + */ +extern UINT32 LOS_SwtmrModify(UINT16 swtmrID, UINT32 interval, UINT8 mode, SWTMR_PROC_FUNC handler, UINT32 arg); + +/** + * @ingroup los_swtmr + * @brief Delete a software timer. + * + * @par Description: + * This API is used to delete a software timer. + * @attention + *
      + *
    • The specific timer should be created and then stopped firstly.
    • + *
    + * + * @param swtmrID [IN] Software timer ID created by LOS_SwtmrCreate. The value of ID should be in + * [0, LOSCFG_BASE_CORE_SWTMR_LIMIT - 1]. + * + * @retval #LOS_ERRNO_SWTMR_ID_INVALID Invalid software timer ID. + * @retval #LOS_ERRNO_SWTMR_NOT_CREATED The software timer is not created. + * @retval #LOS_ERRNO_SWTMR_STATUS_INVALID Invalid software timer state. + * @retval #LOS_OK The software timer is successfully deleted. + * @par Dependency: + *
    • los_swtmr.h: the header file that contains the API declaration.
    + * @see LOS_SwtmrCreate + */ +extern UINT32 LOS_SwtmrDelete(UINT16 swtmrID); +extern UINT32 LOS_SwtmrUsage(VOID); + +#ifdef __cplusplus +#if __cplusplus +} +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +#endif /* _LOS_SWTMR_H */ diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_sys.h b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_sys.h new file mode 100644 index 0000000000000000000000000000000000000000..8308920326dbdfcba8edb6165349e18241635a32 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_sys.h @@ -0,0 +1,195 @@ +/* ---------------------------------------------------------------------------- + * Copyright (c) Huawei Technologies Co., Ltd. 2015-2018. All rights reserved. + * Description: System time + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * --------------------------------------------------------------------------- */ + +/** + * @defgroup los_sys System time + * @ingroup kernel + */ + +#ifndef _LOS_SYS_H +#define _LOS_SYS_H + +#include "los_base.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +/** + * @ingroup los_sys + * System time basic function error code: Null pointer. + * + * Value: 0x02000010 + * + * Solution: Check whether the input parameter is null. + */ +#define LOS_ERRNO_SYS_PTR_NULL LOS_ERRNO_OS_ERROR(LOS_MOD_SYS, 0x10) + +/** + * @ingroup los_sys + * System time basic function error code: Invalid system clock configuration. + * + * Value: 0x02000011 + * + * Solution: Configure a valid system clock in los_config.h. + */ +#define LOS_ERRNO_SYS_CLOCK_INVALID LOS_ERRNO_OS_ERROR(LOS_MOD_SYS, 0x11) + +/** + * @ingroup los_sys + * System time basic function error code: This error code is not in use temporarily. + * + * Value: 0x02000012 + * + * Solution: None. + */ +#define LOS_ERRNO_SYS_MAXNUMOFCORES_IS_INVALID LOS_ERRNO_OS_ERROR(LOS_MOD_SYS, 0x12) + +/** + * @ingroup los_sys + * System time error code: This error code is not in use temporarily. + * + * Value: 0x02000013 + * + * Solution: None. + */ +#define LOS_ERRNO_SYS_PERIERRCOREID_IS_INVALID LOS_ERRNO_OS_ERROR(LOS_MOD_SYS, 0x13) + +/** + * @ingroup los_sys + * System time error code: This error code is not in use temporarily. + * + * Value: 0x02000014 + * + * Solution: None. + */ +#define LOS_ERRNO_SYS_HOOK_IS_FULL LOS_ERRNO_OS_ERROR(LOS_MOD_SYS, 0x14) + +/** + * @ingroup los_typedef + * system time structure. + */ +typedef struct tagSysTime { + UINT16 uwYear; /**< value 1970 ~ 2038 or 1970 ~ 2100 */ + UINT8 ucMonth; /**< value 1 - 12 */ + UINT8 ucDay; /**< value 1 - 31 */ + UINT8 ucHour; /**< value 0 - 23 */ + UINT8 ucMinute; /**< value 0 - 59 */ + UINT8 ucSecond; /**< value 0 - 59 */ + UINT8 ucWeek; /**< value 0 - 6 */ +} SYS_TIME_S; + +/** + * @ingroup los_sys + * @brief Obtain the number of Ticks. + * + * @par Description: + * This API is used to obtain the number of Ticks. + * @attention + *
      + *
    • None
    • + *
    + * + * @param None + * + * @retval UINT64 The number of Ticks. + * @par Dependency: + *
    • los_sys.h: the header file that contains the API declaration.
    + * @see None + */ +extern UINT64 LOS_TickCountGet(VOID); + +/** + * @ingroup los_sys + * @brief Obtain the number of cycles in one second. + * + * @par Description: + * This API is used to obtain the number of cycles in one second. + * @attention + *
      + *
    • None
    • + *
    + * + * @param None + * + * @retval UINT32 Number of cycles obtained in one second. + * @par Dependency: + *
    • los_sys.h: the header file that contains the API declaration.
    + * @see None + */ +extern UINT32 LOS_CyclePerTickGet(VOID); + +/** + * @ingroup los_sys + * @brief Convert Ticks to milliseconds. + * + * @par Description: + * This API is used to convert Ticks to milliseconds. + * @attention + *
      + *
    • The number of milliseconds obtained through the conversion is 32-bit.
    • + *
    + * + * @param ticks [IN] Number of Ticks. The value range is (0,OS_SYS_CLOCK). + * + * @retval UINT32 Number of milliseconds obtained through the conversion. Ticks are successfully converted to + * milliseconds. + * @par Dependency: + *
    • los_sys.h: the header file that contains the API declaration.
    + * @see LOS_MS2Tick + */ +extern UINT32 LOS_Tick2MS(UINT32 ticks); + +/** + * @ingroup los_sys + * @brief Convert milliseconds to Ticks. + * + * @par Description: + * This API is used to convert milliseconds to Ticks. + * @attention + *
      + *
    • If the parameter passed in is equal to 0xFFFFFFFF, the retval is 0xFFFFFFFF. Pay attention to the value to be + * converted because data possibly overflows.
    • + *
    + * + * @param millisec [IN] Number of milliseconds. + * + * @retval UINT32 Number of Ticks obtained through the conversion. + * @par Dependency: + *
    • los_sys.h: the header file that contains the API declaration.
    + * @see LOS_Tick2MS + */ +extern UINT32 LOS_MS2Tick(UINT32 millisec); + +#ifdef __cplusplus +#if __cplusplus +} +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +#endif /* _LOS_SYS_H */ diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_tables.h b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_tables.h new file mode 100644 index 0000000000000000000000000000000000000000..995e00012a47006a1c81202f8979a789a39aec5b --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_tables.h @@ -0,0 +1,41 @@ +/* ---------------------------------------------------------------------------- + * Copyright (c) Huawei Technologies Co., Ltd. 2013-2019. All rights reserved. + * Description: Tables + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * --------------------------------------------------------------------------- */ + +#ifndef _LOS_TABLES_H +#define _LOS_TABLES_H + +#include "los_typedef.h" + +#define __string(x) #x +#define __xstring(x) __string(x) + +#ifndef LOS_HAL_TABLE_ENTRY +#define LOS_HAL_TABLE_ENTRY(_name) \ + LOSBLD_ATTRIB_SECTION(".liteos.table." __xstring(_name) ".data") \ + LOSBLD_ATTRIB_USED +#endif + +#endif /* _LOS_TABLES_H */ diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_task.h b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_task.h new file mode 100644 index 0000000000000000000000000000000000000000..c01c520dacf24624c346fab9215e45dd3a44ff99 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_task.h @@ -0,0 +1,975 @@ +/* ---------------------------------------------------------------------------- + * Copyright (c) Huawei Technologies Co., Ltd. 2013-2015. All rights reserved. + * Description: LiteOS Task Module Implementation + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * --------------------------------------------------------------------------- */ + +/** + * @defgroup los_task Task + * @ingroup kernel + */ + +#ifndef _LOS_TASK_H +#define _LOS_TASK_H + +#include "los_base.h" +#include "los_list.h" +#include "los_sys.h" +#include "los_tick.h" +#include "los_event.h" +#include "los_err.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +/** + * @ingroup los_task + * Task error code: Insufficient memory for task creation. + * + * Value: 0x03000200 + * + * Solution: Allocate bigger memory partition to task creation. + */ +#define LOS_ERRNO_TSK_NO_MEMORY LOS_ERRNO_OS_FATAL(LOS_MOD_TSK, 0x00) + +/** + * @ingroup los_task + * Task error code: Null parameter. + * + * Value: 0x02000201 + * + * Solution: Check the parameter. + */ +#define LOS_ERRNO_TSK_PTR_NULL LOS_ERRNO_OS_ERROR(LOS_MOD_TSK, 0x01) + +/** + * @ingroup los_task + * Task error code: The task stack is not aligned. + * + * Value: 0x02000202 + * + * Solution: Align the task stack. + */ +#define LOS_ERRNO_TSK_STKSZ_NOT_ALIGN LOS_ERRNO_OS_ERROR(LOS_MOD_TSK, 0x02) + +/** + * @ingroup los_task + * Task error code: Incorrect task priority. + * + * Value: 0x02000203 + * + * Solution: Re-configure the task priority by referring to the priority range. + */ +#define LOS_ERRNO_TSK_PRIOR_ERROR LOS_ERRNO_OS_ERROR(LOS_MOD_TSK, 0x03) + +/** + * @ingroup los_task + * Task error code: The task entrance is NULL. + * + * Value: 0x02000204 + * + * Solution: Define the task entrance function. + */ +#define LOS_ERRNO_TSK_ENTRY_NULL LOS_ERRNO_OS_ERROR(LOS_MOD_TSK, 0x04) + +/** + * @ingroup los_task + * Task error code: The task name is NULL. + * + * Value: 0x02000205 + * + * Solution: Set the task name. + */ +#define LOS_ERRNO_TSK_NAME_EMPTY LOS_ERRNO_OS_ERROR(LOS_MOD_TSK, 0x05) + +/** + * @ingroup los_task + * Task error code: The task stack size is too small. + * + * Value: 0x02000206 + * + * Solution: Expand the task stack. + */ +#define LOS_ERRNO_TSK_STKSZ_TOO_SMALL LOS_ERRNO_OS_ERROR(LOS_MOD_TSK, 0x06) + +/** + * @ingroup los_task + * Task error code: Invalid task ID. + * + * Value: 0x02000207 + * + * Solution: Check the task ID. + */ +#define LOS_ERRNO_TSK_ID_INVALID LOS_ERRNO_OS_ERROR(LOS_MOD_TSK, 0x07) + +/** + * @ingroup los_task + * Task error code: The task is already suspended. + * + * Value: 0x02000208 + * + * Solution: Suspend the task after it is resumed. + */ +#define LOS_ERRNO_TSK_ALREADY_SUSPENDED LOS_ERRNO_OS_ERROR(LOS_MOD_TSK, 0x08) + +/** + * @ingroup los_task + * Task error code: The task is not suspended. + * + * Value: 0x02000209 + * + * Solution: Suspend the task. + */ +#define LOS_ERRNO_TSK_NOT_SUSPENDED LOS_ERRNO_OS_ERROR(LOS_MOD_TSK, 0x09) + +/** + * @ingroup los_task + * Task error code: The task is not created. + * + * Value: 0x0200020a + * + * Solution: Create the task. + */ +#define LOS_ERRNO_TSK_NOT_CREATED LOS_ERRNO_OS_ERROR(LOS_MOD_TSK, 0x0a) + +/** + * @ingroup los_task + * Task error code: The task message is nonzero. + * + * Value: 0x0200020c + * + * Solution: This error code is not in use temporarily. + */ +#define LOS_ERRNO_TSK_MSG_NONZERO LOS_ERRNO_OS_ERROR(LOS_MOD_TSK, 0x0c) + +/** + * @ingroup los_task + * Task error code: The task delay occurs during an interrupt. + * + * Value: 0x0300020d + * + * Solution: Perform this operation after exiting from the interrupt. + */ +#define LOS_ERRNO_TSK_DELAY_IN_INT LOS_ERRNO_OS_FATAL(LOS_MOD_TSK, 0x0d) + +/** + * @ingroup los_task + * Task error code: The task delay occurs when the task is locked. + * + * Value: 0x0200020e + * + * Solution: Perform this operation after unlocking the task. + */ +#define LOS_ERRNO_TSK_DELAY_IN_LOCK LOS_ERRNO_OS_ERROR(LOS_MOD_TSK, 0x0e) + +/** + * @ingroup los_task + * Task error code: The task that is being scheduled is invalid. + * + * Value: 0x0200020f + * + * Solution: Check the task. + */ +#define LOS_ERRNO_TSK_YIELD_INVALID_TASK LOS_ERRNO_OS_ERROR(LOS_MOD_TSK, 0x0f) + +/** + * @ingroup los_task + * Task error code: Only one task or no task is available for scheduling. + * + * Value: 0x02000210 + * + * Solution: Increase the number of tasks. + */ +#define LOS_ERRNO_TSK_YIELD_NOT_ENOUGH_TASK LOS_ERRNO_OS_ERROR(LOS_MOD_TSK, 0x10) + +/** + * @ingroup los_task + * Task error code: No free task control block is available. + * + * Value: 0x02000211 + * + * Solution: Increase the number of task control blocks. + */ +#define LOS_ERRNO_TSK_TCB_UNAVAILABLE LOS_ERRNO_OS_ERROR(LOS_MOD_TSK, 0x11) + +/** + * @ingroup los_task + * Task error code: The task hook function is not matchable. + * + * Value: 0x02000212 + * + * Solution: This error code is not in use temporarily. + */ +#define LOS_ERRNO_TSK_HOOK_NOT_MATCH LOS_ERRNO_OS_ERROR(LOS_MOD_TSK, 0x12) + +/** + * @ingroup los_task + * Task error code: The number of task hook functions exceeds the permitted upper limit. + * + * Value: 0x02000213 + * + * Solution: This error code is not in use temporarily. + */ +#define LOS_ERRNO_TSK_HOOK_IS_FULL LOS_ERRNO_OS_ERROR(LOS_MOD_TSK, 0x13) + +/** + * @ingroup los_task + * Task error code: The operation is performed on the idle task. + * + * Value: 0x02000214 + * + * Solution: Check the task ID and do not operate on the idle task. + */ +#define LOS_ERRNO_TSK_OPERATE_IDLE LOS_ERRNO_OS_ERROR(LOS_MOD_TSK, 0x14) + +/** + * @ingroup los_task + * Task error code: The task that is being suspended is locked. + * + * Value: 0x03000215 + * + * Solution: Suspend the task after unlocking the task. + */ +#define LOS_ERRNO_TSK_SUSPEND_LOCKED LOS_ERRNO_OS_FATAL(LOS_MOD_TSK, 0x15) + +/** + * @ingroup los_task + * Task error code: The task stack fails to be freed. + * + * Value: 0x02000217 + * + * Solution: This error code is not in use temporarily. + */ +#define LOS_ERRNO_TSK_FREE_STACK_FAILED LOS_ERRNO_OS_ERROR(LOS_MOD_TSK, 0x17) + +/** + * @ingroup los_task + * Task error code: The task stack area is too small. + * + * Value: 0x02000218 + * + * Solution: This error code is not in use temporarily. + */ +#define LOS_ERRNO_TSK_STKAREA_TOO_SMALL LOS_ERRNO_OS_ERROR(LOS_MOD_TSK, 0x18) + +/** + * @ingroup los_task + * Task error code: The task fails to be activated. + * + * Value: 0x03000219 + * + * Solution: Perform task switching after creating an idle task. + */ +#define LOS_ERRNO_TSK_ACTIVE_FAILED LOS_ERRNO_OS_FATAL(LOS_MOD_TSK, 0x19) + +/** + * @ingroup los_task + * Task error code: Too many task configuration items. + * + * Value: 0x0200021a + * + * Solution: This error code is not in use temporarily. + */ +#define LOS_ERRNO_TSK_CONFIG_TOO_MANY LOS_ERRNO_OS_ERROR(LOS_MOD_TSK, 0x1a) + +/** + * @ingroup los_task + * Task error code: + * + * Value: 0x0200021b + * + * Solution: This error code is not in use temporarily. + */ +#define LOS_ERRNO_TSK_CP_SAVE_AREA_NOT_ALIGN LOS_ERRNO_OS_ERROR(LOS_MOD_TSK, 0x1b) + +/** + * @ingroup los_task + * Task error code: + * + * Value: 0x0200021d + * + * Solution: This error code is not in use temporarily. + */ +#define LOS_ERRNO_TSK_MSG_Q_TOO_MANY LOS_ERRNO_OS_ERROR(LOS_MOD_TSK, 0x1d) + +/** + * @ingroup los_task + * Task error code: + * + * Value: 0x0200021e + * + * Solution: This error code is not in use temporarily. + */ +#define LOS_ERRNO_TSK_CP_SAVE_AREA_NULL LOS_ERRNO_OS_ERROR(LOS_MOD_TSK, 0x1e) + +/** + * @ingroup los_task + * Task error code: + * + * Value: 0x0200021f + * + * Solution: This error code is not in use temporarily. + */ +#define LOS_ERRNO_TSK_SELF_DELETE_ERR LOS_ERRNO_OS_ERROR(LOS_MOD_TSK, 0x1f) + +/** + * @ingroup los_task + * Task error code: The task stack size is too large. + * + * Value: 0x02000220 + * + * Solution: shrink the task stack size parameter. + */ +#define LOS_ERRNO_TSK_STKSZ_TOO_LARGE LOS_ERRNO_OS_ERROR(LOS_MOD_TSK, 0x20) + +/** + * @ingroup los_task + * Task error code: Suspending software timer task is not allowed. + * + * Value: 0x02000221 + * + * Solution: Check the task ID and do not suspend software timer task. + */ +#define LOS_ERRNO_TSK_SUSPEND_SWTMR_NOT_ALLOWED LOS_ERRNO_OS_ERROR(LOS_MOD_TSK, 0x21) + +/** + * @ingroup los_task + * Task error code: The operation is performed on the software timer task. + * + * Value: 0x02000222 + * + * Solution: Check the task ID and do not operate on the software timer task. + */ +#define LOS_ERRNO_TSK_OPERATE_SWTMR LOS_ERRNO_OS_ERROR(LOS_MOD_TSK, 0x22) + +/** + * @ingroup los_task + * Task error code: The task stack pointer is error. + * + * Value: 0x02000223 + * + * Solution: Check the task stack pointer. + */ +#define LOS_ERRNO_TSK_STACK_POINTER_ERROR LOS_ERRNO_OS_ERROR(LOS_MOD_TSK, 0x23) + +/** + * @ingroup los_task + * Define the type of the task switching hook function. + * + */ +typedef VOID (*TSKSWITCHHOOK)(VOID); + +/** + * @ingroup los_task + * User task switching hook function. + * + */ +extern TSKSWITCHHOOK g_pfnUsrTskSwitchHook; + +/** +* @ingroup los_task +* @brief Define the type of a task entrance function. +* +* @par Description: +* This API is used to define the type of a task entrance function and call it after a task is created and triggered. +* @attention None. +* +* @param param1 [IN] Type #UINT32 The first parameter passed to the task handling function. +* @param param2 [IN] Type #UINT32 The second parameter passed to the task handling function. +* @param param3 [IN] Type #UINT32 The third parameter passed to the task handling function. +* @param param4 [IN] Type #UINT32 The fourth parameter passed to the task handling function. +* +* @retval None. +* @par Dependency: +*
    • los_task.h: the header file that contains the API declaration.
    +* @see +*/ +typedef VOID *(*TSK_ENTRY_FUNC)(UINT32 param1, UINT32 param2, UINT32 param3, UINT32 param4); +#define LOS_TASK_STATUS_DETACHED 0x0100 + +#define LOS_TASK_ARG_NUM 4 +/** + * @ingroup los_task + * Define the structure of the parameters used for task creation. + * + * Information of specified parameters passed in during task creation. + */ +typedef struct tagTskInitParam { + TSK_ENTRY_FUNC pfnTaskEntry; /**< Task entrance function */ + UINT16 usTaskPrio; /**< Task priority */ + UINT32 auwArgs[LOS_TASK_ARG_NUM]; /**< Task parameters */ + UINT32 uwStackSize; /**< Task stack size */ + CHAR *pcName; /**< Task name */ + UINT32 uwResved; /**< Reserved */ +} TSK_INIT_PARAM_S; + +/** + * @ingroup los_task + * Task name length + * + */ +#define LOS_TASK_NAMELEN 32 + +/** + * @ingroup los_task + * Task information structure. + * + */ +typedef struct tagTskInfo { + CHAR acName[LOS_TASK_NAMELEN]; /**< Task entrance function */ + UINT32 uwTaskID; /**< Task ID */ + UINT16 usTaskStatus; /**< Task status */ + UINT16 usTaskPrio; /**< Task priority */ + VOID *pTaskSem; /**< Semaphore pointer */ + VOID *pTaskMux; /**< Mutex pointer */ + EVENT_CB_S uwEvent; /**< Event */ + UINT32 uwEventMask; /**< Event mask */ + UINT32 uwStackSize; /**< Task stack size */ + UINT32 uwTopOfStack; /**< Task stack top */ + UINT32 uwBottomOfStack; /**< Task stack bottom */ + UINT32 mstatus; /**< Task current mstatus */ + UINT32 mepc; /**< Task current mepc */ + UINT32 tp; /**< Task current tp */ + UINT32 ra; /**< Task current ra */ + UINT32 uwSP; /**< Task SP pointer */ + UINT32 uwCurrUsed; /**< Current task stack usage */ + UINT32 uwPeakUsed; /**< Task stack usage peak */ + BOOL bOvf; /**< Flag that indicates whether a task stack overflow occurs */ +} TSK_INFO_S; + +/** + * @ingroup los_task + * @brief Create a task and suspend. + * + * @par Description: + * This API is used to create a task and suspend it. This task will not be added to the queue of ready tasks before + * resume it. + * + * @attention + *
      + *
    • During task creation, the task control block and task stack of the task that is previously automatically deleted + * are deallocated.
    • + *
    • The task name is a pointer and is not allocated memory.
    • + *
    • If the size of the task stack of the task to be created is 0, configure #LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE + * to specify the default task stack size. The stack size should be a reasonable value, if the size is too large, may + * cause memory exhaustion.
    • + *
    • The task stack size must be aligned on the boundary of 8 bytes. The size is determined by whether it is big + * enough to avoid task stack overflow.
    • + *
    • Less parameter value indicates higher task priority.
    • + *
    • The task name cannot be null.
    • + *
    • The pointer to the task executing function cannot be null.
    • + *
    • The two parameters of this interface is pointer, it should be a correct value, otherwise, the system may be + * abnormal.
    • + *
    • If user mode is enabled, user should input user stack pointer and size, the size must fit the stack pointer, + * uwStackSize remain as the kernel stack size.
    • + *
    + * + * @param taskID [OUT] Type #UINT32 * Task ID. + * @param taskInitParam [IN] Type #TSK_INIT_PARAM_S * Parameter for task creation. + * + * @retval #LOS_ERRNO_TSK_ID_INVALID Invalid Task ID, param puwTaskID is NULL. + * @retval #LOS_ERRNO_TSK_PTR_NULL Param pstInitParam is NULL. + * @retval #LOS_ERRNO_TSK_NAME_EMPTY The task name is NULL. + * @retval #LOS_ERRNO_TSK_ENTRY_NULL The task entrance is NULL. + * @retval #LOS_ERRNO_TSK_PRIOR_ERROR Incorrect task priority. + * @retval #LOS_ERRNO_TSK_STKSZ_TOO_LARGE The task stack size is too large. + * @retval #LOS_ERRNO_TSK_STKSZ_TOO_SMALL The task stack size is too small. + * @retval #LOS_ERRNO_TSK_TCB_UNAVAILABLE No free task control block is available. + * @retval #LOS_ERRNO_TSK_NO_MEMORY Insufficient memory for task creation. + * @retval #LOS_OK The task is successfully created. + * @par Dependency: + *
    • los_task.h: the header file that contains the API declaration.
    + *
    • los_config.h: the header file that contains system configuration items.
    + * @see LOS_TaskDelete + */ +extern UINT32 LOS_TaskCreateOnly(UINT32 *taskID, TSK_INIT_PARAM_S *taskInitParam); + +/** + * @ingroup los_task + * @brief Create a task. + * + * @par Description: + * This API is used to create a task. If the priority of the task created after system initialized is higher than + * the current task and task scheduling is not locked, it is scheduled for running. + * If not, the created task is added to the queue of ready tasks. + * + * @attention + *
      + *
    • During task creation, the task control block and task stack of the task that is previously automatically + * deleted are deallocated.
    • + *
    • The task name is a pointer and is not allocated memory.
    • + *
    • If the size of the task stack of the task to be created is 0, configure #LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE + * to specify the default task stack size.
    • + *
    • The task stack size must be aligned on the boundary of 8 bytes. The size is determined by whether it is big + * enough to avoid task stack overflow.
    • + *
    • Less parameter value indicates higher task priority.
    • + *
    • The task name cannot be null.
    • + *
    • The pointer to the task executing function cannot be null.
    • + *
    • The two parameters of this interface is pointer, it should be a correct value, otherwise, the system may be + * abnormal.
    • + *
    • If user mode is enabled, user should input user stack pointer and size, the size must fit the stack pointer, + * uwStackSize remain as the kernel stack size.
    • + *
    + * + * @param taskID [OUT] Type #UINT32 * Task ID. + * @param taskInitParam [IN] Type #TSK_INIT_PARAM_S * Parameter for task creation. + * + * @retval #LOS_ERRNO_TSK_ID_INVALID Invalid Task ID, param puwTaskID is NULL. + * @retval #LOS_ERRNO_TSK_PTR_NULL Param pstInitParam is NULL. + * @retval #LOS_ERRNO_TSK_NAME_EMPTY The task name is NULL. + * @retval #LOS_ERRNO_TSK_ENTRY_NULL The task entrance is NULL. + * @retval #LOS_ERRNO_TSK_PRIOR_ERROR Incorrect task priority. + * @retval #LOS_ERRNO_TSK_STKSZ_TOO_LARGE The task stack size is too large. + * @retval #LOS_ERRNO_TSK_STKSZ_TOO_SMALL The task stack size is too small. + * @retval #LOS_ERRNO_TSK_TCB_UNAVAILABLE No free task control block is available. + * @retval #LOS_ERRNO_TSK_NO_MEMORY Insufficient memory for task creation. + * @retval #LOS_OK The task is successfully created. + * @par Dependency: + *
    • los_task.h: the header file that contains the API declaration.
    + *
    • los_config.h: the header file that contains system configuration items.
    + * @see LOS_TaskDelete + */ +extern UINT32 LOS_TaskCreate(UINT32 *taskID, TSK_INIT_PARAM_S *taskInitParam); + +/** + * @ingroup los_task + * @brief Resume a task. + * + * @par Description: + * This API is used to resume a suspended task. + * + * @attention + *
      + *
    • If the task is delayed or blocked, resume the task without adding it to the queue of ready tasks.
    • + *
    • If the priority of the task resumed after system initialized is higher than the current task and task scheduling + * is not locked, it is scheduled for running.
    • + *
    + * + * @param taskID [IN] Type #UINT32 Task ID. The task id value is obtained from task creation. + * + * @retval #LOS_ERRNO_TSK_ID_INVALID Invalid Task ID + * @retval #LOS_ERRNO_TSK_NOT_CREATED The task is not created. + * @retval #LOS_ERRNO_TSK_NOT_SUSPENDED The task is not suspended. + * @retval #LOS_OK The task is successfully resumed. + * @par Dependency: + *
    • los_task.h: the header file that contains the API declaration.
    + * @see LOS_TaskSuspend + */ +extern UINT32 LOS_TaskResume(UINT32 taskID); + +/** + * @ingroup los_task + * @brief Suspend a task. + * + * @par Description: + * This API is used to suspend a specified task, and the task will be removed from the queue of ready tasks. + * + * @attention + *
      + *
    • The task that is running and locked cannot be suspended.
    • + *
    • The idle task and swtmr task cannot be suspended.
    • + *
    + * + * @param taskID [IN] Type #UINT32 Task ID. The task id value is obtained from task creation. + * + * @retval #LOS_ERRNO_TSK_OPERATE_IDLE Check the task ID and do not operate on the idle task. + * @retval #LOS_ERRNO_TSK_SUSPEND_SWTMR_NOT_ALLOWED Check the task ID and do not operate on the swtmr task. + * @retval #LOS_ERRNO_TSK_ID_INVALID Invalid Task ID + * @retval #LOS_ERRNO_TSK_NOT_CREATED The task is not created. + * @retval #LOS_ERRNO_TSK_ALREADY_SUSPENDED The task is already suspended. + * @retval #LOS_ERRNO_TSK_SUSPEND_LOCKED The task being suspended is current task and task scheduling + * is locked. + * @retval #LOS_OK The task is successfully suspended. + * @par Dependency: + *
    • los_task.h: the header file that contains the API declaration.
    + * @see LOS_TaskResume + */ +extern UINT32 LOS_TaskSuspend(UINT32 taskID); + +/** + * @ingroup los_task + * @brief Delete a task. + * + * @par Description: + * This API is used to delete a specified task and release the resources for its task stack and task control block. + * + * @attention + *
      + *
    • The idle task and swtmr task cannot be deleted.
    • + *
    • If delete current task maybe cause unexpected error.
    • + *
    • If a task get a mutex is deleted or automatically deleted before release this mutex, other tasks pended + * this mutex maybe never be shchduled.
    • + *
    + * + * @param taskID [IN] Type #UINT32 Task ID. The task id value is obtained from task creation. + * + * @retval #LOS_ERRNO_TSK_OPERATE_IDLE Check the task ID and do not operate on the idle task. + * @retval #LOS_ERRNO_TSK_SUSPEND_SWTMR_NOT_ALLOWED Check the task ID and do not operate on the swtmr task. + * @retval #LOS_ERRNO_TSK_ID_INVALID Invalid Task ID + * @retval #LOS_ERRNO_TSK_NOT_CREATED The task is not created. + * @retval #LOS_OK The task is successfully deleted. + * @par Dependency: + *
    • los_task.h: the header file that contains the API declaration.
    + * @see LOS_TaskCreate | LOS_TaskCreateOnly + */ +extern UINT32 LOS_TaskDelete(UINT32 taskID); + +/** + * @ingroup los_task + * @brief Delay a task. + * + * @par Description: + * This API is used to delay the execution of the current task. The task is able to be scheduled after it is delayed + * for a specified number of Ticks. + * + * @attention + *
      + *
    • The task fails to be delayed if it is being delayed during interrupt processing or it is locked.
    • + *
    • If 0 is passed in and the task scheduling is not locked, execute the next task in the queue of tasks with + * the same priority of the current task. + * If no ready task with the priority of the current task is available, the task scheduling will not occur, and the + * current task continues to be executed.
    • + *
    • Using the interface before system initialized is not allowed.
    • + *
    + * + * @param tick [IN] Type #UINT32 Number of Ticks for which the task is delayed. + * + * @retval #LOS_ERRNO_TSK_DELAY_IN_INT The task delay occurs during an interrupt. + * @retval #LOS_ERRNO_TSK_DELAY_IN_LOCK The task delay occurs when the task scheduling is locked. + * @retval #LOS_ERRNO_TSK_ID_INVALID Invalid Task ID + * @retval #LOS_ERRNO_TSK_YIELD_NOT_ENOUGH_TASK No tasks with the same priority is available for scheduling. + * @retval #LOS_OK The task is successfully delayed. + * @par Dependency: + *
    • los_task.h: the header file that contains the API declaration.
    + * @see + */ +extern UINT32 LOS_TaskDelay(UINT32 tick); + +/** + * @ingroup los_task + * @brief Lock the task scheduling. + * + * @par Description: + * This API is used to lock the task scheduling. Task switching will not occur if the task scheduling is locked. + * + * @attention + *
      + *
    • If the task scheduling is locked, but interrupts are not disabled, tasks are still able to be interrupted.
    • + *
    • One is added to the number of task scheduling locks if this API is called. The number of locks is decreased by + * one if the task scheduling is unlocked. Therefore, this API should be used together with LOS_TaskUnlock.
    • + *
    + * + * @param None. + * + * @retval None. + * @par Dependency: + *
    • los_task.h: the header file that contains the API declaration.
    + * @see LOS_TaskUnlock + */ +extern VOID LOS_TaskLock(VOID); + +/** + * @ingroup los_task + * @brief Unlock the task scheduling. + * + * @par Description: + * This API is used to unlock the task scheduling. Calling this API will decrease the number of task locks by one. + * If a task is locked more than once, the task scheduling will be unlocked only when the number of locks becomes zero. + * + * @attention + *
      + *
    • The number of locks is decreased by one if this API is called. One is added to the number of task scheduling + * locks if the task scheduling is locked. Therefore, this API should be used together with LOS_TaskLock.
    • + *
    + * + * @param None. + * + * @retval None. + * @par Dependency: + *
    • los_task.h: the header file that contains the API declaration.
    + * @see LOS_TaskLock + */ +extern VOID LOS_TaskUnlock(VOID); + +/** + * @ingroup los_task + * @brief Set a task priority. + * + * @par Description: + * This API is used to set the priority of a specified task. + * + * @attention + *
      + *
    • If the set priority is higher than the priority of the current running task, task scheduling probably occurs. + *
    • + *
    • Changing the priority of the current running task also probably causes task scheduling.
    • + *
    • Using the interface to change the priority of software timer task and idle task is not allowed.
    • + *
    • Using the interface in the interrupt is not allowed.
    • + *
    + * + * @param taskID [IN] Type #UINT32 Task ID. The task id value is obtained from task creation. + * @param taskPrio [IN] Type #UINT16 Task priority. + * + * @retval #LOS_ERRNO_TSK_PRIOR_ERROR Incorrect task priority.Re-configure the task priority + * @retval #LOS_ERRNO_TSK_OPERATE_IDLE Check the task ID and do not operate on the idle task. + * @retval #LOS_ERRNO_TSK_ID_INVALID Invalid Task ID + * @retval #LOS_ERRNO_TSK_NOT_CREATED The task is not created. + * @retval #LOS_OK The task priority is successfully set to a specified priority. + * @par Dependency: + *
    • los_task.h: the header file that contains the API declaration.
    + * @see LOS_TaskPriSet + */ +extern UINT32 LOS_TaskPriSet(UINT32 taskID, UINT16 taskPrio); + +/** + * @ingroup los_task + * @brief Set the priority of the current running task to a specified priority. + * + * @par Description: + * This API is used to set the priority of the current running task to a specified priority. + * + * @attention + *
      + *
    • Changing the priority of the current running task probably causes task scheduling.
    • + *
    • Using the interface to change the priority of software timer task and idle task is not allowed.
    • + *
    • Using the interface in the interrupt is not allowed.
    • + *
    + * + * @param taskPrio [IN] Type #UINT16 Task priority. + * + * @retval #LOS_ERRNO_TSK_PRIOR_ERROR Incorrect task priority.Re-configure the task priority + * @retval #LOS_ERRNO_TSK_OPERATE_IDLE Check the task ID and do not operate on the idle task. + * @retval #LOS_ERRNO_TSK_ID_INVALID Invalid Task ID + * @retval #LOS_ERRNO_TSK_NOT_CREATED The task is not created. + * @retval #LOS_OK The priority of the current running task is successfully set to a specified + * priority. + * @par Dependency: + *
    • los_task.h: the header file that contains the API declaration.
    + * @see LOS_TaskPriGet + */ +extern UINT32 LOS_CurTaskPriSet(UINT16 taskPrio); + +/** + * @ingroup los_task + * @brief Change the scheduling sequence of tasks with the same priority. + * + * @par Description: + * This API is used to move current task in a queue of tasks with the same priority to the tail of the queue of ready + * tasks. + * + * @attention + *
      + *
    • At least two ready tasks need to be included in the queue of ready tasks with the same priority. If the + * less than two ready tasks are included in the queue, an error is reported.
    • + *
    • If call this API after tasklock,it will not report an error, + * and the task will schedule soon after task unlock
    • + *
    + * + * @param None. + * + * @retval #LOS_ERRNO_TSK_ID_INVALID Invalid Task ID + * @retval #LOS_ERRNO_TSK_YIELD_NOT_ENOUGH_TASK No tasks with the same priority is available for scheduling. + * @retval #LOS_OK The scheduling sequence of tasks with same priority is + * successfully changed. + * @par Dependency: + *
    • los_task.h: the header file that contains the API declaration.
    + * @see + */ +extern UINT32 LOS_TaskYield(VOID); + +/** + * @ingroup los_task + * @brief Obtain a task priority. + * + * @par Description: + * This API is used to obtain the priority of a specified task. + * + * @attention None. + * + * @param taskID [IN] Type #UINT32 Task ID. The task id value is obtained from task creation. + * + * @retval #OS_INVALID The task priority fails to be obtained. + * @retval #UINT16 The task priority. + * @par Dependency: + *
    • los_task.h: the header file that contains the API declaration.
    + * @see LOS_TaskPriSet + */ +extern UINT16 LOS_TaskPriGet(UINT32 taskID); + +/** + * @ingroup los_task + * @brief Obtain current running task ID. + * + * @par Description: + * This API is used to obtain the ID of current running task. + * + * @attention + *
      + *
    • This interface should not be called before system initialized.
    • + *
    + * + * @retval #LOS_ERRNO_TSK_ID_INVALID Invalid Task ID. + * @retval #UINT32 Task ID. + * @par Dependency: + *
    • los_task.h: the header file that contains the API declaration.
    + * @see + */ +extern UINT32 LOS_CurTaskIDGet(VOID); + +/** + * @ingroup los_task + * @brief Obtain next running task ID. + * + * @par Description: + * This API is used to obtain the ID of next running task. + * + * @attention None. + * + * + * @retval #NULL invalid Task name. + * @retval #CHAR* task name. + * @par Dependency: + *
    • los_task.h: the header file that contains the API declaration.
    + * @see + */ +extern CHAR *LOS_CurTaskNameGet(VOID); + +/** + * @ingroup los_task + * @brief Obtain a task information structure. + * + * @par Description: + * This API is used to obtain a task information structure. + * + * @attention + *
      + *
    • One parameter of this interface is a pointer, it should be a correct value, otherwise, the system may be + * abnormal.
    • + *
    + * + * @param taskID [IN] Type #UINT32 Task ID. The task id value is obtained from task creation. + * @param taskInfo [OUT] Type #TSK_INFO_S* Pointer to the task information structure to be obtained. + * + * @retval #LOS_ERRNO_TSK_PTR_NULL Null parameter. + * @retval #LOS_ERRNO_TSK_ID_INVALID Invalid task ID. + * @retval #LOS_ERRNO_TSK_NOT_CREATED The task is not created. + * @retval #LOS_OK The task information structure is successfully obtained. + * @par Dependency: + *
    • los_task.h: the header file that contains the API declaration.
    + * @see + */ +extern UINT32 LOS_TaskInfoGet(UINT32 taskID, TSK_INFO_S *taskInfo); + +/** + * @ingroup los_task + * @brief Obtain the task status. + * + * @par Description: + * This API is used to obtain the task status. + * + * @attention None. + * + * @param taskID [IN] Type #TSK_HANDLE_T Task ID. + * @param taskStatus [OUT] Type #UINT32 Pointer to the task status to be obtained. + * + * @retval #LOS_ERRNO_TSK_PTR_NULL 0x02000201: Null parameter. + * @retval #LOS_ERRNO_TSK_ID_INVALID 0x02000207: Invalid task ID. + * @retval #LOS_ERRNO_TSK_NOT_CREATED 0x0200020a: The task is not created. + * @retval #LOS_OK 0: The task information structure is successfully obtained. + * @par Dependency: + *
    • los_task.h: the header file that contains the API declaration.
    + * @see + */ +extern UINT32 LOS_TaskStatusGet(UINT32 taskID, UINT32* taskStatus); + +/** + * @ingroup los_task + * @brief Obtain tasks switch info. + * + * @par Description: + * This API is used to obtain tasks switch info. + * + * @attention None. + * + * @param index [IN] Type #UINT32 Switch info array index. + * @param taskSwitchInfo [OUT] Type #UINT32* First 4 bytes is task id, and then is task name, name len is + * OS_TSK_NAME_LEN. + * + * @retval #LOS_ERRNO_TSK_PTR_NULL 0x02000201: Null parameter. + * @retval #LOS_OK 0: The task switch information is successfully obtained. + * @par Dependency: + *
    • los_task.h: the header file that contains the API declaration.
    + * @see + */ +extern UINT32 LOS_TaskSwitchInfoGet(UINT32 index, UINT32 *taskSwitchInfo); + +/** + * @ingroup los_task + * @brief Obtain tasks schduling info. + * + * @par Description: + * This API is used to obtain task is scheduled. + * + * @attention None. + * + * @param None. + * + * @retval #TRUE Tasks is scheduled. + * @retval #FALSE Tasks not scheduling yet. + * @par Dependency: + *
    • los_task.h: the header file that contains the API declaration.
    + * @see + */ +extern BOOL LOS_TaskIsRunning(VOID); + + /** + * @ingroup los_task + * @brief Obtain current new task name. + * + * @par Description: + * This API is used to obtain the name of new task. + * + * @attention None. + * + * @param taskID [IN] Task ID. + * + * @retval #NULL: invalid Task name. + * @retval # Task name. + * @par Dependency: + *
    • los_task.h: the header file that contains the API declaration.
    + * @see + */ +extern CHAR* LOS_TaskNameGet(UINT32 taskID); + +extern UINT32 LOS_TaskUsage(VOID); + +#ifdef __cplusplus +#if __cplusplus +} +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +#endif /* _LOS_TASK_H */ diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_tick.h b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_tick.h new file mode 100644 index 0000000000000000000000000000000000000000..cfa5a1e2aaf0e9c1fde6b4ea41afcd381a452710 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_tick.h @@ -0,0 +1,118 @@ +/* ---------------------------------------------------------------------------- + * Copyright (c) Huawei Technologies Co., Ltd. 2013-2018. All rights reserved. + * Description: Tick + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * --------------------------------------------------------------------------- */ + +/** + * @defgroup los_tick Tick + * @ingroup kernel + */ + +#ifndef _LOS_TICK_H +#define _LOS_TICK_H + +#include "los_errno.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +/** + * @ingroup los_tick + * Define the type of the platform tick handler function. + * + */ +typedef VOID (*PLATFORM_TICK_HANDLER)(VOID); +extern PLATFORM_TICK_HANDLER g_tickHandler; + +/** + * @ingroup los_tick + * Define the type of the platform tick handler function. + * + */ +typedef VOID (*PLATFORM_GET_CYCLE_FUNC)(UINT32 *cntHi, UINT32 *cntLo); +extern PLATFORM_GET_CYCLE_FUNC g_cycleGetFunc; + +/** + * @ingroup los_tick + * Tick error code: The Tick configuration is incorrect. + * + * Value: 0x02000400 + * + * Solution: Change values of the OS_SYS_CLOCK and LOSCFG_BASE_CORE_TICK_PER_SECOND + * system time configuration modules in Los_config.h. + */ +#define LOS_ERRNO_TICK_CFG_INVALID LOS_ERRNO_OS_ERROR(LOS_MOD_TICK, 0x00) + +/** + * @ingroup los_tick + * Tick error code: This error code is not in use temporarily. + * + * Value: 0x02000401 + * + * Solution: None. + */ +#define LOS_ERRNO_TICK_NO_HWTIMER LOS_ERRNO_OS_ERROR(LOS_MOD_TICK, 0x01) + +/** + * @ingroup los_tick + * Tick error code: The number of Ticks is too small. + * + * Value: 0x02000402 + * + * Solution: Change values of the OS_SYS_CLOCK and LOSCFG_BASE_CORE_TICK_PER_SECOND + * system time configuration modules. + */ +#define LOS_ERRNO_TICK_PER_SEC_TOO_SMALL LOS_ERRNO_OS_ERROR(LOS_MOD_TICK, 0x02) + +/** + * @ingroup los_tick + * @brief: System clock get function. + * + * @par Description: + * This API is used to get system clock. + * + * @attention: + *
    • None.
    + * + * @param: None. + * + * @retval: system clock. + * + * @par Dependency: + *
    • los_tick.h: the header file that contains the API declaration.
    + * @see None. + * + * */ +extern UINT32 LOS_SysClockGet(VOID); + +#ifdef __cplusplus +#if __cplusplus +} +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +#endif /* _LOS_TICK_H */ diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_track.h b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_track.h new file mode 100644 index 0000000000000000000000000000000000000000..8f02e6a99056273ed5815363b62c85b8d6d7c236 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_track.h @@ -0,0 +1,504 @@ +/* ---------------------------------------------------------------------------- + * Copyright (c) Huawei Technologies Co., Ltd. 2013-2018. All rights reserved. + * Description: track + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * --------------------------------------------------------------------------- */ + +#ifndef _LOS_TRACK_H +#define _LOS_TRACK_H + +#include "los_config.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +/** + * @ingroup los_track + * Track mask + */ +typedef enum { + TRACK_ISR_FLAG = 0x10, + TRACK_IRQ_FLAG = 0x20, + TRACK_TASK_FLAG = 0x40, + TRACK_WORKQ_FLAG = 0x80, + TRACK_SWTMR_FLAG = 0x100, + TRACK_MUX_FLAG = 0x200, + TRACK_SEM_FLAG = 0x400, + TRACK_QUE_FLAG = 0x800, + TRACK_EVENT_FLAG = 0x1000 +} LOS_TRACK_MASK; + +/** + * @ingroup los_track + * Track type + */ +typedef enum { + TRAP_INT = TRACK_ISR_FLAG, + + ENABLE_IRQ = TRACK_IRQ_FLAG | 0, + DISABLE_IRQ = TRACK_IRQ_FLAG | 1, + + CREATE_TSK = TRACK_TASK_FLAG | 0, + SCHEDULE_TSK = TRACK_TASK_FLAG | 1, + DELETE_TSK = TRACK_TASK_FLAG | 2, + + ENQUEUE_WORKQ = TRACK_WORKQ_FLAG | 0, + SCHEDULE_WORKQ = TRACK_WORKQ_FLAG | 1, + DEQUEUE_WORKQ = TRACK_WORKQ_FLAG | 2, + + CREATE_SWTMR = TRACK_SWTMR_FLAG | 0, + START_SWTMR = TRACK_SWTMR_FLAG | 1, + MODIFY_SWTMR = TRACK_SWTMR_FLAG | 2, + SCHDING_SWTMR = TRACK_SWTMR_FLAG | 3, + SCHDED_SWTMR = TRACK_SWTMR_FLAG | 4, + STOP_SWTMR = TRACK_SWTMR_FLAG | 5, + DEL_SWTMR = TRACK_SWTMR_FLAG | 6, + DROP_SWTMR = TRACK_SWTMR_FLAG | 7, + + MUX_CREATE = TRACK_MUX_FLAG | 0, + MUX_PEND = TRACK_MUX_FLAG | 1, + MUX_POST = TRACK_MUX_FLAG | 2, + MUX_DEL = TRACK_MUX_FLAG | 3, + + SEM_CREATE = TRACK_SEM_FLAG | 0, + SEM_PEND = TRACK_SEM_FLAG | 1, + SEM_POST = TRACK_SEM_FLAG | 2, + SEM_DEL = TRACK_SEM_FLAG | 3, + + QUE_CREATE = TRACK_QUE_FLAG | 0, + QUE_WRITE = TRACK_QUE_FLAG | 1, + QUE_READ = TRACK_QUE_FLAG | 2, + QUE_DEL = TRACK_QUE_FLAG | 3, + + EVENT_CREATE = TRACK_EVENT_FLAG | 0, + EVENT_WRITE = TRACK_EVENT_FLAG | 1, + EVENT_READ = TRACK_EVENT_FLAG | 2, + EVENT_CLEAR = TRACK_EVENT_FLAG | 3, + EVENT_DEL = TRACK_EVENT_FLAG | 4, +} LOS_TRACK_TYPE; + +/** + * @ingroup los_track + * Track track item structure + */ +typedef struct tagTrackItem { + UINT16 usTrackType; /**< Track type */ + UINT16 usData0; /**< Track ID */ + UINT32 uwData1; /**< Userdata */ + UINT32 uwEntry; /**< Hook function Entry */ + UINT32 uwCurTime; /**< The low 32 bit of the current time */ +} TRACK_ITEM_S; + +/** + * @ingroup los_track + * Track manager structure + */ +typedef struct tagTrackMgr { + UINT16 usCurIndex; /**< The current record index */ + UINT16 usMaxRecordCount; /**< The max num of track items */ + TRACK_ITEM_S *pstTrackItems; /**< Pointer to the track items */ +} TRACK_MGR_S; + +typedef UINT32 (*USER_CUR_US_FUNC)(UINT32 *time); + +/** + * @ingroup los_track + * Define the type of the task track hook function. + * + */ +typedef VOID (*TRACK_PROC_HOOK)(UINT16 trackType, UINT16 trackId, UINT32 userData, UINT32 entry); +extern TRACK_PROC_HOOK g_trackHook; + +/** +* @ingroup los_track +* Track error code: The maximum number of track items is too large. +* +* Value: 0x02001400 +* +* Solution: Decrease the maximum number of track items. +*/ +#define LOS_ERRNO_TRACK_TOO_LARGE_COUNT LOS_ERRNO_OS_ERROR(LOS_MOD_TRACK, 0x00) + +/** +* @ingroup los_track +* Track error code: The maximum number of track items is 0. +* +* Value: 0x02001401 +* +* Solution: Pass in correct maximum number of track items. +*/ +#define LOS_ERRNO_TRACK_PARA_ISZERO LOS_ERRNO_OS_ERROR(LOS_MOD_TRACK, 0x01) + +/** +* @ingroup los_track +* Track error code: The request for memory fails. +* +* Value: 0x02001402 +* +* Solution: Decrease the maximum number of track items. +*/ +#define LOS_ERRNO_TRACK_NO_MEMORY LOS_ERRNO_OS_ERROR(LOS_MOD_TRACK, 0x02) + +/** +* @ingroup los_track +* Track error code: The parameter index is invalid. +* +* Value: 0x02001403 +* +* Solution: Check whether the parameter is applicable for the current operation. +*/ +#define LOS_ERRNO_TRACK_INVALID_PARAM LOS_ERRNO_OS_ERROR(LOS_MOD_TRACK, 0x03) + +/** +* @ingroup los_track +* Track error code: The pointer to an input parameter is NULL. +* +* Value: 0x02001404 +* +* Solution: Check whether the pointer to the input parameter is usable. +*/ +#define LOS_ERRNO_TRACK_PTR_NULL LOS_ERRNO_OS_ERROR(LOS_MOD_TRACK, 0x04) + +/** +* @ingroup los_cpup +* Track error code: The track is not initialized. +* +* Value: 0x02001405 +* +* Solution: Check whether the track is initialized. +*/ +#define LOS_ERRNO_TRACK_NO_INIT LOS_ERRNO_OS_ERROR(LOS_MOD_TRACK, 0x05) + +/** +* @ingroup los_cpup +* Track error code: Reintialize the track memory. +* +* Value: 0x02001406 +* +* Solution:Don't need to intialize the track. +*/ +#define LOS_ERRNO_TRACK_RE_INIT LOS_ERRNO_OS_ERROR(LOS_MOD_TRACK, 0x06) + +/** + * @ingroup los_track + * Mask of information to track + */ +extern UINT16 g_trackMask; + +/** + * @ingroup los_track + * @brief Initializes memory of track manager and track items + * + * @par Description: + * This API is used to initialize memory of track manager and track items + * + * @attention + *
      + *
    • None.
    • + *
    + * + * @param maxRecordCount [IN] #UINT16 The max track count of track items. + * + * @retval LOS_ERRNO_TRACK_RE_INIT Reintialize the track memory. + * @retval LOS_ERRNO_TRACK_TOO_LARGE_COUNT The record count is too large. + * @retval LOS_ERRNO_TRACK_NO_MEMORY The request for memory fails. + * @par Dependency: + *
    • los_track.h: the header file that contains the API declaration.
      • + * @see None. + */ +extern UINT32 LOS_TrackInit(UINT16 maxRecordCount); + +/** + * @ingroup los_track + * @brief Defalt track hookfunction + * + * @par Description: + * This API is used to record the track type,track id,userdata and function entry in the track items. + * + * @attention + *
          + *
        • g_func_get_cur_us funciton is used to get the low 32 bit of current time of each item.
        • + *
        • If the user wants to use own time count funtion, g_func_get_cur_us funciton must be registered first.
        • + *
        • If g_func_get_cur_us function is null, OsTrackhook will transform current tickcount into milliseconds + * and record the low 32 bit of it.
        • + *
        + * + * @param trackType [IN] #UINT16 The type of track. + * @param trackId [IN] #UINT16 The id of track. + * @param userData [IN] #UINT32 The user data . + * @param entry [IN] #UINT32 The entry of function . + * + * @retval None. + * @par Dependency: + *
        • los_track.h: the header file that contains the API declaration.
          • + * @see None. + */ +extern VOID OsTrackhook(UINT16 trackType, UINT16 trackId, UINT32 userData, UINT32 entry); + +/** + * @ingroup los_track + * @brief Start recording the track information. + * + * @par Description: + * This API is used to Start recording the track information. + * + * @attention + *
              + *
            • None.
            • + *
            + * + * @param trackMask [IN] #UINT16 The mask of information needed to track. + * + * @retval #LOS_ERRNO_TRACK_NO_INIT The track is not initialized. + * @retval #LOS_OK The track start successfully. + * @par Dependency: + *
            • los_track.h: the header file that contains the API declaration.
              • + * @see None. + */ +extern UINT32 LOS_TrackStart(UINT16 trackMask); + +/** + * @ingroup los_track + * @brief Stop recording the track information. + * + * @par Description: + * This API is used to Stop recording the track information. + * + * @attention + *
                  + *
                • None.
                • + *
                + * + * @param None. + * + * @retval #UINT16 . Save the mask of information needed to track. + * @par Dependency: + *
                • los_track.h: the header file that contains the API declaration.
                  • + * @see None. + */ +extern UINT16 LOS_TrackStop(VOID); + +/** + * @ingroup los_track + * @brief Get the track manger information. + * + * @par Description: + * This API is used to get the track manger information. + * + * @attention + *
                      + *
                    • None.
                    • + *
                    + * + * @param info [OUT] #TRACK_MGR_S* Pointer to the track manager information structure to be obtained. + * + * @retval type #LOS_ERRNO_TRACK_NO_INIT The track is not initialized. + * @retval type #LOS_ERRNO_TRACK_PTR_NULL Null parameter. + * @retval type #LOS_OK The track manager information structure is successfully obtained. + * @par Dependency: + *
                    • los_track.h: the header file that contains the API declaration.
                      • + * @see None. + */ +extern UINT32 LOS_TrackInfoGet(TRACK_MGR_S *info); + +/** + * @ingroup los_track + * @brief Get the track item information structure by index. + * + * @par Description: + * This API is used to get the track item information structure by index. + * + * @attention + *
                          + *
                        • None.
                        • + *
                        + * + * @param index [IN] #UINT16 The index of track items. + * @param itemInfo [OUT] #TRACK_ITEM_S* Pointer to the track item information structure to be obtained. + * + * @retval type #LOS_ERRNO_TRACK_NO_INIT The track is not initialized. + * @retval type #LOS_ERRNO_TRACK_PTR_NULL Null parameter. + * @retval type #LOS_ERRNO_TRACK_INVALID_PARAM The index is lager than the max count of track item. + * @retval type #LOS_OK The track item information structure is successfully obtained. + * @par Dependency: + *
                        • los_track.h: the header file that contains the API declaration.
                          • + * @see None. + */ +extern UINT32 LOS_TrackItemGetById(UINT16 index, TRACK_ITEM_S *itemInfo); + +/** + * @ingroup los_track + * @brief Delete the track. + * + * @par Description: + * This API is used to delete the track. + * @attention + *
                              + *
                            • None.
                            • + *
                            + * + * @param None. + * + * @retval #LOS_ERRNO_TRACK_NO_INIT The track is not initialized. + * @retval #LOS_OK The track is successfully deleted. + * @par Dependency: + *
                            • los_track.h: the header file that contains the API declaration.
                            + * @see LOS_TrackInit + */ +extern UINT32 LOS_TrackDelete(VOID); +extern UINT32 LOS_CurUsRegHook(USER_CUR_US_FUNC hook); +extern UINT32 LOS_TrackRegHook(TRACK_PROC_HOOK hook); + +#if (LOSCFG_BASE_MISC_TRACK == YES) + +#define LOSCFG_WORKQ_TRACK_ENABLE YES +#define LOSCFG_SWTMR_TRACK_ENABLE YES +#define LOSCFG_TASK_TRACK_ENABLE YES +#define LOSCFG_ISR_TRACK_ENABLE YES +#define LOSCFG_SEM_TRACK_ENABLE YES +#define LOSCFG_MUX_TRACK_ENABLE YES +#define LOSCFG_QUEUE_TRACK_ENABLE YES +#define LOSCFG_EVENT_TRACK_ENABLE YES +#define LOSCFG_IRQ_TRACK_ENABLE YES + +#define LOSCFG_CPUP_ENABLE YES +#endif + +/****************************************************************/ +#if defined(LOSCFG_IRQ_TRACK_ENABLE) && (LOSCFG_IRQ_TRACK_ENABLE == YES) +#define LOS_TRACK_IRQ(type, lr) \ + do { \ + if ((type) & g_trackMask) { \ + OsTrackhook(type, 0, 0, lr); \ + } \ + } while (0) +#else +#define LOS_TRACK_IRQ(type, lr) +#endif +/****************************************************************/ +#if defined(LOSCFG_WORKQ_TRACK_ENABLE) && (LOSCFG_WORKQ_TRACK_ENABLE == YES) +#define LOS_TRACK_WORKQ(type, workPrio, workEntry) \ + do { \ + if ((type) & g_trackMask) { \ + OsTrackhook(type, workPrio, 0, workEntry); \ + } \ + } while (0) +#else +#define LOS_TRACK_WORKQ(type, workPrio, workEntry) +#endif +/****************************************************************/ +#if defined(LOSCFG_TASK_TRACK_ENABLE) && (LOSCFG_TASK_TRACK_ENABLE == YES) +#define LOS_TRACK_TASK(type, taskID) \ + do { \ + if ((type) & g_trackMask) { \ + OsTrackhook(type, taskID, 0, 0); \ + } \ + } while (0) +#else +#define LOS_TRACK_TASK(type, taskID) +#endif +/***************************************************************/ +#if defined(LOSCFG_ISR_TRACK_ENABLE) && (LOSCFG_ISR_TRACK_ENABLE == YES) +#define LOS_TRACK_ISR(type, intVector) \ + do { \ + if ((type) & g_trackMask) { \ + OsTrackhook(type, intVector, 0, 0); \ + } \ + } while (0) +#else +#define LOS_TRACK_ISR(type, intVector) +#endif +/****************************************************************/ +#if defined(LOSCFG_SEM_TRACK_ENABLE) && (LOSCFG_SEM_TRACK_ENABLE == YES) +#define LOS_TRACK_SEM(type, semID, semCnt) \ + do { \ + if ((type) & g_trackMask) { \ + UINT32 entry; \ + __asm__ __volatile__("mv %0, ra" : "=r"(entry)); \ + OsTrackhook(type, semID, semCnt, entry); \ + } \ + } while (0) +#else +#define LOS_TRACK_SEM(type, semID, semCnt) +#endif +/****************************************************************/ +#if defined(LOSCFG_SWTMR_TRACK_ENABLE) && (LOSCFG_SWTMR_TRACK_ENABLE == YES) +#define LOS_TRACK_SWTMR(type, tmrID, time, entry) \ + do { \ + if ((type) & g_trackMask) { \ + OsTrackhook(type, tmrID, time, entry); \ + } \ + } while (0) +#else +#define LOS_TRACK_SWTMR(type, tmrID, time, entry) +#endif +/****************************************************************/ +#if defined(LOSCFG_QUEUE_TRACK_ENABLE) && (LOSCFG_QUEUE_TRACK_ENABLE == YES) +#define LOS_TRACK_QUEUE(type, ret) \ + do { \ + if ((type) & g_trackMask) { \ + UINT32 entry; \ + __asm__ __volatile__("mv %0, ra" : "=r"(entry)); \ + OsTrackhook(type, 0, ret, entry); \ + } \ + } while (0) +#else +#define LOS_TRACK_QUEUE(type, ret) +#endif +/****************************************************************/ +#if defined(LOSCFG_EVENT_TRACK_ENABLE) && (LOSCFG_EVENT_TRACK_ENABLE == YES) +#define LOS_TRACK_EVENT(type, value) \ + do { \ + if ((type) & g_trackMask) { \ + UINT32 entry; \ + __asm__ __volatile__("mv %0, ra" : "=r"(entry)); \ + OsTrackhook(type, 0, value, entry); \ + } \ + } while (0) +#else +#define LOS_TRACK_EVENT(type, value) +#endif +/****************************************************************/ +#if defined(LOSCFG_MUX_TRACK_ENABLE) && (LOSCFG_MUX_TRACK_ENABLE == YES) +#define LOS_TRACK_MUX(type, id, cnt) \ + do { \ + if ((type) & g_trackMask) { \ + UINT32 entry; \ + __asm__ __volatile__("mv %0, ra" : "=r"(entry)); \ + OsTrackhook(type, id, cnt, entry); \ + } \ + } while (0) +#else +#define LOS_TRACK_MUX(type, id, cnt) +#endif +/****************************************************************/ +#ifdef __cplusplus +#if __cplusplus +} +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +#endif /* _LOS_TRACK_H */ diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_typedef.h b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_typedef.h new file mode 100644 index 0000000000000000000000000000000000000000..c686262e4187e4f0e9cb202e2cfbce1fe9faeacc --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/kernel/include/los_typedef.h @@ -0,0 +1,138 @@ +/* ---------------------------------------------------------------------------- + * Copyright (c) Huawei Technologies Co., Ltd. 2013-2018. All rights reserved. + * Description: Type define + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * --------------------------------------------------------------------------- */ + +/** + * @defgroup los_typedef Type define + * @ingroup kernel + */ + +#ifndef _LOS_TYPEDEF_H +#define _LOS_TYPEDEF_H + +#include "los_builddef.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +#ifndef LOS_TYPE_DEF +#define LOS_TYPE_DEF + +/* type definitions */ +typedef unsigned char UINT8; +typedef unsigned short UINT16; +typedef unsigned int UINT32; +typedef signed char INT8; +typedef signed short INT16; +typedef signed int INT32; +typedef float FLOAT; +typedef double DOUBLE; +typedef char CHAR; + +typedef unsigned int BOOL; +typedef unsigned long long UINT64; +typedef signed long long INT64; +typedef unsigned int UINTPTR; +typedef signed int INTPTR; +typedef UINT32 size_t; + +#define VOID void +#endif /* end of #ifndef LOS_TYPE_DEF */ + +#ifndef FALSE +#define FALSE ((BOOL)0) +#endif + +#ifndef TRUE +#define TRUE ((BOOL)1) +#endif + +#ifndef NULL +#define NULL ((VOID *)0) +#endif + +#ifdef YES +#undef YES +#endif +#define YES 1 + +#ifdef NO +#undef NO +#endif +#define NO 0 + +#define OS_NULL_BYTE ((UINT8)0xFF) +#define OS_NULL_SHORT ((UINT16)0xFFFF) +#define OS_NULL_INT ((UINT32)0xFFFFFFFF) + +#ifndef LOS_OK +#define LOS_OK 0U +#endif + +#ifndef LOS_NOK +#define LOS_NOK 1U +#endif + +#define OS_FAIL 1 +#define OS_ERROR (UINT32)(-1) +#define OS_INVALID (UINT32)(-1) + +#ifndef LOS_LABEL_DEFN +#define LOS_LABEL_DEFN(label) (label) +#endif + +#ifndef LOSARC_ALIGNMENT +# define LOSARC_ALIGNMENT 8 +#endif +// And corresponding power of two alignment +#ifndef LOSARC_P2ALIGNMENT +# define LOSARC_P2ALIGNMENT 2 +#endif + +// Give a type or object explicit minimum alignment +# if !defined(LOSBLD_ATTRIB_ALIGN) +# define LOSBLD_ATTRIB_ALIGN(__align__) __attribute__((aligned(__align__))) +# endif + +// Assign a defined variable to a specific section +# if !defined(LOSBLD_ATTRIB_SECTION) +# define LOSBLD_ATTRIB_SECTION(__sect__) __attribute__((section (__sect__))) +# endif + +// Tell the compiler not to throw away a variable or function. Only known +// available on 3.3.2 or above. Old version's didn't throw them away, +// but using the unused attribute should stop warnings. +#define LOSBLD_ATTRIB_USED __attribute__((used)) + +#ifdef __cplusplus +#if __cplusplus +} +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +#endif /* _LOS_TYPEDEF_H */ diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/targets/hi3861v100/commons/printf.h b/sdk_liteos/platform/os/Huawei_LiteOS/targets/hi3861v100/commons/printf.h new file mode 100644 index 0000000000000000000000000000000000000000..ae783185827d689fe2882dbb840ba29e0705e6f9 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/targets/hi3861v100/commons/printf.h @@ -0,0 +1,56 @@ +/* ---------------------------------------------------------------------------- + * Copyright (c) Huawei Technologies Co., Ltd. 2019-2019. All rights reserved. + * Description: printf + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * --------------------------------------------------------------------------- */ + +#ifndef _COMMON_PRINTF_H__ +#define _COMMON_PRINTF_H__ + +#include "los_typedef.h" +#include "stdarg.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +#define MAX_PRINT_SIZE (256) + +typedef int (* OS_SENDCHR2CHL_HOOK_FUNC)(const char*, unsigned int, const void*); +typedef int (*OUTPUT_FUNC)(const char *str, unsigned int length, void *state); +typedef int (* OS_PRINTF_HOOK_FUNC)(const char *format, va_list arg, OUTPUT_FUNC fPutc, void *cookie); + +LITE_OS_SEC_TEXT void register_log_hook(OS_SENDCHR2CHL_HOOK_FUNC uartFun); + +extern OS_SENDCHR2CHL_HOOK_FUNC g_logHook; +extern OS_PRINTF_HOOK_FUNC g_dprintfHook; + +#ifdef __cplusplus +#if __cplusplus +} +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +#endif /* _COMMON_PRINTF_H__ */ diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/targets/hi3861v100/include/hal_sectors.h b/sdk_liteos/platform/os/Huawei_LiteOS/targets/hi3861v100/include/hal_sectors.h new file mode 100644 index 0000000000000000000000000000000000000000..f9560ed7c781dcf4f9f55cdf4f8c1fb407892020 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/targets/hi3861v100/include/hal_sectors.h @@ -0,0 +1,49 @@ +/* ---------------------------------------------------------------------------- + * Copyright (c) Huawei Technologies Co., Ltd. 2019-2019. All rights reserved. + * Description: hal_sectors + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * --------------------------------------------------------------------------- */ + +/****************************************************************************** + * @brief header file for the hal_sectors + * Copyright (c) 2015 LiteOS LIMITED +******************************************************************************/ + +#ifndef _LITEOS_HAL_SECTORS_H +#define _LITEOS_HAL_SECTORS_H + +#include "los_typedef.h" + +/* The size of the RAM assigned to the heap in internal RAM (in octets) */ +extern UINT32 g_halSectorsRamHeapSize; + +/* The pointer to the start of the external RAM assigned to the internal RAM heap */ +extern VOID *g_halSectorsRamHeapStart; + +/* The total size of the RAM (in octets) */ +extern UINT32 g_halSectorsRamSize; + +/* The start address of RAM */ +extern VOID* g_halSectorsRamStart; + +#endif /* _LITEOS_HAL_SECTORS_H */ diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/targets/hi3861v100/include/los_builddef.h b/sdk_liteos/platform/os/Huawei_LiteOS/targets/hi3861v100/include/los_builddef.h new file mode 100644 index 0000000000000000000000000000000000000000..516038aa18c5b5794bc19a4414a04eb1d4a6773f --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/targets/hi3861v100/include/los_builddef.h @@ -0,0 +1,217 @@ +/* ---------------------------------------------------------------------------- + * Copyright (c) Huawei Technologies Co., Ltd. 2019-2019. All rights reserved. + * Description: los_builddef + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * --------------------------------------------------------------------------- */ + +/** + * @defgroup los_builddef + * @ingroup kernel + */ + +#ifndef _LOS_BUILDEF_H +#define _LOS_BUILDEF_H +#include "los_compiler.h" +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif /* __cpluscplus */ +#endif /* __cpluscplus */ + +/** + * @ingroup los_builddef + * Little endian + */ +#define OS_LITTLE_ENDIAN 0x1234 + +/** + * @ingroup los_builddef + * Big endian + */ +#define OS_BIG_ENDIAN 0x4321 + +/** + * @ingroup los_builddef + * Byte order + */ +#ifndef OS_BYTE_ORDER +#define OS_BYTE_ORDER OS_LITTLE_ENDIAN +#endif + +/* Define OS code data sections */ +/* The indicator function is inline */ +/** + * @ingroup los_builddef + * Allow inline sections + */ +#ifndef LITE_OS_SEC_ALW_INLINE +#define LITE_OS_SEC_ALW_INLINE __attribute__((always_inline)) +#endif + +/** + * @ingroup los_builddef + * Vector table section + */ +#ifndef LITE_OS_SEC_VEC +#define LITE_OS_SEC_VEC __attribute__ ((section(".data.vector"))) +#endif + +/** + * @ingroup los_builddef + * .Text section (Code section) + */ +#ifndef LITE_OS_SEC_TEXT +#define LITE_OS_SEC_TEXT +#endif + +/** + * @ingroup los_builddef + * .Text.ddr section + */ +#ifndef LITE_OS_SEC_TEXT_MINOR +#define LITE_OS_SEC_TEXT_MINOR +#endif + +/** + * @ingroup los_builddef + * .Text.init section + */ +#ifndef LITE_OS_SEC_TEXT_INIT +#define LITE_OS_SEC_TEXT_INIT +#endif + +/** + * @ingroup los_builddef + * Redirect .Text section (Code section) + */ +#ifndef LITE_OS_SEC_TEXT_REDIRECT +#define LITE_OS_SEC_TEXT_REDIRECT LITE_OS_SEC_TEXT +#endif + +/** + * @ingroup los_builddef + * Redirect .Text.ddr section + */ +#ifndef LITE_OS_SEC_TEXT_MINOR_REDIRECT +#define LITE_OS_SEC_TEXT_MINOR_REDIRECT LITE_OS_SEC_TEXT_MINOR +#endif + +/** + * @ingroup los_builddef + * Redirect .Text.init section + */ +#ifndef LITE_OS_SEC_TEXT_INIT_REDIRECT +#define LITE_OS_SEC_TEXT_INIT_REDIRECT LITE_OS_SEC_TEXT_INIT +#endif + + +#ifndef LITE_OS_RAM_SECTION +#define LITE_OS_RAM_SECTION __attribute__ ((section(".ram.kernel"))) +#endif + +/** + * @ingroup los_builddef + * .rodata section + */ +#ifndef LITE_OS_SEC_RODATA +#define LITE_OS_SEC_RODATA +#endif + +/** + * @ingroup los_builddef + * .Data section + */ +#ifndef LITE_OS_SEC_DATA +#define LITE_OS_SEC_DATA __attribute__ ((section(".data"))) +#endif + +/** + * @ingroup los_builddef + * .remap section + */ +#ifndef LITE_OS_SEC_REMAP +#define LITE_OS_SEC_REMAP __attribute__ ((section(".fpb.remap"))) +#endif + + +/** + * @ingroup los_builddef + * .Data.init section + */ +#ifndef LITE_OS_SEC_DATA_INIT +#define LITE_OS_SEC_DATA_INIT +#endif + +/** + * @ingroup los_builddef + * Not initialized variable section + */ +#ifndef LITE_OS_SEC_BSS +#define LITE_OS_SEC_BSS +#endif + +/** + * @ingroup los_builddef + * .bss.ddr section + */ +#ifndef LITE_OS_SEC_BSS_MINOR +#define LITE_OS_SEC_BSS_MINOR +#endif + +/** + * @ingroup los_builddef + * .bss.init sections + */ +#ifndef LITE_OS_SEC_BSS_INIT +#define LITE_OS_SEC_BSS_INIT +#endif + +/** + * @ingroup los_builddef + * .text.rom.libsec section + */ +#ifndef LIB_SECURE_SEC_TEXT +#define LIB_SECURE_SEC_TEXT +#endif + +/** + * @ingroup los_builddef + * .text.rom.libc section + */ +#ifndef LIBC_SEC_TEXT +#define LIBC_SEC_TEXT +#endif + +/** + * @ingroup los_builddef + * Define extern + */ +#define EXTERN_FAR extern + +#ifdef __cplusplus +#if __cplusplus +} +#endif /* __cpluscplus */ +#endif /* __cpluscplus */ + +#endif /* _LOS_BUILDEF_H */ diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/targets/hi3861v100/include/los_printf.h b/sdk_liteos/platform/os/Huawei_LiteOS/targets/hi3861v100/include/los_printf.h new file mode 100644 index 0000000000000000000000000000000000000000..7af5f3ec98e8ddd0601f9df739d527b36d27ba53 --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/targets/hi3861v100/include/los_printf.h @@ -0,0 +1,130 @@ +/* ---------------------------------------------------------------------------- + * Copyright (c) Huawei Technologies Co., Ltd. 2019-2019. All rights reserved. + * Description: los_printf + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * --------------------------------------------------------------------------- */ + +/** + * @defgroup los_printf Printf + * @ingroup kernel + */ + +#ifndef _LOS_PRINTF_H +#define _LOS_PRINTF_H + +#include "los_typedef.h" +#include "los_config.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +#define LOS_EMG_LEVEL 0 + +#define LOS_COMMOM_LEVEL (LOS_EMG_LEVEL + 1) + +#define LOS_ERR_LEVEL (LOS_COMMOM_LEVEL + 1) + +#define LOS_WARN_LEVEL (LOS_ERR_LEVEL + 1) + +#define LOS_INFO_LEVEL (LOS_WARN_LEVEL + 1) + +#define LOS_DEBUG_LEVEL (LOS_INFO_LEVEL + 1) + +#ifdef GCOVERAGE +#define PRINT_LEVEL 0 +#else +#define PRINT_LEVEL LOS_ERR_LEVEL +#endif + +extern int printf(const char *fmt, ...); +#define los_printf (VOID)printf + +/** + * @ingroup los_printf + * @brief Format and print data. + * + * @par Description: + * Print argument(s) according to fmt. + * + * @attention + *
                              + *
                            • None
                            • + *
                            + * + * @param fmt [IN] Type char* controls the ouput as in C printf. + * + * @retval None + * @par Dependency: + *
                            • los_printf.h: the header file that contains the API declaration.
                            + * @see printf + */ +#define diag_printf los_printf + +#if PRINT_LEVEL < LOS_DEBUG_LEVEL +#define PRINT_DEBUG(fmt, args...) +#else +#define PRINT_DEBUG(fmt, args...) do { (los_printf("[DEBUG] "), los_printf(fmt, ##args)); } while (0) +#endif + +#if PRINT_LEVEL < LOS_INFO_LEVEL +#define PRINT_INFO(fmt, args...) +#else +#define PRINT_INFO(fmt, args...) do { (los_printf("[INFO] "), los_printf(fmt, ##args)); } while (0) +#endif + +#if PRINT_LEVEL < LOS_WARN_LEVEL +#define PRINT_WARN(fmt, args...) +#else +#define PRINT_WARN(fmt, args...) do { (los_printf("[WARN] "), los_printf(fmt, ##args)); } while (0) +#endif + +#if PRINT_LEVEL < LOS_ERR_LEVEL +#define PRINT_ERR(fmt, args...) +#else +#define PRINT_ERR(fmt, args...) do { (los_printf("[ERR] "), los_printf(fmt, ##args)); } while (0) +#endif + +#if PRINT_LEVEL < LOS_COMMOM_LEVEL +#define PRINTK(fmt, args...) +#else +#define PRINTK(fmt, args...) los_printf(fmt, ##args) +#endif + +#if PRINT_LEVEL < LOS_EMG_LEVEL +#define PRINT_EMG(fmt, args...) +#else +#define PRINT_EMG(fmt, args...) do { (los_printf("[EMG] "), los_printf(fmt, ##args)); } while (0) +#endif + +#define PRINT_RELEASE(fmt, args...) los_printf(fmt, ##args) + +#ifdef __cplusplus +#if __cplusplus +} +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +#endif /* _LOS_PRINTF_H */ diff --git a/sdk_liteos/platform/os/Huawei_LiteOS/targets/hi3861v100/include/target_config.h b/sdk_liteos/platform/os/Huawei_LiteOS/targets/hi3861v100/include/target_config.h new file mode 100644 index 0000000000000000000000000000000000000000..59c546ea79c33ba58186b2442190966702c9f45f --- /dev/null +++ b/sdk_liteos/platform/os/Huawei_LiteOS/targets/hi3861v100/include/target_config.h @@ -0,0 +1,420 @@ +/* ---------------------------------------------------------------------------- + * Copyright (c) Huawei Technologies Co., Ltd. 2019-2019. All rights reserved. + * Description: target config + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used + * to endorse or promote products derived from this software without specific prior written + * permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * --------------------------------------------------------------------------- */ + +/** + * @defgroup los_config System configuration items + * @ingroup kernel + */ + +#ifndef _TARGET_CONFIG_H +#define _TARGET_CONFIG_H + +#include "hal_sectors.h" +#include "hi3861.h" +#include "system_config.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +#define LOSCFG_CORTEX_M3 + +#define _T(x) x + +/*============================================================================= + Lib configurable feature configuration +=============================================================================*/ +/** + * @ingroup los_config + * Configuration lib configurable feature to open + */ +#ifdef LIB_CONFIGURABLE +#define LOSCFG_LIB_CONFIGURABLE YES +#else +#define LOSCFG_LIB_CONFIGURABLE NO +#endif + +/*============================================================================= + Test module configuration +=============================================================================*/ +/** + * @ingroup los_config + * Configuration test case to open + */ +#ifdef HI1131TEST +#define LOSCFG_TEST YES +#endif + +/*============================================================================= + LIBC module configuration +=============================================================================*/ +/** + * @ingroup los_config + * Configuration to support libc + */ +#define LOSCFG_LIB_LIBC YES + +/*============================================================================= + System clock module configuration +=============================================================================*/ +/** + * @ingroup los_config + * System clock (unit: HZ) + */ +#if (LOSCFG_LIB_CONFIGURABLE == YES) +extern UINT32 g_osSysClock; +#define OS_SYS_CLOCK g_osSysClock +#else +#define OS_SYS_CLOCK (40000000UL) /* ԭΪ80000000 */ +#endif + +/** + * @ingroup los_config + * Number of Ticks in one second + */ +#if (LOSCFG_LIB_CONFIGURABLE == YES) +extern UINT32 g_minusOneTickPerSecond; +#define LOSCFG_BASE_CORE_TICK_PER_SECOND (g_minusOneTickPerSecond + 1) /* tick per sencond plus 1 */ +#else +#define LOSCFG_BASE_CORE_TICK_PER_SECOND (100UL) +#endif + +/** + * @ingroup los_config + * External configuration item for timer tailoring + */ +#define LOSCFG_BASE_CORE_TICK_HW_TIME YES + +/*============================================================================= + Hardware interrupt module configuration +=============================================================================*/ +/** + * @ingroup los_config + * Configuration item for hardware interrupt tailoring + */ +#define LOSCFG_PLATFORM_HWI YES + +/** + * @ingroup los_config + * Highest priority of a hardware interrupt. + */ +#ifndef OS_HWI_PRIO_HIGHEST +#define OS_HWI_PRIO_HIGHEST 7 +#endif +/** + * @ingroup los_config + * Lowest priority of a hardware interrupt. + */ +#ifndef OS_HWI_PRIO_LOWEST +#define OS_HWI_PRIO_LOWEST 1 +#endif + +/*============================================================================= + Task module configuration +=============================================================================*/ +/** + * @ingroup los_config + * Minimum stack size. + * + * 0x80 bytes, aligned on a boundary of 4. + */ +#if (LOSCFG_LIB_CONFIGURABLE == YES) +extern UINT32 g_taskMinStkSize; +#define LOSCFG_BASE_CORE_TSK_MIN_STACK_SIZE g_taskMinStkSize +#else +#define LOSCFG_BASE_CORE_TSK_MIN_STACK_SIZE (ALIGN(0x180, 4)) +#endif + +/** + * @ingroup los_config + * Idle task stack size. + */ +#if (LOSCFG_LIB_CONFIGURABLE == YES) +extern UINT32 g_taskIdleStkSize; +#define LOSCFG_BASE_CORE_TSK_IDLE_STACK_SIZE g_taskIdleStkSize +#else +#define LOSCFG_BASE_CORE_TSK_IDLE_STACK_SIZE (0x180UL) +#endif + +/** + * @ingroup los_config + * Maximum supported number of tasks except the idle task rather than the number of usable tasks + */ +#if (LOSCFG_LIB_CONFIGURABLE == YES) +extern UINT32 g_taskLimit; +#define LOSCFG_BASE_CORE_TSK_LIMIT g_taskLimit +#else +#define LOSCFG_BASE_CORE_TSK_LIMIT 32 +#endif + +/** + * @ingroup los_config + * Soft timer task stack size + */ +#if (LOSCFG_LIB_CONFIGURABLE == YES) +extern UINT32 g_taskSwtmrStkSize; +#define LOSCFG_BASE_CORE_TSK_SWTMR_STACK_SIZE g_taskSwtmrStkSize +#else +#define LOSCFG_BASE_CORE_TSK_SWTMR_STACK_SIZE (0x1000UL) +#endif + +/** + * @ingroup los_config + * Default task stack size + */ +#if (LOSCFG_LIB_CONFIGURABLE == YES) +extern UINT32 g_taskDfltStkSize; +#define LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE g_taskDfltStkSize +#else +#define LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE (0x1000UL) +#endif + +/** + * @ingroup los_config + * Longest execution time of tasks with the same priorities + */ +#if (LOSCFG_LIB_CONFIGURABLE == YES) +extern UINT32 g_timeSliceTimeOut; +#define LOSCFG_BASE_CORE_TIMESLICE_TIMEOUT g_timeSliceTimeOut +#else +#define LOSCFG_BASE_CORE_TIMESLICE_TIMEOUT 2 +#endif + +/****************************** PMP module configuration ******************************/ +/** + * @ingroup los_config + * Configuration item for PMP + */ +#define LOSCFG_BASE_CORE_PMP YES + +/** + * @ingroup los_config + * PMP support number : PMP maximum number of region support + */ +#define LOSCFG_PMP_MAX_SUPPORT 16 // PMP maximum support number + +/** + * @ingroup los_config + * PMP support address range : from LOSCFG_PMP_MIN_ADDRESS to LOSCFG_PMP_MAX_ADDRESS + */ +#define LOSCFG_PMP_MIN_ADDRESS 0x00000000UL // Minimum protected address +#define LOSCFG_PMP_MAX_ADDRESS 0x07FFFFFFUL // Maximum protected address + +/** + * @ingroup los_config + * The PMP entry size granularity must be the multiple of cache line size. + */ +#define CACHE_LINE_SIZE 32 // cache line size, +#define LOSCFG_PMP_MAX_SIZE 0xFFFFFFFF + +/*============================================================================= + Semaphore module configuration +=============================================================================*/ +/** + * @ingroup los_config + * Maximum supported number of semaphores + */ +#if (LOSCFG_LIB_CONFIGURABLE == YES) +extern UINT32 g_semLimit; +#define LOSCFG_BASE_IPC_SEM_LIMIT g_semLimit +#else +#define LOSCFG_BASE_IPC_SEM_LIMIT 100 +#endif + +/*============================================================================= + Mutex module configuration +=============================================================================*/ +/** + * @ingroup los_config + * Maximum supported number of mutexes + */ +#if (LOSCFG_LIB_CONFIGURABLE == YES) +extern UINT32 g_muxLimit; +#define LOSCFG_BASE_IPC_MUX_LIMIT g_muxLimit +#else +#define LOSCFG_BASE_IPC_MUX_LIMIT 64 +#endif + +/*============================================================================= + Queue module configuration +=============================================================================*/ +/** + * @ingroup los_config + * Maximum supported number of queues rather than the number of usable queues + */ +#if (LOSCFG_LIB_CONFIGURABLE == YES) +extern UINT32 g_queueLimit; +#define LOSCFG_BASE_IPC_QUEUE_LIMIT g_queueLimit +#else +#define LOSCFG_BASE_IPC_QUEUE_LIMIT 64 +#endif + +/*============================================================================= + Software timer module configuration +=============================================================================*/ +/** + * @ingroup los_config + * Maximum supported number of software timers rather than the number of usable software timers + */ +#if (LOSCFG_LIB_CONFIGURABLE == YES) +extern UINT32 g_swtmrLimit; +#define LOSCFG_BASE_CORE_SWTMR_LIMIT g_swtmrLimit +#else +#define LOSCFG_BASE_CORE_SWTMR_LIMIT 80 +#endif + +/*============================================================================= + Memory module configuration +=============================================================================*/ +/** + * @ingroup los_config + * Starting address of the memory + */ +#define OS_SYS_MEM_ADDR (g_halSectorsRamHeapStart) + +/** + * @ingroup los_config + * Memory size + */ +#define OS_SYS_MEM_SIZE (g_halSectorsRamHeapSize) + +#define LOSCFG_MEMORY_BESTFIT YES + +/** + * @ingroup los_config + * Configuration module tailoring of membox + */ +#define LOSCFG_MEMBOX NO + +/** + * @ingroup los_config + * Configuration module momery water line + */ +#define LOSCFG_MEM_WATERLINE YES + +/** + * @ingroup los_config + * Configuration module tailoring of mem node size checking + */ +#define LOSCFG_BASE_MEM_NODE_SIZE_CHECK NO + +/** + * @ingroup los_config + * Configuration module momery alloc and free check + */ +#define LOSCFG_MEM_ENABLE_ALLOC_CHECK NO + +/*============================================================================= + Exception module configuration +=============================================================================*/ +/** + * @ingroup los_config + * Configuration item for exception tailoring + */ +#define LOSCFG_PLATFORM_EXC YES + +/*============================================================================= + Runstop module configuration +=============================================================================*/ +/** + * @ingroup los_config + * Configuration item for runstop + */ +#define LOSCFG_RUNSTOP_THRESHOLD 2 + +/*============================================================================= + track configuration +=============================================================================*/ +/** + * @ingroup los_config + * Configuration item for track + */ +#define LOSCFG_BASE_MISC_TRACK YES + +/** + * @ingroup los_config + * Max count of track items + */ +#define LOSCFG_BASE_MISC_TRACK_MAX_COUNT 1000 + +/** + * @ingroup los_config + * Configuration item for task (stack) monitoring module tailoring + */ +#define LOSCFG_BASE_CORE_TSK_MONITOR YES + +/*============================================================================= + CPUP configuration +=============================================================================*/ +#if (LOSCFG_BASE_CORE_TSK_MONITOR == YES) +/** + * @ingroup los_config + * Configuration item for CPU task usage tailoring + */ +#define LOSCFG_BASE_CORE_CPUP YES +/** + * @ingroup los_config + * Configuration item for CPU hwi usage tailoring + */ +#if (LOSCFG_BASE_CORE_CPUP == YES) +#define LOSCFG_BASE_CORE_CPUP_HWI YES +#endif + +#endif + +/*============================================================================= + FPB configuration +=============================================================================*/ +/** + * @ingroup los_config + * Configuration item for flash patch + */ +#define LOSCFG_BASE_CORE_FPB YES + +/** + * @ingroup los_config + * flash patch type + */ +#define LOSCFG_FPB_CONFIG_PCO 1 + +#ifdef LOSCFG_DEBUG_KASAN +#if (LOSCFG_LIB_CONFIGURABLE == YES) +extern UINT32 g_kasanLimit; +#define LOSCFG_KASAN_TASK_STACK_NUM g_kasanLimit +#else +#define LOSCFG_KASAN_TASK_STACK_NUM 3 +#endif +#endif + +#ifdef __cplusplus +#if __cplusplus +} +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +#endif /* _TARGET_CONFIG_H */ diff --git a/sdk_liteos/platform/system/Makefile b/sdk_liteos/platform/system/Makefile new file mode 100755 index 0000000000000000000000000000000000000000..e8dffa9b51c1d121072661effec703d019677df4 --- /dev/null +++ b/sdk_liteos/platform/system/Makefile @@ -0,0 +1,36 @@ +include $(MAIN_TOPDIR)/build/make_scripts/config.mk +include $(MAIN_TOPDIR)/$(MODULE_DIR)/module_config.mk +-include $(MAIN_TOPDIR)/$(MODULE_DIR)/srcs.mk + +OBJDIR = $(MAIN_TOPDIR)/$(OBJ_PATH)/$(MODULE_DIR) + +ID_CFG_FILE = $(MAIN_TOPDIR)/$(MODULE_DIR)/file_id.cfg + +LIB_NAME = lib$(LIB).a +SRCS = $($(LIB)_srcs) +LIBOUT = $(MAIN_TOPDIR)/$(LIB_PATH)/$(MODULE_DIR)/$(LIB_NAME) + +ifdef SRC_FILES +OBJ_SRCS := $(filter %.c, $(SRC_FILES)) +ASM_SRCS := $(filter %.S, $(SRC_FILES)) +else +OBJ_SRCS := $(foreach dir, $(SRCS), $(wildcard $(dir)/*.c)) +ASM_SRCS := $(foreach dir, $(SRCS), $(wildcard $(dir)/*.S )) +endif + +OBJ_SRCS := $(filter-out %/ethernetif.c, $(OBJ_SRCS)) +OBJS = $(patsubst %.c, $(OBJDIR)/%.o, $(OBJ_SRCS)) +ASM_OBJS = $(patsubst %.S, $(OBJDIR)/%.o, $(ASM_SRCS)) + +all: $(LIBOUT) +include $(MAIN_TOPDIR)/build/make_scripts/lib.mk + +clean: + $(Q)$(foreach x, $(OBJS) $(ASM_OBJS) $(LIBOUT), \ + if [ -d $(dir $x) ]; \ + then $(RM) $(dir $x); \ + echo clean dir $(dir $x) success; \ + fi;) + +.PHONY: all clean + diff --git a/sdk_liteos/platform/system/SConscript b/sdk_liteos/platform/system/SConscript new file mode 100755 index 0000000000000000000000000000000000000000..c114dbee92ce5871effa62b087c59411b2960f00 --- /dev/null +++ b/sdk_liteos/platform/system/SConscript @@ -0,0 +1,25 @@ +#!/usr/bin/env python3 +# coding=utf-8 +import os +from scripts import common_env +Import('env') +Import('env_cfg') +Import('module') + +module_path = env_cfg.get_module_dir(module) +obj_path = env_cfg.obj_path +module_libs = env_cfg.get_module_libs(module) +libs = [] + +env = env.Clone() +env_cfg.append_environs(env, module) +common_env.print_log_env(env, env_cfg.get_module_dir(module)) + +for lib in module_libs: + print('lib_name:',lib) + src_path = module_libs[lib] + objs = [] + for src in src_path: + objs += env.SConscript(os.path.join(src, 'SConscript'), {'env':env}, variant_dir = os.path.join('#', obj_path, module_path, src), duplicate = 0) + libs += env.Library(lib,objs) +Return('libs') diff --git a/sdk_liteos/platform/system/cfg/SConscript b/sdk_liteos/platform/system/cfg/SConscript new file mode 100755 index 0000000000000000000000000000000000000000..b0e5f0e2b015ebbec8bd8a4344149640ab49ef09 --- /dev/null +++ b/sdk_liteos/platform/system/cfg/SConscript @@ -0,0 +1,4 @@ +Import('env') + +objs = env.Object(Glob('*.c')) +Return('objs') diff --git a/sdk_liteos/platform/system/cfg/sal_cfg.c b/sdk_liteos/platform/system/cfg/sal_cfg.c new file mode 100644 index 0000000000000000000000000000000000000000..445e6b9bab1e6119b76172284f32b8b9ec71fb1b --- /dev/null +++ b/sdk_liteos/platform/system/cfg/sal_cfg.c @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "sal_cfg.h" + +#include +#include +#include +#include +#include + +hi_u32 g_auto_wdg_rst_sys_timeout = PRODUCT_CFG_AUTO_WDG_RESET_SYSTEM_TIMEOUT; + +// #define CONFIG_HILINK_PKI_SUPPORT /* currently hilink not support PKI provision */ +hi_void hi_tee_irq_handler(void) +{ +#ifdef CONFIG_TEE_HUKS_SUPPORT +#if defined(CONFIG_FACTORY_TEST_MODE) && defined(CONFIG_HILINK) && defined(CONFIG_HILINK_PKI_SUPPORT) + hks_handle_secure_pki_provision(); +#else + hks_handle_secure_call(); +#endif +#else + printf("receive tee irq\r\n"); +#endif +} + +hi_u32 hi_get_rf_xtal_compesation_param(rf_cfg_xtal_compesation *xtal_param) +{ + if (xtal_param == HI_NULL) { + return HI_ERR_FAILURE; + } + + return hi_factory_nv_read(INIT_CONFIG_XTAL_COMPESATION, (hi_void *)xtal_param, sizeof(rf_cfg_xtal_compesation), 0); +} + +hi_void hi_diag_register_wifi_log() +{ +#ifdef CONFIG_DIAG_SUPPORT + oam_log_hook_func log_hook = { + hi_diag_log_msg0, + hi_diag_log_msg1, + hi_diag_log_msg2, + hi_diag_log_msg3, + hi_diag_log_msg4, + hi_diag_log_msg_buffer + }; + oam_log_register_hook_func(&log_hook); +#endif +} + +hi_u32 hi_watchdog_set_timeout(hi_u32 timeout_ms) +{ + if (timeout_ms < HI_WDG_MIN_TIMEOUT) { + return HI_ERR_FAILURE; + } + g_auto_wdg_rst_sys_timeout = timeout_ms; + + hi_sal_wdg_clear(); + return HI_ERR_SUCCESS; +} + diff --git a/sdk_liteos/platform/system/cfg/sal_cfg.h b/sdk_liteos/platform/system/cfg/sal_cfg.h new file mode 100644 index 0000000000000000000000000000000000000000..aafbe7da4b170e16184876140f56a433ce6a0eed --- /dev/null +++ b/sdk_liteos/platform/system/cfg/sal_cfg.h @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __SAL_CFG_H__ +#define __SAL_CFG_H__ +#include +#include + +/* defined in tee_hks lib. */ +extern hi_void hks_handle_secure_call(void); +extern hi_void hks_handle_secure_pki_provision(void); + +#define INIT_CONFIG_XTAL_COMPESATION 1 + +typedef struct { + hi_s32 init_cfg_rf_high_temp_threshold; + hi_s32 init_cfg_rf_low_temp_threshold; + hi_s32 init_cfg_rf_ppm_compesation; +} rf_cfg_xtal_compesation; + +/* read rf xtal compesation from Factory NV */ +hi_u32 hi_get_rf_xtal_compesation_param(rf_cfg_xtal_compesation *rf_cfg_xtal_compesatioan); + +typedef hi_u32 (*oam_log_msg0_func)(hi_u32 msg_id, hi_u16 msg_level); +typedef hi_u32 (*oam_log_msg1_func)(hi_u32 msg_id, hi_u32 d0, hi_u16 msg_level); +typedef hi_u32 (*oam_log_msg2_func)(hi_u32 msg_id, hi_u32 d0, hi_u32 d1, hi_u16 msg_level); +typedef hi_u32 (*oam_log_msg3_func)(hi_u32 msg_id, hi_u32 d0, hi_u32 d1, hi_u32 d2, hi_u16 msg_level); +typedef hi_u32 (*oam_log_msg4_func)(hi_u32 msg_id, diag_log_msg log_msg, hi_u16 msg_level); +typedef hi_u32 (*oam_log_msg_buffer_func)(hi_u32 msg_id, hi_pvoid buffer, hi_u16 size, hi_u16 msg_level); + +typedef struct oam_log_hook_func_ { + oam_log_msg0_func oam_log_msg0; + oam_log_msg1_func oam_log_msg1; + oam_log_msg2_func oam_log_msg2; + oam_log_msg3_func oam_log_msg3; + oam_log_msg4_func oam_log_msg4; + oam_log_msg_buffer_func oam_log_msg_buffer; +}oam_log_hook_func; + +hi_void oam_log_register_hook_func(const oam_log_hook_func *hook_func); + +hi_void hi_diag_register_wifi_log(); + +#endif + diff --git a/sdk_liteos/platform/system/cpup/cpup_diag_dfx.h b/sdk_liteos/platform/system/cpup/cpup_diag_dfx.h new file mode 100644 index 0000000000000000000000000000000000000000..e6bb9ee3a2e727b60b454c38dbecaedf7be89073 --- /dev/null +++ b/sdk_liteos/platform/system/cpup/cpup_diag_dfx.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __CPUP_DIAG_DFX_H__ +#define __CPUP_DIAG_DFX_H__ +#include + +void cmd_get_cpup(int argc, unsigned char* argv[]); +#endif \ No newline at end of file diff --git a/sdk_liteos/platform/system/include/brain_pool_p256r1.h b/sdk_liteos/platform/system/include/brain_pool_p256r1.h new file mode 100644 index 0000000000000000000000000000000000000000..5662f20ab793ae8b69d0c83490680dedc6f42374 --- /dev/null +++ b/sdk_liteos/platform/system/include/brain_pool_p256r1.h @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __BRAIN_POOL_P256R1_H__ +#define __BRAIN_POOL_P256R1_H__ + +#include + +HI_EXTERN hi_cipher_ecc_param g_brain_pool_p256r1_verify; + +#endif diff --git a/sdk_liteos/platform/system/include/hi_nvm.h b/sdk_liteos/platform/system/include/hi_nvm.h new file mode 100644 index 0000000000000000000000000000000000000000..05db4544f25635eea23967ff1f4cc7cea214ae6c --- /dev/null +++ b/sdk_liteos/platform/system/include/hi_nvm.h @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __HI_NVM_H__ +#define __HI_NVM_H__ + +#include + +#define HNV_FILE_SIGNATURE hi_make_identifier('H', 'N', 'V', '$') +#define FNV_FILE_SIGNATURE hi_make_identifier('F', 'N', 'V', '#') + +#define FLASH_BLOCK_SIZE 0x1000 +#define HNV_NCRC_SIZE 8 +#define NV_TOTAL_MAX_NUM 255 +#define HNV_FAULT_TOLERANT_TIMES 3 + +#define HNV_MANAGE_FIXED_LEN 24 + +typedef struct _hi_nvm_manage_s_ { + hi_u32 magic; + hi_u32 crc; + hi_u8 ver; + hi_u8 head_len; + hi_u16 total_num; + hi_u32 seq; + hi_u32 ver_magic; + hi_u32 flash_size; + hi_u8 keep_id_range[2]; /* Reserved upg id, size:2 bytes, byte0:upper boundary, byte1:lower boundary */ + hi_u8 reserve[2]; /* Reserved 2 bytes */ + hi_u8 nv_item_data[0]; +} hi_nv_manage; + +typedef struct hi_nv_item_index_s_ { + hi_u8 nv_id; + hi_u8 nv_len; + hi_u16 nv_offset; +} hi_nv_item_index; + +typedef struct _hi_nv_ctrl_s_ { + hi_u32 base_addr; + hi_u32 block_size; + hi_u32 total_block_size; + hi_u32 current_addr; + hi_u32 seq; + hi_u32 sem_handle; + + hi_u8 init_flag; + hi_u8 reserve; + hi_u16 total_num; + hi_u32 ver_magic; + hi_nv_item_index* index; +} hi_nv_ctrl; + +typedef enum _hi_nv_type_e_ { + HI_TYPE_NV = 0, + HI_TYPE_FACTORY_NV, + HI_TYPE_TEMP, + HI_TYPE_NV_MAX, +} hi_nv_type; + +hi_u32 hi_nv_flush_keep_ids(hi_u8* addr, hi_u32 len); +hi_u32 hi_nv_block_write(hi_u8* nv_file, hi_u32 len, hi_u32 flag); + +#endif /* __HI_NVM_H__ */ \ No newline at end of file diff --git a/sdk_liteos/platform/system/include/sal_reset.h b/sdk_liteos/platform/system/include/sal_reset.h new file mode 100644 index 0000000000000000000000000000000000000000..c1deadcfbe558e21c5e5b9e0a009fba410819909 --- /dev/null +++ b/sdk_liteos/platform/system/include/sal_reset.h @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __SAL_RESET_H__ +#define __SAL_RESET_H__ + +#include +#include + +HI_CPP_START + +hi_void hi_reboot(hi_void); + +HI_CPP_END +#endif /* __SAL_RESET_H__ */ diff --git a/sdk_liteos/platform/system/module_config.mk b/sdk_liteos/platform/system/module_config.mk new file mode 100644 index 0000000000000000000000000000000000000000..1a1a7d28f825b1926bb4a1eb8bc24f9f78e779cb --- /dev/null +++ b/sdk_liteos/platform/system/module_config.mk @@ -0,0 +1,8 @@ +cfg_srcs := cfg +parttab_srcs := partition_table +upg_srcs := upg +CCFLAGS += -Werror -fsigned-char +CCFLAGS += -I$(MAIN_TOPDIR)/platform/system/include \ + -I$(MAIN_TOPDIR)/platform/system/upg \ + -I$(MAIN_TOPDIR)/platform/drivers/flash \ + -I$(MAIN_TOPDIR)/platform/os/Huawei_LiteOS/kernel/extended/include diff --git a/sdk_liteos/platform/system/partition_table/SConscript b/sdk_liteos/platform/system/partition_table/SConscript new file mode 100755 index 0000000000000000000000000000000000000000..b0e5f0e2b015ebbec8bd8a4344149640ab49ef09 --- /dev/null +++ b/sdk_liteos/platform/system/partition_table/SConscript @@ -0,0 +1,4 @@ +Import('env') + +objs = env.Object(Glob('*.c')) +Return('objs') diff --git a/sdk_liteos/platform/system/partition_table/flash_partition_table.c b/sdk_liteos/platform/system/partition_table/flash_partition_table.c new file mode 100644 index 0000000000000000000000000000000000000000..398834ba2348975031f3ee5f78d0f66b5f80b0d6 --- /dev/null +++ b/sdk_liteos/platform/system/partition_table/flash_partition_table.c @@ -0,0 +1,225 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include +#include + +#define FACTORY_NV_ADDR_REG (SYSCTRL_SC_GEN_REG3_REG) + +#define PRODUCT_CFG_DEFAULT_BOOT_ADDR 0x0 +#define PRODUCT_CFG_DEFAULT_FNV_ADDR 0x8000 +#define PRODUCT_CFG_DEFAULT_NORMAL_NV_ADDR 0xA000 +#define PRODUCT_CFG_DEFAULT_NORMAL_NV_BACKUP_ADDR 0xC000 +#define PRODUCT_CFG_DEFAULT_KERNEL_A_ADDR 0xD000 +#define PRODUCT_CFG_DEFAULT_KERNEL_B_ADDR 0xF1000 +#define PRODUCT_CFG_DEFAULT_HILINK_ADDR 0x1E3000 +#define PRODUCT_CFG_DEFAULT_FILE_SYSTEM_ADDR 0x1E5000 +#define PRODUCT_CFG_DEFAULT_USER_RESERVE_ADDR 0x1F0000 +#define PRODUCT_CFG_DEFAULT_HILINK_PKI_ADDR 0x1F5000 +#define PRODUCT_CFG_DEFAULT_CRASH_INFO_ADDR 0x1F7000 +#define PRODUCT_CFG_DEFAULT_BOOT_BACK_ADDR 0x1F8000 + +#define PRODUCT_CFG_DEFAULT_BOOT_SIZE 0x8000 /* 32K */ +#define PRODUCT_CFG_DEFAULT_FNV_SIZE 0x2000 /* 8K */ +#define PRODUCT_CFG_DEFAULT_NORMAL_NV_SIZE 0x2000 /* 8K */ +#define PRODUCT_CFG_DEFAULT_NORMAL_NV_BACKUP_SIZE 0x1000 /* 4K */ +#define PRODUCT_CFG_DEFAULT_KERNEL_A_SIZE 0xE4000 /* 912K */ +#define PRODUCT_CFG_DEFAULT_KERNEL_B_SIZE 0xF2000 /* 968K */ +#define PRODUCT_CFG_DEFAULT_HILINK_SIZE 0x2000 /* 8K */ +#define PRODUCT_CFG_DEFAULT_FILE_SYSTEM_SIZE 0xB000 /* 44K */ +#define PRODUCT_CFG_DEFAULT_USER_RESERVE_SIZE 0x5000 /* 20K */ +#define PRODUCT_CFG_DEFAULT_HILINK_PKI_SIZE 0x2000 /* 8K */ +#define PRODUCT_CFG_DEFAULT_CRASH_INFO_SIZE 0x1000 /* 4K */ +#define PRODUCT_CFG_DEFAULT_BOOT_BACK_SIZE 0x8000 /* 32K */ + +#define PRODUCT_CFG_DEFAULT_FACTORY_BIN_ADDR 0x14D000 /* factory bin start addr */ +#define PRODUCT_CFG_DEFAULT_FACTORY_BIN_SIZE 0x96000 /* factory bin size */ + +static hi_flash_partition_table g_partition_table; +hi_flash_partition_table* hi_get_partition_table(hi_void) +{ + return &g_partition_table; +} + +hi_u32 hi_flash_partition_init(hi_void) +{ + hi_flash_partition_table* table = hi_get_partition_table(); +#ifndef CONFIG_QUICK_SEND_MODE + hi_u32 ret = hi_factory_nv_read(HI_NV_FTM_FLASH_PARTIRION_TABLE_ID, table, sizeof(hi_flash_partition_table), 0); +#else + hi_u32 ret = HI_ERR_FAILURE; +#endif + if (ret != HI_ERR_SUCCESS) { /* read nv fail, set flash partition table default value */ + table->table[HI_FLASH_PARTITON_BOOT].addr = PRODUCT_CFG_DEFAULT_BOOT_ADDR; + table->table[HI_FLASH_PARTITON_BOOT].size = PRODUCT_CFG_DEFAULT_BOOT_SIZE; + table->table[HI_FLASH_PARTITON_FACTORY_NV].addr = PRODUCT_CFG_DEFAULT_FNV_ADDR; + table->table[HI_FLASH_PARTITON_FACTORY_NV].size = PRODUCT_CFG_DEFAULT_FNV_SIZE; + table->table[HI_FLASH_PARTITON_NORMAL_NV].addr = PRODUCT_CFG_DEFAULT_NORMAL_NV_ADDR; + table->table[HI_FLASH_PARTITON_NORMAL_NV].size = PRODUCT_CFG_DEFAULT_NORMAL_NV_SIZE; + table->table[HI_FLASH_PARTITON_NORMAL_NV_BACKUP].addr = PRODUCT_CFG_DEFAULT_NORMAL_NV_BACKUP_ADDR; + table->table[HI_FLASH_PARTITON_NORMAL_NV_BACKUP].size = PRODUCT_CFG_DEFAULT_NORMAL_NV_BACKUP_SIZE; + table->table[HI_FLASH_PARTITON_KERNEL_A].addr = PRODUCT_CFG_DEFAULT_KERNEL_A_ADDR; + table->table[HI_FLASH_PARTITON_KERNEL_A].size = PRODUCT_CFG_DEFAULT_KERNEL_A_SIZE; + table->table[HI_FLASH_PARTITON_KERNEL_B].addr = PRODUCT_CFG_DEFAULT_KERNEL_B_ADDR; + table->table[HI_FLASH_PARTITON_KERNEL_B].size = PRODUCT_CFG_DEFAULT_KERNEL_B_SIZE; + table->table[HI_FLASH_PARTITON_HILINK].addr = PRODUCT_CFG_DEFAULT_HILINK_ADDR; + table->table[HI_FLASH_PARTITON_HILINK].size = PRODUCT_CFG_DEFAULT_HILINK_SIZE; + table->table[HI_FLASH_PARTITON_FILE_SYSTEM].addr = PRODUCT_CFG_DEFAULT_FILE_SYSTEM_ADDR; + table->table[HI_FLASH_PARTITON_FILE_SYSTEM].size = PRODUCT_CFG_DEFAULT_FILE_SYSTEM_SIZE; + table->table[HI_FLASH_PARTITON_USR_RESERVE].addr = PRODUCT_CFG_DEFAULT_USER_RESERVE_ADDR; + table->table[HI_FLASH_PARTITON_USR_RESERVE].size = PRODUCT_CFG_DEFAULT_USER_RESERVE_SIZE; + table->table[HI_FLASH_PARTITON_HILINK_PKI].addr = PRODUCT_CFG_DEFAULT_HILINK_PKI_ADDR; + table->table[HI_FLASH_PARTITON_HILINK_PKI].size = PRODUCT_CFG_DEFAULT_HILINK_PKI_SIZE; + table->table[HI_FLASH_PARTITON_CRASH_INFO].addr = PRODUCT_CFG_DEFAULT_CRASH_INFO_ADDR; + table->table[HI_FLASH_PARTITON_CRASH_INFO].size = PRODUCT_CFG_DEFAULT_CRASH_INFO_SIZE; + table->table[HI_FLASH_PARTITON_BOOT_BACK].addr = PRODUCT_CFG_DEFAULT_BOOT_BACK_ADDR; + table->table[HI_FLASH_PARTITON_BOOT_BACK].size = PRODUCT_CFG_DEFAULT_BOOT_BACK_SIZE; + } +#ifdef CONFIG_QUICK_SEND_MODE + ret = HI_ERR_SUCCESS; +#endif + return ret; +} + +hi_u32 hi_get_hilink_partition_table(hi_u32 *addr, hi_u32 *size) +{ + if (addr == HI_NULL || size == HI_NULL) { + return HI_ERR_FAILURE; + } + + hi_flash_partition_table* flash_partion_table = hi_get_partition_table(); + *addr = flash_partion_table->table[HI_FLASH_PARTITON_HILINK].addr; + *size = flash_partion_table->table[HI_FLASH_PARTITON_HILINK].size; + + return HI_ERR_SUCCESS; +} + +hi_u32 hi_get_hilink_pki_partition_table(hi_u32 *addr, hi_u32 *size) +{ + if (addr == HI_NULL || size == HI_NULL) { + return HI_ERR_FAILURE; + } + + hi_flash_partition_table* flash_partion_table = hi_get_partition_table(); + *addr = flash_partion_table->table[HI_FLASH_PARTITON_HILINK_PKI].addr; + *size = flash_partion_table->table[HI_FLASH_PARTITON_HILINK_PKI].size; + + return HI_ERR_SUCCESS; +} + +hi_u32 hi_get_crash_partition_table(hi_u32 *addr, hi_u32 *size) +{ + if (addr == HI_NULL || size == HI_NULL) { + return HI_ERR_FAILURE; + } + + hi_flash_partition_table* flash_partion_table = hi_get_partition_table(); + *addr = flash_partion_table->table[HI_FLASH_PARTITON_CRASH_INFO].addr; + *size = flash_partion_table->table[HI_FLASH_PARTITON_CRASH_INFO].size; + + return HI_ERR_SUCCESS; +} + +hi_u32 hi_get_fs_partition_table(hi_u32 *addr, hi_u32 *size) +{ + if (addr == HI_NULL || size == HI_NULL) { + return HI_ERR_FAILURE; + } + + hi_flash_partition_table* flash_partion_table = hi_get_partition_table(); + *addr = flash_partion_table->table[HI_FLASH_PARTITON_FILE_SYSTEM].addr; + *size = flash_partion_table->table[HI_FLASH_PARTITON_FILE_SYSTEM].size; + + return HI_ERR_SUCCESS; +} + +hi_u32 hi_get_normal_nv_partition_table(hi_u32 *addr, hi_u32 *size) +{ + if (addr == HI_NULL || size == HI_NULL) { + return HI_ERR_FAILURE; + } + + hi_flash_partition_table* flash_partion_table = hi_get_partition_table(); + *addr = flash_partion_table->table[HI_FLASH_PARTITON_NORMAL_NV].addr; + *size = flash_partion_table->table[HI_FLASH_PARTITON_NORMAL_NV].size; + + return HI_ERR_SUCCESS; +} + +hi_u32 hi_get_normal_nv_backup_partition_table(hi_u32 *addr, hi_u32 *size) +{ + if (addr == HI_NULL || size == HI_NULL) { + return HI_ERR_FAILURE; + } + + hi_flash_partition_table* flash_partion_table = hi_get_partition_table(); + *addr = flash_partion_table->table[HI_FLASH_PARTITON_NORMAL_NV_BACKUP].addr; + *size = flash_partion_table->table[HI_FLASH_PARTITON_NORMAL_NV_BACKUP].size; + + return HI_ERR_SUCCESS; +} + +hi_u32 hi_get_usr_partition_table(hi_u32 *addr, hi_u32 *size) +{ + if (addr == HI_NULL || size == HI_NULL) { + return HI_ERR_FAILURE; + } + + hi_flash_partition_table* flash_partion_table = hi_get_partition_table(); + *addr = flash_partion_table->table[HI_FLASH_PARTITON_USR_RESERVE].addr; + *size = flash_partion_table->table[HI_FLASH_PARTITON_USR_RESERVE].size; + + return HI_ERR_SUCCESS; +} + +hi_u32 hi_get_factory_bin_partition_table(hi_u32 *addr, hi_u32 *size) +{ + if (addr == HI_NULL || size == HI_NULL) { + return HI_ERR_FAILURE; + } + + *addr = PRODUCT_CFG_DEFAULT_FACTORY_BIN_ADDR; + *size = PRODUCT_CFG_DEFAULT_FACTORY_BIN_SIZE; + + return HI_ERR_SUCCESS; +} + +hi_u32 hi_nv_restore_by_backup(hi_void) +{ + hi_u32 backup_nv_addr = 0; + hi_u32 backup_nv_size = 0; + hi_u32 nv_addr = 0; + hi_u32 nv_size = 0; + + hi_u32 ret = hi_get_normal_nv_backup_partition_table(&backup_nv_addr, &backup_nv_size); + ret |= hi_get_normal_nv_partition_table(&nv_addr, &nv_size); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + if (nv_size / backup_nv_size != 0x2) { + return HI_ERR_FAILURE; + } + + ret = hi_flash_write(nv_addr, backup_nv_size, (const hi_u8 *)(HI_FLASH_BASE + backup_nv_addr), HI_TRUE); + ret |= hi_flash_write(nv_addr + backup_nv_size, backup_nv_size, + (const hi_u8 *)(HI_FLASH_BASE + backup_nv_addr), HI_TRUE); + + return ret; +} diff --git a/sdk_liteos/platform/system/upg/SConscript b/sdk_liteos/platform/system/upg/SConscript new file mode 100755 index 0000000000000000000000000000000000000000..b0e5f0e2b015ebbec8bd8a4344149640ab49ef09 --- /dev/null +++ b/sdk_liteos/platform/system/upg/SConscript @@ -0,0 +1,4 @@ +Import('env') + +objs = env.Object(Glob('*.c')) +Return('objs') diff --git a/sdk_liteos/platform/system/upg/kernel_crypto.c b/sdk_liteos/platform/system/upg/kernel_crypto.c new file mode 100644 index 0000000000000000000000000000000000000000..d6d7d678e9d05efee79bf876c222eaee2eb54d52 --- /dev/null +++ b/sdk_liteos/platform/system/upg/kernel_crypto.c @@ -0,0 +1,692 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef CONFIG_FLASH_ENCRYPT_SUPPORT +#include +#include +#include +#include +#include +#include +#include +#include +#include "upg_common.h" +#include "kernel_crypto.h" + +#define SFC_BUFFER_BASE_ADDRESS 0x400000 + +static const hi_u8 g_upg_file_magic[IV_BYTE_LENGTH] = { + 0xE4, 0xEE, 0x10, 0x0E, 0x43, 0x4D, 0x94, 0x24, + 0xC7, 0x54, 0x6D, 0xFB, 0x15, 0xA1, 0x46, 0x97 +}; + +encrypt_ctx g_encrypt_param = {0}; + +encrypt_ctx *encrypt_get_ctx(hi_void) +{ + return &g_encrypt_param; +} + +hi_void crypto_clear_content(hi_u8 *content, hi_u32 content_len) +{ + if ((content == HI_NULL) || (content_len == 0)) { + return; + } + + (hi_void)memset_s(content, content_len, 0x0, content_len); +} + +hi_u32 crypto_content_id(encrypt_ctx *cfg, crypto_workkey_partition *content, crypto_workkey_partition *content_bak) +{ + hi_flash_partition_table *partition = hi_get_partition_table(); + hi_u32 kernel_a = partition->table[HI_FLASH_PARTITON_KERNEL_A].addr; + hi_u32 kernel_b = partition->table[HI_FLASH_PARTITON_KERNEL_B].addr; + if (cfg->kernel_start == kernel_a) { + *content = CRYPTO_WORKKEY_KERNEL_A; + *content_bak = CRYPTO_WORKKEY_KERNEL_A_BACKUP; + } else if (cfg->kernel_start == kernel_b) { + *content = CRYPTO_WORKKEY_KERNEL_B; + *content_bak = CRYPTO_WORKKEY_KERNEL_B_BACKUP; + } else { + return HI_ERR_FLASH_CRYPTO_KERNEL_ADDR_ERR; + } + + return HI_ERR_SUCCESS; +} + +static hi_u32 crypto_load_salt(crypto_workkey_partition part, hi_flash_crypto_content *key_content) +{ + hi_u32 ret = HI_ERR_SUCCESS; + hi_u8 salt_e[ROOT_SALT_LENGTH] = { 0 }; + + (hi_void) memset_s(salt_e, sizeof(salt_e), 0x0, ROOT_SALT_LENGTH); + if (part == CRYPTO_WORKKEY_KERNEL_A) { + ret = hi_factory_nv_read(HI_NV_FTM_KERNELA_WORK_ID, key_content, sizeof(hi_flash_crypto_content), 0); + if (ret != HI_ERR_SUCCESS) { + goto fail; + } + } else if (part == CRYPTO_WORKKEY_KERNEL_A_BACKUP) { + ret = hi_factory_nv_read(HI_NV_FTM_BACKUP_KERNELA_WORK_ID, key_content, sizeof(hi_flash_crypto_content), 0); + if (ret != HI_ERR_SUCCESS) { + goto fail; + } + } + + if (memcmp(key_content->root_salt, salt_e, ROOT_SALT_LENGTH) == HI_ERR_SUCCESS) { + ret = HI_ERR_FLASH_CRYPTO_ROOT_SALT_EMPTY_ERR; + goto fail; + } +fail: + return ret; +} + +static hi_u32 crypto_get_root_salt(hi_flash_crypto_content *key_content) +{ + hi_u32 ret = crypto_load_salt(CRYPTO_WORKKEY_KERNEL_A, key_content); + if (ret != HI_ERR_SUCCESS) { + ret = crypto_load_salt(CRYPTO_WORKKEY_KERNEL_A_BACKUP, key_content); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + } + + return HI_ERR_SUCCESS; +} + +static hi_u32 crypto_prepare(hi_flash_crypto_content *save_content) +{ + hi_u32 ret; + hi_u8 rootkey_iv[ROOTKEY_IV_BYTE_LENGTH]; + hi_cipher_kdf_ctrl ctrl; + + ret = hi_cipher_init(); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + ret = crypto_get_root_salt(save_content); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + ret = memcpy_s(rootkey_iv, sizeof(rootkey_iv), save_content->root_salt, ROOT_SALT_LENGTH); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + ctrl.salt = rootkey_iv; + ctrl.salt_len = sizeof(rootkey_iv); + ctrl.kdf_cnt = ENCRYPT_KDF_ITERATION_CNT; + ctrl.kdf_mode = HI_CIPHER_SSS_KDF_KEY_STORAGE; + return hi_cipher_kdf_key_derive(&ctrl); +} + +static hi_void crpto_set_aes_ctrl_default_value(hi_cipher_aes_ctrl *aes_ctrl) +{ + if (aes_ctrl == HI_NULL) { + return; + } + aes_ctrl->random_en = HI_FALSE; + aes_ctrl->key_from = HI_CIPHER_AES_KEY_FROM_CPU; + aes_ctrl->work_mode = HI_CIPHER_AES_WORK_MODE_CBC; + aes_ctrl->key_len = HI_CIPHER_AES_KEY_LENGTH_256BIT; +} + +static hi_u32 crypto_decrypt_hash(hi_flash_crypto_content *key_content) +{ + hi_u32 ret; + hi_u32 content_size = (hi_u32)sizeof(hi_flash_crypto_content); + + hi_flash_crypto_content *content_tmp = (hi_flash_crypto_content *)hi_malloc(HI_MOD_ID_CRYPTO, content_size); + if (content_tmp == HI_NULL) { + return HI_ERR_FLASH_CRYPTO_MALLOC_FAIL; + } + + ret = (hi_u32)memcpy_s(content_tmp, content_size, key_content, content_size); + if (ret != EOK) { + goto fail; + } + + hi_cipher_aes_ctrl aes_ctrl = { + .random_en = HI_FALSE, + .key_from = HI_CIPHER_AES_KEY_FROM_KDF, + .work_mode = HI_CIPHER_AES_WORK_MODE_CBC, + .key_len = HI_CIPHER_AES_KEY_LENGTH_256BIT, + }; + + ret = (hi_u32)memcpy_s(aes_ctrl.iv, sizeof(aes_ctrl.iv), content_tmp->iv_nv, IV_BYTE_LENGTH); + if (ret != EOK) { + goto fail; + } + ret = hi_cipher_aes_config(&aes_ctrl); + if (ret != HI_ERR_SUCCESS) { + goto crypto_fail; + } + ret = hi_cipher_aes_crypto((uintptr_t)content_tmp->iv_content, (uintptr_t)key_content->iv_content, + content_size - ROOT_SALT_LENGTH - IV_BYTE_LENGTH, HI_FALSE); + if (ret != HI_ERR_SUCCESS) { + goto crypto_fail; + } + +crypto_fail: + (hi_void) hi_cipher_aes_destroy_config(); +fail: + crypto_clear_content((hi_u8 *)content_tmp, content_size); + crypto_mem_free(content_tmp); + return ret; +} + +static hi_u32 crypto_encrypt_hash(hi_flash_crypto_content *key_content) +{ + hi_cipher_aes_ctrl aes_ctrl; + hi_u32 content_size = (hi_u32)sizeof(hi_flash_crypto_content); + hi_u32 encrypt_size = content_size - ROOT_SALT_LENGTH - IV_BYTE_LENGTH; + + hi_flash_crypto_content *data_tmp = (hi_flash_crypto_content *)hi_malloc(HI_MOD_ID_CRYPTO, content_size); + if (data_tmp == HI_NULL) { + return HI_ERR_FLASH_CRYPTO_MALLOC_FAIL; + } + + hi_u32 ret = (hi_u32)memcpy_s(aes_ctrl.iv, sizeof(aes_ctrl.iv), key_content->iv_nv, IV_BYTE_LENGTH); + if (ret != EOK) { + goto fail; + } + + aes_ctrl.random_en = HI_FALSE; + aes_ctrl.key_from = HI_CIPHER_AES_KEY_FROM_KDF; + aes_ctrl.work_mode = HI_CIPHER_AES_WORK_MODE_CBC; + aes_ctrl.key_len = HI_CIPHER_AES_KEY_LENGTH_256BIT; + ret = hi_cipher_aes_config(&aes_ctrl); + if (ret != HI_ERR_SUCCESS) { + goto crypto_fail; + } + ret = hi_cipher_aes_crypto((hi_u32)(uintptr_t)key_content->iv_content, (hi_u32)(uintptr_t)(data_tmp->iv_content), + encrypt_size, HI_TRUE); + if (ret != HI_ERR_SUCCESS) { + goto crypto_fail; + } + + ret = (hi_u32)memcpy_s(key_content->iv_content, encrypt_size, data_tmp->iv_content, encrypt_size); + +crypto_fail: + (hi_void) hi_cipher_aes_destroy_config(); +fail: + crypto_clear_content((hi_u8 *)data_tmp, content_size); + crypto_mem_free(data_tmp); + return ret; +} + +static hi_u32 crypto_load_key_content(crypto_workkey_partition part, hi_flash_crypto_content *key_content) +{ + hi_u32 ret = HI_ERR_SUCCESS; + hi_u8 hash[SHA_256_LENGTH]; + hi_u8 key_e[KEY_BYTE_LENGTH] = { 0 }; + + (hi_void) memset_s(key_e, sizeof(key_e), 0x0, KEY_BYTE_LENGTH); + if (part == CRYPTO_WORKKEY_KERNEL_A) { + ret = hi_factory_nv_read(HI_NV_FTM_KERNELA_WORK_ID, key_content, sizeof(hi_flash_crypto_content), 0); + if (ret != HI_ERR_SUCCESS) { + goto fail; + } + } else if (part == CRYPTO_WORKKEY_KERNEL_A_BACKUP) { + ret = hi_factory_nv_read(HI_NV_FTM_BACKUP_KERNELA_WORK_ID, key_content, sizeof(hi_flash_crypto_content), 0); + if (ret != HI_ERR_SUCCESS) { + goto fail; + } + } else if (part == CRYPTO_WORKKEY_KERNEL_B) { + ret = hi_factory_nv_read(HI_NV_FTM_KERNELB_WORK_ID, key_content, sizeof(hi_flash_crypto_content), 0); + if (ret != HI_ERR_SUCCESS) { + goto fail; + } + } else if (part == CRYPTO_WORKKEY_KERNEL_B_BACKUP) { + ret = hi_factory_nv_read(HI_NV_FTM_BACKUP_KERNELB_WORK_ID, key_content, sizeof(hi_flash_crypto_content), 0); + if (ret != HI_ERR_SUCCESS) { + goto fail; + } + } + + if (memcmp(key_content->work_text, key_e, KEY_BYTE_LENGTH) == HI_ERR_SUCCESS) { + ret = HI_ERR_FLASH_CRYPTO_KEY_EMPTY_ERR; + goto fail; + } + + ret = crypto_decrypt_hash(key_content); + if (ret != HI_ERR_SUCCESS) { + goto fail; + } + + ret = hi_cipher_hash_sha256((uintptr_t)(key_content->root_salt), sizeof(hi_flash_crypto_content) - SHA_256_LENGTH, + hash, SHA_256_LENGTH); + if (ret != HI_ERR_SUCCESS) { + goto fail; + } + if (memcmp(key_content->content_sh256, hash, SHA_256_LENGTH) != HI_ERR_SUCCESS) { + ret = HI_ERR_FLASH_CRYPTO_KEY_INVALID_ERR; + goto fail; + } +fail: + return ret; +} + +static hi_u32 crypto_save_work_key(crypto_workkey_partition part, hi_flash_crypto_content *key_content) +{ + hi_u32 ret; + hi_u32 content_size = (hi_u32)sizeof(hi_flash_crypto_content); + hi_flash_crypto_content *content_tmp = (hi_flash_crypto_content *)hi_malloc(HI_MOD_ID_CRYPTO, content_size); + if (content_tmp == HI_NULL) { + return HI_ERR_FLASH_CRYPTO_MALLOC_FAIL; + } + + ret = (hi_u32)memcpy_s(content_tmp, content_size, key_content, content_size); + if (ret != EOK) { + goto fail; + } + + /* Encrypt,then save to factory NV. */ + ret = crypto_encrypt_hash(content_tmp); + if (ret != HI_ERR_SUCCESS) { + goto fail; + } + + if ((hi_u32)part & CRYPTO_WORKKEY_KERNEL_A) { + ret = hi_factory_nv_write(HI_NV_FTM_KERNELA_WORK_ID, content_tmp, content_size, 0); + if (ret != HI_ERR_SUCCESS) { + ret = HI_ERR_FLASH_CRYPTO_KEY_SAVE_ERR; + goto fail; + } + } + if ((hi_u32)part & CRYPTO_WORKKEY_KERNEL_A_BACKUP) { + ret = hi_factory_nv_write(HI_NV_FTM_BACKUP_KERNELA_WORK_ID, content_tmp, content_size, 0); + if (ret != HI_ERR_SUCCESS) { + ret = HI_ERR_FLASH_CRYPTO_KEY_SAVE_ERR; + goto fail; + } + } + + if ((hi_u32)part & CRYPTO_WORKKEY_KERNEL_B) { + ret = hi_factory_nv_write(HI_NV_FTM_KERNELB_WORK_ID, content_tmp, content_size, 0); + if (ret != HI_ERR_SUCCESS) { + ret = HI_ERR_FLASH_CRYPTO_KEY_SAVE_ERR; + goto fail; + } + } + if ((hi_u32)part & CRYPTO_WORKKEY_KERNEL_B_BACKUP) { + ret = hi_factory_nv_write(HI_NV_FTM_BACKUP_KERNELB_WORK_ID, content_tmp, content_size, 0); + if (ret != HI_ERR_SUCCESS) { + ret = HI_ERR_FLASH_CRYPTO_KEY_SAVE_ERR; + goto fail; + } + } + +fail: + crypto_clear_content((hi_u8 *)content_tmp, content_size); + crypto_mem_free(content_tmp); + return ret; +} + +static hi_u32 crypto_gen_key_content(hi_flash_crypto_content *key_content) +{ + hi_u8 salt[IV_BYTE_LENGTH]; + hi_u8 kdf_key[KEY_BYTE_LENGTH]; + hi_cipher_kdf_ctrl ctrl; + + (hi_void)hi_cipher_trng_get_random_bytes(salt, IV_BYTE_LENGTH); + (hi_void)hi_cipher_trng_get_random_bytes(kdf_key, KEY_BYTE_LENGTH); + (hi_void)hi_cipher_trng_get_random_bytes(key_content->iv_nv, IV_BYTE_LENGTH); + (hi_void)hi_cipher_trng_get_random_bytes(key_content->iv_content, IV_BYTE_LENGTH); + + if ((hi_u32)memcpy_s(ctrl.key, sizeof(ctrl.key), kdf_key, sizeof(kdf_key)) != EOK) { + return HI_ERR_FAILURE; + } + ctrl.salt = salt; + ctrl.salt_len = sizeof(salt); + ctrl.kdf_cnt = ENCRYPT_KDF_ITERATION_CNT; + ctrl.kdf_mode = HI_CIPHER_SSS_KDF_KEY_DEVICE; /* In this mode, user should provide root key. */ + if (hi_cipher_kdf_key_derive(&ctrl) != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + + if (memcpy_s(key_content->work_text, KEY_BYTE_LENGTH, ctrl.result, sizeof(ctrl.result)) != EOK) { + return HI_ERR_FAILURE; + } + + if (hi_cipher_hash_sha256((uintptr_t)(key_content->root_salt), sizeof(hi_flash_crypto_content) - SHA_256_LENGTH, + key_content->content_sh256, SHA_256_LENGTH) != HI_ERR_SUCCESS) { + return HI_ERR_FAILURE; + } + + return HI_ERR_SUCCESS; +} + +static hi_u32 crypto_decrypt_kernel(hi_flash_crypto_content *content, encrypt_ctx *para) +{ + hi_u32 ret; + hi_cipher_aes_ctrl aes_ctrl; + hi_u8 *fw_raw_data = para->raw_buf; + + ret = (hi_u32)memcpy_s(aes_ctrl.key, sizeof(aes_ctrl.key), content->work_text, KEY_BYTE_LENGTH); + if (ret != HI_ERR_SUCCESS) { + goto fail; + } + + ret = (hi_u32)memcpy_s(aes_ctrl.iv, sizeof(aes_ctrl.iv), content->iv_content, IV_BYTE_LENGTH); + if (ret != HI_ERR_SUCCESS) { + goto fail; + } + + crpto_set_aes_ctrl_default_value(&aes_ctrl); + ret = hi_cipher_aes_config(&aes_ctrl); + if (ret != HI_ERR_SUCCESS) { + goto fail; + } + + ret = hi_cipher_aes_crypto(para->kernel_start + para->encrypt_offset + SFC_BUFFER_BASE_ADDRESS, + (uintptr_t)fw_raw_data, para->encrypt_size, HI_FALSE); + if (ret != HI_ERR_SUCCESS) { + goto crypto_fail; + } + +crypto_fail: + (hi_void) hi_cipher_aes_destroy_config(); +fail: + return ret; +} + +hi_u32 crypto_decrypt(encrypt_ctx *para) +{ + hi_bool is_backup_content = HI_FALSE; + crypto_workkey_partition werk_content; + crypto_workkey_partition werk_content_bak; + hi_u32 ret = crypto_content_id(para, &werk_content, &werk_content_bak); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + hi_flash_crypto_content *key_content = (hi_flash_crypto_content *)hi_malloc(HI_MOD_ID_CRYPTO, + sizeof(hi_flash_crypto_content)); + if (key_content == HI_NULL) { + return HI_ERR_FLASH_CRYPTO_PREPARE_ERR; + } + + ret = crypto_prepare(key_content); + if (ret != HI_ERR_SUCCESS) { + crypto_clear_content((hi_u8 *)key_content, (hi_u32)sizeof(hi_flash_crypto_content)); + crypto_mem_free(key_content); + return HI_ERR_FLASH_CRYPTO_PREPARE_ERR; + } + + ret = crypto_load_key_content(werk_content, key_content); + if (ret != HI_ERR_SUCCESS) { + ret = crypto_load_key_content(werk_content_bak, key_content); + if (ret != HI_ERR_SUCCESS) { + goto fail; + } else { + ret = crypto_save_work_key(werk_content, key_content); + if (ret != HI_ERR_SUCCESS) { + goto fail; + } + is_backup_content = HI_TRUE; + } + } + + ret = crypto_decrypt_kernel(key_content, para); + if ((ret != HI_ERR_SUCCESS) && (is_backup_content == HI_FALSE)) { + ret = crypto_load_key_content(werk_content_bak, key_content); + if (ret != HI_ERR_SUCCESS) { + goto fail; + } + ret = crypto_decrypt_kernel(key_content, para); + if (ret != HI_ERR_SUCCESS) { + ret = HI_ERR_FLASH_CRYPTO_DATA_DECRYPT_ERR; + goto fail; + } + } +fail: + crypto_clear_content((hi_u8 *)key_content, (hi_u32)sizeof(hi_flash_crypto_content)); + crypto_mem_free(key_content); + return ret; +} + +static hi_u32 crypto_encrypt_data(hi_flash_crypto_content *new_content, encrypt_ctx *para) +{ + hi_u32 ret = HI_ERR_FAILURE; + hi_cipher_aes_ctrl aes_ctrl; + + hi_u8 *fw_cyp_data = hi_malloc(HI_MOD_ID_CRYPTO, para->encrypt_size); + if (fw_cyp_data == HI_NULL) { + return HI_ERR_FLASH_CRYPTO_PREPARE_ERR; + } + + if (memcpy_s(aes_ctrl.key, sizeof(aes_ctrl.key), new_content->work_text, KEY_BYTE_LENGTH) != EOK) { + goto fail; + } + + if (memcpy_s(aes_ctrl.iv, sizeof(aes_ctrl.iv), new_content->iv_content, IV_BYTE_LENGTH) != EOK) { + goto fail; + } + + crpto_set_aes_ctrl_default_value(&aes_ctrl); + ret = hi_cipher_aes_config(&aes_ctrl); + if (ret != HI_ERR_SUCCESS) { + goto fail; + } + + ret = hi_cipher_aes_crypto((uintptr_t)(para->raw_buf), (uintptr_t)fw_cyp_data, para->encrypt_size, HI_TRUE); + (hi_void) hi_cipher_aes_destroy_config(); + if (ret != HI_ERR_SUCCESS) { + goto fail; + } + + ret = hi_flash_write(para->kernel_start + para->encrypt_offset, para->encrypt_size, fw_cyp_data, HI_TRUE); + if (ret != HI_ERR_SUCCESS) { + goto fail; + } + +fail: + crypto_mem_free(fw_cyp_data); + return ret; +} + +hi_u32 encrypt_check_start_addr(hi_u32 offset_addr) +{ + hi_flash_partition_table *partition = hi_get_partition_table(); + hi_u32 kernel_a = partition->table[HI_FLASH_PARTITON_KERNEL_A].addr; + hi_u32 kernel_b = partition->table[HI_FLASH_PARTITON_KERNEL_B].addr; + + if ((offset_addr != kernel_a) && (offset_addr != kernel_b)) { + return HI_ERR_FLASH_CRYPTO_INVALID_PARAM; + } + + return HI_ERR_SUCCESS; +} + +hi_u32 encrypt_upg_data(encrypt_ctx *para) +{ + hi_u32 ret; + crypto_workkey_partition werk_content; + crypto_workkey_partition werk_content_bak; + ret = crypto_content_id(para, &werk_content, &werk_content_bak); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + hi_flash_crypto_content *new_content = (hi_flash_crypto_content *)hi_malloc(HI_MOD_ID_CRYPTO, + sizeof(hi_flash_crypto_content)); + if (new_content == HI_NULL) { + return HI_ERR_FLASH_CRYPTO_PREPARE_ERR; + } + + ret = crypto_prepare(new_content); + if (ret != HI_ERR_SUCCESS) { + crypto_clear_content((hi_u8 *)new_content, (hi_u32)sizeof(hi_flash_crypto_content)); + crypto_mem_free(new_content); + return HI_ERR_FLASH_CRYPTO_PREPARE_ERR; + } + + ret = crypto_gen_key_content(new_content); + if (ret != HI_ERR_SUCCESS) { + goto fail; + } + + ret = crypto_save_work_key(werk_content, new_content); + if (ret != HI_ERR_SUCCESS) { + goto fail; + } + + ret = crypto_encrypt_data(new_content, para); + if (ret != HI_ERR_SUCCESS) { + goto fail; + } + + ret = crypto_save_work_key(werk_content_bak, new_content); + if (ret != HI_ERR_SUCCESS) { + } + +fail: + crypto_clear_content((hi_u8 *)new_content, (hi_u32)sizeof(hi_flash_crypto_content)); + crypto_mem_free(new_content); + return ret; +} + +hi_u32 crypto_init_param(encrypt_ctx *para, uintptr_t kernel_start) +{ + hi_u32 ret; + + hi_upg_head *upg_head = (hi_upg_head *)hi_malloc(HI_MOD_ID_CRYPTO, sizeof(hi_upg_head)); + if (upg_head == HI_NULL) { + return HI_ERR_UPG_CRYPTO_PREPARE_ERR; + } + ret = hi_flash_read(kernel_start, sizeof(hi_upg_head), (hi_u8 *)upg_head); + if (ret != HI_ERR_SUCCESS) { + crypto_print("[%s]get upg head addr:0x%x ret:0x%x \r\n", __FUNCTION__, kernel_start, ret); + goto fail; + } + + para->kernel_start = kernel_start; + para->encrypt_offset = sizeof(hi_upg_file_head); + para->encrypt_size = CRYPTO_KERNEL_LENGTH; + ret = (hi_u32)memcpy_s(para->upg_salt, IV_BYTE_LENGTH, upg_head->common.aes_key, IV_BYTE_LENGTH); + if (ret != EOK) { + goto fail; + } + ret = (hi_u32)memcpy_s(para->upg_iv, IV_BYTE_LENGTH, upg_head->common.aes_iv, IV_BYTE_LENGTH); + if (ret != EOK) { + goto fail; + } + para->raw_buf = (hi_u8 *)hi_malloc(0, para->encrypt_size); + if (para->raw_buf == HI_NULL) { + ret = HI_ERR_UPG_CRYPTO_PREPARE_ERR; + goto fail; + } + +fail: + crypto_mem_free(upg_head); + return ret; +} + +hi_u32 crypto_upg_file_prepare(encrypt_ctx *para) +{ + hi_u32 ret; + hi_cipher_kdf_ctrl ctrl; + hi_u8 salt[ROOTKEY_IV_BYTE_LENGTH] = {0}; + + ret = (hi_u32)memcpy_s((hi_void *)salt, sizeof(salt), (hi_void *)(para->upg_salt), IV_BYTE_LENGTH); + if (ret != EOK) { + return ret; + } + + ret = (hi_u32)memcpy_s((hi_void *)(salt + IV_BYTE_LENGTH), sizeof(salt) - IV_BYTE_LENGTH, + (hi_void *)g_upg_file_magic, IV_BYTE_LENGTH); + if (ret != EOK) { + return ret; + } + + ctrl.salt = salt; + ctrl.salt_len = ROOTKEY_IV_BYTE_LENGTH; + ctrl.kdf_cnt = ENCRYPT_KDF_ITERATION_CNT; + ctrl.kdf_mode = HI_CIPHER_SSS_KDF_KEY_STORAGE; + + ret = hi_cipher_kdf_key_derive(&ctrl); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + return HI_ERR_SUCCESS; +} + +hi_u32 crypto_upg_file_decrypt(encrypt_ctx *para) +{ + hi_u32 ret; + hi_cipher_aes_ctrl aes_ctrl; + hi_u8 *fw_raw_data = para->raw_buf; + + ret = crypto_upg_file_prepare(para); + if (ret != HI_ERR_SUCCESS) { + return HI_ERR_UPG_CRYPTO_PREPARE_ERR; + } + + ret = (hi_u32)memcpy_s(aes_ctrl.iv, sizeof(aes_ctrl.iv), para->upg_iv, IV_BYTE_LENGTH); + if (ret != HI_ERR_SUCCESS) { + goto fail; + } + + aes_ctrl.random_en = HI_FALSE; + aes_ctrl.key_from = HI_CIPHER_AES_KEY_FROM_KDF; + aes_ctrl.work_mode = HI_CIPHER_AES_WORK_MODE_CBC; + aes_ctrl.key_len = HI_CIPHER_AES_KEY_LENGTH_256BIT; + ret = hi_cipher_aes_config(&aes_ctrl); + if (ret != HI_ERR_SUCCESS) { + goto fail; + } + + ret = hi_cipher_aes_crypto(para->kernel_start + para->encrypt_offset + SFC_BUFFER_BASE_ADDRESS, + (uintptr_t)fw_raw_data, para->encrypt_size, HI_FALSE); + if (ret != HI_ERR_SUCCESS) { + goto crypto_fail; + } + +crypto_fail: + (hi_void) hi_cipher_aes_destroy_config(); +fail: + return ret; +} + + +hi_u32 crypto_encrypt_data_to_flash(uintptr_t kernel_offset) +{ + hi_u32 ret; + encrypt_ctx *data = encrypt_get_ctx(); + + ret = crypto_init_param(data, kernel_offset); + if (ret != HI_ERR_SUCCESS) { + goto fail; + } + + ret = crypto_upg_file_decrypt(data); + if (ret != HI_ERR_SUCCESS) { + goto fail; + } + + ret = encrypt_upg_data(data); + if (ret != HI_ERR_SUCCESS) { + goto fail; + } + +fail: + crypto_mem_free(data->raw_buf); + return ret; +} + +#endif diff --git a/sdk_liteos/platform/system/upg/kernel_crypto.h b/sdk_liteos/platform/system/upg/kernel_crypto.h new file mode 100644 index 0000000000000000000000000000000000000000..55c1e43d41e8d5f151e35880af84601ede78ee18 --- /dev/null +++ b/sdk_liteos/platform/system/upg/kernel_crypto.h @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __ENCRYPT_UPG_DUAL_PARTITION_H__ +#define __ENCRYPT_UPG_DUAL_PARTITION_H__ + +#if defined(CONFIG_FLASH_ENCRYPT_SUPPORT) +#include +#include + +#ifdef CRYPTO_DEBUG +#include +#define crypto_print(ftm...) \ + do { \ + printf(ftm); \ + } while (0); +#else +#define crypto_print(ftm...) +#endif + +#define crypto_mem_free(sz) \ + do { \ + if ((sz) != HI_NULL) { \ + hi_free(HI_MOD_ID_CRYPTO, (sz)); \ + } \ + (sz) = HI_NULL; \ + } while (0) + +#define IV_BYTE_LENGTH 16 +#define ROOTKEY_IV_BYTE_LENGTH 32 + +#define DIE_ID_BYTE_LENGTH 24 + +#define KEY_BYTE_LENGTH 32 + +#define SHA_256_LENGTH 32 + +#define ROOT_SALT_LENGTH 32 + +#define CRYPTO_CNT_NUM 6 + +#define CRYPTO_KERNEL_LENGTH 4096 + +#define ENCRYPT_KDF_ITERATION_CNT 1024 + +#define MIN_CRYPTO_BLOCK_SIZE 16 + +#define HI_NV_FTM_KERNELA_WORK_ID 0x4 +#define HI_NV_FTM_BACKUP_KERNELA_WORK_ID 0x5 +#define HI_NV_FTM_KERNELB_WORK_ID 0x6 +#define HI_NV_FTM_BACKUP_KERNELB_WORK_ID 0x7 + +typedef enum { + CRYPTO_WORKKEY_KERNEL_A = 0x1, + CRYPTO_WORKKEY_KERNEL_A_BACKUP = 0x2, + CRYPTO_WORKKEY_KERNEL_A_BOTH = 0x3, + CRYPTO_WORKKEY_KERNEL_B = 0x4, + CRYPTO_WORKKEY_KERNEL_B_BACKUP = 0x8, + CRYPTO_WORKKEY_KERNEL_B_BOTH = 0xC, +} crypto_workkey_partition; + +typedef struct { + hi_u8 root_salt[ROOT_SALT_LENGTH]; + hi_u8 iv_nv[IV_BYTE_LENGTH]; + hi_u8 iv_content[IV_BYTE_LENGTH]; + hi_u8 work_text[KEY_BYTE_LENGTH]; + hi_u8 content_sh256[SHA_256_LENGTH]; +} hi_flash_crypto_content; + +typedef struct { + uintptr_t kernel_start; + uintptr_t encrypt_offset; + hi_u32 encrypt_size; + hi_u8 upg_iv[IV_BYTE_LENGTH]; + hi_u8 upg_salt[IV_BYTE_LENGTH]; + hi_u8 *raw_buf; +} encrypt_ctx; + +encrypt_ctx *encrypt_get_ctx(hi_void); + +hi_u32 crypto_decrypt(encrypt_ctx *para); + +hi_u32 encrypt_upg_data(encrypt_ctx *para); + +hi_u32 crypto_encrypt_data_to_flash(uintptr_t kernel_offset); + +#endif + +#endif diff --git a/sdk_liteos/platform/system/upg/upg_check_boot_bin.c b/sdk_liteos/platform/system/upg/upg_check_boot_bin.c new file mode 100644 index 0000000000000000000000000000000000000000..84932cc833be8ea03fe3e49906cae9ef17c69e2b --- /dev/null +++ b/sdk_liteos/platform/system/upg/upg_check_boot_bin.c @@ -0,0 +1,571 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include + +hi_u32 upg_check_boot_root_pub_key(HI_CONST boot_header *head, HI_CONST hi_u8 *pubk, hi_u32 pubk_len) +{ + hi_u8 hash[SHA_256_LENGTH]; + hi_u8 efuse_hash[SHA_256_LENGTH]; + + if ((head == HI_NULL) || (pubk == HI_NULL)) { + return HI_ERR_UPG_NULL_POINTER; + } + + if (head->root_pubk_length != pubk_len) { + return HI_ERR_UPG_BOOT_ROOT_KEY_LEN; + } + + (hi_void) memset_s(hash, SHA_256_LENGTH, 0, SHA_256_LENGTH); + hi_u32 ret = hi_cipher_hash_sha256((uintptr_t)pubk, pubk_len, hash, sizeof(hash)); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + (hi_void) memset_s(efuse_hash, SHA_256_LENGTH, 0, SHA_256_LENGTH); + ret = hi_efuse_read(HI_EFUSE_ROOT_PUBKEY_RW_ID, efuse_hash, SHA_256_LENGTH); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + if (memcmp(hash, efuse_hash, SHA_256_LENGTH) != EOK) { + ret = HI_ERR_UPG_BOOT_ROOT_KEY; + } + + return ret; +} + +hi_u32 upg_check_die_id(HI_CONST hi_void *sub_key_data) +{ + hi_u8 die_id[DIE_ID_LENGTH] = { 0 }; + hi_u32 ret = HI_ERR_SUCCESS; + sub_key_common *sub_key = (sub_key_common *)sub_key_data; + + if (sub_key->key_type == MAINTENANCE_KEY_TPYE) { + ret = hi_efuse_read(HI_EFUSE_DIE_RW_ID, (hi_u8 *)die_id, (hi_u8)sizeof(die_id)); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + if (memcmp(sub_key->die_id, die_id, DIE_ID_LENGTH) != EOK) { + return HI_ERR_UPG_BOOT_DIE_ID; + } + } + return ret; +} + +hi_u32 upg_check_boot_subk_attr(HI_CONST hi_void *key, hi_u32 alg) +{ + hi_u32 category = (hi_u32)(-1); + hi_u32 rsim = (hi_u32)(-1); + hi_u32 ret = hi_efuse_read(HI_EFUSE_SUBKEY_CAT_RW_ID, (hi_u8 *)(&category), sizeof(hi_u32)); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + sub_key_common *sub_key_com = (sub_key_common *)key; + if (sub_key_com->category != category) { + return HI_ERR_UPG_BOOT_SUB_KEY_CAT; + } + ret = hi_efuse_read(HI_EFUSE_SUBKEY_RSIM_RW_ID, (hi_u8 *)&rsim, SUBKEY_RSIM_BYTES); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + if ((sub_key_com->key_id > SUBKEY_ID_MAX) || (((rsim >> sub_key_com->key_id) & 1) == 1)) { + return HI_ERR_UPG_BOOT_SUB_KEY_RSIM; + } + + if (alg == SIGN_ALG_ECC) { + sub_ecc_key *sub_key = (sub_ecc_key *)key; + if ((sub_key->sign_alg.hash_alg != HI_HASH_ALG_SHA256) || + (sub_key->sign_alg.sign_alg != SIGN_ALG_ECC) || + (sub_key->subkey_length != ECC_64_BYTES)) { + return HI_ERR_UPG_BOOT_SIGN_ALG; + } + } else { + sub_rsa_key *sub_key = (sub_rsa_key *)key; + if ((sub_key->sign_alg.hash_alg != HI_HASH_ALG_SHA256) || + (sub_key->sign_alg.sign_alg > SIGN_ALG_RSA_PSS) || + (sub_key->subkey_length != (RSA_2048_LENGTH + RSA_EXP_E_LENGTH))) { + return HI_ERR_UPG_BOOT_SIGN_ALG; + } + } + ret = upg_check_die_id(key); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg check boot subk attr] die id err:0x%x \r\n", ret); + } + + return ret; +} + +hi_u32 upg_check_boot_sub_key_cpy(const root_rsa_pub_key *root_key, hi_u8 *exp_e) +{ + if (memset_s(exp_e, RSA_4096_LENGTH, 0, RSA_4096_LENGTH) != EOK) { + return HI_ERR_FAILURE; + } + if (memcpy_s((exp_e + RSA_4096_LENGTH - RSA_EXP_E_LENGTH), RSA_EXP_E_LENGTH, root_key->exp_e, RSA_EXP_E_LENGTH) + != EOK) { + return HI_ERR_FAILURE; + } + + return HI_ERR_SUCCESS; +} + +hi_u32 upg_check_boot_sub_key(HI_CONST hi_u8 *pubk, HI_CONST hi_u8 *subk, hi_u32 alg) +{ + hi_u8 hash[SHA_256_LENGTH] = { 0 }; + hi_u32 ret = upg_check_boot_subk_attr(subk, alg); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg check boot sub key]attr err:0x%x \r\n", ret); + return ret; + } + + if (alg == SIGN_ALG_ECC) { + sub_ecc_key *sub_key = (sub_ecc_key *)subk; + root_ecc_pub_key *root_key = (root_ecc_pub_key *)pubk; + ret = hi_cipher_hash_sha256((uintptr_t)sub_key, sizeof(sub_ecc_key) - ECC_64_BYTES, hash, sizeof(hash)); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg check bootbin]hash ecc key hash err:0x%x \r\n", ret); + return ret; + } + + hi_cipher_ecc_verify ecc_verify = { + .px = root_key->px, + .py = root_key->py, + .hash = hash, + .hash_len = PKE_LEN_32_BYTES, + .r = sub_key->r, + .s = sub_key->s, + }; + ret = hi_cipher_ecc_verify_hash(&g_brain_pool_p256r1_verify, &ecc_verify); + } else { + sub_rsa_key *sub_key = (sub_rsa_key *)subk; + root_rsa_pub_key *root_key = (root_rsa_pub_key *)pubk; + ret = hi_cipher_hash_sha256((uintptr_t)sub_key, sizeof(sub_rsa_key) - RSA_4096_LENGTH, hash, sizeof(hash)); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + hi_u8 *exp_e = hi_malloc(HI_MOD_ID_UPG, RSA_4096_LENGTH); + if (exp_e == HI_NULL) { + return HI_ERR_UPG_MALLOC_FAIL; + } + + if (upg_check_boot_sub_key_cpy(root_key, exp_e) != HI_ERR_SUCCESS) { + hi_free(HI_MOD_ID_UPG, exp_e); + return HI_ERR_FAILURE; + } + + hi_cipher_rsa_verify rsa_verify; + rsa_verify.n = root_key->mod_n; + rsa_verify.e = exp_e; + rsa_verify.klen = RSA_4096_LENGTH; + rsa_verify.scheme = (hi_cipher_rsa_sign_scheme)(sub_key->sign_alg.sign_alg); + + ret = hi_cipher_rsa_verify_hash(&rsa_verify, hash, PKE_LEN_32_BYTES, sub_key->sign, RSA_4096_LENGTH); + hi_free(HI_MOD_ID_UPG, exp_e); + } + return ((ret == HI_ERR_FAILURE) ? HI_ERR_UPG_BOOT_SUB_KEY_HASH : ret); +} + +/* data: total boot bin. data_len: length of boot bin. */ +hi_u32 upg_boot_decrypt(hi_u8 *data, hi_u32 data_len) +{ + hi_u8 rootkey_iv[ROOTKEY_IV_BYTE_LENGTH] = { 0 }; + boot_header *head = (boot_header *)data; + hi_u32 ret = HI_ERR_FAILURE; + + if ((head == HI_NULL) || (data_len != (head->sign_offset + head->sign_length + sizeof(boot_tail)))) { + return HI_ERR_UPG_PARAMETER; + } + + hi_u32 decrypt_addr = (hi_u32)(uintptr_t)data + head->code_section_offset; + sub_key_common *sub_key_com = (sub_key_common *)(data + head->sub_key_offset); + hi_cipher_kdf_ctrl *ctrl = hi_malloc(HI_MOD_ID_UPG, sizeof(hi_cipher_kdf_ctrl)); + hi_cipher_aes_ctrl *aes_ctrl = hi_malloc(HI_MOD_ID_UPG, sizeof(hi_cipher_aes_ctrl)); + if ((ctrl == HI_NULL) || (aes_ctrl == HI_NULL)) { + goto end; + } + + memset_s(ctrl, sizeof(hi_cipher_kdf_ctrl), 0, sizeof(hi_cipher_kdf_ctrl)); + memset_s(aes_ctrl, sizeof(hi_cipher_aes_ctrl), 0, sizeof(hi_cipher_aes_ctrl)); + if ((memcpy_s(rootkey_iv, sizeof(rootkey_iv), sub_key_com->boot_key, IV_BYTE_LEN) != EOK) || + (memcpy_s((rootkey_iv + IV_BYTE_LEN), sizeof(rootkey_iv) - IV_BYTE_LEN, g_magic, IV_BYTE_LEN) != EOK)) { + goto end; + } + + ctrl->salt = rootkey_iv; + ctrl->salt_len = ROOTKEY_IV_BYTE_LENGTH; + ctrl->kdf_cnt = KDF_ITERATION_CNT; + ctrl->kdf_mode = HI_CIPHER_SSS_KDF_KEY_STORAGE; + ret = hi_cipher_kdf_key_derive(ctrl); + if (ret != HI_ERR_SUCCESS) { + goto end; + } + if (memcpy_s(aes_ctrl->iv, sizeof(aes_ctrl->iv), sub_key_com->aes_iv, IV_BYTE_LEN) != EOK) { + goto end; + } + aes_ctrl->random_en = HI_TRUE; + aes_ctrl->key_from = HI_CIPHER_AES_KEY_FROM_KDF; + aes_ctrl->work_mode = HI_CIPHER_AES_WORK_MODE_CBC; + aes_ctrl->key_len = HI_CIPHER_AES_KEY_LENGTH_256BIT; + ret = hi_cipher_aes_config(aes_ctrl); + if (ret != HI_ERR_SUCCESS) { + goto end; + } + ret = hi_cipher_aes_crypto(decrypt_addr, decrypt_addr, head->code_section_length, HI_FALSE); + (hi_void) hi_cipher_aes_destroy_config(); +end: + upg_clear_contset((hi_u8 *)ctrl, sizeof(hi_cipher_kdf_ctrl)); + upg_clear_contset((hi_u8 *)aes_ctrl, sizeof(hi_cipher_aes_ctrl)); + upg_mem_free(ctrl); + upg_mem_free(aes_ctrl); + return ret; +} + +hi_u32 upg_check_boot_from_mem(hi_u8 *data, hi_u32 data_len, hi_u8 *key_part1, hi_u8 *key_part2) +{ + hi_u32 ret; + hi_u8 hash[SHA_256_LENGTH] = { 0 }; + boot_header *head = HI_NULL; + hi_u8 *signature = HI_NULL; + + head = (boot_header *)data; + if (data_len != (head->sign_offset + head->sign_length + sizeof(boot_tail))) { + return HI_ERR_UPG_BOOT_LEN; + } + ret = hi_cipher_hash_sha256((uintptr_t)data, (head->code_section_offset + head->code_section_length), + hash, sizeof(hash)); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg check boot code]sha256 err:0x%x \r\n", ret); + return ret; + } + + signature = data + head->sign_offset; + if (head->sign_alg.sign_alg == SIGN_ALG_ECC) { + hi_cipher_ecc_verify ecc_verify = { + .px = key_part1, + .py = key_part2, + .hash = hash, + .hash_len = PKE_LEN_32_BYTES, + .r = signature, + .s = signature + ECC_32_BYTES, + }; + ret = hi_cipher_ecc_verify_hash(&g_brain_pool_p256r1_verify, &ecc_verify); + } else { + hi_cipher_rsa_verify rsa_verify = { + .n = key_part1, + .e = key_part2, + .klen = RSA_2048_LENGTH, + .scheme = (hi_cipher_rsa_sign_scheme)(head->sign_alg.sign_alg), + }; + ret = hi_cipher_rsa_verify_hash(&rsa_verify, hash, PKE_LEN_32_BYTES, signature, head->sign_length); + } + ret = ((ret == HI_ERR_FAILURE) ? HI_ERR_UPG_BOOT_SECTION_HASH : ret); + upg_print("[upg check boot code]verify ret:0x%x \r\n", ret); + return ret; +} + +/* boot_addr:flashboot bin addr without ota head. boot_len: total len. */ +hi_u32 upg_check_encrpt_boot_code(hi_u32 boot_addr, hi_u32 boot_len, hi_u8 *key_part1, hi_u8 *key_part2) +{ + upg_print("[upg check encrpt boot]addr-len:0x%x-0x%x \r\n", boot_addr, boot_len); + hi_u8 *boot = hi_malloc(HI_MOD_ID_UPG, boot_len); + if (boot == HI_NULL) { + upg_print("[upg check encrpt boot]malloc fail,boot_len:0x%x \r\n", boot_len); + return HI_ERR_UPG_MALLOC_FAIL; + } + + hi_u32 ret = hi_flash_read(boot_addr, boot_len, boot); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg check encrpt boot]flash read err:0x%x \r\n", ret); + goto end; + } + /* decrypt data */ + ret = upg_boot_decrypt(boot, boot_len); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg check encrpt boot]decrypt ret:0x%x \r\n", ret); + goto end; + } + + ret = upg_check_boot_from_mem(boot, boot_len, key_part1, key_part2); +end: + upg_mem_free(boot); + return ret; +} + +/* addr:flashboot bin addr without ota head. */ +hi_u32 upg_check_unencrpt_boot_code(hi_u32 addr, HI_CONST boot_header *head, hi_u8 *key_part1, hi_u8 *key_part2) +{ + hi_u8 hash[SHA_256_LENGTH] = { 0 }; + + if (head->sign_length == 0) { + return HI_ERR_UPG_PARAMETER; + } + hi_u32 ret = upg_hash_one_content(addr, (head->code_section_offset + head->code_section_length), + hash, sizeof(hash)); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + hi_u8 *signature = hi_malloc(HI_MOD_ID_UPG, head->sign_length); + if (signature == HI_NULL) { + return HI_ERR_UPG_MALLOC_FAIL; + } + + ret = hi_flash_read(addr + head->sign_offset, head->sign_length, signature); + if (ret != HI_ERR_SUCCESS) { + goto end; + } + + if (head->sign_alg.sign_alg == SIGN_ALG_ECC) { + hi_cipher_ecc_verify ecc_verify = { + .px = key_part1, + .py = key_part2, + .hash = hash, + .hash_len = PKE_LEN_32_BYTES, + .r = signature, + .s = signature + ECC_32_BYTES, + }; + ret = hi_cipher_ecc_verify_hash(&g_brain_pool_p256r1_verify, &ecc_verify); + } else { + hi_cipher_rsa_verify rsa_verify = { + .n = key_part1, + .e = key_part2, + .klen = RSA_2048_LENGTH, + .scheme = (hi_cipher_rsa_sign_scheme)(head->sign_alg.sign_alg), + }; + ret = hi_cipher_rsa_verify_hash(&rsa_verify, hash, PKE_LEN_32_BYTES, signature, head->sign_length); + } + ret = ((ret == HI_ERR_FAILURE) ? HI_ERR_UPG_BOOT_SECTION_HASH : ret); + upg_print("[upg check unencrpt boot code]alg-ret:0x%x-0x%x \r\n", head->sign_alg.sign_alg, ret); +end: + upg_mem_free(signature); + return ret; +} + +/* addr:flashboot bin addr without ota head. */ +hi_u32 upg_verify_flashboot(hi_u32 addr, HI_CONST boot_header *head, hi_u8 *key_part1, + hi_u8 *key_part2, const sub_key_common *subk_com) +{ + hi_u8 encrypt_flag = 0xFF; + hi_u32 ret = hi_efuse_read(HI_EFUSE_ENCRYPT_FLAG_RW_ID, (hi_u8 *)(&encrypt_flag), sizeof(hi_u8)); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg verify flashboot]efuse read err:0x%x \r\n", ret); + return ret; + } + + if ((encrypt_flag == NON_ENCRYPT_FLAG) && (subk_com->encrypt_flag == NON_ENCRYPT_FLAG)) { + ret = upg_check_unencrpt_boot_code(addr, head, key_part1, key_part2); + } else { + ret = upg_check_encrpt_boot_code(addr, (head->sign_offset + head->sign_length + sizeof(boot_tail)), + key_part1, key_part2); + } + upg_print("[upg verify flashboot]ret-efuse-fileflag:0x%x-0x%x-0x%x \r\n", ret, encrypt_flag, + subk_com->encrypt_flag); + return ret; +} + +hi_u32 upg_get_boot_sign_key(HI_CONST boot_header *head, HI_CONST hi_u8 *key, hi_u8 **pubk1, + hi_u8 *pubk2, hi_u32 pubk2_len) +{ + if ((head == HI_NULL) || (key == HI_NULL) || (pubk1 == HI_NULL) || (pubk2 == HI_NULL)) { + return HI_ERR_UPG_NULL_POINTER; + } + + if (head->root_pubk_alg < SIGN_ALG_ECC) { + sub_rsa_key *sub_key = (sub_rsa_key *)key; + if (pubk2_len != RSA_2048_LENGTH) { + return HI_ERR_UPG_PARAMETER; + } + *pubk1 = sub_key->mod_n; + if (memcpy_s((pubk2 + RSA_2048_LENGTH - RSA_EXP_E_LENGTH), RSA_EXP_E_LENGTH, + sub_key->exp_e, RSA_EXP_E_LENGTH) != EOK) { + return HI_ERR_FAILURE; + } + } else { + sub_ecc_key *sub_key = (sub_ecc_key *)key; + if (pubk2_len != ECC_32_BYTES) { + return HI_ERR_UPG_PARAMETER; + } + *pubk1 = sub_key->px; + if (memcpy_s(pubk2, ECC_32_BYTES, sub_key->py, ECC_32_BYTES) != EOK) { + return HI_ERR_FAILURE; + } + } + + return HI_ERR_SUCCESS; +} + +/* boot_addr:flashboot bin addr without ota head. verify_len: from head to sign(not include). */ +hi_u32 upg_check_non_secure_boot_bin(hi_u32 boot_addr, hi_u32 verify_len, hi_u32 sign_addr) +{ + hi_u32 ret; + hi_u8 *cal_hash = hi_malloc(HI_MOD_ID_UPG, SHA_256_LENGTH); + hi_u8 *file_hash = hi_malloc(HI_MOD_ID_UPG, SHA_256_LENGTH); + if ((cal_hash == HI_NULL) || (file_hash == HI_NULL)) { + ret = HI_ERR_UPG_MALLOC_FAIL; + goto end; + } + memset_s(cal_hash, SHA_256_LENGTH, 0, SHA_256_LENGTH); + memset_s(file_hash, SHA_256_LENGTH, 0, SHA_256_LENGTH); + upg_print("[upg_non_secure_boot_bin]addr-verifylen-signaddr:0x%x-0x%x-0x%x \r\n", boot_addr, verify_len, + sign_addr); + ret = upg_hash_one_content(boot_addr, verify_len, cal_hash, SHA_256_LENGTH); + if (ret != HI_ERR_SUCCESS) { + goto end; + } + ret = hi_flash_read(sign_addr, SHA_256_LENGTH, file_hash); + if (ret != HI_ERR_SUCCESS) { + goto end; + } + if (memcmp(cal_hash, file_hash, SHA_256_LENGTH) != EOK) { + ret = HI_ERR_UPG_BOOT_HASH; + } +end: + upg_mem_free(cal_hash); + upg_mem_free(file_hash); + return ret; +} + +hi_u32 upg_check_boot_bin_key(HI_CONST boot_header *head, HI_CONST hi_u8 *pubk, hi_u32 pubk_len, + HI_CONST hi_u8 *subk) +{ + hi_u32 ret = upg_check_boot_root_pub_key(head, pubk, pubk_len); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg check boot pub key]fail,ret:0x%x \r\n", ret); + return ret; + } + + ret = upg_check_boot_sub_key(pubk, subk, head->root_pubk_alg); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg check boot sub key]fail,ret:0x%x \r\n", ret) + } + return ret; +} + +hi_u32 upg_check_boot_get_key_len(HI_CONST boot_header *head, hi_u32 *pubk_len, hi_u32 *subk_len) +{ + if ((head->root_pubk_alg < SIGN_ALG_ECC) && (head->sub_key_length == sizeof(sub_rsa_key))) { + *pubk_len = sizeof(root_rsa_pub_key); + *subk_len = sizeof(sub_rsa_key); + return HI_ERR_SUCCESS; + } + + if ((head->root_pubk_alg == SIGN_ALG_ECC) && (head->sub_key_length == sizeof(sub_ecc_key))) { + *pubk_len = sizeof(root_ecc_pub_key); + *subk_len = sizeof(sub_ecc_key); + return HI_ERR_SUCCESS; + } + return HI_ERR_UPG_BOOT_SUB_KEY_LEN; +} + +/* addr:flashboot bin addr without ota head. */ +hi_u32 upg_check_secure_boot_bin(hi_u32 addr, HI_CONST boot_header *head) +{ + hi_u8 *pubk1 = HI_NULL; + hi_u32 pubk_len; + hi_u32 subk_len; + hi_u32 puk2_len = RSA_2048_LENGTH; + hi_u32 ret = upg_check_boot_get_key_len(head, &pubk_len, &subk_len); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + if (head->root_pubk_alg == SIGN_ALG_ECC) { + puk2_len = ECC_32_BYTES; + } + upg_print("[verify flashboot]pubklen-subklen-puk2len:0x%x-0x%x-0x%x \r\n", pubk_len, subk_len, puk2_len); + hi_u8 *pubk = hi_malloc(HI_MOD_ID_UPG, pubk_len); + hi_u8 *subk = hi_malloc(HI_MOD_ID_UPG, subk_len); + hi_u8 *pubk2 = hi_malloc(HI_MOD_ID_UPG, puk2_len); + if ((pubk == HI_NULL) || (subk == HI_NULL) || (pubk2 == HI_NULL)) { + ret = HI_ERR_UPG_MALLOC_FAIL; + goto end; + } + memset_s(pubk2, puk2_len, 0, puk2_len); + ret = hi_flash_read((addr + head->root_pubk_offset), pubk_len, pubk); + ret |= hi_flash_read((addr + head->sub_key_offset), subk_len, subk); + if (ret != HI_ERR_SUCCESS) { + goto end; + } + + ret = upg_check_boot_bin_key(head, pubk, pubk_len, subk); + if (ret != HI_ERR_SUCCESS) { + goto end; + } + + ret = upg_get_boot_sign_key(head, subk, &pubk1, pubk2, puk2_len); + if (ret != HI_ERR_SUCCESS) { + goto end; + } + + ret = upg_verify_flashboot(addr, head, pubk1, pubk2, (sub_key_common *)subk); + if (ret != HI_ERR_SUCCESS) { + goto end; + } +end: + upg_clear_contset((hi_u8 *)pubk, pubk_len); + upg_clear_contset((hi_u8 *)subk, subk_len); + upg_clear_contset((hi_u8 *)pubk2, puk2_len); + upg_mem_free(pubk); + upg_mem_free(subk); + upg_mem_free(pubk2); + return ret; +} + +/* addr:flashboot bin addr(without ota head). len: length of flashboot bin. */ +hi_u32 upg_check_boot_file(hi_u32 addr, hi_u32 len) +{ + hi_bool flag; + hi_unref_param(len); + hi_u32 ret = upg_is_secure_efuse(&flag); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg check boot bin]get secure efuse err:0x%x \r\n", ret); + return ret; + } + upg_print("[upg check boot bin]addr-len:0x%x-0x%x \r\n", addr, len); + boot_header *head = (boot_header *)hi_malloc(HI_MOD_ID_UPG, sizeof(boot_header)); + if (head == HI_NULL) { + return HI_ERR_UPG_MALLOC_FAIL; + } + ret = hi_flash_read(addr, sizeof(boot_header), (hi_u8 *)head); + if (ret != HI_ERR_SUCCESS) { + goto end; + } + + if ((head->preamble != BOOT_PREAMBLE) || (head->head_magic != BOOT_HEAD_MAGIC)) { + ret = HI_ERR_UPG_BOOT_HEAD; + goto end; + } + + hi_u32 boot_len = head->sign_offset + head->sign_length + sizeof(boot_tail); + if ((boot_len < BOOT_SECURE_MIN_LEN) || (boot_len > BOOT_MAX_LEN)) { + ret = HI_ERR_UPG_BOOT_LEN; + goto end; + } + + if (flag == HI_TRUE) { + ret = upg_check_secure_boot_bin(addr, head); + } else { + ret = upg_check_non_secure_boot_bin(addr, (head->code_section_offset + head->code_section_length), + addr + head->sign_offset); + } +end: + hi_free(HI_MOD_ID_UPG, head); + return ret; +} diff --git a/sdk_liteos/platform/system/upg/upg_check_boot_bin.h b/sdk_liteos/platform/system/upg/upg_check_boot_bin.h new file mode 100644 index 0000000000000000000000000000000000000000..728db98dc8c4405ae6112fa563cc7a4260448fb1 --- /dev/null +++ b/sdk_liteos/platform/system/upg/upg_check_boot_bin.h @@ -0,0 +1,162 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __UPG_CHECK_BOOT_BIN_H__ +#define __UPG_CHECK_BOOT_BIN_H__ + +#include +#include + +#define RSA_4096_LENGTH 512 +#define RSA_2048_LENGTH 256 + +#define SHA_256_LENGTH 32 +#define ECC_32_BYTES 32 +#define ECC_64_BYTES 64 + +#define BOOT_PREAMBLE 0x55AA55AA +#define BOOT_HEAD_MAGIC 0x33CC33CC +#define BOOT_TAIL_MAGIC 0x55AA55AA + +#define DIE_ID_LENGTH 24 + +#define HI_HASH_ALG_SHA256 0 +#define SUBKEY_ID_MAX 23 +#define RSA_EXP_E_LENGTH 4 +#define BOOT_VER_MAX 16 + +#define ROOTKEY_IV_BYTE_LENGTH 32 +#define KEY_BYTE_LENGTH 32 +#define CHECK_BYTE_LENGTH 32 +#define KDF_ITERATION_CNT 1024 + +#define BOOT_MAX_LEN 0x13FC0 /* 80K - 0x40 */ +#define BOOT_SECURE_MIN_LEN 0x01A0 /* 0x150(ecc header len) + 0x40(signature len) + 0x10(tail len) */ +#define BOOT_NON_SECURE_MIN_LEN 0x0070 /* 0x40(sha256 header len) + 0x20(hash len) + 0x10(tail len) */ +#define MAINTENANCE_KEY_TPYE 0x3C965AC3 + +#define NON_SECURE_FLAG 0x42 +#define NON_ENCRYPT_FLAG 0x42 +#define SUBKEY_RSIM_BYTES 0x3 + +static HI_CONST hi_u8 g_magic[IV_BYTE_LEN] = { + 0xE4, 0xEE, 0x10, 0x0E, 0x43, 0x4D, 0x94, 0x24, + 0xC7, 0x54, 0x6D, 0xFB, 0x15, 0xA1, 0x46, 0x97 +}; + +typedef enum { + SIGN_ALG_RSA_V15 = 0x00, + SIGN_ALG_RSA_PSS = 0x01, + SIGN_ALG_ECC = 0x10, +} sign_alg_type; + +typedef struct { + hi_u8 mod_n[RSA_4096_LENGTH]; /* Mod N */ + hi_u8 exp_e[RSA_EXP_E_LENGTH]; /* Exp E */ +} root_rsa_pub_key; + +typedef struct { + hi_u32 version; /* Default 1. */ + sign_alg_param sign_alg; /* The signature algorithm. */ + hi_u32 category; /* The category of SubKey, Used to distinguish different products or chips. */ + hi_u32 key_id; /* [4:0] SubKeyID, 0~31; [31:5] Reserved. */ + hi_u32 key_type; /* 0x3C965AC3: Maintenance mode, should check die_id; + other: normal mode, ignore die_id. */ + hi_u8 die_id[DIE_ID_LENGTH]; /* Die ID. 24Bytes */ + hi_u8 encrypt_flag; /* 0x42: not encrypted; other: encryped. */ + hi_u8 boot_version; /* boot version, range [0, 15] */ + hi_u8 pad[2]; /* reserved 2 bytes. */ + hi_u8 boot_key[IV_BYTE_LEN]; /* part of key factor, 16 Bytes. */ + hi_u8 aes_iv[IV_BYTE_LEN]; /* AES-256 CBC mode, IV, 16 Bytes. */ + hi_u32 subkey_length; /* Length of SubKey. RSA2048: 260 Bytes. */ + hi_u8 mod_n[RSA_2048_LENGTH]; /* Mod N */ + hi_u8 exp_e[RSA_EXP_E_LENGTH]; /* Exp E */ + hi_u8 sign[RSA_4096_LENGTH]; /* Signature of Subkey. */ +} sub_rsa_key; + +typedef struct { + hi_u8 px[ECC_32_BYTES]; /* pubkey x */ + hi_u8 py[ECC_32_BYTES]; /* pubkey y */ +} root_ecc_pub_key; + +typedef struct { + hi_u32 version; /* Default 1. */ + sign_alg_param sign_alg; /* The signature algorithm. */ + hi_u32 category; /* The category of SubKey, Used to distinguish different products or chips. */ + hi_u32 key_id; /* [4:0] SubKeyID, 0~31; [31:5] Reserved. */ + hi_u32 key_type; /* 0x3C965AC3: Maintenance mode, should check die_id; + other: normal mode, ignore die_id. */ + hi_u8 die_id[DIE_ID_LENGTH]; /* Die ID. 24Bytes */ + hi_u8 encrypt_flag; /* 0x42: not encrypted; other: encryped. */ + hi_u8 boot_version; /* boot version, range [0, 16] */ + hi_u8 pad[2]; /* reserved 2 bytes. */ + hi_u8 boot_key[IV_BYTE_LEN]; /* part of key factor, 16 Bytes. */ + hi_u8 aes_iv[IV_BYTE_LEN]; /* AES-256 CBC mode, IV, 16 Bytes. */ + hi_u32 subkey_length; /* Length of SubKey. ECDSA256: 64 Bytes. */ + hi_u8 px[ECC_32_BYTES]; /* X */ + hi_u8 py[ECC_32_BYTES]; /* Y */ + hi_u8 r[ECC_32_BYTES]; /* Signature of Subkey. */ + hi_u8 s[ECC_32_BYTES]; /* Signature of Subkey. */ +} sub_ecc_key; + +typedef struct { + hi_u32 version; /* Default 1. */ + sign_alg_param sign_alg; /* The signature algorithm. */ + hi_u32 category; /* The category of SubKey, Used to distinguish different products or chips. */ + hi_u32 key_id; /* [4:0] SubKeyID, 0~31; [31:5] Reserved. */ + hi_u32 key_type; /* 0x3C965AC3: Maintenance mode, should check die_id; + other: normal mode, ignore die_id. */ + hi_u8 die_id[DIE_ID_LENGTH]; /* Die ID. 24Bytes */ + hi_u8 encrypt_flag; /* 0x42: not encrypted; other: encryped. */ + hi_u8 boot_version; /* boot version, range [0, 16] */ + hi_u8 pad[2]; /* reserved 2 bytes. */ + hi_u8 boot_key[IV_BYTE_LEN]; /* part of key factor, 16 Bytes. */ + hi_u8 aes_iv[IV_BYTE_LEN]; /* AES-256 CBC mode, IV, 16 Bytes. */ + hi_u32 subkey_length; +} sub_key_common; + +typedef struct { + hi_u32 preamble; /* Head information preamble code 0x55AA55AA, Validated at secure startup. */ + hi_u32 head_length; /* Head information total length, sizeof(BOOT_HEADER_S). */ + hi_u32 root_pubk_alg; /* RootPubK algorithm. 0: RSA_PKCS1; 1: RSA_PSS; 0x10: ECC; other: reserved. */ + hi_u32 root_pubk_offset; /* Offset of RootPubK, based on Bootloader head. */ + hi_u32 root_pubk_length; /* RootPubK length. , value is 1024, ECC, value is 64. */ + hi_u32 root_pubk_hash_alg; /* RootPubK HASH algorithm. 0: SHA256, other: reserved. */ + + hi_u32 sub_key_offset; /* Offset of SubKeyCert, based on Bootloader head. */ + hi_u32 sub_key_length; /* Length of SubKeyCert. */ + + hi_u32 code_section_offset; /* Offset of Bootloader Code Section. */ + hi_u32 code_section_length; /* Length of Bootloader Code Section. */ + + sign_alg_param sign_alg; /* The signature algorithm. */ + + hi_u32 sign_offset; /* Offset of Bootloader Code Section Signature. */ + hi_u32 sign_length; /* Length of Bootloader Code Section Signature. */ + + hi_u32 head_magic; /* Head information over. Magic is 0x33CC33CC. + BootROM should check HeadMagic & Preamble at first. */ +} boot_header; + +typedef struct { + hi_u32 pad[2]; /* reserved 2 words. */ + hi_u32 boot_len; /* flashboot len, include head,code,tail */ + hi_u32 tail_magic; /* tail magic:0x55AA55AA */ +} boot_tail; + +hi_u32 upg_check_boot_file(hi_u32 addr, hi_u32 len); + +#endif /* __UPG_CHECK_BOOT_BIN_H__ */ + diff --git a/sdk_liteos/platform/system/upg/upg_check_file.c b/sdk_liteos/platform/system/upg/upg_check_file.c new file mode 100644 index 0000000000000000000000000000000000000000..358ff8fa5c893c7345587c5456d9f41e4726420e --- /dev/null +++ b/sdk_liteos/platform/system/upg/upg_check_file.c @@ -0,0 +1,378 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "upg_check_file.h" +#include "upg_check_secure.h" +#include "upg_check_boot_bin.h" +#include "upg_user_verify.h" + +hi_u32 upg_check_image_id(hi_u32 image_id) +{ + if (image_id != PRODUCT_UPG_FILE_IMAGE_ID) { + upg_print("[upg check image id]fail,image id:0x%x \r\n", image_id); + return HI_ERR_UPG_IMAGE_ID; + } + return HI_ERR_SUCCESS; +} + +hi_u32 upg_check_file_type(hi_u8 file_type) +{ + if ((file_type == HI_UPG_FILE_KERNEL) || (file_type == HI_UPG_FILE_BOOT)) { + return HI_ERR_SUCCESS; + } else { + upg_print("[upg check file type]fail,file type:0x%x \r\n", file_type); + return HI_ERR_UPG_FILE_TYPE; + } +} + +hi_bool upg_check_encrypt_info_is_match(hi_u8 encry_info) +{ +#if defined(CONFIG_FLASH_ENCRYPT_SUPPORT) + if (encry_info != HI_UPG_FILE_ATTR_ENCRYPT) { + upg_print("[upg_check_encrypt_info]encrypt 0x%x \r\n", encry_info); + return HI_FALSE; + } +#else + if (encry_info != HI_UPG_FILE_ATTR_UNENCRYPT) { + upg_print("[upg_check_encrypt_info]unencrypt 0x%x \r\n", encry_info); + return HI_FALSE; + } +#endif + return HI_TRUE; +} + +hi_bool upg_check_ota_info_is_match(hi_u8 file_type, hi_u8 ota_info) +{ +#if defined(CONFIG_COMPRESSION_OTA_SUPPORT) + hi_unref_param(file_type); + if (ota_info != HI_UPG_FILE_ATTR_COMPRESSION) { + upg_print("[upg_check_ota_info]compression 0x%x \r\n", ota_info); + return HI_FALSE; + } +#else + hi_nv_ftm_startup_cfg cfg = { 0 }; + hi_flash_partition_table *partition = hi_get_partition_table(); + uintptr_t kernel_a_addr = partition->table[HI_FLASH_PARTITON_KERNEL_A].addr; + hi_u32 ret = upg_get_start_up_cfg(&cfg); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg_check_ota_info]get cfg fail:0x%x \r\n", ret); + return HI_FALSE; + } + /* check flashboot */ + if (file_type == HI_UPG_FILE_BOOT) { + if (ota_info != (HI_UPG_FILE_ATTR_KERNELA | HI_UPG_FILE_ATTR_KERNELB)) { + upg_print("[upg_check_ota_info]dual flashboot 0x%x \r\n", ota_info); + return HI_FALSE; + } + return HI_TRUE; + } + + if (cfg.addr_start == kernel_a_addr) { + if ((ota_info != HI_UPG_FILE_ATTR_KERNELB)) { + upg_print("[upg_check_ota_info]kernela 0x%x \r\n", ota_info); + return HI_FALSE; + } + return HI_TRUE; + } + + if ((ota_info != HI_UPG_FILE_ATTR_KERNELA)) { + upg_print("[upg_check_ota_info]kernelb 0x%x \r\n", ota_info); + return HI_FALSE; + } +#endif + return HI_TRUE; +} + +hi_u32 upg_check_file_attributes(hi_u8 file_type, hi_u8 file_attr) +{ + hi_u8 file_info = file_attr; + hi_u8 ota_info = file_info & HI_UPG_OTA_SETTINGS_MASK; + hi_u8 encry_info = file_info >> 6; /* 6: ota settings bit number */ + + upg_print("[upg check attributes]type-attr-encry-ota:0x%x-0x%x-0x%x-0x%x \r\n", + file_type, file_attr, encry_info, ota_info); + if (upg_check_encrypt_info_is_match(encry_info) == HI_FALSE) { + return HI_ERR_UPG_ENCRYPT_NOT_MATCH; + } + + if (upg_check_ota_info_is_match(file_type, ota_info) == HI_FALSE) { + return HI_ERR_UPG_OTA_NOT_MATCH; + } + upg_print("[upg check attributes]success \r\n"); + + return HI_ERR_SUCCESS; +} + +hi_u32 upg_check_code_ver(hi_u8 ver) +{ + hi_u8 current_ver; + hi_u32 ret; + + if (ver > KERELN_VER_MAX) { + upg_print("[upg check code ver]file ver:%d \r\n", ver); + return HI_ERR_UPG_KERNEL_VER_OVER; + } + + ret = upg_get_efuse_code_ver(¤t_ver); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg check code ver]get ver ret:0x%x \r\n", ret); + return ret; + } + + if (ver < current_ver) { + upg_print("[upg check code ver]current>file:%d-%d \r\n", current_ver, ver); + return HI_ERR_UPG_LOW_KERNEL_VER; + } + + if ((current_ver == KERELN_VER_MAX) && (ver > KERELN_VER_MAX)) { + upg_print("[upg check code ver]current-file:%d-%d \r\n", current_ver, ver); + return HI_ERR_UPG_FULL_KERNEL_VER; + } + return ret; +} + +hi_u32 upg_check_boot_ver(hi_u8 ver) +{ + hi_u8 current_ver; + hi_u32 ret; + + if (ver > BOOT_VER_MAX) { + upg_print("[upg check boot ver]file ver:%d \r\n", ver); + return HI_ERR_UPG_BOOT_VER_OVER; + } + + ret = upg_get_efuse_boot_ver(¤t_ver); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg check boot ver]get ver ret:0x%x \r\n", ret); + return ret; + } + + if (ver < current_ver) { + upg_print("[upg check boot ver]current>file:%d-%d \r\n", current_ver, ver); + return HI_ERR_UPG_LOW_BOOT_VER; + } + + if ((current_ver == BOOT_VER_MAX) && (ver > BOOT_VER_MAX)) { + upg_print("[upg check boot ver]current-file:%d-%d \r\n", current_ver, ver); + return HI_ERR_UPG_FULL_BOOT_VER; + } + return ret; +} + +hi_u32 upg_check_version(hi_u8 file_type, hi_u8 ver) +{ + hi_u32 ret; + if (file_type == HI_UPG_FILE_KERNEL) { + ret = upg_check_code_ver(ver); + } else if (file_type == HI_UPG_FILE_BOOT) { + ret = upg_check_boot_ver(ver); + } else { + return HI_ERR_UPG_FILE_TYPE; + } + upg_print("[upg check ver]ret:0x%x \r\n", ret); + return ret; +} + +hi_u32 upg_check_file_len(hi_u8 file_type, hi_u32 file_len) +{ + hi_u32 max_len = 0; + hi_u32 ret = upg_get_max_file_len(file_type, &max_len); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + if (file_len > max_len) { + upg_print("[upg check file len]fail,filetype-filelen:0x%x-0x%x-0x%x. \r\n", file_type, file_len, max_len); + return HI_ERR_UPG_FILE_LEN_OVER; + } + return HI_ERR_SUCCESS; +} + +hi_u32 upg_get_common_head_from_flash(hi_u32 addr, hi_upg_common_head *head) +{ + hi_u32 ret = hi_flash_read(addr, sizeof(hi_upg_common_head), (hi_u8 *)head); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg get common head]fail,addr-ret:0x%x-0x%x \r\n", addr, ret); + return ret; + } + return ret; +} + +hi_u32 upg_get_section_head_from_flash(hi_u32 addr, hi_upg_section_head *section_head) +{ + hi_upg_common_head head = { 0 }; + hi_u32 ret; + + if (section_head == HI_NULL) { + upg_print("[upg get section head]is null.\r\n"); + return HI_ERR_UPG_NULL_POINTER; + } + ret = hi_flash_read(addr, sizeof(hi_upg_common_head), (hi_u8 *)(&head)); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg get section head]common head read ret:0x%x \r\n", ret); + return ret; + } + ret = hi_flash_read(addr + head.section_offset, sizeof(hi_upg_section_head), (hi_u8 *)section_head); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg get section head]flash read ret:0x%x \r\n", ret); + return ret; + } + + return ret; +} + +hi_u32 upg_check_alg_param(HI_CONST hi_upg_common_head *head) +{ + sign_alg_param alg_param = {0}; + + if (head == HI_NULL) { + return HI_ERR_FAILURE; + } + + if (memcpy_s(&alg_param, sizeof(sign_alg_param), &(head->param), sizeof(sign_alg_param)) != EOK) { + return HI_ERR_FAILURE; + } + if ((alg_param.sign_alg != HI_MODE_PKCS_V15) && (alg_param.sign_alg != HI_MODE_PKCS_PSS) && + (alg_param.sign_alg != HI_MODE_ECC)) { + return HI_ERR_UPG_SIGN_ALG; + } + + if (alg_param.sign_alg < HI_MODE_ECC) { + if (head->section_offset != (sizeof(hi_upg_common_head) + sizeof(upg_rsa_key) + sizeof(upg_rsa_sign))) { + return HI_ERR_UPG_RSA_HEAD_SIGN; + } + return HI_ERR_SUCCESS; + } + + if (head->section_offset != (sizeof(hi_upg_common_head) + sizeof(upg_ecc_key) + sizeof(upg_ecc_sign))) { + return HI_ERR_UPG_ECC_HEAD_SIGN; + } + return HI_ERR_SUCCESS; +} + +hi_u32 upg_check_head_common_info(const hi_upg_common_head *head, hi_u32 head_size) +{ + hi_bool flag; + + if (head_size != sizeof(hi_upg_common_head)) { + return HI_ERR_UPG_HEAD_LEN; + } + + hi_u32 ret = upg_check_image_id(head->image_id); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + ret = upg_check_file_type(head->file_type); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + ret = upg_check_file_attributes(head->file_type, head->file_attr); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + ret = upg_check_file_len(head->file_type, head->file_len); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + if ((head->file_len != (head->section_offset + head->section_len)) || + (head->section_offset != (sizeof(hi_upg_common_head) + sizeof(hi_upg_key) + sizeof(hi_upg_sign))) || + (head->section_len < (sizeof(hi_upg_section_head) + sizeof(hi_upg_sign)))) { + upg_print("[upg check len]fail:0x%x-0x%x-0x%x \r\n", head->file_len, head->section_offset, head->section_len); + return HI_ERR_UPG_FILE_LEN; + } + + /* The RSA, ECC, and SHA256 authentication modes have the same key length. */ + if (head->key_len != sizeof(upg_rsa_key)) { + return HI_ERR_UPG_KEY_LEN; + } + + ret = upg_is_secure_efuse(&flag); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg check head common]get secure efuse,err:0x%x \r\n", ret); + return ret; + } + + if (flag == HI_FALSE) { + upg_print("[upg check head common]not secure boot.\r\n"); + return HI_ERR_SUCCESS; + } + + ret = upg_check_version(head->file_type, head->file_version); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + return upg_check_alg_param(head); +} + +hi_u32 upg_check_common_head(const hi_upg_common_head *head, hi_u32 head_size) +{ + hi_u32 ret = upg_check_head_common_info(head, head_size); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg check common head]ret:0x%x \r\n", ret); + return ret; + } + ret = upg_user_define_verify(&(head->user_info)); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg check common head]user verify fail,ret:0x%x\r\n", ret); + } + return ret; +} + +hi_u32 upg_verify_file(hi_u32 addr) +{ + hi_u32 ret = HI_ERR_UPG_MALLOC_FAIL; + hi_upg_head *upg_head = (hi_upg_head *)hi_malloc(HI_MOD_ID_UPG, sizeof(hi_upg_head)); + hi_upg_common_head *common_head = HI_NULL; + hi_upg_section_head *section_head = HI_NULL; + + if (upg_head == HI_NULL) { + goto end; + } + ret = hi_flash_read(addr, sizeof(hi_upg_head), (hi_u8 *)upg_head); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg check file]get upg head addr:0x%x ret:0x%x \r\n", addr, ret); + goto end; + } + common_head = &(upg_head->common); + ret = upg_check_upg_file(addr, upg_head); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg check file]secure ret:0x%x \r\n", ret); + goto end; + } + /* Add check boot bin process. */ + if (common_head->file_type == HI_UPG_FILE_BOOT) { + section_head = (hi_upg_section_head *)hi_malloc(HI_MOD_ID_UPG, sizeof(hi_upg_section_head)); + if (section_head == HI_NULL) { + ret = HI_ERR_UPG_MALLOC_FAIL; + goto end; + } + memset_s(section_head, sizeof(hi_upg_section_head), 0, sizeof(hi_upg_section_head)); + ret = hi_flash_read(addr + common_head->section_offset, sizeof(hi_upg_section_head), (hi_u8 *)section_head); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg get section head]flash read ret:0x%x \r\n", ret); + goto end; + } + ret = upg_check_boot_file(addr + section_head->section0_offset, section_head->section0_len); + } +end: + upg_mem_free(upg_head); + upg_mem_free(section_head); + return ret; +} diff --git a/sdk_liteos/platform/system/upg/upg_check_file.h b/sdk_liteos/platform/system/upg/upg_check_file.h new file mode 100644 index 0000000000000000000000000000000000000000..d57d2a971f605be820bb8a45e3759c7776ae6fab --- /dev/null +++ b/sdk_liteos/platform/system/upg/upg_check_file.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __UPG_CHECK_FILE_H__ +#define __UPG_CHECK_FILE_H__ + +#include + +#define PRODUCT_UPG_FILE_IMAGE_ID 0x3C78961E +#define KERELN_VER_MAX 48 +#define KERNEL_VER_LEN 6 +#define BOOT_VER_MAX 16 +#define BOOT_VER_LEN 2 + +#define HI_UPG_FILE_ATTR_UNENCRYPT 0x1 /* kernel or flashboot attributes */ +#define HI_UPG_FILE_ATTR_ENCRYPT 0x2 /* kernel or flashboot attributes */ + +#define HI_UPG_FILE_ATTR_KERNELA 0x1 /* dual partition ota kernelA attributes */ +#define HI_UPG_FILE_ATTR_KERNELB 0x2 /* dual partition ota kernelB attributes */ +#define HI_UPG_FILE_ATTR_COMPRESSION 0x4 /* compression ota kernel or flashboot attributes */ + +#define HI_UPG_OTA_SETTINGS_MASK 0x3F + +hi_u32 upg_check_common_head(const hi_upg_common_head *head, hi_u32 head_size); +hi_u32 upg_get_common_head_from_flash(hi_u32 addr, hi_upg_common_head *head); +hi_u32 upg_get_section_head_from_flash(hi_u32 addr, hi_upg_section_head *section_head); +hi_u32 upg_verify_file(hi_u32 flash_addr); +#endif /* __UPG_CHECK_FILE_H__ */ + diff --git a/sdk_liteos/platform/system/upg/upg_check_secure.c b/sdk_liteos/platform/system/upg/upg_check_secure.c new file mode 100644 index 0000000000000000000000000000000000000000..fc23bf990466a697eafe0257c9db87c3d9013758 --- /dev/null +++ b/sdk_liteos/platform/system/upg/upg_check_secure.c @@ -0,0 +1,364 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include + +#if defined(CONFIG_FLASH_ENCRYPT_SUPPORT) +#include "kernel_crypto.h" +#endif + +hi_u8 g_upg_tool_block[HI_BLOCK_SIZE]; + +hi_u32 upg_is_secure_efuse(hi_bool *secure_flag) +{ + hi_u8 data = 0; + hi_u32 ret = hi_efuse_read(HI_EFUSE_SEC_BOOT_RW_ID, (hi_u8 *)(&data), (hi_u8)(sizeof(hi_u8))); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg]secure efuse read err:0x%x \r\n", ret); + return ret; + } + + if (data == UPG_SEC_BOOT_FLAG) { + *secure_flag = HI_FALSE; + } else { + *secure_flag = HI_TRUE; + } + return HI_ERR_SUCCESS; +} + +hi_u32 upg_hash_one_content(hi_u32 flash_addr, hi_u32 total_size, hi_u8 *hash, hi_u32 hash_size) +{ + hi_u8 *block = g_upg_tool_block; + uintptr_t offset; + uintptr_t this_size; + hi_cipher_hash_atts hash_atts; + + (hi_void) memset_s(&hash_atts, sizeof(hash_atts), 0, sizeof(hash_atts)); + hash_atts.sha_type = HI_CIPHER_HASH_TYPE_SHA256; + hi_u32 ret = hi_cipher_hash_start((hi_cipher_hash_atts *)(&hash_atts)); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg hash one content]cipher start ret:0x%x \r\n", ret); + return ret; + } + + for (offset = 0; offset < total_size;) { + this_size = ((total_size - offset) > HI_BLOCK_SIZE) ? HI_BLOCK_SIZE : (total_size - offset); + + ret = (hi_u32)memcpy_s(block, this_size, (hi_u8 *)(HI_FLASH_BASE + flash_addr + offset), this_size); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg hash one content]flash read ret:0x%x \r\n", ret); + (hi_void) hi_cipher_hash_final(hash, hash_size); + return ret; + } + + ret = hi_cipher_hash_update((uintptr_t)block, this_size); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg hash one content]hash update ret:0x%x \r\n", ret); + return ret; + } + offset += this_size; + } + return hi_cipher_hash_final(hash, hash_size); +} + +hi_u32 upg_hash_more_content(HI_CONST upg_verify_param *param, hi_u8 *hash, hi_u32 hash_size) +{ + hi_u8 *block = g_upg_tool_block; + uintptr_t offset; + uintptr_t this_size; + hi_cipher_hash_atts hash_atts; + + (hi_void) memset_s(&hash_atts, sizeof(hash_atts), 0, sizeof(hash_atts)); + hash_atts.sha_type = HI_CIPHER_HASH_TYPE_SHA256; + hi_u32 ret = hi_cipher_hash_start((hi_cipher_hash_atts *)(&hash_atts)); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg hash more content]cipher start ret:0x%x \r\n", ret); + return ret; + } + + for (hi_u32 i = 0; i < param->buffer_count; i++) { + uintptr_t size = param->total_size[i]; + for (offset = 0; offset < size;) { + this_size = ((size - offset) > HI_BLOCK_SIZE) ? HI_BLOCK_SIZE : (size - offset); + if (param->flash_flag[i]) { + ret = (hi_u32)memcpy_s(block, this_size, (hi_u8 *)(HI_FLASH_BASE + param->flash_addr[i] + offset), + this_size); + } else { + ret = (hi_u32)memcpy_s(block, HI_BLOCK_SIZE, (hi_u8 *)(param->flash_addr[i] + offset), this_size); + } + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg hash more content]get content ret:0x%x \r\n", ret); + (hi_void) hi_cipher_hash_final(hash, hash_size); + return ret; + } + + ret = hi_cipher_hash_update((uintptr_t)block, this_size); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg hash more content]hash update ret:0x%x \r\n", ret); + return ret; + } + offset += this_size; + } + } + return hi_cipher_hash_final(hash, hash_size); +} + +hi_u32 upg_convert_cipher_err(hi_u32 buffer_cnt, hi_u32 cipher_err) +{ + hi_u32 ret = cipher_err; + + if (cipher_err != HI_ERR_FAILURE) { + return ret; + } + if (buffer_cnt < 2) { /* 2: code section buf cnt */ + ret = HI_ERR_UPG_COMMON_HASH; + } else { + ret = HI_ERR_UPG_SECTION_HASH; + } + return ret; +} + +hi_u32 upg_secure_verify(HI_CONST upg_verify_param *param) +{ + hi_bool flag; + hi_u8 hash[SHA_256_LEN] = { 0 }; + hi_u32 ret = upg_hash_more_content(param, hash, sizeof(hash)); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg secure verify]hash more content ret:0x%x \r\n", ret); + return ret; + } + ret = upg_is_secure_efuse(&flag); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + if (flag != HI_TRUE) { + if (memcmp(param->sign, hash, SHA_256_LEN) != EOK) { + ret = HI_ERR_UPG_SECTION_SHA256; + } + /* Common head only check one content. */ + if ((ret != HI_ERR_SUCCESS) && (param->buffer_count < 2)) { /* 2: code section buf cnt */ + ret = HI_ERR_UPG_COMMON_SHA256; + } + return ret; + } + if (param->pad_mode == HI_MODE_ECC) { + hi_cipher_ecc_verify ecc_verify = { + .px = param->key_n, + .py = param->key_e, + .hash = hash, + .hash_len = PKE_LEN_32_BYTES, + .r = (hi_u8 *)param->sign, + .s = (hi_u8 *)param->sign + ECC_32_BYTES, + }; + ret = hi_cipher_ecc_verify_hash(&g_brain_pool_p256r1_verify, &ecc_verify); + } else { + hi_cipher_rsa_verify rsa_verify = { + .n = param->key_n, + .e = param->key_e, + .klen = RSA_2048_LEN, + .scheme = (hi_cipher_rsa_sign_scheme)(param->pad_mode), + }; + ret = hi_cipher_rsa_verify_hash(&rsa_verify, hash, PKE_LEN_32_BYTES, param->sign, sizeof(upg_rsa_sign)); + } + ret = upg_convert_cipher_err(param->buffer_count, ret); + upg_print("[upg secure verify]sign ret-mode:0x%x-0x%x \r\n", ret, param->pad_mode); + return ret; +} + +hi_void upg_get_subkey(hi_u8 *key, hi_u32 key_length, HI_CONST hi_upg_head *upg_head) +{ + hi_u32 key2_offset = sizeof(hi_upg_common_head) + key_length; + memset_s(key, key_length, 0, key_length); + if (upg_head->common.param.sign_alg == HI_MODE_ECC) { + if (memcpy_s(key, key_length, (hi_u8 *)upg_head + key2_offset, ECC_256_LEN) != EOK) { + return; + } + } else { + if (memcpy_s(key + key_length - RSA_EXP_E_LEN, RSA_EXP_E_LEN, (hi_u8 *)upg_head + key2_offset, RSA_EXP_E_LEN) + != EOK) { + return; + } + } +} + +hi_void upg_crypto_set_secure_verify_param(upg_verify_param *param, hi_u32 flash_addr, + const hi_upg_common_head *head) +{ + param->flash_addr[0] = (uintptr_t)flash_addr + head->section_offset; + param->total_size[0] = sizeof(hi_upg_section_head); + param->flash_flag[0] = HI_TRUE; +#if defined(CONFIG_FLASH_ENCRYPT_SUPPORT) && (!defined(CONFIG_COMPRESSION_OTA_SUPPORT)) + encrypt_ctx *para = encrypt_get_ctx(); + para->raw_buf = (hi_u8 *)hi_malloc(0, CRYPTO_KERNEL_LENGTH); + if (para->raw_buf == HI_NULL) { + return; + } + + hi_u32 ret = crypto_decrypt(para); + if (ret != HI_ERR_SUCCESS) { + param->buffer_count = 0; + return; + } + + param->flash_addr[1] = (uintptr_t)(para->raw_buf); + param->total_size[1] = para->encrypt_size; + param->flash_flag[1] = HI_FALSE; + param->flash_addr[FLASH_ADDR_NUM - 1] = flash_addr + head->section_offset + sizeof(hi_upg_section_head) + + sizeof(hi_upg_sign) + para->encrypt_size; + param->total_size[TOTAL_SIZE_NUM - 1] = head->section_len - sizeof(hi_upg_section_head) - sizeof(hi_upg_sign) - + para->encrypt_size; + param->flash_flag[FLASH_FLAG_NUM - 1] = HI_TRUE; + param->buffer_count = 3; /* 3 segments */ +#else + param->flash_addr[1] = flash_addr + head->section_offset + sizeof(hi_upg_section_head) + sizeof(hi_upg_sign); + param->total_size[1] = head->section_len - sizeof(hi_upg_section_head) - sizeof(hi_upg_sign); + param->flash_flag[1] = HI_TRUE; + param->buffer_count = 2; /* 2 segments */ +#endif +} + +hi_void upg_set_secure_verify_param(upg_verify_param *param, hi_u32 flash_addr, const hi_upg_common_head *head) +{ + if (head->file_type == HI_UPG_FILE_KERNEL) { + upg_crypto_set_secure_verify_param(param, flash_addr, head); + } else if (head->file_type == HI_UPG_FILE_BOOT) { + param->flash_addr[0] = (uintptr_t)flash_addr + head->section_offset; + param->total_size[0] = sizeof(hi_upg_section_head); + param->flash_flag[0] = HI_TRUE; + param->flash_addr[1] = flash_addr + head->section_offset + sizeof(hi_upg_section_head) + sizeof(hi_upg_sign); + param->total_size[1] = head->section_len - sizeof(hi_upg_section_head) - sizeof(hi_upg_sign); + param->flash_flag[1] = HI_TRUE; + param->buffer_count = 2; /* 2 segments */ + } +} + +hi_u32 upg_check_upg_file_code(hi_u32 flash_addr, hi_upg_head *upg_head) +{ + hi_upg_common_head *head = &(upg_head->common); + hi_u32 key_length = 0; + hi_u8 *key2 = HI_NULL; + hi_bool flag; + hi_u32 ret = upg_is_secure_efuse(&flag); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + hi_u8 *code_sign = hi_malloc(HI_MOD_ID_UPG, sizeof(hi_upg_sign)); + if (code_sign == HI_NULL) { + return HI_ERR_UPG_MALLOC_FAIL; + } + ret = hi_flash_read(flash_addr + head->section_offset + sizeof(hi_upg_section_head), + sizeof(hi_upg_sign), (hi_u8 *)code_sign); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg verify code]flash read ret:0x%x \r\n", ret); + goto end; + } + if (flag == HI_TRUE) { + key_length = (head->param.sign_alg == HI_MODE_ECC) ? ECC_256_LEN : RSA_2048_LEN; + key2 = hi_malloc(HI_MOD_ID_UPG, key_length); + if (key2 == HI_NULL) { + ret = HI_ERR_UPG_MALLOC_FAIL; + upg_print("[upg verify code] malloc fail. \r\n"); + goto end; + } + upg_get_subkey(key2, key_length, upg_head); + } + upg_verify_param param = { 0 }; + upg_set_secure_verify_param(¶m, flash_addr, head); + param.key_n = (hi_u8 *)upg_head + sizeof(hi_upg_common_head); + param.key_e = key2; + param.key_len = key_length; + param.sign = code_sign; + param.pad_mode = (hi_padding_mode)head->param.sign_alg; + ret = upg_secure_verify(¶m); + +#if (defined(CONFIG_FLASH_ENCRYPT_SUPPORT)) && (!defined(CONFIG_COMPRESSION_OTA_SUPPORT)) + encrypt_ctx *para = encrypt_get_ctx(); + crypto_mem_free(para->raw_buf); +#endif +end: + upg_mem_free(code_sign); + upg_clear_contset((hi_u8 *)key2, key_length); + upg_mem_free(key2); + return ret; +} + +hi_u32 upg_check_upg_file_head(hi_upg_head *upg_head) +{ + hi_upg_common_head *head = &(upg_head->common); + hi_u8 *key = HI_NULL; + hi_u32 key_length = 0; /* 2 key length: (px+py) or (key_n+key_e) */ + hi_bool flag; + hi_u32 ret = upg_is_secure_efuse(&flag); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + if (flag == HI_TRUE) { + key_length = (head->param.sign_alg < HI_MODE_ECC) ? RSA_KEY_LEN : ECC_KEY_LEN; + key = hi_malloc(HI_MOD_ID_UPG, key_length); + if (key == HI_NULL) { + ret = HI_ERR_UPG_MALLOC_FAIL; + upg_print("[upg verify code] malloc fail. \r\n"); + goto end; + } + memset_s(key, key_length, 0, key_length); + + /* Get key from flash */ + if (head->param.sign_alg == HI_MODE_ECC) { + ret = upg_get_ecc_key_from_boot(key, key_length); + } else { + ret = upg_get_rsa_key_from_boot(key, key_length); + } + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg verify head]fail ret:0x%x.\r\n", ret); + goto end; + } + } + upg_verify_param param = { 0 }; + param.flash_addr[0] = (uintptr_t)upg_head; + param.total_size[0] = sizeof(hi_upg_common_head) + head->key_len; + param.buffer_count = 1; /* 1 segments */ + param.key_n = key; + param.key_len = (key_length / 2); /* 2: ken len include (px+py) or (key_n+key_e) */ + param.key_e = key + param.key_len; + param.sign = (hi_u8 *)upg_head + sizeof(hi_upg_common_head) + head->key_len; + param.pad_mode = (hi_padding_mode)head->param.sign_alg; + ret = upg_secure_verify(¶m); +end: + upg_clear_contset((hi_u8 *)key, key_length); + upg_mem_free(key); + return ret; +} + +hi_u32 upg_check_upg_file(hi_u32 flash_addr, hi_upg_head *upg_head) +{ + hi_u32 ret = upg_check_upg_file_head(upg_head); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg check secure info]verify head,ret:0x%x \r\n", ret); + return ret; + } + + ret = upg_check_upg_file_code(flash_addr, upg_head); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg check secure info]verify code,ret:0x%x \r\n", ret); + return ret; + } + return HI_ERR_SUCCESS; +} + diff --git a/sdk_liteos/platform/system/upg/upg_check_secure.h b/sdk_liteos/platform/system/upg/upg_check_secure.h new file mode 100644 index 0000000000000000000000000000000000000000..1abf51797ba491c6f1b341d1c838d10c1dfe448e --- /dev/null +++ b/sdk_liteos/platform/system/upg/upg_check_secure.h @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __UPG_CHECK_SECURE_H__ +#define __UPG_CHECK_SECURE_H__ + +#include + +#define RSA_2048_LEN 256 +#define RSA_KEY_LEN 512 +#define ECC_KEY_LEN 64 +#define ECC_256_LEN 32 +#define HI_BLOCK_SIZE 0x100 + +#if defined(CONFIG_FLASH_ENCRYPT_SUPPORT) +#define FLASH_ADDR_NUM 3 +#define TOTAL_SIZE_NUM 3 +#define FLASH_FLAG_NUM 3 +#else +#define FLASH_ADDR_NUM 2 +#define TOTAL_SIZE_NUM 2 +#define FLASH_FLAG_NUM 2 +#endif + +#define UPG_SEC_BOOT_FLAG 0x42 + +typedef struct { + uintptr_t flash_addr[FLASH_ADDR_NUM]; + uintptr_t total_size[TOTAL_SIZE_NUM]; + hi_u32 buffer_count; + hi_bool flash_flag[FLASH_FLAG_NUM]; + hi_u16 pad; + hi_u8 *key_n; + hi_u8 *key_e; + hi_u8 *sign; + hi_u32 key_len; + hi_padding_mode pad_mode; +} upg_verify_param; + +hi_u32 upg_check_upg_file_code(hi_u32 flash_addr, hi_upg_head *upg_head); +hi_u32 upg_check_upg_file_head(hi_upg_head *upg_head); +hi_u32 upg_check_upg_file(hi_u32 flash_addr, hi_upg_head *upg_head); +hi_u32 upg_hash_one_content(hi_u32 flash_addr, hi_u32 total_size, hi_u8 *hash, hi_u32 hash_size); +hi_u32 upg_is_secure_efuse(hi_bool *secure_flag); + +#endif /* __UPG_CHECK_SECURE_H__ */ + diff --git a/sdk_liteos/platform/system/upg/upg_common.c b/sdk_liteos/platform/system/upg/upg_common.c new file mode 100644 index 0000000000000000000000000000000000000000..a9b91db652253e25ac7ff815702a2400f5870376 --- /dev/null +++ b/sdk_liteos/platform/system/upg/upg_common.c @@ -0,0 +1,1755 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include +#include +#include + +#if defined(CONFIG_FLASH_ENCRYPT_SUPPORT) +#include "kernel_crypto.h" +#endif + +upg_ctx g_upg_ctx = { 0 }; +volatile hi_u8 g_upg_updating_ver = UPG_UPDATE_VER_NONE; /* 非升级中;升级BOOT;升级kernel */ +volatile hi_bool g_upg_update_ver_success = HI_FALSE; +hi_u8 g_upg_efuse_data_boot_ver[BOOT_VER_LEN] = {0}; +hi_u8 g_upg_efuse_data_kernel_ver[KERNEL_VER_LEN] = {0}; + +/************************the following functions are inner functions************************************/ +upg_ctx *upg_get_ctx(hi_void) +{ + return &g_upg_ctx; +} + +hi_bool upg_is_init(hi_void) +{ + upg_ctx *ctx = upg_get_ctx(); + return ctx->is_init; +} + +hi_bool upg_is_transmit_finish(hi_void) +{ + upg_ctx *ctx = upg_get_ctx(); + return ctx->transmit_finish_flag; +} + +hi_u32 upg_lock(hi_void) +{ + upg_ctx *ctx = upg_get_ctx(); + return hi_sem_wait(ctx->upg_sem, HI_SYS_WAIT_FOREVER); +} + +hi_u32 upg_unlock(hi_void) +{ + upg_ctx *ctx = upg_get_ctx(); + return hi_sem_signal(ctx->upg_sem); +} + +hi_bool upg_is_upg_process(hi_void) +{ + upg_ctx *ctx = upg_get_ctx(); + hi_bool flag; + hi_u32 ret = HI_ERR_FAILURE; + if (upg_is_init()) { + ret = upg_lock(); + } + flag = ctx->is_upg_process; + if (ret == HI_ERR_SUCCESS) { + upg_unlock(); + } + + return flag; +} + +hi_void upg_set_upg_process(hi_bool is_upg_process) +{ + upg_ctx *ctx = upg_get_ctx(); + hi_u32 ret = HI_ERR_FAILURE; + if (upg_is_init()) { + ret = upg_lock(); + } + ctx->is_upg_process = is_upg_process; + if (ret == HI_ERR_SUCCESS) { + upg_unlock(); + } +} + +hi_void upg_get_boot_key_addr(hi_void) +{ + hi_u32 val; + hi_u32 rsa_key_addr = { 0 }; + hi_u32 ecc_key_addr = { 0 }; + upg_ctx *ctx = upg_get_ctx(); + + hi_reg_read16(DIAG_CTL_GP_REG0_REG, val); + rsa_key_addr = rsa_key_addr | val; + hi_reg_read16(DIAG_CTL_GP_REG1_REG, val); + rsa_key_addr = rsa_key_addr | (val << BIT_U16); + ctx->rsa_key_addr = rsa_key_addr; + + hi_reg_read16(DIAG_CTL_GP_REG2_REG, val); + ecc_key_addr = ecc_key_addr | val; + hi_reg_read16(DIAG_CTL_GP_REG3_REG, val); + ecc_key_addr = ecc_key_addr | (val << BIT_U16); + ctx->ecc_key_addr = ecc_key_addr; +} + +hi_bool upg_tool_bit_test(const hi_u8 *data, hi_u16 pos, hi_u16 data_len) +{ + hi_u16 base = pos / BIT_U8; + hi_u16 i = pos % BIT_U8; + if (pos > (data_len * BIT_U8)) { + return HI_FALSE; + } + return (hi_bool)bit_get(data[base], i); +} + +hi_void upg_tool_bit_set(hi_u8 *data, hi_u16 pos, hi_u8 val) +{ + hi_u16 base = pos / BIT_U8; + hi_u16 i = pos % BIT_U8; + bit_set(data[base], i, val); +} + +hi_void upg_clear_contset(hi_u8 *content, hi_u32 content_len) +{ + if ((content == HI_NULL) || (content_len == 0)) { + return; + } + + (hi_void)memset_s(content, content_len, 0x0, content_len); +} + +/* + Decompress NV conditions: + 1. The decompressed NV flag exists; + 2. nv file header error (no NV file backup area for wifi); + 3. Upgrade and non-boot upgrade. + */ +hi_bool upg_is_refresh_nv(const hi_nv_ftm_startup_cfg *cfg) +{ + if (cfg->refresh_nv == ENV_REFRESH_NV) { + upg_print("[upg refresh nv]flag is true \r\n"); + return HI_TRUE; + } + + if ((cfg->mode == HI_UPG_MODE_UPGRADE) && (cfg->file_type != HI_UPG_FILE_BOOT)) { + upg_print("[upg refresh nv]mode-filetype:0x%x-0x%x \r\n", cfg->mode, cfg->file_type); + return HI_TRUE; + } + return HI_FALSE; +} + +hi_u32 upg_refresh_nv(hi_void) +{ + hi_nv_ftm_startup_cfg cfg; + hi_upg_section_head section_head = { 0 }; + hi_u32 ret = upg_get_start_up_nv(&cfg); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + /* Not need to decompress NV during normal startup, which is a normal branch and returns successfully. */ + if (upg_is_refresh_nv(&cfg) == HI_FALSE) { + return HI_ERR_SUCCESS; + } + + /* Replace nv first and then initialize NV. */ + ret = upg_get_section_head_from_flash(cfg.addr_start, §ion_head); + if (ret != HI_ERR_SUCCESS) { + return HI_ERR_UPG_GET_SECTION_HEAD; + } + + hi_u32 nv_addr = cfg.addr_start + section_head.section1_offset; + hi_u32 nv_size = section_head.section1_len; + if (nv_size != HI_NV_DEFAULT_BLOCK_SIZE) { + return HI_ERR_UPG_NV_SIZE; + } + hi_pvoid buf = hi_malloc(HI_MOD_ID_UPG, section_head.section1_len); + if (buf == HI_NULL) { + return HI_ERR_MALLOC_FAILUE; + } + ret = hi_flash_read(nv_addr, nv_size, buf); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg refresh nv]flash read fail:nvfrom-nvsize-ret:0x%x-0x%x-0x%x \r\n", nv_addr, nv_size, ret); + goto fail; + } + ret = hi_nv_flush_keep_ids(buf, nv_size); + if (ret != HI_ERR_SUCCESS) { + goto fail; + } + ret = hi_nv_block_write(buf, nv_size, 0); + if (ret != HI_ERR_SUCCESS) { + goto fail; + } + + hi_u32 normal_nv_addr = 0; + hi_u32 normal_nv_size = 0; + ret = hi_get_normal_nv_partition_table(&normal_nv_addr, &normal_nv_size); + if (ret == HI_ERR_SUCCESS) { + ret = hi_nv_init(normal_nv_addr, normal_nv_size, nv_size); + } + +fail: + hi_free(HI_MOD_ID_UPG, (hi_pvoid)buf); + upg_print("[upg]refresh nv ret 0x%x \r\n", ret); + return ret; +} + +hi_u32 upg_get_start_up_cfg(hi_nv_ftm_startup_cfg *cfg) +{ + hi_nv_ftm_startup_cfg tmp_data = { 0 }; + hi_u32 ret = upg_get_start_up_nv(&tmp_data); + if (ret == HI_ERR_SUCCESS) { + if (memcpy_s(cfg, sizeof(hi_nv_ftm_startup_cfg), &tmp_data, sizeof(hi_nv_ftm_startup_cfg)) != EOK) { + return HI_ERR_FAILURE; + } + } + return ret; +} + +hi_u32 upg_set_start_up_cfg(hi_nv_ftm_startup_cfg *cfg) +{ + hi_nv_ftm_startup_cfg current_data = { 0 }; + hi_u32 ret = upg_get_start_up_nv(¤t_data); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + if (memcmp(cfg, ¤t_data, sizeof(hi_nv_ftm_startup_cfg))) { + ret = upg_save_start_up_nv(cfg); + upg_print("[upg set env]ret:0x%x \r\n", ret); + } + return ret; +} + +hi_u32 upg_get_code_file_ver(hi_u8 *ver) +{ + hi_upg_common_head *head = HI_NULL; + hi_nv_ftm_startup_cfg cfg; + hi_u32 ret = upg_get_start_up_cfg(&cfg); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg get file ver]get env ret:0x%x \r\n", ret); + return ret; + } + + head = hi_malloc(HI_MOD_ID_UPG, sizeof(hi_upg_common_head)); + if (head == HI_NULL) { + upg_print("[upg get file ver]malloc fail \r\n"); + return HI_ERR_UPG_MALLOC_FAIL; + } + memset_s(head, sizeof(hi_upg_common_head), 0, sizeof(hi_upg_common_head)); + ret = upg_get_common_head_from_flash(cfg.addr_start, head); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg get file ver]get head ret:0x%x \r\n", ret); + hi_free(HI_MOD_ID_UPG, head); + return ret; + } + *ver = head->file_version; + hi_free(HI_MOD_ID_UPG, head); + upg_print("[upg get file ver]ver:%d \r\n", *ver); + return ret; +} + +hi_u32 upg_set_efuse_code_ver(hi_void) +{ + hi_u8 pos; + hi_u32 ret; + hi_u8 upg_ver; + hi_u8 current_ver; + hi_bool flag; + + ret = upg_is_secure_efuse(&flag); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg set kernel ver]get secure efuse,err:0x%x \r\n", ret); + return ret; + } + + if (flag == HI_FALSE) { + upg_print("[upg set kernel ver]not secure boot.\r\n"); + return HI_ERR_SUCCESS; + } + + ret = upg_get_efuse_code_ver(¤t_ver); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg set kernel ver]get ver ret:0x%x\r\n", ret); + return ret; + } + + ret = upg_get_code_file_ver(&upg_ver); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg set kernel ver]get head ret:0x%x \r\n", ret); + return ret; + } + + if (upg_ver < current_ver) { + upg_print("[upg set kernel ver]current>file:0%d-%d \r\n", current_ver, upg_ver); + return HI_ERR_UPG_LOW_KERNEL_VER; + } + + if ((current_ver == KERELN_VER_MAX) && (upg_ver > KERELN_VER_MAX)) { + upg_print("[upg set kernel ver]current ver:%d \r\n", upg_ver); + return HI_ERR_UPG_FULL_KERNEL_VER; + } + + if (upg_ver == current_ver) { + upg_print("[upg set kernel ver]same ver:%d \r\n", upg_ver); + return HI_ERR_SUCCESS; + } + + (hi_void) memset_s(g_upg_efuse_data_kernel_ver, KERNEL_VER_LEN, 0, KERNEL_VER_LEN); + for (pos = current_ver; ((pos < upg_ver) && (pos < KERELN_VER_MAX)); pos++) { + upg_tool_bit_set(g_upg_efuse_data_kernel_ver, pos, SRV_BIT_HIGH); + } + ret = upg_start_and_wait_update_ver(UPG_UPDATE_VER_FIRMARE); + + upg_print("[upg set kernel ver]ret:0x%x \r\n", ret); + return ret; +} + +hi_u32 upg_get_kernel_size(hi_void) +{ + upg_ctx *ctx = upg_get_ctx(); + return ctx->cur_kernel_size; +} + +hi_u32 upg_set_kernel_size(hi_u32 addr_start) +{ + upg_ctx *ctx = upg_get_ctx(); + hi_u32 kernel_size = 0; + hi_u32 ret = hi_flash_read(addr_start + hi_fieldoffset(hi_upg_common_head, file_len), sizeof(hi_u32), + (hi_u8 *)(&kernel_size)); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg set kernel size]ret:0x%x \r\n", ret); + return ret; + } + ctx->cur_kernel_size = upg_align_next(kernel_size, UPG_FLASH_BLOCK_SIZE); + return HI_ERR_SUCCESS; +} + +hi_u32 upg_mode_init(hi_void) +{ + hi_nv_ftm_startup_cfg cfg = { 0 }; + hi_u32 ret = upg_get_start_up_cfg(&cfg); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg mode init]get env fail:0x%x \r\n", ret); + return ret; + } + + if (cfg.mode != HI_UPG_MODE_UPGRADE) { + if (cfg.refresh_nv == ENV_REFRESH_NV) { + cfg.refresh_nv = 0; + (hi_void) upg_set_start_up_cfg(&cfg); + } + } + + if (cfg.reset_cnt > 0) { + upg_print("[upg mode init]resetcnt:0x%x \r\n", cfg.reset_cnt); + cfg.reset_cnt = 0; + cfg.mode = HI_UPG_MODE_NORMAL; + cfg.refresh_nv = 0; + ret = upg_set_start_up_cfg(&cfg); + if (cfg.file_type == HI_UPG_FILE_KERNEL) { + ret |= upg_set_efuse_code_ver(); + upg_print("[upg mode init]upg set code version ret:0x%x \r\n", ret); + } + } + ret |= upg_set_kernel_size(cfg.addr_start); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg mode init]fail:0x%x \r\n", ret); + } + return ret; +} + +hi_u32 upg_cache_ctrl(hi_u32 offset, hi_u8 *buf, hi_u32 buf_len, hi_bool is_write) +{ + hi_u32 ret; + hi_u32 cache_addr; + upg_ctx *ctx = upg_get_ctx(); + + if (buf == HI_NULL) { + return HI_ERR_UPG_NULL_POINTER; + } + + if (((offset + buf_len) > (ctx->common_head.file_len)) || + ((offset + buf_len) < buf_len)) { + upg_print("[upg cache ctrl]error param:0x%x-0x%x-0x%x \r\n", offset, buf_len, ctx->common_head.file_len); + return HI_ERR_UPG_PARAMETER; + } + + cache_addr = ctx->file_addr; + if (is_write == HI_FALSE) { + ret = hi_flash_read(offset + cache_addr, buf_len, (hi_u8 *)buf); + } else { + ret = hi_flash_write(offset + cache_addr, buf_len, (hi_u8 *)buf, HI_FALSE); + } + return ret; +} + +hi_void upg_clear_ctx(hi_void) +{ + upg_ctx *ctx = upg_get_ctx(); + hi_u32 ret = HI_ERR_FAILURE; + if (upg_is_init()) { + ret = upg_lock(); + } + ctx->is_upg_process = HI_FALSE; + ctx->check_head_flag = HI_FALSE; + ctx->transmit_finish_flag = HI_FALSE; + ctx->cache_size = 0; + ctx->file_addr = 0; + memset_s(&ctx->common_head, sizeof(hi_upg_common_head), 0, sizeof(hi_upg_common_head)); + if (ret == HI_ERR_SUCCESS) { + upg_unlock(); + } +} + +hi_u32 upg_clear_wait_mode(hi_nv_ftm_upg_wait_mode *mode) +{ + hi_u32 ret = memset_s(mode, sizeof(hi_nv_ftm_upg_wait_mode), 0, sizeof(hi_nv_ftm_upg_wait_mode)); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + ret = upg_save_wait_mode_nv(mode); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + return HI_ERR_SUCCESS; +} + +hi_void upg_check_clear_wait_mode(hi_void) +{ + hi_nv_ftm_upg_wait_mode mode_cfg = {0}; + hi_u32 ret = upg_get_wait_mode_nv(&mode_cfg); + if (ret != HI_ERR_SUCCESS) { + upg_print("[check wait mode]ret=0x%x\r\n", ret); + } + + if ((mode_cfg.trans_finish_flag == HI_TRUE) || (mode_cfg.is_upg_process == HI_TRUE)) { + ret = upg_clear_wait_mode(&mode_cfg); + if (ret != HI_ERR_SUCCESS) { + upg_print("[clear wait mode]ret=0x%x\r\n", ret); + } + } +} + +hi_void upg_check_clear_upg_mode(hi_void) +{ + hi_nv_ftm_startup_cfg cfg = { 0 }; + hi_u32 ret = upg_get_start_up_cfg(&cfg); + if (ret != HI_ERR_SUCCESS) { + upg_print("[clear upg mode]get env fail,ret:0x%x.\r\n", ret); + } + + if (cfg.mode == HI_UPG_MODE_UPGRADE_WAIT) { + cfg.mode = HI_UPG_MODE_NORMAL; + ret = upg_set_start_up_cfg(&cfg); + if (ret != HI_ERR_SUCCESS) { + upg_print("[clear upg mode]set env fail,ret=0x%x\r\n", ret); + } + } +} + +/* + 1. Modify to the correct boot mode and boot area; + 2. nv file recovery; + 3. Local global variable recovery. + + */ +hi_u32 upg_stop(hi_u32 error_no) +{ + hi_nv_ftm_startup_cfg cfg = { 0 }; + hi_u32 ret; + + hi_unref_param(error_no); + upg_check_clear_wait_mode(); + upg_print("[upg stop]reason:0x%x.\r\n", error_no); + if (upg_is_upg_process() == HI_FALSE) { + upg_print("[upg stop]is not upg process.\r\n"); + return HI_ERR_UPG_NOT_START; + } + + ret = upg_get_start_up_cfg(&cfg); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg stop]get env fail,ret:0x%x.\r\n", ret); + return ret; + } + if ((cfg.mode == HI_UPG_MODE_UPGRADE) && (cfg.file_type == HI_UPG_FILE_KERNEL)) { +#if defined(CONFIG_COMPRESSION_OTA_SUPPORT) + ret = hi_flash_erase(cfg.addr_write, UPG_FLASH_BLOCK_SIZE); + upg_print("[upg stop]erase ret-addr:0x%x-0x%x.\r\n", ret, cfg.addr_write); +#else + hi_flash_partition_table *partition = hi_get_partition_table(); + uintptr_t kernel_a_addr = partition->table[HI_FLASH_PARTITON_KERNEL_A].addr; + uintptr_t kernel_b_addr = partition->table[HI_FLASH_PARTITON_KERNEL_B].addr; + + ret = hi_flash_erase(cfg.addr_start, UPG_FLASH_BLOCK_SIZE); + upg_print("[upg stop]dual erase ret-addr:0x%x-0x%x.\r\n", ret, cfg.addr_start); + if (cfg.addr_start == kernel_a_addr) { + cfg.addr_start = kernel_b_addr; + } else { + cfg.addr_start = kernel_a_addr; + } +#endif + } + if (cfg.file_type == HI_UPG_FILE_KERNEL) { + cfg.addr_write = 0; + } + + cfg.mode = HI_UPG_MODE_NORMAL; + cfg.file_type = 0; + cfg.refresh_nv = 0; + ret = upg_set_start_up_cfg(&cfg); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + upg_clear_ctx(); + upg_print("[upg stop]ret:0x%x \r\n", ret); + return ret; +} + +hi_u32 upg_check_head(hi_void) +{ + upg_ctx *ctx = upg_get_ctx(); + hi_u32 addr = ctx->file_addr; + hi_u32 ret; + hi_upg_head *upg_head = hi_malloc(HI_MOD_ID_UPG, sizeof(hi_upg_head)); + if (upg_head == HI_NULL) { + return HI_ERR_UPG_MALLOC_FAIL; + } + ret = hi_flash_read(addr, sizeof(hi_upg_head), (hi_u8 *)upg_head); + if (ret != HI_ERR_SUCCESS) { + upg_mem_free(upg_head); + return ret; + } + + ret = upg_check_upg_file_head(upg_head); + upg_print("[upg check head]verify head,ret:0x%x. \r\n", ret); + upg_mem_free(upg_head); + return ret; +} + +hi_u32 upg_get_cache_clear_info(hi_u8 file_type, hi_u32 file_len, hi_u32 *addr, hi_u32 *size) +{ + hi_flash_partition_table *partition = hi_get_partition_table(); + + if (file_type == HI_UPG_FILE_BOOT) { + *addr = partition->table[HI_FLASH_PARTITON_BOOT_BACK].addr; + *size = partition->table[HI_FLASH_PARTITON_BOOT_BACK].size; + } else { +#if defined(CONFIG_COMPRESSION_OTA_SUPPORT) + hi_u32 erase_start_addr = partition->table[HI_FLASH_PARTITON_KERNEL_B].addr + + partition->table[HI_FLASH_PARTITON_KERNEL_B].size - file_len; + hi_u32 erase_end_addr = erase_start_addr + file_len; + erase_start_addr = upg_align_pre(erase_start_addr, UPG_FLASH_BLOCK_SIZE); + erase_end_addr = upg_align_next(erase_end_addr, UPG_FLASH_BLOCK_SIZE); + *addr = erase_start_addr; + *size = erase_end_addr - erase_start_addr; +#else + uintptr_t kernel_a_addr = partition->table[HI_FLASH_PARTITON_KERNEL_A].addr; + uintptr_t kernel_b_addr = partition->table[HI_FLASH_PARTITON_KERNEL_B].addr; + hi_nv_ftm_startup_cfg cfg; + hi_u32 ret = upg_get_start_up_cfg(&cfg); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + /* Change area, read NV to get the current startup address and change to another area. */ + if (cfg.addr_start == kernel_a_addr) { + *addr = kernel_b_addr; + *size = partition->table[HI_FLASH_PARTITON_KERNEL_B].size; + } else if (cfg.addr_start == kernel_b_addr) { + *addr = kernel_a_addr; + *size = partition->table[HI_FLASH_PARTITON_KERNEL_A].size; + } else { + return HI_ERR_UPG_START_ADDR; + } +#endif + } + upg_print("[upg clear info]filetype-filelen-addr-size:0x%x-0x%x-0x%x-0x%x\r\n", file_type, file_len, *addr, *size); + return HI_ERR_SUCCESS; +} + +hi_u32 upg_get_backup_write_addr(hi_u8 file_type, hi_u32 file_len, hi_u32 *addr) +{ + hi_flash_partition_table *partition = hi_get_partition_table(); + + if (file_type == HI_UPG_FILE_BOOT) { + uintptr_t boot_bak_addr = partition->table[HI_FLASH_PARTITON_BOOT_BACK].addr + + partition->table[HI_FLASH_PARTITON_BOOT_BACK].size; + *addr = boot_bak_addr - file_len; + } else { +#if defined(CONFIG_COMPRESSION_OTA_SUPPORT) + hi_u32 erase_st_addr = partition->table[HI_FLASH_PARTITON_KERNEL_B].addr + + partition->table[HI_FLASH_PARTITON_KERNEL_B].size - file_len; + erase_st_addr = upg_align_pre(erase_st_addr, UPG_FLASH_BLOCK_SIZE); + *addr = erase_st_addr; +#else + uintptr_t kernel_a_addr = partition->table[HI_FLASH_PARTITON_KERNEL_A].addr; + uintptr_t kernel_b_addr = partition->table[HI_FLASH_PARTITON_KERNEL_B].addr; + hi_nv_ftm_startup_cfg cfg; + hi_u32 ret = upg_get_start_up_cfg(&cfg); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + /* Change area, read NV to get the current startup address and change to another area. */ + if (cfg.addr_start == kernel_a_addr) { + *addr = kernel_b_addr; + } else if (cfg.addr_start == kernel_b_addr) { + *addr = kernel_a_addr; + } else { + return HI_ERR_UPG_START_ADDR; + } +#endif + } + return HI_ERR_SUCCESS; +} + +hi_u32 upg_get_max_file_len(hi_u8 file_type, hi_u32 *file_len) +{ + hi_u32 ret = HI_ERR_SUCCESS; + hi_flash_partition_table *partition = hi_get_partition_table(); +#if defined(CONFIG_COMPRESSION_OTA_SUPPORT) + if (file_type == HI_UPG_FILE_BOOT) { + *file_len = partition->table[HI_FLASH_PARTITON_BOOT_BACK].size; + } else { + hi_u32 end_addr = partition->table[HI_FLASH_PARTITON_KERNEL_B].addr + + partition->table[HI_FLASH_PARTITON_KERNEL_B].size; + hi_u32 start_addr = partition->table[HI_FLASH_PARTITON_KERNEL_A].addr; + hi_u32 current_kernel_size = upg_get_kernel_size(); + if (current_kernel_size == 0) { + ret = HI_ERR_UPG_KERNEL_LEN; + } else { + *file_len = end_addr - start_addr - current_kernel_size; + } + } +#else + hi_nv_ftm_startup_cfg cfg = { 0 }; + ret = upg_get_start_up_cfg(&cfg); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg get max len]error:0x%x \r\n", ret); + return ret; + } + if (file_type == HI_UPG_FILE_BOOT) { + *file_len = partition->table[HI_FLASH_PARTITON_BOOT_BACK].size; + } else if (cfg.addr_start == partition->table[HI_FLASH_PARTITON_KERNEL_A].addr) { + *file_len = partition->table[HI_FLASH_PARTITON_KERNEL_B].size; + } else if (cfg.addr_start == partition->table[HI_FLASH_PARTITON_KERNEL_B].addr) { + *file_len = partition->table[HI_FLASH_PARTITON_KERNEL_A].size; + } else { + ret = HI_ERR_UPG_PARAMETER; + } +#endif + return ret; +} + +hi_u32 upg_cache_clear(hi_u8 file_type, hi_u32 file_len) +{ + hi_u32 backup_addr = 0; + hi_u8 i; + hi_u32 backup_size = 0; + hi_u32 ret = upg_get_cache_clear_info(file_type, file_len, &backup_addr, &backup_size); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg clear]get info:0x%x\r\n", ret); + return ret; + } + upg_print("[upg clear]start :%d \r\n", hi_get_milli_seconds()); + + for (i = 0; i < UPG_FLASH_RETRY_TIMES; i++) { + ret = hi_flash_erase(backup_addr, backup_size); + if (ret == HI_ERR_SUCCESS) { + break; + } + } + upg_print("[upg clear]end :%d \r\n", hi_get_milli_seconds()); + return ret; +} + +hi_u32 upg_set_flash_write_addr(hi_void) +{ + hi_u32 write_addr; + upg_ctx *ctx = upg_get_ctx(); + hi_u32 ret = upg_get_backup_write_addr(ctx->common_head.file_type, ctx->common_head.file_len, &write_addr); + if (ret == HI_ERR_SUCCESS) { + ctx->file_addr = write_addr; + } + upg_print("[upg write addr]ret-addr-size:0x%x-0x%x-0x%x\r\n", ret, ctx->file_addr, ctx->common_head.file_len); + return ret; +} + +hi_u32 upg_start(hi_u8 *buf, hi_u32 buf_len) +{ + hi_nv_ftm_startup_cfg cfg = { 0 }; + hi_upg_common_head *head = HI_NULL; + upg_ctx *ctx = upg_get_ctx(); + hi_u32 ret; + + if (buf == HI_NULL) { + return HI_ERR_UPG_PARAMETER; + } + + /* The first packet cannot be less than 96 bytes. */ + if (buf_len < sizeof(hi_upg_common_head)) { + return HI_ERR_UPG_BUF_LEN; + } + head = (hi_upg_common_head *)buf; + ret = upg_check_common_head(head, sizeof(hi_upg_common_head)); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + ret = upg_get_start_up_cfg(&cfg); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + cfg.file_type = 0; + cfg.reset_cnt = 0; + + /* Record file header information. */ + if (memcpy_s(&(ctx->common_head), sizeof(hi_upg_common_head), head, sizeof(hi_upg_common_head)) != EOK) { + return HI_ERR_FAILURE; + } + ctx->cache_size = 0; + + /* Erase FLASH. */ + ret = upg_cache_clear(head->file_type, head->file_len); + if (ret == HI_ERR_SUCCESS) { + ret = upg_set_flash_write_addr(); + ctx->transmit_finish_flag = HI_FALSE; + upg_set_upg_process(HI_TRUE); + } + + if (head->file_type == HI_UPG_FILE_KERNEL) { + cfg.addr_write = ctx->file_addr; + } + + if (ret == HI_ERR_SUCCESS) { + ret = upg_set_start_up_cfg(&cfg); + } + return ret; +} + +hi_u32 upg_cache_write(hi_u32 offset, hi_u8 *buf, hi_u32 buf_len) +{ + return upg_cache_ctrl(offset, buf, buf_len, HI_TRUE); +} + +hi_u32 upg_start_and_wait_update_ver(hi_u8 update_ver_type) +{ + if (update_ver_type != UPG_UPDATE_VER_FIRMARE + && update_ver_type != UPG_UPDATE_VER_BOOT) { + return HI_ERR_UPG_UPDATE_VER_INVALID_PARAM; + } + + /* init upg flag */ + g_upg_updating_ver = update_ver_type; + g_upg_update_ver_success = HI_FALSE; + + /* trigger upg nmi */ + hi_reg_setbit(UPG_NMI_BASE_ADDRESS + UPG_NMI_CTRL, UPG_NMI_INT_MOD_DONE_EN_POS); + + /* wait nmi handle finish */ + hi_u32 wait_cnt = 1000; /* wait 10s */ + hi_u32 try_cnt = 0; + /* 小型化和场景考虑,此处实现不采用事件通知 */ + for (try_cnt = 0; try_cnt < wait_cnt; try_cnt++) { + if (g_upg_updating_ver == UPG_UPDATE_VER_NONE) { + break; + } + hi_sleep(10); /* sleep 10ms */ + } + + if (g_upg_update_ver_success == HI_TRUE) { + return HI_ERR_SUCCESS; + } else if (try_cnt == wait_cnt) { + return HI_ERR_UPG_UPDATE_VER_TIMEOUT; + } else { + return HI_ERR_UPG_UPDATE_VER_FAIL; + } +} + +hi_u32 upg_get_efuse_code_ver(hi_u8 *ver) +{ + hi_u8 pos; + hi_u8 efuse_data[KERNEL_VER_LEN]; + hi_u32 ret; + + (hi_void) memset_s(efuse_data, KERNEL_VER_LEN, 0, KERNEL_VER_LEN); + ret = hi_efuse_read(HI_EFUSE_TEE_KERNEL_VER_RW_ID, efuse_data, sizeof(efuse_data)); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + for (pos = 0; pos < KERELN_VER_MAX; pos++) { + if (upg_tool_bit_test(efuse_data, pos, KERNEL_VER_LEN) == HI_FALSE) { + break; + } + } + if (pos >= KERELN_VER_MAX) { + *ver = KERELN_VER_MAX; + } else { + *ver = pos; + } + return ret; +} + +hi_u32 upg_get_efuse_boot_ver(hi_u8 *ver) +{ + hi_u8 pos; + hi_u8 efuse_data[BOOT_VER_LEN] = { 0 }; + hi_u32 ret = hi_efuse_read(HI_EFUSE_TEE_BOOT_VER_RW_ID, efuse_data, sizeof(efuse_data)); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + for (pos = 0; pos < BOOT_VER_MAX; pos++) { + if (upg_tool_bit_test(efuse_data, pos, BOOT_VER_LEN) == HI_FALSE) { + break; + } + } + if (pos >= BOOT_VER_MAX) { + *ver = BOOT_VER_MAX; + } else { + *ver = pos; + } + return ret; +} + +hi_void upg_get_boot_file_ver(hi_u8 *ver) +{ + upg_ctx *ctx = upg_get_ctx(); + *ver = ctx->common_head.file_version; +} + +hi_u32 upg_set_efuse_boot_ver(hi_void) +{ + hi_u8 pos; + hi_u32 ret; + hi_u8 upg_ver; + hi_u8 current_ver; + hi_bool flag; + + ret = upg_is_secure_efuse(&flag); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg set boot ver]get secure efuse,err:0x%x \r\n", ret); + return ret; + } + + if (flag == HI_FALSE) { + upg_print("[upg set boot ver]not secure boot.\r\n"); + return HI_ERR_SUCCESS; + } + + ret = upg_get_efuse_boot_ver(¤t_ver); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg set boot ver]get ver ret:0x%x \r\n", ret); + return ret; + } + upg_get_boot_file_ver(&upg_ver); + + if (upg_ver < current_ver) { + upg_print("[upg set boot ver]current>file:%d-%d \r\n", current_ver, upg_ver); + return HI_ERR_UPG_LOW_BOOT_VER; + } + + if ((current_ver == BOOT_VER_MAX) && (upg_ver > BOOT_VER_MAX)) { + upg_print("[upg set boot ver]current ver:%d \r\n", upg_ver); + return HI_ERR_UPG_FULL_BOOT_VER; + } + + if (upg_ver == current_ver) { + upg_print("[upg set boot ver]same ver:%d \r\n", upg_ver); + return HI_ERR_SUCCESS; + } + (hi_void) memset_s(g_upg_efuse_data_boot_ver, BOOT_VER_LEN, 0, BOOT_VER_LEN); + for (pos = current_ver; ((pos < upg_ver) && (pos < BOOT_VER_MAX)); pos++) { + upg_tool_bit_set(g_upg_efuse_data_boot_ver, pos, SRV_BIT_HIGH); + } + ret = upg_start_and_wait_update_ver(UPG_UPDATE_VER_BOOT); + upg_print("[upg set boot ver]ret:0x%x \r\n", ret); + return ret; +} + +hi_u32 upg_refresh_boot(hi_u32 addr) +{ + hi_u32 offset; + hi_u32 total_size; + hi_u32 this_size; + hi_upg_section_head section_head = { 0 }; + + hi_flash_partition_table *partiton = hi_get_partition_table(); + hi_u32 boot_addr = partiton->table[HI_FLASH_PARTITON_BOOT].addr; + hi_u32 boot_size = partiton->table[HI_FLASH_PARTITON_BOOT].size; + hi_u32 ret = upg_get_section_head_from_flash(addr, §ion_head); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg refresh boot]get section head ret:0x%x \r\n", ret); + return ret; + } + total_size = section_head.section0_len; + if ((total_size == 0) || (total_size > boot_size)) { + upg_print("[upg refresh boot]total size:0x%x \r\n", total_size); + return HI_ERR_UPG_FILE_LEN; + } + + hi_u8 *buf = hi_malloc(HI_MOD_ID_UPG, UPG_FLASH_BLOCK_SIZE); + if (buf == HI_NULL) { + return HI_ERR_UPG_MALLOC_FAIL; + } + upg_print("[upg eraseboot]starttime:%d \r\n", hi_get_milli_seconds()); + ret = hi_flash_erase(boot_addr, boot_size); + upg_print("[upg erase]ret-addr-size-end:0x%x-0x%x-0x%x-%d\r\n", ret, boot_addr, boot_size, hi_get_milli_seconds()); + if (ret != HI_ERR_SUCCESS) { + hi_free(HI_MOD_ID_UPG, buf); + return ret; + } + + for (offset = 0; offset < total_size;) { + this_size = (total_size - offset > UPG_FLASH_BLOCK_SIZE) ? UPG_FLASH_BLOCK_SIZE : (total_size - offset); + ret = hi_flash_read(addr + section_head.section0_offset + offset, this_size, buf); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg refresh boot]flash read ret:0x%x \r\n", ret); + break; + } + ret = hi_flash_write(boot_addr + offset, this_size, buf, HI_FALSE); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg refresh boot]flash write ret:0x%x \r\n", ret); + break; + } + offset += this_size; + } + hi_free(HI_MOD_ID_UPG, buf); + return ret; +} + +hi_u32 upg_get_boot_encrypt_flag(HI_CONST boot_header *head, hi_u8 *flag) +{ + hi_flash_partition_table *partiton = hi_get_partition_table(); + hi_u32 boot_addr = partiton->table[HI_FLASH_PARTITON_BOOT].addr; + sub_key_common *comk = HI_NULL; + hi_u32 ret = HI_ERR_SUCCESS; + + if ((head == HI_NULL) || (flag == HI_NULL)) { + return HI_ERR_UPG_NULL_POINTER; + } + + comk = hi_malloc(HI_MOD_ID_UPG, sizeof(sub_key_common)); + if (comk == HI_NULL) { + ret = HI_ERR_UPG_MALLOC_FAIL; + goto end; + } + + ret = hi_flash_read((boot_addr + head->sub_key_offset), sizeof(sub_key_common), (hi_u8 *)comk); + if (ret != HI_ERR_SUCCESS) { + goto end; + } + + *flag = comk->encrypt_flag; +end: + upg_clear_contset((hi_u8 *)comk, sizeof(sub_key_common)); + upg_mem_free(comk); + return ret; +} + +hi_u32 upg_get_aes_info(HI_CONST boot_header *head, hi_u8 *key, hi_u32 key_len, hi_u8 *iv, hi_u32 iv_len) +{ + hi_flash_partition_table *partiton = hi_get_partition_table(); + hi_u32 boot_addr = partiton->table[HI_FLASH_PARTITON_BOOT].addr; + sub_key_common *comk = HI_NULL; + hi_u32 ret = HI_ERR_SUCCESS; + + if ((head == HI_NULL) || (key_len != IV_BYTE_LEN) || (iv_len != IV_BYTE_LEN)) { + return HI_ERR_UPG_PARAMETER; + } + + comk = hi_malloc(HI_MOD_ID_UPG, sizeof(sub_key_common)); + if (comk == HI_NULL) { + ret = HI_ERR_UPG_MALLOC_FAIL; + goto end; + } + ret = hi_flash_read((boot_addr + head->sub_key_offset), sizeof(sub_key_common), (hi_u8 *)comk); + if (ret != HI_ERR_SUCCESS) { + goto end; + } + + if ((memcpy_s(key, key_len, comk->boot_key, key_len) != EOK) || + (memcpy_s(iv, iv_len, comk->aes_iv, iv_len) != EOK)) { + ret = HI_ERR_FAILURE; + goto end; + } +end: + upg_clear_contset((hi_u8 *)comk, sizeof(sub_key_common)); + upg_mem_free(comk); + return ret; +} + +hi_u32 upg_set_kdf_key(const hi_u8 *boo_key, hi_u32 key_len) +{ + hi_cipher_kdf_ctrl *ctrl = HI_NULL; + hi_u8 rootkey_iv[ROOTKEY_IV_BYTE_LENGTH] = { 0 }; + hi_u32 ret; + + if (key_len != IV_BYTE_LEN) { + return HI_ERR_UPG_PARAMETER; + } + ctrl = hi_malloc(HI_MOD_ID_UPG, sizeof(hi_cipher_kdf_ctrl)); + if (ctrl == HI_NULL) { + return HI_ERR_UPG_MALLOC_FAIL; + } + + if ((memcpy_s(rootkey_iv, IV_BYTE_LEN, boo_key, IV_BYTE_LEN) != EOK) || + (memcpy_s((rootkey_iv + IV_BYTE_LEN), sizeof(rootkey_iv) - IV_BYTE_LEN, g_magic, IV_BYTE_LEN) != EOK)) { + hi_free(HI_MOD_ID_UPG, ctrl); + return HI_ERR_FAILURE; + } + + ctrl->salt = rootkey_iv; + ctrl->salt_len = ROOTKEY_IV_BYTE_LENGTH; + ctrl->kdf_cnt = KDF_ITERATION_CNT; + ctrl->kdf_mode = HI_CIPHER_SSS_KDF_KEY_STORAGE; + + ret = hi_cipher_kdf_key_derive(ctrl); + hi_free(HI_MOD_ID_UPG, ctrl); + return ret; +} + +hi_u32 upg_boot_key_decrypt(hi_u8 *key, hi_u32 key_len, const hi_u8 *iv, hi_u32 iv_len) +{ + hi_cipher_aes_ctrl *aes_ctrl = HI_NULL; + hi_u32 ret; + + if (iv_len != IV_BYTE_LEN) { + return HI_ERR_UPG_PARAMETER; + } + aes_ctrl = hi_malloc(HI_MOD_ID_UPG, sizeof(hi_cipher_aes_ctrl)); + if (aes_ctrl == HI_NULL) { + return HI_ERR_UPG_MALLOC_FAIL; + } + + if (memcpy_s(aes_ctrl->iv, sizeof(aes_ctrl->iv), iv, IV_BYTE_LEN) != EOK) { + hi_free(HI_MOD_ID_UPG, aes_ctrl); + return HI_ERR_FAILURE; + } + aes_ctrl->random_en = HI_TRUE; + aes_ctrl->key_from = HI_CIPHER_AES_KEY_FROM_KDF; + aes_ctrl->work_mode = HI_CIPHER_AES_WORK_MODE_CBC; + aes_ctrl->key_len = HI_CIPHER_AES_KEY_LENGTH_256BIT; + ret = hi_cipher_aes_config(aes_ctrl); + if (ret != HI_ERR_SUCCESS) { + hi_free(HI_MOD_ID_UPG, aes_ctrl); + return ret; + } + ret = hi_cipher_aes_crypto((uintptr_t)key, (uintptr_t)key, key_len, HI_FALSE); + hi_cipher_aes_destroy_config(); + hi_free(HI_MOD_ID_UPG, aes_ctrl); + return ret; +} + +/* key_n:from flash; key_e: use default value 0x10001. */ +hi_u32 upg_get_unencrpt_rsa_key(hi_u8 *key, hi_u32 key_len) +{ + upg_ctx *ctx = upg_get_ctx(); + hi_u32 ret; + + if (ctx->rsa_key_addr == 0) { + return HI_ERR_UPG_RSA_KEY_ADDR; + } + + ret = hi_flash_read(ctx->rsa_key_addr, RSA_2048_LEN, key); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg get unencrpt rsa key]flash read fail:0x%x. \r\n", ret); + return ret; + } + key[key_len - 1] = 0x01; /* 1: first byte. 0x01: part of key_e 0x10001 */ + key[key_len - 3] = 0x01; /* 3: last byte. 0x01: part of key_e 0x10001 */ + upg_print("[upg get unencrpt rsa key]success. \r\n"); + return HI_ERR_SUCCESS; +} + +hi_u32 upg_get_unencrpt_ecc_key(hi_u8 *key, hi_u32 key_len) +{ + upg_ctx *ctx = upg_get_ctx(); + hi_u32 ret; + + if (ctx->ecc_key_addr == 0) { + return HI_ERR_UPG_ECC_KEY_ADDR; + } + + ret = hi_flash_read(ctx->ecc_key_addr, key_len, key); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg get unencrpt ecc key]flash read fail:0x%x. \r\n", ret); + return ret; + } + upg_print("[upg get unencrpt ecc key]success. \r\n"); + return HI_ERR_SUCCESS; +} + +hi_u32 upg_get_decrpt_rsa_key(HI_CONST boot_header *head, hi_u8 *key, hi_u32 key_len) +{ + hi_u32 ret = HI_ERR_SUCCESS; + upg_ctx *ctx = upg_get_ctx(); + hi_flash_partition_table *partiton = hi_get_partition_table(); + hi_u32 boot_addr = partiton->table[HI_FLASH_PARTITON_BOOT].addr; + hi_u8 *raw_data = HI_NULL; + hi_u8 boot_key[IV_BYTE_LEN] = { 0 }; + hi_u8 aes_iv[IV_BYTE_LEN] = { 0 }; + + ret = upg_get_aes_info(head, boot_key, IV_BYTE_LEN, aes_iv, IV_BYTE_LEN); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + if ((ctx->rsa_key_addr == 0) || (ctx->rsa_key_addr < head->code_section_offset)) { + return HI_ERR_UPG_RSA_KEY_ADDR; + } + hi_u32 data_len = upg_align_128bit(ctx->rsa_key_addr - head->code_section_offset + RSA_2048_LEN); + upg_print("[upg get decrpt rsa key]offset-addr-len:0x%x-0x%x-0x%x \r\n", head->code_section_offset, + ctx->rsa_key_addr, data_len); + raw_data = hi_malloc(HI_MOD_ID_UPG, data_len); + if (raw_data == HI_NULL) { + return HI_ERR_UPG_MALLOC_FAIL; + } + ret = hi_flash_read(boot_addr + head->code_section_offset, data_len, raw_data); + if (ret != HI_ERR_SUCCESS) { + goto end; + } + + ret = upg_set_kdf_key(boot_key, IV_BYTE_LEN); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg get decrpt rsa key]kdf ret:0x%x \r\n", ret); + goto end; + } + + ret = upg_boot_key_decrypt(raw_data, data_len, aes_iv, IV_BYTE_LEN); + if (memcpy_s(key, RSA_2048_LEN, raw_data + (ctx->rsa_key_addr - head->code_section_offset), RSA_2048_LEN) != EOK) { + ret = HI_ERR_FAILURE; + goto end; + } + key[key_len - 1] = 0x01; /* 1: first byte. 0x01: part of key_e 0x10001 */ + key[key_len - 3] = 0x01; /* 3: last byte. 0x01: part of key_e 0x10001 */ +end: + upg_clear_contset(raw_data, data_len); + upg_mem_free(raw_data); + return ret; +} + +/* px+py:from flash. */ +hi_u32 upg_get_decrpt_ecc_key(HI_CONST boot_header *head, hi_u8 *key, hi_u32 key_len) +{ + hi_u32 ret = HI_ERR_SUCCESS; + upg_ctx *ctx = upg_get_ctx(); + hi_flash_partition_table *partiton = hi_get_partition_table(); + hi_u32 boot_addr = partiton->table[HI_FLASH_PARTITON_BOOT].addr; + hi_u8 *raw_data = HI_NULL; + hi_u8 boot_key[IV_BYTE_LEN] = { 0 }; + hi_u8 aes_iv[IV_BYTE_LEN] = { 0 }; + + ret = upg_get_aes_info(head, boot_key, IV_BYTE_LEN, aes_iv, IV_BYTE_LEN); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + if ((ctx->ecc_key_addr == 0) || (ctx->ecc_key_addr < head->code_section_offset)) { + return HI_ERR_UPG_ECC_KEY_ADDR; + } + hi_u32 data_len = upg_align_128bit(ctx->ecc_key_addr - head->code_section_offset + key_len); + upg_print("[upg get decrpt ecc key]offset-addr-len:0x%x-0x%x-0x%x \r\n", head->code_section_offset, + ctx->ecc_key_addr, data_len); + raw_data = hi_malloc(HI_MOD_ID_UPG, data_len); + if (raw_data == HI_NULL) { + return HI_ERR_UPG_MALLOC_FAIL; + } + ret = hi_flash_read(boot_addr + head->code_section_offset, data_len, raw_data); + if (ret != HI_ERR_SUCCESS) { + goto end; + } + + ret = upg_set_kdf_key(boot_key, IV_BYTE_LEN); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg get decrpt ecc key]set kdf ret:0x%x \r\n", ret); + goto end; + } + + ret = upg_boot_key_decrypt(raw_data, data_len, aes_iv, IV_BYTE_LEN); + if (memcpy_s(key, key_len, raw_data + (ctx->ecc_key_addr - head->code_section_offset), key_len) != EOK) { + ret = HI_ERR_FAILURE; + } +end: + upg_clear_contset(raw_data, data_len); + upg_mem_free(raw_data); + return ret; +} + +/* key_n:from flash; key_e: use default value 0x10001. */ +hi_u32 upg_get_rsa_key_from_boot(hi_u8 *key, hi_u32 key_len) +{ + hi_u32 ret; + hi_u8 flag; + hi_u8 efuse_flag = 0xFF; + boot_header *head = HI_NULL; + hi_flash_partition_table *partiton = hi_get_partition_table(); + hi_u32 boot_addr = partiton->table[HI_FLASH_PARTITON_BOOT].addr; + + if ((key == HI_NULL) || (key_len != RSA_KEY_LEN)) { + upg_print("[upg get rsa key]param err:len:0x%x \r\n", key_len); + return HI_ERR_UPG_PARAMETER; + } + head = hi_malloc(HI_MOD_ID_UPG, sizeof(boot_header)); + if (head == HI_NULL) { + return HI_ERR_UPG_MALLOC_FAIL; + } + ret = hi_flash_read(boot_addr, sizeof(boot_header), (hi_u8 *)head); + if (ret != HI_ERR_SUCCESS) { + goto end; + } + + ret = upg_get_boot_encrypt_flag(head, &flag); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg get rsa key]get encrypt flag fail:0x%x \r\n", ret); + goto end; + } + + ret = hi_efuse_read(HI_EFUSE_ENCRYPT_FLAG_RW_ID, (hi_u8 *)(&efuse_flag), sizeof(hi_u8)); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg get rsa key]efuse read err:0x%x \r\n", ret); + goto end; + } + + if ((efuse_flag == NON_ENCRYPT_FLAG) && (flag == NON_ENCRYPT_FLAG)) { + ret = upg_get_unencrpt_rsa_key(key, key_len); + } else { + ret = upg_get_decrpt_rsa_key(head, key, key_len); + } + +end: + upg_mem_free(head); + return ret; +} + +/* px+py:from flash. */ +hi_u32 upg_get_ecc_key_from_boot(hi_u8 *key, hi_u32 key_len) +{ + hi_u32 ret; + hi_u8 flag; + hi_u8 efuse_flag = 0xFF; + boot_header *head = HI_NULL; + hi_flash_partition_table *partiton = hi_get_partition_table(); + hi_u32 boot_addr = partiton->table[HI_FLASH_PARTITON_BOOT].addr; + + if ((key == HI_NULL) || (key_len != ECC_KEY_LEN)) { + upg_print("[upg get ecc key]param err:len:0x%x \r\n", key_len); + return HI_ERR_UPG_PARAMETER; + } + head = hi_malloc(HI_MOD_ID_UPG, sizeof(boot_header)); + if (head == HI_NULL) { + return HI_ERR_UPG_MALLOC_FAIL; + } + ret = hi_flash_read(boot_addr, sizeof(boot_header), (hi_u8 *)head); + if (ret != HI_ERR_SUCCESS) { + goto end; + } + ret = upg_get_boot_encrypt_flag(head, &flag); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg get ecc key]get encrypt flag fail:0x%x \r\n", ret); + goto end; + } + + ret = hi_efuse_read(HI_EFUSE_ENCRYPT_FLAG_RW_ID, (hi_u8 *)(&efuse_flag), sizeof(hi_u8)); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg get ecc key]efuse read err:0x%x \r\n", ret); + goto end; + } + + if ((efuse_flag == NON_ENCRYPT_FLAG) && (flag == NON_ENCRYPT_FLAG)) { + ret = upg_get_unencrpt_ecc_key(key, key_len); + } else { + ret = upg_get_decrpt_ecc_key(head, key, key_len); + } + +end: + upg_mem_free(head); + return ret; +} + +hi_u32 upg_boot_process(hi_void) +{ + upg_ctx *ctx = upg_get_ctx(); + hi_u32 ret = hi_flash_protect_enable(HI_FALSE); + if (ret != HI_ERR_SUCCESS) { + upg_stop(ret); + return ret; + } + ret = upg_refresh_boot(ctx->file_addr); + upg_print("[upg transmit finish]refresh boot:0x%x\r\n", ret); + if (ret != HI_ERR_SUCCESS) { + upg_stop(ret); + return ret; + } + ret = hi_flash_protect_enable(HI_TRUE); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg transmit finish]refresh boot:0x%x\r\n", ret); + } + ret = upg_set_efuse_boot_ver(); + if (ret != HI_ERR_SUCCESS) { + upg_stop(ret); + return ret; + } + return ret; +} +/************************the following functions are external interface************************************/ +hi_u32 hi_upg_init(hi_void) +{ + hi_u32 ret; + upg_ctx *ctx = upg_get_ctx(); + + if (ctx->is_init == HI_TRUE) { + return HI_ERR_UPG_INITILIZATION_ALREADY; + } + + ret = hi_sem_bcreate(&ctx->upg_sem, HI_SEM_ONE); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg init]sem create fail: 0x%x\r\n", ret); + return ret; + } + ctx->is_init = HI_TRUE; + upg_get_boot_key_addr(); + ret = upg_refresh_nv(); + ret |= upg_mode_init(); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg init]fail:0x%x \r\n", ret); + } + return ret; +} + +hi_u32 hi_upg_get_max_file_len(hi_u8 file_type, hi_u32 *file_len) +{ + if (file_len == HI_NULL) { + return HI_ERR_UPG_NULL_POINTER; + } + return upg_get_max_file_len(file_type, file_len); +} + +hi_u32 hi_upg_get_content(hi_u32 offset, hi_u8 *buf, hi_u32 buf_len) +{ + hi_nv_ftm_startup_cfg cfg; + hi_nv_ftm_upg_wait_mode mode; + hi_u32 ret = upg_get_start_up_cfg(&cfg); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + if (cfg.mode != HI_UPG_MODE_UPGRADE_WAIT) { + if (upg_is_upg_process() == HI_FALSE) { + return HI_ERR_UPG_NOT_START; + } + + if (upg_is_transmit_finish() == HI_TRUE) { + return HI_ERR_UPG_ALREADY_FINISH; + } + } else { + ret = upg_get_wait_mode_nv(&mode); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + if (mode.is_upg_process == HI_FALSE) { + return HI_ERR_UPG_NOT_START; + } + + upg_ctx *ctx = upg_get_ctx(); + ctx->file_addr = mode.file_addr; + hi_upg_common_head head = {0}; + ret = hi_flash_read(ctx->file_addr, sizeof(hi_upg_common_head), (hi_u8 *)(&head)); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg get content]Failed to read flash,ret=%X\r\n", ret); + return ret; + } + ctx->common_head.file_len = head.file_len; + } + + return upg_cache_ctrl(offset, buf, buf_len, HI_FALSE); +} + +hi_u32 hi_upg_transmit(hi_u32 offset, hi_u8 *buf, hi_u32 buf_len) +{ + hi_u32 ret; + upg_ctx *ctx = upg_get_ctx(); + + if (buf == HI_NULL) { + return HI_ERR_UPG_NULL_POINTER; + } + upg_check_clear_wait_mode(); + upg_check_clear_upg_mode(); + upg_print("[upg transmit]offset-buflen-cachesize:0x%x-0x%x-0x%x\r\n", offset, buf_len, ctx->cache_size); + + if (offset != ctx->cache_size) { + upg_print("[upg transmit]offset-cachesize:0x%x-0x%x\r\n", offset, ctx->cache_size); + upg_stop(HI_ERR_UPG_PARAMETER); + } + + /* The first packet. */ + if (upg_is_upg_process() == HI_FALSE) { + if (offset != 0) { + return HI_ERR_UPG_FIRST_PACKET_OFFSET; + } + ret = upg_start(buf, buf_len); + upg_print("[upg transmit]upg start ret:0x%x\r\n", ret); + if (ret != HI_ERR_SUCCESS) { + upg_stop(ret); + return ret; + } + } + + ret = upg_cache_write(offset, buf, buf_len); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg transmit]cache write err: 0x%x\r\n", ret); + upg_stop(ret); + return ret; + } + ctx->cache_size += buf_len; + if ((ctx->check_head_flag == HI_FALSE) && (ctx->cache_size >= sizeof(hi_upg_head))) { + ret = upg_check_head(); + ctx->check_head_flag = HI_TRUE; + } + + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg transmit]check head fail:0x%x\r\n", ret); + upg_stop(ret); + } + return ret; +} + +hi_u32 upg_file_decrypt(upg_ctx *ctx) +{ + hi_u32 ret = HI_ERR_SUCCESS; +#if (defined(CONFIG_FLASH_ENCRYPT_SUPPORT)) && (!defined(CONFIG_COMPRESSION_OTA_SUPPORT)) + if (ctx->common_head.file_type == HI_UPG_FILE_KERNEL) { + ret = crypto_encrypt_data_to_flash(ctx->file_addr); + if (ret != HI_ERR_SUCCESS) { + upg_stop(ret); + return ret; + } + } +#else + hi_unref_param(ctx); +#endif + + return ret; +} + +hi_u32 hi_upg_transmit_finish(hi_void) +{ + hi_nv_ftm_startup_cfg cfg; + upg_ctx *ctx = upg_get_ctx(); + if (ctx->transmit_finish_flag == HI_TRUE) { + return HI_ERR_UPG_ALREADY_FINISH; + } + + if (upg_is_upg_process() == HI_FALSE) { + return HI_ERR_UPG_NOT_START; + } + hi_u32 ret = upg_get_start_up_cfg(&cfg); + if (ret != HI_ERR_SUCCESS) { + upg_stop(ret); + return ret; + } + + if (upg_file_decrypt(ctx) != HI_ERR_SUCCESS) { + return HI_ERR_UPG_FILE_DECRYPT_ERR; + } + + ret = upg_verify_file(ctx->file_addr); + if (ret != HI_ERR_SUCCESS) { + upg_stop(ret); + return ret; + } + + if (ctx->common_head.file_type == HI_UPG_FILE_BOOT) { + ret = upg_boot_process(); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + } else { + /* Change kernel start address. */ +#if defined(CONFIG_COMPRESSION_OTA_SUPPORT) + cfg.addr_write = ctx->file_addr; +#else + cfg.addr_start = ctx->file_addr; + cfg.addr_write = ctx->file_addr; +#endif + cfg.refresh_nv = ENV_REFRESH_NV; + cfg.reset_cnt = 0; + } + cfg.mode = HI_UPG_MODE_UPGRADE; + cfg.file_type = ctx->common_head.file_type; + ret = upg_set_start_up_cfg(&cfg); + if (ret == HI_ERR_SUCCESS) { + ctx->transmit_finish_flag = HI_TRUE; + } else { + upg_stop(ret); + } + upg_print("[upg transmit finish]start-type-write-ret:0x%x-0x%x-0x%x-0x%x\r\n", + cfg.addr_start, cfg.file_type, cfg.addr_write, ret); + return ret; +} + +hi_void hi_upg_finish(hi_void) +{ + upg_ctx *ctx = upg_get_ctx(); + + upg_print("[upg finish]finish flag:0x%x \r\n", ctx->transmit_finish_flag); + if (ctx->transmit_finish_flag == HI_FALSE) { + hi_soft_reboot(HI_SYS_REBOOT_CAUSE_UPG_B); + } else { + hi_soft_reboot(HI_SYS_REBOOT_CAUSE_UPG); + } +} + +hi_u32 upg_check_transmit_finish_flag(hi_void) +{ + hi_u32 ret; + hi_nv_ftm_upg_wait_mode mode_cfg = {0}; + + ret = upg_get_wait_mode_nv(&mode_cfg); + if (ret != HI_ERR_SUCCESS) { + upg_stop(ret); + return ret; + } + + if (mode_cfg.trans_finish_flag == HI_TRUE) { + return HI_ERR_UPG_ALREADY_FINISH; + } + + return HI_ERR_SUCCESS; +} + +hi_u32 upg_check_download_finish(hi_void) +{ + upg_ctx *ctx = upg_get_ctx(); + hi_u32 addr = ctx->file_addr; + hi_u32 ret; + hi_upg_common_head *comm_head = hi_malloc(HI_MOD_ID_UPG, sizeof(hi_upg_common_head)); + if (comm_head == HI_NULL) { + return HI_ERR_UPG_MALLOC_FAIL; + } + ret = hi_flash_read(addr, sizeof(hi_upg_common_head), (hi_u8 *)comm_head); + if (ret != HI_ERR_SUCCESS) { + upg_mem_free(comm_head); + return ret; + } + + if (ctx->cache_size < comm_head->file_len) { + upg_mem_free(comm_head); + return HI_ERR_UPG_NOT_DOWNLOAD_FINISH; + } + + upg_mem_free(comm_head); + return HI_ERR_SUCCESS; +} + +hi_u32 hi_upg_transmit_finish_save_cache(hi_void) +{ + hi_nv_ftm_startup_cfg cfg; + hi_nv_ftm_upg_wait_mode mode_cfg = {0}; + upg_ctx *ctx = upg_get_ctx(); + if (upg_check_transmit_finish_flag() != HI_ERR_SUCCESS) { + return HI_ERR_UPG_ALREADY_FINISH; + } + + if (upg_is_upg_process() == HI_FALSE) { + return HI_ERR_UPG_NOT_START; + } + + if (upg_check_download_finish() != HI_ERR_SUCCESS) { + return HI_ERR_UPG_NOT_DOWNLOAD_FINISH; + } + + hi_u32 ret = upg_get_start_up_cfg(&cfg); + if (ret != HI_ERR_SUCCESS) { + upg_stop(ret); + return ret; + } + + if (ctx->common_head.file_type == HI_UPG_FILE_BOOT) { + ret = upg_verify_file(ctx->file_addr); + if (ret != HI_ERR_SUCCESS) { + upg_stop(ret); + return ret; + } + mode_cfg.boot_version = ctx->common_head.file_version; + } else { + cfg.refresh_nv = ENV_REFRESH_NV_WAIT; + cfg.reset_cnt = 0; + } + + cfg.mode = HI_UPG_MODE_UPGRADE_WAIT; + cfg.file_type = ctx->common_head.file_type; + ret = upg_set_start_up_cfg(&cfg); + if (ret != HI_ERR_SUCCESS) { + upg_stop(ret); + return ret; + } + + mode_cfg.file_addr = ctx->file_addr; + mode_cfg.file_type = ctx->common_head.file_type; + mode_cfg.is_upg_process = ctx->is_upg_process; + mode_cfg.trans_finish_flag = HI_TRUE; + ret = upg_save_wait_mode_nv(&mode_cfg); + if (ret != HI_ERR_SUCCESS) { + upg_stop(ret); + return ret; + } + + upg_print("[upg transmit finish with cache]start-type-write-ret:0x%x-0x%x-0x%x-0x%x\r\n", + cfg.addr_start, cfg.file_type, cfg.addr_write, ret); + return ret; +} + +hi_u32 upg_kernel_decrypt_and_verify(upg_ctx *ctx) +{ + hi_u32 ret; + if (upg_file_decrypt(ctx) != HI_ERR_SUCCESS) { + upg_stop(HI_ERR_UPG_FILE_DECRYPT_ERR); + return HI_ERR_UPG_FILE_DECRYPT_ERR; + } + + ret = upg_verify_file(ctx->file_addr); + if (ret != HI_ERR_SUCCESS) { + upg_stop(ret); + return ret; + } + + return HI_ERR_SUCCESS; +} + +hi_u32 hi_upg_finish_with_cache(hi_void) +{ + hi_nv_ftm_startup_cfg cfg = {0}; + hi_nv_ftm_upg_wait_mode mode_cfg = {0}; + upg_ctx *ctx = upg_get_ctx(); + hi_u32 ret = upg_get_start_up_cfg(&cfg); + if (ret != HI_ERR_SUCCESS) { + upg_stop(ret); + return ret; + } + + ret = upg_get_wait_mode_nv(&mode_cfg); + if (ret != HI_ERR_SUCCESS) { + upg_stop(ret); + return ret; + } + + if ((cfg.mode != HI_UPG_MODE_UPGRADE_WAIT) || (mode_cfg.is_upg_process != HI_TRUE) || + (mode_cfg.trans_finish_flag != HI_TRUE)) { + return HI_ERR_UPG_NOT_WITH_CACHE_MODE_ERR; + } + + upg_print("[upg finish with cache]file_addr-file_type: 0x%x-0x%x\r\n", mode_cfg.file_addr, mode_cfg.file_type); + ctx->file_addr = mode_cfg.file_addr; + ctx->common_head.file_type = mode_cfg.file_type; + + ret = upg_kernel_decrypt_and_verify(ctx); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + + if (ctx->common_head.file_type == HI_UPG_FILE_BOOT) { + ctx->common_head.file_version = mode_cfg.boot_version; + ret = upg_boot_process(); + if (ret != HI_ERR_SUCCESS) { + return ret; + } + } else { + /* Change kernel start address. */ +#if defined(CONFIG_COMPRESSION_OTA_SUPPORT) + cfg.addr_write = ctx->file_addr; +#else + cfg.addr_start = ctx->file_addr; + cfg.addr_write = ctx->file_addr; +#endif + cfg.refresh_nv = ENV_REFRESH_NV; + } + cfg.mode = HI_UPG_MODE_UPGRADE; + + ret = upg_set_start_up_cfg(&cfg); + if (ret != HI_ERR_SUCCESS) { + upg_stop(ret); + return ret; + } + + ret = upg_clear_wait_mode(&mode_cfg); + if (ret != HI_ERR_SUCCESS) { + upg_stop(ret); + return ret; + } + + hi_soft_reboot(HI_SYS_REBOOT_CAUSE_UPG); + return HI_ERR_SUCCESS; +} + +hi_u32 hi_upg_get_file_index(hi_u8 *index) +{ + hi_nv_ftm_startup_cfg cfg = { 0 }; + hi_flash_partition_table *partition = hi_get_partition_table(); + uintptr_t kernel_a_addr = partition->table[HI_FLASH_PARTITON_KERNEL_A].addr; + hi_u32 ret = upg_get_start_up_cfg(&cfg); + + if (index == HI_NULL) { + return HI_ERR_UPG_PARAMETER; + } + + if (ret != HI_ERR_SUCCESS) { + return ret; + } + if (cfg.addr_start == kernel_a_addr) { + *index = HI_UPG_FILE_FOR_AREA_B; + } else { + *index = HI_UPG_FILE_FOR_AREA_A; + } + upg_print("[upg get file index]index:%d \r\n", *index); + return ret; +} + +hi_u32 hi_upg_stop(hi_void) +{ + return upg_stop(HI_ERR_UPG_STOP); +} + +hi_bool upg_update_ver(hi_void) +{ + if (g_upg_updating_ver == UPG_UPDATE_VER_NONE) { + return HI_FALSE; + } + + hi_u32 ret = HI_ERR_FAILURE; + + if (g_upg_updating_ver == UPG_UPDATE_VER_FIRMARE) { + ret = hi_efuse_write(HI_EFUSE_TEE_KERNEL_VER_RW_ID, g_upg_efuse_data_kernel_ver); + } else if (g_upg_updating_ver == UPG_UPDATE_VER_BOOT) { + ret = hi_efuse_write(HI_EFUSE_TEE_BOOT_VER_RW_ID, g_upg_efuse_data_boot_ver); + } + + if (ret == HI_ERR_SUCCESS) { + g_upg_update_ver_success = HI_TRUE; + } + g_upg_updating_ver = UPG_UPDATE_VER_NONE; + + return HI_TRUE; +} diff --git a/sdk_liteos/platform/system/upg/upg_common.h b/sdk_liteos/platform/system/upg/upg_common.h new file mode 100644 index 0000000000000000000000000000000000000000..ac433402ccceaabdd2710bb4f661f8c869c24388 --- /dev/null +++ b/sdk_liteos/platform/system/upg/upg_common.h @@ -0,0 +1,115 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _UPG_COMMON_H_ +#define _UPG_COMMON_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef UPG_DEBUG +#include +#define upg_print(ftm...) \ + do { \ + printf(ftm); \ + } while (0); +#else +#define upg_print(ftm...) +#endif + +#define HI_UPG_MODE_NORMAL 0 /* normal mode */ +#define HI_UPG_MODE_UPGRADE 1 /* upgrade mode */ +#define HI_UPG_MODE_UPGRADE_WAIT 2 /* asynchronous upgrade mode */ + +#define UPG_FLASH_RETRY_TIMES 3 +#define UPG_MAX_BACKUP_CNT 3 + +#define UPG_FLASH_BLOCK_SIZE 0x1000 +#define UPG_NV_KERNEL_OFFSET 0x1000 + +#define PRODUCT_FLASH_MAX_SIZE 0x200000 + +#define BIT_U8 8 +#define BIT_U16 16 +#define MASK_U16 0xFFFF + +typedef enum { + HI_MODE_PKCS_V15 = 0x00, + HI_MODE_PKCS_PSS = 0x01, + HI_MODE_ECC = 0x10, +} hi_padding_mode; + +typedef struct { + hi_bool is_init; + hi_bool is_upg_process; + hi_bool check_head_flag; + hi_bool transmit_finish_flag; + hi_u32 cache_size; /* cached file size */ + hi_u32 file_addr; /* flash addr of cached file */ + hi_u32 upg_sem; + hi_u32 rsa_key_addr; /* flash addr of rsa key */ + hi_u32 ecc_key_addr; /* flash addr of ecc key */ + hi_u32 cur_kernel_size; /* current kernel size */ + hi_upg_common_head common_head; +} upg_ctx; + +typedef hi_u8 srv_bit; /* value 0 or 1 */ +#define SRV_BIT_LOW 0 +#define SRV_BIT_HIGH 1 + +/* + i must 0~7 b must 0 or 1 x must a character + high ----------------> low + ************************** + 7 6 5 4 3 2 1 0 + ************************** + */ +#define bit_set(x, i, b) ((x) = (hi_u8)((b) ? ((1 << (i)) | (x)) : ((~(hi_u8)(1 << (i))) & (x)))) +#define bit_get(x, i) (((1 << (i)) & (x)) ? 1 : 0) + +#define upg_mem_free(sz) \ + do { \ + if ((sz) != HI_NULL) { \ + hi_free(HI_MOD_ID_UPG, (sz)); \ + } \ + (sz) = HI_NULL; \ + } while (0) + +#define upg_align_128bit(x) ((((x) + (BIT_U16) - 1) / (BIT_U16)) * (BIT_U16)) +#define upg_align_pre(val, a) ((val) & (~((a) - 1))) +#define upg_align_next(val, a) ((((val) + ((a) - 1)) & (~((a) - 1)))) + +hi_u32 upg_get_efuse_code_ver(hi_u8 *ver); +hi_u32 upg_get_efuse_boot_ver(hi_u8 *ver); +hi_u32 upg_get_rsa_key_from_boot(hi_u8 *key, hi_u32 key_len); +hi_u32 upg_get_ecc_key_from_boot(hi_u8 *key, hi_u32 key_len); +hi_u32 upg_get_max_file_len(hi_u8 file_type, hi_u32 *file_len); +hi_bool upg_tool_bit_test(const hi_u8 *data, hi_u16 pos, hi_u16 data_len); +hi_void upg_tool_bit_set(hi_u8 *data, hi_u16 pos, hi_u8 val); +hi_u32 upg_get_start_up_cfg(hi_nv_ftm_startup_cfg *cfg); +hi_void upg_clear_contset(hi_u8 *content, hi_u32 content_len); + +#endif /* _UPG_COMMON_H_ */ diff --git a/sdk_liteos/platform/system/upg/upg_start_up.c b/sdk_liteos/platform/system/upg/upg_start_up.c new file mode 100644 index 0000000000000000000000000000000000000000..dfbde010973ca302f6936eee9c13e7849018ca61 --- /dev/null +++ b/sdk_liteos/platform/system/upg/upg_start_up.c @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +hi_u32 upg_save_start_up_nv(hi_nv_ftm_startup_cfg *cfg) +{ + hi_u32 ret = hi_factory_nv_write(HI_NV_FTM_STARTUP_CFG_ID, cfg, sizeof(hi_nv_ftm_startup_cfg), 0); + upg_print("[upg save nv]write,addr_start:0x%x \r\n", cfg->addr_start); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg save nv]write fail,ret:0x%x \r\n", ret); + return ret; + } + return ret; +} + +hi_u32 upg_check_start_addr(hi_u32 addr) +{ + hi_flash_partition_table *partition = hi_get_partition_table(); + uintptr_t kernel_a_addr = partition->table[HI_FLASH_PARTITON_KERNEL_A].addr; +#if defined(CONFIG_COMPRESSION_OTA_SUPPORT) + if (addr != kernel_a_addr) { + return HI_ERR_UPG_ADD_START; + } +#else + uintptr_t kernel_b_addr = partition->table[HI_FLASH_PARTITON_KERNEL_B].addr; + if ((addr != kernel_a_addr) && (addr != kernel_b_addr)) { + return HI_ERR_UPG_ADD_START; + } +#endif + return HI_ERR_SUCCESS; +} + +hi_u32 upg_get_start_up_nv(hi_nv_ftm_startup_cfg *cfg) +{ + hi_nv_ftm_startup_cfg nv_cfg = { 0 }; + hi_flash_partition_table *partition = hi_get_partition_table(); + uintptr_t kernel_a_addr = partition->table[HI_FLASH_PARTITON_KERNEL_A].addr; + hi_u32 ret = hi_factory_nv_read(HI_NV_FTM_STARTUP_CFG_ID, &nv_cfg, sizeof(hi_nv_ftm_startup_cfg), 0); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg get start nv]read fail:0x%x \r\n", ret); + (hi_void) memset_s(cfg, sizeof(hi_nv_ftm_startup_cfg), 0, sizeof(hi_nv_ftm_startup_cfg)); + cfg->addr_start = kernel_a_addr; + cfg->mode = HI_UPG_MODE_UPGRADE; + cfg->cnt_max = UPG_MAX_BACKUP_CNT; + return HI_ERR_SUCCESS; + } + + ret = upg_check_start_addr(nv_cfg.addr_start); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg get start nv]check addr fail:0x%x \r\n", nv_cfg.addr_start); + (hi_void) memset_s(cfg, sizeof(hi_nv_ftm_startup_cfg), 0, sizeof(hi_nv_ftm_startup_cfg)); + cfg->addr_start = kernel_a_addr; + cfg->mode = HI_UPG_MODE_UPGRADE; + cfg->cnt_max = UPG_MAX_BACKUP_CNT; + } else { + if (memcpy_s(cfg, sizeof(hi_nv_ftm_startup_cfg), &nv_cfg, sizeof(hi_nv_ftm_startup_cfg)) != EOK) { + return HI_ERR_FAILURE; + } + } + + return HI_ERR_SUCCESS; +} + +hi_u32 upg_save_wait_mode_nv(hi_nv_ftm_upg_wait_mode *cfg) +{ + upg_print("[upg save wait mode]file_addr-file_type:0x%x-0x%x", cfg->file_addr, cfg->file_type); + hi_u32 ret = hi_factory_nv_write(HI_NV_FTM_UPG_WAIT_MODE, cfg, sizeof(hi_nv_ftm_upg_wait_mode), 0); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg save wait mode]write nv fail,ret:0x%x \r\n", ret); + } + + return ret; +} + +hi_u32 upg_get_wait_mode_nv(hi_nv_ftm_upg_wait_mode *cfg) +{ + hi_u32 ret = hi_factory_nv_read(HI_NV_FTM_UPG_WAIT_MODE, cfg, sizeof(hi_nv_ftm_upg_wait_mode), 0); + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg get wait mode]read nv fail:0x%x \r\n", ret); + } + + return ret; +} + diff --git a/sdk_liteos/platform/system/upg/upg_start_up.h b/sdk_liteos/platform/system/upg/upg_start_up.h new file mode 100644 index 0000000000000000000000000000000000000000..39ab623d0cddb8dd1768a279d97f28e313baecac --- /dev/null +++ b/sdk_liteos/platform/system/upg/upg_start_up.h @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _UPG_START_UP_H_ +#define _UPG_START_UP_H_ + +#include + +#ifndef offsetof +#define offsetof(type, member) ((hi_u32) & ((type *)0)->member) +#endif + +#define ENV_REFRESH_NV 0x55 +#define ENV_REFRESH_NV_WAIT 0x56 + +hi_u32 upg_get_start_up_nv(hi_nv_ftm_startup_cfg *cfg); +hi_u32 upg_save_start_up_nv(hi_nv_ftm_startup_cfg *cfg); + +hi_u32 upg_get_wait_mode_nv(hi_nv_ftm_upg_wait_mode *cfg); +hi_u32 upg_save_wait_mode_nv(hi_nv_ftm_upg_wait_mode *cfg); + +#endif /* _UPG_START_UP_H_ */ diff --git a/sdk_liteos/platform/system/upg/upg_user_verify.c b/sdk_liteos/platform/system/upg/upg_user_verify.c new file mode 100644 index 0000000000000000000000000000000000000000..f9e3663bcac95336c3309a36bae8c095b01259ba --- /dev/null +++ b/sdk_liteos/platform/system/upg/upg_user_verify.c @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "upg_user_verify.h" + +HI_PRV upg_user_verify_inf g_user_file_verify_inf = {HI_NULL, HI_NULL}; + +upg_user_verify_inf *upg_get_user_verify_inf(hi_void) +{ + return &g_user_file_verify_inf; +} + +hi_u32 upg_user_define_verify(const hi_upg_user_info *info) +{ + hi_u32 ret = HI_ERR_SUCCESS; + upg_user_verify_inf *user_inf_ctx = upg_get_user_verify_inf(); + + if (user_inf_ctx->upg_file_check_fn) { + ret = user_inf_ctx->upg_file_check_fn(info, user_inf_ctx->user_param); + } else { + upg_print("[upg user verify]not define \r\n"); + } + + if (ret != HI_ERR_SUCCESS) { + upg_print("[upg user verify]check ret:0x%x \r\n", ret); + return HI_ERR_UPG_USER_VERIFY; + } + + return HI_ERR_SUCCESS; +} + +hi_u32 hi_upg_register_file_verify_fn( + hi_u32 (*upg_file_check_fn)(const hi_upg_user_info *info, hi_void *param), + hi_void *param) +{ + upg_user_verify_inf *user_info_ctx = upg_get_user_verify_inf(); + + if (!hi_is_valid_code_addr((uintptr_t)upg_file_check_fn)) { + return HI_ERR_UPG_PARAMETER; + } + user_info_ctx->upg_file_check_fn = upg_file_check_fn; + user_info_ctx->user_param = param; + return HI_ERR_SUCCESS; +} diff --git a/sdk_liteos/platform/system/upg/upg_user_verify.h b/sdk_liteos/platform/system/upg/upg_user_verify.h new file mode 100644 index 0000000000000000000000000000000000000000..5858f4984d647420e1ad49f70af4842da6890b09 --- /dev/null +++ b/sdk_liteos/platform/system/upg/upg_user_verify.h @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __UPG_USER_VERIFY_H__ +#define __UPG_USER_VERIFY_H__ + +#include "upg_common.h" + +typedef struct { + hi_u32 (*upg_file_check_fn)(const hi_upg_user_info *info, hi_void *param); + hi_void *user_param; +} upg_user_verify_inf; + +hi_u32 upg_user_define_verify(const hi_upg_user_info *info); + +#endif /* __UPG_USER_VERIFY_H__ */ + diff --git a/sdk_liteos/platform/system/upg/upg_ver_update.h b/sdk_liteos/platform/system/upg/upg_ver_update.h new file mode 100644 index 0000000000000000000000000000000000000000..092eaa813ac4c856d13091337311719a3c21cd09 --- /dev/null +++ b/sdk_liteos/platform/system/upg/upg_ver_update.h @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _UPG_VER_UPDATE_H_ +#define _UPG_VER_UPDATE_H_ + +#include "hi_types.h" + +#define UPG_NMI_BASE_ADDRESS 0x40010000 +#define UPG_NMI_CTRL 0x0258 +#define UPG_NMI_INT_MOD_DONE_EN_POS 0 + +#define UPG_UPDATE_VER_NONE 0 +#define UPG_UPDATE_VER_FIRMARE 1 +#define UPG_UPDATE_VER_BOOT 2 +hi_bool upg_update_ver(hi_void); +hi_u32 upg_start_and_wait_update_ver(hi_u8 update_ver_type); + +#endif /* _UPG_VER_UPDATE_H_ */ diff --git a/sdk_liteos/third_party/lwip_sack/COPYING b/sdk_liteos/third_party/lwip_sack/COPYING new file mode 100644 index 0000000000000000000000000000000000000000..23a2f3bceebe13316686b2bdade998b8accef6bf --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/COPYING @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2001, 2002 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ + + diff --git a/sdk_liteos/third_party/lwip_sack/README b/sdk_liteos/third_party/lwip_sack/README new file mode 100644 index 0000000000000000000000000000000000000000..899dc1784edcb57a94c8bdfbd0a710542585ac98 --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/README @@ -0,0 +1,106 @@ +INTRODUCTION + +lwIP is a small independent implementation of the TCP/IP protocol suite. + +The focus of the lwIP TCP/IP implementation is to reduce the RAM usage +while still having a full scale TCP. This making lwIP suitable for use +in embedded systems with tens of kilobytes of free RAM and room for +around 40 kilobytes of code ROM. + +lwIP was originally developed by Adam Dunkels at the Computer and Networks +Architectures (CNA) lab at the Swedish Institute of Computer Science (SICS) +and is now developed and maintained by a worldwide network of developers. + +FEATURES + + * IP (Internet Protocol, IPv4 and IPv6) including packet forwarding over + multiple network interfaces + * ICMP (Internet Control Message Protocol) for network maintenance and debugging + * IGMP (Internet Group Management Protocol) for multicast traffic management + * MLD (Multicast listener discovery for IPv6). Aims to be compliant with + RFC 2710. No support for MLDv2 + * ND (Neighbor discovery and stateless address autoconfiguration for IPv6). + Aims to be compliant with RFC 4861 (Neighbor discovery) and RFC 4862 + (Address autoconfiguration) + * DHCP, AutoIP/APIPA (Zeroconf) and (stateless) DHCPv6 + * UDP (User Datagram Protocol) including experimental UDP-lite extensions + * TCP (Transmission Control Protocol) with congestion control, RTT estimation + fast recovery/fast retransmit and sending SACKs + * raw/native API for enhanced performance + * Optional Berkeley-like socket API + * TLS: optional layered TCP ("altcp") for nearly transparent TLS for any + TCP-based protocol (ported to mbedTLS) (see changelog for more info) + * PPPoS and PPPoE (Point-to-point protocol over Serial/Ethernet) + * DNS (Domain name resolver incl. mDNS) + * 6LoWPAN (via IEEE 802.15.4, BLE or ZEP) + + +APPLICATIONS + + * HTTP server with SSI and CGI (HTTPS via altcp) + * SNMPv2c agent with MIB compiler (Simple Network Management Protocol), v3 via altcp + * SNTP (Simple network time protocol) + * NetBIOS name service responder + * MDNS (Multicast DNS) responder + * iPerf server implementation + * MQTT client (TLS support via altcp) + + +LICENSE + +lwIP is freely available under a BSD license. + + +DEVELOPMENT + +lwIP has grown into an excellent TCP/IP stack for embedded devices, +and developers using the stack often submit bug fixes, improvements, +and additions to the stack to further increase its usefulness. + +Development of lwIP is hosted on Savannah, a central point for +software development, maintenance and distribution. Everyone can +help improve lwIP by use of Savannah's interface, Git and the +mailing list. A core team of developers will commit changes to the +Git source tree. + +The lwIP TCP/IP stack is maintained in the 'lwip' Git module and +contributions (such as platform ports) are in the 'contrib' Git module. + +See doc/savannah.txt for details on Git server access for users and +developers. + +The current Git trees are web-browsable: + http://git.savannah.gnu.org/cgit/lwip.git + http://git.savannah.gnu.org/cgit/lwip/lwip-contrib.git + +Submit patches and bugs via the lwIP project page: + http://savannah.nongnu.org/projects/lwip/ + +Continuous integration builds (GCC, clang): + https://travis-ci.org/yarrick/lwip-merged + + +DOCUMENTATION + +Self documentation of the source code is regularly extracted from the current +Git sources and is available from this web page: + http://www.nongnu.org/lwip/ + +There is now a constantly growing wiki about lwIP at + http://lwip.wikia.com/wiki/LwIP_Wiki + +Also, there are mailing lists you can subscribe at + http://savannah.nongnu.org/mail/?group=lwip +plus searchable archives: + http://lists.nongnu.org/archive/html/lwip-users/ + http://lists.nongnu.org/archive/html/lwip-devel/ + +lwIP was originally written by Adam Dunkels: + http://dunkels.com/adam/ + +Reading Adam's papers, the files in docs/, browsing the source code +documentation and browsing the mailing list archives is a good way to +become familiar with the design of lwIP. + +Adam Dunkels +Leon Woestenberg diff --git a/sdk_liteos/third_party/lwip_sack/include/arch/atomic.h b/sdk_liteos/third_party/lwip_sack/include/arch/atomic.h new file mode 100644 index 0000000000000000000000000000000000000000..d196fcc66fefec3501935caa49144af303091761 --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/arch/atomic.h @@ -0,0 +1,73 @@ +/* + * Copyright (c) Huawei Technologies Co., Ltd. 2013-2016. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote + * products derived from this software without specific prior + * written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS + * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * Description: define atomic type and function + * Author: none + * Create: 2013 + */ + +#ifndef __ASM_ATOMIC_H__ +#define __ASM_ATOMIC_H__ + +#include "los_atomic.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +#ifdef __LP64__ +#define atomic_t long +#else +#define atomic_t int +#endif + +#define atomic_inc(atom) LOS_AtomicInc(atom) +#define atomic_dec(atom) LOS_AtomicDec(atom) +#define atomic_sub(n, v) LOS_AtomicSub(v, n) +#define atomic_add(n, v) LOS_AtomicAdd(v, n) +#define atomic_read(atom) (*((volatile typeof(atom))(atom))) +#ifdef __LP64__ +#define atomic_set(p, v) LOS_AtomicXchg64bits(p, v) +#else +#define atomic_set(p, v) LOS_AtomicXchg32bits(p, v) +#endif +#define ATOMIC_INIT(x) (x) + +#define atomic_add_return(i, v) LOS_AtomicAdd(v, i) +#define atomic_inc_return(v) LOS_AtomicIncRet(v) +#define atomic_dec_return(v) LOS_AtomicDecRet(v) +#define atomic_dec_and_test(v) (atomic_dec_return(v) == 0) + +#ifdef __cplusplus +#if __cplusplus +} +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +#endif /* __ASM_ATOMIC_H__ */ diff --git a/sdk_liteos/third_party/lwip_sack/include/arch/cc.h b/sdk_liteos/third_party/lwip_sack/include/arch/cc.h new file mode 100644 index 0000000000000000000000000000000000000000..c45a702d2ec333c0a076e0386ba1d92231454b9d --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/arch/cc.h @@ -0,0 +1,126 @@ +/* + * Copyright (c) Huawei Technologies Co., Ltd. 2013-2016. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote + * products derived from this software without specific prior + * written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS + * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * Description: define system adaptor unit + * Author: none + * Create: 2013 + */ + +#ifndef __CC_H__ +#define __CC_H__ + +#include "los_typedef.h" +#include +#ifdef LWIP_DEBUG +#include "stdio.h" +#endif + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif /* __cplusplus */ + +#define LWIP_TIMEVAL_PRIVATE 0 +#define LWIP_NO_INTTYPES_H 1 +#define LWIP_MAX_VALUE 0xFFFFFFFF + +/* Define (sn)printf formatters for these lwIP types */ +#define X8_F "02x" +#define U8_F "hhu" +#define U16_F "hu" +#define S16_F "hd" +#define X16_F "hx" +#define U32_F "u" +#define S32_F "d" +#define X32_F "x" +#define SZT_F "uz" + +/* ARM/LPC17xx is little endian only */ +#ifdef BYTE_ORDER +#undef BYTE_ORDER +#endif +#define BYTE_ORDER LITTLE_ENDIAN + +/* Use LWIP error codes */ +#if defined(__arm__) && defined(__ARMCC_VERSION) +/* Keil uVision4 tools */ +#define PACK_STRUCT_BEGIN __packed +#define PACK_STRUCT_STRUCT +#define PACK_STRUCT_END +#define PACK_STRUCT_FIELD(fld) fld +#define ALIGNED(n) __align(n) +#elif defined (__IAR_SYSTEMS_ICC__) +/* IAR Embedded Workbench tools */ +#define PACK_STRUCT_BEGIN __packed +#define PACK_STRUCT_STRUCT +#define PACK_STRUCT_END +#define PACK_STRUCT_FIELD(fld) fld +#error NEEDS ALIGNED +#else +/* GCC tools (CodeSourcery) */ +#define PACK_STRUCT_BEGIN +#define PACK_STRUCT_STRUCT __attribute__ ((__packed__)) +#define PACK_STRUCT_END +#define PACK_STRUCT_FIELD(fld) fld +#define ALIGNED(n) __attribute__((aligned (n))) +#endif + +/* Provide Thumb-2 routines for GCC to improve performance */ +#if defined(TOOLCHAIN_GCC) && defined(__thumb2__) +#define LWIP_CHKSUM thumb2_checksum +/* + * Set algorithm to 0 so that unused lwip_standard_chksum function + * doesn't generate compiler warning + */ +#define LWIP_CHKSUM_ALGORITHM 0 + +void *thumb2_memcpy(void *pDest, const void *pSource, size_t length); +u16_t thumb2_checksum(void *pData, int length); +#else +/* Used with IP headers only */ +#define LWIP_CHKSUM_ALGORITHM 4 +#endif + +#ifdef LWIP_DEBUG +void assert_printf(char *msg, int line, const char *file); + +/* Plaform specific diagnostic output */ +#define LWIP_PLATFORM_DIAG(vars) printf vars +#define LWIP_PLATFORM_ASSERT(flag) { assert_printf((flag), __LINE__, __FILE__); } +#else +#define LWIP_PLATFORM_DIAG(msg) { ; } +#define LWIP_PLATFORM_ASSERT(flag) { ; } +#endif + +#define LWIP_PLATFORM_PRINT PRINTK +#define LWIP_PLATFORM_HTONS(x) htons(x) +#define LWIP_PLATFORM_HTONL(x) htonl(x) + +#if defined (__cplusplus) && __cplusplus +} +#endif /* __cplusplus */ +#endif /* __CC_H__ */ + diff --git a/sdk_liteos/third_party/lwip_sack/include/arch/perf.h b/sdk_liteos/third_party/lwip_sack/include/arch/perf.h new file mode 100644 index 0000000000000000000000000000000000000000..b968775853705ba30a1df6485f5a07f6a05f9eeb --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/arch/perf.h @@ -0,0 +1,71 @@ +/* + * Copyright (c) <2013-2015>, + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + */ + +#ifndef __LWIP_PERF_H__ +#define __LWIP_PERF_H__ + +#include "lwip/arch.h" +#include "lwip/opt.h" +#include "lwip/def.h" + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +/* PERF_START and PERF_STOP are called in code so its kept as empty here always */ +#define PERF_START /* null definition */ +#define PERF_STOP(x) /* null definition */ + +#if LWIP_PERF + +void +perf_print(u32_t start_ms, u32_t end_ms, char *key); + +#define LWIP_PERF_DECLARATION u32_t start_ms, end_ms +#define LWIP_PERF_START start_ms = sys_now() +#define LWIP_PERF_STOP(x) do { \ + end_ms = sys_now(); \ + perf_print(start_ms, end_ms, x); \ +} while (0) + +void +perf_init(void *data); + +void +perf_fini(void *data); + +#endif /* LWIP_PERF */ + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* __LWIP_PERF_H__ */ + diff --git a/sdk_liteos/third_party/lwip_sack/include/arch/sys_arch.h b/sdk_liteos/third_party/lwip_sack/include/arch/sys_arch.h new file mode 100644 index 0000000000000000000000000000000000000000..443f4e130c95881e4017e8a68868a9c8bb66b681 --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/arch/sys_arch.h @@ -0,0 +1,144 @@ +/* + * Copyright (c) Huawei Technologies Co., Ltd. 2013-2015. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote + * products derived from this software without specific prior + * written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS + * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * Description: define mbox, ticks and memory adaptor + * Author: none + * Create: 2013 + */ + +#ifndef __ARCH_SYS_ARCH_H__ +#define __ARCH_SYS_ARCH_H__ + +#include "lwip/opt.h" + +#if NO_SYS == 0 +#include "los_sem.h" +#include "pthread.h" +#include "los_typedef.h" +#include "semaphore.h" +#include "los_memory.h" + +#define LWIP_OFFSET_OF LOS_OFF_SET_OF +typedef struct posix_sem sys_sem_t; +typedef int sys_prot_t; +#if !LWIP_COMPAT_MUTEX +typedef u32_t sys_mutex_t; +#endif + +#define MBOX_NO_EXPAND 0 +#define MBOX_AUTO_EXPAND 1 + +struct sys_mbox { + int first, last; + void **msgs; + int mbox_size; + int mbox_origin_size; + unsigned char is_full; + unsigned char is_empty; + unsigned char is_auto_expand; + pthread_cond_t not_empty; + pthread_cond_t not_full; + pthread_mutex_t mutex; +}; + +struct sys_dual_mbox { + int first, last; + void **msgs; + int mbox_size; + int mbox_total_used; + int is_full; + int is_empty; + int mbox_used; + pthread_cond_t not_empty; + pthread_cond_t not_full; + pthread_mutex_t mutex; + + int first_p, last_p; + void **msgs_priority; + int mbox_size_priority; + int mbox_used_priority; +}; +typedef struct sys_dual_mbox *sys_dual_mbox_t; + +typedef struct sys_mbox *sys_mbox_t; + +struct sys_thread { + struct sys_thread *next; + pthread_t pthread; +}; + +typedef unsigned int sys_thread_t; + +#define sys_sem_valid(x) (((*x).sem == NULL) ? 0 : 1) +#define sys_sem_set_invalid(x) ((*x).sem = NULL) + + +#define SYS_MBOX_NULL (NULL) +#define sys_mbox_valid(mbox) (((mbox) != (void *)NULL) && (*(mbox) != (void *)NULL)) +#define sys_mbox_set_invalid(mbox) do { \ + if ((mbox) != NULL) { \ + *(mbox) = NULL; \ + } \ +} while (0) + +/* Note: Please make sure the mbox passed is an valid pointer */ +#define sys_dual_mbox_valid(mbox) (*(mbox) != NULL) + +#if (MEM_MALLOC_DMA_ALIGN != 1) +static inline void * +sys_align_malloc(u16_t length) +{ + return LOS_MemAllocAlign(OS_SYS_MEM_ADDR, length, MEM_MALLOC_DMA_ALIGN); +} + +static inline void +sys_align_free(void *mem) +{ + (void)LOS_MemFree(OS_SYS_MEM_ADDR, mem); +} +#endif + +#else +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif +/* \brief Get the current systick time in milliSeconds + * + * Returns the current systick time in milliSeconds. This function is only + * used in standalone systems. + * + * /returns current systick time in milliSeconds + */ +u32_t sys_now(void); + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif + +#endif /* __ARCH_SYS_ARCH_H__ */ diff --git a/sdk_liteos/third_party/lwip_sack/include/compat/posix/arpa/inet.h b/sdk_liteos/third_party/lwip_sack/include/compat/posix/arpa/inet.h new file mode 100644 index 0000000000000000000000000000000000000000..0ed9baf3d9f2e514fdfc043a3c7cb85fa0e2f3d6 --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/compat/posix/arpa/inet.h @@ -0,0 +1,33 @@ +/** + * @file + * This file is a posix wrapper for lwip/sockets.h. + */ + +/* + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + */ + +#include "lwip/sockets.h" diff --git a/sdk_liteos/third_party/lwip_sack/include/compat/posix/net/if.h b/sdk_liteos/third_party/lwip_sack/include/compat/posix/net/if.h new file mode 100644 index 0000000000000000000000000000000000000000..8b8e48198de7de25d97916b61fcc97af32d67824 --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/compat/posix/net/if.h @@ -0,0 +1,36 @@ +/** + * @file + * This file is a posix wrapper for lwip/if_api.h. + */ + +/* + * Copyright (c) 2017 Joel Cunningham, Garmin International, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + */ + +#include "lwip/if_api.h" diff --git a/sdk_liteos/third_party/lwip_sack/include/compat/posix/netdb.h b/sdk_liteos/third_party/lwip_sack/include/compat/posix/netdb.h new file mode 100644 index 0000000000000000000000000000000000000000..12d4c7f566c77fc4ded1aaf30a67072cd3f7d81c --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/compat/posix/netdb.h @@ -0,0 +1,33 @@ +/** + * @file + * This file is a posix wrapper for lwip/netdb.h. + */ + +/* + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + */ + +#include "lwip/netdb.h" diff --git a/sdk_liteos/third_party/lwip_sack/include/compat/posix/sys/socket.h b/sdk_liteos/third_party/lwip_sack/include/compat/posix/sys/socket.h new file mode 100644 index 0000000000000000000000000000000000000000..0ed9baf3d9f2e514fdfc043a3c7cb85fa0e2f3d6 --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/compat/posix/sys/socket.h @@ -0,0 +1,33 @@ +/** + * @file + * This file is a posix wrapper for lwip/sockets.h. + */ + +/* + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + */ + +#include "lwip/sockets.h" diff --git a/sdk_liteos/third_party/lwip_sack/include/compat/stdc/errno.h b/sdk_liteos/third_party/lwip_sack/include/compat/stdc/errno.h new file mode 100644 index 0000000000000000000000000000000000000000..5917c75e24a8e01c9666c2714475dec09d27df0c --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/compat/stdc/errno.h @@ -0,0 +1,33 @@ +/** + * @file + * This file is a posix wrapper for lwip/errno.h. + */ + +/* + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + */ + +#include "lwip/errno.h" diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/api.h b/sdk_liteos/third_party/lwip_sack/include/lwip/api.h new file mode 100644 index 0000000000000000000000000000000000000000..c3d750c915bbc8bfdbd3b2ef651a57517fbbc332 --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/api.h @@ -0,0 +1,531 @@ +/** + * @file + * netconn API (to be used from non-TCPIP threads) + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_API_H +#define LWIP_HDR_API_H + +#include "lwip/opt.h" + +#if LWIP_NETCONN || LWIP_SOCKET /* don't build if not configured for use in lwipopts.h */ +/* Note: Netconn API is always available when sockets are enabled - + * sockets are implemented on top of them */ + +#include "lwip/arch.h" +#include "lwip/netbuf.h" +#include "lwip/sys.h" +#include "lwip/ip_addr.h" +#include "lwip/err.h" +#include "lwip/filter.h" + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +/* Throughout this file, IP_add and port numbers are expected to be in + * the same byte order as in the corresponding pcb. + */ +/* Flags for netconn_write (u8_t) */ +#define NETCONN_NOFLAG 0x00 +#define NETCONN_NOCOPY 0x00 /* Only for source code compatibility */ +#define NETCONN_COPY 0x01 +#define NETCONN_MORE 0x02 +#define NETCONN_DONTBLOCK 0x04 + +/* Flags for struct netconn.flags (u8_t) */ +/* + * TCP: when data passed to netconn_write doesn't fit into the send buffer, + * this temporarily stores whether to wake up the original application task + * if data couldn't be sent in the first try. + */ +#define NETCONN_FLAG_WRITE_DELAYED 0x01 +/* Should this netconn avoid blocking? */ +#define NETCONN_FLAG_NON_BLOCKING 0x02 +/* Was the last connect action a non-blocking one? */ +#define NETCONN_FLAG_IN_NONBLOCKING_CONNECT 0x04 +/* If this is set, a TCP netconn must call netconn_recved() to update + the TCP receive window (done automatically if not set). */ +#define NETCONN_FLAG_NO_AUTO_RECVED 0x08 +/* If a nonblocking write has been rejected before, poll_tcp needs to + check if the netconn is writable again */ +#define NETCONN_FLAG_CHECK_WRITESPACE 0x10 +#if LWIP_IPV6 +/* If this flag is set then only IPv6 communication is allowed on the + netconn. As per RFC#3493 this features defaults to OFF allowing + dual-stack usage by default. */ +#define NETCONN_FLAG_IPV6_V6ONLY 0x20 +#endif /* LWIP_IPV6 */ + +#if LWIP_NETBUF_RECVINFO +/** Received packet info will be recorded for this netconn */ +#define NETCONN_FLAG_PKTINFO 0x40 +#endif /* LWIP_NETBUF_RECVINFO */ + +/* Helpers to process several netconn_types by the same code */ +#define NETCONNTYPE_GROUP(t) ((t)&0xF0) +#define NETCONNTYPE_DATAGRAM(t) ((t)&0xE0) +#if LWIP_IPV6 +#define NETCONN_TYPE_IPV6 0x08 +#define NETCONNTYPE_ISIPV6(t) (((t)&NETCONN_TYPE_IPV6) != 0) +#define NETCONNTYPE_ISUDPLITE(t) (((t)&0xF3) == NETCONN_UDPLITE) +#define NETCONNTYPE_ISUDPNOCHKSUM(t) (((t)&0xF3) == NETCONN_UDPNOCHKSUM) +#else /* LWIP_IPV6 */ +#define NETCONNTYPE_ISIPV6(t) (0) +#define NETCONNTYPE_ISUDPLITE(t) ((t) == NETCONN_UDPLITE) +#define NETCONNTYPE_ISUDPNOCHKSUM(t) ((t) == NETCONN_UDPNOCHKSUM) +#endif /* LWIP_IPV6 */ + +/* @ingroup netconn_common + * Protocol family and type of the netconn + */ +enum netconn_type { + NETCONN_INVALID = 0, + /* TCP IPv4 */ + NETCONN_TCP = 0x10, +#if LWIP_IPV6 + /* TCP IPv6 */ + NETCONN_TCP_IPV6 = NETCONN_TCP | NETCONN_TYPE_IPV6 /* 0x18 */, +#endif /* LWIP_IPV6 */ + /* UDP IPv4 */ + NETCONN_UDP = 0x20, + /* UDP IPv4 lite */ + NETCONN_UDPLITE = 0x21, + /* UDP IPv4 no checksum */ + NETCONN_UDPNOCHKSUM = 0x22, + +#if LWIP_IPV6 + /* UDP IPv6 (dual-stack by default, unless you call @ref netconn_set_ipv6only) */ + NETCONN_UDP_IPV6 = NETCONN_UDP | NETCONN_TYPE_IPV6 /* 0x28 */, + /* UDP IPv6 lite (dual-stack by default, unless you call @ref netconn_set_ipv6only) */ + NETCONN_UDPLITE_IPV6 = NETCONN_UDPLITE | NETCONN_TYPE_IPV6 /* 0x29 */, + /* UDP IPv6 no checksum (dual-stack by default, unless you call @ref netconn_set_ipv6only) */ + NETCONN_UDPNOCHKSUM_IPV6 = NETCONN_UDPNOCHKSUM | NETCONN_TYPE_IPV6 /* 0x2a */, +#endif /* LWIP_IPV6 */ + + /* Raw connection IPv4 */ + NETCONN_RAW = 0x40 +#if LWIP_IPV6 /* Raw connection IPv6 (dual-stack by default, unless you call @ref netconn_set_ipv6only) */ + , NETCONN_RAW_IPV6 = NETCONN_RAW | NETCONN_TYPE_IPV6 /* 0x48 */ +#endif /* LWIP_IPV6 */ +#if PF_PKT_SUPPORT + , NETCONN_PKT_RAW = 0x80 +#endif + , NETCONN_TYPE_LAST = 0xFFFFFFFF +}; + +/* Current state of the netconn. Non-TCP netconns are always + * in state NETCONN_NONE! */ +enum netconn_state { + NETCONN_NONE, + NETCONN_WRITE, + NETCONN_LISTEN, + NETCONN_CONNECT, + NETCONN_CLOSE, + NETCONN_CLOSED, + NETCONN_STATE_LAST = 0xFFFFFFFF +}; + +/* Used to inform the callback function about changes + * + * Event explanation: + * + * In the netconn implementation, there are three ways to block a client: + * + * - accept mbox (sys_arch_mbox_fetch(&conn->acceptmbox, &accept_ptr, 0); in netconn_accept()) + * - receive mbox (sys_arch_mbox_fetch(&conn->recvmbox, &buf, 0); in netconn_recv_data()) + * - send queue is full (sys_arch_sem_wait(LWIP_API_MSG_SEM(msg), 0); in lwip_netconn_do_write()) + * + * The events have to be seen as events signaling the state of these mboxes/semaphores. For non-blocking + * connections, you need to know in advance whether a call to a netconn function call would block or not, + * and these events tell you about that. + * + * RCVPLUS events say: Safe to perform a potentially blocking call call once more. + * They are counted in sockets - three RCVPLUS events for accept mbox means you are safe + * to call netconn_accept 3 times without being blocked. + * Same thing for receive mbox. + * + * RCVMINUS events say: Your call to to a possibly blocking function is "acknowledged". + * Socket implementation decrements the counter. + * + * For TX, there is no need to count, its merely a flag. SENDPLUS means you may send something. + * SENDPLUS occurs when enough data was delivered to peer so netconn_send() can be called again. + * A SENDMINUS event occurs when the next call to a netconn_send() would be blocking. + */ +enum netconn_evt { + NETCONN_EVT_RCVPLUS, + NETCONN_EVT_RCVMINUS, + NETCONN_EVT_SENDPLUS, + NETCONN_EVT_SENDMINUS, + NETCONN_EVT_ERROR +}; + +#if LWIP_IGMP || (LWIP_IPV6 && LWIP_IPV6_MLD) +/* Used for netconn_leave_group() and netconn_leave_group_netif */ +enum netconn_igmp { + NETCONN_JOIN, + NETCONN_LEAVE +}; +#endif /* LWIP_IGMP || (LWIP_IPV6 && LWIP_IPV6_MLD) */ + +enum netconn_shutdown { + NON_SHUTDOWN = 0, + RCV_SHUTDOWN, + SND_SHUTDOWN, + SHUTDOWN_MASK, + NCS_LAST_FLAG = 0xFFFFFFFF +}; + +#if LWIP_DNS +/* Used for netconn_gethostbyname_addrtype(), these should match the DNS_ADDRTYPE defines in dns.h */ +/** @cond liteos */ +/** Try to resolve hostname to an IPv4 address only. */ +#define NETCONN_DNS_IPV4 0 +/** Try to resolve hostname to an IPv6 address only. */ +#define NETCONN_DNS_IPV6 1 +/** Try to resolve hostname to an IPv4 address. If some failure happens or if no A records are received, + then try to resolve the hostname to an IPv6 address. If NETCONN_DNS_DEFAULT + is not defined, then NETCONN_DNS_IPV4_IPV6 will be taken as default. */ +#define NETCONN_DNS_IPV4_IPV6 2 +/** Try to resolve hostname to an IPv6 address. If some failure happens or if no AAAA records are received, + then try to resolve the hostname to an IPv4 address. */ +#define NETCONN_DNS_IPV6_IPV4 3 + +#if LWIP_IPV4 && LWIP_IPV6 +/** NETCONN_DNS_DEFAULT can be set to any one of the following values which describes the default DNS Resolution + behaviour for netconn_gethostbyname_addrtype(). + @ endcond */ +#ifndef NETCONN_DNS_DEFAULT +#define NETCONN_DNS_DEFAULT NETCONN_DNS_IPV4_IPV6 +#endif /* NETCONN_DNS_DEFAULT */ +#elif LWIP_IPV4 +#define NETCONN_DNS_DEFAULT NETCONN_DNS_IPV4 +#else +#define NETCONN_DNS_DEFAULT NETCONN_DNS_IPV6 +#endif /* LWIP_IPV4 && LWIP_IPV6 */ +#endif /* LWIP_DNS */ +#define NETCONN_MBOX_ACTIVE 1 +#define NETCONN_MBOX_DELETING 2 +/* forward-declare some structs to avoid to include their headers */ +struct ip_pcb; +struct tcp_pcb; +struct udp_pcb; +struct raw_pcb; +struct netconn; +struct api_msg; + +/* A callback prototype to inform about events for a netconn */ +typedef void (* netconn_callback)(struct netconn *, enum netconn_evt, u32_t len); + +/* A netconn descriptor */ +struct netconn { + /* type of the netconn (TCP, UDP or RAW) */ + enum netconn_type type; /* read only */ + /* current state of the netconn */ + enum netconn_state state; /* accessed only in tcipthread only */ + /* the lwIP internal protocol control block */ + union { + struct ip_pcb *ip; + struct tcp_pcb *tcp; + struct udp_pcb *udp; + struct raw_pcb *raw; +#if PF_PKT_SUPPORT + struct raw_pcb *pkt_raw; +#endif + } pcb; + +#define net_tcp_pcb pcb.tcp +#define net_tcp_state pcb.tcp->state +#define net_udp_pcb pcb.udp +#define net_raw_pcb pcb.raw +#define net_ip_pcb pcb.ip + + /* the last error this netconn had */ + err_t last_err; /* write in tcipthread, and read in application thread */ +#if !LWIP_NETCONN_SEM_PER_THREAD + /* sem that is used to synchronously execute functions in the core context */ + sys_sem_t op_completed; +#endif + /* mbox where received packets are stored until they are fetched + by the netconn application thread (can grow quite big) */ + sys_mbox_t recvmbox; +#if LWIP_TCP + /* mbox where new connections are stored until processed + by the application thread */ + sys_mbox_t acceptmbox; +#endif /* LWIP_TCP */ + + /* mbox state, used for close event in parallel to recv and send events */ + atomic_t mbox_state; + + /* only used for socket layer */ +#if LWIP_SOCKET + int socket; +#endif /* LWIP_SOCKET */ +#if LWIP_SO_SNDTIMEO + /* timeout to wait for sending data (which means enqueueing data for sending + in internal buffers) in milliseconds */ + s32_t send_timeout; +#endif /* LWIP_SO_RCVTIMEO */ +#if LWIP_SO_RCVTIMEO + /* timeout in milliseconds to wait for new data to be received + (or connections to arrive for listening netconns) */ + int recv_timeout; +#endif /* LWIP_SO_RCVTIMEO */ +#if LWIP_SO_RCVBUF + /* maximum amount of bytes queued in recvmbox + not used for TCP: adjust TCP_WND instead! */ + int recv_bufsize; + /* number of bytes currently in recvmbox to be received, + tested against recv_bufsize to limit bytes on recvmbox + for UDP and RAW, used for FIONREAD */ + int recv_avail; +#endif /* LWIP_SO_RCVBUF */ + /* + * number of bytes left on last recv, for non-stream connections, this value was the buffer_len + * on last peek operation; for stream connection, this value was either the bytes count + * not copied to application on last recv or the buffer_len on last peek operation + */ + u32_t lrcv_left; +#if LWIP_SO_LINGER + /* values <0 mean linger is disabled, values > 0 are seconds to linger */ + s32_t linger; +#endif /* LWIP_SO_LINGER */ + /* flags holding more netconn-internal state, see NETCONN_FLAG_* defines */ + u32_t flags; +#if LWIP_TCP + /* TCP: when data passed to netconn_write doesn't fit into the send buffer, + this temporarily stores how much is already sent. */ + size_t write_offset; + /* TCP: when data passed to netconn_write doesn't fit into the send buffer, + this temporarily stores the message. + Also used during connect and close. */ + struct api_msg *current_msg; +#endif /* LWIP_TCP */ + +#if LWIP_SO_PRIORITY + prio_t priority; +#endif /* LWIP_SO_PRIORITY */ + + /* A callback function that is informed about events for this netconn */ + netconn_callback callback; + atomic_t tcp_connected; + enum netconn_shutdown shutdown; +#if LWIP_SOCK_FILTER + struct sock_fprog sk_filter; +#endif + +#if LWIP_TCP + struct pbuf *refused_data; + ip_addr_t remote_ip; + u16_t remote_port; + /** record pending error state after recving RST */ + u16_t pending_error; +#endif +}; + +/* Register an Network connection event */ +#define API_EVENT(c, e, l) if (c->callback) { \ + (*c->callback)(c, e, l); \ + } + + +/* Set conn->mbox_state to state */ +#define NETCONN_SET_SAFE_MBOX_STATE(conn, state) do { \ + (void)atomic_set(&(conn)->mbox_state, state); \ +} while (0); + +#define NETCONN_SET_SAFE_ERR_VAL(conn, err) do { \ + SYS_ARCH_DECL_PROTECT(netconn_set_safe_err_lev); \ + SYS_ARCH_PROTECT(netconn_set_safe_err_lev); \ + if (!ERR_IS_FATAL((conn)->last_err)) { \ + (conn)->last_err = err; \ + } \ + SYS_ARCH_UNPROTECT(netconn_set_safe_err_lev); \ +} while (0); + +/* Set conn->last_err to err but don't overwrite fatal errors */ +#define NETCONN_SET_SAFE_ERR(conn, err) do { \ + if ((conn) != NULL) { \ + NETCONN_SET_SAFE_ERR_VAL(conn, err); \ + } \ +} while (0); + +/* Network connection functions: */ + +/* @ingroup netconn_common + * Create new netconn connection + * @param t @ref netconn_type */ +#define netconn_new(t) netconn_new_with_proto_and_callback(t, 0, NULL) +#define netconn_new_with_callback(t, c) netconn_new_with_proto_and_callback(t, 0, c) +#if PF_PKT_SUPPORT +struct netconn *netconn_new_with_proto_and_callback(enum netconn_type t, u16_t proto, netconn_callback callback); +#else +struct netconn *netconn_new_with_proto_and_callback(enum netconn_type t, u8_t proto, netconn_callback callback); +#endif + +int netconn_mbox_is_active(struct netconn *conn); + +err_t netconn_initiate_delete(struct netconn *conn); + +void netconn_finish_delete(struct netconn *conn); + +err_t netconn_getconninfo(struct netconn *conn, void *conn_info); + +err_t netconn_delete(struct netconn *conn); +/* Get the type of a netconn (as enum netconn_type). */ +#define NETCONN_TYPE(conn) (conn->type) + +err_t netconn_getaddr(struct netconn *conn, ip_addr_t *addr, + u16_t *port, u8_t local); + +#if LWIP_TCP +void netconn_trygetaddr(struct netconn *conn, ip_addr_t *addr, u16_t *port); +#endif + +/* @ingroup netconn_common */ +#define netconn_peer(c, i, p) netconn_getaddr(c, i, p, 0) +/* @ingroup netconn_common */ +#define netconn_addr(c, i, p) netconn_getaddr(c, i, p, 1) + +#if PF_PKT_SUPPORT +err_t netconn_bind(struct netconn *conn, const ip_addr_t *addr, u16_t port, u8_t ifindex); +#else +err_t netconn_bind(struct netconn *conn, const ip_addr_t *addr, u16_t port); +#endif + +err_t netconn_connect(struct netconn *conn, const ip_addr_t *addr, u16_t port); +err_t netconn_disconnect (struct netconn *conn); +err_t netconn_listen_with_backlog(struct netconn *conn, u8_t backlog); +/* @ingroup netconn_tcp */ +#define netconn_listen(conn) netconn_listen_with_backlog(conn, TCP_DEFAULT_LISTEN_BACKLOG) +err_t netconn_accept(struct netconn *conn, struct netconn **new_conn); +err_t netconn_recv(struct netconn *conn, struct netbuf **new_buf); +err_t netconn_recv_tcp_pbuf(struct netconn *conn, struct pbuf **new_buf); +err_t netconn_sendto(struct netconn *conn, struct netbuf *buf, + const ip_addr_t *addr, u16_t port); +err_t netconn_send(struct netconn *conn, struct netbuf *buf); +err_t netconn_write_partly(struct netconn *conn, const void *dataptr, size_t size, + u8_t apiflags, size_t *bytes_written); +/* @ingroup netconn_tcp */ +#define netconn_write(conn, dataptr, size, apiflags) \ + netconn_write_partly(conn, dataptr, size, apiflags, NULL) +err_t netconn_close(struct netconn *conn); +err_t netconn_shutdown(struct netconn *conn, u8_t shut_rx, u8_t shut_tx); + +#if LWIP_IGMP || (LWIP_IPV6 && LWIP_IPV6_MLD) +/* Internal function */ +err_t netconn_leave_group(struct netconn *conn, const ip_addr_t *multiaddr, + const ip_addr_t *netif_addr, enum netconn_igmp join_or_leave); +/* Stack needs to support to leave group for ipv6 multicast */ +err_t netconn_leave_group_netif(struct netconn *conn, const ip_addr_t *multiaddr, + u8_t if_idx, enum netconn_igmp join_or_leave); +#endif /* LWIP_IGMP || (LWIP_IPV6 && LWIP_IPV6_MLD) */ +#if LWIP_DNS +#if LWIP_IPV4 && LWIP_IPV6 +err_t netconn_gethostbyname_addrtype(const char *name, ip_addr_t *addr, u32_t *count, u8_t dns_addrtype); +#define netconn_gethostbyname(name, addr, count) netconn_gethostbyname_addrtype(name, addr, count, NETCONN_DNS_DEFAULT) +#else /* LWIP_IPV4 && LWIP_IPV6 */ +err_t netconn_gethostbyname(const char *name, ip_addr_t *addr, u32_t *count); +#define netconn_gethostbyname_addrtype(name, addr, count, dns_addrtype) netconn_gethostbyname(name, addr, count) +#endif /* LWIP_IPV4 && LWIP_IPV6 */ +#endif /* LWIP_DNS */ + +#if LWIP_DNS_REVERSE +err_t netconn_getnameinfo(ip_addr_t *addr, char *hostname); +#endif /* LWIP_DNS_REVERSE */ + +#define netconn_err(conn) ((conn)->last_err) +#define netconn_recv_bufsize(conn) ((conn)->recv_bufsize) + +/* Set the blocking status of netconn calls (@todo: write/send is missing) */ +#define netconn_set_nonblocking(conn, val) do { \ + if (val) { \ + (conn)->flags |= NETCONN_FLAG_NON_BLOCKING; \ +} else { \ + (conn)->flags &= (u8_t)~NETCONN_FLAG_NON_BLOCKING; } \ +} while (0) +/* Get the blocking status of netconn calls (@todo: write/send is missing) */ +#define netconn_is_nonblocking(conn) (((conn)->flags & NETCONN_FLAG_NON_BLOCKING) != 0) + +#if LWIP_IPV6 +/* @ingroup netconn_common + * TCP: Set the IPv6 ONLY status of netconn calls (see NETCONN_FLAG_IPV6_V6ONLY) + */ +#define netconn_set_ipv6only(conn, val) do { \ + if (val) { \ + (conn)->flags |= NETCONN_FLAG_IPV6_V6ONLY; \ +} else { \ + (conn)->flags &= (u8_t)~NETCONN_FLAG_IPV6_V6ONLY; } \ +} while (0) +/* @ingroup netconn_common + * TCP: Get the IPv6 ONLY status of netconn calls (see NETCONN_FLAG_IPV6_V6ONLY) + */ +#define netconn_get_ipv6only(conn) (((conn)->flags & NETCONN_FLAG_IPV6_V6ONLY) != 0) +#endif /* LWIP_IPV6 */ + +#if LWIP_SO_SNDTIMEO +/* Set the send timeout in milliseconds */ +#define netconn_set_sendtimeout(conn, timeout) ((conn)->send_timeout = (timeout)) +/* Get the send timeout in milliseconds */ +#define netconn_get_sendtimeout(conn) ((conn)->send_timeout) +#endif /* LWIP_SO_SNDTIMEO */ +#if LWIP_SO_RCVTIMEO +/* Set the receive timeout in milliseconds */ +#define netconn_set_recvtimeout(conn, timeout) ((conn)->recv_timeout = (timeout)) +/* Get the receive timeout in milliseconds */ +#define netconn_get_recvtimeout(conn) ((conn)->recv_timeout) +#endif /* LWIP_SO_RCVTIMEO */ +#if LWIP_SO_RCVBUF +/* Set the receive buffer in bytes */ +#define netconn_set_recvbufsize(conn, recvbufsize) ((conn)->recv_bufsize = (recvbufsize)) +/* Get the receive buffer in bytes */ +#define netconn_get_recvbufsize(conn) ((conn)->recv_bufsize) +#endif /* LWIP_SO_RCVBUF */ + +#if LWIP_NETCONN_SEM_PER_THREAD +void netconn_thread_init(void); +void netconn_thread_cleanup(void); +#else /* LWIP_NETCONN_SEM_PER_THREAD */ +#define netconn_thread_init() +#define netconn_thread_cleanup() +#endif /* LWIP_NETCONN_SEM_PER_THREAD */ + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_NETCONN || LWIP_SOCKET */ + +#endif /* LWIP_HDR_API_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/api_shell.h b/sdk_liteos/third_party/lwip_sack/include/lwip/api_shell.h new file mode 100644 index 0000000000000000000000000000000000000000..dcced5b5cf6400068302fbdb8ef58d19bda55e85 --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/api_shell.h @@ -0,0 +1,135 @@ +/* + * Copyright (c) Huawei Technologies Co., Ltd. 2013-2015. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote + * products derived from this software without specific prior + * written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS + * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * Description: shell cmds APIs declaration + * Author: none + * Create: 2013 + */ + +#ifndef LWIP_API_SHELL_H +#define LWIP_API_SHELL_H + +#include "lwip/opt.h" +#include "lwip/netif.h" +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +extern int tcpip_init_finish; +#ifndef PRINT_USE_CRLF +#define PRINT_USE_CRLF 1 +#endif + +#if PRINT_USE_CRLF +#define CRLF "\r\n" +#else +#define CRLF "\n" +#endif + +/* help convert ptr to u32 array(if 64bit platfrom) */ +union los_ptr_args { + void *ptr; + u32_t args[2]; +}; + +typedef void (*icmp_code_hander)(u8_t code, void *arg); + +#ifdef CUSTOM_AT_COMMAND +typedef enum netstat_trans_type { + TCP_IP6, + TCP, + UDP_IP6, + UDP, + RAW, + PKT_RAW, +} netstat_trans_type; +#endif + +u32_t lwip_ifconfig(int argc, const char **argv); +u32_t lwip_get_ipv4(char *localIp, unsigned char ipLen, unsigned char *ifname); +u32_t lwip_get_mac_addr(unsigned char *macAddr, unsigned int len, unsigned char *ifname); + +u32_t lwip_ifstats(int argc, char **argv); +u32_t lwip_arp(int argc, char **argv); +u32_t at_lwip_arp(int argc, char **argv); +u32_t os_shell_netif_up(int argc, char **argv); +u32_t os_shell_netif_down(int argc, char **argv); +u32_t os_shell_ping(int argc, const char **argv); +#if LWIP_IPV6 +u32_t os_shell_ping6(int argc, const char **argv); +u32_t os_shell_ipdebug(int argc, char **argv); +#endif + +#if LWIP_RPL || LWIP_RIPPLE +u32_t os_shell_rpl(int argc, char **argv); +u32_t os_rte_debug(int argc, char **argv); +#endif + +u32_t os_shell_tftp(int argc, char **argv); +#if LWIP_SNTP +u32_t os_shell_ntpdate(int argc, char **argv); +#endif +#if LWIP_DNS +#ifdef CUSTOM_AT_COMMAND +u32_t os_shell_show_dns(void); +#endif +u32_t os_shell_dns(int argc, const char **argv); +#endif /* LWIP_DNS */ +#if LWIP_IPV4 && LWIP_IGMP +u32_t os_shell_igmp(int argc, char **argv); +u32_t at_os_shell_igmp(int argc, char **argv); +#endif /* LWIP_IPV4 && LWIP_IGMP */ +#if (LWIP_IPV6 && (LWIP_IPV6_MLD || LWIP_IPV6_MLD_QUERIER)) +u32_t os_shell_mld6(int argc, char **argv); +#endif /* (LWIP_IPV6 && (LWIP_IPV6_MLD || LWIP_IPV6_MLD_QUERIER)) */ +#if LWIP_DHCP +u32_t os_shell_dhcp(int argc, const char **argv); +void dhcp_clients_info_show(struct netif *netif_p); +#if LWIP_DHCPS +u32_t os_shell_dhcps(int argc, const char **argv); +void dhcps_info_show(struct netif *netif); +#endif /* LWIP_DHCPS */ +#endif /* LWIP_DHCP */ +u32_t os_shell_netstat(int argc, char **argv); + +void netstat_internal(void *ctx); + +u32_t os_shell_mcast6(int argc, char **argv); +#if LWIP_RIPPLE +u32_t os_shell_l2test(int argc, char **argv); +#endif /* LWIP_RIPPLE */ + +u32_t os_shell_netif(int argc, char **argv); + +u32_t os_shell_display_version(int argc, char **argv); + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif + diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/arch.h b/sdk_liteos/third_party/lwip_sack/include/lwip/arch.h new file mode 100644 index 0000000000000000000000000000000000000000..84585a1db3ac60e1375b63786f5e0ad0645ae579 --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/arch.h @@ -0,0 +1,322 @@ +/** + * @file + * Support for different processor and compiler architectures + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_ARCH_H +#define LWIP_HDR_ARCH_H + +#include +#include "arch/cc.h" + +/* + * @defgroup compiler_abstraction Compiler/platform abstraction + * @ingroup sys_layer + * All defines related to this section must not be placed in lwipopts.h, + * but in arch/cc.h! + * These options cannot be \#defined in lwipopts.h since they are not options + * of lwIP itself, but options of the lwIP port to your system. + * @{ + */ + +/* Define the byte order of the system. + * Needed for conversion of network data to host byte order. + * Allowed values: LITTLE_ENDIAN and BIG_ENDIAN + */ +#ifndef BYTE_ORDER +#define BYTE_ORDER LITTLE_ENDIAN +#endif + +/* Define random number generator function of your system */ +#ifdef __DOXYGEN__ +#define LWIP_RAND() ((u32_t)rand()) +#endif + +/* Platform specific diagnostic output.\n + * Note the default implementation pulls in printf, which may + * in turn pull in a lot of standard libary code. In resource-constrained + * systems, this should be defined to something less resource-consuming. + */ +#ifndef LWIP_PLATFORM_DIAG +#define LWIP_PLATFORM_DIAG(x) do { printf x; } while (0) +#include +#include +#endif + +/* Platform specific assertion handling.\n + * Note the default implementation pulls in printf, fflush and abort, which may + * in turn pull in a lot of standard libary code. In resource-constrained + * systems, this should be defined to something less resource-consuming. + */ +#ifndef LWIP_PLATFORM_ASSERT +#define LWIP_PLATFORM_ASSERT(x) do { printf("Assertion \"%s\" failed at line %d in %s\n", \ + x, __LINE__, __FILE__); fflush(NULL); abort(); } while (0) +#include +#include +#endif + +/* Define this to 1 in arch/cc.h of your port if you do not want to + * include stddef.h header to get size_t. You need to typedef size_t + * by yourself in this case. + */ +#ifndef LWIP_NO_STDDEF_H +#define LWIP_NO_STDDEF_H 0 +#endif + +#if !LWIP_NO_STDDEF_H +#include /* for size_t */ +#endif + +/* Define this to 1 in arch/cc.h of your port if your compiler does not provide + * the stdint.h header. You need to typedef the generic types listed in + * lwip/arch.h yourself in this case (u8_t, u16_t...). + */ +#ifndef LWIP_NO_STDINT_H +#define LWIP_NO_STDINT_H 0 +#endif + +/* Define generic types used in lwIP */ +#if !LWIP_NO_STDINT_H +#include +#include +typedef uint8_t u8_t; +typedef int8_t s8_t; +typedef uint16_t u16_t; +typedef int16_t s16_t; +typedef uint32_t u32_t; +typedef int32_t s32_t; +typedef uint64_t u64_t; +typedef uintptr_t mem_ptr_t; +#endif + +/* Define this to 1 in arch/cc.h of your port if your compiler does not provide + * the inttypes.h header. You need to define the format strings listed in + * lwip/arch.h yourself in this case (X8_F, U16_F...). + */ +#ifndef LWIP_NO_INTTYPES_H +#define LWIP_NO_INTTYPES_H 0 +#endif + +/* Define (sn)printf formatters for these lwIP types */ +#if !LWIP_NO_INTTYPES_H +#include +#ifndef X8_F +#define X8_F "02" PRIx8 +#endif +#ifndef U8_F +#define U8_F PRIu8 +#endif +#ifndef U16_F +#define U16_F PRIu16 +#endif +#ifndef S16_F +#define S16_F PRId16 +#endif +#ifndef X16_F +#define X16_F PRIx16 +#endif +#ifndef U32_F +#define U32_F PRIu32 +#endif +#ifndef S32_F +#define S32_F PRId32 +#endif +#ifndef X32_F +#define X32_F PRIx32 +#endif +#ifndef SZT_F +#define SZT_F PRIuPTR +#endif +#endif + +#ifndef BITS_NUM_PER_BYTE +#define BITS_NUM_PER_BYTE 8 +#endif + +/* Define this to 1 in arch/cc.h of your port if your compiler does not provide + * the limits.h header. You need to define the type limits yourself in this case + * (e.g. INT_MAX). + */ +#ifndef LWIP_NO_LIMITS_H +#define LWIP_NO_LIMITS_H 0 +#endif + +/* Include limits.h? */ +#if !LWIP_NO_LIMITS_H +#include +#endif + +/* C++ const_cast(val) equivalent to remove constness from a value (GCC -Wcast-qual) */ +#ifndef LWIP_CONST_CAST +#define LWIP_CONST_CAST(target_type, val) ((target_type)(void*)((ptrdiff_t)(val))) +#endif + +/* Get rid of alignment cast warnings (GCC -Wcast-align) */ +#ifndef LWIP_ALIGNMENT_CAST +#define LWIP_ALIGNMENT_CAST(target_type, val) LWIP_CONST_CAST(target_type, val) +#endif + +/* Get rid of warnings related to pointer-to-numeric and vice-versa casts, + * e.g. "conversion from 'u8_t' to 'void *' of greater size" + */ +#ifndef LWIP_PTR_NUMERIC_CAST +#define LWIP_PTR_NUMERIC_CAST(target_type, val) LWIP_CONST_CAST(target_type, val) +#endif + +/* Allocates a memory buffer of specified size that is of sufficient size to align + * its start address using LWIP_MEM_ALIGN. + * You can declare your own version here e.g. to enforce alignment without adding + * trailing padding bytes (see LWIP_MEM_ALIGN_BUFFER) or your own section placement + * requirements.\n + * e.g. if you use gcc and need 32 bit alignment:\n + * \#define LWIP_DECLARE_MEMORY_ALIGNED(variable_name, size) u8_t variable_name[size] \_\_attribute\_\_((aligned(4)))\n + * or more portable:\n + * \#define LWIP_DECLARE_MEMORY_ALIGNED(variable_name, size) + * u32_t variable_name[(size + sizeof(u32_t) - 1) / sizeof(u32_t)] + */ +#ifndef LWIP_DECLARE_MEMORY_ALIGNED +#define LWIP_DECLARE_MEMORY_ALIGNED(variable_name, size) u8_t variable_name[LWIP_MEM_ALIGN_BUFFER(size)] +#endif + +/* Calculate memory size for an aligned buffer - returns the next highest + * multiple of MEM_ALIGNMENT (e.g. LWIP_MEM_ALIGN_SIZE(3) and + * LWIP_MEM_ALIGN_SIZE(4) will both yield 4 for MEM_ALIGNMENT == 4). + */ +#ifndef LWIP_MEM_ALIGN_SIZE +#define LWIP_MEM_ALIGN_SIZE(size) (((size) + MEM_ALIGNMENT - 1U) & ~(MEM_ALIGNMENT-1U)) +#endif + +/* Calculate safe memory size for an aligned buffer when using an unaligned + * type as storage. This includes a safety-margin on (MEM_ALIGNMENT - 1) at the + * start (e.g. if buffer is u8_t[] and actual data will be u32_t*) + */ +#ifndef LWIP_MEM_ALIGN_BUFFER +#define LWIP_MEM_ALIGN_BUFFER(size) (((size) + MEM_ALIGNMENT - 1U)) +#endif + +/* Align a memory pointer to the alignment defined by MEM_ALIGNMENT + * so that ADDR % MEM_ALIGNMENT == 0 + */ +#ifndef LWIP_MEM_ALIGN +#define LWIP_MEM_ALIGN(addr) ((void *)(((mem_ptr_t)(addr) + MEM_ALIGNMENT - 1) & ~(mem_ptr_t)(unsigned int)(MEM_ALIGNMENT-1))) // !e511 +#endif + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +/* Packed structs support. + * Placed BEFORE declaration of a packed struct.\n + * For examples of packed struct declarations, see include/lwip/prot/ subfolder.\n + * A port to GCC/clang is included in lwIP, if you use these compilers there is nothing to do here. + */ +#ifndef PACK_STRUCT_BEGIN +#define PACK_STRUCT_BEGIN +#endif /* PACK_STRUCT_BEGIN */ + +/* Packed structs support. + * Placed AFTER declaration of a packed struct.\n + * For examples of packed struct declarations, see include/lwip/prot/ subfolder.\n + * A port to GCC/clang is included in lwIP, if you use these compilers there is nothing to do here. + */ +#ifndef PACK_STRUCT_END +#define PACK_STRUCT_END +#endif /* PACK_STRUCT_END */ + +/* Packed structs support. + * Placed between end of declaration of a packed struct and trailing semicolon.\n + * For examples of packed struct declarations, see include/lwip/prot/ subfolder.\n + * A port to GCC/clang is included in lwIP, if you use these compilers there is nothing to do here. + */ +#ifndef PACK_STRUCT_STRUCT +#if defined(__GNUC__) || defined(__clang__) +#define PACK_STRUCT_STRUCT __attribute__((packed)) +#else +#define PACK_STRUCT_STRUCT +#endif +#endif /* PACK_STRUCT_STRUCT */ + +/* Packed structs support. + * Wraps u32_t and u16_t members.\n + * For examples of packed struct declarations, see include/lwip/prot/ subfolder.\n + * A port to GCC/clang is included in lwIP, if you use these compilers there is nothing to do here. + */ +#ifndef PACK_STRUCT_FIELD +#define PACK_STRUCT_FIELD(x) x +#endif /* PACK_STRUCT_FIELD */ + +/* Packed structs support. + * Wraps u8_t members, where some compilers warn that packing is not necessary.\n + * For examples of packed struct declarations, see include/lwip/prot/ subfolder.\n + * A port to GCC/clang is included in lwIP, if you use these compilers there is nothing to do here. + */ +#ifndef PACK_STRUCT_FLD_8 +#define PACK_STRUCT_FLD_8(x) PACK_STRUCT_FIELD(x) +#endif /* PACK_STRUCT_FLD_8 */ + +/* Packed structs support. + * Wraps members that are packed structs themselves, where some compilers warn that packing is not necessary.\n + * For examples of packed struct declarations, see include/lwip/prot/ subfolder.\n + * A port to GCC/clang is included in lwIP, if you use these compilers there is nothing to do here. + */ +#ifndef PACK_STRUCT_FLD_S +#define PACK_STRUCT_FLD_S(x) PACK_STRUCT_FIELD(x) +#endif /* PACK_STRUCT_FLD_S */ + +/* Packed structs support using \#include files before and after struct to be packed.\n + * The file included BEFORE the struct is "arch/bpstruct.h".\n + * The file included AFTER the struct is "arch/epstruct.h".\n + * This can be used to implement struct packing on MS Visual C compilers, see + * the Win32 port in the lwIP contrib repository for reference. + * For examples of packed struct declarations, see include/lwip/prot/ subfolder.\n + * A port to GCC/clang is included in lwIP, if you use these compilers there is nothing to do here. + */ +#ifdef __DOXYGEN__ +#define PACK_STRUCT_USE_INCLUDES +#endif + +/* Eliminates compiler warning about unused arguments (GCC -Wextra -Wunused). */ +#ifndef LWIP_UNUSED_ARG +#define LWIP_UNUSED_ARG(x) (void)x +#endif /* LWIP_UNUSED_ARG */ + +/* + * @} + */ + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_HDR_ARCH_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/autoip.h b/sdk_liteos/third_party/lwip_sack/include/lwip/autoip.h new file mode 100644 index 0000000000000000000000000000000000000000..0f07e4cf65aa06da66c58fa2b7b1af36b5a973ad --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/autoip.h @@ -0,0 +1,100 @@ +/** + * @file + * + * AutoIP Automatic LinkLocal IP Configuration + */ + +/* + * + * Copyright (c) 2007 Dominik Spies + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * Author: Dominik Spies + * + * This is a AutoIP implementation for the lwIP TCP/IP stack. It aims to conform + * with RFC 3927. + * + */ + +#ifndef LWIP_HDR_AUTOIP_H +#define LWIP_HDR_AUTOIP_H + +#include "lwip/opt.h" + +#if LWIP_IPV4 && LWIP_AUTOIP /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/netif.h" +#include "lwip/etharp.h" + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +/* AutoIP Timing */ +#define AUTOIP_TMR_INTERVAL 100 +#define AUTOIP_TICKS_PER_SECOND (1000 / AUTOIP_TMR_INTERVAL) + +/* AutoIP state information per netif */ +struct autoip { + /* the currently selected, probed, announced or used LL IP-Address */ + ip4_addr_t llipaddr; + /* current AutoIP state machine state */ + u8_t state; + /* sent number of probes or announces, dependent on state */ + u8_t sent_num; + /* ticks to wait, tick is AUTOIP_TMR_INTERVAL long */ + u16_t ttw; + /* ticks until a conflict can be solved by defending */ + u8_t lastconflict; + /* total number of probed/used Link Local IP-Addresses */ + u8_t tried_llipaddr; +}; + +void autoip_set_struct(struct netif *netif, struct autoip *autoip); +/* Remove a struct autoip previously set to the netif using autoip_set_struct() */ +#define autoip_remove_struct(netif) do { (netif)->autoip = NULL; } while (0) +err_t autoip_start(struct netif *netif); +err_t autoip_stop(struct netif *netif); +void autoip_arp_reply(struct netif *netif, struct etharp_hdr *hdr); +void autoip_tmr(void); +void autoip_network_changed(struct netif *netif); +u8_t autoip_supplied_address(const struct netif *netif); + +/* for lwIP internal use by ip4.c */ +u8_t autoip_accept_packet(struct netif *netif, const ip4_addr_t *addr); + +#define netif_autoip_data(netif) ((struct autoip*)netif_get_client_data(netif, LWIP_NETIF_CLIENT_DATA_INDEX_AUTOIP)) + +#if LWIP_LOWPOWER +u32_t autoip_tmr_tick(void); +#endif + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_IPV4 && LWIP_AUTOIP */ + +#endif /* LWIP_HDR_AUTOIP_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/debug.h b/sdk_liteos/third_party/lwip_sack/include/lwip/debug.h new file mode 100644 index 0000000000000000000000000000000000000000..39add880078d424529326245446678a2dc0e51df --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/debug.h @@ -0,0 +1,239 @@ +/** + * @file + * Debug messages infrastructure + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_DEBUG_H +#define LWIP_HDR_DEBUG_H + +#include "lwip/arch.h" +#include "lwip/opt.h" + +#ifdef LWIP_ENABLE_DIAG_SUPPORT +#include "diag_util.h" +#endif + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +/** + * @defgroup debugging_levels LWIP_DBG_MIN_LEVEL and LWIP_DBG_TYPES_ON values + * @ingroup lwip_opts_debugmsg + * @{ + */ + +/** @name Debug level (LWIP_DBG_MIN_LEVEL) + * @{ + */ +/** Debug level: ALL messages*/ +#define LWIP_DBG_LEVEL_ALL 0x00 +/** Debug level: Warnings. bad checksums, dropped packets, ... */ +#define LWIP_DBG_LEVEL_WARNING 0x01 +/** Debug level: Serious. memory allocation failures, ... */ +#define LWIP_DBG_LEVEL_SERIOUS 0x02 +/** Debug level: Severe */ +#define LWIP_DBG_LEVEL_SEVERE 0x03 +/** + * @} + */ + +#define LWIP_DBG_MASK_LEVEL 0x03 +/* compatibility define only */ +#define LWIP_DBG_LEVEL_OFF LWIP_DBG_LEVEL_ALL + +/** @name Enable/disable debug messages completely (LWIP_DBG_TYPES_ON) + * @{ + */ +/** flag for LWIP_DEBUGF to enable that debug message */ +#define LWIP_DBG_ON 0x80U +/** flag for LWIP_DEBUGF to disable that debug message */ +#define LWIP_DBG_OFF 0x00U +/** + * @} + */ + +/** @name Debug message types (LWIP_DBG_TYPES_ON) + * @{ + */ +/** flag for LWIP_DEBUGF indicating a tracing message (to follow program flow) */ +#ifndef LWIP_DBG_TRACE +#define LWIP_DBG_TRACE 0x40U +#endif +/** flag for LWIP_DEBUGF indicating a state dbg message (to follow module states) */ +#define LWIP_DBG_STATE 0x20U +/** flag for LWIP_DEBUGF indicating newly added code, not thoroughly tested yet */ +#define LWIP_DBG_FRESH 0x10U +/** flag for LWIP_DEBUGF to halt after printing this dbg message + * @endcond */ +#define LWIP_DBG_HALT 0x08U +/** + * @} + */ + +/** + * @} + */ + +/** + * @defgroup lwip_assertions Assertion handling + * @ingroup lwip_opts_debug + * @{ + */ +/** + * LWIP_NOASSERT: Disable LWIP_ASSERT checks: + * To disable assertions define LWIP_NOASSERT in arch/cc.h. + */ +#ifdef __DOXYGEN__ +#ifndef LWIP_NOASSERT +#define LWIP_NOASSERT +#undef LWIP_NOASSERT +#endif +#endif +/** + * @} + */ + +#ifndef LWIP_NOASSERT +#define LWIP_ASSERT(message, assertion) do { if (!(assertion)) { \ + LWIP_PLATFORM_ASSERT(message); } } while (0) +#ifndef LWIP_PLATFORM_ASSERT +#error "If you want to use LWIP_ASSERT, LWIP_PLATFORM_ASSERT(message) needs to be defined in your arch/cc.h" +#endif +#else /* LWIP_NOASSERT */ +#define LWIP_ASSERT(message, assertion) +#endif /* LWIP_NOASSERT */ + +#ifndef LWIP_ERROR +#ifndef LWIP_NOASSERT +#define LWIP_PLATFORM_ERROR(message) LWIP_PLATFORM_ASSERT(message) +#elif defined LWIP_DEBUG +#define LWIP_PLATFORM_ERROR(message) LWIP_PLATFORM_DIAG((message)) +#else +#define LWIP_PLATFORM_ERROR(message) +#endif + +#ifdef LWIP_ENABLE_DIAG_SUPPORT +#define LWIP_ERROR_LOG0(message) diag_layer_msg_e0(0, message) +#else +#define LWIP_ERROR_LOG0(message) +#endif + +#ifdef CUSTOM_AT_COMMAND +#define LWIP_ERROR(message, expression, handler) do { \ + if (!(expression)) { \ + LWIP_ERROR_LOG0(message); \ + handler; \ + } \ +} while (0) +#else +/* if "expression" isn't true, then print "message" and execute "handler" expression */ +#define LWIP_ERROR(message, expression, handler) do { if (!(expression)) { \ + LWIP_PLATFORM_ERROR(message); handler; } } while (0) +#endif /* LWIP_ERROR */ +#endif + +/** Enable dbg message printing, but only if debug message type is enabled + * AND is of correct type AND is at least LWIP_DBG_LEVEL. + */ +#ifdef __DOXYGEN__ +#define LWIP_DEBUG +#undef LWIP_DEBUG +#endif + +#ifdef LWIP_DEBUG +#ifndef LWIP_PLATFORM_DIAG +#error "If you want to use LWIP_DEBUG, LWIP_PLATFORM_DIAG(message) needs to be defined in your arch/cc.h" +#endif +#define LWIP_DEBUGF(dbg, message) do { \ + if ( \ + ((dbg) & LWIP_DBG_ON) && \ + ((dbg) & LWIP_DBG_TYPES_ON) && \ + ((s16_t)((dbg) & LWIP_DBG_MASK_LEVEL) >= LWIP_DBG_MIN_LEVEL)) { \ + LWIP_PLATFORM_DIAG(message); \ + if ((dbg) & LWIP_DBG_HALT) { \ + while (1); \ + } \ + } \ +} while (0) + +#else /* LWIP_DEBUG */ +#define LWIP_DEBUGF(debug, message) +#endif /* LWIP_DEBUG */ + +#ifdef LWIP_ENABLE_DIAG_SUPPORT +#define LWIP_DEBUGF_LOG0(dbg, fmt) diag_layer_msg_i0(0, fmt); +#define LWIP_DEBUGF_LOG1(dbg, fmt, p1) diag_layer_msg_i1(0, fmt, (hi_u32)(p1)); +#define LWIP_DEBUGF_LOG2(dbg, fmt, p1, p2) diag_layer_msg_i2(0, fmt, (hi_u32)(p1), (hi_u32)(p2)); +#define LWIP_DEBUGF_LOG3(dbg, fmt, p1, p2, p3) \ + diag_layer_msg_i3(0, fmt, (hi_u32)(p1), (hi_u32)(p2), (hi_u32)(p3)); +#define LWIP_DEBUGF_LOG4(dbg, fmt, p1, p2, p3, p4) \ + diag_layer_msg_i4(0, fmt, (hi_u32)(p1), (hi_u32)(p2), (hi_u32)(p3), (hi_u32)(p4)); +#else +#define LWIP_DEBUGF_LOG0(dbg, fmt) LWIP_DEBUGF(dbg, (fmt)) +#define LWIP_DEBUGF_LOG1(dbg, fmt, p1) LWIP_DEBUGF(dbg, (fmt, p1)); +#define LWIP_DEBUGF_LOG2(dbg, fmt, p1, p2) LWIP_DEBUGF(dbg, (fmt, p1, p2)); +#define LWIP_DEBUGF_LOG3(dbg, fmt, p1, p2, p3) LWIP_DEBUGF(dbg, (fmt, p1, p2, p3)); +#define LWIP_DEBUGF_LOG4(dbg, fmt, p1, p2, p3, p4) LWIP_DEBUGF(dbg, (fmt, p1, p2, p3, p4)); +#endif + +#if defined(PBUF_API) && PBUF_API +#define PBUF_ERROR(...) LWIP_ERROR(__VA_ARGS__) +#else +#define PBUF_ERROR(...) +#endif + +#ifdef LWIP_DEBUG_INFO +void debug_socket_info(int idx, int filter, int expend); +#if LWIP_TCP +void debug_tcppcb_info(void *pcb); +#endif /* LWIP_TCP */ +#if LWIP_UDP || LWIP_UDPLITE +void debug_udppcb_info(void *pcb); +#endif /* LWIP_UDP || LWIP_UDPLITE */ +#if LWIP_RAW +void debug_rawpcb_info(void *pcb); +#endif /* LWIP_RAW */ +void debug_netconn_info(void *netconn_para, int expend); + +void debug_ippcb_info(void *pcb); +void debug_memp_type_info(int type); +void debug_memp_info(void); +void debug_memp_detail(int type); +#endif /* LWIP_DEBUG_INFO */ + +#if defined (__cplusplus) && __cplusplus +} +#endif +#endif /* LWIP_HDR_DEBUG_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/def.h b/sdk_liteos/third_party/lwip_sack/include/lwip/def.h new file mode 100644 index 0000000000000000000000000000000000000000..1ed637582c3f74d03f5d2d0e7f4caf1deef756e6 --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/def.h @@ -0,0 +1,173 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * Copyright (c) <2013-2015>, + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_DEF_H +#define LWIP_HDR_DEF_H + +/* arch.h might define NULL already */ +#include "lwip/arch.h" +#include "lwip/opt.h" + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +/* time unit */ +#define MS_PER_SECOND 1000 +#define US_PER_MSECOND 1000 +#define NS_PER_USECOND 1000 + +#define LWIP_MAX(x, y) (((x) > (y)) ? (x) : (y)) +#define LWIP_MIN(x, y) (((x) < (y)) ? (x) : (y)) + +/* Get the number of entries in an array ('x' must NOT be a pointer!) */ +#define LWIP_ARRAYSIZE(x) (sizeof(x)/sizeof((x)[0])) + +/** Create u32_t value from bytes */ +#define LWIP_MAKEU32(a, b, c, d) (((u32_t)((a) & 0xff) << 24) | \ + ((u32_t)((b) & 0xff) << 16) | \ + ((u32_t)((c) & 0xff) << 8) | \ + (u32_t)((d) & 0xff)) + + +/* Endianess-optimized shifting of two u8_t to create one u16_t */ +#if BYTE_ORDER == LITTLE_ENDIAN +#define LWIP_MAKE_U16(a, b) (((a) << 8) | (b)) +#else +#define LWIP_MAKE_U16(a, b) (((b) << 8) | (a)) +#endif + +#ifndef LWIP_PLATFORM_BYTESWAP +#define LWIP_PLATFORM_BYTESWAP 0 +#endif + +/* workaround for naming collisions on some platforms */ +#ifdef htons +#define lwip_htons htons +#else +#if (BYTE_ORDER == BIG_ENDIAN) +#define lwip_htons(x) ((u16_t)(x)) +#else +u16_t lwip_htons(u16_t x); +#endif +#define htons lwip_htons +#endif /* htons */ +#ifdef htonl +#define lwip_htonl htonl +#else +#if (BYTE_ORDER == BIG_ENDIAN) +#define lwip_htonl(x) ((u32_t)(x)) +#else +u32_t lwip_htonl(u32_t x); +#endif +#define htonl lwip_htonl +#endif /* htonl */ +#ifdef ntohs +#define lwip_ntohs ntohs +#else +#if (BYTE_ORDER == BIG_ENDIAN) +#define lwip_ntohs(x) ((u16_t)(x)) +#else +u16_t lwip_ntohs(u16_t x); +#endif +#define ntohs lwip_ntohs +#endif /* ntohs */ + +#ifdef ntohl +#define lwip_ntohl ntohl +#else +#if (BYTE_ORDER == BIG_ENDIAN) +#define lwip_ntohl(x) ((u32_t)(x)) +#else +u32_t lwip_ntohl(u32_t x); +#endif +#define ntohl lwip_ntohl +#endif /* ntohl */ + +#if (BYTE_ORDER == BIG_ENDIAN) +#define PP_HTONS(x) ((u16_t)(x)) +#define PP_NTOHS(x) ((u16_t)(x)) +#define PP_HTONL(x) ((u32_t)(x)) +#define PP_NTOHL(x) ((u32_t)(x)) +#else /* BYTE_ORDER != BIG_ENDIAN */ + + +/* These macros should be calculated by the preprocessor and are used + with compile-time constants only (so that there is no little-endian + overhead at runtime). */ +#define PP_HTONS(x) ((((x) & 0x00ff) << 8) | (((x) & 0xff00) >> 8)) +#define PP_NTOHS(x) PP_HTONS(x) +#define PP_HTONL(x) ((((x) & 0x000000ffUL) << 24) | \ + (((x) & 0x0000ff00UL) << 8) | \ + (((x) & 0x00ff0000UL) >> 8) | \ + (((x) & 0xff000000UL) >> 24)) +#define PP_NTOHL(x) PP_HTONL(x) + +#endif /* BYTE_ORDER == BIG_ENDIAN */ + +/* Functions that are not available as standard implementations. + * In cc.h, you can #define these to implementations available on + * your platform to save some code bytes if you use these functions + * in your application, too. + */ + +#ifndef lwip_itoa +/* This can be #defined to itoa() or snprintf(result, bufsize, "%d", number) depending on your platform */ +void lwip_itoa(char *result, size_t bufsize, int number); +#endif +#ifndef lwip_strnicmp +/* This can be #defined to strnicmp() or strncasecmp() depending on your platform */ +int lwip_strnicmp(const char *str1, const char *str2, size_t len); +#endif +#ifndef lwip_stricmp +/* This can be #defined to stricmp() or strcasecmp() depending on your platform */ +int lwip_stricmp(const char *str1, const char *str2); +#endif +#ifndef lwip_strnstr +/* This can be #defined to strnstr() depending on your platform */ +char *lwip_strnstr(const char *buffer, const char *token, size_t n); +#endif +#if LWIP_SO_DONTROUTE +/* route entry scope, Actually it is not scope, but distance to the destination. */ +typedef enum rt_scope { + RT_SCOPE_UNIVERSAL, /* everywhere in the Universe */ + RT_SCOPE_LINK, /* destinations located on directly attached link, maybe not same IP network */ + RT_SCOPE_HOST /* our local address */ +} rt_scope_t; +#endif + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_HDR_DEF_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/dhcp.h b/sdk_liteos/third_party/lwip_sack/include/lwip/dhcp.h new file mode 100644 index 0000000000000000000000000000000000000000..c9fc65de0a84bf1073f390f7eb806af992517e60 --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/dhcp.h @@ -0,0 +1,349 @@ +/** + * @file + * DHCP client API + */ + +/* + * Copyright (c) 2001-2004 Leon Woestenberg + * Copyright (c) 2001-2004 Axon Digital Design B.V., The Netherlands. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Leon Woestenberg + * + */ +#ifndef LWIP_HDR_DHCP_H +#define LWIP_HDR_DHCP_H + +#include "lwip/opt.h" + +#if LWIP_DHCP /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/netif.h" +#include "lwip/udp.h" +#include "lwip/dhcps.h" +#include "lwip/prot/dhcp.h" +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +#ifndef LWIP_DHCP_NATIVE_IDX +#define LWIP_DHCP_NATIVE_IDX 0 +#endif + +#ifndef LWIP_DHCP_ANNOUNCE_NUM +#define LWIP_DHCP_ANNOUNCE_NUM 2 +#endif + +#ifndef LWIP_DHCP_ANNOUNCE_INTERVAL +#define LWIP_DHCP_ANNOUNCE_INTERVAL 2 /* seconds */ +#endif + +#if LWIP_DHCP_SUBSTITUTE +struct dhcp_clients_info; +#ifndef DHCP_CLIENT_NUM +#define DHCP_CLIENT_NUM 256 +#endif +typedef u16_t dhcp_num_t; +#define DHCP_NUM_F "hu" +#else +#ifndef DHCP_CLIENT_NUM +#define DHCP_CLIENT_NUM 1 +#endif +typedef u32_t dhcp_num_t; +#define DHCP_NUM_F "u" +#endif /* LWIP_DHCP_SUBSTITUTE */ + +#define IPV4_ADDRESS_PREFIX_CLASS_A 127 +#define IPV4_ADDRESS_PREFIX_CLASS_C 192 + +#define DHCP_XID(_xid, _mac, _mac_len, _dhcp_xid) do { \ + u8_t *_p = (u8_t *)(&(_xid)); \ + _p[0] = (_mac)[(_mac_len) - 3]; \ + _p[1] = (_mac)[(_mac_len) - 2]; \ + _p[2] = (_mac)[(_mac_len) - 1]; \ + _p[3] = _dhcp_xid; \ +} while (0) + +#define DHCP_HOST_TO_IP(_ip, _serv_ip, _mask, _host) do { \ + u32_t _ipaddr = (u32_t)(_host); \ + (_ip) = (((_serv_ip) & (_mask)) | lwip_htonl(_ipaddr)); \ +} while (0) + +#define DHCP_IP_TO_HOST(_host, _ip, _mask) do { \ + (_host) = (dhcp_num_t)(lwip_ntohl(_ip) & (~lwip_ntohl(_mask))); \ +} while (0) + +/* more related events should be defined here */ +#define DHCP_EVENT_HW 0x01 + +/* period (in seconds) of the application calling dhcp_coarse_tmr() */ +#define DHCP_COARSE_TIMER_SECS 10 +/* period (in milliseconds) of the application calling dhcp_coarse_tmr() */ +#define DHCP_COARSE_TIMER_MSECS (DHCP_COARSE_TIMER_SECS * 1000UL) +/* period (in milliseconds) of the application calling dhcp_fine_tmr() */ +#define DHCP_FINE_TIMER_MSECS 500 + +#ifndef DHCP_DISCOVER_RETRANSMIT_INTERVAL +#define DHCP_DISCOVER_RETRANSMIT_INTERVAL 250 +#endif + +#define DHCP_BOOT_FILE_LEN 128U +#define DHCP_BROADCAST_FLAG 0x8000 +/* AutoIP cooperation flags (struct dhcp.autoip_coop_state) */ +typedef enum { + DHCP_AUTOIP_COOP_STATE_OFF = 0, + DHCP_AUTOIP_COOP_STATE_ON = 1 +} dhcp_autoip_coop_state_enum_t; + +/* + * DHCP_OPTION_MAX_MSG_SIZE is set to the MTU + * MTU is checked to be big enough in dhcp_start + */ +#define DHCP_MAX_MSG_LEN(netif) (netif->mtu) +#define DHCP_MAX_MSG_LEN_MIN_REQUIRED 576 + +#if LWIP_DHCP_VENDOR_CLASS_IDENTIFIER +struct vci_info { + /* buffer for vendor class identifier information */ + char vci[DHCP_VCI_MAX_LEN]; + /* real length of vci */ + u8_t vci_len; + /* pad for performance optimization */ + char pad[24]; +}; + +err_t dhcp_set_vci(char *vci, u8_t vci_len); +#if LWIP_DHCP_GET_VENDOR_CLASS_IDENTIFIER +err_t dhcp_get_vci(char *vci, u8_t *vci_len); +#endif /* LWIP_DHCP_GET_VENDOR_CLASS_IDENTIFIER */ +#endif /* LWIP_DHCP_VENDOR_CLASS_IDENTIFIER */ + +/** Minimum length for reply before packet is parsed */ +#define DHCP_MIN_REPLY_LEN 44 + +#define REBOOT_TRIES 2 + +#if LWIP_DNS && LWIP_DHCP_MAX_DNS_SERVERS +#if DNS_MAX_SERVERS > LWIP_DHCP_MAX_DNS_SERVERS +#define LWIP_DHCP_PROVIDE_DNS_SERVERS LWIP_DHCP_MAX_DNS_SERVERS +#else +#define LWIP_DHCP_PROVIDE_DNS_SERVERS DNS_MAX_SERVERS +#endif +#else +#define LWIP_DHCP_PROVIDE_DNS_SERVERS 0 +#endif + +/* + * Option handling: options are parsed in dhcp_parse_reply + * and saved in an array where other functions can load them from. + * This might be moved into the struct dhcp (not necessarily since + * lwIP is single-threaded and the array is only used while in recv + * callback). + */ +enum dhcp_option_idx { + DHCP_OPTION_IDX_OVERLOAD = 0, + DHCP_OPTION_IDX_MSG_TYPE, + DHCP_OPTION_IDX_SERVER_ID, + DHCP_OPTION_IDX_LEASE_TIME, + DHCP_OPTION_IDX_T1, + DHCP_OPTION_IDX_T2, + DHCP_OPTION_IDX_SUBNET_MASK, + DHCP_OPTION_IDX_ROUTER, +#if LWIP_DHCP_PROVIDE_DNS_SERVERS + DHCP_OPTION_IDX_DNS_SERVER, + DHCP_OPTION_IDX_DNS_SERVER_LAST = DHCP_OPTION_IDX_DNS_SERVER + LWIP_DHCP_PROVIDE_DNS_SERVERS - 1, +#endif /* LWIP_DHCP_PROVIDE_DNS_SERVERS */ +#if LWIP_DHCP_GET_NTP_SRV + DHCP_OPTION_IDX_NTP_SERVER, + DHCP_OPTION_IDX_NTP_SERVER_LAST = DHCP_OPTION_IDX_NTP_SERVER + LWIP_DHCP_MAX_NTP_SERVERS - 1, +#endif /* LWIP_DHCP_GET_NTP_SRV */ + DHCP_OPTION_IDX_REQUESTED_IP, +#if LWIP_DHCPS_AGENT_INFO + DHCP_OPTION_IDX_AGENT_INFO, +#endif + DHCP_OPTION_IDX_MAX +}; + +struct dhcp_state { + /* transaction identifier of last sent request */ + u8_t xid; + /* retries of current request <= 255 */ + u8_t tries; + u16_t lease_used; /* #ticks with period DHCP_COARSE_TIMER_SECS since last received DHCP ack */ + u16_t request_timeout; /* #ticks with period DHCP_FINE_TIMER_SECS for request timeout */ + u16_t re_time; /* #ticks with period DHCP_COARSE_TIMER_SECS until next renew/rebind try */ + /* current DHCP state machine state */ + u8_t state: 4; + u8_t hwaddr_len: 4; + /* idx in NAT64 table */ + dhcp_num_t idx; + /* host part of IP */ + dhcp_num_t offered_ip_addr; +}; + +struct dhcp_client { + u16_t t0_timeout; /* #ticks with period DHCP_COARSE_TIMER_SECS for lease time */ + u16_t t1_timeout; /* #ticks with period DHCP_COARSE_TIMER_SECS for renewal time */ + u16_t t2_timeout; /* #ticks with period DHCP_COARSE_TIMER_SECS for rebind time */ + ip_addr_t server_ip_addr; /* dhcp server address that offered this lease (ip_addr_t because passed to UDP) */ + u8_t subnet_mask_given; + ip4_addr_t offered_sn_mask; + ip4_addr_t offered_gw_addr; + ip4_addr_t relay_ip; + u32_t offered_t0_lease; /* lease period (in seconds) */ + u32_t offered_t1_renew; /* recommended renew time (usually 50% of lease period) */ + u32_t offered_t2_rebind; /* recommended rebind time (usually 87.5 of lease period) */ + + /* incoming msg */ + struct dhcp_msg *msg_in; + struct pbuf *p_out; /* pbuf of outcoming msg */ + struct dhcp_msg *msg_out; /* outgoing msg */ + u16_t options_out_len; /* outgoing msg options length */ + + u8_t hwaddr[NETIF_MAX_HWADDR_LEN]; + dhcp_num_t cli_cnt; + /* cli_idx = LWIP_DHCP_NATIVE_IDX always means the client for the netif */ + dhcp_num_t cli_idx; + struct dhcp_state states[DHCP_CLIENT_NUM]; +}; + +struct dhcp { + /* track PCB allocation state */ + u8_t pcb_allocated; +#if LWIP_DHCP_AUTOIP_COOP + u8_t autoip_coop_state; +#endif + +#if LWIP_DHCP_BOOTP_FILE + ip4_addr_t offered_si_addr; + char boot_file_name[DHCP_BOOT_FILE_LEN]; +#endif /* LWIP_DHCP_BOOTPFILE */ +#if LWIP_DHCP_SUBSTITUTE + u8_t flags; + struct dhcp_clients_info *clis_info; +#endif + struct dhcp_client client; +}; + +#ifdef LWIP_DHCPS +struct dyn_lease_addr { + u8_t cli_hwaddr[DHCP_CHADDR_LEN]; + u32_t flags; + u32_t leasetime; + u32_t proposed_leasetime; + ip4_addr_t cli_addr; +}; + +struct dhcps { + struct udp_pcb *pcb; + struct dyn_lease_addr leasearr[LWIP_DHCPS_MAX_LEASE]; + u8_t pcb_allocated; + u8_t lease_num; + struct netif *netif; + ip4_addr_t start_addr; + ip4_addr_t end_addr; +#if LWIP_DHCPS_AGENT_INFO + struct pbuf *p_in; /* pbuf of incoming msg */ +#endif +}; +#endif + +#if LWIP_API_RICH +void dhcp_set_struct(struct netif *netif, struct dhcp *dhcp); +/* Remove a struct dhcp previously set to the netif using dhcp_set_struct() */ +void dhcp_remove_struct(struct netif *netif); +#endif /* LWIP_API_RICH */ + +void dhcp_cleanup(struct netif *netif); +err_t dhcp_is_bound(struct netif *netif); +err_t dhcp_start(struct netif *netif); +err_t dhcp_renew(struct netif *netif); +err_t dhcp_release(struct netif *netif); +void dhcp_stop(struct netif *netif); +void dhcp_inform(struct netif *netif); +void dhcp_network_changed(struct netif *netif); +#if DHCP_DOES_ARP_CHECK +void dhcp_arp_reply(struct netif *netif, const ip4_addr_t *addr); +#endif +#if LWIP_API_RICH +u8_t dhcp_supplied_address(const struct netif *netif); +#endif /* LWIP_API_RICH */ +/* to be called every minute */ +void dhcp_coarse_tmr(void); +/* to be called every half second */ +void dhcp_fine_tmr(void); + +#if LWIP_LOWPOWER +u32_t dhcp_coarse_tmr_tick(void); +u32_t dhcp_fine_tmr_tick(void); +#endif + +#if LWIP_DHCP_GET_NTP_SRV +/* This function must exist, in other to add offered NTP servers to + * the NTP (or SNTP) engine. + * See LWIP_DHCP_MAX_NTP_SERVERS */ +extern void dhcp_set_ntp_servers(u8_t num_ntp_servers, const ip4_addr_t *ntp_server_addrs); +#endif /* LWIP_DHCP_GET_NTP_SRV */ + +#define netif_dhcp_data(netif) ((struct dhcp*)netif_get_client_data(netif, LWIP_NETIF_CLIENT_DATA_INDEX_DHCP)) + +#if LWIP_DHCP_SUBSTITUTE + +struct dhcp_client_info { + ip4_addr_t ipaddr; + u8_t mac[NETIF_MAX_HWADDR_LEN]; +#if NETIF_MAX_HWADDR_LEN != 6 + u8_t mac_len; +#endif +}; + +struct dhcp_clients_info { + dhcp_num_t num; + struct dhcp_client_info clis[0]; +}; + +#if LWIP_ARP +void dhcp_events_record(struct netif *netif, u8_t flags); +void dhcp_events_trigger(struct netif *netif); +#endif /* LWIP_ARP */ +err_t dhcp_substitute_start(struct netif *netif, dhcp_num_t mac_idx); +void dhcp_substitute_stop(struct netif *netif, dhcp_num_t mac_idx); +err_t dhcp_substitute_idx_to_ip(struct netif *netif, dhcp_num_t idx, ip4_addr_t *ip); +err_t dhcp_clients_info_get(struct netif *netif, void *arg); +err_t dhcp_clients_info_free(struct netif *netif, void *arg); +#if LWIP_ENABLE_BASIC_SHELL_CMD +s32_t dhcp_netif_addr_clients_check(const struct netif *netif, const ip4_addr_t *ipaddr); +#endif /* LWIP_ENABLE_BASIC_SHELL_CMD */ +#endif /* LWIP_DHCP_SUBSTITUTE */ + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_DHCP */ + +#endif /* LWIP_HDR_DHCP_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/dhcp6.h b/sdk_liteos/third_party/lwip_sack/include/lwip/dhcp6.h new file mode 100644 index 0000000000000000000000000000000000000000..9c677d639d59174530f274fdf55dc7e7457517a7 --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/dhcp6.h @@ -0,0 +1,150 @@ +/* + * Description: DHCPv6 client: IPv6 address autoconfiguration as per + * RFC 3315 (stateful DHCPv6) and RFC 3736 (stateless DHCPv6). + */ + +#ifndef LWIP_HDR_IP6_DHCP6_H +#define LWIP_HDR_IP6_DHCP6_H + +#include "lwip/opt.h" + +#if LWIP_IPV6_DHCP6 /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/err.h" +#include "lwip/netif.h" + +/* period (in milliseconds) of the application calling dhcp6_tmr() */ +#define DHCP6_TIMER_MSECS 500 +#define DHCP6_IAID_SIZE 4 + +/* DUID: DHCP unique Identifier */ +typedef struct duid { + u16_t duid_len; /* length */ + u8_t *duid_id; /* variable length ID value (must be opaque) */ +} duid_t; + +PACK_STRUCT_BEGIN +struct ia_info { + u32_t dh6_ia_iaid; + u32_t dh6_ia_t1; + u32_t dh6_ia_t2; +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END + +typedef struct iaid { + u16_t iaid_len; + struct ia_info ia; +} iaid_t; + +/* + * General format of Identity Association. + * This format applies to Prefix Delegation (IA_PD) and Non-temporary Addresses + * (IA_NA) + */ +PACK_STRUCT_BEGIN +struct dhcp6opt_ia { + u16_t dh6_ia_type; + u16_t dh6_ia_len; + u32_t dh6_ia_iaid; + u32_t dh6_ia_t1; + u32_t dh6_ia_t2; + /* sub options follow */ +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END + +PACK_STRUCT_BEGIN +struct dhcp6opt_iaaddr { + ip6_addr_t dh6_iaaddr_addr; + u32_t dh6_iaaddr_preferred; + u32_t dh6_iaaddr_valid; + /* sub options follow */ +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END + +typedef struct opt_comm { + struct opt_comm *next; + u16_t opt_type; + u16_t opt_len; + u8_t *opt_start; +} opt_comm_t; + +typedef struct ia { + iaid_t iaid; + struct dhcp6opt_iaaddr iaaddr; +} ia_t; + +typedef struct dhcp6_serverinfo { + struct dhcp6_serverinfo *next; + u8_t *buff; + opt_comm_t *opts; + u16_t buff_len; + u8_t pref; /* server preference */ + ip_addr_t unicast_addr; + bool active; + bool unicast; +} dhcp6_serverinfo_t; + +struct dhcp6 { + /* transaction identifier of last sent request */ + u32_t xid; + /* connection to server */ + struct udp_pcb *pcb; + /* current DHCPv6 state machine state */ + u8_t state; + /* retries of current request */ + u8_t tries; + /* if request config is triggered while another action is active, this keeps track of it */ + u8_t request_config_pending; + /* #ticks with period DHCP6_TIMER_MSECS for request timeout */ + u16_t request_timeout; +#if LWIP_IPV6_DHCP6_STATEFUL + u8_t struct_init; /* indicate whether memory that should be alloced is initialized */ + duid_t duid; /* DHCP Unique Identifier */ + ia_t ia[LWIP_IPV6_NUM_ADDRESSES]; /* Identity Association */ + dhcp6_serverinfo_t *current_serv; /* the server which we contact currently */ + dhcp6_serverinfo_t *serv_list; /* servers which response our Solicit */ + u32_t RT; /* Retransmission timeout */ + u32_t IRT; /* Initial retransmission time */ + u32_t MRC; /* Maximum retransmission count */ + u32_t MRT; /* Maximum retransmission time */ + u32_t MRD; /* Maximum retransmission duration */ + u32_t duration_start; /* record a state start timestamp */ +#endif /* LWIP_IPV6_DHCP6_STATEFUL */ +}; + +void dhcp6_set_struct(struct netif *netif, struct dhcp6 *dhcp6); +/* Remove a struct dhcp6 previously set to the netif using dhcp6_set_struct() */ +#define dhcp6_remove_struct(netif) netif_set_client_data(netif, LWIP_NETIF_CLIENT_DATA_INDEX_DHCP6, NULL) +void dhcp6_cleanup(struct netif *netif); + +err_t dhcp6_enable_stateful(struct netif *netif); +err_t dhcp6_enable_stateless(struct netif *netif); +void dhcp6_disable(struct netif *netif); +err_t dhcp6_release_stateful(struct netif *netif); + +void dhcp6_tmr(void); + +void dhcp6_nd6_ra_trigger(struct netif *netif, u8_t managed_addr_config, u8_t other_config); + +#if LWIP_IPV6_DHCP6_STATEFUL +void dhcp6_dad_handle(struct netif *netif_p, ip6_addr_t *target_address); +#endif + +#if LWIP_DHCP6_GET_NTP_SRV +/* + * This function must exist, in other to add offered NTP servers to the NTP (or SNTP) engine. + * See LWIP_DHCP6_MAX_NTP_SERVERS + */ +extern void dhcp6_set_ntp_servers(u8_t num_ntp_servers, const ip_addr_t *ntp_server_addrs); +#endif /* LWIP_DHCP6_GET_NTP_SRV */ + +#define netif_dhcp6_data(netif) ((struct dhcp6*)netif_get_client_data(netif, LWIP_NETIF_CLIENT_DATA_INDEX_DHCP6)) + +#if LWIP_LOWPOWER +u32_t dhcp6_tmr_tick(); +#endif + + +#endif /* LWIP_IPV6_DHCP6 */ + +#endif /* LWIP_HDR_IP6_DHCP6_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/dhcps.h b/sdk_liteos/third_party/lwip_sack/include/lwip/dhcps.h new file mode 100644 index 0000000000000000000000000000000000000000..b5060c912d46189a92fb434dd1c52ad7a5dfdf2f --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/dhcps.h @@ -0,0 +1,75 @@ +/* + * Copyright (c) Huawei Technologies Co., Ltd. 2013-2015. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote + * products derived from this software without specific prior + * written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS + * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * Description: implementation for IPv4 DHCP server + * Author: none + * Create: 2013 + */ +#ifndef LWIP_HDR_DHCPS_H +#define LWIP_HDR_DHCPS_H + +#include "lwip/opt.h" +#include "lwip/prot/dhcp.h" +#if LWIP_DHCPS /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/netif.h" +#include "lwip/udp.h" + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + + +#ifndef LWIP_DHCPS_MAX_LEASE +#define LWIP_DHCPS_MAX_LEASE 30 +#endif + +#ifndef LWIP_DHCPS_LEASE_TIME +#define LWIP_DHCPS_LEASE_TIME 7200 +#endif + +/* Offer time in seconds */ +#ifndef LWIP_DHCPS_OFFER_TIME +#define LWIP_DHCPS_OFFER_TIME 300 +#endif + +#ifndef LWIP_DHCPS_DECLINE_TIME +#define LWIP_DHCPS_DECLINE_TIME 500 +#endif + +err_t dhcps_start(struct netif *netif, const char *start_ip, u16_t ip_num); +void dhcps_stop(struct netif *netif); +#if LWIP_NETIFAPI_DHCPS_IP +err_t dhcps_find_client_lease(struct netif *netif, u8_t *mac, u8_t maclen, ip_addr_t *ip); +#endif +void dhcps_client_disconnect(struct netif *netif, const u8_t *mac, u8_t maclen); + +#if defined (__cplusplus) && __cplusplus +} +#endif +#endif /* LWIP_DHCPS */ +#endif /* LWIP_HDR_DHCPS_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/dns.h b/sdk_liteos/third_party/lwip_sack/include/lwip/dns.h new file mode 100644 index 0000000000000000000000000000000000000000..dc3b3c2432841a8ca9ad09ea3821aaf4377867c0 --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/dns.h @@ -0,0 +1,242 @@ +/** + * @file + * DNS API + */ + +/** + * lwip DNS resolver header file. + + * Author: Jim Pettinato + * April 2007 + + * ported from uIP resolv.c Copyright (c) 2002-2003, Adam Dunkels. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote + * products derived from this software without specific prior + * written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS + * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef LWIP_HDR_DNS_H +#define LWIP_HDR_DNS_H + +#include "lwip/opt.h" + +#if LWIP_DNS + +#include "lwip/ip_addr.h" + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +/** DNS timer period */ +#define DNS_TMR_INTERVAL 1000 + +/** @cond liteos */ +/** DNS resolve types: */ +/** LWIP_DNS_ADDRTYPE_DEFAULT can be set to + any one of the following values which describes the default DNS Resolution behaviour */ +/** Try to resolve hostname to an IPv4 address only */ +#define LWIP_DNS_ADDRTYPE_IPV4 0 +/** Try to resolve hostname to an IPv6 address only */ +#define LWIP_DNS_ADDRTYPE_IPV6 1 +/** Try to resolve hostname to an IPv4 address, if some failure happends or no A records recieved, + then try to resolve the hostname to an IPv6 address */ +/** If LWIP_DNS_ADDRTYPE_DEFAULT is not defined, then LWIP_DNS_ADDRTYPE_IPV4_IPV6 will be taken as default */ +#define LWIP_DNS_ADDRTYPE_IPV4_IPV6 2 +/** Try to resolve hostname to an IPv6 address, if some failure happends or no AAAA records recieved, + then try to resolve the hostname to an IPv4 address */ +#define LWIP_DNS_ADDRTYPE_IPV6_IPV4 3 +/** @endcond */ +#if LWIP_IPV4 && LWIP_IPV6 +#ifndef LWIP_DNS_ADDRTYPE_DEFAULT +#define LWIP_DNS_ADDRTYPE_DEFAULT LWIP_DNS_ADDRTYPE_IPV4_IPV6 +#endif +#elif LWIP_IPV4 +#define LWIP_DNS_ADDRTYPE_DEFAULT LWIP_DNS_ADDRTYPE_IPV4 +#else +#define LWIP_DNS_ADDRTYPE_DEFAULT LWIP_DNS_ADDRTYPE_IPV6 +#endif /*LWIP_IPV4 && LWIP_IPV6 */ + +#define REVERSE_PTR_TOP_DOMAIN "arpa" +#if LWIP_IPV4 +#define REVERSE_PTR_V4_DOMAIN "in-addr" +#endif /* LWIP_IPV4 */ +#if LWIP_IPV6 +#define REVERSE_PTR_V6_DOMAIN "ip6" +#endif /* LWIP_IPV6 */ + +#if DNS_LOCAL_HOSTLIST +/** struct used for local host-list */ +struct local_hostlist_entry { + /** static hostname */ + const char *name; + /** static host address in network byteorder */ + ip_addr_t addr; + struct local_hostlist_entry *next; +}; +#define DNS_LOCAL_HOSTLIST_ELEM(name, addr_init) {name, addr_init, NULL} +#if DNS_LOCAL_HOSTLIST_IS_DYNAMIC +#ifndef DNS_LOCAL_HOSTLIST_MAX_NAMELEN +#define DNS_LOCAL_HOSTLIST_MAX_NAMELEN DNS_MAX_NAME_LENGTH +#endif +#define LOCALHOSTLIST_ELEM_SIZE ((sizeof(struct local_hostlist_entry) + DNS_LOCAL_HOSTLIST_MAX_NAMELEN + 1)) +#endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */ +#endif /* DNS_LOCAL_HOSTLIST */ + +#if LWIP_IPV4 +extern const ip_addr_t dns_mquery_v4group; +#endif /* LWIP_IPV4 */ +#if LWIP_IPV6 +extern const ip_addr_t dns_mquery_v6group; +#endif /* LWIP_IPV6 */ + +/** Callback which is invoked when a hostname is found. + * A function of this type must be implemented by the application using the DNS resolver. + * @param name pointer to the name that was looked up. + * @param ipaddr pointer to an ip_addr_t containing the IP address of the hostname, + * or NULL if the name could not be found (or on any other error). + * @param count + * If the addr is not NULL, then count is the count number of resolved IP address for hostname. + * If the addr is NULL, then count is the error code (because h_errno is not implemented yet). + * @param callback_arg a user-specified callback argument passed to dns_gethostbyname. + */ +typedef void (*dns_found_callback)(const char *name, const ip_addr_t *ipaddr, u32_t count, void *callback_arg); + + +/* + * Callback which is invoked when a PTR record for the IP-Address is found. + * A function of this type must be implemented by the application using the DNS resolver. + * @param ipaddr pointer to ip_addr_t containing the IP address whose PTR record was looked up. + * @param name pointer to the name that points to ipaddr. + * or NULL if the name could not be found (or on any other error). + * @param count + * If the name is not NULL, then count is the count number of resolved domain name for IP address. + * If the name is NULL, then count is the error code (because h_errno is not implemented yet). + * @param callback_arg a user-specified callback argument passed to reverse_dns_getnamebyhost + */ +typedef void (*reverse_dns_found_callback)(const char *name, u32_t count, void *callback_arg); + +void dns_init(void); +void dns_tmr(void); +void dns_setserver(u8_t numdns, const ip_addr_t *dnsserver); +const ip_addr_t *dns_getserver(u8_t numdns); +#if LWIP_SNTP || (defined LWIP_TESTBED) +err_t dns_gethostbyname(const char *hostname, ip_addr_t *addr, u32_t *count, + dns_found_callback found, void *callback_arg); +#endif /* LWIP_SNTP || (defined LWIP_TESTBED) */ +err_t dns_gethostbyname_addrtype(const char *hostname, ip_addr_t *addr, u32_t *count, + dns_found_callback found, void *callback_arg, + u8_t dns_addrtype); + +err_t reverse_dns_getnamebyhost(ip_addr_t *ipaddr, char *hostname, reverse_dns_found_callback found, + void *callback_arg); +#if DNS_LOCAL_HOSTLIST +size_t dns_local_iterate(dns_found_callback iterator_fn, void *iterator_arg); +err_t dns_local_lookup(const char *hostname, ip_addr_t *addr, u8_t dns_addrtype); +#if DNS_LOCAL_HOSTLIST_IS_DYNAMIC +int dns_local_removehost(const char *hostname, const ip_addr_t *addr); +err_t dns_local_addhost(const char *hostname, const ip_addr_t *addr); +#endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */ +#endif /* DNS_LOCAL_HOSTLIST */ + +#if LWIP_LOWPOWER +u32_t dns_tmr_tick(void); +#endif + +#if LWIP_ENABLE_BASIC_SHELL_CMD || LWIP_API_RICH +/** @defgroup DNS_Interfaces +* @ingroup User_interfaces +* This section contains the DNS Interfaces. +*/ +/* +Func Name: lwip_dns_setserver +*/ +/** +* @ingroup DNS_Interfaces +* @brief This API is used to set the DNS server IP. +* +* @param[in] numdns Index of the DNS server to set [NA] +* @param[in] dnsserver IP_add of the DNS server to set [NA] +* +* @return +* - ERR_OK: On success +* - ERR_MEM: On failure due to memory +* - ERR_VAL: On failure due to Illegal value +* +* +* @note +* 1. Index of the dns server array should be passed as numdns, it should +* be in the range from 0 to (DNS_MAX_SERVERS-1). If it's not in the range +* then this API fails with return value ERR_VAL.\n +* 2. If NULL is passed to dnsserver, then IPADDR_ANY is updated.\n +* 3. This is a Thread safe API, this needs to be used in application instead +* of dns_setserver.\n +* +* @par Related Topics +* lwip_dns_getserver() +*/ +err_t lwip_dns_setserver(u8_t numdns, ip_addr_t *dnsserver); +/* +Func Name: lwip_dns_getserver +*/ +/** +* @ingroup DNS_Interfaces +* @brief This API is used to obtain the configured DNS server. This API +* Gets the DNS server address on the index numdns and updates dnsserver. +* Application should pass valid pointer of type ip_addr_t as dnsserver. +* +* @param[in] numdns index of the DNS server to set. +* @param[out] dnsserver pointer to IP_add variable. +* +* @par Return values +* - ERR_OK: On success +* - ERR_MEM: On failure due to memory +* - ERR_VAL: On failure due to Illegal value +* +* @note +* 1. Index of the dns server array should be passed as numdns, it should +* be in the range from 0 to (DNS_MAX_SERVERS-1). If it's not in the range +* then it updates dnsserver to be IPADDR_ANY.\n +* 2. If NULL is passed to dnsserver, then this API fails with return value +* ERR_VAL.\n +* 3. This is a Thread safe API, this needs to be used in application instead +* of dns_getserver.\n +* +* @par Related Topics +* lwip_dns_setserver() +*/ +err_t lwip_dns_getserver(u8_t numdns, ip_addr_t *dnsserver); +#endif /* LWIP_ENABLE_BASIC_SHELL_CMD || LWIP_API_RICH */ + +u16_t dns_skip_name(const struct pbuf *p, u16_t query_idx); +u8_t lwip_dns_get_server_cnt(u8_t *ip4cnt, u8_t *ip6cnt); +err_t lwip_dns_copy_ip6server_addr(const struct netif *nif, ip6_addr_t *ipaddr, u8_t num); + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_DNS */ + +#endif /* LWIP_HDR_DNS_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/err.h b/sdk_liteos/third_party/lwip_sack/include/lwip/err.h new file mode 100644 index 0000000000000000000000000000000000000000..3f058320d53423c29b3130ed4a322ee26bb0487a --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/err.h @@ -0,0 +1,181 @@ +/** + * @file + * lwIP Error codes + */ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_ERR_H +#define LWIP_HDR_ERR_H + +#include "lwip/opt.h" +#include "lwip/arch.h" + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +/** + * @defgroup infrastructure_errors Error codes + * @ingroup infrastructure + * @{ + */ + +/** Define LWIP_ERR_T in cc.h if you want to use + * a different type for your platform (must be signed). */ +#ifdef LWIP_ERR_T +typedef LWIP_ERR_T err_t; +#else /* LWIP_ERR_T */ +typedef s32_t err_t; +#endif /* LWIP_ERR_T*/ + +/** @cond liteosdebug +* Definitions for error constants. */ +typedef enum { + /** No error, everything OK. */ + ERR_OK = 0, + /** Out of memory error. */ + ERR_MEM = -1, + /** Buffer error. */ + ERR_BUF = -2, + /** Timeout. */ + ERR_TIMEOUT = -3, + /** Routing problem. */ + ERR_RTE = -4, + /** Operation in progress */ + ERR_INPROGRESS = -5, + /** Illegal value. */ + ERR_VAL = -6, + /** Operation would block. */ + ERR_WOULDBLOCK = -7, + /** Address in use. */ + ERR_USE = -8, + /** Already connecting. */ + ERR_ALREADY = -9, + /** Conn already established. */ + ERR_ISCONN = -10, + /** Not connected. */ + ERR_CONN = -11, + /** Low-level netif error */ + ERR_IF = -12, + /** Message too long. */ + ERR_MSGSIZE = -13, + /** No such device. */ + ERR_NODEV = -14, + /** No such device or address. */ + ERR_NODEVADDR = -15, + /** socket is not connection-mode & no peer address is set */ + ERR_NODEST = -16, + /** Network is down */ + ERR_NETDOWN = -17, + /** Address family not supported by protocol */ + ERR_AFNOSUPP = -18, + /** No such address */ + ERR_NOADDR = -19, + /** Operation not supported on transport endpoint */ + ERR_OPNOTSUPP = -20, + + ERR_NETUNREACH = -21, + + /** connection request timedout */ + ERR_CONNECTIMEOUT = -22, + /** Error pipe */ + ERR_PIPE = -23, + /** AF not supported */ + ERR_AFNOSUPPORT = -24, + /** Protocol not available */ + ERR_NOPROTOOPT = -25, + + ERR_ACCESS = -26, + ERR_NFILE = -27, + ERR_RESERVE3 = -28, + ERR_RESERVE4 = -29, + ERR_RESERVE5 = -30, + ERR_RESERVE6 = -31, + ERR_FATAL_START = -32, + + /** Connection aborted. */ + ERR_ABRT = -33, + /** Connection reset. */ + ERR_RST = -34, + /** Connection closed. */ + ERR_CLSD = -35, + /** Illegal argument. @endcond */ + ERR_ARG = -36, + + ERR_CONNREFUSED = -37, + + /** User can't overwrite the existing neighbor entry */ + ERR_NBR_OVERWRITEFORBIDDEN = -38, + + /** Neighbor information not found */ + ERR_NBR_NOTFOUND = -39, + + /** Default router information not found */ + ERR_DEFAULT_ROUTER_NOTFOUND = -40, + + /** IPv6 Prefix information not found */ + ERR_PREFIX_NOT_FOUND = -41, + + /** No free memory available */ + ERR_NO_FREE_ENTRY = -42, + + /** Default route entry already exists */ + ERR_DEFAULT_ROUTE_EXISTS = -43, + + /** Prefix entry already exists */ + ERR_PREFIX_EXISTS = -44, + + /** 6lowpan context infomation not found */ + ERR_LOWPAN_CTX_NOTFOUND = -45, + + /** Neighbor restriction related error code */ + ERR_NBR_NOMORE_DCHILD = -46, + + ERR_DROP_NEW_NBR = -47, + + ERR_MAX_VAL = -48 +} err_enum_t; + + +#define ERR_IS_FATAL(e) ((e) < ERR_FATAL_START) +#ifdef LWIP_DEBUG +extern const char *lwip_strerr(err_t err); +#else +#define lwip_strerr(x) "" +#endif /* LWIP_DEBUG */ + + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_HDR_ERR_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/errno.h b/sdk_liteos/third_party/lwip_sack/include/lwip/errno.h new file mode 100644 index 0000000000000000000000000000000000000000..71f1886f92f88c4a1a5a808ac79578eb1c9e49b1 --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/errno.h @@ -0,0 +1,197 @@ +/** + * @file + * Posix Errno defines + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_ERRNO_H +#define LWIP_HDR_ERRNO_H + +#include "lwip/opt.h" + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +#ifdef LWIP_PROVIDE_ERRNO + +#define EPERM 1 /* Operation not permitted */ +#define ENOENT 2 /* No such file or directory */ +#define ESRCH 3 /* No such process */ +#define EINTR 4 /* Interrupted system call */ +#define EIO 5 /* I/O error */ +#define ENXIO 6 /* No such device or address */ +#define E2BIG 7 /* Arg list too long */ +#define ENOEXEC 8 /* Exec format error */ +#define EBADF 9 /* Bad file number */ +#define ECHILD 10 /* No child processes */ +#define EAGAIN 11 /* Try again */ +#define ENOMEM 12 /* Out of memory */ +#define EACCES 13 /* Permission denied */ +#define EFAULT 14 /* Bad address */ +#define ENOTBLK 15 /* Block device required */ +#define EBUSY 16 /* Device or resource busy */ +#define EEXIST 17 /* File exists */ +#define EXDEV 18 /* Cross-device link */ +#define ENODEV 19 /* No such device */ +#define ENOTDIR 20 /* Not a directory */ +#define EISDIR 21 /* Is a directory */ +#ifndef EINVAL +#define EINVAL 22 /* Invalid argument */ +#endif +#define ENFILE 23 /* File table overflow */ +#define EMFILE 24 /* Too many open files */ +#define ENOTTY 25 /* Not a typewriter */ +#define ETXTBSY 26 /* Text file busy */ +#define EFBIG 27 /* File too large */ +#define ENOSPC 28 /* No space left on device */ +#define ESPIPE 29 /* Illegal seek */ +#define EROFS 30 /* Read-only file system */ +#define EMLINK 31 /* Too many links */ +#define EPIPE 32 /* Broken pipe */ +#define EDOM 33 /* Math argument out of domain of func */ +#ifndef ERANGE +#define ERANGE 34 /* Math result not representable */ +#endif +#define EDEADLK 35 /* Resource deadlock would occur */ +#define ENAMETOOLONG 36 /* File name too long */ +#define ENOLCK 37 /* No record locks available */ +#define ENOSYS 38 /* Function not implemented */ +#define ENOTEMPTY 39 /* Directory not empty */ +#define ELOOP 40 /* Too many symbolic links encountered */ +#define EWOULDBLOCK EAGAIN /* Operation would block */ +#define ENOMSG 42 /* No message of desired type */ +#define EIDRM 43 /* Identifier removed */ +#define ECHRNG 44 /* Channel number out of range */ +#define EL2NSYNC 45 /* Level 2 not synchronized */ +#define EL3HLT 46 /* Level 3 halted */ +#define EL3RST 47 /* Level 3 reset */ +#define ELNRNG 48 /* Link number out of range */ +#define EUNATCH 49 /* Protocol driver not attached */ +#define ENOCSI 50 /* No CSI structure available */ +#define EL2HLT 51 /* Level 2 halted */ +#define EBADE 52 /* Invalid exchange */ +#define EBADR 53 /* Invalid request descriptor */ +#define EXFULL 54 /* Exchange full */ +#define ENOANO 55 /* No anode */ +#define EBADRQC 56 /* Invalid request code */ +#define EBADSLT 57 /* Invalid slot */ + +#define EDEADLOCK EDEADLK + +#define EBFONT 59 /* Bad font file format */ +#define ENOSTR 60 /* Device not a stream */ +#define ENODATA 61 /* No data available */ +#define ETIME 62 /* Timer expired */ +#define ENOSR 63 /* Out of streams resources */ +#define ENONET 64 /* Machine is not on the network */ +#define ENOPKG 65 /* Package not installed */ +#define EREMOTE 66 /* Object is remote */ +#define ENOLINK 67 /* Link has been severed */ +#define EADV 68 /* Advertise error */ +#define ESRMNT 69 /* Srmount error */ +#define ECOMM 70 /* Communication error on send */ +#define EPROTO 71 /* Protocol error */ +#define EMULTIHOP 72 /* Multihop attempted */ +#define EDOTDOT 73 /* RFS specific error */ +#define EBADMSG 74 /* Not a data message */ +#define EOVERFLOW 75 /* Value too large for defined data type */ +#define ENOTUNIQ 76 /* Name not unique on network */ +#define EBADFD 77 /* File descriptor in bad state */ +#define EREMCHG 78 /* Remote address changed */ +#define ELIBACC 79 /* Can not access a needed shared library */ +#define ELIBBAD 80 /* Accessing a corrupted shared library */ +#define ELIBSCN 81 /* .lib section in a.out corrupted */ +#define ELIBMAX 82 /* Attempting to link in too many shared libraries */ +#define ELIBEXEC 83 /* Cannot exec a shared library directly */ +#define EILSEQ 84 /* Illegal byte sequence */ +#define ERESTART 85 /* Interrupted system call should be restarted */ +#define ESTRPIPE 86 /* Streams pipe error */ +#define EUSERS 87 /* Too many users */ +#define ENOTSOCK 88 /* Socket operation on non-socket */ +#define EDESTADDRREQ 89 /* Destination address required */ +#define EMSGSIZE 90 /* Message too long */ +#define EPROTOTYPE 91 /* Protocol wrong type for socket */ +#define ENOPROTOOPT 92 /* Protocol not available */ +#define EPROTONOSUPPORT 93 /* Protocol not supported */ +#define ESOCKTNOSUPPORT 94 /* Socket type not supported */ +#define EOPNOTSUPP 95 /* Operation not supported on transport endpoint */ +#define EPFNOSUPPORT 96 /* Protocol family not supported */ +#define EAFNOSUPPORT 97 /* Address family not supported by protocol */ +#define EADDRINUSE 98 /* Address already in use */ +#define EADDRNOTAVAIL 99 /* Cannot assign requested address */ +#define ENETDOWN 100 /* Network is down */ +#define ENETUNREACH 101 /* Network is unreachable */ +#define ENETRESET 102 /* Network dropped connection because of reset */ +#define ECONNABORTED 103 /* Software caused connection abort */ +#define ECONNRESET 104 /* Connection reset by peer */ +#define ENOBUFS 105 /* No buffer space available */ +#define EISCONN 106 /* Transport endpoint is already connected */ +#define ENOTCONN 107 /* Transport endpoint is not connected */ +#define ESHUTDOWN 108 /* Cannot send after transport endpoint shutdown */ +#define ETOOMANYREFS 109 /* Too many references: cannot splice */ +#define ETIMEDOUT 110 /* Connection timed out */ +#define ECONNREFUSED 111 /* Connection refused */ +#define EHOSTDOWN 112 /* Host is down */ +#define EHOSTUNREACH 113 /* No route to host */ +#define EALREADY 114 /* Operation already in progress */ +#define EINPROGRESS 115 /* Operation now in progress */ +#define ESTALE 116 /* Stale NFS file handle */ +#define EUCLEAN 117 /* Structure needs cleaning */ +#define ENOTNAM 118 /* Not a XENIX named type file */ +#define ENAVAIL 119 /* No XENIX semaphores available */ +#define EISNAM 120 /* Is a named type file */ +#define EREMOTEIO 121 /* Remote I/O error */ +#define EDQUOT 122 /* Quota exceeded */ + +#define ENOMEDIUM 123 /* No medium found */ +#define EMEDIUMTYPE 124 /* Wrong medium type */ + +#ifndef errno +extern __thread int errno; +#endif + +#else /* LWIP_PROVIDE_ERRNO */ + +/* Define LWIP_ERRNO_INCLUDE to to include the error defines here */ +#ifdef LWIP_ERRNO_INCLUDE +#include LWIP_ERRNO_INCLUDE +#endif /* LWIP_ERRNO_INCLUDE */ + +#endif /* LWIP_PROVIDE_ERRNO */ + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_HDR_ERRNO_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/etharp.h b/sdk_liteos/third_party/lwip_sack/include/lwip/etharp.h new file mode 100644 index 0000000000000000000000000000000000000000..e73c0fb1362e9cc3a83082941fef3836b6459046 --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/etharp.h @@ -0,0 +1,177 @@ +/** + * @file + * Ethernet output function - handles OUTGOING ethernet level traffic, implements + * ARP resolving. + * To be used in most low-level netif implementations + */ + +/* + * Copyright (c) 2001-2003 Swedish Institute of Computer Science. + * Copyright (c) 2003-2004 Leon Woestenberg + * Copyright (c) 2003-2004 Axon Digital Design B.V., The Netherlands. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ + +#ifndef LWIP_HDR_NETIF_ETHARP_H +#define LWIP_HDR_NETIF_ETHARP_H + +#include "lwip/opt.h" + +#if LWIP_ARP || LWIP_ETHERNET /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/pbuf.h" +#include "lwip/ip4_addr.h" +#include "lwip/netif.h" +#include "lwip/ip4.h" +#include "lwip/prot/ethernet.h" + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + + +#if LWIP_IPV4 && LWIP_ARP /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/prot/etharp.h" + +/** 1 seconds period */ +#define ARP_TMR_INTERVAL 1000 + +/* 2 seconds period */ +#define DUP_ARP_DETECT_TIME 2000 + +/* ARP message types (opcodes) */ +#define ARP_REQUEST 1 +#define ARP_REPLY 2 + +/* + * Try hard to create a new entry - we want the IP_add to appear in + * the cache (even if this means removing an active entry or so). + */ +#define ETHARP_FLAG_TRY_HARD 1 +#define ETHARP_FLAG_FIND_ONLY 2 +#if ETHARP_SUPPORT_STATIC_ENTRIES +#define ETHARP_FLAG_STATIC_ENTRY 4 +#endif /* ETHARP_SUPPORT_STATIC_ENTRIES */ + +#define ETHTYPE_ARP 0x0806U +#define ETHTYPE_IP 0x0800U +#define ETHTYPE_VLAN 0x8100U +#define ETHTYPE_ALL 0x0003U /* All packets */ + +#if ARP_QUEUEING +/** struct for queueing outgoing packets for unknown address + * defined here to be accessed by memp.h + */ +struct etharp_q_entry { + struct etharp_q_entry *next; + struct pbuf *p; +}; +#endif /* ARP_QUEUEING */ + +enum etharp_state { + ETHARP_STATE_EMPTY = 0, + ETHARP_STATE_PENDING, + ETHARP_STATE_STABLE, + ETHARP_STATE_STABLE_REREQUESTING_1, + ETHARP_STATE_STABLE_REREQUESTING_2 +#if ETHARP_SUPPORT_STATIC_ENTRIES + , ETHARP_STATE_STATIC +#endif /* ETHARP_SUPPORT_STATIC_ENTRIES */ +}; + +struct etharp_entry { +#if ARP_QUEUEING + /* Pointer to queue of pending outgoing packets on this ARP entry. */ + struct etharp_q_entry *q; +#else /* ARP_QUEUEING */ + /* Pointer to a single pending outgoing packet on this ARP entry. */ + struct pbuf *q; +#endif /* ARP_QUEUEING */ + ip4_addr_t ipaddr; + struct netif *netif; + struct eth_addr ethaddr; + u16_t ctime; + u8_t state; +}; + +#define etharp_init() /* Compatibility define, no init needed. */ +void etharp_tmr(void); +s8_t etharp_find_addr(struct netif *netif, const ip4_addr_t *ipaddr, + struct eth_addr **eth_ret, const ip4_addr_t **ip_ret); +err_t etharp_ip_to_mac(const ip4_addr_t *ipaddr, u8_t *mac, u8_t *maclen); +#if LWIP_API_RICH +u8_t etharp_get_entry(u8_t i, ip4_addr_t **ipaddr, struct netif **netif, struct eth_addr **eth_ret); +#endif /* LWIP_API_RICH */ +err_t etharp_output(struct netif *netif, struct pbuf *q, const ip4_addr_t *ipaddr); +err_t etharp_query(struct netif *netif, const ip4_addr_t *ipaddr, struct pbuf *q); +err_t etharp_request(struct netif *netif, const ip4_addr_t *ipaddr); +err_t etharp_announce(struct netif *netif, const ip4_addr_t *ipaddr); +/** For Ethernet network interfaces, we might want to send "gratuitous ARP"; + * this is an ARP packet sent by a node in order to spontaneously cause other + * nodes to update an entry in their ARP cache. + * From RFC 3220 "IP Mobility Support for IPv4" section 4.6. */ +#if LWIP_ARP_GRATUITOUS_REXMIT +err_t etharp_gratuitous_start(struct netif *netif); +#define etharp_gratuitous(netif) etharp_gratuitous_start(netif) +#define ETHARP_GRATUITOUS_NUM 2 +#else +#define etharp_gratuitous(netif) etharp_request((netif), netif_ip4_addr(netif)) +#endif +void etharp_cleanup_netif(struct netif *netif); + +#if ETHARP_SUPPORT_STATIC_ENTRIES +err_t etharp_add_static_entry(const ip4_addr_t *ipaddr, struct eth_addr *ethaddr); +err_t etharp_remove_static_entry(const ip4_addr_t *ipaddr); +#endif /* ETHARP_SUPPORT_STATIC_ENTRIES */ + +#if ETHARP_TRUST_IP_MAC +void etharp_ip_input(struct netif *netif, struct pbuf *p); +#endif /* ETHARP_TRUST_IP_MAC */ + +#if LWIP_LOWPOWER +u32_t etharp_tmr_tick(void); +#endif /* LWIP_LOWPOWER */ + +err_t etharp_update_arp_entry(struct netif *netif, const ip4_addr_t *ipaddr, struct eth_addr *ethaddr, u8_t flags); +#if LWIP_ENABLE_LOS_SHELL_CMD || (defined LWIP_TESTBED) +err_t etharp_delete_arp_entry(struct netif *netif, ip4_addr_t *ipaddr); +#endif /* LWIP_ENABLE_LOS_SHELL_CMD */ +#endif /* LWIP_IPV4 && LWIP_ARP */ + +void etharp_input(struct pbuf *p, struct netif *netif); + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_ARP || LWIP_ETHERNET */ + +#endif /* LWIP_HDR_NETIF_ETHARP_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/ethip6.h b/sdk_liteos/third_party/lwip_sack/include/lwip/ethip6.h new file mode 100644 index 0000000000000000000000000000000000000000..23b130c04fc62eed10ec2ca8067833a55d41652c --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/ethip6.h @@ -0,0 +1,66 @@ +/** + * @file + * + * Ethernet output for IPv6. Uses ND tables for link-layer addressing. + */ + +/* + * Copyright (c) 2010 Inico Technologies Ltd. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Ivan Delamer + * + * + * Please coordinate changes and requests with Ivan Delamer + * + */ + +#ifndef LWIP_HDR_ETHIP6_H +#define LWIP_HDR_ETHIP6_H + +#include "lwip/opt.h" + +#if LWIP_IPV6 && LWIP_ETHERNET /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/pbuf.h" +#include "lwip/ip6.h" +#include "lwip/ip6_addr.h" +#include "lwip/netif.h" + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +err_t ethip6_output(struct netif *netif, struct pbuf *q, const ip6_addr_t *ip6addr); + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_IPV6 && LWIP_ETHERNET */ + +#endif /* LWIP_HDR_ETHIP6_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/ethtool.h b/sdk_liteos/third_party/lwip_sack/include/lwip/ethtool.h new file mode 100644 index 0000000000000000000000000000000000000000..7bb6a78e8513a687e53f03b4e4a80bf3329b452b --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/ethtool.h @@ -0,0 +1,135 @@ +/* + * Copyright (c) Huawei Technologies Co., Ltd. 2013-2015. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote + * products derived from this software without specific prior + * written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS + * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * Description: This file provides information for ethtool. reference to linux kernel :include/uapi/linux/ethtool.h + * Author: none + * Create: 2013 + */ + +#ifndef __ETHTOOL_H +#define __ETHTOOL_H + +#include "lwip/opt.h" + +#if LWIP_NETIF_ETHTOOL /* don't build if not configured for use in lwipopts.h */ +#include "lwip/netif.h" +#include "lwip/sockets.h" +#include "arch/cc.h" +#include "netif/ifaddrs.h" +#if LWIP_LITEOS_COMPAT && !LWIP_LINUX_COMPAT +#include +#endif + +#if LWIP_LITEOS_COMPAT && LWIP_LINUX_COMPAT +#include +#endif + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +#if !LWIP_LITEOS_COMPAT +#define ETHTOOL_GSET 0x00000001 +#define ETHTOOL_SSET 0x00000002 +#define ETHTOOL_GLINK 0x0000000a + +/** @brief This struct is to pass data for link control and status */ +struct ethtool_cmd { + u32_t cmd; /**< Command number = %ETHTOOL_GSET or %ETHTOOL_SSET */ + u32_t supported; /**< Bitmask of %SUPPORTED_* flags for the link modes, physical connectors and other link + features for which the interface supports autonegotiation or auto-detection. Read-only. */ + u32_t advertising; /**< Bitmask of %ADVERTISED_* flags for the link modes, physical connectors and other link + features that are advertised through autonegotiation or enabled for auto-detection. */ + u16_t speed; /**< Low bits of the speed, 1Mb units, 0 to INT_MAX or SPEED_UNKNOWN */ + u8_t duplex; /**< Duplex mode; one of %DUPLEX_* */ + u8_t port; /**< Physical connector type; one of %PORT_* */ + u8_t phy_address; /**< MDIO address of PHY (transceiver); 0 or 255 if not applicable. */ + u8_t transceiver; /**< Historically used to distinguish different possible PHY types, but not in a consistent + way. Deprecated. */ + u8_t autoneg; /**< Enable/disable autonegotiation and auto-detection; either %AUTONEG_DISABLE or + %AUTONEG_ENABLE */ + u8_t mdio_support; /**< Bitmask of %ETH_MDIO_SUPPORTS_* flags for the MDIO protocols supported by the interface; + 0 if unknown. Read-only. */ + u32_t maxtxpkt; /**< Historically used to report TX IRQ coalescing; Read-only; deprecated. */ + u32_t maxrxpkt; /**< Historically used to report RX IRQ coalescing; Read-only; deprecated. */ + u16_t speed_hi; /**< High bits of the speed, 1Mb units, 0 to INT_MAX or SPEED_UNKNOWN */ + u8_t eth_tp_mdix; /**< Ethernet twisted-pair MDI(-X) status; one of %ETH_TP_MDI_*. If the status is unknown or + not applicable, the value will be %ETH_TP_MDI_INVALID. Read-only. */ + u8_t eth_tp_mdix_ctrl; /**< Ethernet twisted pair MDI(-X) control; one of %ETH_TP_MDI_*. If MDI(-X) control is not + implemented, reads yield %ETH_TP_MDI_INVALID and writes may be ignored or rejected. When written successfully, the + link should be renegotiated if necessary. */ + u32_t lp_advertising; /**< Bitmask of %ADVERTISED_* flags for the link modes and other link features that the link + partner advertised through autonegotiation; 0 if unknown or not applicable. Read-only. */ + u32_t reserved[2]; +}; + +/** @brief This structure is for passing single values. */ +struct ethtool_value { + u32_t cmd; /**< Indicates command. */ + u32_t data; /**< Indicates data. */ +}; +#endif + +/** + * @brief Provides optional netdev operations. + * + * All operations are optional (that is, the function pointer may be set + * to %NULL) and callers must take this into account. Callers must + * hold the RTNL lock. + * + * See the structures used by these operations for further documentation. + * + * See &struct net_device and &struct net_device_ops for documentation + * of the generic netdev features interface. + */ +struct ethtool_ops { + /** + * < Reports whether physical link is up. Will only be called if the netdev is up. + * Should usually be set to ethtool_op_get_link(), which usesnetif_carrier_ok(). + */ + s32_t (*get_link)(struct netif *netif); + s32_t (*get_settings)(struct netif *netif, struct ethtool_cmd *cmd); /**< Gets the current settings */ + s32_t (*set_settings)(struct netif *netif, struct ethtool_cmd *cmd); /**< Configures settings */ + /**< Function to be called before any other operation. Returns a negative error code or zero. */ + int (*begin)(struct netif *netif); + /** + * < Function to be called after any other operation except @begin. + * Will be called even if the other operation failed. + */ + void (*complete)(struct netif *netif); +}; + +s32_t dev_ethtool(struct netif *netif, struct ifreq *ifr); +/* [VPPTECH-449] TCP_INFO support */ +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_NETIF_ETHTOOL */ + +#endif /* __ETHTOOL_H */ + diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/filter.h b/sdk_liteos/third_party/lwip_sack/include/lwip/filter.h new file mode 100644 index 0000000000000000000000000000000000000000..920cbe9af24a9628fc0bef606b22665290b7bcec --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/filter.h @@ -0,0 +1,136 @@ +/* + * Copyright (c) Huawei Technologies Co., Ltd. 2013-2019. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote + * products derived from this software without specific prior + * written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS + * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * Description: declaration for socket filter + * Author: none + * Create: 2013 + */ + +#ifndef __LWIP_FILTER_H__ +#define __LWIP_FILTER_H__ + +#include "lwip/opt.h" + +#if LWIP_SOCK_FILTER + +#include "lwip/pbuf.h" +#include "lwip/mem.h" + +#ifdef __cplusplus +extern "C" { +#endif /*__cplusplus */ + +/* @brief Defines codes of socket filter. */ +struct sock_filter { + u16_t code; /* compiler code */ + u8_t jt; /* jump if true */ + u8_t jf; /* jump if false */ + u32_t k; /* misc field */ +}; + +/* @brief Defines value types of SO_ATTACH_FILTER for setsockopt. */ +struct sock_fprog { + u16_t len; /* the length of the filter array */ + struct sock_filter *filter; /* pointer of socket filter codes */ +}; + +#define LSF_CLASS(code) ((code) & 0x07) +#define LSF_LD 0x00 +#define LSF_LDX 0x01 +#define LSF_ST 0x02 +#define LSF_STX 0x03 +#define LSF_ALU 0x04 +#define LSF_JMP 0x05 +#define LSF_RET 0x06 +#define LSF_MISC 0x07 + +/* ld/ldx */ +#define LSF_SIZE(code) ((code) & 0x18) +#define LSF_W 0x00 +#define LSF_H 0x08 +#define LSF_B 0x10 +#define LSF_MODE(code) ((code) & 0xe0) +#define LSF_IMM 0x00 +#define LSF_ABS 0x20 +#define LSF_IND 0x40 +#define LSF_MEM 0x60 +#define LSF_LEN 0x80 +#define LSF_MSH 0xa0 /* unsupported */ + +/* alu/jmp */ +#define LSF_OP(code) ((code) & 0xf0) +#define LSF_ADD 0x00 +#define LSF_SUB 0x10 +#define LSF_MUL 0x20 +#define LSF_DIV 0x30 +#define LSF_OR 0x40 +#define LSF_AND 0x50 +#define LSF_LSH 0x60 +#define LSF_RSH 0x70 +#define LSF_NEG 0x80 +#define LSF_JA 0x00 +#define LSF_JEQ 0x10 +#define LSF_JGT 0x20 +#define LSF_JGE 0x30 +#define LSF_JSET 0x40 +#define LSF_SRC(code) ((code) & 0x08) +#define LSF_K 0x00 +#define LSF_X 0x08 + +/* ret - LSF_K and LSF_X also apply */ +#define LSF_RVAL(code) ((code) & 0x18) +#define LSF_A 0x10 + +/* misc */ +#define LSF_MISCOP(code) ((code) & 0xf8) +#define LSF_TAX 0x00 +#define LSF_TXA 0x80 + +#ifndef LSF_MAXINSNS +#define LSF_MAXINSNS 128 +#endif + + +/* + * Number of scratch memory words for: LSF_ST and LSF_STX + */ +#define LSF_MEMWORDS 16 + +struct netconn; +s32_t sock_filter(struct netconn *conn, struct pbuf *pbuf); +u32_t sock_run_filter(struct pbuf *pbuf, struct sock_filter *filter, u16_t flen); +s32_t sock_attach_filter(struct sock_fprog *fprog, struct netconn *conn); +s32_t sock_detach_filter(struct netconn *conn); +s32_t sock_check_filter(struct sock_filter *filter, int len); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* LWIP_SOCK_FILTER */ +#endif /* __LWIP_FILTER_H__ */ + diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/icmp.h b/sdk_liteos/third_party/lwip_sack/include/lwip/icmp.h new file mode 100644 index 0000000000000000000000000000000000000000..d3f7f6eee3a077792d1c0c19f569044a9c87ee34 --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/icmp.h @@ -0,0 +1,110 @@ +/** + * @file + * ICMP API + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_ICMP_H +#define LWIP_HDR_ICMP_H + +#include "lwip/opt.h" +#include "lwip/pbuf.h" +#include "lwip/ip_addr.h" +#include "lwip/netif.h" +#include "lwip/prot/icmp.h" + +#if LWIP_IPV6 && LWIP_ICMP6 +#include "lwip/icmp6.h" +#endif + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +/* ICMP destination unreachable codes */ +enum icmp_dur_type { + /* net unreachable */ + ICMP_DUR_NET = 0, + /* host unreachable */ + ICMP_DUR_HOST = 1, + /* protocol unreachable */ + ICMP_DUR_PROTO = 2, + /* port unreachable */ + ICMP_DUR_PORT = 3, + /* fragmentation needed and DF set */ + ICMP_DUR_FRAG = 4, + /* source route failed */ + ICMP_DUR_SR = 5 +}; + +/* ICMP time exceeded codes */ +enum icmp_te_type { + /* time to live exceeded in transit */ + ICMP_TE_TTL = 0, + /* fragment reassembly time exceeded */ + ICMP_TE_FRAG = 1 +}; + +#if LWIP_IPV4 && LWIP_ICMP /* don't build if not configured for use in lwipopts.h */ + +void icmp_input(struct pbuf *p, struct netif *inp); +void icmp_dest_unreach(struct pbuf *p, enum icmp_dur_type t); +void icmp_time_exceeded(struct pbuf *p, enum icmp_te_type t); + +#endif /* LWIP_IPV4 && LWIP_ICMP */ + +#if LWIP_IPV4 && LWIP_IPV6 +#if LWIP_ICMP && LWIP_ICMP6 +#define icmp_port_unreach(isipv6, pbuf) ((isipv6) ? \ + icmp6_dest_unreach(pbuf, ICMP6_DUR_PORT) : \ + icmp_dest_unreach(pbuf, ICMP_DUR_PORT)) +#elif LWIP_ICMP +#define icmp_port_unreach(isipv6, pbuf) do { if (!(isipv6)) { icmp_dest_unreach(pbuf, ICMP_DUR_PORT); } }while (0) +#elif LWIP_ICMP6 +#define icmp_port_unreach(isipv6, pbuf) do { if (isipv6) { icmp6_dest_unreach(pbuf, ICMP6_DUR_PORT); } }while (0) +#else +#define icmp_port_unreach(isipv6, pbuf) +#endif +#elif LWIP_IPV6 && LWIP_ICMP6 +#define icmp_port_unreach(isipv6, pbuf) icmp6_dest_unreach(pbuf, ICMP6_DUR_PORT) +#elif LWIP_IPV4 && LWIP_ICMP +#define icmp_port_unreach(isipv6, pbuf) icmp_dest_unreach(pbuf, ICMP_DUR_PORT) +#else /* (LWIP_IPV6 && LWIP_ICMP6) || (LWIP_IPV4 && LWIP_ICMP) */ +#define icmp_port_unreach(isipv6, pbuf) +#endif /* (LWIP_IPV6 && LWIP_ICMP6) || (LWIP_IPV4 && LWIP_ICMP) LWIP_IPV4 */ + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_HDR_ICMP_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/icmp6.h b/sdk_liteos/third_party/lwip_sack/include/lwip/icmp6.h new file mode 100644 index 0000000000000000000000000000000000000000..ede1d9d7a19e86d67d21a3e407401be86f741aec --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/icmp6.h @@ -0,0 +1,234 @@ +/** + * @file + * + * IPv6 version of ICMP, as per RFC 4443. + */ + +/* + * Copyright (c) 2010 Inico Technologies Ltd. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Ivan Delamer + * + * + * Please coordinate changes and requests with Ivan Delamer + * + + * compliance: + * rfc:2292 + * Section: 3.1 Checksum + * Section: 3.2 ICMPv6 Type Filtering + * Each ICMPv6 raw socket has an associated filter whose datatype is + * defined as + * struct icmp6_filter; + * This structure, along with the macros and constants defined later in + * this section, are defined as a result of including the + * header. + * + * The current filter is fetched and stored using getsockopt() and + * setsockopt() with a level of IPPROTO_ICMPV6 and an option name of + * ICMP6_FILTER. + * Six macros operate on an icmp6_filter structure: + * void ICMP6_FILTER_SETPASSALL(struct icmp6_filter *); + * void ICMP6_FILTER_SETBLOCKALL(struct icmp6_filter *); + * + * void ICMP6_FILTER_SETPASS( int, struct icmp6_filter *); + * void ICMP6_FILTER_SETBLOCK( int, struct icmp6_filter *); + * + * int ICMP6_FILTER_WILLPASS(int, const struct icmp6_filter *); + * int ICMP6_FILTER_WILLBLOCK(int, const struct icmp6_filter *); + * + * The first argument to the last four macros (an integer) is an ICMPv6 + * message type, between 0 and 255. The pointer argument to all six + * macros is a pointer to a filter that is modified by the first four + * macros examined by the last two macros. + * + * The first two macros, SETPASSALL and SETBLOCKALL, let us specify that + * all ICMPv6 messages are passed to the application or that all ICMPv6 + * messages are blocked from being passed to the application. + * + * The next two macros, SETPASS and SETBLOCK, let us specify that + * messages of a given ICMPv6 type should be passed to the application + * or not passed to the application (blocked). + * + * The final two macros, WILLPASS and WILLBLOCK, return true or false + * depending whether the specified message type is passed to the + * application or blocked from being passed to the application by the + * filter pointed to by the second argument. + * + * Limitation: IPV6_CHECKSUM Offset need to be set by application based on the + * socket and messages they are passing. + * Checksum option need to be used for the messages of type UDP, TCP and ICMP. + */ + + +#ifndef LWIP_HDR_ICMP6_H +#define LWIP_HDR_ICMP6_H + +#include "lwip/opt.h" +#include "lwip/pbuf.h" +#include "lwip/ip6_addr.h" +#include "lwip/netif.h" +#include "lwip/prot/icmp6.h" + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + + +#if LWIP_ICMP6 && LWIP_IPV6 /* don't build if not configured for use in lwipopts.h */ + + +#if LWIP_ICMP6_ERR_RT_LMT + +/* struct for queueing icmp6 error packet */ +struct icmp6_err_bkt { + u32_t icmp_bkt[ICMP6_ERR_BKT_SIZE]; + u32_t avg; + u16_t bkt_index; + u16_t spare; +}; + +extern struct icmp6_err_bkt icmp6_err_bkt; + +u8_t icmp6_err_update_rate_lmt(void); +void icmp6_err_rate_calc(void); + +#endif + +void icmp6_input(struct pbuf *p, struct netif *inp); +void icmp6_dest_unreach(struct pbuf *p, enum icmp6_dur_code c); +void icmp6_packet_too_big(struct pbuf *p, u32_t mtu); +void icmp6_time_exceeded(struct pbuf *p, enum icmp6_te_code c); +void icmp6_time_exceeded_with_addrs(struct pbuf *p, enum icmp6_te_code c, + const ip6_addr_t *src_addr, const ip6_addr_t *dest_addr); +void icmp6_param_problem(struct pbuf *p, enum icmp6_pp_code c, u32_t pointer); + +#endif /* LWIP_ICMP6 && LWIP_IPV6 */ + +#if LWIP_IPV6 && LWIP_RAW + +/* raw socket checksum offset for ICMPV6 */ +#define IPV6_ICMP_CHKSUM_OFFSET 2 + +/* raw socket checksum offset for UDP */ +#define IPV6_UDP_CHKSUM_OFFSET 6 + +/* raw socket checksum offset for TCP */ +#define IPV6_TCP_CHKSUM_OFFSET 16 + +/* checksum length */ +#define LWIP_IPV6_CHKSUM_LEN 2 + +/* + * ICMP6 structure filter length + */ +#define ICMP_FILTER_LENGTH 8 /* ICMP6 structure filter length */ + +/* icmp6 const filter value */ +#define ICMP6_FILTER_VAL 5 + +/* icmp6 const filter integer bits */ +#define ICMP6_FILTER_INTVAL 31 + +/* icmp6 max value filter value */ +#define ICMP6_FILTER_MAXVAL 0xFF + + +#if !LWIP_LITEOS_COMPAT +/* + * socket option for ICMP6 filering support + */ +#define ICMP6_FILTER 1 /* ICMP filter support */ + + +/* + * stucture to hold the sockets filter state to allow packets to application or not. + * Max size of structure is 256 bits. + */ +struct icmp6_filter { + u32_t icmp6_filt[ICMP_FILTER_LENGTH]; /* 8*32 = 256 bits */ +}; + +/* + * filter macro to check if the raw socket is blocked or not. + */ +#define ICMP6_FILTER_WILLPASS(type, filterp) \ + ((((filterp)->icmp6_filt[(type) >> ICMP6_FILTER_VAL]) & (1U << ((type) & ICMP6_FILTER_INTVAL))) == 0) + + +/* + * filter macro to check if the raw socket to blocked + */ +#define ICMP6_FILTER_WILLBLOCK(type, filterp) \ + ((((filterp)->icmp6_filt[(type) >> ICMP6_FILTER_VAL]) & (1U << ((type) & ICMP6_FILTER_INTVAL))) != 0) + +/* + * filter macro to allow raw socket for giving the data to application + */ +#define ICMP6_FILTER_SETPASS(type, filterp) \ + (((filterp)->icmp6_filt[(type) >> (ICMP6_FILTER_VAL)]) &= (~(u32_t)(1U << ((type) & ICMP6_FILTER_INTVAL)))) + + +/* + * filter macro to block raw socket from giving the data to application + */ +#define ICMP6_FILTER_SETBLOCK(type, filterp) \ + (((filterp)->icmp6_filt[(type) >> ICMP6_FILTER_VAL]) |= (1U << ((type) & ICMP6_FILTER_INTVAL))) + +/* + * filter macro to allow all raw socket to give the data to application + */ +#define ICMP6_FILTER_SETPASSALL(filterp) \ + (void)memset((filterp), 0x00, sizeof(struct icmp6_filter)) + +/* + * filter macro to block all raw socket from giving the data to application + */ +#define ICMP6_FILTER_SETBLOCKALL(filterp) \ + (void)memset((filterp), ICMP6_FILTER_MAXVAL, sizeof(struct icmp6_filter)) + +#endif + +#endif + +#if LWIP_IPV6 && (LWIP_RPL || LWIP_RIPPLE) +void lwip_handle_rpl_ctrl_msg +( + const struct icmpv6_hdr *icmp_hdr, + struct pbuf *buf, + const ip6_addr_t *srcip, + const ip6_addr_t *dstip, + struct netif *intf +); +#endif + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_HDR_ICMP6_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/ieee802154ip6.h b/sdk_liteos/third_party/lwip_sack/include/lwip/ieee802154ip6.h new file mode 100644 index 0000000000000000000000000000000000000000..849a8d4aad5e5568cab440ec0b43af380f50cbaa --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/ieee802154ip6.h @@ -0,0 +1,59 @@ +/* + * Copyright (c) Huawei Technologies Co., Ltd. 2012-2020. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote + * products derived from this software without specific prior + * written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS + * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef LWIP_HDR_IEEE802154SIP6_H +#define LWIP_HDR_IEEE802154SIP6_H + +#include "lwip/opt.h" + +#if LWIP_IPV6 && LWIP_IEEE802154 /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/pbuf.h" +#include "lwip/ip6.h" +#include "lwip/ip6_addr.h" +#include "lwip/netif.h" + +#ifdef __cplusplus +extern "C" { +#endif + +err_t output_ip6_onieee802154(struct netif *netif, struct pbuf *p, + const ip6_addr_t *ipaddr); + +void ieee802154_packet_sent_ack_callback(unsigned char *p_dest_addr, + unsigned int u32_addr_mode, + int status, + unsigned int numtx); +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_IPV6 && LWIP_ETHERNET */ + +#endif /* LWIP_HDR_IEEE802154SIP6_H */ + diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/if_api.h b/sdk_liteos/third_party/lwip_sack/include/lwip/if_api.h new file mode 100644 index 0000000000000000000000000000000000000000..bd8416dc44972f5a93c831d63b949c2045cb868c --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/if_api.h @@ -0,0 +1,202 @@ +/* + * Description: This file contains the implementation for RFC 2553/3493 section Section 4: Interface Identification + */ +/* + * This file contains the implementation for RFC 2553/3493 section Section 4: Interface Identification + * The following functions are implemented + * lwip_if_indextoname + * lwip_if_nametoindex + * lwip_if_nameindex + * lwip_if_freenameindex + * @note: when passing the ifname pointer to the function lwip_if_indextoname: + * The ifname argument must point to a buffer of at least IF_NAMESIZE bytes into which the interface + * name corresponding to the specified + * index is returned. + * IF_NAMESIZE is same as IFNAMSIZ and is of 16 bytes including null + * + */ + +#ifndef LWIP_HDR_IF_H +#define LWIP_HDR_IF_H + +#include "lwip/opt.h" + +#if LWIP_SOCKET /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/netif.h" + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +#if !LWIP_LITEOS_COMPAT + +/* Keep the size same as general interface length */ +#define IF_NAMESIZE IFNAMSIZ + +/** + * Structure to store the if_index and if_name for each interface. + */ +struct if_nameindex { + unsigned int if_index; /* 1, 2, ... */ + char *if_name; /* null terminated name: "eth0", ... */ +}; + +#endif /* !LWIP_LITEOS_COMPAT */ + +#ifdef LWIP_COMPAT_SOCKETS +#if LWIP_COMPAT_SOCKETS != 2 +/* + * Func Name: lwip_if_indextoname + */ +/** + * @ingroup Socket_Interfaces + * @brief + * This function maps an interface index into its corresponding name. + * The ifname argument must point to a buffer of at least IF_NAMESIZE/IFNAMSIZ bytes into which the interface + * name corresponding to the specified index is returned. + * (IF_NAMESIZE is also defined in and its value includes a terminating null byte at the end of the + * interface name.) This pointer is also the return value of the function. + * @param[in] unsigned int ifindex Specifies an interface index for which the name is to be retrieved. + * @param[out] char* ifname Specifies the output interface name which is retrieved based on ifindex + * + * @return + * char * ifname: On success \n + * NULL : On failure. The errno is set to indicate the error. \n + * @par Errors + * @li The if_indextoname() function fails in the following conditions: + * - [ENXIO] : \n The ifindex is more than the max range /There is no name as per the index specified + * - [EFAULT] : \n The ifname is a null pointer + * @par POSIX Conformance: + * Implementation deviates from RFC 3493, POSIX.1-2001.The following are the exceptions to conformance: + * Posix expects errno for scenario If there was a system error (such as running out of memory), if_indextoname + * returns NULL and errno would be set to the proper value (e.g., ENOMEM). + * Stack do not allocate memory in this function, so ENOMEM is not returned + * @note + * The caller of this function should ensure that the ifname point to a buffer of at least IF_NAMESIZE/IFNAMSIZ bytes. + * If there is no interface corresponding to the specified index, NULL is returned, and errno is set to ENXIO. + * Stack only supports ifindex to be max 255 and the index should start from 1 to get a valid name. + * @par Related Topics + * if_nametoindex() + * if_freenameindex() + * if_nameindex() + */ +char *lwip_if_indextoname(unsigned int ifindex, char *ifname); + +/* + * Func Name: lwip_if_nametoindex + */ +/** + * @ingroup Socket_Interfaces + * @brief + * This function maps an interface name into its corresponding index. + * The ifname argument must point to a buffer of at least IF_NAMESIZE/IFNAMSIZ bytes which will contain the + * interface name. + * @param[in] const char *ifname Specifies the interface name for which corresponding interface + * index is required. + * @return + * unsigned int ifindex: On success.The interface index for the interface name mentioned in ifname \n + * 0 : On failure. The errno is set to indicate the error. \n + * @par Errors + * @li The lwip_if_nametoindex() function fails in the following conditions: + * - [ENODEV] : \n Could not find the index corresponding to the interface name + * - [EFAULT] : \n The ifname is a null pointer. + * @par POSIX Conformance: + * Implementation deviates from RFC 3493, POSIX.1-2001.The following are the exceptions to conformance: + * POSIX expects errno for scenario If there was a system error (such as running out of memory), + * if_nametoindex returns 0 and errno would be set to the proper value (e.g., ENOMEM). + * Stack does not allocate memory in this function, so ENOMEM is not returned. + * @note + * The caller of this function should ensure that the ifname point to a buffer of at least + * IF_NAMESIZE/IFNAMSIZ bytes. If there is no interface index corresponding to the specified name, + * 0 is returned, and errno is set to ENODEV. + * 0 is an invalid index. + * @par Related Topics + * if_indextoname() + * if_freenameindex() + * if_nameindex() + */ +unsigned int lwip_if_nametoindex(const char *ifname); + +/* + * Func Name: lwip_if_nameindex + */ +/** + * @ingroup Socket_Interfaces + * @brief + * This function returns an array of if_nameindex structures, one structure per interface. + * The if_nameindex structure holds the information about a single interface and is defined as a result of + * including the header. + * The end of the array of structures is indicated by a structure with an if_index of 0 and an if_name of NULL. + * The function returns a NULL pointer upon an error, and would set errno to the appropriate value. + * The memory used for this array of structures along with the interface names pointed to by the if_name members + * is obtained dynamically. + * @param[in] void The function does not take any input instead returns all the interfaces in format + * if_nameindex structures. + * + * @return + * struct if_nameindex * : On success. The function returns an array of if_nameindex structures, one structure + * per interface. \n + * NULL : On failure. The errno is set to indicate the error. \n + * @par Errors + * @li The if_nameindex() function fails in the following conditions: + * - [ENOBUFS] : \n Insufficient resources available. For this, the function returns NULL. + * @par POSIX Conformance: + * Implementation conforms to POSIX.1-2001, POSIX.1-2008, RFC 3493. + * @note + * The end of the array of structures is indicated by a structure with an if_index of 0 and an if_name of NULL. + * The function returns a NULL pointer upon an error, and would set errno to the appropriate value. + * @par Related Topics + * if_indextoname() + * if_nametoindex() + * if_freenameindex() + */ +struct if_nameindex *lwip_if_nameindex(void); + +/* + * Func Name: lwip_if_freenameindex + */ +/** + * @ingroup Socket_Interfaces + * @brief + * This function frees the dynamic memory that was allocated by if_nameindex(). + * The argument to this function must be a pointer that was returned by if_nameindex(). + * @param[in] struct if_nameindex *ptr The argument to this function must be a pointer that was returned by + * lwip_if_nameindex() + * + * @return + * void : On success.\n + * void : On failure. The errno is not set \n + * @par POSIX Conformance: + * Implementation conforms to POSIX.1-2001, POSIX.1-2008, RFC 3493. + * @par Related Topics + * if_indextoname() + * if_nametoindex() + * if_nameindex() + */ +void lwip_if_freenameindex(struct if_nameindex *ptr); + +/* @ingroup socket */ +#define if_indextoname(ifindex, ifname) lwip_if_indextoname(ifindex, ifname) +/* @ingroup socket */ +#define if_nametoindex(ifname) lwip_if_nametoindex(ifname) +#define if_nameindex(void) lwip_if_nameindex(void) +#define if_freenameindex(ptr) lwip_if_freenameindex(ptr) +#else +/* @ingroup socket */ +#define lwip_if_indextoname(ifindex, ifname) if_indextoname(ifindex, ifname) +/* @ingroup socket */ +#define lwip_if_nametoindex(ifname) if_nametoindex(ifname) +#define lwip_if_nameindex(void) if_nameindex(void) +#define lwip_if_freenameindex(ptr) if_freenameindex(ptr) +#endif /* LWIP_COMPAT_SOCKETS == 2 */ +#endif /* LWIP_COMPAT_SOCKETS */ + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_SOCKET */ + +#endif /* !LWIP_HDR_IF_H */ + diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/igmp.h b/sdk_liteos/third_party/lwip_sack/include/lwip/igmp.h new file mode 100644 index 0000000000000000000000000000000000000000..2d0a17366794eb5709900881ed2a28872fd913dd --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/igmp.h @@ -0,0 +1,231 @@ +/** + * @file + * IGMP API + */ + +/* + * Copyright (c) 2002 CITEL Technologies Ltd. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of CITEL Technologies Ltd nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY CITEL TECHNOLOGIES AND CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL CITEL TECHNOLOGIES OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * This file is a contribution to the lwIP TCP/IP stack. + * The Swedish Institute of Computer Science and Adam Dunkels + * are specifically granted permission to redistribute this + * source code. +*/ + +#ifndef LWIP_HDR_IGMP_H +#define LWIP_HDR_IGMP_H + +#include "lwip/opt.h" +#include "lwip/ip_addr.h" +#include "lwip/netif.h" +#include "lwip/pbuf.h" + +#if LWIP_IPV4 && LWIP_IGMP /* don't build if not configured for use in lwipopts.h */ + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +/* IGMP timer */ +#define IGMP_TMR_INTERVAL 100 /* Milliseconds */ +#define IGMP_V1_DELAYING_MEMBER_TMR (1000 / (IGMP_TMR_INTERVAL)) +#define IGMP_JOIN_DELAYING_MEMBER_TMR (500 / (IGMP_TMR_INTERVAL)) + +/* Compatibility defines (don't use for new code) */ +#define IGMP_DEL_MAC_FILTER NETIF_DEL_MAC_FILTER +#define IGMP_ADD_MAC_FILTER NETIF_ADD_MAC_FILTER + +/* + * igmp group structure - there is + * a list of groups for each interface + * these should really be linked from the interface, but + * if we keep them separate we will not affect the lwip original code + * too much + * + * There will be a group for the all systems group address but this + * will not run the state machine as it is used to kick off reports + * from all the other groups + */ +struct igmp_group { + /* next link */ + struct igmp_group *next; + /* multicast address */ + ip4_addr_t group_address; + /* signifies we were the last person to report */ + u8_t last_reporter_flag; + /* current state of the group */ + u8_t group_state; + /* timer for reporting, negative is OFF */ + u16_t timer; + /* counter of simultaneous uses */ + u8_t use; +#if (LWIP_IGMP_REPORT_TIMES > 2) +#if (LWIP_IGMP_REPORT_TIMES > 10) +#error "invalid LWIP_IGMP_REPORT_TIMES" +#endif + u8_t report_timer; + u8_t report_cnt; +#endif +}; + +/* Prototypes */ +/* + * @ingroup igmp + * Initialize the IGMP module + */ +void igmp_init(void); + +/* + * @ingroup igmp + * Start IGMP processing on interface + * + * @param netif network interface on which start IGMP processing + * @return ERR_OK if IGMP was started on the netif(s), an err_t otherwise + * + * Note: This is an internal function. + */ +err_t igmp_start(struct netif *netif); + +/* + * @ingroup igmp + * Stop IGMP processing on interface + * + * @param netif network interface on which stop IGMP processing + * @return ERR_OK if IGMP was stopped on the netif(s), an err_t otherwise + * + * Note: This is an internal function. + */ +err_t igmp_stop(struct netif *netif); + +/* + * @ingroup igmp + * Report IGMP memberships for this interface + * + * @param netif network interface on which report IGMP memberships + * + * Note: This is an internal function. + */ +void igmp_report_groups(struct netif *netif); + +/* + * @ingroup igmp + * Search for a group in the global igmp_group_list + * + * @param ifp the network interface for which to look + * @param addr the group ip address to search for + * @return a struct igmp_group* if the group has been found, + * NULL if the group wasn't found. + * + * Note: This is an internal function. + */ +struct igmp_group *igmp_lookfor_group(struct netif *ifp, const ip4_addr_t *addr); + +/* + * @ingroup igmp + * Called from ip_input() if a new IGMP packet is received. + * + * @param p received igmp packet, p->payload pointing to the igmp header + * @param inp network interface on which the packet was received + * @param dest destination ip address of the igmp packet + */ +void igmp_input(struct pbuf *p, struct netif *inp, const ip4_addr_t *dest); + +/* + * @ingroup igmp + * Join a group on one network interface. + * + * @param ifaddr ip address of the network interface which should join a new group + * @param groupaddr the ip address of the group which to join + * @return ERR_OK if group was joined on the netif(s), an err_t otherwise + * + * Note: This is an internal function. + */ +err_t igmp_joingroup(const ip4_addr_t *ifaddr, const ip4_addr_t *groupaddr); + +/* + * @ingroup igmp + * Join a group on one network interface. + * + * @param netif the network interface which should join a new group + * @param groupaddr the ip address of the group which to join + * @return ERR_OK if group was joined on the netif, an err_t otherwise + * + * Note: This is an internal function. + */ +err_t igmp_joingroup_netif(struct netif *netif, const ip4_addr_t *groupaddr); + +/* + * @ingroup igmp + * Leave a group on one network interface. + * + * @param ifaddr ip address of the network interface which should leave a group + * @param groupaddr the ip address of the group which to leave + * @return ERR_OK if group was left on the netif(s), an err_t otherwise + * + * Note: This is an internal function. + */ +err_t igmp_leavegroup(const ip4_addr_t *ifaddr, const ip4_addr_t *groupaddr); + +/* + * @ingroup igmp + * Leave a group on one network interface. + * + * @param netif the network interface which should leave a group + * @param groupaddr the ip address of the group which to leave + * @return ERR_OK if group was left on the netif, an err_t otherwise + * + * Note: This is an internal function. + */ +err_t igmp_leavegroup_netif(struct netif *netif, const ip4_addr_t *groupaddr); + +/* + * @ingroup igmp + * + * The igmp timer function + * Should be called every IGMP_TMR_INTERVAL milliseconds (100 ms is default). + */ +void igmp_tmr(void); + +#if LWIP_LOWPOWER +u32_t igmp_tmr_tick(void); +#endif + +/* @ingroup igmp + * Get list head of IGMP groups for netif. + * Note: The allsystems group IP is contained in the list as first entry. + * @see @ref netif_set_igmp_mac_filter() + */ +#define netif_igmp_data(netif) ((struct igmp_group *)netif_get_client_data(netif, LWIP_NETIF_CLIENT_DATA_INDEX_IGMP)) + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_IPV4 && LWIP_IGMP */ + +#endif /* LWIP_HDR_IGMP_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/inet.h b/sdk_liteos/third_party/lwip_sack/include/lwip/inet.h new file mode 100644 index 0000000000000000000000000000000000000000..78e5e41e115c8fec5cee714c2f53dcbb4093dc20 --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/inet.h @@ -0,0 +1,320 @@ +/** + * @file + * This file (together with sockets.h) aims to provide structs and functions from + * - arpa/inet.h + * - netinet/in.h + * + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_INET_H +#define LWIP_HDR_INET_H + +#include "lwip/opt.h" +#include "lwip/def.h" +#include "lwip/ip_addr.h" +#include "lwip/ip6_addr.h" + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + + +#if !LWIP_LITEOS_COMPAT +/* If your port already typedef's in_addr_t, define IN_ADDR_T_DEFINED + to prevent this code from redefining it. */ +#if !defined(in_addr_t) && !defined(IN_ADDR_T_DEFINED) +typedef u32_t in_addr_t; +#endif +/** +* +* @brief Provides a binary notation of the IPv4 address. +*/ +struct in_addr { + in_addr_t s_addr; /** < Specifies the s_addr. */ +}; + + +/** 255.255.255.255 */ +#define INADDR_NONE IPADDR_NONE +/** 127.0.0.1 */ +#define INADDR_LOOPBACK IPADDR_LOOPBACK +/** 0.0.0.0 */ +#define INADDR_ANY IPADDR_ANY +/** 255.255.255.255 */ +#define INADDR_BROADCAST IPADDR_BROADCAST + + +/* Definitions of the bits in an (IPv4) Internet address integer. + + On subnets, host and network parts are found according to + the subnet mask, not these masks. */ +#define IN_CLASSA(a) IP_CLASSA(a) +#define IN_CLASSA_NET IP_CLASSA_NET +#define IN_CLASSA_NSHIFT IP_CLASSA_NSHIFT +#define IN_CLASSA_HOST IP_CLASSA_HOST +#define IN_CLASSA_MAX IP_CLASSA_MAX + +#define IN_CLASSB(b) IP_CLASSB(b) +#define IN_CLASSB_NET IP_CLASSB_NET +#define IN_CLASSB_NSHIFT IP_CLASSB_NSHIFT +#define IN_CLASSB_HOST IP_CLASSB_HOST +#define IN_CLASSB_MAX IP_CLASSB_MAX + +#define IN_CLASSC(c) IP_CLASSC(c) +#define IN_CLASSC_NET IP_CLASSC_NET +#define IN_CLASSC_NSHIFT IP_CLASSC_NSHIFT +#define IN_CLASSC_HOST IP_CLASSC_HOST +#define IN_CLASSC_MAX IP_CLASSC_MAX + +#define IN_CLASSD(d) IP_CLASSD(d) +#define IN_CLASSD_NET IP_CLASSD_NET /* These ones aren't really */ +#define IN_CLASSD_NSHIFT IP_CLASSD_NSHIFT /* net and host fields, but */ +#define IN_CLASSD_HOST IP_CLASSD_HOST /* routing needn't know. */ +#define IN_CLASSD_MAX IP_CLASSD_MAX + +#define IN_MULTICAST(a) IP_MULTICAST(a) + +#define IN_EXPERIMENTAL(a) IP_EXPERIMENTAL(a) +#define IN_BADCLASS(a) IP_BADCLASS(a) + +#define IN_LOOPBACKNET IP_LOOPBACKNET + +struct in6_addr { + union { + u32_t u32_addr[4]; + u8_t u8_addr[16]; + } un; +#define s6_addr un.u8_addr +}; + +/** + * This macro is used to initialize a variable of type struct in6_addr + * to the IPv6 wildcard address. + */ +#ifndef IN6ADDR_ANY_INIT +#define IN6ADDR_ANY_INIT {{{0, 0, 0, 0}}} +#endif +/** + * This macro is used to initialize a variable of type struct in6_addr + * to the IPv6 loopback address. + */ +#ifndef IN6ADDR_LOOPBACK_INIT +#define IN6ADDR_LOOPBACK_INIT {{{0, 0, 0, PP_HTONL(1)}}} +#endif + +#endif /* !LWIP_LITEOS_COMPAT */ + + +/** This variable is initialized by the system to contain the wildcard IPv6 address. */ +extern const struct in6_addr in6addr_any; +/* [Added new structure for ipv6 loopback as per section 3.9 of rfc 2553/3493] */ +extern const struct in6_addr in6addr_loopback; + +#ifndef INET_ADDRSTRLEN +#define INET_ADDRSTRLEN IP4ADDR_STRLEN_MAX +#endif +#if LWIP_IPV6 +#ifndef INET6_ADDRSTRLEN +#define INET6_ADDRSTRLEN IP6ADDR_STRLEN_MAX +#endif +#endif + +#if LWIP_IPV4 + +#define inet_addr_from_ip4addr(target_inaddr, source_ipaddr) ((target_inaddr)->s_addr = ip4_addr_get_u32(source_ipaddr)) +#define inet_addr_to_ip4addr(target_ipaddr, source_inaddr) (ip4_addr_set_u32(target_ipaddr, (source_inaddr)->s_addr)) + +/* directly map this to the lwip internal functions */ +/** +* @defgroup INET_Interfaces INET Interfaces +* This section contains information about INET interfaces. +* @ingroup User_interfaces +*/ +/** +* @ingroup INET_Interfaces +* @brief +* This function is used to convert the IPv4 address from string notation (number and dot format) +* to binary notation of network byte order. +* +* @param[in] cp Indicates a pointer to the IPv4 address string. +* +* @returns +* Valid IP address: On success, in unsigned int (32-bit) format. \n +* IPADDR_NONE: On failure \n + +* @note +* This interface will be available as function if LWIP_INET_ADDR_FUNC is enabled, +* otherwise it will be available as macro. +*/ +#if LWIP_INET_ADDR_FUNC +unsigned int inet_addr(const char *cp); +#else +#define inet_addr(cp) ipaddr_addr(cp) +#endif + +/* +Func Name: inet_aton +*/ +/** +* @ingroup INET_Interfaces +* @brief +* This function is used to convert an IPv4 address from string notation (number and dot format) +* to binary notation of network byte order and store it in the structure that the addr parameter points to. +* +* @param[in] cp Indicates a pointer to an IPv4 address string. +* @param[out] addr Indicates a the generated binary notation of the IPv4 address. +* @returns +* 1 : On success\n +* 0 : On failure \n +* @note +* - This interface is similar to inet_addr(). The only difference is that the generated binary notation +* of IPv4 address is updated in the addr parameter, instead of returning it. +* - This interface is available as a function if LWIP_INET_ATON_FUNC is enabled, +* otherwise it will be available as macro. +*/ +#if LWIP_INET_ATON_FUNC +int inet_aton(const char *cp, struct in_addr *addr); +#else +#define inet_aton(cp, addr) ip4addr_aton(cp, (ip4_addr_t*)addr) +#endif + + +/* +Func Name: inet_ntoa +*/ +/** +* @ingroup INET_Interfaces +* @brief +* This function is used to convert an IPv4 address from binary notation (network byte order) +* to string notation (number and dot format). +* +* @param[in] in Indicates a pointer to the binary notation of an IPv4 address. +* +* @returns +* Valid pointer: On success, returns a pointer to the string notation of the IPv4 address. \n +* NULL: On failure \n +* +* @par Note +* This interface is available as a function if LWIP_INET_NTOA_FUNC is enabled, +* otherwise it will be available as macro. +* +*/ +#if LWIP_INET_NTOA_FUNC +char *inet_ntoa (struct in_addr in); +#else +#define inet_ntoa(addr) ip4addr_ntoa((const ip4_addr_t*)&(addr)) +#endif +/** +* @ingroup INET_Interfaces + + +* @brief +* This function is used to convert an IPv4 address from binary notation (network byte order) +* to string notation (number and dot format). This is the reentrant API of inet_ntoa. The +* generated string notation IPv4 address is updated in the buffer passed by the user. +* +* @param[in] addr Indicates the binary notation of an IPv4 address. +* @param[out] buf Indicates a pointer to a user buffer, in which the output string format + of the IPv4 address is updated. +* @param[in] buflen Indicates the length of the user buffer. +* +* @returns +* Valid pointer : On success, returns a pointer to the buffer passed by the user in buf. \n +* NULL : On failure \n +* + +* @note +* This interface is available as only macro. +* +*/ +#define inet_ntoa_r(addr, buf, buflen) ip4addr_ntoa_r((const ip4_addr_t*)&(addr), buf, buflen) + +#endif /* LWIP_IPV4 */ + +#if LWIP_IPV6 + +#if LWIP_LITEOS_COMPAT +#define inet6_addr_from_ip6addr(target_in6addr, source_ip6addr) { \ + (void)memcpy((target_in6addr)->s6_addr, (source_ip6addr)->addr, sizeof(struct ip6_addr)); } +#define inet6_addr_to_ip6addr(target_ip6addr, source_in6addr) { \ + (void)memcpy((target_ip6addr)->addr, (source_in6addr)->s6_addr, sizeof(struct ip6_addr)); } +#else +#define inet6_addr_from_ip6addr(target_in6addr, source_ip6addr) do { \ + (target_in6addr)->un.u32_addr[0] = (source_ip6addr)->addr[0]; \ + (target_in6addr)->un.u32_addr[1] = (source_ip6addr)->addr[1]; \ + (target_in6addr)->un.u32_addr[2] = (source_ip6addr)->addr[2]; \ + (target_in6addr)->un.u32_addr[3] = (source_ip6addr)->addr[3]; } while (0) + +#define inet6_addr_to_ip6addr(target_ip6addr, source_in6addr) do { \ + (target_ip6addr)->addr[0] = (source_in6addr)->un.u32_addr[0]; \ + (target_ip6addr)->addr[1] = (source_in6addr)->un.u32_addr[1]; \ + (target_ip6addr)->addr[2] = (source_in6addr)->un.u32_addr[2]; \ + (target_ip6addr)->addr[3] = (source_in6addr)->un.u32_addr[3]; } while (0) +#endif + +/* directly map this to the lwip internal functions */ +#define inet6_aton(cp, addr) ip6addr_aton(cp, (ip6_addr_t*)addr) +#define inet6_ntoa(addr) ip6addr_ntoa((const ip6_addr_t*)&(addr)) +/** +* @ingroup INET_Interfaces +* @brief +* This interface is used to convert an IPv6 address from binary notation (network byte order) +* to string notation (colon format). This is the reentrant API of inet6_ntoa. The +* generated string notation IPv6 address is updated in the buffer passed by the user. +* +* @param[in] addr Indicates the binary notation of an IPv6 address. +* @param[out] buf Indicates a pointer to a user buffer, in which the output string + format of the IPv6 address is updated. +* @param[in] buflen Indicates the length of the user buffer. +* +* @returns +* Valid pointer: On success, returns a pointer to the buffer passed by the user in buf. \n +* NULL: On failure \n + +* +* @par Note +* This interface is available as only macro. + +* +*/ +#define inet6_ntoa_r(addr, buf, buflen) ip6addr_ntoa_r((const ip6_addr_t*)&(addr), buf, buflen) + +#endif /* LWIP_IPV6 */ + + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_HDR_INET_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/inet_chksum.h b/sdk_liteos/third_party/lwip_sack/include/lwip/inet_chksum.h new file mode 100644 index 0000000000000000000000000000000000000000..0473cf5ba4486aeb2a52c8ac345f196663f1d8f4 --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/inet_chksum.h @@ -0,0 +1,137 @@ +/** + * @file + * IP checksum calculation functions + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_INET_CHKSUM_H +#define LWIP_HDR_INET_CHKSUM_H + +#include "lwip/opt.h" + +#include "lwip/pbuf.h" +#include "lwip/ip_addr.h" + +/** Swap the bytes in an u16_t: much like lwip_htons() for little-endian */ +#ifndef SWAP_BYTES_IN_WORD +#define SWAP_BYTES_IN_WORD(w) ((u16_t)(((w) & 0xff) << 8) | (u16_t)(((w) & 0xff00) >> 8)) +#endif /* SWAP_BYTES_IN_WORD */ + +/** Split an u32_t in two u16_ts and add them up */ +#ifndef FOLD_U32T +#define FOLD_U32T(u) ((u32_t)(((u) >> 16) + ((u) & 0x0000ffffUL))) +#endif + +#if LWIP_CHECKSUM_ON_COPY +/** Function-like macro: same as MEMCPY but returns the checksum of copied data + as u16_t */ +# ifndef LWIP_CHKSUM_COPY +# define LWIP_CHKSUM_COPY(dst, src, len) lwip_chksum_copy(dst, src, len) +# ifndef LWIP_CHKSUM_COPY_ALGORITHM +# define LWIP_CHKSUM_COPY_ALGORITHM 1 +# endif /* LWIP_CHKSUM_COPY_ALGORITHM */ +# else /* LWIP_CHKSUM_COPY */ +# define LWIP_CHKSUM_COPY_ALGORITHM 0 +# endif /* LWIP_CHKSUM_COPY */ +#else /* LWIP_CHECKSUM_ON_COPY */ +# define LWIP_CHKSUM_COPY_ALGORITHM 0 +#endif /* LWIP_CHECKSUM_ON_COPY */ + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +#if (LWIP_CHKSUM_ALGORITHM == 4) || (LWIP_CHKSUM_COPY_ALGORITHM == 2) +/* @brief Check and reverse the data. + * + * @par Description: + * This API is used to check and reverse the data. The function is + * used for converting 32-bits accumulation into 16-bits checksum. + * + * @attention + * The checksum calculation can be divided into two steps: 1.accumulation; 2.reverse. + * This function is used to complate the second step. The input value get from the first step. + * + * @param sum [IN] the value of sum for the data which is needed to check and reverse. + * + * @retval uint16_t value of checksum. + */ +static inline unsigned short csum_fold(unsigned int sum) +{ +#ifdef ARCH_ARM + __asm__( + "add %0, %1, %1, ror #16 @ csum_fold" + : "=r" (sum) + : "r" (sum) + : "cc"); + return (unsigned short)(~(unsigned int)sum >> 16); +#else + sum = (sum & 0xffff) + (sum >> 16); + sum = (sum & 0xffff) + (sum >> 16); + return (unsigned short)(~sum); +#endif +} +#endif /* (LWIP_CHKSUM_ALGORITHM == 4) || (LWIP_CHKSUM_COPY_ALGORITHM == 2) */ + +u16_t inet_chksum(const void *dataptr, u16_t len); +u16_t inet_chksum_pbuf(struct pbuf *p); +#if LWIP_CHKSUM_COPY_ALGORITHM +u16_t lwip_chksum_copy(void *dst, const void *src, u16_t len); +#endif /* LWIP_CHKSUM_COPY_ALGORITHM */ + +#if LWIP_IPV4 +u16_t inet_chksum_pseudo(struct pbuf *p, u8_t proto, u16_t proto_len, + const ip4_addr_t *src, const ip4_addr_t *dest); +u16_t inet_chksum_pseudo_partial(struct pbuf *p, u8_t proto, + u16_t proto_len, u16_t chksum_len, const ip4_addr_t *src, const ip4_addr_t *dest); +#endif /* LWIP_IPV4 */ + +#if LWIP_IPV6 +u16_t ip6_chksum_pseudo(struct pbuf *p, u8_t proto, u16_t proto_len, + const ip6_addr_t *src, const ip6_addr_t *dest); +u16_t ip6_chksum_pseudo_partial(struct pbuf *p, u8_t proto, u16_t proto_len, + u16_t chksum_len, const ip6_addr_t *src, const ip6_addr_t *dest); +#endif /* LWIP_IPV6 */ + + +u16_t ip_chksum_pseudo(struct pbuf *p, u8_t proto, u16_t proto_len, + const ip_addr_t *src, const ip_addr_t *dest); +u16_t ip_chksum_pseudo_partial(struct pbuf *p, u8_t proto, u16_t proto_len, + u16_t chksum_len, const ip_addr_t *src, const ip_addr_t *dest); + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_HDR_INET_H */ + diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/init.h b/sdk_liteos/third_party/lwip_sack/include/lwip/init.h new file mode 100644 index 0000000000000000000000000000000000000000..b67c70d27d8581cb3f6041db96cef59913922b95 --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/init.h @@ -0,0 +1,101 @@ +/** + * @file + * lwIP initialization API + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_INIT_H +#define LWIP_HDR_INIT_H + +#include "lwip/opt.h" + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +/** + * @defgroup lwip_version Version + * @ingroup lwip + * @{ + */ + +/** X.x.x: Major version of the stack */ +#define LWIP_VERSION_MAJOR 2 +/** x.X.x: Minor version of the stack */ +#define LWIP_VERSION_MINOR 1 +/** x.x.X: Revision of the stack */ +#define LWIP_VERSION_REVISION 2 +/** For release candidates, this is set to 1..254 + * For official releases, this is set to 255 (LWIP_RC_RELEASE) + * For development versions (Git), this is set to 0 (LWIP_RC_DEVELOPMENT) */ +#define LWIP_VERSION_RC LWIP_RC_RELEASE + +/** LWIP_VERSION_RC is set to LWIP_RC_RELEASE for official releases */ +#define LWIP_RC_RELEASE 255 +/** LWIP_VERSION_RC is set to LWIP_RC_DEVELOPMENT for Git versions */ +#define LWIP_RC_DEVELOPMENT 0 + +#define LWIP_VERSION_IS_RELEASE (LWIP_VERSION_RC == LWIP_RC_RELEASE) +#define LWIP_VERSION_IS_DEVELOPMENT (LWIP_VERSION_RC == LWIP_RC_DEVELOPMENT) +#define LWIP_VERSION_IS_RC ((LWIP_VERSION_RC != LWIP_RC_RELEASE) && (LWIP_VERSION_RC != LWIP_RC_DEVELOPMENT)) + +/* Some helper defines to get a version string */ +#define LWIP_VERSTR2(x) #x +#define LWIP_VERSTR(x) LWIP_VERSTR2(x) +#if LWIP_VERSION_IS_RELEASE +#define LWIP_VERSION_STRING_SUFFIX "" +#elif LWIP_VERSION_IS_DEVELOPMENT +#define LWIP_VERSION_STRING_SUFFIX "d" +#else +#define LWIP_VERSION_STRING_SUFFIX "rc" LWIP_VERSTR(LWIP_VERSION_RC) +#endif + +/** Provides the version of the stack */ +#define LWIP_VERSION (((u32_t)LWIP_VERSION_MAJOR) << 24 | ((u32_t)LWIP_VERSION_MINOR) << 16 | \ + ((u32_t)LWIP_VERSION_REVISION) << 8 | ((u32_t)LWIP_VERSION_RC)) +/** Provides the version of the stack as string */ +#define LWIP_VERSION_STRING LWIP_VERSTR(LWIP_VERSION_MAJOR) "." LWIP_VERSTR(LWIP_VERSION_MINOR) "." LWIP_VERSTR(LWIP_VERSION_REVISION) LWIP_VERSION_STRING_SUFFIX + +#define NSTACK_VERSION_STR "nStack RivulNET 2.1.3.B016" +/** + * @} + */ + +/* Modules initialization */ +void lwip_init(void); + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_HDR_INIT_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/ip.h b/sdk_liteos/third_party/lwip_sack/include/lwip/ip.h new file mode 100644 index 0000000000000000000000000000000000000000..c30b21b9abe13cb32c4eced3e55f22cf8dbac0fd --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/ip.h @@ -0,0 +1,431 @@ +/** + * @file + * IP API + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_IP_H +#define LWIP_HDR_IP_H + +#include "lwip/opt.h" + +#include "lwip/def.h" +#include "lwip/pbuf.h" +#include "lwip/ip_addr.h" +#include "lwip/err.h" +#include "lwip/netif.h" +#include "lwip/ip4.h" +#include "lwip/ip6.h" +#include "lwip/prot/ip.h" + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + + +/* This is passed as the destination address to ip_output_if (not + to ip_output), meaning that an IP header already is constructed + in the pbuf. This is used when TCP retransmits. */ +#define LWIP_IP_HDRINCL NULL + +/** pbufs passed to IP must have a ref-count of 1 as their payload pointer + gets altered as the packet is passed down the stack */ +#ifndef LWIP_IP_CHECK_PBUF_REF_COUNT_FOR_TX + +#define LWIP_IP_CHECK_PBUF_REF_COUNT_FOR_TX(p) LWIP_ASSERT("p->ref == 1", (atomic_read(&p->ref) == 1)) +#endif + +#if LWIP_NETIF_USE_HINTS +#define IP_PCB_NETIFHINT ;struct netif_hint netif_hints +#define IP_PAD +#else +#define IP_PCB_NETIFHINT +#define IP_PAD ;u8_t pad_ip +#endif /* LWIP_NETIF_HWADDRHINT */ + +/** This is the common part of all PCB types. It needs to be at the + beginning of a PCB type definition. It is located here so that + changes to this common part are made in one location instead of + having to change all PCB structs. */ +#define IP_PCB \ + /* ip addresses in network byte order */ \ + ip_addr_t local_ip; \ + ip_addr_t remote_ip; \ + /* Socket options */ \ + u32_t so_options; \ + /* Type Of Service */ \ + u8_t tos; \ + /* the netif set by bindtodevice */ \ + u8_t ifindex; \ + /* Time To Live */ \ + u8_t ttl \ + /* link layer address resolution hint */ \ + IP_PCB_NETIFHINT \ + IP_PAD + +struct ip_pcb { + /* Common members of all PCB types */ + IP_PCB; + +#if LWIP_SO_PRIORITY + prio_t priority; +#endif /* LWIP_SO_PRIORITY */ + +#if LWIP_IPV6 && LWIP_MAC_SECURITY + u8_t macsec_reqd: 1; +#endif +}; + +/* + * Option flags per-socket. These are the same like SO_XXX in sockets.h + */ +#define SOF_REUSEADDR 0x04U /* allow local address reuse */ +#define SOF_KEEPALIVE 0x08U /* keep connections alive */ +#define SOF_BROADCAST 0x20U /* permit to send and to receive broadcast messages (see IP_SOF_BROADCAST option) */ +#define SOF_REUSEPORT 0x0200U /* Unimplemented: allow local address & port reuse */ +#define SOF_DONTROUTE 0X0400U /* all packets sent from this socket should only be routed with link scope entry, */ +#define SOF_BINDNONUNICAST 0x0800U /* socket has bind to a non unicast */ + + +/* These flags are inherited (e.g. from a listen-pcb to a connection-pcb): */ +#define SOF_INHERITED (SOF_REUSEADDR | SOF_KEEPALIVE) + +/** Global variables of this module, kept in a struct for efficient access using base+index. */ +struct ip_globals { + /** The interface that accepted the packet for the current callback invocation. */ + struct netif *current_netif; + /** The interface that received the packet for the current callback invocation. */ + struct netif *current_input_netif; +#if LWIP_IPV4 + /** Header of the input packet currently being processed. */ + const struct ip_hdr *current_ip4_header; +#endif /* LWIP_IPV4 */ +#if LWIP_IPV6 + /** Header of the input IPv6 packet currently being processed. */ + struct ip6_hdr *current_ip6_header; +#endif /* LWIP_IPV6 */ + /** Total header length of current_ip4/6_header (i.e. after this, the UDP/TCP header starts) */ + u16_t current_ip_header_tot_len; + /** Source IP address of current_header */ + ip_addr_t current_iphdr_src; + /** Destination IP address of current_header */ + ip_addr_t current_iphdr_dest; + + /* The IP header ID of the next outgoing IP packet */ +#if LWIP_IPV4 + /* ensure this member of this sturcture is not mem set to zero */ + u16_t ip_id; +#endif +}; +extern struct ip_globals ip_data; + + +/** Get the interface that accepted the current packet. + * This may or may not be the receiving netif, depending on your netif/network setup. + * This function must only be called from a receive callback (udp_recv, + * raw_recv, tcp_accept). It will return NULL otherwise. */ +#define ip_current_netif() (ip_data.current_netif) +/** Get the interface that received the current packet. + * This function must only be called from a receive callback (udp_recv, + * raw_recv, tcp_accept). It will return NULL otherwise. */ +#define ip_current_input_netif() (ip_data.current_input_netif) +/** Total header length of ip(6)_current_header() (i.e. after this, the UDP/TCP header starts) */ +#define ip_current_header_tot_len() (ip_data.current_ip_header_tot_len) +/** Source IP address of current_header */ +#define ip_current_src_addr() (&ip_data.current_iphdr_src) +/** Destination IP address of current_header */ +#define ip_current_dest_addr() (&ip_data.current_iphdr_dest) + +#if LWIP_IPV4 && LWIP_IPV6 +/** Get the IPv4 header of the current packet. + * This function must only be called from a receive callback (udp_recv, + * raw_recv, tcp_accept). It will return NULL otherwise. */ +#define ip4_current_header() ip_data.current_ip4_header +/** Get the IPv6 header of the current packet. + * This function must only be called from a receive callback (udp_recv, + * raw_recv, tcp_accept). It will return NULL otherwise. */ +#define ip6_current_header() ((const struct ip6_hdr*)(ip_data.current_ip6_header)) +/** Returns TRUE if the current IP input packet is IPv6, FALSE if it is IPv4 */ +#define ip_current_is_v6() (ip6_current_header() != NULL) +/** Source IPv6 address of current_header */ +#define ip6_current_src_addr() (ip_2_ip6(&ip_data.current_iphdr_src)) +/** Destination IPv6 address of current_header */ +#define ip6_current_dest_addr() (ip_2_ip6(&ip_data.current_iphdr_dest)) +/** Get the transport layer protocol */ +#define ip_current_header_proto() (ip_current_is_v6() ? \ + IP6H_NEXTH(ip6_current_header()) :\ + IPH_PROTO(ip4_current_header())) +/** Get the transport layer header */ +#define ip_next_header_ptr() ((const void*)((ip_current_is_v6() ? \ + (const u8_t*)ip6_current_header() : (const u8_t*)ip4_current_header()) + ip_current_header_tot_len())) + +/** Source IP4 address of current_header */ +#define ip4_current_src_addr() (ip_2_ip4(&ip_data.current_iphdr_src)) +/** Destination IP4 address of current_header */ +#define ip4_current_dest_addr() (ip_2_ip4(&ip_data.current_iphdr_dest)) + +/* get ip id for IPv4 */ +#define ip4_get_ip_id() (ip_data.ip_id) + +/* get last ip id for IPv4 */ +#define ip4_last_ip_id() ((u16_t)(ip_data.ip_id - 1)) + +/* set ip id for IPv4 */ +#define ip4_set_ip_id(val) (ip_data.ip_id = (val)) + +/* inc ip id for IPv4 */ +#define ip4_inc_ip_id() (++ip_data.ip_id) + +#elif LWIP_IPV4 /* LWIP_IPV4 && LWIP_IPV6 */ + +/** Get the IPv4 header of the current packet. + * This function must only be called from a receive callback (udp_recv, + * raw_recv, tcp_accept). It will return NULL otherwise. */ +#define ip4_current_header() ip_data.current_ip4_header +/** Always returns FALSE when only supporting IPv4 only */ +#define ip_current_is_v6() 0 +/** Get the transport layer protocol */ +#define ip_current_header_proto() IPH_PROTO(ip4_current_header()) +/** Get the transport layer header */ +#define ip_next_header_ptr() ((const void*)((const u8_t*)ip4_current_header() + ip_current_header_tot_len())) +/** Source IP4 address of current_header */ +#define ip4_current_src_addr() (&ip_data.current_iphdr_src) +/** Destination IP4 address of current_header */ +#define ip4_current_dest_addr() (&ip_data.current_iphdr_dest) + +/* get ip id for IPv4 */ +#define ip4_get_ip_id() (ip_data.ip_id) + +/* get last ip id for IPv4 */ +#define ip4_last_ip_id() ((u16_t)(ip_data.ip_id - 1)) + +/* set ip id for IPv4 */ +#define ip4_set_ip_id(val) (ip_data.ip_id = (val)) + +/* inc ip id for IPv4 */ +#define ip4_inc_ip_id() (++ip_data.ip_id) + +#elif LWIP_IPV6 /* LWIP_IPV4 && LWIP_IPV6 */ + +/** Get the IPv6 header of the current packet. + * This function must only be called from a receive callback (udp_recv, + * raw_recv, tcp_accept). It will return NULL otherwise. */ +#define ip6_current_header() ((const struct ip6_hdr*)(ip_data.current_ip6_header)) +/** Always returns TRUE when only supporting IPv6 only */ +#define ip_current_is_v6() 1 +/** Get the transport layer protocol */ +#define ip_current_header_proto() IP6H_NEXTH(ip6_current_header()) +/** Get the transport layer header */ +#define ip_next_header_ptr() ((const void*)(((const u8_t*)ip6_current_header()) + ip_current_header_tot_len())) +/** Source IP6 address of current_header */ +#define ip6_current_src_addr() (&ip_data.current_iphdr_src) +/** Destination IP6 address of current_header */ +#define ip6_current_dest_addr() (&ip_data.current_iphdr_dest) + +#endif /* LWIP_IPV6 */ + +/** Union source address of current_header */ +#define ip_current_src_addr() (&ip_data.current_iphdr_src) +/** Union destination address of current_header */ +#define ip_current_dest_addr() (&ip_data.current_iphdr_dest) + +/** Gets an IP pcb option (SOF_* flags) */ +#define ip_get_option(pcb, opt) ((pcb)->so_options & (opt)) +/** Sets an IP pcb option (SOF_* flags) */ +#define ip_set_option(pcb, opt) ((pcb)->so_options |= (opt)) +/** Resets an IP pcb option (SOF_* flags) */ +#define ip_reset_option(pcb, opt) ((pcb)->so_options &= (u8_t)~(opt)) + +#if LWIP_IPV4 && LWIP_IPV6 +#if LWIP_API_RICH +/** + * @ingroup ip + * Output IP packet, netif is selected by source address + */ +#define ip_output(p, src, dest, ttl, tos, proto, pcb) \ + (IP_IS_V6(dest) ? \ + ip6_output(p, ip_2_ip6(src), ip_2_ip6(dest), ttl, tos, proto, pcb) : \ + ip4_output(p, ip_2_ip4(src), ip_2_ip4(dest), ttl, tos, proto, pcb)) +#endif /* LWIP_API_RICH */ +/** + * @ingroup ip + * Output IP packet to specified interface + */ +#define ip_output_if(p, src, dest, ttl, tos, proto, netif) \ + (IP_IS_V6(dest) ? \ + ip6_output_if(p, ip_2_ip6(src), ip_2_ip6(dest), ttl, tos, proto, netif) : \ + ip4_output_if(p, ip_2_ip4(src), ip_2_ip4(dest), ttl, tos, proto, netif)) +/** + * @ingroup ip + * Output IP packet to interface specifying source address + */ +#define ip_output_if_src(p, src, dest, ttl, tos, proto, netif) \ + (IP_IS_V6(dest) ? \ + ip6_output_if_src(p, ip_2_ip6(src), ip_2_ip6(dest), ttl, tos, proto, netif) : \ + ip4_output_if_src(p, ip_2_ip4(src), ip_2_ip4(dest), ttl, tos, proto, netif)) +/** Output IP packet that already includes an IP header. */ +#define ip_output_if_hdrincl(p, src, dest, netif) \ + (IP_IS_V6(dest) ? \ + ip6_output_if(p, ip_2_ip6(src), LWIP_IP_HDRINCL, 0, 0, 0, netif) : \ + ip4_output_if(p, ip_2_ip4(src), LWIP_IP_HDRINCL, 0, 0, 0, netif)) +/** Output IP packet with netif_hint */ +#define ip_output_hinted(p, src, dest, ttl, tos, proto, netif_hint) \ + (IP_IS_V6(dest) ? \ + ip6_output_hinted(p, ip_2_ip6(src), ip_2_ip6(dest), ttl, tos, proto, netif_hint) : \ + ip4_output_hinted(p, ip_2_ip4(src), ip_2_ip4(dest), ttl, tos, proto, netif_hint)) + +#if LWIP_IP_FILTER || LWIP_IPV6_FILTER +/** @cond liteos + * Function prototype for packet_filter functions. Call this function when an ip packet has + * been received and LWIP_IP_FILTER or LWIP_IPV6_FILTERis Enabled. + * @note If this registered callback return other than ERR_OK then packet will be dropped. + * @param p Indicates the received packet, copied into a pbuf. + * @param inp Indicates the netif which received the packet. + * @endcond + */ +typedef err_t (*ip_filter_fn)(const struct pbuf *p, struct netif *inp); + +#if LWIP_IP_FILTER +err_t set_ip4_filter(ip_filter_fn filter_fn); +#endif /* LWIP_IP_FILTER */ + +#if LWIP_IPV6_FILTER +err_t set_ip6_filter(ip_filter_fn filter_fn); +#endif /* LWIP_IPV6_FILTER */ +#endif /* LWIP_IP_FILTER */ + +/** + * @ingroup ip + * Get netif for address combination. See \ref ip6_route and \ref ip4_route + */ +#if LWIP_SO_DONTROUTE +#define ip_route(src, dest, scope) \ + (IP_IS_V6_VAL(*dest) ? \ + ip6_route(ip_2_ip6(src), ip_2_ip6(dest), scope) : \ + ip4_route_src(ip_2_ip4(src), ip_2_ip4(dest), scope)) +#else +#define ip_route(src, dest) \ + (IP_IS_V6_VAL(*dest) ? \ + ip6_route(ip_2_ip6(src), ip_2_ip6(dest)) : \ + ip4_route_src(ip_2_ip4(src), ip_2_ip4(dest))) +#endif + +/** + * @ingroup ip + * Get netif for IP. + */ +#define ip_netif_get_local_ip(netif, dest) (IP_IS_V6(dest) ? \ + ip6_netif_get_local_ip(netif, ip_2_ip6(dest)) : \ + ip4_netif_get_local_ip(netif)) +#define ip_debug_print(is_ipv6, p) ((is_ipv6) ? ip6_debug_print(p) : ip4_debug_print(p)) + +err_t ip_input(struct pbuf *p, struct netif *inp); + +#if LWIP_PLC || LWIP_IEEE802154 +err_t ip_input_lln(struct netif *iface, struct pbuf *p, + struct linklayer_addr *sendermac, struct linklayer_addr *recvermac); +#endif + +#elif LWIP_IPV4 /* LWIP_IPV4 && LWIP_IPV6 */ + +#if LWIP_API_RICH +#define ip_output(p, src, dest, ttl, tos, proto) \ + ip4_output(p, src, dest, ttl, tos, proto, pcb) +#endif /* LWIP_API_RICH */ +#define ip_output_if(p, src, dest, ttl, tos, proto, netif) \ + ip4_output_if(p, src, dest, ttl, tos, proto, netif) +#define ip_output_if_src(p, src, dest, ttl, tos, proto, netif) \ + ip4_output_if_src(p, src, dest, ttl, tos, proto, netif) +#define ip_output_hinted(p, src, dest, ttl, tos, proto, netif_hint) \ + ip4_output_hinted(p, src, dest, ttl, tos, proto, netif_hint) +#define ip_output_if_hdrincl(p, src, dest, netif) \ + ip6_output_if(p, src, LWIP_IP_HDRINCL, 0, 0, 0, netif) + +#if LWIP_SO_DONTROUTE +#define ip_route(src, dest, scope) \ + ip4_route_src(src, dest, scope) +#else +#define ip_route(src, dest) \ + ip4_route_src(src, dest) +#endif + +#define ip_netif_get_local_ip(netif, dest) \ + ip4_netif_get_local_ip(netif) +#define ip_debug_print(is_ipv6, p) ip4_debug_print(p) + +#define ip_input ip4_input + +#elif LWIP_IPV6 /* LWIP_IPV4 && LWIP_IPV6 */ + +#if LWIP_API_RICH +#define ip_output(p, src, dest, ttl, tos, proto) \ + ip6_output(p, src, dest, ttl, tos, proto) +#endif /* LWIP_API_RICH */ +#define ip_output_if(p, src, dest, ttl, tos, proto, netif) \ + ip6_output_if(p, src, dest, ttl, tos, proto, netif) +#define ip_output_if_src(p, src, dest, ttl, tos, proto, netif) \ + ip6_output_if_src(p, src, dest, ttl, tos, proto, netif) +#define ip_output_hinted(p, src, dest, ttl, tos, proto, netif_hint) \ + ip6_output_hinted(p, src, dest, ttl, tos, proto, netif_hint) +#define ip_output_if_hdrincl(p, src, dest, netif) \ + ip4_output_if(p, src, LWIP_IP_HDRINCL, 0, 0, 0, netif) + +#if LWIP_SO_DONTROUTE +#define ip_route(src, dest, scope) \ + ip6_route(src, dest, scope) +#else +#define ip_route(src, dest) \ + ip6_route(src, dest) +#endif +#define ip_netif_get_local_ip(netif, dest) \ + ip6_netif_get_local_ip(netif, dest) +#define ip_debug_print(is_ipv6, p) ip6_debug_print(p) + +#define ip_input ip6_input + +#endif /* LWIP_IPV6 */ + +#define ip_route_get_local_ip(src, dest, netif, ipaddr, scope) do { \ + (netif) = ip_route(src, dest, scope); \ + (ipaddr) = ip_netif_get_local_ip(netif, dest); \ +} while (0) + +struct netif *ip_route_pcb(const ip_addr_t *dest, const struct ip_pcb *pcb); + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_HDR_IP_H */ + + diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/ip4.h b/sdk_liteos/third_party/lwip_sack/include/lwip/ip4.h new file mode 100644 index 0000000000000000000000000000000000000000..099fa0c68088cd90fe670c27250741f67164153b --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/ip4.h @@ -0,0 +1,131 @@ +/** + * @file + * IPv4 API + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_IP4_H +#define LWIP_HDR_IP4_H + +#include "lwip/opt.h" + +#if LWIP_IPV4 + +#include "lwip/def.h" +#include "lwip/pbuf.h" +#include "lwip/ip4_addr.h" +#include "lwip/err.h" +#include "lwip/prot/ip4.h" + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +#define IP_PROTO_VERSION_4 4 + +#ifdef LWIP_HOOK_IP4_ROUTE_SRC +#define LWIP_IPV4_SRC_ROUTING 1 +#else +#define LWIP_IPV4_SRC_ROUTING 0 +#endif + +/** Currently, the function ip_output_if_opt() is only used with IGMP */ +#define IP_OPTIONS_SEND (LWIP_IPV4 && LWIP_IGMP) +struct netif; + +void ip_init(void); /* Compatibility define, no init needed. */ + +#if LWIP_SO_DONTROUTE +struct netif *ip4_route(const ip4_addr_t *dest, rt_scope_t scope); +#if LWIP_IPV4_SRC_ROUTING +struct netif *ip4_route_src(const ip4_addr_t *src, const ip4_addr_t *dest, rt_scope_t scope); +#else /* LWIP_IPV4_SRC_ROUTING */ +#define ip4_route_src(src, dest, scope) ip4_route(dest, scope) +#endif /* LWIP_IPV4_SRC_ROUTING */ +#else +struct netif *ip4_route(const ip4_addr_t *dest); +#if LWIP_IPV4_SRC_ROUTING +struct netif *ip4_route_src(const ip4_addr_t *src, const ip4_addr_t *dest); +#else /* LWIP_IPV4_SRC_ROUTING */ +#define ip4_route_src(src, dest) ip4_route(dest) +#endif /* LWIP_IPV4_SRC_ROUTING */ + +#endif +struct ip_pcb; +err_t ip4_input(struct pbuf *p, struct netif *inp); +#if LWIP_API_RICH +err_t ip4_output(struct pbuf *p, const ip4_addr_t *src, const ip4_addr_t *dest, + u8_t ttl, u8_t tos, u8_t proto, struct ip_pcb *pcb); +#endif /* LWIP_API_RICH */ +err_t ip4_output_if(struct pbuf *p, const ip4_addr_t *src, const ip4_addr_t *dest, + u8_t ttl, u8_t tos, u8_t proto, struct netif *netif); +err_t ip4_output_if_src(struct pbuf *p, const ip4_addr_t *src, const ip4_addr_t *dest, + u8_t ttl, u8_t tos, u8_t proto, struct netif *netif); +#if LWIP_NETIF_USE_HINTS +err_t ip4_output_hinted(struct pbuf *p, const ip4_addr_t *src, const ip4_addr_t *dest, + u8_t ttl, u8_t tos, u8_t proto, struct netif_hint *netif_hint, struct ip_pcb *pcb); +#endif /* LWIP_NETIF_USE_HINTS */ +#if IP_OPTIONS_SEND +err_t ip4_output_if_opt(struct pbuf *p, const ip4_addr_t *src, const ip4_addr_t *dest, + u8_t ttl, u8_t tos, u8_t proto, struct netif *netif, void *ip_options, + u16_t optlen); +err_t ip4_output_if_opt_src(struct pbuf *p, const ip4_addr_t *src, const ip4_addr_t *dest, + u8_t ttl, u8_t tos, u8_t proto, struct netif *netif, void *ip_options, + u16_t optlen); +#endif /* IP_OPTIONS_SEND */ + +#if LWIP_MULTICAST_TX_OPTIONS +void ip4_set_default_multicast_netif(struct netif *default_multicast_netif); +#endif /* LWIP_MULTICAST_TX_OPTIONS */ + +#define ip4_netif_get_local_ip(netif) (((netif) != NULL) ? netif_ip_addr4(netif) : NULL) + +#if IP_DEBUG +void ip4_debug_print(struct pbuf *p); +#else +#define ip4_debug_print(p) (void)0 +#endif /* IP_DEBUG */ + +#if LWIP_NAT64 +err_t ip4_iphdr_chksum(struct ip_hdr *iphdr, struct netif *netif, u16_t *chksum); +#endif /* LWIP_NAT64 */ + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_IPV4 */ + +#endif /* LWIP_HDR_IP_H */ + + diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/ip4_addr.h b/sdk_liteos/third_party/lwip_sack/include/lwip/ip4_addr.h new file mode 100644 index 0000000000000000000000000000000000000000..cc3ea3efa7e6f396b4b7ae9c1a1f735573e5cd2f --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/ip4_addr.h @@ -0,0 +1,231 @@ +/** + * @file + * IPv4 address API + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_IP4_ADDR_H +#define LWIP_HDR_IP4_ADDR_H + +#include "lwip/opt.h" +#include "lwip/def.h" + +#if LWIP_IPV4 + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + + +/** + * @cond liteos This is the aligned version of ip4_addr_t, + used as local variable, on the stack, etc. + * @endcond */ +struct ip4_addr { + u32_t addr; +}; + +/** ip4_addr_t uses a struct for convenience only, so that the same defines can + * operate both on ip4_addr_t as well as on ip4_addr_p_t. */ +typedef struct ip4_addr ip4_addr_t; + +/* Forward declaration to not include netif.h */ +struct netif; + +/** 255.255.255.255 */ +#define IPADDR_NONE ((u32_t)0xffffffffUL) +/** 127.0.0.1 */ +#define IPADDR_LOOPBACK ((u32_t)0x7f000001UL) +/** 0.0.0.0 */ +#define IPADDR_ANY ((u32_t)0x00000000UL) +/** 255.255.255.255 */ +#define IPADDR_BROADCAST ((u32_t)0xffffffffUL) + +/* Definitions of the bits in an Internet address integer. + + On subnets, host and network parts are found according to + the subnet mask, not these masks. */ +#define IP_CLASSA(a) ((((u32_t)(a)) & 0x80000000UL) == 0) +#define IP_CLASSA_NET 0xff000000 +#define IP_CLASSA_NSHIFT 24 +#define IP_CLASSA_HOST (0xffffffff & ~IP_CLASSA_NET) +#define IP_CLASSA_MAX 128 + +#define IP_CLASSB(a) ((((u32_t)(a)) & 0xc0000000UL) == 0x80000000UL) +#define IP_CLASSB_NET 0xffff0000 +#define IP_CLASSB_NSHIFT 16 +#define IP_CLASSB_HOST (0xffffffff & ~IP_CLASSB_NET) +#define IP_CLASSB_MAX 65536 + +#define IP_CLASSC(a) ((((u32_t)(a)) & 0xe0000000UL) == 0xc0000000UL) +#define IP_CLASSC_NET 0xffffff00 +#define IP_CLASSC_NSHIFT 8 +#define IP_CLASSC_HOST (0xffffffff & ~IP_CLASSC_NET) + +#define IP_CLASSD(a) (((u32_t)(a) & 0xf0000000UL) == 0xe0000000UL) +#define IP_CLASSD_NET 0xf0000000 /* These ones aren't really */ +#define IP_CLASSD_NSHIFT 28 /* net and host fields, but */ +#define IP_CLASSD_HOST 0x0fffffff /* routing needn't know. */ +#define IP_MULTICAST(a) IP_CLASSD(a) + +#define IP_EXPERIMENTAL(a) (((u32_t)(a) & 0xf0000000UL) == 0xf0000000UL) +#define IP_BADCLASS(a) (((u32_t)(a) & 0xf0000000UL) == 0xf0000000UL) + +#define IP_LOOPBACKNET 127 /* official! */ + +/** Set an IP address given by the four byte-parts */ +#define IP4_ADDR(ipaddr, a, b, c, d) (ipaddr)->addr = PP_HTONL(LWIP_MAKEU32(a, b, c, d)) + +/** Copy IP address - faster than ip4_addr_set: no NULL check */ +#define ip4_addr_copy(dest, src) ((dest).addr = (src).addr) +/** Safely copy one IP address to another (src may be NULL) */ +#define ip4_addr_set(dest, src) ((dest)->addr = ((src) == NULL ? 0 : (src)->addr)) +/** Set complete address to zero */ +#define ip4_addr_set_zero(ipaddr) ((ipaddr)->addr = 0) +/** Set address to IPADDR_ANY (no need for lwip_htonl()) */ +#define ip4_addr_set_any(ipaddr) ((ipaddr)->addr = IPADDR_ANY) +/** Set address to loopback address */ +#define ip4_addr_set_loopback(ipaddr) ((ipaddr)->addr = PP_HTONL(IPADDR_LOOPBACK)) +/** Check if an address is in the loopback region */ +#define ip4_addr_isloopback(ipaddr) (((ipaddr)->addr & PP_HTONL(IP_CLASSA_NET)) == \ + PP_HTONL(((u32_t)IP_LOOPBACKNET) << 24)) +/** Safely copy one IP address to another and change byte order + * from host- to network-order. */ +#define ip4_addr_set_hton(dest, src) ((dest)->addr = ((src) == NULL ? 0 : lwip_htonl((src)->addr))) +/** IPv4 only: set the IP address given as an u32_t */ +#define ip4_addr_set_u32(dest_ipaddr, src_u32) ((dest_ipaddr)->addr = (src_u32)) +/** IPv4 only: get the IP address as an u32_t */ +#define ip4_addr_get_u32(src_ipaddr) ((src_ipaddr)->addr) + +/** Get the network address by combining host address with netmask */ +#define ip4_addr_get_network(target, host, netmask) do { \ + ((target)->addr = ((host)->addr) & ((netmask)->addr)); } while (0) + +/** + * Determine if two address are on the same network. + * + * @arg addr1 IP address 1 + * @arg addr2 IP address 2 + * @arg mask network identifier mask + * @return !0 if the network identifiers of both address match + */ +#define ip4_addr_netcmp(addr1, addr2, mask) (((addr1)->addr & \ + (mask)->addr) == \ + ((addr2)->addr & \ + (mask)->addr)) +#define ip4_addr_cmp(addr1, addr2) ((addr1)->addr == (addr2)->addr) + +#define ip4_addr_isany_val(addr1) ((addr1).addr == IPADDR_ANY) +#define ip4_addr_isnone_val(addr1) ((addr1).addr == IPADDR_NONE) +#define ip4_addr_isany(addr1) ((addr1) == NULL || ip4_addr_isany_val(*(addr1))) +#define ip4_addr_isnone(addr1) ((addr1) == NULL || ip4_addr_isnone_val(*(addr1))) +#define ip4_addr_isbroadcast(addr1, netif) ip4_addr_isbroadcast_u32((addr1)->addr, netif) +u8_t ip4_addr_isbroadcast_u32(u32_t addr, const struct netif *netif); + +#if LWIP_ENABLE_LOS_SHELL_CMD || LWIP_IOCTL_IF || LWIP_ENABLE_BASIC_SHELL_CMD +#define ip_addr_netmask_valid(netmask) ip4_addr_netmask_valid((netmask)->addr) +u8_t ip4_addr_netmask_valid(u32_t netmask); +#endif + +#define ip4_addr_ismulticast(addr1) (((addr1)->addr & PP_HTONL(0xf0000000UL)) == PP_HTONL(0xe0000000UL)) + +#define ip4_addr_islinklocal(addr1) (((addr1)->addr & PP_HTONL(0xffff0000UL)) == PP_HTONL(0xa9fe0000UL)) + +#ifdef LWIP_DEBUG +#define ip4_addr_debug_print_parts(debug, a, b, c, d) \ + LWIP_DEBUGF(debug, ("%" U16_F ".%" U16_F ".%" U16_F ".%" U16_F, a, b, c, d)) +#define ip4_addr_debug_print(debug, ipaddr) \ + ip4_addr_debug_print_parts(debug, \ + (u16_t)((ipaddr) != NULL ? ip4_addr1_16(ipaddr) : 0), \ + (u16_t)((ipaddr) != NULL ? ip4_addr2_16(ipaddr) : 0), \ + (u16_t)((ipaddr) != NULL ? ip4_addr3_16(ipaddr) : 0), \ + (u16_t)((ipaddr) != NULL ? ip4_addr4_16(ipaddr) : 0)) +#define ip4_addr_debug_print_val(debug, ipaddr) \ + ip4_addr_debug_print_parts(debug, \ + ip4_addr1_16_val(ipaddr), \ + ip4_addr2_16_val(ipaddr), \ + ip4_addr3_16_val(ipaddr), \ + ip4_addr4_16_val(ipaddr)) +#else +#define ip4_addr_debug_print_parts(debug, a, b, c, d) +#define ip4_addr_debug_print(debug, ipaddr) +#define ip4_addr_debug_print_val(debug, ipaddr) +#endif + + +/* Get one byte from the 4-byte address */ +#define ip4_addr_get_byte(ipaddr, idx) (((const u8_t*)(&(ipaddr)->addr))[idx]) +#define ip4_addr1(ipaddr) ip4_addr_get_byte(ipaddr, 0) +#define ip4_addr2(ipaddr) ip4_addr_get_byte(ipaddr, 1) +#define ip4_addr3(ipaddr) ip4_addr_get_byte(ipaddr, 2) +#define ip4_addr4(ipaddr) ip4_addr_get_byte(ipaddr, 3) +/* Get one byte from the 4-byte address, but argument is 'ip4_addr_t', + * not a pointer */ +#define ip4_addr_get_byte_val(ipaddr, idx) ((u8_t)(((ipaddr).addr >> (idx * 8)) & 0xff)) +#define ip4_addr1_val(ipaddr) ip4_addr_get_byte_val(ipaddr, 0) +#define ip4_addr2_val(ipaddr) ip4_addr_get_byte_val(ipaddr, 1) +#define ip4_addr3_val(ipaddr) ip4_addr_get_byte_val(ipaddr, 2) +#define ip4_addr4_val(ipaddr) ip4_addr_get_byte_val(ipaddr, 3) +/* These are cast to u16_t, with the intent that they are often arguments + * to printf using the U16_F format from cc.h. */ +#define ip4_addr1_16(ipaddr) ((u16_t)ip4_addr1(ipaddr)) +#define ip4_addr2_16(ipaddr) ((u16_t)ip4_addr2(ipaddr)) +#define ip4_addr3_16(ipaddr) ((u16_t)ip4_addr3(ipaddr)) +#define ip4_addr4_16(ipaddr) ((u16_t)ip4_addr4(ipaddr)) +#define ip4_addr1_16_val(ipaddr) ((u16_t)ip4_addr1_val(ipaddr)) +#define ip4_addr2_16_val(ipaddr) ((u16_t)ip4_addr2_val(ipaddr)) +#define ip4_addr3_16_val(ipaddr) ((u16_t)ip4_addr3_val(ipaddr)) +#define ip4_addr4_16_val(ipaddr) ((u16_t)ip4_addr4_val(ipaddr)) + +#define IP4ADDR_STRLEN_MAX 16 +#define IP4ADDR_STR_PARTS 4 + +/** For backwards compatibility */ +#define ip_ntoa(ipaddr) ipaddr_ntoa(ipaddr) + +u32_t ipaddr_addr(const char *cp); +int ip4addr_aton(const char *cp, ip4_addr_t *addr); +/** returns ptr to static buffer; not reentrant! */ +char *ip4addr_ntoa(const ip4_addr_t *addr); +char *ip4addr_ntoa_r(const ip4_addr_t *addr, char *buf, int buflen); + +int inet_pton4(const char *src, unsigned char *dst); +const char *lwip_inet_ntop4(const unsigned char *src, char *dst, u32_t size); + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_IPV4 */ + +#endif /* LWIP_HDR_IP_ADDR_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/ip4_frag.h b/sdk_liteos/third_party/lwip_sack/include/lwip/ip4_frag.h new file mode 100644 index 0000000000000000000000000000000000000000..d506fa4a15db023f05ea246d79886caa08ed0098 --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/ip4_frag.h @@ -0,0 +1,106 @@ +/** + * @file + * IP fragmentation/reassembly + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Jani Monoses + * + */ + +#ifndef LWIP_HDR_IP4_FRAG_H +#define LWIP_HDR_IP4_FRAG_H + +#include "lwip/opt.h" +#include "lwip/err.h" +#include "lwip/pbuf.h" +#include "lwip/netif.h" +#include "lwip/ip_addr.h" +#include "lwip/ip.h" + +#if LWIP_IPV4 + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +#if IP_REASSEMBLY +/* The IP reassembly timer interval in milliseconds. */ +#define IP_TMR_INTERVAL 1000 + +/* IP reassembly helper struct. + * This is exported because memp needs to know the size. + */ +struct ip_reassdata { + struct ip_reassdata *next; + struct pbuf *p; + struct ip_hdr iphdr; + u16_t datagram_len; + u8_t flags; + u8_t timer; + u32_t count; +}; + +void ip_reass_init(void); +void ip_reass_tmr(void); +struct pbuf *ip4_reass(struct pbuf *p); +#endif /* IP_REASSEMBLY */ + +#if IP_FRAG +#if !LWIP_NETIF_TX_SINGLE_PBUF +#ifndef LWIP_PBUF_CUSTOM_REF_DEFINED +#define LWIP_PBUF_CUSTOM_REF_DEFINED +/* A custom pbuf that holds a reference to another pbuf, which is freed + * when this custom pbuf is freed. This is used to create a custom PBUF_REF + * that points into the original pbuf. */ +struct pbuf_custom_ref { + /* 'base class' */ + struct pbuf_custom pc; + /* pointer to the original pbuf that is referenced */ + struct pbuf *original; +}; +#endif /* LWIP_PBUF_CUSTOM_REF_DEFINED */ +#endif /* !LWIP_NETIF_TX_SINGLE_PBUF */ + +err_t ip4_frag(struct pbuf *p, struct netif *netif, const ip4_addr_t *dest); + +#if LWIP_LOWPOWER +u32_t ip_reass_tmr_tick(void); +#endif /* LWIP_LOWPOWER */ + +#endif /* IP_FRAG */ + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_IPV4 */ + +#endif /* LWIP_HDR_IP4_FRAG_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/ip6.h b/sdk_liteos/third_party/lwip_sack/include/lwip/ip6.h new file mode 100644 index 0000000000000000000000000000000000000000..76813a3f047a0fbd25788c462fad68ef9f761326 --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/ip6.h @@ -0,0 +1,179 @@ +/** + * @file + * + * IPv6 layer. + */ + +/* + * Copyright (c) 2010 Inico Technologies Ltd. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Ivan Delamer + * + * + * Please coordinate changes and requests with Ivan Delamer + * + */ +#ifndef LWIP_HDR_IP6_H +#define LWIP_HDR_IP6_H + +#include "lwip/opt.h" + +#if LWIP_IPV6 /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/ip6_addr.h" +#include "lwip/prot/ip6.h" +#include "lwip/def.h" +#include "lwip/pbuf.h" +#include "lwip/netif.h" + +#include "lwip/err.h" + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +/* \brief Destination and Hop By Hop extension headers option types */ +#define LWIP_EXT_HDR_OPT_PAD1 0 +#define LWIP_EXT_HDR_OPT_PADN 1 + +#define LWIP_RPL_RPI_TYPE_NEW 0x23 +#define LWIP_RPL_RPI_TYPE_OLD 0x63 + +#define LWIP_IPH_LEN 40 + +#define IP_PROTO_VERSION_6 6 + +/* + * brief is address a multicast address, see RFC 3513 + * a is of type uip_ipaddr_t* + */ +#define lwip_rpl_is_addr_mcast(a) ((a)->addr[0] == 0xFF000000) + +void ip6_process_destination_header_extension_options(struct pbuf *p, struct ip6_dest_hdr *opt_hdr, + u16_t hlen, u8_t *need_ip6_input_cleanup); + +struct netif *ip6_route(const ip6_addr_t *src, const ip6_addr_t *dest +#if LWIP_SO_DONTROUTE + , rt_scope_t scope +#endif + ); + + +/* + * @ingroup ip6 + * Select the best IPv6 source address for a given destination IPv6 address. + * + * This implementation follows RFC 6724 Sec. 5 to the following extent: + * - Rules 1, 2, 3: fully implemented + * - Rules 4, 5, 5.5: not applicable + * - Rule 6: not implemented + * - Rule 7: not applicable + * - Rule 8: limited to addresses with /64 addresses + * + * For Rule 2, we deliberately deviate from RFC 6724 Sec. 3.1 by considering + * ULAs to be of smaller scope than global addresses, to avoid that a preferred + * ULA is picked over a deprecated global address when given a global address + * as destination, as that would likely result in broken two-way communication. + * + * As long as temporary addresses are not supported (as used in Rule 7), a + * proper implementation of Rule 8 would obviate the need to implement Rule 6. + * + * @param netif the netif on which to send a packet + * @param dest the destination we are trying to reach (possibly not properly + * zoned) + * @return the most suitable source address to use, or NULL if no suitable + * source address is found + */ +const ip_addr_t *ip6_select_source_address(struct netif *netif, const ip6_addr_t *dest); + +const ip6_addr_t *ip6_select_first_valid_address(struct netif *netif); + +/* + * @ingroup ip6 + * Compute the number of common network prefix bits between two IPv6 addresses + * + * @param addr1 IPv6 Address 1 + * @param addr2 IPv6 Address 2 + * @param prefix_length Length of network prefix(in bits) + * @return + * Number of common prefix bits in addr1 & addr2 : On success + * -1 : Invalid parameters + */ +int ip6_common_prefix_length(const ip6_addr_t *addr1, const ip6_addr_t *addr2, u8_t prefix_length); + + +err_t ip6_input(struct pbuf *p, struct netif *inp); +#if LWIP_API_RICH +err_t ip6_output(struct pbuf *p, const ip6_addr_t *src, const ip6_addr_t *dest, + u8_t hl, u8_t tc, u8_t nexth, struct ip_pcb *pcb); +#endif /* LWIP_API_RICH */ +err_t ip6_output_if(struct pbuf *p, const ip6_addr_t *src, const ip6_addr_t *dest, + u8_t hl, u8_t tc, u8_t nexth, struct netif *netif); +err_t ip6_output_if_src(struct pbuf *p, const ip6_addr_t *src, const ip6_addr_t *dest, + u8_t hl, u8_t tc, u8_t nexth, struct netif *netif); +#if LWIP_NETIF_USE_HINTS +err_t ip6_output_hinted(struct pbuf *p, const ip6_addr_t *src, const ip6_addr_t *dest, + u8_t hl, u8_t tc, u8_t nexth, struct netif_hint *netif_hint); +#endif /* LWIP_NETIF_USE_HINTS */ +#if LWIP_IPV6_MLD +err_t ip6_options_add_hbh_ra(struct pbuf *p, u8_t nexth, u8_t value); +#endif /* LWIP_IPV6_MLD */ + +#define ip6_netif_get_local_ip(netif, dest) (((netif) != NULL) ? \ + ip6_select_source_address(netif, dest) : NULL) + +#if IP6_DEBUG +void ip6_debug_print(struct pbuf *p); +#else +#define ip6_debug_print(p) (void)0 +#endif /* IP6_DEBUG */ + +#if LWIP_RPL || LWIP_RIPPLE +int lwip_get_pkt_route_status(void); + +void lwip_set_pkt_route_status(int up); + +int lwip_get_rte_nexthop_nonmesh(void); + +void lwip_set_rte_nexthop_nonmesh(int stat); + +/* For accessing hardcoded hbh_len. */ +u16_t lwip_hbh_len(struct pbuf *p); +#endif /* LWIP_RPL || LWIP_RIPPLE */ + +#if LWIP_RPL +struct pbuf *lwip_add_rpi_hdr(struct pbuf *p, u8_t nexth, u16_t hbh_len, u8_t flags); +#endif + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_IPV6 */ + +#endif /* LWIP_HDR_IP6_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/ip6_addr.h b/sdk_liteos/third_party/lwip_sack/include/lwip/ip6_addr.h new file mode 100644 index 0000000000000000000000000000000000000000..5b71bcf243e3388954fb064bf517d178dd3e7c33 --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/ip6_addr.h @@ -0,0 +1,439 @@ +/** + * @file + * + * IPv6 addresses. + */ + +/* + * Copyright (c) 2010 Inico Technologies Ltd. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Ivan Delamer + * + * Structs and macros for handling IPv6 addresses. + * + * Please coordinate changes and requests with Ivan Delamer + * + */ +#ifndef LWIP_HDR_IP6_ADDR_H +#define LWIP_HDR_IP6_ADDR_H + +#include "lwip/opt.h" +#include "def.h" + +#if LWIP_IPV6 /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/ip6_zone.h" + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +#define IP6_ADDR_U32_ARR_SIZE 4 + +/** This is the aligned version of ip6_addr_t, + used as local variable, on the stack, etc. */ +struct ip6_addr { + u32_t addr[IP6_ADDR_U32_ARR_SIZE]; +#if LWIP_IPV6_SCOPES + u8_t zone; +#endif /* LWIP_IPV6_SCOPES */ +}; + +/** IPv6 address */ +typedef struct ip6_addr ip6_addr_t; + +/** Set an IPv6 partial address given by byte-parts */ +#define IP6_ADDR_PART(ip6addr, index, a, b, c, d) \ + (ip6addr)->addr[index] = PP_HTONL(LWIP_MAKEU32(a, b, c, d)) + +/** Set a full IPv6 address by passing the 4 u32_t indices in network byte order + (use PP_HTONL() for constants) */ +#define IP6_ADDR(ip6addr, idx0, idx1, idx2, idx3) do { \ + (ip6addr)->addr[0] = idx0; \ + (ip6addr)->addr[1] = idx1; \ + (ip6addr)->addr[2] = idx2; \ + (ip6addr)->addr[3] = idx3; \ + ip6_addr_clear_zone(ip6addr); } while(0) + +/** Access address in 16-bit block */ +#define IP6_ADDR_BLOCK1(ip6addr) ((u16_t)((lwip_htonl((ip6addr)->addr[0]) >> 16) & 0xffff)) +/** Access address in 16-bit block */ +#define IP6_ADDR_BLOCK2(ip6addr) ((u16_t)((lwip_htonl((ip6addr)->addr[0])) & 0xffff)) +/** Access address in 16-bit block */ +#define IP6_ADDR_BLOCK3(ip6addr) ((u16_t)((lwip_htonl((ip6addr)->addr[1]) >> 16) & 0xffff)) +/** Access address in 16-bit block */ +#define IP6_ADDR_BLOCK4(ip6addr) ((u16_t)((lwip_htonl((ip6addr)->addr[1])) & 0xffff)) +/** Access address in 16-bit block */ +#define IP6_ADDR_BLOCK5(ip6addr) ((u16_t)((lwip_htonl((ip6addr)->addr[2]) >> 16) & 0xffff)) +/** Access address in 16-bit block */ +#define IP6_ADDR_BLOCK6(ip6addr) ((u16_t)((lwip_htonl((ip6addr)->addr[2])) & 0xffff)) +/** Access address in 16-bit block */ +#define IP6_ADDR_BLOCK7(ip6addr) ((u16_t)((lwip_htonl((ip6addr)->addr[3]) >> 16) & 0xffff)) +/** Access address in 16-bit block */ +#define IP6_ADDR_BLOCK8(ip6addr) ((u16_t)((lwip_htonl((ip6addr)->addr[3])) & 0xffff)) + +#if LWIP_SMALL_SIZE +extern const ip6_addr_t ip6_addr_none; +extern const ip6_addr_t ip6_addr_loopback; +extern const ip6_addr_t ip6_addr_allnodes_iflocal; +extern const ip6_addr_t ip6_addr_allnodes_linklocal; +extern const ip6_addr_t ip6_addr_allrpl_nodes_linklocal; +extern const ip6_addr_t ip6_addr_mpl_ip4_bcast; +extern const ip6_addr_t ip6_addr_allrouters_linklocal; +void ip6_addr_set_fun(ip6_addr_t *dest, ip6_addr_t* src); +#endif + +/** Copy IPv6 address - faster than ip6_addr_set: no NULL check */ +#define ip6_addr_copy(dest, src) do { (dest).addr[0] = (src).addr[0]; \ + (dest).addr[1] = (src).addr[1]; \ + (dest).addr[2] = (src).addr[2]; \ + (dest).addr[3] = (src).addr[3]; \ + ip6_addr_copy_zone((dest), (src)); }while(0) +#define ip6_addr_copy_ptr(dest, src) do { (dest)->addr[0] = (src)->addr[0]; \ + (dest)->addr[1] = (src)->addr[1]; \ + (dest)->addr[2] = (src)->addr[2]; \ + (dest)->addr[3] = (src)->addr[3]; } while (0) + +/** Safely copy one IPv6 address to another (src may be NULL) */ +#if LWIP_SMALL_SIZE +#define ip6_addr_set(dest, src) ip6_addr_set_fun((ip6_addr_t *)dest, (ip6_addr_t *)src) +#else +#define ip6_addr_set(dest, src) do { (dest)->addr[0] = (src) == (void *)NULL ? 0 : (src)->addr[0]; \ + (dest)->addr[1] = (src) == (void *)NULL ? 0 : (src)->addr[1]; \ + (dest)->addr[2] = (src) == (void *)NULL ? 0 : (src)->addr[2]; \ + (dest)->addr[3] = (src) == (void *)NULL ? 0 : (src)->addr[3]; \ + ip6_addr_set_zone((dest), (src) == NULL ? IP6_NO_ZONE : ip6_addr_zone(src)); } while (0) +#endif + +#define ip6_addr_set_val(dest, src) do { (dest)->addr[0] = (src)->addr[0]; \ + (dest)->addr[1] = (src)->addr[1]; \ + (dest)->addr[2] = (src)->addr[2]; \ + (dest)->addr[3] = (src)->addr[3]; \ + ip6_addr_set_zone((dest), ip6_addr_zone(src)); } while (0) + +/** Copy packed IPv6 address to unpacked IPv6 address; zone is not set */ +#define ip6_addr_copy_from_packed(dest, src) do{(dest).addr[0] = (src).addr[0]; \ + (dest).addr[1] = (src).addr[1]; \ + (dest).addr[2] = (src).addr[2]; \ + (dest).addr[3] = (src).addr[3]; \ + ip6_addr_clear_zone(&dest); }while(0) + +/** Copy unpacked IPv6 address to packed IPv6 address; zone is lost */ +#define ip6_addr_copy_to_packed(dest, src) do{(dest).addr[0] = (src).addr[0]; \ + (dest).addr[1] = (src).addr[1]; \ + (dest).addr[2] = (src).addr[2]; \ + (dest).addr[3] = (src).addr[3]; }while(0) + +/** Set complete address to zero */ +#define ip6_addr_set_zero(ip6addr) do { (ip6addr)->addr[0] = 0; \ + (ip6addr)->addr[1] = 0; \ + (ip6addr)->addr[2] = 0; \ + (ip6addr)->addr[3] = 0; \ + ip6_addr_clear_zone(ip6addr); } while (0) + +/** Set address to ipv6 'any' (no need for lwip_htonl()) */ +#define ip6_addr_set_any(ip6addr) ip6_addr_set_zero(ip6addr) +/** Set address to ipv6 loopback address */ +#define ip6_addr_set_loopback(ip6addr) do { (ip6addr)->addr[0] = 0; \ + (ip6addr)->addr[1] = 0; \ + (ip6addr)->addr[2] = 0; \ + (ip6addr)->addr[3] = PP_HTONL(0x00000001UL); \ + ip6_addr_clear_zone(ip6addr); } while (0) +/** Safely copy one IPv6 address to another and change byte order + * from host- to network-order. */ +#define ip6_addr_set_hton(dest, src) do { (dest)->addr[0] = (src) == NULL ? 0 : lwip_htonl((src)->addr[0]); \ + (dest)->addr[1] = (src) == NULL ? 0 : lwip_htonl((src)->addr[1]); \ + (dest)->addr[2] = (src) == NULL ? 0 : lwip_htonl((src)->addr[2]); \ + (dest)->addr[3] = (src) == NULL ? 0 : lwip_htonl((src)->addr[3]); \ + ip6_addr_set_zone((dest), (src) == NULL ? IP6_NO_ZONE : ip6_addr_zone(src)); } while (0) + +#if defined(LWIP_RA_PREFIX_DYNAMIC) && LWIP_RA_PREFIX_DYNAMIC +#define LWIP_RA_PREFIX_LONG 80 +#endif + +/** Compare IPv6 networks, ignoring zone information. To be used sparingly! */ +#define ip6_addr_netcmp_zoneless(addr1, addr2) (((addr1)->addr[0] == (addr2)->addr[0]) && \ + ((addr1)->addr[1] == (addr2)->addr[1])) + +/** + * Determine if two IPv6 address are on the same network. + * + * @param addr1 IPv6 address 1 + * @param addr2 IPv6 address 2 + * @return 1 if the network identifiers of both address match, 0 if not + */ +#define ip6_addr_netcmp(addr1, addr2) (ip6_addr_netcmp_zoneless((addr1), (addr2)) && \ + ip6_addr_cmp_zone((addr1), (addr2))) + +/* Exact-host comparison *after* ip6_addr_netcmp() succeeded, for efficiency. */ +#define ip6_addr_nethostcmp(addr1, addr2) (((addr1)->addr[2] == (addr2)->addr[2]) && \ + ((addr1)->addr[3] == (addr2)->addr[3])) + +#define ip6_addr_prefix_netcmp(addr1, addr2, len) (((len) > 0) ? (memcmp((addr1), (addr2), (len)) == 0) : \ + ip6_addr_netcmp((addr1), (addr2))) + +/** Compare IPv6 addresses, ignoring zone information. To be used sparingly! */ +#define ip6_addr_cmp_zoneless(addr1, addr2) (((addr1)->addr[0] == (addr2)->addr[0]) && \ + ((addr1)->addr[1] == (addr2)->addr[1]) && \ + ((addr1)->addr[2] == (addr2)->addr[2]) && \ + ((addr1)->addr[3] == (addr2)->addr[3])) + +/** + * Determine if two IPv6 addresses are the same. In particular, the address + * part of both must be the same, and the zone must be compatible. + * + * @param addr1 IPv6 address 1 + * @param addr2 IPv6 address 2 + * @return 1 if the addresses are considered equal, 0 if not + */ +#define ip6_addr_cmp(addr1, addr2) (ip6_addr_cmp_zoneless((addr1), (addr2)) && \ + ip6_addr_cmp_zone((addr1), (addr2))) + +/** Compare IPv6 address to packed address and zone */ +#define ip6_addr_cmp_packed(ip6addr, paddr, zone_idx) (((ip6addr)->addr[0] == (paddr)->addr[0]) && \ + ((ip6addr)->addr[1] == (paddr)->addr[1]) && \ + ((ip6addr)->addr[2] == (paddr)->addr[2]) && \ + ((ip6addr)->addr[3] == (paddr)->addr[3]) && \ + ip6_addr_equals_zone((ip6addr), (zone_idx))) + +#define ip6_get_subnet_id(ip6addr) (lwip_htonl((ip6addr)->addr[2]) & 0x0000ffffUL) + +#if LWIP_SMALL_SIZE +#define ip6_addr_isany_val(ip6addr) (memcmp(&ip6addr, ip_2_ip6(&ip6_addr_any), sizeof(ip6_addr_t)) == 0) +#define ip6_addr_isnone_val(ip6addr) (memcmp(&ip6addr, &ip6_addr_none, sizeof(ip6_addr_t)) == 0) +#else +#define ip6_addr_isany_val(ip6addr) (((ip6addr).addr[0] == 0) && \ + ((ip6addr).addr[1] == 0) && \ + ((ip6addr).addr[2] == 0) && \ + ((ip6addr).addr[3] == 0)) +#define ip6_addr_isnone_val(ip6addr) (((ip6addr).addr[0] == 0xffffffffUL) && \ + ((ip6addr).addr[1] == 0xffffffffUL) && \ + ((ip6addr).addr[2] == 0xffffffffUL) && \ + ((ip6addr).addr[3] == 0xffffffffUL)) +#endif +#define ip6_addr_isany(ip6addr) (((ip6addr) == NULL) || ip6_addr_isany_val(*(ip6addr))) +#define ip6_addr_isnone(ip6addr) (((ip6addr) == NULL) || ip6_addr_isnone_val(*(ip6addr))) +#if LWIP_SMALL_SIZE +#define ip6_addr_isloopback(ip6addr) (memcmp(ip6addr, &ip6_addr_loopback, sizeof(ip6_addr_t)) == 0) +#else +#define ip6_addr_isloopback(ip6addr) (((ip6addr)->addr[0] == 0UL) && \ + ((ip6addr)->addr[1] == 0UL) && \ + ((ip6addr)->addr[2] == 0UL) && \ + ((ip6addr)->addr[3] == PP_HTONL(0x00000001UL))) +#endif +#define ip6_addr_isglobal(ip6addr) (((ip6addr)->addr[0] & PP_HTONL(0xe0000000UL)) == PP_HTONL(0x20000000UL)) + +#define ip6_addr_islinklocal(ip6addr) (((ip6addr)->addr[0] & PP_HTONL(0xffc00000UL)) == PP_HTONL(0xfe800000UL)) + +#define ip6_addr_issitelocal(ip6addr) (((ip6addr)->addr[0] & PP_HTONL(0xffc00000UL)) == PP_HTONL(0xfec00000UL)) + +#define ip6_addr_isuniquelocal(ip6addr) (((ip6addr)->addr[0] & PP_HTONL(0xfe000000UL)) == PP_HTONL(0xfc000000UL)) + +#define ip6_addr_isipv4mappedipv6(ip6addr) \ + (((ip6addr)->addr[0] == 0) && ((ip6addr)->addr[1] == 0) && \ + (((ip6addr)->addr[2]) == PP_HTONL(0x0000FFFFUL))) +#define ip6_addr_isipv4compatible(ip6addr) \ + (((ip6addr)->addr[0] == 0) && ((ip6addr)->addr[1] == 0) && \ + ((ip6addr)->addr[2] == 0) && (PP_NTOHL((ip6addr)->addr[3]) > 1)) + +#define ip6_addr_ismulticast(ip6addr) (((ip6addr)->addr[0] & PP_HTONL(0xff000000UL)) == PP_HTONL(0xff000000UL)) +#define ip6_addr_link_local_ismulticast(ip6addr) \ + (((ip6addr)->addr[0] & PP_HTONL(0xff020000UL)) == PP_HTONL(0xff020000UL)) +#define ip6_addr_multicast_transient_flag(ip6addr) ((ip6addr)->addr[0] & PP_HTONL(0x00100000UL)) +#define ip6_addr_multicast_prefix_flag(ip6addr) ((ip6addr)->addr[0] & PP_HTONL(0x00200000UL)) +#define ip6_addr_multicast_rendezvous_flag(ip6addr) ((ip6addr)->addr[0] & PP_HTONL(0x00400000UL)) +#define ip6_addr_multicast_scope(ip6addr) ((lwip_htonl((ip6addr)->addr[0]) >> 16) & 0xf) +#define IP6_MULTICAST_SCOPE_RESERVED 0x0 +#define IP6_MULTICAST_SCOPE_RESERVED0 0x0 +#define IP6_MULTICAST_SCOPE_INTERFACE_LOCAL 0x1 +#define IP6_MULTICAST_SCOPE_LINK_LOCAL 0x2 +#define IP6_MULTICAST_SCOPE_RESERVED3 0x3 +#define IP6_MULTICAST_SCOPE_ADMIN_LOCAL 0x4 +#define IP6_MULTICAST_SCOPE_SITE_LOCAL 0x5 +#define IP6_MULTICAST_SCOPE_ORGANIZATION_LOCAL 0x8 +#define IP6_MULTICAST_SCOPE_GLOBAL 0xe +#define IP6_MULTICAST_SCOPE_RESERVEDF 0xf + +#define ip6_addr_ismulticast_reserved_scope(ip6addr) \ + (((ip6addr)->addr[0] & PP_HTONL(0xff8f0000UL)) == PP_HTONL(0xff000000UL)) +#define ip6_addr_ismulticast_iflocal(ip6addr) (((ip6addr)->addr[0] & PP_HTONL(0xff8f0000UL)) == PP_HTONL(0xff010000UL)) +#define ip6_addr_ismulticast_linklocal(ip6addr) (((ip6addr)->addr[0] & PP_HTONL(0xff8f0000UL)) == PP_HTONL(0xff020000UL)) +#define ip6_addr_ismulticast_adminlocal(ip6addr) (((ip6addr)->addr[0] & PP_HTONL(0xff8f0000UL)) == PP_HTONL(0xff040000UL)) +#define ip6_addr_ismulticast_sitelocal(ip6addr) (((ip6addr)->addr[0] & PP_HTONL(0xff8f0000UL)) == PP_HTONL(0xff050000UL)) +#define ip6_addr_ismulticast_orglocal(ip6addr) (((ip6addr)->addr[0] & PP_HTONL(0xff8f0000UL)) == PP_HTONL(0xff080000UL)) +#define ip6_addr_ismulticast_global(ip6addr) (((ip6addr)->addr[0] & PP_HTONL(0xff8f0000UL)) == PP_HTONL(0xff0e0000UL)) + +/* Scoping note: while interface-local and link-local multicast addresses do + * have a scope (i.e., they are meaningful only in the context of a particular + * interface), the following functions are not assigning or comparing zone + * indices. The reason for this is backward compatibility. Any call site that + * produces a non-global multicast address must assign a multicast address as + * appropriate itself. */ +#if LWIP_SMALL_SIZE && !LWIP_IPV6_SCOPES +#define ip6_addr_isallnodes_iflocal(ip6addr) \ + (memcmp(ip6addr, &ip6_addr_allnodes_iflocal, sizeof(ip6_addr_t)) == 0) +#define ip6_addr_isallnodes_linklocal(ip6addr) \ + (memcmp(ip6addr, &ip6_addr_allnodes_linklocal, sizeof(ip6_addr_t)) == 0) +#define ip6_addr_isallrpl_nodes_linklocal(ip6addr) \ + (memcmp(ip6addr, &ip6_addr_allrpl_nodes_linklocal, sizeof(ip6_addr_t)) == 0) +#define ip6_addr_is_mpl_ip4_bcast(ip6addr) \ + (memcmp(ip6addr, &ip6_addr_mpl_ip4_bcast, sizeof(ip6_addr_t)) == 0) +#else +#define ip6_addr_isallnodes_iflocal(ip6addr) (((ip6addr)->addr[0] == PP_HTONL(0xff010000UL)) && \ + ((ip6addr)->addr[1] == 0UL) && \ + ((ip6addr)->addr[2] == 0UL) && \ + ((ip6addr)->addr[3] == PP_HTONL(0x00000001UL))) + +#define ip6_addr_isallnodes_linklocal(ip6addr) (((ip6addr)->addr[0] == PP_HTONL(0xff020000UL)) && \ + ((ip6addr)->addr[1] == 0UL) && \ + ((ip6addr)->addr[2] == 0UL) && \ + ((ip6addr)->addr[3] == PP_HTONL(0x00000001UL))) + +#define ip6_addr_isallrpl_nodes_linklocal(ip6addr) (((ip6addr)->addr[0] == PP_HTONL(0xff020000UL)) && \ + ((ip6addr)->addr[1] == 0UL) && \ + ((ip6addr)->addr[2] == 0UL) && \ + ((ip6addr)->addr[3] == PP_HTONL(0x0000001aUL))) + +#define ip6_addr_is_mpl_ip4_bcast(ip6addr) (((ip6addr)->addr[0] == PP_HTONL(0xff130000UL)) && \ + ((ip6addr)->addr[1] == 0UL) && \ + ((ip6addr)->addr[2] == 0UL) && \ + ((ip6addr)->addr[3] == PP_HTONL(0x000000fcUL))) +#endif + +#define ip6_addr_set_mpl_ip4_bcast(ip6addr) do { (ip6addr)->addr[0] = PP_HTONL(0xff130000UL); \ + (ip6addr)->addr[1] = 0UL; \ + (ip6addr)->addr[2] = 0UL; \ + (ip6addr)->addr[3] = PP_HTONL(0x000000fcUL); } while (0) + +#define ip6_addr_set_allnodes_linklocal(ip6addr) do { (ip6addr)->addr[0] = PP_HTONL(0xff020000UL); \ + (ip6addr)->addr[1] = 0; \ + (ip6addr)->addr[2] = 0; \ + (ip6addr)->addr[3] = PP_HTONL(0x00000001UL); \ + ip6_addr_clear_zone(ip6addr); } while (0) + +#if LWIP_SMALL_SIZE +#define ip6_addr_isallrouters_linklocal(ip6addr) \ + (memcmp(ip6addr, &ip6_addr_allrouters_linklocal, sizeof(ip6_addr_t)) == 0) +#else +#define ip6_addr_isallrouters_linklocal(ip6addr) (((ip6addr)->addr[0] == PP_HTONL(0xff020000UL)) && \ + ((ip6addr)->addr[1] == 0UL) && \ + ((ip6addr)->addr[2] == 0UL) && \ + ((ip6addr)->addr[3] == PP_HTONL(0x00000002UL))) +#endif +#define ip6_addr_set_allrouters_linklocal(ip6addr) do { (ip6addr)->addr[0] = PP_HTONL(0xff020000UL); \ + (ip6addr)->addr[1] = 0; \ + (ip6addr)->addr[2] = 0; \ + (ip6addr)->addr[3] = PP_HTONL(0x00000002UL); \ + ip6_addr_clear_zone(ip6addr); }while (0) + +#define ip6_addr_issolicitednode(ip6addr) (((ip6addr)->addr[0] == PP_HTONL(0xff020000UL)) && \ + ((ip6addr)->addr[2] == PP_HTONL(0x00000001UL)) && \ + (((ip6addr)->addr[3] & PP_HTONL(0xff000000UL)) == PP_HTONL(0xff000000UL))) + +#define ip6_addr_set_solicitednode(ip6addr, if_id) do { (ip6addr)->addr[0] = PP_HTONL(0xff020000UL); \ + (ip6addr)->addr[1] = 0; \ + (ip6addr)->addr[2] = PP_HTONL(0x00000001UL); \ + (ip6addr)->addr[3] = (PP_HTONL(0xff000000UL) | (if_id)); \ + ip6_addr_clear_zone(ip6addr); } while (0) + +#define ip6_addr_cmp_solicitednode(ip6addr, sn_addr) (((ip6addr)->addr[0] == PP_HTONL(0xff020000UL)) && \ + ((ip6addr)->addr[1] == 0) && \ + ((ip6addr)->addr[2] == PP_HTONL(0x00000001UL)) && \ + ((ip6addr)->addr[3] == (PP_HTONL(0xff000000UL) | (sn_addr)->addr[3]))) + +#define lwip_lladdr_cmp(addr1, addr2, len) (memcmp(addr1, addr2, len) == 0) + +/* IPv6 address states. */ +#define IP6_ADDR_INVALID 0x00 +#define IP6_ADDR_TENTATIVE 0x08 +#define IP6_ADDR_TENTATIVE_1 0x09 /* 1 probe sent */ +#define IP6_ADDR_TENTATIVE_2 0x0a /* 2 probes sent */ +#define IP6_ADDR_TENTATIVE_3 0x0b /* 3 probes sent */ +#define IP6_ADDR_TENTATIVE_4 0x0c /* 4 probes sent */ +#define IP6_ADDR_TENTATIVE_5 0x0d /* 5 probes sent */ +#define IP6_ADDR_TENTATIVE_6 0x0e /* 6 probes sent */ +#define IP6_ADDR_TENTATIVE_7 0x0f /* 7 probes sent */ +#define IP6_ADDR_VALID 0x10 /* This bit marks an address as valid (preferred or deprecated) */ +#define IP6_ADDR_PREFERRED 0x30 +#define IP6_ADDR_DEPRECATED 0x10 /* Same as VALID (valid but not preferred) */ +#define IP6_ADDR_DUPLICATED 0x40 /* Failed DAD test, not valid */ + +#define IP6_ADDR_TENTATIVE_COUNT_MASK 0x07 /* 1-7 probes sent */ + +#define ip6_addr_isinvalid(addr_state) (addr_state == IP6_ADDR_INVALID) +#define ip6_addr_istentative(addr_state) (addr_state & IP6_ADDR_TENTATIVE) +#define ip6_addr_isvalid(addr_state) (addr_state & IP6_ADDR_VALID) /* Include valid, preferred, and deprecated. */ +#define ip6_addr_ispreferred(addr_state) (addr_state == IP6_ADDR_PREFERRED) +#define ip6_addr_isdeprecated(addr_state) (addr_state == IP6_ADDR_DEPRECATED) +#define ip6_addr_isduplicated(addr_state) (addr_state == IP6_ADDR_DUPLICATED) + +#if LWIP_IPV6_ADDRESS_LIFETIMES +#define IP6_ADDR_LIFE_STATIC (0) +#define IP6_ADDR_LIFE_INFINITE (0xffffffffUL) +#define ip6_addr_life_isstatic(addr_life) ((addr_life) == IP6_ADDR_LIFE_STATIC) +#define ip6_addr_life_isinfinite(addr_life) ((addr_life) == IP6_ADDR_LIFE_INFINITE) +#endif /* LWIP_IPV6_ADDRESS_LIFETIMES */ + +#define ip6_addr_debug_print_parts(debug, a, b, c, d, e, f, g, h) \ + LWIP_DEBUGF(debug, ("%" X16_F ":%" X16_F ":%" X16_F ":%" X16_F ":%" X16_F ":%" X16_F ":%" X16_F ":%" X16_F, \ + a, b, c, d, e, f, g, h)) +#define ip6_addr_debug_print(debug, ipaddr) \ + ip6_addr_debug_print_parts(debug, \ + (u16_t)((ipaddr) != NULL ? IP6_ADDR_BLOCK1(ipaddr) : 0), \ + (u16_t)((ipaddr) != NULL ? IP6_ADDR_BLOCK2(ipaddr) : 0), \ + (u16_t)((ipaddr) != NULL ? IP6_ADDR_BLOCK3(ipaddr) : 0), \ + (u16_t)((ipaddr) != NULL ? IP6_ADDR_BLOCK4(ipaddr) : 0), \ + (u16_t)((ipaddr) != NULL ? IP6_ADDR_BLOCK5(ipaddr) : 0), \ + (u16_t)((ipaddr) != NULL ? IP6_ADDR_BLOCK6(ipaddr) : 0), \ + (u16_t)((ipaddr) != NULL ? IP6_ADDR_BLOCK7(ipaddr) : 0), \ + (u16_t)((ipaddr) != NULL ? IP6_ADDR_BLOCK8(ipaddr) : 0)) +#define ip6_addr_debug_print_val(debug, ipaddr) \ + ip6_addr_debug_print_parts(debug, \ + IP6_ADDR_BLOCK1(&(ipaddr)), \ + IP6_ADDR_BLOCK2(&(ipaddr)), \ + IP6_ADDR_BLOCK3(&(ipaddr)), \ + IP6_ADDR_BLOCK4(&(ipaddr)), \ + IP6_ADDR_BLOCK5(&(ipaddr)), \ + IP6_ADDR_BLOCK6(&(ipaddr)), \ + IP6_ADDR_BLOCK7(&(ipaddr)), \ + IP6_ADDR_BLOCK8(&(ipaddr))) + +#define IP6ADDR_STRLEN_MAX 46 + +int ip6addr_aton(const char *cp, ip6_addr_t *addr); +/** returns ptr to static buffer; not reentrant! */ +char *ip6addr_ntoa(const ip6_addr_t *addr); +char *ip6addr_ntoa_r(const ip6_addr_t *addr, char *buf, int buflen); + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_IPV6 */ + +#endif /* LWIP_HDR_IP6_ADDR_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/ip6_frag.h b/sdk_liteos/third_party/lwip_sack/include/lwip/ip6_frag.h new file mode 100644 index 0000000000000000000000000000000000000000..a2e35cfad55d673ec69291623cca8233ad8dd43a --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/ip6_frag.h @@ -0,0 +1,148 @@ +/** + * @file + * + * IPv6 fragmentation and reassembly. + */ + +/* + * Copyright (c) 2010 Inico Technologies Ltd. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Ivan Delamer + * + * + * Please coordinate changes and requests with Ivan Delamer + * + */ +#ifndef LWIP_HDR_IP6_FRAG_H +#define LWIP_HDR_IP6_FRAG_H + +#include "lwip/opt.h" +#include "lwip/pbuf.h" +#include "lwip/ip6_addr.h" +#include "lwip/ip6.h" +#include "lwip/netif.h" + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +#if LWIP_IPV6 && LWIP_IPV6_REASS /* don't build if not configured for use in lwipopts.h */ + +/** The IPv6 reassembly timer interval in milliseconds. */ +#define IP6_REASS_TMR_INTERVAL 1000 + +/** IP6_FRAG_COPYHEADER==1: for platforms where sizeof(void*) > 4, "struct + * ip6_reass_helper" is too large to be stored in the IPv6 fragment header, and + * will bleed into the header before it, which may be the IPv6 header or an + * extension header. This means that for each first fragment packet, we need to + * 1) make a copy of some IPv6 header fields (src+dest) that we need later on, + * just in case we do overwrite part of the IPv6 header, and 2) make a copy of + * the header data that we overwrote, so that we can restore it before either + * completing reassembly or sending an ICMPv6 reply. The last part is true even + * if this setting is disabled, but if it is enabled, we need to save a bit + * more data (up to the size of a pointer) because we overwrite more. */ +#ifndef IPV6_FRAG_COPYHEADER +#define IPV6_FRAG_COPYHEADER 0 +#endif + +/* With IPV6_FRAG_COPYHEADER==1, a helper structure may (or, depending on the + * presence of extensions, may not) overwrite part of the IP header. Therefore, + * we copy the fields that we need from the IP header for as long as the helper + * structure may still be in place. This is easier than temporarily restoring + * those fields in the IP header each time we need to perform checks on them. */ +#if IPV6_FRAG_COPYHEADER +#define IPV6_FRAG_SRC(ipr) ((ipr)->src) +#define IPV6_FRAG_DEST(ipr) ((ipr)->dest) +#else /* IPV6_FRAG_COPYHEADER */ +#define IPV6_FRAG_SRC(ipr) ((ipr)->iphdr->src) +#define IPV6_FRAG_DEST(ipr) ((ipr)->iphdr->dest) +#endif /* IPV6_FRAG_COPYHEADER */ + +/* IPv6 reassembly helper struct. + * This is exported because memp needs to know the size. + */ +struct ip6_reassdata { + struct ip6_reassdata *next; + struct pbuf *p; + struct ip6_hdr *iphdr; /* pointer to the first (original) IPv6 header */ +#if IPV6_FRAG_COPYHEADER + ip6_addr_p_t src; /* copy of the source address in the IP header */ + ip6_addr_p_t dest; /* copy of the destination address in the IP header */ + /* This buffer (for the part of the original header that we overwrite) will + * be slightly oversized, but we cannot compute the exact size from here. */ + u8_t orig_hdr[sizeof(struct ip6_frag_hdr) + sizeof(void*)]; +#else /* IPV6_FRAG_COPYHEADER */ + /* In this case we still need the buffer, for sending ICMPv6 replies. */ + u8_t orig_hdr[sizeof(struct ip6_frag_hdr)]; +#endif /* IPV6_FRAG_COPYHEADER */ + u32_t identification; + u16_t datagram_len; + u8_t nexth; + u8_t timer; +#if LWIP_IPV6_SCOPES + u8_t src_zone; /* zone of original packet's source address */ + u8_t dest_zone; /* zone of original packet's destination address */ +#endif /* LWIP_IPV6_SCOPES */ + u32_t count; + u32_t len; +}; + +#define ip6_reass_init() /* Compatibility define */ +void ip6_reass_tmr(void); +struct pbuf *ip6_reass(struct pbuf *p); + +#if LWIP_LOWPOWER +u32_t ip6_reass_tmr_tick(void); +#endif + +#endif /* LWIP_IPV6 && LWIP_IPV6_REASS */ + +#if LWIP_IPV6 && LWIP_IPV6_FRAG /* don't build if not configured for use in lwipopts.h */ + +#ifndef LWIP_PBUF_CUSTOM_REF_DEFINED +#define LWIP_PBUF_CUSTOM_REF_DEFINED +/* A custom pbuf that holds a reference to another pbuf, which is freed + * when this custom pbuf is freed. This is used to create a custom PBUF_REF + * that points into the original pbuf. */ +struct pbuf_custom_ref { + /* 'base class' */ + struct pbuf_custom pc; + /* pointer to the original pbuf that is referenced */ + struct pbuf *original; +}; +#endif /* LWIP_PBUF_CUSTOM_REF_DEFINED */ + +err_t ip6_frag(struct pbuf *p, struct netif *netif, const ip6_addr_t *dest); + +#endif /* LWIP_IPV6 && LWIP_IPV6_FRAG */ + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_HDR_IP6_FRAG_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/ip6_zone.h b/sdk_liteos/third_party/lwip_sack/include/lwip/ip6_zone.h new file mode 100644 index 0000000000000000000000000000000000000000..516dc1475a3c6c2888b0141ea9cd4b2d2a59c24f --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/ip6_zone.h @@ -0,0 +1,285 @@ +/** + * @file + * + * IPv6 address scopes, zones, and scoping policy. + * + * This header provides the means to implement support for IPv6 address scopes, + * as per RFC 4007. An address scope can be either global or more constrained. + * In lwIP, we say that an address "has a scope" or "is scoped" when its scope + * is constrained, in which case the address is meaningful only in a specific + * "zone." For unicast addresses, only link-local addresses have a scope; in + * that case, the scope is the link. For multicast addresses, there are various + * scopes defined by RFC 4007 and others. For any constrained scope, a system + * must establish a (potentially one-to-many) mapping between zones and local + * interfaces. For example, a link-local address is valid on only one link (its + * zone). That link may be attached to one or more local interfaces. The + * decisions on which scopes are constrained and the mapping between zones and + * interfaces is together what we refer to as the "scoping policy" - more on + * this in a bit. + * + * In lwIP, each IPv6 address has an associated zone index. This zone index may + * be set to "no zone" (IP6_NO_ZONE, 0) or an actual zone. We say that an + * address "has a zone" or "is zoned" when its zone index is *not* set to "no + * zone." In lwIP, in principle, each address should be "properly zoned," which + * means that if the address has a zone if and only if has a scope. As such, it + * is a rule that an unscoped (e.g., global) address must never have a zone. + * Even though one could argue that there is always one zone even for global + * scopes, this rule exists for implementation simplicity. Violation of the + * rule will trigger assertions or otherwise result in undesired behavior. + * + * Backward compatibility prevents us from requiring that applications always + * provide properly zoned addresses. We do enforce the rule that the in the + * lwIP link layer (everything below netif->output_ip6() and in particular ND6) + * *all* addresses are properly zoned. Thus, on the output paths down the + * stack, various places deal with the case of addresses that lack a zone. + * Some of them are best-effort for efficiency (e.g. the PCB bind and connect + * API calls' attempts to add missing zones); ultimately the IPv6 output + * handler (@ref ip6_output_if_src) will set a zone if necessary. + * + * Aside from dealing with scoped addresses lacking a zone, a proper IPv6 + * implementation must also ensure that a packet with a scoped source and/or + * destination address does not leave its zone. This is currently implemented + * in the input and forward functions. However, for output, these checks are + * deliberately omitted in order to keep the implementation lightweight. The + * routing algorithm in @ref ip6_route will take decisions such that it will + * not cause zone violations unless the application sets bad addresses, though. + * + * In terms of scoping policy, lwIP implements the default policy from RFC 4007 + * using macros in this file. This policy considers link-local unicast + * addresses and (only) interface-local and link-local multicast addresses as + * having a scope. For all these addresses, the zone is equal to the interface. + * As shown below in this file, it is possible to implement a custom policy. + */ + +/* + * Copyright (c) 2017 The MINIX 3 Project. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: David van Moolenbroek + * + */ +#ifndef LWIP_HDR_IP6_ZONE_H +#define LWIP_HDR_IP6_ZONE_H + +#if LWIP_IPV6 /* don't build if not configured for use in lwipopts.h */ + +/** Identifier for "no zone". */ +#define IP6_NO_ZONE 0 + +#if LWIP_IPV6_SCOPES + +/** Zone initializer for static IPv6 address initialization, including comma. */ +#define IPADDR6_ZONE_INIT , IP6_NO_ZONE + +/** Return the zone index of the given IPv6 address; possibly "no zone". */ +#define ip6_addr_zone(ip6addr) ((ip6addr)->zone) + +/** Does the given IPv6 address have a zone set? (0/1) */ +#define ip6_addr_has_zone(ip6addr) (ip6_addr_zone(ip6addr) != IP6_NO_ZONE) + +/** Set the zone field of an IPv6 address to a particular value. */ +#define ip6_addr_set_zone(ip6addr, zone_idx) ((ip6addr)->zone = (zone_idx)) + +/** Clear the zone field of an IPv6 address, setting it to "no zone". */ +#define ip6_addr_clear_zone(ip6addr) ((ip6addr)->zone = IP6_NO_ZONE) + +/** Copy the zone field from the second IPv6 address to the first one. */ +#define ip6_addr_copy_zone(ip6addr1, ip6addr2) ((ip6addr1).zone = (ip6addr2).zone) + +/** Is the zone field of the given IPv6 address equal to the given zone index? (0/1) */ +#define ip6_addr_equals_zone(ip6addr, zone_idx) ((ip6addr)->zone == (zone_idx)) + +/** Are the zone fields of the given IPv6 addresses equal? (0/1) + * This macro must only be used on IPv6 addresses of the same scope. */ +#define ip6_addr_cmp_zone(ip6addr1, ip6addr2) ((ip6addr1)->zone == (ip6addr2)->zone) + +/** Symbolic constants for the 'type' parameters in some of the macros below. + * These exist for efficiency only, allowing the macros to avoid certain tests + * when the address is known not to be of a certain type. Dead code elimination + * will do the rest. IP6_MULTICAST is supported but currently not optimized. */ +#define IP6_UNKNOWN 0 +#define IP6_UNICAST 1 +#define IP6_MULTICAST 2 + +/** IPV6_CUSTOM_SCOPES: together, the following three macro definitions, + * @ref ip6_addr_has_scope, @ref ip6_addr_assign_zone, and + * @ref ip6_addr_test_zone, completely define the lwIP scoping policy. + * The definitions below implement the default policy from RFC 4007 Sec. 6. + * Should an implementation desire to implement a different policy, it can + * define IPV6_CUSTOM_SCOPES to 1 and supply its own definitions for the three + * macros instead. + */ +#ifndef IPV6_CUSTOM_SCOPES +#define IPV6_CUSTOM_SCOPES 0 +#endif /* !IPV6_CUSTOM_SCOPES */ + +#if !IPV6_CUSTOM_SCOPES + +/** + * Determine whether an IPv6 address has a constrained scope, and as such is + * meaningful only if accompanied by a zone index to identify the scope's zone. + * The given address type may be used to eliminate at compile time certain + * checks that will evaluate to false at run time anyway. + * + * This default implementation follows the default model of RFC 4007, where + * only interface-local and link-local scopes are defined. + * + * Even though the unicast loopback address does have an implied link-local + * scope, in this implementation it does not have an explicitly assigned zone + * index. As such it should not be tested for in this macro. + * + * @param ip6addr the IPv6 address (const); only its address part is examined. + * @param type address type; one of IP6_UNICAST, IP6_MULTICAST, IP6_UNKNOWN. + * @return 1 if the address has a constrained scope, 0 if it does not. + */ +#define ip6_addr_has_scope(ip6addr, type) \ + (ip6_addr_islinklocal(ip6addr) || (((type) != IP6_UNICAST) && \ + (ip6_addr_ismulticast_iflocal(ip6addr) || \ + ip6_addr_ismulticast_linklocal(ip6addr)))) + +/** + * Assign a zone index to an IPv6 address, based on a network interface. If the + * given address has a scope, the assigned zone index is that scope's zone of + * the given netif; otherwise, the assigned zone index is "no zone". + * + * This default implementation follows the default model of RFC 4007, where + * only interface-local and link-local scopes are defined, and the zone index + * of both of those scopes always equals the index of the network interface. + * As such, this default implementation need not distinguish between different + * constrained scopes when assigning the zone. + * + * @param ip6addr the IPv6 address; its address part is examined, and its zone + * index is assigned. + * @param type address type; one of IP6_UNICAST, IP6_MULTICAST, IP6_UNKNOWN. + * @param netif the network interface (const). + */ +#define ip6_addr_assign_zone(ip6addr, type, netif) \ + (ip6_addr_set_zone((ip6addr), \ + ip6_addr_has_scope((ip6addr), (type)) ? netif->ifindex : 0)) + +/** + * Test whether an IPv6 address is "zone-compatible" with a network interface. + * That is, test whether the network interface is part of the zone associated + * with the address. For efficiency, this macro is only ever called if the + * given address is either scoped or zoned, and thus, it need not test this. + * If an address is scoped but not zoned, or zoned and not scoped, it is + * considered not zone-compatible with any netif. + * + * This default implementation follows the default model of RFC 4007, where + * only interface-local and link-local scopes are defined, and the zone index + * of both of those scopes always equals the index of the network interface. + * As such, there is always only one matching netif for a specific zone index, + * but all call sites of this macro currently support multiple matching netifs + * as well (at no additional expense in the common case). + * + * @param ip6addr the IPv6 address (const). + * @param netif the network interface (const). + * @return 1 if the address is scope-compatible with the netif, 0 if not. + */ +#define ip6_addr_test_zone(ip6addr, netif) \ + (ip6_addr_equals_zone((ip6addr), netif->ifindex)) + +#endif /* !IPV6_CUSTOM_SCOPES */ + +/** Does the given IPv6 address have a scope, and as such should also have a + * zone to be meaningful, but does not actually have a zone? (0/1) */ +#define ip6_addr_lacks_zone(ip6addr, type) \ + (!ip6_addr_has_zone(ip6addr) && ip6_addr_has_scope((ip6addr), (type))) + +/** + * Try to select a zone for a scoped address that does not yet have a zone. + * Called from PCB bind and connect routines, for two reasons: 1) to save on + * this (relatively expensive) selection for every individual packet route + * operation and 2) to allow the application to obtain the selected zone from + * the PCB as is customary for e.g. getsockname/getpeername BSD socket calls. + * + * Ideally, callers would always supply a properly zoned address, in which case + * this function would not be needed. It exists both for compatibility with the + * BSD socket API (which accepts zoneless destination addresses) and for + * backward compatibility with pre-scoping lwIP code. + * + * It may be impossible to select a zone, e.g. if there are no netifs. In that + * case, the address's zone field will be left as is. + * + * @param dest the IPv6 address for which to select and set a zone. + * @param src source IPv6 address (const); may be equal to dest. + */ +#if LWIP_SO_DONTROUTE +#define ip6_addr_select_zone(dest, src) do { struct netif *selected_netif; \ + selected_netif = ip6_route((src), (dest), RT_SCOPE_UNIVERSAL); \ + if (selected_netif != NULL) { \ + ip6_addr_assign_zone((dest), IP6_UNKNOWN, selected_netif); \ + } } while (0) +#else +#define ip6_addr_select_zone(dest, src) do { struct netif *selected_netif; \ + selected_netif = ip6_route((src), (dest)); \ + if (selected_netif != NULL) { \ + ip6_addr_assign_zone((dest), IP6_UNKNOWN, selected_netif); \ + } } while (0) +#endif +#else /* LWIP_IPV6_SCOPES */ + +#define IPADDR6_ZONE_INIT +#define ip6_addr_zone(ip6addr) (IP6_NO_ZONE) +#define ip6_addr_has_zone(ip6addr) (0) +#define ip6_addr_set_zone(ip6addr, zone_idx) +#define ip6_addr_clear_zone(ip6addr) +#define ip6_addr_copy_zone(ip6addr1, ip6addr2) +#define ip6_addr_equals_zone(ip6addr, zone_idx) (1) +#define ip6_addr_cmp_zone(ip6addr1, ip6addr2) (1) +#define IPV6_CUSTOM_SCOPES 0 +#define ip6_addr_has_scope(ip6addr, type) (0) +#define ip6_addr_assign_zone(ip6addr, type, netif) +#define ip6_addr_test_zone(ip6addr, netif) (1) +#define ip6_addr_lacks_zone(ip6addr, type) (0) +#define ip6_addr_select_zone(ip6addr, src) + +#endif /* LWIP_IPV6_SCOPES */ + +#if LWIP_IPV6_SCOPES && LWIP_IPV6_SCOPES_DEBUG + +/** Verify that the given IPv6 address is properly zoned. */ +#define IP6_ADDR_ZONECHECK(ip6addr) LWIP_ASSERT("IPv6 zone check failed", \ + ip6_addr_has_scope(ip6addr, IP6_UNKNOWN) == ip6_addr_has_zone(ip6addr)) + +/** Verify that the given IPv6 address is properly zoned for the given netif. */ +#define IP6_ADDR_ZONECHECK_NETIF(ip6addr, netif) LWIP_ASSERT("IPv6 netif zone check failed", \ + ip6_addr_has_scope(ip6addr, IP6_UNKNOWN) ? \ + (ip6_addr_has_zone(ip6addr) && \ + (((netif) == NULL) || ip6_addr_test_zone((ip6addr), (netif)))) : \ + !ip6_addr_has_zone(ip6addr)) + +#else /* LWIP_IPV6_SCOPES && LWIP_IPV6_SCOPES_DEBUG */ + +#define IP6_ADDR_ZONECHECK(ip6addr) +#define IP6_ADDR_ZONECHECK_NETIF(ip6addr, netif) + +#endif /* LWIP_IPV6_SCOPES && LWIP_IPV6_SCOPES_DEBUG */ + +#endif /* LWIP_IPV6 */ + +#endif /* LWIP_HDR_IP6_ADDR_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/ip_addr.h b/sdk_liteos/third_party/lwip_sack/include/lwip/ip_addr.h new file mode 100644 index 0000000000000000000000000000000000000000..8388d3c9b3263ec203046b0e28a4220cde32a92e --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/ip_addr.h @@ -0,0 +1,492 @@ +/** + * @file + * IP address API (common IPv4 and IPv6) + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_IP_ADDR_H +#define LWIP_HDR_IP_ADDR_H + +#include "lwip/opt.h" +#include "lwip/def.h" + +#include "lwip/ip4_addr.h" +#include "lwip/ip6_addr.h" + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +/** @ingroup ipaddr + * IP address types for use in ip_addr_t.type member. + * @see tcp_new_ip_type(), udp_new_ip_type(), raw_new_ip_type(). + */ +enum lwip_ip_addr_type { + /** IPv4 */ + IPADDR_TYPE_V4 = 0U, + /** IPv6 */ + IPADDR_TYPE_V6 = 6U, + /** IPv4+IPv6 ("dual-stack") */ + IPADDR_TYPE_ANY = 46U +}; + +#if LWIP_IPV4 && LWIP_IPV6 +/** + * @ingroup ipaddr + * A union struct for both IP version's addresses. + * ATTENTION: watch out for its size when adding IPv6 address scope! + */ +typedef struct ip_addr { + union { + ip6_addr_t ip6; + ip4_addr_t ip4; + } u_addr; + /** @ref lwip_ip_addr_type */ + u8_t type; +} ip_addr_t; + +extern const ip_addr_t ip_addr_any_type; + +/** @ingroup ip4addr */ +#define IPADDR4_INIT(u32val) { { { { u32val, 0ul, 0ul, 0ul } IPADDR6_ZONE_INIT } }, IPADDR_TYPE_V4 } +/** @ingroup ip4addr */ +#define IPADDR4_INIT_BYTES(a, b, c, d) IPADDR4_INIT(PP_HTONL(LWIP_MAKEU32(a, b, c, d))) +/** @ingroup ip6addr */ +#define IPADDR6_INIT(a, b, c, d) { { { { a, b, c, d } IPADDR6_ZONE_INIT } }, IPADDR_TYPE_V6 } +/** @ingroup ip6addr */ +#define IPADDR6_INIT_HOST(a, b, c, d) { { { { PP_HTONL(a), PP_HTONL(b), PP_HTONL(c), PP_HTONL(d) } IPADDR6_ZONE_INIT } }, IPADDR_TYPE_V6 } + +/** @ingroup ipaddr */ +#define IP_IS_ANY_TYPE_VAL(ipaddr) (IP_GET_TYPE(&ipaddr) == IPADDR_TYPE_ANY) +/** @ingroup ipaddr */ +#define IPADDR_ANY_TYPE_INIT { { { { 0ul, 0ul, 0ul, 0ul } IPADDR6_ZONE_INIT } }, IPADDR_TYPE_ANY } + +/** @ingroup ip4addr */ +#define IP_IS_V4_VAL(ipaddr) (IP_GET_TYPE(&ipaddr) == IPADDR_TYPE_V4) +/** @ingroup ip6addr */ +#define IP_IS_V6_VAL(ipaddr) (IP_GET_TYPE(&ipaddr) == IPADDR_TYPE_V6) +/** @ingroup ip4addr */ +#define IP_IS_V4(ipaddr) (((ipaddr) == (void *)NULL) || IP_IS_V4_VAL(*(ipaddr))) +/** @ingroup ip6addr */ +#define IP_IS_V6(ipaddr) (((ipaddr) != (void *)NULL) && IP_IS_V6_VAL(*(ipaddr))) + +#define IP_SET_TYPE_VAL(ipaddr, iptype) do { (ipaddr).type = (iptype); }while (0) +#define IP_SET_TYPE(ipaddr, iptype) do { if ((void*)(ipaddr) != NULL) { IP_SET_TYPE_VAL(*(ipaddr), iptype); } }while (0) +#define IP_GET_TYPE(ipaddr) ((ipaddr)->type) + +#define IP_ADDR_RAW_SIZE(ipaddr) (IP_GET_TYPE(&ipaddr) == IPADDR_TYPE_V4 ? sizeof(ip4_addr_t) : sizeof(ip6_addr_t)) + +#define IP_ADDR_PCB_VERSION_MATCH_EXACT(pcb, ipaddr) (IP_GET_TYPE(&pcb->local_ip) == IP_GET_TYPE(ipaddr)) +#define IP_ADDR_PCB_VERSION_MATCH(pcb, ipaddr) (IP_IS_ANY_TYPE_VAL(pcb->local_ip) || \ + IP_ADDR_PCB_VERSION_MATCH_EXACT(pcb, ipaddr)) + +/** @ingroup ip6addr + * Convert generic ip address to specific protocol version + */ +#define ip_2_ip6(ipaddr) (&((ipaddr)->u_addr.ip6)) +/** @ingroup ip4addr + * Convert generic ip address to specific protocol version + */ +#define ip_2_ip4(ipaddr) (&((ipaddr)->u_addr.ip4)) + +/** @ingroup ip4addr */ +#define IP_ADDR4(ipaddr, a, b, c, d) do { IP4_ADDR(ip_2_ip4(ipaddr), a, b, c, d); \ + IP_SET_TYPE_VAL(*(ipaddr), IPADDR_TYPE_V4); } while (0) +/** @ingroup ip6addr */ +#define IP_ADDR6(ipaddr, i0, i1, i2, i3) do { IP6_ADDR(ip_2_ip6(ipaddr), i0, i1, i2, i3); \ + IP_SET_TYPE_VAL(*(ipaddr), IPADDR_TYPE_V6); } while (0) +/** @ingroup ip6addr */ +#define IP_ADDR6_HOST(ipaddr, i0, i1, i2, i3) IP_ADDR6(ipaddr, PP_HTONL(i0), PP_HTONL(i1), PP_HTONL(i2), PP_HTONL(i3)) + +/** @ingroup ipaddr */ +#define ip_addr_copy(dest, src) ((dest) = (src)) +/** @ingroup ip6addr */ +#define ip_addr_copy_from_ip6(dest, src) do { \ + ip6_addr_copy(*ip_2_ip6(&(dest)), src); IP_SET_TYPE_VAL(dest, IPADDR_TYPE_V6); } while (0) +/** @ingroup ip6addr */ +#define ip_addr_copy_from_ip6_packed(dest, src) do{ \ + ip6_addr_copy_from_packed(*ip_2_ip6(&(dest)), src); IP_SET_TYPE_VAL(dest, IPADDR_TYPE_V6); } while (0) +/** @ingroup ip4addr */ +#define ip_addr_copy_from_ip4(dest, src) do { \ + ip4_addr_copy(*ip_2_ip4(&(dest)), src); IP_SET_TYPE_VAL(dest, IPADDR_TYPE_V4); } while (0) +/** @ingroup ip4addr */ +#define ip_addr_set_ip4_u32(ipaddr, val) do { if ((void*)ipaddr != NULL) { ip4_addr_set_u32(ip_2_ip4(ipaddr), val); \ + IP_SET_TYPE(ipaddr, IPADDR_TYPE_V4); } } while (0) +/** @ingroup ip4addr */ +#define ip_addr_set_ip4_u32_val(ipaddr, val) do { \ + ip4_addr_set_u32(ip_2_ip4(ipaddr), val); \ + IP_SET_TYPE_VAL(*ipaddr, IPADDR_TYPE_V4); \ +} while (0) + +/* @ingroup ip4addr */ +#define ip_addr_get_ip4_u32(ipaddr) ((((void*)ipaddr != NULL) && IP_IS_V4(ipaddr)) ? \ + ip4_addr_get_u32(ip_2_ip4(ipaddr)) : 0) +/** @ingroup ipaddr */ +#define ip_addr_set(dest, src) ((*dest) = (*src)) + +#define ip_addr_set_val(dest, src) ((*dest) = (*src)) + +/** @ingroup ipaddr */ +#define ip_addr_set_ipaddr(dest, src) ip_addr_set(dest, src) +#define ip_addr_set_ipaddr_val(dest, src) ip_addr_set_val(dest, src) + +/** @ingroup ipaddr */ +#define ip_addr_set_zero(ipaddr) do { \ + ip6_addr_set_zero(ip_2_ip6(ipaddr)); IP_SET_TYPE(ipaddr, 0); } while (0) +/** @ingroup ip5addr */ +#define ip_addr_set_zero_ip4(ipaddr) do { \ + ip6_addr_set_zero(ip_2_ip6(ipaddr)); IP_SET_TYPE(ipaddr, IPADDR_TYPE_V4); } while (0) +/** @ingroup ip6addr */ +#define ip_addr_set_zero_ip6(ipaddr) do { \ + ip6_addr_set_zero(ip_2_ip6(ipaddr)); IP_SET_TYPE(ipaddr, IPADDR_TYPE_V6); } while (0) +/** @ingroup ipaddr */ +#define ip_addr_set_any(is_ipv6, ipaddr) do { if (is_ipv6) { \ + ip6_addr_set_any(ip_2_ip6(ipaddr)); IP_SET_TYPE_VAL(*ipaddr, IPADDR_TYPE_V6); } else { \ + ip4_addr_set_any(ip_2_ip4(ipaddr)); IP_SET_TYPE_VAL(*ipaddr, IPADDR_TYPE_V4); }} while (0) +/** @ingroup ipaddr */ +#define ip_addr_set_any_val(is_ipv6, ipaddr) do { if (is_ipv6) { \ + ip6_addr_set_any(ip_2_ip6(&(ipaddr))); IP_SET_TYPE_VAL(ipaddr, IPADDR_TYPE_V6); } else { \ + ip4_addr_set_any(ip_2_ip4(&(ipaddr))); IP_SET_TYPE_VAL(ipaddr, IPADDR_TYPE_V4); }} while (0) +/** @ingroup ipaddr */ +#define ip_addr_set_loopback(is_ipv6, ipaddr) do { if (is_ipv6) { \ + ip6_addr_set_loopback(ip_2_ip6(ipaddr)); IP_SET_TYPE_VAL(*ipaddr, IPADDR_TYPE_V6); } else { \ + ip4_addr_set_loopback(ip_2_ip4(ipaddr)); IP_SET_TYPE_VAL(*ipaddr, IPADDR_TYPE_V4); }} while (0) +/** @ingroup ipaddr */ +#define ip_addr_set_loopback_val(is_ipv6, ipaddr) do { if (is_ipv6) { \ + ip6_addr_set_loopback(ip_2_ip6(&(ipaddr))); IP_SET_TYPE_VAL(ipaddr, IPADDR_TYPE_V6); } else { \ + ip4_addr_set_loopback(ip_2_ip4(&(ipaddr))); IP_SET_TYPE_VAL(ipaddr, IPADDR_TYPE_V4); }} while (0) +/** @ingroup ipaddr */ +#define ip_addr_set_hton(dest, src) do { if (IP_IS_V6(src)) { \ + ip6_addr_set_hton(ip_2_ip6(ipaddr), (src)); IP_SET_TYPE(dest, IPADDR_TYPE_V6); } else { \ + ip4_addr_set_hton(ip_2_ip4(ipaddr), (src)); IP_SET_TYPE(dest, IPADDR_TYPE_V4); }} while (0) +/** @ingroup ipaddr */ +#define ip_addr_get_network(target, host, netmask) do { if (IP_IS_V6(host)) { \ + ip4_addr_set_zero(ip_2_ip4(target)); IP_SET_TYPE(target, IPADDR_TYPE_V6); } else { \ + ip4_addr_get_network(ip_2_ip4(target), ip_2_ip4(host), \ + ip_2_ip4(netmask)); IP_SET_TYPE(target, IPADDR_TYPE_V4); }} while (0) +/** @ingroup ipaddr */ +#define ip_addr_netcmp(addr1, addr2, mask) ((IP_IS_V6(addr1) && IP_IS_V6(addr2)) ? \ + 0 : \ + ip4_addr_netcmp(ip_2_ip4(addr1), ip_2_ip4(addr2), mask)) + +#define ip_addr_netcmp_val(addr1, addr2, mask) ((IP_IS_V6_VAL(*(addr1)) && IP_IS_V6_VAL(*(addr2))) ? \ + 0 : \ + ip4_addr_netcmp(ip_2_ip4(addr1), ip_2_ip4(addr2), mask)) + +/** @ingroup ipaddr */ +#if LWIP_SMALL_SIZE +int ip_addr_cmp(const ip_addr_t *addr1, const ip_addr_t *addr2); +int ip_addr_isany(const ip_addr_t *ipaddr); +#else +#define ip_addr_cmp(addr1, addr2) ((IP_GET_TYPE(addr1) != IP_GET_TYPE(addr2)) ? 0 : (IP_IS_V6_VAL(*(addr1)) ? \ + ip6_addr_cmp(ip_2_ip6(addr1), ip_2_ip6(addr2)) : \ + ip4_addr_cmp(ip_2_ip4(addr1), ip_2_ip4(addr2)))) +/** @ingroup ipaddr */ +#define ip_addr_isany(ipaddr) (((ipaddr) == NULL) ? 1 : ((IP_IS_V6(ipaddr)) ? \ + ip6_addr_isany(ip_2_ip6(ipaddr)) : \ + ip4_addr_isany(ip_2_ip4(ipaddr)))) +#endif +/** @ingroup ipaddr */ +#define ip_addr_isnone(ipaddr) ((IP_IS_V6(ipaddr)) ? \ + ip6_addr_isnone(ip_2_ip6(ipaddr)) : \ + ip4_addr_isnone(ip_2_ip4(ipaddr))) +/** @ingroup ipaddr */ +#define ip_addr_isany_val(ipaddr) ((IP_IS_V6_VAL(ipaddr)) ? \ + ip6_addr_isany_val(*ip_2_ip6(&(ipaddr))) : \ + ip4_addr_isany_val(*ip_2_ip4(&(ipaddr)))) +/** @ingroup ipaddr */ +#define ip_addr_isbroadcast(ipaddr, netif) ((IP_IS_V6(ipaddr)) ? \ + 0 : \ + ip4_addr_isbroadcast(ip_2_ip4(ipaddr), netif)) +#define ip_addr_isbroadcast_val(ipaddr, netif) ((IP_IS_V6_VAL(*ipaddr)) ? \ + 0 : \ + ip4_addr_isbroadcast(ip_2_ip4(ipaddr), netif)) +/** @ingroup ipaddr */ +#define ip_addr_ismulticast(ipaddr) ((IP_IS_V6(ipaddr)) ? \ + ip6_addr_ismulticast(ip_2_ip6(ipaddr)) : \ + ip4_addr_ismulticast(ip_2_ip4(ipaddr))) +#define ip_addr_ismulticast_val(ipaddr) ((IP_IS_V6_VAL(*ipaddr)) ? \ + ip6_addr_ismulticast(ip_2_ip6(ipaddr)) : \ + ip4_addr_ismulticast(ip_2_ip4(ipaddr))) +/** @ingroup ipaddr */ +#if LWIP_SMALL_SIZE +int ip_addr_isloopback(const ip_addr_t* ipaddr); +#else +#define ip_addr_isloopback(ipaddr) ((IP_IS_V6(ipaddr)) ? \ + ip6_addr_isloopback(ip_2_ip6(ipaddr)) : \ + ip4_addr_isloopback(ip_2_ip4(ipaddr))) +#endif +/** @ingroup ipaddr */ +#define ip_addr_islinklocal(ipaddr) ((IP_IS_V6(ipaddr)) ? \ + ip6_addr_islinklocal(ip_2_ip6(ipaddr)) : \ + ip4_addr_islinklocal(ip_2_ip4(ipaddr))) +#ifdef LWIP_DEBUG +#define ip_addr_debug_print(debug, ipaddr) do { if (IP_IS_V6(ipaddr)) { \ + ip6_addr_debug_print(debug, ip_2_ip6(ipaddr)); } else { \ + ip4_addr_debug_print(debug, ip_2_ip4(ipaddr)); } }while (0) +#define ip_addr_debug_print_val(debug, ipaddr) do { if (IP_IS_V6_VAL(ipaddr)) { \ + ip6_addr_debug_print_val(debug, *ip_2_ip6(&(ipaddr))); } else { \ + ip4_addr_debug_print_val(debug, *ip_2_ip4(&(ipaddr))); } }while (0) +#else +#define ip_addr_debug_print(debug, ipaddr) +#define ip_addr_debug_print_val(debug, ipaddr) +#endif +/** @ingroup ipaddr */ +char *ipaddr_ntoa(const ip_addr_t *addr); +/** @ingroup ipaddr */ +char *ipaddr_ntoa_r(const ip_addr_t *addr, char *buf, int buflen); +int ipaddr_aton(const char *cp, ip_addr_t *addr); + +/** @ingroup ipaddr */ +#define IPADDR_STRLEN_MAX IP6ADDR_STRLEN_MAX + +/** @ingroup ipaddr */ +#define ip4_2_ipv4_mapped_ipv6(ip6addr, ip4addr) do { \ + (ip6addr)->addr[3] = (ip4addr)->addr; \ + (ip6addr)->addr[2] = PP_HTONL(0x0000FFFFUL); \ + (ip6addr)->addr[1] = 0; \ + (ip6addr)->addr[0] = 0; \ + ip6_addr_clear_zone(ip6addr); } while (0) + +/** @ingroup ipaddr */ +#define unmap_ipv4_mapped_ipv6(ip4addr, ip6addr) \ + (ip4addr)->addr = (ip6addr)->addr[3]; + +#define IP46_ADDR_ANY(type) (((type) == IPADDR_TYPE_V6) ? IP6_ADDR_ANY : IP4_ADDR_ANY) + +#else /* LWIP_IPV4 && LWIP_IPV6 */ + +#define IP_ADDR_PCB_VERSION_MATCH(addr, pcb) 1 +#define IP_ADDR_PCB_VERSION_MATCH_EXACT(pcb, ipaddr) 1 + +#define ip_addr_set_any_val(is_ipv6, ipaddr) ip_addr_set_any(is_ipv6, &(ipaddr)) +#define ip_addr_set_loopback_val(is_ipv6, ipaddr) ip_addr_set_loopback(is_ipv6, &(ipaddr)) + +#if LWIP_IPV4 + +typedef ip4_addr_t ip_addr_t; +#define IPADDR4_INIT(u32val) { u32val } +#define IPADDR4_INIT_BYTES(a, b, c, d) IPADDR4_INIT(PP_HTONL(LWIP_MAKEU32(a, b, c, d))) +#define IP_IS_V4_VAL(ipaddr) 1 +#define IP_IS_V6_VAL(ipaddr) 0 +#define IP_IS_V4(ipaddr) 1 +#define IP_IS_V6(ipaddr) 0 +#define IP_IS_ANY_TYPE_VAL(ipaddr) 0 +#define IP_SET_TYPE_VAL(ipaddr, iptype) +#define IP_SET_TYPE(ipaddr, iptype) +#define IP_GET_TYPE(ipaddr) IPADDR_TYPE_V4 +#define IP_ADDR_RAW_SIZE(ipaddr) sizeof(ip4_addr_t) +#define ip_2_ip4(ipaddr) (ipaddr) +#define IP_ADDR4(ipaddr, a, b, c, d) IP4_ADDR(ipaddr, a, b, c, d) + +#define ip_addr_copy(dest, src) ip4_addr_copy(dest, src) +#define ip_addr_copy_from_ip4(dest, src) ip4_addr_copy(dest, src) +#define ip_addr_set_ip4_u32(ipaddr, val) ip4_addr_set_u32(ip_2_ip4(ipaddr), val) +#define ip_addr_set_ip4_u32_val(ipaddr, val) ip_addr_set_ip4_u32(&(ipaddr), val) +#define ip_addr_get_ip4_u32(ipaddr) ip4_addr_get_u32(ip_2_ip4(ipaddr)) +#define ip_addr_set(dest, src) ip4_addr_set(dest, src) + +#define ip_addr_set_val(dest, src) ip4_addr_set(dest, src) + +#define ip_addr_set_ipaddr(dest, src) ip4_addr_set(dest, src) +#define ip_addr_set_ipaddr_val(dest, src) ip4_addr_set(dest, src) + +#define ip_addr_set_zero(ipaddr) ip4_addr_set_zero(ipaddr) +#define ip_addr_set_zero_ip4(ipaddr) ip4_addr_set_zero(ipaddr) +#define ip_addr_set_any(is_ipv6, ipaddr) ip4_addr_set_any(ipaddr) +#define ip_addr_set_loopback(is_ipv6, ipaddr) ip4_addr_set_loopback(ipaddr) +#define ip_addr_set_hton(dest, src) ip4_addr_set_hton(dest, src) +#define ip_addr_get_network(target, host, mask) ip4_addr_get_network(target, host, mask) +#define ip_addr_netcmp(addr1, addr2, mask) ip4_addr_netcmp(addr1, addr2, mask) +#define ip_addr_cmp(addr1, addr2) ip4_addr_cmp(addr1, addr2) +#define ip_addr_isany(ipaddr) ip4_addr_isany(ipaddr) +#define ip_addr_isnone(ipaddr) ip4_addr_isnone(ipaddr) +#define ip_addr_isany_val(ipaddr) ip4_addr_isany_val(ipaddr) +#define ip_addr_isloopback(ipaddr) ip4_addr_isloopback(ipaddr) +#define ip_addr_islinklocal(ipaddr) ip4_addr_islinklocal(ipaddr) +#define ip_addr_isbroadcast(addr, netif) ip4_addr_isbroadcast(addr, netif) +#define ip_addr_ismulticast(ipaddr) ip4_addr_ismulticast(ipaddr) +#define ip_addr_ismulticast_safe(ipaddr) ip4_addr_ismulticast(ipaddr) + +#ifdef LWIP_DEBUG +#define ip_addr_debug_print(debug, ipaddr) ip4_addr_debug_print(debug, ipaddr) +#define ip_addr_debug_print_val(debug, ipaddr) ip4_addr_debug_print_val(debug, ipaddr) +#else +#define ip_addr_debug_print(debug, ipaddr) +#define ip_addr_debug_print_val(debug, ipaddr) +#endif + +#define ipaddr_ntoa(ipaddr) ip4addr_ntoa(ipaddr) +#define ipaddr_ntoa_r(ipaddr, buf, buflen) ip4addr_ntoa_r(ipaddr, buf, buflen) +#define ipaddr_aton(cp, addr) ip4addr_aton(cp, addr) + +#define IPADDR_STRLEN_MAX IP4ADDR_STRLEN_MAX + +#define IP46_ADDR_ANY(type) (IP4_ADDR_ANY) + +#else /* LWIP_IPV4 */ + +typedef ip6_addr_t ip_addr_t; +#define IPADDR6_INIT(a, b, c, d) { { a, b, c, d } IPADDR6_ZONE_INIT } +#define IPADDR6_INIT_HOST(a, b, c, d) { { PP_HTONL(a), PP_HTONL(b), PP_HTONL(c), PP_HTONL(d) } IPADDR6_ZONE_INIT } +#define IP_IS_V4_VAL(ipaddr) 0 +#define IP_IS_V6_VAL(ipaddr) 1 +#define IP_IS_V4(ipaddr) 0 +#define IP_IS_V6(ipaddr) 1 +#define IP_IS_ANY_TYPE_VAL(ipaddr) 0 +#define IP_SET_TYPE_VAL(ipaddr, iptype) +#define IP_SET_TYPE(ipaddr, iptype) +#define IP_GET_TYPE(ipaddr) IPADDR_TYPE_V6 +#define IP_ADDR_RAW_SIZE(ipaddr) sizeof(ip6_addr_t) +#define ip_2_ip6(ipaddr) (ipaddr) +#define IP_ADDR6(ipaddr, i0, i1, i2, i3) IP6_ADDR(ipaddr, i0, i1, i2, i3) +#define IP_ADDR6_HOST(ipaddr, i0, i1, i2, i3) IP_ADDR6(ipaddr, PP_HTONL(i0), PP_HTONL(i1), PP_HTONL(i2), PP_HTONL(i3)) + +#define ip_addr_copy(dest, src) ip6_addr_copy(dest, src) +#define ip_addr_copy_from_ip6(dest, src) ip6_addr_copy(dest, src) +#define ip_addr_copy_from_ip6_packed(dest, src) ip6_addr_copy_from_packed(dest, src) +#define ip_addr_set(dest, src) ip6_addr_set(dest, src) +#define ip_addr_set_val(dest, src) ip6_addr_set(dest, src) + +#define ip_addr_set_ipaddr(dest, src) ip6_addr_set(dest, src) +#define ip_addr_set_ipaddr_val(dest, src) ip6_addr_set(dest, src) + +#define ip_addr_set_zero(ipaddr) ip6_addr_set_zero(ipaddr) +#define ip_addr_set_zero_ip6(ipaddr) ip6_addr_set_zero(ipaddr) +#define ip_addr_set_any(is_ipv6, ipaddr) ip6_addr_set_any(ipaddr) +#define ip_addr_set_loopback(is_ipv6, ipaddr) ip6_addr_set_loopback(ipaddr) +#define ip_addr_set_hton(dest, src) ip6_addr_set_hton(dest, src) +#define ip_addr_get_network(target, host, mask) ip6_addr_set_zero(target) +#define ip_addr_netcmp(addr1, addr2, mask) 0 +#define ip_addr_cmp(addr1, addr2) ip6_addr_cmp(addr1, addr2) +#define ip_addr_isany(ipaddr) ip6_addr_isany(ipaddr) +#define ip_addr_isnone(ipaddr) ip6_addr_isnone(ipaddr) +#define ip_addr_isany_val(ipaddr) ip6_addr_isany_val(ipaddr) +#define ip_addr_isloopback(ipaddr) ip6_addr_isloopback(ipaddr) +#define ip_addr_islinklocal(ipaddr) ip6_addr_islinklocal(ipaddr) +#define ip_addr_isbroadcast(addr, netif) 0 +#define ip_addr_ismulticast(ipaddr) ip6_addr_ismulticast(ipaddr) +#define ip_addr_ismulticast_val(ipaddr) ip6_addr_ismulticast(ipaddr) + +#ifdef LWIP_DEBUG +#define ip_addr_debug_print(debug, ipaddr) ip6_addr_debug_print(debug, ipaddr) +#define ip_addr_debug_print_val(debug, ipaddr) ip6_addr_debug_print_val(debug, ipaddr) +#else +#define ip_addr_debug_print(debug, ipaddr) +#define ip_addr_debug_print_val(debug, ipaddr) +#endif + + +#define ipaddr_ntoa(ipaddr) ip6addr_ntoa(ipaddr) +#define ipaddr_ntoa_r(ipaddr, buf, buflen) ip6addr_ntoa_r(ipaddr, buf, buflen) +#define ipaddr_aton(cp, addr) ip6addr_aton(cp, addr) + +#define IPADDR_STRLEN_MAX IP6ADDR_STRLEN_MAX + +#define IP46_ADDR_ANY(type) (IP6_ADDR_ANY) + +#endif /* LWIP_IPV4 */ +#endif /* LWIP_IPV4 && LWIP_IPV6 */ + +#if LWIP_IPV4 + +extern const ip_addr_t ip_addr_any; +extern const ip_addr_t ip_addr_broadcast; + +/** + * @ingroup ip4addr + * This macro can be used as a fixed/const ip_addr_t + * for the IP wildcard. + * Defined to @ref IP4_ADDR_ANY when IPv4 is enabled. + * Defined to @ref IP6_ADDR_ANY in IPv6 only systems. + * Use this if you can handle IPv4 and IPv6 addresses. + * Use @ref IP4_ADDR_ANY or @ref IP6_ADDR_ANY when the IP address + * type matters. + */ +#define IP_ADDR_ANY IP4_ADDR_ANY +/** + * @ingroup ip4addr + * This macro can be used as a fixed/const ip_addr_t + * for the IPv4 wildcard and the broadcast address + */ +#define IP4_ADDR_ANY (&ip_addr_any) +/** + * @ingroup ip4addr + * This macro can be used as a fixed/const ip4_addr_t + * for the wildcard and the broadcast address + */ +#define IP4_ADDR_ANY4 (ip_2_ip4(&ip_addr_any)) + +/** @ingroup ip4addr */ +#define IP_ADDR_BROADCAST (&ip_addr_broadcast) +/** @ingroup ip4addr */ +#define IP4_ADDR_BROADCAST (ip_2_ip4(&ip_addr_broadcast)) + +#endif /* LWIP_IPV4 */ + +#if LWIP_IPV6 + +extern const ip_addr_t ip6_addr_any; + +/** + * @ingroup ip6addr + * This macro can be used as a fixed ip_addr_t + * for the IPv6 wildcard address + */ +#define IP6_ADDR_ANY (&ip6_addr_any) +/** + * @ingroup ip6addr + * This macro can be used as a fixed ip6_addr_t + * for the IPv6 wildcard address + */ +#define IP6_ADDR_ANY6 (ip_2_ip6(&ip6_addr_any)) + +#if !LWIP_IPV4 +/* IPv6-only configurations */ +#define IP_ADDR_ANY IP6_ADDR_ANY +#endif /* !LWIP_IPV4 */ + +#endif + +#if LWIP_IPV4 && LWIP_IPV6 +/** @ingroup ipaddr */ +#define IP_ANY_TYPE (&ip_addr_any_type) +#else +#define IP_ANY_TYPE IP_ADDR_ANY +#endif + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_HDR_IP_ADDR_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/l3event.h b/sdk_liteos/third_party/lwip_sack/include/lwip/l3event.h new file mode 100644 index 0000000000000000000000000000000000000000..7c7921d49850fc67ba5ae420dbebff58ec2caa48 --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/l3event.h @@ -0,0 +1,108 @@ +/* + * Copyright (c) Huawei Technologies Co., Ltd. 2019-2020. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote + * products derived from this software without specific prior + * written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS + * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * Description: implementation for l3_msg_event + * Author: none + * Create: 2020 + */ + +#ifndef LWIP_HDR_L3EVENT_H +#define LWIP_HDR_L3EVENT_H + +#include "lwip/opt.h" + +/* define the app_callback function point type */ +typedef void (*app_callback_fn)(u8_t, void *); + +#if !NO_SYS /* don't build if not configured for use in lwipopts.h */ +#if LWIP_L3_EVENT_MSG + +typedef enum l3_event_msg_type { +#if LWIP_ROUTE_CHANGE_MSG + L3_EVENT_MSG_ROUTE_CHANGE, +#endif +#if LWIP_RPL_JOIN_SUCC_MSG + L3_EVENT_MSG_RPL_JOIN_SUCC, +#endif +#if LWIP_RPL_PARENT_CLEAR_MSG + L3_EVENT_MSG_PARENT_CLEAR, +#endif +#if LWIP_RPL_BEACON_PRI_RESET + L3_EVENT_MSG_BEACON_PRI_RESET, +#endif +#if LWIP_RPL_GET_IPV4_ADDR_FAIL + L3_EVENT_MSG_GET_IPV4_ADDR_FAIL, +#endif +#if LWIP_RPL_MSTA_GET_IPV4_ADDR_FAIL + L3_EVENT_MSG_MSTA_GET_IPV4_ADDR_FAIL, +#endif +#if LWIP_RPL_MG_FULL + L3_EVENT_MSG_MG_FULL, +#endif +#if LWIP_RPL_RT_FULL + L3_EVENT_MSG_RT_FULL, +#endif + /* other MSG could be added here */ + L3_EVENT_MSG_MAX +} l3_event_msg_type_e; + +/* + * Func Name: l3_invoke_msg_callback + */ +/** + * @brief + * + * This is a thread safe API, used to invoke the l3_event_msg + * + * @param[IN] evt_type: the event type + * msg: the carry msg for using afterwards, can be NULL. + * + * @returns NA \n + * + */ +void l3_invoke_msg_callback(enum l3_event_msg_type evt_type, void *msg); + +/* + * Func Name: l3_event_msg_callback_reg + */ +/** + * @brief + * + * This is a thread safe API, used to register the l3_event_msg + * + * @param[IN] evt_type: the event type + * app_callback: the register callback function, can be NULL if app unregister or don't want to register. + * + * @returns NA \n + * + */ +void l3_event_msg_callback_reg(enum l3_event_msg_type evt_type, app_callback_fn app_callback); + +#endif /* LWIP_L3_EVENT_MSG */ +#endif /* !NO_SYS */ + +#endif /* LWIP_HDR_L3EVENT_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/link_quality.h b/sdk_liteos/third_party/lwip_sack/include/lwip/link_quality.h new file mode 100644 index 0000000000000000000000000000000000000000..6acd3657c627101e7acf7fed7b101479bc82fbac --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/link_quality.h @@ -0,0 +1,86 @@ +/* + * Copyright (c) Huawei Technologies Co., Ltd. 2013-2016. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote + * products derived from this software without specific prior + * written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS + * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * Description: declaration of link quality APIs + * Author: none + * Create: 2013-12-22 + */ + +#ifndef __LINK_QUALITY_H__ +#define __LINK_QUALITY_H__ + +#include "lwip/opt.h" +#include "lwip/netif.h" + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +#ifndef LWIP_RPL_USE_MACACK_FOR_NBR +#define LWIP_RPL_USE_MACACK_FOR_NBR 1 +#endif + +typedef unsigned char LQI_TYPE; +typedef signed char RSSI_TYPE; + +struct netif; +struct linklayer_addr; + +typedef struct _lwip_nbr_linkquality { + /* Link Metric is derived from ETX */ + u16_t link_metric; +} lwip_nbr_linkquality_t; + +void lwip_update_nbr_signal_quality +( + const struct netif *linkiface, + const struct linklayer_addr *sendermac, + RSSI_TYPE link_rssi, + LQI_TYPE link_lqi +); + +typedef enum mac_status { + MAC_STATUS_TX_ACK_OK = 0, + MAC_STATUS_MAX_RETRIES, + MAC_STATUS_ERR_FATAL, + /* + * case of wifi, beacon unavailability can be used to decide peer unreachability. + * In this case if the peer is a parent, then the parent entry should be removed. + */ + MAC_STATUS_PEER_UNREACHABLE, + MAC_STATUS_DROP_POLICY, + MAC_STATUS_BUTT +} mac_status_e; + +int lwip_get_rssi(void); + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* __LINK_QUALITY_H__ */ + diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/lowpower.h b/sdk_liteos/third_party/lwip_sack/include/lwip/lowpower.h new file mode 100644 index 0000000000000000000000000000000000000000..6969cc2b65639394b584bbb5175835391c007443 --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/lowpower.h @@ -0,0 +1,143 @@ +/* + * Description: declaration for lowpower APIs + */ +#ifndef LWIP_HDR_LOWPOWER_H +#define LWIP_HDR_LOWPOWER_H + +#include "lwip/opt.h" +#include "lwip/err.h" +#if !NO_SYS +#include "lwip/sys.h" +#endif + +#if LWIP_LOWPOWER + +#define LOWPOWER_TIMER_DEBUG 0 +#define TIMEOUT_TICK 100 /* 100ms */ +#define TIMEOUT_CHECK 30 + +#if LOWPOWER_TIMER_DEBUG +#define TCP_FASTTMR_NAME ,"tcp_fasttmr" +#define TCP_SLOWTMR_NAME ,"tcp_slowtmr" +#define IP_REASSTRM_NAME ,"ip_reass_tmr" +#define ETHARPTMR_NAME ,"etharp_tmr" +#define DHCP_COARSETMR_NAME ,"dhcp_coarse_tmr" +#define DHCP_FINETMR_NAME ,"dhcp_fine_tmr" +#define AUTOIPTMR_NAME ,"autoip_tmr" +#define IGMPTMR_NAME ,"igmp_tmr" +#define DNSTMR_NAME ,"dns_tmr" +#define NAT64TMR_NAME ,"nat64_tmr" +#define ND6TMR_NAME ,"nd6_tmr" +#define IP6_TREASSTMR_NAME ,"ip6_reass_tmr" +#define MLD6TMR_NAME ,"mld6_tmr" +#define DHCP6TMR_NAME ,"dhcp6_tmr" +#define LOWPAN6TMR_NAME ,"lowpan6_tmr" +#else +#define TCP_FASTTMR_NAME +#define TCP_SLOWTMR_NAME +#define IP_REASSTRM_NAME +#define ETHARPTMR_NAME +#define DHCP_COARSETMR_NAME +#define DHCP_FINETMR_NAME +#define AUTOIPTMR_NAME +#define IGMPTMR_NAME +#define DNSTMR_NAME +#define NAT64TMR_NAME +#define ND6TMR_NAME +#define IP6_TREASSTMR_NAME +#define MLD6TMR_NAME +#define DHCP6TMR_NAME +#define LOWPAN6TMR_NAME +#endif + +#define SET_TMR_TICK(tick, val) do { \ + if ((val) > 0) { \ + if ((tick) == 0) { \ + (tick) = (val); \ + } else { \ + (tick) = (tick) > (val) ? (val) : (tick); \ + } \ + } \ +} while (0) + +typedef void (*lwip_timer_handler)(void); +typedef void (*sys_timeout_handler)(void *args); + +/* get time count to trigger */ +typedef u32_t (*get_next_timeout)(void); + +struct timer_handler { + u32_t interval; + lwip_timer_handler handler; + get_next_timeout next_tick; +#if LOWPOWER_TIMER_DEBUG + char *name; +#endif +}; + +struct timer_entry { + u32_t clock_max; /* tmr interval */ + u32_t timeout; + sys_timeout_handler handler; + void *args; + get_next_timeout next_tick; + struct timer_entry *next; +#if LOWPOWER_TIMER_DEBUG + char *name; +#endif + u8_t enable; +}; + +enum timer_state { + LOW_TMR_GETING_TICKS = 0, + LOW_TMR_TIMER_WAITING, + LOW_TMR_TIMER_HANDLING, +}; + +struct timer_mng { + enum timer_state state; + u32_t waiting_time; +}; + +enum lowpower_msg_type { + LOW_NON_BLOCK = 0, + LOW_BLOCK = 1, + LOW_FORCE_NON_BLOCK = 2, +}; + +enum lowpower_mod { + LOW_TMR_LOWPOWER_MOD = 0, + LOW_TMR_NORMAL_MOD = 1, +}; + +#define lowpower_sem_t sys_sem_t +#define LOWPOWER_SEM_WAIT(lock) sys_sem_wait(&(lock)) +#define LOWPOWER_SIGNAL(lock) sys_sem_signal(&(lock)) +#define LOWPOWER_SEM_NEW(lock, val) \ + do { \ + (val) = sys_sem_new(&(lock), 0); \ + } while (0) +#define LOWPOWER_SEM_FREE(lock) sys_sem_free(&(lock)) + +/* all timer use the same timeout step */ +#define STEP_TIMEOUT_TO_TICK(step, type) (((step) * lwip_cyclic_timers[(type)].interval_ms) / TIMEOUT_TICK) +#define STEP_TICK_TO_TIMEOUT(tick, type) (((tick) * TIMEOUT_TICK) / lwip_cyclic_timers[(type)].interval_ms) +#define sys_timeout(msecs, handler, arg) (void)sys_timeout_ext(msecs, handler, arg) + +#define LOW_TMR_DELAY 20 +void sys_timeout_set_wake_time(u32_t val); +u32_t sys_timeout_get_wake_time(void); + +void sys_untimeout(sys_timeout_handler handler, void *arg); +void sys_restart_timeouts(void); +void sys_timeouts_mbox_fetch(sys_mbox_t *mbox, void **msg); +void sys_timeouts_init(void); +err_t sys_timeout_ext(u32_t msecs, sys_timeout_handler handler, void *arg); +u8_t sys_timeout_waiting_long(void); + +void set_lowpower_mod(enum lowpower_mod sw); +enum lowpower_mod get_lowpowper_mod(void); + +#endif /* LOWEPOWER */ + +#endif /* LWIP_HDR_LOWPOWER_H */ \ No newline at end of file diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/lwip_rpl.h b/sdk_liteos/third_party/lwip_sack/include/lwip/lwip_rpl.h new file mode 100644 index 0000000000000000000000000000000000000000..537462ca489828156fb5e47c037a904b3554f7c5 --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/lwip_rpl.h @@ -0,0 +1,59 @@ +/* + * Description: declare RPL APIs + */ +#ifndef __LWIP_RPL_H__ +#define __LWIP_RPL_H__ + +#include "lwip/opt.h" +#include "lwip/netif.h" + +#if LWIP_RIPPLE + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +u8_t lwip_ipv6_routetbl_is_nbr_nexthop(s8_t nbr_idx); +err_t lwip_stop_rpl(void *nif); +uint8_t lwip_rpl_is_br(void); +uint8_t lwip_rpl_is_router(void); +uint8_t lwip_rpl_is_rpl_netif(const struct netif *nif); +struct netif *lwip_rpl_route_netif_lookup(const ip6_addr_t *src, const ip6_addr_t *dest); +err_t lwip_rpl_get_ra_prefix(const struct netif *nif, ip6_addr_t *prefix); +const ip6_addr_t *lwip_rpl_route_nexthop_lookup(struct netif *iface, const ip6_addr_t *ip6addr); +u8_t lwip_rpl_route_is_ipv4sta(void *rte); +void *lwip_rpl_route_entry_lookup(const ip6_addr_t *ip6addr); +struct pbuf *lwip_add_rpi_hdr(struct pbuf *p, u8_t nexth, u16_t hbh_len, u8_t flags); +int lwip_verify_rplext_header(const struct pbuf *p, u16_t ext_opt_offset); +err_t ip6_update_rpi(struct pbuf *p, const struct netif *inp); +u8_t lwip_ipv6_routetbl_is_nbr_nexthop(s8_t nbr_idx); +void lwip_rpl_dao_proxy(const ip6_addr_t *ip6addr, const u8_t *mac, u8_t maclen); +void lwip_rpl_dao_output_proxy_ip4sta(uint32_t *ip4, uint8_t lifetime, uint8_t flags); +err_t lwip_rpl_behind_mbr_node(const ip6_addr_t *target); +err_t lwip_rpl_nonmesh_node(const ip6_addr_t *target); +err_t lwip_rpl_behind_mbr_solicited_node(const ip6_addr_t *target); +err_t lwip_rpl_nonmesh_solicited_node(const ip6_addr_t *target); +void lwip_rpl_set_ip6_iid(const linklayer_addr_t *lladdr, uint8_t mnid, ip6_addr_t *ip6addr); +void lwip_rpl_set_addr_iid(ip6_addr_t *ip6addr, const linklayer_addr_t *lladdr); +err_t lwip_rpl_get_lladdr(const ip6_addr_t *ip6addr, linklayer_addr_t *lladdr); +void lwip_rpl_init(void); +void lwip_rpl_deinit(void); +int rpl_context_init(void); +int rpl_context_deinit(void); +int rpl_context_netif_free(const struct netif *nif); +err_t lwip_rpl_get_default_prefix(ip6_addr_t *prefix, uint8_t *len); +void lwip_rpl_trigger_global_repair(void); +void lwip_rpl_trigger_global_dao(void); +void lwip_rpl_trigger_msta(void); +uint8_t is_connect_to_ap(uint8_t *is_mesh_ap); +uint8_t is_connected_ap(const uint8_t *mac, uint8_t maclen); +uint8_t lwip_rpl_dag_parent_count(void); +uint8_t lwip_is_rpl_running(void); +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif + +#endif /* __LWIP_RPL_H__ */ + diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/lwipopts.h b/sdk_liteos/third_party/lwip_sack/include/lwip/lwipopts.h new file mode 100644 index 0000000000000000000000000000000000000000..56be37d913b8faba6f4a0367da67cd13dc3e1588 --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/lwipopts.h @@ -0,0 +1,1981 @@ +/* + * Description: lwIP Options Configuration + */ + +#ifndef __LWIPOPTS_H__ +#define __LWIPOPTS_H__ + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif +#ifndef LWIP_PLATFORM_PRINT +#define LWIP_PLATFORM_PRINT PRINTK +#endif + + +#ifndef LWIP_GETHOSTBYNAME +#define LWIP_GETHOSTBYNAME 1 +#endif + +#ifndef LWIP_GETPEERNAME +#define LWIP_GETPEERNAME 1 +#endif + +#ifndef LWIP_GETSOCKNAME +#define LWIP_GETSOCKNAME 1 +#endif + +#ifndef LWIP_SMALL_SIZE +#define LWIP_SMALL_SIZE 1 +#endif + +/* only valid when LWIP_SMALL_SIZE is 1, mean small size with MESH function */ +#ifndef LWIP_SMALL_SIZE_MESH +#define LWIP_SMALL_SIZE_MESH 1 +#endif + +#if LWIP_SMALL_SIZE + +#if LWIP_SMALL_SIZE_MESH + +#ifndef LWIP_L3_EVENT_MSG +#define LWIP_L3_EVENT_MSG 1 +#endif + +#ifndef LWIP_ENABLE_MESH_SHELL_CMD +#define LWIP_ENABLE_MESH_SHELL_CMD 1 +#endif + +#ifndef LWIP_RPL +#define LWIP_RPL 0 +#endif + +#ifndef LWIP_RIPPLE +#define LWIP_RIPPLE 1 +#endif + +#ifndef LWIP_NA_PROXY +#define LWIP_NA_PROXY 1 +#endif + +#ifndef LWIP_RA_PREFIX_DYNAMIC +#define LWIP_RA_PREFIX_DYNAMIC 1 +#endif + +#ifndef LWIP_IPV6_MLD +#define LWIP_IPV6_MLD 0 +#endif + +#ifndef LWIP_IPV6_MLD_QUERIER +#define LWIP_IPV6_MLD_QUERIER 0 +#endif + +#ifndef LWIP_MPL +#define LWIP_MPL 0 +#endif + +#ifndef LWIP_MPL_IPV4 +#define LWIP_MPL_IPV4 0 +#endif + +#ifndef LWIP_MPL_IPV4_BCAST +#define LWIP_MPL_IPV4_BCAST 0 +#endif + +#ifndef LWIP_6LOWPAN +#define LWIP_6LOWPAN 0 +#endif + +#ifndef ETH_6LOWPAN +#define ETH_6LOWPAN 1 +#endif + +#ifndef LWIP_IPV6_AUTOCONFIG_DEFAULT +#define LWIP_IPV6_AUTOCONFIG_DEFAULT 1 +#endif + +#ifndef LWIP_DHCP_SUBSTITUTE +#define LWIP_DHCP_SUBSTITUTE 1 +#endif + +#ifndef LWIP_NAT64 +#define LWIP_NAT64 1 +#endif + +#ifndef LWIP_NAT64_MIN_SUBSTITUTE +#define LWIP_NAT64_MIN_SUBSTITUTE 0 +#endif + +#ifndef LWIP_DNS64 +#define LWIP_DNS64 1 +#endif + +#ifndef LWIP_ND6_ROUTER +#define LWIP_ND6_ROUTER 1 +#endif + +#ifndef LWIP_ND6_DAG_PREFIX +#define LWIP_ND6_DAG_PREFIX 1 +#endif + +#ifndef LWIP_USE_L2_METRICS +#define LWIP_USE_L2_METRICS 1 +#endif + +#ifndef LWIP_SO_PRIORITY +#define LWIP_SO_PRIORITY 1 +#endif + +#ifndef LWIP_ENABLE_ROUTER +#define LWIP_ENABLE_ROUTER 1 +#endif + +/* maximum that an AP can associate with others */ +#ifndef LWIP_AP_ASSOCIATE_NUM +#define LWIP_AP_ASSOCIATE_NUM 5 +#endif + +/* maximum of MBRs */ +#ifndef LWIP_MULTI_MBR_NUM +#define LWIP_MULTI_MBR_NUM 8 +#endif + +/* number of nodes at Router side */ +#ifndef LWIP_ROUTER_NBR_NUM +#define LWIP_ROUTER_NBR_NUM 11 +#endif + +#ifndef LWIP_ND6_NUM_DESTINATIONS +#define LWIP_ND6_NUM_DESTINATIONS \ + (LWIP_ND6_NUM_ROUTERS + LWIP_AP_ASSOCIATE_NUM + (LWIP_MULTI_MBR_NUM - 1) + LWIP_ROUTER_NBR_NUM) +#endif /* LWIP_ND6_NUM_DESTINATIONS */ + +#ifndef LWIP_ND6_NUM_NEIGHBORS +#define LWIP_ND6_NUM_NEIGHBORS LWIP_ND6_NUM_DESTINATIONS +#endif + +#ifndef LWIP_ND6_DESTINATIONS_OLDTIME +#define LWIP_ND6_DESTINATIONS_OLDTIME 180 +#endif + +#endif /* LWIP_SMALL_SIZE_MESH */ + +#ifndef LWIP_L3_EVENT_MSG +#define LWIP_L3_EVENT_MSG 0 +#endif + +#if defined (LOSCFG_CONFIG_MQTT) +#ifndef CONFIG_NFILE_DESCRIPTORS +#define CONFIG_NFILE_DESCRIPTORS 1 +#endif +#endif + +#ifndef LWIP_API_MESH +#define LWIP_API_MESH 1 +#endif + +#ifndef LWIP_API_RICH +#define LWIP_API_RICH 0 +#endif + +#ifndef LWIP_ICMP6_ERR_RT_LMT +#define LWIP_ICMP6_ERR_RT_LMT 0 +#endif + +#ifndef LWIP_DHCPS_AGENT_INFO +#define LWIP_DHCPS_AGENT_INFO 0 +#endif + +#ifndef LWIP_SOCK_OPT_ICMP6_FILTER +#define LWIP_SOCK_OPT_ICMP6_FILTER 0 +#endif + +#ifndef LWIP_IPV6_PER_PROTO_CHKSUM +#define LWIP_IPV6_PER_PROTO_CHKSUM 0 +#endif + +#ifndef LWIP_SOCK_OPT_IPV6_UNICAST_HOPS +#define LWIP_SOCK_OPT_IPV6_UNICAST_HOPS 0 +#endif + +#ifndef LWIP_SOCK_OPT_TCP_QUEUE_SEQ +#define LWIP_SOCK_OPT_TCP_QUEUE_SEQ 0 +#endif + +#ifndef LWIP_LINK_MCAST_FILTER +#define LWIP_LINK_MCAST_FILTER 0 +#endif + +#ifndef LWIP_IOCTL_IPV6DPCTD +#define LWIP_IOCTL_IPV6DPCTD 0 +#endif + +#ifndef LWIP_IOCTL_ROUTE +#define LWIP_IOCTL_ROUTE 0 +#endif + +#ifndef LWIP_IOCTL_IF +#define LWIP_IOCTL_IF 0 +#endif + +#ifndef LWIP_IPV6_DUP_DETECT_ATTEMPTS +#define LWIP_IPV6_DUP_DETECT_ATTEMPTS 0 +#endif + +#ifndef LWIP_NETIFAPI_DHCPS_IP +#define LWIP_NETIFAPI_DHCPS_IP 1 +#endif + +#ifndef LWIP_NETIFAPI_GET_ADDR +#define LWIP_NETIFAPI_GET_ADDR 1 +#endif + +#ifndef LWIP_NETIFAPI_LINK_CALLBACK +#define LWIP_NETIFAPI_LINK_CALLBACK 0 +#endif + +#ifndef LWIP_NETIFAPI_MTU +#define LWIP_NETIFAPI_MTU 0 +#endif + +#ifndef LWIP_NETIFAPI_IF_NUM +#define LWIP_NETIFAPI_IF_NUM 0 +#endif + +#ifndef LWIP_NETIFAPI_IF_INDEX +#define LWIP_NETIFAPI_IF_INDEX 0 +#endif + +#ifndef LWIP_NETIFAPI_IF_HW +#define LWIP_NETIFAPI_IF_HW 0 +#endif + +#ifndef LWIP_NETIFAPI_IP6_ADDR +#define LWIP_NETIFAPI_IP6_ADDR 0 +#endif + +#ifndef LWIP_NETIFAPI_MLD6 +#define LWIP_NETIFAPI_MLD6 0 +#endif + +#ifndef LWIP_NETIFAPI_IF_GET_DEFAULT +#define LWIP_NETIFAPI_IF_GET_DEFAULT 0 +#endif + +#ifndef LWIP_IP_FILTER +#define LWIP_IP_FILTER 0 +#endif + +#ifndef LWIP_IPV6_FILTER +#define LWIP_IPV6_FILTER 0 +#endif + +#ifndef LWIP_NETIF_NBR_CACHE_API +#define LWIP_NETIF_NBR_CACHE_API 0 +#endif + +#if defined (CONFIG_NETIF_HOSTNAME) + +#ifndef LWIP_NETIF_HOSTNAME +#define LWIP_NETIF_HOSTNAME 1 +#endif + +#ifndef LWIP_NETIF_GET_HOSTNAME +#define LWIP_NETIF_GET_HOSTNAME 0 +#endif + +#else + +#ifndef LWIP_NETIF_HOSTNAME +#define LWIP_NETIF_HOSTNAME 0 +#endif +#endif + +#ifndef LWIP_IFADDRS +#define LWIP_IFADDRS 0 +#endif + +#ifndef LWIP_ALLOW_SOCKET_CONFIG +#define LWIP_ALLOW_SOCKET_CONFIG 0 +#endif + +#if defined (CONFIG_DHCP_VENDOR_CLASS_IDENTIFIER) +#ifndef LWIP_DHCP_VENDOR_CLASS_IDENTIFIER +#define LWIP_DHCP_VENDOR_CLASS_IDENTIFIER 1 +#endif + +#ifndef LWIP_DHCP_GET_VENDOR_CLASS_IDENTIFIER +#define LWIP_DHCP_GET_VENDOR_CLASS_IDENTIFIER 0 +#endif + +#else + +#ifndef LWIP_DHCP_VENDOR_CLASS_IDENTIFIER +#define LWIP_DHCP_VENDOR_CLASS_IDENTIFIER 0 +#endif +#endif + +#ifndef LWIP_IPV6_DHCP6 +#define LWIP_IPV6_DHCP6 0 +#endif + +#ifndef LWIP_TCP_TLP_SUPPORT +#define LWIP_TCP_TLP_SUPPORT 0 +#endif + +#ifndef LWIP_WND_SCALE +#define LWIP_WND_SCALE 0 +#endif + +#ifndef LWIP_SNTP +#define LWIP_SNTP 0 +#endif + +#ifndef LWIP_SOCK_FILTER +#define LWIP_SOCK_FILTER 0 +#endif + +#ifndef DRIVER_STATUS_CHECK +#define DRIVER_STATUS_CHECK 0 +#endif + +#ifndef IP6_DEBUG +#define IP6_DEBUG 0 +#endif + +#ifndef LWIP_DBG_TYPES_ON +#define LWIP_DBG_TYPES_ON LWIP_DBG_OFF +#endif + +#ifndef LWIP_DEBUG_TIMERNAMES +#define LWIP_DEBUG_TIMERNAMES 0 +#endif + +#ifndef ETHARP_SUPPORT_STATIC_ENTRIES +#define ETHARP_SUPPORT_STATIC_ENTRIES 1 +#endif + +#ifndef LWIP_DHCPS +#define LWIP_DHCPS 1 +#endif + +#ifndef LWIP_STATS +#define LWIP_STATS 0 +#endif + +#ifndef ICMP6_STATS +#define ICMP6_STATS 0 +#endif + +#ifndef LWIP_TCP_INFO +#define LWIP_TCP_INFO 0 +#endif + +#ifndef LWIP_NETIF_ETHTOOL +#define LWIP_NETIF_ETHTOOL 0 +#endif + +#ifndef LWIP_ENABLE_LOS_SHELL_CMD +#define LWIP_ENABLE_LOS_SHELL_CMD 0 +#endif + +#ifndef LWIP_ENABLE_BASIC_SHELL_CMD +#define LWIP_ENABLE_BASIC_SHELL_CMD 1 +#endif + +#ifndef LWIP_ENABLE_MESH_SHELL_CMD +#define LWIP_ENABLE_MESH_SHELL_CMD 0 +#endif + +#ifndef LWIP_RIPPLE +#define LWIP_RIPPLE 0 +#endif + +#ifndef LWIP_RA_PREFIX_DYNAMIC +#define LWIP_RA_PREFIX_DYNAMIC 0 +#endif + +#ifndef LWIP_DHCP_COAP_RELAY +#define LWIP_DHCP_COAP_RELAY 0 +#endif + +#ifndef LWIP_MPL_IPV4_BCAST +#define LWIP_MPL_IPV4_BCAST 0 +#endif + +#ifndef LWIP_6LOWPAN +#define LWIP_6LOWPAN 0 +#endif + +#ifndef ETH_6LOWPAN +#define ETH_6LOWPAN 0 +#endif + +#ifndef LWIP_DHCP_SUBSTITUTE +#define LWIP_DHCP_SUBSTITUTE 0 +#endif + +#ifndef LWIP_DHCPS_MAX_LEASE +#define LWIP_DHCPS_MAX_LEASE 3 +#endif + +#ifndef LWIP_NAT64 +#define LWIP_NAT64 0 +#endif + +#ifndef LWIP_DNS64 +#define LWIP_DNS64 0 +#endif + +#ifndef LWIP_ND6_ROUTER +#define LWIP_ND6_ROUTER 0 +#endif + +#ifndef LWIP_RPL_RS_DAO +#define LWIP_RPL_RS_DAO 0 +#endif + +#ifndef LWIP_SO_BINDTODEVICE +#define LWIP_SO_BINDTODEVICE 1 +#endif + +#ifndef LWIP_SO_DONTROUTE +#define LWIP_SO_DONTROUTE 1 +#endif + +#ifndef LWIP_NUM_SOCKETS_MAX +#define LWIP_NUM_SOCKETS_MAX 9 +#endif + +#ifndef DEFAULT_LWIP_NUM_SOCKETS +#define DEFAULT_LWIP_NUM_SOCKETS 9 +#endif /* DEFAULT_LWIP_NUM_SOCKETS */ + +#ifndef MEMP_NUM_PBUF +#define MEMP_NUM_PBUF 8 +#endif + +#ifndef MEMP_NUM_RAW_PCB +#define MEMP_NUM_RAW_PCB 1 +#endif + +#ifndef MEMP_NUM_TCPIP_MSG_API +#define MEMP_NUM_TCPIP_MSG_API 64 +#endif + +#ifndef MEMP_NUM_TCPIP_MSG_INPKT +#define MEMP_NUM_TCPIP_MSG_INPKT 128 +#endif + +#ifndef MEMP_NUM_NETCONN +#define MEMP_NUM_NETCONN LWIP_CONFIG_NUM_SOCKETS +#endif + +#ifndef MEMP_NUM_NETBUF +#define MEMP_NUM_NETBUF 2 +#endif + +#ifndef MEMP_NUM_ARP_QUEUE +#define MEMP_NUM_ARP_QUEUE 4 +#endif + +#ifndef MEMP_NUM_UDP_PCB +#define MEMP_NUM_UDP_PCB (7 + LWIP_MPL) +#endif + +#ifndef MEMP_NUM_TCP_PCB +#define MEMP_NUM_TCP_PCB 4 +#endif + +#ifndef MEMP_NUM_TCP_PCB_LISTEN +#define MEMP_NUM_TCP_PCB_LISTEN 2 +#endif + +#ifndef MEMP_NUM_TCP_SEG +#define MEMP_NUM_TCP_SEG 128 +#endif + +#ifndef PBUF_POOL_SIZE +#define PBUF_POOL_SIZE 1 +#endif + +#if defined (CONFIG_LWIP_FOR_WIFI_SIGMA) +#ifndef MEMP_NUM_REASSDATA +#define MEMP_NUM_REASSDATA 64 +#endif +#if !defined IP_REASS_MAXAGE +#define IP_REASS_MAXAGE 1 +#endif +#else +#ifndef MEMP_NUM_REASSDATA +#define MEMP_NUM_REASSDATA 5 +#endif +#endif + +#ifndef TCP_SND_BUF +#ifdef CONFIG_HILINK +#define TCP_SND_BUF (12 * 1024) +#else +#define TCP_SND_BUF (65535 / 3) +#endif +#endif + +#ifndef TCP_SND_QUEUELEN +#define TCP_SND_QUEUELEN (TCP_SND_BUF / TCP_MSS) +#endif + +#ifndef TCP_WND +#ifdef CONFIG_HILINK +#define TCP_WND (8 * 1024) +#else +#define TCP_WND ((TCP_SND_BUF * 2) / 3) +#endif +#endif + +#ifndef LWIP_IGMP +#define LWIP_IGMP 1 +#endif + +#ifndef LWIP_DNS_REVERSE +#define LWIP_DNS_REVERSE 0 +#endif + +#ifndef PF_PKT_SUPPORT +#define PF_PKT_SUPPORT 0 +#endif + +#ifndef LWIP_SO_RCVBUF +#define LWIP_SO_RCVBUF 0 +#endif + +#ifndef LWIP_IPV6_MLD +#define LWIP_IPV6_MLD 0 +#endif + +#ifndef LWIP_IPV6_MLD_QUERIER +#define LWIP_IPV6_MLD_QUERIER 0 +#endif + +#ifndef LWIP_ND6_NUM_NEIGHBORS +#define LWIP_ND6_NUM_NEIGHBORS 5 +#endif + +#ifndef LWIP_SO_PRIORITY +#define LWIP_SO_PRIORITY 0 +#endif + +#ifndef LWIP_NETIF_PROMISC +#define LWIP_NETIF_PROMISC 0 +#endif + +#ifndef LWIP_NETBUF_RECVINFO +#define LWIP_NETBUF_RECVINFO 0 +#endif + +#ifndef LWIP_ND6_STATIC_PREFIX +#define LWIP_ND6_STATIC_PREFIX 0 +#endif + +#ifndef LWIP_USE_L2_METRICS +#define LWIP_USE_L2_METRICS 0 +#endif + +#ifndef MEMP_NUM_NETDB +#define MEMP_NUM_NETDB 1 +#endif + +#ifndef DNS_TABLE_SIZE +#define DNS_TABLE_SIZE 2 +#endif + +#ifndef DNS_MAX_IPADDR +#define DNS_MAX_IPADDR 1 +#endif + +#ifndef LWIP_DNS_SECURE +#define LWIP_DNS_SECURE (LWIP_DNS_SECURE_RAND_XID | LWIP_DNS_SECURE_NO_MULTIPLE_OUTSTANDING | LWIP_DNS_SECURE_RAND_SRC_PORT) +#endif + +#ifndef LWIP_ENABLE_ROUTER +#define LWIP_ENABLE_ROUTER 0 +#endif + +#ifndef LWIP_ND6_NUM_ROUTERS +#define LWIP_ND6_NUM_ROUTERS 1 +#endif + +#endif /* LWIP_SMALL_SIZE */ + +#ifndef LWIP_IGMP_REPORT_TIMES +#define LWIP_IGMP_REPORT_TIMES 5 +#endif + +#ifndef LWIP_LIBCOAP +#define LWIP_LIBCOAP 0 +#endif + +#ifndef LWIP_FCNTL +#define LWIP_FCNTL 1 +#endif + +#ifndef LWIP_API_MESH +#define LWIP_API_MESH 1 +#endif + +#ifndef LWIP_L2_NETDEV_STATUS_CALLBACK +#define LWIP_L2_NETDEV_STATUS_CALLBACK 1 +#endif + +#ifndef LWIP_NETIF_STATUS_CALLBACK +#define LWIP_NETIF_STATUS_CALLBACK 1 +#endif + +#ifndef LWIP_TCP_TLP_SUPPORT +#define LWIP_TCP_TLP_SUPPORT 0 +#endif + +#ifndef LWIP_WND_SCALE +#define LWIP_WND_SCALE 0 +#endif + +#ifndef LWIP_TCP_INFO +#define LWIP_TCP_INFO 0 +#endif + +#ifndef LWIP_API_RICH +#define LWIP_API_RICH 1 +#endif + +#ifndef LWIP_DHCPS_AGENT_INFO +#define LWIP_DHCPS_AGENT_INFO 1 +#endif + +#ifndef LWIP_SOCK_OPT_ICMP6_FILTER +#define LWIP_SOCK_OPT_ICMP6_FILTER 1 +#endif + +#ifndef LWIP_IPV6_PER_PROTO_CHKSUM +#define LWIP_IPV6_PER_PROTO_CHKSUM 1 +#endif + +#ifndef LWIP_SOCK_OPT_IPV6_UNICAST_HOPS +#define LWIP_SOCK_OPT_IPV6_UNICAST_HOPS 1 +#endif + +#ifndef LWIP_SOCK_OPT_TCP_QUEUE_SEQ +#define LWIP_SOCK_OPT_TCP_QUEUE_SEQ 1 +#endif + +#ifndef LWIP_LINK_MCAST_FILTER +#define LWIP_LINK_MCAST_FILTER 1 +#endif + +#ifndef LWIP_IOCTL_IPV6DPCTD +#define LWIP_IOCTL_IPV6DPCTD 1 +#endif + +#ifndef LWIP_IOCTL_ROUTE +#define LWIP_IOCTL_ROUTE 1 +#endif + +#ifndef LWIP_IOCTL_IF +#define LWIP_IOCTL_IF 1 +#endif + +#ifndef LWIP_IPV6_DUP_DETECT_ATTEMPTS +#define LWIP_IPV6_DUP_DETECT_ATTEMPTS 1 +#endif + +#ifndef LWIP_NETIFAPI_DHCPS_IP +#define LWIP_NETIFAPI_DHCPS_IP 1 +#endif + +#ifndef LWIP_NETIFAPI_GET_ADDR +#define LWIP_NETIFAPI_GET_ADDR 1 +#endif + +#ifndef LWIP_NETIFAPI_LINK_CALLBACK +#define LWIP_NETIFAPI_LINK_CALLBACK 1 +#endif + +#ifndef LWIP_NETIFAPI_MTU +#define LWIP_NETIFAPI_MTU 1 +#endif + +#ifndef LWIP_NETIFAPI_IF_NUM +#define LWIP_NETIFAPI_IF_NUM 1 +#endif + +#ifndef LWIP_NETIFAPI_IF_INDEX +#define LWIP_NETIFAPI_IF_INDEX 1 +#endif + +#ifndef LWIP_NETIFAPI_IF_HW +#define LWIP_NETIFAPI_IF_HW 1 +#endif + +#ifndef LWIP_NETIFAPI_IP6_ADDR +#define LWIP_NETIFAPI_IP6_ADDR 1 +#endif + +#ifndef LWIP_NETIFAPI_MLD6 +#define LWIP_NETIFAPI_MLD6 1 +#endif + +#ifndef LWIP_NETIFAPI_IF_GET_DEFAULT +#define LWIP_NETIFAPI_IF_GET_DEFAULT 1 +#endif + +#ifndef LWIP_IFADDRS +#define LWIP_IFADDRS 1 +#endif + +#ifndef LWIP_ENABLE_BASIC_SHELL_CMD +#define LWIP_ENABLE_BASIC_SHELL_CMD 1 +#endif + +#ifndef LWIP_ENABLE_MESH_SHELL_CMD +#define LWIP_ENABLE_MESH_SHELL_CMD 1 +#endif + +#ifndef LWIP_NETIF_ETHTOOL +#define LWIP_NETIF_ETHTOOL 0 +#endif + +#ifndef LWIP_RPL_CTX +#define LWIP_RPL_CTX 0 +#endif + +#ifndef LWIP_TFTP +#define LWIP_TFTP 0 +#endif + +#ifndef IP_REASSEMBLY +#define IP_REASSEMBLY 1 +#endif + +#ifndef LWIP_RPL +#define LWIP_RPL 0 +#endif + +#ifndef LWIP_RIPPLE +#define LWIP_RIPPLE 1 +#endif + +#ifndef LWIP_LITEOS_TASK +#define LWIP_LITEOS_TASK 1 +#endif + +#ifndef LWIP_DHCP_COAP_RELAY +#define LWIP_DHCP_COAP_RELAY 0 +#endif + +#ifndef LWIP_NA_PROXY +#define LWIP_NA_PROXY 1 +#endif + +#ifndef LWIP_RA_PREFIX_DYNAMIC +#define LWIP_RA_PREFIX_DYNAMIC 1 +#endif + +#if LWIP_RIPPLE +#if !defined(LWIP_MPL) +#define LWIP_MPL 1 +#endif +#else +#if !defined(LWIP_MPL) +#define LWIP_MPL 0 +#endif +#endif + +#if LWIP_MPL +#if !defined(LWIP_MPL_IPV4) +#define LWIP_MPL_IPV4 1 +#endif +#else +#if !defined(LWIP_MPL_IPV4) +#define LWIP_MPL_IPV4 0 +#endif +#endif + +#ifndef LWIP_MPL_IPV4_BCAST +#define LWIP_MPL_IPV4_BCAST 1 +#endif + +#ifndef LWIP_6LOWPAN +#define LWIP_6LOWPAN 0 +#endif + +#ifndef ETH_6LOWPAN +#define ETH_6LOWPAN 1 +#endif + +#ifndef LWIP_IPV6_AUTOCONFIG_DEFAULT +#define LWIP_IPV6_AUTOCONFIG_DEFAULT 1 +#endif +/** + * LWIP_DHCP_SUBSTITUTE==1: Enables MBR Querying IPv4 address for non-mesh IPv6 STA. + */ +#ifndef LWIP_DHCP_SUBSTITUTE +#define LWIP_DHCP_SUBSTITUTE 1 +#endif + +#ifndef MEM_SIZE +#define MEM_SIZE (512*1024) +#endif + +#ifndef LWIP_PLC +#define LWIP_PLC 0 +#endif + +#ifndef LWIP_IEEE802154 +#define LWIP_IEEE802154 0 +#endif + +#ifndef LWIP_NAT64 +#define LWIP_NAT64 1 +#endif + +#ifndef LWIP_DNS64 +#define LWIP_DNS64 1 +#endif + +#ifndef LWIP_ND6_ROUTER +#define LWIP_ND6_ROUTER 1 +#endif + +#ifndef LWIP_ND6_DAG_PREFIX +#define LWIP_ND6_DAG_PREFIX 1 +#endif + +#ifndef LWIP_ND6_RDNSS_MAX_DNS_SERVERS +#define LWIP_ND6_RDNSS_MAX_DNS_SERVERS 2 +#endif + +#ifndef LWIP_COMPAT_SOCKETS +#define LWIP_COMPAT_SOCKETS 2 +#endif + +#define LWIP_PLATFORM_BYTESWAP 0 + +#ifndef LWIP_LITEOS_COMPAT +#define LWIP_LITEOS_COMPAT 1 +#endif + +/* Set to 1 if target platform is linux */ +#ifndef LWIP_LINUX_COMPAT +#define LWIP_LINUX_COMPAT 0 +#endif + +#define VALUE_TO_STRING(x) #x +#define VALUE(x) VALUE_TO_STRING(x) +#define VAR_NAME_VALUE(var) #var "=" VALUE(var) + +#ifndef LWIP_CHKSUM_ALGORITHM +#define LWIP_CHKSUM_ALGORITHM 4 +#endif + +#ifndef LWIP_PLATFORM_BYTESWAP +#define LWIP_PLATFORM_BYTESWAP 1 +#endif + +#ifndef LWIP_PROVIDE_ERRNO +#define LWIP_PROVIDE_ERRNO 1 +#endif + +/** Define LWIP_COMPAT_MUTEX if the port has no mutexes and binary semaphores + should be used instead */ +#ifndef LWIP_COMPAT_MUTEX +#define LWIP_COMPAT_MUTEX 0 +#endif + +#ifndef LWIP_COMPAT_MUTEX_ALLOWED +#define LWIP_COMPAT_MUTEX_ALLOWED 0 +#endif + +/** @cond liteos + * LWIP_SO_SNDTIMEO==1: Enable send timeout for sockets/netconns and + * SO_SNDTIMEO processing. + */ +#ifndef LWIP_SO_SNDTIMEO +#define LWIP_SO_SNDTIMEO 1 +#endif + +/** + * LWIP_SO_RCVTIMEO==1: Enable receive timeout for sockets/netconns and + * SO_RCVTIMEO processing. + */ +#ifndef LWIP_SO_RCVTIMEO +#define LWIP_SO_RCVTIMEO 1 +#endif + +/** + * LWIP_SO_BINDTODEVICE==1: Enable bind sockets/netconns to specific netif + */ +#ifndef LWIP_SO_BINDTODEVICE +#define LWIP_SO_BINDTODEVICE 1 +#endif + +/** + * LWIP_SO_DONTROUTE==1: Enable don't use universal route entry + */ +#ifndef LWIP_SO_DONTROUTE +#define LWIP_SO_DONTROUTE 1 +#endif + +#ifndef LWIP_SACK +#define LWIP_SACK 1 +#endif + +#if LWIP_SACK +#ifndef LWIP_SACK_PERF_OPT +#define LWIP_SACK_PERF_OPT 1 +#endif +#else +#define LWIP_SACK_PERF_OPT 0 +#endif + +#ifndef LWIP_SACK_CWND_OPT +#define LWIP_SACK_CWND_OPT LWIP_SACK_PERF_OPT +#endif + +#ifndef LWIP_SACK_DATA_SEG_PIGGYBACK +#define LWIP_SACK_DATA_SEG_PIGGYBACK (LWIP_SACK & 1) +#endif +/** @endcond */ +/** +@page RFC-5827 RFC-5827 +@par RFC-5827 Appendix A. Compliance Information +@par Compliant Sections +Appendix A. Research Issues in Adjusting the Duplicate ACK Threshold +@par Behavior Description +Behavior: Reducing the number of duplicate acks for fast retransmit has drawback during minor \n + network reordering.\n + Our node does not realize the mitigations proposed. So MITIGATION A.1, MITIGATION A.2 and + MITIGATION A.3 are not implemented. +*/ +/** @cond liteos */ +#ifndef LWIP_TCP_ER_SUPPORT +#define LWIP_TCP_ER_SUPPORT 1 +#endif + +#if LWIP_SACK +#ifndef LWIP_TCP_TLP_SUPPORT +#define LWIP_TCP_TLP_SUPPORT 1 +#endif +#else +#define LWIP_TCP_TLP_SUPPORT 0 +#endif + +#if LWIP_SACK +#ifndef LWIP_FACK_THRESHOLD_BASED_FR +#define LWIP_FACK_THRESHOLD_BASED_FR 1 +#endif +#else +#define LWIP_FACK_THRESHOLD_BASED_FR 0 +#endif + +#ifndef TCP_OOSEQ_MAX_PBUFS +#ifdef CONFIG_HILINK +#define TCP_OOSEQ_MAX_PBUFS 5 +#else +#define TCP_OOSEQ_MAX_PBUFS 8 +#endif +#endif + +/** + * NO_SYS==1: Provides very minimal functionality. Otherwise, + * use lwIP facilities. + */ +#define NO_SYS 0 + +/* ---------- DEBUG options --------- */ +/* undef LWIP_DEBUG */ +#ifdef LWIP_DEBUG +#ifndef LWIP_DEBUG_INFO +#define LWIP_DEBUG_INFO +#endif +#ifndef LWIP_DEV_DEBUG +#define LWIP_DEV_DEBUG +#endif +#else +#undef LWIP_DEBUG_INFO +#undef LWIP_DEV_DEBUG +#endif +#ifndef LWIP_DBG_TYPES_ON +#define LWIP_DBG_TYPES_ON LWIP_DBG_ON +#endif +#ifndef IP_DEBUG +#define IP_DEBUG LWIP_DBG_OFF +#endif +#ifndef ETHARP_DEBUG +#define ETHARP_DEBUG LWIP_DBG_OFF +#endif +#ifndef NETIF_DEBUG +#define NETIF_DEBUG LWIP_DBG_OFF +#endif +#ifndef NAT64_DEBUG +#define NAT64_DEBUG LWIP_DBG_OFF +#endif + +/* ---------- Memory options ---------- */ +#if LWIP_LITEOS_COMPAT +/** + * MEM_LIBC_MALLOC==1: Use malloc/free/realloc provided by your C-library + * instead of the lwIP internal allocator. Can save code size if you + * already use it. + */ +#define MEM_LIBC_MALLOC 1 +#ifndef MEM_SIZE +#define MEM_SIZE (4*1024*1024) +#endif + +#ifndef MEM_LIBC_MALLOC_TOTAL_SIZE_LIMIT +#define MEM_LIBC_MALLOC_TOTAL_SIZE_LIMIT 0 +#endif + +#define LWIP_DONT_PROVIDE_BYTEORDER_FUNCTIONS 1 +#else +/* + * MEM_SIZE: the size of the heap memory. If the application will send + * a lot of data that needs to be copied, this should be set high. + */ +#ifndef MEM_SIZE +#define MEM_SIZE (512*1024) +#endif + +#endif + +#if MEM_LIBC_MALLOC +#ifndef MEM_PBUF_RAM_SIZE_LIMIT +#define MEM_PBUF_RAM_SIZE_LIMIT 1 +#endif +#endif + +#ifndef MAX_NUM_PID +#define MAX_NUM_PID 128 +#endif + +/** + * Defines the align size of the DMA memory. If set to 1, then not using DMA. + */ +#ifndef MEM_MALLOC_DMA_ALIGN +#if LWIP_LITEOS_COMPAT +#define MEM_MALLOC_DMA_ALIGN 64 +#else +#define MEM_MALLOC_DMA_ALIGN 1 +#endif +#endif + +/** + * Attention: Be careful while configure large sockets number, i.e, greater than 128, for that + * LWIP_NUM_SOCKETS is bind with file system descriptons CONFIG_NFILE_DESCRIPTORS. + * If socket num is large, file descriptions for file system would be small. See vfs_config.h + * for detail. + */ +#ifndef LWIP_NUM_SOCKETS_MAX +#define LWIP_NUM_SOCKETS_MAX 8 // 128 +#endif + +/** + * LWIP_NUM_SOCKETS can be used to override DEFAULT_LWIP_NUM_SOCKETS in lwipopts_*.h + */ +#ifndef LWIP_NUM_SOCKETS + +/** + * DEFAULT_LWIP_NUM_SOCKETS is default number of sockets. + */ +#ifndef DEFAULT_LWIP_NUM_SOCKETS +#define DEFAULT_LWIP_NUM_SOCKETS 8 +#endif /* DEFAULT_LWIP_NUM_SOCKETS */ + +#else /* else LWIP_NUM_SOCKETS */ + +#ifndef DEFAULT_LWIP_NUM_SOCKETS + +#if LWIP_NUM_SOCKETS > 0 +#define DEFAULT_LWIP_NUM_SOCKETS LWIP_NUM_SOCKETS +#else /* else LWIP_NUM_SOCKETS > 0 */ +#define DEFAULT_LWIP_NUM_SOCKETS 8 +#endif /* LWIP_NUM_SOCKETS */ + +#endif /* DEFAULT_LWIP_NUM_SOCKETS */ +#endif /* LWIP_NUM_SOCKETS */ + +/* + * Provides flexibility to use configured values to spread across code + */ +#ifndef LWIP_ALLOW_SOCKET_CONFIG +#define LWIP_ALLOW_SOCKET_CONFIG 1 +#endif + +#if LWIP_ALLOW_SOCKET_CONFIG == 0 +#ifndef LWIP_CONFIG_NUM_SOCKETS +#define LWIP_CONFIG_NUM_SOCKETS DEFAULT_LWIP_NUM_SOCKETS +#endif + +#else /* LWIP_ALLOW_SOCKET_CONFIG */ +#ifndef LWIP_CONFIG_NUM_SOCKETS +extern unsigned int g_lwip_num_sockets; +#define LWIP_CONFIG_NUM_SOCKETS g_lwip_num_sockets +#endif +#endif /* LWIP_ALLOW_SOCKET_CONFIG */ + +/* + * MEMP_NUM_PBUF: the number of memp struct pbufs. If the application + * sends a lot of data out of ROM (or other static memory), this + * should be set high. + */ +#ifndef MEMP_NUM_PBUF +#define MEMP_NUM_PBUF LWIP_CONFIG_NUM_SOCKETS*2 +#endif + +/* + * Defines the number of raw connection PCBs + * (requires the LWIP_RAW option). + */ +#ifndef MEMP_NUM_RAW_PCB +#define MEMP_NUM_RAW_PCB LWIP_CONFIG_NUM_SOCKETS +#endif + +/* + * Defines the number of struct tcpip_msg, which are used + * for callback/timeout API communication. + * (only needed if you use tcpip.c) + */ +#ifndef MEMP_NUM_TCPIP_MSG_API +#define MEMP_NUM_TCPIP_MSG_API 64 +#endif + +/* + * Defines the number of struct tcpip_msg, which are used + * for incoming packets. + * (only needed if you use tcpip.c) + */ +#ifndef MEMP_NUM_TCPIP_MSG_INPKT +#define MEMP_NUM_TCPIP_MSG_INPKT 512 +#endif + +#ifndef MEMP_NUM_NETCONN +#define MEMP_NUM_NETCONN ((LWIP_CONFIG_NUM_SOCKETS) * 4) +#endif + +/* + * Defines the number of struct netbufs. + * (only needed if you use the sequential API, like api_lib.c) + */ +#ifndef MEMP_NUM_NETBUF +#define MEMP_NUM_NETBUF (65535 * 3 * (LWIP_CONFIG_NUM_SOCKETS) / ((IP_FRAG_MAX_MTU) - 20 - 8)) +#endif + +/* + * Defines the number of simulateously queued outgoing + * packets (pbufs) that are waiting for an ARP request (to resolve + * their destination address) to finish. + * (requires the ARP_QUEUEING option) + */ +#ifndef MEMP_NUM_ARP_QUEUE +// #define MEMP_NUM_ARP_QUEUE (65535*LWIP_CONFIG_NUM_SOCKETS/(IP_FRAG_MAX_MTU-20-8)) +#define MEMP_NUM_ARP_QUEUE 30 +#endif + +/** + * Indicates the number of UDP protocol control blocks. One + * per active UDP "connection". + */ +#ifndef MEMP_NUM_UDP_PCB +#define MEMP_NUM_UDP_PCB LWIP_CONFIG_NUM_SOCKETS +#endif + +/** MEMP_NUM_TCP_PCB: Indicates the number of simultaneously active TCP connections. */ +#ifndef MEMP_NUM_TCP_PCB +#define MEMP_NUM_TCP_PCB LWIP_CONFIG_NUM_SOCKETS +#endif + +/** MEMP_NUM_TCP_PCB_LISTEN: Indicates the number of listening TCP connections. */ +#ifndef MEMP_NUM_TCP_PCB_LISTEN +#define MEMP_NUM_TCP_PCB_LISTEN LWIP_CONFIG_NUM_SOCKETS +#endif + +#ifndef IP_FRAG_MAX_MTU +#define IP_FRAG_MAX_MTU 1500 +#endif + +/* + * As per RFC 791, "Every internet module must be able to forward a datagram of 68 + * octets without further fragmentation. This is because an internet header + * may be up to 60 octets, and the minimum fragment is 8 octets." + */ +#ifndef IP_FRAG_MIN_MTU +#define IP_FRAG_MIN_MTU 68 +#endif + +#ifndef IP_REASS_MAX_PBUFS +#define IP_REASS_MAX_PBUFS ((65535 * 2 * (LWIP_CONFIG_NUM_SOCKETS)) / ((IP_FRAG_MAX_MTU) - 20 - 8)) +#endif +/* Max size(65535 + extra buffer(8192) per MAX MTU) */ +#ifndef IP_REASS_MAX_PBUFS_PER_PKT +#define IP_REASS_MAX_PBUFS_PER_PKT ((65535 + 8192) / ((IP_FRAG_MAX_MTU) - 20 - 8)) +#endif + +/* TCP Maximum segment size. */ +#ifdef LWIP_TCP_MSS +#undef TCP_MSS /* ensure TCP_MSS value is overridden by LWIP_TCP_MSS */ +#define TCP_MSS LWIP_TCP_MSS +#else /* LWIP_TCP_MSS */ +#ifndef TCP_MSS +#define TCP_MSS ((IP_FRAG_MAX_MTU) - 20 - 20) +#endif /* TCP_MSS */ +#endif /* LWIP_TCP_MSS */ + +/* MEMP_NUM_TCP_SEG: the number of simultaneously queued TCP + segments. */ +#ifndef MEMP_NUM_TCP_SEG +// #define MEMP_NUM_TCP_SEG (((TCP_SND_BUF*3/2)+TCP_WND)*LWIP_CONFIG_NUM_SOCKETS/TCP_MSS) +#define MEMP_NUM_TCP_SEG 32 +#endif + +/* ---------- Pbuf options ---------- */ +/** PBUF_POOL_SIZE: Indicates the number of buffers in the pbuf pool. */ +#ifndef PBUF_POOL_SIZE +#define PBUF_POOL_SIZE 64 +// #define PBUF_POOL_SIZE 4 +#endif + +/* PBUF_POOL_BUFSIZE: the size of each pbuf in the pbuf pool. */ +#ifndef PBUF_POOL_BUFSIZE +#define PBUF_POOL_BUFSIZE 1550 +#endif + +#ifndef PBUF_LINK_CHKSUM_LEN +#define PBUF_LINK_CHKSUM_LEN 0 +#endif +/* ---------- ARP options ---------- */ +/** + * ARP_QUEUEING==1: Multiple outgoing packets are queued during hardware address + * resolution. By default, only the most recent packet is queued per IP_add + * This is sufficient for most protocols and mainly reduces TCP connection + * startup time. Set this to 1 if you know that your application sends more than one + * packet in a row to an IP_add that is not in the ARP cache. + */ +#ifndef ARP_QUEUEING +#define ARP_QUEUEING 1 +#endif + +/** + * ETHARP_TRUST_IP_MAC==1: Incoming IP packets cause the ARP table to be + * updated with the source MAC and IP address supplied in the packet. + * You may want to disable this if you do not trust LAN peers to have the + * correct addresses, or as a limited approach to attempt to handle + * spoofing. If disabled, lwIP will need to make a new ARP request if + * the peer is not already in the ARP table, adding a little latency. + * The peer is in the ARP table if it requested our address before. + * Also notice that this slows down input processing of every IP packet. + */ +#ifndef ETHARP_TRUST_IP_MAC +#define ETHARP_TRUST_IP_MAC 1 +#endif + +/** + * Defines the number of bytes added before the ethernet header to ensure + * alignment of payload after that header. Since the header is 14 bytes long, + * without this padding, addresses in the IP header will not be aligned + * on a 32-bit boundary. So setting this to 2 can speed up 32-bit-platforms. + */ +#ifndef ETH_PAD_SIZE +#define ETH_PAD_SIZE 2 +#endif + +/** + * ETHARP_SUPPORT_STATIC_ENTRIES==1: Enables code to support static ARP table + * entries (using etharp_add_static_entry/etharp_remove_static_entry). + */ +#ifndef ETHARP_SUPPORT_STATIC_ENTRIES +#define ETHARP_SUPPORT_STATIC_ENTRIES 1 +#endif + +/* ---------- TCP options ---------- */ +#ifndef LWIP_TCP +#define LWIP_TCP 1 +#endif +/* @ingroup Config_TCP + * Defines the TCP TTL value. + */ +#ifndef TCP_TTL +#define TCP_TTL 255 +#endif + +/* + * Controls if TCP should queue segments that arrive out of + * order. Define to 0 if your device is low on memory. + */ +#define TCP_QUEUE_OOSEQ LWIP_TCP + +/** + * Defines the mailbox size for the tcpip thread messages + * The queue size value itself is platform-dependent, but is passed to + * sys_mbox_new() when tcpip_init is called. + */ +#ifndef TCPIP_MBOX_SIZE +#define TCPIP_MBOX_SIZE 512 +#endif + +/** + * Defines the mailbox size for the incoming packets on a + * NETCONN_TCP. The queue size value itself is platform-dependent, but is passed + * to sys_mbox_new() when the recvmbox is created. + */ +#ifndef DEFAULT_TCP_RECVMBOX_SIZE +#define DEFAULT_TCP_RECVMBOX_SIZE 128 +#endif + +/** + * Defines the mailbox size for the incoming connections. + * The queue size value itself is platform-dependent, but is passed to + * sys_mbox_new() when the acceptmbox is created. + */ +#ifndef DEFAULT_ACCEPTMBOX_SIZE +#define DEFAULT_ACCEPTMBOX_SIZE 32 +#endif + +#ifndef MEMP_NUM_REASSDATA +#define MEMP_NUM_REASSDATA (2*LWIP_CONFIG_NUM_SOCKETS) +#endif + +#ifdef LWIP_DBG_PREPROCESSOR +#pragma message(VAR_NAME_VALUE(TCP_MSS)) +#endif + +/* @ingroup Config_TCP + * TCP sender buffer space (bytes). + */ +#ifndef TCP_SND_BUF +#define TCP_SND_BUF 65535 +// #define TCP_SND_BUF 4096 +#endif + +/* + * @ingroup Config_TCP + * TCP sender buffer space (pbufs). This must be at least = 2 *TCP_SND_BUF/TCP_MSS for things to work. + */ +#ifndef TCP_SND_QUEUELEN +#define TCP_SND_QUEUELEN ((8 * (TCP_SND_BUF)) / (TCP_MSS)) +// #define TCP_SND_QUEUELEN 8 +#endif +/** + * @ingroup Config_TCP + * Defines the size of a TCP receive window. + */ +#ifndef TCP_WND +#define TCP_WND 32768 +// #define TCP_WND 4096 +#endif + +/** + * @ingroup Config_TCP + * Defines the Maximum number of retransmissions of data segments. + */ +#ifndef TCP_MAXRTX +#define TCP_MAXRTX 15 +#endif + +/* ---------- IP options ---------- */ +/** + * IP_FRAG_USES_STATIC_BUF==1: Use a static MTU-sized buffer for IP + * fragmentation. Otherwise pbufs are allocated and reference the original + * packet data to be fragmented (or with LWIP_NETIF_TX_SINGLE_PBUF==1, + * new PBUF_RAM pbufs are used for fragments). + * Note: IP_FRAG_USES_STATIC_BUF==1 may not be used for DMA-enabled MACs. + */ +#ifndef IP_FRAG_USES_STATIC_BUF +#define IP_FRAG_USES_STATIC_BUF 1 +#endif + +/* + * Defines the assumed maximum MTU on any interface for IP fragment buffer + * (requires IP_FRAG_USES_STATIC_BUF==1) + */ +#if IP_FRAG_USES_STATIC_BUF && !defined(IP_FRAG_MAX_MTU) +#define IP_FRAG_MAX_MTU 1500 +#endif + +/* + * As per RFC 791, "Every internet module must be able to forward a datagram of 68 + * octets without further fragmentation. This is because an internet header + * may be up to 60 octets, and the minimum fragment is 8 octets." + */ +#if IP_FRAG_USES_STATIC_BUF && !defined(IP_FRAG_MIN_MTU) +#define IP_FRAG_MIN_MTU 68 +#endif + +/* ---------- ICMP options ---------- */ +/** + * LWIP_ICMP==1: Enables the ICMP module inside the IP stack. + */ +#ifndef LWIP_ICMP +#define LWIP_ICMP 1 +#endif + +/* ---------- IGMP options ---------- */ +#ifndef LWIP_IGMP +#define LWIP_IGMP 1 +#endif + +/* ---------- DHCP options ---------- */ +/** + * LWIP_DHCP==1: Enables the DHCP module. + */ +#ifndef LWIP_DHCP +#define LWIP_DHCP 1 +#endif + +/* ---------- DNS options ---------- */ +/** + * LWIP_DNS==1: Turn on DNS module. UDP must be available for DNS + * transport. + */ +#ifndef LWIP_DNS +#define LWIP_DNS 1 +#endif + +#if LWIP_DNS +#ifndef LWIP_DNS_REVERSE +#define LWIP_DNS_REVERSE 1 +#endif +#else +#undef LWIP_DNS_REVERSE +#define LWIP_DNS_REVERSE 0 +#endif + +/* ---------- UDP options ---------- */ +/** + * LWIP_UDP==1: Turns on UDP. + */ +#ifndef LWIP_UDP +#define LWIP_UDP 1 +#endif + +#ifndef UDP_TTL +#define UDP_TTL 255 +#endif +/** + * Defines the mailbox size for the incoming packets on a + * NETCONN_UDP. The queue size value itself is platform-dependent, but is passed + * to sys_mbox_new() when the recvmbox is created. + */ +#ifndef DEFAULT_UDP_RECVMBOX_SIZE +#define DEFAULT_UDP_RECVMBOX_SIZE 128 +#endif + +/* -----------RAW options -----------*/ +#ifndef DEFAULT_RAW_RECVMBOX_SIZE + +/** + * LWIP_RAW==1: Enables the application layer to hook into the IP layer itself. + */ +#if !defined LWIP_RAW || defined __DOXYGEN__ +#define LWIP_RAW 1 +#endif + +/** + * Enable to support PF_PACKET RAW sockets +*/ +#if defined(LWIP_RAW) && LWIP_RAW +#ifndef PF_PKT_SUPPORT +#define PF_PKT_SUPPORT 1 +#endif +#endif + +/** + * Defines the mailbox size for the incoming packets on a + * NETCONN_RAW. The queue size value itself is platform-dependent, but is passed + * to sys_mbox_new() when the recvmbox is created. + */ +#define DEFAULT_RAW_RECVMBOX_SIZE 128 +#endif + +#ifndef LWIP_MAX_PF_RAW_SEND_SIZE +#define LWIP_MAX_PF_RAW_SEND_SIZE (0xFFFF - 40) // - IPv6 header +#endif + +/* -----------LOOPIF options -----------*/ +#ifndef LWIP_HAVE_LOOPIF +#define LWIP_HAVE_LOOPIF 1 +#endif + +/* -----------LOOPBACK options -----------*/ +#ifndef LWIP_NETIF_LOOPBACK +#define LWIP_NETIF_LOOPBACK 1 +#endif + +/* ---------- Statistics options ---------- */ +/** + * LWIP_STATS==1: Enables statistics gathering in lwip_stats. + */ +#ifndef LWIP_STATS +#define LWIP_STATS 1 +#endif + +/* ---------- TFTP options ---------- */ +#ifndef LWIP_TFTP +#define LWIP_TFTP 1 +#endif + +/* ---------- SNTP options ---------- */ +#ifndef LWIP_SNTP +#define LWIP_SNTP 0 +#endif + +/** + * SO_REUSE==1: Enable SO_REUSEADDR option. + */ +#ifndef SO_REUSE +#define SO_REUSE 1 +#endif + +#define LWIP_ETHERNET 1 +#define LWIP_NETCONN 1 +#define LWIP_SOCKET 1 + +#ifndef IP_FORWARD +#define IP_FORWARD 0 +#endif + +#define LWIP_DHCPS_DISCOVER_BROADCAST 0 + +#if defined (CONFIG_DHCPS_GW) +#ifndef LWIP_DHCPS_GW +#define LWIP_DHCPS_GW 1 +#endif +#else +#ifndef LWIP_DHCPS_GW +#define LWIP_DHCPS_GW 0 +#endif +#endif + +#ifndef LWIP_DHCP_REQUEST_UNICAST +#define LWIP_DHCP_REQUEST_UNICAST 0 +#endif + +#if LWIP_LITEOS_COMPAT +#ifndef TCPIP_THREAD_STACKSIZE +#define TCPIP_THREAD_STACKSIZE 0x6000 +#endif +#ifndef TCPIP_THREAD_PRIO +#define TCPIP_THREAD_PRIO 5 +#endif + +#ifndef LWIP_SOCKET_START_NUM +#define LWIP_SOCKET_START_NUM CONFIG_NFILE_DESCRIPTORS +#endif + +#ifndef LWIP_SOCKET_OFFSET +#define LWIP_SOCKET_OFFSET CONFIG_NFILE_DESCRIPTORS +#endif + +#ifndef LWIP_ENABLE_LOS_SHELL_CMD +#define LWIP_ENABLE_LOS_SHELL_CMD 1 +#endif +#ifndef ERRNO +#define ERRNO +#endif +#ifndef LWIP_PROVIDE_ERRNO +#define LWIP_PROVIDE_ERRNO 0 +#endif +/* Currently pthread_cond_timedwait() in liteos doesn't support absolute time */ +#ifndef LWIP_USE_POSIX_COND_WAIT_WITH_ABS_TIMEOUT +#define LWIP_USE_POSIX_COND_WAIT_WITH_ABS_TIMEOUT 0 +#endif + +#ifndef LWIP_INET_ADDR_FUNC +#define LWIP_INET_ADDR_FUNC 1 +#endif + +#ifndef LWIP_INET_NTOA_FUNC +#define LWIP_INET_NTOA_FUNC 1 +#endif + +#ifndef LWIP_INET_ATON_FUNC +#define LWIP_INET_ATON_FUNC 1 +#endif + +#else +#define ERRNO +#define LWIP_PROVIDE_ERRNO 1 + +#ifndef LWIP_INET_ADDR_FUNC +#define LWIP_INET_ADDR_FUNC 1 +#endif + +#ifndef LWIP_INET_NTOA_FUNC +#define LWIP_INET_NTOA_FUNC 1 +#endif + +#ifndef LWIP_INET_ATON_FUNC +#define LWIP_INET_ATON_FUNC 1 +#endif + +#endif + +/* ---------- Socket Filter options ---------- */ +/** + * implement sock filter based on BPF. + * BPF-extension was not supported. + * only AF_PACKET RAW socket support socket filter now, + * we would add supports for other socket type in the feature. +*/ +#if defined(LWIP_RAW) && LWIP_RAW +#ifndef LWIP_SOCK_FILTER +#define LWIP_SOCK_FILTER 1 +#endif +#else +#define LWIP_SOCK_FILTER 0 +#endif + +/* Requesting application to configure a cryptographically strong random number generator to LWIP_RAND macro */ +#if LWIP_LITEOS_COMPAT && LWIP_API_MESH +#ifndef LWIP_RAND +unsigned int sys_arch_rand(void); +#define LWIP_RAND sys_arch_rand +#endif +#else +#ifndef LWIP_RAND +#define LWIP_RAND rand +#endif +#endif + +#ifndef LWIP_STATIC +#define LWIP_STATIC static +#endif + +#ifndef LWIP_ALWAYS_SEND_HWTYPE_AS_ETHER_IN_DHCP +#define LWIP_ALWAYS_SEND_HWTYPE_AS_ETHER_IN_DHCP 1 +#endif + +#ifndef USE_ONLY_PRIMARY_IFACE +#define USE_ONLY_PRIMARY_IFACE 1 +#endif + +#ifndef DRIVER_STATUS_CHECK +#define DRIVER_STATUS_CHECK 0 +#endif + +#if DRIVER_STATUS_CHECK +#ifndef DRIVER_WAKEUP_INTERVAL +#define DRIVER_WAKEUP_INTERVAL 120000 +#endif +#endif + +/* ---------- NETIF options ---------- */ +/** + * LWIP_NETIF_API==1: Supports netif api (in netifapi.c) + */ +#ifndef LWIP_NETIF_API +#define LWIP_NETIF_API 1 +#endif + +/** + * LWIP_NETIF_EXT_STATUS_CALLBACK==1: Support an extended callback function + * for several netif related event that supports multiple subscribers. + * @see netif_ext_status_callback + */ +#ifndef LWIP_NETIF_EXT_STATUS_CALLBACK +#define LWIP_NETIF_EXT_STATUS_CALLBACK 1 +#endif + +/* + * LWIP_NETIF_LINK_CALLBACK==1: Supports a callback function from an interface + * whenever the link changes. Example: when link goes down. + */ +#ifndef LWIP_NETIF_LINK_CALLBACK +#define LWIP_NETIF_LINK_CALLBACK 1 +#endif + +/* + * LWIP_NETIF_NUM_MAX==255: Defines the maximum support number of same type netif. + */ +/* + * Increase the count of netifs supported by stack. + * Currently stack restricts the number of netif to 5, but older versions of linux kernel supports + * upto 255 interfaces . New versions donot have these restrictions but we stick to 10 + */ +#ifndef LWIP_NETIF_NUM_MAX +#define LWIP_NETIF_NUM_MAX 10 +#endif + +/* ---------- SOCKET options ---------- */ +/** + * LWIP_SO_RCVBUF==1: Enables SO_RCVBUF processing. + */ +#ifndef LWIP_SO_RCVBUF +#define LWIP_SO_RCVBUF 1 +#endif + +/* ---------- Statistics options ---------- */ +/** + * LWIP_STATS_DISPLAY==1: Compile in the statistics output functions. + */ +#ifndef LWIP_STATS_DISPLAY +#define LWIP_STATS_DISPLAY 0 +#endif + +/* ---------- Debugging options ---------- */ +/** + * LWIP_DBG_MIN_LEVEL: After masking, the value of the debug is + * compared against this value. If it is smaller, then debugging + * messages are written. + */ +#ifndef LWIP_DBG_MIN_LEVEL +#define LWIP_DBG_MIN_LEVEL LWIP_DBG_LEVEL_OFF +#endif + +/** + * LWIP_DBG_TYPES_ON: A mask that can be used to globally enable/disable + * debug messages of certain types. + * @endcond + */ +#ifndef LWIP_DBG_TYPES_ON +#define LWIP_DBG_TYPES_ON LWIP_DBG_OFF +#endif + +#ifndef LWIP_SOCKET_POLL +#define LWIP_SOCKET_POLL 0 +#endif + +/** + * LWIP_TCP_INFO==1: support get tcp info by getsockopt API + */ +#ifndef LWIP_TCP_INFO +#define LWIP_TCP_INFO 1 +#endif + +#ifndef PBUF_API +#define PBUF_API 0 +#endif + +#if (0 == LWIP_RPL) && (0 == LWIP_RIPPLE) +#ifndef LWIP_RPL_TIMER_COUNT +#define LWIP_RPL_TIMER_COUNT 0 +#endif +#ifndef LWIP_IPV6_FORWARD +#define LWIP_IPV6_FORWARD 0 +#endif +#ifndef LWIP_IEEE802154 +#define LWIP_IEEE802154 0 +#endif +#else /* LWIP_RPL */ +#ifndef LWIP_RPL_TIMER_COUNT +#define LWIP_RPL_TIMER_COUNT 12 +#endif +#ifndef LWIP_IPV6_FORWARD +#define LWIP_IPV6_FORWARD 1 +#endif + +#ifndef LWIP_NETIF_NBR_CACHE_API +#define LWIP_NETIF_NBR_CACHE_API 1 +#endif + +#ifndef LWIP_RPL_DEBUG +#define LWIP_RPL_DEBUG 1 +#endif +#ifndef LWIP_IEEE802154 +#define LWIP_IEEE802154 1 +#endif +#endif /* LWIP_RPL */ + +#ifndef LWIP_RIPPLE_TIMER_COUNT +#if LWIP_RIPPLE +#define LWIP_RIPPLE_TIMER_COUNT 3 +#else +#define LWIP_RIPPLE_TIMER_COUNT 0 +#endif +#endif + +#ifndef LWIP_IPV6_MLD +#define LWIP_IPV6_MLD 1 +#endif + +#ifndef LWIP_IPV6_MLD_QUERIER +#define LWIP_IPV6_MLD_QUERIER 1 +#endif + +#ifndef LWIP_MLD6_ENABLE_MLD_ON_DAD +#define LWIP_MLD6_ENABLE_MLD_ON_DAD LWIP_IPV6 && LWIP_IPV6_MLD +#endif + +#ifndef LWIP_MLD6_DONE_ONLYFOR_LAST_REPORTER +#define LWIP_MLD6_DONE_ONLYFOR_LAST_REPORTER LWIP_IPV6 && LWIP_IPV6_MLD +#endif +#ifndef NETIF_MAX_HWADDR_LEN +#define NETIF_MAX_HWADDR_LEN 6 +#endif + +#ifndef LWIP_ND6_NUM_NEIGHBORS +#define LWIP_ND6_NUM_NEIGHBORS 10 +#endif + +#ifndef VPPRPL_CONF_RPL_TARGET_ENV +#define VPPRPL_CONF_RPL_TARGET_ENV 3 +#endif + +#ifndef VPPRPL_CONF_LL_80211 +#define VPPRPL_CONF_LL_80211 1 +#endif + +#ifndef VPPRPL_CONF_RPL_CTRLMSG_WITHIPV6_HEDAER +#define VPPRPL_CONF_RPL_CTRLMSG_WITHIPV6_HEDAER 0 +#endif + +#ifndef RPL_CONF_MOP +#define RPL_CONF_MOP 2 +#ifndef LWIP_IPV6_NUM_ROUTE_ENTRIES +#define LWIP_IPV6_NUM_ROUTE_ENTRIES 128 +#endif // LWIP_IPV6_NUM_ROUTE_ENTRIES +#define VPPRPL_CONF_NUM_ROUTES_IN_SMOP LWIP_IPV6_NUM_ROUTE_ENTRIES +#endif + +#if RPL_CONF_MOP == 4 +#define UIP_RPL_CONF_MAX_NSMOP_NODES 128 +#endif + +#ifndef LWIP_SO_PRIORITY +#define LWIP_SO_PRIORITY 1 +#endif + +#ifndef LWIP_ND6_STATIC_NBR +#define LWIP_ND6_STATIC_NBR 0 +#endif + +#ifndef LWIP_NETIF_PROMISC +#define LWIP_NETIF_PROMISC 1 +#endif + +#ifndef LWIP_MAC_SECURITY +#define LWIP_MAC_SECURITY 0 +#endif + +#ifndef LWIP_STATS_API +#define LWIP_STATS_API 1 +#endif + +#ifndef LWIP_NETBUF_RECVINFO +#define LWIP_NETBUF_RECVINFO 1 +#endif + +#ifndef LWIP_ND6_STATIC_PREFIX +#define LWIP_ND6_STATIC_PREFIX 0 +#endif + +#ifndef RPL_CONF_STATS +#define RPL_CONF_STATS 0 +#endif + +#ifndef LWIP_RPL_ROUTE_MEM_OPTIMIZE +#define LWIP_RPL_ROUTE_MEM_OPTIMIZE 1 +#endif + +#ifndef RPL_CONF_DIO_INTERVAL_MIN +#define RPL_CONF_DIO_INTERVAL_MIN 11 +#endif + +#ifndef DNS_MAX_IPADDR +#define DNS_MAX_IPADDR 4 +#endif /* DNS_MAX_IPADDR */ + +#ifndef MEMP_NUM_ND6_QUEUE +#define MEMP_NUM_ND6_QUEUE 4 +#endif /* MEMP_NUM_ND6_QUEUE */ + +#ifndef LWIP_ND6_NUM_DESTINATIONS +#define LWIP_ND6_NUM_DESTINATIONS 4 +#endif /* LWIP_ND6_NUM_DESTINATIONS */ + +#ifndef LWIP_ND6_MAX_PREFIX_ON_INTERFACE +#define LWIP_ND6_MAX_PREFIX_ON_INTERFACE 2 +#endif /* LWIP_ND6_MAX_PREFIX_ON_INTERFACE */ + +#ifndef LWIP_6LOWPAN +#define LWIP_6LOWPAN 0 +#endif /* LWIP_6LOWPAN */ + +#ifndef LWIP_USE_L2_METRICS /* L2 metrics are used for mesh networks */ +#define LWIP_USE_L2_METRICS 1 +#endif /* LWIP_USE_L2_METRICS */ + +#ifndef LWIP_NBRPOLICY_ENABLE_NBR_RESTRICTION +#if LWIP_RPL +#define LWIP_NBRPOLICY_ENABLE_NBR_RESTRICTION 1 +#else +#define LWIP_NBRPOLICY_ENABLE_NBR_RESTRICTION 0 +#endif /* LWIP_RPL */ +#endif + +#ifndef SLIPIF_THREAD_STACKSIZE +#define SLIPIF_THREAD_STACKSIZE 1024 +#endif + +#ifndef SLIPIF_THREAD_PRIO +#define SLIPIF_THREAD_PRIO 25 +#endif + +#ifndef LWIP_L3_EVENT_MSG +#define LWIP_L3_EVENT_MSG 1 +#endif + +#if LWIP_L3_EVENT_MSG + +#ifndef MEMP_NUM_L3_EVENT_MSG +#define MEMP_NUM_L3_EVENT_MSG 15 +#endif + +#ifndef LWIP_ROUTE_CHANGE_MSG +#define LWIP_ROUTE_CHANGE_MSG 1 +#endif + +#ifndef LWIP_RPL_JOIN_SUCC_MSG +#define LWIP_RPL_JOIN_SUCC_MSG 1 +#endif + +#ifndef LWIP_RPL_PARENT_CLEAR_MSG +#define LWIP_RPL_PARENT_CLEAR_MSG 1 +#endif + +#ifndef LWIP_RPL_BEACON_PRI_RESET +#define LWIP_RPL_BEACON_PRI_RESET 1 +#endif + +#ifndef LWIP_RPL_GET_IPV4_ADDR_FAIL +#define LWIP_RPL_GET_IPV4_ADDR_FAIL 1 +#endif + +#ifndef LWIP_RPL_MSTA_GET_IPV4_ADDR_FAIL +#define LWIP_RPL_MSTA_GET_IPV4_ADDR_FAIL 1 +#endif + +#ifndef LWIP_RPL_MG_FULL +#define LWIP_RPL_MG_FULL 1 +#endif + +#ifndef LWIP_RPL_RT_FULL +#define LWIP_RPL_RT_FULL 1 +#endif + +#ifndef LWIP_L3_EVENT_MSG_EXIST +#if (LWIP_ROUTE_CHANGE_MSG || LWIP_RPL_JOIN_SUCC_MSG || \ + LWIP_RPL_PARENT_CLEAR_MSG || LWIP_RPL_BEACON_PRI_RESET || \ + LWIP_RPL_GET_IPV4_ADDR_FAIL || LWIP_RPL_MSTA_GET_IPV4_ADDR_FAIL || \ + LWIP_RPL_MG_FULL || LWIP_RPL_RT_FULL) +#define LWIP_L3_EVENT_MSG_EXIST 1 +#else +#define LWIP_L3_EVENT_MSG_EXIST 0 +#endif +#endif + +#endif /* LWIP_L3_EVENT_MSG */ + +#if defined (__cplusplus) && __cplusplus +} +#endif /* __cplusplus */ + +#endif /* __LWIPOPTS_H__ */ + diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/lwipopts_dev.h b/sdk_liteos/third_party/lwip_sack/include/lwip/lwipopts_dev.h new file mode 100644 index 0000000000000000000000000000000000000000..8e0fdc9d3bcf75695ee7b52b0692b97d5a5e3a9d --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/lwipopts_dev.h @@ -0,0 +1,872 @@ +/* + * Description: lwIP Options Configuration + */ + +#ifndef __LWIPOPTS_H__ +#define __LWIPOPTS_H__ + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif /* __cplusplus */ + +#ifndef LWIP_LITEOS_COMPAT +#define LWIP_LITEOS_COMPAT 1 +#endif + +/* Set to 1 if target platform is linux */ +#ifndef LWIP_LINUX_COMPAT +#define LWIP_LINUX_COMPAT 0 +#endif + +#ifndef LWIP_COMPAT_SOCKETS +#define LWIP_COMPAT_SOCKETS 2 +#define LWIP_POSIX_SOCKETS_IO_NAMES 0 +#endif + +#define LWIP_DONT_PROVIDE_BYTEORDER_FUNCTIONS 1 + +#define VALUE_TO_STRING(x) #x +#define VALUE(x) VALUE_TO_STRING(x) +#define VAR_NAME_VALUE(var) #var "=" VALUE(var) + +#ifndef LWIP_CHKSUM_ALGORITHM +#define LWIP_CHKSUM_ALGORITHM 4 +#endif + +#ifndef LWIP_PLATFORM_BYTESWAP +#define LWIP_PLATFORM_BYTESWAP 1 +#endif + +#ifndef LWIP_NETIF_IFINDEX_MAX +#define LWIP_NETIF_IFINDEX_MAX 0xFE +#endif + +#ifndef LWIP_PROVIDE_ERRNO +#define LWIP_PROVIDE_ERRNO 1 +#endif + +/** Define LWIP_COMPAT_MUTEX if the port has no mutexes and binary semaphores + should be used instead */ +#ifndef LWIP_COMPAT_MUTEX +#define LWIP_COMPAT_MUTEX 0 +#endif + +#ifndef LWIP_COMPAT_MUTEX_ALLOWED +#define LWIP_COMPAT_MUTEX_ALLOWED 0 +#endif + +/** + * LWIP_SO_SNDTIMEO==1: Enable send timeout for sockets/netconns and + * SO_SNDTIMEO processing. + */ +#ifndef LWIP_SO_SNDTIMEO +#define LWIP_SO_SNDTIMEO 1 +#endif + +/** + * LWIP_SO_RCVTIMEO==1: Enable receive timeout for sockets/netconns and + * SO_RCVTIMEO processing. + */ +#ifndef LWIP_SO_RCVTIMEO +#define LWIP_SO_RCVTIMEO 1 +#endif + +/** + * LWIP_SO_BINDTODEVICE==1: Enable bind sockets/netconns to specific netif + */ +#ifndef LWIP_SO_BINDTODEVICE +#define LWIP_SO_BINDTODEVICE 1 +#endif + +/** + * LWIP_SO_DONTROUTE==1: Enable don't use universal route entry + */ +#ifndef LWIP_SO_DONTROUTE +#define LWIP_SO_DONTROUTE 1 +#endif + +#ifndef LWIP_SACK +#define LWIP_SACK 1 +#endif + +#if LWIP_SACK +#ifndef LWIP_SACK_PERF_OPT +#define LWIP_SACK_PERF_OPT 1 +#endif +#else +#define LWIP_SACK_PERF_OPT 0 +#endif + +#ifndef LWIP_SACK_CWND_OPT +#define LWIP_SACK_CWND_OPT LWIP_SACK_PERF_OPT +#endif + +#ifndef LWIP_SACK_DATA_SEG_PIGGYBACK +#define LWIP_SACK_DATA_SEG_PIGGYBACK (LWIP_SACK & 1) +#endif + +/* + * @page RFC-5827 + * @par RFC-5827 Appendix A. Compliance Information + * @par Compliant Sections + * + * @par Behavior Description + * + */ +#ifndef LWIP_TCP_ER_SUPPORT +#define LWIP_TCP_ER_SUPPORT 1 +#endif + +#if LWIP_SACK +#ifndef LWIP_TCP_TLP_SUPPORT +#define LWIP_TCP_TLP_SUPPORT 1 +#endif +#else +#define LWIP_TCP_TLP_SUPPORT 0 +#endif + +#if LWIP_SACK +#ifndef LWIP_FACK_THRESHOLD_BASED_FR +#define LWIP_FACK_THRESHOLD_BASED_FR 1 +#endif +#else +#define LWIP_FACK_THRESHOLD_BASED_FR 0 +#endif + +/** + * NO_SYS==1: Provides very minimal functionality. Otherwise, + * use lwIP facilities. + */ +#define NO_SYS 0 + +/* ---------- DEBUG options --------- */ +#ifndef LWIP_DEV_DEBUG +#define LWIP_DEV_DEBUG +#endif + +/* LWIP_DEBUG_INFO is opened by default. */ +#ifndef LWIP_DEBUG_INFO +#define LWIP_DEBUG_INFO +#endif +#ifndef LWIP_DBG_TYPES_ON +#define LWIP_DBG_TYPES_ON LWIP_DBG_ON +#endif +#ifndef IP_DEBUG +#define IP_DEBUG LWIP_DBG_OFF +#endif +#ifndef ETHARP_DEBUG +#define ETHARP_DEBUG LWIP_DBG_OFF +#endif +#ifndef NETIF_DEBUG +#define NETIF_DEBUG LWIP_DBG_OFF +#endif + +#if LWIP_LITEOS_COMPAT +/** + * MEM_LIBC_MALLOC==1: Use malloc/free/realloc provided by your C-library + * instead of the lwIP internal allocator. Can save code size if you + * already use it. + */ +#define MEM_LIBC_MALLOC 1 +#ifndef MEM_SIZE +#define MEM_SIZE (4*1024*1024) +#endif + +#ifndef MEM_LIBC_MALLOC_TOTAL_SIZE_LIMIT +#define MEM_LIBC_MALLOC_TOTAL_SIZE_LIMIT 0 +#endif + +#define LWIP_DONT_PROVIDE_BYTEORDER_FUNCTIONS 1 +#else +/* + * MEM_SIZE: the size of the heap memory. If the application will send + * a lot of data that needs to be copied, this should be set high. + */ +#ifndef MEM_SIZE +#define MEM_SIZE (512*1024) +#endif + +#endif + +#if MEM_LIBC_MALLOC +#ifndef MEM_PBUF_RAM_SIZE_LIMIT +#define MEM_PBUF_RAM_SIZE_LIMIT 1 +#endif +#endif + +#ifndef MAX_NUM_PID +#define MAX_NUM_PID 128 +#endif + +/** + * Defines the align size of the DMA memory. If set to 1, then not using DMA. + */ +#ifndef MEM_MALLOC_DMA_ALIGN +#if LWIP_LITEOS_COMPAT +#define MEM_MALLOC_DMA_ALIGN 64 +#else +#define MEM_MALLOC_DMA_ALIGN 1 +#endif +#endif + +/** + * Attention: Be careful while configure large sockets number, i.e, greater than 128, for that + * LWIP_NUM_SOCKETS is bind with file system descriptons CONFIG_NFILE_DESCRIPTORS. + * If socket num is large, file descriptions for file system would be small. See vfs_config.h + * for detail. + */ +#ifndef LWIP_NUM_SOCKETS_MAX +#define LWIP_NUM_SOCKETS_MAX 128 +#endif + +/** + * LWIP_NUM_SOCKETS can be used to override DEFAULT_LWIP_NUM_SOCKETS in lwipopts_*.h + */ +#ifndef LWIP_NUM_SOCKETS + +/** + * DEFAULT_LWIP_NUM_SOCKETS is default number of sockets. + */ +#ifndef DEFAULT_LWIP_NUM_SOCKETS +#define DEFAULT_LWIP_NUM_SOCKETS 128 +#endif /* DEFAULT_LWIP_NUM_SOCKETS */ + +#else /* else LWIP_NUM_SOCKETS */ + +#ifndef DEFAULT_LWIP_NUM_SOCKETS + +#if LWIP_NUM_SOCKETS > 0 +#define DEFAULT_LWIP_NUM_SOCKETS LWIP_NUM_SOCKETS +#else /* else LWIP_NUM_SOCKETS > 0 */ +#define DEFAULT_LWIP_NUM_SOCKETS 128 +#endif /* LWIP_NUM_SOCKETS */ + +#endif /* DEFAULT_LWIP_NUM_SOCKETS */ +#endif /* LWIP_NUM_SOCKETS */ + +/* + * Provides flexibility to use configured values to spread across code + */ +#ifndef LWIP_ALLOW_SOCKET_CONFIG +#define LWIP_ALLOW_SOCKET_CONFIG 1 +#endif + +#if LWIP_ALLOW_SOCKET_CONFIG == 0 +#ifndef LWIP_CONFIG_NUM_SOCKETS +#define LWIP_CONFIG_NUM_SOCKETS DEFAULT_LWIP_NUM_SOCKETS +#endif + +#else /* LWIP_ALLOW_SOCKET_CONFIG */ +#ifndef LWIP_CONFIG_NUM_SOCKETS +extern unsigned int g_lwip_num_sockets; +#define LWIP_CONFIG_NUM_SOCKETS ((int)g_lwip_num_sockets) +#endif +#endif /* LWIP_ALLOW_SOCKET_CONFIG */ + +/* + * MEMP_NUM_PBUF: the number of memp struct pbufs. If the application + * sends a lot of data out of ROM (or other static memory), this + * should be set high. + */ +#ifndef MEMP_NUM_PBUF +#define MEMP_NUM_PBUF ((LWIP_CONFIG_NUM_SOCKETS) * 2) +#endif + +/* + * Defines the number of raw connection PCBs + * (requires the LWIP_RAW option). + */ +#ifndef MEMP_NUM_RAW_PCB +#define MEMP_NUM_RAW_PCB LWIP_CONFIG_NUM_SOCKETS +#endif + +/* + * Defines the number of struct tcpip_msg, which are used + * for callback/timeout API communication. + * (only needed if you use tcpip.c) + */ +#ifndef MEMP_NUM_TCPIP_MSG_API +#define MEMP_NUM_TCPIP_MSG_API 64 +#endif + +/* + * Defines the number of struct tcpip_msg, which are used + * for incoming packets. + * (only needed if you use tcpip.c) + */ +#ifndef MEMP_NUM_TCPIP_MSG_INPKT +#define MEMP_NUM_TCPIP_MSG_INPKT 512 +#endif + +#ifndef MEMP_NUM_NETCONN +#define MEMP_NUM_NETCONN ((LWIP_CONFIG_NUM_SOCKETS) * 4) +#endif + +/* + * Defines the number of struct netbufs. + * (only needed if you use the sequential API, like api_lib.c) + */ +#ifndef MEMP_NUM_NETBUF +#define MEMP_NUM_NETBUF (65535 * 3 * (LWIP_CONFIG_NUM_SOCKETS) / ((IP_FRAG_MAX_MTU) - 20 - 8)) +#endif + +/* + * Defines the number of simulateously queued outgoing + * packets (pbufs) that are waiting for an ARP request (to resolve + * their destination address) to finish. + * (requires the ARP_QUEUEING option) + */ +#ifndef MEMP_NUM_ARP_QUEUE +#define MEMP_NUM_ARP_QUEUE (65535 * (LWIP_CONFIG_NUM_SOCKETS) / ((IP_FRAG_MAX_MTU)- 20 - 8)) +#endif + +/** Indicates the number of UDP protocol control blocks. One per active UDP "connection". */ +#ifndef MEMP_NUM_UDP_PCB +#define MEMP_NUM_UDP_PCB LWIP_CONFIG_NUM_SOCKETS +#endif + +/** MEMP_NUM_TCP_PCB: Indicates the number of simultaneously active TCP connections. */ +#ifndef MEMP_NUM_TCP_PCB +#define MEMP_NUM_TCP_PCB LWIP_CONFIG_NUM_SOCKETS +#endif + +/** MEMP_NUM_TCP_PCB_LISTEN: Indicates the number of listening TCP connections. */ +#ifndef MEMP_NUM_TCP_PCB_LISTEN +#define MEMP_NUM_TCP_PCB_LISTEN LWIP_CONFIG_NUM_SOCKETS +#endif + +#ifndef IP_FRAG_MAX_MTU +#define IP_FRAG_MAX_MTU 1500 +#endif + +/* + * As per RFC 791, "Every internet module must be able to forward a datagram of 68 + * octets without further fragmentation. This is because an internet header + * may be up to 60 octets, and the minimum fragment is 8 octets." + */ +#ifndef IP_FRAG_MIN_MTU +#define IP_FRAG_MIN_MTU 68 +#endif + +#ifndef IP_REASS_MAX_PBUFS +#define IP_REASS_MAX_PBUFS ((65535 * 2 * (LWIP_CONFIG_NUM_SOCKETS)) / ((IP_FRAG_MAX_MTU) - 20 - 8)) +#endif +/* Max size(65535 + extra buffer(8192) per MAX MTU) */ +#ifndef IP_REASS_MAX_PBUFS_PER_PKT +#define IP_REASS_MAX_PBUFS_PER_PKT ((65535 + 8192) / ((IP_FRAG_MAX_MTU) - 20 - 8)) +#endif + +/* TCP Maximum segment size. */ +#ifdef LWIP_TCP_MSS +#undef TCP_MSS /* ensure TCP_MSS value is overridden by LWIP_TCP_MSS */ +#define TCP_MSS LWIP_TCP_MSS +#else /* LWIP_TCP_MSS */ +#ifndef TCP_MSS +#define TCP_MSS ((IP_FRAG_MAX_MTU) - 20 - 20) +#endif /* TCP_MSS */ +#endif /* LWIP_TCP_MSS */ + +/* MEMP_NUM_TCP_SEG: the number of simultaneously queued TCP segments. */ +#ifndef MEMP_NUM_TCP_SEG +#define MEMP_NUM_TCP_SEG ((((TCP_SND_BUF) * 3 / 2) + (TCP_WND)) * (LWIP_CONFIG_NUM_SOCKETS) / (TCP_MSS)) +#endif + +/* ---------- Pbuf options ---------- */ +/** PBUF_POOL_SIZE: Indicates the number of buffers in the pbuf pool. */ +#ifndef PBUF_POOL_SIZE +#define PBUF_POOL_SIZE 64 +#endif + +/* PBUF_POOL_BUFSIZE: the size of each pbuf in the pbuf pool. */ +#ifndef PBUF_POOL_BUFSIZE +#define PBUF_POOL_BUFSIZE 1550 +#endif + +#ifndef PBUF_LINK_CHKSUM_LEN +#define PBUF_LINK_CHKSUM_LEN 0 +#endif +/* ---------- ARP options ---------- */ +/** + * ARP_QUEUEING==1: Multiple outgoing packets are queued during hardware address + * resolution. By default, only the most recent packet is queued per IP_add + * This is sufficient for most protocols and mainly reduces TCP connection + * startup time. Set this to 1 if you know that your application sends more than one + * packet in a row to an IP_add that is not in the ARP cache. + */ +#ifndef ARP_QUEUEING +#define ARP_QUEUEING 1 +#endif + +/** + * ETHARP_TRUST_IP_MAC==1: Incoming IP packets cause the ARP table to be + * updated with the source MAC and IP address supplied in the packet. + * You may want to disable this if you do not trust LAN peers to have the + * correct addresses, or as a limited approach to attempt to handle + * spoofing. If disabled, lwIP will need to make a new ARP request if + * the peer is not already in the ARP table, adding a little latency. + * The peer is in the ARP table if it requested our address before. + * Also notice that this slows down input processing of every IP packet. + */ +#ifndef ETHARP_TRUST_IP_MAC +#define ETHARP_TRUST_IP_MAC 1 +#endif + +/** Defines the number of bytes added before the ethernet header to ensure + * alignment of payload after that header. Since the header is 14 bytes long, + * without this padding, addresses in the IP header will not be aligned + * on a 32-bit boundary. So setting this to 2 can speed up 32-bit-platforms. + */ +#ifndef ETH_PAD_SIZE +#define ETH_PAD_SIZE 2 +#endif + +/** ETHARP_SUPPORT_STATIC_ENTRIES==1: Enables code to support static ARP table + * entries (using etharp_add_static_entry/etharp_remove_static_entry). + */ +#ifndef ETHARP_SUPPORT_STATIC_ENTRIES +#define ETHARP_SUPPORT_STATIC_ENTRIES 1 +#endif + +/* ---------- TCP options ---------- */ +#ifndef LWIP_TCP +#define LWIP_TCP 1 +#endif +/* @ingroup Config_TCP +* Defines the TCP TTL value. +*/ +#ifndef TCP_TTL +#define TCP_TTL 255 +#endif + +/* Controls if TCP should queue segments that arrive out of + order. Define to 0 if your device is low on memory. */ +#define TCP_QUEUE_OOSEQ LWIP_TCP + +/** + * Defines the mailbox size for the tcpip thread messages + * The queue size value itself is platform-dependent, but is passed to + * sys_mbox_new() when tcpip_init is called. + */ +#ifndef TCPIP_MBOX_SIZE +#define TCPIP_MBOX_SIZE 512 +#endif + +/** + * Defines the mailbox size for the incoming packets on a + * NETCONN_TCP. The queue size value itself is platform-dependent, but is passed + * to sys_mbox_new() when the recvmbox is created. + */ +#ifndef DEFAULT_TCP_RECVMBOX_SIZE +#define DEFAULT_TCP_RECVMBOX_SIZE 128 +#endif + +/** + * Defines the mailbox size for the incoming connections. + * The queue size value itself is platform-dependent, but is passed to + * sys_mbox_new() when the acceptmbox is created. + */ +#ifndef DEFAULT_ACCEPTMBOX_SIZE +#define DEFAULT_ACCEPTMBOX_SIZE 32 +#endif + +#ifndef MEMP_NUM_REASSDATA +#define MEMP_NUM_REASSDATA (2 * (LWIP_CONFIG_NUM_SOCKETS)) +#endif + +#ifdef LWIP_DBG_PREPROCESSOR +#pragma message(VAR_NAME_VALUE(TCP_MSS)) +#endif + +/* @ingroup Config_TCP +* TCP sender buffer space (bytes). */ +#ifndef TCP_SND_BUF +#define TCP_SND_BUF 65535 +#endif + +/* @ingroup Config_TCP +TCP sender buffer space (pbufs). This must be at least = 2 * + TCP_SND_BUF/TCP_MSS for things to work. */ +#ifndef TCP_SND_QUEUELEN +#define TCP_SND_QUEUELEN ((8 * (TCP_SND_BUF)) / (TCP_MSS)) +#endif +/** + * Defines the size of a TCP receive window. + */ +#ifndef TCP_WND +#define TCP_WND 32768 +#endif + +/** + * Defines the Maximum number of retransmissions of data segments. + */ +#ifndef TCP_MAXRTX +#define TCP_MAXRTX 15 +#endif + +/* ---------- IP options ---------- */ +/** + * IP_FRAG_USES_STATIC_BUF==1: Use a static MTU-sized buffer for IP + * fragmentation. Otherwise pbufs are allocated and reference the original + * packet data to be fragmented (or with LWIP_NETIF_TX_SINGLE_PBUF==1, + * new PBUF_RAM pbufs are used for fragments). + * Note: IP_FRAG_USES_STATIC_BUF==1 may not be used for DMA-enabled MACs. + */ +#ifndef IP_FRAG_USES_STATIC_BUF +#define IP_FRAG_USES_STATIC_BUF 1 +#endif + +/* + * Defines the assumed maximum MTU on any interface for IP fragment buffer + * (requires IP_FRAG_USES_STATIC_BUF==1) + */ +#if IP_FRAG_USES_STATIC_BUF && !defined(IP_FRAG_MAX_MTU) +#define IP_FRAG_MAX_MTU 1500 +#endif + +/* As per RFC 791, "Every internet module must be able to forward a datagram of 68 + * octets without further fragmentation. This is because an internet header + * may be up to 60 octets, and the minimum fragment is 8 octets." */ +#if IP_FRAG_USES_STATIC_BUF && !defined(IP_FRAG_MIN_MTU) +#define IP_FRAG_MIN_MTU 68 +#endif + +/* ---------- ICMP options ---------- */ +/** + * LWIP_ICMP==1: Enables the ICMP module inside the IP stack. + */ +#ifndef LWIP_ICMP +#define LWIP_ICMP 1 +#endif + +/* ---------- IGMP options ---------- */ +#ifndef LWIP_IGMP +#define LWIP_IGMP 1 +#endif + +/* ---------- DHCP options ---------- */ +/** + * LWIP_DHCP==1: Enables the DHCP module. + */ +#ifndef LWIP_DHCP +#define LWIP_DHCP 1 +#endif + +/* ---------- DNS options ---------- */ +/** + * LWIP_DNS==1: Turn on DNS module. UDP must be available for DNS + * transport. + */ +#ifndef LWIP_DNS +#define LWIP_DNS 1 +#endif + +/* ---------- UDP options ---------- */ +/** + * LWIP_UDP==1: Turns on UDP. + */ +#ifndef LWIP_UDP +#define LWIP_UDP 1 +#endif + +#ifndef UDP_TTL +#define UDP_TTL 255 +#endif +/** + * Defines the mailbox size for the incoming packets on a + * NETCONN_UDP. The queue size value itself is platform-dependent, but is passed + * to sys_mbox_new() when the recvmbox is created. + */ +#ifndef DEFAULT_UDP_RECVMBOX_SIZE +#define DEFAULT_UDP_RECVMBOX_SIZE 128 +#endif + +/* -----------RAW options -----------*/ +#ifndef DEFAULT_RAW_RECVMBOX_SIZE + +/** + * LWIP_RAW==1: Enables the application layer to hook into the IP layer itself. + */ +#if !defined LWIP_RAW || defined __DOXYGEN__ +#define LWIP_RAW 1 +#endif + +/** + * Enable to support PF_PACKET RAW sockets +*/ +#if defined(LWIP_RAW) && LWIP_RAW +#ifndef PF_PKT_SUPPORT +#define PF_PKT_SUPPORT 1 +#endif +#endif + +/** + * Defines the mailbox size for the incoming packets on a + * NETCONN_RAW. The queue size value itself is platform-dependent, but is passed + * to sys_mbox_new() when the recvmbox is created. + */ +#define DEFAULT_RAW_RECVMBOX_SIZE 128 +#endif + +#ifndef LWIP_MAX_PF_RAW_SEND_SIZE +#define LWIP_MAX_PF_RAW_SEND_SIZE (0xFFFF - 40) // - IPv6 header +#endif + +/* -----------LOOPIF options -----------*/ +#ifndef LWIP_HAVE_LOOPIF +#define LWIP_HAVE_LOOPIF 1 +#endif + +/* -----------LOOPBACK options -----------*/ +#ifndef LWIP_NETIF_LOOPBACK +#define LWIP_NETIF_LOOPBACK 1 +#endif + +/* ---------- Statistics options ---------- */ +/** + * LWIP_STATS==1: Enables statistics gathering in lwip_stats. + */ +#ifndef LWIP_STATS +#define LWIP_STATS 1 +#endif + +/* ---------- TFTP options ---------- */ +#ifndef LWIP_TFTP +#define LWIP_TFTP 1 +#endif + +/* ---------- SNTP options ---------- */ +#ifndef LWIP_SNTP +#define LWIP_SNTP 1 +#endif + +/** + * SO_REUSE==1: Enable SO_REUSEADDR option. + */ +#ifndef SO_REUSE +#define SO_REUSE 1 +#endif + +#define LWIP_ETHERNET 1 +#define LWIP_NETCONN 1 +#define LWIP_SOCKET 1 + +#ifndef IP_FORWARD +#define IP_FORWARD 0 +#endif + +#define LWIP_DHCPS_DISCOVER_BROADCAST LWIP_LITEOS_COMPAT + +#if LWIP_LITEOS_COMPAT +#ifndef TCPIP_THREAD_STACKSIZE +#define TCPIP_THREAD_STACKSIZE 0x6000 +#endif +#ifndef TCPIP_THREAD_PRIO +#define TCPIP_THREAD_PRIO 5 +#endif + +#ifndef LWIP_SOCKET_START_NUM +#define LWIP_SOCKET_START_NUM CONFIG_NFILE_DESCRIPTORS +#endif + +#ifndef LWIP_SOCKET_OFFSET +#define LWIP_SOCKET_OFFSET CONFIG_NFILE_DESCRIPTORS +#endif + +#ifndef LWIP_ENABLE_LOS_SHELL_CMD +#define LWIP_ENABLE_LOS_SHELL_CMD 1 +#endif +#ifndef ERRNO +#define ERRNO +#endif +#ifndef LWIP_PROVIDE_ERRNO +#define LWIP_PROVIDE_ERRNO 0 +#endif +/* Currently pthread_cond_timedwait() in liteos doesn't support absolute time */ +#ifndef LWIP_USE_POSIX_COND_WAIT_WITH_ABS_TIMEOUT +#define LWIP_USE_POSIX_COND_WAIT_WITH_ABS_TIMEOUT 0 +#endif + +#ifndef LWIP_INET_ADDR_FUNC +#define LWIP_INET_ADDR_FUNC 1 +#endif + +#ifndef LWIP_INET_NTOA_FUNC +#define LWIP_INET_NTOA_FUNC 1 +#endif + +#ifndef LWIP_INET_ATON_FUNC +#define LWIP_INET_ATON_FUNC 1 +#endif + +#else +#define ERRNO +#define LWIP_PROVIDE_ERRNO 1 + +#ifndef LWIP_INET_ADDR_FUNC +#define LWIP_INET_ADDR_FUNC 1 +#endif + +#ifndef LWIP_INET_NTOA_FUNC +#define LWIP_INET_NTOA_FUNC 1 +#endif + +#ifndef LWIP_INET_ATON_FUNC +#define LWIP_INET_ATON_FUNC 1 +#endif + +#endif + +/* ---------- Socket Filter options ---------- */ +/** + * implement sock filter based on BPF. + * BPF-extension was not supported. + * only AF_PACKET RAW socket support socket filter now, + * we would add supports for other socket type in the feature. +*/ +#if defined(LWIP_RAW) && LWIP_RAW +#ifndef LWIP_SOCK_FILTER +#define LWIP_SOCK_FILTER 1 +#endif +#else +#define LWIP_SOCK_FILTER 0 +#endif + +/* Requesting application to configure a cryptographically strong random number generator to LWIP_RAND macro */ +#ifndef LWIP_RAND +#define LWIP_RAND g_stlwIPSecSspCallbacks.pfRand +#endif + +#ifndef LWIP_STATIC +#define LWIP_STATIC static +#endif + +#ifndef LWIP_ALWAYS_SEND_HWTYPE_AS_ETHER_IN_DHCP +#define LWIP_ALWAYS_SEND_HWTYPE_AS_ETHER_IN_DHCP 1 +#endif + +#ifndef USE_ONLY_PRIMARY_IFACE +#define USE_ONLY_PRIMARY_IFACE 1 +#endif + +#ifndef DRIVER_STATUS_CHECK +#define DRIVER_STATUS_CHECK 0 +#endif + +#if DRIVER_STATUS_CHECK +#ifndef DRIVER_WAKEUP_INTERVAL +#define DRIVER_WAKEUP_INTERVAL 120000 +#endif +#endif + +/* ---------- NETIF options ---------- */ +/** + * LWIP_NETIF_API==1: Supports netif api (in netifapi.c) + */ +#ifndef LWIP_NETIF_API +#define LWIP_NETIF_API 1 +#endif + +/* + * LWIP_NETIF_LINK_CALLBACK==1: Supports a callback function from an interface + * whenever the link changes. Example: when link goes down. + */ +#ifndef LWIP_NETIF_LINK_CALLBACK +#define LWIP_NETIF_LINK_CALLBACK 1 +#endif + +/* + * LWIP_NETIF_NUM_MAX==255: Defines the maximum support number of same type netif. + */ +/* + * Increase the count of netifs supported by stack. + * Currently stack restricts the number of netif to 5, but older versions of linux kernel supports + * upto 255 interfaces . New versions donot have these restrictions but we stick to 255 + */ +#ifndef LWIP_NETIF_NUM_MAX +#define LWIP_NETIF_NUM_MAX 255 +#endif + +/* ---------- SOCKET options ---------- */ +/** + * LWIP_SO_RCVBUF==1: Enables SO_RCVBUF processing. + */ +#ifndef LWIP_SO_RCVBUF +#define LWIP_SO_RCVBUF 1 +#endif + +/* ---------- Statistics options ---------- */ +/** + * LWIP_STATS_DISPLAY==1: Compile in the statistics output functions. + */ +#ifndef LWIP_STATS_DISPLAY +#define LWIP_STATS_DISPLAY 1 +#endif + +/* ---------- Debugging options ---------- */ +/** + * LWIP_DBG_MIN_LEVEL: After masking, the value of the debug is + * compared against this value. If it is smaller, then debugging + * messages are written. + */ +#ifndef LWIP_DBG_MIN_LEVEL +#define LWIP_DBG_MIN_LEVEL LWIP_DBG_LEVEL_OFF +#endif + +/** + * LWIP_DBG_TYPES_ON: A mask that can be used to globally enable/disable + * debug messages of certain types. + */ +#ifndef LWIP_DBG_TYPES_ON +#define LWIP_DBG_TYPES_ON LWIP_DBG_OFF +#endif + +#ifndef LWIP_SOCKET_POLL +#define LWIP_SOCKET_POLL 1 +#endif + +/** + * LWIP_TCP_INFO==1: support get tcp info by getsockopt API + */ +#ifndef LWIP_TCP_INFO +#define LWIP_TCP_INFO 1 +#endif + +#ifndef LWIP_RPL +#define LWIP_RPL 0 +#endif + +#ifndef PBUF_API +#define PBUF_API 0 +#endif + +#if !defined(LWIP_RPL) || (0 == LWIP_RPL) +#ifndef LWIP_RPL_TIMER_COUNT +#define LWIP_RPL_TIMER_COUNT 0 +#endif +#else +#ifndef LWIP_RPL_TIMER_COUNT +#define LWIP_RPL_TIMER_COUNT 12 +#endif +#endif + +#ifndef LWIP_IPV6_MLD +#define LWIP_IPV6_MLD 1 +#endif + +#ifndef LWIP_MLD6_ENABLE_MLD_ON_DAD +#define LWIP_MLD6_ENABLE_MLD_ON_DAD LWIP_IPV6 && LWIP_IPV6_MLD +#endif + +#ifndef LWIP_MLD6_DONE_ONLYFOR_LAST_REPORTER +#define LWIP_MLD6_DONE_ONLYFOR_LAST_REPORTER LWIP_IPV6 && LWIP_IPV6_MLD +#endif + +#if defined (__cplusplus) && __cplusplus +} +#endif /* __cplusplus */ + +#endif /* __LWIPOPTS_H__ */ + diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/mem.h b/sdk_liteos/third_party/lwip_sack/include/lwip/mem.h new file mode 100644 index 0000000000000000000000000000000000000000..c25537c60316a04c2cf5ad767510b5ccee872fac --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/mem.h @@ -0,0 +1,82 @@ +/** + * @file + * Heap API + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_MEM_H +#define LWIP_HDR_MEM_H + +#include "lwip/opt.h" + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +#if MEM_LIBC_MALLOC + +#include "lwip/arch.h" + +typedef size_t mem_size_t; +#define MEM_SIZE_F SZT_F + +#elif MEM_USE_POOLS + +typedef u16_t mem_size_t; +#define MEM_SIZE_F U16_F + +#else + +/* MEM_SIZE would have to be aligned, but using 64000 here instead of + * 65535 leaves some room for alignment... + */ +#if MEM_SIZE > 64000L +typedef u32_t mem_size_t; +#define MEM_SIZE_F U32_F +#else +typedef u16_t mem_size_t; +#define MEM_SIZE_F U16_F +#endif /* MEM_SIZE > 64000 */ +#endif + +void mem_init(void); +void *mem_trim(void *mem, mem_size_t size); +void *mem_malloc(mem_size_t size); +void *mem_calloc(mem_size_t count, mem_size_t size); +void mem_free(void *mem); + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_HDR_MEM_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/memp.h b/sdk_liteos/third_party/lwip_sack/include/lwip/memp.h new file mode 100644 index 0000000000000000000000000000000000000000..58e31a77a4b4847454d6177799882bfbaa953956 --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/memp.h @@ -0,0 +1,160 @@ +/** + * @file + * Memory pool API + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ + +#ifndef LWIP_HDR_MEMP_H +#define LWIP_HDR_MEMP_H + +#include "lwip/opt.h" + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +/* run once with empty definition to handle all custom includes in lwippools.h */ +#define LWIP_MEMPOOL(name, num, size, desc) +#include "lwip/priv/memp_std.h" + +/** Create the list of all memory pools managed by memp. MEMP_MAX represents a NULL pool at the end */ +typedef enum { +#define LWIP_MEMPOOL(name, num, size, desc) MEMP_##name, +#include "lwip/priv/memp_std.h" + MEMP_MAX +} memp_t; + +#include "lwip/priv/memp_priv.h" +#include "lwip/stats.h" + +#if LWIP_ALLOW_SOCKET_CONFIG +extern struct memp_desc *memp_pools[MEMP_MAX]; +#else +extern const struct memp_desc *const memp_pools[MEMP_MAX]; +#endif + +/** + * @ingroup mempool + * Declare prototype for private memory pool if it is used in multiple files + */ +#define LWIP_MEMPOOL_PROTOTYPE(name) extern const struct memp_desc memp_ ## name + +#if MEMP_MEM_MALLOC + +#define LWIP_MEMPOOL_DECLARE(name, num, size, desc) \ + LWIP_MEMPOOL_DECLARE_STATS_INSTANCE(memp_stats_ ## name) \ + const struct memp_desc memp_ ## name = { \ + DECLARE_LWIP_MEMPOOL_DESC(desc) \ + LWIP_MEMPOOL_DECLARE_STATS_REFERENCE(memp_stats_ ## name) \ + LWIP_MEM_ALIGN_SIZE(size) \ + }; + +#else /* MEMP_MEM_MALLOC */ + +/** + * @ingroup mempool + * Declare a private memory pool + * Private mempools example: + * .h: only when pool is used in multiple .c files: LWIP_MEMPOOL_PROTOTYPE(my_private_pool); + * .c: + * - in global variables section: LWIP_MEMPOOL_DECLARE(my_private_pool, 10, sizeof(foo), "Some description") + * - call ONCE before using pool (e.g. in some init() function): LWIP_MEMPOOL_INIT(my_private_pool); + * - allocate: void* my_new_mem = LWIP_MEMPOOL_ALLOC(my_private_pool); + * - free: LWIP_MEMPOOL_FREE(my_private_pool, my_new_mem); + * + * To relocate a pool, declare it as extern in cc.h. Example for GCC: + * extern u8_t __attribute__((section(".onchip_mem"))) memp_memory_my_private_pool[]; + */ +#define LWIP_MEMPOOL_DECLARE(name, num, size, desc) \ + LWIP_DECLARE_MEMORY_ALIGNED(memp_memory_ ## name ## _base, ((num) * (MEMP_SIZE + MEMP_ALIGN_SIZE(size)))); \ + \ + LWIP_MEMPOOL_DECLARE_STATS_INSTANCE(memp_stats_ ## name) \ + \ + static struct memp *memp_tab_ ## name; \ + \ + const struct memp_desc memp_ ## name = { \ + DECLARE_LWIP_MEMPOOL_DESC(desc) \ + LWIP_MEMPOOL_DECLARE_STATS_REFERENCE(memp_stats_ ## name) \ + LWIP_MEM_ALIGN_SIZE(size), \ + (num), \ + memp_memory_ ## name ## _base, \ + &memp_tab_ ## name \ + }; + +#endif /* MEMP_MEM_MALLOC */ + +/** + * @ingroup mempool + * Initialize a private memory pool + */ +#define LWIP_MEMPOOL_INIT(name) memp_init_pool(&memp_ ## name) +/** + * @ingroup mempool + * Allocate from a private memory pool + */ +#define LWIP_MEMPOOL_ALLOC(name) memp_malloc_pool(&memp_ ## name) +/** + * @ingroup mempool + * Free element from a private memory pool + */ +#define LWIP_MEMPOOL_FREE(name, x) memp_free_pool(&memp_ ## name, (x)) + +#if MEM_USE_POOLS +/** This structure is used to save the pool one element came from. + * This has to be defined here as it is required for pool size calculation. */ +struct memp_malloc_helper { + memp_t poolnr; +#if MEMP_OVERFLOW_CHECK || (LWIP_STATS && MEM_STATS) + u16_t size; +#endif /* MEMP_OVERFLOW_CHECK || (LWIP_STATS && MEM_STATS) */ +}; +#endif /* MEM_USE_POOLS */ + +void memp_init(void); + +#if MEMP_OVERFLOW_CHECK +void *memp_malloc_fn(memp_t type, const char *file, const int line); +#define memp_malloc(t) memp_malloc_fn((t), __FILE__, __LINE__) +#else +void *memp_malloc(memp_t type); +#endif +void memp_free(memp_t type, void *mem); + +u32_t memp_check(memp_t type, void *mem); + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_HDR_MEMP_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/mld6.h b/sdk_liteos/third_party/lwip_sack/include/lwip/mld6.h new file mode 100644 index 0000000000000000000000000000000000000000..a43daa3f3eac5cc509837467e94f63696067aa60 --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/mld6.h @@ -0,0 +1,165 @@ +/** + * @file + * + * Multicast listener discovery for IPv6. Aims to be compliant with RFC 2710. + * No support for MLDv2. + */ + +/* + * Copyright (c) 2010 Inico Technologies Ltd. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Ivan Delamer + * + * + * Please coordinate changes and requests with Ivan Delamer + * + */ + +#ifndef LWIP_HDR_MLD6_H +#define LWIP_HDR_MLD6_H + +#include "lwip/opt.h" + +#if (LWIP_IPV6 && (LWIP_IPV6_MLD || LWIP_IPV6_MLD_QUERIER)) /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/pbuf.h" +#include "lwip/netif.h" +#if ((LWIP_RPL || LWIP_RIPPLE) && LWIP_MPL) +#include "mcast6.h" +#endif /* ((LWIP_RPL || LWIP_RIPPLE) && LWIP_MPL) */ + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +/** MLD group */ +struct mld_group { + /** next link */ + struct mld_group *next; + /** multicast address */ + ip6_addr_t group_address; + /** signifies we were the last person to report */ + u8_t last_reporter_flag; + /** current state of the group */ + u8_t group_state; + /** timer for reporting */ + u16_t timer; + /** counter of simultaneous uses */ + u8_t use; +}; + +#define MLD6_TMR_INTERVAL 100 /* Milliseconds */ + +err_t mld6_stop(struct netif *netif); +void mld6_report_groups(struct netif *netif); +void mld6_tmr(void); +struct mld_group *mld6_lookfor_group(struct netif *ifp, const ip6_addr_t *addr); +void mld6_input(struct pbuf *p, struct netif *inp); +err_t mld6_joingroup(const ip6_addr_t *srcaddr, const ip6_addr_t *groupaddr); +err_t mld6_joingroup_netif(struct netif *netif, const ip6_addr_t *groupaddr); +err_t mld6_join_staticgroup_netif(struct netif *netif, const ip6_addr_t *groupaddr); +err_t mld6_leavegroup(const ip6_addr_t *srcaddr, const ip6_addr_t *groupaddr); +err_t mld6_leavegroup_netif(struct netif *netif, const ip6_addr_t *groupaddr); + +#if LWIP_LOWPOWER +u32_t mld6_tmr_tick(void); +#endif + +/** @ingroup mld6 + * Get list head of MLD6 groups for netif. + * Note: The allnodes group IP is NOT in the list, since it must always + * be received for correct IPv6 operation. + * @see @ref netif_set_mld_mac_filter() + */ +#define netif_mld6_data(netif) ((struct mld_group *)netif_get_client_data(netif, LWIP_NETIF_CLIENT_DATA_INDEX_MLD6)) + +#if ((LWIP_RPL || LWIP_RIPPLE) && LWIP_MPL) +#ifndef LWIP_CONF_MLD6_JOIN_GRP +#define LWIP_CONF_MLD6_JOIN_GRP lwip_mld6_join_group +#endif /* LWIP_CONF_MLD6_JOIN_GRP */ +#endif /* (LWIP_RPL || LWIP_RIPPLE) && LWIP_MPL */ + +#ifndef LWIP_CONF_MLD6_JOIN_GRP +#define LWIP_CONF_MLD6_JOIN_GRP +#endif /* LWIP_CONF_MLD6_JOIN_GRP */ + +#if LWIP_IPV6_MLD_QUERIER +#ifndef MLD6_MS_PER_SECOND +#define MLD6_MS_PER_SECOND 1000 +#endif /* MLD6_MS_PER_SECOND */ + +#ifndef MLD6_QUERIER_LISTENER_MAX_NUM +#define MLD6_QUERIER_LISTENER_MAX_NUM 4 +#endif /* MLD6_QUERIER_LISTENER_MAX_NUM */ + +enum mld6_listener_state { + MLD6_LISTENER_STATE_NON, + MLD6_LISTENER_STATE_PRESENT, + MLD6_LISTENER_STATE_CHECK +}; + +struct mld6_listener { + struct mld6_listener *next; + ip6_addr_t group_address; + /* mld6_listener_state */ + u8_t state; + u8_t query_count; + u16_t timer; + /* retransmit timer */ + u16_t rexmt_timer; +}; + +enum mld6_querier_state { + MLD6_QUERIER_STATE_STARTUP, + MLD6_QUERIER_STATE_NON_LISTENER, + MLD6_QUERIER_STATE_HAVE_LISTENER +}; + +struct mld6_querier { + u8_t querier_state; + u8_t query_count; // when startup, need to send [Startup Query Count] times of General Query + u16_t timer; + struct mld6_listener *listeners; + u8_t listener_num; +}; + +#define netif_mld6_querier_data(netif) \ + ((struct mld6_querier *)netif_get_client_data(netif, LWIP_NETIF_CLIENT_DATA_INDEX_MLD6_QUERIER)) + +err_t mld6_querier_start(struct netif *netif); +void mld6_querier_stop(struct netif *netif); +struct mld6_listener *mld6_querier_listener_lookfor(struct netif *netif, const ip6_addr_t *addr); +#endif /* LWIP_IPV6_MLD_QUERIER */ + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* (LWIP_IPV6 && (LWIP_IPV6_MLD || LWIP_IPV6_MLD_QUERIER)) */ + +#endif /* LWIP_HDR_MLD6_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/nat64.h b/sdk_liteos/third_party/lwip_sack/include/lwip/nat64.h new file mode 100644 index 0000000000000000000000000000000000000000..685ba16f202ef43f42035634576ecc380dab0c67 --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/nat64.h @@ -0,0 +1,194 @@ +/* + * Description: NAT64 header + */ +#ifndef LWIP_HDR_NAT64_H +#define LWIP_HDR_NAT64_H + +#include "lwip/opt.h" +#include "lwip/lwip_rpl.h" +#include "lwip/netif.h" +#if LWIP_NAT64 +#include "lwip/ip.h" +#include "lwip/dhcp.h" +#include "lwip/prot/tcp.h" +#ifndef LWIP_NAT64_ENTRY_SIZE +#define LWIP_NAT64_ENTRY_SIZE 255 +#endif + +#define NAT64_TMR_INTERVAL 1000 +#define NAT64_TMR_INFINITY 0xfffffffful + +#define NAT64_PKT_HANDLED (1) +#define NAT64_PKT_NOT_HANDLED (0) + +#define NAT64_RET_FAIL (-1) +#define NAT64_RET_OK (0) +#define NAT64_RET_ERR (1) +#define NAT64_RET_ASSEMBLE (2) + +enum nat64_entry_state_e { + NAT64_STATE_INIT, + NAT64_STATE_DAO_RCV, + NAT64_STATE_DHCP_DISCOVER, + NAT64_STATE_DHCP_REQUEST, + NAT64_STATE_STALE, + NAT64_STATE_RELEASE, + NAT64_STATE_ESTABLISH, + NAT64_STATE_MAX +}; + +typedef struct { + linklayer_addr_t mac; +#if LWIP_NA_PROXY_UNSOLICITED + u8_t na_tries : 4; + u8_t na_to : 4; +#endif +#if !LWIP_NAT64_MIN_SUBSTITUTE + ip4_addr_t ip; +#endif + u32_t lifetime; /* in seconds */ + u8_t state; + u8_t dao_sn; + u8_t mnid; +} nat64_entry_t; + +/* init function */ +/* + * @brief + * This API is used to init the nat64 module. + * + * @param[in] none + * + * @returns + * ERR_OK: On success. + * ERR_MEM: On memory alloc fail. + */ +err_t nat64_init(struct netif *ntf); + +/* + * @brief + * This API is used to deinit the nat64 module. + * + * @param[in] none + * + * @returns + * ERR_OK: On success. + * ERR_MEM: On memory free fail. + */ +err_t nat64_deinit(void); + +/* hook function */ +/* + * @brief + * This API is used to hook the ipv4 input packets in two different situations: + * 1) when the packet is received by the non-mesh interface in a mesh gate . + * 2) when the packet is received by the non-mesh interface in a mesh BR . + * + * @param + * [in] + * p : packet received + * iphdr : ip header + * inp : the interface that receive the packet. + * + * @returns + * 0: Hook has not consumed the packet. + * != 0: Hook has consumed the packet. + */ +int nat64_ip4_input(struct pbuf *p, struct ip_hdr *iphdr, const struct netif *inp); + +/* + * @brief + * This API is used to hook the ipv6 input packets in two different situations: + * 1) when the packet is received by the mesh interface in a mesh gate, if non-mesh interface is ipv4 . + * 2) when the packet is received by the mesh interface in a mesh BR, if non-mesh interface is ipv4 . + * + * @param + * [in] + * p : packet received + * iphdr : ip header + * inp : the interface that receive the packet. + * + * @returns + * 0: Hook has not consumed the packet. + * != 0: Hook has consumed the packet. + */ +int nat64_ip6_input(struct pbuf *p, struct ip6_hdr *iphdr, const struct netif *inp); + +/* translate IP function */ +/* + * @brief + * This API is used to translate the ip header from ipv6 to ipv4 + * + * @param + * [in] + * p6 : packet received + * [out] + * p4 : packet translated + * + * @returns + * ERR_OK: On success. + * ERR_MEM: On memory alloc fail. + */ +err_t nat64_translate_6to4(struct pbuf *p6, struct pbuf *p4); + +/* + * @brief + * This API is used to translate the ip header from ipv4 to ipv6 + * + * @param + * [in] + * p4 : packet received + * [out] + * p6 : packet translated + * + * @returns + * ERR_OK: On success. + * ERR_MEM: On memory alloc fail. + */ +err_t nat64_translate_4to6(struct pbuf *p4, struct pbuf *p6); + +/* entry api */ +/* + * @brief + * This API is used to add an entry of nat64 in the MBR, when receive DAO with mac: + * + * @param + * [in] + * mac: mac address received from DAO + * + * @returns + * != NULL: On success. + * NULL: On memory alloc fail. + */ +nat64_entry_t *nat64_entry_add(const u8_t *mac, int maclen); + +err_t nat64_entry_remove(nat64_entry_t *entry); +nat64_entry_t *nat64_entry_lookup_by_mac(const linklayer_addr_t *mac); +int nat64_request_ipv4_addr(const linklayer_addr_t *lladdr, u8_t dao_sn, u8_t mnid, + u32_t lifetime, uint32_t *ipv4); +int nat64_delete_ipv4_addr(linklayer_addr_t *lladdr, u8_t mnid); +int nat64_delete_entry_by_mnid(u8_t mnid); + +err_t nat64_ip4_dest_addr_exist(const ip4_addr_t *ip4addr); +struct netif *nat64_netif_get(void); + +int nat64_status_check(void); + +/* timer api */ +void nat64_tmr(void); +#if LWIP_LOWPOWER +u32_t nat64_tmr_tick(void); +#endif + +err_t nat64_deinit_netif(const struct netif *ntf); + +err_t nat64_entry_mac_to_idx(const u8_t *hwaddr, u8_t hwaddr_len, dhcp_num_t *mac_idx); +err_t nat64_entry_idx_to_mac(dhcp_num_t mac_idx, u8_t *hwaddr, u8_t *hwaddr_len); + +#if LWIP_NA_PROXY_UNSOLICITED +void nat64_proxy_unsolicited_na(const struct netif *netif); +#endif + +#endif + +#endif diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/nat64_addr.h b/sdk_liteos/third_party/lwip_sack/include/lwip/nat64_addr.h new file mode 100644 index 0000000000000000000000000000000000000000..f661cf9a636d1d83d5d22dcc540c69b288b1c1cb --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/nat64_addr.h @@ -0,0 +1,17 @@ +/* + * Description: NAT64 address header + */ +#ifndef LWIP_HDR_NAT64_ADDR_H +#define LWIP_HDR_NAT64_ADDR_H + +#include "lwip/lwip_rpl.h" +#include "lwip/nat64.h" +#if LWIP_NAT64 +int nat64_stateless_addr_4to6(const ip4_addr_t *ip4addr, ip6_addr_t *ip6addr); +int nat64_addr_mac_to6(const linklayer_addr_t *mac, ip6_addr_t *ip6addr); +int nat64_stateless_addr_6to4(const ip6_addr_t *ip6addr, ip4_addr_t *ip4addr); +int nat64_addr_6to4(const ip6_addr_t *ip6addr, ip4_addr_t *ip4addr); +int nat64_addr_is_ip4(const ip6_addr_t *ip6addr); +int nat64_entry_to6(const nat64_entry_t *entry, ip6_addr_t *ip6addr); +#endif +#endif diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/nat64_api.h b/sdk_liteos/third_party/lwip_sack/include/lwip/nat64_api.h new file mode 100644 index 0000000000000000000000000000000000000000..ab4e3c0233c8f17fcba01080d4ab6bceaf31c4e6 --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/nat64_api.h @@ -0,0 +1,12 @@ +/* + * Description: NAT64 api + */ +#ifndef LWIP_HDR_NAT64_API_H +#define LWIP_HDR_NAT64_API_H + +#if LWIP_NAT64 +int lwip_nat64_init(char *name, uint8_t len); +int lwip_nat64_deinit(void); +#endif +#endif + diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/nat64_dns64.h b/sdk_liteos/third_party/lwip_sack/include/lwip/nat64_dns64.h new file mode 100644 index 0000000000000000000000000000000000000000..2c452de412fff720efc49c714ac4910a8d173007 --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/nat64_dns64.h @@ -0,0 +1,18 @@ +/* + * Description: DNS64 header + */ +#ifndef LWIP_HDR_NAT64_DNS64_H +#define LWIP_HDR_NAT64_DNS64_H + +#include "lwip/lwip_rpl.h" + +#if LWIP_DNS64 + +#define NAT64_DNS_PORT 53 + +err_t nat64_dns64_6to4(struct pbuf *p); +err_t nat64_dns64_4to6(const struct pbuf *p4, struct pbuf *p6); +err_t nat64_dns64_extra_count(struct pbuf *p, u16_t *count); +err_t nat64_dns64_get_prefix(ip6_addr_t *ip6addr, u8_t *len); +#endif +#endif diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/nat64_v4_dhcpc.h b/sdk_liteos/third_party/lwip_sack/include/lwip/nat64_v4_dhcpc.h new file mode 100644 index 0000000000000000000000000000000000000000..14c9a4ae739783b4d3b6748ce78f972713924e3c --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/nat64_v4_dhcpc.h @@ -0,0 +1,21 @@ +/* + * Description: NAT64 dhcp proxy header + */ +#ifndef LWIP_HDR_NAT64_V4_DHCPC_H +#define LWIP_HDR_NAT64_V4_DHCPC_H +#include "lwip/opt.h" + +#if LWIP_NAT64 +#include "lwip/lwip_rpl.h" +#include "lwip/netif.h" + +#define NAT64_DHCP_EVENT_RELEASE 0 +#define NAT64_DHCP_EVENT_OFFER 1 +#define NAT64_DHCP_EVENT_RENEW 2 + +err_t nat64_dhcp_request_ip(struct netif *ntf, const linklayer_addr_t *lladdr); +err_t nat64_dhcp_stop(struct netif *ntf, const linklayer_addr_t *lladdr); +void nat64_dhcp_ip4_event(const u8_t *mac, u8_t maclen, const ip4_addr_t *ipaddr, int event); + +#endif +#endif diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/nbr_restriction.h b/sdk_liteos/third_party/lwip_sack/include/lwip/nbr_restriction.h new file mode 100644 index 0000000000000000000000000000000000000000..0ba8aade95ad718362f0448570c012ebfedb070b --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/nbr_restriction.h @@ -0,0 +1,13 @@ +/* + * Description: declaration of nbr restriction APIs + */ + +#ifndef __NBR_RESTRICTION_H__ +#define __NBR_RESTRICTION_H__ +#include "lwip/nd6.h" + +#define LWIP_NBPOL_REASON_DAO 0x01 +#define LWIP_NBPOL_REASON_DIO 0x02 +#define LWIP_NBPOL_REASON_OTHERS 0x04 + +#endif /* __NBR_RESTRICTION_H__ */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/nd6.h b/sdk_liteos/third_party/lwip_sack/include/lwip/nd6.h new file mode 100644 index 0000000000000000000000000000000000000000..ace818dc267f4a965817b5bdfc175ff31a370866 --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/nd6.h @@ -0,0 +1,206 @@ +/** + * @file + * + * Neighbor discovery and stateless address autoconfiguration for IPv6. + * Aims to be compliant with RFC 4861 (Neighbor discovery) and RFC 4862 + * (Address autoconfiguration). + */ + +/* + * Copyright (c) 2010 Inico Technologies Ltd. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Ivan Delamer + * + * + * Please coordinate changes and requests with Ivan Delamer + * + */ + +#ifndef LWIP_HDR_ND6_H +#define LWIP_HDR_ND6_H + +#include "lwip/opt.h" + +#if LWIP_IPV6 /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/ip6_addr.h" +#include "lwip/err.h" + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + + +/** @cond liteos + * 1 second period */ +#define ND6_TMR_INTERVAL 1000 + +/** Router solicitations are sent in 4 second intervals (see RFC 4861, ch. 6.3.7) + * @endcond */ +#ifndef ND6_RTR_SOLICITATION_INTERVAL +#define ND6_RTR_SOLICITATION_INTERVAL 4000 +#endif + +/* [rfc4861][section 10] */ +#ifndef ND6_MAX_NEIGHBOR_ADVERTISEMENT +#define ND6_MAX_NEIGHBOR_ADVERTISEMENT 3 +#endif + +#ifndef ND6_RETRANS_TIMER +#define ND6_RETRANS_TIMER 1000 /* milliseconds */ +#endif + +#define ND6_SEND_FLAG_MULTICAST_DEST 0x01 +#define ND6_SEND_FLAG_ALLNODES_DEST 0x02 +#define ND6_SEND_FLAG_UNSECURE 0x04 + +#define ND6_SEND_FLAG_UNSPEC_SRC 0x10 +#define SIZEOF_RDNSS_OPTION_BASE 8 + +/* Hop limit value */ +#define ND6_HOPLIM 255 +#if LWIP_RPL_RS_DAO +#define ND6_RS_FLAG_DAO (1) +#endif +#define ND6_RS_FLAG_RA (0) +#define RS_LLADDR_OPTION_HEADER_LEN 2 + +struct pbuf; +struct netif; +#ifdef LWIP_TESTBED +void nd6_remove_netif_neighbor_cache_entries(struct netif *netif); +#endif + +#if LWIP_IPV6 && LWIP_NETIF_NBR_CACHE_API +struct nd6_neighbor_info { + struct ip6_addr nbripaddr; + u32_t reachabletime; + u8_t hwaddr[NETIF_MAX_HWADDR_LEN]; + u8_t hwlen; + u8_t curstate; +}; +#endif +void nd6_tmr(void); +void nd6_input(struct pbuf *p, struct netif *inp); +void nd6_rs_input(struct pbuf *p, struct netif *inp, u8_t flags); +err_t nd6_send_ra(struct netif *netif, const ip6_addr_t *target_addr, u8_t flags); +void nd6_clear_destination_cache(void); +struct netif *nd6_find_route(const ip6_addr_t *ip6addr); +err_t nd6_get_next_hop_addr_or_queue(struct netif *netif, struct pbuf *q, const ip6_addr_t *ip6addr, + const u8_t **hwaddrp); +u16_t nd6_get_destination_mtu(const ip6_addr_t *ip6addr, struct netif *netif); +#if LWIP_ND6_TCP_REACHABILITY_HINTS +void nd6_reachability_hint(const ip6_addr_t *ip6addr); +#endif /* LWIP_ND6_TCP_REACHABILITY_HINTS */ +void nd6_cleanup_netif(struct netif *netif); +#if LWIP_IPV6_MLD +void nd6_adjust_mld_membership(struct netif *netif, s8_t addr_idx, u8_t new_state); +#endif /* LWIP_IPV6_MLD */ +void nd6_send_na(struct netif *netif, const ip6_addr_t *target_addr, u8_t flags); + +#if LWIP_IPV6_SEND_ROUTER_SOLICIT +err_t nd6_send_rs(struct netif *netif); +#endif /* LWIP_IPV6_SEND_ROUTER_SOLICIT */ + +#if LWIP_RPL || LWIP_RIPPLE || (defined LWIP_TESTBED) +err_t nd6_add_neighbor_cache_entry(struct netif *netif, const ip6_addr_t *nbr_addr, const u8_t *addr, + const u8_t addrlen, u8_t uc_reason2_add, void *pv_data); +#endif /* LWIP_RPL || LWIP_RIPPLE || (defined LWIP_TESTBED) */ + +#ifdef LWIP_TESTBED +const ip6_addr_t *nd6_get_prefix_addr(const ip6_addr_t *ip6addr, struct netif *netif); +#endif /* LWIP_TESTBED */ + +#if LWIP_IPV6 && LWIP_NETIF_NBR_CACHE_API +err_t nd6_add_neighbor_cache_entry_manually(struct netif *netif, struct nd6_neighbor_info *nbrinfo); +err_t nd6_del_neighbor_cache_entry_manually(struct netif *netif, struct ip6_addr *nbrip); +err_t nd6_get_neighbor_cache_info(struct netif *netif, struct ip6_addr *nbrip, struct nd6_neighbor_info *nbrinfo); +#endif + +#if LWIP_RPL || LWIP_RIPPLE + +void *nd6_add_default_router(const ip6_addr_t *router_addr, u32_t lifetime, struct netif *netif); + +err_t nd6_get_default_router_ip(ip6_addr_t *router_addr, void *default_route); + +void nd6_remove_default_router(void *default_route); + +void nd6_refresh_destination_cache(const ip6_addr_t *nexthop_addr); +void nd6_refresh_destination_cache_by_dest(const ip6_addr_t *dest); +#endif + +#if LWIP_IPV6_AUTOCONFIG +void nd6_clear_netif_autoconf_address(struct netif *netif); +#endif + +int nd6_validate_options(u8_t *opt, int opt_len); +void nd6_restart_netif(struct netif *netif); +void nd6_report_groups(struct netif *netif, s8_t addr_idx); + +#if LWIP_ND6_STATIC_DEFAULT_ROUTE +err_t lwip_nd6_add_static_default_route_manually(struct netif *netif, struct ip6_addr *router_addr); +err_t lwip_nd6_del_static_default_route(struct netif *netif, const ip6_addr_t *router_addr); +#endif /* LWIP_ND6_STATIC_DEFAULT_ROUTE */ +#if LWIP_ND6_STATIC_PREFIX +s8_t nd6_add_static_prefix(struct netif *netif, ip6_addr_t *prefix, u8_t flags); +s8_t nd6_del_static_prefix(struct netif *netif, ip6_addr_t *prefix); +#endif /* LWIP_ND6_STATIC_PREFIX */ + +#if LWIP_RIPPLE +struct nd6_neighbor_cache_entry *nd6_get_neighbor_byindex(s8_t nbrindex); +struct nd6_neighbor_cache_entry *nd6_neighbor_cache_lookup(const ip6_addr_t *ip6addr, struct netif *iface); +void beacon_priority_update(u8_t is_clear); +#endif /* LWIP_RIPPLE */ + +s8_t nd6_find_neighbor_cache_entry(const ip6_addr_t *ip6addr, struct netif *netif); + +#if LWIP_ENABLE_ROUTER +void *nd6_get_neighbor_linkquality_from_lladdr(struct netif *linkiface, const u8_t *sendermac, u8_t hwaddrlen); +u8_t *nd6_get_neighbor_lladdr(struct netif *linkiface, const ip6_addr_t *ip6addr, u8_t *lladdrlen); +void *nd6_get_neighbor_cache_entry_from_lladdr(struct netif *linkiface, u8_t *sendermac, u8_t hwaddrlen); +void nd6_remove_neighbor_cache_entry(struct netif *netif, const ip6_addr_t *nbr_addr); +void nd6_remove_neighbor_by_mac(struct netif *netif, const u8_t *mac, u8_t maclen); +#endif + +#if LWIP_NBRPOLICY_ENABLE_NBR_RESTRICTION +s8_t lwip_nbrpolicy_find_reusable_entry(u8_t uc_reason2_add, void *pv_data, s8_t *index2use); +#endif /* LWIP_NBRPOLICY_ENABLE_NBR_RESTRICTION */ + +u16_t lwip_nbr_cache_free_count(void); + +#ifdef LWIP_LOWPOWER +u32_t nd6_tmr_tick(void); +#endif + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_IPV6 */ + +#endif /* LWIP_HDR_ND6_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/netbuf.h b/sdk_liteos/third_party/lwip_sack/include/lwip/netbuf.h new file mode 100644 index 0000000000000000000000000000000000000000..b90188b13b920dab8ff7a290adbece35da26470c --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/netbuf.h @@ -0,0 +1,139 @@ +/** + * @file + * netbuf API (for netconn API) + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_NETBUF_H +#define LWIP_HDR_NETBUF_H + +#include "lwip/opt.h" + +#if LWIP_NETCONN || LWIP_SOCKET /* don't build if not configured for use in lwipopts.h */ +/* Note: Netconn API is always available when sockets are enabled - + * sockets are implemented on top of them */ + +#include "lwip/pbuf.h" +#include "lwip/ip_addr.h" +#include "lwip/ip6_addr.h" + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +/** This netbuf has dest-addr/port set */ +#define NETBUF_FLAG_DESTADDR 0x01 +/** This netbuf includes a checksum */ +#define NETBUF_FLAG_CHKSUM 0x02 +#if PF_PKT_SUPPORT +/* + * This netbuf includes the destination mac addr only + * this is in case of PF_PACKET RAW sockets + */ +#define NETBUF_FLAG_IFINDEX 0x04 +#endif + +/** "Network buffer" - contains data and addressing info */ +struct netbuf { + struct pbuf *p, *ptr; + ip_addr_t addr; + u16_t port; +#if PF_PKT_SUPPORT + u16_t hatype; + u16_t reserve; /* padded */ + /* Used to store destination mac addr in case of PF_PACKET RAW sockets */ + u8_t netifindex; +#if !LWIP_CHECKSUM_ON_COPY + u8_t flags; +#endif +#endif + +#if LWIP_NETBUF_RECVINFO || LWIP_CHECKSUM_ON_COPY +#if LWIP_CHECKSUM_ON_COPY + u8_t flags; +#endif /* LWIP_CHECKSUM_ON_COPY */ + u16_t toport_chksum; +#if LWIP_NETBUF_RECVINFO + ip_addr_t toaddr; +#endif /* LWIP_NETBUF_RECVINFO */ +#endif /* LWIP_NETBUF_RECVINFO || LWIP_CHECKSUM_ON_COPY */ +}; + +/* Network buffer functions: */ +struct netbuf *netbuf_new (void); +void netbuf_delete (struct netbuf *buf); +void *netbuf_alloc (struct netbuf *buf, u16_t size, u8_t netconn_type); +void netbuf_free (struct netbuf *buf); +err_t netbuf_ref (struct netbuf *buf, + const void *dataptr, u16_t size); +#if LWIP_API_RICH +void netbuf_chain (struct netbuf *head, struct netbuf *tail); + +err_t netbuf_data (struct netbuf *buf, + void **dataptr, u16_t *len); +s8_t netbuf_next (struct netbuf *buf); +void netbuf_first (struct netbuf *buf); +#endif /* LWIP_API_RICH */ + +#define netbuf_copy_partial(buf, dataptr, len, offset) \ + pbuf_copy_partial((buf)->p, (dataptr), (len), (offset)) +#define netbuf_copy(buf, dataptr, len) netbuf_copy_partial(buf, dataptr, len, 0) +#define netbuf_take(buf, dataptr, len) pbuf_take((buf)->p, dataptr, len) +#define netbuf_len(buf) ((buf)->p->tot_len) +#define netbuf_fromaddr(buf) (&((buf)->addr)) +#define netbuf_set_fromaddr(buf, fromaddr) ip_addr_set(&((buf)->addr), fromaddr) +#define netbuf_fromport(buf) ((buf)->port) +#define netbuf_fromifindex(buf) ((buf)->netifindex) +#define netbuf_fromhatype(buf) ((buf)->hatype) + +#if LWIP_NETBUF_RECVINFO +#define netbuf_destaddr(buf) (&((buf)->toaddr)) +#define netbuf_set_destaddr(buf, destaddr) ip_addr_set(&((buf)->toaddr), destaddr) +#if LWIP_CHECKSUM_ON_COPY +#define netbuf_destport(buf) (((buf)->flags & NETBUF_FLAG_DESTADDR) ? (buf)->toport_chksum : 0) +#else /* LWIP_CHECKSUM_ON_COPY */ +#define netbuf_destport(buf) ((buf)->toport_chksum) +#endif /* LWIP_CHECKSUM_ON_COPY */ +#endif /* LWIP_NETBUF_RECVINFO */ +#if LWIP_CHECKSUM_ON_COPY +#define netbuf_set_chksum(buf, chksum) do { (buf)->flags = NETBUF_FLAG_CHKSUM; \ + (buf)->toport_chksum = chksum; } while (0) +#endif /* LWIP_CHECKSUM_ON_COPY */ + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_NETCONN || LWIP_SOCKET */ + +#endif /* LWIP_HDR_NETBUF_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/netdb.h b/sdk_liteos/third_party/lwip_sack/include/lwip/netdb.h new file mode 100644 index 0000000000000000000000000000000000000000..f8f0400a00de02281bc467fc1d8cbf78d824d9b9 --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/netdb.h @@ -0,0 +1,380 @@ +/** + * @file + * NETDB API (sockets) + */ + +/* + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Simon Goldschmidt + * + */ + +/** +* @defgroup netdbapi netdb APIs +* @ingroup User_interfaces +* This contains all the netdb user interfaces. +*/ +#ifndef LWIP_HDR_NETDB_H +#define LWIP_HDR_NETDB_H + +#include "lwip/opt.h" +#if LWIP_LITEOS_COMPAT +#include +#endif +#if LWIP_DNS && LWIP_SOCKET + +#include "lwip/arch.h" +#include "lwip/inet.h" +#include "lwip/sockets.h" + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +#if !LWIP_LITEOS_COMPAT +/* some rarely used options */ +#ifndef LWIP_DNS_API_DECLARE_H_ERRNO +#define LWIP_DNS_API_DECLARE_H_ERRNO 1 +#endif + +#ifndef LWIP_DNS_API_DEFINE_ERRORS +#define LWIP_DNS_API_DEFINE_ERRORS 1 +#endif + +#ifndef LWIP_DNS_API_DEFINE_FLAGS +#define LWIP_DNS_API_DEFINE_FLAGS 1 +#endif + +#ifndef LWIP_DNS_API_DECLARE_STRUCTS +#define LWIP_DNS_API_DECLARE_STRUCTS 1 +#endif + +#if LWIP_DNS_API_DEFINE_ERRORS +/** Errors used by the DNS API functions, h_errno can be one of them */ +#define EAI_NONAME 200 +#define EAI_SERVICE 201 +#define EAI_FAIL 202 +#define EAI_MEMORY 203 +#define EAI_FAMILY 204 +#define EAI_BADFLAGS 205 +#define EAI_OVERFLOW 206 +#define EAI_ADDRFAMILY 207 +#define EAI_AGAIN 208 + +/* h_errno values */ +#define HOST_NOT_FOUND 210 +#define NO_DATA 211 +#define NO_RECOVERY 212 +#define TRY_AGAIN 213 +#endif /* LWIP_DNS_API_DEFINE_ERRORS */ + +#if LWIP_DNS_API_DEFINE_FLAGS +/* input flags for struct addrinfo */ +#define AI_PASSIVE 0x01 +#define AI_CANONNAME 0x02 +#define AI_NUMERICHOST 0x04 +#define AI_NUMERICSERV 0x08 +#define AI_V4MAPPED 0x10 +#define AI_ALL 0x20 +#define AI_ADDRCONFIG 0x40 + +/* input flags for getnameinfo api */ +#define NI_NUMERICHOST 1 +#define NI_NUMERICSERV 2 +#define NI_NOFQDN 4 +#define NI_NAMEREQD 8 +#define NI_DGRAM 16 + +#endif /* LWIP_DNS_API_DEFINE_FLAGS */ + +#if LWIP_DNS_API_DECLARE_STRUCTS +/** +@brief This structure provides information about a host. +*/ +struct hostent { + char *h_name; /**< Indicates the official name of the host. */ + char **h_aliases; /**< Indicates a pointer to an array of pointers to alternative host names, + terminated by a null pointer. */ + int h_addrtype; /**< Indicates the address type. */ + int h_length; /**< Indicates the length, in bytes, of the address. */ + char **h_addr_list; /**< Indicates a pointer to an array of pointers to network addresses (in + network byte order) for the host, terminated by a null pointer. */ +#define h_addr h_addr_list[0] /* for backward compatibility */ +}; +/** +@brief Provides address information that specifies the + criteria for selecting the socket address structures returned in the + list pointed to by the res parameter of the lwip_getaddrinfo() function. +*/ +struct addrinfo { + int ai_flags; /**< Specifies input flags. */ + int ai_family; /**< Specifies the desired address family. + Valid values for this field include AF_INET and AF_INET6. */ + int ai_socktype; /**< Specifies the preferred socket type, for example + SOCK_STREAM or SOCK_DGRAM. Specifying 0 in this + field indicates that socket addresses of any type can be + returned by lwip_getaddrinfo(). */ + int ai_protocol; /**< Specifies the protocol for the returned socket + addresses. Specifying 0 in this field indicates that + socket addresses with any protocol can be returned by + lwip_getaddrinfo(). */ + socklen_t ai_addrlen; /**< Specifies the length of socket address. */ + struct sockaddr *ai_addr; /**< Specifies the socket address of socket. */ + char *ai_canonname; /**< Specifies the canonical name of the service location. */ + struct addrinfo *ai_next; /**< Pointer to next in the list. */ +}; +#endif /* LWIP_DNS_API_DECLARE_STRUCTS */ + +#if LWIP_DNS_API_DECLARE_H_ERRNO +/* application accessible error code set by the DNS API functions */ +extern int h_errno; +#endif /* LWIP_DNS_API_DECLARE_H_ERRNO */ + +#endif + +#define NETDB_ELEM_SIZE (sizeof(struct addrinfo) + sizeof(struct sockaddr_storage) + DNS_MAX_NAME_LENGTH + 1) +#ifndef NI_MAXHOST +/* Maximum size of a fully-qualified domain name */ +#define NI_MAXHOST 1025 +#endif +/* Maximum size of a service name */ +#define NI_MAXSERV 32 + +#if LWIP_GETHOSTBYNAME || (defined(LWIP_COMPAT_SOCKETS) && (LWIP_COMPAT_SOCKETS != 2)) +/** + * @ingroup netdbapi + * @brief This API is used to resolve a hostname (string) into an IP address + and return a structure of type hostent for the given host name. + * @param name Indicates either a hostname that is to be resolved or an IPv4 or IPv6 + address. + * @return + * Pointer to the hostent structure containing addresses of address family AF_INET or AF_INET6 for the host with the + * name 'name' : On success \n + * Null pointer: On error \n + h_errno variable holds an error number. When non-NULL, the return + value may point at static data, see the notes below. + The h_errno variable will contain one among the following error codes in case of failure\n + HOST_NOT_FOUND : Hostname not found in DNS Server.\n + TRY_AGAIN : Didnt receive information from an authoritative server.\n + NO_DATA : Hostname is genuine, but there are no A/AAAA records for it in the server.\n + NO_RECOVERY : Some server failure occured which cant be recovered.\n + EFAULT : If the parameter "name" is passed as NULL.\n + EINVAL : Some internal errors.\n + + * @note + * - This function is not thread-safe and should not be used in multiple threads. + * - If name is an IPv4 or IPv6 address, no lookup is performed and lwip_gethostbyname() + * copies the name into the h_name field and its struct in_addr equivalent + * into the h_addr_list[0] field of the returned hostent structure.\n + * - This API can give more than one resolved IP address.\n + * - While parsing the multiple answer recrods in DNS response message, if + * it encounters any malformed answer record then it stops parsing and returns + * success if it has successfully parsed some record or else it returns failure.\n + * - DNS Query for the name, if needed, will be sent out immediately.\n + * - If the time gap between the transmission of first DNS Query and the periodic + * retransmission of the same query is less than 100ms, then the periodic retransmission + * will be postponed by another 1100ms. + */ +struct hostent *lwip_gethostbyname(const char *name); +#endif /* LWIP_GETHOSTBYNAME || (defined(LWIP_COMPAT_SOCKETS) && (LWIP_COMPAT_SOCKETS != 2)) */ + +#if (defined(LWIP_COMPAT_SOCKETS) && LWIP_COMPAT_SOCKETS != 2) || LWIP_ENABLE_BASIC_SHELL_CMD +/** + * @ingroup netdbapi + * @brief This function is the thread-safe variant of the lwip_gethostbyname() function. + * It is used to resolve a hostname (string) into an IP address and return a structure of type hostent for the given + * host name. Here name is either a hostname, or an IPv4/IPv6 address in standard dot/colon notation respectively. + * Instead of using a static buffer, this function takes buf and h_errnop pointers as arguments + * and uses these for the result. + * @param name The hostname that is to be resolved. + * @param ret The pre-allocated structure where the result is stored. + * @param buf The pre-allocated buffer where additional data is stored. + * @param buflen The size of the buffer. + * @param result This is a double pointer to hostent which is set to ret on success + * and set to zero on error scenario. + * @param h_errnop Indicates the pointer to an int where to store errors (instead of modifying + * the global h_errno) + * @return + * 0: On success \n + * -1: On failure. + * The h_errnop variable will contain one among the following error codes in case of failure.\n + * HOST_NOT_FOUND : Hostname not found in DNS Server.\n + * TRY_AGAIN : Didnt receive information from an authoritative server.\n + * NO_DATA : Hostname is genuine, but there are no A/AAAA records for it in the server.\n + * NO_RECOVERY : Some server failure occured which cant be recovered.\n + * EINVAL : Invalid arguments.\n + * ERANGE : Result not representable due to storage size limitations.\n + * @note + * - Additional error information is stored in *h_errnop instead of h_errno to be thread-safe.\n + * - If name is an IPv4 or IPv6 address, no lookup is performed and lwip_gethostbyname_r() + * copies the name into the h_name field and its struct in_addr equivalent + * into the h_addr_list[0] field of the returned hostent structure.\n + * - This API can give more than one resolved IP address.\n + * - While parsing the multiple answer recrods in DNS response message, if + * it encounters any malformed answer record then it stops parsing and returns + * success if it has successfully parsed some record or else it returns failure.\n + * - DNS Query for the name, if needed, will be sent out immediately.\n + * - If the time gap between the transmission of first DNS Query and the periodic + * retransmission of the same query is less than 100ms, then the periodic retransmission + * will be postponed by another 1100ms. + */ +int lwip_gethostbyname_r(const char *name, struct hostent *ret, char *buf, + size_t buflen, struct hostent **result, int *h_errnop); +#endif /* (defined(LWIP_COMPAT_SOCKETS) && LWIP_COMPAT_SOCKETS != 2) || LWIP_ENABLE_BASIC_SHELL_CMD */ + +#if (defined(LWIP_COMPAT_SOCKETS) && LWIP_COMPAT_SOCKETS != 2) || LWIP_ENABLE_LOS_SHELL_CMD +/** + * @ingroup netdbapi + * @brief This API is used to free one or more addrinfo + * structures returned by the lwip_getaddrinfo() function, along with any additional + * storage associated with those structures. If the ai_next field of the + * structure ai is not null, the entire list of structures is freed. + * + * @param ai The struct addrinfo to free. + * @return + * None + */ +void lwip_freeaddrinfo(struct addrinfo *ai); + + +/** + * @ingroup netdbapi + * @brief Translates the name of a service location (for example, a host name) and + * a service name and returns a set of socket addresses and associated + * information to be used in creating a socket with which to address the + * specified service. + * Memory for the result is allocated internally and must be freed by calling + * lwip_freeaddrinfo(). \n + * + * The servname parameter supports only port numbers, and does not support service names. + * @param nodename Indicates a descriptive name or address string of the host. NULL denotes a + local address. + * @param servname Indicates the port number of the service as string or NULL. + * @param hints Indicates a structure containing input values that set socktype and protocol. + * @param res Indicates a pointer to a pointer indicating where to store the result. This is set to NULL on failure. + * @return + * 0: On success \n + * Non-zero error number: On failure\n + * EAI_FAIL : If the input parameter res is NULL or the name server returned a permanent failure indication.\n + * EAI_FAMILY : The requested address family is not supported.\n + * EAI_NONAME : The node or service is not known; or both node and service are + NULL; or service was not a numeric port-number string. Currently, + service supports only AI_NUMERICSERV flag.\n + * EAI_MEMORY : Out of memory.\n + * EAI_ADDRFAMILY : The specified network host does not have any network addresses in the requested address family.\n + * EAI_AGAIN : The name server returned a temporary failure indication. Try again later. + + * @par Note + * - Either nodename or servname, but not both, may be NULL. + * - No support for translation of service names.\n + * - If the specified network host does not have any network addresses in the requested address family, + * EAI_FAIL will be returned. + * - Either nodename or servname, but not both, may be NULL. + */ +int lwip_getaddrinfo(const char *nodename, + const char *servname, + const struct addrinfo *hints, + struct addrinfo **res); +#endif /* (defined(LWIP_COMPAT_SOCKETS) && LWIP_COMPAT_SOCKETS != 2) || LWIP_ENABLE_LOS_SHELL_CMD */ + +#if LWIP_DNS_REVERSE +/** + * @ingroup netdbapi + * @brief Converts a socket address to a corresponding host and service, in a + * protocol-independent manner. It is reentrant and allows programs to eliminate + * IPv4-versus-IPv6 dependencies. + * Memory for the result is allocated by the caller. + * + * @param sa Indicates a pointer to a generic socket address structure + * (of type sockaddr_in or sockaddr_in6) that holds the + * input IP address and port number. + * @param salen Indicates the size of the generic socket address structure "sa". + * @param host Indicates a pointer to caller-allocated buffer which will holds the null terminated hostname string. + * @param hostlen Indicates the size of "host" buffer. + * @param serv Indicates a pointer to caller-allocated buffer which will holds the null terminated service-name string. + * @param servlen Indicates the size of "serv" buffer. + * @param flags Used to modify the behaviour of lwip_getnameinfo() and can have the following values: + * - NI_NAMEREQD : If set, then an error is returned if the hostname cannot be determined. + * - NI_DGRAM : If set, then the service is datagram (UDP) based rather than stream (TCP) based and causes + * getservbyport() to be called with a second argument of "udp" instead of its default of "tcp". + * This is required for the few ports (512-514) that have different services for UDP and TCP. + * - NI_NOFQDN : If set, return only the hostname part of the fully qualified domain name for local hosts. + * - NI_NUMERICHOST : If set, then the numeric form of the hostname is returned. (When not set, this will still happen + * in case the node's name cannot be determined.) + * - NI_NUMERICSERV : If set, then the numeric form of the service address is returned. (When not set, this will still + * happen in case the service's name cannot be determined.) + * @return + * 0: On success \n + * Non-zero error number: On failure + * EAI_FAIL : A nonrecoverable error occurred.. + * EAI_FAMILY : The requested address family is not supported. + * EAI_NONAME : The name does not resolve for the supplied arguments. NI_NAMEREQD is set and the host's name cannot be + * located, or neither hostname nor service name were requested. + * EAI_OVERFLOW : The buffer pointed to by host or serv was too small. + * EAI_BADFLAGS : The "flags" argument has an invalid value.. + + * @par Note + * - No support for translation of service names.\n + * - Since there is no support for Service names, the flags - NI_DGRAM, NI_NUMERICSERV is not supported. + * - NI_NOFQDN is not currently implemented + * - Reverse DNS Query for the IP Address, if needed, will be sent out immediately.\n + * - If the time gap between the transmission of first Reverse DNS Query and the periodic + * retransmission of the same query is less than 100ms, then the periodic retransmission + * will be postponed by another 1100ms. + */ +int lwip_getnameinfo(const struct sockaddr *sa, + socklen_t salen, + char *host, + size_t hostlen, + char *serv, + size_t servlen, + int flags); +#endif /* LWIP_DNS_REVERSE */ + +#if defined(LWIP_COMPAT_SOCKETS) && LWIP_COMPAT_SOCKETS != 2 +/** @ingroup netdbapi */ +#define gethostbyname(name) lwip_gethostbyname(name) +/** @ingroup netdbapi */ +#define gethostbyname_r(name, ret, buf, buflen, result, h_errnop) \ + lwip_gethostbyname_r(name, ret, buf, buflen, result, h_errnop) +/** @ingroup netdbapi */ +#define freeaddrinfo(addrinfo) lwip_freeaddrinfo(addrinfo) +/** @ingroup netdbapi */ +#define getaddrinfo(nodname, servname, hints, res) \ + lwip_getaddrinfo(nodname, servname, hints, res) + +/* @ingroup netdbapi */ +#define getnameinfo(sock, sock_size, host, host_len, servname, servname_size, flags) \ + lwip_getnameinfo(sock, sock_size, host, host_len, servname, servname_size, flags) +#endif /* defined(LWIP_COMPAT_SOCKETS) && LWIP_COMPAT_SOCKETS != 2 */ + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_DNS && LWIP_SOCKET */ + +#endif /* LWIP_HDR_NETDB_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/netif.h b/sdk_liteos/third_party/lwip_sack/include/lwip/netif.h new file mode 100644 index 0000000000000000000000000000000000000000..7131b2d74b1a85f45407bf5a19ffa0f9cca617de --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/netif.h @@ -0,0 +1,1121 @@ +/** + * @file + * netif API (to be used from TCPIP thread) + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_NETIF_H +#define LWIP_HDR_NETIF_H + +#include "lwip/opt.h" + +#define ENABLE_LOOPBACK (LWIP_NETIF_LOOPBACK || LWIP_HAVE_LOOPIF) + +#include "lwip/nd6.h" +#include "lwip/err.h" + +#include "lwip/ip_addr.h" + +#include "lwip/def.h" +#include "lwip/pbuf.h" +#include "lwip/stats.h" +#include "netif/etharp.h" +#include "netif/driverif.h" +#include "arch/sys_arch.h" +#include "lwip/if_api.h" +#include "lwip/prot/ethernet.h" +#if LWIP_NETIF_PROMISC +#include "lwip/sys.h" +#endif + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +/* Throughout this file, IP addresses are expected to be in + * the same byte order as in IP_PCB. */ +/** @cond liteosnetif + The maximum of all used hardware address lengths + across all types of interfaces in use. + This does not have to be changed, normally. */ +#ifndef NETIF_MAX_HWADDR_LEN +#define NETIF_MAX_HWADDR_LEN 6U +#endif + +/** + * @defgroup netif_flags Flags + * @ingroup netif + * @{ + */ + +/** Defines whether the network interface is 'up'. This is + * a software flag used to control whether this network + * interface is enabled and processes traffic. + * It must be set by the startup code before this netif can be used + * (also for dhcp/autoip). + */ +#define NETIF_FLAG_UP 0x01U +/** If set, the netif has broadcast capability. + * Set by the netif driver in its init function. */ +#define NETIF_FLAG_BROADCAST 0x02U +/** If set, the interface has an active link + * (set by the network interface driver). + * Either set by the netif driver in its init function (if the link + * is up at that time) or at a later point when the link comes up + * (if link detection is supported by the hardware). */ +#define NETIF_FLAG_LINK_UP 0x04U +/** If set, the netif is an ethernet device using ARP. + * Set by the netif driver in its init function. + * Used to check input packet types and use of DHCP. */ +#define NETIF_FLAG_ETHARP 0x08U +/** If set, the netif is an ethernet device. It might not use + * ARP or TCP/IP if it is used for PPPoE only. + */ +#define NETIF_FLAG_ETHERNET 0x10U +/** If set, the netif has IGMP capability. + * Set by the netif driver in its init function. */ +#define NETIF_FLAG_IGMP 0x20U +/** If set, the netif has MLD6 capability. + * Set by the netif driver in its init function. */ +#define NETIF_FLAG_MLD6 0x40U + +/** If set, the interface is configured using DHCP. + * Set by the DHCP code when starting or stopping DHCP. */ +#define NETIF_FLAG_DHCP 0x80U + +#if DRIVER_STATUS_CHECK +/** If set, the netif has send capability. + * Set by the netif driver when its is ready to send. */ +#define NETIF_FLAG_DRIVER_RDY 0x100U +#endif +/** If set, the netif is one end of a point-to-point connection. + * Set by the netif driver in its init function. */ +#define NETIF_FLAG_POINTTOPOINT 0x200U + +#if LWIP_TX_CSUM_OFFLOAD +/* If set, the netif has checksum offload capability, Set by the netif driver */ +#define NETIF_FLAG_DRIVER_CSUM_SUPPORT 0x400U +#endif + +#define NETIF_FLAG_LOOPBACK 0x800 + + +#if LWIP_NETIF_PROMISC +#define NETIF_FLAG_PROMISC 0x1000U +#define NETIF_FLAG_PROMISC_RUNNING 0x2000U +#endif /* LWIP_NETIF_PROMISC */ + +#if LWIP_MAC_SECURITY +#define NETIF_FLAG_MAC_SECURITY_SUPPORT 0x4000U +#endif + +#if LWIP_IPV6 && (LWIP_RPL || LWIP_RIPPLE) +#define NETIF_IS_RPL_UP 0x8000U +#endif + +/** + * @} + */ + +enum lwip_internal_netif_client_data_index { +#if LWIP_IPV4 +#if LWIP_DHCP + LWIP_NETIF_CLIENT_DATA_INDEX_DHCP, +#endif +#if LWIP_AUTOIP + LWIP_NETIF_CLIENT_DATA_INDEX_AUTOIP, +#endif +#if LWIP_IGMP + LWIP_NETIF_CLIENT_DATA_INDEX_IGMP, +#endif +#endif /* LWIP_IPV4 */ +#if LWIP_IPV6 +#if LWIP_IPV6_DHCP6 + LWIP_NETIF_CLIENT_DATA_INDEX_DHCP6, +#endif +#if LWIP_IPV6_MLD + LWIP_NETIF_CLIENT_DATA_INDEX_MLD6, +#endif /* LWIP_IPV6_MLD */ +#if LWIP_IPV6_MLD_QUERIER + LWIP_NETIF_CLIENT_DATA_INDEX_MLD6_QUERIER, +#endif /* LWIP_IPV6_MLD_QUERIER */ +#endif /* LWIP_IPV6 */ + LWIP_NETIF_CLIENT_DATA_INDEX_MAX +}; + +#if LWIP_CHECKSUM_CTRL_PER_NETIF +#define NETIF_CHECKSUM_GEN_IP 0x0001 +#define NETIF_CHECKSUM_GEN_UDP 0x0002 +#define NETIF_CHECKSUM_GEN_TCP 0x0004 +#define NETIF_CHECKSUM_GEN_ICMP 0x0008 +#define NETIF_CHECKSUM_GEN_ICMP6 0x0010 +#define NETIF_CHECKSUM_CHECK_IP 0x0100 +#define NETIF_CHECKSUM_CHECK_UDP 0x0200 +#define NETIF_CHECKSUM_CHECK_TCP 0x0400 +#define NETIF_CHECKSUM_CHECK_ICMP 0x0800 +#define NETIF_CHECKSUM_CHECK_ICMP6 0x1000 +#define NETIF_CHECKSUM_ENABLE_ALL 0xFFFF +#define NETIF_CHECKSUM_DISABLE_ALL 0x0000 +#endif /* LWIP_CHECKSUM_CTRL_PER_NETIF */ + +struct netif; +struct linklayer_addr; + +#ifndef IFNAMSIZ +/* Length of interface name. */ +#define IFNAMSIZ 16 +#endif + +/** MAC Filter Actions, these are passed to a netif's igmp_mac_filter or + * mld_mac_filter callback function. */ +enum netif_mac_filter_action { + /** Delete a filter entry */ + NETIF_DEL_MAC_FILTER = 0, + /** Add a filter entry */ + NETIF_ADD_MAC_FILTER = 1 +}; + +struct linklayer_addr { + u8_t addr[NETIF_MAX_HWADDR_LEN]; + u8_t addrlen; +}; + +typedef struct linklayer_addr linklayer_addr_t; + +s8_t netif_find_dst_ip6addr_mac_addr(ip_addr_t *ipaddr, ip_addr_t **dst_addr, struct eth_addr **eth_ret); +/** Function prototype for netif init functions. Set up flags and output/linkoutput + * callback functions in this function. + * + * @param netif Indicates the netif to initialize. + */ +typedef err_t (*netif_init_fn)(struct netif *netif); +/** Function prototype for netif->input functions. This function is saved as 'input' + * callback function in the netif struct. Call this function when a packet has been received. + * Note- + * Passing a pbuf chain to ethernet_input (src/netif/ethernet.c) will not work as the function assumes the + packet is stored in one pbuf + * (for example, checks (p->len <= SIZEOF_ETH_HDR) instead of comparing p->tot_len, and assuming that the + next header offsets are on the same pbuf. + * + * @param p Indicates the received packet, copied into a pbuf. + * @param inp Indicates the netif which received the packet. + */ +typedef err_t (*netif_input_fn)(struct pbuf *p, struct netif *inp); + +#if LWIP_IPV4 +/** Function prototype for netif->output functions. Called by lwIP when a packet + * is sent. For ethernet netif, set this to 'etharp_output' and set + * 'linkoutput'. + * + * @param netif Indicates the netif which sends a packet. + * @param p Indicates the packet to send (p->payload points to IP header) + * @param ipaddr Indicates the IP address to which the packet is sent. + */ +typedef err_t (*netif_output_fn)(struct netif *netif, struct pbuf *p, + const ip4_addr_t *ipaddr); +#endif /* LWIP_IPV4*/ + +#if LWIP_IPV6 +/** Function prototype for netif->output_ip6 functions. Called by lwIP when a packet + * shall be sent. For ethernet netif, set this to 'ethip6_output' and set + * 'linkoutput'. + * + * @param netif The netif which shall send a packet + * @param p The packet to send (p->payload points to IP header) + * @param ipaddr The IPv6 address to which the packet shall be sent + */ +typedef err_t (*netif_output_ip6_fn)(struct netif *netif, struct pbuf *p, + const ip6_addr_t *ipaddr); + +#if LWIP_6LOWPAN +/* + * Function prototype for netif->output_ip6_over_lln functions. Called by lwIP when a packet + * shall be sent over link layers having limited MTU. + * For ieee802164 netif and plc netif , set this to 'output_ip6_over_lln' and set + * 'lln_linkoutput'. + * + * @param netif The netif which shall send a packet + * @param p The packet to send (p->payload points to IP header) + * @param dstlinkaddr The link layer address to which the packet shall be sent. + Source link layer address will be retrived from + the netif. + */ +typedef err_t (*netif_lowpan_output_fn)(struct netif *netif, struct pbuf *p, + const struct linklayer_addr *dstlinkaddr); +#endif +#endif /* LWIP_IPV6 */ + +#if LWIP_PLC || LWIP_IEEE802154 + +/* + * Function prototype for netif->input_lln functions. Called by MAC driver when a packet + * shall be sent to the lwip network interface to be processed by the upper layers. + * This need to be called by only plc mac driver and IEE802154 mac driver (In + * future versions), or any other MAC driver that want to use 6lowpan. + * + * @param netif The netif which will receive the packet + * @param p The packet to send (p->payload points to 6lowpan fragment or IPHC header) + * @param sendermac The link layer address of the sender. + * @param recvermac The link layer address of the receiver. + */ +typedef err_t (*netif_lln_input_fn)(struct netif *iface, struct pbuf *p, + struct linklayer_addr *sendermac, struct linklayer_addr *recvermac); +#endif + +/** Function prototype for netif->linkoutput functions. Only used for ethernet + * netifs. This function is called by ARP when a packet shall be sent. + * + * @param netif The netif which shall send a packet + * @param p The packet to send (raw ethernet packet) + */ +typedef err_t (*netif_linkoutput_fn)(struct netif *netif, struct pbuf *p); +/* Function prototype for netif status- or link-callback functions. */ +/** +* @ingroup Threadsafe_Network_Interfaces +* @par Description +* Netif status callback. +*/ +typedef void (*netif_status_callback_fn)(struct netif *netif); +#if LWIP_IPV4 && LWIP_IGMP && LWIP_LINK_MCAST_FILTER +/** Function prototype for netif igmp_mac_filter functions */ +typedef err_t (*netif_igmp_mac_filter_fn)(struct netif *netif, + const ip4_addr_t *group, enum netif_mac_filter_action action); +#endif /* LWIP_IPV4 && LWIP_IGMP && LWIP_LINK_MCAST_FILTER */ +#if LWIP_IPV6 && LWIP_IPV6_MLD && LWIP_LINK_MCAST_FILTER +/** Function prototype for netif mld_mac_filter functions */ +typedef err_t (*netif_mld_mac_filter_fn)(struct netif *netif, + const ip6_addr_t *group, enum netif_mac_filter_action action); +#endif /* LWIP_IPV6 && LWIP_IPV6_MLD && LWIP_LINK_MCAST_FILTER */ + +#if LWIP_API_MESH +typedef enum linklayer_event_type { + LL_EVENT_TX_INFO = 0, + LL_EVENT_NEW_PEER, + LL_EVENT_DEL_PEER, + LL_EVENT_AP_CONN, + LL_EVENT_AP_DISCONN, + LL_EVENT_STA_CONN, + LL_EVENT_STA_DISCONN, + LL_EVENT_MAX +} linklayer_event_type_e; + +typedef struct linklayer_event_ap_conn { + struct linklayer_addr addr; + u8_t is_mesh_ap; + s8_t rssi; +} linklayer_event_ap_conn_t; +typedef struct linklayer_event_sta_conn { + struct linklayer_addr addr; +} linklayer_event_sta_conn_t; + +typedef err_t (*netif_linklayer_event_fn)(struct netif *netif, u8_t evt_type, void *evt_info); + +#if LWIP_RPL || LWIP_RIPPLE +typedef u16_t uniqid_t; + +typedef struct linklayer_event_tx_info { + struct linklayer_addr addr; + u8_t status; + u8_t retry_count; + u16_t pkt_sz; + u32_t data_rate; /* unit kbps */ + u32_t bandwidth; /* unit kbps */ +} linklayer_event_tx_info_t; + +typedef struct linklayer_event_new_peer { + struct linklayer_addr addr; + u8_t is_mesh_user; + s8_t rssi; + u8_t beacon_prio; + u8_t lqi; +} linklayer_event_new_peer_t; + +typedef struct linklayer_event_del_peer { + struct linklayer_addr addr; + u8_t is_mesh_user; +} linklayer_event_del_peer_t; + +typedef err_t (*netif_remove_peer_fn)(struct netif *netif, struct linklayer_addr *peeraddr); +typedef err_t (*netif_set_beacon_prio_fn)(struct netif *netif, u8_t prio); +typedef err_t (*netif_set_unique_id_fn)(struct netif *netif, uniqid_t id); +typedef err_t (*netif_get_peer_count_fn)(struct netif *netif, u16_t *count); +typedef err_t (*netif_set_rank_fn)(struct netif *netif, u16_t rank); +#endif /* LWIP_RPL || LWIP_RIPPLE */ +#endif /* LWIP_API_MESH */ + +#if LWIP_DHCP || LWIP_AUTOIP || LWIP_IGMP || LWIP_IPV6_MLD || (LWIP_NUM_NETIF_CLIENT_DATA > 0) +u8_t netif_alloc_client_data_id(void); +/** @ingroup netif_cd + * Set client data. Obtain ID from netif_alloc_client_data_id(). + */ +#define netif_set_client_data(netif, id, data) netif_get_client_data(netif, id) = (data) +/** @ingroup netif_cd + * Get client data. Obtain ID from netif_alloc_client_data_id(). + */ +#define netif_get_client_data(netif, id) (netif)->client_data[(id)] +#endif /* LWIP_DHCP || LWIP_AUTOIP || (LWIP_NUM_NETIF_CLIENT_DATA > 0) */ + +#if LWIP_NETIF_HWADDRHINT +struct netif_hint { + u8_t addr_hint; +}; +#endif /* LWIP_NETIF_HWADDRHINT */ + +#if LWIP_IPV6 +/* A callback prototype for handling duplicate address. */ +typedef void (*lwip_ipv6_addr_event)(struct netif *, ip6_addr_t, u8_t); + +#define LWIP_IPV6_ND6_FLAG_DAD 0x01U +#define LWIP_IPV6_ND6_FLAG_DEPRECATED 0x02U + +#if (defined(LWIP_IPV6_DUP_DETECT_ATTEMPTS) && LWIP_IPV6_DUP_DETECT_ATTEMPTS) +#define LWIP_IS_DAD_ENABLED(netif) (((netif)->ipv6_flags & LWIP_IPV6_ND6_FLAG_DAD)) +#else +#define LWIP_IS_DAD_ENABLED(netif) 0 +#endif +#endif /* LWIP_IPV6*/ + +/** Generic data structure used for all lwIP network interfaces. + * The following fields should be filled in by the initialization + * function for the device driver: hwaddr_len, hwaddr[], mtu, flags */ +struct netif { +#if !LWIP_SINGLE_NETIF + /** Indicates a pointer to next in linked list. */ + struct netif *next; +#endif +#if LWIP_API_MESH + netif_linklayer_event_fn linklayer_event; /* registered by lwip and called by linklayer */ +#if LWIP_RPL || LWIP_RIPPLE + netif_remove_peer_fn remove_peer; + netif_set_beacon_prio_fn set_beacon_prio; + netif_set_unique_id_fn set_unique_id; + netif_get_peer_count_fn get_peer_count; + netif_set_rank_fn set_rank; +#endif +#endif /* LWIP_API_MESH */ + +#if LWIP_IPV4 + /** IP address configuration in network byte order */ + ip_addr_t ip_addr; /**< Indicates the IP address configuration in network byte order. */ + ip_addr_t netmask; /**< Indicates the netmask for the IP. */ + ip_addr_t gw; /**< Indicates the gateway. */ + +#endif /* LWIP_IPV4 */ +#if LWIP_IPV6 + /** Array of IPv6 addresses for this netif. */ + ip_addr_t ip6_addr[LWIP_IPV6_NUM_ADDRESSES]; + /** The state of each IPv6 address (Tentative, Preferred, etc). + * @see ip6_addr.h */ + u8_t ip6_addr_state[LWIP_IPV6_NUM_ADDRESSES]; +#if defined(LWIP_IP6_DYNAMIC_PREFIX) && LWIP_IP6_DYNAMIC_PREFIX + u8_t ip6_prefix_len[LWIP_IPV6_NUM_ADDRESSES]; +#endif +#if LWIP_IPV6_ADDRESS_LIFETIMES + /** + * Remaining valid and preferred lifetime of each IPv6 address, in seconds. + * For valid lifetimes, the special value of IP6_ADDR_LIFE_STATIC (0) + * indicates the address is static and has no lifetimes. */ + u32_t ip6_addr_valid_life[LWIP_IPV6_NUM_ADDRESSES]; + u32_t ip6_addr_pref_life[LWIP_IPV6_NUM_ADDRESSES]; +#endif /* LWIP_IPV6_ADDRESS_LIFETIMES */ +#endif /* LWIP_IPV6 */ + /** This function is called by the network device driver + * to pass a packet up the TCP/IP stack. */ + netif_input_fn input; +#if LWIP_IPV4 + /** This function is called by the IP module when it wants + * to send a packet on the interface. This function typically + * first resolves the hardware address, then sends the packet. + * For ethernet physical layer, this is usually etharp_output() */ + netif_output_fn output; +#endif /* LWIP_IPV4 */ + /** This function is called by ethernet_output() when it wants + * to send a packet on the interface. This function outputs + * the pbuf as-is on the link medium. */ + netif_linkoutput_fn linkoutput; +#if LWIP_IPV6 + /** This function is called by the IPv6 module when it wants + * to send a packet on the interface. This function typically + * first resolves the hardware address, then sends the packet. + * For ethernet physical layer, this is usually ethip6_output() */ + netif_output_ip6_fn output_ip6; + + /* + * This function will be called by the 6lowpan or driver adaptor layer to + * send the packet to the MAC driver + */ + drv_send_lln_fn drv_lln_send; + +#if LWIP_6LOWPAN + netif_lowpan_output_fn lowpan_output; +#endif +#endif /* LWIP_IPV6 */ + +#if LWIP_PLC || LWIP_IEEE802154 + netif_lln_input_fn input_lln; +#endif +#if LWIP_L2_NETDEV_STATUS_CALLBACK + netif_status_callback_fn l2_netdev_status_callback; /**< notice for wifi when AT command is ifconfig down/up */ +#endif +#if LWIP_NETIF_STATUS_CALLBACK + /** This function is called when the netif state is set to up or down + */ + netif_status_callback_fn status_callback; /**< Called when the netif state is set to up or down. */ +#endif /* LWIP_NETIF_STATUS_CALLBACK */ +#if LWIP_NETIF_LINK_CALLBACK + /** This function is called when the netif link is set to up or down + */ + netif_status_callback_fn link_callback; /**< Called when the netif link is set to up or down. */ +#endif /* LWIP_NETIF_LINK_CALLBACK */ +#if LWIP_NETIF_REMOVE_CALLBACK + /** This function is called when the netif has been removed */ + netif_status_callback_fn remove_callback; /**< Called when the netif is removed. */ +#endif /* LWIP_NETIF_REMOVE_CALLBACK */ + /** This field can be set by the device driver and could point + * to state information for the device. */ + void *state; /**< This field can be set by the device driver and could point to state information + for the device. */ + /* This function is called by lwIP to send a packet on the interface. */ + drv_send_fn drv_send; /**< This function is called when lwIP wants to send a packet to interface. */ + /* This function is called by lwIP + * to set the mac_address of the interface. */ + drv_set_hwaddr_fn drv_set_hwaddr; /**< This function is called when lwIP wants to set the mac_address + of the interface. */ +#if LWIP_NETIF_ETHTOOL + struct ethtool_ops *ethtool_ops; +#endif +#if LWIP_DHCPS + /* DHCP Server Informarion for this netif */ + struct dhcps *dhcps; +#endif +#if LWIP_NETIF_PROMISC + /** This function is called by lwIP + * to set/unset the promiscuous mode of the interface. */ + drv_config_fn drv_config; +#endif /*LWIP_NETIF_PROMISC*/ +#ifdef netif_get_client_data + void *client_data[LWIP_NETIF_CLIENT_DATA_INDEX_MAX + LWIP_NUM_NETIF_CLIENT_DATA]; +#endif +#if LWIP_IPV6_AUTOCONFIG + /** Indicates whether this netif is enabled for IPv6 autoconfiguration. */ + u8_t ip6_autoconfig_enabled; +#endif /* LWIP_IPV6_AUTOCONFIG */ +#if LWIP_IPV6_SEND_ROUTER_SOLICIT + /** Number of Router Solicitation messages that remain to be sent. */ + u8_t rs_count; +#endif /* LWIP_IPV6_SEND_ROUTER_SOLICIT */ + /* the hostname buffer for this netif. */ + char hostname[NETIF_HOSTNAME_MAX_LEN]; +#if LWIP_CHECKSUM_CTRL_PER_NETIF + u16_t chksum_flags; +#endif /* LWIP_CHECKSUM_CTRL_PER_NETIF*/ + /** maximum transfer unit (in bytes) */ + u16_t mtu; /**< Maximum transfer unit (in bytes). */ +#if LWIP_IPV6 && LWIP_ND6_ALLOW_RA_UPDATES + /** maximum transfer unit (in bytes), updated by RA */ + u16_t mtu6; +#endif /* LWIP_IPV6 && LWIP_ND6_ALLOW_RA_UPDATES */ + /** number of bytes used in hwaddr */ + u8_t hwaddr_len; /**< Number of bytes used in hwaddr. \n */ + /* Indicates the link level hardware address of this interface. */ + u8_t hwaddr[NETIF_MAX_HWADDR_LEN]; /**< Indicates the link level hardware address + of this interface. */ + /* link layer type, ethernet or wifi */ + u16_t link_layer_type; /**< Indicates whether the link layer type is ethernet or wifi. */ + /* flags (see NETIF_FLAG_ above) */ + u32_t flags; /**< Indicates flags (see NETIF_FLAG_ above). */ + +#if LWIP_NETIF_PROMISC + atomic_t flags_ext; + u32_t flags_ext1; +#endif /* LWIP_NETIF_PROMISC */ + /** descriptive abbreviation */ + char name[IFNAMSIZ]; /**< Descriptive abbreviation. */ + /** number of this interface */ + u8_t num; /**< Indicates the number of this interface. */ + u8_t ifindex; /* Interface Index mapped to each netif. Starts from 1 */ +#if MIB2_STATS + /** link type (from "snmp_ifType" enum from snmp_mib2.h) */ + u8_t link_type; /**< Indicates the Link type (from "snmp_ifType" enum from snmp.h). */ + /** (estimate) link speed */ + u32_t link_speed; /**< Indicates the (estimate) Link speed. */ + /** timestamp at last change made (up/down) */ + u32_t ts; /**< Indicates the timestamp at last change made (up/down). */ + /** counters */ + struct stats_mib2_netif_ctrs mib2_counters; /**< Indicates counters. */ +#endif /* MIB2_STATS */ +#if LWIP_IPV4 && LWIP_IGMP && LWIP_LINK_MCAST_FILTER + /** This function could be called to add or delete an entry in the multicast + filter table of the ethernet MAC. */ + netif_igmp_mac_filter_fn igmp_mac_filter; /**< This function must be called to add or delete a + entry in the multicast filter table of the ethernet MAC. */ +#endif /* LWIP_IPV4 && LWIP_IGMP && LWIP_LINK_MCAST_FILTER */ +#if LWIP_IPV6 && LWIP_IPV6_MLD && LWIP_LINK_MCAST_FILTER + /** This function must be called to add or delete an entry in the IPv6 multicast + filter table of the ethernet MAC. */ + netif_mld_mac_filter_fn mld_mac_filter; +#endif /* LWIP_IPV6 && LWIP_IPV6_MLD && LWIP_LINK_MCAST_FILTER */ +#if LWIP_NETIF_USE_HINTS + struct netif_hint *hints; +#endif /* LWIP_NETIF_USE_HINTS */ +#if ENABLE_LOOPBACK + /* List of packets to be queued for ourselves. */ + struct pbuf *loop_first; /**< Indicates the list of packets to be queued for ourselves. */ + struct pbuf *loop_last; /**< Indicates the list of packets to be queued for ourselves. */ +#if LWIP_LOOPBACK_MAX_PBUFS + u16_t loop_cnt_current; /**< Indicates the pbuf count. */ +#endif /* LWIP_LOOPBACK_MAX_PBUFS */ +#endif /* ENABLE_LOOPBACK */ +#if DRIVER_STATUS_CHECK + s32_t waketime; /**< Started when netif_stop_queue is called from driver. */ +#endif + +#if LWIP_IPV6 + /** Call back needs to be registered if adaptor requires notification for IPv6 DAD */ + lwip_ipv6_addr_event ipv6_addr_event_cb; + u8_t ipv6_flags; +#if LWIP_ND6_ROUTER + u8_t forwarding; + u8_t accept_ra; + u8_t ra_enable; + u8_t ra_init_cnt; + u32_t ra_timer; +#endif +#endif + +#if LWIP_IPV6 && LWIP_6LOWPAN + /* If this network inetrface need to use 6lowpan */ + u8_t enabled6lowpan; +#endif +#if LWIP_MAC_SECURITY + /* If this network inetrface has finished mac layer authenication procedure */ + u8_t is_auth_sucess; +#endif +#if LWIP_ARP && LWIP_ARP_GRATUITOUS_REXMIT + u8_t arp_gratuitous_doing : 1; + u8_t arp_gratuitous_cnt : 7; +#endif +}; + +#if LWIP_CHECKSUM_CTRL_PER_NETIF +#define NETIF_SET_CHECKSUM_CTRL(netif, chksumflags) do { \ + (netif)->chksum_flags = chksumflags; } while (0) +#define IF__NETIF_CHECKSUM_ENABLED(netif, chksumflag) if (((netif) == NULL) || (((netif)->chksum_flags & (chksumflag)) != 0)) +#else /* LWIP_CHECKSUM_CTRL_PER_NETIF */ +#define NETIF_SET_CHECKSUM_CTRL(netif, chksumflags) +#define IF__NETIF_CHECKSUM_ENABLED(netif, chksumflag) +#endif /* LWIP_CHECKSUM_CTRL_PER_NETIF */ + +#if LWIP_SINGLE_NETIF +#define NETIF_FOREACH(netif) if (((netif) = netif_default) != NULL) +#else /* LWIP_SINGLE_NETIF */ +/** The list of network interfaces. */ +extern struct netif *netif_list; +#define NETIF_FOREACH(netif) for ((netif) = netif_list; (netif) != NULL; (netif) = (netif)->next) +#endif /* LWIP_SINGLE_NETIF */ +/** The default network interface. */ +extern struct netif *netif_default; +s8_t netif_find_dst_ipaddr(ip_addr_t *ipaddr, ip_addr_t **dst_addr); +void netif_init(void); + +#if LWIP_DHCP +#if LWIP_IOCTL_IF || LWIP_ENABLE_LOS_SHELL_CMD || LWIP_ENABLE_BASIC_SHELL_CMD +err_t netif_dhcp_off(struct netif *netif); +#endif +#endif +u8_t netif_is_valid(struct netif *nif); +u8_t netif_check_num_isusing(const char *ifname, const u8_t num); + +/** + * open or close netdev by netif without block as not using mutex + * the api only called by AT command ifconfig up/down + * @param netif the lwip network interface structure + * @return ERR_OK callback is ok + * ERR_VAL netif is NULL + */ +#if LWIP_L2_NETDEV_STATUS_CALLBACK +u8_t netif_l2_netdev_status_callback(struct netif *nif); +#endif + +#if LWIP_IPV4 +struct netif *netif_add(struct netif *netif, const ip4_addr_t *ipaddr, + const ip4_addr_t *netmask, const ip4_addr_t *gw); +#else +struct netif *netif_add(struct netif *netif); +#endif + +#if LWIP_IPV4 +err_t netif_set_addr(struct netif *netif, const ip4_addr_t *ipaddr, const ip4_addr_t *netmask, + const ip4_addr_t *gw); + +#if LWIP_NETIFAPI_GET_ADDR +err_t +netif_get_addr(struct netif *netif, ip4_addr_t *ipaddr, ip4_addr_t *netmask, ip4_addr_t *gw); +#endif /* LWIP_NETIFAPI_GET_ADDR */ +#endif /* LWIP_IPV4 */ +#ifdef LWIP_TESTBED +err_t netif_reset(struct netif *netif); +#endif +err_t netif_remove(struct netif *netif); + +/* Returns a network interface given its name. The name is of the form + "et0", where the first two letters are the "name" field in the + netif structure, and the digit is in the num field in the same + structure. */ +struct netif *netif_find(const char *name); + +struct netif *netif_find_by_ipaddr(const ip_addr_t *ipaddr); + +u8_t netif_ipaddr_isbrdcast(const ip_addr_t *ipaddr); + + +err_t netif_set_default(struct netif *netif); + +#if LWIP_IPV4 +void netif_set_ipaddr(struct netif *netif, const ip4_addr_t *ipaddr); +void netif_set_netmask(struct netif *netif, const ip4_addr_t *netmask); +void netif_set_gw(struct netif *netif, const ip4_addr_t *gw); +struct netif *netif_find_by_ip4addr(const ip_addr_t *ipaddr); +/** @ingroup netif_ip4 */ +#define netif_ip4_addr(netif) ((const ip4_addr_t*)ip_2_ip4(&((netif)->ip_addr))) +/** @ingroup netif_ip4 */ +#define netif_ip4_netmask(netif) ((const ip4_addr_t*)ip_2_ip4(&((netif)->netmask))) +/** @ingroup netif_ip4 */ +#define netif_ip4_gw(netif) ((const ip4_addr_t*)ip_2_ip4(&((netif)->gw))) +/** @ingroup netif_ip4 */ +#define netif_ip_addr4(netif) ((const ip_addr_t*)&((netif)->ip_addr)) +/** @ingroup netif_ip4 */ +#define netif_ip_netmask4(netif) ((const ip_addr_t*)&((netif)->netmask)) +/** @ingroup netif_ip4 */ +#define netif_ip_gw4(netif) ((const ip_addr_t*)&((netif)->gw)) +#endif /* LWIP_IPV4 */ + +err_t netif_set_up(struct netif *netif); +err_t netif_set_down(struct netif *netif); +#if LWIP_ENABLE_LOS_SHELL_CMD || LWIP_IOCTL_IF || LWIP_NETIFAPI_MTU || LWIP_ENABLE_BASIC_SHELL_CMD +err_t netif_set_mtu(struct netif *netif, u16_t netif_mtu); +err_t netif_set_hwaddr(struct netif *netif, const unsigned char *hw_addr, int hw_len); +#endif + +void +netif_get_hwaddr(struct netif *netif, unsigned char *hw_addr, int hw_len); +/** @ingroup netif + * Ask if an interface is up + */ +#define netif_is_up(netif) (((netif)->flags & NETIF_FLAG_UP) ? (u8_t)1 : (u8_t)0) + +#if LWIP_NETIF_STATUS_CALLBACK +/* Sets the callback to call when the interface is brought up/down. */ +void netif_set_status_callback(struct netif *netif, netif_status_callback_fn status_callback); +#endif /* LWIP_NETIF_STATUS_CALLBACK */ +#if LWIP_NETIF_REMOVE_CALLBACK + +/** + * @ingroup Driver_Interfaces + * @brief + * Sets the callback to call when the interface is removed. + * + * @param[in] netif Indicates the netif structure. + * @param[in] netif_status_callback_fn Indicates the netif set status callback function. + */ +void netif_set_remove_callback(struct netif *netif, netif_status_callback_fn remove_callback); +#endif /* LWIP_NETIF_REMOVE_CALLBACK */ + +err_t netif_set_link_up(struct netif *netif); +err_t netif_set_link_down(struct netif *netif); +void netif_set_link_up_interface(void *arg); +void netif_set_link_down_interface(void *arg); + +/** Ask if a link is up */ +#define netif_is_link_up(netif) (((netif)->flags & NETIF_FLAG_LINK_UP) ? (u8_t)1 : (u8_t)0) + +#if LWIP_NETIF_PROMISC +void netif_update_promiscuous_mode_status(struct netif *netif, u8_t set); +void netif_start_promisc_mode(u8_t ifindex); +void netif_stop_promisc_mode(u8_t ifindex); +#endif /* LWIP_NETIF_PROMISC */ + +#if DRIVER_STATUS_CHECK +err_t +netif_wake_queue(struct netif *netif); +err_t +netif_stop_queue(struct netif *netif); +#endif + +#if DRIVER_STATUS_CHECK +/** Ask if a driver is ready to send */ +#define netif_is_ready(netif) (((netif)->flags & NETIF_FLAG_DRIVER_RDY) ? (u8_t)1 : (u8_t)0) +#endif + +#if LWIP_NETIF_LINK_CALLBACK +err_t netif_set_link_callback(struct netif *netif, netif_status_callback_fn link_callback); +#endif /* LWIP_NETIF_LINK_CALLBACK */ + +#if LWIP_NETIF_HOSTNAME +/** @ingroup netif */ +#define netif_set_hostname(netif, name) do { if ((netif) != NULL) { (netif)->hostname = name; } } while (0) +#if LWIP_NETIF_GET_HOSTNAME +/** @ingroup netif */ +#define netif_get_hostname(netif) (((netif) != NULL) ? ((netif)->hostname) : NULL) +#endif /* LWIP_NETIF_GET_HOSTNAME */ +#endif /* LWIP_NETIF_HOSTNAME */ + +#if LWIP_IGMP && LWIP_LINK_MCAST_FILTER +/** @ingroup netif */ +/** + * + * Macro to set the IGMP mac filter function. + * The macro should be used after enabling LWIP_IPV4 and LWIP_IGMP + * The netif igmp_mac_filter function must be called to add or delete an ipv4 entry in the multicast filter + table of the ethernet MAC. + * The macro is not thread safe , and the set macro should be called immediately after netif_add. + * This macro cannot be called in runtime. + */ +#define netif_set_igmp_mac_filter(netif, function) do { \ + if ((netif) != NULL) { (netif)->igmp_mac_filter = function; } } while (0) +/** + * Macro to get the IGMP mac filter function . + * The macro should be used after enabling LWIP_IPV4 and LWIP_IGMP + * The netif igmp_mac_filter function must be called to add or delete an ipv4 entry in the multicast filter + table of the ethernet MAC. + * The macro is not thread safe , and the get macro should be called immediately after netif_add. + */ +#define netif_get_igmp_mac_filter(netif) (((netif) != NULL) ? ((netif)->igmp_mac_filter) : NULL) +#endif /* LWIP_IGMP && LWIP_LINK_MCAST_FILTER */ + +#if LWIP_IPV6 && LWIP_IPV6_MLD && LWIP_LINK_MCAST_FILTER +/** @ingroup netif */ +/** + * Macro to set the MLD6 mac filter function + * The macro should be used after enabling LWIP_IPV6 and LWIP_IPV6_MLD + * netif mld_mac_filter filter function must be called to add or delete an ipv6 entry in the multicast filter + table of the ethernet MAC. + * The macro is not thread safe , and the set macro should be called immediately after netif_add. + * This macro cannot be called in runtime. + */ +#define netif_set_mld_mac_filter(netif, function) do { \ + if ((netif) != NULL) { (netif)->mld_mac_filter = function; } } while (0) +/** + * Macro to get the MLD6 mac filter function + * The macro should be used after enabling LWIP_IPV6 and LWIP_IPV6_MLD + * netif mld_mac_filter filter function must be called to add or delete an ipv6 entry in the multicast filter + table of the ethernet MAC. + * The macro is not thread safe , and the get macro should be called immediately after netif_add. + */ +#define netif_get_mld_mac_filter(netif) (((netif) != NULL) ? ((netif)->mld_mac_filter) : NULL) +/** + * Macro to access the mld_mac_filter function added through the the netif_set_mld_mac_filter. + * The macro should be used after enabling LWIP_IPV6 and LWIP_IPV6_MLD + * netif mld_mac_filter filter function must be called to add or delete an ipv6 entry in the multicast filter + table of the ethernet MAC. + * The macro is not thread safe , and the macro should be called after netif_add. + */ +#define netif_mld_mac_filter(netif, addr, action) do { \ + if ((netif) && (netif)->mld_mac_filter) { (netif)->mld_mac_filter((netif), (addr), (action)); } } while (0) +#endif /* LWIP_IPV6 && LWIP_IPV6_MLD && LWIP_LINK_MCAST_FILTER */ + +#if ENABLE_LOOPBACK +err_t netif_loop_output(struct netif *netif, struct pbuf *p); +void netif_poll(struct netif *netif); +#if !LWIP_NETIF_LOOPBACK_MULTITHREADING +void netif_poll_all(void); +#endif /* !LWIP_NETIF_LOOPBACK_MULTITHREADING */ +#endif /* ENABLE_LOOPBACK */ + +#if LWIP_API_RICH +err_t netif_input(struct pbuf *p, struct netif *inp); +#endif /* LWIP_API_RICH */ + +#if LWIP_NETIFAPI_IF_NUM +err_t netif_change_if_num(struct netif *netif, u8_t num); +#endif + +#if LWIP_IPV6 +/** @ingroup netif_ip6 */ +#define netif_ip_addr6(netif, i) ((const ip_addr_t*)(&((netif)->ip6_addr[i]))) +/** @ingroup netif_ip6 @endcond */ +#define netif_ip6_addr(netif, i) ((const ip6_addr_t*)ip_2_ip6(&((netif)->ip6_addr[i]))) +#if LWIP_API_RICH +void netif_ip6_addr_set(struct netif *netif, s8_t addr_idx, const ip6_addr_t *addr6); +#endif /* LWIP_API_RICH */ + +#if LWIP_NETIFAPI_IP6_ADDR +err_t netif_do_add_ipv6_addr(struct netif *netif, void *arguments); +#endif /* LWIP_NETIFAPI_IP6_ADDR */ +#if LWIP_NETIFAPI_IP6_ADDR || LWIP_ENABLE_BASIC_SHELL_CMD +err_t netif_do_rmv_ipv6_addr(struct netif *netif, void *arguments); +#endif /* LWIP_NETIFAPI_IP6_ADDR || LWIP_ENABLE_BASIC_SHELL_CMD */ +#if LWIP_API_RICH || LWIP_IPV6_DHCP6 +void netif_ip6_addr_set_parts(struct netif *netif, s8_t addr_idx, u32_t i0, u32_t i1, u32_t i2, u32_t i3); +#endif /* LWIP_API_RICH || LWIP_IPV6_DHCP6 */ +#define netif_ip6_addr_state(netif, i) ((netif)->ip6_addr_state[i]) +void netif_ip6_addr_set_state(struct netif *netif, s8_t addr_idx, u8_t state); +s8_t netif_get_ip6_addr_match(struct netif *netif, const ip6_addr_t *ip6addr); +err_t netif_create_ip6_linklocal_address(struct netif *netif, u8_t from_mac_48bit); +err_t netif_create_ip6_linklocal_address_from_mac(const linklayer_addr_t *mac, ip6_addr_t *ip6addr); + +#if LWIP_API_RICH +err_t netif_get_ip6_linklocal_address(struct netif *netif, ip6_addr_t *addr); +#endif /* LWIP_API_RICH */ +#if LWIP_RIPPLE || LWIP_NETIFAPI_IP6_ADDR || LWIP_ENABLE_BASIC_SHELL_CMD +err_t netif_add_ip6_address(struct netif *netif, const ip6_addr_t *ip6addr, s8_t *chosen_idx); +#endif + +#if LWIP_NETIFAPI_IP6_ADDR || LWIP_ENABLE_BASIC_SHELL_CMD +void netif_ip6_addr_setinvalid(struct netif *netif, const ip6_addr_t *addr6); +#endif + +#if defined(LWIP_RA_PREFIX_DYNAMIC) && LWIP_RA_PREFIX_DYNAMIC +void netif_create_ip6_address_80bit_prefix(struct netif *netif, const ip6_addr_t *prefix, ip6_addr_t *ip6addr); +#endif /* defined(LWIP_RA_PREFIX_DYNAMIC) && LWIP_RA_PREFIX_DYNAMIC */ +struct netif *netif_find_by_ip6addr(const ip6_addr_t *ip6addr); + +#if LWIP_IPV6_AUTOCONFIG +void netif_set_ip6_autoconfig_enabled(struct netif *netif); +void netif_set_ip6_autoconfig_disabled(struct netif *netif); +#endif /* LWIP_IPV6_AUTOCONFIG */ + +#if LWIP_IPV6_ADDRESS_LIFETIMES +#define netif_ip6_addr_valid_life(netif, i) \ + (((netif) != NULL) ? ((netif)->ip6_addr_valid_life[i]) : IP6_ADDR_LIFE_STATIC) +#define netif_ip6_addr_set_valid_life(netif, i, secs) \ + do { if (netif != NULL) { (netif)->ip6_addr_valid_life[i] = (secs); }} while (0) +#define netif_ip6_addr_pref_life(netif, i) \ + (((netif) != NULL) ? ((netif)->ip6_addr_pref_life[i]) : IP6_ADDR_LIFE_STATIC) +#define netif_ip6_addr_set_pref_life(netif, i, secs) \ + do { if (netif != NULL) { (netif)->ip6_addr_pref_life[i] = (secs); }} while (0) +#define netif_ip6_addr_isstatic(netif, i) \ + (netif_ip6_addr_valid_life((netif), (i)) == IP6_ADDR_LIFE_STATIC) +#else /* !LWIP_IPV6_ADDRESS_LIFETIMES */ +#define netif_ip6_addr_isstatic(netif, i) (1) /* all addresses are static */ +#endif /* !LWIP_IPV6_ADDRESS_LIFETIMES */ + + +#if LWIP_ND6_ALLOW_RA_UPDATES +#define netif_mtu6(netif) ((netif)->mtu6) +#else /* LWIP_ND6_ALLOW_RA_UPDATES */ +#define netif_mtu6(netif) ((netif)->mtu) +#endif /* LWIP_ND6_ALLOW_RA_UPDATES */ +#endif /* LWIP_IPV6 */ + +#if LWIP_NETIF_HWADDRHINT +#define NETIF_SET_HINTS(netif, netifhint) (netif)->hints = (netifhint) +#define NETIF_RESET_HINTS(netif) (netif)->hints = NULL +#else /* LWIP_NETIF_HWADDRHINT */ +#define NETIF_SET_HINTS(netif, netifhint) +#define NETIF_RESET_HINTS(netif) +#endif /* LWIP_NETIF_HWADDRHINT */ + +/* To identify as invalid index */ +#define LWIP_INVALID_IPV6_IDX 255 + +#if LWIP_NETIFAPI_IF_INDEX +/* @ingroup netif */ +u8_t netif_name_to_index(const char *name); +char *netif_index_to_name(u8_t uIndex, char *name); +err_t netif_get_nameindex_all(struct if_nameindex **p_if_list); +#endif /* LWIP_NETIFAPI_IF_INDEX */ + +err_t lwip_pkt_transmission_status_callback +( + struct netif *linkIface, + struct linklayer_addr *sendermac, + s32_t trStatus, + u32_t trcount +); + +/* Interface indexes always start at 1 per RFC 3493, section 4, num starts at 0 .. 8 for padding */ +#define IF_NAMEINDEX_ELE_SIZE (sizeof(struct if_nameindex) + IFNAMSIZ + 4) + +/* The interface index 0 is an invalid index */ +struct netif *netif_get_by_index(u8_t idx); + +#if LWIP_API_RICH +/* Send NA/IGMP/MLD/RS events, e.g. on addr-change */ +void netif_ip6_issue_reports(struct netif *netif); +#endif /* LWIP_API_RICH */ + +#if LWIP_RIPPLE +u8_t netif_count(void); +#endif /* LWIP_RIPPLE */ + +#if LWIP_API_MESH +/* + * Linklayer Event Indication handler + */ +struct linklayer_event_info { + u8_t type; + union { +#if LWIP_RPL || LWIP_RIPPLE + linklayer_event_tx_info_t tx_info; + linklayer_event_new_peer_t new_peer; + linklayer_event_del_peer_t del_peer; +#endif /* LWIP_RPL || LWIP_RIPPLE */ + linklayer_event_ap_conn_t ap_conn; + linklayer_event_sta_conn_t sta_conn; + } info; +}; + +err_t netif_linklayer_event_callback(struct netif *netif, u8_t evt_type, void *evt_info); +#if LWIP_RPL || LWIP_RIPPLE + +/** + * Function prototype for linklayer event handler. Called by + * netif_linklayer_event_callback() + * + * @param netif The netif on which event has occurred + * @param evt The event received from linklayer + */ +err_t netif_linklayer_event_handler(struct netif *netif, + const struct linklayer_event_info *evt); + +#ifndef NETIF_BEACON_PRIORITY_MAX +#define NETIF_BEACON_PRIORITY_MAX 254 +#endif + +err_t netif_remove_peer(struct netif *netif, struct linklayer_addr *peeraddr); +err_t netif_set_beacon_prio(struct netif *netif, u8_t prio); +err_t netif_set_unique_id(struct netif *netif, uniqid_t id); +err_t netif_get_peer_count(struct netif *netif, u16_t *count); +err_t netif_set_rank(struct netif *netif, u16_t rank); +#endif /* LWIP_RPL || LWIP_RIPPLE */ +#endif /* LWIP_API_MESH */ + +#if LWIP_NETIF_EXT_STATUS_CALLBACK +/** + * @ingroup netif + * Extended netif status callback (NSC) reasons flags. + * May be extended in the future! + */ +typedef u16_t netif_nsc_reason_t; + +/* used for initialization only */ +#define LWIP_NSC_NONE 0x0000 +/** netif was added. arg: NULL. Called AFTER netif was added. */ +#define LWIP_NSC_NETIF_ADDED 0x0001 +/** netif was removed. arg: NULL. Called BEFORE netif is removed. */ +#define LWIP_NSC_NETIF_REMOVED 0x0002 +/** link changed */ +#define LWIP_NSC_LINK_CHANGED 0x0004 +/** netif administrative status changed.\n + * up is called AFTER netif is set up.\n + * down is called BEFORE the netif is actually set down. */ +#define LWIP_NSC_STATUS_CHANGED 0x0008 +/** IPv4 address has changed */ +#define LWIP_NSC_IPV4_ADDRESS_CHANGED 0x0010 +/** IPv4 gateway has changed */ +#define LWIP_NSC_IPV4_GATEWAY_CHANGED 0x0020 +/** IPv4 netmask has changed */ +#define LWIP_NSC_IPV4_NETMASK_CHANGED 0x0040 +/** called AFTER IPv4 address/gateway/netmask changes have been applied */ +#define LWIP_NSC_IPV4_SETTINGS_CHANGED 0x0080 +/** IPv6 address was added */ +#define LWIP_NSC_IPV6_SET 0x0100 +/** IPv6 address state has changed */ +#define LWIP_NSC_IPV6_ADDR_STATE_CHANGED 0x0200 + +/** @ingroup netif + * Argument supplied to netif_ext_callback_fn. + */ +typedef union { + /** Args to LWIP_NSC_LINK_CHANGED callback */ + struct link_changed_s { + /** 1: up; 0: down */ + u8_t state; + } link_changed; + /** Args to LWIP_NSC_STATUS_CHANGED callback */ + struct status_changed_s { + /** 1: up; 0: down */ + u8_t state; + } status_changed; + /** Args to LWIP_NSC_IPV4_ADDRESS_CHANGED, LWIP_NSC_IPV4_GATEWAY_CHANGED, + * LWIP_NSC_IPV4_NETMASK_CHANGED and LWIP_NSC_IPV4_SETTINGS_CHANGED callback + */ + struct ipv4_changed_s { + /** Old IPv4 address */ + const ip_addr_t *old_address; + const ip_addr_t *old_netmask; + const ip_addr_t *old_gw; + } ipv4_changed; + /** Args to LWIP_NSC_IPV6_SET callback */ + struct ipv6_set_s { + /** Index of changed IPv6 address */ + s8_t addr_index; + /** Old IPv6 address */ + const ip_addr_t *old_address; + } ipv6_set; + /** Args to LWIP_NSC_IPV6_ADDR_STATE_CHANGED callback */ + struct ipv6_addr_state_changed_s { + /** Index of affected IPv6 address */ + s8_t addr_index; + /** Old IPv6 address state */ + u8_t old_state; + /** Affected IPv6 address */ + const ip_addr_t *address; + } ipv6_addr_state_changed; +} netif_ext_callback_args_t; + +/** + * @ingroup netif + * Function used for extended netif status callbacks + * Note: When parsing reason argument, keep in mind that more reasons may be added in the future! + * @param netif netif that is affected by change + * @param reason change reason + * @param args depends on reason, see reason description + */ +typedef void (*netif_ext_callback_fn)(struct netif *netif, netif_nsc_reason_t reason, + const netif_ext_callback_args_t *args); + +struct netif_ext_callback; +typedef struct netif_ext_callback { + netif_ext_callback_fn callback_fn; + struct netif_ext_callback *next; +} netif_ext_callback_t; + +#define NETIF_DECLARE_EXT_CALLBACK(name) static netif_ext_callback_t name; +void netif_add_ext_callback(netif_ext_callback_t *callback, netif_ext_callback_fn fn); +void netif_remove_ext_callback(netif_ext_callback_t *callback); +void netif_invoke_ext_callback(struct netif *netif, netif_nsc_reason_t reason, const netif_ext_callback_args_t *args); +#else +#define NETIF_DECLARE_EXT_CALLBACK(name) +#define netif_add_ext_callback(callback, fn) +#define netif_remove_ext_callback(callback) +#define netif_invoke_ext_callback(netif, reason, args) +#endif + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#define NETIF_MTU_MIN 1280 +#endif /* LWIP_HDR_NETIF_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/netifapi.h b/sdk_liteos/third_party/lwip_sack/include/lwip/netifapi.h new file mode 100644 index 0000000000000000000000000000000000000000..09dc45f10e0473f2e5a9602d6a5edab6e25997ed --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/netifapi.h @@ -0,0 +1,1742 @@ +/** + * @file + * netif API (to be used from non-TCPIP threads) + */ +/* + * Copyright (c) <2013-2016>, + * All rights reserved. + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + */ + +#ifndef LWIP_HDR_NETIFAPI_H +#define LWIP_HDR_NETIFAPI_H + +#include "lwip/opt.h" + +#if LWIP_NETIF_API /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/sys.h" +#include "lwip/netif.h" +#include "lwip/dhcp.h" +#if LWIP_IPV6_DHCP6 +#include "lwip/dhcp6.h" +#endif /* LWIP_IPV6_DHCP6 */ +#include "lwip/autoip.h" +#include "lwip/priv/tcpip_priv.h" +#include "lwip/prot/ethernet.h" + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +#if LWIP_MPU_COMPATIBLE +#define NETIFAPI_IPADDR_DEF(type, m) type m +#else /* LWIP_MPU_COMPATIBLE */ +#define NETIFAPI_IPADDR_DEF(type, m) const type * m +#endif /* LWIP_MPU_COMPATIBLE */ + +typedef void (*netifapi_void_fn)(struct netif *netif); +typedef err_t (*netifapi_arg_fn)(struct netif *netif, void *arg); + +typedef err_t (*netifapi_errt_fn)(struct netif *netif); + +#if LWIP_IPV6 && LWIP_NETIF_NBR_CACHE_API +struct ipv6_neighbor { + struct ip6_addr nbripaddr; + u32_t reachabletime; + u8_t hwaddr[NETIF_MAX_HWADDR_LEN]; + u8_t hwlen; + u8_t curstate; +}; +#endif + +typedef struct name_for_netif { + struct netif *p_netif; + char name[IFNAMSIZ]; +} name_for_netif_t; + +struct netifapi_msg { + struct tcpip_api_call_data call; + struct netif *netif; +#if LWIP_MAC_SECURITY + u8_t authstatus; +#endif + union { + struct { + struct netif *main_netif; +#if LWIP_IPV4 + NETIFAPI_IPADDR_DEF(ip4_addr_t, ipaddr); + NETIFAPI_IPADDR_DEF(ip4_addr_t, netmask); + NETIFAPI_IPADDR_DEF(ip4_addr_t, gw); +#endif /* LWIP_IPV4 */ + void *state; + netif_init_fn init; + netif_input_fn input; + } add; + struct { + netifapi_void_fn voidfunc; + netifapi_errt_fn errtfunc; + } common; +#if LWIP_NETIFAPI_GET_ADDR + struct { + struct netif *main_netif; +#if LWIP_IPV4 + ip4_addr_t *ipaddr; + ip4_addr_t *netmask; + ip4_addr_t *gw; +#endif /* LWIP_IPV4 */ + void *state; + netif_init_fn init; + netif_input_fn input; + } add_get; +#endif + struct { + netifapi_arg_fn argfunc; + void *arg; + } arg_cb; +#if LWIP_DHCP + struct { + struct dhcp *dhcp; + } dhcp_struct; +#endif +#if LWIP_DHCPS + struct { + char *start_ip; + u16_t ip_num; + } dhcp_start_params; +#if LWIP_NETIFAPI_DHCPS_IP + struct { + u8_t *mac; + u8_t maclen; + ip_addr_t *ip; + } dhcp_get_ip_params; +#endif +#endif +#if LWIP_NETIFAPI_LINK_CALLBACK + struct { + netif_status_callback_fn link_callback; + } netif_link_cb; +#endif +#if LWIP_NETIF_EXT_STATUS_CALLBACK + struct { + netif_ext_callback_t *cb; + netif_ext_callback_fn fn; + } netif_ext_cb; +#endif +#if LWIP_NETIFAPI_MTU + struct { + u16_t mtu; + } netif_mtu; +#endif + struct { + u8_t num; + } netif_num; +#if LWIP_NETIF_HOSTNAME + struct { + char *name; + u8_t namelen; + } hostname; +#endif /* LWIP_NETIF_HOSTNAME */ +#if LWIP_NETIFAPI_IF_INDEX + struct { +#if LWIP_MPU_COMPATIBLE + char name[IF_NAMESIZE]; +#else /* LWIP_MPU_COMPATIBLE */ + char *name; +#endif /* LWIP_MPU_COMPATIBLE */ + u8_t index; + } ifs; + struct if_nameindex *p_if_list; +#endif +#if LWIP_DHCP_VENDOR_CLASS_IDENTIFIER + struct { + char *vci; + u8_t *vci_len; + } vci; +#endif /* LWIP_DHCP_VENDOR_CLASS_IDENTIFIER */ +#if LWIP_IP_FILTER | LWIP_IPV6_FILTER + struct { + ip_filter_fn filter_fn; + int type; + } ip_filter; +#endif /* LWIP_IP_FILTER | LWIP_IP_FILTER */ + +#if LWIP_IPV6 && (LWIP_NETIF_NBR_CACHE_API || LWIP_ND6_STATIC_DEFAULT_ROUTE) + struct { + struct ipv6_neighbor *nbrinfo; + struct ip6_addr *nodeip; + } ipv6_tables_access_params; +#endif +#if LWIP_IPV6 && LWIP_6LOWPAN + struct { + struct ip6_addr *ctxprefix; + u8_t index; + } lowpanctx; +#endif +#if LWIP_IPV6 + struct { + u8_t state; + } ip6_state; +#endif +#if LWIP_IPV6 && LWIP_ND6_STATIC_PREFIX + struct { + struct ip6_addr *prefix; + u8_t auto_config_flags; + } prefix_params; +#endif +#if LWIP_ENABLE_ROUTER || LWIP_API_MESH + struct { + const struct linklayer_event_info *evt; + } linklayer_event; +#endif +#if LWIP_NETIFAPI_IF_HW + struct { + u8_t *hw_addr; + s32_t hw_len; + } hw; +#endif +#if LWIP_LOWPOWER + struct { + enum lowpower_mod mod; + } lp; +#endif +#if LWIP_IPV4 && LWIP_ARP + struct { + ip4_addr_t *ip; + u8_t *mac; + u8_t *maclen; + } arp; +#endif + } msg; +}; + +/* User can add neighbors with below states */ +#define ND6_STATE_REACHABLE 2 +#if LWIP_ND6_STATIC_NBR +#define ND6_STATE_PERMANENT 6 +#endif + +#define AUTHENTICATION_SUCCESS 1 +#define AUTHENTICATION_FAILURE 0 + +#if LWIP_ARP && LWIP_IPV4 +/* Used for netfiapi_arp_* APIs */ +enum netifapi_arp_entry { + NETIFAPI_ARP_PERM /* Permanent entry */ + /* Other entry types can be added here */ +}; + +/** @ingroup netifapi_arp */ +err_t netifapi_arp_add(const ip4_addr_t *ipaddr, struct eth_addr *ethaddr, enum netifapi_arp_entry type); +/** @ingroup netifapi_arp */ +err_t netifapi_arp_remove(const ip4_addr_t *ipaddr, enum netifapi_arp_entry type); +#endif /* LWIP_ARP && LWIP_IPV4 */ + +/** + * @cond liteosnetif + * @defgroup Threadsafe_Network_Interfaces Network Interfaces + * This section contains the Thread safe Network related interfaces. + */ +/** + * @defgroup Threadsafe_DHCP_Interfaces DHCP Interfaces + * This section contains the Thread safe DHCP interfaces. + */ +/** + * @ingroup Threadsafe_Network_Interfaces + * @brief + * This is a thread safe API, used to add a network interface to the list of lwIP netifs. It is recommended + * to use this API instead of netif_add(). + * + * @param[in] netif Indicates the pre-allocated netif structure. + * @param[in] ipaddr Indicates the IP_add for the new netif. + * @param[in] netmask Indicates the network mask for the new netif. + * @param[in] gw Indicates the default gateway IP_add for the new netif. + * + * @returns + * 0 : On success. \n + * Negative value : On failure. + * + * struct netif is a shared data structure across driver and lwIP. So, Following paramters MUST be initialized by driver + * when netifapi_netif_add is called: + * 1, state, maybe private handler only used by driver, not accessed by lwip protocol, MUST be initialized by driver. + * 2, drv_send, used to do packet transmission, driver MUST initialized it with NON NULL value. + * 3, drv_config, used to configure promisic mode, driver MUST initialized it with NON NULL value. + * 4, drv_set_hwaddr, used to set hardware address, MUST be initialized by driver. NULL is also a valid value. + * 5, ethtool_ops, used to configure phy mode(10/100M, duplex), can be NULL if phy mode change not supported by driver. + * 6, link_layer_type, MUST be ETHERNET_DRIVER_IF or WIFI_DRIVER_IF. + * 7, hwaddr, hardware address. + * 8, hwaddr_len, hardware address length. + * + * @note + * For IPv4 stack, if NULL is passed to ipaddr/netmask/gw then 0.0.0.0 will be set as the corresponding address on + * the netif. \n + * For IPv6: Don't forget to call netif_create_ip6_linklocal_address() after setting the MAC address + * in struct netif.hwaddr (IPv6 requires a link-local address). + * + * @par Related Topics + * netif_add() + */ +err_t netifapi_netif_add(struct netif *netif +#if LWIP_IPV4 + , const ip4_addr_t *ipaddr, const ip4_addr_t *netmask, const ip4_addr_t *gw +#endif /* LWIP_IPV4 */ + ); + +/* + * Func Name: netifapi_netif_remove + */ +/** + * @ingroup Threadsafe_Network_Interfaces + * @brief + * This API is used to remove a network interface from the list of lwIP netifs + * in a thread-safe manner. + * The Ethernet driver calls this API in a thread-safe manner to remove a network + * interface from the list of lwIP netifs. + * + * @param[in] netif Indicates the network interface to be removed. + * + * @returns + * ERR_OK: On success. \n + * ERR_VAL: On failure due to illegal value. \n + * ERR_ARG: On passing invalid arguments. + * + * @note + - Any data sent by the application will return success, + but the data will not be sent if only netifapi_netif_remove() API is called and not the sockets. + - The adaptor must close all the connections on socket before netifapi_netif_remove() + API is called, as netifapi_netif_remove() does not close established connections. + */ +err_t netifapi_netif_remove(struct netif *netif); + +#if LWIP_NETIFAPI_IF_HW +/* + * Func Name: netifapi_netif_set_hwaddr + */ +/** + * @ingroup Threadsafe_Network_Interfaces + * @brief + * This API is used to change the hardware address for a network interface + * in a thread-safe manner. + * + * @param[in] netif Indicates the network interface to change the hardware address. + * @param[in] hw_addr Indicates the new hardware address. + * @param[in] hw_len Indicates the length of new hardware address. + * + * @returns + * ERR_OK: On success. \n + * ERR_IF: On failure due to netif driver error. \n + * ERR_ARG: On passing invalid arguments. + * + * @note + - This API will try to call netif registed function drv_set_hwaddr() if this function is registed. + If this API returns ERR_IF, this means that some error occur while carrying out function drv_set_hwaddr(). + */ +err_t netifapi_netif_set_hwaddr(struct netif *netif, u8_t *hw_addr, s32_t hw_len); + +/* + * Func Name: netifapi_netif_get_hwaddr + */ +/** + * @ingroup Threadsafe_Network_Interfaces + * @brief + * This API is used to get the hardware address for a network interface + * in a thread-safe manner. + * + * @param[in] netif Indicates the network interface to get the hardware address. + * @param[out] hw_addr Indicates the buffer to record hardware address. + * @param[in] hw_len Indicates the length of hw_addr. + * + * @note + - hw_len MUST be equal to NETIF_MAX_HWADDR_LEN. + */ +void netifapi_netif_get_hwaddr(struct netif *netif, u8_t *hw_addr, s32_t hw_len); +#endif /* LWIP_NETIFAPI_IF_HW */ + +#if LWIP_IPV4 + +/* + * Func Name: netifapi_netif_set_addr + */ +/** + * @ingroup Threadsafe_Network_Interfaces + * This is a thread safe API, used to change IP_add configuration for a + * network interface (including netmask and default gateway). + * It is recommended to use this API instead of netif_set_addr(). + * @param[in] netif Indicates the network interface to change. + * @param[in] ipaddr Indicates the new IP address. + * @param[in] netmask Indicates the new network mask. + * @param[in] gw Indicates the new default gateway IP address. + * @returns + * 0 : On success. \n + * Negative value : On failure. + * + * @par Related Topics + * netif_set_addr() + * + * @note + * - If NULL is passed to ipaddr/netmask/gw, then 0.0.0.0 will be set as the corresponding address on the netif + */ +err_t netifapi_netif_set_addr(struct netif *netif, + const ip4_addr_t *ipaddr, + const ip4_addr_t *netmask, + const ip4_addr_t *gw); + +#if LWIP_NETIFAPI_GET_ADDR +/* + * Func Name: netifapi_netif_get_addr + */ +/** + * @ingroup Threadsafe_Network_Interfaces + * + * @brief + * + * This is a thread safe API, used to get IP_add configuration for a network interface + * (including netmask and default gateway). + * It is recommended to use this API instead of netif_get_addr() + * + * @param[in] netif Indicates the network interface to get. + * @param[in] ipaddr Indicates the IP address. + * @param[in] netmask Indicates the network mask. + * @param[in] gw Indicates the default gateway IP address. + * + * @returns + * 0 : On success \n + * Negative value : On failure \n + * + * @par Related Topics + * netif_get_addr() + * + * @note + * - netmask and/or gw can be passed NULL, if these details about the netif are not needed + */ +err_t netifapi_netif_get_addr(struct netif *netif, + ip4_addr_t *ipaddr, + ip4_addr_t *netmask, + ip4_addr_t *gw); +#endif /* LWIP_NETIFAPI_GET_ADDR */ +#endif /* LWIP_IPV4 */ +/** + * @ingroup Threadsafe_Network_Interfaces + * @brief + * This API is used to call all netif related APIs in a thread safe manner. The netif related APIs must be + * of prototype to receive only struct netif* as argument and return type can of type err_t or void. You + * must pass either viodfunc or errtfunc. + * + * @param[in] netif Indicates the network interface to be passed as argument. + * @param[in] voidfunc Callback with return type of void, will be called if errtfunc is NULL. + * @param[in] errtfunc Callback with return type of err_t. + * + * @returns + * 0 : On success. \n + * Negative value : On failure. + * + * @note + * The prototype for netifapi_void_fn and netifapi_errt_fn are as follows:\n + * typedef void (*netifapi_void_fn)(struct netif *netif); \n + * typedef err_t (*netifapi_errt_fn)(struct netif *netif); \n + */ +err_t netifapi_netif_common(struct netif *netif, netifapi_void_fn voidfunc, + netifapi_errt_fn errtfunc); + +#if LWIP_NETIFAPI_IP6_ADDR +/** + * @ingroup Threadsafe_Network_Interfaces + * @brief + * This function allows for the easy addition of a new IPv6 address to an interface. + * It takes care of finding an empty slot and then sets the address tentative + * (to make sure that all the subsequent processing happens). + * + * @param[in] netif Indicates the netif to add the address on. + * @param[in] ip6addr Indicates the address to add. + */ +err_t +netifapi_netif_add_ip6_address(struct netif *netif, ip_addr_t *ipaddr); + +/** + * @ingroup Threadsafe_Network_Interfaces + * @brief + * This function allows for the easy removal of an existing IPv6 address from an interface. + * + * + * @param[in] netif Indicates the netif to remove the address from. + * @param[in] ip6addr Indicates the address to remove. + * @note + * - This interface may force any blocking accept() to return failure with errno ECONNABORTED. + */ +#endif /* LWIP_NETIFAPI_IP6_ADDR */ + +#if LWIP_NETIFAPI_IP6_ADDR || LWIP_ENABLE_BASIC_SHELL_CMD +void +netifapi_netif_rmv_ip6_address(struct netif *netif, ip_addr_t *ipaddr); +#endif + +#if LWIP_IPV6_MLD && LWIP_NETIFAPI_MLD6 +/** + * @ingroup Threadsafe_Network_Interfaces + * @brief + * This function allows to join a group without sending out MLD6 Report message. + * This function is not RFC 2710 compliant and is a custom function + * + * + * @param[in] netif Indicates the netif which want to join a group. + * @param[in] ip6addr Indicates the group address. + */ +err_t +netifapi_netif_join_ip6_multicastgroup(struct netif *netif, ip6_addr_t *ip6addr); +#endif + + +/* + * @ingroup Threadsafe_Network_Interfaces + * This function allows for the easy addition of a new IPv6 link local address to an interface. + * It uses slot fixed for link local address and then sets the address tentative + * (to make sure that all the subsequent processing happens). + * This Interface MUST be called to configure link local IP address, after addition of netif. + * + * @param netif netif to add the address on + * @param ip6addr address to add + * @param from_mac_48bit specifies whether mac address is 48 bit for 64 bit format */ +err_t +netifapi_netif_add_ip6_linklocal_address(struct netif *netif, u8_t from_mac_48bit); + +#if LWIP_IPV6_AUTOCONFIG +/** + * @ingroup Threadsafe_Network_Interfaces + * @brief + * This function is used to enable autoconfig for IPv6 address in a thread-safe way. + * That is, the indicated network interface will send out an RS packet immediately to obtain RA. + * + * @param[in] netif Indicates the lwIP network interface. + * + * @note + * + * For netifapi_set_ip6_autoconfig_enabled(): + * - It enables stateless autoconfiguration. + * - It requires the router/default-gateway to understand and implement RFC-4862, but requires no DHCPv6 server. + * - No server keeps track of what has or hasn't been assigned, and no server approves the use of the address, + * or pass it out. + * - Once called: send out an RS packet immediately to obtain RA. + * - When receiving an RA, lwIP can generate an IPv6 address (DAD first) and update routing information. + * + * For netifapi_dhcp6_enable_stateful(): + * - It enables stateful DHCPv6 client autoconfiguration (stateless disabled). + * - It requires the DHCPv6 server(s) to provide addressing and service information. + * - The DHCP server and the client both maintain state information to keep addresses from conflicting, + * to handle leases, and to renew addresses over time. + * - Once called: disable autoconfig for IPv6 address (clean autoconfig generated addresses), + * and start DHCPv6 procedure to create a stateful DHCPv6 client (if no stateful DHCPv6 client). + * + * For netifapi_dhcp6_enable_stateless(): + * - It is used to get "Other configuration" in RFC-4861. + * - It requires the DHCPv6 server(s) to provide service information (like DNS servers and NTP servers), + * but no addressing information. + * - Once called: no effect to current IPv6 addresses, + * and start DHCPv6 procedure to create a stateless DHCPv6 client (if no DHCPv6 client). + * + * @par Related Topics + * netifapi_dhcp6_enable_stateful() + * netifapi_dhcp6_enable_stateless() + */ +err_t +netifapi_set_ip6_autoconfig_enabled(struct netif *netif); + +/** + * @ingroup Threadsafe_Network_Interfaces + * @brief + * This function is used to disable autoconfig for IPv6 address in a thread-safe way. + * That is, autoconfig generated addresses on the indicated network interface will be invalid. + * + * @param[in] netif Indicates the lwIP network interface. + * + * @note + * For now, since only prefixes have the autoconfig generated flag, while IPv6 addresses don't have, + * lwIP can only invalid addresses by prefixes rather than addresses. So, when a network interface has + * a manually configured IPv6 address, and an autoconfig generated IPv6 address which have the same + * prefix, calling netifapi_set_ip6_autoconfig_disabled() will invalid both addresses. + * + * @par Related Topics + * netifapi_dhcp6_disable() + * netifapi_dhcp6_release_stateful() + */ +err_t +netifapi_set_ip6_autoconfig_disabled(struct netif *netif); +#endif /* LWIP_IPV6_AUTOCONFIG */ + +/* + * @ingroup Threadsafe_Network_Interfaces + * @brief + * Call the "argfunc" with argument arg in a thread-safe way by running that function inside the tcpip_thread context. + * @note Use this function only for functions where there is only "netif" parameter. + */ +err_t +netifapi_netif_call_argcb(struct netif *netif, netifapi_arg_fn argfunc, void *arg); + +/* + * @ingroup Threadsafe_Network_Interfaces + * @brief + * Call the "argfunc" with argument arg in a thread-safe way by running that function inside the tcpip_thread context. + */ +err_t +netifapi_call_argcb(netifapi_arg_fn argfunc, void *arg); + +/** +* @ingroup Threadsafe_Network_Interfaces +* @brief +* This interface is used to bring an interface up in a thread-safe way. +* That is, the interface is available for processing traffic. +* +* @param[in] n Indicates the network interface. +* +* @note +* Enabling DHCP on a down interface will make it come up once configured. +* +* @par Related Topics +* netifapi_dhcp_start() +*/ +err_t netifapi_netif_set_up(struct netif *netif); + +/** +* @ingroup Threadsafe_Network_Interfaces +* @brief +* This interface is used to bring an interface down in a thread-safe way. +* That is, the interface disables any traffic processing. +* +* @param[in] n Indicates the network interface. +* +* @note +* Enabling DHCP on a down interface will make it come up once configured. +* +* @par Related Topics +* netifapi_dhcp_start() +*/ +err_t netifapi_netif_set_down(struct netif *netif); + +/* +Func Name: netifapi_netif_set_default +*/ +/** +* @ingroup Threadsafe_Network_Interfaces +* +* @param[in] netif Indicates the network interface to be set as default. +* +* @brief +* This interface is used to set a network interface as the default network interface. +* It is used to output all packets for which no specific route is found. +*/ +err_t netifapi_netif_set_default(struct netif *netif); + +#if LWIP_NETIFAPI_IF_GET_DEFAULT +/* +Func Name: netifapi_netif_get_default +*/ +/** +* @ingroup Threadsafe_Network_Interfaces + +* @brief +* This API is used to get the default network interface. +* It is used to output all packets for which no specific route is found. +* +* @return +* NULL: if either the default netif was NOT exist or the default netif was down \n +* Others: the default netif \n +*/ +struct netif *netifapi_netif_get_default(void); +#endif + +/** +* @ingroup Threadsafe_Network_Interfaces +* @brief +* This thread-safe interface is called when to find interface +*/ +struct netif *netifapi_netif_find(const char *name); + +/** +* @ingroup Threadsafe_Network_Interfaces +* @brief +* This thread-safe interface is called by the driver when its link goes up. +*/ +err_t netifapi_netif_set_link_up(struct netif *netif); + +/** +* @ingroup Threadsafe_Network_Interfaces +* @brief +* This thread-safe interface is called by the driver when its link goes down. +*/ +err_t netifapi_netif_set_link_down(struct netif *netif); + +/* + * @defgroup netifapi_dhcp4 DHCPv4 + * @ingroup netifapi + * To be called from non-TCPIP threads + */ +#if LWIP_DHCP +/** @ingroup Threadsafe_DHCP_Interfaces +* @brief +* This interface is used to start DHCP negotiation for a network interface. If no DHCP client instance +* is attached to this interface, a new client is created first. If a DHCP client instance is already +* present, it restarts negotiation. It is the thread-safe way for calling dhcp_start in the user space. +* */ +err_t netifapi_dhcp_start(struct netif *netif); + +/** @ingroup Threadsafe_DHCP_Interfaces +* @brief +* This interface is used to remove the DHCP client from the interface. It stops DHCP configuration. +* It is the thread-safe way for calling dhcp_stop in the user space. */ +err_t netifapi_dhcp_stop(struct netif *netif); + +/** @ingroup Threadsafe_DHCP_Interfaces +* @brief +* This interface is used to make the DHCP client inform the DHCP server regarding its manual(static) IP configuration. +* This is done by sending a DHCP_INFORM message from the client to the server. +* It is the thread-safe way for calling dhcp_inform in the user space. */ +err_t netifapi_dhcp_inform(struct netif *netif); + +/** @ingroup Threadsafe_DHCP_Interfaces +* @brief +* This interface is used to make the DHCP client running on the interface to renew its existing IP configuration to the +* DHCP server from whom it has leased the IP Configuration. +* This is done by sending a DHCP_REQUEST message from the client to the server after T1-Timer Expiry. +* It is the thread-safe way for calling dhcp_renew in the user space. */ +err_t netifapi_dhcp_renew(struct netif *netif); + + +/** @ingroup Threadsafe_DHCP_Interfaces +* @brief +* This interface is used to release the IP Configuration on a network interface that it has leased from the DHCP Server +* and informs the DHCP server that this IP Configuration is no longer needed by the client. +* This is done by sending a DHCP_RELEASE message from the client to the server. +* It is the thread-safe way for calling dhcp_release in the user space. */ +err_t netifapi_dhcp_release(struct netif *netif); + +/** +* @ingroup Threadsafe_DHCP_Interfaces +* @brief +* This interface is used to free the memory allocated for DHCP during DHCP start. +* It is the thread-safe way for calling dhcp_cleanup in the user space. +* +*/ +err_t netifapi_dhcp_cleanup(struct netif *netif); + +/** @ingroup Threadsafe_DHCP_Interfaces +* @brief +* This interface is used to get the DHCP negotiation status for a network interface. +* It is the thread-safe way for calling dhcp_is_bound() in the user space. +*/ +err_t netifapi_dhcp_is_bound(struct netif *netif); + +#if LWIP_API_RICH +/** @ingroup Threadsafe_DHCP_Interfaces +* @brief +* This API is used to set a static DHCP structure to the netif. +* @note +* If this API is used before netifapi_dhcp_start(), the application needs to use +* netifapi_dhcp_remove_struct() instead of netifapi_dhcp_cleanup() to remove +* the struct dhcp. */ +err_t netifapi_dhcp_set_struct(struct netif *netif, struct dhcp *dhcp); + +/** @ingroup Threadsafe_DHCP_Interfaces +* @brief +* This interface is used to remove the static DHCP structure from netif, which was set +* using the netifapi_dhcp_set_struct() API. +* @note +* The application needs to use this API instead of netifapi_dhcp_cleanup() if the +* DHCP structure is previously set on netif using netifapi_dhcp_set_struct(). */ +err_t netifapi_dhcp_remove_struct(struct netif *netif); +#endif /* LWIP_API_RICH */ + +#if LWIP_DHCP_SUBSTITUTE +/** @ingroup Threadsafe_DHCP_Interfaces +* @brief +* This API is used to get MAC and IP of all the dhcp clients to the netif. +* +* @param[in] netif Indicates the netif structure on which DHCPC start. +* @param[out] clis_info To get the dhcp clients information. +* +* @returns +* ERR_OK : On success. \n +* Negative value : On failure. \n +* +* @note +* The clis_info got from this API must be freed by netifapi_dhcp_clients_info_free(). +* If the last got clis_info not freed, this API will fail with return value ERR_INPROGRESS. */ +err_t netifapi_dhcp_clients_info_get(struct netif *netif, struct dhcp_clients_info **clis_info); + +/** @ingroup Threadsafe_DHCP_Interfaces +* @brief +* This API is used to free clis_info to the netif. +* +* @param[in] netif Indicates the netif structure on which DHCPC start. +* @param[in] clis_info To clis_info got from netifapi_dhcp_clients_info_get(). +* +* @returns +* ERR_OK : On success. \n +* Negative value : On failure. \n +* +* @note +* The clis_info must be got from netifapi_dhcp_clients_info_get(). */ +err_t netifapi_dhcp_clients_info_free(struct netif *netif, struct dhcp_clients_info **clis_info); +#endif /* LWIP_DHCP_SUBSTITUTE */ +#endif /* LWIP_DHCP */ + +/** + * @defgroup Threadsafe_DHCPv6_Interfaces DHCPv6 Interfaces + * @ingroup Threadsafe_DHCP_Interfaces + * This section contains the Thread safe DHCPv6 interfaces. + * To be called from non-TCPIP threads + */ +#if LWIP_IPV6_DHCP6 +/* +Func Name: netifapi_dhcp6_enable_stateful +*/ +/** +* @ingroup Threadsafe_DHCPv6_Interfaces +* +* @brief +* This interface is used to enable stateful DHCPv6 client negotiation for a network interface (stateless disabled). +* If no DHCPv6 client instance is attached to this interface, a new client is created first. If a DHCPv6 client +* instance is already present and stateful DHCPv6 client has been enabled, it will return without doing anything. +* It is the thread-safe way for calling dhcp6_enable_stateful in the user space. +* +* @param[in] netif Indicates the lwIP network interface. +* +* @return +* ERR_OK: On success \n +* ERR_MEM: On failure due to memory \n +* ERR_VAL: On failure due to Illegal value or linklocal address is not preferred \n +* ERR_NOADDR: No available address + + +* @note +* \n +* - Only one addr of IA_NA is supported. Multiple addresses is not supported yet. +* - Not supported options : IA_TA/Relay/Authentication/Rapid Commit/User Class/Vendor Class/Vendor-specific +* Information/Interface-Id/Reconfigure Message/Reconfigure Accept/DOMAIN_LIST/IA_PD/IAPREFIX +* - First SOLICIT will not be sent until linklocal IPv6 address is REFERRED +* +* @par Related Topics +* netifapi_set_ip6_autoconfig_enabled() +* netifapi_dhcp6_release_stateful() +* netifapi_dhcp6_disable() +*/ +err_t netifapi_dhcp6_enable_stateful(struct netif *netif); + +/* +Func Name: netifapi_dhcp6_enable_stateless +*/ +/** +* @ingroup Threadsafe_DHCPv6_Interfaces + +* +* @brief +* This interface is used to enable stateless DHCPv6 client negotiation for a network interface (stateful disabled). +* If no DHCPv6 client instance is attached to this interface, a new client is created first. If a DHCPv6 client +* instance is already present and stateless DHCPv6 client has been enabled, it will return without doing anything. +* This interface only enables other config for DHCPv6. Autoconfig for IPv6 address will not be enabled by this +* interface. +* It is the thread-safe way for calling dhcp6_enable_stateless in the user space. +* +* @param[in] netif Indicates the lwIP network interface. +* +* @return +* ERR_OK: On success \n +* ERR_MEM: On failure due to memory \n +* ERR_VAL: On failure due to Illegal value + +* @note +* \n +* - Only RA from one Router will be handled correctly. RAs from multi Routers will cause unexpected problem. +* - Device will send INFORM-REQUEST after every receved RA. +* +* @par Related Topics +* netifapi_dhcp6_disable() +*/ +err_t netifapi_dhcp6_enable_stateless(struct netif *netif); + +/* +Func Name: netifapi_dhcp6_disable +*/ +/** +* @ingroup Threadsafe_DHCPv6_Interfaces +* +* @brief +* This interface is used to disable stateful or stateless DHCPv6 on a network interface. +* If no DHCPv6 client instance is attached to this interface, it will return without doing anything. +* If stateful DHCPv6 is enabled, it will try to send a RELEASE, but won't handle the REPLY of this RELEASE. +* It is the thread-safe way for calling dhcp6_disable in the user space. +* +* @param[in] netif Indicates the lwIP network interface. +* +* @return +* ERR_OK: On success \n +* ERR_VAL: On failure due to Illegal value +* + +* @note +* \n +* - To disable stateful DHCPv6, call after netifapi_dhcp6_release_stateful. +*/ +err_t netifapi_dhcp6_disable(struct netif *netif); + +/* +Func Name: netifapi_dhcp6_release_stateful +*/ +/** +* @ingroup Threadsafe_DHCPv6_Interfaces + +* +* @brief +* This interface is used to try to send a RELEASE when stateful DHCPv6 is enabled on a network interface. +* If stateful DHCPv6 client is doing RELEASE, it will return without doing anything. +* If stateless DHCPv6 is enabled on a network interface, it will return ERR_VAL and do nothing else. +* If no DHCPv6 client instance is attached to this interface, it will return ERR_VAL and do nothing else. +* If stateful DHCPv6 is enabled and a valid IPv6 address is using, it will try to send a RELEASE and will +* handle the REPLY of this RELEASE. It will stop using the IPv6 address to be released as soon as the client +* begins the Release message exchange process. +* It is the thread-safe way for calling dhcp6_release_stateful in the user space. +* +* @param[in] netif Indicates the lwIP network interface. +* +* @return +* ERR_OK: On success \n +* ERR_VAL: On failure due to Illegal value + +*/ +err_t netifapi_dhcp6_release_stateful(struct netif *netif); + +/* +Func Name: netifapi_dhcp6_cleanup +*/ +/** +* @ingroup Threadsafe_DHCPv6_Interfaces +* +* @brief +* This interface is used to free the memory allocated for DHCPv6 during DHCPv6 enable. +* It is the thread-safe way for calling dhcp_cleanup in the user space. +* +* @param[in] netif Indicates the lwIP network interface. +* +* @return +* ERR_OK: On success \n +* ERR_VAL: On failure due to Illegal value +* + +* @note +* \n +* - Call after DHCPv6 client is disabled. +* - Call netifapi_dhcp6_disable() before calling netifapi_dhcp6_cleanup. +*/ +err_t netifapi_dhcp6_cleanup(struct netif *netif); +#endif /* LWIP_IPV6_DHCP6 */ + +#if LWIP_AUTOIP + +/** +* @ingroup Threadsafe_Network_Interfaces +* @par Description +* Call autoip_start() in a thread-safe way by running that function inside the tcpip_thread context. + +* +* @param[in] netif Indicates the lwIP network interface. +* +* @returns +* ERR_OK: On success \n +* ERR_MEM: On failure due to memory \n +* ERR_VAL: On failure due to Illegal value. +*/ +err_t netifapi_autoip_start(struct netif *netif); + +/** +* @ingroup Threadsafe_Network_Interfaces +* @brief +* Thread-safe API to stop the AutoIP client. +* +* @param[in] netif Indicates the lwIP network interface. +* +* @returns +* ERR_OK: On success. \n +* ERR_ARG: On passing invalid arguments. +* +* @note +* - Call the autoip_stop API to stop the AutoIP service. +* - Use only for functions where there is only "netif" parameter. +*/ +err_t netifapi_autoip_stop(struct netif *netif); + +#endif /* LWIP_AUTOIP */ + +#if LWIP_NETIF_LINK_CALLBACK && LWIP_NETIFAPI_LINK_CALLBACK +/* +Func Name: netifapi_netif_set_link_callback +*/ +/** +* @ingroup Threadsafe_Network_Interfaces +* @brief +* This API is used to set callback to netif. This API is called whenever a link is brought up or down. +* +* @param[in] netif Indicates the lwIP network interface. +* @param[in] link_callback The callback pointer. +* +* @returns +* ERR_OK: This API always returns this value. \n +*/ +err_t +netifapi_netif_set_link_callback(struct netif *netif, netif_status_callback_fn link_callback); +#endif /* LWIP_NETIF_LINK_CALLBACK && LWIP_NETIFAPI_LINK_CALLBACK */ + +#if LWIP_NETIF_EXT_STATUS_CALLBACK +/* +Func Name: netifapi_netif_add_ext_callback +*/ +/** +* @ingroup Threadsafe_Network_Interfaces +* @brief +* This API is used to add an extended netif status callback (NSC). +* +* @param[in] callback Indicates the NSC data structure. +* @param[in] fn The callback function pointer. +* +* @returns +* ERR_OK: On success. \n +* ERR_ARG: On passing invalid arguments. +*/ +err_t netifapi_netif_add_ext_callback(netif_ext_callback_t *callback, netif_ext_callback_fn fn); + +/* +Func Name: netifapi_netif_remove_ext_callback +*/ +/** +* @ingroup Threadsafe_Network_Interfaces +* @brief +* This API is used to remove an extended netif status callback (NSC). +* +* @param[in] callback Indicates the NSC data structure. +* +* @returns +* ERR_OK: On success. \n +* ERR_VAL: On passing invalid arguments. +*/ +err_t netifapi_netif_remove_ext_callback(netif_ext_callback_t *callback); +#endif /* LWIP_NETIF_EXT_STATUS_CALLBACK */ + +#if LWIP_NETIFAPI_MTU +/* +Func Name: netifapi_netif_set_mtu +*/ +/** +* @ingroup Threadsafe_Network_Interfaces +* @brief +* This API is used to set the MTU of the netif. Call this API whenever the MTU needs to be changed. +* @param[in] netif Indicates the lwIP network interface. +* @param[in] mtu Indicates the new MTU of the network interface. Valid values are 68 to 1500. +* +* @returns +* ERR_OK: On success. \n +* ERR_ARG: On passing invalid arguments. +* +* @note +* - The value of the new mtu which is passed should be in the range 68 to 1500. +* - On modifying the MTU, the MTU change comes into effect immediately. +* - IP packets for existing connections are also sent according to new MTU. +* - Ideally, the application must ensure that connections are terminated before MTU modification or at +* init time to avoid side effects, since peer might be expecting a different MTU. +* - Effective MSS for existing connection will not change, it might remain same. It is not +* suggested to change the MTU at runtime. +* - Only for new connections, effective MSS is used for connection setup. \n +* +*/ +err_t netifapi_netif_set_mtu(struct netif *netif, u16_t mtu); +#endif /* LWIP_NETIFAPI_MTU */ + +#if LWIP_NETIFAPI_IF_NUM +/* +Func Name: netifapi_netif_change_if_num +*/ +/** +* @ingroup Threadsafe_Network_Interfaces +* @brief +* This API is used to change the num of the netif. +* @param[in] netif Indicates the lwIP network interface. +* @param[in] num Indicates the new num of the network interface. Valid values are 0 to 9. +* +* @returns +* ERR_OK: On success. \n +* ERR_ARG: On passing invalid arguments. +* ERR_VAL: On passing the same num in the netif_list. +*/ +err_t +netifapi_netif_change_if_num(struct netif *netif, u8_t num); +#endif + +#if LWIP_DHCPS + +/* +Func Name: netifapi_dhcps_start +*/ +/** +* @ingroup Threadsafe_DHCP_Interfaces +* @brief +* This API is used to start DHCPv4 Server on the netif. This should be called only + once when the DHCPv4 Server needs to be started on the netif. +* +* @param[in] netif Indicates the lwIP network interface. +* @param[in] start_ip Indicates the starting IP address of the DHCPv4 address pool. +* @param[in] ip_num Indicates the number of IP addresses that need to be in the pool. +* +* @par Return values +* ERR_OK: On success \n +* ERR_ARG: On passing invalid arguments. \n +* ERR_MEM: On trying to start a DHCPv4 server on a netif where DHCPv4 server is already running \n +* +* @par Note +* - If the DHCPv4 scope (Address Pool) use the default configuration, then both +* start_ip and ip_num must be NULL. +* - If the DHCPv4 scope (Address Pool) is manually configured, then both start_ip And +* ip_num must not be NULL. +* - In case of default DHCPv4 scope (Address Pool) configuration, the default start IP is ((netif_ip & netif_mask) + 2). +* - In case of manual DHCPv4 scope (Address Pool) configuration, start_ip should be in the same subnet of the netif. +* - The total number of addresses in the DHCPv4 Scope will be the minimum of non-zero ip_num & LWIP_DHCPS_MAX_LEASE. +* - No matter in case of default configuration or manual configuration, if the IP address of the DHCPv4 server lies in +* the range of address pool, then the total number of addresses available in the pool for clients will be decreased +* one, since one of the addresses in the pool has been taken up by the DHCPv4 Server and only others will be available +* to the DHCPv4 Clients. \n +* - In case of manual DHCPv4 scope configuration, if ip_start+ip_num goes beyond the maximum host IP, then the total +* number of addresses in the pool will be from [ip_start, maximum host IP] only. +* e.g. netmask is 255.255.255.0 and so maximum host IP is x.y.z.254, if ip_start+ip_num goes beyond x.y.z.254, +* then the total number of addresses in the pool will be from [ip_start, x.y.z.254] only. +*/ +err_t netifapi_dhcps_start(struct netif *netif, char *start_ip, u16_t ip_num); + +/* +Func Name: netifapi_dhcps_stop +*/ +/** + +* @ingroup Threadsafe_DHCP_Interfaces +* +* @brief +* This API is used to stop DHCPv4 Server on the netif where a DHCPv4 server is running. +* + +* @param[in] netif Indicates the lwIP network interface. +* @par Return values +* ERR_OK: On success \n + +* +* @par Note +* The DHCPv4 server can be restarted on a netif only after it is stopped on that netif. +* +*/ +err_t netifapi_dhcps_stop(struct netif *netif); + +#if LWIP_NETIFAPI_DHCPS_IP +err_t netifapi_dhcps_get_client_ip(struct netif *netif, u8_t *mac, u8_t maclen, ip_addr_t *ip); +#endif +#endif /* LWIP_DHCPS */ + +#if DRIVER_STATUS_CHECK + +/** +* @ingroup Threadsafe_Network_Interfaces +* @brief +* This API is used to set the netif driver status to the "Driver Not Ready" state. the driver must call this API +* to intimate the stack that the send buffer in the driver is full. +* +* @param[in] netif Indicates the lwIP network interface. +* +* @returns +* ERR_OK: On success \n +* ERR_ARG: On passing invalid arguments. \n +*/ +err_t netifapi_stop_queue(struct netif *netif); + +/** +* @ingroup Threadsafe_Network_Interfaces +* @brief +* This API is used to set the netif driver status to the "Driver Ready" state. This API is called by the driver to +* inform the stack that the driver send buffer is available to send after netifapi_stop_queue() was called +* previously. +* +* @param[in] netif Indicates the lwIP network interface. +* +* @returns +* ERR_OK: On success \n +* ERR_ARG: On passing invalid arguments. \n +*/ +err_t netifapi_wake_queue(struct netif *netif); +#endif + +#if LWIP_NETIFAPI_IF_INDEX +/* @ingroup netifapi_netif */ +err_t netifapi_netif_name_to_index(const char *name, u8_t *uIndex); +/* @ingroup netifapi_netif */ +err_t netifapi_netif_index_to_name(u8_t uIndex, char *name); + +/* @ingroup netifapi_netif */ +err_t netifapi_netif_nameindex_all(struct if_nameindex **pp_if_list); +#endif /* LWIP_NETIFAPI_IF_INDEX */ + +#if LWIP_NETIF_HOSTNAME +/* +Func Name: netifapi_set_hostname +*/ +/** +* @ingroup Threadsafe_DHCP_Interfaces + +* +* @brief +* This API is used to set the hostname of the netif, which is using in DHCP +* message. The hostname string lenght should be less than NETIF_HOSTNAME_MAX_LEN, +* otherwise the hostname will truncate to (NETIF_HOSTNAME_MAX_LEN-1). +* +* @param[in] netif Indicates the lwIP network interface. +* @param[in] hostname The new hostname to use. +* @param[in] namelen The hostname string length, should be within the scope of 0~NETIF_HOSTNAME_MAX_LEN-1. +* +* @return +* ERR_OK: On success \n +* ERR_ARG: On passing invalid arguments. \n +* + +*/ +err_t netifapi_set_hostname(struct netif *netif, char *hostname, u8_t namelen); + +#if LWIP_NETIF_GET_HOSTNAME +/* +Func Name: netifapi_get_hostname +*/ +/** +* @ingroup Threadsafe_DHCP_Interfaces + +* +* @brief +* This API is used to get the hostname of the netif, which is using in DHCP +* message. the hostname buffer length shoud not smaller than NETIF_HOSTNAME_MAX_LEN, +* otherwise it will get a truncated hostname. +* +* @param[in] netif Indicates the lwIP network interface. +* @param[out] hostname The buffer to stroe hostname string of the netif. +* @param[in] namelen The hostname string buffer length. +* +* @return +* ERR_OK: On success \n +* ERR_ARG: On passing invalid arguments. \n +* + +*/ +err_t netifapi_get_hostname(struct netif *netif, char *hostname, u8_t namelen); +#endif /* LWIP_NETIF_GET_HOSTNAME */ +#endif /* LWIP_NETIF_HOSTNAME */ + +#if LWIP_DHCP_VENDOR_CLASS_IDENTIFIER +/* +Func Name: netifapi_set_vci +*/ +/** +* @ingroup Threadsafe_DHCP_Interfaces + +* + +* @brief +* This API is used to set the vendor class identifier information, which is used in +* DHCP message. Length of vendor class identifier information string +* should be not more than DHCP_VCI_MAX_LEN(default 32), otherwise it +* will return with ERR_ARG. vci_len is the real length of vendor class identifier +* information string. +* +* @param[in] vci The new vendor class identifier information to use. +* It is a string of n octets [RFC2132 Section 9.13]. +* @param[in] vci_len The length of vendor class identifier information string, +* should be not more than DHCP_VCI_MAX_LEN. +* +* @return +* ERR_OK: On success \n +* ERR_ARG: On passing invalid arguments. \n +* ERR_VAL: On failure. \n + +*/ +err_t netifapi_set_vci(char *vci, u8_t vci_len); + +#if LWIP_DHCP_GET_VENDOR_CLASS_IDENTIFIER +/* +Func Name: netifapi_get_vci +*/ +/** +* @ingroup Threadsafe_DHCP_Interfaces + +* @brief +* This API is used to get the vendor class identifier information, which is used in +* DHCP message. Length of the buffer which is used to store vendor +* class identifier string must be not smaller than DHCP_VCI_MAX_LEN, otherwise +* it will return with ERR_ARG. Default value of DHCP_VCI_MAX_LEN is 32. +* If there is no vendor class identifier information related to DHCP, it will +* return with ERR_VAL. +* +* @param[out] vci The buffer to store vendor class identifier string of DHCP. +* @param[in,out] vci_len The length of buffer to store vendor class identifier string, +* and the real length of the vendor class identifier string. +* +* @return +* ERR_OK: On success \n +* ERR_ARG: On passing invalid arguments. \n +* ERR_VAL: On failure. \n +* +*/ +err_t netifapi_get_vci(char *vci, u8_t *vci_len); +#endif /* LWIP_DHCP_GET_VENDOR_CLASS_IDENTIFIER */ +#endif /* LWIP_DHCP_VENDOR_CLASS_IDENTIFIER */ + +#if LWIP_IP_FILTER +/* +Func Name: netifapi_set_ip_filter +*/ +/** +* @ingroup Threadsafe_Network_Interfaces + +* + +* +* @brief +* This API is used to set an ip filter for ip packets. The filter function will be called when +* a packet pass to ip_input. User can define rules to accept or drop a packet in filter_fn, +* returning 0 means accept, -1 means drop. +* +* @param[in] filter_fn The filter function which user implement. Prototype for filter_fn +* is err_t (*ip_filter_fn)(const struct pbuf *p, struct netif *inp); +* NULL indicate to disable the filter. +* @param[in] type IP address type as IPv4 or IPv6. IPADDR_TYPE_V4 is for IPv4 and IPADDR_TYPE_V6 +* is for IPv6. +* +* @return +* ERR_OK: On success \n +* ERR_VAL: On failure due to Illegal value +* + +* +* @note +* 1. User can access pbuf in filter_fn, modify pbuf data and access pbuf after filter_fn return are +* not allowed. \n +* 2. User can define rules to accept or drop a packet in filter_fn, return 0 means accept the +* packet, -1 means drop the packet and user no need to care about free pbuf. \n +* 3. Rules in filter_fn which user implement should be light and not complex, sleep and other block +* function must not be called, or it will have a negative influence to TCP/IP stack. \n +* 4. Filter only effect to IP packet. +* +* +* @endcond +*/ +err_t +netifapi_set_ip_filter(ip_filter_fn filter_fn, int type); +#endif /* LWIP_IP_FILTER */ + +#if LWIP_IPV6 +#if LWIP_NETIF_NBR_CACHE_API + +/* +Func Name: netifapi_add_ipv6_neighbor +*/ +/** +* @ingroup Threadsafe_Network_Interfaces + +* +* @brief +* This API is used to add a neighbor entry to the neighbor cache table. User +* can use this to add both static and non-sttaic neighbor. The neighbor state +* passed to the API will determine if the neighbor to be added is static or +* dynamic. To add static neighbor using this API user must set the confiburation +* LWIP_ND6_STATIC_NBR to 1 + +* +* @param[in] netif Indicates the network interface object through which this neighbor can be + reached. +* @param[in] nbr Provides information about the neighbor to be added. It includes +* IPv6 address of the neighbor, Its hardware +* address and its length, current state of the + neighbor, and Initial reachable duration of the neighbor. +* +* @return +* ERR_OK: On success \n +* ERR_ARG: If any parameter is invalid \n +* ERR_VAL: On failure due to illegal value \n +* ERR_MEM: If no more space available \n +* ERR_NBR_OVERWRITEFORBIDDEN: If try to add a neighbor that already exists +* + +* +* @note +* 1. The allowed states for the neighbor are ND6_STATE_REACHABLE(2) for non +* static neighbor and ND6_STATE_PERMANENT(6) for static neighbor \n +* 2. For static neighbor user must set the reachable time to 0. \n +* 3. For non static neighbors the initial reachable time cannot be greater than +* the LWIP_ND6_REACHABLE_TIME configured. Once the rechable time set by the +* user expires, neighbor will move to stale state. When it again moves to the +* reachable state, the rechable time will be set to LWIP_ND6_REACHABLE_TIME. \n +* 4. If you try to add a neighbor that already exists and it is not a static +* neighbor we do not allow it to be overwritten. For static neighbor we will +* update the new hw address. \n +* 5. To use this API user MUST set LWIP_NETIF_NBR_CACHE_API configuration to 1. +* \n + +*/ +err_t netifapi_add_ipv6_neighbor(struct netif *netif, struct ipv6_neighbor *nbr); + +/* +Func Name: netifapi_del_ipv6_neighbor +*/ +/** +* @ingroup Threadsafe_Network_Interfaces + +* @brief +* This API is used to delete a neighbor entry to the neighbor cache table. User +* can use this to delete both static and non-sttaic neighbor. +* +* @param[in] netif Indicates the network interface object which the neighbor is part of. +* @param[in] ipaddr Indicates the IP address of the neighbor to remove. +* +* @return +* ERR_OK: On success \n +* ERR_ARG: If any parameter is invalid \n +* ERR_NBR_NOTFOUND: If the neighbor does not exist + +* @note +* 1. If the neighbor to be deleted has an associated default router entry we +* will remove the default route also. \n +* +* 2. To use this API user MUST set LWIP_NETIF_NBR_CACHE_API configuration to 1 +* \n +*/ +err_t netifapi_del_ipv6_neighbor(struct netif *netif, struct ip6_addr *ipaddr); + +/* +Func Name: netifapi_query_ipv6_neighbor +*/ +/** +* @ingroup Threadsafe_Network_Interfaces + +* @brief +* This API is used to query a neighbor entry from the neighbor cache table. User +* can use this to query both static and non-static neighbor. +* +* @param[in] netif Indicates the network interface object which the neighbor is part of. +* @param[in] ipaddr Indicates the IP address of the neighbor to be queried. +* @param[out] nbrinfo Indicates information about the neighbor. +* +* @return +* ERR_OK: On success \n +* ERR_ARG: If any parameter is invalid \n +* ERR_NBR_NOTFOUND: If the neighbor does not exist + +* +* @note +* 1. The nbrinfo parameter must be a valid memory of type struct ipv6_neighbor. \n +* +* 2. To use this API user must set LWIP_NETIF_NBR_CACHE_API configuration to 1 +* \n +*/ +err_t netifapi_query_ipv6_neighbor(struct netif *netif, struct ip6_addr *ipaddr, + struct ipv6_neighbor *nbrinfo); +#endif /* LWIP_NETIF_NBR_CACHE_API */ + +#if LWIP_6LOWPAN +/* +Func Name: netifapi_set_6lowpan_context +*/ +/** +* @ingroup Threadsafe_Network_Interfaces +* @brief +* This API is used to add 6lowpan context identifier. +* +* @param[in] netif Indicates the network interface object which this network prefix is part of. +* @param[in] ctxid Indicates the identifier (ID) associated with the context. This value must be within the +* range 0 to 15. +* @param[out] context_prefix Indicates the IPv6 prefix to be represented by the context ID. +* +* @return +* ERR_OK: On success \n +* ERR_ARG: If any parameter is invalid \n +* ERR_MEM: No more free CB available +* +* +* @par Note +* 1. If the user adds a 6lowpan context with context ID that already exists, we +* will overwrite the existing one. \n +* 2. To use this API, the user must set LWIP_6LOWPAN configuration to 1. \n +* 3. User must also set LWIP_6LOWPAN_NUM_CONTEXTS to a value greater than 0 as per +* the need. +* 4. If netifapi_set_6lowpan_context returns ERR_MEM then user must call the +* netifapi_remove_6lowpan_context() API to free some unused context then call the +* netifapi_set_6lowpan_context() API to add the new context. +* 5. If you have multiple interfaces, context IDs on the interfaces must not be +* same as we use the context ID as a unique key. This limitation will be removed in a future version. +* \n +*/ +err_t netifapi_set_6lowpan_context(struct netif *netif, u8_t ctxid, + struct ip6_addr *context_prefix); + +/* +Func Name: netifapi_remove_6lowpan_context +*/ +/** +* @ingroup Threadsafe_Network_Interfaces +* @brief +* This API is used to remove 6lowpan context identifier. +* +* @param[in] netif Indicates the network interface object which this network prefix is part of. +* @param[in] ctxid Indicates the identifier (ID) associated with the context. This value must be within the range +* 0 to 15. +* +* @return +* ERR_OK: On success \n +* ERR_ARG: If any parameter is invalid \n +* ERR_LOWPAN_CTX_NOTFOUND: If the given context id doesn't exists +* +* \n +*/ +err_t netifapi_remove_6lowpan_context(struct netif *netif, u8_t ctxid); + +#endif /* LWIP_6LOWPAN */ + +#if LWIP_ND6_STATIC_DEFAULT_ROUTE +/* +Func Name: netifapi_add_ipv6_static_default_route +*/ +/** +* @ingroup Threadsafe_Network_Interfaces + +* @brief +* This API is used to add a static deafult route entry. It adds the +* corresponding non static neighbor cache entry if the neighbor does not exist. + +* @param[in] netif Indicates the network interface which this default route belongs to. +* @param[in] router_addr Indicates the ink local IPv6 address of the deafult route entry. +* +* @return +* ERR_OK: On success \n +* ERR_ARG: If any parameter is invalid \n +* ERR_DEFAULT_ROUTE_EXISTS: Default route already exists \n +* ERR_NO_FREE_ENTRY: No free +* +* @note +* 1. To use this API user MUST set LWIP_ND6_STATIC_DEFAULT_ROUTE configuration to 1. +* \n + +* +*/ +err_t netifapi_add_ipv6_static_default_route(struct netif *netif, + struct ip6_addr *router_addr); + +/* +Func Name: netifapi_del_ipv6_static_default_route +*/ +/** +* @ingroup Threadsafe_Network_Interfaces + +* +* @brief +* This API is used to delete a static default route entry. +* + +* @param[in] netif Indicates the network interface which this default route belongs to. +* @param[in] router_addr Indicates the link local IPv6 address of the default route entry. +* +* @return +* ERR_OK: On success \n +* ERR_ARG: If any parameter is invalid \n +* ERR_DEFAULT_ROUTER_NOTFOUND: default route does not exists +* +* @note +* 1. To use this API the user must set LWIP_ND6_STATIC_DEFAULT_ROUTE configuration to 1. +* \n +* N/A +* +*/ +err_t netifapi_del_ipv6_static_default_route(struct netif *netif, + struct ip6_addr *router_addr); + +#endif /* LWIP_ND6_STATIC_DEFAULT_ROUTE */ + +#if LWIP_ND6_STATIC_PREFIX +#define USE_PREFIX_AUTOCONFIG_AUTONOMOUS 0x01 +/* +Func Name: netifapi_add_static_prefix +*/ +/** +* @ingroup Threadsafe_Network_Interfaces + +* @brief +* This API is used to add static network prefix. +* + +* +* @param[in] netif Indicates the network interface which this default route belongs to. +* @param[in] prefix Indicates the network prefix. +* @param[in] flags Indicates the address auto configuration flag. +* +* +* @return +* ERR_OK: On success \n +* ERR_ARG: If any parameter is invalid \n +* ERR_PREFIX_EXISTS: Given prefix already exists \n +* ERR_NO_FREE_ENTRY: No free entry exists to add this prefix. +* + +* @par Note +* 1. If the address needs to be auto configured using this prefix to be added, then the user must +* set the USE_PREFIX_AUTOCONFIG_AUTONOMOUS flag. \n +* 2. To use this API the user must set LWIP_ND6_STATIC_PREFIX configuration to 1. +* \n +*/ +err_t netifapi_add_static_prefix(struct netif *netif, struct ip6_addr *prefix, + u8_t flags); +/* +Func Name: netifapi_del_static_prefix +*/ +/** +* @ingroup Threadsafe_Network_Interfaces + +* +* @brief +* This API is used to remove static network prefix. When the prefix is removed +* address configured from this prefix on the network interface will also be +* removed. +* +* @param[in] netif Indicates the network interface which this default route belongs to. +* @param[in] prefix Indicates the network prefix. +* +* +* @return +* ERR_OK: On success \n +* ERR_ARG: If any parameter is invalid \n +* ERR_PREFIX_NOT_FOUND: Prefix to be removed is not found. \n +* ERR_VAL: If prefix to be removed is not a static one +* + +* @note +* 1. To use this API the user must set the LWIP_ND6_STATIC_PREFIX configuration to 1. +* \n +*/ +err_t netifapi_del_static_prefix(struct netif *netif, struct ip6_addr *prefix); +#endif /* LWIP_ND6_STATIC_PREFIX */ + +#if LWIP_ND6_ROUTER +err_t netifapi_set_ra_enable(struct netif *netif, u8_t ra_enable); +err_t netifapi_set_ipv6_forwarding(struct netif *netif, u8_t forwarding); +err_t netifapi_set_accept_ra(struct netif *netif, u8_t accept_ra); +#endif + +#if LWIP_6LOWPAN +err_t netifapi_set_6lowpan_enable(struct netif *netif, u8_t enable); +#endif + +#endif /*LWIP_IPV6*/ + +#if LWIP_MAC_SECURITY + +/* +Func Name: netifapi_set_authentication_status +*/ +/** +* @ingroup Threadsafe_Network_Interfaces + +* +* @brief +* This API is used by the MAC driver layer to indicate network interface +* about the status of the authentication procedure. +* +* @param[in] netif Indicates the network interface which this default route belongs to. +* @param[in] authstatus Indicates the authentication procedure status. It can be +* either AUTHENTICATION_SUCCESS or +* AUTHENTICATION_FAILURE. +* +* +* @return +* ERR_OK: On success \n +* ERR_ARG: If any parameter is invalid \n +* ERR_PREFIX_NOT_FOUND: Prefix to be removed is not found. \n +* ERR_VAL: If prefix to be removed is not a static one \n +* +* +* @note +* 1. To use this API the user must set the LWIP_MAC_SECURITY configuration to 1. \n +* +* 2. Currently when user adds a network interface of type PLC, we will set +* a flag NETIF_FLAG_MAC_SECURITY_SUPPORT to the interface object to +* indicate that this interface will have MAC layer security and we need to +* apply below mentioned rule for the network traffic via this network interface. \n +* 3. When the user enables MAC layer security its considered that all the traffic +* to and from the network will be secured using the MAC layer security. \n +* 4. When MAC layer security is enabled for application messages sent or received +* via TCP or UDP protocols over IPv6, by default all will be secure, unless the +* user allows unsecure traffic by setting the socket option. \n +* 5. For IPv6 layer control messages, all traffic will be secure by default. We +* will consider exception for the ND6 messages like (NS/RS) which an already +* joined router/host can receive from a new node. We will also add exception +* for echo request send to the link local addresses. \n +* 6. Currently in smart grid network with PLC or RF there will be no RS traffic so +* we can ignore that. There will be NS/NA traffic from an unauthorized host/ +* router to an authorized router (i) or from authorized router to the new un- +* authorized host/router (ii). These two kinds of NS/NA traffic need to be +* allowed unsecure \n +* 7. For a new node, once this API is called and flag is set the outgoing NS +* message will also be always secure.\n +* +*/ +err_t netifapi_set_authentication_status(struct netif *netif, + u8_t authstatus); + +#endif /*LWIP_MAC_SECURITY*/ + +#if LWIP_LOWPOWER +err_t netifapi_enable_lowpower(void); +err_t netifapi_disable_lowpower(void); +#endif + +#if LWIP_IPV4 && LWIP_ARP +/* +Func Name: netifapi_ip_to_mac +*/ +/** @ingroup Threadsafe_Network_Interfaces +* @brief +* This API is used to get MAC address through IPv4 address. +* +* @param[in] ip Indicates the IPv4 address to find related MAC address. +* @param[out] mac The buffer to record the related MAC address. +* @param[in/out] maclen As in parameter, indicates the length of mac buffer. +* As out parameter, indicates the length of related MAC address. +* +* @returns +* ERR_OK : On success. \n +* Negative value : On failure. \n +*/ +err_t netifapi_ip_to_mac(const ip4_addr_t *ip, u8_t *mac, u8_t *maclen); +#endif + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_NETIF_API */ + +#endif /* LWIP_HDR_NETIFAPI_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/opt.h b/sdk_liteos/third_party/lwip_sack/include/lwip/opt.h new file mode 100644 index 0000000000000000000000000000000000000000..d78f2ceefdc314f9b25625492d2eb9664da33a81 --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/opt.h @@ -0,0 +1,4345 @@ +/** + * @file + * + * lwIP Options Configuration + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ + +/** +* @file opt.h +* @ingroup lwIP_Compiletime_Configuration +*/ +/* + * NOTE: || defined __DOXYGEN__ is a workaround for doxygen bug - + * without this, doxygen does not see the actual #define + */ +/** @defgroup lwIP_Compiletime_Configuration lwIP Compile Time Configuration +* @ingroup Configuration_Interfaces +*/ +/* Below comment section is RFC table for IDG supports, please add only one time for each RFC */ + +#if !defined LWIP_HDR_OPT_H +#define LWIP_HDR_OPT_H + +#ifndef LWIP_IPV6_PREFIX_LEN +#define LWIP_IPV6_PREFIX_LEN 64 +#endif + +/* + * Include user defined options first. Anything not defined in these files + * will be set to standard values. Override anything you don't like! + */ +#ifdef LWIP_CONFIG_FILE +#include LWIP_CONFIG_FILE +#else +#include "lwip/lwipopts.h" +#endif // LWIP_CONFIG_FILE + +#include "lwip/debug.h" +#if LWIP_LITEOS_COMPAT +#include "sys/select.h" +#include "sys/socket.h" +#include "sys/ioctl.h" +#include "arch/atomic.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +/* Added for missing declaration of IN6ADDR_ANY_INIT */ +#if !LWIP_LINUX_COMPAT +#else +#include +#endif + +#endif + +#include "securec.h" + +/* + * @defgroup lwip_opts Options (lwipopts.h) + * @ingroup lwip + * + * @defgroup lwip_opts_debug Debugging + * @ingroup lwip_opts + * + * @defgroup lwip_opts_infrastructure Infrastructure + * @ingroup lwip_opts + * + * @defgroup lwip_opts_callback Callback-style APIs + * @ingroup lwip_opts + * + * @defgroup lwip_opts_threadsafe_apis Thread-safe APIs + * @ingroup lwip_opts + */ + +/* + ------------------------------------ + -------------- NO SYS -------------- + ------------------------------------ +*/ + +/** + * NO_SYS==1: Use lwIP without OS-awareness (no thread, semaphores, mutexes or + * mboxes). This means that threaded APIs such as socket APIs or netconn APIs cannot be used. + * Only the callback-style raw APIs are + * available. Ensure that you do not access + * lwIP functions/structures from more than one context at a time. + */ +#if !defined NO_SYS || defined __DOXYGEN__ +#define NO_SYS 0 +#endif +/** + * @} + */ + +/* + * @defgroup lwip_opts_timers Timers + * @ingroup lwip_opts_infrastructure + * @{ + */ +/** + * LWIP_TIMERS==0: Drop support for sys_timeout and lwip-internal cyclic timers + * (the array of lwip-internal cyclic timers is still provided). + * Refer to NO_SYS_NO_TIMERS for compatibility to old versions. + */ +#if !defined LWIP_TIMERS || defined __DOXYGEN__ +#ifdef NO_SYS_NO_TIMERS +#define LWIP_TIMERS (!NO_SYS || (NO_SYS && !NO_SYS_NO_TIMERS)) +#else +#define LWIP_TIMERS 1 +#endif +#endif + +/** + * LWIP_TIMERS_CUSTOM==1: Provide your own timer implementation. + * Function prototypes in timeouts.h and the array of lwip-internal cyclic timers + * are still included, but the implementation is not included. The following functions + * are required: sys_timeouts_init(), sys_timeout(), sys_untimeout(), + * sys_timeouts_mbox_fetch() + */ +#if !defined LWIP_TIMERS_CUSTOM || defined __DOXYGEN__ +#define LWIP_TIMERS_CUSTOM 0 +#endif +#ifndef TCPIP_PRTY_MBOX_SIZE +#define TCPIP_PRTY_MBOX_SIZE 16 +#endif + +#define lwIP_TRUE 1 +#define lwIP_FALSE 0 +extern int g_is_lwip_initialized; +/** + * @} + */ + +/* + ------------------------------------ + ----------- Core locking ----------- + ------------------------------------ +*/ +/* + * @defgroup lwip_opts_lock Core locking and MPU + * @ingroup lwip_opts_infrastructure + * @{ + */ +/** + * LWIP_MPU_COMPATIBLE: Enables a special memory management mechanism + * which makes lwip able to work on MPU (Memory Protection Unit) system + * by not passing stack-pointers to other threads + * (this decreases performance as memory is allocated from pools instead + * of keeping it on the stack) + */ +#if !defined LWIP_MPU_COMPATIBLE || defined __DOXYGEN__ +#define LWIP_MPU_COMPATIBLE 0 +#endif + +/** + * LWIP_TCPIP_CORE_LOCKING + * Creates a global mutex that is held during TCPIP thread operations. + * Can be locked by client code to perform lwIP operations without changing + * into TCPIP thread using callbacks. See LOCK_TCPIP_CORE() and + * UNLOCK_TCPIP_CORE(). + * Your system should provide mutexes supporting priority inversion to use this. + */ +#if !defined LWIP_TCPIP_CORE_LOCKING || defined __DOXYGEN__ +#define LWIP_TCPIP_CORE_LOCKING 1 +#endif + +/** + * LWIP_TCPIP_CORE_LOCKING_INPUT: when LWIP_TCPIP_CORE_LOCKING is enabled, + * this macro lets tcpip_input() grab the mutex for input packets as well, + * instead of allocating a message and passing it to tcpip_thread. + * + * @note This macro does not work when tcpip_input() is called from the + * interrupt context. + */ +#if !defined LWIP_TCPIP_CORE_LOCKING_INPUT || defined __DOXYGEN__ +#define LWIP_TCPIP_CORE_LOCKING_INPUT 0 +#endif + +/** + * @ingroup Securelib_Interface + * SYS_LIGHTWEIGHT_PROT==1: Enables inter-task protection (and task-vs-interrupt + * protection) for certain critical regions during buffer allocation and deallocation, + * and memory allocation and deallocation. + * @note This macro is required when using lwIP from more than one context. If + * this macro is disabled, you must be sure what you are doing. + */ +#if !defined SYS_LIGHTWEIGHT_PROT || defined __DOXYGEN__ +#define SYS_LIGHTWEIGHT_PROT 1 +#endif +/** + * @} + */ + +/** + * Macro/function to check whether lwIP's threading/locking + * requirements are satisfied during current function call. + * This macro usually calls a function that is implemented in the OS-dependent + * sys layer and performs the following checks: + * - Not in ISR (this should be checked for NO_SYS==1, too!) + * - If @ref LWIP_TCPIP_CORE_LOCKING = 1: TCPIP core lock is held + * - If @ref LWIP_TCPIP_CORE_LOCKING = 0: function is called from TCPIP thread + * @see @ref multithreading + */ +#if !defined LWIP_ASSERT_CORE_LOCKED || defined __DOXYGEN__ +#define LWIP_ASSERT_CORE_LOCKED() +#endif + +/** + * Called as first thing in the lwIP TCPIP thread. Can be used in conjunction + * with @ref LWIP_ASSERT_CORE_LOCKED to check core locking. + * @see @ref multithreading + */ +#if !defined LWIP_MARK_TCPIP_THREAD || defined __DOXYGEN__ +#define LWIP_MARK_TCPIP_THREAD() +#endif + +/* + ------------------------------------ + ---------- Memory options ---------- + ------------------------------------ +*/ +/* + * @defgroup lwip_opts_mem Heap and memory pools + * @ingroup lwip_opts_infrastructure + * @{ + */ +/** + * MEM_LIBC_MALLOC==1: Use malloc/free/realloc provided by your C library + * instead of the lwIP internal allocator. This can save code size if you + * already use it. + */ +#if !defined MEM_LIBC_MALLOC || defined __DOXYGEN__ +#define MEM_LIBC_MALLOC 0 +#endif + +#ifndef MEM_LIBC_MALLOC_TOTAL_SIZE_LIMIT +#define MEM_LIBC_MALLOC_TOTAL_SIZE_LIMIT 0 +#endif + +/** + * MEMP_MEM_MALLOC==1: Use mem_malloc/mem_free instead of the lwIP pool allocator. + * Especially useful with MEM_LIBC_MALLOC, but be cautious regarding execution + * speed (heap alloc can be much slower than pool alloc) and usage from interrupts + * especially if your netif driver allocates PBUF_POOL pbufs for received frames + * from interrupt. + * @note Currently, this macro uses the heap for all pools, including private pools, and + * not only for internal pools defined in memp_std.h. + */ +#if !defined MEMP_MEM_MALLOC || defined __DOXYGEN__ +#define MEMP_MEM_MALLOC 0 +#endif + +/** + * MEMP_MEM_INIT==1: Force use of memset to initialize pool memory. + * Useful if pool are moved in uninitialized section of memory. This will ensure + * default values in pcbs struct are well initialized in all conditions. + */ +#if !defined MEMP_MEM_INIT || defined __DOXYGEN__ +#define MEMP_MEM_INIT 0 +#endif + +#ifndef TCP_PBUF_MALLOC +#define TCP_PBUF_MALLOC 1 +#endif + +/** + * This macro must be set to the alignment of the CPU \n + * 4 byte alignment -> \#define MEM_ALIGNMENT 4 \n + * 2 byte alignment -> \#define MEM_ALIGNMENT 2 + */ +#ifdef LOSCFG_ARCH_CORTEX_A53_AARCH64 +#define MEM_ALIGNMENT 8U // for 64bit support +#else +#define MEM_ALIGNMENT 4U +#endif + +/** +* This macro sets the minimum size required for pbuf with type PBUF_RAM +* When setting size using the pbuf_ram_size_set, the input size should be greater than the +* minimum size of PBUF_RAM_SIZE_MIN. +*/ +#if !defined PBUF_RAM_SIZE_MIN || defined __DOXYGEN__ +#define PBUF_RAM_SIZE_MIN 1024 +#endif + +#if !defined PBUF_RAM_SIZE_MAX || defined __DOXYGEN__ +#define PBUF_RAM_SIZE_MAX 0x7FFFFFFF +#endif + +/** + * This macro sets the maximum length to be passed to pbuf alloc for PBUF_RAM type. + */ +#if !defined MAX_PBUF_RAM_SIZE_TO_ALLOC || defined __DOXYGEN__ +#define MAX_PBUF_RAM_SIZE_TO_ALLOC 65535U +#endif + +/** + * This macro sets the align size of the DMA memory. If set to 1, then DMA is not used. + */ +#ifndef MEM_MALLOC_DMA_ALIGN +#define MEM_MALLOC_DMA_ALIGN 64 +#endif + +/** + * MEM_SIZE: This macro defines the size of the heap memory. If the application will send + * a lot of data that needs to be copied, this should be set high. + */ +#if !defined MEM_SIZE || defined __DOXYGEN__ +#define MEM_SIZE 1600 +#endif + +/** + * This macro reserves a configurable + * amount of bytes before and after each memp element in every pool and fills + * it with a prominent default value. + * MEMP_OVERFLOW_CHECK == 0 No checking \n + * MEMP_OVERFLOW_CHECK == 1 Checks each element when it is freed \n + * MEMP_OVERFLOW_CHECK >= 2 Checks each element in every pool every time + * memp_malloc() or memp_free() is called. This is useful, but slow. + */ +#if !defined MEMP_OVERFLOW_CHECK || defined __DOXYGEN__ +#define MEMP_OVERFLOW_CHECK 0 +#endif + +/** + * MEMP_SANITY_CHECK==1: Runs a sanity check after each memp_free() to make + * sure that there are no cycles in the linked lists. + */ +#if !defined MEMP_SANITY_CHECK || defined __DOXYGEN__ +#define MEMP_SANITY_CHECK 0 +#endif + +/** + * MEM_OVERFLOW_CHECK: mem overflow protection reserves a configurable + * amount of bytes before and after each heap allocation chunk and fills + * it with a prominent default value. + * MEM_OVERFLOW_CHECK == 0 no checking + * MEM_OVERFLOW_CHECK == 1 checks each element when it is freed + * MEM_OVERFLOW_CHECK >= 2 checks all heap elements every time + * mem_malloc() or mem_free() is called (useful but slow!) + */ +#if !defined MEM_OVERFLOW_CHECK || defined __DOXYGEN__ +#define MEM_OVERFLOW_CHECK 0 +#endif + +/** + * MEM_SANITY_CHECK==1: run a sanity check after each mem_free() to make + * sure that the linked list of heap elements is not corrupted. + */ +#if !defined MEM_SANITY_CHECK || defined __DOXYGEN__ +#define MEM_SANITY_CHECK 0 +#endif + +/** + * MEM_USE_POOLS==1: Uses an alternative to malloc() by allocating from a set + * of memory pools of various sizes. When mem_malloc is called, an element of + * the smallest pool that can provide the length needed is returned. + * To use this, MEMP_USE_CUSTOM_POOLS also has to be enabled. + */ +#if !defined MEM_USE_POOLS || defined __DOXYGEN__ +#define MEM_USE_POOLS 0 +#endif + +/** + * MEM_USE_POOLS_TRY_BIGGER_POOL==1: If one malloc-pool is empty, try the next + * bigger pool. \n + * WARNING: This might waste memory, but it can make a system more + * reliable. */ +#if !defined MEM_USE_POOLS_TRY_BIGGER_POOL || defined __DOXYGEN__ +#define MEM_USE_POOLS_TRY_BIGGER_POOL 0 +#endif + +/** + * MEMP_USE_CUSTOM_POOLS==1: Indicates whether to include a user file lwippools.h + * that defines additional pools beyond the standard files required + * by lwIP. If you set this to 1, you must have lwippools.h in your + * include path. + */ +#if !defined MEMP_USE_CUSTOM_POOLS || defined __DOXYGEN__ +#define MEMP_USE_CUSTOM_POOLS 0 +#endif + +/** + * Set this macro to 1 to free PBUF_RAM pbufs (or call mem_free()) from + * interrupt context, or another context that does not allow waiting for a + * semaphore. + * If set to 1, mem_malloc will be protected by a semaphore and SYS_ARCH_PROTECT, + * while mem_free will only use SYS_ARCH_PROTECT. mem_malloc SYS_ARCH_UNPROTECTs + * with each loop so that mem_free can run. + * + * @par Note + * As mentioned in the description, this leads to disabling or + * enabling interrupts often, which can reduce the speed. Also, on low memory, mem_malloc + * can require a longer execution time. \n + * + * If you do not want that behavior, at least for NO_SYS=0, you can still use the following + * functions to enqueue a deallocation call which then runs in the tcpip_thread + * context: + * - pbuf_free_callback(p); + * - mem_free_callback(m); + */ +#if !defined LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT || defined __DOXYGEN__ +#define LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT 0 +#endif + +/** + * MEM_PBUF_RAM_SIZE_LIMIT : This configuration if enabled, limits the memory size usage by MEM_SIZE + * value.The configuration can be enabled under MEM_LIBC_MALLOC . + */ +#if MEM_LIBC_MALLOC +#ifndef MEM_PBUF_RAM_SIZE_LIMIT +#define MEM_PBUF_RAM_SIZE_LIMIT 1 +#endif +#else +#ifndef MEM_PBUF_RAM_SIZE_LIMIT +#define MEM_PBUF_RAM_SIZE_LIMIT 0 +#endif +#endif + +#ifndef LWIP_NAT64 +#define LWIP_NAT64 0 +#endif + +#ifndef LWIP_NAT64_PRIORITY_KEEP +#define LWIP_NAT64_PRIORITY_KEEP 1 +#endif + +/** + * LWIP_MBR_BROADCAST_SYNC : This configuration if enabled, starts the broadcast sync function in the sdv. + * the sync function will also use one timer. + */ +#ifndef LWIP_MBR_BROADCAST_SYNC +#define LWIP_MBR_BROADCAST_SYNC 0 +#endif + +/** + * @} + */ + +/* + ------------------------------------------------ + ---------- Internal Memory Pool Sizes ---------- + ------------------------------------------------ +*/ +/* + * @defgroup lwip_opts_memp Internal memory pools + * @ingroup lwip_opts_infrastructure + * @{ + */ +/** + * Indicates the number of memp struct pbufs (used for PBUF_ROM and PBUF_REF). + * If the application sends a lot of data out of ROM (or other static memory), + * this macro must be set to a high value. + */ +#if !defined MEMP_NUM_PBUF || defined __DOXYGEN__ +#define MEMP_NUM_PBUF 16 +#endif + +/** + * Indicates the number of raw connection PCBs. + * This macro requires the LWIP_RAW option. + */ +#if !defined MEMP_NUM_RAW_PCB || defined __DOXYGEN__ +#define MEMP_NUM_RAW_PCB 4 +#endif + +/** + * Indicates the number of UDP protocol control blocks. One + * per active UDP connection. + * This macro requires the LWIP_UDP option. + */ +#if !defined MEMP_NUM_UDP_PCB || defined __DOXYGEN__ +#define MEMP_NUM_UDP_PCB 4 +#endif + +/** + * Defines the number of simultaneously active TCP connections. + * This macro requires the LWIP_TCP option. + */ +#if !defined MEMP_NUM_TCP_PCB || defined __DOXYGEN__ +#define MEMP_NUM_TCP_PCB 5 +#endif + +/** + * Defines the number of listening TCP connections. + * This macro requires the LWIP_TCP option. + */ +#if !defined MEMP_NUM_TCP_PCB_LISTEN || defined __DOXYGEN__ +#define MEMP_NUM_TCP_PCB_LISTEN 8 +#endif + +/** + * Defines the number of simultaneously queued TCP segments. + * This macro requires the LWIP_TCP option. + */ +#if !defined MEMP_NUM_TCP_SEG || defined __DOXYGEN__ +#define MEMP_NUM_TCP_SEG 16 +#endif + +/** + * Defines the number of IP packets simultaneously queued for + * reassembly. + */ +#if !defined MEMP_NUM_REASSDATA || defined __DOXYGEN__ +#define MEMP_NUM_REASSDATA 5 +#endif + +/** + * Defines the number of IP fragments simultaneously sent. + * This is only used with LWIP_NETIF_TX_SINGLE_PBUF==0 and only has to be greater than 1 + * with DMA-enabled MACs where the packet is not yet sent when netif->output + * returns. + */ +#if !defined MEMP_NUM_FRAG_PBUF || defined __DOXYGEN__ +#define MEMP_NUM_FRAG_PBUF 15 +#endif + +/** + * Defines the number of simultaneously queued outgoing + * packets (pbufs) that are waiting for an ARP request (to resolve + * their destination address) to finish. + * This macro requires the ARP_QUEUEING option. + */ +#if !defined MEMP_NUM_ARP_QUEUE || defined __DOXYGEN__ +#define MEMP_NUM_ARP_QUEUE 30 +#endif + +/** + * Defines the number of multicast groups whose network interfaces + * can be members at the same time (one per netif - allsystems group -, plus one + * per netif membership). + * This macro requires the LWIP_IGMP option. + */ +#if !defined MEMP_NUM_IGMP_GROUP || defined __DOXYGEN__ +#define MEMP_NUM_IGMP_GROUP 8 +#endif + +/** + * Defines the number of default number of sockets + */ +#ifndef DEFAULT_LWIP_NUM_SOCKETS +#define DEFAULT_LWIP_NUM_SOCKETS 8 +#endif + +/* + * Provides flexibility to use configured values to spread across code + */ +/** +* LWIP_ALLOW_SOCKET_CONFIG ==0 allows stack to use default value of the number of sockets. +* That is LWIP_CONFIG_NUM_SOCKETS will be DEFAULT_LWIP_NUM_SOCKETS. +* LWIP_ALLOW_SOCKET_CONFIG ==1 allows application to use the configured value. +* Application can configure the Number of sockets using the API lwip_set_socket_num and retrieve the +* value through API lwip_get_socket_num. +*/ +#ifndef LWIP_ALLOW_SOCKET_CONFIG +#define LWIP_ALLOW_SOCKET_CONFIG 0 +#endif + +#if LWIP_ALLOW_SOCKET_CONFIG == 0 +#ifndef LWIP_CONFIG_NUM_SOCKETS +#define LWIP_CONFIG_NUM_SOCKETS DEFAULT_LWIP_NUM_SOCKETS +#endif + +#else /* LWIP_ALLOW_SOCKET_CONFIG */ +#ifndef LWIP_CONFIG_NUM_SOCKETS +extern unsigned int g_lwip_num_sockets; +#define LWIP_CONFIG_NUM_SOCKETS g_lwip_num_sockets +#endif +#endif /* LWIP_ALLOW_SOCKET_CONFIG */ + +#ifndef CONFIG_NFILE_DESCRIPTORS +#define CONFIG_NFILE_DESCRIPTORS 0 +#endif + +/** +* Defines the maximum number of sockets supported. +*/ +#ifndef LWIP_NUM_SOCKETS_MAX +#define LWIP_NUM_SOCKETS_MAX (FD_SETSIZE - CONFIG_NFILE_DESCRIPTORS) +#endif + +/** + * Defines the number of Maximum number of configurable sockets + */ +#ifndef LWIP_NUM_SOCKETS_MAX +#define LWIP_NUM_SOCKETS_MAX 128 +#endif + +/** + * Defines the number of simultaneously active timeouts. + * The default number of timeouts is calculated in this macro, for all enabled modules. + * The formula expects settings to be either '0' or '1'. + */ +#if !defined MEMP_NUM_SYS_TIMEOUT || defined __DOXYGEN__ +#define MEMP_NUM_SYS_TIMEOUT (LWIP_TCP + IP_REASSEMBLY + LWIP_ARP + (2*LWIP_DHCP) + LWIP_AUTOIP + LWIP_IGMP + LWIP_DNS \ + + LWIP_LIBCOAP + (LWIP_IPV6 ? (1 + LWIP_IPV6_REASS + LWIP_IPV6_MLD + LWIP_IPV6_DHCP6 + LWIP_RPL_TIMER_COUNT \ + + LWIP_RIPPLE_TIMER_COUNT + LWIP_6LOWPAN + LWIP_NAT64 + LWIP_MBR_BROADCAST_SYNC) : 0)) +#endif + +/** + * Defines the number of struct netbufs. + * This macro is only needed if you use sequential APIs, like api_lib.c. + */ +#if !defined MEMP_NUM_NETBUF || defined __DOXYGEN__ +#define MEMP_NUM_NETBUF 2 +#endif + +/** + * Defines the number of struct netconns. + * This macro is only needed if you use sequential APIs, like api_lib.c. + */ +#if !defined MEMP_NUM_NETCONN || defined __DOXYGEN__ +#define MEMP_NUM_NETCONN 4 +#endif + +/** + * Defines the number of struct tcpip_msg, which are used + * for callback/timeout API communication. + * This macro is only needed if you use tcpip.c. + */ +#if !defined MEMP_NUM_TCPIP_MSG_API || defined __DOXYGEN__ +#define MEMP_NUM_TCPIP_MSG_API 8 +#endif + +/** + * Defines the number of struct tcpip_msg, which are used + * for incoming packets. + * This macro is only needed if you use tcpip.c. + */ +#if !defined MEMP_NUM_TCPIP_MSG_INPKT || defined __DOXYGEN__ +#define MEMP_NUM_TCPIP_MSG_INPKT 8 +#endif + +/** + * Defines the number of concurrently running lwip_addrinfo() calls, + * before freeing the corresponding memory using lwip_freeaddrinfo(). + */ +#if !defined MEMP_NUM_NETDB || defined __DOXYGEN__ +#define MEMP_NUM_NETDB 8 +#endif + +/** + * Defines the number of host entries in the local host list + * if DNS_LOCAL_HOSTLIST_IS_DYNAMIC==1. + */ +#if !defined MEMP_NUM_LOCALHOSTLIST || defined __DOXYGEN__ +#define MEMP_NUM_LOCALHOSTLIST 1 +#endif +#ifndef LWIP_DNS_API_DECLARE_H_ERRNO +#define LWIP_DNS_API_DECLARE_H_ERRNO 0 +#endif + +/** + * Defines the number of buffers in the pbuf pool. + */ +#if !defined PBUF_POOL_SIZE || defined __DOXYGEN__ +#define PBUF_POOL_SIZE 16 +#endif + +/** Defines the number of concurrently active calls to various + * socket, netconn, and tcpip functions. + */ +#if !defined MEMP_NUM_API_MSG || defined __DOXYGEN__ +#define MEMP_NUM_API_MSG MEMP_NUM_TCPIP_MSG_API +#endif + +/** Defines the number of concurrently active calls to netconn_gethostbyname. + */ +#if !defined MEMP_NUM_DNS_API_MSG || defined __DOXYGEN__ +#define MEMP_NUM_DNS_API_MSG MEMP_NUM_TCPIP_MSG_API +#endif + +/** Defines the number of concurrently active calls + * to getsockopt/setsockopt. + */ +#if !defined MEMP_NUM_SOCKET_SETGETSOCKOPT_DATA || defined __DOXYGEN__ +#define MEMP_NUM_SOCKET_SETGETSOCKOPT_DATA MEMP_NUM_TCPIP_MSG_API +#endif + +/** Defines the number of concurrently active calls to the + * netifapi functions. + */ +#if !defined MEMP_NUM_NETIFAPI_MSG || defined __DOXYGEN__ +#define MEMP_NUM_NETIFAPI_MSG MEMP_NUM_TCPIP_MSG_API +#endif + +/** + * Defines the number of struct rpl_api_msg, which are used + * for callback/timeout RPL API communication. + * This macro is only needed if you use RPL. + */ +#if !defined MEMP_NUM_RPL_API_MSG || defined __DOXYGEN__ +#define MEMP_NUM_RPL_API_MSG 4 +#endif + +/** + * @} + */ + +/* + --------------------------------- + ---------- ARP options ---------- + --------------------------------- +*/ +/* + * @defgroup lwip_opts_arp ARP + * @ingroup lwip_opts_ipv4 + * @{ + */ +/** + * LWIP_ARP==1: Enables ARP functionality. + */ +#if !defined LWIP_ARP || defined __DOXYGEN__ +#define LWIP_ARP 1 +#endif + +#ifndef LWIP_ARP_GRATUITOUS_REXMIT +#define LWIP_ARP_GRATUITOUS_REXMIT 1 +#endif + +/** + * ARP_TABLE_SIZE: Indicates the number of active MAC-IP address pairs cached. + */ +#if !defined ARP_TABLE_SIZE || defined __DOXYGEN__ +#define ARP_TABLE_SIZE 10 +#endif + +/** Defines the time an ARP entry stays valid after its last update. + * For ARP_TMR_INTERVAL = 1000, this is + * (60 * 5) seconds = 5 minutes. + */ +#if !defined ARP_MAXAGE || defined __DOXYGEN__ +#define ARP_MAXAGE 300 +#endif + +/** + * ARP_QUEUEING==1: Multiple outgoing packets are queued during hardware address + * resolution. By default, only the most recent packet is queued per IP address. + * This is sufficient for most protocols and mainly reduces TCP connection + * startup time. Set this to 1 if you know your application sends more than one + * packet in a row to an IP address that is not in the ARP cache. + */ +#if !defined ARP_QUEUEING || defined __DOXYGEN__ +#define ARP_QUEUEING 0 +#endif + +/** + * ETHARP_TRUST_IP_MAC==1: Incoming IP packets cause the ARP table to be + * updated with the source MAC and IP_add supplied in the packet. + * Disable this if you do not trust LAN peers to have the + * correct addresses, or as a limited approach to attempt to handle + * spoofing. If disabled, lwIP must make a new ARP request if + * the peer is not already in the ARP table, adding a little latency. + * The peer is in the ARP table if it requested our address earlier. + * Also note that this slows down input processing of every IP packet. + */ +#ifndef ETHARP_TRUST_IP_MAC +#define ETHARP_TRUST_IP_MAC 1 +#endif + +/** Defines the maximum number of packets which may be queued for each + * unresolved address by other network layers. The default is 3. The value 0 means disabled. + * Old packets are dropped, and new packets are queued. + */ +#if !defined ARP_QUEUE_LEN || defined __DOXYGEN__ +#define ARP_QUEUE_LEN 3 +#endif + +/** + * ETHARP_SUPPORT_VLAN==1: Support receiving and sending ethernet packets with + * VLAN header. See the description of LWIP_HOOK_VLAN_CHECK and + * LWIP_HOOK_VLAN_SET hooks to check/set VLAN headers. + * Additionally, you can define ETHARP_VLAN_CHECK to an u16_t VLAN ID to check. + * If ETHARP_VLAN_CHECK is defined, only VLAN-traffic for this VLAN is accepted. + * If ETHARP_VLAN_CHECK is not defined, all traffic is accepted. + * Alternatively, define a function/define ETHARP_VLAN_CHECK_FN(eth_hdr, vlan) + * that returns 1 to accept a packet or 0 to drop a packet. + */ +#if !defined ETHARP_SUPPORT_VLAN || defined __DOXYGEN__ +#define ETHARP_SUPPORT_VLAN 0 +#endif + +/** LWIP_ETHERNET==1: Enables ethernet support even though ARP might be disabled. + */ +#if !defined LWIP_ETHERNET || defined __DOXYGEN__ +#define LWIP_ETHERNET LWIP_ARP +#endif + +/** Defines the number of bytes added before the ethernet header to ensure + * alignment of payload after that header. Since the header is 14 bytes long, + * without this padding (for example, addresses in the IP header will not be aligned + * on a 32-bit boundary), so setting this to 2 can speed up 32-bit-platforms. + */ +#if !defined ETH_PAD_SIZE || defined __DOXYGEN__ +#define ETH_PAD_SIZE 0 +#endif + +/** ETHARP_SUPPORT_STATIC_ENTRIES==1: Enables code to support static ARP table + * entries (using etharp_add_static_entry/etharp_remove_static_entry). + */ +#if !defined ETHARP_SUPPORT_STATIC_ENTRIES || defined __DOXYGEN__ +#define ETHARP_SUPPORT_STATIC_ENTRIES 0 +#endif + +/** ETHARP_TABLE_MATCH_NETIF==1: Match netif for ARP table entries. + * If disabled, duplicate IP address on multiple netifs are not supported + * (but this should only occur for AutoIP). + */ +#if !defined ETHARP_TABLE_MATCH_NETIF || defined __DOXYGEN__ +#define ETHARP_TABLE_MATCH_NETIF !LWIP_SINGLE_NETIF +#endif +/** + * @} + */ + +/** LWIP_PLC==1: Enables PLC support even though ARP might be disabled. + */ +#if !defined LWIP_PLC || defined __DOXYGEN__ +#define LWIP_PLC 0 +#endif + +/** LWIP_IEEE802154==1: Enables 802.15.4 support. + */ +#if !defined LWIP_IEEE802154 || defined __DOXYGEN__ +#define LWIP_IEEE802154 0 +#endif + +/* + -------------------------------- + ---------- IP options ---------- + -------------------------------- +*/ +/* + * @defgroup lwip_opts_ipv4 IPv4 + * @ingroup lwip_opts + * @{ + */ +/** + * LWIP_IPV4==1: Enables IPv4. + */ +#if !defined LWIP_IPV4 || defined __DOXYGEN__ +#define LWIP_IPV4 1 +#endif + +/** + * IP_FORWARD==1: Enables the ability to forward IP packets across network + * interfaces. If you are going to run lwIP on a device with only one network + * interface, define this to 0. + */ +#if !defined IP_FORWARD || defined __DOXYGEN__ +#define IP_FORWARD 0 +#endif + +/** + * IP_REASSEMBLY==1: Reassemble incoming fragmented IP packets. Note that + * this option does not affect outgoing packet sizes, which can be controlled + * using IP_FRAG. + */ +#if !defined IP_REASSEMBLY || defined __DOXYGEN__ +#define IP_REASSEMBLY 0 +#endif + +/** + * IP_FRAG==1: Fragments outgoing IP packets if their size exceeds MTU. Note + * that this option does not affect incoming packet sizes, which can be + * controlled using IP_REASSEMBLY. + */ +#if !defined IP_FRAG || defined __DOXYGEN__ +#define IP_FRAG 1 +#endif + +#if !LWIP_IPV4 +/* disable IPv4 extensions when IPv4 is disabled */ +#undef IP_FORWARD +#define IP_FORWARD 0 +#undef IP_REASSEMBLY +#define IP_REASSEMBLY 0 +#undef IP_FRAG +#define IP_FRAG 0 +#endif /* !LWIP_IPV4 */ + +/** + * Defines the behavior for IP options. \n + * IP_OPTIONS_ALLOWED==0: All packets with IP options are dropped. \n + * IP_OPTIONS_ALLOWED==1: IP options are allowed (but not parsed). \n + */ +#if !defined IP_OPTIONS_ALLOWED || defined __DOXYGEN__ +#define IP_OPTIONS_ALLOWED 1 +#endif + +/** + * Defines the maximum time (in multiples of IP_TMR_INTERVAL - so seconds, normally) + * a fragmented IP packet waits for all fragments to arrive. If all fragments have not arrived + * in this time, the whole packet is discarded. + */ +#if !defined IP_REASS_MAXAGE || defined __DOXYGEN__ +#define IP_REASS_MAXAGE 3 +#endif + +/** + * Defines the maximum number of pbufs waiting to be reassembled. + * Since the received pbufs are enqueued, configure + * PBUF_POOL_SIZE > IP_REASS_MAX_PBUFS so that the stack is still able to receive + * packets even if the maximum amount of fragments is enqueued for reassembly. + */ +#if !defined IP_REASS_MAX_PBUFS || defined __DOXYGEN__ +#define IP_REASS_MAX_PBUFS 10 +#endif + +/** + * IP_FRAG_USES_STATIC_BUF==1: Use a static MTU-sized buffer for IP + * fragmentation. Otherwise, pbufs are allocated and reference the original + * packet data to be fragmented. + */ +#ifndef IP_FRAG_USES_STATIC_BUF +#define IP_FRAG_USES_STATIC_BUF 0 +#endif + +/** + * Defines the assumed maximum MTU on any interface for IP fragment buffer + * (requires IP_FRAG_USES_STATIC_BUF==1).This is not a configurable value. + */ +#if IP_FRAG_USES_STATIC_BUF && !defined(IP_FRAG_MAX_MTU) +#define IP_FRAG_MAX_MTU 1500 + +#endif +/* As per RFC 791, "Every internet module must be able to forward a datagram of 68 + * octets without further fragmentation. This is because an internet header + * may be up to 60 octets, and the minimum fragment is 8 octets." */ +#if IP_FRAG_USES_STATIC_BUF && !defined(IP_FRAG_MIN_MTU) +#define IP_FRAG_MIN_MTU 68 +#endif + +/** IP_DEFAULT_TTL: Defines the default value for Time-To-Live used by transport layers. + */ +#if !defined IP_DEFAULT_TTL || defined __DOXYGEN__ +#define IP_DEFAULT_TTL 255 +#endif + +/** + * IP_SOF_BROADCAST=1: Use the SOF_BROADCAST field to enable broadcast + * filter per pcb on udp and raw send operations. To enable broadcast filter + * on recv operations, you also have to set IP_SOF_BROADCAST_RECV=1. + */ +#if !defined IP_SOF_BROADCAST || defined __DOXYGEN__ +#define IP_SOF_BROADCAST 1 +#endif + +/** + * IP_SOF_BROADCAST_RECV (requires IP_SOF_BROADCAST=1) enables the broadcast + * filter on recv operations. + * @par Note + * This macro will affect the way of recving broadcast packets for IPv4 UDP + * and RAW socket. + * For IPv4 UDP socket: + * - Mode 1: The incoming broadcast packet whose destination IP address fully + * match the binding address will be accepted. Socket binding with ANY address + * can receive any broadcast packets. + * - Mode 2: The incoming broadcast packet whose destination IP address is on + * the same subnet of binding address will be accepted. Broadcast packet with + * 255.255.255.255 as destination will be accepted by all sockets. Socket + * bindng with ANY address will receive any broadcast packets. + * For IPv4 RAW socket: + * - Mode 1: The incoming broadcast packet whose destination IP address fully + * match the binding address will be accepted. Socket binding with ANY address + * can receive any broadcast packets. + * - Mode 2: Only socket binding with ANY address can receive broadcast packets. + * When this macro is disabled, both IPv4 UDP/RAW socket works on mode 2. + * When this macro is enabled and SO_BROADCAST is not enabled, both works on mode 1. + * When this macro is enalbed and SO_BROADCAST is enabled, both works on mode 2. + */ +#if !defined IP_SOF_BROADCAST_RECV || defined __DOXYGEN__ +#define IP_SOF_BROADCAST_RECV 1 +#endif + +/** + * IP_FORWARD_ALLOW_TX_ON_RX_NETIF==1: Allows ip_forward() to send packets back + * out on the netif where it was received. This should only be used for + * wireless networks. + * @par Note + * When this is 1, ensure that the netif driver correctly marks incoming + * link-layer-broadcast/multicast packets using the corresponding pbuf flags. + */ +#if !defined IP_FORWARD_ALLOW_TX_ON_RX_NETIF || defined __DOXYGEN__ +#define IP_FORWARD_ALLOW_TX_ON_RX_NETIF 0 +#endif + +/** + * @} + */ + +/* + ---------------------------------- + ---------- ICMP options ---------- + ---------------------------------- +*/ +/* + * @defgroup lwip_opts_icmp ICMP + * @ingroup lwip_opts_ipv4 + * @{ + */ +/** + * LWIP_ICMP==1: Enables the ICMP module inside the IP stack. + * Disabling this macro make your product non-compliant to RFC1122. + */ +#if !defined LWIP_ICMP || defined __DOXYGEN__ +#define LWIP_ICMP 1 +#endif + +/** + * Defines the default value for Time-To-Live used by ICMP packets. + */ +#if !defined ICMP_TTL || defined __DOXYGEN__ +#define ICMP_TTL (IP_DEFAULT_TTL) +#endif + +/** + * LWIP_BROADCAST_PING==1: Responds to broadcast pings (default is unicast only). + */ +#if !defined LWIP_BROADCAST_PING || defined __DOXYGEN__ +#define LWIP_BROADCAST_PING 0 +#endif + +/** + * LWIP_MULTICAST_PING==1: Respond to multicast pings (default allows multicast ping). + */ +#if !defined LWIP_MULTICAST_PING || defined __DOXYGEN__ +#define LWIP_MULTICAST_PING 1 +#endif +/** + * @} + */ + +/** + * DRIVER_STATUS_CHECK =0. If enabled can create low performance + * Usage should be avoided. + */ +#ifndef DRIVER_STATUS_CHECK +#define DRIVER_STATUS_CHECK 0 +#endif + +/** + * DRIVER_WAKEUP_INTERVAL = 120000. Not a configurable value. + */ +#if DRIVER_STATUS_CHECK +#ifndef DRIVER_WAKEUP_INTERVAL +#define DRIVER_WAKEUP_INTERVAL 120000 +#endif +#endif + +/* netif ifindex MUST NOT start from 0 as this value means no netif was bond to sockets */ +/** + * LWIP_NETIF_IFINDEX_START==1: Defines the start index of the interface list. + * Not a configurable value. + */ +#ifndef LWIP_NETIF_IFINDEX_START +#define LWIP_NETIF_IFINDEX_START 1 +#endif /* LWIP_NETIF_IFINDEX_START */ + +/** + * LWIP_NETIF_IFINDEX_MAX==10: Defines the start index of the interface list. + * Not a configurable value. + */ +#ifndef LWIP_NETIF_IFINDEX_MAX +#define LWIP_NETIF_IFINDEX_MAX 0xFE +#endif + +/* + --------------------------------- + ---------- RAW options ---------- + --------------------------------- +*/ +/* + * @defgroup lwip_opts_raw RAW + * @ingroup lwip_opts_callback + * @{ + */ +/** + * LWIP_RAW==1: Enables the application layer to hook into the IP layer itself. + */ +#if !defined LWIP_RAW || defined __DOXYGEN__ +#define LWIP_RAW 1 +#endif + +/** + * LWIP_RAW==1: Enables the application layer to hook into the IP layer itself. + */ +#if !defined RAW_TTL || defined __DOXYGEN__ +#define RAW_TTL (IP_DEFAULT_TTL) +#endif +/** + * @} + */ + +/** + * If PF_PKT_SUPPORT==1 Enables support for PF packet raw sockets. + * Requires LWIP_RAW ==1 to be enabled. + */ +#if LWIP_RAW +#ifndef PF_PKT_SUPPORT +#define PF_PKT_SUPPORT 1 +#endif +#else +#undef PF_PKT_SUPPORT +#define PF_PKT_SUPPORT 0 +#endif + +/** + * If LWIP_NETIF_PROMISC==1 Enables the promiscuous mode of the netif. + * Requires PF_PKT_SUPPORT ==1 to be enabled. + */ +#if PF_PKT_SUPPORT +#ifndef LWIP_NETIF_PROMISC +#define LWIP_NETIF_PROMISC 1 +#endif +#else +#ifndef LWIP_NETIF_PROMISC +#define LWIP_NETIF_PROMISC 0 +#endif +#endif + +/* + ---------------------------------- + ---------- DHCP options ---------- + ---------------------------------- +*/ +/* + * @defgroup lwip_opts_dhcp DHCP + * @ingroup lwip_opts_ipv4 + * @{ + */ +/** + * LWIP_DHCP==1: Enables the DHCP module. + */ +#if !defined LWIP_DHCP || defined __DOXYGEN__ +#define LWIP_DHCP 0 +#endif +#if !LWIP_IPV4 +/* disable DHCP when IPv4 is disabled */ +#undef LWIP_DHCP +#define LWIP_DHCP 0 +#endif /* !LWIP_IPV4 */ + +/** + * If LWIP_DHCPS==1: Enables the DHCP server handling. + * Requires LWIP_DHCP ==1 to be enabled. + */ +#if !defined LWIP_DHCPS || defined __DOXYGEN__ +#if LWIP_DHCP +#define LWIP_DHCPS 1 +#else +#define LWIP_DHCPS 0 +#endif +#endif + +#if (defined LWIP_DHCPS) && (LWIP_DHCPS) && (LWIP_DNS) +#define LWIP_DHCPS_DNS_OPTION 1 +#endif /* LWIP_DHCPS */ + +/** + * DHCP_DOES_ARP_CHECK==1: Does an ARP check on the offered address. + */ +#if !defined DHCP_DOES_ARP_CHECK || defined __DOXYGEN__ +#define DHCP_DOES_ARP_CHECK ((LWIP_DHCP) && (LWIP_ARP)) +#endif + +/** + * LWIP_DHCP_BOOTP_FILE==1: Stores offered_si_addr and boot_file_name. + */ +#if !defined LWIP_DHCP_BOOTP_FILE || defined __DOXYGEN__ +#define LWIP_DHCP_BOOTP_FILE 0 +#endif + +/** + * LWIP_DHCP_VENDOR_CLASS_IDENTIFIER==1: use DHCP_OPTION_VCI into DHCP message. + */ +#ifndef LWIP_DHCP_VENDOR_CLASS_IDENTIFIER +#define LWIP_DHCP_VENDOR_CLASS_IDENTIFIER 1 +#endif + +/** + * LWIP_DHCP_GETS_NTP==1: Requests NTP servers with discover/select. For each + * response packet, a callback is called, which has to be provided by the port: + * void dhcp_set_ntp_servers(u8_t num_ntp_servers, ip_addr_t* ntp_server_addrs); +*/ +#if !defined LWIP_DHCP_GET_NTP_SRV || defined __DOXYGEN__ +#define LWIP_DHCP_GET_NTP_SRV 0 +#endif + +/** + * The maximum of NTP servers requested. + */ +#if !defined LWIP_DHCP_MAX_NTP_SERVERS || defined __DOXYGEN__ +#define LWIP_DHCP_MAX_NTP_SERVERS 1 +#endif + +/** + * LWIP_DHCP_MAX_DNS_SERVERS > 0: Requests the DNS servers with discover/select. + * DHCP servers received in the response are passed to DNS via @ref dns_setserver() + * (up to the maximum limit defined here). + */ +#if !defined LWIP_DHCP_MAX_DNS_SERVERS || defined __DOXYGEN__ +#define LWIP_DHCP_MAX_DNS_SERVERS DNS_MAX_SERVERS +#endif +/** + * @} + */ + +/* + ------------------------------------ + ---------- AUTOIP options ---------- + ------------------------------------ +*/ +/* + * @defgroup lwip_opts_autoip AUTOIP + * @ingroup lwip_opts_ipv4 + * @{ + */ +/** + * LWIP_AUTOIP==1: Enable AUTOIP module. + */ +#if !defined LWIP_AUTOIP || defined __DOXYGEN__ +#define LWIP_AUTOIP 0 +#endif +#if !LWIP_IPV4 +/* disable AUTOIP when IPv4 is disabled */ +#undef LWIP_AUTOIP +#define LWIP_AUTOIP 0 +#endif /* !LWIP_IPV4 */ + +/** + * LWIP_DHCP_AUTOIP_COOP==1: Allow DHCP and AUTOIP to be both enabled on + * the same interface at the same time. + */ +#if !defined LWIP_DHCP_AUTOIP_COOP || defined __DOXYGEN__ +#define LWIP_DHCP_AUTOIP_COOP 0 +#endif + +/** + * LWIP_DHCP_AUTOIP_COOP_TRIES: Defines the number of DHCP DISCOVER probes + * that should be sent before falling back on AUTOIP (the DHCP client keeps + * running in this case). This can be set as low as 1 to get an AutoIP address + * very quickly, but you should be prepared to handle a changing IP address + * when DHCP overrides AutoIP. + */ +#if !defined LWIP_DHCP_AUTOIP_COOP_TRIES || defined __DOXYGEN__ +#define LWIP_DHCP_AUTOIP_COOP_TRIES 64 +#endif +/** + * @} + */ + +/* + ---------------------------------- + ----- SNMP MIB2 support ----- + ---------------------------------- +*/ +/* + * @defgroup lwip_opts_mib2 SNMP MIB2 callbacks + * @ingroup lwip_opts_infrastructure + * @{ + */ +/** + * LWIP_MIB2_CALLBACKS==1: Turns on SNMP MIB2 callbacks. + * Turn this on to get callbacks needed to implement MIB2. + * Usually MIB2_STATS should also be enabled. + */ +#if !defined LWIP_MIB2_CALLBACKS || defined __DOXYGEN__ +#define LWIP_MIB2_CALLBACKS 0 +#endif +/** + * @} + */ + +/* + ---------------------------------- + -------- Multicast options ------- + ---------------------------------- +*/ +/** + * @defgroup lwip_opts_multicast Multicast + * @ingroup lwip_opts_infrastructure + * @{ + */ +/** + * LWIP_MULTICAST_TX_OPTIONS==1: Enable multicast TX support like the socket options + * IP_MULTICAST_TTL/IP_MULTICAST_IF/IP_MULTICAST_LOOP, as well as (currently only) + * core support for the corresponding IPv6 options. + */ +#if !defined LWIP_MULTICAST_TX_OPTIONS || defined __DOXYGEN__ +#define LWIP_MULTICAST_TX_OPTIONS ((LWIP_IGMP || LWIP_IPV6_MLD) && LWIP_UDP) +#endif +/** + * @} + */ + +/* + ---------------------------------- + ---------- IGMP options ---------- + ---------------------------------- +*/ +/** + * @defgroup lwip_opts_igmp IGMP + * @ingroup lwip_opts_ipv4 + * @{ + */ +/** + * LWIP_IGMP==1: Turns on IGMP module. + */ +#if !defined LWIP_IGMP || defined __DOXYGEN__ +#define LWIP_IGMP 0 +#endif +#if !LWIP_IPV4 +#undef LWIP_IGMP +#define LWIP_IGMP 0 +#endif + +/** + * times to send IGMP report messages + * may increase this value depend on the packet loss rate + */ +#ifndef LWIP_IGMP_REPORT_TIMES +#define LWIP_IGMP_REPORT_TIMES 2 +#endif +/** + * @} + */ + +/* + ---------------------------------- + ---------- DNS options ----------- + ---------------------------------- +*/ +/* + * @defgroup lwip_opts_dns DNS + * @ingroup lwip_opts_callback + * @{ + */ +/** + * LWIP_DNS==1: Turn on DNS module. UDP must be available for DNS + * transport. + */ +#if !defined LWIP_DNS || defined __DOXYGEN__ +#define LWIP_DNS 0 +#endif + +/** Defines the maximum number of DNS entries to maintain locally. */ +#if !defined DNS_TABLE_SIZE || defined __DOXYGEN__ +#define DNS_TABLE_SIZE 4 +#endif + +/** Defines the maximum DNS host name length supported in the name table. */ +#if !defined DNS_MAX_NAME_LENGTH || defined __DOXYGEN__ +#define DNS_MAX_NAME_LENGTH 256 +#endif + +/** Defines the maximum of DNS servers. + * The first server can be initialized automatically by defining + * DNS_SERVER_ADDRESS(ipaddr), where 'ipaddr' is an 'ip_addr_t*' + */ +#if !defined DNS_MAX_SERVERS || defined __DOXYGEN__ +#define DNS_MAX_SERVERS 2 +#endif + +/** Defines the maximum number of IP addresses supported.**/ +#ifndef DNS_MAX_IPADDR +#define DNS_MAX_IPADDR 10 +#endif + +/** Defines the maximum DNS label length as per RFC. **/ +#ifndef DNS_MAX_LABEL_LENGTH +#define DNS_MAX_LABEL_LENGTH 63 +#endif + +/** Defines whether DNS does a name checking between the query and the response. */ +#if !defined DNS_DOES_NAME_CHECK || defined __DOXYGEN__ +#define DNS_DOES_NAME_CHECK 1 +#endif + +/** Controls the security level of the DNS implementation + * Use all DNS security features by default. + * This is overridable but should only be needed by very small targets + * or when using against non-standard DNS servers. */ +#if !defined LWIP_DNS_SECURE || defined __DOXYGEN__ +#define LWIP_DNS_SECURE (LWIP_DNS_SECURE_RAND_XID | LWIP_DNS_SECURE_NO_MULTIPLE_OUTSTANDING | LWIP_DNS_SECURE_RAND_SRC_PORT) +#endif + +/* A list of DNS security features follows */ +#define LWIP_DNS_SECURE_RAND_XID 1 +#define LWIP_DNS_SECURE_NO_MULTIPLE_OUTSTANDING 2 +#define LWIP_DNS_SECURE_RAND_SRC_PORT 4 + +/** Implements a local host-to-address list. If enabled, you must define an initializer: + * \#define DNS_LOCAL_HOSTLIST_INIT {DNS_LOCAL_HOSTLIST_ELEM("host_ip4", IPADDR4_INIT_BYTES(1,2,3,4)), \ + * DNS_LOCAL_HOSTLIST_ELEM("host_ip6", IPADDR6_INIT_HOST(123, 234, 345, 456)} + * + * Instead, you can also use an external function: + * \#define DNS_LOOKUP_LOCAL_EXTERN(x) + * extern err_t my_lookup_function(const char *name, ip_addr_t *addr, u8_t dns_addrtype) + * that looks up the IP address and returns ERR_OK if found (LWIP_DNS_ADDRTYPE_xxx is passed in dns_addrtype). + */ +#if !defined DNS_LOCAL_HOSTLIST || defined __DOXYGEN__ +#define DNS_LOCAL_HOSTLIST 0 +#endif /* DNS_LOCAL_HOSTLIST */ + +/** If this macro is enabled, the local host-list can be dynamically changed + * at runtime. */ +#if !defined DNS_LOCAL_HOSTLIST_IS_DYNAMIC || defined __DOXYGEN__ +#define DNS_LOCAL_HOSTLIST_IS_DYNAMIC 0 +#endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */ + +/** Set this macro to 1 to enable querying ".local" names via mDNS + * using a One-Shot Multicast DNS Query */ +#if !defined LWIP_DNS_SUPPORT_MDNS_QUERIES || defined __DOXYGEN__ +#define LWIP_DNS_SUPPORT_MDNS_QUERIES 0 +#endif +/** + * @} + */ + +/* + ---------------------------------- + ---------- SNTP options ---------- + ---------------------------------- +*/ +/** + * LWIP_SNTP==1: Enables the SNTP module. + */ + +#ifndef LWIP_SNTP +#define LWIP_SNTP 0 +#endif + +#ifndef LWIP_6LOWPAN +#define LWIP_6LOWPAN 0 +#endif + +#ifndef ETH_6LOWPAN +#define ETH_6LOWPAN 0 +#endif + +#ifndef LWIP_ETH_6LOWPAN_ENABLE +#define LWIP_ETH_6LOWPAN_ENABLE 0 +#endif + +/* + --------------------------------- + ---------- UDP options ---------- + --------------------------------- +*/ +/* + * @defgroup lwip_opts_udp UDP + * @ingroup lwip_opts_callback + * @{ + */ +/** + * LWIP_UDP==1: Enables UDP. + */ +#if !defined LWIP_UDP || defined __DOXYGEN__ +#define LWIP_UDP 1 +#endif + +/** + * LWIP_UDPLITE==1: Enables UDP-Lite. (Requires LWIP_UDP) + */ +#if !defined LWIP_UDPLITE || defined __DOXYGEN__ +#define LWIP_UDPLITE 0 +#endif + +/** + * Defines the default Time-To-Live value. + */ +#if !defined UDP_TTL || defined __DOXYGEN__ +#define UDP_TTL (IP_DEFAULT_TTL) +#endif + +/** + * Appends destination addr and port to every netbuf. + */ +#if !defined LWIP_NETBUF_RECVINFO || defined __DOXYGEN__ +#define LWIP_NETBUF_RECVINFO 0 +#endif +/** + * @} + */ + +/* + --------------------------------- + ---------- TCP options ---------- + --------------------------------- +*/ +/* + * @defgroup lwip_opts_tcp TCP + * @ingroup lwip_opts_callback + * @{ + */ +/** + + * Defines whether to enable TCP. + */ +#if !defined LWIP_TCP || defined __DOXYGEN__ +#define LWIP_TCP 1 +#endif + +/** + * @ingroup Config_TCP + * Defines the default Time-To-Live value. + */ +#if !defined TCP_TTL || defined __DOXYGEN__ +#define TCP_TTL (IP_DEFAULT_TTL) +#endif +/** +* @ingroup Config_TCP + * Defines the TCP Maximum segment size. + * For the receive side, this MSS is advertised to the remote side + * when opening a connection. For the transmit size, this MSS sets + * an upper limit on the MSS advertised by the remote host. + */ +/* TCP Maximum segment size. */ +#ifdef LWIP_TCP_MSS +#undef TCP_MSS /* ensure TCP_MSS value is overridden by LWIP_TCP_MSS */ +#define TCP_MSS LWIP_TCP_MSS +#else /* LWIP_TCP_MSS */ +#ifndef TCP_MSS +#define TCP_MSS (IP_FRAG_MAX_MTU - 20 - 20) +#endif /* TCP_MSS */ +#endif /* LWIP_TCP_MSS */ + +/** + * @ingroup Config_TCP + * Defines the size of a TCP receive window. This must be at least + * (2 * TCP_MSS). + * @par Note + * When using TCP_RCV_SCALE, TCP_WND is the total size + * with scaling applied. Maximum window value in the TCP header + * will be TCP_WND >> TCP_RCV_SCALE. + */ +#if !defined TCP_WND || defined __DOXYGEN__ +#define TCP_WND (4 * TCP_MSS) +#endif + +/** + * Defines the minimum TTL value. This value cannot be less than 8. + */ +#ifndef TCP_TTL_MIN_VALUE +#define TCP_TTL_MIN_VALUE 8 +#endif + +/** + * Defines the maximum value of the RTO duration. This value must be at least 60 seconds. + */ +#ifndef TCP_MAX_RTO_DURATION +#define TCP_MAX_RTO_DURATION 60000 +#endif + +/** + * Defines the maximum number of retransmissions. This value must not be less than 3. + */ +#ifndef TCP_MAXRTX_MIN_VALUE +#define TCP_MAXRTX_MIN_VALUE 3 +#endif + +/** + * @ingroup Config_TCP + * Defines the maximum number of retransmissions of data segments. + */ +#if !defined TCP_MAXRTX || defined __DOXYGEN__ +#define TCP_MAXRTX 15 +#endif + +/** + * Defines the maximum number of retransmissions of SYN segments. + */ +#if !defined TCP_SYNMAXRTX || defined __DOXYGEN__ +#define TCP_SYNMAXRTX 6 +#endif + +/** + * Defines the Maximum number of retransmissions of data segments in FIN_WAIT_1 or CLOSING. + */ +#ifndef TCP_FW1MAXRTX +#define TCP_FW1MAXRTX 8 +#endif + +/** + * TCP_QUEUE_OOSEQ==1: TCP will queue segments that arrive out of order. + * Define to 0 if your device is low on memory. + */ +#if !defined TCP_QUEUE_OOSEQ || defined __DOXYGEN__ +#define TCP_QUEUE_OOSEQ (LWIP_TCP) +#endif + +/** + * TCP_CALCULATE_EFF_SEND_MSS: "The maximum size of a segment that TCP really + * sends, the 'effective send MSS,' MUST be the smaller of the send MSS (which + * reflects the available reassembly buffer size at the remote host) and the + * largest size permitted by the IP layer" (RFC 1122) + * Setting this to 1 enables code that checks TCP_MSS against the MTU of the + * netif used for a connection and limits the MSS if it would be too big otherwise. + */ +#if !defined TCP_CALCULATE_EFF_SEND_MSS || defined __DOXYGEN__ +#define TCP_CALCULATE_EFF_SEND_MSS 1 +#endif + +/** + * @ingroup Config_TCP + * Defines the TCP sender buffer space in bytes. + * To achieve good performance, this should be at least 2 * TCP_MSS. + */ +#if !defined TCP_SND_BUF || defined __DOXYGEN__ +#define TCP_SND_BUF (2 * TCP_MSS) +#endif + +/** + * TCP_SND_QUEUELEN: TCP sender buffer space (pbufs). This must be at least + * as much as (2 * TCP_SND_BUF/TCP_MSS) for things to work. + */ +#if !defined TCP_SND_QUEUELEN || defined __DOXYGEN__ +#define TCP_SND_QUEUELEN ((4 * (TCP_SND_BUF) + ((TCP_MSS) - 1)) / (TCP_MSS)) +#endif + +/** + * TCP_OOSEQ_MAX_BYTES: The default maximum number of bytes queued on ooseq per + * pcb if TCP_OOSEQ_BYTES_LIMIT is not defined. Default is 0 (no limit). + * Only valid for TCP_QUEUE_OOSEQ==1. + */ +#if !defined TCP_OOSEQ_MAX_BYTES || defined __DOXYGEN__ +#define TCP_OOSEQ_MAX_BYTES 0 +#endif + +/** + * TCP_OOSEQ_BYTES_LIMIT(pcb): Return the maximum number of bytes to be queued + * on ooseq per pcb, given the pcb. Only valid for TCP_QUEUE_OOSEQ==1 && + * TCP_OOSEQ_MAX_BYTES==1. + * Use this to override TCP_OOSEQ_MAX_BYTES to a dynamic value per pcb. + */ +#if !defined TCP_OOSEQ_BYTES_LIMIT +#if TCP_OOSEQ_MAX_BYTES +#define TCP_OOSEQ_BYTES_LIMIT(pcb) TCP_OOSEQ_MAX_BYTES +#elif defined __DOXYGEN__ +#define TCP_OOSEQ_BYTES_LIMIT(pcb) +#endif +#endif + +/** + * TCP_OOSEQ_MAX_PBUFS: The default maximum number of pbufs queued on ooseq per + * pcb if TCP_OOSEQ_BYTES_LIMIT is not defined. Default is 0 (no limit). + * Only valid for TCP_QUEUE_OOSEQ==1. + */ +#if !defined TCP_OOSEQ_MAX_PBUFS || defined __DOXYGEN__ +#define TCP_OOSEQ_MAX_PBUFS 0 +#endif + +/** + * TCP_OOSEQ_PBUFS_LIMIT(pcb): Return the maximum number of pbufs to be queued + * on ooseq per pcb, given the pcb. Only valid for TCP_QUEUE_OOSEQ==1 && + * TCP_OOSEQ_MAX_PBUFS==1. + * Use this to override TCP_OOSEQ_MAX_PBUFS to a dynamic value per pcb. + */ +#if !defined TCP_OOSEQ_PBUFS_LIMIT +#if TCP_OOSEQ_MAX_PBUFS +#define TCP_OOSEQ_PBUFS_LIMIT(pcb) TCP_OOSEQ_MAX_PBUFS +#elif defined __DOXYGEN__ +#define TCP_OOSEQ_PBUFS_LIMIT(pcb) +#endif +#endif + +/** + * Defines whether to enable the backlog option for tcp listen pcb. + */ +#if !defined TCP_LISTEN_BACKLOG || defined __DOXYGEN__ +#define TCP_LISTEN_BACKLOG 1 +#endif + +/** + * Defines the maximum allowed backlog for TCP listen netconns. + * This backlog is used unless another is explicitly specified. + * 0xff is the maximum (u8_t). + */ +#if !defined TCP_DEFAULT_LISTEN_BACKLOG || defined __DOXYGEN__ +#define TCP_DEFAULT_LISTEN_BACKLOG 16 +#endif + +/** + * TCP_OVERSIZE: The maximum number of bytes that tcp_write may + * allocate ahead of time in an attempt to create shorter pbuf chains + * for transmission. The meaningful range is 0 to TCP_MSS. Some + * suggested values are: + * + * 0: Disable oversized allocation. Each tcp_write() allocates a new + pbuf (old behaviour). + * 1: Allocate size-aligned pbufs with minimal excess. Use this if your + * scatter-gather DMA requires aligned fragments. + * 128: Limit the pbuf/memory overhead to 20%. + * TCP_MSS: Try to create unfragmented TCP packets. + * TCP_MSS/4: Try to create 4 fragments or less per TCP packet. + */ +#if !defined TCP_OVERSIZE || defined __DOXYGEN__ +#define TCP_OVERSIZE TCP_MSS +#endif + +/** + * LWIP_TCP_TIMESTAMPS==1: Support the TCP timestamp option. + * The timestamp option is currently only used to help remote hosts, and it is not + * really used locally. Therefore, it is only enabled when a TS option is + * received in the initial SYN packet from a remote host. + */ +#if !defined LWIP_TCP_TIMESTAMPS || defined __DOXYGEN__ +#define LWIP_TCP_TIMESTAMPS 0 +#endif + +/** + * Defines the difference in window to trigger an + * explicit window update. + */ +#if !defined TCP_WND_UPDATE_THRESHOLD || defined __DOXYGEN__ +#define TCP_WND_UPDATE_THRESHOLD LWIP_MIN((TCP_WND / 4), (TCP_MSS * 4)) +#endif + +/** + * LWIP_EVENT_API and LWIP_CALLBACK_API: Only one of these should be set to 1. + * LWIP_EVENT_API==1: The user defines lwip_tcp_event() to receive all + * events (accept, sent, etc) that happen in the system. + * LWIP_CALLBACK_API==1: The PCB callback function is called directly + * for the event. This is the default and is not a configurable value. + */ +#if !defined(LWIP_EVENT_API) && !defined(LWIP_CALLBACK_API) || defined __DOXYGEN__ +#define LWIP_EVENT_API 0 +#define LWIP_CALLBACK_API 1 +#else +#ifndef LWIP_EVENT_API +#define LWIP_EVENT_API 0 +#endif +#ifndef LWIP_CALLBACK_API +#define LWIP_CALLBACK_API 0 +#endif +#endif + +/** + * LWIP_WND_SCALE and TCP_RCV_SCALE: + * Set LWIP_WND_SCALE to 1 to enable window scaling. + * Set TCP_RCV_SCALE to the desired scaling factor (shift count in the + * range of [0..14]). + * When LWIP_WND_SCALE is enabled but TCP_RCV_SCALE is 0, we can use a large + * send window while having a small receive window only. + */ +#if !defined LWIP_WND_SCALE || defined __DOXYGEN__ +#define LWIP_WND_SCALE 1 +#define TCP_RCV_SCALE 7 +#else +#if !defined TCP_RCV_SCALE || defined __DOXYGEN__ +#define TCP_RCV_SCALE 7 +#endif +#endif + +/** + * LWIP_TCP_PCB_NUM_EXT_ARGS: + * When this is > 0, every tcp pcb (including listen pcb) includes a number of + * additional argument entries in an array (see tcp_ext_arg_alloc_id) + */ +#if !defined LWIP_TCP_PCB_NUM_EXT_ARGS || defined __DOXYGEN__ +#define LWIP_TCP_PCB_NUM_EXT_ARGS 0 +#endif + +/** + * @} + */ + +/* + ---------------------------------- + ---------- Pbuf options ---------- + ---------------------------------- +*/ +/* + * @defgroup lwip_opts_pbuf PBUF + * @ingroup lwip_opts + * @{ + */ +/** + * Defines the number of bytes that should be allocated for a + * link level header. The default is 14, the standard value for + * Ethernet. + */ +#if !defined PBUF_LINK_HLEN || defined __DOXYGEN__ +#if defined LWIP_HOOK_VLAN_SET && !defined __DOXYGEN__ +#define PBUF_LINK_HLEN (18 + ETH_PAD_SIZE) +#else /* LWIP_HOOK_VLAN_SET */ +#define PBUF_LINK_HLEN (14 + ETH_PAD_SIZE) +#endif /* LWIP_HOOK_VLAN_SET */ +#endif + +/** + * Defines the number of bytes that should be allocated + * for an additional encapsulation header before Ethernet headers such as e.g. 802.11. + */ +#if !defined PBUF_LINK_ENCAPSULATION_HLEN || defined __DOXYGEN__ +#define PBUF_LINK_ENCAPSULATION_HLEN 0u +#endif + +/** + * Defines the size of each pbuf in the pbuf pool. The default is + * designed to accommodate single full size TCP frame in one pbuf, including + * TCP_MSS, IP header, and link header. + */ +#if !defined PBUF_POOL_BUFSIZE || defined __DOXYGEN__ +#define PBUF_POOL_BUFSIZE LWIP_MEM_ALIGN_SIZE((TCP_MSS) + 40 + (PBUF_LINK_ENCAPSULATION_HLEN) + (PBUF_LINK_HLEN)) +#endif +/** + * @} + */ + +/* + ------------------------------------------------ + ---------- Network Interfaces options ---------- + ------------------------------------------------ +*/ +/* + * @defgroup lwip_opts_netif NETIF + * @ingroup lwip_opts + * @{ + */ +/** + * @defgroup lwip_opts_netif NETIF + * @ingroup lwip_opts + * @{ + */ +/** + * LWIP_SINGLE_NETIF==1: use a single netif only. This is the common case for + * small real-life targets. Some code like routing etc. can be left out. + */ +#if !defined LWIP_SINGLE_NETIF || defined __DOXYGEN__ +#define LWIP_SINGLE_NETIF 0 +#endif + +/** + * LWIP_NETIF_HOSTNAME==1: Use DHCP_OPTION_HOSTNAME with netifs hostname + * field. + */ +#if !defined LWIP_NETIF_HOSTNAME || defined __DOXYGEN__ +#define LWIP_NETIF_HOSTNAME 1 +#endif + +/** + * LWIP_NETIF_HOSTNAME_DEFAULT: netif's hostname after init + * field.This is not a configurable value. + */ +#if !defined LWIP_NETIF_HOSTNAME_DEFAULT || defined __DOXYGEN__ +#define LWIP_NETIF_HOSTNAME_DEFAULT "DEFAULT" +#endif + +/** + * NETIF_HOSTNAME_MAX_LEN: Max length for buffer store the hostname string. + * The value should be 4 byte aligned and not exceed 256. The minimum value + * requirement is capable to store string of LWIP_NETIF_HOSTNAME_DEFAULT + * including tailing zero.This is not a configurable value. + */ +#if !defined NETIF_HOSTNAME_MAX_LEN || defined __DOXYGEN__ +#define NETIF_HOSTNAME_MAX_LEN 64U +#endif + +/** + * LWIP_NETIF_API==1: Support netif APIs (in netifapi.c) + */ +#if !defined LWIP_NETIF_API || defined __DOXYGEN__ +#define LWIP_NETIF_API 0 +#endif + +/** + * LWIP_NETIF_API==1: Support NBR Cache APIs (in netifapi.c) + */ +#if !defined LWIP_NETIF_NBR_CACHE_API || defined __DOXYGEN__ +#define LWIP_NETIF_NBR_CACHE_API 1 +#endif + +/** + * LWIP_NETIF_STATUS_CALLBACK==1: Support a callback function for wifi whenever + * at commaond ifconfig up/down. + */ +#if !defined LWIP_L2_NETDEV_STATUS_CALLBACK || defined __DOXYGEN__ +#define LWIP_L2_NETDEV_STATUS_CALLBACK 0 +#endif + + +/** + * LWIP_NETIF_STATUS_CALLBACK==1: Support a callback function whenever an interface + * changes its up/down status (That is, due to DHCP IP acquisition). + */ +#if !defined LWIP_NETIF_STATUS_CALLBACK || defined __DOXYGEN__ +#define LWIP_NETIF_STATUS_CALLBACK 0 +#endif + +/** + * LWIP_NETIF_EXT_STATUS_CALLBACK==1: Support an extended callback function + * for several netif related event that supports multiple subscribers. + * @see netif_ext_status_callback + */ +#ifndef LWIP_NETIF_EXT_STATUS_CALLBACK +#define LWIP_NETIF_EXT_STATUS_CALLBACK 1 +#endif + +/** + * LWIP_NETIF_LINK_CALLBACK==1: Supports a callback function from an interface + * whenever the link changes (That is, link down). + */ +#if !defined LWIP_NETIF_LINK_CALLBACK || defined __DOXYGEN__ +#define LWIP_NETIF_LINK_CALLBACK 0 +#endif + +#ifndef LWIP_NETIF_DEFAULT_LINK_DOWN +#define LWIP_NETIF_DEFAULT_LINK_DOWN 0 +#endif + +/** + * LWIP_IP_FILTER==1: Support define a IP(v4) filter rule by user. + */ +#ifndef LWIP_IP_FILTER +#define LWIP_IP_FILTER 1 +#endif + +/** + * LWIP_IPV6_FILTER==1: Support define a IPv6 filter rule by user. + */ +#ifndef LWIP_IPV6_FILTER +#define LWIP_IPV6_FILTER 1 +#endif + +/** + * LWIP_NETIF_REMOVE_CALLBACK==1: Supports a callback function that is called + * when a netif has been removed. + */ +#if !defined LWIP_NETIF_REMOVE_CALLBACK || defined __DOXYGEN__ +#define LWIP_NETIF_REMOVE_CALLBACK 0 +#endif + +/** + * LWIP_NETIF_HWADDRHINT==1: Cache link-layer-address hints, such as table + * indices, in struct netif. TCP and UDP can make use of this to prevent + * scanning the ARP table for every sent packet. While this is faster for big + * ARP tables or many concurrent connections, it might be counter productive + * if you have a tiny ARP table or if there never are concurrent connections. + */ +#if !defined LWIP_NETIF_HWADDRHINT || defined __DOXYGEN__ +#define LWIP_NETIF_HWADDRHINT 0 +#endif + +#if LWIP_NETIF_HWADDRHINT +#define LWIP_NETIF_USE_HINTS 1 +#else /* LWIP_NETIF_HWADDRHINT */ +#define LWIP_NETIF_USE_HINTS 0 +#endif /* LWIP_NETIF_HWADDRHINT */ + +/** + * LWIP_NETIF_TX_SINGLE_PBUF: If this is set to 1, lwIP tries to put all data + * to be sent into one single pbuf. This is for compatibility with DMA-enabled + * MACs that do not support scatter-gather. + * Note: This might involve CPU-memcpy before transmitting that would not + * be needed without this flag. Use this flag only if required. + * + * @note TCP and IP-frag do not work with this. + */ +#if !defined LWIP_NETIF_TX_SINGLE_PBUF || defined __DOXYGEN__ +#define LWIP_NETIF_TX_SINGLE_PBUF 1 +#endif /* LWIP_NETIF_TX_SINGLE_PBUF */ + +#if !defined LWIP_CHECK_ADDR_ALIGN || defined __DOXYGEN__ +#define LWIP_CHECK_ADDR_ALIGN 0 +#endif /* dLWIP_CHECK_ADDR_ALIGN */ + +/** + * LWIP_NUM_NETIF_CLIENT_DATA: Defines the number of clients that may store + * data in client_data member array of struct netif (max. 256). + */ +#if !defined LWIP_NUM_NETIF_CLIENT_DATA || defined __DOXYGEN__ +#define LWIP_NUM_NETIF_CLIENT_DATA 0 +#endif + +/** + * LWIP_NUM_NETIF_CLIENT_DATA: Defines the number of clients that may store + * data in client_data member array of struct netif. + */ +#if ! defined NETIF_USE_6BYTE_HWLEN_FOR_IEEE802154 || defined __DOXYGEN__ +#if (NETIF_MAX_HWADDR_LEN == 6) +#define NETIF_USE_6BYTE_HWLEN_FOR_IEEE802154 1 +#else +#define NETIF_USE_6BYTE_HWLEN_FOR_IEEE802154 0 +#endif +#endif + +/** + * @} + */ + +/* + ------------------------------------ + ---------- LOOPIF options ---------- + ------------------------------------ +*/ +/* + * @defgroup lwip_opts_loop Loopback interface + * @ingroup lwip_opts_netif + * @{ + */ +/** + * LWIP_HAVE_LOOPIF==1: Supports loop interface (127.0.0.1). + * This is only needed when no real netifs are available. If at least one other + * netif is available, loopback traffic uses this netif. + */ +#if !defined LWIP_HAVE_LOOPIF || defined __DOXYGEN__ +#define LWIP_HAVE_LOOPIF (LWIP_NETIF_LOOPBACK && !LWIP_SINGLE_NETIF) +#endif + +/** + * LWIP_LOOPIF_MULTICAST==1: Supports multicast/IGMP on loop interface (127.0.0.1). + */ +#if !defined LWIP_LOOPIF_MULTICAST || defined __DOXYGEN__ +#define LWIP_LOOPIF_MULTICAST 0 +#endif + +/** + * LWIP_NETIF_LOOPBACK==1: Supports sending packets with a destination IP + * address equal to the netif IP address, looping them back up the stack. + */ +#if !defined LWIP_NETIF_LOOPBACK || defined __DOXYGEN__ +#define LWIP_NETIF_LOOPBACK 0 +#endif + +/** + * Defines the maximum number of pbufs on queue for loopback + * sending for each netif. The default value is 0, which denotes disabling this option. + */ +#if !defined LWIP_LOOPBACK_MAX_PBUFS || defined __DOXYGEN__ +#define LWIP_LOOPBACK_MAX_PBUFS 0 +#endif + +/** + * Indicates whether threading is enabled in + * the system, as netifs must change how they behave depending on this setting + * for the LWIP_NETIF_LOOPBACK option to work. + * Setting this is needed to avoid reentering non-reentrant functions such as + * tcp_input(). + * LWIP_NETIF_LOOPBACK_MULTITHREADING==1: Indicates that the user is using a + * multithreaded environment such as tcpip.c. In this case, netif->input() + * is called directly. + * LWIP_NETIF_LOOPBACK_MULTITHREADING==0: Indicates a polling (or NO_SYS) setup. + * The packets are put on a list and netif_poll() must be called in + * the main application loop. + */ +#if !defined LWIP_NETIF_LOOPBACK_MULTITHREADING || defined __DOXYGEN__ +#define LWIP_NETIF_LOOPBACK_MULTITHREADING (!NO_SYS) +#endif +/** + * @} + */ + +/* + ------------------------------------ + ---------- Thread options ---------- + ------------------------------------ +*/ +/* + * @defgroup lwip_opts_thread Threading + * @ingroup lwip_opts_infrastructure + * @{ + */ +/** + * TCPIP_THREAD_NAME: The name assigned to the main tcpip thread. + */ +#if !defined TCPIP_THREAD_NAME || defined __DOXYGEN__ +#define TCPIP_THREAD_NAME "tcpip_thread" +#endif + +/** + * Defines the stack size used by the main tcpip thread. + * The stack size value itself is platform-dependent, but is passed to + * sys_thread_new() when the thread is created. + */ +#if !defined TCPIP_THREAD_STACKSIZE || defined __DOXYGEN__ +#define TCPIP_THREAD_STACKSIZE 0 +#endif + +/** + * Defines the priority assigned to the main tcpip thread. + * The priority value itself is platform-dependent, but is passed to + * sys_thread_new() when the thread is created. + */ +#if !defined TCPIP_THREAD_PRIO || defined __DOXYGEN__ +#define TCPIP_THREAD_PRIO 1 +#endif + +#ifndef LWIP_NETIF_ETHTOOL +#define LWIP_NETIF_ETHTOOL 1 +#endif +/** + * TCPIP_MBOX_SIZE: Defines the mailbox size for the tcpip thread messages. + * The queue size value itself is platform-dependent, but is passed to + * sys_mbox_new() when tcpip_init is called. + */ +#if !defined TCPIP_MBOX_SIZE || defined __DOXYGEN__ +#define TCPIP_MBOX_SIZE 0 +#endif + +/** + * Define this to something that triggers a watchdog. This is called from + * tcpip_thread after processing a message. + */ +#if !defined LWIP_TCPIP_THREAD_ALIVE || defined __DOXYGEN__ +#define LWIP_TCPIP_THREAD_ALIVE() +#endif + +/** + * Defines the name assigned to the slipif_loop thread. + */ +#if !defined SLIPIF_THREAD_NAME || defined __DOXYGEN__ +#define SLIPIF_THREAD_NAME "slipif_loop" +#endif + +/** + * Defines the stack size used by the slipif_loop thread. + * The stack size value itself is platform-dependent, but is passed to + * sys_thread_new() when the thread is created. + */ +#if !defined SLIPIF_THREAD_STACKSIZE || defined __DOXYGEN__ +#define SLIPIF_THREAD_STACKSIZE 0 +#endif + +/** + * Defines the priority assigned to the slipif_loop thread. + * The priority value itself is platform-dependent, but is passed to + * sys_thread_new() when the thread is created. + */ +#if !defined SLIPIF_THREAD_PRIO || defined __DOXYGEN__ +#define SLIPIF_THREAD_PRIO 1 +#endif + +/** + * DEFAULT_THREAD_NAME: The name assigned to any other lwIP thread. + */ +#if !defined DEFAULT_THREAD_NAME || defined __DOXYGEN__ +#define DEFAULT_THREAD_NAME "lwIP" +#endif + +/** + * Defines the stack size used by any other lwIP thread. + * The stack size value itself is platform-dependent, but is passed to + * sys_thread_new() when the thread is created. + */ +#if !defined DEFAULT_THREAD_STACKSIZE || defined __DOXYGEN__ +#define DEFAULT_THREAD_STACKSIZE 0 +#endif + +/** + * Defines the priority assigned to any other lwIP thread. + * The priority value itself is platform-dependent, but is passed to + * sys_thread_new() when the thread is created. + */ +#if !defined DEFAULT_THREAD_PRIO || defined __DOXYGEN__ +#define DEFAULT_THREAD_PRIO 1 +#endif + +/** + * Defines the mailbox size for the incoming packets on a + * NETCONN_RAW. The queue size value itself is platform-dependent, but is passed + * to sys_mbox_new() when the recvmbox is created. + */ +#if !defined DEFAULT_RAW_RECVMBOX_SIZE || defined __DOXYGEN__ +#define DEFAULT_RAW_RECVMBOX_SIZE 0 +#endif + +/** + * Defines the mailbox size for the incoming packets on a + * NETCONN_UDP. The queue size value itself is platform-dependent, but is passed + * to sys_mbox_new() when the recvmbox is created. + */ +#if !defined DEFAULT_UDP_RECVMBOX_SIZE || defined __DOXYGEN__ +#define DEFAULT_UDP_RECVMBOX_SIZE 0 +#endif + +/** + * Maximum size of a UDP RAW packet. + * Different memory alignment can limit max packet size. + * LWIP_MAX_UDP_RAW_SEND_SIZE not a configurable value. + */ +#if (MEM_MALLOC_DMA_ALIGN != 1) +#ifndef LWIP_MAX_UDP_RAW_SEND_SIZE +#define LWIP_MAX_UDP_RAW_SEND_SIZE 65332 +#endif /* LWIP_MAX_UDP_RAW_SEND_SIZE */ +#else +#ifndef LWIP_MAX_UDP_RAW_SEND_SIZE +#define LWIP_MAX_UDP_RAW_SEND_SIZE 65432 +#endif /* LWIP_MAX_UDP_RAW_SEND_SIZE */ +#endif /* (MEM_MALLOC_DMA_ALIGN != 1) */ + +/** + * Defines the mailbox size for the incoming packets on a + * NETCONN_TCP. The queue size value itself is platform-dependent, but is passed + * to sys_mbox_new() when the recvmbox is created. + */ +#if !defined DEFAULT_TCP_RECVMBOX_SIZE || defined __DOXYGEN__ +#define DEFAULT_TCP_RECVMBOX_SIZE 0 +#endif + +/** + * Defines the mailbox size for the incoming connections. + * The queue size value itself is platform-dependent, but is passed to + * sys_mbox_new() when the acceptmbox is created. + */ +#if !defined DEFAULT_ACCEPTMBOX_SIZE || defined __DOXYGEN__ +#define DEFAULT_ACCEPTMBOX_SIZE 0 +#endif +/** + * @} + */ +/** + * Defines the maximum mailbox size for the incoming packets on a + * NETCONN_*. make it small to save memory. + */ +#ifndef MAX_MBOX_SIZE +#define MAX_MBOX_SIZE 2048 +#endif + +/* + ---------------------------------------------- + ---------- Sequential layer options ---------- + ---------------------------------------------- +*/ +/* + * @defgroup lwip_opts_netconn Netconn + * @ingroup lwip_opts_threadsafe_apis + * @{ + */ +/** + * LWIP_NETCONN==1: Enables Netconn APIs (required to use api_lib.c) + */ +#if !defined LWIP_NETCONN || defined __DOXYGEN__ +#define LWIP_NETCONN 1 +#endif + +/** LWIP_TCPIP_TIMEOUT==1: Enables tcpip_timeout/tcpip_untimeout to create + * timers running in tcpip_thread from another thread. + */ +#if !defined LWIP_TCPIP_TIMEOUT || defined __DOXYGEN__ +#define LWIP_TCPIP_TIMEOUT 0 +#endif + +/** LWIP_NETCONN_SEM_PER_THREAD==1: Use one (thread-local) semaphore per + * thread calling socket/netconn functions instead of allocating one + * semaphore per netconn and per select. + * Note: A thread-local semaphore for API calls is needed in the following cases: + * - LWIP_NETCONN_THREAD_SEM_GET() returns a sys_sem_t* + * - LWIP_NETCONN_THREAD_SEM_ALLOC() creates the semaphore + * - LWIP_NETCONN_THREAD_SEM_FREE() frees the semaphore + * The latter 2 can be invoked up by calling netconn_thread_init()/netconn_thread_cleanup(). + * Ports may call these for threads created with sys_thread_new(). + */ +#if !defined LWIP_NETCONN_SEM_PER_THREAD || defined __DOXYGEN__ +#define LWIP_NETCONN_SEM_PER_THREAD 0 +#endif + +/** LWIP_NETCONN_FULLDUPLEX==1: Enables code that allows reading from one thread, + * writing from a second thread, and closing from a third thread at the same time. + */ +#if !defined LWIP_NETCONN_FULLDUPLEX || defined __DOXYGEN__ +#define LWIP_NETCONN_FULLDUPLEX 1 +#endif +/** + * @} + */ + +/* + ------------------------------------ + ---------- Socket options ---------- + ------------------------------------ +*/ +/* + * @defgroup lwip_opts_socket Sockets + * @ingroup lwip_opts_threadsafe_apis + * @{ + */ +/** + * LWIP_SOCKET==1: Enables Socket API (require to use sockets.c) + */ +#if !defined LWIP_SOCKET || defined __DOXYGEN__ +#define LWIP_SOCKET 1 +#endif + +/* LWIP_SOCKET_SET_ERRNO==1: Set errno when socket functions cannot complete + * successfully, as required by POSIX. Default is POSIX-compliant.Not a configurable value. + */ +#if !defined LWIP_SOCKET_SET_ERRNO || defined __DOXYGEN__ +#define LWIP_SOCKET_SET_ERRNO 1 +#endif + +/** + * LWIP_COMPAT_SOCKETS==1: Enables BSD-style sockets functions names through defines. \n + * LWIP_COMPAT_SOCKETS==2: Same as ==1 but correctly named functions are created. + * While this helps code completion, it might conflict with existing libraries. + * (only used if you use sockets.c) + */ +#if !defined LWIP_COMPAT_SOCKETS || defined __DOXYGEN__ +#define LWIP_COMPAT_SOCKETS 2 +#endif + +/** + * LWIP_POSIX_SOCKETS_IO_NAMES==1: Enables POSIX-style sockets functions names. + * Disable this option if you use a POSIX operating system that uses the same + * names (read, write & close). This option only used if you use sockets.c. + */ +#if !defined LWIP_POSIX_SOCKETS_IO_NAMES || defined __DOXYGEN__ +#define LWIP_POSIX_SOCKETS_IO_NAMES 0 +#endif + +/** + * LWIP_SOCKET_OFFSET==n: Increases the file descriptor number created by LwIP with n. + * This can be useful when there are multiple APIs which create file descriptors. + * When they all start with a different offset and you won't make them overlap you can + * reimplement read/write/close/ioctl/fnctl to send the requested action to the right + * library (sharing select will need more work though). + */ +#if !defined LWIP_SOCKET_OFFSET || defined __DOXYGEN__ +#define LWIP_SOCKET_OFFSET 0 +#endif + +/** + * LWIP_TCP_KEEPALIVE==1: Enable TCP_KEEPIDLE, TCP_KEEPINTVL, and TCP_KEEPCNT + * options processing. Note that TCP_KEEPIDLE and TCP_KEEPINTVL have to be set + * in seconds. (does not require sockets.c, and will affect tcp.c) + */ +#if !defined LWIP_TCP_KEEPALIVE || defined __DOXYGEN__ +#define LWIP_TCP_KEEPALIVE 1 +#endif + +/** + * LWIP_SO_SNDTIMEO==1: Enables send timeout for sockets/netconns and + * SO_SNDTIMEO processing. + */ +#if !defined LWIP_SO_SNDTIMEO || defined __DOXYGEN__ +#define LWIP_SO_SNDTIMEO 0 +#endif + +/** + * LWIP_SO_RCVTIMEO==1: Enables receive timeout for sockets/netconns and + * SO_RCVTIMEO processing. + */ +#if !defined LWIP_SO_RCVTIMEO || defined __DOXYGEN__ +#define LWIP_SO_RCVTIMEO 0 +#endif + +/** + * LWIP_SO_SNDRCVTIMEO_NONSTANDARD==1: SO_RCVTIMEO/SO_SNDTIMEO take an int + * (milliseconds, much like winsock does) instead of a struct timeval (default). + */ +#if !defined LWIP_SO_SNDRCVTIMEO_NONSTANDARD || defined __DOXYGEN__ +#define LWIP_SO_SNDRCVTIMEO_NONSTANDARD 0 +#endif + +/** + * LWIP_SO_RCVBUF==1: Enables SO_RCVBUF processing. + */ +#if !defined LWIP_SO_RCVBUF || defined __DOXYGEN__ +#define LWIP_SO_RCVBUF 0 +#endif + +/** + * Defines the default value for recv_bufsize if LWIP_SO_RCVBUF is used. + */ +#if !defined RECV_BUFSIZE_DEFAULT || defined __DOXYGEN__ +#define RECV_BUFSIZE_DEFAULT 65535 +#endif + +/** + * RECV_BUFSIZE_MIN =256 Defines the minimum buffer size required for SO_RCVBUF configuration. + * Value not configurable. + */ +#ifndef RECV_BUFSIZE_MIN +#define RECV_BUFSIZE_MIN 256 +#endif + +/** + * LWIP_SO_SNDBUF==1: Enables SO_SNDBUF processing. + * Currently, only TCP socket in CLOSED or ESTABLISHED state supports settung sndbuf. + */ +#ifndef LWIP_SO_SNDBUF +#define LWIP_SO_SNDBUF 1 +#endif + +/** + * SEND_BUFSIZE_MIN =TCP_MSS*2 Defines the minimum buffer size required for SO_SNDBUF configuration. + * Value not configurable. + */ +#ifndef SEND_BUFSIZE_MIN +#define SEND_BUFSIZE_MIN (TCP_MSS*2) +#endif + +/** + * SEND_BUFSIZE_MAX Defines the maximum buffer size allowed for SO_SNDBUF configuration. + * Value not configurable. + */ +#if LWIP_WND_SCALE +#ifndef SEND_BUFSIZE_MAX +#define SEND_BUFSIZE_MAX 0x40000 +#endif +#else +#ifndef SEND_BUFSIZE_MAX +#define SEND_BUFSIZE_MAX 65535 +#endif +#endif /* LWIP_WND_SCALE */ + +/** + * LWIP_SO_LINGER==1: Enable SO_LINGER processing. + */ +#if !defined LWIP_SO_LINGER || defined __DOXYGEN__ +#define LWIP_SO_LINGER 0 +#endif + +/** + * By default, TCP socket/netconn close waits 20 seconds max to send the FIN + */ +#if !defined LWIP_TCP_CLOSE_TIMEOUT_MS_DEFAULT || defined __DOXYGEN__ +#define LWIP_TCP_CLOSE_TIMEOUT_MS_DEFAULT 20000 +#endif + +/** + * SO_REUSE==1: Enables the SO_REUSEADDR option. + */ +#if !defined SO_REUSE || defined __DOXYGEN__ +#define SO_REUSE 0 +#endif + +/** + * SO_REUSE_RXTOALL==1: Passes a copy of incoming broadcast/multicast packets + * to all local matches if SO_REUSEADDR is turned on. + * Warning: This option adds a memcpy for every packet if passing to more than one PCB. + */ +#if !defined SO_REUSE_RXTOALL || defined __DOXYGEN__ +#define SO_REUSE_RXTOALL 1 +#endif + +/** + * LWIP_FIONREAD_LINUXMODE==0 (default): ioctl/FIONREAD returns the amount of + * pending data in the network buffer. This is the way Windows does it. It's + * the default for lwIP since it is smaller. + * LWIP_FIONREAD_LINUXMODE==1: ioctl/FIONREAD returns the size of the next + * pending datagram in bytes. This is the way Linux does it. This code is only + * here for compatibility. + */ +#if !defined LWIP_FIONREAD_LINUXMODE || defined __DOXYGEN__ +#define LWIP_FIONREAD_LINUXMODE 0 +#endif + +/** + * LWIP_SOCKET_SELECT==1 (default): enable select() for sockets (uses a netconn + * callback to keep track of events). + * This saves RAM (counters per socket) and code (netconn event callback), which + * should improve performance a bit). + */ +#if !defined LWIP_SOCKET_SELECT || defined __DOXYGEN__ +#define LWIP_SOCKET_SELECT 1 +#endif + +/** + * LWIP_SOCKET_POLL==0 (default): enable poll() for sockets (including + * struct pollfd, nfds_t, and constants) + */ +#if !defined LWIP_SOCKET_POLL || defined __DOXYGEN__ +#define LWIP_SOCKET_POLL 0 +#endif + +/** + * This will enable the network stack to use MAC layer security. At the + transport layer only UDP will be using this mac layer security. + */ +#if !defined LWIP_MAC_SECURITY || defined __DOXYGEN__ +#define LWIP_MAC_SECURITY 1 +#endif + +/** + * LWIP_SO_PRIORITY==1: Enable SO_PRIORITY processing. We don't support any priority queue at IP + layer. It just enables the user to inform the priority of application packets + to the mac layer. + */ +#if !defined LWIP_SO_PRIORITY || defined __DOXYGEN__ +#define LWIP_SO_PRIORITY 1 +#endif + +#if LWIP_SO_PRIORITY +#if LWIP_PLC +typedef s32_t prio_t; +#ifndef LWIP_PKT_PRIORITY_DEFAULT +#define LWIP_PKT_PRIORITY_DEFAULT 1 +#endif +#else +typedef u8_t prio_t; +#ifndef LWIP_PKT_PRIORITY_DEFAULT +#define LWIP_PKT_PRIORITY_DEFAULT LWIP_PKT_PRIORITY_MIN +#endif +#endif + +#ifndef LWIP_PKT_PRIORITY_MIN +#define LWIP_PKT_PRIORITY_MIN 0 +#endif + +#ifndef LWIP_PKT_PRIORITY_MAX +#define LWIP_PKT_PRIORITY_MAX 3 +#endif + +#ifndef LWIP_PKT_PRIORITY_CTRL +#define LWIP_PKT_PRIORITY_CTRL LWIP_PKT_PRIORITY_MAX +#endif + +#ifndef LWIP_PKT_PRIORITY_DHCP +#define LWIP_PKT_PRIORITY_DHCP LWIP_PKT_PRIORITY_MAX +#endif + +#ifndef LWIP_PKT_PRIORITY_DHCPS +#define LWIP_PKT_PRIORITY_DHCPS LWIP_PKT_PRIORITY_MAX +#endif + +#ifndef LWIP_PKT_PRIORITY_DHCP6 +#define LWIP_PKT_PRIORITY_DHCP6 LWIP_PKT_PRIORITY_MAX +#endif + +#ifndef LWIP_PKT_PRIORITY_DNS +#define LWIP_PKT_PRIORITY_DNS LWIP_PKT_PRIORITY_MAX +#endif + +#ifndef LWIP_PKT_PRIORITY_SNTP +#define LWIP_PKT_PRIORITY_SNTP LWIP_PKT_PRIORITY_MAX +#endif +#endif + +/** + * @} + */ + +/* + --------------------------------------- + ------------- Utitlity APIs --------------- + --------------------------------------- +*/ + +/** LWIP_ENABLE_LOS_SHELL_CMD==1 Enables shell utility functions */ +#if !defined LWIP_ENABLE_LOS_SHELL_CMD || defined __DOXYGEN__ +#define LWIP_ENABLE_LOS_SHELL_CMD 1 +#endif + +/** LWIP_SHELL_CMD_PING_RETRY_TIMES: Configuration value to determine how many times ping command has to send + echo msg */ +#if !defined LWIP_SHELL_CMD_PING_RETRY_TIMES || defined __DOXYGEN__ +#define LWIP_SHELL_CMD_PING_RETRY_TIMES 4 +#endif + +/** LWIP_SHELL_CMD_PING_TIMEOUT =2000 :Ping cmd waiting timeout (in millisec) to receive ping response */ +#if !defined LWIP_SHELL_CMD_PING_TIMEOUT || defined __DOXYGEN__ +#define LWIP_SHELL_CMD_PING_TIMEOUT 2000 +#endif + +/** LWIP_SHELL_CMD_PING_TIMEOUT: Ping cmd waiting timeout max(in millisec) to receive ping response */ +#if !defined LWIP_SHELL_CMD_PING_TIMEOUT_MAX || defined __DOXYGEN__ +#define LWIP_SHELL_CMD_PING_TIMEOUT_MAX 10000 +#endif + +/** LWIP_SHELL_CMD_PING_TIMEOUT: Ping cmd waiting timeout min(in millisec) to receive ping response */ +#if !defined LWIP_SHELL_CMD_PING_TIMEOUT_MIN || defined __DOXYGEN__ +#define LWIP_SHELL_CMD_PING_TIMEOUT_MIN 1000 +#endif + +/* + ---------------------------------------- + ---------- Statistics options ---------- + ---------------------------------------- +*/ +/* + * @defgroup lwip_opts_stats Statistics + * @ingroup lwip_opts_debug + * @{ + */ +/** + * LWIP_STATS==1: Enables statistics collection in lwip_stats. + */ +#if !defined LWIP_STATS || defined __DOXYGEN__ +#define LWIP_STATS 1 +#endif + +#if LWIP_STATS + +/** + * LWIP_STATS_DISPLAY==1: Compiles in the statistics output functions. + */ +#if !defined LWIP_STATS_DISPLAY || defined __DOXYGEN__ +#define LWIP_STATS_DISPLAY 0 +#endif + +/** + * LWIP_STATS_API==1: Compiles in the statistics API functions. + */ +#if !defined LWIP_STATS_API || defined __DOXYGEN__ +#define LWIP_STATS_API 1 +#endif + +/** + * LINK_STATS==1: Enables the link stats. + */ +#if !defined LINK_STATS || defined __DOXYGEN__ +#define LINK_STATS 1 +#endif + +/** + * ETHARP_STATS==1: Enables etharp stats. + */ +#if !defined ETHARP_STATS || defined __DOXYGEN__ +#define ETHARP_STATS (LWIP_ARP) +#endif + +/** + * IP_STATS==1: Enables IP stats. + */ +#if !defined IP_STATS || defined __DOXYGEN__ +#define IP_STATS 1 +#endif + +/** + * IPFRAG_STATS==1: Enables IP fragmentation stats. Default is + * on if using either frag or reass. + */ +#if !defined IPFRAG_STATS || defined __DOXYGEN__ +#define IPFRAG_STATS (IP_REASSEMBLY || IP_FRAG) +#endif + +/** + * ICMP_STATS==1: Enables ICMP stats. + */ +#if !defined ICMP_STATS || defined __DOXYGEN__ +#define ICMP_STATS 1 +#endif + +/** + * IGMP_STATS==1: Enable IGMP stats. + */ +#if !defined IGMP_STATS || defined __DOXYGEN__ +#define IGMP_STATS (LWIP_IGMP) +#endif + +/** + * UDP_STATS==1: Enables UDP stats. Default is on if + * UDP enabled, otherwise off. + */ +#if !defined UDP_STATS || defined __DOXYGEN__ +#define UDP_STATS (LWIP_UDP) +#endif + +/** + * TCP_STATS==1: Enables TCP stats. Default is on if TCP + * enabled, otherwise off. + */ +#if !defined TCP_STATS || defined __DOXYGEN__ +#define TCP_STATS (LWIP_TCP) +#endif + +/** + * MEM_STATS==1: Enables mem.c stats. + */ +#if !defined MEM_STATS || defined __DOXYGEN__ +#define MEM_STATS ((MEM_LIBC_MALLOC == 0) && (MEM_USE_POOLS == 0)) +#endif + +/** + * MEMP_STATS==1: Enables memp.c pool stats. + */ +#if !defined MEMP_STATS || defined __DOXYGEN__ +#define MEMP_STATS (MEMP_MEM_MALLOC == 0) +#endif + +/** + * SYS_STATS==1: Enables system stats (sem and mbox counts, etc). + */ +#if !defined SYS_STATS || defined __DOXYGEN__ +#define SYS_STATS (NO_SYS == 0) +#endif + +/** + * IP6_STATS==1: Enable IPv6 stats. + */ +#if !defined IP6_STATS || defined __DOXYGEN__ +#define IP6_STATS (LWIP_IPV6) +#endif + +/** + * ICMP6_STATS==1: Enables ICMP for IPv6 stats. + */ +#if !defined ICMP6_STATS || defined __DOXYGEN__ +#define ICMP6_STATS (LWIP_IPV6 && LWIP_ICMP6) +#endif + +/** + * IP6_FRAG_STATS==1: Enables IPv6 fragmentation stats. + */ +#if !defined IP6_FRAG_STATS || defined __DOXYGEN__ +#define IP6_FRAG_STATS (LWIP_IPV6 && (LWIP_IPV6_FRAG || LWIP_IPV6_REASS)) +#endif + +/** + * MLD6_STATS==1: Enables MLD for IPv6 stats. + */ +#if !defined MLD6_STATS || defined __DOXYGEN__ +#define MLD6_STATS (LWIP_IPV6 && LWIP_IPV6_MLD) +#endif + +/** + * ND6_STATS==1: Enables neighbor discovery for IPv6 stats. + */ +#if !defined ND6_STATS || defined __DOXYGEN__ +#define ND6_STATS (LWIP_IPV6) +#endif + +/** + * MIB2_STATS==1: Defines stats for SNMP MIB2. + */ +#if !defined MIB2_STATS || defined __DOXYGEN__ +#define MIB2_STATS 0 +#endif + +/** + * DHCP6_STATS==1: Enables stats for DHCPv6. + */ +#if !defined DHCP6_STATS || defined __DOXYGEN__ +#define DHCP6_STATS (LWIP_IPV6_DHCP6) +#endif + +#else + +#define LINK_STATS 0 +#define ETHARP_STATS 0 +#define IP_STATS 0 +#define IPFRAG_STATS 0 +#define ICMP_STATS 0 +#define IGMP_STATS 0 +#define UDP_STATS 0 +#define TCP_STATS 0 +#define MEM_STATS 0 +#define MEMP_STATS 0 +#define SYS_STATS 0 +#ifndef LWIP_STATS_DISPLAY +#define LWIP_STATS_DISPLAY 0 +#endif +#define IP6_STATS 0 +#define ICMP6_STATS 0 +#define IP6_FRAG_STATS 0 +#define MLD6_STATS 0 +#define ND6_STATS 0 +#define MIB2_STATS 0 +#define DHCP6_STATS 0 + +#endif /* LWIP_STATS */ +/** + * @} + */ + +/* + ---------------------------------- + ---------- BIRDGE options ----------- + ---------------------------------- +*/ +/** + * BRIDGE_SUPPORT==1: Turns on BRIDGE module. + */ +#ifndef BRIDGE_SUPPORT +#define BRIDGE_SUPPORT 1 +#endif + +/* + -------------------------------------- + ---------- Checksum options ---------- + -------------------------------------- +*/ +/* + * @defgroup lwip_opts_checksum Checksum + * @ingroup lwip_opts_infrastructure + * @{ + */ +/** + * LWIP_CHECKSUM_CTRL_PER_NETIF==1: Checksum generation/check can be enabled/disabled + * per netif. + * Note: If enabled, the CHECKSUM_GEN_* and CHECKSUM_CHECK_* defines must be enabled. + */ +#if !defined LWIP_CHECKSUM_CTRL_PER_NETIF || defined __DOXYGEN__ +#define LWIP_CHECKSUM_CTRL_PER_NETIF 0 +#endif + +/** + * CHECKSUM_GEN_IP==1: Generates checksums in software for outgoing IP packets. + */ +#if !defined CHECKSUM_GEN_IP || defined __DOXYGEN__ +#define CHECKSUM_GEN_IP 1 +#endif + +/** + * CHECKSUM_GEN_UDP==1: Generates checksums in software for outgoing UDP packets. + */ +#if !defined CHECKSUM_GEN_UDP || defined __DOXYGEN__ +#define CHECKSUM_GEN_UDP 1 +#endif + +/** + * CHECKSUM_GEN_TCP==1: Generates checksums in software for outgoing TCP packets. + */ +#if !defined CHECKSUM_GEN_TCP || defined __DOXYGEN__ +#define CHECKSUM_GEN_TCP 1 +#endif + +/** + * CHECKSUM_GEN_ICMP==1: Generates checksums in software for outgoing ICMP packets. + */ +#if !defined CHECKSUM_GEN_ICMP || defined __DOXYGEN__ +#define CHECKSUM_GEN_ICMP 1 +#endif + +/** + * CHECKSUM_GEN_ICMP6==1: Generates checksums in software for outgoing ICMP6 packets. + */ +#if !defined CHECKSUM_GEN_ICMP6 || defined __DOXYGEN__ +#define CHECKSUM_GEN_ICMP6 1 +#endif + +/** + * CHECKSUM_CHECK_IP==1: Checks checksums in software for incoming IP packets. + */ +#if !defined CHECKSUM_CHECK_IP || defined __DOXYGEN__ +#define CHECKSUM_CHECK_IP 1 +#endif + +/** + * CHECKSUM_CHECK_UDP==1: Checks checksums in software for incoming UDP packets. + */ +#if !defined CHECKSUM_CHECK_UDP || defined __DOXYGEN__ +#define CHECKSUM_CHECK_UDP 1 +#endif + +/** + * CHECKSUM_CHECK_TCP==1: Checks checksums in software for incoming TCP packets. + */ +#if !defined CHECKSUM_CHECK_TCP || defined __DOXYGEN__ +#define CHECKSUM_CHECK_TCP 1 +#endif + +/** + * CHECKSUM_CHECK_ICMP==1: Checks checksums in software for incoming ICMP packets. + */ +#if !defined CHECKSUM_CHECK_ICMP || defined __DOXYGEN__ +#define CHECKSUM_CHECK_ICMP 1 +#endif + +/** + * CHECKSUM_CHECK_ICMP6==1: Checks checksums in software for incoming ICMPv6 packets + */ +#if !defined CHECKSUM_CHECK_ICMP6 || defined __DOXYGEN__ +#define CHECKSUM_CHECK_ICMP6 1 +#endif + +/** + * LWIP_CHECKSUM_ON_COPY==1: Calculates the checksum when copying data from + * application buffers to pbufs. + */ +#if !defined LWIP_CHECKSUM_ON_COPY || defined __DOXYGEN__ +#define LWIP_CHECKSUM_ON_COPY 1 +#endif + +/** + * LWIP_TX_CSUM_OFFLOAD==1: Allows TX checksum offload + */ +#ifndef LWIP_TX_CSUM_OFFLOAD +#define LWIP_TX_CSUM_OFFLOAD 0 +#endif +/** + * @} + */ + +/* + --------------------------------------- + ---------- Common options --------------- + --------------------------------------- +*/ +/** + * LWIP_ENABLE_IP_CONFLICT_SIGNAL==1: Enables IP conflict detection + */ +#ifndef LWIP_ENABLE_IP_CONFLICT_SIGNAL +#define LWIP_ENABLE_IP_CONFLICT_SIGNAL 1 +#endif + +/* + --------------------------------------- + ---------- IPv6 options --------------- + --------------------------------------- +*/ +/* + * @defgroup lwip_opts_ipv6 IPv6 + * @ingroup lwip_opts + * @{ + */ +#if !defined LWIP_ENABLE_ROUTER || defined __DOXYGEN__ +#define LWIP_ENABLE_ROUTER 1 +#endif + +#if !defined LWIP_LOWER_RSSI_THRESHOLD || defined __DOXYGEN__ +#define LWIP_LOWER_RSSI_THRESHOLD (-90) +#endif + +/** + * LWIP_IPV6==1: Enables IPv6. + */ +#if !defined LWIP_IPV6 || defined __DOXYGEN__ +#define LWIP_IPV6 1 +#endif + +/** + * IPV6_REASS_MAXAGE: Maximum time (in multiples of IP6_REASS_TMR_INTERVAL - so seconds, normally) + * a fragmented IP packet waits for all fragments to arrive. If not all fragments arrived + * in this time, the whole packet is discarded. + */ +#if !defined IPV6_REASS_MAXAGE || defined __DOXYGEN__ +#define IPV6_REASS_MAXAGE 3 +#endif + +/** + * LWIP_IPV6_SCOPES==1: Enable support for IPv6 address scopes, ensuring that + * e.g. link-local addresses are really treated as link-local. Disable this + * setting only for single-interface configurations. + */ +#if !defined LWIP_IPV6_SCOPES || defined __DOXYGEN__ +#define LWIP_IPV6_SCOPES 0 +#endif + +/** + * LWIP_IPV6_SCOPES_DEBUG==1: Perform run-time checks to verify that addresses + * are properly zoned (see ip6_zone.h on what that means) where it matters. + * Enabling this setting is highly recommended when upgrading from an existing + * installation that is not yet scope-aware; otherwise it may be too expensive. + */ +#if !defined LWIP_IPV6_SCOPES_DEBUG || defined __DOXYGEN__ +#define LWIP_IPV6_SCOPES_DEBUG 0 +#endif + +/** + * Defines the number of IPv6 addresses per netif. + */ +#if !defined LWIP_IPV6_NUM_ADDRESSES || defined __DOXYGEN__ +#define LWIP_IPV6_NUM_ADDRESSES 5 +#endif + +/** + * LWIP_IPV6_FORWARD==1: Forwards IPv6 packets across netifs. + */ +#if !defined LWIP_IPV6_FORWARD || defined __DOXYGEN__ +#define LWIP_IPV6_FORWARD 1 +#endif + +/** + * LWIP_IPV6_FRAG==1: Fragments outgoing IPv6 packets that are too big. + */ +#if !defined LWIP_IPV6_FRAG || defined __DOXYGEN__ +#define LWIP_IPV6_FRAG 1 +#endif + +/** + * LWIP_IPV6_REASS==1: Reassembles incoming IPv6 packets that fragmented. + */ +#if !defined LWIP_IPV6_REASS || defined __DOXYGEN__ +#define LWIP_IPV6_REASS (LWIP_IPV6) +#endif + +/** + * LWIP_IPV6_SEND_ROUTER_SOLICIT==1: Sends router solicitation messages during + * network startup. + */ +#if !defined LWIP_IPV6_SEND_ROUTER_SOLICIT || defined __DOXYGEN__ +#define LWIP_IPV6_SEND_ROUTER_SOLICIT 1 +#endif + +/** + * LWIP_IPV6_AUTOCONFIG==1: Enables stateless address autoconfiguration as per RFC 4862. + */ +#if !defined LWIP_IPV6_AUTOCONFIG || defined __DOXYGEN__ +#define LWIP_IPV6_AUTOCONFIG (LWIP_IPV6) +#endif + +#if !defined LWIP_IPV6_AUTOCONFIG_DEFAULT || defined __DOXYGEN__ +#define LWIP_IPV6_AUTOCONFIG_DEFAULT 0 +#endif + +/** + * LWIP_IPV6_ADDRESS_LIFETIMES==1: Keep valid and preferred lifetimes for each + * IPv6 address. Required for LWIP_IPV6_AUTOCONFIG. May still be enabled + * otherwise, in which case the application may assign address lifetimes with + * the appropriate macros. Addresses with no lifetime are assumed to be static. + * If this option is disabled, all addresses are assumed to be static. + */ +#if !defined LWIP_IPV6_ADDRESS_LIFETIMES || defined __DOXYGEN__ +#define LWIP_IPV6_ADDRESS_LIFETIMES LWIP_IPV6_AUTOCONFIG +#endif + +/** + * LWIP_IPV6_DUP_DETECT_ATTEMPTS=[0..7]: Defines the number of duplicate address detection attempts. + */ +#if !defined LWIP_IPV6_DUP_DETECT_ATTEMPTS || defined __DOXYGEN__ +#define LWIP_IPV6_DUP_DETECT_ATTEMPTS 1 +#endif + +/** + * LWIP_ADDR_EXPIRATION_ALLOWED==1: Allwos address expiration in neighbour discovery. + */ +#if !defined LWIP_ADDR_EXPIRATION_ALLOWED || defined __DOXYGEN__ +#define LWIP_ADDR_EXPIRATION_ALLOWED 1 +#endif + +/** + * @} + */ + +/* + * @defgroup lwip_opts_icmp6 ICMP6 + * @ingroup lwip_opts_ipv6 + * @{ + */ +/** + * LWIP_ICMP6==1: Enables ICMPv6 (mandatory per RFC) + */ +#if !defined LWIP_ICMP6 || defined __DOXYGEN__ +#define LWIP_ICMP6 (LWIP_IPV6) +#endif + +/** + * Defines the bytes from original packet to send back in + * ICMPv6 error messages. + */ +#if !defined LWIP_ICMP6_DATASIZE || defined __DOXYGEN__ +#define LWIP_ICMP6_DATASIZE 8 +#endif + +/** + * Defines the default hop limit for ICMPv6 messages. + */ +#if !defined LWIP_ICMP6_HL || defined __DOXYGEN__ +#define LWIP_ICMP6_HL 255 +#endif +/** + * @} + */ + +/* + * @defgroup lwip_opts_mld6 Multicast listener discovery + * @ingroup lwip_opts_ipv6 + * @{ + */ +/** + * LWIP_IPV6_MLD==1: Enables multicast listener discovery protocol. + * If LWIP_IPV6 is enabled, but this setting is disabled, the MAC layer must + * indiscriminately pass all inbound IPv6 multicast traffic to lwIP. + */ +#if !defined LWIP_IPV6_MLD || defined __DOXYGEN__ +#define LWIP_IPV6_MLD 0 +#endif +#if !LWIP_IPV6 +#undef LWIP_IPV6_MLD +#define LWIP_IPV6_MLD 0 +#endif + +/** + * LWIP_MLD6_ENABLE_MLD_ON_DAD==1:Enables sending MLD REPORT OR DONE for solicited node + address when state changes during neighbour discovery. + */ +#if !defined LWIP_MLD6_ENABLE_MLD_ON_DAD || defined __DOXYGEN__ +#define LWIP_MLD6_ENABLE_MLD_ON_DAD 0 +#endif +#if !LWIP_IPV6_MLD +#undef LWIP_MLD6_ENABLE_MLD_ON_DAD +#define LWIP_MLD6_ENABLE_MLD_ON_DAD 0 +#endif + +/** + * LWIP_MLD6_DONE_ONLYFOR_LAST_REPORTER==1:Enables sending MLD DONE only if the group + is the last listener on the interface for a specific multicast address. If group is not the last reporter + Done message will not be sent. By disabling the configuration, stack will send Done irrespective of the + last reporter flag. +RFC 2710 If the node's most recent Report message was suppressed by hearing another Report +message, it MAY send nothing, as it is highly likely that there is another listener +for that address still present on the same link. If this optimization is implemented +, it MUST be able to be turned off but SHOULD default to on. */ +#if !defined LWIP_MLD6_DONE_ONLYFOR_LAST_REPORTER || defined __DOXYGEN__ +#define LWIP_MLD6_DONE_ONLYFOR_LAST_REPORTER LWIP_IPV6 && LWIP_IPV6_MLD +#endif + +/** + * MEMP_NUM_MLD6_GROUP: Defines the maximum number of IPv6 multicast groups that can be joined. + * There must be enough groups so that each netif can join the solicited-node + * multicast group for each of its local addresses, plus one for MDNS if + * applicable, plus any number of groups to be joined on UDP sockets. + */ +#if !defined MEMP_NUM_MLD6_GROUP || defined __DOXYGEN__ +#define MEMP_NUM_MLD6_GROUP 4 +#endif + +/** LWIP_NETIF_IFINDEX_MAX_EX : The max value allowed for netif interface index: +* Not a configurable value. +*/ +/* As the ifindex variable is a uint8 value , restricting the number of index handled in the +interface identification API */ +#ifndef LWIP_NETIF_IFINDEX_MAX_EX +#define LWIP_NETIF_IFINDEX_MAX_EX LWIP_NETIF_NUM_MAX +#endif + +/** NETIF_NO_INDEX :The interface index 0 is an invalid index . Not a configurable value. */ +#ifndef NETIF_NO_INDEX +#define NETIF_NO_INDEX 0 +#endif + +/* RPL Options */ +#if !defined LWIP_RPL || defined __DOXYGEN__ +#define LWIP_RPL 0 +#endif + +/** + * @} + */ + +/* + * @defgroup lwip_opts_nd6 Neighbor discovery + * @ingroup lwip_opts_ipv6 + * @{ + */ +/** + * LWIP_ND6_QUEUEING==1: Queues outgoing IPv6 packets while MAC address + * is being resolved. + */ +#if !defined LWIP_ND6_QUEUEING || defined __DOXYGEN__ +#define LWIP_ND6_QUEUEING (LWIP_IPV6) +#endif + +/** + * Defines the maximum number of IPv6 packets to queue during MAC resolution. + */ +#if !defined MEMP_NUM_ND6_QUEUE || defined __DOXYGEN__ +#define MEMP_NUM_ND6_QUEUE 20 +#endif + +/** + * Defines the number of entries in IPv6 neighbor cache. + */ +#if !defined LWIP_ND6_NUM_NEIGHBORS || defined __DOXYGEN__ +#define LWIP_ND6_NUM_NEIGHBORS 10 +#endif + +/** + * Defines the number of entries in IPv6 destination cache. + */ +#if !defined LWIP_ND6_NUM_DESTINATIONS || defined __DOXYGEN__ +#define LWIP_ND6_NUM_DESTINATIONS 10 +#endif + +/** + * LWIP_ND6_NUM_PREFIXES: number of entries in IPv6 on-link prefixes cache + */ +#if !defined LWIP_ND6_NUM_PREFIXES || defined __DOXYGEN__ +#define LWIP_ND6_NUM_PREFIXES 10 +#endif + +/** + * Defines the number of entries in IPv6 default router cache. + */ +#if !defined LWIP_ND6_NUM_ROUTERS || defined __DOXYGEN__ +#define LWIP_ND6_NUM_ROUTERS 3 +#endif + +/** + * Defines the maximum number of multicast solicit messages to send + * (neighbor solicit and router solicit). + */ +#if !defined LWIP_ND6_MAX_MULTICAST_SOLICIT || defined __DOXYGEN__ +#define LWIP_ND6_MAX_MULTICAST_SOLICIT 3 +#endif + +/** + * Defines the maximum number of unicast neighbor solicitation messages + * to send during neighbor reachability detection. + */ +#if !defined LWIP_ND6_MAX_UNICAST_SOLICIT || defined __DOXYGEN__ +#define LWIP_ND6_MAX_UNICAST_SOLICIT 3 +#endif + +/** + * Unused: See ND RFC (time in milliseconds). + */ +#if !defined LWIP_ND6_MAX_ANYCAST_DELAY_TIME || defined __DOXYGEN__ +#define LWIP_ND6_MAX_ANYCAST_DELAY_TIME 1000 +#endif + +/** + * Unused: See ND RFC + */ +#if !defined LWIP_ND6_MAX_NEIGHBOR_ADVERTISEMENT || defined __DOXYGEN__ +#define LWIP_ND6_MAX_NEIGHBOR_ADVERTISEMENT 3 +#endif + +/** + * Defines the default neighbor reachable time in milliseconds. + * May be updated by router advertisement messages. + */ +#if !defined LWIP_ND6_REACHABLE_TIME || defined __DOXYGEN__ +#define LWIP_ND6_REACHABLE_TIME 30000 +#endif + +/** + * Defines the default retransmission timer for solicitation messages. + */ +#if !defined LWIP_ND6_RETRANS_TIMER || defined __DOXYGEN__ +#define LWIP_ND6_RETRANS_TIMER 1000 +#endif + +/** + * Defines the delay before first unicast neighbor solicitation + * message is sent, during neighbor reachability detection. + */ +#if !defined LWIP_ND6_DELAY_FIRST_PROBE_TIME || defined __DOXYGEN__ +#define LWIP_ND6_DELAY_FIRST_PROBE_TIME 5000 +#endif + +/** + * LWIP_ND6_ALLOW_RA_UPDATES==1: Allows Router Advertisement messages to update + * Reachable time and retransmission timers, and netif MTU. + */ +#if !defined LWIP_ND6_ALLOW_RA_UPDATES || defined __DOXYGEN__ +#define LWIP_ND6_ALLOW_RA_UPDATES 1 +#endif + +/** + * LWIP_ND6_TCP_REACHABILITY_HINTS==1: Allows TCP to provide Neighbor Discovery + * with reachability hints for connected destinations. This helps avoid sending + * unicast neighbor solicitation messages. + */ +#if !defined LWIP_ND6_TCP_REACHABILITY_HINTS || defined __DOXYGEN__ +#define LWIP_ND6_TCP_REACHABILITY_HINTS 1 +#endif + +/** + * LWIP_ND6_RDNSS_MAX_DNS_SERVERS > 0: Uses IPv6 Router Advertisement Recursive + * DNS Server Option (as per RFC 6106) to copy a defined maximum number of DNS + * servers to the DNS module. + */ +#if !defined LWIP_ND6_RDNSS_MAX_DNS_SERVERS || defined __DOXYGEN__ +#define LWIP_ND6_RDNSS_MAX_DNS_SERVERS 0 +#endif + +/* Configurations related to neighbor restriction */ +#ifndef LWIP_NBRPOLICY_ENABLE_NBR_RESTRICTION +#define LWIP_NBRPOLICY_ENABLE_NBR_RESTRICTION 0 +#endif + +#if LWIP_NBRPOLICY_ENABLE_NBR_RESTRICTION + +#ifndef LWIP_NBRPOLICY_DCHILD_PERCENT +#define LWIP_NBRPOLICY_DCHILD_PERCENT 60 +#endif + +#ifndef LWIP_NBRPOLICY_PARENT_PERCENT +#define LWIP_NBRPOLICY_PARENT_PERCENT 20 +#endif + +#ifndef LWIP_NBRPOLICY_DCHILD_MAX_NUM +#define LWIP_NBRPOLICY_DCHILD_MAX_NUM \ + (((LWIP_ND6_NUM_NEIGHBORS) * (LWIP_NBRPOLICY_DCHILD_PERCENT)) / 100) +#endif + +#ifndef LWIP_NBRPOLICY_PARENT_MAX_NUM +#define LWIP_NBRPOLICY_PARENT_MAX_NUM \ + (((LWIP_ND6_NUM_NEIGHBORS) * (LWIP_NBRPOLICY_PARENT_PERCENT)) / 100) +#endif + +#if (LWIP_NBRPOLICY_PARENT_MAX_NUM == 0) || (LWIP_NBRPOLICY_DCHILD_MAX_NUM == 0) +#error "Neither number of parent nor direct child can be zero" +#endif + +#endif + +/** + * @} + */ + +/* + * @defgroup lwip_opts_dhcpv6 DHCPv6 + * @ingroup lwip_opts_ipv6 + * @{ + */ +/** + * LWIP_IPV6_DHCP6==1: enable DHCPv6 stateful/stateless address autoconfiguration. + * LWIP_ND6_RDNSS_MAX_DNS_SERVERS should be 0 + */ +#if !defined LWIP_IPV6_DHCP6 || defined __DOXYGEN__ +#define LWIP_IPV6_DHCP6 1 +#endif + +/** + * LWIP_IPV6_DHCP6_STATEFUL==1: enable DHCPv6 stateful address autoconfiguration. + * (not supported, yet!) + */ +#if !defined LWIP_IPV6_DHCP6_STATEFUL || defined __DOXYGEN__ +#define LWIP_IPV6_DHCP6_STATEFUL 1 +#endif + +/** + * LWIP_IPV6_DHCP6_STATELESS==1: enable DHCPv6 stateless address autoconfiguration. + */ +#if !defined LWIP_IPV6_DHCP6_STATELESS || defined __DOXYGEN__ +#define LWIP_IPV6_DHCP6_STATELESS LWIP_IPV6_DHCP6 +#endif + +/** + * LWIP_DHCP6_GETS_NTP==1: Request NTP servers via DHCPv6. For each + * response packet, a callback is called, which has to be provided by the port: + * void dhcp6_set_ntp_servers(u8_t num_ntp_servers, ip_addr_t* ntp_server_addrs); +*/ +#if !defined LWIP_DHCP6_GET_NTP_SRV || defined __DOXYGEN__ +#define LWIP_DHCP6_GET_NTP_SRV 0 +#endif + +/** + * The maximum of NTP servers requested + */ +#if !defined LWIP_DHCP6_MAX_NTP_SERVERS || defined __DOXYGEN__ +#define LWIP_DHCP6_MAX_NTP_SERVERS 1 +#endif + +/** + * LWIP_DHCP6_MAX_DNS_SERVERS > 0: Request DNS servers via DHCPv6. + * DNS servers received in the response are passed to DNS via @ref dns_setserver() + * (up to the maximum limit defined here). + */ +#if !defined LWIP_DHCP6_MAX_DNS_SERVERS || defined __DOXYGEN__ +#define LWIP_DHCP6_MAX_DNS_SERVERS DNS_MAX_SERVERS +#endif + +/* + * @defgroup lwip_icmp6_rate_limit + * @ingroup lwip_icmp6_rate_limit + * @{ + */ +/** + * LWIP_ICMP6_ERR==1: option to use rate limit feature or not + */ +#if !defined LWIP_ICMP6_ERR_RT_LMT || defined __DOXYGEN__ +#define LWIP_ICMP6_ERR_RT_LMT 1 +#endif + +/** + * Defines the maximum number of Icmp6 error buckets to check the average rate. + * bucket size need to be power of 2. Eg. Correct values will be 2,4,8,16,32... + */ +#if !defined ICMP6_ERR_BKT_SIZE || defined __DOXYGEN__ +#define ICMP6_ERR_BKT_SIZE 2 +#endif + +/** + * Defines the max average/threshold rate at which the data can be recieved. + */ +#if !defined ICMP6_ERR_THRESHOLD_LEVEL || defined __DOXYGEN__ +#define ICMP6_ERR_THRESHOLD_LEVEL 5 +#endif + +/** + * Enables the addition and deletion operation for static perfixes. + */ +#if !defined LWIP_ND6_STATIC_PREFIX || defined __DOXYGEN__ +#define LWIP_ND6_STATIC_PREFIX 0 +#endif + +/** + * Enables the addition and deletion operation for static default routes. + */ +#if !defined LWIP_ND6_STATIC_DEFAULT_ROUTE || defined __DOXYGEN__ +#define LWIP_ND6_STATIC_DEFAULT_ROUTE 0 +#endif + +/** + * Enables the static neighbor entry support These entries can't be replaced. + */ +#if !defined LWIP_ND6_STATIC_NBR || defined __DOXYGEN__ +#define LWIP_ND6_STATIC_NBR 1 +#endif + +#if !defined LWIP_USE_LQI_FOR_LINK_METRIC || defined __DOXYGEN__ +#define LWIP_USE_LQI_FOR_LINK_METRIC 0 +#endif + +#if !defined LWIP_USE_RSSI_FOR_LINK_METRIC || defined __DOXYGEN__ +#define LWIP_USE_RSSI_FOR_LINK_METRIC 1 +#endif + +#ifndef LWIP_DHCP_COAP_RELAY +#define LWIP_DHCP_COAP_RELAY 0 +#endif + +#ifndef LWIP_ND6_ROUTER +#define LWIP_ND6_ROUTER 0 +#endif + +#ifndef LWIP_ND6_DESTINATIONS_OLDTIME +#define LWIP_ND6_DESTINATIONS_OLDTIME 0 +#endif + +#ifndef LWIP_RPL_RS_DAO +#define LWIP_RPL_RS_DAO 0 +#endif + +#ifndef LWIP_NA_PROXY +#define LWIP_NA_PROXY 0 +#endif + +#ifndef LWIP_NA_PROXY_UNSOLICITED +#define LWIP_NA_PROXY_UNSOLICITED 1 +#endif + +/** + * our nat64 module depends on rpl + */ +#if LWIP_RPL == 0 && LWIP_RIPPLE == 0 +#if defined(LWIP_NAT64) && (LWIP_NAT64 != 0) +#undef LWIP_NAT64 +#define LWIP_NAT64 0 +#endif +#endif + +#ifndef LWIP_NAT64_MIN_SUBSTITUTE +#define LWIP_NAT64_MIN_SUBSTITUTE 0 +#endif + +/* + --------------------------------------- + ---------- Hook options --------------- + --------------------------------------- +*/ + +/* + * @defgroup lwip_opts_hooks Hooks + * @ingroup lwip_opts_infrastructure + * Hooks are undefined by default. Define them to a function if you need them. + * @{ + */ + +/** + * LWIP_HOOK_FILENAME: Custom filename to #include in files that provide hooks. + * Declare your hook function prototypes in this file. You may also #include all headers + * providing data types that are need in this file. + */ +#ifdef __DOXYGEN__ +#define LWIP_HOOK_FILENAME "path/to/my/lwip_hooks.h" +#endif + +/** + * LWIP_HOOK_TCP_ISN: + * Defines the hook for generation of the Initial Sequence Number (ISN) for a new TCP + * connection. The default lwIP ISN generation algorithm is very basic and may + * allow for TCP spoofing attacks. This hook provides the means to implement + * the standardized ISN generation algorithm from RFC 6528 (see contrib/adons/tcp_isn), + * or any other desired algorithm as a replacement. + * Called from tcp_connect() and tcp_listen_input() when an ISN is needed for + * a new TCP connection, if TCP support (@ref LWIP_TCP) is enabled.\n + * Signature: u32_t my_hook_tcp_isn(const ip_addr_t* local_ip, + * u16_t local_port, const ip_addr_t* remote_ip, u16_t remote_port); \n + * It may be necessary to use "struct ip_addr" (ip4_addr, ip6_addr) instead of "ip_addr_t" in function declarations. \n + * Arguments: + * - local_ip: Pointer to the local IP address of the connection + * - local_port: Local port number of the connection (host-byte order) + * - remote_ip: Pointer to the remote IP address of the connection + * - remote_port: Remote port number of the connection (host-byte order)\n + * Return Value \n + * Returns the 32-bit Initial Sequence Number to use for the new TCP connection. + */ +#ifdef __DOXYGEN__ +#define LWIP_HOOK_TCP_ISN(local_ip, local_port, remote_ip, remote_port) +#endif + +/** + * LWIP_HOOK_TCP_INPACKET_PCB: + * Hook for intercepting incoming packets before they are passed to a pcb. This + * allows updating some state or even dropping a packet. + * Signature:\code{.c} + * err_t my_hook_tcp_inpkt(struct tcp_pcb *pcb, struct tcp_hdr *hdr, u16_t optlen, u16_t opt1len, u8_t *opt2, struct pbuf *p); + * \endcode + * Arguments: + * - pcb: tcp_pcb selected for input of this packet (ATTENTION: this may be + * struct tcp_pcb_listen if pcb->state == LISTEN) + * - hdr: pointer to tcp header (ATTENTION: tcp options may not be in one piece!) + * - optlen: tcp option length + * - opt1len: tcp option length 1st part + * - opt2: if this is != NULL, tcp options are split among 2 pbufs. In that case, + * options start at right after the tcp header ('(u8_t*)(hdr + 1)') for + * the first 'opt1len' bytes and the rest starts at 'opt2'. opt2len can + * be simply calculated: 'opt2len = optlen - opt1len;' + * - p: input packet, p->payload points to application data (that's why tcp hdr + * and options are passed in seperately) + * Return value: + * - ERR_OK: continue input of this packet as normal + * - != ERR_OK: drop this packet for input (don't continue input processing) + * + * ATTENTION: don't call any tcp api functions that might change tcp state (pcb + * state or any pcb lists) from this callback! + */ +#ifdef __DOXYGEN__ +#define LWIP_HOOK_TCP_INPACKET_PCB(pcb, hdr, optlen, opt1len, opt2, p) +#endif + +/** + * LWIP_HOOK_TCP_OUT_TCPOPT_LENGTH: + * Hook for increasing the size of the options allocated with a tcp header. + * Together with LWIP_HOOK_TCP_OUT_ADD_TCPOPTS, this can be used to add custom + * options to outgoing tcp segments. + * Signature:\code{.c} + * u8_t my_hook_tcp_out_tcpopt_length(const struct tcp_pcb *pcb, u8_t internal_option_length); + * \endcode + * Arguments: + * - pcb: tcp_pcb that transmits (ATTENTION: this may be NULL or + * struct tcp_pcb_listen if pcb->state == LISTEN) + * - internal_option_length: tcp option length used by the stack internally + * Return value: + * - a number of bytes to allocate for tcp options (internal_option_length <= ret <= 40) + * + * ATTENTION: don't call any tcp api functions that might change tcp state (pcb + * state or any pcb lists) from this callback! + */ +#ifdef __DOXYGEN__ +#define LWIP_HOOK_TCP_OUT_TCPOPT_LENGTH(pcb, internal_len) +#endif + +/** + * LWIP_HOOK_TCP_OUT_ADD_TCPOPTS: + * Hook for adding custom options to outgoing tcp segments. + * Space for these custom options has to be reserved via LWIP_HOOK_TCP_OUT_TCPOPT_LENGTH. + * Signature:\code{.c} + * u32_t *my_hook_tcp_out_add_tcpopts(struct pbuf *p, struct tcp_hdr *hdr, const struct tcp_pcb *pcb, u32_t *opts); + * \endcode + * Arguments: + * - p: output packet, p->payload pointing to tcp header, data follows + * - hdr: tcp header + * - pcb: tcp_pcb that transmits (ATTENTION: this may be NULL or + * struct tcp_pcb_listen if pcb->state == LISTEN) + * - opts: pointer where to add the custom options (there may already be options + * between the header and these) + * Return value: + * - pointer pointing directly after the inserted options + * + * ATTENTION: don't call any tcp api functions that might change tcp state (pcb + * state or any pcb lists) from this callback! + */ +#ifdef __DOXYGEN__ +#define LWIP_HOOK_TCP_OUT_ADD_TCPOPTS(p, hdr, pcb, opts) +#endif + +/** + * This is called from ip_input() (IPv4) \n + * Arguments: + * - pbuf: Received struct pbuf passed to ip_input() + * - input_netif: struct netif on which the packet has been received. + * Return Value \n + * - 0: Hook has not consumed the packet. Packet is processed as normal. + * - != 0: Hook has consumed the packet. + * If the hook consumed the packet, the hook must free the 'pbuf' when it is done. + */ +#ifdef __DOXYGEN__ +#define LWIP_HOOK_IP4_INPUT(pbuf, input_netif) +#endif + +/** + * This is called from ip_route() (IPv4) \n + + * Returns the destination netif or NULL if no destination netif is found. In + * that case, ip_route() continues as normal. + */ +#ifdef __DOXYGEN__ +#define LWIP_HOOK_IP4_ROUTE() +#endif + +/** + * LWIP_HOOK_IP4_ROUTE_SRC(src, dest): + * Source-based routing for IPv4 - called from ip_route() (IPv4) + * Signature: + * struct netif *my_hook(const ip4_addr_t *src, const ip4_addr_t *dest); + * Arguments: + * - dest: destination IPv4 address + * - src: local/source IPv4 address + * Returns values: + * - the destination netif + * - NULL if no destination netif is found. In that case, ip_route() continues as normal. + */ +#ifdef __DOXYGEN__ +#define LWIP_HOOK_IP4_ROUTE_SRC(src, dest) +#endif + + +/** + * LWIP_HOOK_IP4_CANFORWARD(src, dest): + * Check if an IPv4 can be forwarded - called from: + * ip4_input() -> ip4_forward() -> ip4_canforward() (IPv4) + * - source address is available via ip4_current_src_addr() + * - calling an output function in this context (e.g. multicast router) is allowed + * Signature:\code{.c} + * int my_hook(struct pbuf *p, u32_t dest_addr_hostorder); + * \endcode + * Arguments: + * - p: packet to forward + * - dest: destination IPv4 address + * Returns values: + * - 1: forward + * - 0: don't forward + * - -1: no decision. In that case, ip4_canforward() continues as normal. + */ +#ifdef __DOXYGEN__ +#define LWIP_HOOK_IP4_CANFORWARD(src, dest) +#endif + +/** + * LWIP_HOOK_ETHARP_GET_GW(netif, dest) is called from etharp_output() (IPv4) \n + * Arguments: + * - netif: the netif used for sending + * - dest: the destination IPv4 address \n + * Returns the IPv4 address of the gateway to handle the specified destination + * IPv4 address. If NULL is returned, the netif's default gateway is used. + * The returned address must be directly reachable on the specified netif. + * This function is meant to implement advanced IPv4 routing together with + * LWIP_HOOK_IP4_ROUTE(). The actual routing/gateway table implementation is + * not part of lwIP but can e.g. be hidden in the netif's state argument. +*/ +#ifdef __DOXYGEN__ +#define LWIP_HOOK_ETHARP_GET_GW(netif, dest) +#endif + +/** + * LWIP_HOOK_IP6_INPUT(pbuf, input_netif)is called from ip6_input() (IPv6) + * Arguments: + * - pbuf: received struct pbuf passed to ip6_input() + * - input_netif: struct netif on which the packet has been received \n + * Return Values + * - 0: Hook has not consumed the packet, packet is processed as normal + * - != 0: Hook has consumed the packet. \n + * If the hook consumed the packet, the hook must free the 'pbuf' when it is done. + */ +#ifdef __DOXYGEN__ +#define LWIP_HOOK_IP6_INPUT(pbuf, input_netif) +#endif + +/** + * LWIP_HOOK_IP6_ROUTE(src, dest) is called from ip6_route() (IPv6) \n + * Arguments: + * - src: sourc IPv6 address + * - dest: destination IPv6 address \n + * Returns the destination netif or NULL if no destination netif is found. In + * that case, ip6_route() continues as normal. + */ +#if LWIP_RPL || LWIP_RIPPLE +#define LWIP_HOOK_IP6_ROUTE(src, dest) lwip_rpl_route_netif_lookup(src, dest) +#else +#define LWIP_HOOK_IP6_ROUTE(src, dest) +#endif + +/** + * LWIP_HOOK_ND6_GET_GW(netif, dest) is called from nd6_get_next_hop_entry() (IPv6) + * Arguments: + * - netif: The netif used for sending + * - dest: The destination IPv6 address + * Returns the IPv6 address of the next hop to handle the specified destination + * IPv6 address. If NULL is returned, a NDP-discovered router is used instead. + * The returned address MUST be directly reachable on the specified netif. + * This function is meant to implement advanced IPv6 routing together with + * LWIP_HOOK_IP6_ROUTE(). The actual routing/gateway table implementation is + * not part of lwIP but can be hidden in the netif's state argument. +*/ +#if LWIP_RPL || LWIP_RIPPLE +#define LWIP_HOOK_ND6_GET_GW(netif, dest) lwip_rpl_route_nexthop_lookup(netif, dest) +#else +#define LWIP_HOOK_ND6_GET_GW(netif, dest) +#endif + +/** + * LWIP_HOOK_VLAN_CHECK(netif, eth_hdr, vlan_hdr) is called from ethernet_input() if VLAN support is enabled + * Arguments: + * - netif: struct netif on which the packet has been received + * - eth_hdr: struct eth_hdr of the packet + * - vlan_hdr: struct eth_vlan_hdr of the packet + * Return Values \n + * - 0: Packet must be dropped. + * - != 0: Packet must be accepted. + */ +#ifdef __DOXYGEN__ +#define LWIP_HOOK_VLAN_CHECK(netif, eth_hdr, vlan_hdr) +#endif + +/** + * LWIP_HOOK_VLAN_SET: + * Hook can be used to set prio_vid field of vlan_hdr. If you need to store data + * on per-netif basis to implement this callback, see @ref netif_cd. + * Called from ethernet_output() if VLAN support (@ref ETHARP_SUPPORT_VLAN) is enabled.\n + * Signature: s32_t my_hook_vlan_set(struct netif* netif, struct pbuf* pbuf, const struct eth_addr* src, + const struct eth_addr* dst, u16_t eth_type);\n + * Arguments: + * - netif: struct netif that the packet will be sent through + * - p: struct pbuf packet to be sent + * - src: source eth address + * - dst: destination eth address + * - eth_type: ethernet type to packet to be sent\n + * + * + * Return values: + * - <0: Packet shall not contain VLAN header. + * - 0 <= return value <= 0xFFFF: Packet shall contain VLAN header. Return value is prio_vid in host byte order. + */ +#ifdef __DOXYGEN__ +#define LWIP_HOOK_VLAN_SET(netif, p, src, dst, eth_type) +#endif + +/** + * LWIP_HOOK_MEMP_AVAILABLE(memp_t_type): + * - called from memp_free() when a memp pool was empty and an item is now available + */ +#ifdef __DOXYGEN__ +#define LWIP_HOOK_MEMP_AVAILABLE(memp_t_type) +#endif + +/** + * LWIP_HOOK_UNKNOWN_ETH_PROTOCOL(pbuf, netif): + * Called from ethernet_input() when an unknown eth type is encountered. + * Returns ERR_OK if packet is accepted, any error code otherwise. + * The payload points to ethernet header. + */ +#ifdef __DOXYGEN__ +#define LWIP_HOOK_UNKNOWN_ETH_PROTOCOL(pbuf, netif) +#endif + +/** + * LWIP_HOOK_DHCP6_APPEND_OPTIONS(netif, dhcp6, state, msg, msg_type, options_len_ptr, max_len): + * Called from various dhcp6 functions when sending a DHCP6 message. + * This hook is called just before the DHCP6 message is sent, so the + * options are at the end of a DHCP6 message. + * Signature:\code{.c} + * void my_hook(struct netif *netif, struct dhcp6 *dhcp, u8_t state, struct dhcp6_msg *msg, + * u8_t msg_type, u16_t *options_len_ptr); + * \endcode + * Arguments: + * - netif: struct netif that the packet will be sent through + * - dhcp6: struct dhcp6 on that netif + * - state: current dhcp6 state (dhcp6_state_enum_t as an u8_t) + * - msg: struct dhcp6_msg that will be sent + * - msg_type: dhcp6 message type to be sent (u8_t) + * - options_len_ptr: pointer to the current length of options in the dhcp6_msg "msg" + * (must be increased when options are added!) + * + * Options need to appended like this: + * u8_t *options = (u8_t *)(msg + 1); + * LWIP_ASSERT("dhcp option overflow", sizeof(struct dhcp6_msg) + *options_len_ptr + newoptlen <= max_len); + * options[(*options_len_ptr)++] = <option_data>; + * [...] + */ +#ifdef __DOXYGEN__ +#define LWIP_HOOK_DHCP6_APPEND_OPTIONS(netif, dhcp6, state, msg, msg_type, options_len_ptr, max_len) +#endif + +/** + * LWIP_HOOK_SOCKETS_SETSOCKOPT(s, sock, level, optname, optval, optlen, err) + * Called from socket API to implement setsockopt() for options not provided by lwIP. + * Core lock is held when this hook is called. + * Signature:\code{.c} + * int my_hook(int s, struct lwip_sock *sock, int level, int optname, const void *optval, socklen_t optlen, int *err) + * \endcode + * Arguments: + * - s: socket file descriptor + * - sock: internal socket descriptor (see lwip/priv/sockets_priv.h) + * - level: protocol level at which the option resides + * - optname: option to set + * - optval: value to set + * - optlen: size of optval + * - err: output error + * Return values: + * - 0: Hook has not consumed the option, code continues as normal (to internal options) + * - != 0: Hook has consumed the option, 'err' is returned + */ +#ifdef __DOXYGEN__ +#define LWIP_HOOK_SOCKETS_SETSOCKOPT(s, sock, level, optname, optval, optlen, err) +#endif + +/** + * LWIP_HOOK_SOCKETS_GETSOCKOPT(s, sock, level, optname, optval, optlen, err) + * Called from socket API to implement getsockopt() for options not provided by lwIP. + * Core lock is held when this hook is called. + * Signature:\code{.c} + * int my_hook(int s, struct lwip_sock *sock, int level, int optname, void *optval, socklen_t *optlen, int *err) + * \endcode + * Arguments: + * - s: socket file descriptor + * - sock: internal socket descriptor (see lwip/priv/sockets_priv.h) + * - level: protocol level at which the option resides + * - optname: option to get + * - optval: value to get + * - optlen: size of optval + * - err: output error + * Return values: + * - 0: Hook has not consumed the option, code continues as normal (to internal options) + * - != 0: Hook has consumed the option, 'err' is returned + */ +#ifdef __DOXYGEN__ +#define LWIP_HOOK_SOCKETS_GETSOCKOPT(s, sock, level, optname, optval, optlen, err) +#endif + +/** + * LWIP_HOOK_NETCONN_EXTERNAL_RESOLVE(name, addr, addrtype, err) + * Called from netconn APIs (not usable with callback apps) allowing an + * external DNS resolver (which uses sequential API) to handle the query. + * Signature:\code{.c} + * int my_hook(const char *name, ip_addr_t *addr, u8_t addrtype, err_t *err) + * \endcode + * Arguments: + * - name: hostname to resolve + * - addr: output host address + * - addrtype: type of address to query + * - err: output error + * Return values: + * - 0: Hook has not consumed hostname query, query continues into DNS module + * - != 0: Hook has consumed the query + * + * err must also be checked to determine if the hook consumed the query, but + * the query failed + */ +#ifdef __DOXYGEN__ +#define LWIP_HOOK_NETCONN_EXTERNAL_RESOLVE(name, addr, addrtype, err) +#endif +/** + * @} + */ + +/* + --------------------------------------- + ---------- Debugging options ---------- + --------------------------------------- +*/ +/* + * @defgroup lwip_opts_debugmsg Debug messages + * @ingroup lwip_opts_debug + * @{ + */ +/** + * LWIP_DBG_MIN_LEVEL: After masking, the value of the debug is + * compared against this value. If it is smaller, then debugging + * messages are written. + * @see debugging_levels + */ +#if !defined LWIP_DBG_MIN_LEVEL || defined __DOXYGEN__ +#define LWIP_DBG_MIN_LEVEL LWIP_DBG_LEVEL_ALL +#endif + +/** + * Defines a mask that can be used to globally enable/disable + * debug messages of certain types. + * @see debugging_levels + */ +#if !defined LWIP_DBG_TYPES_ON || defined __DOXYGEN__ +#define LWIP_DBG_TYPES_ON LWIP_DBG_OFF +#endif + +/** + * Defines whether to enable debugging in etharp.c. + */ +#if !defined ETHARP_DEBUG || defined __DOXYGEN__ +#define ETHARP_DEBUG LWIP_DBG_OFF +#endif + +/** + * Defines whether to enable debugging in netif.c. + */ +#if !defined NETIF_DEBUG || defined __DOXYGEN__ +#define NETIF_DEBUG LWIP_DBG_OFF +#endif + +/** + * Defines whether to enable debugging in pbuf.c. + */ +#if !defined PBUF_DEBUG || defined __DOXYGEN__ +#define PBUF_DEBUG LWIP_DBG_OFF +#endif + +/** + * Defines whether to enable debugging in api_lib.c. + */ +#if !defined API_LIB_DEBUG || defined __DOXYGEN__ +#define API_LIB_DEBUG LWIP_DBG_OFF +#endif + +/** + * Defines whether to enable debugging in api_msg.c. + */ +#if !defined API_MSG_DEBUG || defined __DOXYGEN__ +#define API_MSG_DEBUG LWIP_DBG_OFF +#endif + +/** + * Defines whether to enable debugging in sockets.c. + */ +#if !defined SOCKETS_DEBUG || defined __DOXYGEN__ +#define SOCKETS_DEBUG LWIP_DBG_OFF +#endif + +/** + * Defines whether to enable debugging in icmp.c. + */ +#if !defined ICMP_DEBUG || defined __DOXYGEN__ +#define ICMP_DEBUG LWIP_DBG_OFF +#endif + +/** + * Defines whether to enable debugging in igmp.c. + */ +#if !defined IGMP_DEBUG || defined __DOXYGEN__ +#define IGMP_DEBUG LWIP_DBG_OFF +#endif + +/** + * Defines whether to enable debugging in inet.c. + */ +#if !defined INET_DEBUG || defined __DOXYGEN__ +#define INET_DEBUG LWIP_DBG_OFF +#endif + +/** + * Defines whether to enable debugging for IP. + */ +#if !defined IP_DEBUG || defined __DOXYGEN__ +#define IP_DEBUG LWIP_DBG_OFF +#endif + +/** + * Defines whether to enable debugging for driver module. + */ +#ifndef DRIVERIF_DEBUG +#define DRIVERIF_DEBUG LWIP_DBG_OFF +#endif +/** + * Defines whether to enable debugging in ip_frag.c for both frag & reass. + */ +#if !defined IP_REASS_DEBUG || defined __DOXYGEN__ +#define IP_REASS_DEBUG LWIP_DBG_OFF +#endif + +/** + * Defines whether to enable debugging in raw.c. + */ +#if !defined RAW_DEBUG || defined __DOXYGEN__ +#define RAW_DEBUG LWIP_DBG_OFF +#endif + +/** + * Defines whether to enable debugging in mem.c. + */ +#if !defined MEM_DEBUG || defined __DOXYGEN__ +#define MEM_DEBUG LWIP_DBG_OFF +#endif + +/** + * Defines whether to enable debugging in memp.c. + */ +#if !defined MEMP_DEBUG || defined __DOXYGEN__ +#define MEMP_DEBUG LWIP_DBG_OFF +#endif + +/** + * SYS_DEBUG: Enable debugging in sys.c. + */ +#if !defined SYS_DEBUG || defined __DOXYGEN__ +#define SYS_DEBUG LWIP_DBG_OFF +#endif + +/** + * Defines whether to enable debugging in timers.c. + */ +#if !defined TIMERS_DEBUG || defined __DOXYGEN__ +#define TIMERS_DEBUG LWIP_DBG_OFF +#endif + +/** + * Defines whether to enable debugging for TCP. + */ +#if !defined TCP_DEBUG || defined __DOXYGEN__ +#define TCP_DEBUG LWIP_DBG_OFF +#endif + +/** + * TCP_ERR_DEBUG: Enables debugging for TCP. + */ +#if !defined TCP_ERR_DEBUG || defined __DOXYGEN__ +#define TCP_ERR_DEBUG LWIP_DBG_OFF +#endif + +/** + * TCP_INPUT_DEBUG: Enables debugging in tcp_in.c for incoming debug. + */ +#if !defined TCP_INPUT_DEBUG || defined __DOXYGEN__ +#define TCP_INPUT_DEBUG LWIP_DBG_OFF +#endif + +/** + * Defines whether to enable debugging in tcp_in.c for fast retransmit. + */ +#if !defined TCP_FR_DEBUG || defined __DOXYGEN__ +#define TCP_FR_DEBUG LWIP_DBG_OFF +#endif + +/** + * Defines whether to enable debugging in TCP for retransmit + * timeout. + */ +#if !defined TCP_RTO_DEBUG || defined __DOXYGEN__ +#define TCP_RTO_DEBUG LWIP_DBG_OFF +#endif + +/** + * Defines whether to enable debugging for TCP congestion window. + */ +#if !defined TCP_CWND_DEBUG || defined __DOXYGEN__ +#define TCP_CWND_DEBUG LWIP_DBG_OFF +#endif + +/** + * Defines whether to enable debugging in tcp_in.c for window updating. + */ +#if !defined TCP_WND_DEBUG || defined __DOXYGEN__ +#define TCP_WND_DEBUG LWIP_DBG_OFF +#endif + +/** + * TCP_OUTPUT_DEBUG: Enable debugging in tcp_out.c output functions. + */ +#if !defined TCP_OUTPUT_DEBUG || defined __DOXYGEN__ +#define TCP_OUTPUT_DEBUG LWIP_DBG_OFF +#endif + +/** + * Defines whether to enable debugging for TCP with the RST message. + */ +#if !defined TCP_RST_DEBUG || defined __DOXYGEN__ +#define TCP_RST_DEBUG LWIP_DBG_OFF +#endif + +/** +* Defines whether to enable debugging for TCP queue lengths. + */ +#if !defined TCP_QLEN_DEBUG || defined __DOXYGEN__ +#define TCP_QLEN_DEBUG LWIP_DBG_OFF +#endif + +/** + * Defines whether to enable debugging for TCP Selective ACK (SACK) + */ +#if !defined TCP_SACK_DEBUG || defined __DOXYGEN__ +#define TCP_SACK_DEBUG LWIP_DBG_OFF +#endif + +/** + * Defines whether to enable debugging for TCP Tail Loss Probe(TLP) + */ +#if !defined TCP_TLP_DEBUG || defined __DOXYGEN__ +#define TCP_TLP_DEBUG LWIP_DBG_OFF +#endif + +/** + * Defines whether to enable debugging in UDP. + */ +#if !defined UDP_DEBUG || defined __DOXYGEN__ +#define UDP_DEBUG LWIP_DBG_OFF +#endif + +/** + * Defines whether to enable debugging in tcpip.c. + */ +#if !defined TCPIP_DEBUG || defined __DOXYGEN__ +#define TCPIP_DEBUG LWIP_DBG_OFF +#endif + +/** + * Defines whether to enable debugging in tcpip.c. + */ +#if !defined L3_EVENT_MSG_DEBUG || defined __DOXYGEN__ +#define L3_EVENT_MSG_DEBUG LWIP_DBG_OFF +#endif + +/** + * Defines whether to enable debugging in slipif.c. + */ +#if !defined SLIP_DEBUG || defined __DOXYGEN__ +#define SLIP_DEBUG LWIP_DBG_OFF +#endif + +/** + * Defines whether to enable debugging in dhcp.c. + */ +#if !defined DHCP_DEBUG || defined __DOXYGEN__ +#define DHCP_DEBUG LWIP_DBG_OFF +#endif + +/** + * Defines whether to enable debugging in autoip.c. + */ +#if !defined AUTOIP_DEBUG || defined __DOXYGEN__ +#define AUTOIP_DEBUG LWIP_DBG_OFF +#endif + +/** + * Defines whether to enable debugging for DNS. + */ +#if !defined DNS_DEBUG || defined __DOXYGEN__ +#define DNS_DEBUG LWIP_DBG_OFF +#endif + +/** +* Defines whether to enable debugging for DNS. + */ +#ifndef TFTP_DEBUG +#define TFTP_DEBUG LWIP_DBG_OFF +#endif + +/** * Defines whether to enable debugging for DNS. */ +#ifndef SYS_ARCH_DEBUG +#define SYS_ARCH_DEBUG LWIP_DBG_OFF +#endif + +/** + * Defines whether to enable debugging for SNTP. + */ +#ifndef SNTP_DEBUG +#define SNTP_DEBUG LWIP_DBG_OFF +#endif + +/** + * Defines whether to enabledebugging for IPv6. + */ +#if !defined IP6_DEBUG || defined __DOXYGEN__ +#define IP6_DEBUG LWIP_DBG_OFF +#endif + +/** + * DHCP6_DEBUG: Enable debugging in dhcp6.c. + */ +#if !defined DHCP6_DEBUG || defined __DOXYGEN__ +#define DHCP6_DEBUG LWIP_DBG_OFF +#endif + +/** + * Defines whether to enabledebugging for IPv6. + */ +#if !defined RPL_DEBUG || defined __DOXYGEN__ +#define RPL_DEBUG LWIP_DBG_OFF +#endif + +/** + * Defines whether to enabledebugging for RPL Adaptor module. + */ +#if !defined RPLADPT_DEBUG || defined __DOXYGEN__ +#define RPLADPT_DEBUG LWIP_DBG_OFF +#endif + +/** + * Defines whether to enabledebugging for MLD6 module. + */ +#if !defined MLD6_DEBUG || defined __DOXYGEN__ +#define MLD6_DEBUG LWIP_DBG_OFF +#endif + +/** + * @} + */ + +/** + * LWIP_TESTMODE: Changes to make unit test possible + */ +#if !defined LWIP_TESTMODE +#define LWIP_TESTMODE 0 +#endif + +/** + * Defines whether to enable debugging for Driver Status + */ +#ifndef DRV_STS_DEBUG +#define DRV_STS_DEBUG LWIP_DBG_OFF +#endif + +/** + * Defines whether to enable debugging for NAT64. + */ +#if !defined NAT64_DEBUG || defined __DOXYGEN__ +#define NAT64_DEBUG LWIP_DBG_OFF +#endif + +/* + -------------------------------------------------- + ---------- Performance tracking options ---------- + -------------------------------------------------- +*/ +/* + * @defgroup lwip_opts_perf Performance + * @ingroup lwip_opts_debug + * @{ + */ +/** + * Defines whether to enable performance testing for lwIP. + * If enabled, arch/perf.h is included. + */ +#if !defined LWIP_PERF || defined __DOXYGEN__ +#define LWIP_PERF 0 +#endif +#include "arch/perf.h" +/** + * @} + */ + +/** + * Defines the mailbox size for the tcpip thread messages + * The queue size value itself is platform-dependent, but is passed to + * sys_mbox_new() when tcpip_init is called. + */ +#ifndef TCPIP_MBOX_SIZE +#if LWIP_NETIF_PROMISC +#define TCPIP_MBOX_SIZE 512 +#else +#define TCPIP_MBOX_SIZE 320 +#endif +#endif + +#ifndef TCPIP_PRTY_MBOX_SIZE +#define TCPIP_PRTY_MBOX_SIZE 16 +#endif + +#ifndef PBUF_LINK_CHKSUM_LEN +#define PBUF_LINK_CHKSUM_LEN 0 +#endif + +#ifndef LWIP_SACK_PERF_OPT +#if LWIP_SACK +#define LWIP_SACK_PERF_OPT 0 +#else +#define LWIP_SACK_PERF_OPT 0 +#endif +#endif /* LWIP_SACK_PERF_OPT */ + +#ifndef LWIP_SACK_CWND_OPT +#define LWIP_SACK_CWND_OPT LWIP_SACK_PERF_OPT +#endif + +/** + * PBUF_API macro must be enabled by the application in case the pbuf APIs are directly used by + * the application code. This macro enables NULL validations and can have a performance impact. + */ +#ifndef PBUF_API +#define PBUF_API 0 // add in opt.h +#endif + +/** + * enable LWIP_LOWPOWER macro to use lowpower function + */ +#undef LWIP_LOWPOWER +#if LWIP_TIMERS && !LWIP_TIMERS_CUSTOM +#if defined (CONFIG_LWIP_LOWPOWER) +#define LWIP_LOWPOWER 1 +#else +#define LWIP_LOWPOWER 0 +#endif +#else +#define LWIP_LOWPOWER 0 +#endif + +#if LWIP_LOWPOWER + +#ifndef LOWPOWER_DBG +#define LOWPOWER_DBG 0 +#endif + +#if LOWPOWER_DBG +#define LOWPOWER_DEBUG(msg) printf msg +#else +#define LOWPOWER_DEBUG(msg) +#endif + +#ifndef MEMP_NUM_TCPIP_MSG_LOWPOWER +#define MEMP_NUM_TCPIP_MSG_LOWPOWER 10 +#endif + +#if LWIP_SNTP +#define LWIP_NSTP_TIMER 2 +#else +#define LWIP_NSTP_TIMER 0 +#endif + +#define LOWPOWER_TCP_TIMER 1 + +#define MEMP_NUM_SYS_TIMEOUT_LOW (MEMP_NUM_SYS_TIMEOUT + LWIP_NSTP_TIMER + LOWPOWER_TCP_TIMER) +#endif /* LWIP_LOWPOWER */ + +#ifndef LWIP_L3_EVENT_MSG +#define LWIP_L3_EVENT_MSG 0 +#endif + +#endif /* LWIP_HDR_OPT_H */ + diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/pbuf.h b/sdk_liteos/third_party/lwip_sack/include/lwip/pbuf.h new file mode 100644 index 0000000000000000000000000000000000000000..563229e50ead7ac1dd831c8a1667310e9cc9ffd1 --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/pbuf.h @@ -0,0 +1,604 @@ +/** + * @file + * pbuf API + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ + +#ifndef LWIP_HDR_PBUF_H +#define LWIP_HDR_PBUF_H + +#include "arch/atomic.h" +#include "lwip/opt.h" +#include "lwip/err.h" + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +#define SIZEOF_STRUCT_PBUF LWIP_MEM_ALIGN_SIZE(sizeof(struct pbuf)) + +/** + * @defgroup Buffer_Interfaces Buffer Interfaces + * @ingroup System_interfaces + */ +/** + * LWIP_SUPPORT_CUSTOM_PBUF==1: Custom pbufs behave similar to its pbuf type, + * but it is are allocated by external code (initialized by calling + * pbuf_alloced_custom()), and when pbuf_free gives up the last reference, the custom pbufs + * are freed by calling pbuf_custom->custom_free_function(). + * Currently, the pbuf_custom code is only needed for one specific configuration + * of IP_FRAG, unless required by the external driver/application code. */ +#ifndef LWIP_SUPPORT_CUSTOM_PBUF +#define LWIP_SUPPORT_CUSTOM_PBUF ((IP_FRAG && !LWIP_NETIF_TX_SINGLE_PBUF) || (LWIP_IPV6 && LWIP_IPV6_FRAG)) +#endif + +/** PBUF_NEEDS_COPY(p): return a boolean value indicating whether the given + * pbuf needs to be copied in order to be kept around beyond the current call + * stack without risking being corrupted. The default setting provides safety: + * it will make a copy iof any pbuf chain that does not consist entirely of + * PBUF_ROM type pbufs. For setups with zero-copy support, it may be redefined + * to evaluate to true in all cases, for example. However, doing so also has an + * effect on the application side: any buffers that are *not* copied must also + * *not* be reused by the application after passing them to lwIP. For example, + * when setting PBUF_NEEDS_COPY to (0), after using udp_send() with a PBUF_RAM + * pbuf, the application must free the pbuf immediately, rather than reusing it + * for other purposes. For more background information on this, see tasks #6735 + * and #7896, and bugs #11400 and #49914. */ +#ifndef PBUF_NEEDS_COPY +#define PBUF_NEEDS_COPY(p) (p->type_internal != PBUF_ROM) +#endif /* PBUF_NEEDS_COPY */ + +/* @todo: We need a mechanism to prevent wasting memory in every pbuf + (TCP vs. UDP, IPv4 vs. IPv6: UDP/IPv4 packets may waste up to 28 bytes) */ + +#define PBUF_TRANSPORT_HLEN 20 +#if LWIP_IPV6 +#define PBUF_IP_HLEN 40 +#else +#define PBUF_IP_HLEN 20 +#endif + +/* for zero copy */ +#define PBUF_ZERO_COPY_RESERVE 36 + +/** + * @ingroup pbuf + * Enumeration of pbuf layers + */ +typedef enum { + /** Includes spare room for transport layer headers such as UDP header. + * Use this if you intend to pass the pbuf to functions like udp_send(). + */ + PBUF_TRANSPORT, + /** Includes spare room for IP header. + * Use this if you intend to pass the pbuf to functions like raw_send(). + */ + PBUF_IP, + /** Includes spare room for link layer header (ethernet header). + * Use this if you intend to pass the pbuf to functions like ethernet_output(). + * @see PBUF_LINK_HLEN + */ + PBUF_LINK, + /** Includes spare room for additional encapsulation header before ethernet + * headers such as 802.11. + * Use this if you intend to pass the pbuf to functions like netif->linkoutput(). + * @see PBUF_LINK_ENCAPSULATION_HLEN + */ + PBUF_RAW_TX, + /** Use this for input packets in a netif driver when calling netif->input(). + * The most common case is ethernet-layer netif driver. */ + PBUF_RAW +} pbuf_layer; + + +/* Base flags for pbuf_type definitions: */ + +/** Indicates that the payload directly follows the struct pbuf. + * This makes @ref pbuf_header work in both directions. */ +#define PBUF_TYPE_FLAG_STRUCT_DATA_CONTIGUOUS 0x80 +/** Indicates the data stored in this pbuf can change. If this pbuf needs + * to be queued, it must be copied/duplicated. */ +#define PBUF_TYPE_FLAG_DATA_VOLATILE 0x40 +/** 4 bits are reserved for 16 allocation sources (e.g. heap, pool1, pool2, etc) + * Internally, we use: 0=heap, 1=MEMP_PBUF, 2=MEMP_PBUF_POOL -> 13 types free*/ +#define PBUF_TYPE_ALLOC_SRC_MASK 0x0F +/** Indicates this pbuf is used for RX (if not set, indicates use for TX). + * This information can be used to keep some spare RX buffers e.g. for + * receiving TCP ACKs to unblock a connection) */ +#define PBUF_ALLOC_FLAG_RX 0x0100 +/** Indicates the application needs the pbuf payload to be in one piece */ +#define PBUF_ALLOC_FLAG_DATA_CONTIGUOUS 0x0200 + +#define PBUF_TYPE_ALLOC_SRC_MASK_STD_HEAP 0x00 +#define PBUF_TYPE_ALLOC_SRC_MASK_STD_MEMP_PBUF 0x01 +#define PBUF_TYPE_ALLOC_SRC_MASK_STD_MEMP_PBUF_POOL 0x02 +/** First pbuf allocation type for applications */ +#define PBUF_TYPE_ALLOC_SRC_MASK_APP_MIN 0x03 +/** Last pbuf allocation type for applications */ +#define PBUF_TYPE_ALLOC_SRC_MASK_APP_MAX PBUF_TYPE_ALLOC_SRC_MASK + +/** + * @ingroup pbuf + * Enumeration of pbuf types + */ +typedef enum { + /** pbuf data is stored in RAM, used for TX mostly, struct pbuf and its payload + are allocated in one piece of contiguous memory (so the first payload byte + can be calculated from struct pbuf). + pbuf_alloc() allocates PBUF_RAM pbufs as unchained pbufs (although that might + change in future versions). + This should be used for all OUTGOING packets (TX).*/ + PBUF_RAM = (PBUF_ALLOC_FLAG_DATA_CONTIGUOUS | PBUF_TYPE_FLAG_STRUCT_DATA_CONTIGUOUS | PBUF_TYPE_ALLOC_SRC_MASK_STD_HEAP), + /** pbuf data is stored in ROM, i.e. struct pbuf and its payload are located in + totally different memory areas. Since it points to ROM, payload does not + have to be copied when queued for transmission. */ + PBUF_ROM = PBUF_TYPE_ALLOC_SRC_MASK_STD_MEMP_PBUF, + /** pbuf comes from the pbuf pool. Much like PBUF_ROM but payload might change + so it has to be duplicated when queued before transmitting, depending on + who has a 'ref' to it. */ + PBUF_REF = (PBUF_TYPE_FLAG_DATA_VOLATILE | PBUF_TYPE_ALLOC_SRC_MASK_STD_MEMP_PBUF), + /** pbuf payload refers to RAM. This one comes from a pool and should be used + for RX. Payload can be chained (scatter-gather RX) but like PBUF_RAM, struct + pbuf and its payload are allocated in one piece of contiguous memory (so + the first payload byte can be calculated from struct pbuf). + Don't use this for TX, if the pool becomes empty e.g. because of TCP queuing, + you are unable to receive TCP acks! */ + PBUF_POOL = (PBUF_ALLOC_FLAG_RX | PBUF_TYPE_FLAG_STRUCT_DATA_CONTIGUOUS | PBUF_TYPE_ALLOC_SRC_MASK_STD_MEMP_PBUF_POOL) +} pbuf_type; +#define LWIP_MEM_DMA_ALIGN_SIZE(size) (((size) + (MEM_MALLOC_DMA_ALIGN) - 1) & ~(u32_t)((MEM_MALLOC_DMA_ALIGN) - 1)) +#if (MEM_MALLOC_DMA_ALIGN != 1) +struct pbuf_dma_info { + void *dma; + /** Pointer to the MAC header in the buffer, used by the driver. */ + void *mac_header; + + atomic_t dma_ref; + u16_t dma_len; + /** Indicates the link layer data totlen, used by the driver. */ + u16_t link_len; +}; +#endif + +/** Indicates that the data of the packet must be immediately passed to the application. */ +#define PBUF_FLAG_PUSH 0x01U +/** Indicates that this is a custom pbuf. pbuf_free calls pbuf_custom->custom_free_function() + when the last reference is released (custom PBUF_RAM cannot be trimmed). */ +#define PBUF_FLAG_IS_CUSTOM 0x02U +/** Indicates that this pbuf is UDP multicast to be looped back. */ +#define PBUF_FLAG_MCASTLOOP 0x04U +/** Indicates that this pbuf was received as link-level broadcast. */ +#define PBUF_FLAG_LLBCAST 0x08U +/** Indicates that this pbuf was received as link-level multicast. */ +#define PBUF_FLAG_LLMCAST 0x10U +/** Indicates that this pbuf includes a TCP FIN flag. */ +#define PBUF_FLAG_TCP_FIN 0x20U +/** Flag to denote presence of for HBH-RPI. */ +#define PBUF_FLAG_RPI 0x40U + +/** Flag to denote presence of space for HBH. */ +#define PBUF_FLAG_HBH_SPACE 0x80U +/* NETIF DRIVER STATUS CHANGE BEGIN */ +#if DRIVER_STATUS_CHECK +/** Indicates this pbuf is from DHCP application. */ +#define PBUF_FLAG_DHCP_BUF 0x80U +#endif + +#define PBUF_FLAG_HOST 0x100U +#define PBUF_FLAG_OUTGOING 0x200U + +#if LWIP_SO_DONTROUTE +/** indicates the destination of this pbuf located on directly attached link */ +#define PBUF_FLAG_IS_LINK_ONLY 0x400U +#endif /* LWIP_SO_DONTROUTE */ + +/** indicates this pbuf need to be sent nonsecure manner */ +#define PBUF_FLAG_WITH_ENCRYPTION 0x400U + +#if LWIP_IPV6 && (LWIP_RPL || LWIP_RIPPLE) +#define PBUF_FLAG_6LO_PKT 0x1000U +#endif /* LWIP_IPV6 && (LWIP_RPL || LWIP_RIPPLE) */ + +#define PBUF_FLAG_CTRL_PKT 0x2000U + +/** Indicates the main packet buffer struct. */ +struct pbuf { + /** Indicates the next pbuf in singly-linked pbuf chain. */ + struct pbuf *next; + + /** Indicates a pointer to the actual data in the buffer. */ + void *payload; + + /** + * Indicates the total length of the buffer and all next buffers in chain + * belonging to the same packet. + * + * For non-queue packet chains this is the invariant: + * p->tot_len == p->len + (p->next? p->next->tot_len: 0) + */ + u16_t tot_len; + + /** Indicates the length of the buffer. */ + u16_t len; + + struct pbuf *list; + + /** + * Indicates the reference count. This is always equal to the number of pointers + * that refer to this pbuf. The pointers can be pointers from an application, + * the stack itself, or pbuf->next pointers from a chain. + */ + atomic_t ref; +#if (MEM_MALLOC_DMA_ALIGN != 1) + struct pbuf_dma_info *dma_info; +#endif +#if MEM_PBUF_RAM_SIZE_LIMIT + u16_t malloc_len; +#endif + + /** Indicates miscellaneous flags. */ + u16_t flags; + /** Indicates pbuf_type as u8_t instead of enum to save space. */ + u16_t type_internal; /* pbuf_type */ + + /** For incoming packets, this contains the input netif's index */ + u8_t if_idx; + +#if LWIP_RIPPLE + u8_t pkt_up; + u8_t pkt_flags; +#endif +#if LWIP_RIPPLE && defined(LWIP_NA_PROXY) && LWIP_NA_PROXY + u8_t na_proxy; +#endif +#if LWIP_IPV6 +#if LWIP_RPL || LWIP_RIPPLE +#if LWIP_USE_L2_METRICS + u8_t mac_address[NETIF_MAX_HWADDR_LEN]; + s8_t pkt_rssi; + u8_t pkt_lqi; +#endif +#endif +#endif + +#if LWIP_SO_PRIORITY + prio_t priority; +#endif /* LWIP_SO_PRIORITY */ + +#if MEM_PBUF_RAM_SIZE_LIMIT +#if LWIP_SO_PRIORITY +#if LWIP_PLC + u8_t pad[2]; +#else /* LWIP_PLC */ + u8_t pad[1]; +#endif /* LWIP_PLC */ +#else /* LWIP_SO_PRIORITY */ + u8_t pad[2]; +#endif /* LWIP_SO_PRIORITY */ +#else /* MEM_PBUF_RAM_SIZE_LIMIT */ +#if LWIP_SO_PRIORITY +#if (LWIP_PLC == 0) + u8_t pad[3]; +#endif /* LWIP_PLC == 0 */ +#endif /* LWIP_SO_PRIORITY */ +#endif /* MEM_PBUF_RAM_SIZE_LIMIT */ +}; + +/** Helper struct for const-correctness only. + * The purpose of this struct is to provide a const payload pointer + * for PBUF_ROM type. + */ +struct pbuf_rom { + /** Indicates the next pbuf in singly linked pbuf chain. */ + struct pbuf *next; + + /** Indicates a pointer to the actual data in the buffer. */ + const void *payload; +}; + +#if LWIP_SUPPORT_CUSTOM_PBUF +/** Indicates the prototype for a function to free a custom pbuf. */ +typedef void (*pbuf_free_custom_fn)(struct pbuf *p); + +/** Indicates a custom pbuf. This is similar to a pbuf, but following a function pointer to free it. */ +struct pbuf_custom { + /** Indicates the actual pbuf. */ + struct pbuf pbuf; + /** This function is called when pbuf_free deallocates this pbuf(_custom) */ + pbuf_free_custom_fn custom_free_function; +}; +#endif /* LWIP_SUPPORT_CUSTOM_PBUF */ + +/** Define this to 0 to prevent freeing ooseq pbufs when the PBUF_POOL is empty */ +#ifndef PBUF_POOL_FREE_OOSEQ +#define PBUF_POOL_FREE_OOSEQ 1 +#endif /* PBUF_POOL_FREE_OOSEQ */ +#if LWIP_TCP && TCP_QUEUE_OOSEQ && NO_SYS && PBUF_POOL_FREE_OOSEQ +extern volatile u8_t pbuf_free_ooseq_pending; +void pbuf_free_ooseq(void); +/** When not using sys_check_timeouts(), call PBUF_CHECK_FREE_OOSEQ() + at regular intervals from main level to check if ooseq pbufs need to be + freed! */ +#define PBUF_CHECK_FREE_OOSEQ() do { if (pbuf_free_ooseq_pending) { \ + /* pbuf_alloc() reported PBUF_POOL to be empty -> try to free some \ + ooseq queued pbufs now */ \ + pbuf_free_ooseq(); } }while (0) +#else /* LWIP_TCP && TCP_QUEUE_OOSEQ && NO_SYS && PBUF_POOL_FREE_OOSEQ */ +/* Otherwise declare an empty PBUF_CHECK_FREE_OOSEQ */ +#define PBUF_CHECK_FREE_OOSEQ() +#endif /* LWIP_TCP && TCP_QUEUE_OOSEQ && NO_SYS && PBUF_POOL_FREE_OOSEQ */ + +/* Initializes the pbuf module. This call is empty for now, but may not be in future. */ +#define pbuf_init() + +#define pbuf_set_encypted(pbuffer) \ + pbuffer->flags |= PBUF_FLAG_WITH_ENCRYPTION + +#if LWIP_IPV6 +#if LWIP_RPL || LWIP_RIPPLE +#if LWIP_USE_L2_METRICS +#define PBUF_SET_RSSI(pbuffer, rssi) \ + pbuffer->pkt_rssi = rssi + +#define PBUF_GET_RSSI(pbuffer) \ + pbuffer->pkt_rssi + +#define PBUF_SET_LQI(pbuffer, lqi) \ + pbuffer->pkt_lqi = lqi + +#define PBUF_GET_LQI(pbuffer) \ + pbuffer->pkt_lqi +#endif /* LWIP_USE_L2_METRICS */ +#endif /* LWIP_RPL || LWIP_RIPPLE */ +#endif /* LWIP_IPV6 */ + +u8_t pbuf_ram_in_deflation(void); +struct pbuf *pbuf_alloc(pbuf_layer l, u16_t length, pbuf_type type); +struct pbuf *pbuf_alloc_for_rx(pbuf_layer layer, u16_t length); + +#if LWIP_SUPPORT_CUSTOM_PBUF +struct pbuf *pbuf_alloced_custom(pbuf_layer l, u16_t length, pbuf_type type, + struct pbuf_custom *p, void *payload_mem, + u16_t payload_mem_len); +#endif /* LWIP_SUPPORT_CUSTOM_PBUF */ +void pbuf_realloc(struct pbuf *p, u16_t size); +#define pbuf_get_allocsrc(p) ((p)->type_internal & PBUF_TYPE_ALLOC_SRC_MASK) +#define pbuf_match_allocsrc(p, type) (pbuf_get_allocsrc(p) == ((type) & PBUF_TYPE_ALLOC_SRC_MASK)) +#define pbuf_match_type(p, type) pbuf_match_allocsrc(p, type) +u8_t pbuf_header(struct pbuf *p, s16_t header_size); +u8_t pbuf_header_force(struct pbuf *p, s16_t header_size); +u8_t pbuf_add_header(struct pbuf *p, size_t header_size_increment); +u8_t pbuf_add_header_force(struct pbuf *p, size_t header_size_increment); +u8_t pbuf_remove_header(struct pbuf *p, size_t header_size); +struct pbuf *pbuf_free_header(struct pbuf *q, u16_t size); +void pbuf_ref(struct pbuf *p); +u8_t pbuf_free(struct pbuf *p); +u16_t pbuf_clen(const struct pbuf *p); +void pbuf_cat(struct pbuf *head, struct pbuf *tail); +void pbuf_chain(struct pbuf *head, struct pbuf *tail); +#if LWIP_API_RICH +/** + * Dechains the first pbuf from its succeeding pbufs in the chain. This function makes p->tot_len field equal to p->len. + * @param[in] p Indicates the pbuf to dechain. + * @return Returns the remainder of the pbuf chain, or NULL if it was de-allocated. + * @note + * - Do not call this function on a packet queue. + * - The PBUF_API macro must be enabled by the application in case the pbuf APIs are + * directly used by the application code. This macro enables NULL validations and can have a performance impact. + */ +struct pbuf *pbuf_dechain(struct pbuf *p); +#endif /* LWIP_API_RICH */ +err_t pbuf_copy(struct pbuf *p_to, const struct pbuf *p_from); +u16_t pbuf_copy_partial(const struct pbuf *p, void *dataptr, u16_t len, u16_t offset); +#if LWIP_IPV6_DHCP6 +void *pbuf_get_contiguous(const struct pbuf *p, void *buffer, size_t bufsize, u16_t len, u16_t offset); +#endif /* LWIP_IPV6_DHCP6 */ +err_t pbuf_take(struct pbuf *buf, const void *dataptr, u16_t len); +/** + * @ingroup pbuf + * @brief This function is the same as pbuf_take(), but puts data at an offset. + * + * @param buf Indicates the pbuf to fill with data. + * @param dataptr Indicates the application supplied data buffer. + * @param len Indicates the length of the application supplied data buffer. + * @param offset Indicates the offset in pbuf to copy dataptr to. + * + * @return ERR_OK if successful, ERR_MEM if the pbuf is not big enough. + * @note The PBUF_API macro must be enabled by the application in case the pbuf APIs are directly used by + * the application code. This macro enables NULL validations and can have a performance impact. + */ +err_t pbuf_take_at(struct pbuf *buf, const void *dataptr, u16_t len, u16_t offset); +struct pbuf *pbuf_skip(struct pbuf *in, u16_t in_offset, u16_t *out_offset); +#if LWIP_API_RICH +/** + * @ingroup pbuf + * @brief + * Creates a single pbuf from a queue of pbufs. This function either frees or returns the pbuf 'p'. + * Therefore, the caller must check the result. + * + * @param p the Indicates the source pbuf. + * @param layer Indicates the pbuf_layer of the new pbuf. + * + * @return Returns a new, single pbuf (p->next is NULL) or returns the old pbuf if allocation fails. + * @note The PBUF_API macro must be enabled by the application in case the pbuf APIs are directly used + * by the application code. This macro enables NULL validations and can have a performance impact. + */ +struct pbuf *pbuf_coalesce(struct pbuf *p, pbuf_layer layer); +#endif /* LWIP_API_RICH */ +struct pbuf *pbuf_clone(pbuf_layer l, pbuf_type type, struct pbuf *p); +#if (MEM_MALLOC_DMA_ALIGN != 1) +#if LWIP_API_RICH +struct pbuf *pbuf_dma_alloc(u16_t len); +err_t pbuf_dma_ref(struct pbuf_dma_info *dma_info); +#endif /* LWIP_API_RICH */ +void pbuf_dma_free(struct pbuf_dma_info *dma_info); +#endif + +#if LWIP_CHECKSUM_ON_COPY +#if LWIP_API_RICH +err_t pbuf_fill_chksum(struct pbuf *p, u16_t start_offset, const void *dataptr, + u16_t len, u16_t *chksum); +#endif /* LWIP_API_RICH */ +#endif /* LWIP_CHECKSUM_ON_COPY */ +#if LWIP_TCP && TCP_QUEUE_OOSEQ && LWIP_WND_SCALE +/** + * @ingroup pbuf + * @brief + * This method modifies a pbuf chain, so that its total length is + * smaller than 64K. The remainder of the original pbuf chain is stored + * in *rest. + * This function does not create new pbufs. Instead, it splits an existing chain + * in two parts. The total length of the modified packet queue will be + * smaller than 64K. This function does not support packet queues. + * + * @param[in] p Indicates the pbuf queue to be split. + * @param[in] rest Indicates the pointer to store the remainder (after the first 64K) of the original pbuf chain. + * @note + * The PBUF_API macro must be enabled by the application in case the pbuf APIs + * are directly used by the application code. This macro enables NULL validations and can have a performance impact. + */ +void pbuf_split_64k(struct pbuf *p, struct pbuf **rest); +#endif /* LWIP_TCP && TCP_QUEUE_OOSEQ && LWIP_WND_SCALE */ +/** + * @ingroup pbuf + * @brief + * Gets one byte from the specified position in a pbuf. + * + * + * @param p Indicates the pbuf to parse. + * @param offset Indicates the offset into p of the byte to return. + * The offset must be set to a value less than p->tot_len. + * @return Returns a byte at an offset into p, or zero if offset >= p->tot_len. + */ +u8_t pbuf_get_at(const struct pbuf *p, u16_t offset); +/** + * @ingroup pbuf + * @brief Gets one byte from the specified position in a pbuf. + * + * @param p Indicates the pbuf to parse. + * @param offset Indicates the offset into p of the byte to return. + * @return Returns a byte at an offset into p [0..0xFF] or negative if offset >= p->tot_len. + */ +int pbuf_try_get_at(const struct pbuf *p, u16_t offset); +void pbuf_put_at(struct pbuf *p, u16_t offset, u8_t data); +#if LWIP_API_RICH +/** + * @ingroup pbuf + * @brief + * Compares pbuf contents at a specified offset with memory s2, both of length n. + * + * @param p Indicates the pbuf to compare. + * @param offset Indicates the offset into p at which to start comparing. + * @param s2 Indicates the buffer to compare. + * @param n Indicates the length of buffer to compare. + * @return Returns zero if equal, nonzero otherwise (0xffff if p is too short, diff offset+1 otherwise) + * @note The PBUF_API macro must be enabled by the application in case the pbuf APIs are directly + * used by the application code. This macro enables NULL validations and can have a performance impact. + */ +u16_t pbuf_memcmp(const struct pbuf *p, u16_t offset, const void *s2, u16_t n); +/** + * @ingroup pbuf + * Finds the occurrence of mem (with length mem_len) in pbuf p, starting at offset + * start_offset. + * + * @param p Indicates the pbuf to search. The maximum length is 0xFFFE since 0xFFFF is used as + * return value 'not found'. + * @param mem Indicates the buffer contents to search for. + * @param mem_len Indicates the length of mem. + * @param start_offset Indicates the offset into p at which to start searching. + * @return Returns the index where mem was found in p, or returns 0xFFFF if mem was not found in p. + * @note The PBUF_API macro must be enabled by the application in case the pbuf APIs are directly + * used by the application code. This macro enables NULL validations and can have a performance impact. + */ +u16_t pbuf_memfind(const struct pbuf *p, const void *mem, u16_t mem_len, u16_t start_offset); + +/** + * Finds the occurrence of substr with length substr_len in pbuf p, starting at offset + * start_offset. + * + * @param p Indicates the pbuf to search. The maximum length is 0xFFFE since 0xFFFF is used as + * return value 'not found'. + * @param substr Indicates the string to search for in p, maximum length is 0xFFFE + * @return Returns 0xFFFF if substr was not found in p, or returns the index where it was found. + * @note The PBUF_API macro must be enabled by the application in case the pbuf APIs are directly + * used by the application code. This macro enables NULL validations and can have a performance impact. + */ +u16_t pbuf_strstr(const struct pbuf *p, const char *substr); +#endif /* LWIP_API_RICH */ + +#if MEM_PBUF_RAM_SIZE_LIMIT +/* + * Func Name: pbuf_ram_size_set + */ +/** + * @ingroup Buffer_Interfaces + * @pbrief + * This API is used to set the maximum buffer size of PBUF_RAM allocation. + * + * @param[in] ram_max_size Indicates the maximum RAM buffer size allowed. + * [The ram_max_size must be greater than PBUF_RAM_SIZE_MIN and less than 0x7FFFFFFF.] + * + * @returns + * Zero : On failure \n + * Non Zero value: Previous maximum RAM buffer size. + * @note + * The PBUF_API macro must be enabled by the application in case the pbuf APIs are + * directly used by the application code. This macro enables NULL validations and can have a performance impact. + */ +u32_t pbuf_ram_size_set(u32_t ram_max_size); +#ifdef LWIP_DEBUG +/* + * Func Name: pbuf_ram_display + */ +/** + * @ingroup Buffer_Interfaces + * @brief + * This API is used to display the pbuf RAM details. + * + * @par Parameter + * \n + * void + * @return + * void + * @note + * This API is enabled only if the LWIP_DEBUG macro is enabled. \n + * The PBUF_API macro must be enabled by the application in case the pbuf APIs are directly + used by the application code. This macro enables NULL validations and can have a performance impact. + */ +void pbuf_ram_display(void); +#endif +#endif +#if defined (__cplusplus) && __cplusplus +} +#endif +#endif /* LWIP_HDR_PBUF_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/plcip6.h b/sdk_liteos/third_party/lwip_sack/include/lwip/plcip6.h new file mode 100644 index 0000000000000000000000000000000000000000..fa491c62e06f3d7ac1d1b5139620df28764d377e --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/plcip6.h @@ -0,0 +1,32 @@ +/* + * Description: declaration of PLC IPv6 APIs + */ + +#ifndef LWIP_HDR_PLCIP6_H +#define LWIP_HDR_PLCIP6_H + +#include "lwip/opt.h" + +#if LWIP_IPV6 && LWIP_PLC /* don't build if not configured for use in +lwipopts.h */ + +#include "lwip/pbuf.h" +#include "lwip/ip6.h" +#include "lwip/ip6_addr.h" +#include "lwip/netif.h" + +#ifdef __cplusplus +extern "C" { +#endif + +err_t output_ip6_onplc(struct netif *netif, struct pbuf *p, + const ip6_addr_t *ip6addr); + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_IPV6 && LWIP_ETHERNET */ + +#endif /* LWIP_HDR_PLCIP6_H */ + diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/priv/api_msg.h b/sdk_liteos/third_party/lwip_sack/include/lwip/priv/api_msg.h new file mode 100644 index 0000000000000000000000000000000000000000..57d31b8a4dc6e6e6ce4a44812b38eadff1541c3d --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/priv/api_msg.h @@ -0,0 +1,295 @@ +/** + * @file + * netconn API lwIP internal implementations (do not use in application code) + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_API_MSG_H +#define LWIP_HDR_API_MSG_H + +#include "lwip/opt.h" + +#if LWIP_NETCONN || LWIP_SOCKET /* don't build if not configured for use in lwipopts.h */ +/* + * Note: Netconn API is always available when sockets are enabled - + * sockets are implemented on top of them + */ +#include "lwip/arch.h" +#include "lwip/ip_addr.h" +#include "lwip/err.h" +#include "lwip/sys.h" +#include "lwip/igmp.h" +#include "lwip/api.h" +#include "lwip/priv/tcpip_priv.h" + +#if LWIP_DNS_REVERSE +#include "lwip/netdb.h" +#endif + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +#if LWIP_MPU_COMPATIBLE +#if LWIP_NETCONN_SEM_PER_THREAD +#define API_MSG_M_DEF_SEM(m) *m +#else +#define API_MSG_M_DEF_SEM(m) API_MSG_M_DEF(m) +#endif +#else /* LWIP_MPU_COMPATIBLE */ +#define API_MSG_M_DEF_SEM(m) API_MSG_M_DEF(m) +#endif /* LWIP_MPU_COMPATIBLE */ + +/* For the netconn API, these values are use as a bitmask! */ +#define NETCONN_SHUT_RD 1 +#define NETCONN_SHUT_WR 2 +#define NETCONN_SHUT_RDWR (NETCONN_SHUT_RD | NETCONN_SHUT_WR) + +/* RST is received and is pending to be handled */ +#define NETCONN_PENDING_ERR_RST 1 +/* Close event is pending to be handled in refused data (when recvmbox is full) */ +#define NETCONN_PENDING_ERR_CLSD 2 +/* RST is ready to be handled after NETCONN_PENDING_ERR_CLSD */ +#define NETCONN_READY_ERR_RST 3 +/* FIN and RST received in the order, yet to be processed */ +#define NETCONN_PENDING_ERR_FIN_RST 4 + +#if LWIP_TCP +extern u8_t netconn_reset; +#endif + +#if PF_PKT_SUPPORT +/* Packet Types */ +#define PACKET_HOST 0 /* To us */ +#define PACKET_BROADCAST 1 /* To all */ +#define PACKET_MULTICAST 2 /* To group */ +#define PACKET_OTHERHOST 3 /* To someone else */ +#define PACKET_OUTGOING 4 +#endif + +/* + * IP addresses and port numbers are expected to be in + * the same byte order as in the corresponding pcb. + */ +/** This struct includes everything that is necessary to execute a function + for a netconn in another thread context (mainly used to process netconns + in the tcpip_thread context to be thread safe). */ +struct api_msg { + /** The netconn which to process - always needed: it includes the semaphore + which is used to block the application thread until the function finished. */ + struct netconn *conn; + /** The return value of the function executed in tcpip_thread. */ + err_t err; + /** Depending on the executed function, one of these union members is used */ + union { + struct tcpip_conn *conn_info; + /** used for lwip_netconn_do_send */ + struct netbuf *b; + /** used for lwip_netconn_do_newconn */ + struct { +#if PF_PKT_SUPPORT + u16_t proto; +#else + u8_t proto; +#endif + } n; + /** used for lwip_netconn_do_bind and lwip_netconn_do_connect */ + struct { + API_MSG_M_DEF_C(ip_addr_t, ipaddr); + u16_t port; +#if PF_PKT_SUPPORT + u8_t netifindex; +#endif + } bc; + /** used for lwip_netconn_do_getaddr */ + struct { + ip_addr_t API_MSG_M_DEF(ipaddr); + u16_t API_MSG_M_DEF(port); + u8_t local; + } ad; + /** used for lwip_netconn_do_write */ + struct { + const void *dataptr; + size_t len; + u8_t apiflags; +#if LWIP_SO_SNDTIMEO + u32_t time_started; +#endif /* LWIP_SO_SNDTIMEO */ + } w; + /** used for lwip_netconn_do_recv */ + struct { + u32_t len; + } r; +#if LWIP_TCP + /** used for lwip_netconn_do_close (/shutdown) */ + struct { + u8_t shut; +#if LWIP_SO_SNDTIMEO || LWIP_SO_LINGER + u32_t time_started; +#else /* LWIP_SO_SNDTIMEO || LWIP_SO_LINGER */ + u8_t polls_left; +#endif /* LWIP_SO_SNDTIMEO || LWIP_SO_LINGER */ + } sd; +#endif /* LWIP_TCP */ +#if LWIP_IGMP || (LWIP_IPV6 && LWIP_IPV6_MLD) + /* used for lwip_netconn_do_leave_group */ + struct { + API_MSG_M_DEF_C(ip_addr_t, multiaddr); + API_MSG_M_DEF_C(ip_addr_t, netif_addr); + u8_t if_idx; + enum netconn_igmp join_or_leave; + } jl; +#endif /* LWIP_IGMP || (LWIP_IPV6 && LWIP_IPV6_MLD) */ +#if TCP_LISTEN_BACKLOG + struct { + u8_t backlog; + } lb; +#endif /* TCP_LISTEN_BACKLOG */ + } msg; +#if LWIP_NETCONN_SEM_PER_THREAD + sys_sem_t *op_completed_sem; +#endif /* LWIP_NETCONN_SEM_PER_THREAD */ +}; + +#if LWIP_NETCONN_SEM_PER_THREAD +#define LWIP_API_MSG_SEM(msg) ((msg)->op_completed_sem) +#else /* LWIP_NETCONN_SEM_PER_THREAD */ +#define LWIP_API_MSG_SEM(msg) (&(msg)->conn->op_completed) +#endif /* LWIP_NETCONN_SEM_PER_THREAD */ + + +#if LWIP_DNS +/** As lwip_netconn_do_gethostbyname requires more arguments but doesn't require a netconn, + it has its own struct (to avoid struct api_msg getting bigger than necessary). + lwip_netconn_do_gethostbyname must be called using tcpip_callback instead of tcpip_apimsg + (see netconn_gethostbyname). */ +struct dns_api_msg { + /** Hostname to query or dotted IP address string */ +#if LWIP_MPU_COMPATIBLE + char name[DNS_MAX_NAME_LENGTH]; +#else /* LWIP_MPU_COMPATIBLE */ + const char *name; +#endif /* LWIP_MPU_COMPATIBLE */ + /** The resolved address is stored here */ + ip_addr_t API_MSG_M_DEF(addr); +#if LWIP_IPV4 && LWIP_IPV6 + /** Type of resolve call */ + u8_t dns_addrtype; +#endif /* LWIP_IPV4 && LWIP_IPV6 */ + /** This semaphore is posted when the name is resolved, the application thread + should wait on it. */ + sys_sem_t API_MSG_M_DEF_SEM(sem); + /** Errors are given back here */ + err_t API_MSG_M_DEF(err); + /* to check how many IPaddress are updated */ + u32_t *count; +}; + +#if LWIP_DNS_REVERSE +struct reverse_dns_api_msg { + /* The IP Address to be resolved to hostname via reverse DNS */ + ip_addr_t API_MSG_M_DEF(addr); + /* Resolved hostname of addr */ +#if LWIP_MPU_COMPATIBLE + char hostname[NI_MAXHOST]; +#else /* LWIP_MPU_COMPATIBLE */ + char *hostname; +#endif /* LWIP_MPU_COMPATIBLE */ + /* This semaphore is posted when the name is resolved, the application thread should wait on it. */ + sys_sem_t API_MSG_M_DEF_SEM(sem); + /* Errors are given back here */ + err_t API_MSG_M_DEF(err); +}; +#endif /* LWIP_DNS_REVERSE */ +#endif /* LWIP_DNS */ + +#if LWIP_TCP +extern u8_t netconn_aborted; +extern u8_t netconn_memory_err; + +#endif /* LWIP_TCP */ + +#if LWIP_LOWPOWER +/* check wether need to poll tcp */ +u8_t poll_tcp_needed(void *arg, struct tcp_pcb *pcb); +#endif + +void lwip_netconn_do_newconn (void *m); +void lwip_netconn_do_delconn (void *m); +void lwip_netconn_do_bind (void *m); +void lwip_netconn_do_connect (void *m); +void lwip_netconn_do_disconnect (void *m); +void lwip_netconn_do_listen (void *m); +void lwip_netconn_do_send (void *m); +void lwip_netconn_do_recv (void *m); +#if TCP_LISTEN_BACKLOG +void lwip_netconn_do_accepted (void *m); +#endif /* TCP_LISTEN_BACKLOG */ +void lwip_netconn_do_write (void *m); +void lwip_netconn_do_getaddr (void *m); +void lwip_netconn_do_close (void *m); +void lwip_netconn_do_shutdown (void *m); +#ifdef LWIP_GET_CONN_INFO +void do_getconninfo (void *m); +#endif /* LWIP_GET_CONN_INFO */ + +/* Internal functions */ +#if LWIP_IGMP || (LWIP_IPV6 && LWIP_IPV6_MLD) +void lwip_netconn_do_leave_group(void *m); + +#endif /* LWIP_IGMP || (LWIP_IPV6 && LWIP_IPV6_MLD) */ + +#if LWIP_DNS +void lwip_netconn_do_gethostbyname(void *arg); +#if LWIP_DNS_REVERSE +void lwip_netconn_do_getnamebyhost(void *arg); +#endif /* LWIP_DNS_REVERSE */ +#endif /* LWIP_DNS */ + +struct netconn *netconn_alloc(enum netconn_type t, netconn_callback callback); +void netconn_free(struct netconn *conn); + +#if LWIP_UDP +void recv_udp(void *arg, struct udp_pcb *pcb, struct pbuf *p, + const ip_addr_t *addr, u16_t port); +#endif +#if DRIVER_STATUS_CHECK +void update_tcp_sndplus_event(void *arg, struct tcp_pcb *pcb); +#endif +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_NETCONN || LWIP_SOCKET */ + +#endif /* LWIP_HDR_API_MSG_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/priv/mem_priv.h b/sdk_liteos/third_party/lwip_sack/include/lwip/priv/mem_priv.h new file mode 100644 index 0000000000000000000000000000000000000000..f27fc1d0653280c6aeb22f015ad3a1bec11b2c7f --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/priv/mem_priv.h @@ -0,0 +1,84 @@ +/** + * @file + * lwIP internal memory implementations (do not use in application code) + */ + +/* + * Copyright (c) 2018 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Simon Goldschmidt + * + */ + +#ifndef LWIP_HDR_MEM_PRIV_H +#define LWIP_HDR_MEM_PRIV_H + +#include "lwip/opt.h" + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +#include "lwip/mem.h" + +#if MEM_OVERFLOW_CHECK || MEMP_OVERFLOW_CHECK +/* if MEM_OVERFLOW_CHECK or MEMP_OVERFLOW_CHECK is turned on, we reserve some + * bytes at the beginning and at the end of each element, initialize them as + * 0xcd and check them later. + * If MEM(P)_OVERFLOW_CHECK is >= 2, on every call to mem(p)_malloc or mem(p)_free, + * every single element in each pool/heap is checked! + * This is VERY SLOW but also very helpful. + * MEM_SANITY_REGION_BEFORE and MEM_SANITY_REGION_AFTER can be overridden in + * lwipopts.h to change the amount reserved for checking. */ +#ifndef MEM_SANITY_REGION_BEFORE +#define MEM_SANITY_REGION_BEFORE 16 +#endif /* MEM_SANITY_REGION_BEFORE*/ +#if MEM_SANITY_REGION_BEFORE > 0 +#define MEM_SANITY_REGION_BEFORE_ALIGNED LWIP_MEM_ALIGN_SIZE(MEM_SANITY_REGION_BEFORE) +#else +#define MEM_SANITY_REGION_BEFORE_ALIGNED 0 +#endif /* MEM_SANITY_REGION_BEFORE*/ +#ifndef MEM_SANITY_REGION_AFTER +#define MEM_SANITY_REGION_AFTER 16 +#endif /* MEM_SANITY_REGION_AFTER*/ +#if MEM_SANITY_REGION_AFTER > 0 +#define MEM_SANITY_REGION_AFTER_ALIGNED LWIP_MEM_ALIGN_SIZE(MEM_SANITY_REGION_AFTER) +#else +#define MEM_SANITY_REGION_AFTER_ALIGNED 0 +#endif /* MEM_SANITY_REGION_AFTER*/ + +void mem_overflow_init_raw(void *p, size_t size); +void mem_overflow_check_raw(void *p, size_t size, const char *descr1, const char *descr2); + +#endif /* MEM_OVERFLOW_CHECK || MEMP_OVERFLOW_CHECK */ + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_HDR_MEMP_PRIV_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/priv/memp_priv.h b/sdk_liteos/third_party/lwip_sack/include/lwip/priv/memp_priv.h new file mode 100644 index 0000000000000000000000000000000000000000..c975c9fac683bd14b2f57ea58f1d0775bb9cbecf --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/priv/memp_priv.h @@ -0,0 +1,166 @@ +/** + * @file + * memory pools lwIP internal implementations (do not use in application code) + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ + +#ifndef LWIP_HDR_MEMP_PRIV_H +#define LWIP_HDR_MEMP_PRIV_H + +#include "lwip/opt.h" + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +#include "lwip/mem.h" +#include "lwip/priv/mem_priv.h" + +#if MEMP_OVERFLOW_CHECK + +/* MEMP_SIZE: save space for struct memp and for sanity check */ +#define MEMP_SIZE (LWIP_MEM_ALIGN_SIZE(sizeof(struct memp)) + MEM_SANITY_REGION_BEFORE_ALIGNED) +#define MEMP_ALIGN_SIZE(x) (LWIP_MEM_ALIGN_SIZE(x) + MEM_SANITY_REGION_AFTER_ALIGNED) + +#else /* MEMP_OVERFLOW_CHECK */ +/* + * No sanity checks + * We don't need to preserve the struct memp while not allocated, so we + * can save a little space and set MEMP_SIZE to 0. + */ +#define MEMP_SIZE 0 +#define MEMP_ALIGN_SIZE(x) (LWIP_MEM_ALIGN_SIZE(x)) + +#endif /* MEMP_OVERFLOW_CHECK */ + +#if !MEMP_MEM_MALLOC || MEMP_OVERFLOW_CHECK +struct memp { + struct memp *next; +#if MEMP_OVERFLOW_CHECK + const char *file; + int line; +#endif /* MEMP_OVERFLOW_CHECK */ +}; +#endif /* !MEMP_MEM_MALLOC || MEMP_OVERFLOW_CHECK */ + +#if MEM_USE_POOLS && MEMP_USE_CUSTOM_POOLS +/* Use a helper type to get the start and end of the user "memory pools" for mem_malloc */ +typedef enum { + /* Get the first (via: MEMP_POOL_HELPER_START = ((u8_t) 1*MEMP_POOL_A + 0*MEMP_POOL_B + 0*MEMP_POOL_C + 0) */ + MEMP_POOL_HELPER_FIRST = ((u8_t) +#define LWIP_MEMPOOL(name, num, size, desc) +#define LWIP_MALLOC_MEMPOOL_START 1 +#define LWIP_MALLOC_MEMPOOL(num, size) * MEMP_POOL_##size + 0 +#define LWIP_MALLOC_MEMPOOL_END +#include "lwip/priv/memp_std.h" + ), + /* Get the last (via: + MEMP_POOL_HELPER_END = ((u8_t) 0 + MEMP_POOL_A*0 + MEMP_POOL_B*0 + MEMP_POOL_C*1) */ + MEMP_POOL_HELPER_LAST = ((u8_t) +#define LWIP_MEMPOOL(name, num, size, desc) +#define LWIP_MALLOC_MEMPOOL_START +#define LWIP_MALLOC_MEMPOOL(num, size) 0 + MEMP_POOL_##size * +#define LWIP_MALLOC_MEMPOOL_END 1 +#include "lwip/priv/memp_std.h" + ) +} memp_pool_helper_t; + +/* The actual start and stop values are here (cast them over) + We use this helper type and these defines so we can avoid using const memp_t values */ +#define MEMP_POOL_FIRST ((memp_t) MEMP_POOL_HELPER_FIRST) +#define MEMP_POOL_LAST ((memp_t) MEMP_POOL_HELPER_LAST) +#endif /* MEM_USE_POOLS && MEMP_USE_CUSTOM_POOLS */ + +/** Memory pool descriptor */ +struct memp_desc { +#if defined(LWIP_DEBUG) || MEMP_OVERFLOW_CHECK || LWIP_STATS_DISPLAY + /** Textual description */ + const char *desc; +#endif /* LWIP_DEBUG || MEMP_OVERFLOW_CHECK || LWIP_STATS_DISPLAY */ +#if MEMP_STATS + /** Statistics */ + struct stats_mem *stats; +#endif + + /** Element size */ + u16_t size; + +#if !MEMP_MEM_MALLOC + /** Number of elements */ + u16_t num; + + /** Base address */ + u8_t *base; + + /** First free element of each pool. Elements form a linked list. */ + struct memp **tab; +#if LWIP_ALLOW_SOCKET_CONFIG + struct memp *tab_tail; +#endif +#endif /* MEMP_MEM_MALLOC */ +}; + +#if defined(LWIP_DEBUG) || MEMP_OVERFLOW_CHECK || LWIP_STATS_DISPLAY +#define DECLARE_LWIP_MEMPOOL_DESC(desc) (desc), +#else +#define DECLARE_LWIP_MEMPOOL_DESC(desc) +#endif + +#if MEMP_STATS +#define LWIP_MEMPOOL_DECLARE_STATS_INSTANCE(name) static struct stats_mem name; +#define LWIP_MEMPOOL_DECLARE_STATS_REFERENCE(name) &name, +#else +#define LWIP_MEMPOOL_DECLARE_STATS_INSTANCE(name) +#define LWIP_MEMPOOL_DECLARE_STATS_REFERENCE(name) +#endif + +#if LWIP_ALLOW_SOCKET_CONFIG +void memp_init_pool(const char *szdesc, u32_t num, u16_t size, u8_t type); +#else +void memp_init_pool(const struct memp_desc *desc); +#endif + +#if MEMP_OVERFLOW_CHECK +void *memp_malloc_pool_fn(const struct memp_desc *desc, const char *file, const int line); +#define memp_malloc_pool(d) memp_malloc_pool_fn((d), __FILE__, __LINE__) +#else +void *memp_malloc_pool(const struct memp_desc *desc); +#endif +void memp_free_pool(const struct memp_desc *desc, void *mem); + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_HDR_MEMP_PRIV_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/priv/memp_std.h b/sdk_liteos/third_party/lwip_sack/include/lwip/priv/memp_std.h new file mode 100644 index 0000000000000000000000000000000000000000..649bd2727f6bfc889bf3aef5edad9eb7136b02b6 --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/priv/memp_std.h @@ -0,0 +1,159 @@ +/** + * @file + * lwIP internal memory pools (do not use in application code) + * This file is deliberately included multiple times: once with empty + * definition of LWIP_MEMPOOL() to handle all includes and multiple times + * to build up various lists of mem pools. + */ + +/* + * SETUP: Make sure we define everything we will need. + * + * We have create three types of pools: + * 1) MEMPOOL - standard pools + * 2) MALLOC_MEMPOOL - to be used by mem_malloc in mem.c + * 3) PBUF_MEMPOOL - a mempool of pbuf's, so include space for the pbuf struct + * + * If the include'r doesn't require any special treatment of each of the types + * above, then will declare #2 & #3 to be just standard mempools. + */ +#ifndef LWIP_MALLOC_MEMPOOL +/* This treats "malloc pools" just like any other pool. + The pools are a little bigger to provide 'size' as the amount of user data. */ +#define LWIP_MALLOC_MEMPOOL(num, size) LWIP_MEMPOOL(POOL_##size, num, (size + LWIP_MEM_ALIGN_SIZE(sizeof(struct memp_malloc_helper))), "MALLOC_"#size) +#define LWIP_MALLOC_MEMPOOL_START +#define LWIP_MALLOC_MEMPOOL_END +#endif /* LWIP_MALLOC_MEMPOOL */ + +#ifndef LWIP_PBUF_MEMPOOL +/* This treats "pbuf pools" just like any other pool. + * Allocates buffers for a pbuf struct AND a payload size */ +#define LWIP_PBUF_MEMPOOL(name, num, payload, desc) LWIP_MEMPOOL(name, num, (MEMP_ALIGN_SIZE(sizeof(struct pbuf)) + MEMP_ALIGN_SIZE(payload)), desc) +#endif /* LWIP_PBUF_MEMPOOL */ + + +/* + * A list of internal pools used by LWIP. + * + * LWIP_MEMPOOL(pool_name, number_elements, element_size, pool_description) + * creates a pool name MEMP_pool_name. description is used in stats.c + */ +#if LWIP_RAW +LWIP_MEMPOOL(RAW_PCB, MEMP_NUM_RAW_PCB, sizeof(struct raw_pcb), "RAW_PCB") +#endif /* LWIP_RAW */ + +#if LWIP_UDP +LWIP_MEMPOOL(UDP_PCB, MEMP_NUM_UDP_PCB, sizeof(struct udp_pcb), "UDP_PCB") +#endif /* LWIP_UDP */ + +#if LWIP_TCP +LWIP_MEMPOOL(TCP_PCB, MEMP_NUM_TCP_PCB, sizeof(struct tcp_pcb), "TCP_PCB") +LWIP_MEMPOOL(TCP_PCB_LISTEN, MEMP_NUM_TCP_PCB_LISTEN, sizeof(struct tcp_pcb_listen), "TCP_PCB_LISTEN") +LWIP_MEMPOOL(TCP_SEG, MEMP_NUM_TCP_SEG, sizeof(struct tcp_seg), "TCP_SEG") +#endif /* LWIP_TCP */ + +#if LWIP_IPV4 && IP_REASSEMBLY +LWIP_MEMPOOL(REASSDATA, MEMP_NUM_REASSDATA, sizeof(struct ip_reassdata), "REASSDATA") +#endif /* LWIP_IPV4 && IP_REASSEMBLY */ +#if (IP_FRAG && !LWIP_NETIF_TX_SINGLE_PBUF) || (LWIP_IPV6 && LWIP_IPV6_FRAG) +LWIP_MEMPOOL(FRAG_PBUF, MEMP_NUM_FRAG_PBUF, sizeof(struct pbuf_custom_ref), "FRAG_PBUF") +#endif /* IP_FRAG && !LWIP_NETIF_TX_SINGLE_PBUF || (LWIP_IPV6 && LWIP_IPV6_FRAG) */ + +#if LWIP_NETCONN || LWIP_SOCKET +LWIP_MEMPOOL(NETBUF, MEMP_NUM_NETBUF, sizeof(struct netbuf), "NETBUF") +LWIP_MEMPOOL(NETCONN, MEMP_NUM_NETCONN, sizeof(struct netconn), "NETCONN") +#endif /* LWIP_NETCONN || LWIP_SOCKET */ + +#if NO_SYS==0 +LWIP_MEMPOOL(TCPIP_MSG_API, MEMP_NUM_TCPIP_MSG_API, sizeof(struct tcpip_msg), "TCPIP_MSG_API") +#if LWIP_MPU_COMPATIBLE +LWIP_MEMPOOL(API_MSG, MEMP_NUM_API_MSG, sizeof(struct api_msg), "API_MSG") +#if LWIP_DNS +LWIP_MEMPOOL(DNS_API_MSG, MEMP_NUM_DNS_API_MSG, sizeof(struct dns_api_msg), "DNS_API_MSG") +#endif +#if LWIP_SOCKET && !LWIP_TCPIP_CORE_LOCKING +LWIP_MEMPOOL(SOCKET_SETGETSOCKOPT_DATA, MEMP_NUM_SOCKET_SETGETSOCKOPT_DATA, sizeof(struct lwip_setgetsockopt_data), + "SOCKET_SETGETSOCKOPT_DATA") +#endif +#if LWIP_NETIF_API +LWIP_MEMPOOL(NETIFAPI_MSG, MEMP_NUM_NETIFAPI_MSG, sizeof(struct netifapi_msg), "NETIFAPI_MSG") +#endif +#endif /* LWIP_MPU_COMPATIBLE */ +#if !LWIP_TCPIP_CORE_LOCKING_INPUT +LWIP_MEMPOOL(TCPIP_MSG_INPKT, MEMP_NUM_TCPIP_MSG_INPKT, sizeof(struct tcpip_msg), "TCPIP_MSG_INPKT") +#endif /* !LWIP_TCPIP_CORE_LOCKING_INPUT */ +#endif /* NO_SYS==0 */ + +#if LWIP_IPV4 && LWIP_ARP && ARP_QUEUEING +LWIP_MEMPOOL(ARP_QUEUE, MEMP_NUM_ARP_QUEUE, sizeof(struct etharp_q_entry), "ARP_QUEUE") +#endif /* LWIP_IPV4 && LWIP_ARP && ARP_QUEUEING */ + +#if LWIP_IGMP +LWIP_MEMPOOL(IGMP_GROUP, MEMP_NUM_IGMP_GROUP, sizeof(struct igmp_group), "IGMP_GROUP") +#endif /* LWIP_IGMP */ + +#if LWIP_TIMERS && !LWIP_TIMERS_CUSTOM +#if LWIP_LOWPOWER +LWIP_MEMPOOL(SYS_TIMEOUT, MEMP_NUM_SYS_TIMEOUT_LOW, sizeof(struct timer_entry), "SYS_TIMEOUT") +LWIP_MEMPOOL(TCPIP_MSG_LOWPOWER, MEMP_NUM_TCPIP_MSG_LOWPOWER, sizeof(struct tcpip_msg), "TCPIP_MSG_NA") +#else +LWIP_MEMPOOL(SYS_TIMEOUT, MEMP_NUM_SYS_TIMEOUT, sizeof(struct sys_timeo), "SYS_TIMEOUT") +#endif /* LWIP_LOWPOWER */ +#endif /* LWIP_TIMERS && !LWIP_TIMERS_CUSTOM */ + +#if LWIP_L3_EVENT_MSG +LWIP_MEMPOOL(L3_EVENT_MSG, MEMP_NUM_L3_EVENT_MSG, sizeof(struct tcpip_msg), "L3_EVENT_MSG") +#endif /* LWIP_L3_EVENT_MSG */ + +#if LWIP_DNS && LWIP_SOCKET +LWIP_MEMPOOL(NETDB, MEMP_NUM_NETDB, NETDB_ELEM_SIZE, "NETDB") +#endif /* LWIP_DNS && LWIP_SOCKET */ +#if LWIP_DNS && DNS_LOCAL_HOSTLIST && DNS_LOCAL_HOSTLIST_IS_DYNAMIC +LWIP_MEMPOOL(LOCALHOSTLIST, MEMP_NUM_LOCALHOSTLIST, LOCALHOSTLIST_ELEM_SIZE, "LOCALHOSTLIST") +#endif /* LWIP_DNS && DNS_LOCAL_HOSTLIST && DNS_LOCAL_HOSTLIST_IS_DYNAMIC */ + +#if LWIP_IPV6 && LWIP_ND6_QUEUEING +LWIP_MEMPOOL(ND6_QUEUE, MEMP_NUM_ND6_QUEUE, sizeof(struct nd6_q_entry), "ND6_QUEUE") +#endif /* LWIP_IPV6 && LWIP_ND6_QUEUEING */ + +#if LWIP_IPV6 && LWIP_IPV6_REASS +LWIP_MEMPOOL(IP6_REASSDATA, MEMP_NUM_REASSDATA, sizeof(struct ip6_reassdata), "IP6_REASSDATA") +#endif /* LWIP_IPV6 && LWIP_IPV6_REASS */ + +#if LWIP_IPV6 && LWIP_IPV6_MLD +LWIP_MEMPOOL(MLD6_GROUP, MEMP_NUM_MLD6_GROUP, sizeof(struct mld_group), "MLD6_GROUP") +#endif /* LWIP_IPV6 && LWIP_IPV6_MLD */ + +#if LWIP_RPL +LWIP_MEMPOOL(RPL_API_MSG, MEMP_NUM_RPL_API_MSG, sizeof(struct rplapi_msg), "RPL_API_MSG") +#endif + +/* + * A list of pools of pbuf's used by LWIP. + * + * LWIP_PBUF_MEMPOOL(pool_name, number_elements, pbuf_payload_size, pool_description) + * creates a pool name MEMP_pool_name. description is used in stats.c + * This allocates enough space for the pbuf struct and a payload. + * (Example: pbuf_payload_size=0 allocates only size for the struct) + */ +LWIP_PBUF_MEMPOOL(PBUF, MEMP_NUM_PBUF, 0, "PBUF_REF/ROM") +LWIP_PBUF_MEMPOOL(PBUF_POOL, PBUF_POOL_SIZE, PBUF_POOL_BUFSIZE, "PBUF_POOL") + + +/* + * Allow for user-defined pools; this must be explicitly set in lwipopts.h + * since the default is to NOT look for lwippools.h + */ +#if MEMP_USE_CUSTOM_POOLS +#include "lwippools.h" +#endif /* MEMP_USE_CUSTOM_POOLS */ + +/* + * REQUIRED CLEANUP: Clear up so we don't get "multiply defined" error later + * (#undef is ignored for something that is not defined) + */ +#undef LWIP_MEMPOOL +#undef LWIP_MALLOC_MEMPOOL +#undef LWIP_MALLOC_MEMPOOL_START +#undef LWIP_MALLOC_MEMPOOL_END +#undef LWIP_PBUF_MEMPOOL diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/priv/nd6_priv.h b/sdk_liteos/third_party/lwip_sack/include/lwip/priv/nd6_priv.h new file mode 100644 index 0000000000000000000000000000000000000000..a2cf946f256199faa5619c71a501d1ae78a1745c --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/priv/nd6_priv.h @@ -0,0 +1,181 @@ +/** + * @file + * + * Neighbor discovery and stateless address autoconfiguration for IPv6. + * Aims to be compliant with RFC 4861 (Neighbor discovery) and RFC 4862 + * (Address autoconfiguration). + */ + +/* + * Copyright (c) 2010 Inico Technologies Ltd. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Ivan Delamer + * + * + * Please coordinate changes and requests with Ivan Delamer + * + */ + +#ifndef LWIP_HDR_ND6_PRIV_H +#define LWIP_HDR_ND6_PRIV_H + +#include "lwip/opt.h" + +#if LWIP_IPV6 /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/pbuf.h" +#include "lwip/ip6_addr.h" +#include "lwip/netif.h" +#include "lwip/link_quality.h" + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +#define LWIP_IS_DEPRECATED(validation_timer, diff_preferred_lifetime) \ + (diff_preferred_lifetime > validation_timer) + +/* + * API netifapi_add_prefix: adds prefixes with infinite time. so these macros + * implements the infinte timer. + */ +#if LWIP_ND6_STATIC_PREFIX || LWIP_ND6_STATIC_DEFAULT_ROUTE || LWIP_RPL || LWIP_RIPPLE +#ifndef LWIP_INFINITE_TIMER +#define LWIP_INFINITE_TIMER 0xffffffff +#endif +#endif + +#if LWIP_ND6_QUEUEING +/** struct for queueing outgoing packets for unknown address + * defined here to be accessed by memp.h + */ +struct nd6_q_entry { + struct nd6_q_entry *next; + struct pbuf *p; +}; +#endif /* LWIP_ND6_QUEUEING */ + +/** Struct for tables. */ +struct nd6_neighbor_cache_entry { + ip6_addr_t next_hop_address; + struct netif *netif; + u8_t lladdr[NETIF_MAX_HWADDR_LEN]; + u8_t lladdrlen; + /* u32_t pmtu; */ +#if LWIP_ND6_QUEUEING + /** Pointer to queue of pending outgoing packets on this entry. */ + struct nd6_q_entry *q; +#else /* LWIP_ND6_QUEUEING */ + /** Pointer to a single pending outgoing packet on this entry. */ + struct pbuf *q; +#endif /* LWIP_ND6_QUEUEING */ + u8_t state; + u8_t isrouter; + union { + u32_t reachable_time; /* in ms since value may originate from network packet */ + u32_t delay_time; /* ticks (ND6_TMR_INTERVAL) */ + u32_t probes_sent; + u32_t stale_time; /* ticks (ND6_TMR_INTERVAL) */ + } counter; + +#if LWIP_ENABLE_ROUTER && LWIP_RPL + lwip_nbr_linkquality_t nbrlinkquality; +#endif +}; + +struct nd6_destination_cache_entry { + ip6_addr_t destination_addr; + ip6_addr_t next_hop_addr; + u16_t pmtu; + u32_t age; +}; + +struct nd6_prefix_list_entry { + ip6_addr_t prefix; + struct netif *netif; + u32_t invalidation_timer; /* in seconds */ + u8_t prefix_len; + u8_t is_static: 1; +}; + +struct nd6_router_list_entry { + struct nd6_neighbor_cache_entry *neighbor_entry; + u32_t invalidation_timer; /* in seconds */ + u8_t flags; + u8_t is_static: 1; +}; + +enum nd6_neighbor_cache_entry_state { + ND6_NO_ENTRY = 0, + ND6_INCOMPLETE, + ND6_REACHABLE, + ND6_STALE, + ND6_DELAY, + ND6_PROBE +#if LWIP_ND6_STATIC_NBR + , ND6_PERMANENT +#endif +}; + +#if LWIP_RPL || LWIP_RIPPLE +extern void lwip_ipv6_neighbor_callback(const struct nd6_neighbor_cache_entry *nbr); +/* only define the callback if RPL is active */ +#ifndef LWIP_CONF_ND6_NEIGHBOR_STATE_CHANGED +#define LWIP_CONF_ND6_NEIGHBOR_STATE_CHANGED lwip_ipv6_neighbor_callback +#endif /* LWIP_CONF_ND6_NEIGHBOR_STATE_CHANGED */ +#endif /* LWIP_RPL || LWIP_RIPPLE */ + +#if LWIP_RIPPLE +#ifndef LWIP_CONF_UPDATE_BEACON_PRIORITY +#define LWIP_CONF_UPDATE_BEACON_PRIORITY 1 +#endif /* LWIP_CONF_UPDATE_BEACON_PRIORITY */ +#else +#ifndef LWIP_CONF_UPDATE_BEACON_PRIORITY +#define LWIP_CONF_UPDATE_BEACON_PRIORITY 0 +#endif /* LWIP_CONF_UPDATE_BEACON_PRIORITY */ +#endif +#define ND6_2HRS 7200 /* two hours, expressed in number of seconds */ + +/* Router tables. */ +/* @todo make these static? and entries accessible through API? */ +extern struct nd6_neighbor_cache_entry neighbor_cache[LWIP_ND6_NUM_NEIGHBORS]; +extern struct nd6_destination_cache_entry destination_cache[LWIP_ND6_NUM_DESTINATIONS]; +extern struct nd6_prefix_list_entry prefix_list[LWIP_ND6_NUM_PREFIXES]; +extern struct nd6_router_list_entry default_router_list[LWIP_ND6_NUM_ROUTERS]; + +/* Default values, can be updated by a RA message. */ +extern u32_t reachable_time; +extern u32_t retrans_timer; + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_IPV6 */ + +#endif /* LWIP_HDR_ND6_PRIV_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/priv/raw_priv.h b/sdk_liteos/third_party/lwip_sack/include/lwip/priv/raw_priv.h new file mode 100644 index 0000000000000000000000000000000000000000..59718ca3393c6af24b758bf28f2e0b7a3ec115ca --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/priv/raw_priv.h @@ -0,0 +1,61 @@ +/** + * @file + * raw API internal implementations (do not use in application code) + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_RAW_PRIV_H +#define LWIP_HDR_RAW_PRIV_H + +#include "lwip/opt.h" + +#if LWIP_RAW /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/raw.h" + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +/* The following functions are the lower layer interface to RAW. */ +u8_t raw_input(struct pbuf *p, struct netif *inp); + +void raw_netif_ip_addr_changed(const ip_addr_t* old_addr, const ip_addr_t* new_addr); + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_RAW */ + +#endif /* LWIP_HDR_RAW_PRIV_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/priv/sockets_priv.h b/sdk_liteos/third_party/lwip_sack/include/lwip/priv/sockets_priv.h new file mode 100644 index 0000000000000000000000000000000000000000..b412a1936f7766908d90f6177701b1f98f18f7f2 --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/priv/sockets_priv.h @@ -0,0 +1,97 @@ +/** + * @file + * Sockets API internal implementations (do not use in application code) + */ + +/* + * Copyright (c) 2017 Joel Cunningham, Garmin International, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Joel Cunningham + * + */ +#ifndef LWIP_HDR_SOCKETS_PRIV_H +#define LWIP_HDR_SOCKETS_PRIV_H + +#include "lwip/opt.h" + +#if LWIP_SOCKET /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/err.h" +#include "lwip/sockets.h" + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +#if LWIP_SOCKET_SET_ERRNO +#ifndef set_errno +#define set_errno(err) do { if (err) { errno = (err); } } while(0) +#endif +#else /* LWIP_SOCKET_SET_ERRNO */ +#define set_errno(err) +#endif /* LWIP_SOCKET_SET_ERRNO */ + +#if !LWIP_TCPIP_CORE_LOCKING +/** Maximum optlen used by setsockopt/getsockopt */ +#define LWIP_SETGETSOCKOPT_MAXOPTLEN LWIP_MAX(16, sizeof(struct ifreq)) + +/** This struct is used to pass data to the set/getsockopt_internal + * functions running in tcpip_thread context (only a void* is allowed) */ +struct lwip_setgetsockopt_data { + /** socket index for which to change options */ + int s; + /** level of the option to process */ + int level; + /** name of the option to process */ + int optname; + /** set: value to set the option to + * get: value of the option is stored here */ +#if LWIP_MPU_COMPATIBLE + u8_t optval[LWIP_SETGETSOCKOPT_MAXOPTLEN]; +#else + union { + void *p; + const void *pc; + } optval; +#endif + /** size of *optval */ + socklen_t optlen; + /** if an error occurs, it is temporarily stored here */ + int err; + /** semaphore to wake up the calling task */ + void *completed_sem; +}; +#endif /* !LWIP_TCPIP_CORE_LOCKING */ + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_SOCKET */ + +#endif /* LWIP_HDR_SOCKETS_PRIV_H */ \ No newline at end of file diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/priv/tcp_priv.h b/sdk_liteos/third_party/lwip_sack/include/lwip/priv/tcp_priv.h new file mode 100644 index 0000000000000000000000000000000000000000..92953624c22c0ad227681dbbacf358683c75a9cb --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/priv/tcp_priv.h @@ -0,0 +1,634 @@ +/** + * @file + * TCP internal implementations (do not use in application code) + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_TCP_PRIV_H +#define LWIP_HDR_TCP_PRIV_H + +#include "lwip/opt.h" + +#if LWIP_TCP /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/tcp.h" +#include "lwip/mem.h" +#include "lwip/pbuf.h" +#include "lwip/ip.h" +#include "lwip/icmp.h" +#include "lwip/err.h" +#include "lwip/ip6.h" +#include "lwip/ip6_addr.h" +#include "lwip/prot/tcp.h" + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +/* Functions for interfacing with TCP: */ + +/* Lower layer interface to TCP: */ +void tcp_init (void); /* Initialize this module. */ +void tcp_tmr (void); /* Must be called every + TCP_TMR_INTERVAL + ms. (Typically 250 ms). */ +/* It is also possible to call these two functions at the right + intervals (instead of calling tcp_tmr()). */ +void tcp_slowtmr (void); +void tcp_fasttmr (void); + +#if LWIP_API_RICH +/* Call this from a netif driver (watch out for threading issues!) that has + returned a memory error on transmit and now has free buffers to send more. + This iterates all active pcbs that had an error and tries to call + tcp_output, so use this with care as it might slow down the system. */ +void tcp_txnow (void); +#endif /* LWIP_API_RICH */ + +/* Only used by IP to pass a TCP segment to TCP: */ +void tcp_input (struct pbuf *p, struct netif *inp); +/* Used within the TCP code only: */ +struct tcp_pcb *tcp_alloc (u8_t prio); +void tcp_free (struct tcp_pcb *pcb); +void tcp_abandon (struct tcp_pcb *pcb, int reset); +void tcp_send_rst_abort (struct tcp_pcb *pcb, int reset); +err_t tcp_send_empty_ack(struct tcp_pcb *pcb); +err_t tcp_rexmit (struct tcp_pcb *pcb); +void tcp_rexmit_rto (struct tcp_pcb *pcb); +void tcp_rexmit_fast (struct tcp_pcb *pcb); +u32_t tcp_update_rcv_ann_wnd(struct tcp_pcb *pcb); +err_t tcp_process_refused_data(struct tcp_pcb *pcb); + + +#define TCP_SEQ_LT(a, b) ((s32_t)((u32_t)(a) - (u32_t)(b)) < 0) +#define TCP_SEQ_LEQ(a, b) ((s32_t)((u32_t)(a) - (u32_t)(b)) <= 0) +#define TCP_SEQ_GT(a, b) ((s32_t)((u32_t)(a) - (u32_t)(b)) > 0) +#define TCP_SEQ_GEQ(a, b) ((s32_t)((u32_t)(a) - (u32_t)(b)) >= 0) +/* is b <= a <=c ? */ +/* see bug #10548 */ +#define TCP_SEQ_BETWEEN(a, b, c) (TCP_SEQ_GEQ(a, b) && TCP_SEQ_LEQ(a, c)) + +/* Minshall's variant of the Nagle send check. */ +#define tcp_nagle_minshall_check(tpcb) (TCP_SEQ_GT(tpcb->snd_sml, tpcb->lastack) && TCP_SEQ_LEQ(tpcb->snd_sml, tpcb->snd_nxt)) + +/** + * This is the Nagle algorithm: try to combine usrdata to send as few TCP + * segments as possible. Only send if + * - no previously transmitted data on the connection remains unacknowledged or + * - the TF_NODELAY flag is set (nagle algorithm turned off for this pcb) or + * - the only unsent segment is at least pcb->mss bytes long (or there is more + * than one unsent segment - with lwIP, this can happen although unsent->len < mss) + * - or if we are in fast-retransmit (TF_INFR) + * - With Minshall's variant: all sent small packets are ACKed. + */ +#define tcp_do_output_nagle(tpcb) ((((tpcb)->unacked == NULL) || \ + ((tpcb)->flags & (TF_NODELAY | TF_INFR)) || \ + (((tpcb)->unsent != NULL) && (((tpcb)->unsent->next != NULL) || \ + ((tpcb)->unsent->len >= (tpcb)->mss) || !tcp_nagle_minshall_check(tpcb))) \ + ) ? 1 : 0) + +#define tcp_output_nagle(tpcb) (tcp_do_output_nagle(tpcb) ? tcp_output(tpcb) : ERR_OK) + +/* + * 100 value looks awkward, + * A fast timer every 100 milliseconds (yet beats delay ack duration of 200msec of linux.) + * Slow timer every 200 milliseconds, + */ +#ifndef TCP_TMR_INTERVAL +#define TCP_TMR_INTERVAL 100 /* The TCP timer interval in milliseconds. */ +#endif /* TCP_TMR_INTERVAL */ + +#ifndef TCP_FAST_INTERVAL +#define TCP_FAST_INTERVAL TCP_TMR_INTERVAL /* the fine grained timeout in milliseconds */ +#endif /* TCP_FAST_INTERVAL */ + +#ifndef TCP_SLOW_INTERVAL + +#ifndef TCP_SLOW_INTERVAL_PERIOD +#define TCP_SLOW_INTERVAL_PERIOD 2 /* the fine grained timeout in milliseconds */ +#endif /* TCP_SLOW_INTERVAL_PERIOD */ + +/* the coarse grained timeout in milliseconds */ +#define TCP_SLOW_INTERVAL (TCP_SLOW_INTERVAL_PERIOD * TCP_TMR_INTERVAL) +#endif /* TCP_SLOW_INTERVAL */ + +/** + * @cond liteos + * TCP_INITIAL_RTO_DURATION: Minimum RTO default duration has been reduced to 1 second from 3 seconds, RFC6298 + */ +#ifndef TCP_INITIAL_RTO_DURATION +#define TCP_INITIAL_RTO_DURATION 1000 +#endif + +/* RTO druation of 400ms ensures that RTO expiry will be always between 200ms-400ms */ +#ifndef TCP_MIN_RTO_DURATION +#define TCP_MIN_RTO_DURATION 400 +#endif + +#ifndef TCP_RTO_DURATION_AFTER_SYN_RTX +#define TCP_RTO_DURATION_AFTER_SYN_RTX 3000 +#endif + +/** + * TCP_MAX_RTO_DURATION A maximum value MAY be placed on RTO provided it is at least 60 seconds. + */ +#ifndef TCP_MAX_RTO_DURATION +#define TCP_MAX_RTO_DURATION 60000 +#endif + +#ifndef TCP_MIN_RTO_TICKS +#define TCP_MIN_RTO_TICKS (TCP_MIN_RTO_DURATION / TCP_SLOW_INTERVAL) +#endif + +#ifndef TCP_MAX_RTO_TICKS +#define TCP_MAX_RTO_TICKS (TCP_MAX_RTO_DURATION / TCP_SLOW_INTERVAL) +#endif + +#ifndef TCP_RTO_TICKS_AFTER_SYN_RTX +#define TCP_RTO_TICKS_AFTER_SYN_RTX (TCP_RTO_DURATION_AFTER_SYN_RTX / TCP_SLOW_INTERVAL) +#endif + +#if DRIVER_STATUS_CHECK +/* will round off to the higher value in case it is not multiples of TCP_SLOW_INTERVAL */ +#define DRIVER_WAKEUP_COUNT ((DRIVER_WAKEUP_INTERVAL + (TCP_SLOW_INTERVAL - 1)) / TCP_SLOW_INTERVAL) +#endif + +#define TCP_FIN_WAIT_TIMEOUT 20000 /* milliseconds */ +#define TCP_SYN_RCVD_TIMEOUT 20000 /* milliseconds */ + +#define TCP_OOSEQ_TIMEOUT 6 /* x RTO */ + +#ifndef TCP_MSL +#define TCP_MSL 60000UL /* The maximum segment lifetime in milliseconds */ +#endif + +/* Keepalive values, compliant with RFC 1122. Don't change this unless you know what you're doing */ +#ifndef TCP_KEEPIDLE_DEFAULT +#define TCP_KEEPIDLE_DEFAULT 7200000UL /* Default KEEPALIVE timer in milliseconds */ +#endif + +#ifndef TCP_KEEPINTVL_DEFAULT +#define TCP_KEEPINTVL_DEFAULT 75000UL /* Default Time between KEEPALIVE probes in milliseconds */ +#endif + +#ifndef TCP_KEEPCNT_DEFAULT +#define TCP_KEEPCNT_DEFAULT 9U /* Default Counter for KEEPALIVE probes */ +#endif + +#define TCP_MAXIDLE TCP_KEEPCNT_DEFAULT * TCP_KEEPINTVL_DEFAULT /* Maximum KEEPALIVE probe time */ + +#define TCP_TCPLEN(seg) ((seg)->len + (((TCPH_FLAGS((seg)->tcphdr) & (TCP_FIN | TCP_SYN)) != 0) ? 1U : 0U)) + +/** Flags used on input processing, not on pcb->flags +*/ +#define TF_RESET (u8_t)0x08U /* Connection was reset. */ +#define TF_CLOSED (u8_t)0x10U /* Connection was successfully closed. */ +#define TF_GOT_FIN (u8_t)0x20U /* Connection was closed by the remote end. */ + + +#if LWIP_EVENT_API + +#define TCP_EVENT_ACCEPT(lpcb, pcb, arg, err, ret) ret = lwip_tcp_event(arg, (pcb), \ + LWIP_EVENT_ACCEPT, NULL, 0, err) +#define TCP_EVENT_SENT(pcb, space, ret) ret = lwip_tcp_event((pcb)->callback_arg, (pcb), \ + LWIP_EVENT_SENT, NULL, space, ERR_OK) +#define TCP_EVENT_RECV(pcb, p, err, ret) ret = lwip_tcp_event((pcb)->callback_arg, (pcb), \ + LWIP_EVENT_RECV, (p), 0, (err)) +#define TCP_EVENT_CLOSED(pcb, ret) ret = lwip_tcp_event((pcb)->callback_arg, (pcb), \ + LWIP_EVENT_RECV, NULL, 0, ERR_OK) +#define TCP_EVENT_CONNECTED(pcb, err, ret) ret = lwip_tcp_event((pcb)->callback_arg, (pcb), \ + LWIP_EVENT_CONNECTED, NULL, 0, (err)) +#define TCP_EVENT_POLL(pcb, ret) \ + do { \ + if ((pcb)->state != SYN_RCVD) { \ + ret = lwip_tcp_event((pcb)->callback_arg, (pcb), LWIP_EVENT_POLL, NULL, 0, ERR_OK); \ + } else { \ + ret = ERR_ARG; \ + } \ + } while (0) +#define TCP_EVENT_ERR(last_state, errf, arg, err) do { if (last_state != SYN_RCVD) { \ + lwip_tcp_event((arg), NULL, LWIP_EVENT_ERR, NULL, 0, (err)); } } while (0) + +#else /* LWIP_EVENT_API */ + +#define TCP_EVENT_ACCEPT(lpcb, pcb, arg, err, ret) \ + do { \ + if ((lpcb)->accept != NULL) { \ + (ret) = (lpcb)->accept((arg), (pcb), (err)); \ + } else { \ + (ret) = ERR_ARG; \ + } \ + } while (0) + +#define TCP_EVENT_SENT(pcb, space, ret) \ + do { \ + if ((pcb)->sent != NULL) { \ + (ret) = (pcb)->sent((pcb)->callback_arg, (pcb), (space)); \ + } else { \ + (ret) = ERR_OK; \ + } \ + } while (0) + +#define TCP_EVENT_RECV(pcb, p, err, ret) \ + do { \ + if ((pcb)->recv != NULL) { \ + (ret) = (pcb)->recv((pcb)->callback_arg, (pcb), (p), (err)); \ + } else { \ + (ret) = tcp_recv_null(NULL, (pcb), (p), (err)); \ + } \ + } while (0) + +#define TCP_EVENT_CLOSED(pcb, ret) \ + do { \ + if (((pcb)->recv != NULL)) { \ + (ret) = (pcb)->recv((pcb)->callback_arg, (pcb), NULL, ERR_OK); \ + } else { \ + (ret) = ERR_OK; \ + } \ + } while (0) + +#define TCP_EVENT_CONNECTED(pcb, err, ret) \ + do { \ + if ((pcb)->connected != NULL) { \ + (ret) = (pcb)->connected((pcb)->callback_arg, (pcb), (err)); \ + } else { \ + (ret) = ERR_OK; \ + } \ + } while (0) + +#define TCP_EVENT_POLL(pcb, ret) \ + do { \ + if ((pcb)->poll != NULL) { \ + (ret) = (pcb)->poll((pcb)->callback_arg, (pcb)); \ + } else { \ + (ret) = ERR_OK; \ + } \ + } while (0) + +#define TCP_EVENT_ERR(last_state, errf, arg, err) \ + do { \ + LWIP_UNUSED_ARG(last_state); \ + if ((errf) != NULL) { \ + (errf)((arg), (err)); \ + } \ + } while (0) + +#endif /* LWIP_EVENT_API */ + +/** Enabled extra-check for TCP_OVERSIZE if LWIP_DEBUG is enabled */ +#if TCP_OVERSIZE && defined(LWIP_DEBUG) +#define TCP_OVERSIZE_DBGCHECK 1 +#else +#define TCP_OVERSIZE_DBGCHECK 0 +#endif + +/** Don't generate checksum on copy if CHECKSUM_GEN_TCP is disabled */ +#define TCP_CHECKSUM_ON_COPY (LWIP_CHECKSUM_ON_COPY && CHECKSUM_GEN_TCP) + +/* This structure represents a TCP segment on the unsent, unacked and ooseq queues */ +struct tcp_seg { + struct tcp_seg *next; /* used when putting segments on a queue */ + struct pbuf *p; /* buffer containing data + TCP header */ + u16_t len; /* the TCP length of this segment */ +#if TCP_OVERSIZE_DBGCHECK + u16_t oversize_left; /* Extra bytes available at the end of the last + pbuf in unsent (used for asserting vs. + tcp_pcb.unsent_oversize only) */ +#endif /* TCP_OVERSIZE_DBGCHECK */ +#if TCP_CHECKSUM_ON_COPY + u16_t chksum; + u8_t chksum_swapped; +#endif /* TCP_CHECKSUM_ON_COPY */ + u8_t flags; +#define TF_SEG_OPTS_MSS (u8_t)0x01U /* Include MSS option. */ +#define TF_SEG_OPTS_TS (u8_t)0x02U /* Include timestamp option. */ +#define TF_SEG_DATA_CHECKSUMMED (u8_t)0x04U /* ALL data (not the header) is + checksummed into 'chksum' */ +#define TF_SEG_OPTS_WND_SCALE (u8_t)0x08U /* Include WND SCALE option */ + +/* Adding for SACK */ +#define TF_SEG_OPTS_SACK (u8_t)0x10U /* Include SACK option */ +#define TF_SEG_OPTS_SACK_PERMITTED (u8_t)0x20U /* Include SACK Permitted option */ +#define TF_SEG_OPTS_SACK_OPTIONS (u8_t)0x40U /* Include SACK Options */ + +/* Adding for SACK */ +#if LWIP_SACK + + u32_t state; /* This will be used to maintain SACK scoreboard as per RFC 6675 */ +#define TF_SEG_NONE 0x0000U +#define TF_SEG_SACKED 0x0001U /* Segment Sacked */ +#define TF_SEG_RETRANSMITTED 0x0002U /* Retransmitted as part of SACK based loss recovery alg */ + + u32_t order; /* order of the segment in the ooseq q */ +#if LWIP_SACK_PERF_OPT + u32_t pkt_trans_seq_cntr; +#endif +#endif /* LWIP_SACK */ + +/* NETIF DRIVER STATUS BEGIN */ +#if DRIVER_STATUS_CHECK + u32_t seg_type; +#endif + + struct tcp_hdr *tcphdr; /* the TCP header */ +}; + +#define LWIP_TCP_OPT_EOL 0 +#define LWIP_TCP_OPT_NOP 1 +#define LWIP_TCP_OPT_MSS 2 +#define LWIP_TCP_OPT_WS 3 +#define LWIP_TCP_OPT_TS 8 + +/* Adding for SACK */ +#define LWIP_TCP_OPT_SACK_PERMITTED 4 +#define LWIP_TCP_OPT_SACK 5 + + +#define LWIP_TCP_OPT_LEN_MSS 4 +#if LWIP_TCP_TIMESTAMPS +#define LWIP_TCP_OPT_LEN_TS 10 +#define LWIP_TCP_OPT_LEN_TS_OUT 12 /* aligned for output (includes NOP padding) */ +#else +#define LWIP_TCP_OPT_LEN_TS_OUT 0 +#endif +#if LWIP_WND_SCALE +#define LWIP_TCP_OPT_LEN_WS 3 +#define LWIP_TCP_OPT_LEN_WS_OUT 4 /* aligned for output (includes NOP padding) */ +#else +#define LWIP_TCP_OPT_LEN_WS_OUT 0 +#endif + +#if LWIP_SACK +#define LWIP_TCP_OPT_LEN_SACK_PERMITTED 2 +#define LWIP_TCP_OPT_LEN_SACK_PERMITTED_OUT 4 /* aligned for output (includes NOP padding) */ +#else +#define LWIP_TCP_OPT_LEN_SACK_PERMITTED_OUT 0 +#endif + +#define LWIP_TCP_OPT_LENGTH(flags) \ + (flags & TF_SEG_OPTS_MSS ? LWIP_TCP_OPT_LEN_MSS : 0) + \ + (flags & TF_SEG_OPTS_TS ? LWIP_TCP_OPT_LEN_TS_OUT : 0) + \ + (flags & TF_SEG_OPTS_WND_SCALE ? LWIP_TCP_OPT_LEN_WS_OUT : 0) + \ + (flags & TF_SEG_OPTS_SACK_PERMITTED ? LWIP_TCP_OPT_LEN_SACK_PERMITTED_OUT : 0) + +/* 4 -> padding + kind + length. 8 -> each SACK block */ +#define LWIP_TCP_SACK_OPT_LENGTH(__cnt) __cnt > 0 ? (u8_t)(4 + (__cnt * 8)) : 0 + +/** This returns a TCP header option for MSS in an u32_t */ +#define TCP_BUILD_MSS_OPTION(mss) lwip_htonl(0x02040000 | ((u32_t)((mss) & 0xFFFF))) + +#if LWIP_WND_SCALE +#define TCPWNDSIZE_F U32_F +#define TCPWND_MAX 0xFFFFFFFFU +#define TCPWND_CHECK16(x) LWIP_ASSERT("window size > 0xFFFF", (x) <= 0xFFFF) +#define TCPWND_MIN16(x) ((u16_t)LWIP_MIN((x), 0xFFFF)) +#else /* LWIP_WND_SCALE */ +#define TCPWNDSIZE_F U16_F +#define TCPWND_MAX 0xFFFFU +#define TCPWND_CHECK16(x) +#define TCPWND_MIN16(x) x +#endif /* LWIP_WND_SCALE */ + +/* Global variables: */ +extern struct tcp_pcb *tcp_input_pcb; +extern u32_t tcp_ticks; +extern u8_t tcp_active_pcbs_changed; + +/* The TCP PCB lists. */ +union tcp_listen_pcbs_t { /* List of all TCP PCBs in LISTEN state. */ + struct tcp_pcb_listen *listen_pcbs; + struct tcp_pcb *pcbs; +}; +extern struct tcp_pcb *tcp_bound_pcbs; +extern union tcp_listen_pcbs_t tcp_listen_pcbs; +extern struct tcp_pcb *tcp_active_pcbs; /* List of all TCP PCBs that are in a + state in which they accept or send + data. */ +extern struct tcp_pcb *tcp_tw_pcbs; /* List of all TCP PCBs in TIME-WAIT. */ + +#define NUM_TCP_PCB_LISTS_NO_TIME_WAIT 3 +#define NUM_TCP_PCB_LISTS 4 +extern struct tcp_pcb **const tcp_pcb_lists[NUM_TCP_PCB_LISTS]; + +/* Axioms about the above lists: + 1) Every TCP PCB that is not CLOSED is in one of the lists. + 2) A PCB is only in one of the lists. + 3) All PCBs in the tcp_listen_pcbs list is in LISTEN state. + 4) All PCBs in the tcp_tw_pcbs list is in TIME-WAIT state. +*/ +/* Define two macros, TCP_REG and TCP_RMV that registers a TCP PCB + with a PCB list or removes a PCB from a list, respectively. */ +#ifndef TCP_DEBUG_PCB_LISTS +#define TCP_DEBUG_PCB_LISTS 0 +#endif +#if TCP_DEBUG_PCB_LISTS +#define TCP_REG(pcbs, npcb) do {\ + struct tcp_pcb *tcp_tmp_pcb; \ + LWIP_DEBUGF(TCP_DEBUG, ("TCP_REG %p local port %d\n", (npcb), (npcb)->local_port)); \ + for (tcp_tmp_pcb = *(pcbs); \ + tcp_tmp_pcb != NULL; \ + tcp_tmp_pcb = tcp_tmp_pcb->next) { \ + LWIP_ASSERT("TCP_REG: already registered\n", tcp_tmp_pcb != (npcb)); \ + } \ + LWIP_ASSERT("TCP_REG: pcb->state != CLOSED", \ + ((pcbs) == &tcp_bound_pcbs) || ((npcb)->state != CLOSED)); \ + (npcb)->next = *(pcbs); \ + LWIP_ASSERT("TCP_REG: npcb->next != npcb", (npcb)->next != (npcb)); \ + *(pcbs) = (npcb); \ + LWIP_ASSERT("TCP_RMV: tcp_pcbs sane", tcp_pcbs_sane()); \ + tcp_timer_needed(); \ + } while (0) +#define TCP_RMV(pcbs, npcb) do { \ + struct tcp_pcb *tcp_tmp_pcb; \ + LWIP_ASSERT("TCP_RMV: pcbs != NULL", *(pcbs) != NULL); \ + LWIP_DEBUGF(TCP_DEBUG, ("TCP_RMV: removing %p from %p\n", (npcb), *(pcbs))); \ + if (*(pcbs) == (npcb)) { \ + *(pcbs) = (*pcbs)->next; \ + } else for (tcp_tmp_pcb = *(pcbs); tcp_tmp_pcb != NULL; tcp_tmp_pcb = tcp_tmp_pcb->next) { \ + if (tcp_tmp_pcb->next == (npcb)) { \ + tcp_tmp_pcb->next = (npcb)->next; \ + break; \ + } \ + } \ + (npcb)->next = NULL; \ + LWIP_ASSERT("TCP_RMV: tcp_pcbs sane", tcp_pcbs_sane()); \ + LWIP_DEBUGF(TCP_DEBUG, ("TCP_RMV: removed %p from %p\n", (npcb), *(pcbs))); \ + } while (0) + +#else /* LWIP_DEBUG */ + +#define TCP_REG(pcbs, npcb) \ + do { \ + (npcb)->next = *pcbs; \ + *(pcbs) = (npcb); \ + tcp_timer_needed(); \ + } while (0) + +#if !LWIP_SMALL_SIZE +#define TCP_RMV(pcbs, npcb) \ + do { \ + if (*(pcbs) == (npcb)) { \ + (*(pcbs)) = (*pcbs)->next; \ + } \ + else { \ + struct tcp_pcb *tcp_tmp_pcb; \ + for (tcp_tmp_pcb = *pcbs; \ + tcp_tmp_pcb != NULL; \ + tcp_tmp_pcb = tcp_tmp_pcb->next) { \ + if (tcp_tmp_pcb->next == (npcb)) { \ + tcp_tmp_pcb->next = (npcb)->next; \ + break; \ + } \ + } \ + } \ + (npcb)->next = NULL; \ + } while (0) +#else +void tcp_remove(struct tcp_pcb **pcbs, struct tcp_pcb *npcb); +#define TCP_RMV(pcbs, npcb) tcp_remove(pcbs, npcb) +#endif + +#endif /* LWIP_DEBUG */ + +#define TCP_REG_ACTIVE(npcb) \ + do { \ + TCP_REG(&tcp_active_pcbs, npcb); \ + tcp_active_pcbs_changed = 1; \ + } while (0) + +#define TCP_RMV_ACTIVE(npcb) \ + do { \ + TCP_RMV(&tcp_active_pcbs, npcb); \ + tcp_active_pcbs_changed = 1; \ + } while (0) + +#define TCP_PCB_REMOVE_ACTIVE(pcb) \ + do { \ + tcp_pcb_remove(&tcp_active_pcbs, pcb); \ + tcp_active_pcbs_changed = 1; \ + } while (0) + +/* Internal functions: */ +struct tcp_pcb *tcp_pcb_copy(struct tcp_pcb *pcb); +void tcp_pcb_purge(struct tcp_pcb *pcb); +void tcp_listen_pcb_remove(struct tcp_pcb **pcblist, struct tcp_pcb_listen *lpcb); +void tcp_pcb_remove(struct tcp_pcb **pcblist, struct tcp_pcb *pcb); + +#if LWIP_SACK_PERF_OPT +void tcp_fr_segs_free(struct tcp_sack_fast_rxmited *seg); +#endif + +void tcp_segs_free(struct tcp_seg *seg); +void tcp_seg_free(struct tcp_seg *seg); +struct tcp_seg *tcp_seg_copy(struct tcp_seg *seg); + +#define tcp_ack(pcb) \ + do { \ + if ((pcb)->flags & TF_ACK_DELAY) { \ + (pcb)->flags &= (tcpflags_t)~TF_ACK_DELAY; \ + (pcb)->flags |= TF_ACK_NOW; \ + } else { \ + (pcb)->flags |= TF_ACK_DELAY; \ + } \ + } while (0) + +#define tcp_ack_now(pcb) \ + do { \ + (pcb)->flags |= TF_ACK_NOW; \ + } while (0) + +err_t tcp_send_fin(struct tcp_pcb *pcb); +err_t tcp_enqueue_flags(struct tcp_pcb *pcb, u8_t flags); + +void tcp_rexmit_seg(struct tcp_pcb *pcb, struct tcp_seg *seg); + +void tcp_rst(u32_t seqno, u32_t ackno, + const ip_addr_t *local_ip, const ip_addr_t *remote_ip, + u16_t local_port, u16_t remote_port, struct tcp_pcb *pcb); + +u32_t tcp_next_iss(struct tcp_pcb *pcb); + +err_t tcp_keepalive(struct tcp_pcb *pcb); +err_t tcp_zero_window_probe(struct tcp_pcb *pcb); +void tcp_trigger_input_pcb_close(void); + +#if TCP_CALCULATE_EFF_SEND_MSS +u16_t tcp_eff_send_mss_impl(u16_t sendmss, const ip_addr_t *dest +#if LWIP_IPV6 || LWIP_IPV4_SRC_ROUTING + , const ip_addr_t *src +#endif /* LWIP_IPV6 || LWIP_IPV4_SRC_ROUTING */ + , struct netif *netif); +#if LWIP_IPV6 || LWIP_IPV4_SRC_ROUTING +#define tcp_eff_send_mss(sendmss, src, dest, netif) tcp_eff_send_mss_impl(sendmss, dest, src, netif) +#else /* LWIP_IPV6 || LWIP_IPV4_SRC_ROUTING */ +#define tcp_eff_send_mss(sendmss, src, dest, netif) tcp_eff_send_mss_impl(sendmss, dest, netif) +#endif /* LWIP_IPV6 || LWIP_IPV4_SRC_ROUTING */ +#endif /* TCP_CALCULATE_EFF_SEND_MSS */ + +#if LWIP_CALLBACK_API +err_t tcp_recv_null(void *arg, struct tcp_pcb *pcb, struct pbuf *p, err_t err); +#endif /* LWIP_CALLBACK_API */ + +#if TCP_DEBUG || TCP_INPUT_DEBUG || TCP_OUTPUT_DEBUG +void tcp_debug_print(struct tcp_hdr *tcphdr); +void tcp_debug_print_flags(u8_t flags); +void tcp_debug_print_state(enum tcp_state s); +void tcp_debug_print_pcbs(void); +s16_t tcp_pcbs_sane(void); +#else +# define tcp_debug_print(tcphdr) +# define tcp_debug_print_flags(flags) +# define tcp_debug_print_state(s) +# define tcp_debug_print_pcbs() +# define tcp_pcbs_sane() 1 +#endif /* TCP_DEBUG */ + +/** External function (implemented in timers.c), called when TCP detects + * that a timer is needed (i.e. active- or time-wait-pcb found). */ +void tcp_timer_needed(void); + +void tcp_netif_ip_addr_changed(const ip_addr_t *old_addr, const ip_addr_t *new_addr); + +err_t tcp_output_segment(struct tcp_seg *seg, struct tcp_pcb *pcb); + +#if LWIP_TCP_PCB_NUM_EXT_ARGS +err_t tcp_ext_arg_invoke_callbacks_passive_open(struct tcp_pcb_listen *lpcb, struct tcp_pcb *cpcb); +#endif + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_TCP */ + +#endif /* LWIP_HDR_TCP_PRIV_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/priv/tcpip_priv.h b/sdk_liteos/third_party/lwip_sack/include/lwip/priv/tcpip_priv.h new file mode 100644 index 0000000000000000000000000000000000000000..9fbbc2702f14a90a0a722136eeebefa4f5804d01 --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/priv/tcpip_priv.h @@ -0,0 +1,199 @@ +/** + * @file + * TCPIP API internal implementations (do not use in application code) + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_TCPIP_PRIV_H +#define LWIP_HDR_TCPIP_PRIV_H + +#include "lwip/opt.h" + +#if !NO_SYS /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/tcpip.h" +#include "lwip/sys.h" +#include "lwip/timeouts.h" + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +struct pbuf; +struct netif; + +#if LWIP_MPU_COMPATIBLE +#define API_VAR_REF(name) (*(name)) +#define API_VAR_DECLARE(type, name) type * name +#define API_VAR_ALLOC(type, pool, name, errorval) do { \ + name = (type *)memp_malloc(pool); \ + if (name == NULL) { \ + return errorval; \ + } \ + } while (0) +#define API_VAR_ALLOC_POOL(type, pool, name, errorval) do { \ + name = (type *)LWIP_MEMPOOL_ALLOC(pool); \ + if (name == NULL) { \ + return errorval; \ + } \ + } while (0) +#define API_VAR_FREE(pool, name) memp_free(pool, name) +#define API_VAR_FREE_POOL(pool, name) LWIP_MEMPOOL_FREE(pool, name) +#define API_EXPR_REF(expr) (&(expr)) +#if LWIP_NETCONN_SEM_PER_THREAD +#define API_EXPR_REF_SEM(expr) (expr) +#else +#define API_EXPR_REF_SEM(expr) API_EXPR_REF(expr) +#endif +#define API_EXPR_DEREF(expr) expr +#define API_MSG_M_DEF(m) m +#define API_MSG_M_DEF_C(t, m) t m +#else /* LWIP_MPU_COMPATIBLE */ +#define API_VAR_REF(name) name +#define API_VAR_DECLARE(type, name) type name +#define API_VAR_ALLOC(type, pool, name, errorval) +#define API_VAR_ALLOC_POOL(type, pool, name, errorval) +#define API_VAR_FREE(pool, name) +#define API_VAR_FREE_POOL(pool, name) +#define API_EXPR_REF(expr) expr +#define API_EXPR_REF_SEM(expr) API_EXPR_REF(expr) +#define API_EXPR_DEREF(expr) (*(expr)) +#define API_MSG_M_DEF(m) *m +#define API_MSG_M_DEF_C(t, m) const t * m +#endif /* LWIP_MPU_COMPATIBLE */ + +err_t tcpip_send_msg_wait_sem(tcpip_callback_fn fn, void *apimsg, sys_sem_t *sem); + +struct tcpip_api_call_data { +#if ((!LWIP_TCPIP_CORE_LOCKING) || LWIP_API_MESH) + err_t err; +#if !LWIP_NETCONN_SEM_PER_THREAD + sys_sem_t sem; +#endif /* LWIP_NETCONN_SEM_PER_THREAD */ +#else /* !LWIP_TCPIP_CORE_LOCKING */ + u8_t dummy; /* avoid empty struct :-( */ +#endif /* ((!LWIP_TCPIP_CORE_LOCKING) || LWIP_API_MESH) */ +}; +typedef err_t (*tcpip_api_call_fn)(struct tcpip_api_call_data *call); +err_t tcpip_api_call(tcpip_api_call_fn fn, struct tcpip_api_call_data *call); +#if LWIP_API_MESH +err_t tcpip_linklayer_event_call(tcpip_api_call_fn fn, struct tcpip_api_call_data *call); +#endif + +#if LWIP_TCP +void tcp_unlock_accept(ip6_addr_t *ipaddr); +#endif + +#ifdef DUAL_MBOX +err_t +tcpip_netifapi_priority(tcpip_api_call_fn fn, struct tcpip_api_call_data *call); +#endif +enum tcpip_msg_type { + TCPIP_MSG_API, + TCPIP_MSG_API_CALL, +#if LWIP_API_MESH + TCPIP_MSG_LL_EVENT_CALL, +#endif + TCPIP_MSG_INPKT, +#if LWIP_TCPIP_TIMEOUT && LWIP_TIMERS + TCPIP_MSG_TIMEOUT, + TCPIP_MSG_UNTIMEOUT, +#endif /* LWIP_TCPIP_TIMEOUT && LWIP_TIMERS */ + TCPIP_MSG_CALLBACK, + TCPIP_MSG_CALLBACK_STATIC, +#if LWIP_PLC || LWIP_IEEE802154 + TCPIP_MSG_INPKT_LLN, +#endif +#if LWIP_LOWPOWER + TCPIP_MSG_NA, +#endif +#if LWIP_L3_EVENT_MSG + TCPIP_L3_EVENT_MSG, +#endif +}; + +struct tcpip_msg { + enum tcpip_msg_type type; + union { + struct { + tcpip_callback_fn function; + void *msg; + } api_msg; + struct { + tcpip_api_call_fn function; + struct tcpip_api_call_data *arg; + sys_sem_t *sem; + } api_call; + struct { + struct pbuf *p; + struct netif *netif; + netif_input_fn input_fn; +#if LWIP_PLC || LWIP_IEEE802154 + struct linklayer_addr st_sender_mac; + struct linklayer_addr st_recevr_mac; + netif_lln_input_fn input_lln_fn; +#endif + } inp; + struct { + tcpip_callback_fn function; + void *ctx; + } cb; +#if LWIP_TCPIP_TIMEOUT && LWIP_TIMERS + struct { + u32_t msecs; + sys_timeout_handler h; + void *arg; + } tmo; +#endif /* LWIP_TCPIP_TIMEOUT && LWIP_TIMERS */ +#if LWIP_LOWPOWER + struct { + enum lowpower_msg_type type; + lowpower_sem_t wait_up; + } lowpower; +#endif +#if LWIP_L3_EVENT_MSG + struct { + enum l3_event_msg_type type; + void *msg; + } l3_event_msg; +#endif + } msg; +}; + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* !NO_SYS */ + +#endif /* LWIP_HDR_TCPIP_PRIV_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/prot/autoip.h b/sdk_liteos/third_party/lwip_sack/include/lwip/prot/autoip.h new file mode 100644 index 0000000000000000000000000000000000000000..0bb190f4a612f44bc3f973de9bdd776b51b6601c --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/prot/autoip.h @@ -0,0 +1,78 @@ +/** + * @file + * AutoIP protocol definitions + */ + +/* + * + * Copyright (c) 2007 Dominik Spies + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * Author: Dominik Spies + * + * This is a AutoIP implementation for the lwIP TCP/IP stack. It aims to conform + * with RFC 3927. + * + */ + +#ifndef LWIP_HDR_PROT_AUTOIP_H +#define LWIP_HDR_PROT_AUTOIP_H + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +/* 169.254.0.0 */ +#define AUTOIP_NET 0xA9FE0000 +/* 169.254.1.0 */ +#define AUTOIP_RANGE_START (AUTOIP_NET | 0x0100) +/* 169.254.254.255 */ +#define AUTOIP_RANGE_END (AUTOIP_NET | 0xFEFF) + +/* RFC 3927 Constants */ +#define PROBE_WAIT 1 /* second (initial random delay) */ +#define PROBE_MIN 1 /* second (minimum delay till repeated probe) */ +#define PROBE_MAX 2 /* seconds (maximum delay till repeated probe) */ +#define PROBE_NUM 3 /* (number of probe packets) */ +#define ANNOUNCE_NUM 2 /* (number of announcement packets) */ +#define ANNOUNCE_INTERVAL 2 /* seconds (time between announcement packets) */ +#define ANNOUNCE_WAIT 2 /* seconds (delay before announcing) */ +#define MAX_CONFLICTS 10 /* (max conflicts before rate limiting) */ +#define RATE_LIMIT_INTERVAL 60 /* seconds (delay between successive attempts) */ +#define DEFEND_INTERVAL 10 /* seconds (min. wait between defensive ARPs) */ + +/* AutoIP client states */ +typedef enum { + AUTOIP_STATE_OFF = 0, + AUTOIP_STATE_PROBING = 1, + AUTOIP_STATE_ANNOUNCING = 2, + AUTOIP_STATE_BOUND = 3 +} autoip_state_enum_t; + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_HDR_PROT_AUTOIP_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/prot/dhcp.h b/sdk_liteos/third_party/lwip_sack/include/lwip/prot/dhcp.h new file mode 100644 index 0000000000000000000000000000000000000000..0f6c8898e7b1a6dd7ce2d015ed42d4e280a3bf71 --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/prot/dhcp.h @@ -0,0 +1,213 @@ +/** + * @file + * DHCP protocol definitions + */ + +/* + * Copyright (c) 2001-2004 Leon Woestenberg + * Copyright (c) 2001-2004 Axon Digital Design B.V., The Netherlands. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Leon Woestenberg + * + */ +#ifndef LWIP_HDR_PROT_DHCP_H +#define LWIP_HDR_PROT_DHCP_H + +#include "lwip/opt.h" + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +#define DHCP_RELAY_PORT LWIP_IANA_PORT_DHCP_SERVER + +/* DHCP message item offsets and length */ +#define DHCP_CHADDR_LEN 16U +#define DHCP_SNAME_OFS 44U +#define DHCP_SNAME_LEN 64U +#define DHCP_FILE_OFS 108U +#define DHCP_FILE_LEN 128U +#define DHCP_MSG_LEN 236U +#define DHCP_OPTIONS_OFS (DHCP_MSG_LEN + 4U) /* 4 byte: cookie */ + +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +/* minimum set of fields of any DHCP message */ +struct dhcp_msg { + PACK_STRUCT_FLD_8(u8_t op); + PACK_STRUCT_FLD_8(u8_t htype); + PACK_STRUCT_FLD_8(u8_t hlen); + PACK_STRUCT_FLD_8(u8_t hops); + PACK_STRUCT_FIELD(u32_t xid); + PACK_STRUCT_FIELD(u16_t secs); + PACK_STRUCT_FIELD(u16_t flags); + PACK_STRUCT_FLD_S(ip4_addr_p_t ciaddr); + PACK_STRUCT_FLD_S(ip4_addr_p_t yiaddr); + PACK_STRUCT_FLD_S(ip4_addr_p_t siaddr); + PACK_STRUCT_FLD_S(ip4_addr_p_t giaddr); + PACK_STRUCT_FLD_8(u8_t chaddr[DHCP_CHADDR_LEN]); + PACK_STRUCT_FLD_8(u8_t sname[DHCP_SNAME_LEN]); + PACK_STRUCT_FLD_8(u8_t file[DHCP_FILE_LEN]); + PACK_STRUCT_FIELD(u32_t cookie); + +#define DHCP_MIN_OPTIONS_LEN 68U + +/* Max length of the vendor class identifier information string can be stored */ +#define DHCP_VCI_MAX_LEN 32U + +#if (LWIP_NETIF_HOSTNAME && LWIP_DHCP_VENDOR_CLASS_IDENTIFIER) +#define DHCP_MIN_OPTIONS_BUFFER_LEN ((DHCP_MIN_OPTIONS_LEN) + \ + (NETIF_HOSTNAME_MAX_LEN) + \ + (DHCP_VCI_MAX_LEN) + \ + 4U) +#elif LWIP_NETIF_HOSTNAME + /* Minimum option buffer length include: + minimum option len + 2 bytes of type/length + max hostname len + 2 bytes padding */ +#define DHCP_MIN_OPTIONS_BUFFER_LEN ((DHCP_MIN_OPTIONS_LEN) + \ + (NETIF_HOSTNAME_MAX_LEN) + \ + 4U) +#elif LWIP_DHCP_VENDOR_CLASS_IDENTIFIER +#define DHCP_MIN_OPTIONS_BUFFER_LEN ((DHCP_MIN_OPTIONS_LEN) + \ + (DHCP_VCI_MAX_LEN) + \ + 4U) +#else +#define DHCP_MIN_OPTIONS_BUFFER_LEN (DHCP_MIN_OPTIONS_LEN) +#endif + +/** make sure user does not configure this too small */ +#if ((defined(DHCP_OPTIONS_LEN)) && (DHCP_OPTIONS_LEN < DHCP_MIN_OPTIONS_BUFFER_LEN)) +# undef DHCP_OPTIONS_LEN +#endif +/* allow this to be configured in lwipopts.h, but not too small */ +#if (!defined(DHCP_OPTIONS_LEN)) +/* set this to be sufficient for your options in outgoing DHCP msgs */ +#define DHCP_OPTIONS_LEN DHCP_MIN_OPTIONS_BUFFER_LEN +#endif + PACK_STRUCT_FLD_8(u8_t options[DHCP_OPTIONS_LEN]); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +/* DHCP client states */ +typedef enum { + DHCP_STATE_OFF = 0, + DHCP_STATE_REQUESTING = 1, + DHCP_STATE_INIT = 2, + DHCP_STATE_REBOOTING = 3, + DHCP_STATE_REBINDING = 4, + DHCP_STATE_RENEWING = 5, + DHCP_STATE_SELECTING = 6, + DHCP_STATE_INFORMING = 7, + DHCP_STATE_CHECKING = 8, + DHCP_STATE_PERMANENT = 9, /* not yet implemented */ + DHCP_STATE_BOUND = 10, + DHCP_STATE_RELEASING = 11, /* not yet implemented */ + DHCP_STATE_BACKING_OFF = 12 +} dhcp_state_enum_t; + +/* DHCP op codes */ +#define DHCP_BOOTREQUEST 1 +#define DHCP_BOOTREPLY 2 + +/* DHCP message types */ +#define DHCP_DISCOVER 1 +#define DHCP_OFFER 2 +#define DHCP_REQUEST 3 +#define DHCP_DECLINE 4 +#define DHCP_ACK 5 +#define DHCP_NAK 6 +#define DHCP_RELEASE 7 +#define DHCP_INFORM 8 + +#define DHCP_MAGIC_COOKIE 0x63825363UL + +/* This is a list of options for BOOTP and DHCP, see RFC 2132 for descriptions */ + +/* BootP options */ +#define DHCP_OPTION_PAD 0 +#define DHCP_OPTION_SUBNET_MASK 1 /* RFC 2132 3.3 */ +#define DHCP_OPTION_SUBNET_MASK_SIZE 4 +#define DHCP_OPTION_ROUTER 3 +#define DHCP_OPTION_ROUTER_LEN 4 +#define DHCP_OPTION_DNS_SERVER 6 +#define DHCP_OPTION_HOSTNAME 12 +#define DHCP_OPTION_IP_TTL 23 +#define DHCP_OPTION_MTU 26 +#define DHCP_OPTION_BROADCAST 28 +#define DHCP_OPTION_TCP_TTL 37 +#define DHCP_OPTION_NTP 42 +#define DHCP_OPTION_END 255 + +/* DHCP options */ +#define DHCP_OPTION_REQUESTED_IP 50 /* RFC 2132 9.1, requested IP address */ +#define DHCP_OPTION_LEASE_TIME 51 /* RFC 2132 9.2, time in seconds, in 4 bytes */ +#define DHCP_OPTION_LEASE_TIME_SIZE 4 +#define DHCP_OPTION_OVERLOAD 52 /* RFC2132 9.3, use file and/or sname field for options */ + +#define DHCP_OPTION_MESSAGE_TYPE 53 /* RFC 2132 9.6, important for DHCP */ +#define DHCP_OPTION_MESSAGE_TYPE_LEN 1 + +#define DHCP_OPTION_SERVER_ID 54 /* RFC 2132 9.7, server IP address */ +#define DHCP_OPTION_SERVER_ID_LEN 4 +#define DHCP_OPTION_PARAMETER_REQUEST_LIST 55 /* RFC 2132 9.8, requested option types */ + +#define DHCP_OPTION_MAX_MSG_SIZE 57 /* RFC 2132 9.10, message size accepted >= 576 */ +#define DHCP_OPTION_MAX_MSG_SIZE_LEN 2 + +#define DHCP_OPTION_T1 58 /* T1 renewal time */ +#define DHCP_OPTION_T1_LEN 4 +#define DHCP_OPTION_T2 59 /* T2 rebinding time */ +#define DHCP_OPTION_T2_LEN 4 +#define DHCP_OPTION_VCI 60 +#define DHCP_OPTION_CLIENT_ID 61 +#define DHCP_OPTION_CLIENT_ID_LEN 7 +#define DHCP_OPTION_TFTP_SERVERNAME 66 +#define DHCP_OPTION_BOOTFILE 67 + +#define DHCP_OPTION_AGENT_INFO 82 +#define DHCP_OPTION_AGENT_INFO_CID 1 +#define DHCP_OPTION_AGENT_INFO_RID 2 + +#define GEN_FLG(name) (1U << (DHCP_OPTION_##name - 32)) + + +/* possible combinations of overloading the file and sname fields with options */ +#define DHCP_OVERLOAD_NONE 0 +#define DHCP_OVERLOAD_FILE 1 +#define DHCP_OVERLOAD_SNAME 2 +#define DHCP_OVERLOAD_SNAME_FILE 3 + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_HDR_PROT_DHCP_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/prot/dhcp6.h b/sdk_liteos/third_party/lwip_sack/include/lwip/prot/dhcp6.h new file mode 100644 index 0000000000000000000000000000000000000000..ccd0bca6e9f1a80ecdafa3eee9de3ae8332ea0f7 --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/prot/dhcp6.h @@ -0,0 +1,242 @@ +/* + * Description: DHCPv6 protocol definitions + */ +#ifndef LWIP_HDR_PROT_DHCP6_H +#define LWIP_HDR_PROT_DHCP6_H + +#include "lwip/opt.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define DHCP6_CLIENT_PORT 546 +#define DHCP6_SERVER_PORT 547 + +#define DHCP6_ENABLE_UNICAST_SUPPORT 0 + +#define DHCP6_OPT_HEADER_LEN 4 +/* DHCPv6 message item offsets and length */ +#define DHCP6_TRANSACTION_ID_LEN 3 + +#define DHCPv6_ELAPSED_TIME_VALUE_BYTES 2 +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +/** minimum set of fields of any DHCPv6 message */ +struct dhcp6_msg { + PACK_STRUCT_FLD_8(u8_t msgtype); + PACK_STRUCT_FLD_8(u8_t transaction_id[DHCP6_TRANSACTION_ID_LEN]); + /* options follow */ +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +/* DHCP6 client states */ +typedef enum { + DHCP6_STATE_OFF = 0, + DHCP6_STATE_STATELESS_IDLE = 1, + DHCP6_STATE_REQUESTING_CONFIG = 2, +#if LWIP_IPV6_DHCP6_STATEFUL + DHCP6_STATE_STATEFUL_INIT = 3, + DHCP6_STATE_STATEFUL_SOLICIT = 4, + DHCP6_STATE_STATEFUL_INFOREQ = 5, + DHCP6_STATE_STATEFUL_REQUEST = 6, + DHCP6_STATE_STATEFUL_RENEW = 7, + DHCP6_STATE_STATEFUL_REBIND = 8, + DHCP6_STATE_STATEFUL_RELEASE = 9, + DHCP6_STATE_STATEFUL_DECLINE = 10, + DHCP6_STATE_STATEFUL_IDLE = 11 +#endif /* LWIP_IPV6_DHCP6_STATEFUL */ +} dhcp6_state_enum_t; + +/* DHCPv6 message types */ +/* More message types see https://www.iana.org/assignments/dhcpv6-parameters/dhcpv6-parameters.xhtml */ +#define DHCP6_SOLICIT 1 +#define DHCP6_ADVERTISE 2 +#define DHCP6_REQUEST 3 +#define DHCP6_CONFIRM 4 +#define DHCP6_RENEW 5 +#define DHCP6_REBIND 6 +#define DHCP6_REPLY 7 +#define DHCP6_RELEASE 8 +#define DHCP6_DECLINE 9 +#define DHCP6_RECONFIGURE 10 +#define DHCP6_INFOREQUEST 11 +#define DHCP6_RELAYFORW 12 +#define DHCP6_RELAYREPL 13 +#define DHCP6_MESSAGE_END 14 + +/** DHCPv6 status codes */ +/* More status codes see https://www.iana.org/assignments/dhcpv6-parameters/dhcpv6-parameters.xhtml */ +#define DHCP6_STATUS_SUCCESS 0 /* Success. */ + +/* + * Failure, reason unspecified; this status code is sent by either a client or a server to + * indicate a failure not explicitly specified in this document. + */ +#define DHCP6_STATUS_UNSPECFAIL 1 + +/* Server has no addresses available to assign to the IA(s). */ +#define DHCP6_STATUS_NOADDRSAVAIL 2 + +/* Client record (binding) unavailable. */ +#define DHCP6_STATUS_NOBINDING 3 + +/* The prefix for the address is not appropriate for the link to which the client is attached. */ +#define DHCP6_STATUS_NOTONLINK 4 + +/* + * Sent by a server to a client to force the client to send messages to the server + * using the All_DHCP_Relay_Agents_and_Servers address. + */ +#define DHCP6_STATUS_USEMULTICAST 5 + +/* Delegating router has no prefixes available to assign to the IAPD(s), RFC 3633 */ +#define DHCP6_STATUS_NOPREFIXAVAIL 6 + +/** DHCPv6 DUID types */ +#define DHCP6_DUID_LLT 1 /* LLT: Link-layer Address Plus Time */ +#define DHCP6_DUID_EN 2 /* EN: Enterprise number */ +#define DHCP6_DUID_LL 3 /* LL: Link-layer Address */ +#define DHCP6_DUID_UUID 4 /* UUID (RFC 6355) */ + +/* DHCPv6 Possible values for hardware type (htype) field... */ +#define DHCP6HTYPE_ETHER 1 /* Ethernet 10Mbps */ +#define DHCP6HTYPE_IEEE802 6 /* IEEE 802.2 Token Ring... */ +#define DHCP6HTYPE_FDDI 8 /* FDDI... */ +#define DHCP6HTYPE_INFINIBAND 32 /* IP over Infiniband */ + +/* IPMP - random hw address - there is no standard for this so we just steal a type */ +#define DHCP6HTYPE_IPMP 255 + +/* DHCPv6 options */ +#define DHCP6_OPTION_CLIENTID 1 +#define DHCP6_OPTION_SERVERID 2 +#define DHCP6_OPTION_IA_NA 3 +#define DHCP6_OPTION_IA_TA 4 +#define DHCP6_OPTION_IAADDR 5 +#define DHCP6_OPTION_ORO 6 +#define DHCP6_OPTION_PREFERENCE 7 +#define DHCP6_OPTION_ELAPSED_TIME 8 +#define DHCP6_OPTION_RELAY_MSG 9 +#define DHCP6_OPTION_AUTH 11 +#define DHCP6_OPTION_UNICAST 12 +#define DHCP6_OPTION_STATUS_CODE 13 +#define DHCP6_OPTION_RAPID_COMMIT 14 +#define DHCP6_OPTION_USER_CLASS 15 +#define DHCP6_OPTION_VENDOR_CLASS 16 +#define DHCP6_OPTION_VENDOR_OPTS 17 +#define DHCP6_OPTION_INTERFACE_ID 18 +#define DHCP6_OPTION_RECONF_MSG 19 +#define DHCP6_OPTION_RECONF_ACCEPT 20 +/* More options see https://www.iana.org/assignments/dhcpv6-parameters/dhcpv6-parameters.xhtml */ +#define DHCP6_OPTION_DNS_SERVERS 23 /* RFC 3646 */ +#define DHCP6_OPTION_DOMAIN_LIST 24 /* RFC 3646 */ +#define DHCP6_OPTION_IA_PD 25 /* RFC 3633 */ +#define DHCP6_OPTION_IAPREFIX 26 /* RFC 3633 */ +#define DHCP6_OPTION_SNTP_SERVERS 31 /* RFC 4075 */ + +#define DHCP6_OPTION_PREFERENCE_MAX 255 + +/* + * DHCPv6 Retransmission Constants (RFC3315 section 5.5, RFC 5007) + */ +#ifndef SOL_MAX_DELAY +#define SOL_MAX_DELAY 1 +#endif /* SOL_MAX_DELAY */ +#ifndef SOL_TIMEOUT +#define SOL_TIMEOUT 1 +#endif /* SOL_TIMEOUT */ +#ifndef SOL_MAX_RT +#define SOL_MAX_RT 120 +#endif /* SOL_MAX_RT */ +#ifndef REQ_TIMEOUT +#define REQ_TIMEOUT 1 +#endif /* REQ_TIMEOUT */ +#ifndef REQ_MAX_RT +#define REQ_MAX_RT 30 +#endif /* REQ_MAX_RT */ +#ifndef REQ_MAX_RC +#define REQ_MAX_RC 10 +#endif /* REQ_MAX_RC */ +#ifndef CNF_MAX_DELAY +#define CNF_MAX_DELAY 1 +#endif /* CNF_MAX_DELAY */ +#ifndef CNF_TIMEOUT +#define CNF_TIMEOUT 1 +#endif /* CNF_TIMEOUT */ +#ifndef CNF_MAX_RT +#define CNF_MAX_RT 4 +#endif /* CNF_MAX_RT */ +#ifndef CNF_MAX_RD +#define CNF_MAX_RD 10 +#endif /* CNF_MAX_RD */ +#ifndef REN_TIMEOUT +#define REN_TIMEOUT 10 +#endif /* REN_TIMEOUT */ +#ifndef REN_MAX_RT +#define REN_MAX_RT 600 +#endif /* REN_MAX_RT */ +#ifndef REB_TIMEOUT +#define REB_TIMEOUT 10 +#endif /* REB_TIMEOUT */ +#ifndef REB_MAX_RT +#define REB_MAX_RT 600 +#endif /* REB_MAX_RT */ +#ifndef INF_MAX_DELAY +#define INF_MAX_DELAY 1 +#endif /* INF_MAX_DELAY */ +#ifndef INF_TIMEOUT +#define INF_TIMEOUT 1 +#endif /* INF_TIMEOUT */ +#ifndef INF_MAX_RT +#define INF_MAX_RT 120 +#endif /* INF_MAX_RT */ +#ifndef REL_TIMEOUT +#define REL_TIMEOUT 1 +#endif /* REL_TIMEOUT */ +#ifndef REL_MAX_RC +#define REL_MAX_RC 5 +#endif /* REL_MAX_RC */ +#ifndef DEC_TIMEOUT +#define DEC_TIMEOUT 1 +#endif /* DEC_TIMEOUT */ +#ifndef DEC_MAX_RC +#define DEC_MAX_RC 5 +#endif /* DEC_MAX_RC */ +#ifndef REC_TIMEOUT +#define REC_TIMEOUT 2 +#endif /* REC_TIMEOUT */ +#ifndef REC_MAX_RC +#define REC_MAX_RC 8 +#endif /* REC_MAX_RC */ +#ifndef HOP_COUNT_LIMIT +#define HOP_COUNT_LIMIT 32 +#endif /* HOP_COUNT_LIMIT */ +#ifndef LQ6_TIMEOUT +#define LQ6_TIMEOUT 1 +#endif /* LQ6_TIMEOUT */ +#ifndef LQ6_MAX_RT +#define LQ6_MAX_RT 10 +#endif /* LQ6_MAX_RT */ +#ifndef LQ6_MAX_RC +#define LQ6_MAX_RC 5 +#endif /* LQ6_MAX_RC */ + +/** Infinite duration */ +#define DHCP6_DURATION_INFINITE 0xffffffff + +#define DHCP6_SERVERINFO_MAX_LEN 720 +#define DHCP6_SERVERINFO_MAX_OPT_NUM 16 + +#define DHCPV6_RT_RAND (((LWIP_RAND() % 21) - 10) / 100.0) + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_HDR_PROT_DHCP6_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/prot/dns.h b/sdk_liteos/third_party/lwip_sack/include/lwip/prot/dns.h new file mode 100644 index 0000000000000000000000000000000000000000..3ea238090ebf729a1010af1d1f5f375b05bfffd8 --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/prot/dns.h @@ -0,0 +1,179 @@ +/** + * @file + * DNS - host name to IP address resolver. + */ + +/* + * Port to lwIP from uIP + * by Jim Pettinato April 2007 + * + * security fixes and more by Simon Goldschmidt + * + * uIP version Copyright (c) 2002-2003, Adam Dunkels. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote + * products derived from this software without specific prior + * written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS + * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef LWIP_HDR_PROT_DNS_H +#define LWIP_HDR_PROT_DNS_H + +#include "lwip/arch.h" + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +/** + * @cond liteos + * DNS server port address + */ +#ifndef DNS_SERVER_PORT +#define DNS_SERVER_PORT 53 +#endif + +/* DNS field TYPE used for "Resource Records" */ +#define DNS_RRTYPE_A 1 /* a host address */ +#define DNS_RRTYPE_NS 2 /* an authoritative name server */ +#define DNS_RRTYPE_MD 3 /* a mail destination (Obsolete - use MX) */ +#define DNS_RRTYPE_MF 4 /* a mail forwarder (Obsolete - use MX) */ +#define DNS_RRTYPE_CNAME 5 /* the canonical name for an alias */ +#define DNS_RRTYPE_SOA 6 /* marks the start of a zone of authority */ +#define DNS_RRTYPE_MB 7 /* a mailbox domain name (EXPERIMENTAL) */ +#define DNS_RRTYPE_MG 8 /* a mail group member (EXPERIMENTAL) */ +#define DNS_RRTYPE_MR 9 /* a mail rename domain name (EXPERIMENTAL) */ +#define DNS_RRTYPE_NULL 10 /* a null RR (EXPERIMENTAL) */ +#define DNS_RRTYPE_WKS 11 /* a well known service description */ +#define DNS_RRTYPE_PTR 12 /* a domain name pointer */ +#define DNS_RRTYPE_HINFO 13 /* host information */ +#define DNS_RRTYPE_MINFO 14 /* mailbox or mail list information */ +#define DNS_RRTYPE_MX 15 /* mail exchange */ +#define DNS_RRTYPE_TXT 16 /* text strings */ +#define DNS_RRTYPE_AAAA 28 /* IPv6 address */ +#define DNS_RRTYPE_SRV 33 /* service location */ +#define DNS_RRTYPE_ANY 255 /* any type */ + +/* DNS field CLASS used for "Resource Records" */ +#define DNS_RRCLASS_IN 1 /* the Internet */ +#define DNS_RRCLASS_CS 2 /* the CSNET class (Obsolete - used only for examples in some obsolete RFCs) */ +#define DNS_RRCLASS_CH 3 /* the CHAOS class */ +#define DNS_RRCLASS_HS 4 /* Hesiod [Dyer 87] */ +#define DNS_RRCLASS_ANY 255 /* any class */ +#define DNS_RRCLASS_FLUSH 0x800 /* Flush bit */ + +/* DNS protocol flags */ +#define DNS_FLAG1_RESPONSE 0x80 +#define DNS_FLAG1_OPCODE_STATUS 0x10 +#define DNS_FLAG1_OPCODE_INVERSE 0x08 +#define DNS_FLAG1_OPCODE_STANDARD 0x00 +#define DNS_FLAG1_AUTHORATIVE 0x04 +#define DNS_FLAG1_TRUNC 0x02 +#define DNS_FLAG1_RD 0x01 +#define DNS_FLAG2_RA 0x80 +#define DNS_FLAG2_ERR_MASK 0x0f +#define DNS_FLAG2_ERR_NONE 0x00 +#define DNS_FLAG2_ERR_SERVER_FAILURE 0x02 +#define DNS_FLAG2_ERR_NAME 0x03 + +#define DNS_HDR_GET_OPCODE(hdr) ((((hdr)->flags1) >> 3) & 0xF) + +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +/* DNS message header */ +struct dns_hdr { + PACK_STRUCT_FIELD(u16_t id); + PACK_STRUCT_FLD_8(u8_t flags1); + PACK_STRUCT_FLD_8(u8_t flags2); + PACK_STRUCT_FIELD(u16_t numquestions); + PACK_STRUCT_FIELD(u16_t numanswers); + PACK_STRUCT_FIELD(u16_t numauthrr); + PACK_STRUCT_FIELD(u16_t numextrarr); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END + +/* DNS query message structure. */ +PACK_STRUCT_BEGIN +struct dns_query { + /* + * DNS query record starts with either a domain name or a pointer + * to a name already present somewhere in the packet. + */ + PACK_STRUCT_FIELD(u16_t type); + PACK_STRUCT_FIELD(u16_t cls); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#define SIZEOF_DNS_QUERY 4 + +/* DNS answer message structure. */ +PACK_STRUCT_BEGIN +struct dns_answer { + /* + * NS answer record starts with either a domain name or a pointer + * to a name already present somewhere in the packet. + */ + PACK_STRUCT_FIELD(u16_t type); + PACK_STRUCT_FIELD(u16_t cls); + PACK_STRUCT_FIELD(u32_t ttl); + PACK_STRUCT_FIELD(u16_t len); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END + +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif +#define SIZEOF_DNS_HDR 12 + + +/* Multicast DNS definitions */ + +/** UDP port for multicast DNS queries. + * @endcond */ +#ifndef DNS_MQUERY_PORT +#define DNS_MQUERY_PORT 5353 +#endif + +/* IPv4 group for multicast DNS queries: 224.0.0.251 */ +#ifndef DNS_MQUERY_IPV4_GROUP_INIT +#define DNS_MQUERY_IPV4_GROUP_INIT IPADDR4_INIT_BYTES(224, 0, 0, 251) +#endif + +/* IPv6 group for multicast DNS queries: FF02::FB */ +#ifndef DNS_MQUERY_IPV6_GROUP_INIT +#define DNS_MQUERY_IPV6_GROUP_INIT IPADDR6_INIT_HOST(0xFF020000, 0, 0, 0xFB) +#endif + +#define SIZEOF_DNS_ANSWER 10 +/* maximum allowed size for the struct due to non-packed */ +#define SIZEOF_DNS_ANSWER_ASSERT 12 + +#define DNS_LIFETIME_INFINITY 0xFFFFFFFF + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_HDR_PROT_DNS_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/prot/etharp.h b/sdk_liteos/third_party/lwip_sack/include/lwip/prot/etharp.h new file mode 100644 index 0000000000000000000000000000000000000000..dd903a7b51b17709debcea43510804ca43a81e9b --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/prot/etharp.h @@ -0,0 +1,100 @@ +/** + * @file + * ARP protocol definitions + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_PROT_ETHARP_H +#define LWIP_HDR_PROT_ETHARP_H + +#include "lwip/arch.h" +#include "lwip/prot/ethernet.h" + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +#ifndef ETHARP_HWADDR_LEN +#define ETHARP_HWADDR_LEN ETH_HWADDR_LEN +#endif + +/** + * struct ipaddr2 is used in the definition of the ARP packet format in + * order to support compilers that don't have structure packing. + */ +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct ip4_addr_wordaligned { + PACK_STRUCT_FIELD(u16_t addrw[2]); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +/** the ARP message, see RFC 826 ("Packet format") */ +struct etharp_hdr { + PACK_STRUCT_FIELD(u16_t hwtype); + PACK_STRUCT_FIELD(u16_t proto); + PACK_STRUCT_FLD_8(u8_t hwlen); + PACK_STRUCT_FLD_8(u8_t protolen); + PACK_STRUCT_FIELD(u16_t opcode); + PACK_STRUCT_FLD_S(struct eth_addr shwaddr); + PACK_STRUCT_FLD_S(struct ip4_addr_wordaligned sipaddr); + PACK_STRUCT_FLD_S(struct eth_addr dhwaddr); + PACK_STRUCT_FLD_S(struct ip4_addr_wordaligned dipaddr); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +#define SIZEOF_ETHARP_HDR 28 + +/* ARP message types (opcodes) */ +enum etharp_opcode { + ARP_REQUEST = 1, + ARP_REPLY = 2 +}; + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_HDR_PROT_ETHARP_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/prot/ethernet.h b/sdk_liteos/third_party/lwip_sack/include/lwip/prot/ethernet.h new file mode 100644 index 0000000000000000000000000000000000000000..ec72800cd999fec510cc920501f64ee8ea53ec87 --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/prot/ethernet.h @@ -0,0 +1,125 @@ +/** + * @file + * Ethernet protocol definitions + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_PROT_ETHERNET_H +#define LWIP_HDR_PROT_ETHERNET_H + +#include "lwip/arch.h" +#include "lwip/prot/ieee.h" + +#if LWIP_LITEOS_COMPAT +#include +#endif + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +#ifndef ETH_HWADDR_LEN +#ifdef ETHARP_HWADDR_LEN +#define ETH_HWADDR_LEN ETHARP_HWADDR_LEN /* compatibility mode */ +#else +#define ETH_HWADDR_LEN 6 +#endif +#endif + +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct eth_addr { + PACK_STRUCT_FLD_8(u8_t addr[ETH_HWADDR_LEN]); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +/* Ethernet header */ +struct eth_hdr { +#if ETH_PAD_SIZE + PACK_STRUCT_FLD_8(u8_t padding[ETH_PAD_SIZE]); +#endif + PACK_STRUCT_FLD_S(struct eth_addr dest); + PACK_STRUCT_FLD_S(struct eth_addr src); + PACK_STRUCT_FIELD(u16_t type); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +#define SIZEOF_ETH_HDR (14 + ETH_PAD_SIZE) + +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +/* VLAN header inserted between ethernet header and payload + * if 'type' in ethernet header is ETHTYPE_VLAN. + * See IEEE802.Q */ +struct eth_vlan_hdr { + PACK_STRUCT_FIELD(u16_t prio_vid); + PACK_STRUCT_FIELD(u16_t tpid); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +#define SIZEOF_VLAN_HDR 4 +#define VLAN_ID(vlan_hdr) (lwip_htons((vlan_hdr)->prio_vid) & 0xFFF) + +/** The 24-bit IANA IPv4-multicast OUI is 01-00-5e: */ +#define LL_IP4_MULTICAST_ADDR_0 0x01 +#define LL_IP4_MULTICAST_ADDR_1 0x00 +#define LL_IP4_MULTICAST_ADDR_2 0x5e + +/* IPv6 multicast uses this prefix */ +#define LL_IP6_MULTICAST_ADDR_0 0x33 +#define LL_IP6_MULTICAST_ADDR_1 0x33 + +#define eth_addr_cmp(addr1, addr2) (memcmp((addr1)->addr, (addr2)->addr, ETH_HWADDR_LEN) == 0) + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_HDR_PROT_ETHERNET_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/prot/iana.h b/sdk_liteos/third_party/lwip_sack/include/lwip/prot/iana.h new file mode 100644 index 0000000000000000000000000000000000000000..4ef9b64abe19df504d9fc6852fd7980161ce695c --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/prot/iana.h @@ -0,0 +1,98 @@ +/** + * @file + * IANA assigned numbers (RFC 1700 and successors) + * + * @defgroup iana IANA assigned numbers + * @ingroup infrastructure + */ + +/* + * Copyright (c) 2017 Dirk Ziegelmeier. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Dirk Ziegelmeier + * + */ + +#ifndef LWIP_HDR_PROT_IANA_H +#define LWIP_HDR_PROT_IANA_H + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +/** + * @ingroup iana + * Hardware types + */ +enum lwip_iana_hwtype { + /** Ethernet */ + LWIP_IANA_HWTYPE_ETHERNET = 1 +}; + +/** + * @ingroup iana + * Port numbers + * https://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.txt + */ +enum lwip_iana_port_number { + /** SMTP */ + LWIP_IANA_PORT_SMTP = 25, + /** DHCP server */ + LWIP_IANA_PORT_DHCP_SERVER = 67, + /** DHCP client */ + LWIP_IANA_PORT_DHCP_CLIENT = 68, + /** TFTP */ + LWIP_IANA_PORT_TFTP = 69, + /** HTTP */ + LWIP_IANA_PORT_HTTP = 80, + /** SNTP */ + LWIP_IANA_PORT_SNTP = 123, + /** NETBIOS */ + LWIP_IANA_PORT_NETBIOS = 137, + /** SNMP */ + LWIP_IANA_PORT_SNMP = 161, + /** SNMP traps */ + LWIP_IANA_PORT_SNMP_TRAP = 162, + /** HTTPS */ + LWIP_IANA_PORT_HTTPS = 443, + /** SMTPS */ + LWIP_IANA_PORT_SMTPS = 465, + /** MQTT */ + LWIP_IANA_PORT_MQTT = 1883, + /** MDNS */ + LWIP_IANA_PORT_MDNS = 5353, + /** Secure MQTT */ + LWIP_IANA_PORT_SECURE_MQTT = 8883 +}; + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_HDR_PROT_IANA_H */ + diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/prot/icmp.h b/sdk_liteos/third_party/lwip_sack/include/lwip/prot/icmp.h new file mode 100644 index 0000000000000000000000000000000000000000..2e315b8dc76ca1db48497bd8012cfaf5f1e25b6f --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/prot/icmp.h @@ -0,0 +1,91 @@ +/** + * @file + * ICMP protocol definitions + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_PROT_ICMP_H +#define LWIP_HDR_PROT_ICMP_H + +#include "lwip/arch.h" + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +#define ICMP_ER 0 /* echo reply */ +#define ICMP_DUR 3 /* destination unreachable */ +#define ICMP_SQ 4 /* source quench */ +#define ICMP_RD 5 /* redirect */ +#define ICMP_ECHO 8 /* echo */ +#define ICMP_TE 11 /* time exceeded */ +#define ICMP_PP 12 /* parameter problem */ +#define ICMP_TS 13 /* timestamp */ +#define ICMP_TSR 14 /* timestamp reply */ +#define ICMP_IRQ 15 /* information request */ +#define ICMP_IR 16 /* information reply */ +#define ICMP_AM 17 /* address mask request */ +#define ICMP_AMR 18 /* address mask reply */ + +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +/* This is the standard ICMP header only that the u32_t data + * is split to two u16_t like ICMP echo needs it. + * This header is also used for other ICMP types that do not + * use the data part. + */ +PACK_STRUCT_BEGIN +struct icmp_echo_hdr { + PACK_STRUCT_FLD_8(u8_t type); + PACK_STRUCT_FLD_8(u8_t code); + PACK_STRUCT_FIELD(u16_t chksum); + PACK_STRUCT_FIELD(u16_t id); + PACK_STRUCT_FIELD(u16_t seqno); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +/* Compatibility defines, old versions used to combine type and code to an u16_t */ +#define ICMPH_TYPE(hdr) ((hdr)->type) +#define ICMPH_CODE(hdr) ((hdr)->code) +#define ICMPH_TYPE_SET(hdr, t) ((hdr)->type = (t)) +#define ICMPH_CODE_SET(hdr, c) ((hdr)->code = (c)) + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_HDR_PROT_ICMP_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/prot/icmp6.h b/sdk_liteos/third_party/lwip_sack/include/lwip/prot/icmp6.h new file mode 100644 index 0000000000000000000000000000000000000000..b57bda042e701e8fbf8cba61db17a0dd5fbbf17d --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/prot/icmp6.h @@ -0,0 +1,180 @@ +/** + * @file + * ICMP6 protocol definitions + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_PROT_ICMP6_H +#define LWIP_HDR_PROT_ICMP6_H + +#include "lwip/arch.h" + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +/** ICMP type */ +enum icmp6_type { + /** Destination unreachable */ + ICMP6_TYPE_DUR = 1, + /** Packet too big */ + ICMP6_TYPE_PTB = 2, + /** Time exceeded */ + ICMP6_TYPE_TE = 3, + /** Parameter problem */ + ICMP6_TYPE_PP = 4, + /** Private experimentation */ + ICMP6_TYPE_PE1 = 100, + /** Private experimentation */ + ICMP6_TYPE_PE2 = 101, + /** Reserved for expansion of error messages */ + ICMP6_TYPE_RSV_ERR = 127, + + /** Echo request */ + ICMP6_TYPE_EREQ = 128, + /** Echo reply */ + ICMP6_TYPE_EREP = 129, + /** Multicast listener query */ + ICMP6_TYPE_MLQ = 130, + /** Multicast listener report */ + ICMP6_TYPE_MLR = 131, + /** Multicast listener done */ + ICMP6_TYPE_MLD = 132, + /** Router solicitation */ + ICMP6_TYPE_RS = 133, + /** Router advertisement */ + ICMP6_TYPE_RA = 134, + /** Neighbor solicitation */ + ICMP6_TYPE_NS = 135, + /** Neighbor advertisement */ + ICMP6_TYPE_NA = 136, + /** Redirect */ + ICMP6_TYPE_RD = 137, + /** Multicast router advertisement */ + ICMP6_TYPE_MRA = 151, + /** Multicast router solicitation */ + ICMP6_TYPE_MRS = 152, + /** Multicast router termination */ + ICMP6_TYPE_MRT = 153, + /* Routing Protocol for Low-Power and Lossy Networks */ + ICMP6_TYPE_RPL = 155, + /** Private experimentation */ + ICMP6_TYPE_PE3 = 200, + /** Private experimentation */ + ICMP6_TYPE_PE4 = 201, + /** Reserved for expansion of informational messages */ + ICMP6_TYPE_RSV_INF = 255 +}; + +#if LWIP_MPL +#define ICMP6_TYPE_ESMRF ICMP6_TYPE_PE4 /* ESMRF Multicast */ +#define ESMRF_ICMP_CODE 0 /* ICMPv6 code field */ +#define ESMRF_IP_HOP_LIMIT 0xFF /* Hop limit for ICMP messages */ +#endif + +/** ICMP destination unreachable codes */ +enum icmp6_dur_code { + /** No route to destination */ + ICMP6_DUR_NO_ROUTE = 0, + /** Communication with destination administratively prohibited */ + ICMP6_DUR_PROHIBITED = 1, + /** Beyond scope of source address */ + ICMP6_DUR_SCOPE = 2, + /** Address unreachable */ + ICMP6_DUR_ADDRESS = 3, + /** Port unreachable */ + ICMP6_DUR_PORT = 4, + /** Source address failed ingress/egress policy */ + ICMP6_DUR_POLICY = 5, + /** Reject route to destination */ + ICMP6_DUR_REJECT_ROUTE = 6 +}; + +/** ICMP time exceeded codes */ +enum icmp6_te_code { + /** Hop limit exceeded in transit */ + ICMP6_TE_HL = 0, + /** Fragment reassembly time exceeded */ + ICMP6_TE_FRAG = 1 +}; + +/** ICMP parameter code */ +enum icmp6_pp_code { + /** Erroneous header field encountered */ + ICMP6_PP_FIELD = 0, + /** Unrecognized next header type encountered */ + ICMP6_PP_HEADER = 1, + /** Unrecognized IPv6 option encountered */ + ICMP6_PP_OPTION = 2 +}; + +#define ICMP6_HLEN 4 + +/** This is the standard ICMP6 header. */ +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct icmpv6_hdr { + PACK_STRUCT_FLD_8(u8_t type); + PACK_STRUCT_FLD_8(u8_t code); + PACK_STRUCT_FIELD(u16_t chksum); + PACK_STRUCT_FIELD(u32_t data); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +/** This is the ICMP6 header adapted for echo req/resp. */ +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct icmp6_echo_hdr { + PACK_STRUCT_FLD_8(u8_t type); + PACK_STRUCT_FLD_8(u8_t code); + PACK_STRUCT_FIELD(u16_t chksum); + PACK_STRUCT_FIELD(u16_t id); + PACK_STRUCT_FIELD(u16_t seqno); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_HDR_PROT_ICMP6_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/prot/ieee.h b/sdk_liteos/third_party/lwip_sack/include/lwip/prot/ieee.h new file mode 100644 index 0000000000000000000000000000000000000000..bce349075ebfe1fe51a4ef4bdd9857d827f17663 --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/prot/ieee.h @@ -0,0 +1,91 @@ +/** + * @file + * IEEE assigned numbers + * + * @defgroup ieee IEEE assigned numbers + * @ingroup infrastructure + */ + +/* + * Copyright (c) 2017 Dirk Ziegelmeier. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Dirk Ziegelmeier + * + */ + +#ifndef LWIP_HDR_PROT_IEEE_H +#define LWIP_HDR_PROT_IEEE_H + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +/** + * @ingroup ieee + * A list of often ethtypes (although lwIP does not use all of them). + */ +enum lwip_ieee_eth_type { + /* Internet protocol v4 */ + ETHTYPE_IP = 0x0800U, + /* Address resolution protocol */ + ETHTYPE_ARP = 0x0806U, + /* Wake on lan */ + ETHTYPE_WOL = 0x0842U, + /* RARP */ + ETHTYPE_RARP = 0x8035U, + /* Virtual local area network */ + ETHTYPE_VLAN = 0x8100U, + /* Internet protocol v6 */ + ETHTYPE_IPV6 = 0x86DDU, + /* Jumbo Frames */ + ETHTYPE_JUMBO = 0x8870U, + /* Process field network */ + ETHTYPE_PROFINET = 0x8892U, + /* Ethernet for control automation technology */ + ETHTYPE_ETHERCAT = 0x88A4U, + /* Link layer discovery protocol */ + ETHTYPE_LLDP = 0x88CCU, + /* Serial real-time communication system */ + ETHTYPE_SERCOS = 0x88CDU, + /* Media redundancy protocol */ + ETHTYPE_MRP = 0x88E3U, + /* Precision time protocol */ + ETHTYPE_PTP = 0x88F7U, + /* 6lowpan protocol */ + ETHTYPE_6LOWPAN = 0xA0EDU, + /* Q-in-Q, 802.1ad */ + ETHTYPE_QINQ = 0x9100U, + /* All packets **/ + ETHTYPE_ALL = 0x0003U +}; + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_HDR_PROT_IEEE_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/prot/igmp.h b/sdk_liteos/third_party/lwip_sack/include/lwip/prot/igmp.h new file mode 100644 index 0000000000000000000000000000000000000000..c5814996f59184415868c9a579a9a65c9bac016d --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/prot/igmp.h @@ -0,0 +1,90 @@ +/** + * @file + * IGMP protocol definitions + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_PROT_IGMP_H +#define LWIP_HDR_PROT_IGMP_H + +#include "lwip/arch.h" +#include "lwip/ip4_addr.h" + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +/* + * IGMP constants + */ +#define IGMP_TTL 1 +#define IGMP_MINLEN 8 +#define ROUTER_ALERT 0x9404U +#define ROUTER_ALERTLEN 4 + +/* + * IGMP message types, including version number. + */ +#define IGMP_MEMB_QUERY 0x11 /* Membership query */ +#define IGMP_V1_MEMB_REPORT 0x12 /* Ver. 1 membership report */ +#define IGMP_V2_MEMB_REPORT 0x16 /* Ver. 2 membership report */ +#define IGMP_LEAVE_GROUP 0x17 /* Leave-group message */ + +/* Group membership states */ +#define IGMP_GROUP_NON_MEMBER 0 +#define IGMP_GROUP_DELAYING_MEMBER 1 +#define IGMP_GROUP_IDLE_MEMBER 2 + +/* + * IGMP packet format. + */ +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct igmp_msg { + PACK_STRUCT_FLD_8(u8_t igmp_msgtype); + PACK_STRUCT_FLD_8(u8_t igmp_maxresp); + PACK_STRUCT_FIELD(u16_t igmp_checksum); + PACK_STRUCT_FLD_S(ip4_addr_p_t igmp_group_address); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_HDR_PROT_IGMP_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/prot/ip.h b/sdk_liteos/third_party/lwip_sack/include/lwip/prot/ip.h new file mode 100644 index 0000000000000000000000000000000000000000..0c1587336b7531e402f08b869e7722e27326a449 --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/prot/ip.h @@ -0,0 +1,51 @@ +/** + * @file + * IP protocol definitions + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_PROT_IP_H +#define LWIP_HDR_PROT_IP_H + +#include "lwip/arch.h" + +#define IP_PROTO_ICMP 1 +#define IP_PROTO_IGMP 2 +#define IP_PROTO_UDP 17 +#define IP_PROTO_UDPLITE 136 +#define IP_PROTO_TCP 6 + +/* This operates on a void* by loading the first byte */ +#define IP_HDR_GET_VERSION(ptr) ((*(u8_t*)(ptr)) >> 4) + +#endif /* LWIP_HDR_PROT_IP_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/prot/ip4.h b/sdk_liteos/third_party/lwip_sack/include/lwip/prot/ip4.h new file mode 100644 index 0000000000000000000000000000000000000000..412b9f74cd4df457241728b071497b109e5fec23 --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/prot/ip4.h @@ -0,0 +1,141 @@ +/** + * @file + * IPv4 protocol definitions + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_PROT_IP4_H +#define LWIP_HDR_PROT_IP4_H + +#include "lwip/arch.h" +#include "lwip/ip4_addr.h" +#if LWIP_LITEOS_COMPAT +#include +#endif + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +/* This is the packed version of ip4_addr_t, + used in network headers that are itself packed */ +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct ip4_addr_packed { + PACK_STRUCT_FIELD(u32_t addr); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +typedef struct ip4_addr_packed ip4_addr_p_t; + +/* Size of the IPv4 header. Same as 'sizeof(struct ip_hdr)'. */ +#define IP_HLEN 20 + +/* Maximum size of the IPv4 header with options. */ +#define IP_HLEN_MAX 60 + +#ifndef IP_RF +#define IP_RF 0x8000U /* reserved fragment flag */ +#endif +#ifndef IP_DF +#define IP_DF 0x4000U /* don't fragment flag */ +#endif +#ifndef IP_MF +#define IP_MF 0x2000U /* more fragments flag */ +#endif +#ifndef IP_OFFMASK +#define IP_OFFMASK 0x1fffU /* mask for fragmenting bits */ +#endif + +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +/* The IPv4 header */ +struct ip_hdr { + /* version / header length */ + PACK_STRUCT_FLD_8(u8_t _v_hl); + /* type of service */ + PACK_STRUCT_FLD_8(u8_t _tos); + /* total length */ + PACK_STRUCT_FIELD(u16_t _len); + /* identification */ + PACK_STRUCT_FIELD(u16_t _id); + /* fragment offset field */ + PACK_STRUCT_FIELD(u16_t _offset); + /* time to live */ + PACK_STRUCT_FLD_8(u8_t _ttl); + /* protocol*/ + PACK_STRUCT_FLD_8(u8_t _proto); + /* checksum */ + PACK_STRUCT_FIELD(u16_t _chksum); + /* source and destination IP addresses */ + PACK_STRUCT_FLD_S(ip4_addr_p_t src); + PACK_STRUCT_FLD_S(ip4_addr_p_t dest); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +/* Macros to get struct ip_hdr fields: */ +#define IPH_V(hdr) ((hdr)->_v_hl >> 4) +#define IPH_HL(hdr) ((hdr)->_v_hl & 0x0f) +#define IPH_TOS(hdr) ((hdr)->_tos) +#define IPH_LEN(hdr) ((hdr)->_len) +#define IPH_ID(hdr) ((hdr)->_id) +#define IPH_OFFSET(hdr) ((hdr)->_offset) +#define IPH_TTL(hdr) ((hdr)->_ttl) +#define IPH_PROTO(hdr) ((hdr)->_proto) +#define IPH_CHKSUM(hdr) ((hdr)->_chksum) + +/* Macros to set struct ip_hdr fields: */ +#define IPH_VHL_SET(hdr, v, hl) (hdr)->_v_hl = (u8_t)((((v) << 4) | (hl))) +#define IPH_TOS_SET(hdr, tos) (hdr)->_tos = (tos) +#define IPH_LEN_SET(hdr, len) (hdr)->_len = (len) +#define IPH_ID_SET(hdr, id) (hdr)->_id = (id) +#define IPH_OFFSET_SET(hdr, off) (hdr)->_offset = (off) +#define IPH_TTL_SET(hdr, ttl) (hdr)->_ttl = (u8_t)(ttl) +#define IPH_PROTO_SET(hdr, proto) (hdr)->_proto = (u8_t)(proto) +#define IPH_CHKSUM_SET(hdr, chksum) (hdr)->_chksum = (chksum) + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_HDR_PROT_IP4_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/prot/ip6.h b/sdk_liteos/third_party/lwip_sack/include/lwip/prot/ip6.h new file mode 100644 index 0000000000000000000000000000000000000000..9cd9e9b4083f19943a3ffa56c94977749c7c31ed --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/prot/ip6.h @@ -0,0 +1,230 @@ +/** + * @file + * IPv6 protocol definitions + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_PROT_IP6_H +#define LWIP_HDR_PROT_IP6_H + +#include "lwip/arch.h" +#include "lwip/ip6_addr.h" + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +/** This is the packed version of ip6_addr_t, + used in network headers that are itself packed */ +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct ip6_addr_packed { + PACK_STRUCT_FIELD(u32_t addr[4]); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif +typedef struct ip6_addr_packed ip6_addr_p_t; + +#define IP6_HLEN 40 + +#define IP6_ADDR_LEN 128 // 128 bits + +#define IP6_NEXTH_HOPBYHOP 0 +#define IP6_NEXTH_TCP 6 +#define IP6_NEXTH_UDP 17 +#define IP6_NEXTH_ENCAPS 41 +#define IP6_NEXTH_ROUTING 43 +#define IP6_NEXTH_FRAGMENT 44 +#define IP6_NEXTH_ICMP6 58 +#define IP6_NEXTH_NONE 59 +#define IP6_NEXTH_DESTOPTS 60 +#define IP6_NEXTH_UDPLITE 136 + +/* + * include Next Header (8bits) and Hdr Ext Len (8bits) + */ +#define IP6_EXTENSION_HEADER_MIN_LEN 2 + +/* + * Extension Header + * Hdr Ext Len: + * 8-bit unsigned integer. Length of the Routing header in 8-octet units, not including the first 8 octets. + */ +#define IP6_HDR_EXT_LEN_UNIT 8 + +/** The IPv6 header. */ +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct ip6_hdr { + /** version / traffic class / flow label */ + PACK_STRUCT_FIELD(u32_t _v_tc_fl); + /** payload length */ + PACK_STRUCT_FIELD(u16_t _plen); + /** next header */ + PACK_STRUCT_FLD_8(u8_t _nexth); + /** hop limit */ + PACK_STRUCT_FLD_8(u8_t _hoplim); + /** source and destination IP addresses */ + PACK_STRUCT_FLD_S(ip6_addr_p_t src); + PACK_STRUCT_FLD_S(ip6_addr_p_t dest); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +/* Hop-by-hop router alert option. */ +#define IP6_HBH_HLEN 8 +/* Hop-by-Hop header. */ +#define IP6_HBH_HALFHLEN 2 + +#define IP6_PAD1_OPTION 0 +#define IP6_PADN_ALERT_OPTION 1 +#define IP6_PADN_OPTION IP6_PADN_ALERT_OPTION + +#define IP6_ROUTER_ALERT_OPTION 5 +#define IP6_JUMBO_OPTION 194 +#define IP6_ROUTER_ALERT_VALUE_MLD 0 + +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct ip6_opt_hdr { + /* router alert option type */ + PACK_STRUCT_FLD_8(u8_t _opt_type); + /* router alert option data len */ + PACK_STRUCT_FLD_8(u8_t _opt_dlen); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END + + +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif +#define IP6_OPT_HLEN 2 +#define IP6_OPT_TYPE_ACTION(hdr) ((((hdr)->_opt_type) >> 6) & 0x3) +#define IP6_OPT_TYPE_CHANGE(hdr) ((((hdr)->_opt_type) >> 5) & 0x1) +#define IP6_OPT_TYPE(hdr) ((hdr)->_opt_type) +#define IP6_OPT_DLEN(hdr) ((hdr)->_opt_dlen) + +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct ip6_hbh_hdr { + /* next header */ + PACK_STRUCT_FLD_8(u8_t _nexth); + /* header length */ + PACK_STRUCT_FLD_8(u8_t _hlen); + /* router alert option type */ + PACK_STRUCT_FLD_8(u8_t _ra_opt_type); + /* router alert option data len */ + PACK_STRUCT_FLD_8(u8_t _ra_opt_dlen); + /* router alert option data */ + PACK_STRUCT_FIELD(u16_t _ra_opt_data); + /* PadN option type */ + PACK_STRUCT_FLD_8(u8_t _padn_opt_type); + /* PadN option data len */ + PACK_STRUCT_FLD_8(u8_t _padn_opt_dlen); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +/* Destination header. */ +#define IP6_DEST_HLEN 2 + +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct ip6_dest_hdr { + /* next header */ + PACK_STRUCT_FLD_8(u8_t _nexth); + /* header length in 8-octet units */ + PACK_STRUCT_FLD_8(u8_t _hlen); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END + +/* Fragment header. */ +#define IP6_FRAG_HLEN 8 +#define IP6_FRAG_OFFSET_MASK 0xfff8 +#define IP6_FRAG_MORE_FLAG 0x0001 +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct ip6_frag_hdr { + /* next header */ + PACK_STRUCT_FLD_8(u8_t _nexth); + /* reserved */ + PACK_STRUCT_FLD_8(u8_t reserved); + /* fragment offset */ + PACK_STRUCT_FIELD(u16_t _fragment_offset); + /* fragmented packet identification */ + PACK_STRUCT_FIELD(u32_t _identification); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +#define IP6H_V(hdr) ((lwip_ntohl((hdr)->_v_tc_fl) >> 28) & 0x0f) +#define IP6H_TC(hdr) ((lwip_ntohl((hdr)->_v_tc_fl) >> 20) & 0xff) +#define IP6H_FL(hdr) (lwip_ntohl((hdr)->_v_tc_fl) & 0x000fffff) +#define IP6H_PLEN(hdr) (lwip_ntohs((hdr)->_plen)) +#define IP6H_NEXTH(hdr) ((hdr)->_nexth) +#define IP6H_HOPLIM(hdr) ((hdr)->_hoplim) + +#define IP6H_VTCFL_SET(hdr, v, tc, fl) (hdr)->_v_tc_fl = (lwip_htonl((((u32_t)(v)) << 28) | (((u32_t)(tc)) << 20) | (fl))) +#define IP6H_PLEN_SET(hdr, plen) (hdr)->_plen = lwip_htons(plen) +#define IP6H_NEXTH_SET(hdr, nexth) (hdr)->_nexth = (nexth) +#define IP6H_HOPLIM_SET(hdr, hl) (hdr)->_hoplim = (u8_t)(hl) + + +#define IP6H_FRAG_MBIT(hdr) (lwip_ntohs((hdr)->_fragment_offset) & 0x1) + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_HDR_PROT_IP6_H */ + diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/prot/mld6.h b/sdk_liteos/third_party/lwip_sack/include/lwip/prot/mld6.h new file mode 100644 index 0000000000000000000000000000000000000000..9f8f87bd3a48b2243660372835298b63a0165504 --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/prot/mld6.h @@ -0,0 +1,108 @@ +/** + * @file + * MLD6 protocol definitions + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_PROT_MLD6_H +#define LWIP_HDR_PROT_MLD6_H + +#include "lwip/arch.h" +#include "lwip/prot/ip6.h" + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +/* Multicast listener report/query/done message header. */ +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct mld_header { + PACK_STRUCT_FLD_8(u8_t type); + PACK_STRUCT_FLD_8(u8_t code); + PACK_STRUCT_FIELD(u16_t chksum); + PACK_STRUCT_FIELD(u16_t max_resp_delay); + PACK_STRUCT_FIELD(u16_t reserved); + PACK_STRUCT_FLD_S(ip6_addr_p_t multicast_address); + /* Options follow. */ +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +#ifndef MLD6_ROBUSTNESS_VARIABLE +#define MLD6_ROBUSTNESS_VARIABLE 5 +#endif /* MLD6_ROBUSTNESS_VARIABLE */ + +#ifndef MLD6_QUERY_INTERVAL +#define MLD6_QUERY_INTERVAL 125 /* in units of seconds */ +#endif /* MLD6_QUERY_INTERVAL */ + +#ifndef MLD6_STARTUP_QUERY_COUNT +#define MLD6_STARTUP_QUERY_COUNT (MLD6_ROBUSTNESS_VARIABLE) +#endif /* MLD6_STARTUP_QUERY_COUNT */ + +#ifndef MLD6_STARTUP_QUERY_INTERVAL +#define MLD6_STARTUP_QUERY_INTERVAL 1 /* in units of seconds */ +#endif /* MLD6_STARTUP_QUERY_INTERVAL */ + +/* The number of seconds represented by the [Query Response Interval] must be less than the [Query Interval] */ +#ifndef MLD6_QUERY_RESPONSE_INTERVAL +#define MLD6_QUERY_RESPONSE_INTERVAL 10000 /* in units of milliseconds */ +#endif /* MLD6_QUERY_RESPONSE_INTERVAL */ + +#if (((MLD6_QUERY_RESPONSE_INTERVAL) / 1000) >= MLD6_QUERY_INTERVAL) +#error "The number of seconds represented by the [Query Response Interval] must be less than the [Query Interval]" +#endif + +#ifndef MLD6_LISTENER_INTERVAL +#define MLD6_LISTENER_INTERVAL (((MLD6_ROBUSTNESS_VARIABLE) * (MLD6_QUERY_INTERVAL)) + \ + ((MLD6_QUERY_RESPONSE_INTERVAL) / (MLD6_MS_PER_SECOND))) +#endif /* MLD6_LISTENER_INTERVAL */ + +#ifndef MLD6_LAST_LISTENER_QUERY_INTERVAL +#define MLD6_LAST_LISTENER_QUERY_INTERVAL 1000 /* in units of milliseconds */ +#endif /* MLD6_LAST_LISTENER_QUERY_INTERVAL */ + +#ifndef MLD6_LAST_LISTENER_QUERY_COUNT +#define MLD6_LAST_LISTENER_QUERY_COUNT (MLD6_ROBUSTNESS_VARIABLE) +#endif /* MLD6_LAST_LISTENER_QUERY_COUNT */ + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_HDR_PROT_MLD6_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/prot/nd6.h b/sdk_liteos/third_party/lwip_sack/include/lwip/prot/nd6.h new file mode 100644 index 0000000000000000000000000000000000000000..2755a756e9a0087c7cc790a6d3a0f73c88c84a5b --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/prot/nd6.h @@ -0,0 +1,297 @@ +/** + * @file + * ND6 protocol definitions + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_PROT_ND6_H +#define LWIP_HDR_PROT_ND6_H + +#include "lwip/arch.h" +#include "lwip/ip6_addr.h" +#include "lwip/prot/ip6.h" + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +/** Neighbor solicitation message header. */ +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct ns_header { + PACK_STRUCT_FLD_8(u8_t type); + PACK_STRUCT_FLD_8(u8_t code); + PACK_STRUCT_FIELD(u16_t chksum); + PACK_STRUCT_FIELD(u32_t reserved); + PACK_STRUCT_FLD_S(ip6_addr_p_t target_address); + /* Options follow. */ +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +/** Neighbor advertisement message header. */ +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct na_header { + PACK_STRUCT_FLD_8(u8_t type); + PACK_STRUCT_FLD_8(u8_t code); + PACK_STRUCT_FIELD(u16_t chksum); + PACK_STRUCT_FLD_8(u8_t flags); + PACK_STRUCT_FLD_8(u8_t reserved[3]); + PACK_STRUCT_FLD_S(ip6_addr_p_t target_address); + /* Options follow. */ +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif +#define ND6_FLAG_ROUTER 0x80 +#define ND6_FLAG_SOLICITED 0x40 +#define ND6_FLAG_OVERRIDE 0x20 + +/** Router solicitation message header. */ +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct rs_header { + PACK_STRUCT_FLD_8(u8_t type); + PACK_STRUCT_FLD_8(u8_t code); + PACK_STRUCT_FIELD(u16_t chksum); + PACK_STRUCT_FIELD(u32_t reserved); + /* Options follow. */ +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +/** Router advertisement message header. */ +#define ND6_RA_FLAG_MANAGED_ADDR_CONFIG 0x80 +#define ND6_RA_FLAG_OTHER_CONFIG 0x40 +#define ND6_RA_FLAG_HOME_AGENT 0x20 +#define ND6_RA_PREFERENCE_MASK 0x18 +#define ND6_RA_PREFERENCE_HIGH 0x08 +#define ND6_RA_PREFERENCE_MEDIUM 0x00 +#define ND6_RA_PREFERENCE_LOW 0x18 +#define ND6_RA_PREFERENCE_DISABLED 0x10 + +#define ND6_RA_INIT_COUNT 3 +#define ND6_RA_INIT_INTERVAL 3 +#define ND6_RA_NORMAL_INTERVAL 16 + +#ifndef ND6_RA_MAX_INTERVAL +#define ND6_RA_MAX_INTERVAL 600 +#endif + +#ifndef ND6_RA_ROUTER_LIFETIME +#define ND6_RA_ROUTER_LIFETIME (3 * (ND6_RA_MAX_INTERVAL)) +#endif + +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct ra_header { + PACK_STRUCT_FLD_8(u8_t type); + PACK_STRUCT_FLD_8(u8_t code); + PACK_STRUCT_FIELD(u16_t chksum); + PACK_STRUCT_FLD_8(u8_t current_hop_limit); + PACK_STRUCT_FLD_8(u8_t flags); + PACK_STRUCT_FIELD(u16_t router_lifetime); + PACK_STRUCT_FIELD(u32_t reachable_time); + PACK_STRUCT_FIELD(u32_t retrans_timer); + /* Options follow. */ +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +/** Redirect message header. */ +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct redirect_header { + PACK_STRUCT_FLD_8(u8_t type); + PACK_STRUCT_FLD_8(u8_t code); + PACK_STRUCT_FIELD(u16_t chksum); + PACK_STRUCT_FIELD(u32_t reserved); + PACK_STRUCT_FLD_S(ip6_addr_p_t target_address); + PACK_STRUCT_FLD_S(ip6_addr_p_t destination_address); + /* Options follow. */ +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +/** Link-layer address option. */ +#define ND6_OPTION_TYPE_SOURCE_LLADDR 0x01 +#define ND6_OPTION_TYPE_TARGET_LLADDR 0x02 + +/* Redirected Header option */ +#define ND6_OPTION_TYPE_REDIRECT_HEADER 0x04 + +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct lladdr_option { + PACK_STRUCT_FLD_8(u8_t type); + PACK_STRUCT_FLD_8(u8_t length); + PACK_STRUCT_FLD_8(u8_t addr[NETIF_MAX_HWADDR_LEN]); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +/** Prefix information option. */ +#define ND6_OPTION_TYPE_PREFIX_INFO 0x03 +#define ND6_PREFIX_FLAG_ON_LINK 0x80 +#define ND6_PREFIX_FLAG_AUTONOMOUS 0x40 +#define ND6_PREFIX_FLAG_ROUTER_ADDRESS 0x20 +#define ND6_PREFIX_FLAG_SITE_PREFIX 0x10 +#define ND6_PREFIX_FIXED_LEN 64 +#define ND6_PREFIX_LIFETIME_INFINITY 0xFFFFFFFF + +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct prefix_option { + PACK_STRUCT_FLD_8(u8_t type); + PACK_STRUCT_FLD_8(u8_t length); + PACK_STRUCT_FLD_8(u8_t prefix_length); + PACK_STRUCT_FLD_8(u8_t flags); + PACK_STRUCT_FIELD(u32_t valid_lifetime); + PACK_STRUCT_FIELD(u32_t preferred_lifetime); + PACK_STRUCT_FLD_8(u8_t reserved2[4]); + PACK_STRUCT_FLD_S(ip6_addr_p_t prefix); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +/** Redirected header option. */ +#define ND6_OPTION_TYPE_REDIR_HDR 0x04 +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct redirected_header_option { + PACK_STRUCT_FLD_8(u8_t type); + PACK_STRUCT_FLD_8(u8_t length); + PACK_STRUCT_FLD_8(u8_t reserved[6]); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +/** MTU option. */ +#define ND6_OPTION_TYPE_MTU 0x05 +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct mtu_option { + PACK_STRUCT_FLD_8(u8_t type); + PACK_STRUCT_FLD_8(u8_t length); + PACK_STRUCT_FIELD(u16_t reserved); + PACK_STRUCT_FIELD(u32_t mtu); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +/** Route information option. */ +#define ND6_OPTION_TYPE_ROUTE_INFO 24 +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct route_option { + PACK_STRUCT_FLD_8(u8_t type); + PACK_STRUCT_FLD_8(u8_t length); + PACK_STRUCT_FLD_8(u8_t prefix_length); + PACK_STRUCT_FLD_8(u8_t preference); + PACK_STRUCT_FIELD(u32_t route_lifetime); + PACK_STRUCT_FLD_S(ip6_addr_p_t prefix); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +/** Recursive DNS Server Option. */ +#if LWIP_ND6_RDNSS_MAX_DNS_SERVERS +#define LWIP_RDNSS_OPTION_MAX_SERVERS LWIP_ND6_RDNSS_MAX_DNS_SERVERS +#else +#define LWIP_RDNSS_OPTION_MAX_SERVERS 1 +#endif +#define ND6_OPTION_TYPE_RDNSS 25 + +#define ND6_OPTION_RDNSS_MAX_LEN (1 + (2 * (LWIP_RDNSS_OPTION_MAX_SERVERS))) +#define ND6_RDNSS_LIFETIME_INFINITY 0xFFFFFFFF +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct rdnss_option { + PACK_STRUCT_FLD_8(u8_t type); + PACK_STRUCT_FLD_8(u8_t length); + PACK_STRUCT_FIELD(u16_t reserved); + PACK_STRUCT_FIELD(u32_t lifetime); + PACK_STRUCT_FLD_S(ip6_addr_p_t rdnss_address[LWIP_RDNSS_OPTION_MAX_SERVERS]); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_HDR_PROT_ND6_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/prot/tcp.h b/sdk_liteos/third_party/lwip_sack/include/lwip/prot/tcp.h new file mode 100644 index 0000000000000000000000000000000000000000..293a892d6884cf9941f794cd67d24d1f34decba7 --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/prot/tcp.h @@ -0,0 +1,103 @@ +/** + * @file + * TCP protocol definitions + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_PROT_TCP_H +#define LWIP_HDR_PROT_TCP_H + +#include "lwip/arch.h" + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +/* Length of the TCP header, excluding options. */ +#define TCP_HLEN 20 + +/* Fields are (of course) in network byte order. + * Some fields are converted to host byte order in tcp_input(). + */ +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct tcp_hdr { + PACK_STRUCT_FIELD(u16_t src); + PACK_STRUCT_FIELD(u16_t dest); + PACK_STRUCT_FIELD(u32_t seqno); + PACK_STRUCT_FIELD(u32_t ackno); + PACK_STRUCT_FIELD(u16_t _hdrlen_rsvd_flags); + PACK_STRUCT_FIELD(u16_t wnd); + PACK_STRUCT_FIELD(u16_t chksum); + PACK_STRUCT_FIELD(u16_t urgp); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +/* TCP header flags bits */ +#define TCP_FIN 0x01U +#define TCP_SYN 0x02U +#define TCP_RST 0x04U +#define TCP_PSH 0x08U +#define TCP_ACK 0x10U +#define TCP_URG 0x20U +#define TCP_ECE 0x40U +#define TCP_CWR 0x80U +/* Valid TCP header flags */ +#define TCP_FLAGS 0x3fU + +#define TCPH_HDRLEN(phdr) ((u16_t)(lwip_ntohs((phdr)->_hdrlen_rsvd_flags) >> 12)) +#define TCPH_FLAGS(phdr) ((u16_t)(lwip_ntohs((phdr)->_hdrlen_rsvd_flags) & TCP_FLAGS)) + +#define TCPH_HDRLEN_SET(phdr, len) do { \ + (phdr)->_hdrlen_rsvd_flags = lwip_htons(((len) << 12) | TCPH_FLAGS(phdr)); } while (0) +#define TCPH_FLAGS_SET(phdr, flags) do { \ + (phdr)->_hdrlen_rsvd_flags = (u16_t)(((phdr)->_hdrlen_rsvd_flags & PP_HTONS((u16_t)(~(u16_t)TCP_FLAGS))) | \ + lwip_htons(flags)); } while (0) +#define TCPH_HDRLEN_FLAGS_SET(phdr, len, flags) do { \ + (phdr)->_hdrlen_rsvd_flags = (u16_t)(lwip_htons((u16_t)(((u16_t)((len) << 12)) | (flags)))); } while (0) + +#define TCPH_SET_FLAG(phdr, flags) do { \ + (phdr)->_hdrlen_rsvd_flags = ((phdr)->_hdrlen_rsvd_flags | lwip_htons(flags)); } while (0) +#define TCPH_UNSET_FLAG(phdr, flags) do { \ + (phdr)->_hdrlen_rsvd_flags = ((phdr)->_hdrlen_rsvd_flags & ~lwip_htons(flags)); } while (0) + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_HDR_PROT_TCP_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/prot/udp.h b/sdk_liteos/third_party/lwip_sack/include/lwip/prot/udp.h new file mode 100644 index 0000000000000000000000000000000000000000..6d96847984b04cccaf8160c0748a3286a511e572 --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/prot/udp.h @@ -0,0 +1,68 @@ +/** + * @file + * UDP protocol definitions + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_PROT_UDP_H +#define LWIP_HDR_PROT_UDP_H + +#include "lwip/arch.h" + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +#define UDP_HLEN 8 + +/* Fields are (of course) in network byte order. */ +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct udp_hdr { + PACK_STRUCT_FIELD(u16_t src); + PACK_STRUCT_FIELD(u16_t dest); /* src/dest UDP ports */ + PACK_STRUCT_FIELD(u16_t len); + PACK_STRUCT_FIELD(u16_t chksum); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_HDR_PROT_UDP_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/raw.h b/sdk_liteos/third_party/lwip_sack/include/lwip/raw.h new file mode 100644 index 0000000000000000000000000000000000000000..9f9a2cd9ae8cd81bc3ef8ad1a31e55b048588fc5 --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/raw.h @@ -0,0 +1,209 @@ +/** + * @file + * raw API (to be used from TCPIP thread)\n + * See also @ref raw_raw + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_RAW_H +#define LWIP_HDR_RAW_H + +#include "lwip/opt.h" + +#if LWIP_RAW /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/pbuf.h" +#include "lwip/def.h" +#include "lwip/ip.h" +#include "lwip/ip_addr.h" +#include "lwip/ip6_addr.h" +#include "lwip/icmp6.h" + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +#define RAW_FLAGS_CONNECTED 0x01U +#define RAW_FLAGS_HDRINCL 0x02U +#define RAW_FLAGS_MULTICAST_LOOP 0x04U + +struct raw_pcb; +extern struct raw_pcb *raw_pcbs; + +#if PF_PKT_SUPPORT +extern struct raw_pcb *pkt_raw_pcbs; +extern struct raw_pcb *all_pkt_raw_pcbs; +extern const struct eth_hdr *g_lwip_current_eth_hdr; +extern const struct netif *g_lwip_current_netif; + +/* + * Dest MAC add of current ethernet header of RAW packets + * received for PF_PACKET family + */ +#define eth_current_hdr() (g_lwip_current_eth_hdr) +#define eth_current_netif() (g_lwip_current_netif) +#endif + +#if LWIP_NETIF_PROMISC +extern u8_t pkt_raw_pcbs_using_netif(u8_t ifindex); +#endif /* LWIP_NETIF_PROMISC */ + +#ifndef IPPROTO_ICMPV6 +#define IPPROTO_ICMPV6 58 +#endif + +/* Function prototype for raw pcb receive callback functions. + * @param arg user supplied argument (raw_pcb.recv_arg) + * @param pcb the raw_pcb which received data + * @param p the packet buffer that was received + * @param addr the remote IP address from which the packet was received + * @return 1 if the packet was 'eaten' (aka. deleted), + * 0 if the packet lives on + * If returning 1, the callback is responsible for freeing the pbuf + * if it's not used any more. + */ +typedef u8_t (*raw_recv_fn)(void *arg, struct raw_pcb *pcb, struct pbuf *p, + const ip_addr_t *addr); + +/* the RAW protocol control block */ +struct raw_pcb { + /* Common members of all PCB types */ + IP_PCB; + u8_t hdrincl; + + struct raw_pcb *next; +#if PF_PKT_SUPPORT + struct raw_pcb *all_next; + u8_t netifindex; + + union { + u16_t eth_proto; /* Ethernet HeaderType/Protocol for Packet sockets */ +#define raw_proto proto.protocol + u8_t protocol; /* IP protocol for AF_INET sockets */ + } proto; +#else +#define raw_proto protocol + u8_t protocol; +#endif + +#if LWIP_MULTICAST_TX_OPTIONS + /** outgoing network interface for multicast packets, by interface index (if nonzero) */ + u8_t mcast_ifindex; + /** TTL for outgoing multicast packets */ + u8_t mcast_ttl; +#endif /* LWIP_MULTICAST_TX_OPTIONS */ + + /* receive callback function */ + raw_recv_fn recv; + /* user-supplied argument for the recv callback */ + void *recv_arg; + +#if LWIP_SO_PRIORITY + prio_t priority; +#endif /* LWIP_SO_PRIORITY */ + +#if LWIP_IPV6 + /* fields for handling checksum computations as per RFC3542. */ + u16_t chksum_offset; + u8_t chksum_reqd; + +#if LWIP_MAC_SECURITY + u8_t macsec_reqd: 1; +#endif +#if LWIP_SOCK_OPT_ICMP6_FILTER + struct icmp6_filter icmp6_filter; +#endif +#endif + + u32_t flags; +}; + +#if LWIP_SO_PRIORITY +#define raw_getpriority(pcb) ((pcb)->priority) +#endif /* LWIP_SO_PRIORITY */ + +/* The following functions is the application layer interface to the + RAW code. */ +struct raw_pcb *raw_new (u8_t proto); +struct raw_pcb *raw_new_ip_type(u8_t type, u8_t proto); +void raw_remove (struct raw_pcb *pcb); +err_t raw_bind (struct raw_pcb *pcb, const ip_addr_t *ipaddr); +err_t raw_connect (struct raw_pcb *pcb, const ip_addr_t *ipaddr); +void raw_disconnect (struct raw_pcb *pcb); + +err_t raw_sendto (struct raw_pcb *pcb, struct pbuf *p, const ip_addr_t *ipaddr); +err_t raw_sendto_if_src(struct raw_pcb *pcb, struct pbuf *p, const ip_addr_t *dst_ip, struct netif *netif, const ip_addr_t *src_ip); +err_t raw_send (struct raw_pcb *pcb, struct pbuf *p); + +void raw_recv (struct raw_pcb *pcb, raw_recv_fn recv, void *recv_arg); + +#define raw_flags(pcb) ((pcb)->flags) +#define raw_setflags(pcb,f) ((pcb)->flags = (f)) + +#define raw_set_flags(pcb, set_flags) do { (pcb)->flags = (u8_t)((pcb)->flags | (set_flags)); } while(0) +#define raw_clear_flags(pcb, clr_flags) do { (pcb)->flags = (u8_t)((pcb)->flags & (u8_t)(~(clr_flags) & 0xff)); } while(0) +#define raw_is_flag_set(pcb, flag) (((pcb)->flags & (flag)) != 0) + +#if PF_PKT_SUPPORT +struct raw_pcb *raw_pkt_new (u16_t proto); +void raw_pkt_remove (struct raw_pcb *pcb); +void raw_pkt_input (struct pbuf *p, struct netif *inp, struct raw_pcb *from); +err_t raw_pkt_sendto (struct raw_pcb *pcb, struct pbuf *p, u8_t ifindex); +err_t raw_pkt_bind (struct raw_pcb *pcb, u8_t ifindex, u16_t proto); +#endif + +#define raw_init() /* Compatibility define, no init needed. */ + +/* for compatibility with older implementation */ +#define raw_new_ip6(proto) raw_new_ip_type(IPADDR_TYPE_V6, proto) + +#if LWIP_MULTICAST_TX_OPTIONS +#define raw_set_multicast_netif_index(pcb, idx) ((pcb)->mcast_ifindex = (idx)) +#define raw_get_multicast_netif_index(pcb) ((pcb)->mcast_ifindex) +#define raw_set_multicast_ttl(pcb, value) ((pcb)->mcast_ttl = (value)) +#define raw_get_multicast_ttl(pcb) ((pcb)->mcast_ttl) +#endif /* LWIP_MULTICAST_TX_OPTIONS */ + +#if LWIP_IPV6 && LWIP_RAW + +u8_t raw_input6(struct pbuf *p, s16_t proto, s8_t *isCheckSumInvalid, + struct netif *inp); +#endif + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_RAW */ + +#endif /* LWIP_HDR_RAW_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/sio.h b/sdk_liteos/third_party/lwip_sack/include/lwip/sio.h new file mode 100644 index 0000000000000000000000000000000000000000..9eaa197eb374b0d581de7179f3e7b53483642209 --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/sio.h @@ -0,0 +1,142 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + */ + +/* + * This is the interface to the platform specific serial IO module + * It needs to be implemented by those platforms which need SLIP or PPP + */ + +#ifndef SIO_H +#define SIO_H + +#include "lwip/arch.h" +#include "lwip/opt.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* If you want to define sio_fd_t elsewhere or differently, + define this in your cc.h file. */ +#ifndef __sio_fd_t_defined +typedef void *sio_fd_t; +#endif + +/* The following functions can be defined to something else in your cc.h file + or be implemented in your custom sio.c file. */ + +#ifndef sio_open +/** + * Opens a serial device for communication. + * + * @param devnum device number + * @return handle to serial device if successful, NULL otherwise + */ +sio_fd_t sio_open(u8_t devnum); +#endif + +#ifndef sio_send +/** + * Sends a single character to the serial device. + * + * @param c character to send + * @param fd serial device handle + * + * @note This function will block until the character can be sent. + */ +void sio_send(u8_t c, sio_fd_t fd); +#endif + +#ifndef sio_recv +/** + * Receives a single character from the serial device. + * + * @param fd serial device handle + * + * @note This function will block until a character is received. + */ +u8_t sio_recv(sio_fd_t fd); +#endif + +#ifndef sio_read +/** + * Reads from the serial device. + * + * @param fd serial device handle + * @param data pointer to data buffer for receiving + * @param len maximum length (in bytes) of data to receive + * @return number of bytes actually received - may be 0 if aborted by sio_read_abort + * + * @note This function will block until data can be received. The blocking + * can be cancelled by calling sio_read_abort(). + */ +u32_t sio_read(sio_fd_t fd, u8_t *data, u32_t len); +#endif + +#ifndef sio_tryread +/** + * Tries to read from the serial device. Same as sio_read but returns + * immediately if no data is available and never blocks. + * + * @param fd serial device handle + * @param data pointer to data buffer for receiving + * @param len maximum length (in bytes) of data to receive + * @return number of bytes actually received + */ +u32_t sio_tryread(sio_fd_t fd, u8_t *data, u32_t len); +#endif + +#ifndef sio_write +/** + * Writes to the serial device. + * + * @param fd serial device handle + * @param data pointer to data to send + * @param len length (in bytes) of data to send + * @return number of bytes actually sent + * + * @note This function will block until all data can be sent. + */ +u32_t sio_write(sio_fd_t fd, u8_t *data, u32_t len); +#endif + +#ifndef sio_read_abort +/** + * Aborts a blocking sio_read() call. + * + * @param fd serial device handle + */ +void sio_read_abort(sio_fd_t fd); +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* SIO_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/snmp.h b/sdk_liteos/third_party/lwip_sack/include/lwip/snmp.h new file mode 100644 index 0000000000000000000000000000000000000000..24a167e87ff59cfb990eb03ea9a5d25e2ffcfdbc --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/snmp.h @@ -0,0 +1,213 @@ +/** + * @file + * SNMP support API for implementing netifs and statitics for MIB2 + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Dirk Ziegelmeier + * + */ +#ifndef LWIP_HDR_SNMP_H +#define LWIP_HDR_SNMP_H + +#include "lwip/opt.h" +#include "lwip/ip_addr.h" + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +struct udp_pcb; +struct netif; + +/* + * @defgroup netif_mib2 MIB2 statistics + * @ingroup netif + */ + +/* MIB2 statistics functions */ +#if MIB2_STATS /* don't build if not configured for use in lwipopts.h */ +/* + * @ingroup netif_mib2 + * @see RFC1213, "MIB-II, 6. Definitions" + */ +enum snmp_ifType { + snmp_ifType_other = 1, /* none of the following */ + snmp_ifType_regular1822, + snmp_ifType_hdh1822, + snmp_ifType_ddn_x25, + snmp_ifType_rfc877_x25, + snmp_ifType_ethernet_csmacd, + snmp_ifType_iso88023_csmacd, + snmp_ifType_iso88024_tokenBus, + snmp_ifType_iso88025_tokenRing, + snmp_ifType_iso88026_man, + snmp_ifType_starLan, + snmp_ifType_proteon_10Mbit, + snmp_ifType_proteon_80Mbit, + snmp_ifType_hyperchannel, + snmp_ifType_fddi, + snmp_ifType_lapb, + snmp_ifType_sdlc, + snmp_ifType_ds1, /* T-1 */ + snmp_ifType_e1, /* european equiv. of T-1 */ + snmp_ifType_basicISDN, + snmp_ifType_primaryISDN, /* proprietary serial */ + snmp_ifType_propPointToPointSerial, + snmp_ifType_ppp, + snmp_ifType_softwareLoopback, + snmp_ifType_eon, /* CLNP over IP [11] */ + snmp_ifType_ethernet_3Mbit, + snmp_ifType_nsip, /* XNS over IP */ + snmp_ifType_slip, /* generic SLIP */ + snmp_ifType_ultra, /* ULTRA technologies */ + snmp_ifType_ds3, /* T-3 */ + snmp_ifType_sip, /* SMDS */ + snmp_ifType_frame_relay +}; + +/* This macro has a precision of ~49 days because sys_now returns u32_t. \#define your own if you want ~490 days. */ +#ifndef MIB2_COPY_SYSUPTIME_TO +#define MIB2_COPY_SYSUPTIME_TO(ptrToVal) (*(ptrToVal) = (sys_now() / 10)) +#endif + +/* + * @ingroup netif_mib2 + * Increment stats member for SNMP MIB2 stats (struct stats_mib2_netif_ctrs) + */ +#define MIB2_STATS_NETIF_INC(n, x) do { ++(n)->mib2_counters.x; } while (0) +/* + * @ingroup netif_mib2 + * Add value to stats member for SNMP MIB2 stats (struct stats_mib2_netif_ctrs) + */ +#define MIB2_STATS_NETIF_ADD(n, x, val) do { (n)->mib2_counters.x += (val); } while (0) + +/* + * @ingroup netif_mib2 + * Init MIB2 statistic counters in netif + * @param netif Netif to init + * @param type one of enum @ref snmp_ifType + * @param speed your link speed here (units: bits per second) + */ +#define MIB2_INIT_NETIF(netif, type, speed) do { \ + (netif)->link_type = (type); \ + (netif)->link_speed = (speed);\ + (netif)->ts = 0; \ + (netif)->mib2_counters.ifinoctets = 0; \ + (netif)->mib2_counters.ifinucastpkts = 0; \ + (netif)->mib2_counters.ifinnucastpkts = 0; \ + (netif)->mib2_counters.ifindiscards = 0; \ + (netif)->mib2_counters.ifinerrors = 0; \ + (netif)->mib2_counters.ifinunknownprotos = 0; \ + (netif)->mib2_counters.ifoutoctets = 0; \ + (netif)->mib2_counters.ifoutucastpkts = 0; \ + (netif)->mib2_counters.ifoutnucastpkts = 0; \ + (netif)->mib2_counters.ifoutdiscards = 0; \ + (netif)->mib2_counters.ifouterrors = 0; } while (0) +#else /* MIB2_STATS */ +#ifndef MIB2_COPY_SYSUPTIME_TO +#define MIB2_COPY_SYSUPTIME_TO(ptrToVal) +#endif +#define MIB2_INIT_NETIF(netif, type, speed) +#define MIB2_STATS_NETIF_INC(n, x) +#define MIB2_STATS_NETIF_ADD(n, x, val) +#endif /* MIB2_STATS */ + +/* LWIP MIB2 callbacks */ +#if LWIP_MIB2_CALLBACKS /* don't build if not configured for use in lwipopts.h */ +/* network interface */ +void mib2_netif_added(struct netif *ni); +void mib2_netif_removed(struct netif *ni); + +#if LWIP_IPV4 && LWIP_ARP +/* ARP (for atTable and ipNetToMediaTable) */ +void mib2_add_arp_entry(struct netif *ni, ip4_addr_t *ip); +void mib2_remove_arp_entry(struct netif *ni, ip4_addr_t *ip); +#else /* LWIP_IPV4 && LWIP_ARP */ +#define mib2_add_arp_entry(ni, ip) +#define mib2_remove_arp_entry(ni, ip) +#endif /* LWIP_IPV4 && LWIP_ARP */ + +/* IP */ +#if LWIP_IPV4 +void mib2_add_ip4(struct netif *ni); +void mib2_remove_ip4(struct netif *ni); +void mib2_add_route_ip4(u8_t dflt, struct netif *ni); +void mib2_remove_route_ip4(u8_t dflt, struct netif *ni); +#endif /* LWIP_IPV4 */ + +/* UDP */ +#if LWIP_UDP +void mib2_udp_bind(struct udp_pcb *pcb); +void mib2_udp_unbind(struct udp_pcb *pcb); +#endif /* LWIP_UDP */ + +#else /* LWIP_MIB2_CALLBACKS */ +/* LWIP_MIB2_CALLBACKS support not available */ +/* define everything to be empty */ + +/* network interface */ +#define mib2_netif_added(ni) +#define mib2_netif_removed(ni) + +/* ARP */ +#define mib2_add_arp_entry(ni, ip) +#define mib2_remove_arp_entry(ni, ip) + +/* IP */ +#define mib2_add_ip4(ni) +#define mib2_remove_ip4(ni) +#define mib2_add_route_ip4(dflt, ni) +#define mib2_remove_route_ip4(dflt, ni) + +/* UDP */ +#define mib2_udp_bind(pcb) +#define mib2_udp_unbind(pcb) +#endif /* LWIP_MIB2_CALLBACKS */ + +/* for source-code compatibility reasons only, can be removed (not used internally) */ +#define NETIF_INIT_SNMP MIB2_INIT_NETIF +#define snmp_add_ifinoctets(ni, value) MIB2_STATS_NETIF_ADD(ni, ifinoctets, value) +#define snmp_inc_ifinucastpkts(ni) MIB2_STATS_NETIF_INC(ni, ifinucastpkts) +#define snmp_inc_ifinnucastpkts(ni) MIB2_STATS_NETIF_INC(ni, ifinnucastpkts) +#define snmp_inc_ifindiscards(ni) MIB2_STATS_NETIF_INC(ni, ifindiscards) +#define snmp_inc_ifinerrors(ni) MIB2_STATS_NETIF_INC(ni, ifinerrors) +#define snmp_inc_ifinunknownprotos(ni) MIB2_STATS_NETIF_INC(ni, ifinunknownprotos) +#define snmp_add_ifoutoctets(ni, value) MIB2_STATS_NETIF_ADD(ni, ifoutoctets, value) +#define snmp_inc_ifoutucastpkts(ni) MIB2_STATS_NETIF_INC(ni, ifoutucastpkts) +#define snmp_inc_ifoutnucastpkts(ni) MIB2_STATS_NETIF_INC(ni, ifoutnucastpkts) +#define snmp_inc_ifoutdiscards(ni) MIB2_STATS_NETIF_INC(ni, ifoutdiscards) +#define snmp_inc_ifouterrors(ni) MIB2_STATS_NETIF_INC(ni, ifouterrors) + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_HDR_SNMP_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/sntp.h b/sdk_liteos/third_party/lwip_sack/include/lwip/sntp.h new file mode 100644 index 0000000000000000000000000000000000000000..b6a518bfa25cb4551d777997daa079cb9cdbe0f8 --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/sntp.h @@ -0,0 +1,116 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ + +#ifndef __SNTP_H__ +#define __SNTP_H__ + +#include "lwip/sntp_opts.h" +#include "arch/sys_arch.h" +#include "lwip/err.h" +#include "lwip/ip_addr.h" + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif +/* + * SNTP operating modes: default is to poll using unicast. + * The mode has to be set before calling sntp_init(). + */ +#define SNTP_OPMODE_POLL 0 +#define SNTP_OPMODE_LISTENONLY 1 +void sntp_setoperatingmode(u8_t operating_mode); +u8_t sntp_getoperatingmode(void); + +void sntp_init(void *arg); + +u8_t sntp_enabled(void); + +void sntp_setserver(u8_t idx, const ip_addr_t *addr); +const ip_addr_t *sntp_getserver(u8_t idx); + +#if SNTP_SERVER_DNS +void sntp_setservername(u8_t idx, char *server); +char *sntp_getservername(u8_t idx); +#endif /* SNTP_SERVER_DNS */ + +#if SNTP_GET_SERVERS_FROM_DHCP +void sntp_servermode_dhcp(int set_servers_from_dhcp); +#else /* SNTP_GET_SERVERS_FROM_DHCP */ +#define sntp_servermode_dhcp(x) +#endif /* SNTP_GET_SERVERS_FROM_DHCP */ + +/** +* @cond liteos +* @defgroup SNTP_Interfaces +* This section contains the SNTP related interfaces. +*/ +/* +Func Name: lwip_sntp_start +*/ +/** +* @defgroup lwip_sntp_start +* @ingroup SNTP_Interfaces +* +* @brief +* This API is used to start the SNTP module. +* +* @param[in] server_num Total servers in param sntp_server [N/A] +* @param[in] sntp_server Domain name or IP_add of SNTP server in string format [N/A] +* @param[out] time the time of server if lwip_sntp_start return successfully. [N/A] +* +* @par Return values +* ERR_OK: On success\n +* ERR_MEM: On failure, due to memory error\n +* ERR_ARG: On failure, due to incorrect arg\n +* ERR_TIMEOUT: On failure, due to sntp server is not response\n +* ERR_INPROGRESS: On failure, SNTP client is already running.\n + +* +* @par Note +* 1. If input parameter sntp_server passed as NULL or server_num passed as 0 to this API, +* in that case this API will fail with return value ERR_ARG. \n +* 2. This API will block for a few seconds waiting for sntp server reply.\n +* 3. If this API return successfully, and param time is not NULL, +* then 'time' will be the time obtain from sntp server.\n +* 4. This API doesn't support concurrent operation. Calling it before other operation +* done will fail with ERR_INPROGRESS. +* +* @endcond +* +*/ +int lwip_sntp_start(int server_num, char **sntp_server, struct timeval *time); + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* __SNTP_H__ */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/sntp_opts.h b/sdk_liteos/third_party/lwip_sack/include/lwip/sntp_opts.h new file mode 100644 index 0000000000000000000000000000000000000000..7a92453cebfe3ec762bb6581336979f033e75a83 --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/sntp_opts.h @@ -0,0 +1,231 @@ +/** + * @file + * SNTP client options list + */ + +/* + * Copyright (c) 2007-2009 Frédéric Bernon, Simon Goldschmidt + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Frédéric Bernon, Simon Goldschmidt + * + */ +#ifndef LWIP_HDR_APPS_SNTP_OPTS_H +#define LWIP_HDR_APPS_SNTP_OPTS_H + +#include "lwip/opt.h" +#include +/* + * @defgroup sntp_opts Options + * @ingroup sntp + * @{ + */ +/** + * LWIP_SNTP==1: Turn on SNTP module. + */ +#ifndef LWIP_SNTP +#define LWIP_SNTP 1 +#endif + +/** SNTP server port */ +#ifndef SNTP_PORT +#define SNTP_PORT 123 +#endif + +#ifndef SNTP_SERVER_ADDR_SIZE +#define SNTP_SERVER_ADDR_SIZE 255 +#endif + +/** + * Set this to 1 to support DNS names (or IP address strings) to set sntp servers + * One server address/name can be defined as default if SNTP_SERVER_DNS == 1: + * \#define SNTP_SERVER_ADDRESS "pool.ntp.org" + */ +#if LWIP_DNS +#ifndef SNTP_SERVER_DNS +#define SNTP_SERVER_DNS 1 +#endif +#else +#ifndef SNTP_SERVER_DNS +#define SNTP_SERVER_DNS 0 +#endif +#endif /* LWIP_DNS*/ + +/** + * SNTP server address: + * - as IPv4 address in "u32_t" format + * - as a DNS name if SNTP_SERVER_DNS is set to 1 + * May contain multiple server names (For example, "pool.ntp.org","second.time.server") + */ +#ifndef SNTP_SERVER_ADDRESS +#if SNTP_SERVER_DNS +#define SNTP_SERVER_ADDRESS "pool.ntp.org" +#endif +#endif + +/** + * After SNTP send request to server, retry to server will happen SNTP_MAX_REQUEST_RETRANSMIT times + * default is set to 3, retransmission will happen thrice after the original transmission. + */ +#ifndef SNTP_MAX_REQUEST_RETRANSMIT +#define SNTP_MAX_REQUEST_RETRANSMIT 3 +#endif + +/** + * SNTP macro to change system time in seconds + * Define SNTP_SET_SYSTEM_TIME_US(sec, us) to set the time in microseconds instead of this one + * if you need the additional precision. + * SNTP macro to change system time and/or the update the RTC clock + */ +#ifndef SNTP_SET_SYSTEM_TIME +#define SNTP_SET_SYSTEM_TIME(sec) (void)stime(&sec) +#endif + +/** SNTP macro to change system time including microseconds */ +#ifdef SNTP_SET_SYSTEM_TIME_US +#define SNTP_CALC_TIME_US 1 +#define SNTP_RECEIVE_TIME_SIZE 2 +#else +#define SNTP_SET_SYSTEM_TIME_US(sec, us) +#define SNTP_CALC_TIME_US 0 +#define SNTP_RECEIVE_TIME_SIZE 1 +#endif + +/** The maximum number of SNTP servers that can be set */ +#if !defined SNTP_MAX_SERVERS || defined __DOXYGEN__ +#define SNTP_MAX_SERVERS LWIP_DHCP_MAX_NTP_SERVERS +#endif + +/** + * Set this to 1 to implement the callback function called by dhcp when + * NTP servers are received. + */ +#if !defined SNTP_GET_SERVERS_FROM_DHCP || defined __DOXYGEN__ +#define SNTP_GET_SERVERS_FROM_DHCP LWIP_DHCP_GET_NTP_SRV +#endif + +/** + * SNTP_DEBUG: Enable debugging for SNTP. + */ +#if !defined SNTP_DEBUG || defined __DOXYGEN__ +#define SNTP_DEBUG LWIP_DBG_OFF +#endif + +/** SNTP server port */ +#if !defined SNTP_PORT || defined __DOXYGEN__ +#define SNTP_PORT 123 +#endif + +/** + * Sanity check: + * Define this to + * - 0 to turn off sanity checks (default; smaller code) + * - >= 1 to check address and port of the response packet to ensure the + * response comes from the server we sent the request to. + * - >= 2 to check returned Originate Timestamp against Transmit Timestamp + * sent to the server (to ensure response to older request). + * - >= 3 @todo: discard reply if any of the LI, Stratum, or Transmit Timestamp + * fields is 0 or the Mode field is not 4 (unicast) or 5 (broadcast). + * - >= 4 @todo: to check that the Root Delay and Root Dispersion fields are each + * greater than or equal to 0 and less than infinity, where infinity is + * currently a cozy number like one second. This check avoids using a + * server whose synchronization source has expired for a very long time. + */ +#if !defined SNTP_CHECK_RESPONSE || defined __DOXYGEN__ +#define SNTP_CHECK_RESPONSE 2 +#endif + +/** + * According to the RFC, this shall be a random delay + * between 1 and 5 minutes (in milliseconds) to prevent load peaks. + * This can be defined to a random generation function, + * which must return the delay in milliseconds as u32_t. + * Turned off by default. + */ +#if !defined SNTP_STARTUP_DELAY || defined __DOXYGEN__ +#define SNTP_STARTUP_DELAY 0 +#endif + +/** + * If you want the startup delay to be a function, define this + * to a function (including the brackets) and define SNTP_STARTUP_DELAY to 1. + */ +#if !defined SNTP_STARTUP_DELAY_FUNC || defined __DOXYGEN__ +#define SNTP_STARTUP_DELAY_FUNC SNTP_STARTUP_DELAY +#endif + +/** + * SNTP receive timeout - in milliseconds + * Also used as retry timeout - this shouldn't be too low. + * Default is 3 seconds. + */ +#if !defined SNTP_RECV_TIMEOUT || defined __DOXYGEN__ +#define SNTP_RECV_TIMEOUT 3000 +#endif + +/** + * SNTP update delay - in milliseconds + * Default is 1 hour. Must not be beolw 15 seconds by specification (i.e. 15000) + */ +#if !defined SNTP_UPDATE_DELAY || defined __DOXYGEN__ +#define SNTP_UPDATE_DELAY 3600000 +#endif + +/** + * SNTP macro to get system time, used with SNTP_CHECK_RESPONSE >= 2 + * to send in request and compare in response. + */ +#if !defined SNTP_GET_SYSTEM_TIME || defined __DOXYGEN__ +#define SNTP_GET_SYSTEM_TIME(sec, us) do { (sec) = 0; (us) = 0; } while (0) +#endif + +/** + * Default retry timeout (in milliseconds) if the response + * received is invalid. + * This is doubled with each retry until SNTP_RETRY_TIMEOUT_MAX is reached. + */ +#if !defined SNTP_RETRY_TIMEOUT || defined __DOXYGEN__ +#define SNTP_RETRY_TIMEOUT SNTP_RECV_TIMEOUT +#endif + +/** Maximum retry timeout (in milliseconds). */ +#if !defined SNTP_RETRY_TIMEOUT_MAX || defined __DOXYGEN__ +#define SNTP_RETRY_TIMEOUT_MAX (SNTP_RETRY_TIMEOUT * 10) +#endif + +/** + * Increase retry timeout with every retry sent + * Default is on to conform to RFC. + */ +#if !defined SNTP_RETRY_TIMEOUT_EXP || defined __DOXYGEN__ +#define SNTP_RETRY_TIMEOUT_EXP 1 +#endif + +/* + * @} + */ +#endif /* LWIP_HDR_APPS_SNTP_OPTS_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/sockets.h b/sdk_liteos/third_party/lwip_sack/include/lwip/sockets.h new file mode 100644 index 0000000000000000000000000000000000000000..b6078267a9037364f1ac1082cb749ab8274865e9 --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/sockets.h @@ -0,0 +1,2584 @@ +/** + * @file + * Socket API (to be used from non-TCPIP threads) + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * Copyright (c) <2013-2016>, + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +/** @mainpage RFC Compliance + * The following pages provide information about RFC Compliance. + * - Click the RFC number for more information about limitations or RFC implementation. + * - @subpage RFC-2292 + * - @subpage RFC-2460 + * - @subpage RFC-2553 + * - @subpage RFC-2553_RFC-3493 + * - @subpage RFC-2710 + * - @subpage RFC-3493 + * - @subpage RFC-4213 + * - @subpage RFC-4291 + * - @subpage RFC-4443 + * - @subpage RFC-4861 + * - @subpage RFC-4862 + * - @subpage RFC-5827 + * - @subpage RFC-6052 + * - @subpage RFC-6724 + * - @subpage RFC-8028 + */ +#ifndef LWIP_HDR_SOCKETS_H +#define LWIP_HDR_SOCKETS_H + +#include "lwip/opt.h" + +#if LWIP_SOCKET /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/ip_addr.h" +#include "lwip/err.h" +#include "lwip/inet.h" +#include "lwip/errno.h" + +#if LWIP_LITEOS_COMPAT +#include +#include +#endif +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +#if !LWIP_LITEOS_COMPAT +/** + * @defgroup User_interfaces User Interfaces + * This contains all the user interfaces. + */ +/** + * @defgroup Socket_Interfaces Socket Interfaces + * @ingroup User_interfaces + * This file contains socket interfaces. + */ +/* If your port already typedef's sa_family_t, define SA_FAMILY_T_DEFINED + to prevent this code from redefining it. */ +#if !defined(sa_family_t) && !defined(SA_FAMILY_T_DEFINED) +typedef u16_t sa_family_t; +#endif +/* If your port already typedef's in_port_t, define IN_PORT_T_DEFINED + to prevent this code from redefining it. */ +#if !defined(in_port_t) && !defined(IN_PORT_T_DEFINED) +typedef u16_t in_port_t; +#endif + +#if LWIP_IPV4 +#ifndef SIN_ZERO_LEN +#define SIN_ZERO_LEN 8 +#endif + +/** @brief Defines the socket address. */ +struct sockaddr_in { + u8_t sin_len; /**< Specifies the socket length. */ + sa_family_t sin_family; /**< Specifies the socket family. */ + in_port_t sin_port; /**< Specifies the port. */ + struct in_addr sin_addr; /**< Specifies the address. */ + char sin_zero[SIN_ZERO_LEN]; /**< Indicates an 6-bit padding. */ +}; +#endif /* LWIP_IPV4 */ + +#if LWIP_IPV6 +/* @brief Defines the socket address. */ +/** + * @page RFC-2553_RFC-3493 RFC-2553/3493 + * @par Compliant Sections + * Section 3.4 Socket Address Structure for 4.4 BSD-Based Systems + * @par Behavior Description + * Systems that provide this version of the sockaddr_in6 data structure must also declare SIN6_LEN + * as a result of including the header. This macro allows applications to determine + * whether they are being built on a system that supports the 4.3BSD or 4.4BSD variants of the data structure. \n + * Behavior: Macro SIN6_LEN for applications to determine which version of sockaddr_in6 stack supports.\n + * If SIN6_LEN is defined the version of sockaddr_in6 is 4.4 BSD compliant. + */ +/* + * RFC 2553/3493 + * Systems that provide this version of the sockaddr_in6(4.4 BSD) data structure must also + * declare SIN6_LEN . This macro allows applications to determine whether they are being built + * on a system that supports the 4.3BSD or 4.4BSD variants of the data structure. + */ +#define SIN6_LEN + +struct sockaddr_in6 { + u8_t sin6_len; /*< Specifies the length of the structure. */ + sa_family_t sin6_family; /*< Specifies the socket family. */ + in_port_t sin6_port; /*< Specifies the transport layer port number. */ + u32_t sin6_flowinfo; /*< Specifies the IPv6 flow information. */ + struct in6_addr sin6_addr; /*< Specifies the IPv6 address. */ + u32_t sin6_scope_id; /*< Specifies the set of interfaces for scope */ +}; + +#define IN6_IS_ADDR_MULTICAST(a) (((__const u8_t *) (a))[0] == 0xff) + +#endif /* LWIP_IPV6 */ +/** + * @brief Indicates socket address. + */ +struct sockaddr { + u8_t sa_len; /**< Specifies the length of the structure. */ + sa_family_t sa_family; /**< Specifies the socket family. */ + char sa_data[14]; /**< Specifies the address. */ +}; + +#if PF_PKT_SUPPORT + +/** + * @note + * You must enable PF_PKT_SUPPORT to use the sockaddr_ll data structure. \n + */ +struct sockaddr_ll { + u16_t sll_family; /**< Specifies the socket family. Always AF_PACKET */ + u16_t sll_protocol; /**< Specifies the Ethernet protocol. Physical layer protocol. */ + int sll_ifindex; /**< Specifies the network interface index. Starts from 1. */ + u16_t sll_hatype; /**< Specifies the hat type. */ + u8_t sll_pkttype; /**< Specifies the packet type.*/ + u8_t sll_halen; /**< Specifies the physical layer address length. */ + u8_t sll_addr[8]; /**< Specifies the physical layer address. */ +}; +#endif /* PF_PKT_SUPPORT*/ + +struct sockaddr_storage { + u8_t s2_len; + sa_family_t ss_family; + char s2_data1[2]; + u32_t s2_data2[3]; +#if LWIP_IPV6 + u32_t s2_data3[3]; +#endif /* LWIP_IPV6 */ +}; + +/* If your port already typedef's socklen_t, define SOCKLEN_T_DEFINED + to prevent this code from redefining it. */ +#if !defined(socklen_t) && !defined(SOCKLEN_T_DEFINED) +typedef u32_t socklen_t; +#endif + +struct lwip_sock; + +#if !defined(iovec) +struct iovec { + void *iov_base; + size_t iov_len; +}; +#endif + +struct msghdr { + void *msg_name; + socklen_t msg_namelen; + struct iovec *msg_iov; + size_t msg_iovlen; + void *msg_control; + socklen_t msg_controllen; + int msg_flags; +}; + +/** Socket protocol types (TCP/UDP/RAW) */ +#define SOCK_STREAM 1 +#define SOCK_DGRAM 2 +#define SOCK_RAW 3 +#define SOCK_MAX (SOCK_RAW + 1) + +#define SOCK_TYPE_MASK 0xf + +/* + * Option flags per-socket. These must match the SOF_ flags in ip.h (checked in init.c) + */ +#define SO_REUSEADDR 0x0004 /* Allow local address reuse */ +#define SO_KEEPALIVE 0x0008 /* keep connections alive */ +#define SO_BROADCAST 0x0020 /* permit to send and to receive broadcast messages (see IP_SOF_BROADCAST option) */ + +/* + * Additional options, not kept in so_options. + */ +#define SO_DEBUG 0x0001 /* Unimplemented: turn on debugging info recording */ +/** Socket has had listen() */ +#define SO_ACCEPTCONN 0x0002 + +#define SO_DONTROUTE 0x0010 + +#ifndef SO_BINDTODEVICE +#define SO_BINDTODEVICE 25 +#endif + +#ifndef SO_ATTACH_FILTER +#define SO_ATTACH_FILTER 26 +#endif + +#ifndef SO_DETACH_FILTER +#define SO_DETACH_FILTER 27 +#endif + +#define SO_USELOOPBACK 0x0040 /* Unimplemented: bypass hardware when possible */ +/** Linger on close, if data is present. */ +#define SO_LINGER 0x0080 /* linger on close if data present */ +#define SO_DONTLINGER ((int)(~SO_LINGER)) + +#define SO_OOBINLINE 0x0100 /* Unimplemented: Leave received OOB data in line */ + +#define SO_REUSEPORT 0x0200 /* Unimplemented: allow local address & port reuse */ +#define SO_SNDBUF 0x1001 /* Unimplemented: send buffer size */ +#define SO_RCVBUF 0x1002 /* receive buffer size */ +#define SO_SNDLOWAT 0x1003 /* Unimplemented: send low-water mark */ +#define SO_RCVLOWAT 0x1004 /* Unimplemented: receive low-water mark */ +/** Indicates the Send timeout. */ +#define SO_SNDTIMEO 0x1005 +/** Indicates the receive timeout. */ +#define SO_RCVTIMEO 0x1006 +/** Gets the error status and clear. */ +#define SO_ERROR 0x1007 +/** Get the socket type */ +#define SO_TYPE 0x1008 + +#define SO_CONTIMEO 0x1009 +/** Do not create UDP checksum. */ +#define SO_NO_CHECK 0x100a + +#define SO_PRIORITY 0x100b + +/** + * Structure used for manipulating linger option. + */ +struct linger { + int l_onoff; /**< Indicates whether the linger option is on/off. */ + int l_linger; /**< Indicates the linger time in seconds. */ +}; + +/* + * Level number for (get/set)sockopt() to apply to socket itself. + */ +#define SOL_SOCKET 1 /* options for socket level */ + +#define AF_UNSPEC 0 +#define AF_INET 2 +#if LWIP_IPV6 +#define AF_INET6 10 +#else /* LWIP_IPV6 */ +#define AF_INET6 AF_UNSPEC +#endif /* LWIP_IPV6 */ +#define PF_INET AF_INET +#define PF_INET6 AF_INET6 +#define PF_UNSPEC AF_UNSPEC + +#if PF_PKT_SUPPORT +/** Packet family. */ +#define PF_PACKET 17 +/** Pakcet family socket level */ +#define SOL_PACKET 263 +#endif + +#define IPPROTO_IP 0 +#define IPPROTO_ICMP 1 +#define IPPROTO_TCP 6 +#define IPPROTO_UDP 17 +#if LWIP_IPV6 +#define IPPROTO_IPV6 41 +#define IPPROTO_ICMPV6 58 +#endif /* LWIP_IPV6 */ +#define IPPROTO_UDPLITE 136 +#define IPPROTO_RAW 255 + +/* Flags we can use with send and recv. */ +/** Peeks at an incoming message */ +#define MSG_PEEK 0x01 +/* Unimplemented: Requests that the function block until the full amount of data requested can be returned */ +#define MSG_WAITALL 0x02 +/* Unimplemented: Requests out-of-band data. The significance and semantics of out-of-band data are protocol-specific */ +#define MSG_OOB 0x04 +/** Nonblocking I/O for this operation only */ +#define MSG_DONTWAIT 0x08 +/** Sender will send more messages. */ +#define MSG_MORE 0x10 + +/* Do not generate SIGPIPE */ +#define MSG_NOSIGNAL 0x4000 + +/* + * Options for level IPPROTO_IP + */ +#define IP_TOS 1 +#define IP_TTL 2 +#define IP_PKTINFO 8 + +#if LWIP_TCP +/* + * Options for level IPPROTO_TCP + */ +#define TCP_NODELAY 0x01 /* don't delay send to coalesce packets */ +/** Send KEEPALIVE Signals when idle for pcb->keep_idle milliseconds */ +#define TCP_KEEPALIVE 0x02 +/** Set pcb->keep_idle - Same as TCP_KEEPALIVE, but use seconds for get/setsockopt */ +#define TCP_KEEPIDLE 0x03 +/** Set pcb->keep_intvl - Use seconds for get/setsockopt */ +#define TCP_KEEPINTVL 0x04 +/** Set pcb->keep_cnt - Use number of Signals sent for get/setsockopt */ +#define TCP_KEEPCNT 0x05 +/** Set sequence number of repaired queue. */ +#define TCP_QUEUE_SEQ 0x15 +/* [VPPTECH-449] TCP_INFO support */ +/* + * User-gettable options (used with getsockopt). + */ +#ifndef TCP_INFO +/** Information about this connection. */ +#define TCP_INFO 11 +#endif +/* [VPPTECH-449] TCP_INFO support */ +#endif /* LWIP_TCP */ + +#if LWIP_IPV6 +/* + * Options for level IPPROTO_IPV6 + */ +#define IPV6_CHECKSUM 7 /* RFC3542: calculate and insert the ICMPv6 checksum for raw sockets. */ +#define IPV6_V6ONLY 27 /* RFC3493: boolean control to restrict AF_INET6 sockets to IPv6 communications only. */ + +/* + * RFC 2553/3493 : To set/get the unicast hop limit for outgoing unicast packets + * As of now stack support only get options + */ +#define IPV6_UNICAST_HOPS 16 + +#if LWIP_MULTICAST_TX_OPTIONS +/* + * RFC 2553/3493 : To Set/get the hop limit to use for outgoing multicast packets + * As of now stack support only get options, also not supported for RAW as of now + */ +#define IPV6_MULTICAST_HOPS 18 + +#endif /* LWIP_MULTICAST_TX_OPTIONS */ +#define IPV6_RECVPKTINFO 49 +#define IPV6_PKTINFO 50 +#endif /* LWIP_IPV6 */ + +#if LWIP_TCP +#define TCP_KEEPALIVE 0x02 /* send KEEPALIVE probes when idle for pcb->keep_idle milliseconds */ + +/** @brief Indicates socket repair options. */ +enum { + TCP_NO_QUEUE, /**< Indicates no queue. */ + TCP_RECV_QUEUE, /**< Indicates the receive queue. */ + TCP_SEND_QUEUE, /**< Indicates the send queue. */ + TCP_QUEUES_NR, /**< Indicates Queue NR. */ +}; +#endif /* LWIP_TCP */ + +#if LWIP_UDP && LWIP_UDPLITE +/* + * Options for level IPPROTO_UDPLITE + */ +/** Indicates sender checksum coverage. */ +#define UDPLITE_SEND_CSCOV 0x01 +/** Indicates minimal receiver checksum coverage. */ +#define UDPLITE_RECV_CSCOV 0x02 +#endif /* LWIP_UDP && LWIP_UDPLITE */ + +#if LWIP_MULTICAST_TX_OPTIONS +/** + * Options and types for UDP multicast traffic handling + */ +#define IP_MULTICAST_TTL 5 +#define IP_MULTICAST_IF 6 +#define IP_MULTICAST_LOOP 7 +#endif /* LWIP_MULTICAST_TX_OPTIONS */ + +#if !LWIP_LITEOS_COMPAT +#if LWIP_IGMP +/* + * Options and types related to multicast membership + */ +#ifndef IP_ADD_MEMBERSHIP +#define IP_ADD_MEMBERSHIP 35 +#endif /* IP_ADD_MEMBERSHIP */ + +#ifndef IP_DROP_MEMBERSHIP +#define IP_DROP_MEMBERSHIP 36 +#endif /* IP_DROP_MEMBERSHIP */ +typedef struct ip_mreq { + struct in_addr imr_multiaddr; /**< Indicates the IP multicast address of the group. */ + struct in_addr imr_interface; /**< Indicates the local IP address of the interface. */ +} ip_mreq; +#endif /* LWIP_IGMP */ +#if LWIP_IPV6 && LWIP_IPV6_MLD +/* + * Options and types related to IPv6 multicast membership + */ +#define IPV6_JOIN_GROUP 20 +#define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP +#define IPV6_LEAVE_GROUP 21 +#define IPV6_DROP_MEMBERSHIP IPV6_LEAVE_GROUP + +typedef struct ipv6_mreq { + struct in6_addr ipv6mr_multiaddr; /* IPv6 multicast addr */ + unsigned int ipv6mr_interface; /* interface index, or 0 */ +} ipv6_mreq; +#endif /* LWIP_IPV6 && LWIP_IPV6_MLD */ +#if !LWIP_LITEOS_COMPAT +#if LWIP_IPV6 +struct in6_ifreq { + struct in6_addr ifr6_addr; + u32_t ifr6_prefixlen; + s32_t ifr6_ifindex; +}; +#endif /* LWIP_IPV6 */ +#endif /* !LWIP_LITEOS_COMPAT */ +#if LWIP_RAW +#ifndef IP_HDRINCL +#define IP_HDRINCL 0x3 /* int; Header is included with data. */ +#endif /* IP_HDRINCL */ +#endif /* LWIP_RAW */ +#endif /* !LWIP_LITEOS_COMPAT */ + +#if LWIP_IPV4 +struct in_pktinfo { + unsigned int ipi_ifindex; /* Interface index */ + struct in_addr ipi_addr; /* Destination (from header) address */ +}; +#endif /* LWIP_IPV4 */ + +/** + * The Type of Service provides an indication of the abstract + * parameters of the quality of service desired. These parameters are + * to be used to guide the selection of the actual service parameters + * when transmitting a datagram through a particular network. Several + * networks offer service precedence, which somehow treats high + * precedence traffic as more important than other traffic (generally + * by accepting only traffic above a certain precedence at time of high + * load). The major choice is a three way tradeoff between low-delay, + * high-reliability, and high-throughput. + * The use of the Delay, Throughput, and Reliability indications may + * increase the cost (in some sense) of the service. In many networks + * better performance for one of these parameters is coupled with worse + * performance on another. Except for very unusual cases at most two + * of these three indications should be set. + */ +#define IPTOS_TOS_MASK 0x1E +/** Refer to IPTOS_TOS_MASK description. */ +#define IPTOS_TOS(tos) ((tos) & IPTOS_TOS_MASK) +/** Refer to IPTOS_TOS_MASK description. */ +#define IPTOS_LOWDELAY 0x10 +/** Refer to IPTOS_TOS_MASK description. */ +#define IPTOS_THROUGHPUT 0x08 +/** Refer to IPTOS_TOS_MASK description. */ +#define IPTOS_RELIABILITY 0x04 +/** Refer to IPTOS_TOS_MASK description. */ +#define IPTOS_LOWCOST 0x02 +/** Refer to IPTOS_TOS_MASK description. */ +#define IPTOS_MINCOST IPTOS_LOWCOST + +/** + * The Network Control precedence designation is intended to be used + * within a network only. The actual use and control of that + * designation is up to each network. The Internetwork Control + * designation is intended for use by gateway control originators only. + * If the actual use of these precedence designations is of concern to + * a particular network, it is the responsibility of that network to + * control the access to, and use of, those precedence designations. + */ +#define IPTOS_PREC_MASK 0xe0 +/** Refer to IPTOS_PREC_MASK description. */ +#define IPTOS_PREC(tos) ((tos) & IPTOS_PREC_MASK) +/** Refer to IPTOS_PREC_MASK description. */ +#define IPTOS_PREC_NETCONTROL 0xe0 +/** Refer to IPTOS_PREC_MASK description. */ +#define IPTOS_PREC_INTERNETCONTROL 0xc0 +/** Refer to IPTOS_PREC_MASK description. */ +#define IPTOS_PREC_CRITIC_ECP 0xa0 +/** Refer to IPTOS_PREC_MASK description. */ +#define IPTOS_PREC_FLASHOVERRIDE 0x80 +/** Refer to IPTOS_PREC_MASK description. */ +#define IPTOS_PREC_FLASH 0x60 +/** Refer to IPTOS_PREC_MASK description. */ +#define IPTOS_PREC_IMMEDIATE 0x40 +/** Refer to IPTOS_PREC_MASK description. */ +#define IPTOS_PREC_PRIORITY 0x20 +/** Refer to IPTOS_PREC_MASK description. */ +#define IPTOS_PREC_ROUTINE 0x00 + +/* + * Commands for ioctlsocket(), taken from the BSD file fcntl.h. + * lwip_ioctl only supports FIONREAD and FIONBIO, for now + * + * Ioctl's have the command encoded in the lower word, + * and the size of any in or out parameters in the upper + * word. The high 2 bits of the upper word are used + * to encode the in/out status of the parameter; for now + * we restrict parameters to at most 128 bytes. + */ +#if !defined(FIONREAD) || !defined(FIONBIO) +#ifndef IOCPARM_MASK +#define IOCPARM_MASK 0x7fU /* parameters must be < 128 bytes */ +#endif +#ifndef IOC_VOID +#define IOC_VOID 0x20000000UL /* no parameters */ +#endif +#ifndef IOC_OUT +#define IOC_OUT 0x40000000UL /* copy out parameters */ +#endif +#ifndef IOC_IN +#define IOC_IN 0x80000000UL /* copy in parameters */ +#endif +#ifndef IOC_INOUT +#define IOC_INOUT (IOC_IN | IOC_OUT) +#endif +/* 0x20000000 distinguishes new & + old ioctl's */ +#ifndef _IO +#define _IO(x, y) (IOC_VOID | ((x) << 8) | (y)) +#endif +#ifndef _IOR +#define _IOR(x, y, t) (IOC_OUT | ((sizeof(t) & IOCPARM_MASK) << 16) | ((x) << 8) | (y)) +#endif +#ifndef _IOW +#define _IOW(x, y, t) (IOC_IN | ((sizeof(t) & IOCPARM_MASK) << 16) | ((x) << 8) | (y)) +#endif +#ifndef _IOWR +#define _IOWR(x, y, t) (IOC_INOUT | ((sizeof(t) & IOCPARM_MASK) << 16) | ((x) << 8) | (y)) +#endif +#endif /* !defined(FIONREAD) || !defined(FIONBIO) */ + +#ifndef FIONREAD +#define FIONREAD _IOR('f', 127, unsigned long) /* get # bytes to read */ +#endif +#ifndef FIONBIO +#define FIONBIO _IOW('f', 126, unsigned long) /* set/clear non-blocking i/o */ +#endif + +/* Socket I/O Controls: unimplemented */ +#ifndef SIOCSHIWAT +#define SIOCSHIWAT _IOW('s', 0, unsigned long) /* set high watermark */ +#define SIOCGHIWAT _IOR('s', 1, unsigned long) /* get high watermark */ +#define SIOCSLOWAT _IOW('s', 2, unsigned long) /* set low watermark */ +#define SIOCGLOWAT _IOR('s', 3, unsigned long) /* get low watermark */ +#define SIOCATMARK _IOR('s', 7, unsigned long) /* at oob mark? */ +#endif +/** + * @page RFC-4862 RFC-4862 + * @par RFC-4862 Compliance Information + * @par Compliant Sections + * Section 5.5.4. Address Lifetime Expiry + * @par Behavior Description + * Test: System management MUST have the ability to disable preferred_lifetime facility, + * and the facility MUST be disabled by default. + */ +/* commands for fnctl */ +#ifndef F_GETFL +#define F_GETFL 3 +#endif +#ifndef F_SETFL +#define F_SETFL 4 +#endif + +/* File status flags and file access modes for fnctl, + these are bits in an int. */ +#ifndef O_NONBLOCK +#define O_NONBLOCK 4U /* nonblocking I/O */ +#endif +#ifndef O_NDELAY +#define O_NDELAY O_NONBLOCK /* same as O_NONBLOCK, for compatibility */ +#endif + +#ifndef SHUT_RD +#define SHUT_RD 0 +#define SHUT_WR 1 +#define SHUT_RDWR 2 +#endif + +/* FD_SET used for lwip_select */ +#ifndef FD_SET +#undef FD_SETSIZE +/* Make FD_SETSIZE match NUM_SOCKETS in socket.c */ +#define FD_SETSIZE MEMP_NUM_NETCONN +#define FDSETSAFESET(n, code) do { \ + if (((n) - LWIP_SOCKET_OFFSET < MEMP_NUM_NETCONN) && (((int)(n) - LWIP_SOCKET_OFFSET) >= 0)) { \ + code; } } while (0) +#define FDSETSAFEGET(n, code) (((n) - LWIP_SOCKET_OFFSET < MEMP_NUM_NETCONN) && (((int)(n) - LWIP_SOCKET_OFFSET) >= 0) ?\ + (code) : 0) +#define FD_SET(n, p) \ + FDSETSAFESET(n, (p)->fd_bits[((u32_t)((n) - LWIP_SOCKET_OFFSET)) / 8] |= (1 << (((n)-LWIP_SOCKET_OFFSET) & 7))) +#define FD_CLR(n, p) \ + FDSETSAFESET(n, (p)->fd_bits[((u32_t)((n) - LWIP_SOCKET_OFFSET)) / 8] &= ~(1 << (((n)-LWIP_SOCKET_OFFSET) & 7))) +#define FD_ISSET(n, p) \ + FDSETSAFEGET(n, (p)->fd_bits[((u32_t)((n) - LWIP_SOCKET_OFFSET)) / 8] & (1 << (((n)-LWIP_SOCKET_OFFSET) & 7))) +#define FD_ZERO(p) memset((void*)(p), 0, sizeof(*(p))) + +typedef struct fd_set { + unsigned char fd_bits [(FD_SETSIZE + 7) / 8]; +} fd_set; + +#elif LWIP_SOCKET_OFFSET +#error LWIP_SOCKET_OFFSET does not work with external FD_SET! +#elif FD_SETSIZE < MEMP_NUM_NETCONN +#error "external FD_SETSIZE too small for number of sockets" +#endif /* FD_SET */ + +/** LWIP_TIMEVAL_PRIVATE: If you want to use the struct timeval provided + * by your system, set this to 0 and include in cc.h */ +#ifndef LWIP_TIMEVAL_PRIVATE +#define LWIP_TIMEVAL_PRIVATE 1 +#endif + +#if LWIP_TIMEVAL_PRIVATE +struct timeval { + long tv_sec; /* seconds */ + long tv_usec; /* and microseconds */ +}; +#endif /* LWIP_TIMEVAL_PRIVATE */ + +#define lwip_socket_init() /* Compatibility define, no init needed. */ +#endif +#if LWIP_NETCONN_SEM_PER_THREAD +void lwip_socket_thread_init(void); /* LWIP_NETCONN_SEM_PER_THREAD==1: initialize thread-local semaphore */ +void lwip_socket_thread_cleanup(void); /* LWIP_NETCONN_SEM_PER_THREAD==1: destroy thread-local semaphore */ +#endif + +#if LWIP_IPV6 +/** + * @ingroup Duplicate_Address_Detection_IOCTL + * @brief + * This is a IOCTL to turn on/off Duplicate Address Detection at run time. + * IOCTL cmd: SIOCSIPV6DAD. + * + * @param[in] s Indicates socket index, but not used. + * @param[in] cmd Indicates IOCTL unique command. + * @param[in] argp Indicates void pointer to struct ifreq. + * Valid struct ifreq must have valid ifrn_name + * (interface name.) and ifru_ivalue 0 or 1,\n + * 0 indicates turnoff.\n + * 1 indicates turnon. + * + * @returns + * 0 : On success. \n + * Negative Value : On failure. + */ +#ifndef SIOCSIPV6DAD +#define SIOCSIPV6DAD _IOW('z', 0, unsigned long) /* set DAD enable/disable on netif */ +#endif + +/** + * @ingroup Duplicate_Address_Detection_IOCTL + * @brief + * This is a IOCTL to get status of Duplicate Address Detection. + * IOCTL cmd: SIOCGIPV6DAD. + * + * + * @param[in] s Indicates socket index, but not used. + * @param[in] cmd Indicates IOCTL unique command. + * @param[out] argp Indicates void pointer to struct ifreq. + * Valid struct ifreq must have valid ifrn_name + * (interface name.). \n + * User can read value of ifru_ivalue in struct + * ifreq. + * 0 indicates turnoff.\n + * 1 indicates turnon. + * + * @returns + * 0 : On sucess. \n + * Negative Value : On failure. + */ +#ifndef SIOCGIPV6DAD +#define SIOCGIPV6DAD _IOR('z', 1, unsigned long) /* get DAD status on netif */ +#endif + +/* set DEPRECATION enable/disable on netif */ +/** + + * @brief + * + * This is a IOCTL to turn on/off Preferred and Deprecation state facility for + * address at run time. + * IOCTL cmd: SIOCSIPV6DPCTD. + * + * @param[in] s Indicates socket index, but not used. + * @param[in] cmd Indicates IOCTL unique command. + * @param[in] argp Indicates void pointer to struct ifreq. + * Valid struct ifreq must have valid ifrn_name + * (interface name.) and ifru_ivalue 0 or 1,\n + * 0 indicates turnoff.\n + * 1 indicates turnon. + * + * @returns + * 0 : On sucess. \n + * Negative Value : On failure. + */ +#ifndef SIOCSIPV6DPCTD +#define SIOCSIPV6DPCTD _IOW('z', 2, unsigned long) +#endif + +/* get DEPRECATION status on netif */ +/** + + * @brief + * This is a IOCTL to get status of Duplicate Address Detection. + * IOCTL cmd: SIOCGIPV6DPCTD. + * + * + * @param[in] s Indicates socket index, but not used. + * @param[in] cmd Indicates IOCTL unique command. + * @param[out] argp Indicates void pointer to struct ifreq. + * Valid struct ifreq must have valid ifrn_name + * (interface name.). \n + * User can read value of ifru_ivalue in struct + * ifreq. + * 0 indicates turnoff.\n + * 1 indicates turnon. + * + * @returns + * 0 : On sucess. \n + * Negative Value : On failure. + */ +#ifndef SIOCGIPV6DPCTD +#define SIOCGIPV6DPCTD _IOR('z', 3, unsigned long) +#endif + +#endif + +#if LWIP_MAC_SECURITY +#define IP_MACSEC 128 +#endif + +#if LWIP_LITEOS_COMPAT + +#ifndef TCP_KEEPALIVE +#define TCP_KEEPALIVE 0x02 /* send KEEPALIVE probes when idle for pcb->keep_idle milliseconds */ +#endif +#ifndef SIN_ZERO_LEN +#define SIN_ZERO_LEN 8 +#endif + +#ifndef SOCK_MAX +#define SOCK_MAX (SOCK_RAW + 1) +#endif + +#ifndef SOCK_TYPE_MASK +#define SOCK_TYPE_MASK 0xf +#endif +#endif + +#if LWIP_IPV6 +#define LWIP_IS_IPPROTOCOL(protocol) ((protocol) == IPPROTO_IP || (protocol) == IPPROTO_IPV6 || (protocol) == 0) +#if PF_PACKET +#define LWIP_IS_VALID_DOMAIN(domain) (((domain) == AF_INET) || ((domain) == AF_INET6) || ((domain) == PF_PACKET)) +#else +#define LWIP_IS_VALID_DOMAIN(domain) ((domain) == AF_INET) || ((domain) == AF_INET6) +#endif +#else +#define LWIP_IS_IPPROTOCOL(protocol) ((protocol) == IPPROTO_IP || (protocol) == 0) +#if PF_PACKET +#define LWIP_IS_VALID_DOMAIN(domain) (((domain) == AF_INET) || ((domain) == PF_PACKET)) +#else +#define LWIP_IS_VALID_DOMAIN(domain) ((domain) == AF_INET) +#endif +#endif + +#if LWIP_COMPAT_SOCKETS == 2 +/* This helps code parsers/code completion by not having the COMPAT functions as defines */ +#define lwip_accept accept +#define lwip_bind bind +#define lwip_shutdown shutdown +#define lwip_close closesocket +#define lwip_connect connect +#define lwip_getsockname getsockname +#define lwip_getpeername getpeername +#define lwip_setsockopt setsockopt +#define lwip_getsockopt getsockopt + +#define lwip_listen listen +#define lwip_recv recv +#define lwip_recvfrom recvfrom +#define lwip_send send +#define lwip_sendmsg sendmsg +#define lwip_sendto sendto +#define lwip_socket socket +#if LWIP_SOCKET_SELECT +#define lwip_select select +#endif +#define lwip_ioctlsocket ioctl +#define lwip_inet_ntop inet_ntop +#define lwip_inet_pton inet_pton +#ifdef LWIP_FCNTL +#define lwip_fcntl fcntl +#endif + +#if LWIP_GETHOSTBYNAME +#define lwip_gethostbyname(name) gethostbyname(name) +#endif + +#if !LWIP_LITEOS_COMPAT +#define lwip_if_indextoname if_indextoname +#define lwip_if_nametoindex if_nametoindex +#define lwip_if_freenameindex if_freenameindex +#define lwip_if_nameindex if_nameindex +#endif + +#if LWIP_DNS + +#define lwip_gethostbyname(name) gethostbyname(name) +#define lwip_gethostbyname_r gethostbyname_r +#define lwip_freeaddrinfo freeaddrinfo +#define lwip_getaddrinfo getaddrinfo +#define lwip_getnameinfo getnameinfo +#endif + +#if LWIP_POSIX_SOCKETS_IO_NAMES +#define lwip_read read +#define lwip_write write +#define lwip_writev writev +#undef lwip_close +#define lwip_close close +#define closesocket(s) close(s) +#define lwip_fcntl fcntl +#define lwip_ioctl ioctl +#endif /* LWIP_POSIX_SOCKETS_IO_NAMES */ +#endif /* LWIP_COMPAT_SOCKETS == 2 */ + +/* + * Func Name: lwip_accept + */ +/** + * @ingroup Socket_Interfaces + * @brief This API accepts a new connection on a socket. + * The accept() function extracts the first connection on the queue of pending connections, + * creates a new socket with the same socket type protocol and address family as the specified socket, + * and allocates a new file descriptor for that socket. + * If the address is not a null pointer, the address of the peer for the accepted connection shall be + * stored in the sockaddr structure pointed to by address, + * and the length of this address shall be stored in the object pointed to by address_len. + * If the actual length of the address is greater than the length of the supplied sockaddr structure, + * the stored address shall be truncated. + * If the listen queue is empty of connection requests and O_NONBLOCK is not set on the file descriptor + * for the socket, accept() shall block until a connection is present.* + * If the listen() queue is empty of connection requests and O_NONBLOCK is set on the file descriptor for the socket, + * accept() shall fail and set errno to [EWOULDBLOCK]. + * @param[in] socket Specifies a socket that was created with socket(), has been bound to an address with + * bind(), and has issued a successful call to listen(). + * @param[out] address Indicates either a null pointer, or a pointer to a sockaddr structure + * where the address of the connecting socket shall be returned. + * @param[in,out] address_len Indicates either a null pointer, if address is a null pointer, + * or a pointer to a socklen_t object which on input + * specifies the length of the supplied sockaddr structure, + * and on output specifies the length of the stored address. + * + * @return + * The non-negative file descriptor of the accepted socket: On success \n + * -1: On failure. The errno shall be set to indicate the error, + * and any object pointed to by address_len shall remain unchanged. \n + * + * @par Errors + * \li The accept() function fails if: + * - [EBADF] : \n The socket argument is not a valid file descriptor. + * - [ECONNABORTED] : \n A connection has been aborted. + * - [ECONNABORTED] : \n IP address of stack has changed or removed while accept() was waiting. + * - [EFAULT] : \n A valid address length provide with address pointing to invalid memory. + * - [EINVAL] : \n The socket is not listening for connections. + * - [EINVAL] : \n The address length is invalid (For example, address_len is negative). + * - [ENFILE] : \n The maximum number of sockets in the system are already open. + * - [ENOBUFS] : \n No buffer space is available. + * - [ENOMEM] : \n There was insufficient memory available to complete the operation. + * - [EOPNOTSUPP] : \n The referenced socket is not of type SOCK_STREAM. + * - [EWOULDBLOCK] : \n O_NONBLOCK is set for the socket file descriptor + * and no connections are present to be accepted. + * - [EWOULDBLOCK] : \n O_NONBLOCK is not set but SO_RCVTIMEO is set, + * and no connections are present within accept timeout. + + * \li The accept() function may fail if: + * - [EIO] : \n Internal errors + * @par POSIX Conformance: + * @li Implementation deviates from POSIX.1-2008 (IEEE Std 1003.1-2008, 2016 Edition). + * - The following are the exceptions to conformance: + * - The new socket return by accept() inherit socket options such as SOF_REUSEADDR,SOF_KEEPALIVE. + * - This behaviour may differ from other implementations. + * - Portable programs should not rely on inheritance or non inheritance of file status flags or socket options, + * - and always explicitly set all required flags or options on the socket returned from the accept() API. + * - EIO is an lwIP specific errno, not defined by POSIX. + * - Portable programs must not use these options in applications. + * @cond liteos + * - If IP address of stack changes or removed due to netif_remove, + * - while accept() is waiting,then stack might return ECONNABORTED. + * - If accept() called after IP address bind to socket has been removed, + * - then accept() might block indefinitely. + * @endcond + * + * @note + * - This API does not support the PF_PACKET option. + * @par Related Topics + * connect() + */ +int lwip_accept(int socket, struct sockaddr *address, socklen_t *address_len); + +/* + * Func Name: lwip_bind + */ +/** + * @ingroup Socket_Interfaces + * @brief + * The bind() function assigns a local socket address address to a socket identified by descriptor socket + * that has no local socket address assigned. Sockets created with the socket() function are initially unnamed; + * they are identified only by their address family. This API assigns the address specified by name to the socket + * by the file descriptor s. namelen specifies the size, in bytes, of the address + * referred to structure pointed to by name. + * + * @param[in] s Specifies the file descriptor of the socket to be bound. + * @param[in] name Points to a sockaddr structure containing the address to be bound to the socket + * The length and format of the address depend on the address family of the socket. + * @param[in] namelen Specifies the length of the sockaddr structure pointed to by the address argument + * + * @return + * 0: On success \n + * -1: On failure. The errno is set to indicate the error. \n + * + * @par Errors + * @li The bind() function shall fail if: + * - [EADDRINUSE] : \n The specified address is already in use. + * - [EADDRINUSE] : \n For AF_INET/AF_INET6 socket, the port number was specified + * - as zero in the socket address structure, but, upon attempting to bind to an ephemeral port, + * - .it was determined that all port numbers in the ephemeral port range are currently in use. + * - [EADDRNOTAVAIL] : \n The specified address is not available from the local machine. + * - [EAFNOSUPPORT] : \n The specified address is not a valid address + * - for the address family of the specified socket. + * - [EBADF] : \n The socket argument is not a valid file descriptor. + * - [EINVAL] : \n The socket is already bound to an address, + * - and the protocol does not support binding to a new address. + * - [EINVAL] : \n The namelen argument is not a valid length for the address family. + * - [EINVAL] : \n For PF_PACKET socket, the ifindex is out of system netif index range. + * - [EISCONN] : \n The specified socket is already connected. + * - [ENOBUFS] : \n Insufficient resources were available to complete the call. + * - [ENODEV] : \n For PF_PACKET socket, the netif can not be determined by the ifindex. + * - [ENETDOWN] : \n For PF_PACKET socket, the netif determined by the ifindex was down. + * - [EOPNOTSUPP] : \n The socket type of the specified socket does not support binding to an address. + + * @par POSIX Conformance: + * Confirming to POSIX.1-2008 (IEEE Std 1003.1-2008, 2016 Edition) + * @note + * - Multiple bind call behavior: bind() call will change port binding of UDP socket. + * - On UDP socket will change local binding port. + * - On TCP socket it is not allowed, will return failure with errno EINVAL. + * - On AF_INET/AF_INET6 SOCK_RAW socket, it will update local IP address. + * - ON PF_PAKCET socket, it will change binding to new interface index. \n + * - AF_INET/AF_INET6 SOCK_RAW bind does not check if socket address is available or not. + */ +int lwip_bind(int s, const struct sockaddr *name, socklen_t namelen); + +/* + * Func Name: lwip_shutdown + */ +/** + * @ingroup Socket_Interfaces + * @brief + * This API is used to shut down socket send and receive operations.\n + * The shutdown() function shall cause all or part of a full-duplex connection on the socket associated + * with the file descriptor socket to be shut down. + * + * @param[in] socket Specifies a file descriptor referring to the socket. + * @param[in] how Specifies the type of shut-down. The values are as follows: \n + * SHUT_RD Disables further receive operations. \n SHUT_WR: Disables further send operations. \n + * SHUT_RDWR: Disables further send and receive operations. \n + + * The shutdown() function disables subsequent send and/or receive operations on a socket, + * depending on the value of the how argument. + * @return + * 0: On success \n + * -1: On failure. The errno is set to indicate the error. \n + * + * @par Errors + * @li The shutdown() function shall fail if: + * - [EBADF] : \n The socket argument is not a valid file descriptor. + * - [EINPROGRESS] : \n If WRITE/CONNECTING/CLOSE is in progress, lwIP may fail. + * - [EINVAL] : \n The 'how' argument is invalid. + * - [ENOMEM] : \n There was insufficient memory available to complete the operation. + * - [ENOTCONN] : \n If socket is not connected, or already shutdown. lwIP shall fail with ENOTCONN. + * - [ENOTCONN] : \n lwIP does not support half close, ENOTCONN is returned. + * - [ENOTCONN] : \n Socket is not TCP, lwIP shall fail. + + * @par POSIX Conformance: + * Implementation deviates from POSIX.1-2008 (IEEE Std 1003.1-2008, 2016 Edition). + * The following are the exceptions to conformance: + * - lwIP does not support half shutdown. That is, if you try to shutdown with either SHUT_RD or SHUT_WR alone, + * this API returns error ENOTCONN. + * @note + * - This API does not support the PF_PACKET option. + * - The listen socket does not support half shutdown. + * @par Limitations + * - If shutdown is called with SHUT_RDWR or SHUT_RD flag, any pending data to be received shall be cleared by lwIP, + * - and RST is sent to peer, application must read all data before calling SHUT_RDWR or SHUT_RD. + * - This behavior is a limitation of lwIP. \n + * - When send is blocked, and shutdown(SHUT_RDWR) is called, the shutdown will return EINPROGRESS (115). + */ +int lwip_shutdown(int socket, int how); + +#if LWIP_GETPEERNAME || (LWIP_COMPAT_SOCKETS != 2) +/* + * Func Name: lwip_getpeername + */ +/** + * @ingroup Socket_Interfaces + * @brief + * The getpeername() API returns the address of the peer connected to the socket 's', in the buffer pointed to by name. + * Initialize the namelen argument to indicate the amount of space pointed to by the name parameter. + * On return it contains the actual size, in bytes, of the name returned. + * The name is truncated if the buffer provided is too small. + * + * @param[in] s Specifies the file descriptor referring to the connected socket. + * @param[out] name Indicates the pointer to the sockaddr structure of remote peer. + * @param[in,out] namelen Specifies the size of name structure. + * + * @return + * 0: On success \n + * -1: On failure. The errno is set to indicate the error. \n + * @par Errors + * @li The getpeername() function fails if: + * - [EBADF] : The socket argument is not a valid file descriptor. + * - [EINVAL] : The name or namelen are NULL, then EINVAL is returned. + * - [ENOTCONN] : The socket is not connected or otherwise has not had the peer pre-specified. + * - [EOPNOTSUPP] : The operation is not supported for the socket protocol. + + * @par POSIX Conformance: + * Implementation deviates from POSIX.1-2008 (IEEE Std 1003.1-2008, 2016 Edition). + * The following are the exceptions to conformance: + * - lwIP does not check if connection-mode socket have been shutdown, and does not return failure with errno [EINVAL] + * + * @note + * - For PF_PACKET socket type, name should be pointing to sockaddr_ll type or memory of size struct sockaddr_ll + * + * @par Related Topics + * getsockname() + */ +int lwip_getpeername(int s, struct sockaddr *name, socklen_t *namelen); +#endif /* LWIP_GETPEERNAME || (LWIP_COMPAT_SOCKETS != 2) */ + +#if LWIP_GETSOCKNAME || (LWIP_COMPAT_SOCKETS != 2) +/* + * Func Name: lwip_getsockname + */ +/** + * @ingroup Socket_Interfaces + * @brief + * This API returns the current address to which the socket 's' is bound, + * in the buffer pointed to by the name parameter. + * Initialize the namelen argument to indicate the amount of space (in bytes) pointed to by the name parameter. + * The returned address is truncated if the buffer provided is too small. + * + * @param[in] s Specifies the file descriptor referring to connected socket. + * @param[out] name Indicates a pointer to sockaddr structure of local peer. + * @param[in,out] namelen Specifies the size of name structure. + * + * @return + * 0: On success \n + * -1: On failure. The errno is set to indicate the error. \n + * @par Errors + * @li The getsockname() function shall fail if: + * - [EBADF] : \n The socket argument is not a valid file descriptor. + * - [EINVAL] : \n If name or namelen are NULL, then this errno will be set. + * - [EOPNOTSUPP] : \n The operation is not supported for this socket's protocol. + * - .For PF_PACKET/SOCK_RAW sockets, this error is returned. + + * @par POSIX Conformance: + * Implementation deviates from POSIX.1-2008 (IEEE Std 1003.1-2008, 2016 Edition) + * The following are the exceptions to conformance: + * - lwIP does not check if connection-mode socket have been shutdown, + * - and does not return failure with errno [EINVAL]. + * @note + * \n + * - For PF_PACKET socket type, name should be pointing to sockaddr_ll type or memory of size struct sockaddr_ll + * + * @par Related Topics + * getpeername() + */ +int lwip_getsockname(int s, struct sockaddr *name, socklen_t *namelen); +#endif /* LWIP_GETSOCKNAME || (LWIP_COMPAT_SOCKETS != 2) */ + +/* + * Func Name: lwip_getsockopt + */ +/** + * @ingroup Socket_Interfaces + * @brief + * This API is used to get options set on a socket. + * This API retrieves the value for the option specified by the optname argument for the socket + * specified by sockfd. If the size of the optval is greater than optlen, the value stored in the object + * pointed to by the optval argument is silently truncated. + + * + * @param[in] sockfd Specifies a socket file descriptor. + * @param[in] level Specifies the protocol level at which the option resides. + * @param[in] optname Specifies a single option to be retrieved. + * @param[out] optval Indicates an address to store option value. + * @param[in,out] optlen Specifies the size of the option value. + * + * @return + * 0: On success \n + * -1: On failure. The errno is set to indicate the error. \n + + * + * @par Errors + * @li The getsockopt() function fails in the following conditions: + * - [EBADF] : \n The socket argument is not a valid file descriptor. + * - [EFAULT] : \n If opt or optlen are NULL,option or option length is incorrect. + * - [EINVAL] : \n If option length is incorrect for specified opt. + * - [EINVAL] : \n The specified option is invalid at the specified socket level. + * - [EINVAL] : \n The specified optval is invalid for specified opt. + * - [EINVAL] : \n The specified socket is already closed or has been disconnected. + * - [ENOMEM] : \n There was insufficient memory available to complete the operation. + * - [ENOPROTOOPT] : \n The option is not supported by the protocol. + * @par POSIX Conformance: + * Implementation deviates from POSIX.1-2008 (IEEE Std 1003.1-2008, 2016 Edition). + * The following are the exceptions to conformance: + * - lwIP does not check if connection-mode socket have been shutdown, and does not return failure with errno [EINVAL] + * @note + * - The following protocol levels are supported: + * - SOL_SOCKET + * - IPPROTO_IP + * - IPPROTO_TCP + * - IPPROTO_RAW + * - IPPROTO_IPV6 + * - IPPROTO_UDPLITE + * - The following options are supported under SOL_SOCKET:\n + * - SO_ACCEPTCONN + * - SO_BROADCAST + * - SO_ERROR + * - SO_KEEPALIVE + * - SO_SNDTIMEO + * - SO_RCVTIMEO + * - SO_RCVBUF + * - SO_SNDBUF + * - SO_REUSEADDR + * - SO_TYPE + * - SO_NO_CHECK + * - SO_BINDTODEVICE + * - SO_DONTROUTE + * - SO_LINGER + * @cond liteos For SO_SNDTIMEO, SO_RCVTIMEO, SO_RCVBUF, the macros LWIP_SO_SNDTIMEO, + * LWIP_SO_RCVTIMEO, and LWIP_SO_RCVBUF must be defined at compile time.\n + * For SO_REUSEADDR, the macro SO_REUSE must be defined at compile time.\n + * For SO_BINDTODEVICE, the macro + * LWIP_SO_BINDTODEVCE should have been defined at compile time. For SO_DONTROUTE, + * the macro LWIP_SO_DONTROUTE should have been defined at compile time. + * For SO_SNDBUF, the macro LWIP_SO_SNDBUF must be defined at compile time.\n @endcond + * - The following options are supported under IPPROTO_IP: + * - IP_MULTICAST_TTL + * - IP_MULTICAST_LOOP + * - IP_MULTICAST_IF + * - IP_HDRINCL + * - IP_TTL + * - IP_TOS + * If IP_HDRINCL is set , other options like IP_TTL and IP_TOS will be still able to set but will be effective only + * when IP_HDRINCL is unset.\n + * - The following options are supported under IPPROTO_TCP: + * - TCP_NODELAY + * - TCP_KEEPIDLE + * - TCP_KEEPINTVL + * - TCP_KEEPCNT + * - TCP_INFO + * - TCP_QUEUE_SEQ + * @cond liteos - For TCP_KEEPIDLE, TCP_KEEPINTVL, TCP_KEEPCNT, the macro LWIP_TCP_KEEPALIVE + * should have been defined at compile time. @endcond + * - SO_ERROR is not supported when socket is SOCK_RAW type. + * @cond For TCP_INFO, the macro LWIP_TCP_INFO should have been defined at compile time.\n @endcond + * - For TCP_INFO, Only tcpi_state, tcpi_retransmits, tcpi_probes, tcpi_backoff, tcpi_options, + * -. tcpi_rto, tcpi_snd_mss, tcpi_rcv_mss, tcpi_unacked, + * tcpi_rtt, tcpi_rttvar, tcpi_snd_ssthresh, tcpi_snd_cwnd, tcpi_reordering in + * struct tcp_info are supported. Other fields are not supported and may contain undefined values. \n + * - The following options are supported under IPPROTO_RAW: + * - IPV6_CHECKSUM: Checksum option to the offset for raw socket for updating the checksum. \n + * - The following options are supported under IPPROTO_IPV6: + * - IPV6_V6ONLY: Sets the ipv6 option. + * - IPV6_CHECKSUM: Checksum option to the offset for raw socket for updating the checksum. + * - IPV6_UNICAST_HOPS:To get the hop limit value used in outgoing unicast IPv6 packets + * - Only supported in get implementation. + * - IPV6_MULTICAST_HOPS: To get the hop limit value used for outgoing multicast packets, + * - only for UDP. Only supported in get implementation. + * - The following options are supported under IPPROTO_UDPLITE:\n + * - UDPLITE_SEND_CSCOV \n + * - UDPLITE_RECV_CSCOV\n + * + * + * @par Related Topics \n + * setsockopt() + */ +int lwip_getsockopt(int sockfd, int level, int optname, + void *optval, socklen_t *optlen); + +/* + * Func Name: lwip_setsockopt + */ +/** + * @ingroup Socket_Interfaces + * @brief + * The setsockopt() function sets the option specified by the option_name argument, + * at the protocol level specified by the level argument,to the value pointed to by the option_value argument + * for the socket associated with the file descriptor specified by the socket argument + + * The level argument specifies the protocol level at which the option resides. To set options at the socket level, + * specify the level argument as SOL_SOCKET. To set options at other levels, + * supply the appropriate level identifier for the protocol controlling the option. + * For example, to indicate that an option is interpreted by the TCP (Transport Control Protocol), + * set level to IPPROTO_TCP. + + * The option_name argument specifies a single option to set. + * If option_name is equal to SO_RCVTIMEO or SO_SNDTIMEO and the implementation supports setting the option, + * the struct timeval pointed to by option_value is rounded up to align with the resolution of the clock being used. + * If setsockopt() is called with option_name equal to SO_ACCEPTCONN, SO_ERROR, or SO_TYPE, the setsockopt fails. + * + * @param[in] socket Specifies a socket file descriptor. + * @param[in] level Specifies the protocol level at which the option resides. + * @param[in] option_name Specifies a single option to set. + * @param[out] option_value Indicates the pointer to the option value. + * @param[in] option_len Specifies the size of option value. + * + * @return + * 0: On success \n + * -1: On failure. The errno is set to indicate the error. \n + + * @par Errors + * @li The setsockopt() function fails in the following conditions: + * - [EBADF] : \n The socket argument is not a valid file descriptor. + * - [EDOM] : \n The send and receive timeout values are too big to + * - [EDOM] : \n fit into the timeout fields in the socket structure. + * - [EFAULT] : \n If optval is NULL pointer, lwIP fails. + * - [EINVAL] : \n If for PF_PACKET socket type, level is neither SOL_PACKET nor SOL_SOCKET, lwIP fails. + * - [EINVAL] : If for PF_PACKET socket type, level is neither SOL_PACKET nor SOL_SOCKET, lwIP shall fail. + * - [EINVAL] : \n If option_len does not match optval for corresponding option_name, lwIP fails. + * - [EINVAL] : \n If the send and receive timeout values are smaller than 10000 microseconds, lwIP fails. + * - [ENOENT] : \n The option is SO_DETACH_FILTER while no previous socket filter was attached. + * - [ENOMEM] : \n There was insufficient memory available for the operation to complete. + * - [ENOPROTOOPT] : \n The option is not supported by the protocol. + * @par POSIX Conformance: + * Implementation deviates from POSIX.1-2008 (IEEE Std 1003.1-2008, 2016 Edition). + * The following are the exceptions to conformance: + * - If connection oriented socket is shutdown, setsockopt does not check for this and does not return failure + * - with errno EINVAL as expected by POSIX. + * - If socket option is INVALID at specified socket level, setsockopt returns failure with errno set to ENOPROTOOPT, + * - which is not in conformance to POSIX. + * - setsockopt does not check if connection is already connected for the specified options + * - if can not be set while socket is connected. + * @note + * - The following protocol levels are supported: + * - SOL_SOCKET + * - IPPROTO_IP + * - IPPROTO_IPV6 + * - IPPROTO_TCP + * - IPPROTO_RAW + * - IPPROTO_UDPLITE + * - The following options are supported under SOL_SOCKET: + * - SO_BROADCAST + * - SO_KEEPALIVE + * - SO_LINGER + * - SO_SNDTIMEO + * - SO_RCVTIMEO + * - SO_RCVBUF + * - SO_SNDBUF + * - SO_ATTACH_FILTER + * - SO_DETACH_FILTER + * - SO_BINDTODEVICE + * - SO_DONTROUTE + * - SO_REUSEADDR + * - SO_NO_CHECK + * @cond liteos + * For SO_ATTACH_FILTER, SO_DETACH_FILTER, + * the macro LWIP_SOCKET_FILTER should have been defined at compile time. + * @endcond + * SO_ATTACH_FILTER: \n + * - LSF_MSH are not supported, due to which LSF_LDX hack for loading IP header length wont be supported. Hence, \n + * Following mode of filter is not supported: \n + * LSF_LDX+LSF_B+LSF_MSH X <- 4*(P[k:1]&0xf)\n + * Only PF_PACKET RAW socket supports SO_ATTACH_FILTER and SO_DETACH_FILTER now.\n + * @cond liteos + * For SO_SNDTIMEO, SO_RCVTIMEO, SO_RCVBUF, the macros LWIP_SO_SNDTIMEO, LWIP_SO_RCVTIMEO + * and LWIP_SO_RCVBUF must be defined at compile time. \n + * For SO_DONTROUTE, the macro LWIP_SO_DONTROUTE should have been defined at compile time, + * and RT_SCOPE_HOST is not supported. \n + * For SO_SNDBUF, the macro LWIP_SO_SNDBUF must be defined at compile time.\n + * For SO_REUSEADDR, the macro SO_REUSE must be defined at compile time.\n + * @endcond + * SO_REUSEADDR: \n + * - SO_REUSEADDR does not distribute datagrams evenly across the receiving threads.\n + * Only TCP socket in listen or closed states supports SO_SNDBUF.\n + * - The following options are supported under IPPROTO_IP: + * - IP_ADD_MEMBERSHIP + * - IP_DROP_MEMBERSHIP + * - IP_MULTICAST_TTL + * - IP_MULTICAST_LOOP + * - IP_MULTICAST_IF + * - IP_HDRINCL + * - IP_TTL + * - IP_TOS + * - The following options are supported under IPPROTO_IPV6: + * - IPV6_V6ONLY + * - IPV6_CHECKSUM + * -IPV6_JOIN_GROUP(IPV6_ADD_MEMBERSHIP) + * If the interface index is specified as 0, stack will not handle further, application has to give the valid index. + * -IPV6_LEAVE_GROUP(IPV6_DROP_MEMBERSHIP) + * - The following options are supported under IPPROTO_RAW: + * - IPV6_CHECKSUM + * - The following options are supported under IPPROTO_TCP: + * - TCP_NODELAY + * - TCP_KEEPIDLE + * - TCP_KEEPINTVL + * - TCP_KEEPCNT + * @cond liteos For TCP_KEEPIDLE, TCP_KEEPINTVL and TCP_KEEPCNT, + * - the macro LWIP_TCP_KEEPALIVE must be defined at compile time.\n @endcond + * - The following options are supported under IPPROTO_UDPLITE the options supported are: + * - UDPLITE_SEND_CSCOV + * - UDPLITE_RECV_CSCOV\n + * @cond liteos For IPPROTO_UDPLITE, the macro LWIP_UDPLITE must be defined at compile time.\n @endcond + + * @par Related Topics + * getsockopt() + */ +int lwip_setsockopt(int socket, int level, int option_name, + const void *option_value, socklen_t option_len); + +/* + * Func Name: lwip_close + */ +/** + * @ingroup Socket_Interfaces + * @brief + * This API is used to close the socket. + * If O_NONBLOCK is not set and if there is data on the module's write queue, close() + * waits for an unspecified time for any output to drain before dismantling the STREAM + * If the O_NONBLOCK flag is set, close() does not wait for output to drain, and dismantles the STREAM immediately + * + * @param[in] s Specifies a socket file descriptor. + * + * @return + * 0: On success \n + * -1: On failure. The errno is set to indicate the error. \n + * @par Errors + * @li The close() function shall fail if: + * - [EBADF] : \n The files argument is not a open file descriptor. Invalid file descriptor. + * + * @par Note + * The API must not be called concurrently with other BSD API on the same socket, + * because this scenario maybe causes other BSD API to return with unexpected behavior. + * + * @par POSIX Conformance: + * Implementation deviates from POSIX.1-2008 (IEEE Std 1003.1-2008, 2016 Edition) + * The following are the exceptions to conformance: + * - Does not support SO_LINGER socket option. + * + * + */ +int lwip_close(int s); + +/* + * Func Name: lwip_connect + */ +/** + * @ingroup Socket_Interfaces + * @brief + * The connect() function shall attempt to make a connection on a connection-mode socket + * or to set or reset the peer address of a connectionless-mode socket.\n + * Specifies the length of the sockaddr structure pointed to by the address argument. \n + * If the socket has not already been bound to a local address, + * connect() shall bind it to an address which is an unused local address. + * If the initiating socket is not connection-mode, then connect() shall set the socket's peer address, + * and no connection is made. For SOCK_DGRAM sockets, + * the peer address identifies where all datagrams are sent on subsequent send() functions, + * and limits the remote sender for subsequent recv() functions. + * + * If the initiating socket is connection-mode, then connect() shall attempt to establish a connection + * to the address specified by the address argument. If the connection cannot be established immediately + * and O_NONBLOCK is not set for the file descriptor for the socket, connect() shall block for up to + * an unspecified timeout interval until the connection is established. If the timeout interval expires before + * the connection is established, connect() shall fail and the connection attempt shall be aborted. + * + * If the connection cannot be established immediately and O_NONBLOCK is set for the file descriptor for the socket, + * connect() shall fail and set errno to [EINPROGRESS], but the connection request shall not be aborted, + * and the connection shall be established asynchronously. + * + * + * @param[in] s Specifies a socket file descriptor. + * @param[in] name Specifies a pointer to the sockaddr structure which identifies the connection. + * @param[in] namelen Specifies the size of name structure. + * + * + * @return + * 0: On success \n + * -1: On failure \n + * @par Errors + * @li The connect() function shall fail if: + * - [EACCES] : \n The user tried to connect to a broadcast address without having the socket broadcast flag + * enabled. + * - [EADDRNOTAVAIL] : \n For AF_INET/AF_INET6 socket, the socket had not previously been bound to + * an address and, upon attempting to bind it to an ephemeral port, + * it was determined that all port numbers in the ephemeral port + * range are currently in use. + * - [EAFNOSUPPORT] : \n The passed address did not have the correct address family in its sa_family field. + * - [EALREADY] : \n The socket is nonblocking and a previous connection attempt has not yet been completed. + * - [EBADF] : \n The socket argument is not a valid file descriptor. + * - [ECONNREFUSED] : \n The target address was not listening + * for connections or refused the connection request. + * - [ECONNRESET] : \n Remote host reset the connection request. + * - [EINPROGRESS] : \n O_NONBLOCK is set for the file descriptor for the socket + * and the connection cannot be immediately established; + * the connection shall be established asynchronously. + * - [EINVAL] : \n The address_len argument is not a valid length for the address family. + * - [EAFNOSUPPORT] : \n The specified address is not a valid address for the address family + * of the specified socket. + * - [EISCONN] : \n The specified socket is connection-mode and is already connected. + * - [ENETUNREACH] : \n No route to the network is present. + * - [ENOBUFS] : \n No buffer space is available. + * - [EOPNOTSUPP] : \n The referenced socket is not of domain AF_INET. + * - [EOPNOTSUPP] : \n The socket is listening and cannot be connected. + * - [ETIMEDOUT] : \n The attempt to connect timed out before a connection was made. + * + * @par POSIX Conformance: + * Implementation deviates from POSIX.1-2008 (IEEE Std 1003.1-2008, 2016 Edition). + * The following are the exceptions to conformance: + * - lwIP does not check if specified address has a different type + * than the socket bound to the specified peer address. Behavior is unspecified. + */ +int lwip_connect(int s, const struct sockaddr *name, socklen_t namelen); + +/* + * Func Name: lwip_listen + */ +/** + * @ingroup Socket_Interfaces + * @brief + * This API is used to set a socket into listen mode. + * This API marks the socket referred to by sockfd as a passive socket. + * That is, as a socket that will be used + * to accept incoming connection requests using accept(). + * + * @param[in] sockfd Specifies a file descriptor that refers to a socket of type SOCK_STREAM. + * @param[in] backlog Defines the maximum length to which the queue of pending connections for sockfd may grow + * If a connection request arrives + * when the queue is full, the client may receive an error with an indication of ECONNREFUSED + * or, if the underlying protocol + * supports retransmission, the request may be ignored + * so that a later reattempt at connection succeeds. + * + * @par Errors + * @li The listen() function shall fail if: + * - [EBADF] : \n The socket argument is not a valid file descriptor. + * - [EDESTADDRREQ] : \n The socket is not bound to a local address, + * and the protocol does not support listening on an unbound socket. + * - [EINVAL] : \n The socket is in state which is not acceptable for listen. + * - [ENOBUFS] : \n Insufficient resources are available in the system to complete the call. + * - [EOPNOTSUPP] : \n The socket protocol does not support listen(). + * + * @return + * 0: On success \n + * -1: On failure. The errno is set to indicate the error. \n + * @par POSIX Conformance: + * POSIX.1-2008 (IEEE Std 1003.1-2008, 2016 Edition) + * @note + * - Maximum value of backlog is 16, and minimum value of backlog is 0. + * - If backlog value is 0 or less than zero, backlog value of 1 is used. + * - This API does not support the PF_PACKET socket. + * - lwIP does not support auto binding in listen operation, so bind() must be called before listen(). + * - The listen() API supports multiple calls. If socket is already listening, it will update listen backlog. + * - New backlog value shall be applicable only for new incoming connection requests. + */ +int lwip_listen(int sockfd, int backlog); + +/* + * Func Name: lwip_recv + */ +/** + * @ingroup Socket_Interfaces + * @brief + * This API is used to recieve a message from connected socket. The recv() function shall receive a message + * from a connection-mode or connectionless-mode socket. It is normally used with connected sockets + * because it does not permit the application to retrieve the source address of received data. + * If no messages are available at the socket and O_NONBLOCK is not set on the socket's file descriptor, + * recv() shall block until a message arrives. If no messages are available at the socket and O_NONBLOCK + * is set on the socket's file descriptor, recv() shall fail and set errno to [EWOULDBLOCK]. + * + * @param[in] socket Specifies the socket file descriptor. + * @param[in] buffer Points to a buffer where the message should be stored. + * @param[in] length Specifies the length in bytes of the buffer pointed to by the buffer argument. + * @param[in] flags Specifies the type of message reception. + * Values of this argument are formed by logically OR'ing zero or more of the + * following values:\n + * MSG_PEEK : Peeks at an incoming message. The data is treated as unread and the next recv() + * or similar function shall still return this data. \n + * MSG_DONTWAIT : Enables nonblocking operation;if the operation would block, + * or similar function shall still EWOULDBLOCK.\n + * MSG_NOSIGNAL : Disables raising of SIGPIPE + * on stream sockets when the other end disappears.\n + * + * @return + * The length of the message in bytes. : On success. If no messages are available to be received + * and the peer has performed an orderly shutdown, recv() returns 0. \n + * -1: On failure. The errno is set to indicate the error. + * + * @par Errors + * @li The recv() function fails if: + * - [EBADF] : \n The socket argument is not a valid file descriptor. + * - [ECONNRESET] : \n A connection was forcibly closed by a peer. + * - [EINVAL]: \n Invalid input parameters. If mem, len is null or flags is less than zero, + * lwIP returns failure. + * - [ENOBUFS] : \n Insufficient resources were available in the system to perform the operation. + * - [ENOMEM] : \n Insufficient memory was available to fulfil the request. + * - [ENOTCONN] : \n A receive is attempted on a connection-mode socket that is not connected. + * - [EOPNOTSUPP] : \n Some bit in the flags argument is unsupported for the socket type. + * - [EWOULDBLOCK] : \n The socket's file descriptor is marked O_NONBLOCK or MSG_DONTWAIT flag + * is set and no data is waiting to be received. + * - [EWOULDBLOCK] : \n The socket was not marked with O_NONBLOCK, + * but set with option SO_RCVTIMEO, and elapsed time is more than timeout value. + * + * @li The recv() function may fail if: + * - [EIO]: \n Internal errors. + * + * @par POSIX Conformance: + * Implementation deviates from POSIX.1-2008 (IEEE Std 1003.1-2008, 2016 Edition). + * The following are the exceptions to conformance: + * For UDP MSG_PEEK is not suported and data is discarded even if it is set. + * MSG_OOB, MSG_WAITALL flags are not supported. + * + * @note + * - TCP receive buffer is a list, which holds the segement received from peer. + * If application is calling recv to get the data, then it just tries to get the + * first entry from the list and gives back to application. This doesn't get recursively + * from list to fill the complete user buffer. \n + * - lwIP updates this receive buffer list when it gets the next expected segment. + * If there is any out of order segment which is next to the received segment, + * lwIP merges the segments and puts that as one segment on to the receive buffer list. + * - If the apps don't read the packet form the socket and the recv buffered + * packets up to MAX_MBOX_SIZE, the incoming packet may be discard by lwIP and cause + * retransmission for tcp connection.\n + * - MSG_PEEK is not supported for UDP or RAW sockets. + * - UDP or RAW does not report memory allocation failure if memory allocation failed for received packet. + * - Instead of MSG_WAITALL, MSG_DONTWAIT is supported. + * - SO_RECVTIMEO socket option is set, and socket is not marked as O_NONBLOCK, (nonblocking), + * - and non data is received for timeout duration on socket, error is returned with ETIMEDOUT set. + * - For TCP connection, when RST is received after FIN, this API will return 0 to indicate FIN, + * - then return -1 and set errno to ECONNRESET for RST. + * - For TCP connection, when data is received and RST is recevied together (push, ack, rst) flag is set + * - then the data will be lost and RST will be processed. + * This API is not thread-safe. + * @par Related Topics + * read() + * recvfrom() + */ +ssize_t lwip_recv(int socket, void *buffer, size_t length, int flags); + +/* + * Func Name: lwip_read + */ +/** + * @ingroup Socket_Interfaces + * @brief + * The read() function shall attempt to read nbyte bytes from the file associated with the open file descriptor, + * fildes, into the buffer pointed to by buf. The behavior of multiple concurrent reads on the same device/socket is + * unspecified. + * Before any action described below is taken, and if nbyte is zero, the read() function may detect + * and return errors as described below. In the absence of errors, or if error detection is not performed, + * the read() function shall return zero and have no other results. + * If no messages are available at the socket and O_NONBLOCK is not set on the socket's file descriptor, + * recv() shall block until a message arrives. + * If no messages are available at the socket and O_NONBLOCK is set on the socket's file descriptor, + * recv() shall fail and set errno to [EWOULDBLOCK]. + * For message-based sockets, such as SOCK_DGRAM and SOCK_SEQPACKET, + * the entire message shall be read in a single operation. + * If a message is too long to fit in the supplied buffer, the excess bytes shall be discarded. + * + * + * @param[in] fildes Specifies a socket file descriptor. + * @param[out] buf Specifies the buffer to store the received data. + * @param[in] nbyte Specifies the number of bytes of data to receive. + * + * @return + * Number of bytes received: On success. \n + * -1: On failure. \n + * + * @par Errors + * @li The read() function fails if: + * - [EBADF] : \n The socket argument is not a valid file descriptor. + * - [ECONNRESET] : \n A connection was forcibly closed by a peer. + * - [EINVAL]: \n Invalid input parameters. If mem, len is null or flags is less than zero, + * lwIP returns failure. + * - [ENOBUFS] : \n Insufficient resources were available in the system to perform the operation. + * - [ENOMEM] : \n Insufficient memory was available to fulfil the request. + * - [ENOTCONN] : \n A receive is attempted on a connection-mode socket that is not connected. + * - [EWOULDBLOCK] : \n The socket's file descriptor is marked O_NONBLOCK + * or MSG_DONTWAIT flag is set and no data is waiting to be received. + * - [EWOULDBLOCK] : \n The socket was not marked with O_NONBLOCK, but set with option SO_RCVTIMEO, + * and elapsed time is more than timeout value. + * @li The read() function may fail if: + * - [EIO]: \n Internal errors. + * @par POSIX Conformance: + * Implementation deviates from POSIX.1-2008 (IEEE Std 1003.1-2008, 2016 Edition). + * The following are the exceptions to conformance: + * @par Related Topics + * recv() \n + * recvfrom() + * + * + */ +ssize_t lwip_read(int fildes, void *buf, size_t nbyte); + +/* + * Func Name: lwip_recvfrom + */ +/** + * @ingroup Socket_Interfaces + * @brief + * The recvfrom() function shall receive a message from a connection-mode or connectionless-mode socket. + * It is normally used with connectionless-mode sockets + * because it permits the application to retrieve the source address of received data. + * The function shall return the length of the message written to the buffer pointed to by the buffer argument. + * For message-based sockets, such as [RS] [Option Start] SOCK_RAW, [Option End] SOCK_DGRAM, and SOCK_SEQPACKET, + * the entire message shall be read in a single operation. If a message is too long to fit in the supplied buffer, + * the excess bytes shall be discarded. + * + * For stream-based sockets, such as SOCK_STREAM, message boundaries shall be ignored. In this case, + * data shall be returned to the user as soon as it becomes available, and no data shall be discarded. + * + * Not all protocols provide the source address for messages. If the address argument is not a null pointer + * and the protocol provides the source address of messages, the source address of the received message shall be stored + * in the sockaddr structure pointed to by the address argument, + * and the length of this address shall be stored in the object pointed to by the address_len argument. + * + * If the actual length of the address is greater than the length of the supplied sockaddr structure, + * the stored address shall be truncated. + * + * If no messages are available at the socket and O_NONBLOCK is not set on the socket's file descriptor, + * recvfrom() shall block until a message arrives. + * If no messages are available at the socket and O_NONBLOCK is set on the socket's file descriptor, + * recvfrom() shall fail and set errno to [EWOULDBLOCK]. + * + * @param[in] socket Specifies the socket file descriptor. + * @param[out] buffer Points to the buffer where the message should be stored. + * @param[in] length Specifies the length in bytes of the buffer pointed to by the buffer argument. + * @param[in] flags Specifies the type of message reception. + * Values of this argument are formed by logically OR'ing zero + * or more of the following values: \n + * MSG_PEEK : Peeks at an incoming message. The data is treated as unread and the next recv() + * or similar function shall still + * return this data. \n + * MSG_DONTWAIT : Enables nonblocking operation; if the operation would block, + * the call fails with the error EAGAIN or + * EWOULDBLOCK. \n + * MSG_NOSIGNAL : Disables raising of SIGPIPE on stream sockets when the other end disappears.\n + * @param[out] address A null pointer, or points to a sockaddr structure in which the sending address is to be stored. + * The length and format of the address depend on the address family of the socket. + * @param[out] address_len Either a null pointer, if address is a null pointer, or a pointer to a socklen_t object + * which on input specifies the length of the supplied sockaddr structure, + * and on output specifies the length of the stored address. + * + * @return + * Number of bytes received: Indicates a successful execution. \n + * -1: Indicates a failure. + * + * @par Required Header File + * sockets.h + * @par Errors + * @li The recvfrom() function fails if: + * - [EBADF] : \n The socket argument is not a valid file descriptor. + * - [ECONNRESET] : \n A connection was forcibly closed by a peer. + * - [EINVAL]: \n Invalid input parameters. If mem, len is null or flags is less than zero + * lwIP returns failure. + * - [ENOBUFS] : \n Insufficient resources were available in the system to perform the operation. + * - [ENOMEM] : \n Insufficient memory was available to fulfil the request. + * - [ENOTCONN] : \n A receive is attempted on a connection-mode socket that is not connected. + * - [EOPNOTSUPP] : \n Some bit in the flags argument is unsupported for the socket type. + * - [EWOULDBLOCK] : \n The socket's file descriptor is marked O_NONBLOCK or MSG_DONTWAIT + * flag is set and no data is waiting to be received. + * - [EWOULDBLOCK] : \n The socket was not marked with O_NONBLOCK, + * but set with option SO_RCVTIMEO, and elapsed time is more than timeout value. + * + * @li The recvfrom() function may fail if: + * - [EIO]: \n Internal errors. + * @par Return value + * Upon successful completion, recvfrom() shall return the length of the message in bytes. + * If no messages are available to be received and the peer has performed an orderly shutdown, + * recvfrom() shall return 0. Otherwise, the function shall return -1 and set errno to indicate the error. + * + * @par POSIX Conformance: + * Implementation deviates from POSIX.1-2008 (IEEE Std 1003.1-2008, 2016 Edition). + * The following are the exceptions to conformance: + * - For UDP MSG_PEEK is not suported and data is discarded even if it is set. + * - MSG_OOB, MSG_WAITALL flags are not supported. + * + * @note + * The behaviour of multiple concurrent reads on the same socket, is unspecified. + * - MSG_PEEK is not supported for UDP or RAW sockets. + * -UDP or RAW does not report memory allocation failure if memory allocation failed for received packet. + * - Instead of MSG_WAITALL, MSG_DONTWAIT is supported. + * - On TCP sockets, recvfrom() attempts to receive all the data from receive buffer if available. + * -TCP receive buffer is a list which holds the segment received from the peer. + * -If the application calls the recv function to get the data, the function gets the first entry from the list + * -and gives it back to application. This function does not recursively get entries + * -from the list to fill the complete user buffer. + * -lwIP updates this receive buffer list when it gets the next expected segment. + * -If there is any out of order segment which is next to the received segment, + * -lwIP merges the segments and puts that as one segment on to the receive buffer list. + * - If the apps don't read the packet form the socket and the recv buffered packets up to MAX_MBOX_SIZE, + * - the incoming packet may be discard by lwIP. + * - If the 'length' parameter is passed as zero, the stack will return -1 and errno will be set to EINVAL. + * - This behaviour is unspecified in POSIX specification, and a deviation from the LINUX implementation of recvfrom(), + * - where it returns 0 when the buffer size is passed as zero. + * - MSG_TRUNC flag is not supported. + * - For TCP connection, when RST is received after FIN, this API will return 0 to indicate FIN, then return -1 + * - and set errno to ECONNRESET for RST. + * - For TCP connection, when data is received and RST is recevied together (push, ack, rst) flag is set + * - then the data will be lost and RST will be processed. + * - This API is not thread-safe. + * @par Related Topics + * read() \n + * recv() + */ +ssize_t lwip_recvfrom(int socket, void *buffer, size_t length, + int flags, struct sockaddr *address, + socklen_t *address_len); + +/* + * Func Name: lwip_send + */ +/** + * @ingroup Socket_Interfaces + * @brief + * This API initiates transmission of a message from the specified socket to its peer. + * It sends a message only when the socket is connected. + * + * @param[in] s Specifies the socket file descriptor. + * @param[in] dataptr Specifies a buffer containing message to send. + * @param[in] size Specifies the length of the message to send. + * @param[in] flags Indicates the flags of message transmission. + * + * @return + * Number of bytes sent: Indicates a successful execution.\n + * -1: Indicates failure. + * + * @par Errors + * @li The send() function fails if: + * - [EADDINUSE] : For PF_INET/SOCK_DGRAM socket without local port bond, \ + * when attempting to bind to an ephemeral port, + * it was determined that all port numbers in the ephemeral port range are currently in use. + * - [EBADF] : The socket argument is not a valid file descriptor. + * - [ECONNRESET] : A connection was forcibly closed by a peer. + * - [EDESTADDRREQ] : The socket is not connection-mode and does not have its peer address set. + * - [EINPROGRESS] : For PF_INET/SOCK_STREAM, there was one send operation in progress, + * and concurrent sending was not supported. + * - [EINVAL] : Invalid argument passed, e.g. dataptr is NULL, size is zero. + * - [EMSGSIZE] : The socket type requires that message be sent atomically,\ + * and the size of the message to be sent made this impossible. + * For PF_PACKET/SOCK_RAW socket, it means the packet is larger than + * the MTU of out network interface. For PF_INET/(SOCK_RAW,SOCK_DGRAM) socket, + * it means the packet is larger than 65000 bytes. + * - [ENETDOWN] : For PF_PACKET/SOCK_RAW socket, the binding network interface was down. + * - [ENOBUFS] : Insufficient resources were available in the system to perform the operation. + * - [ENODEVADDR] : For PF_PACKET/SOCK_RAW socket, the binding network interface does not exist. + * - [ENOMEM] : Insufficient memory was available to fulfill the request. + * - [ENOTCONN] : The socket is not connected. + * - [EOPNOTSUPP] : Some bit in the flags argument is unsupported for the socket type. + * - [EPIPE] : The socket is shut down for writing, or the socket is connection-mode + * and is no longer connected.In the latter case, and if the socket is of type SOCK_STREAM. + * - [EWOULDBLOCK] : The socket's file descriptor is marked O_NONBLOCK or MSG_DONWAIT flag is set + * and the requested operation would block. + * - [EWOULDBLOCK] : The socket was not marked with O_NONBLOCK, but set with option SO_SNDTIMEO, + * and elapsed time is more than timeout value. + + * @li The send() function may fail if: + * - [EIO] : Internal errors. + * @par POSIX Conformance: + * Implementation deviates from POSIX.1-2008 (IEEE Std 1003.1-2008, 2016 Edition). + * The following are the exceptions to conformance: + * - lwIP do not support half-close, if sending data on the socket that was shut down for writing, + * it would failed and errno set to ENOTCONN, while it is EPIPE in POSIX. + * - Return type is int instead of ssize_t + * - If the socket is in connecting LwIP would return EINPROGRESS, which is ENOTCONN in POSIX. + * + * @note + * - UDP and RAW connection can send only data of maximum length 65332. Sending more than data + * will return -1 and errno set to EMSGSIZE. + * - Only flag MSG_MORE and MSG_DONTWAIT is supported. + * - Other flags, such as MSG_OOB/MSG_NOSIGNAL/MSG_EOR are not supported.\n + * + * + * @par Related Topics + * write() + * sendto() + */ +ssize_t lwip_send(int s, const void *dataptr, size_t size, int flags); +/** + * @ingroup Socket_Interfaces + * @brief + * This API initiates transmission of a message from the specified socket to its peer. + * It sends a message only when the socket is connected. The sendmsg() call also allows + * sending ancillary data (also known as control information). + * + * @param[in] s Specifies the socket file descriptor. + * @param[in] message Specifies a buffer containing message to send. + * @param[in] flags Indicates the types of message transmission. + * + * @return + * Number of bytes sent: Indicates a successful execution.\n + * -1: Indicates failure. + * + * @par Errors + * @li The sendmsg() function fails if: + * - [EADDINUSE] : For PF_INET/SOCK_DGRAM socket without local port bond, when attempting to + * bind to an ephemeral port, it was determined that all port numbers in the ephemeral port range are currently in use. + * - [EBADF] : The socket argument is not a valid file descriptor. + * - [ECONNRESET] : A connection was forcibly closed by a peer. + * - [EDESTADDRREQ] : The socket is not connection-mode and does not have its peer address set. + * - [EINPROGRESS] : For PF_INET/SOCK_STREAM, there was one send operation in progress, + * and concurrent sending was not supported. + * - [EINVAL] : Invalid argument passed, e.g. dataptr is NULL, size is zero. + * - [EMSGSIZE] : The socket type requires that message be sent atomically, and the size of the message + * to be sent made this impossible. For PF_PACKET/SOCK_RAW socket, + * it means the packet is larger than the MTU of out network interface. For PF_INET/(SOCK_RAW,SOCK_DGRAM) socket, + * it means the packet is larger than 65000 bytes. + * - [ENETDOWN] : For PF_PACKET/SOCK_RAW socket, the binding network interface was down. + * - [ENOBUFS] : Insufficient resources were available in the system to perform the operation. + * - [ENODEVADDR] : For PF_PACKET/SOCK_RAW socket, the binding network interface does not exist. + * - [ENOMEM] : Insufficient memory was available to fulfill the request. + * - [ENOTCONN] : The socket is not connected. + * - [EOPNOTSUPP] : Some bit in the flags argument is unsupported for the socket type. + * - [EPIPE] : The socket is shut down for writing, or the socket is connection-mode + * and is no longer connected. In the latter case, and if the socket is of type SOCK_STREAM. + * - [EWOULDBLOCK] : The socket's file descriptor is marked O_NONBLOCK + * or MSG_DONWAIT flag is set and the requested operation would block. + * - [EWOULDBLOCK] : The socket was not marked with O_NONBLOCK, + * but set with option SO_SNDTIMEO, and elapsed time is more than timeout value. + * + * @li The sendmsg() function may fail if: + * - [EIO] : Internal errors. + * @par POSIX Conformance: + * Implementation deviates from POSIX.1-2008 (IEEE Std 1003.1-2008, 2016 Edition). + * The following are the exceptions to conformance: + * - lwIP do not support half-close, if sending data on the socket that was shut down + * for writing, it would failed and errno set to ENOTCONN, while it is EPIPE in POSIX. + * - Return type is int instead of ssize_t + * - If the socket is in connecting LwIP would return EINPROGRESS, which is ENOTCONN in POSIX. + * + * @note + * - UDP and RAW connection can send only data of maximum length 65332. Sending more than data + * will return -1 and errno set to EMSGSIZE. + * - Only flag MSG_MORE and MSG_DONTWAIT is supported. Other flags, such as + * MSG_OOB/MSG_NOSIGNAL/MSG_EOR are not supported.\n + * + * + * @par Related Topics + * write() + * sendto() + */ +ssize_t lwip_sendmsg(int s, const struct msghdr *message, int flags); + +/* + * Func Name: lwip_sendto + */ +/** + * @ingroup Socket_Interfaces + * @brief + * This API is used to send messages from a connection-oriented and connectionless sockets. + * If the socket is in the connectionless mode, the message is sent to the address specified by the 'to' parameter. + * If the socket is in the connection mode, the destination address in the 'to' parameter is ignored. + * + * @param[in] s Specifies a socket file descriptor. + * @param[in] dataptr Specifies a buffer containing the message to send. + * @param[in] size Specifies the length of the message to send. + * @param[in] flags Indicates the flags of message transmission. + * @param[in] to Specifies a pointer to the sockaddr structure that contains the destination address. + * @param[in] tolen Specifies the size of the 'to' structure. + * + * @return + * Number of bytes sent: Indicates a successful execution. \n + * -1: Indicates a failure. + * @par Errors + * @li The sendto() function fails if: + * - [EACCES] : For PF_INET/(SOCK_RAW,SOCK_DGRAM) socket, + * the destination address is broadcast but SO_BROADCAST option was not enabled. + * - [EADDINUSE] : For PF_INET/SOCK_DGRAM socket without local port bond, + * when attempting to bind to an ephemeral port, it was determined that all port + * numbers in the ephemeral port range are currently in use. + * - [EAFNOSUPPORT] : Addresses in the specified address family cannot be used with this socket. + * - [EBADF] : The socket argument is not a valid file descriptor. + * - [ECONNRESET] : A connection was forcibly closed by a peer. + * - [EDESTADDRREQ] : The socket is not connection-mode and does not have its peer address set, + * and no destination address was specified. + * - [EINPROGRESS] : For PF_INET/SOCK_STREAM, there was one send operation in progress, + * and concurrent sending was not supported. + * - [EINVAL] : Invalid argument passed. For example, dataptr is NULL, size is zero. + * - [EMSGSIZE] : The socket type requires that message be sent atomically, + * and the size of the message to be sent made this impossible. + * For PF_PACKET/SOCK_RAW socket, + * it means the packet is larger than the MTU of out network interface. + * For PF_INET/(SOCK_RAW,SOCK_DGRAM) socket, it means the packet is larger than 65000 bytes. + * - [ENETDOWN] : For PF_PACKET/SOCK_RAW socket, the out network interface was down. + * - [ENETUNREACH] : No route to the destination is present. + * - [ENOBUFS] : Insufficient resources were available in the system to perform the operation. + * - [ENOMEM] : Insufficient memory was available to fulfill the request. + * - [ENOTCONN] : The socket is not connected. + * - [ENXIO] : For PF_PACKET/SOCK_RAW socket, the given network interface does not exist. + * - [EOPNOTSUPP] : Some bit in the flags argument is unsupported for the socket type. + * - [EPIPE] : The socket is shut down for writing, + * or the socket is connection-mode and is no longer connected. + * In the latter case, and if the socket is of type SOCK_STREAM . + * - [EWOULDBLOCK] : The socket's file descriptor is marked O_NONBLOCK + * or MSG_DONTWAIT flag is set and the requested operation would block. + * - [EWOULDBLOCK] : The socket was not marked with O_NONBLOCK, but set with option SO_SNDTIMEO, + * and elapsed time is more than timeout value. + + * @li The sendto() function may fail if: + * - [EIO] : Internal error. + * @par POSIX Conformance: + * Implementation deviates from POSIX.1-2008 (IEEE Std 1003.1-2008, 2016 Edition). + * *The following are the exceptions to conformance: + * - For UDP/RAW socket, sendto() override peer address set in connect by address provided in sendto, + * - and does not return failure with EISCONN. + * - TCP ignore destination address provided in sendto(), and use connection set up by connect() + * - MSG_EOR, MSG_OOB, MSG_NOSIGNAL, are not suported, lwip fails with errnor set to EOPNOTSUPP. + * - LwIP does not support half-close, if sending data on the socket that was shut down for writing, + * - it would failed and errno set to ENOTCONN, while it is EPIPE in POSIX. + * - For PF_PACKET SOCK_RAW socket, if given network interface index does not exist, + * - lwIP return failure with errno ENXIO. + * - If the socket is in connecting LwIP would return EINPROGRESS, which is ENOTCONN in POSIX. + * @note + * - AF_INET/AF_INET6 UDP and RAW connection can send only data of maximum length 65332. Sending more than data + * will return failure with return value -1 and errno set to EMSGSIZE. + * - Only flag MSG_MORE and MSG_DONTWAIT is supported, other flags, + * - such as MSG_OOB/MSG_NOSIGNAL/MSG_EOR is not supported + * + * @par Related Topics + * write() \n + * send() + */ +ssize_t lwip_sendto(int s, const void *dataptr, size_t size, int flags, + const struct sockaddr *to, socklen_t tolen); + +/* + * Func Name: lwip_socket + */ +/** + * @ingroup Socket_Interfaces + * @brief + * This API is used to allocate a socket. + * It creates an endpoint for communication and returns a file descriptor. + * + * @param[in] domain Specifies a protocol family. + * @param[in] type Specifies the socket type. [SOCK_RAW|SOCK_DGRAM,SOCK_STREAM] + * @param[in] protocol Specifies the protocol to be used with the socket. + * + * @return + * Valid socket file descriptor: On success. \n + * -1: On failure. + * @par Errors + * @li The socket() function fails if: + * - [EAFNOSUPPORT] : \n The implementation does not support the specified address family. + * - [EINVAL] : \n Invalid type or invalid flags in type. + * - [ENFILE] : \n The maximum number of sockets in the system are already open. + * - [ENOBUFS] : \n Insufficient resources were available in the system to perform the operation. + * - [EPROTONOSUPPORT] : \n The specified protocol is not supported within this domain & type. + * - [ESOCKTNOSUPPORT] : \n The socket type is not supported within this domain. + * @par POSIX Conformance: + * Implementation deviates from POSIX.1-2008 (IEEE Std 1003.1-2008, 2016 Edition). + * The following are the exceptions to conformance: + * - socket() does not validate domain. It assumes it to be AF_INET(PF_INET) if not PF_PACKET. + * As per POSIX it should return failure with errno [EAFNOSUPPORT], but it does not return that error. + * - For socket type not recognised by socket it returns failure with errno ESOCKTNOSUPPORT instead of EPROTOTYPE. + * @note + * - PF_PACKET is supported only for SOCK_RAW. + * - For AF_INET socket SOCK_RAW | SOCK_DGRAM | SOCK_STREAM types are supported. + * - For AF_PACKET, only the SOCK_RAW type is supported. + * - For AF_INET6 socket SOCK_RAW | SOCK_DGRAM | SOCK_STREAM types are supported. + */ +int lwip_socket(int domain, int type, int protocol); + +/* + * Func Name: lwip_write + */ +/** + * @ingroup Socket_Interfaces + * @brief + * This API is used to send data on connection-oriented sockets. + * + * @param[in] s Specifies a socket file descriptor. + * @param[in] dataptr Specifies a buffer containing the message to send. + * @param[in] size Specifies the length of the message to send. + * + * @return + * Number of bytes sent: Indicates success. \n + * -1: Indicates failure. + * + * @par Errors + * @li The write() function shall fail if: + * - [EWOULDBLOCK] : The socket's file descriptor is marked O_NONBLOCK or MSG_DONWAIT flag is set + * and the requested operation would block. + * - [EWOULDBLOCK] : The socket was not marked with O_NONBLOCK, but set with option SO_SNDTIMEO, + * and elapsed time is more than timeout value. + * - [EADDINUSE] : For PF_INET/SOCK_DGRAM socket without local port bond, + * when attempting to bind to an ephemeral port,* + * it was determined that all port numbers in the ephemeral port + * range are currently in use. + * - [EBADF] : The socket argument is not a valid file descriptor. + * - [ECONNRESET] : A connection was forcibly closed by a peer. + * - [EDESTADDRREQ] : The socket is not connection-mode and does not have its peer address set. + * - [EINPROGRESS] : For PF_INET/SOCK_STREAM, there was one send operation in progress, + * and concurrent sending was not supported. + * - [EINVAL] : Invalid argument passed. For example, dataptr is NULL or size is zero. + * - [EMSGSIZE] : The socket type requires that message be sent atomically, and the size of the message + * to be sent made this impossible. For PF_PACKET/SOCK_RAW socket, + * it means the packet is larger than the MTU of out network interface. + * For PF_INET/(SOCK_RAW,SOCK_DGRAM) socket, it means the packet is larger than 65000 bytes. + * - [ENETDOWN] : For PF_PACKET/SOCK_RAW socket, the binding network interface was down. + * - [ENOBUFS] : Insufficient resources were available in the system to perform the operation. + * - [ENOMEM] : Insufficient memory was available to fulfill the request. + * - [ENODEVADDR] : For PF_PACKET/SOCK_RAW socket, the binding network interface does not exist. + * - [ENOTCONN] : The socket is not connected. + * + * @li The write() function may fail if: + * - [EIO] : Internal errors. + * + * @par POSIX Conformance: + * Implementation deviates from POSIX.1-2008 (IEEE Std 1003.1-2008, 2016 Edition). + * The following are the exceptions to conformance: + * - Return type is int instead of ssize_t + * - lwIP sets EWOULDBLOCK instead of EAGAIN, wherever EAGAIN is set to errno. + * @note + * - For sockets not marked with O_NONBLOCK, and socket set with option SP_SENDTIMEO, + and elapsed time is more than timeout value, lwIP shall fail with errno EAGAIN. + * @par Related Topics + * send() \n + * sendto() + */ +int lwip_write(int s, const void *dataptr, size_t size); +/** + * @ingroup Socket_Interfaces + * @brief + * The writev() function writes iovcnt buffers of data described + * by iov to the file associated with the file descriptor s. + * + * @param[in] s Specifies a file descriptor. + * @param[in] iov Indicates buffers of data. + * @param[in] iovcnt Indicates the number of buffers. + * + * @return + * Number of bytes sent: Indicates success. \n + * -1: Indicates failure. + * + * @par Errors + * @li The writev() function shall fail if: + * - [EWOULDBLOCK] : The socket's file descriptor is marked O_NONBLOCK + * or MSG_DONWAIT flag is set and the requested operation would block. + * - [EWOULDBLOCK] : The socket was not marked with O_NONBLOCK, + * but set with option SO_SNDTIMEO, and elapsed time is more than timeout value. + * - [EADDINUSE] : For PF_INET/SOCK_DGRAM socket without local port bond, + * when attempting to bind to an ephemeral port, it was determined + * that all port numbers in the ephemeral port range are currently in use. + * - [EBADF] : The socket argument is not a valid file descriptor. + * - [ECONNRESET] : A connection was forcibly closed by a peer. + * - [EDESTADDRREQ] : The socket is not connection-mode and does not have its peer address set. + * - [EINPROGRESS] : For PF_INET/SOCK_STREAM, there was one send operation + * in progress, and concurrent sending was not supported. + * - [EINVAL] : Invalid argument passed. For example, dataptr is NULL or size is zero. + * - [EMSGSIZE] : The socket type requires that message be sent atomically, + * and the size of the message to be sent made this impossible. For PF_PACKET/SOCK_RAW socket, + * it means the packet is larger than the MTU of out network interface. + * For PF_INET/(SOCK_RAW,SOCK_DGRAM) socket, it means the packet is larger than 65000 bytes. + * - [ENETDOWN] : For PF_PACKET/SOCK_RAW socket, the binding network interface was down. + * - [ENOBUFS] : Insufficient resources were available in the system to perform the operation. + * - [ENOMEM] : Insufficient memory was available to fulfil the request. + * - [ENODEVADDR] : For PF_PACKET/SOCK_RAW socket, the binding network interface does not exist. + * - [ENOTCONN] : The socket is not connected. + * + * @li The writev() function may fail if: + * - [EIO] : Internal errors. + * + * @par POSIX Conformance: + * Implementation deviates from POSIX.1-2008 (IEEE Std 1003.1-2008, 2016 Edition). + * The following are the exceptions to conformance: + * - Return type is int instead of ssize_t + * - lwIP sets EWOULDBLOCK instead of EAGAIN, wherever EAGAIN is set to errno. + * @note + * - For sockets not marked with O_NONBLOCK, + * and socket set with option SP_SENDTIMEO, and elapsed time is more than timeout value, + * lwIP shall fail with errno EAGAIN. + * @par Related Topics + * send() \n + * sendto() + */ +int lwip_writev(int s, const struct iovec *iov, int iovcnt); + +#if LWIP_SOCKET_POLL +/* + * Func Name: lwip_poll + * */ +/** + * @ingroup Socket_Interfaces + * @brief + * This API is used to poll on multiple file descriptors, waiting until one or more of the file descriptors + * become "ready" for some of I/O operations. + * @param[in] sockfd socket file descriptor + * @param[in] wait Indicates poll table struct include events provided by the user. + * @return + * Socket file descriptor: On success \n + * -1: On failure \n + */ +int lwip_poll(int sockfd, poll_table *wait); +#endif /* LWIP_SOCKET_POLL*/ + +#if LWIP_SOCKET_SELECT +/* + * Func Name: lwip_select + */ +/** + * @ingroup Socket_Interfaces + * @brief + * + * select() allows a program to monitor multiple file + * descriptors, waiting until one or more of the file descriptors become + * "ready" for some class of I/O operation (input possible). A + * file descriptor is considered ready if it is possible to perform a + * corresponding I/O operation (read() without blocking, or a + * sufficiently small write()). + * + * select() can monitor only file descriptors numbers that are less than + * FD_SETSIZE. + * + * select() uses a timeout that is a struct timeval (with seconds + * and microseconds). + * Three independent sets of file descriptors are watched. The file + * descriptors listed in readfds will be watched to see if characters + * become available for reading (more precisely, to see if a read will + * not block; in particular, a file descriptor is also ready on end-of- + * file). The file descriptors in writefds will be watched to see if + * space is available for write (though a large write may still block). + * The file descriptors in exceptfds will be watched for exceptional + * conditions. + * On exit, each of the file descriptor sets is modified in place to + * indicate which file descriptors actually changed status. (Thus, if + * using select() within a loop, the sets must be reinitialized before + * each call.) + * + * Each of the three file descriptor sets may be specified as NULL if no + * file descriptors are to be watched for the corresponding class of + * events. + * + * Four macros are provided to manipulate the sets. FD_ZERO() clears a + * set. FD_SET() and FD_CLR() respectively add and remove a given file + * descriptor from a set. FD_ISSET() tests to see if a file descriptor + * is part of the set; this is useful after select() returns. + * + * nfds should be set to the highest-numbered file descriptor in any of + * the three sets, plus 1. The indicated file descriptors in each set + * are checked, up to this limit + * + * The timeout argument specifies the interval that select() should + * block waiting for a file descriptor to become ready. The call will + * block until either: + * - a file descriptor becomes ready; + * - the timeout expires. + * + * Note that the timeout interval will be rounded up to the system clock + * granularity, and kernel scheduling delays mean that the blocking + * interval may overrun by a small amount. If both fields of the + * timeval structure are zero, then select() returns immediately. (This + * is useful for polling.) If timeout is NULL (no timeout), select() + * can block indefinitely. + * + * @param[in] nfds Specifies a range of file descriptors. + * @param[in] readfds Specifies a pointer to struct fd_set, + * and specifies the descriptor to check for being ready to read. + * @param[in] writefds Specifies a pointer to struct fd_set, + * and specifies the descriptor to check for being ready to write. + * @param[in] exceptfds Specifies a pointer to struct fd_set, + * and specifies the descriptor to check for pending error conditions. + * @param[in] timeout Specifies a pointer to struct timeval, for timeout application. + * + * @return + * Socket file descriptor: On success \n + * -1: On failure \n + * @par POSIX Conformance: + * Implementation deviates from POSIX.1-2008 (IEEE Std 1003.1-2008, 2016 Edition). + * The following are the exceptions to conformance: + * - select() does not validate if nfds argument, + * - does not check if argument is less than zero or greater than FD_SETSIZE + * - As per POSIX, implementations may place limitations on the maximum timeout interval supported. + * All implementations shall support a maximum timeout interval of at least 31 days, + * but lwIP limits value until any overflow happens, + * timer with very high value might result in unspecified behavior. + + * @par Errors + * The select() function shall fail if: + * - [EBADF] : \n One or more of the file descriptor sets specified a file descriptor + * that is not a valid open file descriptor. + * - [EINVAL] : \n An invalid timeout interval was specified. \n + * - [ENOMEM] : \n Insufficient resources or memory, memory allocation failed. + + * @note + * - The select() API does not update the timeout argument to indicate how much time was left. + * - FD_SETSIZE is compile time configurable in lwIP, and application must ensure it does not violate this boundary, + * - lwIP does not validate this at runtime. + * + * @par Multithreaded Application + * If a file descriptor being monitored by select() is closed in another + * thread, the result is unspecified. lwIP may return without setting any fdset. + * On some UNIX systems, select() unblocks and returns, with an indication that the file descriptor is + * ready (a subsequent I/O operation will likely fail with an error, + * unless another the file descriptor reopened between the time select() + * returned and the I/O operations was performed). On Linux (and some + * other systems), closing the file descriptor in another thread has no + * effect on select(). In summary, any application that relies on a + * particular behaviour in this scenario must be considered buggy. + */ +int lwip_select(int nfds, fd_set *readfds, + fd_set *writefds, fd_set *exceptfds, + struct timeval *timeout); +#endif /* LWIP_SOCKET_SELECT */ + + /* + Func Name: lwip_ioctl + */ + /** + * @ingroup Socket_Interfaces + * @brief + This function manipulates the underlying device parameters of + special files. In particular, many operating characteristics of + character special files (for example, terminals) may be controlled with + ioctl() requests. The argument fd must be an open file descriptor. + + The second argument is a device-dependent request code. + + An ioctl() request has encoded in it whether the argument is an input + parameter or output parameter, and the size of the argument argp in + bytes. + + * @param[in] s Specifies an open socket file descriptor. + * @param[in] request Specifies a device-dependent request code. + * @param[in] argp Specifies additional information, if required. + * + * + * @return + * Usually, on success zero is returned. A few ioctl() requests use the + * return value as an output parameter and return a nonnegative value on + * success. On error, -1 is returned, and errno is set appropriately. + * + * @par Errors + * @li The ioctl() function shall fail if: + * - [EBADF] : The fd argument is not a valid open file descriptor. + * - [EINVAL] : The request or arg argument is not valid for this device. + * - [ENOMEM] : If any resource allocation fails, ENOMEM is set as errno. + * - [ENODEV] : If no device found, ENODEV is set as errno. + * - [EPERM] : If specified device is loopback i.e. "lo", EPERM is set as errno. + * @li The ioctl() function may fail if: + * - [EAFNOSUPPORT] : If socket created with PF_PACKET, SOCK_RAW is called with SIOCADDRT. + * - [EIO] : If socket failed to set/get ethtool settings, called with SIOCETHTOOL. + * - [ENOSYS] : If specified option is not supported/unimplemented, then errno is set as ENOSYS. + * @note + * - Linux API supports variable argument support. The lwIP API supports only one void * as the + * third argument. \n + * - This API supports the following options: \n + * - SIOCADDRT: Set IF gateway, soft-route is not support by lwIP yet. \n + * - SIOCGIFADDR: Get ifnet address.\n + * - SIOCGIFFLAGS: Get ifnet flags.\n + * - SIOCSIFFLAGS: Set ifnet flags.\n + * - IFF_UP: Interface is up.\n + * - IFF_BROADCAST: Broadcast address valid.\n + * - IFF_LOOPBACK: Is a loopback net.\n + * - IFF_POINTOPOINT: Is a point-to-point link.\n + * - IFF_DRV_RUNNING: Resources allocated.\n + * - IFF_NOARP: No address resolution protocol.\n + * - IFF_MULTICAST: Supports multicast.\n + * - IFF_DYNAMIC: Dialup device with changing addresses.\n + * - IFF_DYNAMIC_S: Dialup device with changing addresses.\n + * + * - This API also supports the following options: \n + * - SIOCGIFADDR: Get ifnet address.\n + * - SIOCSIFADDR: Set ifnet address.\n + * - SIOCGIFNETMASK: Get net addr mask.\n + * - SIOCSIFNETMASK : Set net addr mask.\n + * - SIOCSIFHWADDR: Set IF mac_address.\n + * - SIOCGIFHWADDR: Get IF mac_address\n + * - SIOCGIFNAME: Get IF name.\n + * - SIOCSIFNAME: Set IF name.\n + * - SIOCGIFMTU: Get IF mtu size.\n + * - SIOCSIFMTU: Set IF mtu size.\n + * - SIOCGIFINDEX: Get IF index.\n + * - SIOCGIFCONF: Get ifnet config. \n + * - SIOCETHTOOL: Detect eth link status. \n + * - FIONBIO: Set/clear non-blocking i/o.\n + * - FIONREAD:get the size of buffer.\n + * - For SIOCSIFNAME, the new name must be consisted by letters and numbers, + * - and the letters must be in front of numbers. + * The number range is from 0 to 255.\n @cond liteos + * - For FIONREAD option, argp should point to an application variable of type signed int. + * - FIONREAD is supported if LWIP_SO_RCVBUF is enabled. \n @endcond + * - For PF_PACKET sockets SIOCADDRT option is not supported. The options supported are: + * - FIONBIO + * - SIOCGIFADDR + * - SIOCSIFADDR + * - SIOCGIFNETMASK + * - SIOCSIFNETMASK + * - SIOCSIFHWADDR + * - SIOCGIFHWADDR + * - SIOCGIFFLAGS + * - SIOCSIFFLAGS + * - SIOCGIFNAME + * - SIOCSIFNAME + * - SIOCGIFINDEX + * - SIOCGIFCONF + * - For SIOCSIFADDR/SIOSIFNETMASK option, the gateway address is reset if the changed\n + * netif was the default netif and the gateway was unreachable after changing.\n + * Also duplicate network is forbidden.\n + * - For SIOCADDRT, only gateway setting is supported(flags in "struct rtentry" must be RTF_GATEWAY).\n + * + */ + int lwip_ioctl(int s, long request, void *argp); + + /* + Func Name: lwip_fcntl + */ + /** + * @ingroup Socket_Interfaces + * @brief + * The fcntl() function performs the operations described below on open files. The fd argument is a file descriptor. + * @li The available values for cmd are as follows: + * - F_GETFL: Get the file status flags and file access mode for the file description associated + * - with file descriptor. The flags returned may include non-standard file status flags + * - which the application did not set, provided that these additional flags + * - do not alter the behavior of a conforming application. + * - F_SETFL: val the file status flags for the file description associated with fildes + * - from thecorresponding bits in the third argument, val, taken as type int. Bits corresponding + * - to the file access mode and the file creation flags, that are set in arg shall be ignored. + * - If any bits in val other than those mentioned here are changed by the application, the result is unspecified. + * - If fildes does not support non-blocking operations. + * - it is unspecified whether the O_NONBLOCK flag will be ignored. + * + + * @param[in] s Indicates the socket file descriptor. + * @param[in] cmd Indicates a command to select an operation [F_GETFL, F_SETFL]. + * @param[in] val Indicates an additional flag, to set non-blocking. + * + * @return + * Upon successful completion, the value returned depends on cmd as follows: + * @li F_GETFL: Value of file status flags and access modes. The return value is not negative. + * @li F_SETFL: Value other than -1. + * + * @par Errors + * @li The fcntl() function shall fail if: + * - [EBADF] : \n The field argument is not a valid opened file descriptor. + * - [EINVAL] : \n The cmd argument is invalid, or cmd not supported by implementation, + * or if val is set to any other value other than O_NONBLOCK. + * Only F_GETFL and F_SETFL are supported by lwIP. + * @par POSIX Conformance: + Implementation deviates from POSIX.1-2008 (IEEE Std 1003.1-2008, 2016 Edition). + The following are the exceptions to conformance: + - Function prototype does not support variable arguments like POSIX or Linux fcntl API. + - The arg values to F_GETFL, and F_SETFL all represent flag values to allow for future growth. + - Applications using these functions should do a read-modify-write operation on them, + - rather than assuming that only the values defined by POSIX.1-2008 are valid.\ + - It is a common error to forget this, particularly in the case of F_SETFD. + - Some implementations set additional file status flags to advise the application of default behavior, + - even though the application did not request these flags. + * @note + + * - Only F_GETFL & F_SETFL commands are supported. For F_SETFL, only O_NONBLOCK is supported for val. + * - PF_PACKET sockets supports the F_SETFL and F_GETFL option. + */ +int lwip_fcntl(int s, int cmd, int val); + +/* + * internal function. + * Call this function to intialise global socket resources + */ +int sock_init(void); + +/** + * @ingroup Socket_Interfaces + * @brief + * This API is used to get TCP or UDP connection information. + + * @param[in] s Indicates a socket file descriptor. + * @param[out] conninfo Connection information details of given socket. + * + * + * @return + * 0: On success \n + * Negative value: On failure + + * @par Errors + * \li The lwip_get_conn_info() function fails if: + * - [ERR_CLSD] : The Connections are not valid TCP or UDP connections. + * - [EIO] : Internal Error , validation issue. + * - [EOPNOTSUPP] : Not a UDP/TCP connection or TCP connection in listen state. + * - [ERR_CONN] : For unconnected TCP connections. + * + * @note + * - This function called to get TCP or UDP connection information. + * - The void pointer is of type tcpip_conn. + * - This API does not support getting connection information of the TCP socket in LISTEN state.\n + */ +int lwip_get_conn_info (int s, void *conninfo); + +#if LWIP_API_RICH +struct lwip_sock *get_socket(int s); +#endif /* LWIP_API_RICH */ +struct lwip_sock *get_socket_ext(int s); + +#if LWIP_COMPAT_SOCKETS +#if LWIP_COMPAT_SOCKETS != 2 +/** @ingroup socket */ +#define accept(s, addr, addrlen) lwip_accept(s, addr, addrlen) +/** @ingroup socket */ +#define bind(s, name, namelen) lwip_bind(s, name, namelen) +/** @ingroup socket */ +#define shutdown(s, how) lwip_shutdown(s, how) +/** @ingroup socket */ +#define getpeername(s, name, namelen) lwip_getpeername(s, name, namelen) +/** @ingroup socket */ +#define getsockname(s, name, namelen) lwip_getsockname(s, name, namelen) +/** @ingroup socket */ +#define setsockopt(s, level, optname, opval, optlen) lwip_setsockopt(s, level, optname, opval, optlen) +/** @ingroup socket */ +#define getsockopt(s, level, optname, opval, optlen) lwip_getsockopt(s, level, optname, opval, optlen) +/** @ingroup socket */ +#define closesocket(s) lwip_close(s) +/** @ingroup socket */ +#define connect(s, name, namelen) lwip_connect(s, name, namelen) +/** @ingroup socket */ +#define listen(s, backlog) lwip_listen(s, backlog) +/** @ingroup socket */ +#define recv(s, mem, len, flags) lwip_recv(s, mem, len, flags) +/** @ingroup socket */ +#define recvfrom(s, mem, len, flags, from, fromlen) lwip_recvfrom(s, mem, len, flags, from, fromlen) +/** @ingroup socket */ +#define send(s, dataptr, size, flags) lwip_send(s, dataptr, size, flags) +/** @ingroup socket */ +#define sendmsg(s, message, flags) lwip_sendmsg(s, message, flags) +/** @ingroup socket */ +#define sendto(s, dataptr, size, flags, to, tolen) lwip_sendto(s, dataptr, size, flags, to, tolen) +/** @ingroup socket */ +#define socket(domain, type, protocol) lwip_socket(domain, type, protocol) +#if LWIP_SOCKET_SELECT +/** @ingroup socket */ +#define select(maxfdp1, readset, writeset, exceptset, timeout) \ + lwip_select(maxfdp1, readset, writeset, exceptset, timeout) +#endif +/** @ingroup socket */ +#define ioctlsocket(s, cmd, argp) lwip_ioctl(s, cmd, argp) +/** @ingroup socket */ +#define inet_ntop(af, src, dst, size) lwip_inet_ntop(af, src, dst, size) +/** @ingroup socket */ +#define inet_pton(af, src, dst) lwip_inet_pton(af, src, dst) + +#if LWIP_POSIX_SOCKETS_IO_NAMES +/** @ingroup socket */ +#define read(s, mem, len) lwip_read(s, mem, len) +/** @ingroup socket */ +#define write(s, dataptr, len) lwip_write(s, dataptr, len) +/** @ingroup socket */ +#define writev(s, iov, iovcnt) lwip_writev(s, iov, iovcnt) +/** @ingroup socket */ +#define close(s) lwip_close(s) +/** @ingroup socket */ +#define fcntl(s, cmd, val) lwip_fcntl(s, cmd, val) +/** @ingroup socket */ +#define ioctl(s, cmd, argp) lwip_ioctl(s, cmd, argp) +#endif /* LWIP_POSIX_SOCKETS_IO_NAMES */ +#endif /* LWIP_COMPAT_SOCKETS != 2 */ + +/* + * Func Name: lwip_inet_ntop + */ +/** + * @ingroup Socket_Interfaces + * @brief + * This function converts the network address structure src in the af address family into a + * character string. The resulting string is copied to the buffer pointed to by dst, which + * must be a non-null pointer. The following address families are currently supported: + * AF_INET + * src points to a struct in_addr (in network byte order) which is converted to an IPv4 network address + * in the dotted-decimal format, "ddd.ddd.ddd.ddd".The buffer dst must be at least INET_ADDRSTRLEN bytes long. + * + * AF_INET6 + * src points to a struct in6_addr (in network byte order) which is converted to a representation of this + * address in the most appropriate IPv6 network address format for this address. + * The buffer dst must be at least INET6_ADDRSTRLEN bytes long. + * + * @param[in] af Specifies the Address family. + * @param[in] src Indicates Network Address structure. + * @param[in] dst Indicates the buffer to store the result string. + * @param[in] size Indicates the number of bytes available in the dst string. + * + * @return + * non NULL pointer to dst: On success \n + * NULL: Error case,with errno set to indicate the error \n + * + * @par Errors + * @li The inet_ntop() function shall fail if: + * - [EAFNOSUPPORT] : af was not a valid address family. + * - [ENOSPC] : The converted address string would exceed the size given by size. + */ +const char *lwip_inet_ntop(int af, const void *src, char *dst, socklen_t size); + +/* + * Func Name: lwip_inet_pton + */ +/** + * @ingroup Socket_Interfaces + * @brief + * This function converts the character string src into a network address structure in the + * af address family, then copies the network address structure to dst.The following address + * families are currently supported: + * AF_INET + * src points to a character string containing an IPv4 network address in dotted-decimal format, + * "ddd.ddd.ddd.ddd", where ddd is a decimal number of up to three digits in the range 0 to 255. + * The address is converted to a struct in_addr and copied to dst, + * which must be sizeof(struct in_addr) (4) bytes (32 bits) long. + * + * AF_INET6 + * src points to a character string containing an IPv6 network address. The address is converted + * to a struct in6_addr and copied to dst, which must be sizeof(struct in6_addr) (16) bytes (128 bits) long. + * + * @param[in] af Specifies the Address family. + * @param[in] src Indicates a character string with IPv4 or IPv6 address. + * @param[in] dst Indicates Network address structure. + * + * @return + * 1: On success (network address was successfully converted) \n + * 0: if src doesnot contain character string representing a valid network address in the specified address family\n + * -1: invalid address family and errno is set\n + * + * @par Errors + * @li The inet_pton() function shall fail if: + * - [EAFNOSUPPORT] : af was not a valid address family. + */ +int lwip_inet_pton(int af, const char *src, void *dst); + +#endif /* LWIP_COMPAT_SOCKETS */ + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_SOCKET */ + +#endif /* LWIP_HDR_SOCKETS_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/stats.h b/sdk_liteos/third_party/lwip_sack/include/lwip/stats.h new file mode 100644 index 0000000000000000000000000000000000000000..89fa7f8ca3b4ad013736cbb7eef5fce947bd4125 --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/stats.h @@ -0,0 +1,702 @@ +/** + * @file + * Statistics API (to be used from TCPIP thread) + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_STATS_H +#define LWIP_HDR_STATS_H + +#include "lwip/opt.h" +#include "netif/lowpan6_opts.h" +#include "lwip/mem.h" +#include "lwip/memp.h" +#include "lwip/err.h" + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +#if LWIP_STATS + +#ifndef LWIP_STATS_LARGE +#define LWIP_STATS_LARGE 0 +#endif + +#if LWIP_STATS_LARGE +#define STAT_COUNTER u32_t +#define STAT_COUNTER_F U32_F +#else +#define STAT_COUNTER u16_t +#define STAT_COUNTER_F U16_F +#endif + +/* Protocol related stats */ +struct stats_proto { + STAT_COUNTER xmit; /* Transmitted packets. */ + STAT_COUNTER recv; /* Received packets. */ + STAT_COUNTER fw; /* Forwarded packets. */ + STAT_COUNTER drop; /* Dropped packets. */ + STAT_COUNTER chkerr; /* Checksum error. */ + STAT_COUNTER lenerr; /* Invalid length error. */ + STAT_COUNTER memerr; /* Out of memory error. */ + STAT_COUNTER rterr; /* Routing error. */ + STAT_COUNTER proterr; /* Protocol error. */ + STAT_COUNTER opterr; /* Error in options. */ + STAT_COUNTER err; /* Misc error. */ + STAT_COUNTER cachehit; + STAT_COUNTER cache_miss; /* When NCE,RLE,DCE or PLE is missded. */ + STAT_COUNTER cache_full; /* When NCE,RLE,DCE or PLE is full. */ + +#ifdef LWIP_IPV6 + STAT_COUNTER destunreachs; /* Destination unreachable packets */ + STAT_COUNTER timeexcds; /* Time exceeded packets */ + STAT_COUNTER parmprobs; /* Parameter problem */ +#endif + +#if LWIP_NAT64 + STAT_COUNTER natfw; /* Forwarded packets. */ + STAT_COUNTER natdrop; /* Dropped packets. */ +#endif + + STAT_COUNTER link_rx_drop; /* Recvd frames discard count */ + STAT_COUNTER link_tx_drop; /* To be sent frames discard count */ + STAT_COUNTER link_rx_overrun; /* FIFO overrun */ + STAT_COUNTER ip_rx_err; /* Recvd IP packet error */ + STAT_COUNTER ip_tx_err; /* Sent IP packet error */ + STAT_COUNTER ip_rx_bytes; /* Recvd byte count at IP layer */ + STAT_COUNTER ip_tx_bytes; /* Sent byte count at IP layer */ + STAT_COUNTER reserve; /* reserve */ +}; + +/* IGMP stats */ +struct stats_igmp { + STAT_COUNTER xmit; /* Transmitted packets. */ + STAT_COUNTER recv; /* Received packets. */ + STAT_COUNTER drop; /* Dropped packets. */ + STAT_COUNTER chkerr; /* Checksum error. */ + STAT_COUNTER lenerr; /* Invalid length error. */ + STAT_COUNTER memerr; /* Out of memory error. */ + STAT_COUNTER proterr; /* Protocol error. */ + STAT_COUNTER rx_v1; /* Received v1 frames. */ + STAT_COUNTER rx_group; /* Received group-specific queries. */ + STAT_COUNTER rx_general; /* Received general queries. */ + STAT_COUNTER rx_report; /* Received reports. */ + STAT_COUNTER tx_join; /* Sent joins. */ + STAT_COUNTER tx_leave; /* Sent leaves. */ + STAT_COUNTER tx_report; /* Sent reports. */ +}; + +/* Memory stats */ +struct stats_mem { +#if defined(LWIP_DEBUG) || LWIP_STATS_DISPLAY + const char *name; +#endif /* defined(LWIP_DEBUG) || LWIP_STATS_DISPLAY */ + STAT_COUNTER err; + mem_size_t avail; + mem_size_t used; + mem_size_t max; + STAT_COUNTER illegal; +}; + +/* System element stats */ +struct stats_syselem { + STAT_COUNTER used; + STAT_COUNTER max; + STAT_COUNTER err; +}; + +/* System stats */ +struct stats_sys { + struct stats_syselem sem; + struct stats_syselem mutex; + struct stats_syselem mbox; +}; + +/* SNMP MIB2 stats */ +struct stats_mib2 { + /* IP */ + u32_t ipinhdrerrors; + u32_t ipinaddrerrors; + u32_t ipinunknownprotos; + u32_t ipindiscards; + u32_t ipindelivers; + u32_t ipoutrequests; + u32_t ipoutdiscards; + u32_t ipoutnoroutes; + u32_t ipreasmoks; + u32_t ipreasmfails; + u32_t ipfragoks; + u32_t ipfragfails; + u32_t ipfragcreates; + u32_t ipreasmreqds; + u32_t ipforwdatagrams; + u32_t ipinreceives; + + /* TCP */ + u32_t tcpactiveopens; + u32_t tcppassiveopens; + u32_t tcpattemptfails; + u32_t tcpestabresets; + u32_t tcpoutsegs; + u32_t tcpretranssegs; + u32_t tcpinsegs; + u32_t tcpinerrs; + u32_t tcpoutrsts; + + /* UDP */ + u32_t udpindatagrams; + u32_t udpnoports; + u32_t udpinerrors; + u32_t udpoutdatagrams; + + /* ICMP */ + u32_t icmpinmsgs; + u32_t icmpinerrors; + u32_t icmpindestunreachs; + u32_t icmpintimeexcds; + u32_t icmpinparmprobs; + u32_t icmpinsrcquenchs; + u32_t icmpinredirects; + u32_t icmpinechos; + u32_t icmpinechoreps; + u32_t icmpintimestamps; + u32_t icmpintimestampreps; + u32_t icmpinaddrmasks; + u32_t icmpinaddrmaskreps; + u32_t icmpoutmsgs; + u32_t icmpouterrors; + u32_t icmpoutdestunreachs; + u32_t icmpouttimeexcds; + u32_t icmpoutechos; /* can be incremented by user application ('ping') */ + u32_t icmpoutechoreps; +}; + +/* + * @ingroup netif_mib2 + * SNMP MIB2 interface stats + */ +struct stats_mib2_netif_ctrs { + /* The total number of octets received on the interface, including framing characters */ + u32_t ifinoctets; + /* The number of packets, delivered by this sub-layer to a higher (sub-)layer, which were + * not addressed to a multicast or broadcast address at this sub-layer */ + u32_t ifinucastpkts; + /* The number of packets, delivered by this sub-layer to a higher (sub-)layer, which were + * addressed to a multicast or broadcast address at this sub-layer */ + u32_t ifinnucastpkts; + /* The number of inbound packets which were chosen to be discarded even though no errors had + * been detected to prevent their being deliverable to a higher-layer protocol. One possible + * reason for discarding such a packet could be to free up buffer space */ + u32_t ifindiscards; + /* For packet-oriented interfaces, the number of inbound packets that contained errors + * preventing them from being deliverable to a higher-layer protocol. For character- + * oriented or fixed-length interfaces, the number of inbound transmission units that + * contained errors preventing them from being deliverable to a higher-layer protocol. */ + u32_t ifinerrors; + /* For packet-oriented interfaces, the number of packets received via the interface which + * were discarded because of an unknown or unsupported protocol. For character-oriented + * or fixed-length interfaces that support protocol multiplexing the number of transmission + * units received via the interface which were discarded because of an unknown or unsupported + * protocol. For any interface that does not support protocol multiplexing, this counter will + * always be 0 */ + u32_t ifinunknownprotos; + /* The number of inbound packets which were chosen to be discarded because of fifo overrun */ + u32_t ifinoverruns; + /* The total number of octets transmitted out of the interface, including framing characters. */ + u32_t ifoutoctets; + /* The total number of packets that higher-level protocols requested be transmitted, and + * which were not addressed to a multicast or broadcast address at this sub-layer, including + * those that were discarded or not sent. */ + u32_t ifoutucastpkts; + /* The total number of packets that higher-level protocols requested be transmitted, and which + * were addressed to a multicast or broadcast address at this sub-layer, including + * those that were discarded or not sent. */ + u32_t ifoutnucastpkts; + /* The number of outbound packets which were chosen to be discarded even though no errors had + * been detected to prevent their being transmitted. One possible reason for discarding + * such a packet could be to free up buffer space. */ + u32_t ifoutdiscards; + /* For packet-oriented interfaces, the number of outbound packets that could not be transmitted + * because of errors. For character-oriented or fixed-length interfaces, the number of outbound + * transmission units that could not be transmitted because of errors. */ + u32_t ifouterrors; +}; + +/** + * @ingroup stats + * 6LOWPAN stats */ +struct stats_lowpan6 { + STAT_COUNTER pkt_from_ip; /**< Pkt received from top layer */ + STAT_COUNTER pkt_xmit; /**< Transmitted packets. */ + STAT_COUNTER comp_fail; /**< Compression Failure */ + + STAT_COUNTER frag_recvd; /**< Fragments Received from network. */ + STAT_COUNTER pkt_recvd; /**< Packet Received from network. */ + STAT_COUNTER pkt_to_ip; /**< Packet sent to top layer. */ + + STAT_COUNTER decomp_fail; /**< Decompression failures. */ + STAT_COUNTER discard_pkt; /**< Invalid packet/fragment. */ + STAT_COUNTER reass_tout; /**< Fragment reassemble timed out. */ + STAT_COUNTER dup_frag; /**< Duplicate fragment. */ + STAT_COUNTER oo_frag; /**< Out of Order fragments. */ + STAT_COUNTER rogue_frag; /**< Nth Fragment without first fragment. */ + STAT_COUNTER corrupt_pkt; /**< Corrupt 6lowpan frame. */ +}; +/* lwIP stats container */ +struct stats_ { +#if LINK_STATS + /* Link level */ + struct stats_proto link; +#endif +#if ETHARP_STATS + /* ARP */ + struct stats_proto etharp; +#endif +#if IPFRAG_STATS + /* Fragmentation */ + struct stats_proto ip_frag; +#endif +#if IP_STATS + /* IP */ + struct stats_proto ip; +#endif +#if ICMP_STATS + /* ICMP */ + struct stats_proto icmp; +#endif +#if IGMP_STATS + /* IGMP */ + struct stats_igmp igmp; +#endif +#if UDP_STATS + /* UDP */ + struct stats_proto udp; +#endif +#if TCP_STATS + /* TCP */ + struct stats_proto tcp; +#endif +#if MEM_STATS + /* Heap */ + struct stats_mem mem; +#endif +#if MEMP_STATS + /* Internal memory pools */ + struct stats_mem *memp[MEMP_MAX]; +#endif +#if SYS_STATS + /* System */ + struct stats_sys sys; +#endif +#if IP6_STATS + /* IPv6 */ + struct stats_proto ip6; +#endif +#if ICMP6_STATS + /* ICMP6 */ + struct stats_proto icmp6; +#endif +#if IP6_FRAG_STATS + /* IPv6 fragmentation */ + struct stats_proto ip6_frag; +#endif +#if MLD6_STATS + /* Multicast listener discovery */ + struct stats_igmp mld6; +#endif +#if ND6_STATS + /* Neighbor discovery */ + struct stats_proto nd6; +#endif +#if MIB2_STATS + /* SNMP MIB2 */ + struct stats_mib2 mib2; +#endif +#if DHCP6_STATS + /* DHCPv6 */ + struct stats_proto dhcp6; +#endif +#if LWIP_6LOWPAN + /** 6lowpan */ + struct stats_lowpan6 lowpan6; +#endif +}; + +/* Global variable containing lwIP internal statistics. Add this to your debugger's watchlist. */ +extern struct stats_ lwip_stats; + +/* Init statistics */ +void stats_init(void); + +#define STATS_INC(x) ++lwip_stats.x +#define STATS_DEC(x) --lwip_stats.x +#define STATS_INC_USED(x, y, type) do { lwip_stats.x.used = (type)(lwip_stats.x.used + y); \ + if (lwip_stats.x.max < lwip_stats.x.used) { \ + lwip_stats.x.max = lwip_stats.x.used; \ + } \ + } while (0) +#define STATS_GET(x) lwip_stats.x +#else /* LWIP_STATS */ +#define stats_init() +#define STATS_INC(x) +#define STATS_DEC(x) +#define STATS_INC_USED(x, y, type) +#endif /* LWIP_STATS */ + +#if TCP_STATS +#define TCP_STATS_INC(x) STATS_INC(x) +#define TCP_STATS_DISPLAY() stats_display_proto(&lwip_stats.tcp, "TCP") +#else +#define TCP_STATS_INC(x) +#define TCP_STATS_DISPLAY() +#endif + +#if UDP_STATS +#define UDP_STATS_INC(x) STATS_INC(x) +#define UDP_STATS_DISPLAY() stats_display_proto(&lwip_stats.udp, "UDP") +#else +#define UDP_STATS_INC(x) +#define UDP_STATS_DISPLAY() +#endif + +#if ICMP_STATS +#define ICMP_STATS_INC(x) STATS_INC(x) +#define ICMP_STATS_DISPLAY() stats_display_proto(&lwip_stats.icmp, "ICMP") +#else +#define ICMP_STATS_INC(x) +#define ICMP_STATS_DISPLAY() +#endif + +#if IGMP_STATS +#define IGMP_STATS_INC(x) STATS_INC(x) +#define IGMP_STATS_DISPLAY() stats_display_igmp(&lwip_stats.igmp, "IGMP") +#else +#define IGMP_STATS_INC(x) +#define IGMP_STATS_DISPLAY() +#endif + +#if IP_STATS +#define IP_STATS_INC(x) STATS_INC(x) +#define IP_STATS_DISPLAY() stats_display_proto(&lwip_stats.ip, "IP") +#else +#define IP_STATS_INC(x) +#define IP_STATS_DISPLAY() +#endif + +#if IPFRAG_STATS +#define IPFRAG_STATS_INC(x) STATS_INC(x) +#define IPFRAG_STATS_DISPLAY() stats_display_proto(&lwip_stats.ip_frag, "IP_FRAG") +#else +#define IPFRAG_STATS_INC(x) +#define IPFRAG_STATS_DISPLAY() +#endif + +#if ETHARP_STATS +#define ETHARP_STATS_INC(x) STATS_INC(x) +#define ETHARP_STATS_DISPLAY() stats_display_proto(&lwip_stats.etharp, "ETHARP") +#else +#define ETHARP_STATS_INC(x) +#define ETHARP_STATS_DISPLAY() +#endif + +#if LINK_STATS +#define LINK_STATS_INC(x) STATS_INC(x) +#define LINK_STATS_DISPLAY() stats_display_proto(&lwip_stats.link, "LINK") +#else +#define LINK_STATS_INC(x) +#define LINK_STATS_DISPLAY() +#endif + +#if MEM_STATS +#define MEM_STATS_AVAIL(x, y) lwip_stats.mem.x = y +#define MEM_STATS_INC(x) STATS_INC(mem.x) +#define MEM_STATS_INC_USED(x, y) STATS_INC_USED(mem, y, mem_size_t) +#define MEM_STATS_DEC_USED(x, y) lwip_stats.mem.x = (mem_size_t)((lwip_stats.mem.x) - (y)) +#define MEM_STATS_DISPLAY() stats_display_mem(&lwip_stats.mem, "HEAP") +#else +#define MEM_STATS_AVAIL(x, y) +#define MEM_STATS_INC(x) +#define MEM_STATS_INC_USED(x, y) +#define MEM_STATS_DEC_USED(x, y) +#define MEM_STATS_DISPLAY() +#endif + +#if MEMP_STATS +#define MEMP_STATS_DEC(x, i) STATS_DEC(memp[i]->x) +#define MEMP_STATS_DISPLAY(i) stats_display_memp(lwip_stats.memp[i], i) +#define MEMP_STATS_GET(x, i) STATS_GET(memp[i]->x) +#else +#define MEMP_STATS_DEC(x, i) +#define MEMP_STATS_DISPLAY(i) +#define MEMP_STATS_GET(x, i) 0 +#endif + +#if SYS_STATS +#define SYS_STATS_INC(x) STATS_INC(sys.x) +#define SYS_STATS_DEC(x) STATS_DEC(sys.x) +#define SYS_STATS_INC_USED(x) STATS_INC_USED(sys.x, 1, STAT_COUNTER) +#define SYS_STATS_DISPLAY() stats_display_sys(&lwip_stats.sys) +#else +#define SYS_STATS_INC(x) +#define SYS_STATS_DEC(x) +#define SYS_STATS_INC_USED(x) +#define SYS_STATS_DISPLAY() +#endif + +#if IP6_STATS +#define IP6_STATS_INC(x) STATS_INC(x) +#define IP6_STATS_DISPLAY() stats_display_proto(&lwip_stats.ip6, "IPv6") +#else +#define IP6_STATS_INC(x) +#define IP6_STATS_DISPLAY() +#endif + +#if ICMP6_STATS +#define ICMP6_STATS_INC(x) STATS_INC(x) +#define ICMP6_STATS_DISPLAY() stats_display_proto(&lwip_stats.icmp6, "ICMPv6") +#else +#define ICMP6_STATS_INC(x) +#define ICMP6_STATS_DISPLAY() +#endif + +#if IP6_FRAG_STATS +#define IP6_FRAG_STATS_INC(x) STATS_INC(x) +#define IP6_FRAG_STATS_DISPLAY() stats_display_proto(&lwip_stats.ip6_frag, "IPv6 FRAG") +#else +#define IP6_FRAG_STATS_INC(x) +#define IP6_FRAG_STATS_DISPLAY() +#endif + +#if MLD6_STATS +#define MLD6_STATS_INC(x) STATS_INC(x) +#define MLD6_STATS_DISPLAY() stats_display_igmp(&lwip_stats.mld6, "MLDv1") +#else +#define MLD6_STATS_INC(x) +#define MLD6_STATS_DISPLAY() +#endif + +#if ND6_STATS +#define ND6_STATS_INC(x) STATS_INC(x) +#define ND6_STATS_DISPLAY() stats_display_proto(&lwip_stats.nd6, "ND") +#else +#define ND6_STATS_INC(x) +#define ND6_STATS_DISPLAY() +#endif + +#if LOWPAN6_STATS +#define LOWPAN6_STATS_INC(x) STATS_INC(x) +#define LOWPAN6_STATS_DISPLAY() stats_display_lowpan6(&lwip_stats.lowpan6, "6LOWPAN") +#else +#define LOWPAN6_STATS_INC(x) +#define LOWPAN6_STATS_DISPLAY() +#endif + +#if MIB2_STATS +#define MIB2_STATS_INC(x) STATS_INC(x) +#else +#define MIB2_STATS_INC(x) +#endif + +#if DHCP6_STATS +#define DHCP6_STATS_INC(x) STATS_INC(x) +#define DHCP6_STATS_DISPLAY() stats_display_proto(&lwip_stats.dhcp6, "DHCP6") +#else +#define DHCP6_STATS_INC(x) +#define DHCP6_STATS_DISPLAY() +#endif + +#if LWIP_STATS /* LWIP_STATS */ + +/* Display of statistics */ +#if LWIP_STATS_DISPLAY +void stats_display(void); +void stats_display_proto(struct stats_proto *proto, const char *name); +void stats_display_igmp(struct stats_igmp *igmp, const char *name); +void stats_display_mem(struct stats_mem *mem, const char *name); +void stats_display_memp(struct stats_mem *mem, int index); +void stats_display_sys(struct stats_sys *sys); + +#if LOWPAN6_STATS +void stats_display_lowpan6(struct stats_lowpan6 *lowpan6, const char *name); +#endif + +#else /* LWIP_STATS_DISPLAY */ +#define stats_display() +#define stats_display_proto(proto, name) +#define stats_display_igmp(igmp, name) +#define stats_display_mem(mem, name) +#define stats_display_memp(mem, index) +#define stats_display_sys(sys) + +#if LOWPAN6_STATS +#define stats_display_lowpan6(lowpan6, name) +#endif +#endif /* LWIP_STATS_DISPLAY */ + +#if LWIP_STATS_API +/* + * Func Name: lwip_statsapi_get_ipv6_stats + */ +/** + * @ingroup stats + * @brief + * This API is used to get IPv6 statistics information. + * + * @param[in,out] ipv6 Memory to get the IPv6 statistics information. + * + * @return + * ERR_OK: On success \n + * ERR_ARG: If any parameter is invalid \n + * -1: If lwip is not started + * + * + * @note + * 1. The statistics information provided here will have information of all the interfaces. + */ +err_t lwip_statsapi_get_ipv6_stats(struct stats_proto *ipv6); + +/* + * Func Name: lwip_statsapi_get_icmpv6_stats + */ +/** + * @ingroup stats + * @brief + * This API is used to get icmpv6 statistics information. + * + * @param[in,out] icmpv6 Memory to get the icmpv6 statistics information. + * + * @return + * ERR_OK: On success \n + * ERR_ARG: If any parameter is invalid \n + * -1: If lwip is not started + * + * + * @note + * 1. The statistics information provided here will have information of all the interfaces. + */ +err_t lwip_statsapi_get_icmpv6_stats(struct stats_proto *icmpv6); + +/* + * Func Name: lwip_statsapi_get_nd6_stats + */ +/** + * @ingroup stats + * @brief + * This API is used to get neighbor discovery protoco statistics information. + * + * @param[in,out] nd6 Memory to get the neighbor discovery protocol statistics information. + * + * @return + * ERR_OK: On success \n + * ERR_ARG: If any parameter is invalid \n + * -1: If lwip is not started + * + * + * @note + * 1. The statistics information provided here will have information of all the interfaces. + */ +err_t lwip_statsapi_get_nd6_stats(struct stats_proto *nd6); + +/* + * Func Name: lwip_statsapi_get_tcp_stats + */ +/** + * @ingroup stats + * @brief + * This API is used to get tcp statistics information. + * + * @param[in,out] tcp Memory to get the tcp statistics information. + * + * @return + * ERR_OK: On success \n + * ERR_ARG: If any parameter is invalid \n + * -1: If lwip is not started + * + * + * @note + * 1. The statistics information provided here will have information of all the interfaces. + */ +err_t lwip_statsapi_get_tcp_stats(struct stats_proto *tcp); + +/* + * Func Name: lwip_statsapi_get_udp_stats + */ +/** + * @ingroup stats + * @brief + * This API is used to get udp statistics information. + * + * @param[in,out] udp Memory to get the udp statistics information. + * + * @return + * ERR_OK: On success \n + * ERR_ARG: If any parameter is invalid \n + * -1: If lwip is not started + * + * + * @note + * 1. The statistics information provided here will have information of all the interfaces. + */ +err_t lwip_statsapi_get_udp_stats(struct stats_proto *udp); + +/* + * Func Name: lwip_statsapi_get_lowpan6_stats + */ +/** + * @ingroup stats + * @brief + * This API is used to get lowpan statistics information. + * + * @param[in,out] lowpan6 Memory to get the lowpan6 statistics information. + * + * @return + * ERR_OK: On success \n + * ERR_ARG: If any parameter is invalid \n + * -1: If lwip is not started + * + * + * @note + * 1. The statistics information provided here will have information of all the interfaces. + */ +err_t lwip_statsapi_get_lowpan6_stats(struct stats_lowpan6 *lowpan6); +err_t lwip_statsapi_clear_lowpan6_stats(void); +#endif + +#endif /* LWIP_STATS */ + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_HDR_STATS_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/sys.h b/sdk_liteos/third_party/lwip_sack/include/lwip/sys.h new file mode 100644 index 0000000000000000000000000000000000000000..34aa43fd7bcf52173714701b8cb6d6c8f87dc67e --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/sys.h @@ -0,0 +1,513 @@ +/** + * @file + * OS abstraction layer + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + */ + +#ifndef LWIP_HDR_SYS_H +#define LWIP_HDR_SYS_H + +#include "lwip/opt.h" + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +#if NO_SYS + +/* For a totally minimal and standalone system, we provide null + definitions of the sys_ functions. */ +typedef u8_t sys_sem_t; +typedef u8_t sys_mutex_t; +typedef u8_t sys_mbox_t; +typedef u8_t sys_dual_mbox_t; + +#define sys_sem_new(s, c) ERR_OK +#define sys_sem_signal(s) +#define sys_sem_wait(s) +#define sys_arch_sem_wait(s, t) +#define sys_sem_free(s) +#define sys_sem_valid(s) 0 +#define sys_sem_valid_val(s) 0 +#define sys_sem_set_invalid(s) +#define sys_sem_set_invalid_val(s) +#define sys_mutex_new(mu) ERR_OK +#define sys_mutex_lock(mu) +#define sys_mutex_unlock(mu) +#define sys_mutex_free(mu) +#define sys_mutex_valid(mu) 0 +#define sys_mutex_set_invalid(mu) +#define sys_mbox_new(m, s) ERR_OK +#define sys_mbox_fetch(m, d) +#define sys_mbox_tryfetch(m, d) +#define sys_mbox_post(m, d) +#define sys_mbox_trypost(m, d) +#define sys_mbox_free(m) +#define sys_mbox_valid(m) +#define sys_mbox_valid_val(m) +#define sys_mbox_set_invalid(m) +#define sys_dual_mbox_valid(m) +#define sys_mbox_set_invalid_val(m) + +#define sys_dual_mbox_new(m, s) ERR_OK +#define sys_dual_mbox_fetch(m, d) +#define sys_dual_mbox_tryfetch(m, d) +#define sys_dual_mbox_post(m, d) +#define sys_dual_mbox_trypost(m, d) +#define sys_dual_mbox_post_priority(m, d) +#define sys_dual_mbox_free(m) +#define sys_dual_mbox_valid(m) +#define sys_dual_mbox_set_invalid(m) + +#define sys_thread_new(n, t, a, s, p) + +#define sys_msleep(t) + +/* Return code for Error from sys_thread_new and sys_arch_sem_wait */ +#define SYS_ARCH_ERROR 0xffffffffU + +#else /* NO_SYS */ + +/* Return code for Error from sys_thread_new and sys_arch_sem_wait */ +#define SYS_ARCH_ERROR 0xffffffffU + +/* Return code for timeouts from sys_arch_mbox_fetch and sys_arch_sem_wait */ +#define SYS_ARCH_TIMEOUT 0x7fffffffUL + +/* sys_mbox_tryfetch() returns SYS_MBOX_EMPTY if appropriate. + * For now we use the same magic value, but we allow this to change in future. + */ +#define SYS_MBOX_EMPTY SYS_ARCH_TIMEOUT + +#include "lwip/err.h" +#include "arch/sys_arch.h" + +/* Function prototype for thread functions */ +typedef void (*lwip_thread_fn)(void *arg); + +/* Function prototypes for functions to be implemented by platform ports + (in sys_arch.c) */ + +/* Mutex functions: */ + +/* Define LWIP_COMPAT_MUTEX if the port has no mutexes and binary semaphores + should be used instead */ +#ifndef LWIP_COMPAT_MUTEX +#define LWIP_COMPAT_MUTEX 0 +#endif + +#if LWIP_COMPAT_MUTEX +/* for old ports that don't have mutexes: define them to binary semaphores */ +#define sys_mutex_t sys_sem_t +#define sys_mutex_new(mutex) sys_sem_new(mutex, 1) +#define sys_mutex_lock(mutex) sys_sem_wait(mutex) +#define sys_mutex_unlock(mutex) sys_sem_signal(mutex) +#define sys_mutex_free(mutex) sys_sem_free(mutex) +#define sys_mutex_valid(mutex) sys_sem_valid(mutex) +#define sys_mutex_set_invalid(mutex) sys_sem_set_invalid(mutex) + +#else /* LWIP_COMPAT_MUTEX */ + +/* + * @ingroup sys_mutex + * Create a new mutex. + * Note that mutexes are expected to not be taken recursively by the lwIP code, + * so both implementation types (recursive or non-recursive) should work. + * @param mutex pointer to the mutex to create + * @return ERR_OK if successful, another err_t otherwise + */ +err_t sys_mutex_new(sys_mutex_t *mutex); +/* + * @ingroup sys_mutex + * Lock a mutex + * @param mutex the mutex to lock + */ +void sys_mutex_lock(sys_mutex_t *mutex); +/* + * @ingroup sys_mutex + * Unlock a mutex + * @param mutex the mutex to unlock + */ +void sys_mutex_unlock(sys_mutex_t *mutex); +/* + * @ingroup sys_mutex + * Delete a semaphore + * @param mutex the mutex to delete + */ +void sys_mutex_free(sys_mutex_t *mutex); +#ifndef sys_mutex_valid +/* + * @ingroup sys_mutex + * Check if a mutex is valid/allocated: return 1 for valid, 0 for invalid + */ +int sys_mutex_valid(sys_mutex_t *mutex); +#endif +#ifndef sys_mutex_set_invalid +/* + * @ingroup sys_mutex + * Set a mutex invalid so that sys_mutex_valid returns 0 + */ +void sys_mutex_set_invalid(sys_mutex_t *mutex); +#endif +#endif /* LWIP_COMPAT_MUTEX */ + +/* Semaphore functions: */ + +/* + * @ingroup sys_sem + * Create a new semaphore + * @param sem pointer to the semaphore to create + * @param count initial count of the semaphore + * @return ERR_OK if successful, another err_t otherwise + */ +err_t sys_sem_new(sys_sem_t *sem, u8_t count); +/* + * @ingroup sys_sem + * Signals a semaphore + * @param sem the semaphore to signal + */ +void sys_sem_signal(sys_sem_t *sem); +/* + * @ingroup sys_sem + * Wait for a semaphore for the specified timeout + * @param sem the semaphore to wait for + * @param timeout timeout in milliseconds to wait (0 = wait forever) + * @return time (in milliseconds) waited for the semaphore + * or SYS_ARCH_TIMEOUT on timeout + */ +u32_t sys_arch_sem_wait(sys_sem_t *sem, u32_t timeout); +/* + * @ingroup sys_sem + * Delete a semaphore + * @param sem semaphore to delete + */ +void sys_sem_free(sys_sem_t *sem); +/* Wait for a semaphore - forever/no timeout */ +#define sys_sem_wait(sem) sys_arch_sem_wait(sem, 0) +#ifndef sys_sem_valid +/* + * @ingroup sys_sem + * Check if a semaphore is valid/allocated: return 1 for valid, 0 for invalid + */ +int sys_sem_valid(sys_sem_t *sem); +#endif +#ifndef sys_sem_set_invalid +/* + * @ingroup sys_sem + * Set a semaphore invalid so that sys_sem_valid returns 0 + */ +void sys_sem_set_invalid(sys_sem_t *sem); +#endif +#ifndef sys_sem_valid_val +/* + * Same as sys_sem_valid() but taking a value, not a pointer + */ +#define sys_sem_valid_val(sem) sys_sem_valid(&(sem)) +#endif +#ifndef sys_sem_set_invalid_val +/* + * Same as sys_sem_set_invalid() but taking a value, not a pointer + */ +#define sys_sem_set_invalid_val(sem) sys_sem_set_invalid(&(sem)) +#endif + +#ifndef sys_msleep +/* + * @ingroup sys_misc + * Sleep for specified number of ms + */ +void sys_msleep(u32_t ms); /* only has a (close to) 1 ms resolution. */ +#endif + +/* Mailbox functions. */ + +/* + * @ingroup sys_mbox + * Create a new mbox of specified size + * @param mbox pointer to the mbox to create + * @param size (minimum) number of messages in this mbox + * @return ERR_OK if successful, another err_t otherwise + */ +err_t sys_mbox_new_ext(sys_mbox_t *mbox, int size, unsigned char is_auto_expand); +#define sys_mbox_new(_mb, size) sys_mbox_new_ext((_mb), (size), MBOX_NO_EXPAND) +#define sys_mbox_new_auto_expand(_mb, size) sys_mbox_new_ext((_mb), (size), MBOX_AUTO_EXPAND) + +/* + * @ingroup sys_mbox + * Post a message to an mbox - may not fail + * -> blocks if full, only used from tasks not from ISR + * @param mbox mbox to posts the message + * @param msg message to post (ATTENTION: can be NULL) + */ +void sys_mbox_post(sys_mbox_t *mbox, void *msg); +#ifdef DUAL_MBOX +err_t sys_dual_mbox_new(sys_dual_mbox_t *dmbox, int size); +void sys_dual_mbox_post(sys_dual_mbox_t *dmbox, void *msg); +void sys_dual_mbox_post_priority(sys_dual_mbox_t *dmbox, void *msg); +#endif /* DUAL_MBOX */ + +/* + * @ingroup sys_mbox + * Try to post a message to an mbox - may fail if full or ISR + * @param mbox mbox to posts the message + * @param msg message to post (ATTENTION: can be NULL) + */ +err_t sys_mbox_trypost(sys_mbox_t *mbox, void *msg); +#ifdef DUAL_MBOX +err_t sys_dual_mbox_trypost(sys_dual_mbox_t *dmbox, void *msg); +#endif /* DUAL_MBOX */ + +u32_t sys_arch_mbox_fetch_ext(sys_mbox_t *mbox, void **msg, u32_t timeout, u8_t ignore_timeout); +#ifdef DUAL_MBOX +u32_t sys_arch_dual_mbox_fetch_ext(sys_dual_mbox_t *dmbox, void **msg, u32_t timeout, u8_t ignore_timeout); +#endif /* DUAL_MBOX */ + +/* Wait for a new message to arrive in the mbox + * @param mbox mbox to get a message from + * @param msg pointer where the message is stored + * @param timeout maximum time (in milliseconds) to wait for a message (0 = wait forever) + * @return time (in milliseconds) waited for a message, may be 0 if not waited + or SYS_ARCH_TIMEOUT on timeout + * The returned time has to be accurate to prevent timer jitter! + */ +u32_t sys_arch_mbox_fetch(sys_mbox_t *mbox, void **msg, u32_t timeout); +#ifdef DUAL_MBOX +u32_t sys_arch_dual_mbox_fetch(sys_dual_mbox_t *dmbox, void **msg, u32_t timeout); +#endif /* DUAL_MBOX */ + +/* Allow port to override with a macro, e.g. special timout for sys_arch_mbox_fetch() */ +#define sys_arch_mbox_tryfetch(mbox, msg) sys_arch_mbox_fetch_ext(mbox, msg, 1, 1) +#ifdef DUAL_MBOX +#define sys_arch_dual_mbox_tryfetch(dmbox, msg) sys_arch_dual_mbox_fetch_ext(dmbox, msg, 1, 1) +#endif /* DUAL_MBOX */ + +/* For now, we map straight to sys_arch implementation. */ +#define sys_mbox_tryfetch(mbox, msg) sys_arch_mbox_tryfetch(mbox, msg) +#ifdef DUAL_MBOX +#define sys_dual_mbox_tryfetch(dmbox, msg) sys_arch_dual_mbox_tryfetch(dmbox, msg) +#endif /* DUAL_MBOX */ +/* + * @ingroup sys_mbox + * Delete an mbox + * @param mbox mbox to delete + */ +void sys_mbox_free(sys_mbox_t *mbox); +#ifdef DUAL_MBOX +void sys_dual_mbox_free(sys_dual_mbox_t *dmbox); +#endif /* DUAL_MBOX */ + +#define sys_mbox_fetch(mbox, msg) sys_arch_mbox_fetch(mbox, msg, 0) +#ifdef DUAL_MBOX +#define sys_dual_mbox_fetch(dmbox, msg) sys_arch_dual_mbox_fetch(dmbox, msg, 0) +#endif /* DUAL_MBOX */ + +#ifndef sys_mbox_valid +/* + * @ingroup sys_mbox + * Check if an mbox is valid/allocated: return 1 for valid, 0 for invalid + */ +int sys_mbox_valid(sys_mbox_t *mbox); +#endif +#ifndef sys_mbox_set_invalid +/* + * @ingroup sys_mbox + * Set an mbox invalid so that sys_mbox_valid returns 0 + */ +void sys_mbox_set_invalid(sys_mbox_t *mbox); +#endif + +#ifndef sys_dual_mbox_valid +/* Check if an mbox is valid/allocated: return 1 for valid, 0 for invalid */ +int sys_dual_mbox_valid(sys_dual_mbox_t *dmbox); +#endif +#ifndef sys_dual_mbox_set_invalid +/* Set an mbox invalid so that sys_mbox_valid returns 0 */ +void sys_dual_mbox_set_invalid(sys_dual_mbox_t *dmbox); +#endif + +#ifndef sys_mbox_valid_val +/* + * Same as sys_mbox_valid() but taking a value, not a pointer + */ +#define sys_mbox_valid_val(mbox) sys_mbox_valid(&(mbox)) +#endif +#ifndef sys_mbox_set_invalid_val +/* + * Same as sys_mbox_set_invalid() but taking a value, not a pointer + */ +#define sys_mbox_set_invalid_val(mbox) sys_mbox_set_invalid(&(mbox)) +#endif + +/* + * @ingroup sys_misc + * The only thread function: + * Creates a new thread + * ATTENTION: although this function returns a value, it MUST NOT FAIL (ports have to assert this!) + * @param name human-readable name for the thread (used for debugging purposes) + * @param thread thread-function + * @param arg parameter passed to 'thread' + * @param stacksize stack size in bytes for the new thread (may be ignored by ports) + * @param prio priority of the new thread (may be ignored by ports) */ +sys_thread_t sys_thread_new(const char *name, lwip_thread_fn thread, void *arg, int stacksize, int prio); + +#endif /* NO_SYS */ + +/* sys_init() must be called before anything else. */ +void sys_init(void); + +#ifndef sys_jiffies +/* + * Ticks/jiffies since power up. + */ +u32_t sys_jiffies(void); +#endif + +/* + * @ingroup sys_time + * Returns the current time in milliseconds, + * may be the same as sys_jiffies or at least based on it. + */ +u32_t sys_now(void); + +/* Critical Region Protection */ +/* These functions must be implemented in the sys_arch.c file. + In some implementations they can provide a more light-weight protection + mechanism than using semaphores. Otherwise semaphores can be used for + implementation */ +#ifndef SYS_ARCH_PROTECT +/* SYS_LIGHTWEIGHT_PROT + * define SYS_LIGHTWEIGHT_PROT in lwipopts.h if you want inter-task protection + * for certain critical regions during buffer allocation, deallocation and memory + * allocation and deallocation. + */ +#if SYS_LIGHTWEIGHT_PROT + +/* + * @ingroup sys_prot + * SYS_ARCH_DECL_PROTECT + * declare a protection variable. This macro will default to defining a variable of + * type sys_prot_t. If a particular port needs a different implementation, then + * this macro may be defined in sys_arch.h. + */ +#define SYS_ARCH_DECL_PROTECT(lev) sys_prot_t lev +/* + * @ingroup sys_prot + * SYS_ARCH_PROTECT + * Perform a "fast" protect. This could be implemented by + * disabling interrupts for an embedded system or by using a semaphore or + * mutex. The implementation should allow calling SYS_ARCH_PROTECT when + * already protected. The old protection level is returned in the variable + * "lev". This macro will default to calling the sys_arch_protect() function + * which should be implemented in sys_arch.c. If a particular port needs a + * different implementation, then this macro may be defined in sys_arch.h + */ +#define SYS_ARCH_PROTECT(lev) lev = sys_arch_protect() +/* + * @ingroup sys_prot + * SYS_ARCH_UNPROTECT + * Perform a "fast" set of the protection level to "lev". This could be + * implemented by setting the interrupt level to "lev" within the MACRO or by + * using a semaphore or mutex. This macro will default to calling the + * sys_arch_unprotect() function which should be implemented in + * sys_arch.c. If a particular port needs a different implementation, then + * this macro may be defined in sys_arch.h + */ +#define SYS_ARCH_UNPROTECT(lev) sys_arch_unprotect(lev) +sys_prot_t sys_arch_protect(void); +void sys_arch_unprotect(sys_prot_t pval); + +#else + +#define SYS_ARCH_DECL_PROTECT(lev) +#define SYS_ARCH_PROTECT(lev) +#define SYS_ARCH_UNPROTECT(lev) + +#endif /* SYS_LIGHTWEIGHT_PROT */ + +#endif /* SYS_ARCH_PROTECT */ + +/* + * Macros to set/get and increase/decrease variables in a thread-safe way. + * Use these for accessing variable that are used from more than one thread. + */ + +#ifndef SYS_ARCH_INC +#define SYS_ARCH_INC(var, val) do { \ + SYS_ARCH_DECL_PROTECT(old_level); \ + SYS_ARCH_PROTECT(old_level); \ + var += val; \ + SYS_ARCH_UNPROTECT(old_level); \ + } while (0) +#endif /* SYS_ARCH_INC */ + +#ifndef SYS_ARCH_DEC +#define SYS_ARCH_DEC(var, val) do { \ + SYS_ARCH_DECL_PROTECT(old_level); \ + SYS_ARCH_PROTECT(old_level); \ + var -= val; \ + SYS_ARCH_UNPROTECT(old_level); \ + } while (0) +#endif /* SYS_ARCH_DEC */ + +#ifndef SYS_ARCH_GET +#define SYS_ARCH_GET(var, ret) do { \ + SYS_ARCH_DECL_PROTECT(old_level); \ + SYS_ARCH_PROTECT(old_level); \ + ret = var; \ + SYS_ARCH_UNPROTECT(old_level); \ + } while (0) +#endif /* SYS_ARCH_GET */ + +#ifndef SYS_ARCH_SET +#define SYS_ARCH_SET(var, val) do { \ + SYS_ARCH_DECL_PROTECT(old_level); \ + SYS_ARCH_PROTECT(old_level); \ + var = val; \ + SYS_ARCH_UNPROTECT(old_level); \ + } while (0) +#endif /* SYS_ARCH_SET */ + +#ifndef SYS_ARCH_LOCKED +#define SYS_ARCH_LOCKED(code) do { \ + SYS_ARCH_DECL_PROTECT(old_level); \ + SYS_ARCH_PROTECT(old_level); \ + code; \ + SYS_ARCH_UNPROTECT(old_level); \ + } while (0) +#endif /* SYS_ARCH_LOCKED */ + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_HDR_SYS_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/tcp.h b/sdk_liteos/third_party/lwip_sack/include/lwip/tcp.h new file mode 100644 index 0000000000000000000000000000000000000000..365b936e57f7e416aa5a1b4e5ba67c0f4e4c9e5f --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/tcp.h @@ -0,0 +1,861 @@ +/** + * @file + * TCP API (to be used from TCPIP thread)\n + * See also @ref tcp_raw + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_TCP_H +#define LWIP_HDR_TCP_H + +#include "lwip/opt.h" + +#if LWIP_TCP /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/tcpbase.h" +#include "lwip/mem.h" +#include "lwip/pbuf.h" +#include "lwip/ip.h" +#include "lwip/icmp.h" +#include "lwip/err.h" +#include "lwip/ip6.h" +#include "lwip/ip6_addr.h" + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +struct tcp_pcb; +struct tcp_pcb_listen; + +/** + * @brief Function prototype for TCP accept callback functions. Called when a new + * connection can be accepted on a listening PCB. + * + * @param arg Indicates an additional argument to pass to the callback function (Refer to tcp_arg()). + * @param newpcb Indicates the new connection PCB. + * @param err Indicates an error code if there has been an error. + * This function returns ERR_ABRT if you have called tcp_abort() from within the + * callback function. + */ +typedef err_t (*tcp_accept_fn)(void *arg, struct tcp_pcb *newpcb, err_t err); + +/** @brief Function prototype for TCP receive callback functions. Called when data has + * been received. + * + * @param arg Indicates an additional argument to pass to the callback function (Refer to tcp_arg()). + * @param tpcb Indicates the connection PCB which received data. + * @param p Indicates the received data, or NULL when the connection has been closed. + * @param err Indicates an error code if there is an error in receiving. + * This function returns ERR_ABRT if you have called tcp_abort from within the + * callback function. + */ +typedef err_t (*tcp_recv_fn)(void *arg, struct tcp_pcb *tpcb, + struct pbuf *p, err_t err); + +/** @brief Function prototype for TCP sent callback functions. Called when sent data has + * been acknowledged by the remote side. Used to free corresponding resources. + * This also means that the PCB has now space available to send new data. + * + * @param arg Indicates an additional argument to pass to the callback function (Refer to tcp_arg()). + * @param tpcb Indicates the connection PCB for which data has been acknowledged. + * @param len Indicates the amount of bytes acknowledged. + * @return ERR_OK: try to send some data by calling tcp_output() + * This function returns ERR_ABRT if you have called tcp_abort() from within the + * callback function. + */ +typedef err_t (*tcp_sent_fn)(void *arg, struct tcp_pcb *tpcb, + u16_t len); + +/** @brief Function prototype for TCP poll callback functions. Called periodically as + * specified by tcp_poll(). + * + * @param arg Indicates an additional argument to pass to the callback function + (Refer to tcp_arg()). + * @param tpcb Indicates the TCP PCB. + * @return ERR_OK: try to send some data by calling tcp_output() + * This function returns ERR_ABRT if you have called tcp_abort() from within the + * callback function. + */ +typedef err_t (*tcp_poll_fn)(void *arg, struct tcp_pcb *tpcb); + +/** @brief Function prototype for TCP error callback functions. Called when the PCB + * receives a RST or is unexpectedly closed for any other reason. + * + * @note The corresponding PCB is already freed when this callback is called. + * + * @param arg Indicates an additional argument to pass to the callback function + (Refer to tcp_arg()). + * @param err Provides an error code to indicate why the PCB has been closed. \n + * ERR_ABRT: Aborted through tcp_abort or by a TCP timer. \n + * ERR_RST: The connection was reset by the remote host. + */ +typedef void (*tcp_err_fn)(void *arg, err_t err); + +/** @brief Function prototype for TCP connected callback functions. Called when a PCB + * is connected to the remote side after initiating a connection attempt by + * calling tcp_connect(). + * + * @param arg Indicates an additional argument to pass to the callback function + (Refer to tcp_arg()). + * @param tpcb Indicates the connection PCB which is connected. + * @param err Indicates an unused error code, always ERR_OK currently. + * Only return ERR_ABRT if you have called tcp_abort from within the + * callback function + * + * @note When a connection attempt fails, the error callback is currently called. + */ +typedef err_t (*tcp_connected_fn)(void *arg, struct tcp_pcb *tpcb, err_t err); + +#if DRIVER_STATUS_CHECK +typedef void (*tcp_event_sndplus_fn)(void *arg, struct tcp_pcb *tpcb); +#endif + +#if LWIP_WND_SCALE +/** Recv Window Scaling. Announce Window Size. */ +#define RCV_WND_SCALE(pcb, wnd) (((wnd) >> (pcb)->rcv_scale)) +/** Send Window Scaling. Sender Window Size */ +#define SND_WND_SCALE(pcb, wnd) (((tcpwnd_size_t)(wnd) << (pcb)->snd_scale)) +/** Window Scaling. Actual Window Size. */ +#define ACTUAL_WND_SIZE(pcb, wnd) ((tcpwnd_size_t)((wnd) >> (pcb)->rcv_scale) << (pcb)->rcv_scale) +/** TCP Window Size. */ +#define TCPWND16(x) ((u16_t)LWIP_MIN((x), 0xFFFF)) +/** TCP maximum window size. */ +#define TCP_WND_MAX(pcb) ((tcpwnd_size_t)(((pcb)->flags & TF_WND_SCALE) ? TCP_WND : TCPWND16(TCP_WND))) +#else /* LWIP_WND_SCALE */ +#define RCV_WND_SCALE(pcb, wnd) (wnd) +#define SND_WND_SCALE(pcb, wnd) (wnd) +#define TCPWND16(x) (x) +#define TCP_WND_MAX(pcb) TCP_WND +#endif /* LWIP_WND_SCALE */ + +typedef u32_t tcpflags_t; + +#define TCP_ALLFLAGS 0xFFFFFFFFU +#define SNDQUEUE_MAX 0xFFFF +#define SNDQUEUE_MIN 5 + +/* Increments a tcpwnd_size_t and holds at max value rather than rollover */ +#define TCP_WND_INC(wnd, inc) do { \ + if ((tcpwnd_size_t)((wnd) + (inc)) >= (wnd)) { \ + (wnd) = (tcpwnd_size_t)((wnd) + (inc)); \ + } else { \ + (wnd) = (tcpwnd_size_t)-1; \ + } \ +} while (0) + +#define TCP_WND_DEC(wnd, dec, mss) do { \ + if ((wnd) >= (dec) && (wnd) >= (mss)) { \ + (wnd) = (tcpwnd_size_t)(wnd - (dec)); \ + } else { \ + (wnd) = (mss); \ + } \ +} while (0) + +#ifndef LWIP_INITIAL_CWND_OVERRIDE +/* + [RFC 5681] [3.1. Slow Start and Congestion Avoidance] + IW, the initial value of cwnd, MUST be set using the following guidelines as an upper bound. +*/ +#define LWIP_TCP_CALC_INITIAL_CWND(SMSS, IW) do { \ + if ((SMSS) > 2190) { \ + (IW) = (tcpwnd_size_t)(2 * (SMSS)); \ + } else if (((SMSS) > 1095) && ((SMSS) <= 2190)) { \ + (IW) = (tcpwnd_size_t)(3 * (SMSS)); \ + } else if ((SMSS) <= 1095) { \ + (IW) = (tcpwnd_size_t)(4 * (SMSS)); \ + } \ +} while (0) +#else +#define LWIP_TCP_CALC_INITIAL_CWND(SMSS, IW) do { \ + IW = (tcpwnd_size_t)((LWIP_INITIAL_CWND_OVERRIDE) * (SMSS)); \ +} while (0) +#endif + +/* Increments a wnd * mss and holds at max value rather than rollover */ +#define TCP_CALC_SSTHRESH(pcb, ssthresh, wnd, mss) do { \ + if (((u64_t)(wnd) * (mss)) < TCP_WND_MAX(pcb)) { \ + (ssthresh) = (tcpwnd_size_t)((wnd) * (mss)); \ + } else { \ + (ssthresh) = TCP_WND_MAX(pcb); \ + } \ +} while (0) + +#ifndef LWIP_CONGCNTRL_DUPACK_THRESH +/** Congestion Control duplicate Acknowledgement Threshold */ +#define DUPACK_THRESH 3 +#else +#define DUPACK_THRESH LWIP_CONGCNTRL_DUPACK_THRESH +#endif + +#ifndef LWIP_CONGCNTRL_INITIAL_SSTHRESH +/** Initial Congestion Control Slow Start Threshold. */ +#define INITIAL_SSTHRESH 40 +#else +#define INITIAL_SSTHRESH LWIP_CONGCNTRL_INITIAL_SSTHRESH +#endif + +#if DRIVER_STATUS_CHECK +#define DRV_READY 1 +#define DRV_NOT_READY 0 +#endif + +/* Indicates that this pbuf includes a TCP FIN flag and post to mbox is failed */ +#define TCP_PBUF_FLAG_TCP_FIN_RECV_SYSPOST_FAIL 0x01U + +/* Adding for SACK */ +#if LWIP_SACK +struct _sack_seq { + struct _sack_seq *next; + u32_t left; + u32_t right; + u32_t order; +}; +#endif + +#if LWIP_SACK_PERF_OPT +struct tcp_sack_fast_rxmited { + struct tcp_sack_fast_rxmited *next; + struct tcp_seg *seg; +}; +#endif + +#if LWIP_SO_SNDBUF +#define LWIP_SO_SNDBUF_DECL tcpwnd_size_t snd_buf_static; /* Configured send buffer size */ +#else +#define LWIP_SO_SNDBUF_DECL +#endif /* LWIP_SO_SNDBUF */ + +/** Function prototype for deallocation of arguments. Called *just before* the + * pcb is freed, so don't expect to be able to do anything with this pcb! + * + * @param id ext arg id (allocated via @ref tcp_ext_arg_alloc_id) + * @param data pointer to the data (set via @ref tcp_ext_arg_set before) + */ +typedef void (*tcp_extarg_callback_pcb_destroyed_fn)(u8_t id, void *data); + +/** Function prototype to transition arguments from a listening pcb to an accepted pcb + * + * @param id ext arg id (allocated via @ref tcp_ext_arg_alloc_id) + * @param lpcb the listening pcb accepting a connection + * @param cpcb the newly allocated connection pcb + * @return ERR_OK if OK, any error if connection should be dropped + */ +typedef err_t (*tcp_extarg_callback_passive_open_fn)(u8_t id, struct tcp_pcb_listen *lpcb, struct tcp_pcb *cpcb); + +/** A table of callback functions that is invoked for ext arguments */ +struct tcp_ext_arg_callbacks { + /** @ref tcp_extarg_callback_pcb_destroyed_fn */ + tcp_extarg_callback_pcb_destroyed_fn destroy; + /** @ref tcp_extarg_callback_passive_open_fn */ + tcp_extarg_callback_passive_open_fn passive_open; +}; + +#define LWIP_TCP_PCB_NUM_EXT_ARG_ID_INVALID 0xFF + +#if LWIP_TCP_PCB_NUM_EXT_ARGS +/* This is the structure for ext args in tcp pcbs (used as array) */ +struct tcp_pcb_ext_args { + const struct tcp_ext_arg_callbacks *callbacks; + void *data; +}; +/* This is a helper define to prevent zero size arrays if disabled */ +#define TCP_PCB_EXTARGS struct tcp_pcb_ext_args ext_args[LWIP_TCP_PCB_NUM_EXT_ARGS]; +#else +#define TCP_PCB_EXTARGS +#endif + +/** + * Indicates members common to struct tcp_pcb and struct tcp_listen_pcb. + */ +#define TCP_PCB_COMMON(type) \ + type *next; /* for the linked list */ \ + void *callback_arg; \ + enum tcp_state state; /* TCP state */ \ + u8_t prio; \ + /* ports are in host byte order */ \ + u16_t local_port; \ + /* Configured send buffer size */ \ + LWIP_SO_SNDBUF_DECL + +#if LWIP_TCP_TLP_SUPPORT + +#define TCP_TLP_MAX_PROBE_CNT 2 + +#define LWIP_TCP_TLP_CLEAR_VARS(_pcb) do { \ + _pcb->tlp_pto_cnt = 0; \ + _pcb->tlp_rtx_out = 0; \ + _pcb->tlp_high_rxt = 0; \ + _pcb->tlp_time_stamp = 0; \ +} while (0) + +#define LWIP_TCP_TLP_WCDELACKT 200 /* RECOMMENDED value is 200ms */ +#endif /* LWIP_TCP_TLP_SUPPORT */ + +/** Indicates the TCP protocol control block for listening PCBs. */ +struct tcp_pcb_listen { + /** Common members of all PCB types */ + IP_PCB; + /** Protocol specific PCB members */ + TCP_PCB_COMMON(struct tcp_pcb_listen) + +#if LWIP_CALLBACK_API + /* Function to call when a listener has been connected. */ + tcp_accept_fn accept; +#endif /* LWIP_CALLBACK_API */ + +#if LWIP_SO_PRIORITY + prio_t priority; +#endif /* LWIP_SO_PRIORITY */ + +#if TCP_LISTEN_BACKLOG + u8_t backlog; + u8_t accepts_pending; +#endif /* TCP_LISTEN_BACKLOG */ +}; + +/** Delayed ACK. */ +#define TF_ACK_DELAY 0x01U +/** Immediate ACK. */ +#define TF_ACK_NOW 0x02U +/** In fast recovery. */ +#define TF_INFR 0x04U +/** If this is set, tcp_close failed to enqueue the FIN (retried in tcp_tmr) */ +#define TF_CLOSEPEND 0x08U +/** Rx is closed by tcp_shutdown */ +#define TF_RXCLOSED 0x10U +/** Connection was closed locally (FIN segment enqueued). */ +#define TF_FIN 0x20U +/** Disable Nagle algorithm */ +#define TF_NODELAY 0x40U +/** Nagle algorithm is enabled. memerr. Try to output to prevent delayed ACK to happen */ +#define TF_NAGLEMEMERR 0x80U +#if LWIP_WND_SCALE +/** Window Scale option enabled */ +#define TF_WND_SCALE 0x0100U +#endif +#if TCP_LISTEN_BACKLOG +/** If this is set, a connection PCB has increased the backlog on its listener */ +#define TF_BACKLOGPEND 0x0200U +#endif +#if LWIP_TCP_TIMESTAMPS +/** Timestamp option enabled */ +#define TF_TIMESTAMP 0x0400U +#endif +/** Tx closed by tcp_shutdown */ +#define TF_TXCLOSED 0x0800U + +/* TCP flags for New Reno */ +#define TF_INFR_PACK ((tcpflags_t)0x1000U) /* Partial ACK recved flag */ +#define TF_RTO ((tcpflags_t)0x2000U) /* RTO timer has fired, in-flight data moved to unsent and being retransmitted */ +#define TF_INFR_FPACK ((tcpflags_t)0x4000U) /* Flag for wait for first parital ack */ + +#if LWIP_SACK +/** TCP SACK option enabled. */ +#define TF_SACK ((tcpflags_t)0x10000U) +/** In SACK based Fast retransmit & loss recovery algorithm */ +#define TF_IN_SACK_FRLR ((tcpflags_t)0x20000U) +/** From loss recovery, it entered to Retrasnmit timeout state. */ +#define TF_IN_SACK_RTO ((tcpflags_t)0x40000U) +#endif + +#if DRIVER_STATUS_CHECK +#define TF_RST_ON_DRV_WAKE ((tcpflags_t)0x80000U) /* From loss receovery it entered to Retrasnmit timeout state */ +#endif + +/** the TCP protocol control block */ +struct tcp_pcb { + /** common PCB members */ + IP_PCB; + /** protocol specific PCB members */ + TCP_PCB_COMMON(struct tcp_pcb) + + /* ports are in host byte order */ + u16_t remote_port; + u16_t pad1; + + tcpflags_t flags; + +#if DRIVER_STATUS_CHECK + /* Netif driver status */ + u8_t drv_status; /* 0 - Driver not ready. 1- Driver is ready */ + u8_t pad0; +#endif + + /* the rest of the fields are in host byte order + as we have to do some math with them */ + /* Timers */ + u8_t polltmr, pollinterval; + u8_t last_timer; + u32_t tmr; + + /* receiver variables */ + u32_t rcv_nxt; /* next seqno expected */ + tcpwnd_size_t rcv_wnd; /* receiver window available */ + tcpwnd_size_t rcv_ann_wnd; /* receiver window to announce */ + u32_t rcv_ann_right_edge; /* announced right edge of window */ + + /* Retransmission timer. */ + s16_t rtime; + + u16_t mss; /* maximum segment size, the real value used to do segmentation */ + u16_t rcv_mss; /* mss from peer side */ + + u16_t pad4; + + /* RTT (round trip time) estimation variables */ + u32_t rttest; /* The start time of RTT sample in ms, the granularity is system tick */ + u32_t rtseq; /* sequence number being timed */ + s16_t sa; /* smoothed round-trip time, 8 times of SRTT in RFC6298 */ + s16_t sv; /* round-trip time variation, 4 times of RTTVAR in RFC6298 */ + + s16_t rto; /* retransmission time-out (in ticks of TCP_SLOW_INTERVAL) */ + u8_t nrtx; /* number of retransmissions */ + + /* fast retransmit/recovery */ + u8_t dupacks; + + u16_t pad5; + + u32_t lastack; /* Highest acknowledged seqno, also knowns SND.UNA */ + + /* congestion avoidance/control variables */ + tcpwnd_size_t iw; + tcpwnd_size_t cwnd; + tcpwnd_size_t ssthresh; + u32_t rto_end; + + /* sender variables */ + u32_t snd_nxt; /* next new seqno to be sent */ + u32_t snd_sml; /* The last byte of the most recently transmitted small packet */ + u32_t snd_wl1, snd_wl2; /* Sequence and acknowledgement numbers of last + window update. */ + u32_t snd_lbb; /* Sequence number of next byte to be buffered. */ + tcpwnd_size_t snd_wnd; /* sender window */ + tcpwnd_size_t snd_wnd_max; /* the maximum sender window announced by the remote host */ + + tcpwnd_size_t snd_buf; /* Available buffer space for sending (in bytes). */ + + tcpwnd_size_t bytes_acked; + +#if LWIP_WND_SCALE +#define TCP_SNDQUEUELEN_OVERFLOW (0x03ffffffU - 3) +#else /* LWIP_WND_SCALE */ +#define TCP_SNDQUEUELEN_OVERFLOW (0xffffU - 3) +#endif /* LWIP_WND_SCALE */ + tcpwnd_size_t snd_queuelen; /* Available buffer space for sending (in tcp_segs). */ + + tcpwnd_size_t snd_queuelen_max; + tcpwnd_size_t snd_queuelen_lowat; + tcpwnd_size_t snd_buf_lowat; + +#if TCP_OVERSIZE + /* Extra bytes available at the end of the last pbuf in unsent. */ + u16_t unsent_oversize; + u16_t pad2; +#endif /* TCP_OVERSIZE */ + + /* These are ordered by sequence number: */ + struct tcp_seg *unsent; /* Unsent (queued) segments. */ + struct tcp_seg *unacked; /* Sent but unacknowledged segments. */ +#if TCP_QUEUE_OOSEQ + struct tcp_seg *ooseq; /* Received out of sequence segments. */ +#endif /* TCP_QUEUE_OOSEQ */ + + struct pbuf *refused_data; /* Data previously received but not yet taken by upper layer */ + +#if LWIP_CALLBACK_API || TCP_LISTEN_BACKLOG + struct tcp_pcb_listen *listener; +#endif /* LWIP_CALLBACK_API || TCP_LISTEN_BACKLOG */ + +#if LWIP_CALLBACK_API + /* Function to be called when more send buffer space is available. */ + tcp_sent_fn sent; + /* Function to be called when (in-sequence) data has arrived. */ + tcp_recv_fn recv; + /* Function to be called when a connection has been set up. */ + tcp_connected_fn connected; + /* Function which is called periodically. */ + tcp_poll_fn poll; + /* Function to be called whenever a fatal error occurs. */ + tcp_err_fn errf; +#endif /* LWIP_CALLBACK_API */ + +#if DRIVER_STATUS_CHECK + tcp_event_sndplus_fn sndplus; +#endif + +#if LWIP_TCP_TIMESTAMPS + u32_t ts_lastacksent; + u32_t ts_recent; +#endif /* LWIP_TCP_TIMESTAMPS */ + + /* idle time before KEEPALIVE is sent */ + u32_t keep_idle; +#if LWIP_TCP_KEEPALIVE + u32_t keep_intvl; + u32_t keep_cnt; +#endif /* LWIP_TCP_KEEPALIVE */ + + /* Persist timer counter */ + u8_t persist_cnt; + /* Persist timer back-off */ + u8_t persist_backoff; + /* Number of persist probes, used for timeout calculation */ + u8_t persist_probe; + /* KEEPALIVE counter */ + u8_t keep_cnt_sent; + + u32_t last_payload_len; + + u32_t fast_recovery_point; /* snd_nxt when enter fast recovery */ + +#if LWIP_SACK + struct _sack_seq *sack_seq; + /* SACK based pipe algorthim Changes */ + /* Pipe to hold the number of octets available in network */ + u32_t pipe; + /* Recovery point for stopping loss recovery phase */ + u32_t recovery_point; + /* highest octet covered by any received SACK block */ + u32_t high_sacked; + + /* Loss recovery check needs to be started from this seg instead of pcb->unacked */ + /* This excludes the rexmited and sacked seg from pcb->unacked */ + /* That means, next_seg_for_lr points to first unsacked and not retransmitted seg */ + /* Optimization of SACK based pipe algorthim */ + struct tcp_seg *next_seg_for_lr; + + /* highest data trasnfered so far, equivalent to snd_nxt */ + u32_t high_data; + /* highest octet retransmitted so far, as part of SACK based loss recovery algorithm */ + u32_t high_rxt; + /* Rescure rxt as per loss recovery algorithm */ + u32_t rescue_rxt; + + u32_t num_sacks; + u32_t ooseq_cnt; + +#if LWIP_SACK_PERF_OPT + u32_t pkt_seq_num; /* packet order on which they are transmitted out of stack */ + u32_t high_sacked_pkt_seq; + struct tcp_sack_fast_rxmited *fr_segs; /* List of fast retransmitted segments */ + /* + * The latest fast retransmitted segment. This stores the latest + * fast retransmitted segment so that when more segments are retransmitted, + * it can be appended to this segmetn without iterating whole list + */ + struct tcp_sack_fast_rxmited *last_frseg; +#if LWIP_SACK_CWND_OPT + tcpwnd_size_t recover_cwnd; + tcpwnd_size_t recover_ssthresh; +#endif /* LWIP_SACK_CWND_OPT */ +#endif /*LWIP_SACK_PERF_OPT*/ + u32_t sacked; /* The total SACKed segments count */ + +#if LWIP_FACK_THRESHOLD_BASED_FR + u32_t fack; +#endif /* LWIP_FACK_THRESHOLD_BASED_FR */ + +#if LWIP_TCP_TLP_SUPPORT + u8_t tlp_pto_cnt; /* Consecutive PTOs */ + u8_t tlp_rtx_out; /* the number of unacknowledged TLP retransmissions in current TLP episode */ + u32_t tlp_high_rxt; /* SND.NXT at the time it starts doing TLP transmissions during a given TLP episode */ + u32_t tlp_time_stamp; /* PTO trigger time in ms. 0 is one specially value which means PTO is not scheduled */ +#endif /* LWIP_TCP_TLP_SUPPORT */ +#endif /* LWIP_SACK */ + +#if LWIP_SO_PRIORITY + prio_t priority; +#endif /* LWIP_SO_PRIORITY */ + +#if LWIP_WND_SCALE + u8_t snd_scale; + u8_t rcv_scale; +#endif + + u8_t tcp_pcb_flag; +}; + +#if LWIP_EVENT_API + +enum lwip_event { + LWIP_EVENT_ACCEPT, + LWIP_EVENT_SENT, + LWIP_EVENT_RECV, + LWIP_EVENT_CONNECTED, + LWIP_EVENT_POLL, + LWIP_EVENT_ERR +}; + +err_t lwip_tcp_event(void *arg, struct tcp_pcb *pcb, + enum lwip_event, + struct pbuf *p, + u16_t size, + err_t err); + +#endif /* LWIP_EVENT_API */ + +#if LWIP_API_RICH +/* Application program's interface: */ +/** + * @ingroup tcp_raw + * Creates a new TCP protocol control block but does not place it on + * any of the TCP PCB lists. + * The PCB is not put on any list until binding using tcp_bind(). + * + * @note Maybe there should be a idle TCP PCB list where these + * PCBs are put on. Port reservation using tcp_bind() is implemented but + * allocated pcbs that are not bound cannot be killed automatically if wanting + * to allocate a PCB with higher prio. + * + * @return Returns a new tcp_pcb that initially is in state CLOSED. + */ +struct tcp_pcb *tcp_new (void); +#endif /* LWIP_API_RICH */ + +/** + * @ingroup tcp_raw + * Creates a new TCP protocol control block but doesn't + * place it on any of the TCP PCB lists. + * The PCB is not put on any list until binding using tcp_bind(). + * + * @param type IP address type. + * If you want to listen to IPv4 and IPv6 (dual-stack) connections, + * supply @ref IPADDR_TYPE_ANY as argument and bind to @ref IP_ANY_TYPE. + * @return Returns a new tcp_pcb that initially is in state CLOSED. + */ +struct tcp_pcb *tcp_new_ip_type (u8_t type); +/** + * @ingroup tcp_raw + * Used to specify the argument that should be passed callback + * functions. + * + * @param pcb Indicates the tcp_pcb to set the callback argument. + * @param arg A void pointer argument to pass to callback functions. + */ +void tcp_arg (struct tcp_pcb *pcb, void *arg); +#if LWIP_CALLBACK_API +/** + * @ingroup tcp_raw + * Used to specify the function that should be called when a TCP + * connection receives data. + * + * @param pcb Indicates the tcp_pcb to set the recv callback + * @param recv A callback function to call for this PCB when data is received. + */ +void tcp_recv (struct tcp_pcb *pcb, tcp_recv_fn recv); +/** + * @ingroup tcp_raw + * Used to specify the function that should be called when TCP data + * has been successfully delivered to the remote host. + * + * @param pcb Indicates the tcp_pcb to set the sent callback. + * @param sent A callback function to call for this pcb when data is successfully sent + */ +void tcp_sent (struct tcp_pcb *pcb, tcp_sent_fn sent); +/** + * @ingroup tcp_raw + * Used to specify the function that should be called when a fatal error + * has occurred on the connection. + * + * @note The corresponding PCB is already freed when this callback is called! + * + * @param pcb Indicates a tcp_pcb to set the err callback. + * @param err callback function to call for this PCB when a fatal error + * has occurred on the connection. + */ +void tcp_err (struct tcp_pcb *pcb, tcp_err_fn err); + +/** + * @ingroup tcp_raw + * Used for specifying the function that should be called when a + * listening connection has been connected to another host. + * + * @param pcb Indicates the tcp_pcb to set the accept callback. + * @param accept callback function to call for this PCB when listening + * connection has been connected to another host. + */ +void tcp_accept (struct tcp_pcb *pcb, tcp_accept_fn accept); +#endif /* LWIP_CALLBACK_API */ +/** + * @ingroup tcp_raw + * Used to specify the function that should be called periodically + * from TCP. The interval is specified in terms of the TCP coarse + * timer interval, which is called twice a second. + * + */ +void tcp_poll (struct tcp_pcb *pcb, tcp_poll_fn poll, u8_t interval); + +#if LWIP_LOWPOWER +u32_t tcp_fast_tmr_tick(void); +u32_t tcp_slow_tmr_tick(void); +#endif + +#if LWIP_TCP_TIMESTAMPS +#define tcp_mss(pcb) (((pcb)->flags & TF_TIMESTAMP) ? ((pcb)->mss - 12) : (pcb)->mss) +#else /* LWIP_TCP_TIMESTAMPS */ +#define tcp_mss(pcb) ((pcb)->mss) +#endif /* LWIP_TCP_TIMESTAMPS */ +#define tcp_sndbuf(pcb) ((pcb)->snd_buf) +#define tcp_sndqueuelen(pcb) ((pcb)->snd_queuelen) + +#if LWIP_SO_SNDBUF +#define tcp_set_sendbufsize(pcb, size) ((pcb)->snd_buf_static = (tcpwnd_size_t)(size)) +#define tcp_get_sendbufsize(pcb) ((pcb)->snd_buf_static) +#endif /* LWIP_SO_SNDBUF */ + +#if LWIP_SO_PRIORITY +#define tcp_getpriority(pcb) ((pcb)->priority) +#endif /* LWIP_SO_PRIORITY */ + +#define tcp_set_flags(pcb, set_flags) do { \ + (pcb)->flags = (tcpflags_t)((pcb)->flags | (set_flags)); } while (0) +#define tcp_clear_flags(pcb, clr_flags) do { \ + (pcb)->flags = (tcpflags_t)((pcb)->flags & (tcpflags_t)(~(clr_flags) & TCP_ALLFLAGS)); } while (0) +#define tcp_is_flag_set(pcb, flag) (((pcb)->flags & (flag)) != 0) + +/** @ingroup tcp_raw */ +#define tcp_nagle_disable(pcb) ((pcb)->flags |= TF_NODELAY) +/** @ingroup tcp_raw +* Enables Nagle algorithm. */ +#define tcp_nagle_enable(pcb) ((pcb)->flags = (tcpflags_t)((pcb)->flags & ~TF_NODELAY)) +/** @ingroup tcp_raw +* Disables Nagle algorithm. */ +#define tcp_nagle_disabled(pcb) (((pcb)->flags & TF_NODELAY) != 0) + +#if TCP_LISTEN_BACKLOG +#define tcp_backlog_set(pcb, new_backlog) do { \ + LWIP_ASSERT("pcb->state == LISTEN (called for wrong pcb?)", (pcb)->state == LISTEN); \ + ((struct tcp_pcb_listen *)(pcb))->backlog = (u8_t)((new_backlog) ? (new_backlog) : 1); } while (0) +void tcp_backlog_delayed(struct tcp_pcb *pcb); +void tcp_backlog_accepted(struct tcp_pcb *pcb); +#else /* TCP_LISTEN_BACKLOG */ +#define tcp_backlog_set(pcb, new_backlog) +#define tcp_backlog_delayed(pcb) +#define tcp_backlog_accepted(pcb) +#endif /* TCP_LISTEN_BACKLOG */ +#define tcp_accepted(pcb) do { LWIP_UNUSED_ARG(pcb); } while (0) /* compatibility define, no need any more */ + +void tcp_recved (struct tcp_pcb *pcb, u16_t len); +err_t tcp_bind (struct tcp_pcb *pcb, const ip_addr_t *ipaddr, + u16_t port); +err_t tcp_connect (struct tcp_pcb *pcb, const ip_addr_t *ipaddr, + u16_t port, tcp_connected_fn connected); + +struct tcp_pcb *tcp_listen_with_backlog_and_err(struct tcp_pcb *pcb, u8_t backlog, err_t *err); +#if LWIP_API_RICH +struct tcp_pcb *tcp_listen_with_backlog(struct tcp_pcb *pcb, u8_t backlog); +/** @ingroup tcp_raw */ +#define tcp_listen(pcb) tcp_listen_with_backlog(pcb, TCP_DEFAULT_LISTEN_BACKLOG) +#endif /* LWIP_API_RICH */ + +void tcp_abort (struct tcp_pcb *pcb); +err_t tcp_close (struct tcp_pcb *pcb); +err_t tcp_shutdown(struct tcp_pcb *pcb, int shut_rx, int shut_tx); + +err_t tcp_write (struct tcp_pcb *pcb, const void *dataptr, tcpwnd_size_t len, + u8_t apiflags); + +#if LWIP_API_RICH +void tcp_setprio (struct tcp_pcb *pcb, u8_t prio); +#endif /* LWIP_API_RICH */ + +#if LWIP_TCP_TLP_SUPPORT +/* + * This is the TLP probe timeout function as in draft-dukkipati-tcpm-tcp-loss-probe-01 + * + * When PTO fires: + * (a) If a new previously unsent segment exists: + * -> Transmit new segment. + * -> FlightSize += SMSS. cwnd remains unchanged. + * (b) If no new segment exists: + * -> Retransmit the last segment. + * (c) Increment statistics counter for loss probes. + * (d) If conditions in (2) are satisfied: + * -> Reschedule next PTO. + * Else: + * -> Rearm RTO to fire at epoch 'now+RTO'. + * + * @param pcb Protocol control block for the TCP connection to send data + * @return None + * + */ +void tcp_pto_fire(struct tcp_pcb *pcb); +#endif + +err_t tcp_output (struct tcp_pcb *pcb); + +#if API_MSG_DEBUG || (defined LWIP_DEBUG) +const char *tcp_debug_state_str(enum tcp_state s); +#endif /* API_MSG_DEBUG */ + +#if DRIVER_STATUS_CHECK +unsigned char tcp_is_netif_addr_check_success(struct tcp_pcb *pcb, struct netif *netif); +void tcp_flush_pcb_on_wake_queue(struct tcp_pcb *pcb, u8_t status); +void tcpip_flush_on_wake_queue(struct netif *netif, u8_t status); +void tcp_ip_flush_pcblist_on_wake_queue(struct netif *netif, struct tcp_pcb *pcb_list, u8_t status); +void tcpip_upd_status_to_tcp_pcbs(struct netif *netif, u8_t status); +void tcp_ip_event_sendplus_on_wake_queue(struct netif *netif); +void tcp_update_drv_status_to_pcbs(struct tcp_pcb *pcb_list, struct netif *netif, u8_t status); +#endif + +/* for compatibility with older implementation */ +#define tcp_new_ip6() tcp_new_ip_type(IPADDR_TYPE_V6) + +void tcp_sndbuf_init(struct tcp_pcb *pcb); + +#if LWIP_API_RICH +const char *get_lwip_version(void); +#endif /* LWIP_API_RICH */ + +void tcp_handle_closepend(void); + +#if LWIP_TCP_TLP_SUPPORT +void tcp_tlp_schedule_probe(struct tcp_pcb *pcb, u32_t wnd); +#endif /* LWIP_TCP_TLP_SUPPORT */ + +#if LWIP_TCP_PCB_NUM_EXT_ARGS +u8_t tcp_ext_arg_alloc_id(void); +void tcp_ext_arg_set_callbacks(struct tcp_pcb *pcb, uint8_t id, const struct tcp_ext_arg_callbacks * const callbacks); +void tcp_ext_arg_set(struct tcp_pcb *pcb, uint8_t id, void *arg); +void *tcp_ext_arg_get(const struct tcp_pcb *pcb, uint8_t id); +#endif + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_TCP */ + +#endif /* LWIP_HDR_TCP_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/tcp_info.h b/sdk_liteos/third_party/lwip_sack/include/lwip/tcp_info.h new file mode 100644 index 0000000000000000000000000000000000000000..b8d18bf0ca6f46c0cf86a1d14f692c04ba84f824 --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/tcp_info.h @@ -0,0 +1,102 @@ +/* + * Description: TCP_INFO support + */ + +#ifndef __LWIP_TCP_INFO_H__ +#define __LWIP_TCP_INFO_H__ + +#include "opt.h" +#include "arch/cc.h" +#include "lwip/priv/tcp_priv.h" + +#if LWIP_TCP_INFO + +#ifdef LWIP_TCP +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + + +/* [VPPTECH-449] TCP_INFO support */ +/* + * TCP FSM state definitions. + * Per RFC793, September, 1981. + */ + +#define TCP_NSTATES 11 + +/* for TCP_INFO socket option */ +#define TCPI_OPT_TIMESTAMPS 1 +#define TCPI_OPT_SACK 2 +#define TCPI_OPT_WSCALE 4 +#define TCPI_OPT_ECN 8 /* ECN was negociated at TCP session init */ /* Not supported in TCP_INFO */ +#define TCPI_OPT_ECN_SEEN 16 /* we received at least one packet with ECT */ /* Not supported in TCP_INFO */ +#define TCPI_OPT_SYN_DATA 32 /* SYN-ACK acked data in SYN sent or rcvd */ /* Not supported in TCP_INFO */ + +#if !defined(LWIP_TCP_INFO) || (0 == LWIP_TCP_INFO) || !LWIP_LITEOS_COMPAT +/** + * @cond liteos + * @defgroup Config_TCP TCP Configuration Interfaces + * @ingroup Configuration_Interfaces + */ +/** + * @defgroup Configuration_Interfaces Configuration Interfaces + * This contains all the configuration APIs + * @endcond + */ +/** This structure gives information about the TCP connection. */ +struct tcp_info { + u8_t tcpi_state; /**< Indicates state of a TCP connection. This is currently supported. */ + u8_t tcpi_ca_state; /**< Indicates the CA state. This is currently set to 0. */ + u8_t tcpi_retransmits; /**< Indicates retransmit. This is currently supported. */ + u8_t tcpi_probes; /**< Indicates probes. This is currently supported. */ + u8_t tcpi_backoff; /**< Indicates backoff. This is currently supported. */ + u8_t tcpi_options; /**< Indicates options . This is currently supported. */ + /**< Indicates send and receive of wscale. This is currently set to 0. */ + u8_t tcpi_snd_wscale : 4, tcpi_rcv_wscale : 4; + + u32_t tcpi_rto; /**< Indicates rto. This is currently supported.*/ + u32_t tcpi_ato; /**< Indicates ato. This is currently set to 0.*/ + u32_t tcpi_snd_mss; /**< Indicates the send message. This is currently supported.*/ + u32_t tcpi_rcv_mss; /**< Indicates the receive message state. This is currently supported.*/ + + u32_t tcpi_unacked; /**< Indicates unacknowledge. This is currently supported.*/ + u32_t tcpi_sacked; /**< Indicates sack. This is currently set to 0.*/ + u32_t tcpi_lost; /**< Indicates lost packet. This is currently set to 0.*/ + u32_t tcpi_retrans; /**< Indicates retransmit. This is currently set to 0.*/ + u32_t tcpi_fackets; /**< Indicates fackets. This is currently set to 0.*/ + + /* Times. */ + u32_t tcpi_last_data_sent; /**< Indicates the last data sent. This is currently set to 0.*/ + u32_t tcpi_last_ack_sent; /**< Indicates the last acknowledge sent. This is currently set to 0.*/ + u32_t tcpi_last_data_recv; /**< Indicates last data receive. This is currently set to 0.*/ + u32_t tcpi_last_ack_recv; /**< Indicates the last acknowledge receive. This is currently set to 0.*/ + + /* Metrics. */ + u32_t tcpi_pmtu; /**< Indicates mtu. This is currently set to 0.*/ + u32_t tcpi_rcv_ssthresh; /**< Indicates slow start threshold receive. This is currently set to 0.*/ + u32_t tcpi_rtt; /**< Indicates the rtt. This is currently supported.*/ + u32_t tcpi_rttvar; /**< Indicates rttvar. This is currently supported.*/ + u32_t tcpi_snd_ssthresh; /**< Indicates slow start threshold send. This is currently supported.*/ + u32_t tcpi_snd_cwnd; /**< Indicates send cwnd. This is currently supported.*/ + u32_t tcpi_advmss; /**< Indicates advmss. This is currently set to 0.*/ + u32_t tcpi_reordering; /**< Indicates reordering. This is currently supported.*/ + + u32_t tcpi_rcv_rtt; /**< Indicates receive rtt. This is currently set to 0.*/ + u32_t tcpi_rcv_space; /**< Indicates TCPI receive space. This is currently set to 0.*/ + + u32_t tcpi_total_retrans; /**< Indicates total retransmit. This is currently set to 0.*/ +}; + +#endif /* !LWIP_TCP_INFO */ + +void tcp_get_info(const struct tcp_pcb *pcb, struct tcp_info *tcpinfo); +#endif + +/* [VPPTECH-449] TCP_INFO support */ +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_TCP */ +#endif /* __LWIP_TCP_CONFIG_H__ */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/tcp_sack.h b/sdk_liteos/third_party/lwip_sack/include/lwip/tcp_sack.h new file mode 100644 index 0000000000000000000000000000000000000000..00b5e619511f14ee3ab009dc1f1d209b4c0bec99 --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/tcp_sack.h @@ -0,0 +1,76 @@ +/* + * Description: declaration for TCP SACK APIs + */ + +#ifndef __LWIP_TCP_SACK_CA__ +#define __LWIP_TCP_SACK_CA__ + +#include "lwip/tcp.h" +#include "lwip/priv/tcp_priv.h" + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + + +#define UNSACKED_AND_LOST_SEG 0x0001U +#define UNSENT_SEG 0x0002U +#define UNSACKED_SEG 0x0004U +#define RESCUE_RX_SEG 0x0008U +#define SACK_SYNC_PERMITTED_OPTION 0x04020101U +#define SACK_OPTIONS 0x01010500UL +#define MAX_ORDER 0xFFFFFFFF +#if DRIVER_STATUS_CHECK +#define FAST_RETX_SEG 0x0010U /* First Segment retransmitted as part of Fast retransmit algorithm */ +#define SEG_TYPE_NONE 0x0000U +#endif + +extern u32_t +tcp_parseopt_sack(u8_t *opts, u16_t c); + +extern u32_t +tcp_sack_update(struct tcp_pcb *pcb, u32_t ackno); + +extern void +tcp_sack_based_fast_rexmit_alg(struct tcp_pcb *pcb); + +extern void +tcp_sack_based_loss_recovery_alg(struct tcp_pcb *pcb); + +#if LWIP_SACK_PERF_OPT +extern void +tcp_sack_rexmit_lost_rexmitted(struct tcp_pcb *pcb); +#endif + +extern void +tcp_sack_set_pipe(struct tcp_pcb *pcb); + +extern int +tcp_sack_is_lost(struct tcp_pcb *pcb, struct tcp_seg *seg); + +void tcp_pcb_reset_sack_seq(struct tcp_pcb *pcb); +void tcp_update_sack_for_received_ooseq_segs(struct tcp_pcb *pcb); +void tcp_update_sack_fields_for_new_seg(struct tcp_seg *seg); +void tcp_enqueue_flags_sack(struct tcp_pcb *pcb, u8_t *optflags); +void tcp_build_sack_permitted_option(u32_t *opts); +u8_t tcp_get_sack_block_count_for_send(struct tcp_pcb *pcb, u8_t optlen); +void tcp_build_sack_option(struct tcp_pcb *pcb, u8_t cnt, u32_t *options); +void tcp_parseopt_sack_permitted(struct tcp_pcb *pcb); +void tcp_connect_update_sack(struct tcp_pcb *pcb, u32_t iss); +struct tcp_seg *tcp_sack_get_next_seg(struct tcp_pcb *pcb, u32_t next_seg_type); + +#if LWIP_SACK_DATA_SEG_PIGGYBACK +#if LWIP_SACK +u8_t tcp_check_and_alloc_sack_options(struct tcp_seg *seg, struct tcp_pcb *pcb); +#endif +#endif +#if DRIVER_STATUS_CHECK +#if LWIP_SACK +void tcp_search_and_flush_sack_on_wake_queue(struct tcp_pcb *pcb, u32_t sack_type); +#endif +#endif +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/tcpbase.h b/sdk_liteos/third_party/lwip_sack/include/lwip/tcpbase.h new file mode 100644 index 0000000000000000000000000000000000000000..a520829f1267529b01827fa354bdcff2c85dabff --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/tcpbase.h @@ -0,0 +1,119 @@ +/** + * @file + * Base TCP API definitions shared by TCP and ALTCP\n + * See also @ref tcp_raw + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_TCPBASE_H +#define LWIP_HDR_TCPBASE_H + +#include "lwip/opt.h" + +#if LWIP_TCP /* don't build if not configured for use in lwipopts.h */ + +#ifdef __cplusplus +extern "C" { +#endif + + +#if LWIP_WND_SCALE +typedef u32_t tcpwnd_size_t; +#else +typedef u16_t tcpwnd_size_t; +#endif + +/** Indicates the TCP state. */ +enum tcp_state { + CLOSED = 0, /**< Indicates that there is no connection. */ + /** + * Indicates that the local end-point waits for a connection + * request from a remote end-point. That is, a passive open was performed. + */ + LISTEN = 1, + SYN_SENT = 2, /**< SYN packet is sent. */ + SYN_RCVD = 3, /**< SYN packet is received. */ + /** + * The third step of the three-way connection handshake + * was performed. The connection is open. + */ + ESTABLISHED = 4, + /** + * The first step of an active close (four-way handshake) + * was performed. The local end-point has sent a connection termination request to the remote end-point. + */ + FIN_WAIT_1 = 5, + /** + * The remote end-point has sent an acknowledgement for the previouslysent connection termination request. + * The local end-point waits for an active connection termination request from the remote end-point. + */ + FIN_WAIT_2 = 6, + /** + * The local end-point has received a connection termination request + * and acknowledged it e.g. a passive close has been performed + * and the local end-point needs to perform an active close + * to leave this state. + */ + CLOSE_WAIT = 7, + /** + * The local end-point is waiting for an acknowledgement for a connection + * termination request before going to the TIME-WAIT state. + */ + CLOSING = 8, + /** + * The local end-point has performed a passive close and has + * initiated an active close by sending a connection termination request to the remote end-point. + */ + LAST_ACK = 9, + /** + * The local end-point waits for twice the maximum segment lifetime (MSL) + * to pass before going to CLOSED to be sure that the remote end-point received the acknowledgement. + */ + TIME_WAIT = 10 +}; + +/* Flags for "apiflags" parameter in tcp_write */ +#define TCP_WRITE_FLAG_COPY 0x01 +#define TCP_WRITE_FLAG_MORE 0x02 + +#define TCP_PRIO_MIN 1 +#define TCP_PRIO_NORMAL 64 +#define TCP_PRIO_MAX 127 + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_TCP */ + +#endif /* LWIP_HDR_TCPBASE_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/tcpip.h b/sdk_liteos/third_party/lwip_sack/include/lwip/tcpip.h new file mode 100644 index 0000000000000000000000000000000000000000..0f2d6b85351fe9c92475936642052247ea33c919 --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/tcpip.h @@ -0,0 +1,232 @@ +/** + * @file + * Functions to sync with TCPIP thread + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_TCPIP_H +#define LWIP_HDR_TCPIP_H + +#include "lwip/opt.h" + +#if !NO_SYS /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/err.h" +#include "lwip/timeouts.h" +#include "lwip/netif.h" + +#if LWIP_L3_EVENT_MSG +#include "lwip/l3event.h" +#endif + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +#if LWIP_TCPIP_CORE_LOCKING +/** The global semaphore to lock the stack. */ +extern sys_mutex_t lock_tcpip_core; +/** Lock lwIP core mutex (needs @ref LWIP_TCPIP_CORE_LOCKING 1) */ +#define LOCK_TCPIP_CORE() (void)sys_mutex_lock(&lock_tcpip_core) +/** Unlock lwIP core mutex (needs @ref LWIP_TCPIP_CORE_LOCKING 1) */ +#define UNLOCK_TCPIP_CORE() sys_mutex_unlock(&lock_tcpip_core) +#else /* LWIP_TCPIP_CORE_LOCKING */ +#define LOCK_TCPIP_CORE() +#define UNLOCK_TCPIP_CORE() +#endif /* LWIP_TCPIP_CORE_LOCKING */ + +extern int tcpip_init_finish; + +struct pbuf; +struct netif; + +/** + * @ingroup Tcip_interface + * @brief + * This callback checks whether initialization is done. + * + * @param[in] arg Specifies the argument to pass to tcpip_init_done. + * + * + * @par Return values + * None + */ +typedef void (*tcpip_init_done_fn)(void *arg); +/** Function prototype for functions passed to tcpip_callback() */ +typedef void (*tcpip_callback_fn)(void *ctx); + +/* Forward declarations */ +struct tcpip_callback_msg; + +/* + * Func Name: tcpip_init + */ +/** + * @ingroup Tcip_interface + * @brief + * This API initializes all sub modules and starts the tcpip_thread. + * + * @param[in] tcpip_init_done Specifies the function to call when the + * tcpip_thread is running and finished initializing. + * @param[in] arg Specifies the argument to pass to tcpip_init_done. + * @par Return values + * None + */ +void tcpip_init(tcpip_init_done_fn tcpip_init_done, void *arg); +#if LWIP_ALLOW_SOCKET_CONFIG + +/* + * Func Name: lwip_set_socket_num + */ +/** + * @ingroup TCPIP_Interfaces + * + * + * @brief + * This API is used to configure maximum number of allowed sockets in the lwIP stack. + * + * + * + * @param[in] socketnum Indicates the maximum number of sockets. + * + * @return + * 0: On Success\n + * Non Zero value: On Failure + * + * + * @Note + * \n + * Call this API before tcpip_init, or it will be failed. + * If this API is not invoked, maximum socket number is set to DEFAULT_LWIP_NUM_SOCKETS, which is defined in + * opt.h/lwipopts.h. + * @par Related Topics + * \n + * None + */ +int lwip_set_socket_num(unsigned int socketnum); + +/* + * Func Name: lwip_get_socket_num + */ +/** + * @ingroup TCPIP_Interfaces + * + * + * @brief + * This API is used to get the maximum socket num setting in lwIP. + * + * + * @param[in] void + * + * @return + * current max socket number + * + * @par Required Header File + * tcpip.h + * + * @par Note + * None + */ +unsigned int lwip_get_socket_num(void); +#endif /* LWIP_ALLOW_SOCKET_CONFIG */ + +err_t tcpip_inpkt(struct pbuf *p, struct netif *inp, netif_input_fn input_fn); +err_t tcpip_input(struct pbuf *p, struct netif *inp); + +#if LWIP_PLC || LWIP_IEEE802154 +err_t tcpip_lln_inpkt(struct netif *iface, struct pbuf *p, + struct linklayer_addr *sender_mac, struct linklayer_addr *recver_mac, + netif_lln_input_fn input_lln_fn); + +err_t tcpip_lln_input(struct netif *iface, struct pbuf *p, + struct linklayer_addr *sendermac, struct linklayer_addr *recvermac); +#endif +err_t tcpip_callback_with_block(tcpip_callback_fn function, void *ctx, u8_t block); +/** + * @ingroup lwip_os + * @see tcpip_callback_with_block + */ +#define tcpip_callback(f, ctx) tcpip_callback_with_block(f, ctx, 1) + +#if LWIP_API_RICH +struct tcpip_callback_msg *tcpip_callbackmsg_new(tcpip_callback_fn function, void *ctx); +void tcpip_callbackmsg_delete(struct tcpip_callback_msg *msg); +err_t tcpip_trycallback(struct tcpip_callback_msg *msg); + +/* free pbufs or heap memory from another context without blocking */ +err_t pbuf_free_callback(struct pbuf *p); +err_t mem_free_callback(void *m); +#endif /* LWIP_API_RICH */ + +#if LWIP_TCPIP_TIMEOUT && LWIP_TIMERS +err_t tcpip_timeout(u32_t msecs, sys_timeout_handler h, void *arg); +err_t tcpip_untimeout(sys_timeout_handler h, void *arg); +#endif /* LWIP_TCPIP_TIMEOUT && LWIP_TIMERS */ + +/** This structure defines TCP IP connections. */ +struct tcpip_conn { + struct eth_addr dst_mac; /**< Specifies the destination MAC. */ + ip_addr_t src_ip; /**< Specifies the source IP address. */ + ip_addr_t dst_ip; /**< Specifies the destination IP address of a TCP/UDP connection. + If lwip_connect is not called for a UDP connection, then this field will be set to 0 for that UDP connection. */ + u16_t ipid; /**< Retains the same value as identification field in the IP header. */ + u16_t srcport; /**< Specifies the source port address. */ + u16_t dstport; /**< Specifies the destination port address. If connect is not called for a + UDP connection, then this field will be set to 0 for that UDP connection. */ + u32_t tcpwin; /**< Specifies the TCP window of the last sent TCP packet. For a UDP connection, + this field is set to 0. */ + u32_t seqnum; /**< Specifies the TCP sequence number of the last ACKED byte of a TCP connection. + For a UDP connection, this field is set to 0. */ + u32_t acknum; /**< Specifies the TCP Ack number of the last sent packet in the TCP connection. + For a UDP connection, this field is set to 0. */ + u32_t last_payload_len; /**< Specifies the UDP/TCP payload length of the last packet sent in + the UDP/TCP connection. */ + u32_t tsval; /**< Indicates the timestamp value. This field is 0 for both TCP and UDP connections. */ + u32_t tsecr; /**< Indicates the timestamp echo reply. This field is 0 for both TCP and UDP connections. */ +}; + +#if LWIP_LOWPOWER +void tcpip_send_msg_na(enum lowpower_msg_type type); +#endif + +#if LWIP_L3_EVENT_MSG +void tcpip_send_msg_l3_event(enum l3_event_msg_type type, void *rinfo); +#endif + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* !NO_SYS */ + +#endif /* LWIP_HDR_TCPIP_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/tftpc.h b/sdk_liteos/third_party/lwip_sack/include/lwip/tftpc.h new file mode 100644 index 0000000000000000000000000000000000000000..c70cad2df0922a69d57626c04a74f32c39ca010a --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/tftpc.h @@ -0,0 +1,279 @@ +/* + * Description: declaration of tftpc APIs + */ + +#ifndef __LWIP_TFTP_H__ +#define __LWIP_TFTP_H__ + +#include "lwip/opt.h" +#include "lwip/sockets.h" + +#if LWIP_TFTP /* don't build if not configured for use in lwipopts.h */ + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +#define TFTP_NULL_UINT32 ((u32_t)0xffffffffUL) + +#define TFTP_NULL_INT32 -1 + +/** + * + * This Enum is used to specify the transfer mode of the file to be handled by TFTP client. + */ +typedef enum tag_tftpc_transfermode { + TRANSFER_MODE_ASCII = 0, /**< Indicates that the mode of transfer is ASCII. */ + TRANSFER_MODE_BINARY, /**< Indicates that the mode of transfer is Binary */ + TRANSFER_MODE_BUTT /**< Indicates invalid transfer mode.*/ +} TFTPC_TRANSFER_MODE_E; + +/** + * This Enum is used to specify the transfer mode to be handled by TFTP client + * This Enum indicates the TFTP client transfer mode of the file + */ +typedef enum tag_tftpc_errcode { + + TFTPC_SOCKET_FAILURE = 1, /**< Error while creating UDP socket. */ + TFTPC_BIND_FAILURE = 2, /**< Error while binding to the UDP socket. */ + TFTPC_SELECT_ERROR = 3, /**< Error returned by select() system call. */ + TFTPC_RECVFROM_ERROR = 4, /**< Error while receiving data from the peer. */ + TFTPC_SENDTO_ERROR = 5, /**< Error while sending data to the peer. */ + TFTPC_FILE_NOT_FOUND = 6, /**< Requested file is not found. */ + TFTPC_CANNOT_RESOLVE_HOSTNAME = 7, /**< This is the error sent by the server when host name cannot be + resolved. */ + TFTPC_INVALID_PARAVALUE = 8, /**< Input parameters passed to TFTP interfaces are invalid. */ + TFTPC_PROTO_ERROR = 9, /**< Error detected in TFTP packet or the error received from the + TFTP server. */ + TFTPC_SYNC_FAILURE = 10, /**< Error during packet synchronization while sending or unexpected packet + is received. */ + TFTPC_FILE_TOO_BIG = 11, /**< File size limit crossed, Max block can be 0xFFFF, each block containing + 512 bytes. */ + TFTPC_SRC_FILENAME_LENGTH_ERROR = 12, /**< File name length greater than 256. */ + TFTPC_IP_NOT_WITHIN_RANGE = 13, /**< Host name IP is not valid. */ + TFTPC_ACCESS_ERROR = 14, /**< TFTP server returned file access error. */ + TFTPC_DISK_FULL = 15, /**< TFTP server returned error signifying that the DISK is full to + write. */ + TFTPC_FILE_EXISTS = 16, /**< TFTP server returned error signifying that the file exists. */ + TFTPC_FILE_NOT_EXIST = 17, /**< tftp_put_file_by_filename returned error signifying that the source + file name do not exist. */ + TFTPC_MEMALLOC_ERROR = 18, /**< Memory allocation failed in TFTP client. */ + TFTPC_FILEOPEN_ERROR = 19, /**< File open failed. */ + TFTPC_FILEREAD_ERROR = 20, /**< File read error. */ + TFTPC_FILECREATE_ERROR = 21, /**< File create error. */ + TFTPC_FILEWRITE_ERROR = 22, /**< File write error. */ + TFTPC_TIMEOUT_ERROR = 23, /**< Max time expired while waiting for file to be received. */ + TFTPC_PKT_SIZE_ERROR = 24, /**< Error when the received packet is less than 4 bytes (error length) or + greater than 512 bytes. */ + TFTPC_ERROR_NOT_DEFINED = 25, /**< Returned by TFTP server for protocol user error. */ + TFTPC_DEST_PATH_LENGTH_ERROR = 26, /**< If the destination file path length is greater than 256. */ + TFTPC_UNKNOWN_TRANSFER_ID = 27, /**< Returned by TFTP server for undefined transfer ID. */ + TFTPC_IOCTLSOCKET_FAILURE = 28, /**< IOCTL function failed at TFTP client while setting the socket to + non-block. */ + TFTPC_MEMCPY_FAILURE = 29 /**< TFTP memcpy failure. */ +} TFTPC_ERR_CODE_E; + +typedef enum tag_tftpc_opcode { + TFTPC_OP_RRQ = 1, /* read request */ + TFTPC_OP_WRQ, /* write request */ + TFTPC_OP_DATA, /* data packet */ + TFTPC_OP_ACK, /* acknowledgement */ + TFTPC_OP_ERROR, /* error code */ + TFTPC_OP_OPT /* option code */ +} TFTPC_OPCODE_E; + +typedef enum tagtftpc_protocol_errcode { + TFTPC_PROTOCOL_USER_DEFINED = 0, + TFTPC_PROTOCOL_FILE_NOT_FOUND, + TFTPC_PROTOCOL_ACCESS_ERROR, + TFTPC_PROTOCOL_DISK_FULL, + TFTPC_PROTOCOL_PROTO_ERROR, + TFTPC_PROTOCOL_UNKNOWN_TRANSFER_ID, + TFTPC_PROTOCOL_FILE_EXISTS, + TFTPC_PROTOCOL_CANNOT_RESOLVE_HOSTNAME +} TFTPC_PROT_ERRCODE_E; + +#ifndef TFTPC_MAX_SEND_REQ_ATTEMPTS +#define TFTPC_MAX_SEND_REQ_ATTEMPTS 5 /* tftp max attempts */ +#endif + +#ifndef TFTPC_TIMEOUT_PERIOD +#define TFTPC_TIMEOUT_PERIOD 5 /* tftp timeout period,unit :s */ +#endif + +#define TFTPC_SERVER_PORT 69 /* tftp server well known port no. */ + +/* + * MAX file size in TFTP is 32 MB. + * Reason for keeping 75 here , is ((75*512=38400bytes)/1024) = 37MB. So the recv/Send Loop can + * receive the complete MAX message from the network + */ +#define TFTPC_MAX_WAIT_IN_LOOP 75 + +#define TFTP_BLKSIZE 512 /* data block size (IEN-133) */ +#define TFTP_HDRSIZE 4 /* TFTP header size */ +#define TFTP_PKTSIZE (TFTP_BLKSIZE + TFTP_HDRSIZE) /* Packet size */ +#define TFTP_MAX_MODE_SIZE 9 /* max size of mode string */ +#define TFTP_MAXERRSTRSIZE 100 /* max size of error message string */ +#define TFTP_MAX_PATH_LENGTH 256 /* Max path or filename length */ +#define TFTP_MAX_BLK_NUM (0xFFFFL) /* MAximum block number */ + +/* IP address not including reserved IPs(0 and 127) and multicast addresses(Class D) */ +#define TFTPC_IP_ADDR_MIN 0x01000000 +#define TFTPC_IP_ADDR_EX_RESV 0x7effffff +#define TFTPC_IP_ADDR_CLASS_B 0x80000000 +#define TFTPC_IP_ADDR_EX_CLASS_DE 0xdfffffff + +#define TFTPC_FOUR 4 /* minimum packet size */ + +/****************************************************************************/ +/* Structure definitions */ +/****************************************************************************/ +/* Tftp data packet */ +typedef struct tagtftpc_data { + u16_t us_blknum; /* block number */ + u8_t uc_databuf[TFTP_BLKSIZE]; /* Actual data */ +} tftpc_data_s; + +/* TFTP error packet */ +typedef struct tagtftpc_error { + u16_t us_errnum; /* error number */ + u8_t uc_errmesg[TFTP_MAXERRSTRSIZE]; /* error message */ +} tftpc_error_s; + +/* TFTP packet format */ +typedef struct tagtftpc_packet { + u16_t us_opcode; /* Opcode value */ + union { + /* it contains mode and filename */ + s8_t uc_name_mode[TFTP_MAX_PATH_LENGTH + TFTP_MAX_MODE_SIZE]; + u16_t us_blknum; /* Block Number */ + tftpc_data_s sttftp_data; /* Data Packet */ + tftpc_error_s sttftp_err; /* Error Packet */ + } u; +} tftpc_packet_s; + +/** + * @defgroup TFTP_Interfaces + * This section contains the TFTP Interfaces + */ +/* + * Func Name: lwip_tftp_get_file_by_filename + */ +/** + * @ingroup TFTP_Interfaces + * @brief + * This API gets the source file from the server. It then stores the received file in the destination path + * on the client system. + * + * @param[in] ul_hostaddr IP address of Host. This is the TFTP server IP. [NA] + * @param[in] us_tftpservport TFTP server port. If the value is passed as 0 then the default TFTP + * PORT 69 is used. [NA] + * @param[in] uc_tftptransmode File transfer mode, either TRANSFER_MODE_BINARY or TRANSFER_MODE_ASCII. [NA] + * @param[in] sz_srcfilename Source file in the tftp server. [NA] + * @param[in] sz_destdirpath Destination file path in the in the client. [NA] + * @param[out] [N/A] + * + * @return + * ERR_OK: On success \n + * TFTPC_ERR_CODE_E: On failure + * + * @note + * \n + * The behavior of this API is such that if the destination file already exists, it will be overwritten. + */ +u32_t lwip_tftp_get_file_by_filename +( + u32_t ul_hostaddr, + u16_t us_tftpservport, + u8_t uc_tftptransmode, + s8_t *sz_srcfilename, + s8_t *sz_destdirpath +); + +/* @defgroup TFTP_Interfaces + * This section contains the TFTP Interfaces + */ +/* + * Func Name: lwip_tftp_put_file_by_filename + */ +/** + * @ingroup TFTP_Interfaces + * + * @brief + * This API reads the contents of the source file on the client system and sends it to the server and + * server then receives the data and stores it in the specified destination path. + * + * @param[in] ul_hostaddr Indicates the IP address of Host. This is the TFTP server IP. + * @param[in] us_tftpservport Indicates the TFTP server port. If the value is passed as 0 then the default TFTP + * PORT 69 is used. + * @param[in] uc_tftptransmode Indicates the file transfer mode, either TRANSFER_MODE_BINARY or + * TRANSFER_MODE_ASCII. + * @param[in] sz_srcfilename Indicates the source file in the client. + * @param[in] sz_destdirpath Indicates the destination file path on the tftp server. + * + * @return + * ERR_OK: On success \n + * TFTPC_ERR_CODE_E: On failure + * + */ +u32_t lwip_tftp_put_file_by_filename +( + u32_t ul_hostaddr, + u16_t us_tftpservport, + u8_t uc_tftptransmode, + s8_t *sz_srcfilename, + s8_t *sz_destdirpath +); + +#ifdef TFTP_TO_RAWMEM +/* @defgroup TFTP_Interfaces + * This section contains the TFTP Interfaces + */ +/* + * Func Name: lwip_tftp_get_file_by_filename_to_rawmem +*/ +/** + * @ingroup TFTP_Interfaces + * + * @brief + * This API gets the source file from the server. It then stores the received file in the target memory + * on the client system. + * + * @param[in] ul_hostaddr Indicates the IP address of the Host. This is the TFTP server IP. + * @param[in] us_tftpservport Indicates the TFTP server port. If the value is passed as 0 then the default TFTP + * PORT 69 is used. + * @param[in] uc_tftptransmode Indicates the File transfer mode, either TRANSFER_MODE_BINARY or + * TRANSFER_MODE_ASCII. + * @param[in] sz_srcfilename Indicates the Source file in the TFTP server. + * @param[in] sz_destmemaddr Indicates the target memory address in the client. + * @param[in/out] ul_filelength Indicates the target memory address can cache the size of the content,and The + * real size of the Source file. + * + * @return + * ERR_OK: On success \n + * TFTPC_ERR_CODE_E: On failure + * @note + * + * 1.You must define TFTP_TO_RAWMEM when using this API. \n + * 2.The behavior of this API is such that if the destination file already exists, it will be overwritten. + * @endcond + */ +u32_t lwip_tftp_get_file_by_filename_to_rawmem +( + u32_t ul_hostaddr, + u16_t us_tftpservport, + u8_t uc_tftptransmode, + s8_t *sz_srcfilename, + s8_t *sz_destmemaddr, + u32_t *ul_filelength +); +#endif + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_TFTP */ + +#endif /* __LWIP_TFTP_H__ */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/timeouts.h b/sdk_liteos/third_party/lwip_sack/include/lwip/timeouts.h new file mode 100644 index 0000000000000000000000000000000000000000..20ae74b51949e950146cd91e7e519b8639191d04 --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/timeouts.h @@ -0,0 +1,141 @@ +/** + * @file + * Timer implementations + * @cond liteos + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * Simon Goldschmidt + * + */ +#ifndef LWIP_HDR_TIMEOUTS_H +#define LWIP_HDR_TIMEOUTS_H + +#include "lwip/opt.h" +#include "lwip/err.h" +#if !NO_SYS +#include "lwip/sys.h" +#endif +#if LWIP_LOWPOWER +#include "lwip/lowpower.h" +#endif + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +#if !LWIP_LOWPOWER + +#define LWIP_MAX_VALUE 0xFFFFFFFF + +#ifndef LWIP_DEBUG_TIMERNAMES +#ifdef LWIP_DEBUG +#define LWIP_DEBUG_TIMERNAMES SYS_DEBUG +#else /* LWIP_DEBUG */ +#define LWIP_DEBUG_TIMERNAMES 0 +#endif /* LWIP_DEBUG */ +#endif + +/* Function prototype for a stack-internal timer function that has to be + * called at a defined interval */ +typedef void (* lwip_cyclic_timer_handler)(void); + +/* This struct contains information about a stack-internal timer function + that has to be called at a defined interval */ +struct lwip_cyclic_timer { + u32_t interval_ms; + lwip_cyclic_timer_handler handler; +#if LWIP_DEBUG_TIMERNAMES + const char *handler_name; +#endif /* LWIP_DEBUG_TIMERNAMES */ +}; + +/* This array contains all stack-internal cyclic timers. To get the number of + * timers, use LWIP_ARRAYSIZE() */ +extern const struct lwip_cyclic_timer lwip_cyclic_timers[]; + +#if LWIP_TIMERS + +/** Function prototype for a timeout callback function. Register such a function + * using sys_timeout(). + * + * @param arg Additional argument to pass to the function - set up by sys_timeout() + * @endcond + */ +typedef void (* sys_timeout_handler)(void *arg); + +struct sys_timeo { + struct sys_timeo *next; + u32_t time; + sys_timeout_handler h; + void *arg; +#if LWIP_DEBUG_TIMERNAMES + const char *handler_name; +#endif /* LWIP_DEBUG_TIMERNAMES */ +}; + +void sys_timeouts_init(void); + +#if LWIP_DEBUG_TIMERNAMES +err_t sys_timeout_debug(u32_t msecs, sys_timeout_handler handler, void *arg, const char *handler_name); +#define sys_timeout_ext(msecs, handler, arg) sys_timeout_debug(msecs, handler, arg, #handler) +#else /* LWIP_DEBUG_TIMERNAMES */ +err_t sys_timeout_ext(u32_t msecs, sys_timeout_handler handler, void *arg); +#endif /* LWIP_DEBUG_TIMERNAMES */ + +#define sys_timeout(msecs, handler, arg) (void)sys_timeout_ext(msecs, handler, arg) + +void sys_untimeout(sys_timeout_handler handler, void *arg); +#if LWIP_API_RICH +void sys_restart_timeouts(void); +#endif /* LWIP_API_RICH */ +#if LWIP_TESTMODE || NO_SYS +void sys_check_timeouts(void); +u32_t sys_timeouts_sleeptime(void); +#endif +#if !NO_SYS +void sys_timeouts_mbox_fetch(sys_mbox_t *mbox, void **msg); +#ifdef DUAL_MBOX +void sys_timeouts_dual_mbox_fetch(sys_dual_mbox_t *mbox, void **msg); +#endif /* DUAL_MBOX */ +#endif /* NO_SYS */ + +#if LWIP_TESTMODE +struct sys_timeo** lwip_sys_timers_get_next_timout(void); +#endif + +#endif /* LWIP_TIMERS */ +#endif /* LWIP_LOWPOWER */ +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_HDR_TIMEOUTS_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/lwip/udp.h b/sdk_liteos/third_party/lwip_sack/include/lwip/udp.h new file mode 100644 index 0000000000000000000000000000000000000000..040c0f00fc93fe5f68ff06b9e5e57fc3e98d5795 --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/lwip/udp.h @@ -0,0 +1,203 @@ +/** + * @file + * UDP API (to be used from TCPIP thread)\n + * See also @ref udp_raw + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_UDP_H +#define LWIP_HDR_UDP_H + +#include "lwip/opt.h" + +#if LWIP_UDP /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/pbuf.h" +#include "lwip/netif.h" +#include "lwip/ip_addr.h" +#include "lwip/ip.h" +#include "lwip/ip6_addr.h" +#include "lwip/prot/udp.h" + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +#define UDP_FLAGS_NOCHKSUM 0x01U +#define UDP_FLAGS_UDPLITE 0x02U +#define UDP_FLAGS_CONNECTED 0x04U +#define UDP_FLAGS_MULTICAST_LOOP 0x08U +#define UDP_FLAGS_PEER_ADDR_SET 0x10U + +struct udp_pcb; + +/* Function prototype for udp pcb receive callback functions + * addr and port are in same byte order as in the pcb + * The callback is responsible for freeing the pbuf + * if it's not used any more. + * + * ATTENTION: Be aware that 'addr' might point into the pbuf 'p' so freeing this pbuf + * can make 'addr' invalid, too. + * + * @param arg user supplied argument (udp_pcb.recv_arg) + * @param pcb the udp_pcb which received data + * @param p the packet buffer that was received + * @param addr the remote IP address from which the packet was received + * @param port the remote port from which the packet was received + */ +typedef void (*udp_recv_fn)(void *arg, struct udp_pcb *pcb, struct pbuf *p, + const ip_addr_t *addr, u16_t port); + +/* the UDP protocol control block */ +struct udp_pcb { + /* Common members of all PCB types */ + IP_PCB; + + /* Protocol specific PCB members */ + + struct udp_pcb *next; + + u8_t flags; + /* ports are in host byte order */ + u16_t local_port, remote_port; + u32_t last_payload_len; +#if LWIP_MULTICAST_TX_OPTIONS +#if LWIP_IPV4 + /** outgoing network interface for multicast packets, by IPv4 address (if not 'any') */ + ip4_addr_t mcast_ip4; +#endif /* LWIP_IPV4 */ + /** outgoing network interface for multicast packets, by interface index (if nonzero) */ + u8_t mcast_ifindex; + /** TTL for outgoing multicast packets */ + u8_t mcast_ttl; +#endif /* LWIP_MULTICAST_TX_OPTIONS */ + +#if LWIP_UDPLITE + /* used for UDP_LITE only */ + u16_t chksum_len_rx, chksum_len_tx; +#endif /* LWIP_UDPLITE */ + + /* receive callback function */ + udp_recv_fn recv; + /* user-supplied argument for the recv callback */ + void *recv_arg; + +#if LWIP_SO_PRIORITY + prio_t priority; +#endif /* LWIP_SO_PRIORITY */ + +#if LWIP_IPV6 && LWIP_MAC_SECURITY + u8_t macsec_reqd: 1; +#endif +}; +/* udp_pcbs export for external reference (e.g. SNMP agent) */ +extern struct udp_pcb *udp_pcbs; + +/* The following functions is the application layer interface to the + UDP code. */ +struct udp_pcb *udp_new (void); +struct udp_pcb *udp_new_ip_type (u8_t type); +void udp_remove (struct udp_pcb *pcb); +err_t udp_bind (struct udp_pcb *pcb, const ip_addr_t *ipaddr, + u16_t port); +err_t udp_connect (struct udp_pcb *pcb, const ip_addr_t *ipaddr, + u16_t port); +void udp_disconnect (struct udp_pcb *pcb); +void udp_recv (struct udp_pcb *pcb, udp_recv_fn recv, + void *recv_arg); +err_t udp_sendto_if (struct udp_pcb *pcb, struct pbuf *p, + const ip_addr_t *dst_ip, u16_t dst_port, + struct netif *netif); +err_t udp_sendto_if_src(struct udp_pcb *pcb, struct pbuf *p, + const ip_addr_t *dst_ip, u16_t dst_port, + struct netif *netif, const ip_addr_t *src_ip); +err_t udp_sendto (struct udp_pcb *pcb, struct pbuf *p, + const ip_addr_t *dst_ip, u16_t dst_port); +err_t udp_send (struct udp_pcb *pcb, struct pbuf *p); + +#if LWIP_CHECKSUM_ON_COPY && CHECKSUM_GEN_UDP +err_t udp_sendto_if_chksum (struct udp_pcb *pcb, struct pbuf *p, + const ip_addr_t *dst_ip, u16_t dst_port, + struct netif *netif, u8_t have_chksum, + u16_t chksum); +err_t udp_sendto_chksum (struct udp_pcb *pcb, struct pbuf *p, + const ip_addr_t *dst_ip, u16_t dst_port, + u8_t have_chksum, u16_t chksum); +err_t udp_send_chksum (struct udp_pcb *pcb, struct pbuf *p, + u8_t have_chksum, u16_t chksum); +err_t udp_sendto_if_src_chksum(struct udp_pcb *pcb, struct pbuf *p, + const ip_addr_t *dst_ip, u16_t dst_port, struct netif *netif, + u8_t have_chksum, u16_t chksum, const ip_addr_t *src_ip); +#endif /* LWIP_CHECKSUM_ON_COPY && CHECKSUM_GEN_UDP */ + +#define udp_flags(pcb) ((pcb)->flags) +#define udp_setflags(pcb, f) ((pcb)->flags = (u8_t)(f)) + +#if LWIP_SO_PRIORITY +#define udp_getpriority(pcb) ((pcb)->priority) +#endif /* LWIP_SO_PRIORITY */ + +/* The following functions are the lower layer interface to UDP. */ +void udp_input (struct pbuf *p, struct netif *inp); + +void udp_init (void); + +/* for compatibility with older implementation */ +#define udp_new_ip6() udp_new_ip_type(IPADDR_TYPE_V6) + +#if LWIP_MULTICAST_TX_OPTIONS +#if LWIP_IPV4 +#define udp_set_multicast_netif_addr(pcb, ip4addr) ip4_addr_copy((pcb)->mcast_ip4, *(ip4addr)) +#define udp_get_multicast_netif_addr(pcb) (&(pcb)->mcast_ip4) +#endif /* LWIP_IPV4 */ +#define udp_set_multicast_netif_index(pcb, idx) ((pcb)->mcast_ifindex = (idx)) +#define udp_get_multicast_netif_index(pcb) ((pcb)->mcast_ifindex) +#define udp_set_multicast_ttl(pcb, value) ((pcb)->mcast_ttl = (value)) +#define udp_get_multicast_ttl(pcb) ((pcb)->mcast_ttl) +#endif /* LWIP_MULTICAST_TX_OPTIONS */ + +#if UDP_DEBUG +void udp_debug_print(struct udp_hdr *udphdr); +#else +#define udp_debug_print(udphdr) +#endif + +void udp_netif_ip_addr_changed(const ip_addr_t *old_addr, const ip_addr_t *new_addr); + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_UDP */ + +#endif /* LWIP_HDR_UDP_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/netif/driverif.h b/sdk_liteos/third_party/lwip_sack/include/netif/driverif.h new file mode 100644 index 0000000000000000000000000000000000000000..03544f7e22d362043bd0ff4ccb049e0c047938de --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/netif/driverif.h @@ -0,0 +1,90 @@ +/* + * Description: declaration of driverif APIs + */ + +#ifndef __DRIVERIF_H__ +#define __DRIVERIF_H__ +/** + * @file driverif.h + */ +/** + * @defgroup System_interfaces System Interfaces + * This contains all the system interfaces. + */ +#include "lwip/opt.h" +#include "netif/etharp.h" + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +/** Type of link layer, these macros should be used for link_layer_type of struct netif */ +#define LOOPBACK_IF 772 +#define LOOPBACK_MTU ((16 * 1024) + 20 + 20 + 12) +/** Type of link layer, these macros should be used for link_layer_type of struct netif */ +#define ETHERNET_DRIVER_IF 1 +/** Type of link layer, these macros should be used for link_layer_type of struct netif */ +#define WIFI_DRIVER_IF 801 +/** Type of link layer, these macros should be used for link_layer_type of struct netif */ +#define PLC_DRIVER_IF 10 +/** Type of link layer, these macros should be used for link_layer_type of struct netif */ +#define IEEE802154_DRIVER_IF 11 + +/** Short names of link layer */ +#define LOOPBACK_IFNAME "lo" +/** Short names of link layer */ +#define ETHERNET_IFNAME "eth" +/** Short names of link layer */ +#define WIFI_IFNAME "wlan" +#define PLC_IFNAME "plc" +#define RF_IFNAME "ieee802154" + +struct linklayer_addr; + +/** + * @defgroup Driver_Interfaces Driver Interfaces + * This section provides information about the Network driver related interfaces. + */ +/** Function pointer of driver send function */ +typedef void (*drv_send_fn)(struct netif *netif, struct pbuf *p); + +#if LWIP_IPV6 +typedef err_t (*drv_send_lln_fn)(struct netif *netif, struct pbuf *p, struct linklayer_addr *destmac); +#endif + +/** Function pointer of driver set hw address function */ +/* This callback function should return 0 in case of success */ +typedef u8_t (*drv_set_hwaddr_fn)(struct netif *netif, u8_t *addr, u8_t len); + +err_t driverif_init(struct netif *netif); + +#if LWIP_NETIF_PROMISC +/** Function pointer of driver set/unset promiscuous mode on interface */ +typedef void (*drv_config_fn)(struct netif *netif, u32_t config_flags, u8_t setBit); +#endif /* LWIP_NETIF_PROMISC */ + +/* + * Func Name: driverif_input + */ +/** + * @ingroup Driver_Interfaces + * @brief This API must be called by the network driver to pass the input packet to lwIP. + * Before calling this API, the driver has to keep the packet in the pbuf structure. The driver must + * call pbuf_alloc() with the type as PBUF_RAM to create the pbuf structure. The driver + * has to pass the pbuf structure to this API to add the pbuf into the TCPIP thread. + * After this packet is processed by TCPIP thread, pbuf will be freed. The driver is not required to + * free the pbuf. + * @param[in] netif Indicates the lwIP network interface. + * @param[in] p Indicates the packet in the pbuf structure. + * @return None + * @note + * None + */ +void driverif_input(struct netif *netif, struct pbuf *p); + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif + diff --git a/sdk_liteos/third_party/lwip_sack/include/netif/driverif_ieee802154.h b/sdk_liteos/third_party/lwip_sack/include/netif/driverif_ieee802154.h new file mode 100644 index 0000000000000000000000000000000000000000..0e157c96696f6ef475e038185dee93a90f4283ba --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/netif/driverif_ieee802154.h @@ -0,0 +1,27 @@ +#ifndef __DRIVERIF_IEEE802154__H__ +#define __DRIVERIF_IEEE802154__H__ +/** + * @file driverif_ieee802154.h + */ +#include "lwip/opt.h" +#include "netif/etharp.h" +#include "lwip/netif.h" + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +#if !defined NETIF_USE_6BYTE_HWLEN_FOR_IEEE802154 || (NETIF_USE_6BYTE_HWLEN_FOR_IEEE802154 == 0) +#ifndef NETIF_802154_MAX_HWADDR_LEN +#define NETIF_802154_MAX_HWADDR_LEN 8 +#endif +#endif + +err_t ieee802154driverif_init(struct netif *netif); + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* __DRIVERIF_IEEE802154__H__ */ + diff --git a/sdk_liteos/third_party/lwip_sack/include/netif/driverif_plc.h b/sdk_liteos/third_party/lwip_sack/include/netif/driverif_plc.h new file mode 100644 index 0000000000000000000000000000000000000000..1017298ad1ede8b5f68fdccd832a94cac5ac2428 --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/netif/driverif_plc.h @@ -0,0 +1,23 @@ +/* + * Description: declaration of driverif PLC APIs + */ +#ifndef __DRIVERIF_PLC__H__ +#define __DRIVERIF_PLC__H__ +/** + * @file driverif_plc.h + */ +#include "lwip/opt.h" +#include "netif/etharp.h" +#include "lwip/netif.h" +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +err_t plcdriverif_init(struct netif *netif); + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* __DRIVERIF_PLC__H__ */ + diff --git a/sdk_liteos/third_party/lwip_sack/include/netif/etharp.h b/sdk_liteos/third_party/lwip_sack/include/netif/etharp.h new file mode 100644 index 0000000000000000000000000000000000000000..2b32a45f79a2666fe3c14940bb1ce8b6c93571be --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/netif/etharp.h @@ -0,0 +1,8 @@ +/* ARP has been moved to core/ipv4, provide this #include for compatibility only */ +#ifndef LWIP_HDR_ETHARP_H +#define LWIP_HDR_ETHARP_H + +#include "lwip/etharp.h" +#include "netif/ethernet.h" + +#endif /* LWIP_HDR_ETHARP_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/netif/ethernet.h b/sdk_liteos/third_party/lwip_sack/include/netif/ethernet.h new file mode 100644 index 0000000000000000000000000000000000000000..3821701b473b3ea7b1e780b4a6c49ee6c825536e --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/netif/ethernet.h @@ -0,0 +1,79 @@ +/** + * @file + * Ethernet input function - handles INCOMING ethernet level traffic + * To be used in most low-level netif implementations + */ + +/* + * Copyright (c) 2001-2003 Swedish Institute of Computer Science. + * Copyright (c) 2003-2004 Leon Woestenberg + * Copyright (c) 2003-2004 Axon Digital Design B.V., The Netherlands. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ + +#ifndef LWIP_HDR_NETIF_ETHERNET_H +#define LWIP_HDR_NETIF_ETHERNET_H + +#include "lwip/opt.h" + +#include "lwip/pbuf.h" +#include "lwip/netif.h" +#include "lwip/prot/ethernet.h" + +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +#if LWIP_ARP || LWIP_ETHERNET + +/* Define this to 1 and define LWIP_ARP_FILTER_NETIF_FN(pbuf, netif, type) + * to a filter function that returns the correct netif when using multiple + * netifs on one hardware interface where the netif's low-level receive + * routine cannot decide for the correct netif (e.g. when mapping multiple + * IP addresses to one hardware interface). + */ +#ifndef LWIP_ARP_FILTER_NETIF +#define LWIP_ARP_FILTER_NETIF 0 +#endif + +err_t ethernet_input(struct pbuf *p, struct netif *netif); +err_t ethernet_input_list(struct pbuf *p, struct netif *netif); +err_t ethernet_output(struct netif *netif, struct pbuf *p, const struct eth_addr *src, const struct eth_addr *dst, + u16_t eth_type); + +extern const struct eth_addr ethbroadcast, ethzero; + +#endif /* LWIP_ARP || LWIP_ETHERNET */ + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_HDR_NETIF_ETHERNET_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/netif/ifaddrs.h b/sdk_liteos/third_party/lwip_sack/include/netif/ifaddrs.h new file mode 100644 index 0000000000000000000000000000000000000000..45f8b678ae6917c2cf8ec748b033c677fa2f84af --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/netif/ifaddrs.h @@ -0,0 +1,290 @@ +/* + * Description: declare BSD APIs : getifaddrs freeifaddrs + */ +#if LWIP_IFADDRS +#if LWIP_IPV4 && LWIP_IPV6 +#ifndef __LWIP_IFADDRS_H +#define __LWIP_IFADDRS_H + +#include "lwip/netif.h" +#include "lwip/sockets.h" +#include "lwip/netif.h" +#include "arch/cc.h" + +#if LWIP_LITEOS_COMPAT + +#ifndef SIOCETHTOOL +#define SIOCETHTOOL _IOW('i', 56, struct ifreq) +#endif + +#else +#define SIOCADDRT _IOW('R', 9, struct rtentry) +#define SIOCDELRT _IOW('R', 10, struct rtentry) + +#define SIOCGIFFLAGS _IOWR('i', 17, struct ifreq) /* get ifnet flags */ +#define SIOCSIFFLAGS _IOW('i', 16, struct ifreq) /* set ifnet flags */ +#define SIOCGIFADDR _IOWR('i', 33, struct ifreq) /* get ifnet address */ +#define SIOCSIFADDR _IOW('i', 12, struct ifreq) /* set ifnet address */ + +#define SIOCDIFADDR _IOW('i', 25, struct ifreq) /* delete IF addr */ + +#define SIOCGIFNETMASK _IOWR('i', 37, struct ifreq) /* get net addr mask */ +#define SIOCSIFNETMASK _IOW('i', 22, struct ifreq) /* set net addr mask */ +#define SIOCSIFHWADDR _IOW('i', 140, struct ifreq) /* set IF name */ +#define SIOCGIFHWADDR _IOW('i', 141, struct ifreq) /* set IF name */ +#define SIOCGIFNAME _IOW('i', 142, struct ifreq) /* set IF name */ +#define SIOCSIFNAME _IOW('i', 40, struct ifreq) /* set IF name */ + +/** Gets IF mtu */ +#define SIOCGIFMTU _IOWR('i', 51, struct ifreq) +/** Sets IF mtu */ +#define SIOCSIFMTU _IOW('i', 52, struct ifreq) +/** ethtool */ +#define SIOCETHTOOL _IOW('i', 56, struct ifreq) + +/* provide PF_PACKET option on SOCK_RAW */ +#define SIOCGIFINDEX _IOWR('i', 32, struct ifreq) /* get IF index */ +#define SIOCGIFCONF _IOWR('i', 36, struct ifconf) /* get ifnet list */ + +/** (n) Indicates that the interface is up */ +#define IFF_UP 0x1 +/** (i) Indicates that the broadcast address valid */ +#define IFF_BROADCAST 0x2 +/** (n) Turns on debugging */ +#define IFF_DEBUG 0x4 +/** (i) A loopback net */ +#define IFF_LOOPBACK 0x8 +/** (i) Indicates a point-to-point link */ +#define IFF_POINTOPOINT 0x10 +/* 0x20 was IFF_SMART */ +/** (d) Indicates that the resources are allocated */ +#define IFF_DRV_RUNNING 0x40 +/** (n) No address resolution protocol */ +#define IFF_NOARP 0x80 +/** (n) Receive all packets */ +#define IFF_PROMISC 0x100 +/** (n) Receive all multicast packets */ +#define IFF_ALLMULTI 0x200 +/** (d) Indicates that the tx hardware queue is full */ +#define IFF_DRV_OACTIVE 0x400 +/** (i) Cannot hear own transmissions */ +#define IFF_SIMPLEX 0x800 +/** Per link layer defined bit */ +#define IFF_LINK0 0x1000 +/** Per link layer defined bit */ +#define IFF_LINK1 0x2000 +/** Per link layer defined bit */ +#define IFF_LINK2 0x4000 +/** Use alternate physical connection */ +#define IFF_ALTPHYS IFF_LINK2 +/** Supports multicast */ +#define IFF_MULTICAST 0x8000 +/** (i) Unconfigurable using ioctl(2) */ +#define IFF_CANTCONFIG 0x10000 +/** (n) User-requested promisc mode */ +#define IFF_PPROMISC 0x20000 +/** (n) User-requested IFF_MONITOR mode */ +#define IFF_MONITOR 0x40000 +/** (n) Static ARP */ +#define IFF_STATICARP 0x80000 +/** (n) Interface is winding down */ +#define IFF_DYING 0x200000 +/** (n) Interface is being renamed */ +#define IFF_RENAMING 0x400000 +/** (n) Dialup device with changing addresses */ +#define IFF_DYNAMIC 0x800000 +/** (n) Dialup device with changing addresses */ +#define IFF_DYNAMIC_S 0x1000000 + +#define IFF_RUNNING IFF_DRV_RUNNING +struct ifreq { +#define IFHWADDRLEN 6 + union { + char ifrn_name[IFNAMSIZ]; + } ifr_ifrn; + union { + struct sockaddr ifru_addr; + struct sockaddr ifru_dstaddr; + struct sockaddr ifru_broadaddr; + struct sockaddr ifru_netmask; + struct sockaddr ifru_hwaddr; + short ifru_flags[2]; + int ifru_ivalue; + int ifru_mtu; + char ifru_slave[IFNAMSIZ]; + char ifru_newname[IFNAMSIZ]; + void *ifru_data; + } ifr_ifru; +}; +#define ifr_name ifr_ifrn.ifrn_name +#define ifr_hwaddr ifr_ifru.ifru_hwaddr +#define ifr_addr ifr_ifru.ifru_addr +#define ifr_dstaddr ifr_ifru.ifru_dstaddr +#define ifr_broadaddr ifr_ifru.ifru_broadaddr +#define ifr_netmask ifr_ifru.ifru_netmask +#define ifr_flags ifr_ifru.ifru_flags[0] /* flags (low 16 bits) */ +#define ifr_flagshigh ifr_ifru.ifru_flags[1] /* flags (high 16 bits) */ +#define ifr_metric ifr_ifru.ifru_ivalue +#define ifr_mtu ifr_ifru.ifru_mtu +#define ifr_slave ifr_ifru.ifru_slave +#define ifr_data ifr_ifru.ifru_data +#define ifr_ifindex ifr_ifru.ifru_ivalue +#define ifr_bandwidth ifr_ifru.ifru_ivalue +#define ifr_qlen ifr_ifru.ifru_ivalue +#define ifr_newname ifr_ifru.ifru_newname +#define ifr_index ifr_ifindex + +struct ifconf { + int ifc_len; + union { + char *ifcu_buf; + struct ifreq *ifcu_req; + } ifc_ifcu; +}; + +#define ifc_buf ifc_ifcu.ifcu_buf +#define ifc_req ifc_ifcu.ifcu_req + +struct ifaddrs { + struct ifaddrs *ifa_next; /**< Pointer to the next network interfaces.f */ + char *ifa_name; /**< Pointer to the name of the network interfaces */ + unsigned int ifa_flags; /**< Pointer to the status flag. */ + struct sockaddr *ifa_addr; /**< Pointer to the address. */ + struct sockaddr *ifa_netmask; /**< Pointer to the net masking. */ + struct sockaddr *ifa_dstaddr; /**< Pointer to the destination address. */ + void *ifa_data; /**< Pointer to the data. */ +}; + +/* + * This may have been defined in . Note that if is + * to be included it must be included before this header file. + */ +#ifndef ifa_broadaddr +/** @brief Indicates a broadcast address interface. */ +#define ifa_broadaddr ifa_dstaddr /* brcast address interface */ +#endif + +struct rtentry { + struct sockaddr rt_dst; /**< Indicates the target address. */ + struct sockaddr rt_gateway; /**< Indicates the gateway address (RTF_GATEWAY). */ + struct sockaddr rt_genmask; /**< Indicates the target network mask (IP). */ + unsigned int rt_flags; +}; +/** Indicates that the route is usable */ +#define RTF_UP 0x1 +/** Indicates that the destination is a gateway */ +#define RTF_GATEWAY 0x2 +/** Indicates the host entry (net otherwise) */ +#define RTF_HOST 0x4 +/** Indicates the host or net is unreachable */ +#define RTF_REJECT 0x8 +/** Created dynamically (by redirect) */ +#define RTF_DYNAMIC 0x10 +/** Modified dynamically (by redirect) */ +#define RTF_MODIFIED 0x20 +/** Message confirmed. */ +#define RTF_DONE 0x40 +/* 0x80 unused, was RTF_DELCLONE */ +/* 0x100 unused, was RTF_CLONING */ +/** Indicates that the external daemon resolves name */ +#define RTF_XRESOLVE 0x200 +/** DEPRECATED - exists ONLY for backward + compatibility */ +#define RTF_LLINFO 0x400 +/** Used by apps to add/del L2 entries */ +#define RTF_LLDATA 0x400 +/** Manually added */ +#define RTF_STATIC 0x800 +/** Discard packets */ +#define RTF_BLACKHOLE 0x1000 +/** Protocol specific routing flag */ +#define RTF_PROTO2 0x4000 +/** Protocol specific routing flag */ +/* 0x10000 unused, was RTF_PRCLONING */ +#define RTF_PROTO1 0x8000 +/* 0x10000 unused, was RTF_PRCLONING */ +/* 0x20000 unused, was RTF_WASCLONED */ +/** Protocol specific routing flag */ +#define RTF_PROTO3 0x40000 +/** MTU was explicitly specified */ +#define RTF_FIXEDMTU 0x80000 +/** Route is immutable */ +#define RTF_PINNED 0x100000 +/** Route represents a local address */ +#define RTF_LOCAL 0x200000 +/** Route represents a broadcast address */ +#define RTF_BROADCAST 0x400000 +/** Route represents a multicast address */ +#define RTF_MULTICAST 0x800000 +/* 0x8000000 and up unassigned */ +/** Always route dst->src */ +#define RTF_STICKY 0x10000000 +/** Radix node head is locked */ +#define RTF_RNH_LOCKED 0x40000000 +/** Indicates the compatibility bit for interacting + with existing routing apps */ +#define RTF_GWFLAG_COMPAT 0x80000000 + +/* Mask of RTF flags that are allowed to be modified by RTM_CHANGE. */ +#define RTF_FMASK \ + (RTF_PROTO1 | RTF_PROTO2 | RTF_PROTO3 | RTF_BLACKHOLE | \ + RTF_REJECT | RTF_STATIC | RTF_STICKY) + +/** + * @defgroup Network_Interfaces_Info Network Interfaces Info + * This section contains the interfaces to get information about Network interfaces in lwIP. + * @ingroup User_interfaces + */ +/* + * Func Name: getifaddrs + */ +/** + * @ingroup Network_Interfaces_Info + * @brief Creates a linked list of struct ifaddrs, which holds the information + * about the network interfaces of the local system. The ifa_next field contains a + * pointer to the next structure on the list, or NULL if this is the last item of the list. + * The ifa_name points to the null-terminated interface name. The ifa_flags field + * contains the interface flags. The ifa_addr field points to a structure containing + * the interface address. The ifa_netmask field points to a structure containing + * the netmask associated with ifa_addr, if applicable, for the address family. + * Depending on whether the bit IFF_brcast or IFF_POINTOPOINT is set + * in ifa_flags (only one can be set at a time), either ifa_broadaddr will contain + * the broadcast address associated with ifa_addr (if applicable for the address + * family) or ifa_dstaddr will contain the destination address of the point-to-point + * interface. + * For IPv6, stack supports only IFF_UP,IFF_MULTICAST, IFF_DRV_RUNNING, and IFF_LOOPBACK + * flags. + * @param[in] ifap Indicates a double pointer to the ifaddrs structure. + * @return + * On success, getifaddrs() returns zero; on error, -1 is returned, and errno is set appropriately. + * @par Errors + * @li The getifaddrs() function shall fail if: + * - [EACCES] : \n Invalid state of system. + * - [ENOMEM] : \n In-sufficient memory. + * @note + * None + */ +int getifaddrs(struct ifaddrs **ifap); + +/* + * Func Name: freeifaddrs + */ +/** + * @ingroup Network_Interfaces_Info + * @brief The function getifaddrs, provides the list of network interfaces in the ifaddrs* structure. + * The application has to free the memory of the ifaddrs * structure by using this function. + * @param[in] ifa Indicates a pointer to the ifaddrs structure. + * @return + * Void + * @note + * None + */ +void freeifaddrs(struct ifaddrs *ifa); + +#endif /* !LWIP_LITEOS_COMPAT */ +int get_ipv6_ifaddr(struct netif *netif, struct ifaddrs *ifaddr, int tmp_index); +int get_ipv4_ifaddr(struct netif *netif, struct ifaddrs *ifaddr); +struct ifaddrs_storage *new_ifaddrs_storage(void); +#endif /* __LWIP_IFADDRS_H */ +#endif /* LWIP_IPV4 && !LWIP_IPV6 */ +#endif /* LWIP_IFADDRS */ diff --git a/sdk_liteos/third_party/lwip_sack/include/netif/lowpan6.h b/sdk_liteos/third_party/lwip_sack/include/netif/lowpan6.h new file mode 100644 index 0000000000000000000000000000000000000000..18e194a5e680a8548ffd55a0c9947e83d3017f8e --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/netif/lowpan6.h @@ -0,0 +1,114 @@ +/** + * @file + * + * 6LowPAN output for IPv6. Uses ND tables for link-layer addressing. Fragments packets to 6LowPAN units. + */ + +/* + * Copyright (c) 2015 Inico Technologies Ltd. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Ivan Delamer + * + * + * Please coordinate changes and requests with Ivan Delamer + * + */ + +#ifndef LWIP_HDR_LOWPAN6_H +#define LWIP_HDR_LOWPAN6_H + +#include "netif/lowpan6_opts.h" + +#if LWIP_IPV6 && LWIP_6LOWPAN /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/pbuf.h" +#include "lwip/ip.h" +#include "lwip/ip_addr.h" +#include "lwip/netif.h" +#if defined (__cplusplus) && __cplusplus +extern "C" { +#endif + +/* + * 6lowpan context identifier information need to be dessiminated to the nodes + * in the LLNs using some upper layer protocols. For example The 6LoWPAN Context Option (6CO) + * suggested in the RFC 6775 (ND Optimization for 6LoWPANs). So the below + * data structure can be used to store the context information . + */ +struct lowpan6_context_info { + ip6_addr_t context_prefix; + /* + * Its basically the netif that added the lowpan context + * currently it doesn't have much use . Added for future purpose + */ + void *iface; + u8_t context_id; + u8_t is_used; +}; + +/** 1 second period */ +#define LOWPAN6_TMR_INTERVAL 1000 + +/* As per RFC 4944 The reassembly timeout MUST be set to a maximum of 60 seconds */ +#define LOWPAN6_REASS_TIMEOUT 60 + +void lowpan6_tmr(void); +#if LWIP_LOWPOWER +u32_t lowpan6_tmr_tick(void); +#endif + +err_t lowpan6_set_context(struct netif *hwface, u8_t index, const ip6_addr_t *context); +err_t lowpan6_remove_context(struct netif *hwface, u8_t ctxid); +err_t lowpan6_set_short_addr(u8_t addr_high, u8_t addr_low); + +#if LWIP_IPV4 +err_t lowpan4_output(struct netif *netif, struct pbuf *q, const ip4_addr_t *ipaddr); +#endif /* LWIP_IPV4 */ +err_t lowpan6_output(struct netif *netif, struct pbuf *q, const struct linklayer_addr *dstlinkaddr); + +err_t lowpan6_input(struct pbuf *p, struct netif *netif, + const struct linklayer_addr *sendermac, + const struct linklayer_addr *recvrmac); + +err_t lowpan6_if_init(struct netif *netif); + +/* pan_id in network byte order. */ +err_t lowpan6_set_pan_id(u16_t pan_id); + +#if !NO_SYS +err_t tcpip_6lowpan_input(struct pbuf *p, struct netif *inp); +#endif /* !NO_SYS */ +void lowpan6_free_reass_context(struct netif *netif); + +#if defined (__cplusplus) && __cplusplus +} +#endif + +#endif /* LWIP_IPV6 && LWIP_6LOWPAN */ + +#endif /* LWIP_HDR_LOWPAN6_H */ diff --git a/sdk_liteos/third_party/lwip_sack/include/netif/lowpan6_opts.h b/sdk_liteos/third_party/lwip_sack/include/netif/lowpan6_opts.h new file mode 100644 index 0000000000000000000000000000000000000000..6d65261cd87767ba45f56e1e9bd5b1851e6cba6a --- /dev/null +++ b/sdk_liteos/third_party/lwip_sack/include/netif/lowpan6_opts.h @@ -0,0 +1,134 @@ +/** + * @file + * 6LowPAN options list + */ + +/* + * Copyright (c) 2015 Inico Technologies Ltd. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Ivan Delamer + * + * + * Please coordinate changes and requests with Ivan Delamer + * + */ + +#ifndef LWIP_HDR_LOWPAN6_OPTS_H +#define LWIP_HDR_LOWPAN6_OPTS_H + +#include "lwip/opt.h" + +#define LOWPAN_LINK_LAYER_TYPE_RF 1 +#define LOWPAN_LINK_LAYER_TYPE_PLC 2 + +/* + * This configuration will enable the 6lowpan layer processing for the IPv6 + * traffic. 6lopwan enables the IPv6 packets to sned over the link whose MTU is + * less than the default IPv6 MTU. + */ +#ifndef LWIP_6LOWPAN +#define LWIP_6LOWPAN 1 +#endif + +/* + * This configuration will enable the 6lowpan layer statistics. + */ +#if !defined LOWPAN6_STATS || defined __DOXYGEN__ +#define LOWPAN6_STATS (LWIP_STATS && LWIP_IPV6 && LWIP_6LOWPAN) +#endif + +#define LWIP_6LOWPAN_MAX_CTXID 15 + +/* + * Defines the number of 6lowpan contexts that can be added to the 6lowpan layer. + */ +#ifndef LWIP_6LOWPAN_NUM_CONTEXTS +#define LWIP_6LOWPAN_NUM_CONTEXTS 10 +#endif + +#ifndef LWIP_6LOWPAN_INFER_SHORT_ADDRESS +#define LWIP_6LOWPAN_INFER_SHORT_ADDRESS 1 +#endif + +#ifndef LWIP_6LOWPAN_IPHC +#define LWIP_6LOWPAN_IPHC 1 +#endif + +#ifndef LWIP_6LOWPAN_HW_CRC +#define LWIP_6LOWPAN_HW_CRC 1 +#endif +/* + * Enables debug log for 6lowpan module. + */ +#ifndef LOWPAN6_DEBUG +#define LOWPAN6_DEBUG LWIP_DBG_OFF +#endif + +/* + * Defines the MTU of PLC link. + */ +#ifndef LOWPAN6_PLC_MAX_LINK_MTU +#define LOWPAN6_PLC_MAX_LINK_MTU 512 +#endif + +/* + * Defines the MTU of RF link. + */ +#ifndef LOWPAN6_RF_MAX_LINK_MTU +#define LOWPAN6_RF_MAX_LINK_MTU 128 +#endif + +/* + * Defines the MAC layer overhead for PLC link. + */ +#ifndef LOWPAN6_PLC_MAC_FIXED_OVERHEAD +#define LOWPAN6_PLC_MAC_FIXED_OVERHEAD 16 +#endif + +/* + * Defines the MAC layer overhead for PLC link. + */ +#ifndef LOWPAN6_RF_MAC_FIXED_OVERHEAD +#define LOWPAN6_RF_MAC_FIXED_OVERHEAD 23 +#endif + +/* + * Defines the maximum IPv6 MTU over PLC link. + */ +#ifndef LOWPAN6_IPV6_MAX_MTU_OVER_IEE802154 +#define LOWPAN6_IPV6_MAX_MTU_OVER_IEE802154 1280 +#endif + +/* + * Defines the maximum IPv6 MTU over RF link. + */ +#ifndef LOWPAN6_IPV6_MAX_MTU_OVER_PLC +#define LOWPAN6_IPV6_MAX_MTU_OVER_PLC 1280 +#endif + +#endif /* LWIP_HDR_LOWPAN6_OPTS_H */ diff --git a/sdk_liteos/third_party/mbedtls/include/.gitignore b/sdk_liteos/third_party/mbedtls/include/.gitignore new file mode 100755 index 0000000000000000000000000000000000000000..bf67d02ed8af25c794e7271366d8a0401bc2fb6d --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/.gitignore @@ -0,0 +1,4 @@ +Makefile +*.sln +*.vcxproj +mbedtls/check_config diff --git a/sdk_liteos/third_party/mbedtls/include/CMakeLists.txt b/sdk_liteos/third_party/mbedtls/include/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..c2f2bd4e6f298e7fbffce1dad9cbb70453788219 --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/CMakeLists.txt @@ -0,0 +1,16 @@ +option(INSTALL_MBEDTLS_HEADERS "Install mbed TLS headers." ON) + +if(INSTALL_MBEDTLS_HEADERS) + + file(GLOB headers "mbedtls/*.h") + + install(FILES ${headers} + DESTINATION include/mbedtls + PERMISSIONS OWNER_READ OWNER_WRITE GROUP_READ WORLD_READ) + +endif(INSTALL_MBEDTLS_HEADERS) + +# Make config.h available in an out-of-source build. ssl-opt.sh requires it. +if (ENABLE_TESTING AND NOT ${CMAKE_CURRENT_BINARY_DIR} STREQUAL ${CMAKE_CURRENT_SOURCE_DIR}) + link_to_source(mbedtls) +endif() diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/aes.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/aes.h new file mode 100644 index 0000000000000000000000000000000000000000..94e7282d36d0f515236550e31b6de25b808f0280 --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/aes.h @@ -0,0 +1,674 @@ +/** + * \file aes.h + * + * \brief This file contains AES definitions and functions. + * + * The Advanced Encryption Standard (AES) specifies a FIPS-approved + * cryptographic algorithm that can be used to protect electronic + * data. + * + * The AES algorithm is a symmetric block cipher that can + * encrypt and decrypt information. For more information, see + * FIPS Publication 197: Advanced Encryption Standard and + * ISO/IEC 18033-2:2006: Information technology -- Security + * techniques -- Encryption algorithms -- Part 2: Asymmetric + * ciphers. + * + * The AES-XTS block mode is standardized by NIST SP 800-38E + * + * and described in detail by IEEE P1619 + * . + */ + +/* Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of Mbed TLS (https://tls.mbed.org) + */ + +#ifndef MBEDTLS_AES_H +#define MBEDTLS_AES_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include +#include + +/* padlock.c and aesni.c rely on these values! */ +#define MBEDTLS_AES_ENCRYPT 1 /**< AES encryption. */ +#define MBEDTLS_AES_DECRYPT 0 /**< AES decryption. */ + +/* Error codes in range 0x0020-0x0022 */ +#define MBEDTLS_ERR_AES_INVALID_KEY_LENGTH -0x0020 /**< Invalid key length. */ +#define MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH -0x0022 /**< Invalid data input length. */ + +/* Error codes in range 0x0021-0x0025 */ +#define MBEDTLS_ERR_AES_BAD_INPUT_DATA -0x0021 /**< Invalid input data. */ + +/* MBEDTLS_ERR_AES_FEATURE_UNAVAILABLE is deprecated and should not be used. */ +#define MBEDTLS_ERR_AES_FEATURE_UNAVAILABLE -0x0023 /**< Feature not available. For example, an unsupported AES key size. */ + +/* MBEDTLS_ERR_AES_HW_ACCEL_FAILED is deprecated and should not be used. */ +#define MBEDTLS_ERR_AES_HW_ACCEL_FAILED -0x0025 /**< AES hardware accelerator failed. */ + +#if ( defined(__ARMCC_VERSION) || defined(_MSC_VER) ) && \ + !defined(inline) && !defined(__cplusplus) +#define inline __inline +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +#if !defined(MBEDTLS_AES_ALT) +// Regular implementation +// + +/** + * \brief The AES context-type definition. + */ +typedef struct mbedtls_aes_context +{ + int nr; /*!< The number of rounds. */ + uint32_t *rk; /*!< AES round keys. */ + uint32_t buf[68]; /*!< Unaligned data buffer. This buffer can + hold 32 extra Bytes, which can be used for + one of the following purposes: +
                            • Alignment if VIA padlock is + used.
                            • +
                            • Simplifying key expansion in the 256-bit + case by generating an extra round key. +
                            */ +} +mbedtls_aes_context; + +#if defined(MBEDTLS_CIPHER_MODE_XTS) +/** + * \brief The AES XTS context-type definition. + */ +typedef struct mbedtls_aes_xts_context +{ + mbedtls_aes_context crypt; /*!< The AES context to use for AES block + encryption or decryption. */ + mbedtls_aes_context tweak; /*!< The AES context used for tweak + computation. */ +} mbedtls_aes_xts_context; +#endif /* MBEDTLS_CIPHER_MODE_XTS */ + +#else /* MBEDTLS_AES_ALT */ +#include "aes_alt.h" +#endif /* MBEDTLS_AES_ALT */ + +/** + * \brief This function initializes the specified AES context. + * + * It must be the first API called before using + * the context. + * + * \param ctx The AES context to initialize. This must not be \c NULL. + */ +void mbedtls_aes_init( mbedtls_aes_context *ctx ); + +/** + * \brief This function releases and clears the specified AES context. + * + * \param ctx The AES context to clear. + * If this is \c NULL, this function does nothing. + * Otherwise, the context must have been at least initialized. + */ +void mbedtls_aes_free( mbedtls_aes_context *ctx ); + +#if defined(MBEDTLS_CIPHER_MODE_XTS) +/** + * \brief This function initializes the specified AES XTS context. + * + * It must be the first API called before using + * the context. + * + * \param ctx The AES XTS context to initialize. This must not be \c NULL. + */ +void mbedtls_aes_xts_init( mbedtls_aes_xts_context *ctx ); + +/** + * \brief This function releases and clears the specified AES XTS context. + * + * \param ctx The AES XTS context to clear. + * If this is \c NULL, this function does nothing. + * Otherwise, the context must have been at least initialized. + */ +void mbedtls_aes_xts_free( mbedtls_aes_xts_context *ctx ); +#endif /* MBEDTLS_CIPHER_MODE_XTS */ + +/** + * \brief This function sets the encryption key. + * + * \param ctx The AES context to which the key should be bound. + * It must be initialized. + * \param key The encryption key. + * This must be a readable buffer of size \p keybits bits. + * \param keybits The size of data passed in bits. Valid options are: + *
                            • 128 bits
                            • + *
                            • 192 bits
                            • + *
                            • 256 bits
                            + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_AES_INVALID_KEY_LENGTH on failure. + */ +int mbedtls_aes_setkey_enc( mbedtls_aes_context *ctx, const unsigned char *key, + unsigned int keybits ); + +/** + * \brief This function sets the decryption key. + * + * \param ctx The AES context to which the key should be bound. + * It must be initialized. + * \param key The decryption key. + * This must be a readable buffer of size \p keybits bits. + * \param keybits The size of data passed. Valid options are: + *
                            • 128 bits
                            • + *
                            • 192 bits
                            • + *
                            • 256 bits
                            + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_AES_INVALID_KEY_LENGTH on failure. + */ +int mbedtls_aes_setkey_dec( mbedtls_aes_context *ctx, const unsigned char *key, + unsigned int keybits ); + +#if defined(MBEDTLS_CIPHER_MODE_XTS) +/** + * \brief This function prepares an XTS context for encryption and + * sets the encryption key. + * + * \param ctx The AES XTS context to which the key should be bound. + * It must be initialized. + * \param key The encryption key. This is comprised of the XTS key1 + * concatenated with the XTS key2. + * This must be a readable buffer of size \p keybits bits. + * \param keybits The size of \p key passed in bits. Valid options are: + *
                            • 256 bits (each of key1 and key2 is a 128-bit key)
                            • + *
                            • 512 bits (each of key1 and key2 is a 256-bit key)
                            + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_AES_INVALID_KEY_LENGTH on failure. + */ +int mbedtls_aes_xts_setkey_enc( mbedtls_aes_xts_context *ctx, + const unsigned char *key, + unsigned int keybits ); + +/** + * \brief This function prepares an XTS context for decryption and + * sets the decryption key. + * + * \param ctx The AES XTS context to which the key should be bound. + * It must be initialized. + * \param key The decryption key. This is comprised of the XTS key1 + * concatenated with the XTS key2. + * This must be a readable buffer of size \p keybits bits. + * \param keybits The size of \p key passed in bits. Valid options are: + *
                            • 256 bits (each of key1 and key2 is a 128-bit key)
                            • + *
                            • 512 bits (each of key1 and key2 is a 256-bit key)
                            + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_AES_INVALID_KEY_LENGTH on failure. + */ +int mbedtls_aes_xts_setkey_dec( mbedtls_aes_xts_context *ctx, + const unsigned char *key, + unsigned int keybits ); +#endif /* MBEDTLS_CIPHER_MODE_XTS */ + +/** + * \brief This function performs an AES single-block encryption or + * decryption operation. + * + * It performs the operation defined in the \p mode parameter + * (encrypt or decrypt), on the input data buffer defined in + * the \p input parameter. + * + * mbedtls_aes_init(), and either mbedtls_aes_setkey_enc() or + * mbedtls_aes_setkey_dec() must be called before the first + * call to this API with the same context. + * + * \param ctx The AES context to use for encryption or decryption. + * It must be initialized and bound to a key. + * \param mode The AES operation: #MBEDTLS_AES_ENCRYPT or + * #MBEDTLS_AES_DECRYPT. + * \param input The buffer holding the input data. + * It must be readable and at least \c 16 Bytes long. + * \param output The buffer where the output data will be written. + * It must be writeable and at least \c 16 Bytes long. + + * \return \c 0 on success. + */ +int mbedtls_aes_crypt_ecb( mbedtls_aes_context *ctx, + int mode, + const unsigned char input[16], + unsigned char output[16] ); + +#if defined(MBEDTLS_CIPHER_MODE_CBC) +/** + * \brief This function performs an AES-CBC encryption or decryption operation + * on full blocks. + * + * It performs the operation defined in the \p mode + * parameter (encrypt/decrypt), on the input data buffer defined in + * the \p input parameter. + * + * It can be called as many times as needed, until all the input + * data is processed. mbedtls_aes_init(), and either + * mbedtls_aes_setkey_enc() or mbedtls_aes_setkey_dec() must be called + * before the first call to this API with the same context. + * + * \note This function operates on full blocks, that is, the input size + * must be a multiple of the AES block size of \c 16 Bytes. + * + * \note Upon exit, the content of the IV is updated so that you can + * call the same function again on the next + * block(s) of data and get the same result as if it was + * encrypted in one call. This allows a "streaming" usage. + * If you need to retain the contents of the IV, you should + * either save it manually or use the cipher module instead. + * + * + * \param ctx The AES context to use for encryption or decryption. + * It must be initialized and bound to a key. + * \param mode The AES operation: #MBEDTLS_AES_ENCRYPT or + * #MBEDTLS_AES_DECRYPT. + * \param length The length of the input data in Bytes. This must be a + * multiple of the block size (\c 16 Bytes). + * \param iv Initialization vector (updated after use). + * It must be a readable and writeable buffer of \c 16 Bytes. + * \param input The buffer holding the input data. + * It must be readable and of size \p length Bytes. + * \param output The buffer holding the output data. + * It must be writeable and of size \p length Bytes. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH + * on failure. + */ +int mbedtls_aes_crypt_cbc( mbedtls_aes_context *ctx, + int mode, + size_t length, + unsigned char iv[16], + const unsigned char *input, + unsigned char *output ); +#endif /* MBEDTLS_CIPHER_MODE_CBC */ + +#if defined(MBEDTLS_CIPHER_MODE_XTS) +/** + * \brief This function performs an AES-XTS encryption or decryption + * operation for an entire XTS data unit. + * + * AES-XTS encrypts or decrypts blocks based on their location as + * defined by a data unit number. The data unit number must be + * provided by \p data_unit. + * + * NIST SP 800-38E limits the maximum size of a data unit to 2^20 + * AES blocks. If the data unit is larger than this, this function + * returns #MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH. + * + * \param ctx The AES XTS context to use for AES XTS operations. + * It must be initialized and bound to a key. + * \param mode The AES operation: #MBEDTLS_AES_ENCRYPT or + * #MBEDTLS_AES_DECRYPT. + * \param length The length of a data unit in Bytes. This can be any + * length between 16 bytes and 2^24 bytes inclusive + * (between 1 and 2^20 block cipher blocks). + * \param data_unit The address of the data unit encoded as an array of 16 + * bytes in little-endian format. For disk encryption, this + * is typically the index of the block device sector that + * contains the data. + * \param input The buffer holding the input data (which is an entire + * data unit). This function reads \p length Bytes from \p + * input. + * \param output The buffer holding the output data (which is an entire + * data unit). This function writes \p length Bytes to \p + * output. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH if \p length is + * smaller than an AES block in size (16 Bytes) or if \p + * length is larger than 2^20 blocks (16 MiB). + */ +int mbedtls_aes_crypt_xts( mbedtls_aes_xts_context *ctx, + int mode, + size_t length, + const unsigned char data_unit[16], + const unsigned char *input, + unsigned char *output ); +#endif /* MBEDTLS_CIPHER_MODE_XTS */ + +#if defined(MBEDTLS_CIPHER_MODE_CFB) +/** + * \brief This function performs an AES-CFB128 encryption or decryption + * operation. + * + * It performs the operation defined in the \p mode + * parameter (encrypt or decrypt), on the input data buffer + * defined in the \p input parameter. + * + * For CFB, you must set up the context with mbedtls_aes_setkey_enc(), + * regardless of whether you are performing an encryption or decryption + * operation, that is, regardless of the \p mode parameter. This is + * because CFB mode uses the same key schedule for encryption and + * decryption. + * + * \note Upon exit, the content of the IV is updated so that you can + * call the same function again on the next + * block(s) of data and get the same result as if it was + * encrypted in one call. This allows a "streaming" usage. + * If you need to retain the contents of the + * IV, you must either save it manually or use the cipher + * module instead. + * + * + * \param ctx The AES context to use for encryption or decryption. + * It must be initialized and bound to a key. + * \param mode The AES operation: #MBEDTLS_AES_ENCRYPT or + * #MBEDTLS_AES_DECRYPT. + * \param length The length of the input data in Bytes. + * \param iv_off The offset in IV (updated after use). + * It must point to a valid \c size_t. + * \param iv The initialization vector (updated after use). + * It must be a readable and writeable buffer of \c 16 Bytes. + * \param input The buffer holding the input data. + * It must be readable and of size \p length Bytes. + * \param output The buffer holding the output data. + * It must be writeable and of size \p length Bytes. + * + * \return \c 0 on success. + */ +int mbedtls_aes_crypt_cfb128( mbedtls_aes_context *ctx, + int mode, + size_t length, + size_t *iv_off, + unsigned char iv[16], + const unsigned char *input, + unsigned char *output ); + +/** + * \brief This function performs an AES-CFB8 encryption or decryption + * operation. + * + * It performs the operation defined in the \p mode + * parameter (encrypt/decrypt), on the input data buffer defined + * in the \p input parameter. + * + * Due to the nature of CFB, you must use the same key schedule for + * both encryption and decryption operations. Therefore, you must + * use the context initialized with mbedtls_aes_setkey_enc() for + * both #MBEDTLS_AES_ENCRYPT and #MBEDTLS_AES_DECRYPT. + * + * \note Upon exit, the content of the IV is updated so that you can + * call the same function again on the next + * block(s) of data and get the same result as if it was + * encrypted in one call. This allows a "streaming" usage. + * If you need to retain the contents of the + * IV, you should either save it manually or use the cipher + * module instead. + * + * + * \param ctx The AES context to use for encryption or decryption. + * It must be initialized and bound to a key. + * \param mode The AES operation: #MBEDTLS_AES_ENCRYPT or + * #MBEDTLS_AES_DECRYPT + * \param length The length of the input data. + * \param iv The initialization vector (updated after use). + * It must be a readable and writeable buffer of \c 16 Bytes. + * \param input The buffer holding the input data. + * It must be readable and of size \p length Bytes. + * \param output The buffer holding the output data. + * It must be writeable and of size \p length Bytes. + * + * \return \c 0 on success. + */ +int mbedtls_aes_crypt_cfb8( mbedtls_aes_context *ctx, + int mode, + size_t length, + unsigned char iv[16], + const unsigned char *input, + unsigned char *output ); +#endif /*MBEDTLS_CIPHER_MODE_CFB */ + +#if defined(MBEDTLS_CIPHER_MODE_OFB) +/** + * \brief This function performs an AES-OFB (Output Feedback Mode) + * encryption or decryption operation. + * + * For OFB, you must set up the context with + * mbedtls_aes_setkey_enc(), regardless of whether you are + * performing an encryption or decryption operation. This is + * because OFB mode uses the same key schedule for encryption and + * decryption. + * + * The OFB operation is identical for encryption or decryption, + * therefore no operation mode needs to be specified. + * + * \note Upon exit, the content of iv, the Initialisation Vector, is + * updated so that you can call the same function again on the next + * block(s) of data and get the same result as if it was encrypted + * in one call. This allows a "streaming" usage, by initialising + * iv_off to 0 before the first call, and preserving its value + * between calls. + * + * For non-streaming use, the iv should be initialised on each call + * to a unique value, and iv_off set to 0 on each call. + * + * If you need to retain the contents of the initialisation vector, + * you must either save it manually or use the cipher module + * instead. + * + * \warning For the OFB mode, the initialisation vector must be unique + * every encryption operation. Reuse of an initialisation vector + * will compromise security. + * + * \param ctx The AES context to use for encryption or decryption. + * It must be initialized and bound to a key. + * \param length The length of the input data. + * \param iv_off The offset in IV (updated after use). + * It must point to a valid \c size_t. + * \param iv The initialization vector (updated after use). + * It must be a readable and writeable buffer of \c 16 Bytes. + * \param input The buffer holding the input data. + * It must be readable and of size \p length Bytes. + * \param output The buffer holding the output data. + * It must be writeable and of size \p length Bytes. + * + * \return \c 0 on success. + */ +int mbedtls_aes_crypt_ofb( mbedtls_aes_context *ctx, + size_t length, + size_t *iv_off, + unsigned char iv[16], + const unsigned char *input, + unsigned char *output ); + +#endif /* MBEDTLS_CIPHER_MODE_OFB */ + +#if defined(MBEDTLS_CIPHER_MODE_CTR) +/** + * \brief This function performs an AES-CTR encryption or decryption + * operation. + * + * This function performs the operation defined in the \p mode + * parameter (encrypt/decrypt), on the input data buffer + * defined in the \p input parameter. + * + * Due to the nature of CTR, you must use the same key schedule + * for both encryption and decryption operations. Therefore, you + * must use the context initialized with mbedtls_aes_setkey_enc() + * for both #MBEDTLS_AES_ENCRYPT and #MBEDTLS_AES_DECRYPT. + * + * \warning You must never reuse a nonce value with the same key. Doing so + * would void the encryption for the two messages encrypted with + * the same nonce and key. + * + * There are two common strategies for managing nonces with CTR: + * + * 1. You can handle everything as a single message processed over + * successive calls to this function. In that case, you want to + * set \p nonce_counter and \p nc_off to 0 for the first call, and + * then preserve the values of \p nonce_counter, \p nc_off and \p + * stream_block across calls to this function as they will be + * updated by this function. + * + * With this strategy, you must not encrypt more than 2**128 + * blocks of data with the same key. + * + * 2. You can encrypt separate messages by dividing the \p + * nonce_counter buffer in two areas: the first one used for a + * per-message nonce, handled by yourself, and the second one + * updated by this function internally. + * + * For example, you might reserve the first 12 bytes for the + * per-message nonce, and the last 4 bytes for internal use. In that + * case, before calling this function on a new message you need to + * set the first 12 bytes of \p nonce_counter to your chosen nonce + * value, the last 4 to 0, and \p nc_off to 0 (which will cause \p + * stream_block to be ignored). That way, you can encrypt at most + * 2**96 messages of up to 2**32 blocks each with the same key. + * + * The per-message nonce (or information sufficient to reconstruct + * it) needs to be communicated with the ciphertext and must be unique. + * The recommended way to ensure uniqueness is to use a message + * counter. An alternative is to generate random nonces, but this + * limits the number of messages that can be securely encrypted: + * for example, with 96-bit random nonces, you should not encrypt + * more than 2**32 messages with the same key. + * + * Note that for both stategies, sizes are measured in blocks and + * that an AES block is 16 bytes. + * + * \warning Upon return, \p stream_block contains sensitive data. Its + * content must not be written to insecure storage and should be + * securely discarded as soon as it's no longer needed. + * + * \param ctx The AES context to use for encryption or decryption. + * It must be initialized and bound to a key. + * \param length The length of the input data. + * \param nc_off The offset in the current \p stream_block, for + * resuming within the current cipher stream. The + * offset pointer should be 0 at the start of a stream. + * It must point to a valid \c size_t. + * \param nonce_counter The 128-bit nonce and counter. + * It must be a readable-writeable buffer of \c 16 Bytes. + * \param stream_block The saved stream block for resuming. This is + * overwritten by the function. + * It must be a readable-writeable buffer of \c 16 Bytes. + * \param input The buffer holding the input data. + * It must be readable and of size \p length Bytes. + * \param output The buffer holding the output data. + * It must be writeable and of size \p length Bytes. + * + * \return \c 0 on success. + */ +int mbedtls_aes_crypt_ctr( mbedtls_aes_context *ctx, + size_t length, + size_t *nc_off, + unsigned char nonce_counter[16], + unsigned char stream_block[16], + const unsigned char *input, + unsigned char *output ); +#endif /* MBEDTLS_CIPHER_MODE_CTR */ + +/** + * \brief Internal AES block encryption function. This is only + * exposed to allow overriding it using + * \c MBEDTLS_AES_ENCRYPT_ALT. + * + * \param ctx The AES context to use for encryption. + * \param input The plaintext block. + * \param output The output (ciphertext) block. + * + * \return \c 0 on success. + */ +int mbedtls_internal_aes_encrypt( mbedtls_aes_context *ctx, + const unsigned char input[16], + unsigned char output[16] ); + +/** + * \brief Internal AES block decryption function. This is only + * exposed to allow overriding it using see + * \c MBEDTLS_AES_DECRYPT_ALT. + * + * \param ctx The AES context to use for decryption. + * \param input The ciphertext block. + * \param output The output (plaintext) block. + * + * \return \c 0 on success. + */ +int mbedtls_internal_aes_decrypt( mbedtls_aes_context *ctx, + const unsigned char input[16], + unsigned char output[16] ); + +#if !defined(MBEDTLS_DEPRECATED_REMOVED) +#if defined(MBEDTLS_DEPRECATED_WARNING) +#define MBEDTLS_DEPRECATED __attribute__((deprecated)) +#else +#define MBEDTLS_DEPRECATED +#endif +/** + * \brief Deprecated internal AES block encryption function + * without return value. + * + * \deprecated Superseded by mbedtls_internal_aes_encrypt() + * + * \param ctx The AES context to use for encryption. + * \param input Plaintext block. + * \param output Output (ciphertext) block. + */ +MBEDTLS_DEPRECATED void mbedtls_aes_encrypt( mbedtls_aes_context *ctx, + const unsigned char input[16], + unsigned char output[16] ); + +/** + * \brief Deprecated internal AES block decryption function + * without return value. + * + * \deprecated Superseded by mbedtls_internal_aes_decrypt() + * + * \param ctx The AES context to use for decryption. + * \param input Ciphertext block. + * \param output Output (plaintext) block. + */ +MBEDTLS_DEPRECATED void mbedtls_aes_decrypt( mbedtls_aes_context *ctx, + const unsigned char input[16], + unsigned char output[16] ); + +#undef MBEDTLS_DEPRECATED +#endif /* !MBEDTLS_DEPRECATED_REMOVED */ + + +#if defined(MBEDTLS_SELF_TEST) +/** + * \brief Checkup routine. + * + * \return \c 0 on success. + * \return \c 1 on failure. + */ +int mbedtls_aes_self_test( int verbose ); + +#endif /* MBEDTLS_SELF_TEST */ + +#ifdef __cplusplus +} +#endif + +#endif /* aes.h */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/aes_alt.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/aes_alt.h new file mode 100644 index 0000000000000000000000000000000000000000..a80cc4f3b0b71fda2d779c6790c5e8a955d2b3a1 --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/aes_alt.h @@ -0,0 +1,61 @@ +/** + * \file aes.h + * + * \brief This file contains AES definitions and functions. + * + * The Advanced Encryption Standard (AES) specifies a FIPS-approved + * cryptographic algorithm that can be used to protect electronic + * data. + * + * The AES algorithm is a symmetric block cipher that can + * encrypt and decrypt information. For more information, see + * FIPS Publication 197: Advanced Encryption Standard and + * ISO/IEC 18033-2:2006: Information technology -- Security + * techniques -- Encryption algorithms -- Part 2: Asymmetric + * ciphers. + * + * The AES-XTS block mode is standardized by NIST SP 800-38E + * + * and described in detail by IEEE P1619 + * . + */ + +/* Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of Mbed TLS (https://tls.mbed.org) + */ + +#ifndef MBEDTLS_AES_ALT_H +#define MBEDTLS_AES_ALT_H +#include "hi_cipher.h" +#include "securec.h" +/** + * \brief The AES context-type definition. + */ +#define mbedtls_aes_context hi_cipher_aes_ctrl + +#if defined(MBEDTLS_CIPHER_MODE_XTS) +typedef struct mbedtls_aes_xts_context +{ + mbedtls_aes_context crypt; /*!< The AES context to use for AES block + encryption or decryption. */ + mbedtls_aes_context tweak; /*!< The AES context used for tweak + computation. */ +} mbedtls_aes_xts_context; + +#endif /* MBEDTLS_CIPHER_MODE_XTS */ + +#endif /* aes_alt.h */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/aesni.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/aesni.h new file mode 100644 index 0000000000000000000000000000000000000000..a4ca012f8a10d8534c6601025b66f2669ae42ab6 --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/aesni.h @@ -0,0 +1,138 @@ +/** + * \file aesni.h + * + * \brief AES-NI for hardware AES acceleration on some Intel processors + * + * \warning These functions are only for internal use by other library + * functions; you must not call them directly. + */ +/* + * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ +#ifndef MBEDTLS_AESNI_H +#define MBEDTLS_AESNI_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include "aes.h" + +#define MBEDTLS_AESNI_AES 0x02000000u +#define MBEDTLS_AESNI_CLMUL 0x00000002u + +#if defined(MBEDTLS_HAVE_ASM) && defined(__GNUC__) && \ + ( defined(__amd64__) || defined(__x86_64__) ) && \ + ! defined(MBEDTLS_HAVE_X86_64) +#define MBEDTLS_HAVE_X86_64 +#endif + +#if defined(MBEDTLS_HAVE_X86_64) + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \brief Internal function to detect the AES-NI feature in CPUs. + * + * \note This function is only for internal use by other library + * functions; you must not call it directly. + * + * \param what The feature to detect + * (MBEDTLS_AESNI_AES or MBEDTLS_AESNI_CLMUL) + * + * \return 1 if CPU has support for the feature, 0 otherwise + */ +int mbedtls_aesni_has_support( unsigned int what ); + +/** + * \brief Internal AES-NI AES-ECB block encryption and decryption + * + * \note This function is only for internal use by other library + * functions; you must not call it directly. + * + * \param ctx AES context + * \param mode MBEDTLS_AES_ENCRYPT or MBEDTLS_AES_DECRYPT + * \param input 16-byte input block + * \param output 16-byte output block + * + * \return 0 on success (cannot fail) + */ +int mbedtls_aesni_crypt_ecb( mbedtls_aes_context *ctx, + int mode, + const unsigned char input[16], + unsigned char output[16] ); + +/** + * \brief Internal GCM multiplication: c = a * b in GF(2^128) + * + * \note This function is only for internal use by other library + * functions; you must not call it directly. + * + * \param c Result + * \param a First operand + * \param b Second operand + * + * \note Both operands and result are bit strings interpreted as + * elements of GF(2^128) as per the GCM spec. + */ +void mbedtls_aesni_gcm_mult( unsigned char c[16], + const unsigned char a[16], + const unsigned char b[16] ); + +/** + * \brief Internal round key inversion. This function computes + * decryption round keys from the encryption round keys. + * + * \note This function is only for internal use by other library + * functions; you must not call it directly. + * + * \param invkey Round keys for the equivalent inverse cipher + * \param fwdkey Original round keys (for encryption) + * \param nr Number of rounds (that is, number of round keys minus one) + */ +void mbedtls_aesni_inverse_key( unsigned char *invkey, + const unsigned char *fwdkey, + int nr ); + +/** + * \brief Internal key expansion for encryption + * + * \note This function is only for internal use by other library + * functions; you must not call it directly. + * + * \param rk Destination buffer where the round keys are written + * \param key Encryption key + * \param bits Key size in bits (must be 128, 192 or 256) + * + * \return 0 if successful, or MBEDTLS_ERR_AES_INVALID_KEY_LENGTH + */ +int mbedtls_aesni_setkey_enc( unsigned char *rk, + const unsigned char *key, + size_t bits ); + +#ifdef __cplusplus +} +#endif + +#endif /* MBEDTLS_HAVE_X86_64 */ + +#endif /* MBEDTLS_AESNI_H */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/arc4.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/arc4.h new file mode 100644 index 0000000000000000000000000000000000000000..fb044d5b7fd33d4a2f8b25192a29ec31b8b6f3be --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/arc4.h @@ -0,0 +1,146 @@ +/** + * \file arc4.h + * + * \brief The ARCFOUR stream cipher + * + * \warning ARC4 is considered a weak cipher and its use constitutes a + * security risk. We recommend considering stronger ciphers instead. + */ +/* + * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + * + */ +#ifndef MBEDTLS_ARC4_H +#define MBEDTLS_ARC4_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include + +/* MBEDTLS_ERR_ARC4_HW_ACCEL_FAILED is deprecated and should not be used. */ +#define MBEDTLS_ERR_ARC4_HW_ACCEL_FAILED -0x0019 /**< ARC4 hardware accelerator failed. */ + +#ifdef __cplusplus +extern "C" { +#endif + +#if !defined(MBEDTLS_ARC4_ALT) +// Regular implementation +// + +/** + * \brief ARC4 context structure + * + * \warning ARC4 is considered a weak cipher and its use constitutes a + * security risk. We recommend considering stronger ciphers instead. + * + */ +typedef struct mbedtls_arc4_context +{ + int x; /*!< permutation index */ + int y; /*!< permutation index */ + unsigned char m[256]; /*!< permutation table */ +} +mbedtls_arc4_context; + +#else /* MBEDTLS_ARC4_ALT */ +#include "arc4_alt.h" +#endif /* MBEDTLS_ARC4_ALT */ + +/** + * \brief Initialize ARC4 context + * + * \param ctx ARC4 context to be initialized + * + * \warning ARC4 is considered a weak cipher and its use constitutes a + * security risk. We recommend considering stronger ciphers + * instead. + * + */ +void mbedtls_arc4_init( mbedtls_arc4_context *ctx ); + +/** + * \brief Clear ARC4 context + * + * \param ctx ARC4 context to be cleared + * + * \warning ARC4 is considered a weak cipher and its use constitutes a + * security risk. We recommend considering stronger ciphers + * instead. + * + */ +void mbedtls_arc4_free( mbedtls_arc4_context *ctx ); + +/** + * \brief ARC4 key schedule + * + * \param ctx ARC4 context to be setup + * \param key the secret key + * \param keylen length of the key, in bytes + * + * \warning ARC4 is considered a weak cipher and its use constitutes a + * security risk. We recommend considering stronger ciphers + * instead. + * + */ +void mbedtls_arc4_setup( mbedtls_arc4_context *ctx, const unsigned char *key, + unsigned int keylen ); + +/** + * \brief ARC4 cipher function + * + * \param ctx ARC4 context + * \param length length of the input data + * \param input buffer holding the input data + * \param output buffer for the output data + * + * \return 0 if successful + * + * \warning ARC4 is considered a weak cipher and its use constitutes a + * security risk. We recommend considering stronger ciphers + * instead. + * + */ +int mbedtls_arc4_crypt( mbedtls_arc4_context *ctx, size_t length, const unsigned char *input, + unsigned char *output ); + +#if defined(MBEDTLS_SELF_TEST) + +/** + * \brief Checkup routine + * + * \return 0 if successful, or 1 if the test failed + * + * \warning ARC4 is considered a weak cipher and its use constitutes a + * security risk. We recommend considering stronger ciphers + * instead. + * + */ +int mbedtls_arc4_self_test( int verbose ); + +#endif /* MBEDTLS_SELF_TEST */ + +#ifdef __cplusplus +} +#endif + +#endif /* arc4.h */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/aria.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/aria.h new file mode 100644 index 0000000000000000000000000000000000000000..1e8956ed13c5955352cf19b35ac537c7fc57d1c1 --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/aria.h @@ -0,0 +1,370 @@ +/** + * \file aria.h + * + * \brief ARIA block cipher + * + * The ARIA algorithm is a symmetric block cipher that can encrypt and + * decrypt information. It is defined by the Korean Agency for + * Technology and Standards (KATS) in KS X 1213:2004 (in + * Korean, but see http://210.104.33.10/ARIA/index-e.html in English) + * and also described by the IETF in RFC 5794. + */ +/* Copyright (C) 2006-2018, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ + +#ifndef MBEDTLS_ARIA_H +#define MBEDTLS_ARIA_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include +#include + +#include "platform_util.h" + +#define MBEDTLS_ARIA_ENCRYPT 1 /**< ARIA encryption. */ +#define MBEDTLS_ARIA_DECRYPT 0 /**< ARIA decryption. */ + +#define MBEDTLS_ARIA_BLOCKSIZE 16 /**< ARIA block size in bytes. */ +#define MBEDTLS_ARIA_MAX_ROUNDS 16 /**< Maxiumum number of rounds in ARIA. */ +#define MBEDTLS_ARIA_MAX_KEYSIZE 32 /**< Maximum size of an ARIA key in bytes. */ + +#if !defined(MBEDTLS_DEPRECATED_REMOVED) +#define MBEDTLS_ERR_ARIA_INVALID_KEY_LENGTH MBEDTLS_DEPRECATED_NUMERIC_CONSTANT( -0x005C ) +#endif /* !MBEDTLS_DEPRECATED_REMOVED */ +#define MBEDTLS_ERR_ARIA_BAD_INPUT_DATA -0x005C /**< Bad input data. */ + +#define MBEDTLS_ERR_ARIA_INVALID_INPUT_LENGTH -0x005E /**< Invalid data input length. */ + +/* MBEDTLS_ERR_ARIA_FEATURE_UNAVAILABLE is deprecated and should not be used. + */ +#define MBEDTLS_ERR_ARIA_FEATURE_UNAVAILABLE -0x005A /**< Feature not available. For example, an unsupported ARIA key size. */ + +/* MBEDTLS_ERR_ARIA_HW_ACCEL_FAILED is deprecated and should not be used. */ +#define MBEDTLS_ERR_ARIA_HW_ACCEL_FAILED -0x0058 /**< ARIA hardware accelerator failed. */ + +#if !defined(MBEDTLS_ARIA_ALT) +// Regular implementation +// + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \brief The ARIA context-type definition. + */ +typedef struct mbedtls_aria_context +{ + unsigned char nr; /*!< The number of rounds (12, 14 or 16) */ + /*! The ARIA round keys. */ + uint32_t rk[MBEDTLS_ARIA_MAX_ROUNDS + 1][MBEDTLS_ARIA_BLOCKSIZE / 4]; +} +mbedtls_aria_context; + +#else /* MBEDTLS_ARIA_ALT */ +#include "aria_alt.h" +#endif /* MBEDTLS_ARIA_ALT */ + +/** + * \brief This function initializes the specified ARIA context. + * + * It must be the first API called before using + * the context. + * + * \param ctx The ARIA context to initialize. This must not be \c NULL. + */ +void mbedtls_aria_init( mbedtls_aria_context *ctx ); + +/** + * \brief This function releases and clears the specified ARIA context. + * + * \param ctx The ARIA context to clear. This may be \c NULL, in which + * case this function returns immediately. If it is not \c NULL, + * it must point to an initialized ARIA context. + */ +void mbedtls_aria_free( mbedtls_aria_context *ctx ); + +/** + * \brief This function sets the encryption key. + * + * \param ctx The ARIA context to which the key should be bound. + * This must be initialized. + * \param key The encryption key. This must be a readable buffer + * of size \p keybits Bits. + * \param keybits The size of \p key in Bits. Valid options are: + *
                            • 128 bits
                            • + *
                            • 192 bits
                            • + *
                            • 256 bits
                            + * + * \return \c 0 on success. + * \return A negative error code on failure. + */ +int mbedtls_aria_setkey_enc( mbedtls_aria_context *ctx, + const unsigned char *key, + unsigned int keybits ); + +/** + * \brief This function sets the decryption key. + * + * \param ctx The ARIA context to which the key should be bound. + * This must be initialized. + * \param key The decryption key. This must be a readable buffer + * of size \p keybits Bits. + * \param keybits The size of data passed. Valid options are: + *
                            • 128 bits
                            • + *
                            • 192 bits
                            • + *
                            • 256 bits
                            + * + * \return \c 0 on success. + * \return A negative error code on failure. + */ +int mbedtls_aria_setkey_dec( mbedtls_aria_context *ctx, + const unsigned char *key, + unsigned int keybits ); + +/** + * \brief This function performs an ARIA single-block encryption or + * decryption operation. + * + * It performs encryption or decryption (depending on whether + * the key was set for encryption on decryption) on the input + * data buffer defined in the \p input parameter. + * + * mbedtls_aria_init(), and either mbedtls_aria_setkey_enc() or + * mbedtls_aria_setkey_dec() must be called before the first + * call to this API with the same context. + * + * \param ctx The ARIA context to use for encryption or decryption. + * This must be initialized and bound to a key. + * \param input The 16-Byte buffer holding the input data. + * \param output The 16-Byte buffer holding the output data. + + * \return \c 0 on success. + * \return A negative error code on failure. + */ +int mbedtls_aria_crypt_ecb( mbedtls_aria_context *ctx, + const unsigned char input[MBEDTLS_ARIA_BLOCKSIZE], + unsigned char output[MBEDTLS_ARIA_BLOCKSIZE] ); + +#if defined(MBEDTLS_CIPHER_MODE_CBC) +/** + * \brief This function performs an ARIA-CBC encryption or decryption operation + * on full blocks. + * + * It performs the operation defined in the \p mode + * parameter (encrypt/decrypt), on the input data buffer defined in + * the \p input parameter. + * + * It can be called as many times as needed, until all the input + * data is processed. mbedtls_aria_init(), and either + * mbedtls_aria_setkey_enc() or mbedtls_aria_setkey_dec() must be called + * before the first call to this API with the same context. + * + * \note This function operates on aligned blocks, that is, the input size + * must be a multiple of the ARIA block size of 16 Bytes. + * + * \note Upon exit, the content of the IV is updated so that you can + * call the same function again on the next + * block(s) of data and get the same result as if it was + * encrypted in one call. This allows a "streaming" usage. + * If you need to retain the contents of the IV, you should + * either save it manually or use the cipher module instead. + * + * + * \param ctx The ARIA context to use for encryption or decryption. + * This must be initialized and bound to a key. + * \param mode The mode of operation. This must be either + * #MBEDTLS_ARIA_ENCRYPT for encryption, or + * #MBEDTLS_ARIA_DECRYPT for decryption. + * \param length The length of the input data in Bytes. This must be a + * multiple of the block size (16 Bytes). + * \param iv Initialization vector (updated after use). + * This must be a readable buffer of size 16 Bytes. + * \param input The buffer holding the input data. This must + * be a readable buffer of length \p length Bytes. + * \param output The buffer holding the output data. This must + * be a writable buffer of length \p length Bytes. + * + * \return \c 0 on success. + * \return A negative error code on failure. + */ +int mbedtls_aria_crypt_cbc( mbedtls_aria_context *ctx, + int mode, + size_t length, + unsigned char iv[MBEDTLS_ARIA_BLOCKSIZE], + const unsigned char *input, + unsigned char *output ); +#endif /* MBEDTLS_CIPHER_MODE_CBC */ + +#if defined(MBEDTLS_CIPHER_MODE_CFB) +/** + * \brief This function performs an ARIA-CFB128 encryption or decryption + * operation. + * + * It performs the operation defined in the \p mode + * parameter (encrypt or decrypt), on the input data buffer + * defined in the \p input parameter. + * + * For CFB, you must set up the context with mbedtls_aria_setkey_enc(), + * regardless of whether you are performing an encryption or decryption + * operation, that is, regardless of the \p mode parameter. This is + * because CFB mode uses the same key schedule for encryption and + * decryption. + * + * \note Upon exit, the content of the IV is updated so that you can + * call the same function again on the next + * block(s) of data and get the same result as if it was + * encrypted in one call. This allows a "streaming" usage. + * If you need to retain the contents of the + * IV, you must either save it manually or use the cipher + * module instead. + * + * + * \param ctx The ARIA context to use for encryption or decryption. + * This must be initialized and bound to a key. + * \param mode The mode of operation. This must be either + * #MBEDTLS_ARIA_ENCRYPT for encryption, or + * #MBEDTLS_ARIA_DECRYPT for decryption. + * \param length The length of the input data \p input in Bytes. + * \param iv_off The offset in IV (updated after use). + * This must not be larger than 15. + * \param iv The initialization vector (updated after use). + * This must be a readable buffer of size 16 Bytes. + * \param input The buffer holding the input data. This must + * be a readable buffer of length \p length Bytes. + * \param output The buffer holding the output data. This must + * be a writable buffer of length \p length Bytes. + * + * \return \c 0 on success. + * \return A negative error code on failure. + */ +int mbedtls_aria_crypt_cfb128( mbedtls_aria_context *ctx, + int mode, + size_t length, + size_t *iv_off, + unsigned char iv[MBEDTLS_ARIA_BLOCKSIZE], + const unsigned char *input, + unsigned char *output ); +#endif /* MBEDTLS_CIPHER_MODE_CFB */ + +#if defined(MBEDTLS_CIPHER_MODE_CTR) +/** + * \brief This function performs an ARIA-CTR encryption or decryption + * operation. + * + * This function performs the operation defined in the \p mode + * parameter (encrypt/decrypt), on the input data buffer + * defined in the \p input parameter. + * + * Due to the nature of CTR, you must use the same key schedule + * for both encryption and decryption operations. Therefore, you + * must use the context initialized with mbedtls_aria_setkey_enc() + * for both #MBEDTLS_ARIA_ENCRYPT and #MBEDTLS_ARIA_DECRYPT. + * + * \warning You must never reuse a nonce value with the same key. Doing so + * would void the encryption for the two messages encrypted with + * the same nonce and key. + * + * There are two common strategies for managing nonces with CTR: + * + * 1. You can handle everything as a single message processed over + * successive calls to this function. In that case, you want to + * set \p nonce_counter and \p nc_off to 0 for the first call, and + * then preserve the values of \p nonce_counter, \p nc_off and \p + * stream_block across calls to this function as they will be + * updated by this function. + * + * With this strategy, you must not encrypt more than 2**128 + * blocks of data with the same key. + * + * 2. You can encrypt separate messages by dividing the \p + * nonce_counter buffer in two areas: the first one used for a + * per-message nonce, handled by yourself, and the second one + * updated by this function internally. + * + * For example, you might reserve the first 12 bytes for the + * per-message nonce, and the last 4 bytes for internal use. In that + * case, before calling this function on a new message you need to + * set the first 12 bytes of \p nonce_counter to your chosen nonce + * value, the last 4 to 0, and \p nc_off to 0 (which will cause \p + * stream_block to be ignored). That way, you can encrypt at most + * 2**96 messages of up to 2**32 blocks each with the same key. + * + * The per-message nonce (or information sufficient to reconstruct + * it) needs to be communicated with the ciphertext and must be unique. + * The recommended way to ensure uniqueness is to use a message + * counter. An alternative is to generate random nonces, but this + * limits the number of messages that can be securely encrypted: + * for example, with 96-bit random nonces, you should not encrypt + * more than 2**32 messages with the same key. + * + * Note that for both stategies, sizes are measured in blocks and + * that an ARIA block is 16 bytes. + * + * \warning Upon return, \p stream_block contains sensitive data. Its + * content must not be written to insecure storage and should be + * securely discarded as soon as it's no longer needed. + * + * \param ctx The ARIA context to use for encryption or decryption. + * This must be initialized and bound to a key. + * \param length The length of the input data \p input in Bytes. + * \param nc_off The offset in Bytes in the current \p stream_block, + * for resuming within the current cipher stream. The + * offset pointer should be \c 0 at the start of a + * stream. This must not be larger than \c 15 Bytes. + * \param nonce_counter The 128-bit nonce and counter. This must point to + * a read/write buffer of length \c 16 bytes. + * \param stream_block The saved stream block for resuming. This must + * point to a read/write buffer of length \c 16 bytes. + * This is overwritten by the function. + * \param input The buffer holding the input data. This must + * be a readable buffer of length \p length Bytes. + * \param output The buffer holding the output data. This must + * be a writable buffer of length \p length Bytes. + * + * \return \c 0 on success. + * \return A negative error code on failure. + */ +int mbedtls_aria_crypt_ctr( mbedtls_aria_context *ctx, + size_t length, + size_t *nc_off, + unsigned char nonce_counter[MBEDTLS_ARIA_BLOCKSIZE], + unsigned char stream_block[MBEDTLS_ARIA_BLOCKSIZE], + const unsigned char *input, + unsigned char *output ); +#endif /* MBEDTLS_CIPHER_MODE_CTR */ + +#if defined(MBEDTLS_SELF_TEST) +/** + * \brief Checkup routine. + * + * \return \c 0 on success, or \c 1 on failure. + */ +int mbedtls_aria_self_test( int verbose ); +#endif /* MBEDTLS_SELF_TEST */ + +#ifdef __cplusplus +} +#endif + +#endif /* aria.h */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/asn1.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/asn1.h new file mode 100644 index 0000000000000000000000000000000000000000..96c1c9a8ab217573cd4c3775eb13f8314962532d --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/asn1.h @@ -0,0 +1,358 @@ +/** + * \file asn1.h + * + * \brief Generic ASN.1 parsing + */ +/* + * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ +#ifndef MBEDTLS_ASN1_H +#define MBEDTLS_ASN1_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include + +#if defined(MBEDTLS_BIGNUM_C) +#include "bignum.h" +#endif + +/** + * \addtogroup asn1_module + * \{ + */ + +/** + * \name ASN1 Error codes + * These error codes are OR'ed to X509 error codes for + * higher error granularity. + * ASN1 is a standard to specify data structures. + * \{ + */ +#define MBEDTLS_ERR_ASN1_OUT_OF_DATA -0x0060 /**< Out of data when parsing an ASN1 data structure. */ +#define MBEDTLS_ERR_ASN1_UNEXPECTED_TAG -0x0062 /**< ASN1 tag was of an unexpected value. */ +#define MBEDTLS_ERR_ASN1_INVALID_LENGTH -0x0064 /**< Error when trying to determine the length or invalid length. */ +#define MBEDTLS_ERR_ASN1_LENGTH_MISMATCH -0x0066 /**< Actual length differs from expected length. */ +#define MBEDTLS_ERR_ASN1_INVALID_DATA -0x0068 /**< Data is invalid. (not used) */ +#define MBEDTLS_ERR_ASN1_ALLOC_FAILED -0x006A /**< Memory allocation failed */ +#define MBEDTLS_ERR_ASN1_BUF_TOO_SMALL -0x006C /**< Buffer too small when writing ASN.1 data structure. */ + +/* \} name */ + +/** + * \name DER constants + * These constants comply with the DER encoded ASN.1 type tags. + * DER encoding uses hexadecimal representation. + * An example DER sequence is:\n + * - 0x02 -- tag indicating INTEGER + * - 0x01 -- length in octets + * - 0x05 -- value + * Such sequences are typically read into \c ::mbedtls_x509_buf. + * \{ + */ +#define MBEDTLS_ASN1_BOOLEAN 0x01 +#define MBEDTLS_ASN1_INTEGER 0x02 +#define MBEDTLS_ASN1_BIT_STRING 0x03 +#define MBEDTLS_ASN1_OCTET_STRING 0x04 +#define MBEDTLS_ASN1_NULL 0x05 +#define MBEDTLS_ASN1_OID 0x06 +#define MBEDTLS_ASN1_UTF8_STRING 0x0C +#define MBEDTLS_ASN1_SEQUENCE 0x10 +#define MBEDTLS_ASN1_SET 0x11 +#define MBEDTLS_ASN1_PRINTABLE_STRING 0x13 +#define MBEDTLS_ASN1_T61_STRING 0x14 +#define MBEDTLS_ASN1_IA5_STRING 0x16 +#define MBEDTLS_ASN1_UTC_TIME 0x17 +#define MBEDTLS_ASN1_GENERALIZED_TIME 0x18 +#define MBEDTLS_ASN1_UNIVERSAL_STRING 0x1C +#define MBEDTLS_ASN1_BMP_STRING 0x1E +#define MBEDTLS_ASN1_PRIMITIVE 0x00 +#define MBEDTLS_ASN1_CONSTRUCTED 0x20 +#define MBEDTLS_ASN1_CONTEXT_SPECIFIC 0x80 + +/* + * Bit masks for each of the components of an ASN.1 tag as specified in + * ITU X.690 (08/2015), section 8.1 "General rules for encoding", + * paragraph 8.1.2.2: + * + * Bit 8 7 6 5 1 + * +-------+-----+------------+ + * | Class | P/C | Tag number | + * +-------+-----+------------+ + */ +#define MBEDTLS_ASN1_TAG_CLASS_MASK 0xC0 +#define MBEDTLS_ASN1_TAG_PC_MASK 0x20 +#define MBEDTLS_ASN1_TAG_VALUE_MASK 0x1F + +/* \} name */ +/* \} addtogroup asn1_module */ + +/** Returns the size of the binary string, without the trailing \\0 */ +#define MBEDTLS_OID_SIZE(x) (sizeof(x) - 1) + +/** + * Compares an mbedtls_asn1_buf structure to a reference OID. + * + * Only works for 'defined' oid_str values (MBEDTLS_OID_HMAC_SHA1), you cannot use a + * 'unsigned char *oid' here! + */ +#define MBEDTLS_OID_CMP(oid_str, oid_buf) \ + ( ( MBEDTLS_OID_SIZE(oid_str) != (oid_buf)->len ) || \ + memcmp( (oid_str), (oid_buf)->p, (oid_buf)->len) != 0 ) + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \name Functions to parse ASN.1 data structures + * \{ + */ + +/** + * Type-length-value structure that allows for ASN1 using DER. + */ +typedef struct mbedtls_asn1_buf +{ + int tag; /**< ASN1 type, e.g. MBEDTLS_ASN1_UTF8_STRING. */ + size_t len; /**< ASN1 length, in octets. */ + unsigned char *p; /**< ASN1 data, e.g. in ASCII. */ +} +mbedtls_asn1_buf; + +/** + * Container for ASN1 bit strings. + */ +typedef struct mbedtls_asn1_bitstring +{ + size_t len; /**< ASN1 length, in octets. */ + unsigned char unused_bits; /**< Number of unused bits at the end of the string */ + unsigned char *p; /**< Raw ASN1 data for the bit string */ +} +mbedtls_asn1_bitstring; + +/** + * Container for a sequence of ASN.1 items + */ +typedef struct mbedtls_asn1_sequence +{ + mbedtls_asn1_buf buf; /**< Buffer containing the given ASN.1 item. */ + struct mbedtls_asn1_sequence *next; /**< The next entry in the sequence. */ +} +mbedtls_asn1_sequence; + +/** + * Container for a sequence or list of 'named' ASN.1 data items + */ +typedef struct mbedtls_asn1_named_data +{ + mbedtls_asn1_buf oid; /**< The object identifier. */ + mbedtls_asn1_buf val; /**< The named value. */ + struct mbedtls_asn1_named_data *next; /**< The next entry in the sequence. */ + unsigned char next_merged; /**< Merge next item into the current one? */ +} +mbedtls_asn1_named_data; + +/** + * \brief Get the length of an ASN.1 element. + * Updates the pointer to immediately behind the length. + * + * \param p The position in the ASN.1 data + * \param end End of data + * \param len The variable that will receive the value + * + * \return 0 if successful, MBEDTLS_ERR_ASN1_OUT_OF_DATA on reaching + * end of data, MBEDTLS_ERR_ASN1_INVALID_LENGTH if length is + * unparseable. + */ +int mbedtls_asn1_get_len( unsigned char **p, + const unsigned char *end, + size_t *len ); + +/** + * \brief Get the tag and length of the tag. Check for the requested tag. + * Updates the pointer to immediately behind the tag and length. + * + * \param p The position in the ASN.1 data + * \param end End of data + * \param len The variable that will receive the length + * \param tag The expected tag + * + * \return 0 if successful, MBEDTLS_ERR_ASN1_UNEXPECTED_TAG if tag did + * not match requested tag, or another specific ASN.1 error code. + */ +int mbedtls_asn1_get_tag( unsigned char **p, + const unsigned char *end, + size_t *len, int tag ); + +/** + * \brief Retrieve a boolean ASN.1 tag and its value. + * Updates the pointer to immediately behind the full tag. + * + * \param p The position in the ASN.1 data + * \param end End of data + * \param val The variable that will receive the value + * + * \return 0 if successful or a specific ASN.1 error code. + */ +int mbedtls_asn1_get_bool( unsigned char **p, + const unsigned char *end, + int *val ); + +/** + * \brief Retrieve an integer ASN.1 tag and its value. + * Updates the pointer to immediately behind the full tag. + * + * \param p The position in the ASN.1 data + * \param end End of data + * \param val The variable that will receive the value + * + * \return 0 if successful or a specific ASN.1 error code. + */ +int mbedtls_asn1_get_int( unsigned char **p, + const unsigned char *end, + int *val ); + +/** + * \brief Retrieve a bitstring ASN.1 tag and its value. + * Updates the pointer to immediately behind the full tag. + * + * \param p The position in the ASN.1 data + * \param end End of data + * \param bs The variable that will receive the value + * + * \return 0 if successful or a specific ASN.1 error code. + */ +int mbedtls_asn1_get_bitstring( unsigned char **p, const unsigned char *end, + mbedtls_asn1_bitstring *bs); + +/** + * \brief Retrieve a bitstring ASN.1 tag without unused bits and its + * value. + * Updates the pointer to the beginning of the bit/octet string. + * + * \param p The position in the ASN.1 data + * \param end End of data + * \param len Length of the actual bit/octect string in bytes + * + * \return 0 if successful or a specific ASN.1 error code. + */ +int mbedtls_asn1_get_bitstring_null( unsigned char **p, const unsigned char *end, + size_t *len ); + +/** + * \brief Parses and splits an ASN.1 "SEQUENCE OF " + * Updated the pointer to immediately behind the full sequence tag. + * + * \param p The position in the ASN.1 data + * \param end End of data + * \param cur First variable in the chain to fill + * \param tag Type of sequence + * + * \return 0 if successful or a specific ASN.1 error code. + */ +int mbedtls_asn1_get_sequence_of( unsigned char **p, + const unsigned char *end, + mbedtls_asn1_sequence *cur, + int tag); + +#if defined(MBEDTLS_BIGNUM_C) +/** + * \brief Retrieve a MPI value from an integer ASN.1 tag. + * Updates the pointer to immediately behind the full tag. + * + * \param p The position in the ASN.1 data + * \param end End of data + * \param X The MPI that will receive the value + * + * \return 0 if successful or a specific ASN.1 or MPI error code. + */ +int mbedtls_asn1_get_mpi( unsigned char **p, + const unsigned char *end, + mbedtls_mpi *X ); +#endif /* MBEDTLS_BIGNUM_C */ + +/** + * \brief Retrieve an AlgorithmIdentifier ASN.1 sequence. + * Updates the pointer to immediately behind the full + * AlgorithmIdentifier. + * + * \param p The position in the ASN.1 data + * \param end End of data + * \param alg The buffer to receive the OID + * \param params The buffer to receive the params (if any) + * + * \return 0 if successful or a specific ASN.1 or MPI error code. + */ +int mbedtls_asn1_get_alg( unsigned char **p, + const unsigned char *end, + mbedtls_asn1_buf *alg, mbedtls_asn1_buf *params ); + +/** + * \brief Retrieve an AlgorithmIdentifier ASN.1 sequence with NULL or no + * params. + * Updates the pointer to immediately behind the full + * AlgorithmIdentifier. + * + * \param p The position in the ASN.1 data + * \param end End of data + * \param alg The buffer to receive the OID + * + * \return 0 if successful or a specific ASN.1 or MPI error code. + */ +int mbedtls_asn1_get_alg_null( unsigned char **p, + const unsigned char *end, + mbedtls_asn1_buf *alg ); + +/** + * \brief Find a specific named_data entry in a sequence or list based on + * the OID. + * + * \param list The list to seek through + * \param oid The OID to look for + * \param len Size of the OID + * + * \return NULL if not found, or a pointer to the existing entry. + */ +mbedtls_asn1_named_data *mbedtls_asn1_find_named_data( mbedtls_asn1_named_data *list, + const char *oid, size_t len ); + +/** + * \brief Free a mbedtls_asn1_named_data entry + * + * \param entry The named data entry to free + */ +void mbedtls_asn1_free_named_data( mbedtls_asn1_named_data *entry ); + +/** + * \brief Free all entries in a mbedtls_asn1_named_data list + * Head will be set to NULL + * + * \param head Pointer to the head of the list of named data entries to free + */ +void mbedtls_asn1_free_named_data_list( mbedtls_asn1_named_data **head ); + +#ifdef __cplusplus +} +#endif + +#endif /* asn1.h */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/asn1write.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/asn1write.h new file mode 100644 index 0000000000000000000000000000000000000000..a194243696ac8254a09d131f0b24f16fb2d748db --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/asn1write.h @@ -0,0 +1,329 @@ +/** + * \file asn1write.h + * + * \brief ASN.1 buffer writing functionality + */ +/* + * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ +#ifndef MBEDTLS_ASN1_WRITE_H +#define MBEDTLS_ASN1_WRITE_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include "asn1.h" + +#define MBEDTLS_ASN1_CHK_ADD(g, f) \ + do \ + { \ + if( ( ret = (f) ) < 0 ) \ + return( ret ); \ + else \ + (g) += ret; \ + } while( 0 ) + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \brief Write a length field in ASN.1 format. + * + * \note This function works backwards in data buffer. + * + * \param p The reference to the current position pointer. + * \param start The start of the buffer, for bounds-checking. + * \param len The length value to write. + * + * \return The number of bytes written to \p p on success. + * \return A negative \c MBEDTLS_ERR_ASN1_XXX error code on failure. + */ +int mbedtls_asn1_write_len( unsigned char **p, unsigned char *start, + size_t len ); +/** + * \brief Write an ASN.1 tag in ASN.1 format. + * + * \note This function works backwards in data buffer. + * + * \param p The reference to the current position pointer. + * \param start The start of the buffer, for bounds-checking. + * \param tag The tag to write. + * + * \return The number of bytes written to \p p on success. + * \return A negative \c MBEDTLS_ERR_ASN1_XXX error code on failure. + */ +int mbedtls_asn1_write_tag( unsigned char **p, unsigned char *start, + unsigned char tag ); + +/** + * \brief Write raw buffer data. + * + * \note This function works backwards in data buffer. + * + * \param p The reference to the current position pointer. + * \param start The start of the buffer, for bounds-checking. + * \param buf The data buffer to write. + * \param size The length of the data buffer. + * + * \return The number of bytes written to \p p on success. + * \return A negative \c MBEDTLS_ERR_ASN1_XXX error code on failure. + */ +int mbedtls_asn1_write_raw_buffer( unsigned char **p, unsigned char *start, + const unsigned char *buf, size_t size ); + +#if defined(MBEDTLS_BIGNUM_C) +/** + * \brief Write a arbitrary-precision number (#MBEDTLS_ASN1_INTEGER) + * in ASN.1 format. + * + * \note This function works backwards in data buffer. + * + * \param p The reference to the current position pointer. + * \param start The start of the buffer, for bounds-checking. + * \param X The MPI to write. + * + * \return The number of bytes written to \p p on success. + * \return A negative \c MBEDTLS_ERR_ASN1_XXX error code on failure. + */ +int mbedtls_asn1_write_mpi( unsigned char **p, unsigned char *start, + const mbedtls_mpi *X ); +#endif /* MBEDTLS_BIGNUM_C */ + +/** + * \brief Write a NULL tag (#MBEDTLS_ASN1_NULL) with zero data + * in ASN.1 format. + * + * \note This function works backwards in data buffer. + * + * \param p The reference to the current position pointer. + * \param start The start of the buffer, for bounds-checking. + * + * \return The number of bytes written to \p p on success. + * \return A negative \c MBEDTLS_ERR_ASN1_XXX error code on failure. + */ +int mbedtls_asn1_write_null( unsigned char **p, unsigned char *start ); + +/** + * \brief Write an OID tag (#MBEDTLS_ASN1_OID) and data + * in ASN.1 format. + * + * \note This function works backwards in data buffer. + * + * \param p The reference to the current position pointer. + * \param start The start of the buffer, for bounds-checking. + * \param oid The OID to write. + * \param oid_len The length of the OID. + * + * \return The number of bytes written to \p p on success. + * \return A negative \c MBEDTLS_ERR_ASN1_XXX error code on failure. + */ +int mbedtls_asn1_write_oid( unsigned char **p, unsigned char *start, + const char *oid, size_t oid_len ); + +/** + * \brief Write an AlgorithmIdentifier sequence in ASN.1 format. + * + * \note This function works backwards in data buffer. + * + * \param p The reference to the current position pointer. + * \param start The start of the buffer, for bounds-checking. + * \param oid The OID of the algorithm to write. + * \param oid_len The length of the algorithm's OID. + * \param par_len The length of the parameters, which must be already written. + * If 0, NULL parameters are added + * + * \return The number of bytes written to \p p on success. + * \return A negative \c MBEDTLS_ERR_ASN1_XXX error code on failure. + */ +int mbedtls_asn1_write_algorithm_identifier( unsigned char **p, + unsigned char *start, + const char *oid, size_t oid_len, + size_t par_len ); + +/** + * \brief Write a boolean tag (#MBEDTLS_ASN1_BOOLEAN) and value + * in ASN.1 format. + * + * \note This function works backwards in data buffer. + * + * \param p The reference to the current position pointer. + * \param start The start of the buffer, for bounds-checking. + * \param boolean The boolean value to write, either \c 0 or \c 1. + * + * \return The number of bytes written to \p p on success. + * \return A negative \c MBEDTLS_ERR_ASN1_XXX error code on failure. + */ +int mbedtls_asn1_write_bool( unsigned char **p, unsigned char *start, + int boolean ); + +/** + * \brief Write an int tag (#MBEDTLS_ASN1_INTEGER) and value + * in ASN.1 format. + * + * \note This function works backwards in data buffer. + * + * \param p The reference to the current position pointer. + * \param start The start of the buffer, for bounds-checking. + * \param val The integer value to write. + * + * \return The number of bytes written to \p p on success. + * \return A negative \c MBEDTLS_ERR_ASN1_XXX error code on failure. + */ +int mbedtls_asn1_write_int( unsigned char **p, unsigned char *start, int val ); + +/** + * \brief Write a string in ASN.1 format using a specific + * string encoding tag. + + * \note This function works backwards in data buffer. + * + * \param p The reference to the current position pointer. + * \param start The start of the buffer, for bounds-checking. + * \param tag The string encoding tag to write, e.g. + * #MBEDTLS_ASN1_UTF8_STRING. + * \param text The string to write. + * \param text_len The length of \p text in bytes (which might + * be strictly larger than the number of characters). + * + * \return The number of bytes written to \p p on success. + * \return A negative error code on failure. + */ +int mbedtls_asn1_write_tagged_string( unsigned char **p, unsigned char *start, + int tag, const char *text, + size_t text_len ); + +/** + * \brief Write a string in ASN.1 format using the PrintableString + * string encoding tag (#MBEDTLS_ASN1_PRINTABLE_STRING). + * + * \note This function works backwards in data buffer. + * + * \param p The reference to the current position pointer. + * \param start The start of the buffer, for bounds-checking. + * \param text The string to write. + * \param text_len The length of \p text in bytes (which might + * be strictly larger than the number of characters). + * + * \return The number of bytes written to \p p on success. + * \return A negative error code on failure. + */ +int mbedtls_asn1_write_printable_string( unsigned char **p, + unsigned char *start, + const char *text, size_t text_len ); + +/** + * \brief Write a UTF8 string in ASN.1 format using the UTF8String + * string encoding tag (#MBEDTLS_ASN1_PRINTABLE_STRING). + * + * \note This function works backwards in data buffer. + * + * \param p The reference to the current position pointer. + * \param start The start of the buffer, for bounds-checking. + * \param text The string to write. + * \param text_len The length of \p text in bytes (which might + * be strictly larger than the number of characters). + * + * \return The number of bytes written to \p p on success. + * \return A negative error code on failure. + */ +int mbedtls_asn1_write_utf8_string( unsigned char **p, unsigned char *start, + const char *text, size_t text_len ); + +/** + * \brief Write a string in ASN.1 format using the IA5String + * string encoding tag (#MBEDTLS_ASN1_IA5_STRING). + * + * \note This function works backwards in data buffer. + * + * \param p The reference to the current position pointer. + * \param start The start of the buffer, for bounds-checking. + * \param text The string to write. + * \param text_len The length of \p text in bytes (which might + * be strictly larger than the number of characters). + * + * \return The number of bytes written to \p p on success. + * \return A negative error code on failure. + */ +int mbedtls_asn1_write_ia5_string( unsigned char **p, unsigned char *start, + const char *text, size_t text_len ); + +/** + * \brief Write a bitstring tag (#MBEDTLS_ASN1_BIT_STRING) and + * value in ASN.1 format. + * + * \note This function works backwards in data buffer. + * + * \param p The reference to the current position pointer. + * \param start The start of the buffer, for bounds-checking. + * \param buf The bitstring to write. + * \param bits The total number of bits in the bitstring. + * + * \return The number of bytes written to \p p on success. + * \return A negative error code on failure. + */ +int mbedtls_asn1_write_bitstring( unsigned char **p, unsigned char *start, + const unsigned char *buf, size_t bits ); + +/** + * \brief Write an octet string tag (#MBEDTLS_ASN1_OCTET_STRING) + * and value in ASN.1 format. + * + * \note This function works backwards in data buffer. + * + * \param p The reference to the current position pointer. + * \param start The start of the buffer, for bounds-checking. + * \param buf The buffer holding the data to write. + * \param size The length of the data buffer \p buf. + * + * \return The number of bytes written to \p p on success. + * \return A negative error code on failure. + */ +int mbedtls_asn1_write_octet_string( unsigned char **p, unsigned char *start, + const unsigned char *buf, size_t size ); + +/** + * \brief Create or find a specific named_data entry for writing in a + * sequence or list based on the OID. If not already in there, + * a new entry is added to the head of the list. + * Warning: Destructive behaviour for the val data! + * + * \param list The pointer to the location of the head of the list to seek + * through (will be updated in case of a new entry). + * \param oid The OID to look for. + * \param oid_len The size of the OID. + * \param val The data to store (can be \c NULL if you want to fill + * it by hand). + * \param val_len The minimum length of the data buffer needed. + * + * \return A pointer to the new / existing entry on success. + * \return \c NULL if if there was a memory allocation error. + */ +mbedtls_asn1_named_data *mbedtls_asn1_store_named_data( mbedtls_asn1_named_data **list, + const char *oid, size_t oid_len, + const unsigned char *val, + size_t val_len ); + +#ifdef __cplusplus +} +#endif + +#endif /* MBEDTLS_ASN1_WRITE_H */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/base64.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/base64.h new file mode 100644 index 0000000000000000000000000000000000000000..0d024164c5659979f10d373c149fa9526e428c6f --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/base64.h @@ -0,0 +1,98 @@ +/** + * \file base64.h + * + * \brief RFC 1521 base64 encoding/decoding + */ +/* + * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ +#ifndef MBEDTLS_BASE64_H +#define MBEDTLS_BASE64_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include + +#define MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL -0x002A /**< Output buffer too small. */ +#define MBEDTLS_ERR_BASE64_INVALID_CHARACTER -0x002C /**< Invalid character in input. */ + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \brief Encode a buffer into base64 format + * + * \param dst destination buffer + * \param dlen size of the destination buffer + * \param olen number of bytes written + * \param src source buffer + * \param slen amount of data to be encoded + * + * \return 0 if successful, or MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL. + * *olen is always updated to reflect the amount + * of data that has (or would have) been written. + * If that length cannot be represented, then no data is + * written to the buffer and *olen is set to the maximum + * length representable as a size_t. + * + * \note Call this function with dlen = 0 to obtain the + * required buffer size in *olen + */ +int mbedtls_base64_encode( unsigned char *dst, size_t dlen, size_t *olen, + const unsigned char *src, size_t slen ); + +/** + * \brief Decode a base64-formatted buffer + * + * \param dst destination buffer (can be NULL for checking size) + * \param dlen size of the destination buffer + * \param olen number of bytes written + * \param src source buffer + * \param slen amount of data to be decoded + * + * \return 0 if successful, MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL, or + * MBEDTLS_ERR_BASE64_INVALID_CHARACTER if the input data is + * not correct. *olen is always updated to reflect the amount + * of data that has (or would have) been written. + * + * \note Call this function with *dst = NULL or dlen = 0 to obtain + * the required buffer size in *olen + */ +int mbedtls_base64_decode( unsigned char *dst, size_t dlen, size_t *olen, + const unsigned char *src, size_t slen ); + +#if defined(MBEDTLS_SELF_TEST) +/** + * \brief Checkup routine + * + * \return 0 if successful, or 1 if the test failed + */ +int mbedtls_base64_self_test( int verbose ); + +#endif /* MBEDTLS_SELF_TEST */ + +#ifdef __cplusplus +} +#endif + +#endif /* base64.h */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/bignum.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/bignum.h new file mode 100644 index 0000000000000000000000000000000000000000..22b373113edb9bc34cad562b049ce7e863c6a81b --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/bignum.h @@ -0,0 +1,984 @@ +/** + * \file bignum.h + * + * \brief Multi-precision integer library + */ +/* + * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ +#ifndef MBEDTLS_BIGNUM_H +#define MBEDTLS_BIGNUM_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include +#include + +#if defined(MBEDTLS_FS_IO) +#include +#endif + +#define MBEDTLS_ERR_MPI_FILE_IO_ERROR -0x0002 /**< An error occurred while reading from or writing to a file. */ +#define MBEDTLS_ERR_MPI_BAD_INPUT_DATA -0x0004 /**< Bad input parameters to function. */ +#define MBEDTLS_ERR_MPI_INVALID_CHARACTER -0x0006 /**< There is an invalid character in the digit string. */ +#define MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL -0x0008 /**< The buffer is too small to write to. */ +#define MBEDTLS_ERR_MPI_NEGATIVE_VALUE -0x000A /**< The input arguments are negative or result in illegal output. */ +#define MBEDTLS_ERR_MPI_DIVISION_BY_ZERO -0x000C /**< The input argument for division is zero, which is not allowed. */ +#define MBEDTLS_ERR_MPI_NOT_ACCEPTABLE -0x000E /**< The input arguments are not acceptable. */ +#define MBEDTLS_ERR_MPI_ALLOC_FAILED -0x0010 /**< Memory allocation failed. */ + +#define MBEDTLS_MPI_CHK(f) \ + do \ + { \ + if( ( ret = (f) ) != 0 ) \ + goto cleanup; \ + } while( 0 ) + +/* + * Maximum size MPIs are allowed to grow to in number of limbs. + */ +#define MBEDTLS_MPI_MAX_LIMBS 10000 + +#if !defined(MBEDTLS_MPI_WINDOW_SIZE) +/* + * Maximum window size used for modular exponentiation. Default: 6 + * Minimum value: 1. Maximum value: 6. + * + * Result is an array of ( 2 << MBEDTLS_MPI_WINDOW_SIZE ) MPIs used + * for the sliding window calculation. (So 64 by default) + * + * Reduction in size, reduces speed. + */ +#define MBEDTLS_MPI_WINDOW_SIZE 6 /**< Maximum windows size used. */ +#endif /* !MBEDTLS_MPI_WINDOW_SIZE */ + +#if !defined(MBEDTLS_MPI_MAX_SIZE) +/* + * Maximum size of MPIs allowed in bits and bytes for user-MPIs. + * ( Default: 512 bytes => 4096 bits, Maximum tested: 2048 bytes => 16384 bits ) + * + * Note: Calculations can temporarily result in larger MPIs. So the number + * of limbs required (MBEDTLS_MPI_MAX_LIMBS) is higher. + */ +#define MBEDTLS_MPI_MAX_SIZE 1024 /**< Maximum number of bytes for usable MPIs. */ +#endif /* !MBEDTLS_MPI_MAX_SIZE */ + +#define MBEDTLS_MPI_MAX_BITS ( 8 * MBEDTLS_MPI_MAX_SIZE ) /**< Maximum number of bits for usable MPIs. */ + +/* + * When reading from files with mbedtls_mpi_read_file() and writing to files with + * mbedtls_mpi_write_file() the buffer should have space + * for a (short) label, the MPI (in the provided radix), the newline + * characters and the '\0'. + * + * By default we assume at least a 10 char label, a minimum radix of 10 + * (decimal) and a maximum of 4096 bit numbers (1234 decimal chars). + * Autosized at compile time for at least a 10 char label, a minimum radix + * of 10 (decimal) for a number of MBEDTLS_MPI_MAX_BITS size. + * + * This used to be statically sized to 1250 for a maximum of 4096 bit + * numbers (1234 decimal chars). + * + * Calculate using the formula: + * MBEDTLS_MPI_RW_BUFFER_SIZE = ceil(MBEDTLS_MPI_MAX_BITS / ln(10) * ln(2)) + + * LabelSize + 6 + */ +#define MBEDTLS_MPI_MAX_BITS_SCALE100 ( 100 * MBEDTLS_MPI_MAX_BITS ) +#define MBEDTLS_LN_2_DIV_LN_10_SCALE100 332 +#define MBEDTLS_MPI_RW_BUFFER_SIZE ( ((MBEDTLS_MPI_MAX_BITS_SCALE100 + MBEDTLS_LN_2_DIV_LN_10_SCALE100 - 1) / MBEDTLS_LN_2_DIV_LN_10_SCALE100) + 10 + 6 ) + +/* + * Define the base integer type, architecture-wise. + * + * 32 or 64-bit integer types can be forced regardless of the underlying + * architecture by defining MBEDTLS_HAVE_INT32 or MBEDTLS_HAVE_INT64 + * respectively and undefining MBEDTLS_HAVE_ASM. + * + * Double-width integers (e.g. 128-bit in 64-bit architectures) can be + * disabled by defining MBEDTLS_NO_UDBL_DIVISION. + */ +#if !defined(MBEDTLS_HAVE_INT32) + #if defined(_MSC_VER) && defined(_M_AMD64) + /* Always choose 64-bit when using MSC */ + #if !defined(MBEDTLS_HAVE_INT64) + #define MBEDTLS_HAVE_INT64 + #endif /* !MBEDTLS_HAVE_INT64 */ + typedef int64_t mbedtls_mpi_sint; + typedef uint64_t mbedtls_mpi_uint; + #elif defined(__GNUC__) && ( \ + defined(__amd64__) || defined(__x86_64__) || \ + defined(__ppc64__) || defined(__powerpc64__) || \ + defined(__ia64__) || defined(__alpha__) || \ + ( defined(__sparc__) && defined(__arch64__) ) || \ + defined(__s390x__) || defined(__mips64) ) + #if !defined(MBEDTLS_HAVE_INT64) + #define MBEDTLS_HAVE_INT64 + #endif /* MBEDTLS_HAVE_INT64 */ + typedef int64_t mbedtls_mpi_sint; + typedef uint64_t mbedtls_mpi_uint; + #if !defined(MBEDTLS_NO_UDBL_DIVISION) + /* mbedtls_t_udbl defined as 128-bit unsigned int */ + typedef unsigned int mbedtls_t_udbl __attribute__((mode(TI))); + #define MBEDTLS_HAVE_UDBL + #endif /* !MBEDTLS_NO_UDBL_DIVISION */ + #elif defined(__ARMCC_VERSION) && defined(__aarch64__) + /* + * __ARMCC_VERSION is defined for both armcc and armclang and + * __aarch64__ is only defined by armclang when compiling 64-bit code + */ + #if !defined(MBEDTLS_HAVE_INT64) + #define MBEDTLS_HAVE_INT64 + #endif /* !MBEDTLS_HAVE_INT64 */ + typedef int64_t mbedtls_mpi_sint; + typedef uint64_t mbedtls_mpi_uint; + #if !defined(MBEDTLS_NO_UDBL_DIVISION) + /* mbedtls_t_udbl defined as 128-bit unsigned int */ + typedef __uint128_t mbedtls_t_udbl; + #define MBEDTLS_HAVE_UDBL + #endif /* !MBEDTLS_NO_UDBL_DIVISION */ + #elif defined(MBEDTLS_HAVE_INT64) + /* Force 64-bit integers with unknown compiler */ + typedef int64_t mbedtls_mpi_sint; + typedef uint64_t mbedtls_mpi_uint; + #endif +#endif /* !MBEDTLS_HAVE_INT32 */ + +#if !defined(MBEDTLS_HAVE_INT64) + /* Default to 32-bit compilation */ + #if !defined(MBEDTLS_HAVE_INT32) + #define MBEDTLS_HAVE_INT32 + #endif /* !MBEDTLS_HAVE_INT32 */ + typedef int32_t mbedtls_mpi_sint; + typedef uint32_t mbedtls_mpi_uint; + #if !defined(MBEDTLS_NO_UDBL_DIVISION) + typedef uint64_t mbedtls_t_udbl; + #define MBEDTLS_HAVE_UDBL + #endif /* !MBEDTLS_NO_UDBL_DIVISION */ +#endif /* !MBEDTLS_HAVE_INT64 */ + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \brief MPI structure + */ +typedef struct mbedtls_mpi +{ + int s; /*!< Sign: -1 if the mpi is negative, 1 otherwise */ + size_t n; /*!< total # of limbs */ + mbedtls_mpi_uint *p; /*!< pointer to limbs */ +} +mbedtls_mpi; + +/** + * \brief Initialize an MPI context. + * + * This makes the MPI ready to be set or freed, + * but does not define a value for the MPI. + * + * \param X The MPI context to initialize. This must not be \c NULL. + */ +void mbedtls_mpi_init( mbedtls_mpi *X ); + +/** + * \brief This function frees the components of an MPI context. + * + * \param X The MPI context to be cleared. This may be \c NULL, + * in which case this function is a no-op. If it is + * not \c NULL, it must point to an initialized MPI. + */ +void mbedtls_mpi_free( mbedtls_mpi *X ); + +/** + * \brief Enlarge an MPI to the specified number of limbs. + * + * \note This function does nothing if the MPI is + * already large enough. + * + * \param X The MPI to grow. It must be initialized. + * \param nblimbs The target number of limbs. + * + * \return \c 0 if successful. + * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed. + * \return Another negative error code on other kinds of failure. + */ +int mbedtls_mpi_grow( mbedtls_mpi *X, size_t nblimbs ); + +/** + * \brief This function resizes an MPI downwards, keeping at least the + * specified number of limbs. + * + * If \c X is smaller than \c nblimbs, it is resized up + * instead. + * + * \param X The MPI to shrink. This must point to an initialized MPI. + * \param nblimbs The minimum number of limbs to keep. + * + * \return \c 0 if successful. + * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed + * (this can only happen when resizing up). + * \return Another negative error code on other kinds of failure. + */ +int mbedtls_mpi_shrink( mbedtls_mpi *X, size_t nblimbs ); + +/** + * \brief Make a copy of an MPI. + * + * \param X The destination MPI. This must point to an initialized MPI. + * \param Y The source MPI. This must point to an initialized MPI. + * + * \note The limb-buffer in the destination MPI is enlarged + * if necessary to hold the value in the source MPI. + * + * \return \c 0 if successful. + * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed. + * \return Another negative error code on other kinds of failure. + */ +int mbedtls_mpi_copy( mbedtls_mpi *X, const mbedtls_mpi *Y ); + +/** + * \brief Swap the contents of two MPIs. + * + * \param X The first MPI. It must be initialized. + * \param Y The second MPI. It must be initialized. + */ +void mbedtls_mpi_swap( mbedtls_mpi *X, mbedtls_mpi *Y ); + +/** + * \brief Perform a safe conditional copy of MPI which doesn't + * reveal whether the condition was true or not. + * + * \param X The MPI to conditionally assign to. This must point + * to an initialized MPI. + * \param Y The MPI to be assigned from. This must point to an + * initialized MPI. + * \param assign The condition deciding whether to perform the + * assignment or not. Possible values: + * * \c 1: Perform the assignment `X = Y`. + * * \c 0: Keep the original value of \p X. + * + * \note This function is equivalent to + * `if( assign ) mbedtls_mpi_copy( X, Y );` + * except that it avoids leaking any information about whether + * the assignment was done or not (the above code may leak + * information through branch prediction and/or memory access + * patterns analysis). + * + * \return \c 0 if successful. + * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed. + * \return Another negative error code on other kinds of failure. + */ +int mbedtls_mpi_safe_cond_assign( mbedtls_mpi *X, const mbedtls_mpi *Y, unsigned char assign ); + +/** + * \brief Perform a safe conditional swap which doesn't + * reveal whether the condition was true or not. + * + * \param X The first MPI. This must be initialized. + * \param Y The second MPI. This must be initialized. + * \param assign The condition deciding whether to perform + * the swap or not. Possible values: + * * \c 1: Swap the values of \p X and \p Y. + * * \c 0: Keep the original values of \p X and \p Y. + * + * \note This function is equivalent to + * if( assign ) mbedtls_mpi_swap( X, Y ); + * except that it avoids leaking any information about whether + * the assignment was done or not (the above code may leak + * information through branch prediction and/or memory access + * patterns analysis). + * + * \return \c 0 if successful. + * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed. + * \return Another negative error code on other kinds of failure. + * + */ +int mbedtls_mpi_safe_cond_swap( mbedtls_mpi *X, mbedtls_mpi *Y, unsigned char assign ); + +/** + * \brief Store integer value in MPI. + * + * \param X The MPI to set. This must be initialized. + * \param z The value to use. + * + * \return \c 0 if successful. + * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed. + * \return Another negative error code on other kinds of failure. + */ +int mbedtls_mpi_lset( mbedtls_mpi *X, mbedtls_mpi_sint z ); + +/** + * \brief Get a specific bit from an MPI. + * + * \param X The MPI to query. This must be initialized. + * \param pos Zero-based index of the bit to query. + * + * \return \c 0 or \c 1 on success, depending on whether bit \c pos + * of \c X is unset or set. + * \return A negative error code on failure. + */ +int mbedtls_mpi_get_bit( const mbedtls_mpi *X, size_t pos ); + +/** + * \brief Modify a specific bit in an MPI. + * + * \note This function will grow the target MPI if necessary to set a + * bit to \c 1 in a not yet existing limb. It will not grow if + * the bit should be set to \c 0. + * + * \param X The MPI to modify. This must be initialized. + * \param pos Zero-based index of the bit to modify. + * \param val The desired value of bit \c pos: \c 0 or \c 1. + * + * \return \c 0 if successful. + * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed. + * \return Another negative error code on other kinds of failure. + */ +int mbedtls_mpi_set_bit( mbedtls_mpi *X, size_t pos, unsigned char val ); + +/** + * \brief Return the number of bits of value \c 0 before the + * least significant bit of value \c 1. + * + * \note This is the same as the zero-based index of + * the least significant bit of value \c 1. + * + * \param X The MPI to query. + * + * \return The number of bits of value \c 0 before the least significant + * bit of value \c 1 in \p X. + */ +size_t mbedtls_mpi_lsb( const mbedtls_mpi *X ); + +/** + * \brief Return the number of bits up to and including the most + * significant bit of value \c 1. + * + * * \note This is same as the one-based index of the most + * significant bit of value \c 1. + * + * \param X The MPI to query. This must point to an initialized MPI. + * + * \return The number of bits up to and including the most + * significant bit of value \c 1. + */ +size_t mbedtls_mpi_bitlen( const mbedtls_mpi *X ); + +/** + * \brief Return the total size of an MPI value in bytes. + * + * \param X The MPI to use. This must point to an initialized MPI. + * + * \note The value returned by this function may be less than + * the number of bytes used to store \p X internally. + * This happens if and only if there are trailing bytes + * of value zero. + * + * \return The least number of bytes capable of storing + * the absolute value of \p X. + */ +size_t mbedtls_mpi_size( const mbedtls_mpi *X ); + +/** + * \brief Import an MPI from an ASCII string. + * + * \param X The destination MPI. This must point to an initialized MPI. + * \param radix The numeric base of the input string. + * \param s Null-terminated string buffer. + * + * \return \c 0 if successful. + * \return A negative error code on failure. + */ +int mbedtls_mpi_read_string( mbedtls_mpi *X, int radix, const char *s ); + +/** + * \brief Export an MPI to an ASCII string. + * + * \param X The source MPI. This must point to an initialized MPI. + * \param radix The numeric base of the output string. + * \param buf The buffer to write the string to. This must be writable + * buffer of length \p buflen Bytes. + * \param buflen The available size in Bytes of \p buf. + * \param olen The address at which to store the length of the string + * written, including the final \c NULL byte. This must + * not be \c NULL. + * + * \note You can call this function with `buflen == 0` to obtain the + * minimum required buffer size in `*olen`. + * + * \return \c 0 if successful. + * \return #MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL if the target buffer \p buf + * is too small to hold the value of \p X in the desired base. + * In this case, `*olen` is nonetheless updated to contain the + * size of \p buf required for a successful call. + * \return Another negative error code on different kinds of failure. + */ +int mbedtls_mpi_write_string( const mbedtls_mpi *X, int radix, + char *buf, size_t buflen, size_t *olen ); + +#if defined(MBEDTLS_FS_IO) +/** + * \brief Read an MPI from a line in an opened file. + * + * \param X The destination MPI. This must point to an initialized MPI. + * \param radix The numeric base of the string representation used + * in the source line. + * \param fin The input file handle to use. This must not be \c NULL. + * + * \note On success, this function advances the file stream + * to the end of the current line or to EOF. + * + * The function returns \c 0 on an empty line. + * + * Leading whitespaces are ignored, as is a + * '0x' prefix for radix \c 16. + * + * \return \c 0 if successful. + * \return #MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL if the file read buffer + * is too small. + * \return Another negative error code on failure. + */ +int mbedtls_mpi_read_file( mbedtls_mpi *X, int radix, FILE *fin ); + +/** + * \brief Export an MPI into an opened file. + * + * \param p A string prefix to emit prior to the MPI data. + * For example, this might be a label, or "0x" when + * printing in base \c 16. This may be \c NULL if no prefix + * is needed. + * \param X The source MPI. This must point to an initialized MPI. + * \param radix The numeric base to be used in the emitted string. + * \param fout The output file handle. This may be \c NULL, in which case + * the output is written to \c stdout. + * + * \return \c 0 if successful. + * \return A negative error code on failure. + */ +int mbedtls_mpi_write_file( const char *p, const mbedtls_mpi *X, + int radix, FILE *fout ); +#endif /* MBEDTLS_FS_IO */ + +/** + * \brief Import an MPI from unsigned big endian binary data. + * + * \param X The destination MPI. This must point to an initialized MPI. + * \param buf The input buffer. This must be a readable buffer of length + * \p buflen Bytes. + * \param buflen The length of the input buffer \p p in Bytes. + * + * \return \c 0 if successful. + * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed. + * \return Another negative error code on different kinds of failure. + */ +int mbedtls_mpi_read_binary( mbedtls_mpi *X, const unsigned char *buf, + size_t buflen ); + +/** + * \brief Export an MPI into unsigned big endian binary data + * of fixed size. + * + * \param X The source MPI. This must point to an initialized MPI. + * \param buf The output buffer. This must be a writable buffer of length + * \p buflen Bytes. + * \param buflen The size of the output buffer \p buf in Bytes. + * + * \return \c 0 if successful. + * \return #MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL if \p buf isn't + * large enough to hold the value of \p X. + * \return Another negative error code on different kinds of failure. + */ +int mbedtls_mpi_write_binary( const mbedtls_mpi *X, unsigned char *buf, + size_t buflen ); + +/** + * \brief Perform a left-shift on an MPI: X <<= count + * + * \param X The MPI to shift. This must point to an initialized MPI. + * \param count The number of bits to shift by. + * + * \return \c 0 if successful. + * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed. + * \return Another negative error code on different kinds of failure. + */ +int mbedtls_mpi_shift_l( mbedtls_mpi *X, size_t count ); + +/** + * \brief Perform a right-shift on an MPI: X >>= count + * + * \param X The MPI to shift. This must point to an initialized MPI. + * \param count The number of bits to shift by. + * + * \return \c 0 if successful. + * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed. + * \return Another negative error code on different kinds of failure. + */ +int mbedtls_mpi_shift_r( mbedtls_mpi *X, size_t count ); + +/** + * \brief Compare the absolute values of two MPIs. + * + * \param X The left-hand MPI. This must point to an initialized MPI. + * \param Y The right-hand MPI. This must point to an initialized MPI. + * + * \return \c 1 if `|X|` is greater than `|Y|`. + * \return \c -1 if `|X|` is lesser than `|Y|`. + * \return \c 0 if `|X|` is equal to `|Y|`. + */ +int mbedtls_mpi_cmp_abs( const mbedtls_mpi *X, const mbedtls_mpi *Y ); + +/** + * \brief Compare two MPIs. + * + * \param X The left-hand MPI. This must point to an initialized MPI. + * \param Y The right-hand MPI. This must point to an initialized MPI. + * + * \return \c 1 if \p X is greater than \p Y. + * \return \c -1 if \p X is lesser than \p Y. + * \return \c 0 if \p X is equal to \p Y. + */ +int mbedtls_mpi_cmp_mpi( const mbedtls_mpi *X, const mbedtls_mpi *Y ); + +/** + * \brief Check if an MPI is less than the other in constant time. + * + * \param X The left-hand MPI. This must point to an initialized MPI + * with the same allocated length as Y. + * \param Y The right-hand MPI. This must point to an initialized MPI + * with the same allocated length as X. + * \param ret The result of the comparison: + * \c 1 if \p X is less than \p Y. + * \c 0 if \p X is greater than or equal to \p Y. + * + * \return 0 on success. + * \return MBEDTLS_ERR_MPI_BAD_INPUT_DATA if the allocated length of + * the two input MPIs is not the same. + */ +int mbedtls_mpi_lt_mpi_ct( const mbedtls_mpi *X, const mbedtls_mpi *Y, + unsigned *ret ); + +/** + * \brief Compare an MPI with an integer. + * + * \param X The left-hand MPI. This must point to an initialized MPI. + * \param z The integer value to compare \p X to. + * + * \return \c 1 if \p X is greater than \p z. + * \return \c -1 if \p X is lesser than \p z. + * \return \c 0 if \p X is equal to \p z. + */ +int mbedtls_mpi_cmp_int( const mbedtls_mpi *X, mbedtls_mpi_sint z ); + +/** + * \brief Perform an unsigned addition of MPIs: X = |A| + |B| + * + * \param X The destination MPI. This must point to an initialized MPI. + * \param A The first summand. This must point to an initialized MPI. + * \param B The second summand. This must point to an initialized MPI. + * + * \return \c 0 if successful. + * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed. + * \return Another negative error code on different kinds of failure. + */ +int mbedtls_mpi_add_abs( mbedtls_mpi *X, const mbedtls_mpi *A, + const mbedtls_mpi *B ); + +/** + * \brief Perform an unsigned subtraction of MPIs: X = |A| - |B| + * + * \param X The destination MPI. This must point to an initialized MPI. + * \param A The minuend. This must point to an initialized MPI. + * \param B The subtrahend. This must point to an initialized MPI. + * + * \return \c 0 if successful. + * \return #MBEDTLS_ERR_MPI_NEGATIVE_VALUE if \p B is greater than \p A. + * \return Another negative error code on different kinds of failure. + * + */ +int mbedtls_mpi_sub_abs( mbedtls_mpi *X, const mbedtls_mpi *A, + const mbedtls_mpi *B ); + +/** + * \brief Perform a signed addition of MPIs: X = A + B + * + * \param X The destination MPI. This must point to an initialized MPI. + * \param A The first summand. This must point to an initialized MPI. + * \param B The second summand. This must point to an initialized MPI. + * + * \return \c 0 if successful. + * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed. + * \return Another negative error code on different kinds of failure. + */ +int mbedtls_mpi_add_mpi( mbedtls_mpi *X, const mbedtls_mpi *A, + const mbedtls_mpi *B ); + +/** + * \brief Perform a signed subtraction of MPIs: X = A - B + * + * \param X The destination MPI. This must point to an initialized MPI. + * \param A The minuend. This must point to an initialized MPI. + * \param B The subtrahend. This must point to an initialized MPI. + * + * \return \c 0 if successful. + * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed. + * \return Another negative error code on different kinds of failure. + */ +int mbedtls_mpi_sub_mpi( mbedtls_mpi *X, const mbedtls_mpi *A, + const mbedtls_mpi *B ); + +/** + * \brief Perform a signed addition of an MPI and an integer: X = A + b + * + * \param X The destination MPI. This must point to an initialized MPI. + * \param A The first summand. This must point to an initialized MPI. + * \param b The second summand. + * + * \return \c 0 if successful. + * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed. + * \return Another negative error code on different kinds of failure. + */ +int mbedtls_mpi_add_int( mbedtls_mpi *X, const mbedtls_mpi *A, + mbedtls_mpi_sint b ); + +/** + * \brief Perform a signed subtraction of an MPI and an integer: + * X = A - b + * + * \param X The destination MPI. This must point to an initialized MPI. + * \param A The minuend. This must point to an initialized MPI. + * \param b The subtrahend. + * + * \return \c 0 if successful. + * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed. + * \return Another negative error code on different kinds of failure. + */ +int mbedtls_mpi_sub_int( mbedtls_mpi *X, const mbedtls_mpi *A, + mbedtls_mpi_sint b ); + +/** + * \brief Perform a multiplication of two MPIs: X = A * B + * + * \param X The destination MPI. This must point to an initialized MPI. + * \param A The first factor. This must point to an initialized MPI. + * \param B The second factor. This must point to an initialized MPI. + * + * \return \c 0 if successful. + * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed. + * \return Another negative error code on different kinds of failure. + * + */ +int mbedtls_mpi_mul_mpi( mbedtls_mpi *X, const mbedtls_mpi *A, + const mbedtls_mpi *B ); + +/** + * \brief Perform a multiplication of an MPI with an unsigned integer: + * X = A * b + * + * \param X The destination MPI. This must point to an initialized MPI. + * \param A The first factor. This must point to an initialized MPI. + * \param b The second factor. + * + * \return \c 0 if successful. + * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed. + * \return Another negative error code on different kinds of failure. + * + */ +int mbedtls_mpi_mul_int( mbedtls_mpi *X, const mbedtls_mpi *A, + mbedtls_mpi_uint b ); + +/** + * \brief Perform a division with remainder of two MPIs: + * A = Q * B + R + * + * \param Q The destination MPI for the quotient. + * This may be \c NULL if the value of the + * quotient is not needed. + * \param R The destination MPI for the remainder value. + * This may be \c NULL if the value of the + * remainder is not needed. + * \param A The dividend. This must point to an initialized MPi. + * \param B The divisor. This must point to an initialized MPI. + * + * \return \c 0 if successful. + * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed. + * \return #MBEDTLS_ERR_MPI_DIVISION_BY_ZERO if \p B equals zero. + * \return Another negative error code on different kinds of failure. + */ +int mbedtls_mpi_div_mpi( mbedtls_mpi *Q, mbedtls_mpi *R, const mbedtls_mpi *A, + const mbedtls_mpi *B ); + +/** + * \brief Perform a division with remainder of an MPI by an integer: + * A = Q * b + R + * + * \param Q The destination MPI for the quotient. + * This may be \c NULL if the value of the + * quotient is not needed. + * \param R The destination MPI for the remainder value. + * This may be \c NULL if the value of the + * remainder is not needed. + * \param A The dividend. This must point to an initialized MPi. + * \param b The divisor. + * + * \return \c 0 if successful. + * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed. + * \return #MBEDTLS_ERR_MPI_DIVISION_BY_ZERO if \p b equals zero. + * \return Another negative error code on different kinds of failure. + */ +int mbedtls_mpi_div_int( mbedtls_mpi *Q, mbedtls_mpi *R, const mbedtls_mpi *A, + mbedtls_mpi_sint b ); + +/** + * \brief Perform a modular reduction. R = A mod B + * + * \param R The destination MPI for the residue value. + * This must point to an initialized MPI. + * \param A The MPI to compute the residue of. + * This must point to an initialized MPI. + * \param B The base of the modular reduction. + * This must point to an initialized MPI. + * + * \return \c 0 if successful. + * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed. + * \return #MBEDTLS_ERR_MPI_DIVISION_BY_ZERO if \p B equals zero. + * \return #MBEDTLS_ERR_MPI_NEGATIVE_VALUE if \p B is negative. + * \return Another negative error code on different kinds of failure. + * + */ +int mbedtls_mpi_mod_mpi( mbedtls_mpi *R, const mbedtls_mpi *A, + const mbedtls_mpi *B ); + +/** + * \brief Perform a modular reduction with respect to an integer. + * r = A mod b + * + * \param r The address at which to store the residue. + * This must not be \c NULL. + * \param A The MPI to compute the residue of. + * This must point to an initialized MPi. + * \param b The integer base of the modular reduction. + * + * \return \c 0 if successful. + * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed. + * \return #MBEDTLS_ERR_MPI_DIVISION_BY_ZERO if \p b equals zero. + * \return #MBEDTLS_ERR_MPI_NEGATIVE_VALUE if \p b is negative. + * \return Another negative error code on different kinds of failure. + */ +int mbedtls_mpi_mod_int( mbedtls_mpi_uint *r, const mbedtls_mpi *A, + mbedtls_mpi_sint b ); + +/** + * \brief Perform a sliding-window exponentiation: X = A^E mod N + * + * \param X The destination MPI. This must point to an initialized MPI. + * \param A The base of the exponentiation. + * This must point to an initialized MPI. + * \param E The exponent MPI. This must point to an initialized MPI. + * \param N The base for the modular reduction. This must point to an + * initialized MPI. + * \param _RR A helper MPI depending solely on \p N which can be used to + * speed-up multiple modular exponentiations for the same value + * of \p N. This may be \c NULL. If it is not \c NULL, it must + * point to an initialized MPI. If it hasn't been used after + * the call to mbedtls_mpi_init(), this function will compute + * the helper value and store it in \p _RR for reuse on + * subsequent calls to this function. Otherwise, the function + * will assume that \p _RR holds the helper value set by a + * previous call to mbedtls_mpi_exp_mod(), and reuse it. + * + * \return \c 0 if successful. + * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed. + * \return #MBEDTLS_ERR_MPI_BAD_INPUT_DATA if \c N is negative or + * even, or if \c E is negative. + * \return Another negative error code on different kinds of failures. + * + */ +int mbedtls_mpi_exp_mod( mbedtls_mpi *X, const mbedtls_mpi *A, + const mbedtls_mpi *E, const mbedtls_mpi *N, + mbedtls_mpi *_RR ); + +/** + * \brief Fill an MPI with a number of random bytes. + * + * \param X The destination MPI. This must point to an initialized MPI. + * \param size The number of random bytes to generate. + * \param f_rng The RNG function to use. This must not be \c NULL. + * \param p_rng The RNG parameter to be passed to \p f_rng. This may be + * \c NULL if \p f_rng doesn't need a context argument. + * + * \return \c 0 if successful. + * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed. + * \return Another negative error code on failure. + * + * \note The bytes obtained from the RNG are interpreted + * as a big-endian representation of an MPI; this can + * be relevant in applications like deterministic ECDSA. + */ +int mbedtls_mpi_fill_random( mbedtls_mpi *X, size_t size, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng ); + +/** + * \brief Compute the greatest common divisor: G = gcd(A, B) + * + * \param G The destination MPI. This must point to an initialized MPI. + * \param A The first operand. This must point to an initialized MPI. + * \param B The second operand. This must point to an initialized MPI. + * + * \return \c 0 if successful. + * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed. + * \return Another negative error code on different kinds of failure. + */ +int mbedtls_mpi_gcd( mbedtls_mpi *G, const mbedtls_mpi *A, + const mbedtls_mpi *B ); + +/** + * \brief Compute the modular inverse: X = A^-1 mod N + * + * \param X The destination MPI. This must point to an initialized MPI. + * \param A The MPI to calculate the modular inverse of. This must point + * to an initialized MPI. + * \param N The base of the modular inversion. This must point to an + * initialized MPI. + * + * \return \c 0 if successful. + * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed. + * \return #MBEDTLS_ERR_MPI_BAD_INPUT_DATA if \p N is less than + * or equal to one. + * \return #MBEDTLS_ERR_MPI_NOT_ACCEPTABLE if \p has no modular inverse + * with respect to \p N. + */ +int mbedtls_mpi_inv_mod( mbedtls_mpi *X, const mbedtls_mpi *A, + const mbedtls_mpi *N ); + +#if !defined(MBEDTLS_DEPRECATED_REMOVED) +#if defined(MBEDTLS_DEPRECATED_WARNING) +#define MBEDTLS_DEPRECATED __attribute__((deprecated)) +#else +#define MBEDTLS_DEPRECATED +#endif +/** + * \brief Perform a Miller-Rabin primality test with error + * probability of 2-80. + * + * \deprecated Superseded by mbedtls_mpi_is_prime_ext() which allows + * specifying the number of Miller-Rabin rounds. + * + * \param X The MPI to check for primality. + * This must point to an initialized MPI. + * \param f_rng The RNG function to use. This must not be \c NULL. + * \param p_rng The RNG parameter to be passed to \p f_rng. + * This may be \c NULL if \p f_rng doesn't use a + * context parameter. + * + * \return \c 0 if successful, i.e. \p X is probably prime. + * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed. + * \return #MBEDTLS_ERR_MPI_NOT_ACCEPTABLE if \p X is not prime. + * \return Another negative error code on other kinds of failure. + */ +MBEDTLS_DEPRECATED int mbedtls_mpi_is_prime( const mbedtls_mpi *X, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng ); +#undef MBEDTLS_DEPRECATED +#endif /* !MBEDTLS_DEPRECATED_REMOVED */ + +/** + * \brief Miller-Rabin primality test. + * + * \warning If \p X is potentially generated by an adversary, for example + * when validating cryptographic parameters that you didn't + * generate yourself and that are supposed to be prime, then + * \p rounds should be at least the half of the security + * strength of the cryptographic algorithm. On the other hand, + * if \p X is chosen uniformly or non-adversially (as is the + * case when mbedtls_mpi_gen_prime calls this function), then + * \p rounds can be much lower. + * + * \param X The MPI to check for primality. + * This must point to an initialized MPI. + * \param rounds The number of bases to perform the Miller-Rabin primality + * test for. The probability of returning 0 on a composite is + * at most 2-2*\p rounds. + * \param f_rng The RNG function to use. This must not be \c NULL. + * \param p_rng The RNG parameter to be passed to \p f_rng. + * This may be \c NULL if \p f_rng doesn't use + * a context parameter. + * + * \return \c 0 if successful, i.e. \p X is probably prime. + * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed. + * \return #MBEDTLS_ERR_MPI_NOT_ACCEPTABLE if \p X is not prime. + * \return Another negative error code on other kinds of failure. + */ +int mbedtls_mpi_is_prime_ext( const mbedtls_mpi *X, int rounds, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng ); +/** + * \brief Flags for mbedtls_mpi_gen_prime() + * + * Each of these flags is a constraint on the result X returned by + * mbedtls_mpi_gen_prime(). + */ +typedef enum { + MBEDTLS_MPI_GEN_PRIME_FLAG_DH = 0x0001, /**< (X-1)/2 is prime too */ + MBEDTLS_MPI_GEN_PRIME_FLAG_LOW_ERR = 0x0002, /**< lower error rate from 2-80 to 2-128 */ +} mbedtls_mpi_gen_prime_flag_t; + +/** + * \brief Generate a prime number. + * + * \param X The destination MPI to store the generated prime in. + * This must point to an initialized MPi. + * \param nbits The required size of the destination MPI in bits. + * This must be between \c 3 and #MBEDTLS_MPI_MAX_BITS. + * \param flags A mask of flags of type #mbedtls_mpi_gen_prime_flag_t. + * \param f_rng The RNG function to use. This must not be \c NULL. + * \param p_rng The RNG parameter to be passed to \p f_rng. + * This may be \c NULL if \p f_rng doesn't use + * a context parameter. + * + * \return \c 0 if successful, in which case \p X holds a + * probably prime number. + * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed. + * \return #MBEDTLS_ERR_MPI_BAD_INPUT_DATA if `nbits` is not between + * \c 3 and #MBEDTLS_MPI_MAX_BITS. + */ +int mbedtls_mpi_gen_prime( mbedtls_mpi *X, size_t nbits, int flags, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng ); + +#if defined(MBEDTLS_SELF_TEST) + +/** + * \brief Checkup routine + * + * \return 0 if successful, or 1 if the test failed + */ +int mbedtls_mpi_self_test( int verbose ); + +#endif /* MBEDTLS_SELF_TEST */ + +#ifdef __cplusplus +} +#endif + +#endif /* bignum.h */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/blowfish.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/blowfish.h new file mode 100644 index 0000000000000000000000000000000000000000..f01573dcaf8d0fab5e8efbe720e776865ee46513 --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/blowfish.h @@ -0,0 +1,287 @@ +/** + * \file blowfish.h + * + * \brief Blowfish block cipher + */ +/* + * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ +#ifndef MBEDTLS_BLOWFISH_H +#define MBEDTLS_BLOWFISH_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include +#include + +#include "platform_util.h" + +#define MBEDTLS_BLOWFISH_ENCRYPT 1 +#define MBEDTLS_BLOWFISH_DECRYPT 0 +#define MBEDTLS_BLOWFISH_MAX_KEY_BITS 448 +#define MBEDTLS_BLOWFISH_MIN_KEY_BITS 32 +#define MBEDTLS_BLOWFISH_ROUNDS 16 /**< Rounds to use. When increasing this value, make sure to extend the initialisation vectors */ +#define MBEDTLS_BLOWFISH_BLOCKSIZE 8 /* Blowfish uses 64 bit blocks */ + +#if !defined(MBEDTLS_DEPRECATED_REMOVED) +#define MBEDTLS_ERR_BLOWFISH_INVALID_KEY_LENGTH MBEDTLS_DEPRECATED_NUMERIC_CONSTANT( -0x0016 ) +#endif /* !MBEDTLS_DEPRECATED_REMOVED */ +#define MBEDTLS_ERR_BLOWFISH_BAD_INPUT_DATA -0x0016 /**< Bad input data. */ + +#define MBEDTLS_ERR_BLOWFISH_INVALID_INPUT_LENGTH -0x0018 /**< Invalid data input length. */ + +/* MBEDTLS_ERR_BLOWFISH_HW_ACCEL_FAILED is deprecated and should not be used. + */ +#define MBEDTLS_ERR_BLOWFISH_HW_ACCEL_FAILED -0x0017 /**< Blowfish hardware accelerator failed. */ + +#ifdef __cplusplus +extern "C" { +#endif + +#if !defined(MBEDTLS_BLOWFISH_ALT) +// Regular implementation +// + +/** + * \brief Blowfish context structure + */ +typedef struct mbedtls_blowfish_context +{ + uint32_t P[MBEDTLS_BLOWFISH_ROUNDS + 2]; /*!< Blowfish round keys */ + uint32_t S[4][256]; /*!< key dependent S-boxes */ +} +mbedtls_blowfish_context; + +#else /* MBEDTLS_BLOWFISH_ALT */ +#include "blowfish_alt.h" +#endif /* MBEDTLS_BLOWFISH_ALT */ + +/** + * \brief Initialize a Blowfish context. + * + * \param ctx The Blowfish context to be initialized. + * This must not be \c NULL. + */ +void mbedtls_blowfish_init( mbedtls_blowfish_context *ctx ); + +/** + * \brief Clear a Blowfish context. + * + * \param ctx The Blowfish context to be cleared. + * This may be \c NULL, in which case this function + * returns immediately. If it is not \c NULL, it must + * point to an initialized Blowfish context. + */ +void mbedtls_blowfish_free( mbedtls_blowfish_context *ctx ); + +/** + * \brief Perform a Blowfish key schedule operation. + * + * \param ctx The Blowfish context to perform the key schedule on. + * \param key The encryption key. This must be a readable buffer of + * length \p keybits Bits. + * \param keybits The length of \p key in Bits. This must be between + * \c 32 and \c 448 and a multiple of \c 8. + * + * \return \c 0 if successful. + * \return A negative error code on failure. + */ +int mbedtls_blowfish_setkey( mbedtls_blowfish_context *ctx, const unsigned char *key, + unsigned int keybits ); + +/** + * \brief Perform a Blowfish-ECB block encryption/decryption operation. + * + * \param ctx The Blowfish context to use. This must be initialized + * and bound to a key. + * \param mode The mode of operation. Possible values are + * #MBEDTLS_BLOWFISH_ENCRYPT for encryption, or + * #MBEDTLS_BLOWFISH_DECRYPT for decryption. + * \param input The input block. This must be a readable buffer + * of size \c 8 Bytes. + * \param output The output block. This must be a writable buffer + * of size \c 8 Bytes. + * + * \return \c 0 if successful. + * \return A negative error code on failure. + */ +int mbedtls_blowfish_crypt_ecb( mbedtls_blowfish_context *ctx, + int mode, + const unsigned char input[MBEDTLS_BLOWFISH_BLOCKSIZE], + unsigned char output[MBEDTLS_BLOWFISH_BLOCKSIZE] ); + +#if defined(MBEDTLS_CIPHER_MODE_CBC) +/** + * \brief Perform a Blowfish-CBC buffer encryption/decryption operation. + * + * \note Upon exit, the content of the IV is updated so that you can + * call the function same function again on the following + * block(s) of data and get the same result as if it was + * encrypted in one call. This allows a "streaming" usage. + * If on the other hand you need to retain the contents of the + * IV, you should either save it manually or use the cipher + * module instead. + * + * \param ctx The Blowfish context to use. This must be initialized + * and bound to a key. + * \param mode The mode of operation. Possible values are + * #MBEDTLS_BLOWFISH_ENCRYPT for encryption, or + * #MBEDTLS_BLOWFISH_DECRYPT for decryption. + * \param length The length of the input data in Bytes. This must be + * multiple of \c 8. + * \param iv The initialization vector. This must be a read/write buffer + * of length \c 8 Bytes. It is updated by this function. + * \param input The input data. This must be a readable buffer of length + * \p length Bytes. + * \param output The output data. This must be a writable buffer of length + * \p length Bytes. + * + * \return \c 0 if successful. + * \return A negative error code on failure. + */ +int mbedtls_blowfish_crypt_cbc( mbedtls_blowfish_context *ctx, + int mode, + size_t length, + unsigned char iv[MBEDTLS_BLOWFISH_BLOCKSIZE], + const unsigned char *input, + unsigned char *output ); +#endif /* MBEDTLS_CIPHER_MODE_CBC */ + +#if defined(MBEDTLS_CIPHER_MODE_CFB) +/** + * \brief Perform a Blowfish CFB buffer encryption/decryption operation. + * + * \note Upon exit, the content of the IV is updated so that you can + * call the function same function again on the following + * block(s) of data and get the same result as if it was + * encrypted in one call. This allows a "streaming" usage. + * If on the other hand you need to retain the contents of the + * IV, you should either save it manually or use the cipher + * module instead. + * + * \param ctx The Blowfish context to use. This must be initialized + * and bound to a key. + * \param mode The mode of operation. Possible values are + * #MBEDTLS_BLOWFISH_ENCRYPT for encryption, or + * #MBEDTLS_BLOWFISH_DECRYPT for decryption. + * \param length The length of the input data in Bytes. + * \param iv_off The offset in the initialiation vector. + * The value pointed to must be smaller than \c 8 Bytes. + * It is updated by this function to support the aforementioned + * streaming usage. + * \param iv The initialization vector. This must be a read/write buffer + * of size \c 8 Bytes. It is updated after use. + * \param input The input data. This must be a readable buffer of length + * \p length Bytes. + * \param output The output data. This must be a writable buffer of length + * \p length Bytes. + * + * \return \c 0 if successful. + * \return A negative error code on failure. + */ +int mbedtls_blowfish_crypt_cfb64( mbedtls_blowfish_context *ctx, + int mode, + size_t length, + size_t *iv_off, + unsigned char iv[MBEDTLS_BLOWFISH_BLOCKSIZE], + const unsigned char *input, + unsigned char *output ); +#endif /*MBEDTLS_CIPHER_MODE_CFB */ + +#if defined(MBEDTLS_CIPHER_MODE_CTR) +/** + * \brief Perform a Blowfish-CTR buffer encryption/decryption operation. + * + * \warning You must never reuse a nonce value with the same key. Doing so + * would void the encryption for the two messages encrypted with + * the same nonce and key. + * + * There are two common strategies for managing nonces with CTR: + * + * 1. You can handle everything as a single message processed over + * successive calls to this function. In that case, you want to + * set \p nonce_counter and \p nc_off to 0 for the first call, and + * then preserve the values of \p nonce_counter, \p nc_off and \p + * stream_block across calls to this function as they will be + * updated by this function. + * + * With this strategy, you must not encrypt more than 2**64 + * blocks of data with the same key. + * + * 2. You can encrypt separate messages by dividing the \p + * nonce_counter buffer in two areas: the first one used for a + * per-message nonce, handled by yourself, and the second one + * updated by this function internally. + * + * For example, you might reserve the first 4 bytes for the + * per-message nonce, and the last 4 bytes for internal use. In that + * case, before calling this function on a new message you need to + * set the first 4 bytes of \p nonce_counter to your chosen nonce + * value, the last 4 to 0, and \p nc_off to 0 (which will cause \p + * stream_block to be ignored). That way, you can encrypt at most + * 2**32 messages of up to 2**32 blocks each with the same key. + * + * The per-message nonce (or information sufficient to reconstruct + * it) needs to be communicated with the ciphertext and must be unique. + * The recommended way to ensure uniqueness is to use a message + * counter. + * + * Note that for both stategies, sizes are measured in blocks and + * that a Blowfish block is 8 bytes. + * + * \warning Upon return, \p stream_block contains sensitive data. Its + * content must not be written to insecure storage and should be + * securely discarded as soon as it's no longer needed. + * + * \param ctx The Blowfish context to use. This must be initialized + * and bound to a key. + * \param length The length of the input data in Bytes. + * \param nc_off The offset in the current stream_block (for resuming + * within current cipher stream). The offset pointer + * should be \c 0 at the start of a stream and must be + * smaller than \c 8. It is updated by this function. + * \param nonce_counter The 64-bit nonce and counter. This must point to a + * read/write buffer of length \c 8 Bytes. + * \param stream_block The saved stream-block for resuming. This must point to + * a read/write buffer of length \c 8 Bytes. + * \param input The input data. This must be a readable buffer of + * length \p length Bytes. + * \param output The output data. This must be a writable buffer of + * length \p length Bytes. + * + * \return \c 0 if successful. + * \return A negative error code on failure. + */ +int mbedtls_blowfish_crypt_ctr( mbedtls_blowfish_context *ctx, + size_t length, + size_t *nc_off, + unsigned char nonce_counter[MBEDTLS_BLOWFISH_BLOCKSIZE], + unsigned char stream_block[MBEDTLS_BLOWFISH_BLOCKSIZE], + const unsigned char *input, + unsigned char *output ); +#endif /* MBEDTLS_CIPHER_MODE_CTR */ + +#ifdef __cplusplus +} +#endif + +#endif /* blowfish.h */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/bn_mul.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/bn_mul.h new file mode 100644 index 0000000000000000000000000000000000000000..748975ea51225e184af2845950fda35eb0aa1212 --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/bn_mul.h @@ -0,0 +1,916 @@ +/** + * \file bn_mul.h + * + * \brief Multi-precision integer library + */ +/* + * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ +/* + * Multiply source vector [s] with b, add result + * to destination vector [d] and set carry c. + * + * Currently supports: + * + * . IA-32 (386+) . AMD64 / EM64T + * . IA-32 (SSE2) . Motorola 68000 + * . PowerPC, 32-bit . MicroBlaze + * . PowerPC, 64-bit . TriCore + * . SPARC v8 . ARM v3+ + * . Alpha . MIPS32 + * . C, longlong . C, generic + */ +#ifndef MBEDTLS_BN_MUL_H +#define MBEDTLS_BN_MUL_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include "bignum.h" + +#if defined(MBEDTLS_HAVE_ASM) + +#ifndef asm +#define asm __asm +#endif + +/* armcc5 --gnu defines __GNUC__ but doesn't support GNU's extended asm */ +#if defined(__GNUC__) && \ + ( !defined(__ARMCC_VERSION) || __ARMCC_VERSION >= 6000000 ) + +/* + * Disable use of the i386 assembly code below if option -O0, to disable all + * compiler optimisations, is passed, detected with __OPTIMIZE__ + * This is done as the number of registers used in the assembly code doesn't + * work with the -O0 option. + */ +#if defined(__i386__) && defined(__OPTIMIZE__) + +#define MULADDC_INIT \ + asm( \ + "movl %%ebx, %0 \n\t" \ + "movl %5, %%esi \n\t" \ + "movl %6, %%edi \n\t" \ + "movl %7, %%ecx \n\t" \ + "movl %8, %%ebx \n\t" + +#define MULADDC_CORE \ + "lodsl \n\t" \ + "mull %%ebx \n\t" \ + "addl %%ecx, %%eax \n\t" \ + "adcl $0, %%edx \n\t" \ + "addl (%%edi), %%eax \n\t" \ + "adcl $0, %%edx \n\t" \ + "movl %%edx, %%ecx \n\t" \ + "stosl \n\t" + +#if defined(MBEDTLS_HAVE_SSE2) + +#define MULADDC_HUIT \ + "movd %%ecx, %%mm1 \n\t" \ + "movd %%ebx, %%mm0 \n\t" \ + "movd (%%edi), %%mm3 \n\t" \ + "paddq %%mm3, %%mm1 \n\t" \ + "movd (%%esi), %%mm2 \n\t" \ + "pmuludq %%mm0, %%mm2 \n\t" \ + "movd 4(%%esi), %%mm4 \n\t" \ + "pmuludq %%mm0, %%mm4 \n\t" \ + "movd 8(%%esi), %%mm6 \n\t" \ + "pmuludq %%mm0, %%mm6 \n\t" \ + "movd 12(%%esi), %%mm7 \n\t" \ + "pmuludq %%mm0, %%mm7 \n\t" \ + "paddq %%mm2, %%mm1 \n\t" \ + "movd 4(%%edi), %%mm3 \n\t" \ + "paddq %%mm4, %%mm3 \n\t" \ + "movd 8(%%edi), %%mm5 \n\t" \ + "paddq %%mm6, %%mm5 \n\t" \ + "movd 12(%%edi), %%mm4 \n\t" \ + "paddq %%mm4, %%mm7 \n\t" \ + "movd %%mm1, (%%edi) \n\t" \ + "movd 16(%%esi), %%mm2 \n\t" \ + "pmuludq %%mm0, %%mm2 \n\t" \ + "psrlq $32, %%mm1 \n\t" \ + "movd 20(%%esi), %%mm4 \n\t" \ + "pmuludq %%mm0, %%mm4 \n\t" \ + "paddq %%mm3, %%mm1 \n\t" \ + "movd 24(%%esi), %%mm6 \n\t" \ + "pmuludq %%mm0, %%mm6 \n\t" \ + "movd %%mm1, 4(%%edi) \n\t" \ + "psrlq $32, %%mm1 \n\t" \ + "movd 28(%%esi), %%mm3 \n\t" \ + "pmuludq %%mm0, %%mm3 \n\t" \ + "paddq %%mm5, %%mm1 \n\t" \ + "movd 16(%%edi), %%mm5 \n\t" \ + "paddq %%mm5, %%mm2 \n\t" \ + "movd %%mm1, 8(%%edi) \n\t" \ + "psrlq $32, %%mm1 \n\t" \ + "paddq %%mm7, %%mm1 \n\t" \ + "movd 20(%%edi), %%mm5 \n\t" \ + "paddq %%mm5, %%mm4 \n\t" \ + "movd %%mm1, 12(%%edi) \n\t" \ + "psrlq $32, %%mm1 \n\t" \ + "paddq %%mm2, %%mm1 \n\t" \ + "movd 24(%%edi), %%mm5 \n\t" \ + "paddq %%mm5, %%mm6 \n\t" \ + "movd %%mm1, 16(%%edi) \n\t" \ + "psrlq $32, %%mm1 \n\t" \ + "paddq %%mm4, %%mm1 \n\t" \ + "movd 28(%%edi), %%mm5 \n\t" \ + "paddq %%mm5, %%mm3 \n\t" \ + "movd %%mm1, 20(%%edi) \n\t" \ + "psrlq $32, %%mm1 \n\t" \ + "paddq %%mm6, %%mm1 \n\t" \ + "movd %%mm1, 24(%%edi) \n\t" \ + "psrlq $32, %%mm1 \n\t" \ + "paddq %%mm3, %%mm1 \n\t" \ + "movd %%mm1, 28(%%edi) \n\t" \ + "addl $32, %%edi \n\t" \ + "addl $32, %%esi \n\t" \ + "psrlq $32, %%mm1 \n\t" \ + "movd %%mm1, %%ecx \n\t" + +#define MULADDC_STOP \ + "emms \n\t" \ + "movl %4, %%ebx \n\t" \ + "movl %%ecx, %1 \n\t" \ + "movl %%edi, %2 \n\t" \ + "movl %%esi, %3 \n\t" \ + : "=m" (t), "=m" (c), "=m" (d), "=m" (s) \ + : "m" (t), "m" (s), "m" (d), "m" (c), "m" (b) \ + : "eax", "ebx", "ecx", "edx", "esi", "edi" \ + ); + +#else + +#define MULADDC_STOP \ + "movl %4, %%ebx \n\t" \ + "movl %%ecx, %1 \n\t" \ + "movl %%edi, %2 \n\t" \ + "movl %%esi, %3 \n\t" \ + : "=m" (t), "=m" (c), "=m" (d), "=m" (s) \ + : "m" (t), "m" (s), "m" (d), "m" (c), "m" (b) \ + : "eax", "ebx", "ecx", "edx", "esi", "edi" \ + ); +#endif /* SSE2 */ +#endif /* i386 */ + +#if defined(__amd64__) || defined (__x86_64__) + +#define MULADDC_INIT \ + asm( \ + "xorq %%r8, %%r8\n" + +#define MULADDC_CORE \ + "movq (%%rsi), %%rax\n" \ + "mulq %%rbx\n" \ + "addq $8, %%rsi\n" \ + "addq %%rcx, %%rax\n" \ + "movq %%r8, %%rcx\n" \ + "adcq $0, %%rdx\n" \ + "nop \n" \ + "addq %%rax, (%%rdi)\n" \ + "adcq %%rdx, %%rcx\n" \ + "addq $8, %%rdi\n" + +#define MULADDC_STOP \ + : "+c" (c), "+D" (d), "+S" (s) \ + : "b" (b) \ + : "rax", "rdx", "r8" \ + ); + +#endif /* AMD64 */ + +#if defined(__mc68020__) || defined(__mcpu32__) + +#define MULADDC_INIT \ + asm( \ + "movl %3, %%a2 \n\t" \ + "movl %4, %%a3 \n\t" \ + "movl %5, %%d3 \n\t" \ + "movl %6, %%d2 \n\t" \ + "moveq #0, %%d0 \n\t" + +#define MULADDC_CORE \ + "movel %%a2@+, %%d1 \n\t" \ + "mulul %%d2, %%d4:%%d1 \n\t" \ + "addl %%d3, %%d1 \n\t" \ + "addxl %%d0, %%d4 \n\t" \ + "moveq #0, %%d3 \n\t" \ + "addl %%d1, %%a3@+ \n\t" \ + "addxl %%d4, %%d3 \n\t" + +#define MULADDC_STOP \ + "movl %%d3, %0 \n\t" \ + "movl %%a3, %1 \n\t" \ + "movl %%a2, %2 \n\t" \ + : "=m" (c), "=m" (d), "=m" (s) \ + : "m" (s), "m" (d), "m" (c), "m" (b) \ + : "d0", "d1", "d2", "d3", "d4", "a2", "a3" \ + ); + +#define MULADDC_HUIT \ + "movel %%a2@+, %%d1 \n\t" \ + "mulul %%d2, %%d4:%%d1 \n\t" \ + "addxl %%d3, %%d1 \n\t" \ + "addxl %%d0, %%d4 \n\t" \ + "addl %%d1, %%a3@+ \n\t" \ + "movel %%a2@+, %%d1 \n\t" \ + "mulul %%d2, %%d3:%%d1 \n\t" \ + "addxl %%d4, %%d1 \n\t" \ + "addxl %%d0, %%d3 \n\t" \ + "addl %%d1, %%a3@+ \n\t" \ + "movel %%a2@+, %%d1 \n\t" \ + "mulul %%d2, %%d4:%%d1 \n\t" \ + "addxl %%d3, %%d1 \n\t" \ + "addxl %%d0, %%d4 \n\t" \ + "addl %%d1, %%a3@+ \n\t" \ + "movel %%a2@+, %%d1 \n\t" \ + "mulul %%d2, %%d3:%%d1 \n\t" \ + "addxl %%d4, %%d1 \n\t" \ + "addxl %%d0, %%d3 \n\t" \ + "addl %%d1, %%a3@+ \n\t" \ + "movel %%a2@+, %%d1 \n\t" \ + "mulul %%d2, %%d4:%%d1 \n\t" \ + "addxl %%d3, %%d1 \n\t" \ + "addxl %%d0, %%d4 \n\t" \ + "addl %%d1, %%a3@+ \n\t" \ + "movel %%a2@+, %%d1 \n\t" \ + "mulul %%d2, %%d3:%%d1 \n\t" \ + "addxl %%d4, %%d1 \n\t" \ + "addxl %%d0, %%d3 \n\t" \ + "addl %%d1, %%a3@+ \n\t" \ + "movel %%a2@+, %%d1 \n\t" \ + "mulul %%d2, %%d4:%%d1 \n\t" \ + "addxl %%d3, %%d1 \n\t" \ + "addxl %%d0, %%d4 \n\t" \ + "addl %%d1, %%a3@+ \n\t" \ + "movel %%a2@+, %%d1 \n\t" \ + "mulul %%d2, %%d3:%%d1 \n\t" \ + "addxl %%d4, %%d1 \n\t" \ + "addxl %%d0, %%d3 \n\t" \ + "addl %%d1, %%a3@+ \n\t" \ + "addxl %%d0, %%d3 \n\t" + +#endif /* MC68000 */ + +#if defined(__powerpc64__) || defined(__ppc64__) + +#if defined(__MACH__) && defined(__APPLE__) + +#define MULADDC_INIT \ + asm( \ + "ld r3, %3 \n\t" \ + "ld r4, %4 \n\t" \ + "ld r5, %5 \n\t" \ + "ld r6, %6 \n\t" \ + "addi r3, r3, -8 \n\t" \ + "addi r4, r4, -8 \n\t" \ + "addic r5, r5, 0 \n\t" + +#define MULADDC_CORE \ + "ldu r7, 8(r3) \n\t" \ + "mulld r8, r7, r6 \n\t" \ + "mulhdu r9, r7, r6 \n\t" \ + "adde r8, r8, r5 \n\t" \ + "ld r7, 8(r4) \n\t" \ + "addze r5, r9 \n\t" \ + "addc r8, r8, r7 \n\t" \ + "stdu r8, 8(r4) \n\t" + +#define MULADDC_STOP \ + "addze r5, r5 \n\t" \ + "addi r4, r4, 8 \n\t" \ + "addi r3, r3, 8 \n\t" \ + "std r5, %0 \n\t" \ + "std r4, %1 \n\t" \ + "std r3, %2 \n\t" \ + : "=m" (c), "=m" (d), "=m" (s) \ + : "m" (s), "m" (d), "m" (c), "m" (b) \ + : "r3", "r4", "r5", "r6", "r7", "r8", "r9" \ + ); + + +#else /* __MACH__ && __APPLE__ */ + +#define MULADDC_INIT \ + asm( \ + "ld %%r3, %3 \n\t" \ + "ld %%r4, %4 \n\t" \ + "ld %%r5, %5 \n\t" \ + "ld %%r6, %6 \n\t" \ + "addi %%r3, %%r3, -8 \n\t" \ + "addi %%r4, %%r4, -8 \n\t" \ + "addic %%r5, %%r5, 0 \n\t" + +#define MULADDC_CORE \ + "ldu %%r7, 8(%%r3) \n\t" \ + "mulld %%r8, %%r7, %%r6 \n\t" \ + "mulhdu %%r9, %%r7, %%r6 \n\t" \ + "adde %%r8, %%r8, %%r5 \n\t" \ + "ld %%r7, 8(%%r4) \n\t" \ + "addze %%r5, %%r9 \n\t" \ + "addc %%r8, %%r8, %%r7 \n\t" \ + "stdu %%r8, 8(%%r4) \n\t" + +#define MULADDC_STOP \ + "addze %%r5, %%r5 \n\t" \ + "addi %%r4, %%r4, 8 \n\t" \ + "addi %%r3, %%r3, 8 \n\t" \ + "std %%r5, %0 \n\t" \ + "std %%r4, %1 \n\t" \ + "std %%r3, %2 \n\t" \ + : "=m" (c), "=m" (d), "=m" (s) \ + : "m" (s), "m" (d), "m" (c), "m" (b) \ + : "r3", "r4", "r5", "r6", "r7", "r8", "r9" \ + ); + +#endif /* __MACH__ && __APPLE__ */ + +#elif defined(__powerpc__) || defined(__ppc__) /* end PPC64/begin PPC32 */ + +#if defined(__MACH__) && defined(__APPLE__) + +#define MULADDC_INIT \ + asm( \ + "lwz r3, %3 \n\t" \ + "lwz r4, %4 \n\t" \ + "lwz r5, %5 \n\t" \ + "lwz r6, %6 \n\t" \ + "addi r3, r3, -4 \n\t" \ + "addi r4, r4, -4 \n\t" \ + "addic r5, r5, 0 \n\t" + +#define MULADDC_CORE \ + "lwzu r7, 4(r3) \n\t" \ + "mullw r8, r7, r6 \n\t" \ + "mulhwu r9, r7, r6 \n\t" \ + "adde r8, r8, r5 \n\t" \ + "lwz r7, 4(r4) \n\t" \ + "addze r5, r9 \n\t" \ + "addc r8, r8, r7 \n\t" \ + "stwu r8, 4(r4) \n\t" + +#define MULADDC_STOP \ + "addze r5, r5 \n\t" \ + "addi r4, r4, 4 \n\t" \ + "addi r3, r3, 4 \n\t" \ + "stw r5, %0 \n\t" \ + "stw r4, %1 \n\t" \ + "stw r3, %2 \n\t" \ + : "=m" (c), "=m" (d), "=m" (s) \ + : "m" (s), "m" (d), "m" (c), "m" (b) \ + : "r3", "r4", "r5", "r6", "r7", "r8", "r9" \ + ); + +#else /* __MACH__ && __APPLE__ */ + +#define MULADDC_INIT \ + asm( \ + "lwz %%r3, %3 \n\t" \ + "lwz %%r4, %4 \n\t" \ + "lwz %%r5, %5 \n\t" \ + "lwz %%r6, %6 \n\t" \ + "addi %%r3, %%r3, -4 \n\t" \ + "addi %%r4, %%r4, -4 \n\t" \ + "addic %%r5, %%r5, 0 \n\t" + +#define MULADDC_CORE \ + "lwzu %%r7, 4(%%r3) \n\t" \ + "mullw %%r8, %%r7, %%r6 \n\t" \ + "mulhwu %%r9, %%r7, %%r6 \n\t" \ + "adde %%r8, %%r8, %%r5 \n\t" \ + "lwz %%r7, 4(%%r4) \n\t" \ + "addze %%r5, %%r9 \n\t" \ + "addc %%r8, %%r8, %%r7 \n\t" \ + "stwu %%r8, 4(%%r4) \n\t" + +#define MULADDC_STOP \ + "addze %%r5, %%r5 \n\t" \ + "addi %%r4, %%r4, 4 \n\t" \ + "addi %%r3, %%r3, 4 \n\t" \ + "stw %%r5, %0 \n\t" \ + "stw %%r4, %1 \n\t" \ + "stw %%r3, %2 \n\t" \ + : "=m" (c), "=m" (d), "=m" (s) \ + : "m" (s), "m" (d), "m" (c), "m" (b) \ + : "r3", "r4", "r5", "r6", "r7", "r8", "r9" \ + ); + +#endif /* __MACH__ && __APPLE__ */ + +#endif /* PPC32 */ + +/* + * The Sparc(64) assembly is reported to be broken. + * Disable it for now, until we're able to fix it. + */ +#if 0 && defined(__sparc__) +#if defined(__sparc64__) + +#define MULADDC_INIT \ + asm( \ + "ldx %3, %%o0 \n\t" \ + "ldx %4, %%o1 \n\t" \ + "ld %5, %%o2 \n\t" \ + "ld %6, %%o3 \n\t" + +#define MULADDC_CORE \ + "ld [%%o0], %%o4 \n\t" \ + "inc 4, %%o0 \n\t" \ + "ld [%%o1], %%o5 \n\t" \ + "umul %%o3, %%o4, %%o4 \n\t" \ + "addcc %%o4, %%o2, %%o4 \n\t" \ + "rd %%y, %%g1 \n\t" \ + "addx %%g1, 0, %%g1 \n\t" \ + "addcc %%o4, %%o5, %%o4 \n\t" \ + "st %%o4, [%%o1] \n\t" \ + "addx %%g1, 0, %%o2 \n\t" \ + "inc 4, %%o1 \n\t" + + #define MULADDC_STOP \ + "st %%o2, %0 \n\t" \ + "stx %%o1, %1 \n\t" \ + "stx %%o0, %2 \n\t" \ + : "=m" (c), "=m" (d), "=m" (s) \ + : "m" (s), "m" (d), "m" (c), "m" (b) \ + : "g1", "o0", "o1", "o2", "o3", "o4", \ + "o5" \ + ); + +#else /* __sparc64__ */ + +#define MULADDC_INIT \ + asm( \ + "ld %3, %%o0 \n\t" \ + "ld %4, %%o1 \n\t" \ + "ld %5, %%o2 \n\t" \ + "ld %6, %%o3 \n\t" + +#define MULADDC_CORE \ + "ld [%%o0], %%o4 \n\t" \ + "inc 4, %%o0 \n\t" \ + "ld [%%o1], %%o5 \n\t" \ + "umul %%o3, %%o4, %%o4 \n\t" \ + "addcc %%o4, %%o2, %%o4 \n\t" \ + "rd %%y, %%g1 \n\t" \ + "addx %%g1, 0, %%g1 \n\t" \ + "addcc %%o4, %%o5, %%o4 \n\t" \ + "st %%o4, [%%o1] \n\t" \ + "addx %%g1, 0, %%o2 \n\t" \ + "inc 4, %%o1 \n\t" + +#define MULADDC_STOP \ + "st %%o2, %0 \n\t" \ + "st %%o1, %1 \n\t" \ + "st %%o0, %2 \n\t" \ + : "=m" (c), "=m" (d), "=m" (s) \ + : "m" (s), "m" (d), "m" (c), "m" (b) \ + : "g1", "o0", "o1", "o2", "o3", "o4", \ + "o5" \ + ); + +#endif /* __sparc64__ */ +#endif /* __sparc__ */ + +#if defined(__microblaze__) || defined(microblaze) + +#define MULADDC_INIT \ + asm( \ + "lwi r3, %3 \n\t" \ + "lwi r4, %4 \n\t" \ + "lwi r5, %5 \n\t" \ + "lwi r6, %6 \n\t" \ + "andi r7, r6, 0xffff \n\t" \ + "bsrli r6, r6, 16 \n\t" + +#define MULADDC_CORE \ + "lhui r8, r3, 0 \n\t" \ + "addi r3, r3, 2 \n\t" \ + "lhui r9, r3, 0 \n\t" \ + "addi r3, r3, 2 \n\t" \ + "mul r10, r9, r6 \n\t" \ + "mul r11, r8, r7 \n\t" \ + "mul r12, r9, r7 \n\t" \ + "mul r13, r8, r6 \n\t" \ + "bsrli r8, r10, 16 \n\t" \ + "bsrli r9, r11, 16 \n\t" \ + "add r13, r13, r8 \n\t" \ + "add r13, r13, r9 \n\t" \ + "bslli r10, r10, 16 \n\t" \ + "bslli r11, r11, 16 \n\t" \ + "add r12, r12, r10 \n\t" \ + "addc r13, r13, r0 \n\t" \ + "add r12, r12, r11 \n\t" \ + "addc r13, r13, r0 \n\t" \ + "lwi r10, r4, 0 \n\t" \ + "add r12, r12, r10 \n\t" \ + "addc r13, r13, r0 \n\t" \ + "add r12, r12, r5 \n\t" \ + "addc r5, r13, r0 \n\t" \ + "swi r12, r4, 0 \n\t" \ + "addi r4, r4, 4 \n\t" + +#define MULADDC_STOP \ + "swi r5, %0 \n\t" \ + "swi r4, %1 \n\t" \ + "swi r3, %2 \n\t" \ + : "=m" (c), "=m" (d), "=m" (s) \ + : "m" (s), "m" (d), "m" (c), "m" (b) \ + : "r3", "r4", "r5", "r6", "r7", "r8", \ + "r9", "r10", "r11", "r12", "r13" \ + ); + +#endif /* MicroBlaze */ + +#if defined(__tricore__) + +#define MULADDC_INIT \ + asm( \ + "ld.a %%a2, %3 \n\t" \ + "ld.a %%a3, %4 \n\t" \ + "ld.w %%d4, %5 \n\t" \ + "ld.w %%d1, %6 \n\t" \ + "xor %%d5, %%d5 \n\t" + +#define MULADDC_CORE \ + "ld.w %%d0, [%%a2+] \n\t" \ + "madd.u %%e2, %%e4, %%d0, %%d1 \n\t" \ + "ld.w %%d0, [%%a3] \n\t" \ + "addx %%d2, %%d2, %%d0 \n\t" \ + "addc %%d3, %%d3, 0 \n\t" \ + "mov %%d4, %%d3 \n\t" \ + "st.w [%%a3+], %%d2 \n\t" + +#define MULADDC_STOP \ + "st.w %0, %%d4 \n\t" \ + "st.a %1, %%a3 \n\t" \ + "st.a %2, %%a2 \n\t" \ + : "=m" (c), "=m" (d), "=m" (s) \ + : "m" (s), "m" (d), "m" (c), "m" (b) \ + : "d0", "d1", "e2", "d4", "a2", "a3" \ + ); + +#endif /* TriCore */ + +/* + * Note, gcc -O0 by default uses r7 for the frame pointer, so it complains about + * our use of r7 below, unless -fomit-frame-pointer is passed. + * + * On the other hand, -fomit-frame-pointer is implied by any -Ox options with + * x !=0, which we can detect using __OPTIMIZE__ (which is also defined by + * clang and armcc5 under the same conditions). + * + * So, only use the optimized assembly below for optimized build, which avoids + * the build error and is pretty reasonable anyway. + */ +#if defined(__GNUC__) && !defined(__OPTIMIZE__) +#define MULADDC_CANNOT_USE_R7 +#endif + +#if defined(__arm__) && !defined(MULADDC_CANNOT_USE_R7) + +#if defined(__thumb__) && !defined(__thumb2__) + +#define MULADDC_INIT \ + asm( \ + "ldr r0, %3 \n\t" \ + "ldr r1, %4 \n\t" \ + "ldr r2, %5 \n\t" \ + "ldr r3, %6 \n\t" \ + "lsr r7, r3, #16 \n\t" \ + "mov r9, r7 \n\t" \ + "lsl r7, r3, #16 \n\t" \ + "lsr r7, r7, #16 \n\t" \ + "mov r8, r7 \n\t" + +#define MULADDC_CORE \ + "ldmia r0!, {r6} \n\t" \ + "lsr r7, r6, #16 \n\t" \ + "lsl r6, r6, #16 \n\t" \ + "lsr r6, r6, #16 \n\t" \ + "mov r4, r8 \n\t" \ + "mul r4, r6 \n\t" \ + "mov r3, r9 \n\t" \ + "mul r6, r3 \n\t" \ + "mov r5, r9 \n\t" \ + "mul r5, r7 \n\t" \ + "mov r3, r8 \n\t" \ + "mul r7, r3 \n\t" \ + "lsr r3, r6, #16 \n\t" \ + "add r5, r5, r3 \n\t" \ + "lsr r3, r7, #16 \n\t" \ + "add r5, r5, r3 \n\t" \ + "add r4, r4, r2 \n\t" \ + "mov r2, #0 \n\t" \ + "adc r5, r2 \n\t" \ + "lsl r3, r6, #16 \n\t" \ + "add r4, r4, r3 \n\t" \ + "adc r5, r2 \n\t" \ + "lsl r3, r7, #16 \n\t" \ + "add r4, r4, r3 \n\t" \ + "adc r5, r2 \n\t" \ + "ldr r3, [r1] \n\t" \ + "add r4, r4, r3 \n\t" \ + "adc r2, r5 \n\t" \ + "stmia r1!, {r4} \n\t" + +#define MULADDC_STOP \ + "str r2, %0 \n\t" \ + "str r1, %1 \n\t" \ + "str r0, %2 \n\t" \ + : "=m" (c), "=m" (d), "=m" (s) \ + : "m" (s), "m" (d), "m" (c), "m" (b) \ + : "r0", "r1", "r2", "r3", "r4", "r5", \ + "r6", "r7", "r8", "r9", "cc" \ + ); + +#elif (__ARM_ARCH >= 6) && \ + defined (__ARM_FEATURE_DSP) && (__ARM_FEATURE_DSP == 1) + +#define MULADDC_INIT \ + asm( + +#define MULADDC_CORE \ + "ldr r0, [%0], #4 \n\t" \ + "ldr r1, [%1] \n\t" \ + "umaal r1, %2, %3, r0 \n\t" \ + "str r1, [%1], #4 \n\t" + +#define MULADDC_STOP \ + : "=r" (s), "=r" (d), "=r" (c) \ + : "r" (b), "0" (s), "1" (d), "2" (c) \ + : "r0", "r1", "memory" \ + ); + +#else + +#define MULADDC_INIT \ + asm( \ + "ldr r0, %3 \n\t" \ + "ldr r1, %4 \n\t" \ + "ldr r2, %5 \n\t" \ + "ldr r3, %6 \n\t" + +#define MULADDC_CORE \ + "ldr r4, [r0], #4 \n\t" \ + "mov r5, #0 \n\t" \ + "ldr r6, [r1] \n\t" \ + "umlal r2, r5, r3, r4 \n\t" \ + "adds r7, r6, r2 \n\t" \ + "adc r2, r5, #0 \n\t" \ + "str r7, [r1], #4 \n\t" + +#define MULADDC_STOP \ + "str r2, %0 \n\t" \ + "str r1, %1 \n\t" \ + "str r0, %2 \n\t" \ + : "=m" (c), "=m" (d), "=m" (s) \ + : "m" (s), "m" (d), "m" (c), "m" (b) \ + : "r0", "r1", "r2", "r3", "r4", "r5", \ + "r6", "r7", "cc" \ + ); + +#endif /* Thumb */ + +#endif /* ARMv3 */ + +#if defined(__alpha__) + +#define MULADDC_INIT \ + asm( \ + "ldq $1, %3 \n\t" \ + "ldq $2, %4 \n\t" \ + "ldq $3, %5 \n\t" \ + "ldq $4, %6 \n\t" + +#define MULADDC_CORE \ + "ldq $6, 0($1) \n\t" \ + "addq $1, 8, $1 \n\t" \ + "mulq $6, $4, $7 \n\t" \ + "umulh $6, $4, $6 \n\t" \ + "addq $7, $3, $7 \n\t" \ + "cmpult $7, $3, $3 \n\t" \ + "ldq $5, 0($2) \n\t" \ + "addq $7, $5, $7 \n\t" \ + "cmpult $7, $5, $5 \n\t" \ + "stq $7, 0($2) \n\t" \ + "addq $2, 8, $2 \n\t" \ + "addq $6, $3, $3 \n\t" \ + "addq $5, $3, $3 \n\t" + +#define MULADDC_STOP \ + "stq $3, %0 \n\t" \ + "stq $2, %1 \n\t" \ + "stq $1, %2 \n\t" \ + : "=m" (c), "=m" (d), "=m" (s) \ + : "m" (s), "m" (d), "m" (c), "m" (b) \ + : "$1", "$2", "$3", "$4", "$5", "$6", "$7" \ + ); +#endif /* Alpha */ + +#if defined(__mips__) && !defined(__mips64) + +#define MULADDC_INIT \ + asm( \ + "lw $10, %3 \n\t" \ + "lw $11, %4 \n\t" \ + "lw $12, %5 \n\t" \ + "lw $13, %6 \n\t" + +#define MULADDC_CORE \ + "lw $14, 0($10) \n\t" \ + "multu $13, $14 \n\t" \ + "addi $10, $10, 4 \n\t" \ + "mflo $14 \n\t" \ + "mfhi $9 \n\t" \ + "addu $14, $12, $14 \n\t" \ + "lw $15, 0($11) \n\t" \ + "sltu $12, $14, $12 \n\t" \ + "addu $15, $14, $15 \n\t" \ + "sltu $14, $15, $14 \n\t" \ + "addu $12, $12, $9 \n\t" \ + "sw $15, 0($11) \n\t" \ + "addu $12, $12, $14 \n\t" \ + "addi $11, $11, 4 \n\t" + +#define MULADDC_STOP \ + "sw $12, %0 \n\t" \ + "sw $11, %1 \n\t" \ + "sw $10, %2 \n\t" \ + : "=m" (c), "=m" (d), "=m" (s) \ + : "m" (s), "m" (d), "m" (c), "m" (b) \ + : "$9", "$10", "$11", "$12", "$13", "$14", "$15", "lo", "hi" \ + ); + +#endif /* MIPS */ +#endif /* GNUC */ + +#if (defined(_MSC_VER) && defined(_M_IX86)) || defined(__WATCOMC__) + +#define MULADDC_INIT \ + __asm mov esi, s \ + __asm mov edi, d \ + __asm mov ecx, c \ + __asm mov ebx, b + +#define MULADDC_CORE \ + __asm lodsd \ + __asm mul ebx \ + __asm add eax, ecx \ + __asm adc edx, 0 \ + __asm add eax, [edi] \ + __asm adc edx, 0 \ + __asm mov ecx, edx \ + __asm stosd + +#if defined(MBEDTLS_HAVE_SSE2) + +#define EMIT __asm _emit + +#define MULADDC_HUIT \ + EMIT 0x0F EMIT 0x6E EMIT 0xC9 \ + EMIT 0x0F EMIT 0x6E EMIT 0xC3 \ + EMIT 0x0F EMIT 0x6E EMIT 0x1F \ + EMIT 0x0F EMIT 0xD4 EMIT 0xCB \ + EMIT 0x0F EMIT 0x6E EMIT 0x16 \ + EMIT 0x0F EMIT 0xF4 EMIT 0xD0 \ + EMIT 0x0F EMIT 0x6E EMIT 0x66 EMIT 0x04 \ + EMIT 0x0F EMIT 0xF4 EMIT 0xE0 \ + EMIT 0x0F EMIT 0x6E EMIT 0x76 EMIT 0x08 \ + EMIT 0x0F EMIT 0xF4 EMIT 0xF0 \ + EMIT 0x0F EMIT 0x6E EMIT 0x7E EMIT 0x0C \ + EMIT 0x0F EMIT 0xF4 EMIT 0xF8 \ + EMIT 0x0F EMIT 0xD4 EMIT 0xCA \ + EMIT 0x0F EMIT 0x6E EMIT 0x5F EMIT 0x04 \ + EMIT 0x0F EMIT 0xD4 EMIT 0xDC \ + EMIT 0x0F EMIT 0x6E EMIT 0x6F EMIT 0x08 \ + EMIT 0x0F EMIT 0xD4 EMIT 0xEE \ + EMIT 0x0F EMIT 0x6E EMIT 0x67 EMIT 0x0C \ + EMIT 0x0F EMIT 0xD4 EMIT 0xFC \ + EMIT 0x0F EMIT 0x7E EMIT 0x0F \ + EMIT 0x0F EMIT 0x6E EMIT 0x56 EMIT 0x10 \ + EMIT 0x0F EMIT 0xF4 EMIT 0xD0 \ + EMIT 0x0F EMIT 0x73 EMIT 0xD1 EMIT 0x20 \ + EMIT 0x0F EMIT 0x6E EMIT 0x66 EMIT 0x14 \ + EMIT 0x0F EMIT 0xF4 EMIT 0xE0 \ + EMIT 0x0F EMIT 0xD4 EMIT 0xCB \ + EMIT 0x0F EMIT 0x6E EMIT 0x76 EMIT 0x18 \ + EMIT 0x0F EMIT 0xF4 EMIT 0xF0 \ + EMIT 0x0F EMIT 0x7E EMIT 0x4F EMIT 0x04 \ + EMIT 0x0F EMIT 0x73 EMIT 0xD1 EMIT 0x20 \ + EMIT 0x0F EMIT 0x6E EMIT 0x5E EMIT 0x1C \ + EMIT 0x0F EMIT 0xF4 EMIT 0xD8 \ + EMIT 0x0F EMIT 0xD4 EMIT 0xCD \ + EMIT 0x0F EMIT 0x6E EMIT 0x6F EMIT 0x10 \ + EMIT 0x0F EMIT 0xD4 EMIT 0xD5 \ + EMIT 0x0F EMIT 0x7E EMIT 0x4F EMIT 0x08 \ + EMIT 0x0F EMIT 0x73 EMIT 0xD1 EMIT 0x20 \ + EMIT 0x0F EMIT 0xD4 EMIT 0xCF \ + EMIT 0x0F EMIT 0x6E EMIT 0x6F EMIT 0x14 \ + EMIT 0x0F EMIT 0xD4 EMIT 0xE5 \ + EMIT 0x0F EMIT 0x7E EMIT 0x4F EMIT 0x0C \ + EMIT 0x0F EMIT 0x73 EMIT 0xD1 EMIT 0x20 \ + EMIT 0x0F EMIT 0xD4 EMIT 0xCA \ + EMIT 0x0F EMIT 0x6E EMIT 0x6F EMIT 0x18 \ + EMIT 0x0F EMIT 0xD4 EMIT 0xF5 \ + EMIT 0x0F EMIT 0x7E EMIT 0x4F EMIT 0x10 \ + EMIT 0x0F EMIT 0x73 EMIT 0xD1 EMIT 0x20 \ + EMIT 0x0F EMIT 0xD4 EMIT 0xCC \ + EMIT 0x0F EMIT 0x6E EMIT 0x6F EMIT 0x1C \ + EMIT 0x0F EMIT 0xD4 EMIT 0xDD \ + EMIT 0x0F EMIT 0x7E EMIT 0x4F EMIT 0x14 \ + EMIT 0x0F EMIT 0x73 EMIT 0xD1 EMIT 0x20 \ + EMIT 0x0F EMIT 0xD4 EMIT 0xCE \ + EMIT 0x0F EMIT 0x7E EMIT 0x4F EMIT 0x18 \ + EMIT 0x0F EMIT 0x73 EMIT 0xD1 EMIT 0x20 \ + EMIT 0x0F EMIT 0xD4 EMIT 0xCB \ + EMIT 0x0F EMIT 0x7E EMIT 0x4F EMIT 0x1C \ + EMIT 0x83 EMIT 0xC7 EMIT 0x20 \ + EMIT 0x83 EMIT 0xC6 EMIT 0x20 \ + EMIT 0x0F EMIT 0x73 EMIT 0xD1 EMIT 0x20 \ + EMIT 0x0F EMIT 0x7E EMIT 0xC9 + +#define MULADDC_STOP \ + EMIT 0x0F EMIT 0x77 \ + __asm mov c, ecx \ + __asm mov d, edi \ + __asm mov s, esi \ + +#else + +#define MULADDC_STOP \ + __asm mov c, ecx \ + __asm mov d, edi \ + __asm mov s, esi \ + +#endif /* SSE2 */ +#endif /* MSVC */ + +#endif /* MBEDTLS_HAVE_ASM */ + +#if !defined(MULADDC_CORE) +#if defined(MBEDTLS_HAVE_UDBL) + +#define MULADDC_INIT \ +{ \ + mbedtls_t_udbl r; \ + mbedtls_mpi_uint r0, r1; + +#define MULADDC_CORE \ + r = *(s++) * (mbedtls_t_udbl) b; \ + r0 = (mbedtls_mpi_uint) r; \ + r1 = (mbedtls_mpi_uint)( r >> biL ); \ + r0 += c; r1 += (r0 < c); \ + r0 += *d; r1 += (r0 < *d); \ + c = r1; *(d++) = r0; + +#define MULADDC_STOP \ +} + +#else +#define MULADDC_INIT \ +{ \ + mbedtls_mpi_uint s0, s1, b0, b1; \ + mbedtls_mpi_uint r0, r1, rx, ry; \ + b0 = ( b << biH ) >> biH; \ + b1 = ( b >> biH ); + +#define MULADDC_CORE \ + s0 = ( *s << biH ) >> biH; \ + s1 = ( *s >> biH ); s++; \ + rx = s0 * b1; r0 = s0 * b0; \ + ry = s1 * b0; r1 = s1 * b1; \ + r1 += ( rx >> biH ); \ + r1 += ( ry >> biH ); \ + rx <<= biH; ry <<= biH; \ + r0 += rx; r1 += (r0 < rx); \ + r0 += ry; r1 += (r0 < ry); \ + r0 += c; r1 += (r0 < c); \ + r0 += *d; r1 += (r0 < *d); \ + c = r1; *(d++) = r0; + +#define MULADDC_STOP \ +} + +#endif /* C (generic) */ +#endif /* C (longlong) */ + +#endif /* bn_mul.h */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/camellia.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/camellia.h new file mode 100644 index 0000000000000000000000000000000000000000..3eeb66366d68224c0662a3b0dd0ee3bb81e4f747 --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/camellia.h @@ -0,0 +1,326 @@ +/** + * \file camellia.h + * + * \brief Camellia block cipher + */ +/* + * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ +#ifndef MBEDTLS_CAMELLIA_H +#define MBEDTLS_CAMELLIA_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include +#include + +#include "platform_util.h" + +#define MBEDTLS_CAMELLIA_ENCRYPT 1 +#define MBEDTLS_CAMELLIA_DECRYPT 0 + +#if !defined(MBEDTLS_DEPRECATED_REMOVED) +#define MBEDTLS_ERR_CAMELLIA_INVALID_KEY_LENGTH MBEDTLS_DEPRECATED_NUMERIC_CONSTANT( -0x0024 ) +#endif /* !MBEDTLS_DEPRECATED_REMOVED */ +#define MBEDTLS_ERR_CAMELLIA_BAD_INPUT_DATA -0x0024 /**< Bad input data. */ + +#define MBEDTLS_ERR_CAMELLIA_INVALID_INPUT_LENGTH -0x0026 /**< Invalid data input length. */ + +/* MBEDTLS_ERR_CAMELLIA_HW_ACCEL_FAILED is deprecated and should not be used. + */ +#define MBEDTLS_ERR_CAMELLIA_HW_ACCEL_FAILED -0x0027 /**< Camellia hardware accelerator failed. */ + +#ifdef __cplusplus +extern "C" { +#endif + +#if !defined(MBEDTLS_CAMELLIA_ALT) +// Regular implementation +// + +/** + * \brief CAMELLIA context structure + */ +typedef struct mbedtls_camellia_context +{ + int nr; /*!< number of rounds */ + uint32_t rk[68]; /*!< CAMELLIA round keys */ +} +mbedtls_camellia_context; + +#else /* MBEDTLS_CAMELLIA_ALT */ +#include "camellia_alt.h" +#endif /* MBEDTLS_CAMELLIA_ALT */ + +/** + * \brief Initialize a CAMELLIA context. + * + * \param ctx The CAMELLIA context to be initialized. + * This must not be \c NULL. + */ +void mbedtls_camellia_init( mbedtls_camellia_context *ctx ); + +/** + * \brief Clear a CAMELLIA context. + * + * \param ctx The CAMELLIA context to be cleared. This may be \c NULL, + * in which case this function returns immediately. If it is not + * \c NULL, it must be initialized. + */ +void mbedtls_camellia_free( mbedtls_camellia_context *ctx ); + +/** + * \brief Perform a CAMELLIA key schedule operation for encryption. + * + * \param ctx The CAMELLIA context to use. This must be initialized. + * \param key The encryption key to use. This must be a readable buffer + * of size \p keybits Bits. + * \param keybits The length of \p key in Bits. This must be either \c 128, + * \c 192 or \c 256. + * + * \return \c 0 if successful. + * \return A negative error code on failure. + */ +int mbedtls_camellia_setkey_enc( mbedtls_camellia_context *ctx, + const unsigned char *key, + unsigned int keybits ); + +/** + * \brief Perform a CAMELLIA key schedule operation for decryption. + * + * \param ctx The CAMELLIA context to use. This must be initialized. + * \param key The decryption key. This must be a readable buffer + * of size \p keybits Bits. + * \param keybits The length of \p key in Bits. This must be either \c 128, + * \c 192 or \c 256. + * + * \return \c 0 if successful. + * \return A negative error code on failure. + */ +int mbedtls_camellia_setkey_dec( mbedtls_camellia_context *ctx, + const unsigned char *key, + unsigned int keybits ); + +/** + * \brief Perform a CAMELLIA-ECB block encryption/decryption operation. + * + * \param ctx The CAMELLIA context to use. This must be initialized + * and bound to a key. + * \param mode The mode of operation. This must be either + * #MBEDTLS_CAMELLIA_ENCRYPT or #MBEDTLS_CAMELLIA_DECRYPT. + * \param input The input block. This must be a readable buffer + * of size \c 16 Bytes. + * \param output The output block. This must be a writable buffer + * of size \c 16 Bytes. + * + * \return \c 0 if successful. + * \return A negative error code on failure. + */ +int mbedtls_camellia_crypt_ecb( mbedtls_camellia_context *ctx, + int mode, + const unsigned char input[16], + unsigned char output[16] ); + +#if defined(MBEDTLS_CIPHER_MODE_CBC) +/** + * \brief Perform a CAMELLIA-CBC buffer encryption/decryption operation. + * + * \note Upon exit, the content of the IV is updated so that you can + * call the function same function again on the following + * block(s) of data and get the same result as if it was + * encrypted in one call. This allows a "streaming" usage. + * If on the other hand you need to retain the contents of the + * IV, you should either save it manually or use the cipher + * module instead. + * + * \param ctx The CAMELLIA context to use. This must be initialized + * and bound to a key. + * \param mode The mode of operation. This must be either + * #MBEDTLS_CAMELLIA_ENCRYPT or #MBEDTLS_CAMELLIA_DECRYPT. + * \param length The length in Bytes of the input data \p input. + * This must be a multiple of \c 16 Bytes. + * \param iv The initialization vector. This must be a read/write buffer + * of length \c 16 Bytes. It is updated to allow streaming + * use as explained above. + * \param input The buffer holding the input data. This must point to a + * readable buffer of length \p length Bytes. + * \param output The buffer holding the output data. This must point to a + * writable buffer of length \p length Bytes. + * + * \return \c 0 if successful. + * \return A negative error code on failure. + */ +int mbedtls_camellia_crypt_cbc( mbedtls_camellia_context *ctx, + int mode, + size_t length, + unsigned char iv[16], + const unsigned char *input, + unsigned char *output ); +#endif /* MBEDTLS_CIPHER_MODE_CBC */ + +#if defined(MBEDTLS_CIPHER_MODE_CFB) +/** + * \brief Perform a CAMELLIA-CFB128 buffer encryption/decryption + * operation. + * + * \note Due to the nature of CFB mode, you should use the same + * key for both encryption and decryption. In particular, calls + * to this function should be preceded by a key-schedule via + * mbedtls_camellia_setkey_enc() regardless of whether \p mode + * is #MBEDTLS_CAMELLIA_ENCRYPT or #MBEDTLS_CAMELLIA_DECRYPT. + * + * \note Upon exit, the content of the IV is updated so that you can + * call the function same function again on the following + * block(s) of data and get the same result as if it was + * encrypted in one call. This allows a "streaming" usage. + * If on the other hand you need to retain the contents of the + * IV, you should either save it manually or use the cipher + * module instead. + * + * \param ctx The CAMELLIA context to use. This must be initialized + * and bound to a key. + * \param mode The mode of operation. This must be either + * #MBEDTLS_CAMELLIA_ENCRYPT or #MBEDTLS_CAMELLIA_DECRYPT. + * \param length The length of the input data \p input. Any value is allowed. + * \param iv_off The current offset in the IV. This must be smaller + * than \c 16 Bytes. It is updated after this call to allow + * the aforementioned streaming usage. + * \param iv The initialization vector. This must be a read/write buffer + * of length \c 16 Bytes. It is updated after this call to + * allow the aforementioned streaming usage. + * \param input The buffer holding the input data. This must be a readable + * buffer of size \p length Bytes. + * \param output The buffer to hold the output data. This must be a writable + * buffer of length \p length Bytes. + * + * \return \c 0 if successful. + * \return A negative error code on failure. + */ +int mbedtls_camellia_crypt_cfb128( mbedtls_camellia_context *ctx, + int mode, + size_t length, + size_t *iv_off, + unsigned char iv[16], + const unsigned char *input, + unsigned char *output ); +#endif /* MBEDTLS_CIPHER_MODE_CFB */ + +#if defined(MBEDTLS_CIPHER_MODE_CTR) +/** + * \brief Perform a CAMELLIA-CTR buffer encryption/decryption operation. + * + * *note Due to the nature of CTR mode, you should use the same + * key for both encryption and decryption. In particular, calls + * to this function should be preceded by a key-schedule via + * mbedtls_camellia_setkey_enc() regardless of whether \p mode + * is #MBEDTLS_CAMELLIA_ENCRYPT or #MBEDTLS_CAMELLIA_DECRYPT. + * + * \warning You must never reuse a nonce value with the same key. Doing so + * would void the encryption for the two messages encrypted with + * the same nonce and key. + * + * There are two common strategies for managing nonces with CTR: + * + * 1. You can handle everything as a single message processed over + * successive calls to this function. In that case, you want to + * set \p nonce_counter and \p nc_off to 0 for the first call, and + * then preserve the values of \p nonce_counter, \p nc_off and \p + * stream_block across calls to this function as they will be + * updated by this function. + * + * With this strategy, you must not encrypt more than 2**128 + * blocks of data with the same key. + * + * 2. You can encrypt separate messages by dividing the \p + * nonce_counter buffer in two areas: the first one used for a + * per-message nonce, handled by yourself, and the second one + * updated by this function internally. + * + * For example, you might reserve the first \c 12 Bytes for the + * per-message nonce, and the last \c 4 Bytes for internal use. + * In that case, before calling this function on a new message you + * need to set the first \c 12 Bytes of \p nonce_counter to your + * chosen nonce value, the last four to \c 0, and \p nc_off to \c 0 + * (which will cause \p stream_block to be ignored). That way, you + * can encrypt at most \c 2**96 messages of up to \c 2**32 blocks + * each with the same key. + * + * The per-message nonce (or information sufficient to reconstruct + * it) needs to be communicated with the ciphertext and must be + * unique. The recommended way to ensure uniqueness is to use a + * message counter. An alternative is to generate random nonces, + * but this limits the number of messages that can be securely + * encrypted: for example, with 96-bit random nonces, you should + * not encrypt more than 2**32 messages with the same key. + * + * Note that for both stategies, sizes are measured in blocks and + * that a CAMELLIA block is \c 16 Bytes. + * + * \warning Upon return, \p stream_block contains sensitive data. Its + * content must not be written to insecure storage and should be + * securely discarded as soon as it's no longer needed. + * + * \param ctx The CAMELLIA context to use. This must be initialized + * and bound to a key. + * \param length The length of the input data \p input in Bytes. + * Any value is allowed. + * \param nc_off The offset in the current \p stream_block (for resuming + * within current cipher stream). The offset pointer to + * should be \c 0 at the start of a stream. It is updated + * at the end of this call. + * \param nonce_counter The 128-bit nonce and counter. This must be a read/write + * buffer of length \c 16 Bytes. + * \param stream_block The saved stream-block for resuming. This must be a + * read/write buffer of length \c 16 Bytes. + * \param input The input data stream. This must be a readable buffer of + * size \p length Bytes. + * \param output The output data stream. This must be a writable buffer + * of size \p length Bytes. + * + * \return \c 0 if successful. + * \return A negative error code on failure. + */ +int mbedtls_camellia_crypt_ctr( mbedtls_camellia_context *ctx, + size_t length, + size_t *nc_off, + unsigned char nonce_counter[16], + unsigned char stream_block[16], + const unsigned char *input, + unsigned char *output ); +#endif /* MBEDTLS_CIPHER_MODE_CTR */ + +#if defined(MBEDTLS_SELF_TEST) + +/** + * \brief Checkup routine + * + * \return 0 if successful, or 1 if the test failed + */ +int mbedtls_camellia_self_test( int verbose ); + +#endif /* MBEDTLS_SELF_TEST */ + +#ifdef __cplusplus +} +#endif + +#endif /* camellia.h */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/ccm.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/ccm.h new file mode 100644 index 0000000000000000000000000000000000000000..f03e3b580eae0c842277fd11cc2b94e98f04ed5a --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/ccm.h @@ -0,0 +1,310 @@ +/** + * \file ccm.h + * + * \brief This file provides an API for the CCM authenticated encryption + * mode for block ciphers. + * + * CCM combines Counter mode encryption with CBC-MAC authentication + * for 128-bit block ciphers. + * + * Input to CCM includes the following elements: + *
                            • Payload - data that is both authenticated and encrypted.
                            • + *
                            • Associated data (Adata) - data that is authenticated but not + * encrypted, For example, a header.
                            • + *
                            • Nonce - A unique value that is assigned to the payload and the + * associated data.
                            + * + * Definition of CCM: + * http://csrc.nist.gov/publications/nistpubs/800-38C/SP800-38C_updated-July20_2007.pdf + * RFC 3610 "Counter with CBC-MAC (CCM)" + * + * Related: + * RFC 5116 "An Interface and Algorithms for Authenticated Encryption" + * + * Definition of CCM*: + * IEEE 802.15.4 - IEEE Standard for Local and metropolitan area networks + * Integer representation is fixed most-significant-octet-first order and + * the representation of octets is most-significant-bit-first order. This is + * consistent with RFC 3610. + */ +/* + * Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of Mbed TLS (https://tls.mbed.org) + */ + +#ifndef MBEDTLS_CCM_H +#define MBEDTLS_CCM_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include "cipher.h" + +#define MBEDTLS_ERR_CCM_BAD_INPUT -0x000D /**< Bad input parameters to the function. */ +#define MBEDTLS_ERR_CCM_AUTH_FAILED -0x000F /**< Authenticated decryption failed. */ + +/* MBEDTLS_ERR_CCM_HW_ACCEL_FAILED is deprecated and should not be used. */ +#define MBEDTLS_ERR_CCM_HW_ACCEL_FAILED -0x0011 /**< CCM hardware accelerator failed. */ + +#ifdef __cplusplus +extern "C" { +#endif + +#if !defined(MBEDTLS_CCM_ALT) +// Regular implementation +// + +/** + * \brief The CCM context-type definition. The CCM context is passed + * to the APIs called. + */ +typedef struct mbedtls_ccm_context +{ + mbedtls_cipher_context_t cipher_ctx; /*!< The cipher context used. */ +} +mbedtls_ccm_context; + +#else /* MBEDTLS_CCM_ALT */ +#include "ccm_alt.h" +#endif /* MBEDTLS_CCM_ALT */ + +/** + * \brief This function initializes the specified CCM context, + * to make references valid, and prepare the context + * for mbedtls_ccm_setkey() or mbedtls_ccm_free(). + * + * \param ctx The CCM context to initialize. This must not be \c NULL. + */ +void mbedtls_ccm_init( mbedtls_ccm_context *ctx ); + +/** + * \brief This function initializes the CCM context set in the + * \p ctx parameter and sets the encryption key. + * + * \param ctx The CCM context to initialize. This must be an initialized + * context. + * \param cipher The 128-bit block cipher to use. + * \param key The encryption key. This must not be \c NULL. + * \param keybits The key size in bits. This must be acceptable by the cipher. + * + * \return \c 0 on success. + * \return A CCM or cipher-specific error code on failure. + */ +int mbedtls_ccm_setkey( mbedtls_ccm_context *ctx, + mbedtls_cipher_id_t cipher, + const unsigned char *key, + unsigned int keybits ); + +/** + * \brief This function releases and clears the specified CCM context + * and underlying cipher sub-context. + * + * \param ctx The CCM context to clear. If this is \c NULL, the function + * has no effect. Otherwise, this must be initialized. + */ +void mbedtls_ccm_free( mbedtls_ccm_context *ctx ); + +/** + * \brief This function encrypts a buffer using CCM. + * + * \note The tag is written to a separate buffer. To concatenate + * the \p tag with the \p output, as done in RFC-3610: + * Counter with CBC-MAC (CCM), use + * \p tag = \p output + \p length, and make sure that the + * output buffer is at least \p length + \p tag_len wide. + * + * \param ctx The CCM context to use for encryption. This must be + * initialized and bound to a key. + * \param length The length of the input data in Bytes. + * \param iv The initialization vector (nonce). This must be a readable + * buffer of at least \p iv_len Bytes. + * \param iv_len The length of the nonce in Bytes: 7, 8, 9, 10, 11, 12, + * or 13. The length L of the message length field is + * 15 - \p iv_len. + * \param add The additional data field. If \p add_len is greater than + * zero, \p add must be a readable buffer of at least that + * length. + * \param add_len The length of additional data in Bytes. + * This must be less than `2^16 - 2^8`. + * \param input The buffer holding the input data. If \p length is greater + * than zero, \p input must be a readable buffer of at least + * that length. + * \param output The buffer holding the output data. If \p length is greater + * than zero, \p output must be a writable buffer of at least + * that length. + * \param tag The buffer holding the authentication field. This must be a + * readable buffer of at least \p tag_len Bytes. + * \param tag_len The length of the authentication field to generate in Bytes: + * 4, 6, 8, 10, 12, 14 or 16. + * + * \return \c 0 on success. + * \return A CCM or cipher-specific error code on failure. + */ +int mbedtls_ccm_encrypt_and_tag( mbedtls_ccm_context *ctx, size_t length, + const unsigned char *iv, size_t iv_len, + const unsigned char *add, size_t add_len, + const unsigned char *input, unsigned char *output, + unsigned char *tag, size_t tag_len ); + +/** + * \brief This function encrypts a buffer using CCM*. + * + * \note The tag is written to a separate buffer. To concatenate + * the \p tag with the \p output, as done in RFC-3610: + * Counter with CBC-MAC (CCM), use + * \p tag = \p output + \p length, and make sure that the + * output buffer is at least \p length + \p tag_len wide. + * + * \note When using this function in a variable tag length context, + * the tag length has to be encoded into the \p iv passed to + * this function. + * + * \param ctx The CCM context to use for encryption. This must be + * initialized and bound to a key. + * \param length The length of the input data in Bytes. + * \param iv The initialization vector (nonce). This must be a readable + * buffer of at least \p iv_len Bytes. + * \param iv_len The length of the nonce in Bytes: 7, 8, 9, 10, 11, 12, + * or 13. The length L of the message length field is + * 15 - \p iv_len. + * \param add The additional data field. This must be a readable buffer of + * at least \p add_len Bytes. + * \param add_len The length of additional data in Bytes. + * This must be less than 2^16 - 2^8. + * \param input The buffer holding the input data. If \p length is greater + * than zero, \p input must be a readable buffer of at least + * that length. + * \param output The buffer holding the output data. If \p length is greater + * than zero, \p output must be a writable buffer of at least + * that length. + * \param tag The buffer holding the authentication field. This must be a + * readable buffer of at least \p tag_len Bytes. + * \param tag_len The length of the authentication field to generate in Bytes: + * 0, 4, 6, 8, 10, 12, 14 or 16. + * + * \warning Passing \c 0 as \p tag_len means that the message is no + * longer authenticated. + * + * \return \c 0 on success. + * \return A CCM or cipher-specific error code on failure. + */ +int mbedtls_ccm_star_encrypt_and_tag( mbedtls_ccm_context *ctx, size_t length, + const unsigned char *iv, size_t iv_len, + const unsigned char *add, size_t add_len, + const unsigned char *input, unsigned char *output, + unsigned char *tag, size_t tag_len ); + +/** + * \brief This function performs a CCM authenticated decryption of a + * buffer. + * + * \param ctx The CCM context to use for decryption. This must be + * initialized and bound to a key. + * \param length The length of the input data in Bytes. + * \param iv The initialization vector (nonce). This must be a readable + * buffer of at least \p iv_len Bytes. + * \param iv_len The length of the nonce in Bytes: 7, 8, 9, 10, 11, 12, + * or 13. The length L of the message length field is + * 15 - \p iv_len. + * \param add The additional data field. This must be a readable buffer + * of at least that \p add_len Bytes.. + * \param add_len The length of additional data in Bytes. + * This must be less than 2^16 - 2^8. + * \param input The buffer holding the input data. If \p length is greater + * than zero, \p input must be a readable buffer of at least + * that length. + * \param output The buffer holding the output data. If \p length is greater + * than zero, \p output must be a writable buffer of at least + * that length. + * \param tag The buffer holding the authentication field. This must be a + * readable buffer of at least \p tag_len Bytes. + * \param tag_len The length of the authentication field to generate in Bytes: + * 4, 6, 8, 10, 12, 14 or 16. + * + * \return \c 0 on success. This indicates that the message is authentic. + * \return #MBEDTLS_ERR_CCM_AUTH_FAILED if the tag does not match. + * \return A cipher-specific error code on calculation failure. + */ +int mbedtls_ccm_auth_decrypt( mbedtls_ccm_context *ctx, size_t length, + const unsigned char *iv, size_t iv_len, + const unsigned char *add, size_t add_len, + const unsigned char *input, unsigned char *output, + const unsigned char *tag, size_t tag_len ); + +/** + * \brief This function performs a CCM* authenticated decryption of a + * buffer. + * + * \note When using this function in a variable tag length context, + * the tag length has to be decoded from \p iv and passed to + * this function as \p tag_len. (\p tag needs to be adjusted + * accordingly.) + * + * \param ctx The CCM context to use for decryption. This must be + * initialized and bound to a key. + * \param length The length of the input data in Bytes. + * \param iv The initialization vector (nonce). This must be a readable + * buffer of at least \p iv_len Bytes. + * \param iv_len The length of the nonce in Bytes: 7, 8, 9, 10, 11, 12, + * or 13. The length L of the message length field is + * 15 - \p iv_len. + * \param add The additional data field. This must be a readable buffer of + * at least that \p add_len Bytes. + * \param add_len The length of additional data in Bytes. + * This must be less than 2^16 - 2^8. + * \param input The buffer holding the input data. If \p length is greater + * than zero, \p input must be a readable buffer of at least + * that length. + * \param output The buffer holding the output data. If \p length is greater + * than zero, \p output must be a writable buffer of at least + * that length. + * \param tag The buffer holding the authentication field. This must be a + * readable buffer of at least \p tag_len Bytes. + * \param tag_len The length of the authentication field in Bytes. + * 0, 4, 6, 8, 10, 12, 14 or 16. + * + * \warning Passing \c 0 as \p tag_len means that the message is nos + * longer authenticated. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CCM_AUTH_FAILED if the tag does not match. + * \return A cipher-specific error code on calculation failure. + */ +int mbedtls_ccm_star_auth_decrypt( mbedtls_ccm_context *ctx, size_t length, + const unsigned char *iv, size_t iv_len, + const unsigned char *add, size_t add_len, + const unsigned char *input, unsigned char *output, + const unsigned char *tag, size_t tag_len ); + +#if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_AES_C) +/** + * \brief The CCM checkup routine. + * + * \return \c 0 on success. + * \return \c 1 on failure. + */ +int mbedtls_ccm_self_test( int verbose ); +#endif /* MBEDTLS_SELF_TEST && MBEDTLS_AES_C */ + +#ifdef __cplusplus +} +#endif + +#endif /* MBEDTLS_CCM_H */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/ccm_alt.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/ccm_alt.h new file mode 100644 index 0000000000000000000000000000000000000000..c44297422028e2f56df41e24072efe71e1982ea0 --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/ccm_alt.h @@ -0,0 +1,78 @@ +/** + * \file ccm.h + * + * \brief This file provides an API for the CCM authenticated encryption + * mode for block ciphers. + * + * CCM combines Counter mode encryption with CBC-MAC authentication + * for 128-bit block ciphers. + * + * Input to CCM includes the following elements: + *
                            • Payload - data that is both authenticated and encrypted.
                            • + *
                            • Associated data (Adata) - data that is authenticated but not + * encrypted, For example, a header.
                            • + *
                            • Nonce - A unique value that is assigned to the payload and the + * associated data.
                            + * + * Definition of CCM: + * http://csrc.nist.gov/publications/nistpubs/800-38C/SP800-38C_updated-July20_2007.pdf + * RFC 3610 "Counter with CBC-MAC (CCM)" + * + * Related: + * RFC 5116 "An Interface and Algorithms for Authenticated Encryption" + * + * Definition of CCM*: + * IEEE 802.15.4 - IEEE Standard for Local and metropolitan area networks + * Integer representation is fixed most-significant-octet-first order and + * the representation of octets is most-significant-bit-first order. This is + * consistent with RFC 3610. + */ +/* + * Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of Mbed TLS (https://tls.mbed.org) + */ + +#ifndef MBEDTLS_CCM_ALT_H +#define MBEDTLS_CCM_ALT_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include "cipher.h" +#include "cipher_internal.h" +#include "hi_cipher.h" +#include "securec.h" +#include "aes.h" + +#ifdef __cplusplus +extern "C" { +#endif +typedef struct mbedtls_ccm_context +{ + mbedtls_cipher_context_t cipher_ctx; /*!< The cipher context used. */ +} +mbedtls_ccm_context; + + +#ifdef __cplusplus +} +#endif + +#endif /* MBEDTLS_CCM_ALT_H */ \ No newline at end of file diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/certs.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/certs.h new file mode 100644 index 0000000000000000000000000000000000000000..179ebbbad22a3aba4ccf09a930da53a51d124d6c --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/certs.h @@ -0,0 +1,252 @@ +/** + * \file certs.h + * + * \brief Sample certificates and DHM parameters for testing + */ +/* + * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ +#ifndef MBEDTLS_CERTS_H +#define MBEDTLS_CERTS_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* List of all PEM-encoded CA certificates, terminated by NULL; + * PEM encoded if MBEDTLS_PEM_PARSE_C is enabled, DER encoded + * otherwise. */ +extern const char * mbedtls_test_cas[]; +extern const size_t mbedtls_test_cas_len[]; + +/* List of all DER-encoded CA certificates, terminated by NULL */ +extern const unsigned char * mbedtls_test_cas_der[]; +extern const size_t mbedtls_test_cas_der_len[]; + +#if defined(MBEDTLS_PEM_PARSE_C) +/* Concatenation of all CA certificates in PEM format if available */ +extern const char mbedtls_test_cas_pem[]; +extern const size_t mbedtls_test_cas_pem_len; +#endif /* MBEDTLS_PEM_PARSE_C */ + +/* + * CA test certificates + */ + +extern const char mbedtls_test_ca_crt_ec_pem[]; +extern const char mbedtls_test_ca_key_ec_pem[]; +extern const char mbedtls_test_ca_pwd_ec_pem[]; +extern const char mbedtls_test_ca_key_rsa_pem[]; +extern const char mbedtls_test_ca_pwd_rsa_pem[]; +extern const char mbedtls_test_ca_crt_rsa_sha1_pem[]; +extern const char mbedtls_test_ca_crt_rsa_sha256_pem[]; + +extern const unsigned char mbedtls_test_ca_crt_ec_der[]; +extern const unsigned char mbedtls_test_ca_key_ec_der[]; +extern const unsigned char mbedtls_test_ca_key_rsa_der[]; +extern const unsigned char mbedtls_test_ca_crt_rsa_sha1_der[]; +extern const unsigned char mbedtls_test_ca_crt_rsa_sha256_der[]; + +extern const size_t mbedtls_test_ca_crt_ec_pem_len; +extern const size_t mbedtls_test_ca_key_ec_pem_len; +extern const size_t mbedtls_test_ca_pwd_ec_pem_len; +extern const size_t mbedtls_test_ca_key_rsa_pem_len; +extern const size_t mbedtls_test_ca_pwd_rsa_pem_len; +extern const size_t mbedtls_test_ca_crt_rsa_sha1_pem_len; +extern const size_t mbedtls_test_ca_crt_rsa_sha256_pem_len; + +extern const size_t mbedtls_test_ca_crt_ec_der_len; +extern const size_t mbedtls_test_ca_key_ec_der_len; +extern const size_t mbedtls_test_ca_pwd_ec_der_len; +extern const size_t mbedtls_test_ca_key_rsa_der_len; +extern const size_t mbedtls_test_ca_pwd_rsa_der_len; +extern const size_t mbedtls_test_ca_crt_rsa_sha1_der_len; +extern const size_t mbedtls_test_ca_crt_rsa_sha256_der_len; + +/* Config-dependent dispatch between PEM and DER encoding + * (PEM if enabled, otherwise DER) */ + +extern const char mbedtls_test_ca_crt_ec[]; +extern const char mbedtls_test_ca_key_ec[]; +extern const char mbedtls_test_ca_pwd_ec[]; +extern const char mbedtls_test_ca_key_rsa[]; +extern const char mbedtls_test_ca_pwd_rsa[]; +extern const char mbedtls_test_ca_crt_rsa_sha1[]; +extern const char mbedtls_test_ca_crt_rsa_sha256[]; + +extern const size_t mbedtls_test_ca_crt_ec_len; +extern const size_t mbedtls_test_ca_key_ec_len; +extern const size_t mbedtls_test_ca_pwd_ec_len; +extern const size_t mbedtls_test_ca_key_rsa_len; +extern const size_t mbedtls_test_ca_pwd_rsa_len; +extern const size_t mbedtls_test_ca_crt_rsa_sha1_len; +extern const size_t mbedtls_test_ca_crt_rsa_sha256_len; + +/* Config-dependent dispatch between SHA-1 and SHA-256 + * (SHA-256 if enabled, otherwise SHA-1) */ + +extern const char mbedtls_test_ca_crt_rsa[]; +extern const size_t mbedtls_test_ca_crt_rsa_len; + +/* Config-dependent dispatch between EC and RSA + * (RSA if enabled, otherwise EC) */ + +extern const char * mbedtls_test_ca_crt; +extern const char * mbedtls_test_ca_key; +extern const char * mbedtls_test_ca_pwd; +extern const size_t mbedtls_test_ca_crt_len; +extern const size_t mbedtls_test_ca_key_len; +extern const size_t mbedtls_test_ca_pwd_len; + +/* + * Server test certificates + */ + +extern const char mbedtls_test_srv_crt_ec_pem[]; +extern const char mbedtls_test_srv_key_ec_pem[]; +extern const char mbedtls_test_srv_pwd_ec_pem[]; +extern const char mbedtls_test_srv_key_rsa_pem[]; +extern const char mbedtls_test_srv_pwd_rsa_pem[]; +extern const char mbedtls_test_srv_crt_rsa_sha1_pem[]; +extern const char mbedtls_test_srv_crt_rsa_sha256_pem[]; + +extern const unsigned char mbedtls_test_srv_crt_ec_der[]; +extern const unsigned char mbedtls_test_srv_key_ec_der[]; +extern const unsigned char mbedtls_test_srv_key_rsa_der[]; +extern const unsigned char mbedtls_test_srv_crt_rsa_sha1_der[]; +extern const unsigned char mbedtls_test_srv_crt_rsa_sha256_der[]; + +extern const size_t mbedtls_test_srv_crt_ec_pem_len; +extern const size_t mbedtls_test_srv_key_ec_pem_len; +extern const size_t mbedtls_test_srv_pwd_ec_pem_len; +extern const size_t mbedtls_test_srv_key_rsa_pem_len; +extern const size_t mbedtls_test_srv_pwd_rsa_pem_len; +extern const size_t mbedtls_test_srv_crt_rsa_sha1_pem_len; +extern const size_t mbedtls_test_srv_crt_rsa_sha256_pem_len; + +extern const size_t mbedtls_test_srv_crt_ec_der_len; +extern const size_t mbedtls_test_srv_key_ec_der_len; +extern const size_t mbedtls_test_srv_pwd_ec_der_len; +extern const size_t mbedtls_test_srv_key_rsa_der_len; +extern const size_t mbedtls_test_srv_pwd_rsa_der_len; +extern const size_t mbedtls_test_srv_crt_rsa_sha1_der_len; +extern const size_t mbedtls_test_srv_crt_rsa_sha256_der_len; + +/* Config-dependent dispatch between PEM and DER encoding + * (PEM if enabled, otherwise DER) */ + +extern const char mbedtls_test_srv_crt_ec[]; +extern const char mbedtls_test_srv_key_ec[]; +extern const char mbedtls_test_srv_pwd_ec[]; +extern const char mbedtls_test_srv_key_rsa[]; +extern const char mbedtls_test_srv_pwd_rsa[]; +extern const char mbedtls_test_srv_crt_rsa_sha1[]; +extern const char mbedtls_test_srv_crt_rsa_sha256[]; + +extern const size_t mbedtls_test_srv_crt_ec_len; +extern const size_t mbedtls_test_srv_key_ec_len; +extern const size_t mbedtls_test_srv_pwd_ec_len; +extern const size_t mbedtls_test_srv_key_rsa_len; +extern const size_t mbedtls_test_srv_pwd_rsa_len; +extern const size_t mbedtls_test_srv_crt_rsa_sha1_len; +extern const size_t mbedtls_test_srv_crt_rsa_sha256_len; + +/* Config-dependent dispatch between SHA-1 and SHA-256 + * (SHA-256 if enabled, otherwise SHA-1) */ + +extern const char mbedtls_test_srv_crt_rsa[]; +extern const size_t mbedtls_test_srv_crt_rsa_len; + +/* Config-dependent dispatch between EC and RSA + * (RSA if enabled, otherwise EC) */ + +extern const char * mbedtls_test_srv_crt; +extern const char * mbedtls_test_srv_key; +extern const char * mbedtls_test_srv_pwd; +extern const size_t mbedtls_test_srv_crt_len; +extern const size_t mbedtls_test_srv_key_len; +extern const size_t mbedtls_test_srv_pwd_len; + +/* + * Client test certificates + */ + +extern const char mbedtls_test_cli_crt_ec_pem[]; +extern const char mbedtls_test_cli_key_ec_pem[]; +extern const char mbedtls_test_cli_pwd_ec_pem[]; +extern const char mbedtls_test_cli_key_rsa_pem[]; +extern const char mbedtls_test_cli_pwd_rsa_pem[]; +extern const char mbedtls_test_cli_crt_rsa_pem[]; + +extern const unsigned char mbedtls_test_cli_crt_ec_der[]; +extern const unsigned char mbedtls_test_cli_key_ec_der[]; +extern const unsigned char mbedtls_test_cli_key_rsa_der[]; +extern const unsigned char mbedtls_test_cli_crt_rsa_der[]; + +extern const size_t mbedtls_test_cli_crt_ec_pem_len; +extern const size_t mbedtls_test_cli_key_ec_pem_len; +extern const size_t mbedtls_test_cli_pwd_ec_pem_len; +extern const size_t mbedtls_test_cli_key_rsa_pem_len; +extern const size_t mbedtls_test_cli_pwd_rsa_pem_len; +extern const size_t mbedtls_test_cli_crt_rsa_pem_len; + +extern const size_t mbedtls_test_cli_crt_ec_der_len; +extern const size_t mbedtls_test_cli_key_ec_der_len; +extern const size_t mbedtls_test_cli_key_rsa_der_len; +extern const size_t mbedtls_test_cli_crt_rsa_der_len; + +/* Config-dependent dispatch between PEM and DER encoding + * (PEM if enabled, otherwise DER) */ + +extern const char mbedtls_test_cli_crt_ec[]; +extern const char mbedtls_test_cli_key_ec[]; +extern const char mbedtls_test_cli_pwd_ec[]; +extern const char mbedtls_test_cli_key_rsa[]; +extern const char mbedtls_test_cli_pwd_rsa[]; +extern const char mbedtls_test_cli_crt_rsa[]; + +extern const size_t mbedtls_test_cli_crt_ec_len; +extern const size_t mbedtls_test_cli_key_ec_len; +extern const size_t mbedtls_test_cli_pwd_ec_len; +extern const size_t mbedtls_test_cli_key_rsa_len; +extern const size_t mbedtls_test_cli_pwd_rsa_len; +extern const size_t mbedtls_test_cli_crt_rsa_len; + +/* Config-dependent dispatch between EC and RSA + * (RSA if enabled, otherwise EC) */ + +extern const char * mbedtls_test_cli_crt; +extern const char * mbedtls_test_cli_key; +extern const char * mbedtls_test_cli_pwd; +extern const size_t mbedtls_test_cli_crt_len; +extern const size_t mbedtls_test_cli_key_len; +extern const size_t mbedtls_test_cli_pwd_len; + +#ifdef __cplusplus +} +#endif + +#endif /* certs.h */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/chacha20.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/chacha20.h new file mode 100644 index 0000000000000000000000000000000000000000..2ae5e6e5f4ee8ae0967af68a36272bb191412eb7 --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/chacha20.h @@ -0,0 +1,226 @@ +/** + * \file chacha20.h + * + * \brief This file contains ChaCha20 definitions and functions. + * + * ChaCha20 is a stream cipher that can encrypt and decrypt + * information. ChaCha was created by Daniel Bernstein as a variant of + * its Salsa cipher https://cr.yp.to/chacha/chacha-20080128.pdf + * ChaCha20 is the variant with 20 rounds, that was also standardized + * in RFC 7539. + * + * \author Daniel King + */ + +/* Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of Mbed TLS (https://tls.mbed.org) + */ + +#ifndef MBEDTLS_CHACHA20_H +#define MBEDTLS_CHACHA20_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include +#include + +#define MBEDTLS_ERR_CHACHA20_BAD_INPUT_DATA -0x0051 /**< Invalid input parameter(s). */ + +/* MBEDTLS_ERR_CHACHA20_FEATURE_UNAVAILABLE is deprecated and should not be + * used. */ +#define MBEDTLS_ERR_CHACHA20_FEATURE_UNAVAILABLE -0x0053 /**< Feature not available. For example, s part of the API is not implemented. */ + +/* MBEDTLS_ERR_CHACHA20_HW_ACCEL_FAILED is deprecated and should not be used. + */ +#define MBEDTLS_ERR_CHACHA20_HW_ACCEL_FAILED -0x0055 /**< Chacha20 hardware accelerator failed. */ + +#ifdef __cplusplus +extern "C" { +#endif + +#if !defined(MBEDTLS_CHACHA20_ALT) + +typedef struct mbedtls_chacha20_context +{ + uint32_t state[16]; /*! The state (before round operations). */ + uint8_t keystream8[64]; /*! Leftover keystream bytes. */ + size_t keystream_bytes_used; /*! Number of keystream bytes already used. */ +} +mbedtls_chacha20_context; + +#else /* MBEDTLS_CHACHA20_ALT */ +#include "chacha20_alt.h" +#endif /* MBEDTLS_CHACHA20_ALT */ + +/** + * \brief This function initializes the specified ChaCha20 context. + * + * It must be the first API called before using + * the context. + * + * It is usually followed by calls to + * \c mbedtls_chacha20_setkey() and + * \c mbedtls_chacha20_starts(), then one or more calls to + * to \c mbedtls_chacha20_update(), and finally to + * \c mbedtls_chacha20_free(). + * + * \param ctx The ChaCha20 context to initialize. + * This must not be \c NULL. + */ +void mbedtls_chacha20_init( mbedtls_chacha20_context *ctx ); + +/** + * \brief This function releases and clears the specified + * ChaCha20 context. + * + * \param ctx The ChaCha20 context to clear. This may be \c NULL, + * in which case this function is a no-op. If it is not + * \c NULL, it must point to an initialized context. + * + */ +void mbedtls_chacha20_free( mbedtls_chacha20_context *ctx ); + +/** + * \brief This function sets the encryption/decryption key. + * + * \note After using this function, you must also call + * \c mbedtls_chacha20_starts() to set a nonce before you + * start encrypting/decrypting data with + * \c mbedtls_chacha_update(). + * + * \param ctx The ChaCha20 context to which the key should be bound. + * It must be initialized. + * \param key The encryption/decryption key. This must be \c 32 Bytes + * in length. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CHACHA20_BAD_INPUT_DATA if ctx or key is NULL. + */ +int mbedtls_chacha20_setkey( mbedtls_chacha20_context *ctx, + const unsigned char key[32] ); + +/** + * \brief This function sets the nonce and initial counter value. + * + * \note A ChaCha20 context can be re-used with the same key by + * calling this function to change the nonce. + * + * \warning You must never use the same nonce twice with the same key. + * This would void any confidentiality guarantees for the + * messages encrypted with the same nonce and key. + * + * \param ctx The ChaCha20 context to which the nonce should be bound. + * It must be initialized and bound to a key. + * \param nonce The nonce. This must be \c 12 Bytes in size. + * \param counter The initial counter value. This is usually \c 0. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CHACHA20_BAD_INPUT_DATA if ctx or nonce is + * NULL. + */ +int mbedtls_chacha20_starts( mbedtls_chacha20_context* ctx, + const unsigned char nonce[12], + uint32_t counter ); + +/** + * \brief This function encrypts or decrypts data. + * + * Since ChaCha20 is a stream cipher, the same operation is + * used for encrypting and decrypting data. + * + * \note The \p input and \p output pointers must either be equal or + * point to non-overlapping buffers. + * + * \note \c mbedtls_chacha20_setkey() and + * \c mbedtls_chacha20_starts() must be called at least once + * to setup the context before this function can be called. + * + * \note This function can be called multiple times in a row in + * order to encrypt of decrypt data piecewise with the same + * key and nonce. + * + * \param ctx The ChaCha20 context to use for encryption or decryption. + * It must be initialized and bound to a key and nonce. + * \param size The length of the input data in Bytes. + * \param input The buffer holding the input data. + * This pointer can be \c NULL if `size == 0`. + * \param output The buffer holding the output data. + * This must be able to hold \p size Bytes. + * This pointer can be \c NULL if `size == 0`. + * + * \return \c 0 on success. + * \return A negative error code on failure. + */ +int mbedtls_chacha20_update( mbedtls_chacha20_context *ctx, + size_t size, + const unsigned char *input, + unsigned char *output ); + +/** + * \brief This function encrypts or decrypts data with ChaCha20 and + * the given key and nonce. + * + * Since ChaCha20 is a stream cipher, the same operation is + * used for encrypting and decrypting data. + * + * \warning You must never use the same (key, nonce) pair more than + * once. This would void any confidentiality guarantees for + * the messages encrypted with the same nonce and key. + * + * \note The \p input and \p output pointers must either be equal or + * point to non-overlapping buffers. + * + * \param key The encryption/decryption key. + * This must be \c 32 Bytes in length. + * \param nonce The nonce. This must be \c 12 Bytes in size. + * \param counter The initial counter value. This is usually \c 0. + * \param size The length of the input data in Bytes. + * \param input The buffer holding the input data. + * This pointer can be \c NULL if `size == 0`. + * \param output The buffer holding the output data. + * This must be able to hold \p size Bytes. + * This pointer can be \c NULL if `size == 0`. + * + * \return \c 0 on success. + * \return A negative error code on failure. + */ +int mbedtls_chacha20_crypt( const unsigned char key[32], + const unsigned char nonce[12], + uint32_t counter, + size_t size, + const unsigned char* input, + unsigned char* output ); + +#if defined(MBEDTLS_SELF_TEST) +/** + * \brief The ChaCha20 checkup routine. + * + * \return \c 0 on success. + * \return \c 1 on failure. + */ +int mbedtls_chacha20_self_test( int verbose ); +#endif /* MBEDTLS_SELF_TEST */ + +#ifdef __cplusplus +} +#endif + +#endif /* MBEDTLS_CHACHA20_H */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/chachapoly.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/chachapoly.h new file mode 100644 index 0000000000000000000000000000000000000000..49e615d278fad937d2843039a69a4584ead4e1a6 --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/chachapoly.h @@ -0,0 +1,358 @@ +/** + * \file chachapoly.h + * + * \brief This file contains the AEAD-ChaCha20-Poly1305 definitions and + * functions. + * + * ChaCha20-Poly1305 is an algorithm for Authenticated Encryption + * with Associated Data (AEAD) that can be used to encrypt and + * authenticate data. It is based on ChaCha20 and Poly1305 by Daniel + * Bernstein and was standardized in RFC 7539. + * + * \author Daniel King + */ + +/* Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of Mbed TLS (https://tls.mbed.org) + */ + +#ifndef MBEDTLS_CHACHAPOLY_H +#define MBEDTLS_CHACHAPOLY_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +/* for shared error codes */ +#include "poly1305.h" + +#define MBEDTLS_ERR_CHACHAPOLY_BAD_STATE -0x0054 /**< The requested operation is not permitted in the current state. */ +#define MBEDTLS_ERR_CHACHAPOLY_AUTH_FAILED -0x0056 /**< Authenticated decryption failed: data was not authentic. */ + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum +{ + MBEDTLS_CHACHAPOLY_ENCRYPT, /**< The mode value for performing encryption. */ + MBEDTLS_CHACHAPOLY_DECRYPT /**< The mode value for performing decryption. */ +} +mbedtls_chachapoly_mode_t; + +#if !defined(MBEDTLS_CHACHAPOLY_ALT) + +#include "chacha20.h" + +typedef struct mbedtls_chachapoly_context +{ + mbedtls_chacha20_context chacha20_ctx; /**< The ChaCha20 context. */ + mbedtls_poly1305_context poly1305_ctx; /**< The Poly1305 context. */ + uint64_t aad_len; /**< The length (bytes) of the Additional Authenticated Data. */ + uint64_t ciphertext_len; /**< The length (bytes) of the ciphertext. */ + int state; /**< The current state of the context. */ + mbedtls_chachapoly_mode_t mode; /**< Cipher mode (encrypt or decrypt). */ +} +mbedtls_chachapoly_context; + +#else /* !MBEDTLS_CHACHAPOLY_ALT */ +#include "chachapoly_alt.h" +#endif /* !MBEDTLS_CHACHAPOLY_ALT */ + +/** + * \brief This function initializes the specified ChaCha20-Poly1305 context. + * + * It must be the first API called before using + * the context. It must be followed by a call to + * \c mbedtls_chachapoly_setkey() before any operation can be + * done, and to \c mbedtls_chachapoly_free() once all + * operations with that context have been finished. + * + * In order to encrypt or decrypt full messages at once, for + * each message you should make a single call to + * \c mbedtls_chachapoly_crypt_and_tag() or + * \c mbedtls_chachapoly_auth_decrypt(). + * + * In order to encrypt messages piecewise, for each + * message you should make a call to + * \c mbedtls_chachapoly_starts(), then 0 or more calls to + * \c mbedtls_chachapoly_update_aad(), then 0 or more calls to + * \c mbedtls_chachapoly_update(), then one call to + * \c mbedtls_chachapoly_finish(). + * + * \warning Decryption with the piecewise API is discouraged! Always + * use \c mbedtls_chachapoly_auth_decrypt() when possible! + * + * If however this is not possible because the data is too + * large to fit in memory, you need to: + * + * - call \c mbedtls_chachapoly_starts() and (if needed) + * \c mbedtls_chachapoly_update_aad() as above, + * - call \c mbedtls_chachapoly_update() multiple times and + * ensure its output (the plaintext) is NOT used in any other + * way than placing it in temporary storage at this point, + * - call \c mbedtls_chachapoly_finish() to compute the + * authentication tag and compared it in constant time to the + * tag received with the ciphertext. + * + * If the tags are not equal, you must immediately discard + * all previous outputs of \c mbedtls_chachapoly_update(), + * otherwise you can now safely use the plaintext. + * + * \param ctx The ChachaPoly context to initialize. Must not be \c NULL. + */ +void mbedtls_chachapoly_init( mbedtls_chachapoly_context *ctx ); + +/** + * \brief This function releases and clears the specified + * ChaCha20-Poly1305 context. + * + * \param ctx The ChachaPoly context to clear. This may be \c NULL, in which + * case this function is a no-op. + */ +void mbedtls_chachapoly_free( mbedtls_chachapoly_context *ctx ); + +/** + * \brief This function sets the ChaCha20-Poly1305 + * symmetric encryption key. + * + * \param ctx The ChaCha20-Poly1305 context to which the key should be + * bound. This must be initialized. + * \param key The \c 256 Bit (\c 32 Bytes) key. + * + * \return \c 0 on success. + * \return A negative error code on failure. + */ +int mbedtls_chachapoly_setkey( mbedtls_chachapoly_context *ctx, + const unsigned char key[32] ); + +/** + * \brief This function starts a ChaCha20-Poly1305 encryption or + * decryption operation. + * + * \warning You must never use the same nonce twice with the same key. + * This would void any confidentiality and authenticity + * guarantees for the messages encrypted with the same nonce + * and key. + * + * \note If the context is being used for AAD only (no data to + * encrypt or decrypt) then \p mode can be set to any value. + * + * \warning Decryption with the piecewise API is discouraged, see the + * warning on \c mbedtls_chachapoly_init(). + * + * \param ctx The ChaCha20-Poly1305 context. This must be initialized + * and bound to a key. + * \param nonce The nonce/IV to use for the message. + * This must be a redable buffer of length \c 12 Bytes. + * \param mode The operation to perform: #MBEDTLS_CHACHAPOLY_ENCRYPT or + * #MBEDTLS_CHACHAPOLY_DECRYPT (discouraged, see warning). + * + * \return \c 0 on success. + * \return A negative error code on failure. + */ +int mbedtls_chachapoly_starts( mbedtls_chachapoly_context *ctx, + const unsigned char nonce[12], + mbedtls_chachapoly_mode_t mode ); + +/** + * \brief This function feeds additional data to be authenticated + * into an ongoing ChaCha20-Poly1305 operation. + * + * The Additional Authenticated Data (AAD), also called + * Associated Data (AD) is only authenticated but not + * encrypted nor included in the encrypted output. It is + * usually transmitted separately from the ciphertext or + * computed locally by each party. + * + * \note This function is called before data is encrypted/decrypted. + * I.e. call this function to process the AAD before calling + * \c mbedtls_chachapoly_update(). + * + * You may call this function multiple times to process + * an arbitrary amount of AAD. It is permitted to call + * this function 0 times, if no AAD is used. + * + * This function cannot be called any more if data has + * been processed by \c mbedtls_chachapoly_update(), + * or if the context has been finished. + * + * \warning Decryption with the piecewise API is discouraged, see the + * warning on \c mbedtls_chachapoly_init(). + * + * \param ctx The ChaCha20-Poly1305 context. This must be initialized + * and bound to a key. + * \param aad_len The length in Bytes of the AAD. The length has no + * restrictions. + * \param aad Buffer containing the AAD. + * This pointer can be \c NULL if `aad_len == 0`. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA + * if \p ctx or \p aad are NULL. + * \return #MBEDTLS_ERR_CHACHAPOLY_BAD_STATE + * if the operations has not been started or has been + * finished, or if the AAD has been finished. + */ +int mbedtls_chachapoly_update_aad( mbedtls_chachapoly_context *ctx, + const unsigned char *aad, + size_t aad_len ); + +/** + * \brief Thus function feeds data to be encrypted or decrypted + * into an on-going ChaCha20-Poly1305 + * operation. + * + * The direction (encryption or decryption) depends on the + * mode that was given when calling + * \c mbedtls_chachapoly_starts(). + * + * You may call this function multiple times to process + * an arbitrary amount of data. It is permitted to call + * this function 0 times, if no data is to be encrypted + * or decrypted. + * + * \warning Decryption with the piecewise API is discouraged, see the + * warning on \c mbedtls_chachapoly_init(). + * + * \param ctx The ChaCha20-Poly1305 context to use. This must be initialized. + * \param len The length (in bytes) of the data to encrypt or decrypt. + * \param input The buffer containing the data to encrypt or decrypt. + * This pointer can be \c NULL if `len == 0`. + * \param output The buffer to where the encrypted or decrypted data is + * written. This must be able to hold \p len bytes. + * This pointer can be \c NULL if `len == 0`. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CHACHAPOLY_BAD_STATE + * if the operation has not been started or has been + * finished. + * \return Another negative error code on other kinds of failure. + */ +int mbedtls_chachapoly_update( mbedtls_chachapoly_context *ctx, + size_t len, + const unsigned char *input, + unsigned char *output ); + +/** + * \brief This function finished the ChaCha20-Poly1305 operation and + * generates the MAC (authentication tag). + * + * \param ctx The ChaCha20-Poly1305 context to use. This must be initialized. + * \param mac The buffer to where the 128-bit (16 bytes) MAC is written. + * + * \warning Decryption with the piecewise API is discouraged, see the + * warning on \c mbedtls_chachapoly_init(). + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CHACHAPOLY_BAD_STATE + * if the operation has not been started or has been + * finished. + * \return Another negative error code on other kinds of failure. + */ +int mbedtls_chachapoly_finish( mbedtls_chachapoly_context *ctx, + unsigned char mac[16] ); + +/** + * \brief This function performs a complete ChaCha20-Poly1305 + * authenticated encryption with the previously-set key. + * + * \note Before using this function, you must set the key with + * \c mbedtls_chachapoly_setkey(). + * + * \warning You must never use the same nonce twice with the same key. + * This would void any confidentiality and authenticity + * guarantees for the messages encrypted with the same nonce + * and key. + * + * \param ctx The ChaCha20-Poly1305 context to use (holds the key). + * This must be initialized. + * \param length The length (in bytes) of the data to encrypt or decrypt. + * \param nonce The 96-bit (12 bytes) nonce/IV to use. + * \param aad The buffer containing the additional authenticated + * data (AAD). This pointer can be \c NULL if `aad_len == 0`. + * \param aad_len The length (in bytes) of the AAD data to process. + * \param input The buffer containing the data to encrypt or decrypt. + * This pointer can be \c NULL if `ilen == 0`. + * \param output The buffer to where the encrypted or decrypted data + * is written. This pointer can be \c NULL if `ilen == 0`. + * \param tag The buffer to where the computed 128-bit (16 bytes) MAC + * is written. This must not be \c NULL. + * + * \return \c 0 on success. + * \return A negative error code on failure. + */ +int mbedtls_chachapoly_encrypt_and_tag( mbedtls_chachapoly_context *ctx, + size_t length, + const unsigned char nonce[12], + const unsigned char *aad, + size_t aad_len, + const unsigned char *input, + unsigned char *output, + unsigned char tag[16] ); + +/** + * \brief This function performs a complete ChaCha20-Poly1305 + * authenticated decryption with the previously-set key. + * + * \note Before using this function, you must set the key with + * \c mbedtls_chachapoly_setkey(). + * + * \param ctx The ChaCha20-Poly1305 context to use (holds the key). + * \param length The length (in Bytes) of the data to decrypt. + * \param nonce The \c 96 Bit (\c 12 bytes) nonce/IV to use. + * \param aad The buffer containing the additional authenticated data (AAD). + * This pointer can be \c NULL if `aad_len == 0`. + * \param aad_len The length (in bytes) of the AAD data to process. + * \param tag The buffer holding the authentication tag. + * This must be a readable buffer of length \c 16 Bytes. + * \param input The buffer containing the data to decrypt. + * This pointer can be \c NULL if `ilen == 0`. + * \param output The buffer to where the decrypted data is written. + * This pointer can be \c NULL if `ilen == 0`. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CHACHAPOLY_AUTH_FAILED + * if the data was not authentic. + * \return Another negative error code on other kinds of failure. + */ +int mbedtls_chachapoly_auth_decrypt( mbedtls_chachapoly_context *ctx, + size_t length, + const unsigned char nonce[12], + const unsigned char *aad, + size_t aad_len, + const unsigned char tag[16], + const unsigned char *input, + unsigned char *output ); + +#if defined(MBEDTLS_SELF_TEST) +/** + * \brief The ChaCha20-Poly1305 checkup routine. + * + * \return \c 0 on success. + * \return \c 1 on failure. + */ +int mbedtls_chachapoly_self_test( int verbose ); +#endif /* MBEDTLS_SELF_TEST */ + +#ifdef __cplusplus +} +#endif + +#endif /* MBEDTLS_CHACHAPOLY_H */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/check_config.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/check_config.h new file mode 100644 index 0000000000000000000000000000000000000000..93de091c4db572a11c72cf46cd2de762f8a532db --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/check_config.h @@ -0,0 +1,729 @@ +/** + * \file check_config.h + * + * \brief Consistency checks for configuration options + */ +/* + * Copyright (C) 2006-2018, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ + +/* + * It is recommended to include this file from your config.h + * in order to catch dependency issues early. + */ + +#ifndef MBEDTLS_CHECK_CONFIG_H +#define MBEDTLS_CHECK_CONFIG_H + +/* + * We assume CHAR_BIT is 8 in many places. In practice, this is true on our + * target platforms, so not an issue, but let's just be extra sure. + */ +#include +#if CHAR_BIT != 8 +#error "mbed TLS requires a platform with 8-bit chars" +#endif + +#if defined(_WIN32) +#if !defined(MBEDTLS_PLATFORM_C) +#error "MBEDTLS_PLATFORM_C is required on Windows" +#endif + +/* Fix the config here. Not convenient to put an #ifdef _WIN32 in config.h as + * it would confuse config.pl. */ +#if !defined(MBEDTLS_PLATFORM_SNPRINTF_ALT) && \ + !defined(MBEDTLS_PLATFORM_SNPRINTF_MACRO) +#define MBEDTLS_PLATFORM_SNPRINTF_ALT +#endif +#endif /* _WIN32 */ + +#if defined(TARGET_LIKE_MBED) && \ + ( defined(MBEDTLS_NET_C) || defined(MBEDTLS_TIMING_C) ) +#error "The NET and TIMING modules are not available for mbed OS - please use the network and timing functions provided by mbed OS" +#endif + +#if defined(MBEDTLS_DEPRECATED_WARNING) && \ + !defined(__GNUC__) && !defined(__clang__) +#error "MBEDTLS_DEPRECATED_WARNING only works with GCC and Clang" +#endif + +#if defined(MBEDTLS_HAVE_TIME_DATE) && !defined(MBEDTLS_HAVE_TIME) +#error "MBEDTLS_HAVE_TIME_DATE without MBEDTLS_HAVE_TIME does not make sense" +#endif + +#if defined(MBEDTLS_AESNI_C) && !defined(MBEDTLS_HAVE_ASM) +#error "MBEDTLS_AESNI_C defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_CTR_DRBG_C) && !defined(MBEDTLS_AES_C) +#error "MBEDTLS_CTR_DRBG_C defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_DHM_C) && !defined(MBEDTLS_BIGNUM_C) +#error "MBEDTLS_DHM_C defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_SSL_TRUNCATED_HMAC_COMPAT) && !defined(MBEDTLS_SSL_TRUNCATED_HMAC) +#error "MBEDTLS_SSL_TRUNCATED_HMAC_COMPAT defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_CMAC_C) && \ + !defined(MBEDTLS_AES_C) && !defined(MBEDTLS_DES_C) +#error "MBEDTLS_CMAC_C defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_NIST_KW_C) && \ + ( !defined(MBEDTLS_AES_C) || !defined(MBEDTLS_CIPHER_C) ) +#error "MBEDTLS_NIST_KW_C defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_ECDH_C) && !defined(MBEDTLS_ECP_C) +#error "MBEDTLS_ECDH_C defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_ECDSA_C) && \ + ( !defined(MBEDTLS_ECP_C) || \ + !defined(MBEDTLS_ASN1_PARSE_C) || \ + !defined(MBEDTLS_ASN1_WRITE_C) ) +#error "MBEDTLS_ECDSA_C defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_ECJPAKE_C) && \ + ( !defined(MBEDTLS_ECP_C) || !defined(MBEDTLS_MD_C) ) +#error "MBEDTLS_ECJPAKE_C defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_ECP_RESTARTABLE) && \ + ( defined(MBEDTLS_ECDH_COMPUTE_SHARED_ALT) || \ + defined(MBEDTLS_ECDH_GEN_PUBLIC_ALT) || \ + defined(MBEDTLS_ECDSA_SIGN_ALT) || \ + defined(MBEDTLS_ECDSA_VERIFY_ALT) || \ + defined(MBEDTLS_ECDSA_GENKEY_ALT) || \ + defined(MBEDTLS_ECP_INTERNAL_ALT) || \ + defined(MBEDTLS_ECP_ALT) ) +#error "MBEDTLS_ECP_RESTARTABLE defined, but it cannot coexist with an alternative ECP implementation" +#endif + +#if defined(MBEDTLS_ECDSA_DETERMINISTIC) && !defined(MBEDTLS_HMAC_DRBG_C) +#error "MBEDTLS_ECDSA_DETERMINISTIC defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_ECP_C) && ( !defined(MBEDTLS_BIGNUM_C) || ( \ + !defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED) && \ + !defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED) && \ + !defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED) && \ + !defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED) && \ + !defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED) && \ + !defined(MBEDTLS_ECP_DP_BP256R1_ENABLED) && \ + !defined(MBEDTLS_ECP_DP_BP384R1_ENABLED) && \ + !defined(MBEDTLS_ECP_DP_BP512R1_ENABLED) && \ + !defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED) && \ + !defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED) && \ + !defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED) && \ + !defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED) && \ + !defined(MBEDTLS_ECP_DP_CURVE448_ENABLED) ) ) +#error "MBEDTLS_ECP_C defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_PK_PARSE_C) && !defined(MBEDTLS_ASN1_PARSE_C) +#error "MBEDTLS_PK_PARSE_C defined, but not all prerequesites" +#endif + +#if defined(MBEDTLS_ENTROPY_C) && (!defined(MBEDTLS_SHA512_C) && \ + !defined(MBEDTLS_SHA256_C)) +#error "MBEDTLS_ENTROPY_C defined, but not all prerequisites" +#endif +#if defined(MBEDTLS_ENTROPY_C) && defined(MBEDTLS_SHA512_C) && \ + defined(MBEDTLS_CTR_DRBG_ENTROPY_LEN) && (MBEDTLS_CTR_DRBG_ENTROPY_LEN > 64) +#error "MBEDTLS_CTR_DRBG_ENTROPY_LEN value too high" +#endif +#if defined(MBEDTLS_ENTROPY_C) && \ + ( !defined(MBEDTLS_SHA512_C) || defined(MBEDTLS_ENTROPY_FORCE_SHA256) ) \ + && defined(MBEDTLS_CTR_DRBG_ENTROPY_LEN) && (MBEDTLS_CTR_DRBG_ENTROPY_LEN > 32) +#error "MBEDTLS_CTR_DRBG_ENTROPY_LEN value too high" +#endif +#if defined(MBEDTLS_ENTROPY_C) && \ + defined(MBEDTLS_ENTROPY_FORCE_SHA256) && !defined(MBEDTLS_SHA256_C) +#error "MBEDTLS_ENTROPY_FORCE_SHA256 defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_TEST_NULL_ENTROPY) && \ + ( !defined(MBEDTLS_ENTROPY_C) || !defined(MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES) ) +#error "MBEDTLS_TEST_NULL_ENTROPY defined, but not all prerequisites" +#endif +#if defined(MBEDTLS_TEST_NULL_ENTROPY) && \ + ( defined(MBEDTLS_ENTROPY_NV_SEED) || defined(MBEDTLS_ENTROPY_HARDWARE_ALT) || \ + defined(MBEDTLS_HAVEGE_C) ) +#error "MBEDTLS_TEST_NULL_ENTROPY defined, but entropy sources too" +#endif + +#if defined(MBEDTLS_GCM_C) && ( \ + !defined(MBEDTLS_AES_C) && !defined(MBEDTLS_CAMELLIA_C) ) +#error "MBEDTLS_GCM_C defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_ECP_RANDOMIZE_JAC_ALT) && !defined(MBEDTLS_ECP_INTERNAL_ALT) +#error "MBEDTLS_ECP_RANDOMIZE_JAC_ALT defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_ECP_ADD_MIXED_ALT) && !defined(MBEDTLS_ECP_INTERNAL_ALT) +#error "MBEDTLS_ECP_ADD_MIXED_ALT defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_ECP_DOUBLE_JAC_ALT) && !defined(MBEDTLS_ECP_INTERNAL_ALT) +#error "MBEDTLS_ECP_DOUBLE_JAC_ALT defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_ECP_NORMALIZE_JAC_MANY_ALT) && !defined(MBEDTLS_ECP_INTERNAL_ALT) +#error "MBEDTLS_ECP_NORMALIZE_JAC_MANY_ALT defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_ECP_NORMALIZE_JAC_ALT) && !defined(MBEDTLS_ECP_INTERNAL_ALT) +#error "MBEDTLS_ECP_NORMALIZE_JAC_ALT defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT) && !defined(MBEDTLS_ECP_INTERNAL_ALT) +#error "MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_ECP_RANDOMIZE_MXZ_ALT) && !defined(MBEDTLS_ECP_INTERNAL_ALT) +#error "MBEDTLS_ECP_RANDOMIZE_MXZ_ALT defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_ECP_NORMALIZE_MXZ_ALT) && !defined(MBEDTLS_ECP_INTERNAL_ALT) +#error "MBEDTLS_ECP_NORMALIZE_MXZ_ALT defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_HAVEGE_C) && !defined(MBEDTLS_TIMING_C) +#error "MBEDTLS_HAVEGE_C defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_HKDF_C) && !defined(MBEDTLS_MD_C) +#error "MBEDTLS_HKDF_C defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_HMAC_DRBG_C) && !defined(MBEDTLS_MD_C) +#error "MBEDTLS_HMAC_DRBG_C defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED) && \ + ( !defined(MBEDTLS_ECDH_C) || !defined(MBEDTLS_X509_CRT_PARSE_C) ) +#error "MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) && \ + ( !defined(MBEDTLS_ECDH_C) || !defined(MBEDTLS_X509_CRT_PARSE_C) ) +#error "MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED) && !defined(MBEDTLS_DHM_C) +#error "MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) && \ + !defined(MBEDTLS_ECDH_C) +#error "MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) && \ + ( !defined(MBEDTLS_DHM_C) || !defined(MBEDTLS_RSA_C) || \ + !defined(MBEDTLS_X509_CRT_PARSE_C) || !defined(MBEDTLS_PKCS1_V15) ) +#error "MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) && \ + ( !defined(MBEDTLS_ECDH_C) || !defined(MBEDTLS_RSA_C) || \ + !defined(MBEDTLS_X509_CRT_PARSE_C) || !defined(MBEDTLS_PKCS1_V15) ) +#error "MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) && \ + ( !defined(MBEDTLS_ECDH_C) || !defined(MBEDTLS_ECDSA_C) || \ + !defined(MBEDTLS_X509_CRT_PARSE_C) ) +#error "MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) && \ + ( !defined(MBEDTLS_RSA_C) || !defined(MBEDTLS_X509_CRT_PARSE_C) || \ + !defined(MBEDTLS_PKCS1_V15) ) +#error "MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) && \ + ( !defined(MBEDTLS_RSA_C) || !defined(MBEDTLS_X509_CRT_PARSE_C) || \ + !defined(MBEDTLS_PKCS1_V15) ) +#error "MBEDTLS_KEY_EXCHANGE_RSA_ENABLED defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) && \ + ( !defined(MBEDTLS_ECJPAKE_C) || !defined(MBEDTLS_SHA256_C) || \ + !defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED) ) +#error "MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_MEMORY_BUFFER_ALLOC_C) && \ + ( !defined(MBEDTLS_PLATFORM_C) || !defined(MBEDTLS_PLATFORM_MEMORY) ) +#error "MBEDTLS_MEMORY_BUFFER_ALLOC_C defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_MEMORY_BACKTRACE) && !defined(MBEDTLS_MEMORY_BUFFER_ALLOC_C) +#error "MBEDTLS_MEMORY_BACKTRACE defined, but not all prerequesites" +#endif + +#if defined(MBEDTLS_MEMORY_DEBUG) && !defined(MBEDTLS_MEMORY_BUFFER_ALLOC_C) +#error "MBEDTLS_MEMORY_DEBUG defined, but not all prerequesites" +#endif + +#if defined(MBEDTLS_PADLOCK_C) && !defined(MBEDTLS_HAVE_ASM) +#error "MBEDTLS_PADLOCK_C defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_PEM_PARSE_C) && !defined(MBEDTLS_BASE64_C) +#error "MBEDTLS_PEM_PARSE_C defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_PEM_WRITE_C) && !defined(MBEDTLS_BASE64_C) +#error "MBEDTLS_PEM_WRITE_C defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_PK_C) && \ + ( !defined(MBEDTLS_RSA_C) && !defined(MBEDTLS_ECP_C) ) +#error "MBEDTLS_PK_C defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_PK_PARSE_C) && !defined(MBEDTLS_PK_C) +#error "MBEDTLS_PK_PARSE_C defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_PK_WRITE_C) && !defined(MBEDTLS_PK_C) +#error "MBEDTLS_PK_WRITE_C defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_PKCS11_C) && !defined(MBEDTLS_PK_C) +#error "MBEDTLS_PKCS11_C defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_PLATFORM_EXIT_ALT) && !defined(MBEDTLS_PLATFORM_C) +#error "MBEDTLS_PLATFORM_EXIT_ALT defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_PLATFORM_EXIT_MACRO) && !defined(MBEDTLS_PLATFORM_C) +#error "MBEDTLS_PLATFORM_EXIT_MACRO defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_PLATFORM_EXIT_MACRO) &&\ + ( defined(MBEDTLS_PLATFORM_STD_EXIT) ||\ + defined(MBEDTLS_PLATFORM_EXIT_ALT) ) +#error "MBEDTLS_PLATFORM_EXIT_MACRO and MBEDTLS_PLATFORM_STD_EXIT/MBEDTLS_PLATFORM_EXIT_ALT cannot be defined simultaneously" +#endif + +#if defined(MBEDTLS_PLATFORM_TIME_ALT) &&\ + ( !defined(MBEDTLS_PLATFORM_C) ||\ + !defined(MBEDTLS_HAVE_TIME) ) +#error "MBEDTLS_PLATFORM_TIME_ALT defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_PLATFORM_TIME_MACRO) &&\ + ( !defined(MBEDTLS_PLATFORM_C) ||\ + !defined(MBEDTLS_HAVE_TIME) ) +#error "MBEDTLS_PLATFORM_TIME_MACRO defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_PLATFORM_TIME_TYPE_MACRO) &&\ + ( !defined(MBEDTLS_PLATFORM_C) ||\ + !defined(MBEDTLS_HAVE_TIME) ) +#error "MBEDTLS_PLATFORM_TIME_TYPE_MACRO defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_PLATFORM_TIME_MACRO) &&\ + ( defined(MBEDTLS_PLATFORM_STD_TIME) ||\ + defined(MBEDTLS_PLATFORM_TIME_ALT) ) +#error "MBEDTLS_PLATFORM_TIME_MACRO and MBEDTLS_PLATFORM_STD_TIME/MBEDTLS_PLATFORM_TIME_ALT cannot be defined simultaneously" +#endif + +#if defined(MBEDTLS_PLATFORM_TIME_TYPE_MACRO) &&\ + ( defined(MBEDTLS_PLATFORM_STD_TIME) ||\ + defined(MBEDTLS_PLATFORM_TIME_ALT) ) +#error "MBEDTLS_PLATFORM_TIME_TYPE_MACRO and MBEDTLS_PLATFORM_STD_TIME/MBEDTLS_PLATFORM_TIME_ALT cannot be defined simultaneously" +#endif + +#if defined(MBEDTLS_PLATFORM_FPRINTF_ALT) && !defined(MBEDTLS_PLATFORM_C) +#error "MBEDTLS_PLATFORM_FPRINTF_ALT defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_PLATFORM_FPRINTF_MACRO) && !defined(MBEDTLS_PLATFORM_C) +#error "MBEDTLS_PLATFORM_FPRINTF_MACRO defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_PLATFORM_FPRINTF_MACRO) &&\ + ( defined(MBEDTLS_PLATFORM_STD_FPRINTF) ||\ + defined(MBEDTLS_PLATFORM_FPRINTF_ALT) ) +#error "MBEDTLS_PLATFORM_FPRINTF_MACRO and MBEDTLS_PLATFORM_STD_FPRINTF/MBEDTLS_PLATFORM_FPRINTF_ALT cannot be defined simultaneously" +#endif + +#if defined(MBEDTLS_PLATFORM_FREE_MACRO) &&\ + ( !defined(MBEDTLS_PLATFORM_C) || !defined(MBEDTLS_PLATFORM_MEMORY) ) +#error "MBEDTLS_PLATFORM_FREE_MACRO defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_PLATFORM_FREE_MACRO) &&\ + defined(MBEDTLS_PLATFORM_STD_FREE) +#error "MBEDTLS_PLATFORM_FREE_MACRO and MBEDTLS_PLATFORM_STD_FREE cannot be defined simultaneously" +#endif + +#if defined(MBEDTLS_PLATFORM_FREE_MACRO) && !defined(MBEDTLS_PLATFORM_CALLOC_MACRO) +#error "MBEDTLS_PLATFORM_CALLOC_MACRO must be defined if MBEDTLS_PLATFORM_FREE_MACRO is" +#endif + +#if defined(MBEDTLS_PLATFORM_CALLOC_MACRO) &&\ + ( !defined(MBEDTLS_PLATFORM_C) || !defined(MBEDTLS_PLATFORM_MEMORY) ) +#error "MBEDTLS_PLATFORM_CALLOC_MACRO defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_PLATFORM_CALLOC_MACRO) &&\ + defined(MBEDTLS_PLATFORM_STD_CALLOC) +#error "MBEDTLS_PLATFORM_CALLOC_MACRO and MBEDTLS_PLATFORM_STD_CALLOC cannot be defined simultaneously" +#endif + +#if defined(MBEDTLS_PLATFORM_CALLOC_MACRO) && !defined(MBEDTLS_PLATFORM_FREE_MACRO) +#error "MBEDTLS_PLATFORM_FREE_MACRO must be defined if MBEDTLS_PLATFORM_CALLOC_MACRO is" +#endif + +#if defined(MBEDTLS_PLATFORM_MEMORY) && !defined(MBEDTLS_PLATFORM_C) +#error "MBEDTLS_PLATFORM_MEMORY defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_PLATFORM_PRINTF_ALT) && !defined(MBEDTLS_PLATFORM_C) +#error "MBEDTLS_PLATFORM_PRINTF_ALT defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_PLATFORM_PRINTF_MACRO) && !defined(MBEDTLS_PLATFORM_C) +#error "MBEDTLS_PLATFORM_PRINTF_MACRO defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_PLATFORM_PRINTF_MACRO) &&\ + ( defined(MBEDTLS_PLATFORM_STD_PRINTF) ||\ + defined(MBEDTLS_PLATFORM_PRINTF_ALT) ) +#error "MBEDTLS_PLATFORM_PRINTF_MACRO and MBEDTLS_PLATFORM_STD_PRINTF/MBEDTLS_PLATFORM_PRINTF_ALT cannot be defined simultaneously" +#endif + +#if defined(MBEDTLS_PLATFORM_SNPRINTF_ALT) && !defined(MBEDTLS_PLATFORM_C) +#error "MBEDTLS_PLATFORM_SNPRINTF_ALT defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_PLATFORM_SNPRINTF_MACRO) && !defined(MBEDTLS_PLATFORM_C) +#error "MBEDTLS_PLATFORM_SNPRINTF_MACRO defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_PLATFORM_SNPRINTF_MACRO) &&\ + ( defined(MBEDTLS_PLATFORM_STD_SNPRINTF) ||\ + defined(MBEDTLS_PLATFORM_SNPRINTF_ALT) ) +#error "MBEDTLS_PLATFORM_SNPRINTF_MACRO and MBEDTLS_PLATFORM_STD_SNPRINTF/MBEDTLS_PLATFORM_SNPRINTF_ALT cannot be defined simultaneously" +#endif + +#if defined(MBEDTLS_PLATFORM_STD_MEM_HDR) &&\ + !defined(MBEDTLS_PLATFORM_NO_STD_FUNCTIONS) +#error "MBEDTLS_PLATFORM_STD_MEM_HDR defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_PLATFORM_STD_CALLOC) && !defined(MBEDTLS_PLATFORM_MEMORY) +#error "MBEDTLS_PLATFORM_STD_CALLOC defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_PLATFORM_STD_CALLOC) && !defined(MBEDTLS_PLATFORM_MEMORY) +#error "MBEDTLS_PLATFORM_STD_CALLOC defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_PLATFORM_STD_FREE) && !defined(MBEDTLS_PLATFORM_MEMORY) +#error "MBEDTLS_PLATFORM_STD_FREE defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_PLATFORM_STD_EXIT) &&\ + !defined(MBEDTLS_PLATFORM_EXIT_ALT) +#error "MBEDTLS_PLATFORM_STD_EXIT defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_PLATFORM_STD_TIME) &&\ + ( !defined(MBEDTLS_PLATFORM_TIME_ALT) ||\ + !defined(MBEDTLS_HAVE_TIME) ) +#error "MBEDTLS_PLATFORM_STD_TIME defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_PLATFORM_STD_FPRINTF) &&\ + !defined(MBEDTLS_PLATFORM_FPRINTF_ALT) +#error "MBEDTLS_PLATFORM_STD_FPRINTF defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_PLATFORM_STD_PRINTF) &&\ + !defined(MBEDTLS_PLATFORM_PRINTF_ALT) +#error "MBEDTLS_PLATFORM_STD_PRINTF defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_PLATFORM_STD_SNPRINTF) &&\ + !defined(MBEDTLS_PLATFORM_SNPRINTF_ALT) +#error "MBEDTLS_PLATFORM_STD_SNPRINTF defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_ENTROPY_NV_SEED) &&\ + ( !defined(MBEDTLS_PLATFORM_C) || !defined(MBEDTLS_ENTROPY_C) ) +#error "MBEDTLS_ENTROPY_NV_SEED defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_PLATFORM_NV_SEED_ALT) &&\ + !defined(MBEDTLS_ENTROPY_NV_SEED) +#error "MBEDTLS_PLATFORM_NV_SEED_ALT defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_PLATFORM_STD_NV_SEED_READ) &&\ + !defined(MBEDTLS_PLATFORM_NV_SEED_ALT) +#error "MBEDTLS_PLATFORM_STD_NV_SEED_READ defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_PLATFORM_STD_NV_SEED_WRITE) &&\ + !defined(MBEDTLS_PLATFORM_NV_SEED_ALT) +#error "MBEDTLS_PLATFORM_STD_NV_SEED_WRITE defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_PLATFORM_NV_SEED_READ_MACRO) &&\ + ( defined(MBEDTLS_PLATFORM_STD_NV_SEED_READ) ||\ + defined(MBEDTLS_PLATFORM_NV_SEED_ALT) ) +#error "MBEDTLS_PLATFORM_NV_SEED_READ_MACRO and MBEDTLS_PLATFORM_STD_NV_SEED_READ cannot be defined simultaneously" +#endif + +#if defined(MBEDTLS_PLATFORM_NV_SEED_WRITE_MACRO) &&\ + ( defined(MBEDTLS_PLATFORM_STD_NV_SEED_WRITE) ||\ + defined(MBEDTLS_PLATFORM_NV_SEED_ALT) ) +#error "MBEDTLS_PLATFORM_NV_SEED_WRITE_MACRO and MBEDTLS_PLATFORM_STD_NV_SEED_WRITE cannot be defined simultaneously" +#endif + +#if defined(MBEDTLS_RSA_C) && ( !defined(MBEDTLS_BIGNUM_C) || \ + !defined(MBEDTLS_OID_C) ) +#error "MBEDTLS_RSA_C defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_RSA_C) && ( !defined(MBEDTLS_PKCS1_V21) && \ + !defined(MBEDTLS_PKCS1_V15) ) +#error "MBEDTLS_RSA_C defined, but none of the PKCS1 versions enabled" +#endif + +#if defined(MBEDTLS_X509_RSASSA_PSS_SUPPORT) && \ + ( !defined(MBEDTLS_RSA_C) || !defined(MBEDTLS_PKCS1_V21) ) +#error "MBEDTLS_X509_RSASSA_PSS_SUPPORT defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_SSL_PROTO_SSL3) && ( !defined(MBEDTLS_MD5_C) || \ + !defined(MBEDTLS_SHA1_C) ) +#error "MBEDTLS_SSL_PROTO_SSL3 defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_SSL_PROTO_TLS1) && ( !defined(MBEDTLS_MD5_C) || \ + !defined(MBEDTLS_SHA1_C) ) +#error "MBEDTLS_SSL_PROTO_TLS1 defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_SSL_PROTO_TLS1_1) && ( !defined(MBEDTLS_MD5_C) || \ + !defined(MBEDTLS_SHA1_C) ) +#error "MBEDTLS_SSL_PROTO_TLS1_1 defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && ( !defined(MBEDTLS_SHA1_C) && \ + !defined(MBEDTLS_SHA256_C) && !defined(MBEDTLS_SHA512_C) ) +#error "MBEDTLS_SSL_PROTO_TLS1_2 defined, but not all prerequisites" +#endif + +#if (defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \ + defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2)) && \ + !(defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) || \ + defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \ + defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \ + defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) || \ + defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \ + defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED) || \ + defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) || \ + defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED) || \ + defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) || \ + defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) || \ + defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) ) +#error "One or more versions of the TLS protocol are enabled " \ + "but no key exchange methods defined with MBEDTLS_KEY_EXCHANGE_xxxx" +#endif + +#if defined(MBEDTLS_SSL_PROTO_DTLS) && \ + !defined(MBEDTLS_SSL_PROTO_TLS1_1) && \ + !defined(MBEDTLS_SSL_PROTO_TLS1_2) +#error "MBEDTLS_SSL_PROTO_DTLS defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_SSL_CLI_C) && !defined(MBEDTLS_SSL_TLS_C) +#error "MBEDTLS_SSL_CLI_C defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_SSL_TLS_C) && ( !defined(MBEDTLS_CIPHER_C) || \ + !defined(MBEDTLS_MD_C) ) +#error "MBEDTLS_SSL_TLS_C defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_SSL_SRV_C) && !defined(MBEDTLS_SSL_TLS_C) +#error "MBEDTLS_SSL_SRV_C defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_SSL_TLS_C) && (!defined(MBEDTLS_SSL_PROTO_SSL3) && \ + !defined(MBEDTLS_SSL_PROTO_TLS1) && !defined(MBEDTLS_SSL_PROTO_TLS1_1) && \ + !defined(MBEDTLS_SSL_PROTO_TLS1_2)) +#error "MBEDTLS_SSL_TLS_C defined, but no protocols are active" +#endif + +#if defined(MBEDTLS_SSL_TLS_C) && (defined(MBEDTLS_SSL_PROTO_SSL3) && \ + defined(MBEDTLS_SSL_PROTO_TLS1_1) && !defined(MBEDTLS_SSL_PROTO_TLS1)) +#error "Illegal protocol selection" +#endif + +#if defined(MBEDTLS_SSL_TLS_C) && (defined(MBEDTLS_SSL_PROTO_TLS1) && \ + defined(MBEDTLS_SSL_PROTO_TLS1_2) && !defined(MBEDTLS_SSL_PROTO_TLS1_1)) +#error "Illegal protocol selection" +#endif + +#if defined(MBEDTLS_SSL_TLS_C) && (defined(MBEDTLS_SSL_PROTO_SSL3) && \ + defined(MBEDTLS_SSL_PROTO_TLS1_2) && (!defined(MBEDTLS_SSL_PROTO_TLS1) || \ + !defined(MBEDTLS_SSL_PROTO_TLS1_1))) +#error "Illegal protocol selection" +#endif + +#if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && !defined(MBEDTLS_SSL_PROTO_DTLS) +#error "MBEDTLS_SSL_DTLS_HELLO_VERIFY defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) && \ + !defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) +#error "MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) && \ + ( !defined(MBEDTLS_SSL_TLS_C) || !defined(MBEDTLS_SSL_PROTO_DTLS) ) +#error "MBEDTLS_SSL_DTLS_ANTI_REPLAY defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT) && \ + ( !defined(MBEDTLS_SSL_TLS_C) || !defined(MBEDTLS_SSL_PROTO_DTLS) ) +#error "MBEDTLS_SSL_DTLS_BADMAC_LIMIT defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) && \ + !defined(MBEDTLS_SSL_PROTO_TLS1) && \ + !defined(MBEDTLS_SSL_PROTO_TLS1_1) && \ + !defined(MBEDTLS_SSL_PROTO_TLS1_2) +#error "MBEDTLS_SSL_ENCRYPT_THEN_MAC defined, but not all prerequsites" +#endif + +#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET) && \ + !defined(MBEDTLS_SSL_PROTO_TLS1) && \ + !defined(MBEDTLS_SSL_PROTO_TLS1_1) && \ + !defined(MBEDTLS_SSL_PROTO_TLS1_2) +#error "MBEDTLS_SSL_EXTENDED_MASTER_SECRET defined, but not all prerequsites" +#endif + +#if defined(MBEDTLS_SSL_TICKET_C) && !defined(MBEDTLS_CIPHER_C) +#error "MBEDTLS_SSL_TICKET_C defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING) && \ + !defined(MBEDTLS_SSL_PROTO_SSL3) && !defined(MBEDTLS_SSL_PROTO_TLS1) +#error "MBEDTLS_SSL_CBC_RECORD_SPLITTING defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) && \ + !defined(MBEDTLS_X509_CRT_PARSE_C) +#error "MBEDTLS_SSL_SERVER_NAME_INDICATION defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_THREADING_PTHREAD) +#if !defined(MBEDTLS_THREADING_C) || defined(MBEDTLS_THREADING_IMPL) +#error "MBEDTLS_THREADING_PTHREAD defined, but not all prerequisites" +#endif +#define MBEDTLS_THREADING_IMPL +#endif + +#if defined(MBEDTLS_THREADING_ALT) +#if !defined(MBEDTLS_THREADING_C) || defined(MBEDTLS_THREADING_IMPL) +#error "MBEDTLS_THREADING_ALT defined, but not all prerequisites" +#endif +#define MBEDTLS_THREADING_IMPL +#endif + +#if defined(MBEDTLS_THREADING_C) && !defined(MBEDTLS_THREADING_IMPL) +#error "MBEDTLS_THREADING_C defined, single threading implementation required" +#endif +#undef MBEDTLS_THREADING_IMPL + +#if defined(MBEDTLS_VERSION_FEATURES) && !defined(MBEDTLS_VERSION_C) +#error "MBEDTLS_VERSION_FEATURES defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_X509_USE_C) && ( !defined(MBEDTLS_BIGNUM_C) || \ + !defined(MBEDTLS_OID_C) || !defined(MBEDTLS_ASN1_PARSE_C) || \ + !defined(MBEDTLS_PK_PARSE_C) ) +#error "MBEDTLS_X509_USE_C defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_X509_CREATE_C) && ( !defined(MBEDTLS_BIGNUM_C) || \ + !defined(MBEDTLS_OID_C) || !defined(MBEDTLS_ASN1_WRITE_C) || \ + !defined(MBEDTLS_PK_WRITE_C) ) +#error "MBEDTLS_X509_CREATE_C defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_CERTS_C) && !defined(MBEDTLS_X509_USE_C) +#error "MBEDTLS_CERTS_C defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_X509_CRT_PARSE_C) && ( !defined(MBEDTLS_X509_USE_C) ) +#error "MBEDTLS_X509_CRT_PARSE_C defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_X509_CRL_PARSE_C) && ( !defined(MBEDTLS_X509_USE_C) ) +#error "MBEDTLS_X509_CRL_PARSE_C defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_X509_CSR_PARSE_C) && ( !defined(MBEDTLS_X509_USE_C) ) +#error "MBEDTLS_X509_CSR_PARSE_C defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_X509_CRT_WRITE_C) && ( !defined(MBEDTLS_X509_CREATE_C) ) +#error "MBEDTLS_X509_CRT_WRITE_C defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_X509_CSR_WRITE_C) && ( !defined(MBEDTLS_X509_CREATE_C) ) +#error "MBEDTLS_X509_CSR_WRITE_C defined, but not all prerequisites" +#endif + +#if defined(MBEDTLS_HAVE_INT32) && defined(MBEDTLS_HAVE_INT64) +#error "MBEDTLS_HAVE_INT32 and MBEDTLS_HAVE_INT64 cannot be defined simultaneously" +#endif /* MBEDTLS_HAVE_INT32 && MBEDTLS_HAVE_INT64 */ + +#if ( defined(MBEDTLS_HAVE_INT32) || defined(MBEDTLS_HAVE_INT64) ) && \ + defined(MBEDTLS_HAVE_ASM) +#error "MBEDTLS_HAVE_INT32/MBEDTLS_HAVE_INT64 and MBEDTLS_HAVE_ASM cannot be defined simultaneously" +#endif /* (MBEDTLS_HAVE_INT32 || MBEDTLS_HAVE_INT64) && MBEDTLS_HAVE_ASM */ + +/* + * Avoid warning from -pedantic. This is a convenient place for this + * workaround since this is included by every single file before the + * #if defined(MBEDTLS_xxx_C) that results in empty translation units. + */ +typedef int mbedtls_iso_c_forbids_empty_translation_units; + +#endif /* MBEDTLS_CHECK_CONFIG_H */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/cipher.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/cipher.h new file mode 100644 index 0000000000000000000000000000000000000000..082a69174159cce9ecdeb7623f2615134c455cce --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/cipher.h @@ -0,0 +1,872 @@ +/** + * \file cipher.h + * + * \brief This file contains an abstraction interface for use with the cipher + * primitives provided by the library. It provides a common interface to all of + * the available cipher operations. + * + * \author Adriaan de Jong + */ +/* + * Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of Mbed TLS (https://tls.mbed.org) + */ + +#ifndef MBEDTLS_CIPHER_H +#define MBEDTLS_CIPHER_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include +#include "platform_util.h" + +#if defined(MBEDTLS_GCM_C) || defined(MBEDTLS_CCM_C) || defined(MBEDTLS_CHACHAPOLY_C) +#define MBEDTLS_CIPHER_MODE_AEAD +#endif + +#if defined(MBEDTLS_CIPHER_MODE_CBC) +#define MBEDTLS_CIPHER_MODE_WITH_PADDING +#endif + +#if defined(MBEDTLS_ARC4_C) || defined(MBEDTLS_CIPHER_NULL_CIPHER) || \ + defined(MBEDTLS_CHACHA20_C) +#define MBEDTLS_CIPHER_MODE_STREAM +#endif + +#if ( defined(__ARMCC_VERSION) || defined(_MSC_VER) ) && \ + !defined(inline) && !defined(__cplusplus) +#define inline __inline +#endif + +#define MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE -0x6080 /**< The selected feature is not available. */ +#define MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA -0x6100 /**< Bad input parameters. */ +#define MBEDTLS_ERR_CIPHER_ALLOC_FAILED -0x6180 /**< Failed to allocate memory. */ +#define MBEDTLS_ERR_CIPHER_INVALID_PADDING -0x6200 /**< Input data contains invalid padding and is rejected. */ +#define MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED -0x6280 /**< Decryption of block requires a full block. */ +#define MBEDTLS_ERR_CIPHER_AUTH_FAILED -0x6300 /**< Authentication failed (for AEAD modes). */ +#define MBEDTLS_ERR_CIPHER_INVALID_CONTEXT -0x6380 /**< The context is invalid. For example, because it was freed. */ + +/* MBEDTLS_ERR_CIPHER_HW_ACCEL_FAILED is deprecated and should not be used. */ +#define MBEDTLS_ERR_CIPHER_HW_ACCEL_FAILED -0x6400 /**< Cipher hardware accelerator failed. */ + +#define MBEDTLS_CIPHER_VARIABLE_IV_LEN 0x01 /**< Cipher accepts IVs of variable length. */ +#define MBEDTLS_CIPHER_VARIABLE_KEY_LEN 0x02 /**< Cipher accepts keys of variable length. */ + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \brief Supported cipher types. + * + * \warning RC4 and DES are considered weak ciphers and their use + * constitutes a security risk. Arm recommends considering stronger + * ciphers instead. + */ +typedef enum { + MBEDTLS_CIPHER_ID_NONE = 0, /**< Placeholder to mark the end of cipher ID lists. */ + MBEDTLS_CIPHER_ID_NULL, /**< The identity cipher, treated as a stream cipher. */ + MBEDTLS_CIPHER_ID_AES, /**< The AES cipher. */ + MBEDTLS_CIPHER_ID_DES, /**< The DES cipher. */ + MBEDTLS_CIPHER_ID_3DES, /**< The Triple DES cipher. */ + MBEDTLS_CIPHER_ID_CAMELLIA, /**< The Camellia cipher. */ + MBEDTLS_CIPHER_ID_BLOWFISH, /**< The Blowfish cipher. */ + MBEDTLS_CIPHER_ID_ARC4, /**< The RC4 cipher. */ + MBEDTLS_CIPHER_ID_ARIA, /**< The Aria cipher. */ + MBEDTLS_CIPHER_ID_CHACHA20, /**< The ChaCha20 cipher. */ +} mbedtls_cipher_id_t; + +/** + * \brief Supported {cipher type, cipher mode} pairs. + * + * \warning RC4 and DES are considered weak ciphers and their use + * constitutes a security risk. Arm recommends considering stronger + * ciphers instead. + */ +typedef enum { + MBEDTLS_CIPHER_NONE = 0, /**< Placeholder to mark the end of cipher-pair lists. */ + MBEDTLS_CIPHER_NULL, /**< The identity stream cipher. */ + MBEDTLS_CIPHER_AES_128_ECB, /**< AES cipher with 128-bit ECB mode. */ + MBEDTLS_CIPHER_AES_192_ECB, /**< AES cipher with 192-bit ECB mode. */ + MBEDTLS_CIPHER_AES_256_ECB, /**< AES cipher with 256-bit ECB mode. */ + MBEDTLS_CIPHER_AES_128_CBC, /**< AES cipher with 128-bit CBC mode. */ + MBEDTLS_CIPHER_AES_192_CBC, /**< AES cipher with 192-bit CBC mode. */ + MBEDTLS_CIPHER_AES_256_CBC, /**< AES cipher with 256-bit CBC mode. */ + MBEDTLS_CIPHER_AES_128_CFB128, /**< AES cipher with 128-bit CFB128 mode. */ + MBEDTLS_CIPHER_AES_192_CFB128, /**< AES cipher with 192-bit CFB128 mode. */ + MBEDTLS_CIPHER_AES_256_CFB128, /**< AES cipher with 256-bit CFB128 mode. */ + MBEDTLS_CIPHER_AES_128_CTR, /**< AES cipher with 128-bit CTR mode. */ + MBEDTLS_CIPHER_AES_192_CTR, /**< AES cipher with 192-bit CTR mode. */ + MBEDTLS_CIPHER_AES_256_CTR, /**< AES cipher with 256-bit CTR mode. */ + MBEDTLS_CIPHER_AES_128_GCM, /**< AES cipher with 128-bit GCM mode. */ + MBEDTLS_CIPHER_AES_192_GCM, /**< AES cipher with 192-bit GCM mode. */ + MBEDTLS_CIPHER_AES_256_GCM, /**< AES cipher with 256-bit GCM mode. */ + MBEDTLS_CIPHER_CAMELLIA_128_ECB, /**< Camellia cipher with 128-bit ECB mode. */ + MBEDTLS_CIPHER_CAMELLIA_192_ECB, /**< Camellia cipher with 192-bit ECB mode. */ + MBEDTLS_CIPHER_CAMELLIA_256_ECB, /**< Camellia cipher with 256-bit ECB mode. */ + MBEDTLS_CIPHER_CAMELLIA_128_CBC, /**< Camellia cipher with 128-bit CBC mode. */ + MBEDTLS_CIPHER_CAMELLIA_192_CBC, /**< Camellia cipher with 192-bit CBC mode. */ + MBEDTLS_CIPHER_CAMELLIA_256_CBC, /**< Camellia cipher with 256-bit CBC mode. */ + MBEDTLS_CIPHER_CAMELLIA_128_CFB128, /**< Camellia cipher with 128-bit CFB128 mode. */ + MBEDTLS_CIPHER_CAMELLIA_192_CFB128, /**< Camellia cipher with 192-bit CFB128 mode. */ + MBEDTLS_CIPHER_CAMELLIA_256_CFB128, /**< Camellia cipher with 256-bit CFB128 mode. */ + MBEDTLS_CIPHER_CAMELLIA_128_CTR, /**< Camellia cipher with 128-bit CTR mode. */ + MBEDTLS_CIPHER_CAMELLIA_192_CTR, /**< Camellia cipher with 192-bit CTR mode. */ + MBEDTLS_CIPHER_CAMELLIA_256_CTR, /**< Camellia cipher with 256-bit CTR mode. */ + MBEDTLS_CIPHER_CAMELLIA_128_GCM, /**< Camellia cipher with 128-bit GCM mode. */ + MBEDTLS_CIPHER_CAMELLIA_192_GCM, /**< Camellia cipher with 192-bit GCM mode. */ + MBEDTLS_CIPHER_CAMELLIA_256_GCM, /**< Camellia cipher with 256-bit GCM mode. */ + MBEDTLS_CIPHER_DES_ECB, /**< DES cipher with ECB mode. */ + MBEDTLS_CIPHER_DES_CBC, /**< DES cipher with CBC mode. */ + MBEDTLS_CIPHER_DES_EDE_ECB, /**< DES cipher with EDE ECB mode. */ + MBEDTLS_CIPHER_DES_EDE_CBC, /**< DES cipher with EDE CBC mode. */ + MBEDTLS_CIPHER_DES_EDE3_ECB, /**< DES cipher with EDE3 ECB mode. */ + MBEDTLS_CIPHER_DES_EDE3_CBC, /**< DES cipher with EDE3 CBC mode. */ + MBEDTLS_CIPHER_BLOWFISH_ECB, /**< Blowfish cipher with ECB mode. */ + MBEDTLS_CIPHER_BLOWFISH_CBC, /**< Blowfish cipher with CBC mode. */ + MBEDTLS_CIPHER_BLOWFISH_CFB64, /**< Blowfish cipher with CFB64 mode. */ + MBEDTLS_CIPHER_BLOWFISH_CTR, /**< Blowfish cipher with CTR mode. */ + MBEDTLS_CIPHER_ARC4_128, /**< RC4 cipher with 128-bit mode. */ + MBEDTLS_CIPHER_AES_128_CCM, /**< AES cipher with 128-bit CCM mode. */ + MBEDTLS_CIPHER_AES_192_CCM, /**< AES cipher with 192-bit CCM mode. */ + MBEDTLS_CIPHER_AES_256_CCM, /**< AES cipher with 256-bit CCM mode. */ + MBEDTLS_CIPHER_CAMELLIA_128_CCM, /**< Camellia cipher with 128-bit CCM mode. */ + MBEDTLS_CIPHER_CAMELLIA_192_CCM, /**< Camellia cipher with 192-bit CCM mode. */ + MBEDTLS_CIPHER_CAMELLIA_256_CCM, /**< Camellia cipher with 256-bit CCM mode. */ + MBEDTLS_CIPHER_ARIA_128_ECB, /**< Aria cipher with 128-bit key and ECB mode. */ + MBEDTLS_CIPHER_ARIA_192_ECB, /**< Aria cipher with 192-bit key and ECB mode. */ + MBEDTLS_CIPHER_ARIA_256_ECB, /**< Aria cipher with 256-bit key and ECB mode. */ + MBEDTLS_CIPHER_ARIA_128_CBC, /**< Aria cipher with 128-bit key and CBC mode. */ + MBEDTLS_CIPHER_ARIA_192_CBC, /**< Aria cipher with 192-bit key and CBC mode. */ + MBEDTLS_CIPHER_ARIA_256_CBC, /**< Aria cipher with 256-bit key and CBC mode. */ + MBEDTLS_CIPHER_ARIA_128_CFB128, /**< Aria cipher with 128-bit key and CFB-128 mode. */ + MBEDTLS_CIPHER_ARIA_192_CFB128, /**< Aria cipher with 192-bit key and CFB-128 mode. */ + MBEDTLS_CIPHER_ARIA_256_CFB128, /**< Aria cipher with 256-bit key and CFB-128 mode. */ + MBEDTLS_CIPHER_ARIA_128_CTR, /**< Aria cipher with 128-bit key and CTR mode. */ + MBEDTLS_CIPHER_ARIA_192_CTR, /**< Aria cipher with 192-bit key and CTR mode. */ + MBEDTLS_CIPHER_ARIA_256_CTR, /**< Aria cipher with 256-bit key and CTR mode. */ + MBEDTLS_CIPHER_ARIA_128_GCM, /**< Aria cipher with 128-bit key and GCM mode. */ + MBEDTLS_CIPHER_ARIA_192_GCM, /**< Aria cipher with 192-bit key and GCM mode. */ + MBEDTLS_CIPHER_ARIA_256_GCM, /**< Aria cipher with 256-bit key and GCM mode. */ + MBEDTLS_CIPHER_ARIA_128_CCM, /**< Aria cipher with 128-bit key and CCM mode. */ + MBEDTLS_CIPHER_ARIA_192_CCM, /**< Aria cipher with 192-bit key and CCM mode. */ + MBEDTLS_CIPHER_ARIA_256_CCM, /**< Aria cipher with 256-bit key and CCM mode. */ + MBEDTLS_CIPHER_AES_128_OFB, /**< AES 128-bit cipher in OFB mode. */ + MBEDTLS_CIPHER_AES_192_OFB, /**< AES 192-bit cipher in OFB mode. */ + MBEDTLS_CIPHER_AES_256_OFB, /**< AES 256-bit cipher in OFB mode. */ + MBEDTLS_CIPHER_AES_128_XTS, /**< AES 128-bit cipher in XTS block mode. */ + MBEDTLS_CIPHER_AES_256_XTS, /**< AES 256-bit cipher in XTS block mode. */ + MBEDTLS_CIPHER_CHACHA20, /**< ChaCha20 stream cipher. */ + MBEDTLS_CIPHER_CHACHA20_POLY1305, /**< ChaCha20-Poly1305 AEAD cipher. */ +} mbedtls_cipher_type_t; + +/** Supported cipher modes. */ +typedef enum { + MBEDTLS_MODE_NONE = 0, /**< None. */ + MBEDTLS_MODE_ECB, /**< The ECB cipher mode. */ + MBEDTLS_MODE_CBC, /**< The CBC cipher mode. */ + MBEDTLS_MODE_CFB, /**< The CFB cipher mode. */ + MBEDTLS_MODE_OFB, /**< The OFB cipher mode. */ + MBEDTLS_MODE_CTR, /**< The CTR cipher mode. */ + MBEDTLS_MODE_GCM, /**< The GCM cipher mode. */ + MBEDTLS_MODE_STREAM, /**< The stream cipher mode. */ + MBEDTLS_MODE_CCM, /**< The CCM cipher mode. */ + MBEDTLS_MODE_XTS, /**< The XTS cipher mode. */ + MBEDTLS_MODE_CHACHAPOLY, /**< The ChaCha-Poly cipher mode. */ +} mbedtls_cipher_mode_t; + +/** Supported cipher padding types. */ +typedef enum { + MBEDTLS_PADDING_PKCS7 = 0, /**< PKCS7 padding (default). */ + MBEDTLS_PADDING_ONE_AND_ZEROS, /**< ISO/IEC 7816-4 padding. */ + MBEDTLS_PADDING_ZEROS_AND_LEN, /**< ANSI X.923 padding. */ + MBEDTLS_PADDING_ZEROS, /**< Zero padding (not reversible). */ + MBEDTLS_PADDING_NONE, /**< Never pad (full blocks only). */ +} mbedtls_cipher_padding_t; + +/** Type of operation. */ +typedef enum { + MBEDTLS_OPERATION_NONE = -1, + MBEDTLS_DECRYPT = 0, + MBEDTLS_ENCRYPT, +} mbedtls_operation_t; + +enum { + /** Undefined key length. */ + MBEDTLS_KEY_LENGTH_NONE = 0, + /** Key length, in bits (including parity), for DES keys. */ + MBEDTLS_KEY_LENGTH_DES = 64, + /** Key length in bits, including parity, for DES in two-key EDE. */ + MBEDTLS_KEY_LENGTH_DES_EDE = 128, + /** Key length in bits, including parity, for DES in three-key EDE. */ + MBEDTLS_KEY_LENGTH_DES_EDE3 = 192, +}; + +/** Maximum length of any IV, in Bytes. */ +#define MBEDTLS_MAX_IV_LENGTH 16 +/** Maximum block size of any cipher, in Bytes. */ +#define MBEDTLS_MAX_BLOCK_LENGTH 16 + +/** + * Base cipher information (opaque struct). + */ +typedef struct mbedtls_cipher_base_t mbedtls_cipher_base_t; + +/** + * CMAC context (opaque struct). + */ +typedef struct mbedtls_cmac_context_t mbedtls_cmac_context_t; + +/** + * Cipher information. Allows calling cipher functions + * in a generic way. + */ +typedef struct mbedtls_cipher_info_t +{ + /** Full cipher identifier. For example, + * MBEDTLS_CIPHER_AES_256_CBC. + */ + mbedtls_cipher_type_t type; + + /** The cipher mode. For example, MBEDTLS_MODE_CBC. */ + mbedtls_cipher_mode_t mode; + + /** The cipher key length, in bits. This is the + * default length for variable sized ciphers. + * Includes parity bits for ciphers like DES. + */ + unsigned int key_bitlen; + + /** Name of the cipher. */ + const char * name; + + /** IV or nonce size, in Bytes. + * For ciphers that accept variable IV sizes, + * this is the recommended size. + */ + unsigned int iv_size; + + /** Bitflag comprised of MBEDTLS_CIPHER_VARIABLE_IV_LEN and + * MBEDTLS_CIPHER_VARIABLE_KEY_LEN indicating whether the + * cipher supports variable IV or variable key sizes, respectively. + */ + int flags; + + /** The block size, in Bytes. */ + unsigned int block_size; + + /** Struct for base cipher information and functions. */ + const mbedtls_cipher_base_t *base; + +} mbedtls_cipher_info_t; + +/** + * Generic cipher context. + */ +typedef struct mbedtls_cipher_context_t +{ + /** Information about the associated cipher. */ + const mbedtls_cipher_info_t *cipher_info; + + /** Key length to use. */ + int key_bitlen; + + /** Operation that the key of the context has been + * initialized for. + */ + mbedtls_operation_t operation; + +#if defined(MBEDTLS_CIPHER_MODE_WITH_PADDING) + /** Padding functions to use, if relevant for + * the specific cipher mode. + */ + void (*add_padding)( unsigned char *output, size_t olen, size_t data_len ); + int (*get_padding)( unsigned char *input, size_t ilen, size_t *data_len ); +#endif + + /** Buffer for input that has not been processed yet. */ + unsigned char unprocessed_data[MBEDTLS_MAX_BLOCK_LENGTH]; + + /** Number of Bytes that have not been processed yet. */ + size_t unprocessed_len; + + /** Current IV or NONCE_COUNTER for CTR-mode, data unit (or sector) number + * for XTS-mode. */ + unsigned char iv[MBEDTLS_MAX_IV_LENGTH]; + + /** IV size in Bytes, for ciphers with variable-length IVs. */ + size_t iv_size; + + /** The cipher-specific context. */ + void *cipher_ctx; + +#if defined(MBEDTLS_CMAC_C) + /** CMAC-specific context. */ + mbedtls_cmac_context_t *cmac_ctx; +#endif +} mbedtls_cipher_context_t; + +/** + * \brief This function retrieves the list of ciphers supported by the generic + * cipher module. + * + * \return A statically-allocated array of ciphers. The last entry + * is zero. + */ +const int *mbedtls_cipher_list( void ); + +/** + * \brief This function retrieves the cipher-information + * structure associated with the given cipher name. + * + * \param cipher_name Name of the cipher to search for. This must not be + * \c NULL. + * + * \return The cipher information structure associated with the + * given \p cipher_name. + * \return \c NULL if the associated cipher information is not found. + */ +const mbedtls_cipher_info_t *mbedtls_cipher_info_from_string( const char *cipher_name ); + +/** + * \brief This function retrieves the cipher-information + * structure associated with the given cipher type. + * + * \param cipher_type Type of the cipher to search for. + * + * \return The cipher information structure associated with the + * given \p cipher_type. + * \return \c NULL if the associated cipher information is not found. + */ +const mbedtls_cipher_info_t *mbedtls_cipher_info_from_type( const mbedtls_cipher_type_t cipher_type ); + +/** + * \brief This function retrieves the cipher-information + * structure associated with the given cipher ID, + * key size and mode. + * + * \param cipher_id The ID of the cipher to search for. For example, + * #MBEDTLS_CIPHER_ID_AES. + * \param key_bitlen The length of the key in bits. + * \param mode The cipher mode. For example, #MBEDTLS_MODE_CBC. + * + * \return The cipher information structure associated with the + * given \p cipher_id. + * \return \c NULL if the associated cipher information is not found. + */ +const mbedtls_cipher_info_t *mbedtls_cipher_info_from_values( const mbedtls_cipher_id_t cipher_id, + int key_bitlen, + const mbedtls_cipher_mode_t mode ); + +/** + * \brief This function initializes a \p cipher_context as NONE. + * + * \param ctx The context to be initialized. This must not be \c NULL. + */ +void mbedtls_cipher_init( mbedtls_cipher_context_t *ctx ); + +/** + * \brief This function frees and clears the cipher-specific + * context of \p ctx. Freeing \p ctx itself remains the + * responsibility of the caller. + * + * \param ctx The context to be freed. If this is \c NULL, the + * function has no effect, otherwise this must point to an + * initialized context. + */ +void mbedtls_cipher_free( mbedtls_cipher_context_t *ctx ); + + +/** + * \brief This function initializes and fills the cipher-context + * structure with the appropriate values. It also clears + * the structure. + * + * \param ctx The context to initialize. This must be initialized. + * \param cipher_info The cipher to use. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on + * parameter-verification failure. + * \return #MBEDTLS_ERR_CIPHER_ALLOC_FAILED if allocation of the + * cipher-specific context fails. + * + * \internal Currently, the function also clears the structure. + * In future versions, the caller will be required to call + * mbedtls_cipher_init() on the structure first. + */ +int mbedtls_cipher_setup( mbedtls_cipher_context_t *ctx, + const mbedtls_cipher_info_t *cipher_info ); + +/** + * \brief This function returns the block size of the given cipher. + * + * \param ctx The context of the cipher. This must be initialized. + * + * \return The block size of the underlying cipher. + * \return \c 0 if \p ctx has not been initialized. + */ +static inline unsigned int mbedtls_cipher_get_block_size( + const mbedtls_cipher_context_t *ctx ) +{ + MBEDTLS_INTERNAL_VALIDATE_RET( ctx != NULL, 0 ); + if( ctx->cipher_info == NULL ) + return 0; + + return ctx->cipher_info->block_size; +} + +/** + * \brief This function returns the mode of operation for + * the cipher. For example, MBEDTLS_MODE_CBC. + * + * \param ctx The context of the cipher. This must be initialized. + * + * \return The mode of operation. + * \return #MBEDTLS_MODE_NONE if \p ctx has not been initialized. + */ +static inline mbedtls_cipher_mode_t mbedtls_cipher_get_cipher_mode( + const mbedtls_cipher_context_t *ctx ) +{ + MBEDTLS_INTERNAL_VALIDATE_RET( ctx != NULL, MBEDTLS_MODE_NONE ); + if( ctx->cipher_info == NULL ) + return MBEDTLS_MODE_NONE; + + return ctx->cipher_info->mode; +} + +/** + * \brief This function returns the size of the IV or nonce + * of the cipher, in Bytes. + * + * \param ctx The context of the cipher. This must be initialized. + * + * \return The recommended IV size if no IV has been set. + * \return \c 0 for ciphers not using an IV or a nonce. + * \return The actual size if an IV has been set. + */ +static inline int mbedtls_cipher_get_iv_size( + const mbedtls_cipher_context_t *ctx ) +{ + MBEDTLS_INTERNAL_VALIDATE_RET( ctx != NULL, 0 ); + if( ctx->cipher_info == NULL ) + return 0; + + if( ctx->iv_size != 0 ) + return (int) ctx->iv_size; + + return (int) ctx->cipher_info->iv_size; +} + +/** + * \brief This function returns the type of the given cipher. + * + * \param ctx The context of the cipher. This must be initialized. + * + * \return The type of the cipher. + * \return #MBEDTLS_CIPHER_NONE if \p ctx has not been initialized. + */ +static inline mbedtls_cipher_type_t mbedtls_cipher_get_type( + const mbedtls_cipher_context_t *ctx ) +{ + MBEDTLS_INTERNAL_VALIDATE_RET( + ctx != NULL, MBEDTLS_CIPHER_NONE ); + if( ctx->cipher_info == NULL ) + return MBEDTLS_CIPHER_NONE; + + return ctx->cipher_info->type; +} + +/** + * \brief This function returns the name of the given cipher + * as a string. + * + * \param ctx The context of the cipher. This must be initialized. + * + * \return The name of the cipher. + * \return NULL if \p ctx has not been not initialized. + */ +static inline const char *mbedtls_cipher_get_name( + const mbedtls_cipher_context_t *ctx ) +{ + MBEDTLS_INTERNAL_VALIDATE_RET( ctx != NULL, 0 ); + if( ctx->cipher_info == NULL ) + return 0; + + return ctx->cipher_info->name; +} + +/** + * \brief This function returns the key length of the cipher. + * + * \param ctx The context of the cipher. This must be initialized. + * + * \return The key length of the cipher in bits. + * \return #MBEDTLS_KEY_LENGTH_NONE if ctx \p has not been + * initialized. + */ +static inline int mbedtls_cipher_get_key_bitlen( + const mbedtls_cipher_context_t *ctx ) +{ + MBEDTLS_INTERNAL_VALIDATE_RET( + ctx != NULL, MBEDTLS_KEY_LENGTH_NONE ); + if( ctx->cipher_info == NULL ) + return MBEDTLS_KEY_LENGTH_NONE; + + return (int) ctx->cipher_info->key_bitlen; +} + +/** + * \brief This function returns the operation of the given cipher. + * + * \param ctx The context of the cipher. This must be initialized. + * + * \return The type of operation: #MBEDTLS_ENCRYPT or #MBEDTLS_DECRYPT. + * \return #MBEDTLS_OPERATION_NONE if \p ctx has not been initialized. + */ +static inline mbedtls_operation_t mbedtls_cipher_get_operation( + const mbedtls_cipher_context_t *ctx ) +{ + MBEDTLS_INTERNAL_VALIDATE_RET( + ctx != NULL, MBEDTLS_OPERATION_NONE ); + if( ctx->cipher_info == NULL ) + return MBEDTLS_OPERATION_NONE; + + return ctx->operation; +} + +/** + * \brief This function sets the key to use with the given context. + * + * \param ctx The generic cipher context. This must be initialized and + * bound to a cipher information structure. + * \param key The key to use. This must be a readable buffer of at + * least \p key_bitlen Bits. + * \param key_bitlen The key length to use, in Bits. + * \param operation The operation that the key will be used for: + * #MBEDTLS_ENCRYPT or #MBEDTLS_DECRYPT. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on + * parameter-verification failure. + * \return A cipher-specific error code on failure. + */ +int mbedtls_cipher_setkey( mbedtls_cipher_context_t *ctx, + const unsigned char *key, + int key_bitlen, + const mbedtls_operation_t operation ); + +#if defined(MBEDTLS_CIPHER_MODE_WITH_PADDING) +/** + * \brief This function sets the padding mode, for cipher modes + * that use padding. + * + * The default passing mode is PKCS7 padding. + * + * \param ctx The generic cipher context. This must be initialized and + * bound to a cipher information structure. + * \param mode The padding mode. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE + * if the selected padding mode is not supported. + * \return #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA if the cipher mode + * does not support padding. + */ +int mbedtls_cipher_set_padding_mode( mbedtls_cipher_context_t *ctx, + mbedtls_cipher_padding_t mode ); +#endif /* MBEDTLS_CIPHER_MODE_WITH_PADDING */ + +/** + * \brief This function sets the initialization vector (IV) + * or nonce. + * + * \note Some ciphers do not use IVs nor nonce. For these + * ciphers, this function has no effect. + * + * \param ctx The generic cipher context. This must be initialized and + * bound to a cipher information structure. + * \param iv The IV to use, or NONCE_COUNTER for CTR-mode ciphers. This + * must be a readable buffer of at least \p iv_len Bytes. + * \param iv_len The IV length for ciphers with variable-size IV. + * This parameter is discarded by ciphers with fixed-size IV. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on + * parameter-verification failure. + */ +int mbedtls_cipher_set_iv( mbedtls_cipher_context_t *ctx, + const unsigned char *iv, + size_t iv_len ); + +/** + * \brief This function resets the cipher state. + * + * \param ctx The generic cipher context. This must be initialized. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on + * parameter-verification failure. + */ +int mbedtls_cipher_reset( mbedtls_cipher_context_t *ctx ); + +#if defined(MBEDTLS_GCM_C) || defined(MBEDTLS_CHACHAPOLY_C) +/** + * \brief This function adds additional data for AEAD ciphers. + * Currently supported with GCM and ChaCha20+Poly1305. + * This must be called exactly once, after + * mbedtls_cipher_reset(). + * + * \param ctx The generic cipher context. This must be initialized. + * \param ad The additional data to use. This must be a readable + * buffer of at least \p ad_len Bytes. + * \param ad_len the Length of \p ad Bytes. + * + * \return \c 0 on success. + * \return A specific error code on failure. + */ +int mbedtls_cipher_update_ad( mbedtls_cipher_context_t *ctx, + const unsigned char *ad, size_t ad_len ); +#endif /* MBEDTLS_GCM_C || MBEDTLS_CHACHAPOLY_C */ + +/** + * \brief The generic cipher update function. It encrypts or + * decrypts using the given cipher context. Writes as + * many block-sized blocks of data as possible to output. + * Any data that cannot be written immediately is either + * added to the next block, or flushed when + * mbedtls_cipher_finish() is called. + * Exception: For MBEDTLS_MODE_ECB, expects a single block + * in size. For example, 16 Bytes for AES. + * + * \note If the underlying cipher is used in GCM mode, all calls + * to this function, except for the last one before + * mbedtls_cipher_finish(), must have \p ilen as a + * multiple of the block size of the cipher. + * + * \param ctx The generic cipher context. This must be initialized and + * bound to a key. + * \param input The buffer holding the input data. This must be a + * readable buffer of at least \p ilen Bytes. + * \param ilen The length of the input data. + * \param output The buffer for the output data. This must be able to + * hold at least `ilen + block_size`. This must not be the + * same buffer as \p input. + * \param olen The length of the output data, to be updated with the + * actual number of Bytes written. This must not be + * \c NULL. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on + * parameter-verification failure. + * \return #MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE on an + * unsupported mode for a cipher. + * \return A cipher-specific error code on failure. + */ +int mbedtls_cipher_update( mbedtls_cipher_context_t *ctx, const unsigned char *input, + size_t ilen, unsigned char *output, size_t *olen ); + +/** + * \brief The generic cipher finalization function. If data still + * needs to be flushed from an incomplete block, the data + * contained in it is padded to the size of + * the last block, and written to the \p output buffer. + * + * \param ctx The generic cipher context. This must be initialized and + * bound to a key. + * \param output The buffer to write data to. This needs to be a writable + * buffer of at least \p block_size Bytes. + * \param olen The length of the data written to the \p output buffer. + * This may not be \c NULL. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on + * parameter-verification failure. + * \return #MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED on decryption + * expecting a full block but not receiving one. + * \return #MBEDTLS_ERR_CIPHER_INVALID_PADDING on invalid padding + * while decrypting. + * \return A cipher-specific error code on failure. + */ +int mbedtls_cipher_finish( mbedtls_cipher_context_t *ctx, + unsigned char *output, size_t *olen ); + +#if defined(MBEDTLS_GCM_C) || defined(MBEDTLS_CHACHAPOLY_C) +/** + * \brief This function writes a tag for AEAD ciphers. + * Currently supported with GCM and ChaCha20+Poly1305. + * This must be called after mbedtls_cipher_finish(). + * + * \param ctx The generic cipher context. This must be initialized, + * bound to a key, and have just completed a cipher + * operation through mbedtls_cipher_finish() the tag for + * which should be written. + * \param tag The buffer to write the tag to. This must be a writable + * buffer of at least \p tag_len Bytes. + * \param tag_len The length of the tag to write. + * + * \return \c 0 on success. + * \return A specific error code on failure. + */ +int mbedtls_cipher_write_tag( mbedtls_cipher_context_t *ctx, + unsigned char *tag, size_t tag_len ); + +/** + * \brief This function checks the tag for AEAD ciphers. + * Currently supported with GCM and ChaCha20+Poly1305. + * This must be called after mbedtls_cipher_finish(). + * + * \param ctx The generic cipher context. This must be initialized. + * \param tag The buffer holding the tag. This must be a readable + * buffer of at least \p tag_len Bytes. + * \param tag_len The length of the tag to check. + * + * \return \c 0 on success. + * \return A specific error code on failure. + */ +int mbedtls_cipher_check_tag( mbedtls_cipher_context_t *ctx, + const unsigned char *tag, size_t tag_len ); +#endif /* MBEDTLS_GCM_C || MBEDTLS_CHACHAPOLY_C */ + +/** + * \brief The generic all-in-one encryption/decryption function, + * for all ciphers except AEAD constructs. + * + * \param ctx The generic cipher context. This must be initialized. + * \param iv The IV to use, or NONCE_COUNTER for CTR-mode ciphers. + * This must be a readable buffer of at least \p iv_len + * Bytes. + * \param iv_len The IV length for ciphers with variable-size IV. + * This parameter is discarded by ciphers with fixed-size + * IV. + * \param input The buffer holding the input data. This must be a + * readable buffer of at least \p ilen Bytes. + * \param ilen The length of the input data in Bytes. + * \param output The buffer for the output data. This must be able to + * hold at least `ilen + block_size`. This must not be the + * same buffer as \p input. + * \param olen The length of the output data, to be updated with the + * actual number of Bytes written. This must not be + * \c NULL. + * + * \note Some ciphers do not use IVs nor nonce. For these + * ciphers, use \p iv = NULL and \p iv_len = 0. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on + * parameter-verification failure. + * \return #MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED on decryption + * expecting a full block but not receiving one. + * \return #MBEDTLS_ERR_CIPHER_INVALID_PADDING on invalid padding + * while decrypting. + * \return A cipher-specific error code on failure. + */ +int mbedtls_cipher_crypt( mbedtls_cipher_context_t *ctx, + const unsigned char *iv, size_t iv_len, + const unsigned char *input, size_t ilen, + unsigned char *output, size_t *olen ); + +#if defined(MBEDTLS_CIPHER_MODE_AEAD) +/** + * \brief The generic autenticated encryption (AEAD) function. + * + * \param ctx The generic cipher context. This must be initialized and + * bound to a key. + * \param iv The IV to use, or NONCE_COUNTER for CTR-mode ciphers. + * This must be a readable buffer of at least \p iv_len + * Bytes. + * \param iv_len The IV length for ciphers with variable-size IV. + * This parameter is discarded by ciphers with fixed-size IV. + * \param ad The additional data to authenticate. This must be a + * readable buffer of at least \p ad_len Bytes. + * \param ad_len The length of \p ad. + * \param input The buffer holding the input data. This must be a + * readable buffer of at least \p ilen Bytes. + * \param ilen The length of the input data. + * \param output The buffer for the output data. This must be able to + * hold at least \p ilen Bytes. + * \param olen The length of the output data, to be updated with the + * actual number of Bytes written. This must not be + * \c NULL. + * \param tag The buffer for the authentication tag. This must be a + * writable buffer of at least \p tag_len Bytes. + * \param tag_len The desired length of the authentication tag. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on + * parameter-verification failure. + * \return A cipher-specific error code on failure. + */ +int mbedtls_cipher_auth_encrypt( mbedtls_cipher_context_t *ctx, + const unsigned char *iv, size_t iv_len, + const unsigned char *ad, size_t ad_len, + const unsigned char *input, size_t ilen, + unsigned char *output, size_t *olen, + unsigned char *tag, size_t tag_len ); + +/** + * \brief The generic autenticated decryption (AEAD) function. + * + * \note If the data is not authentic, then the output buffer + * is zeroed out to prevent the unauthentic plaintext being + * used, making this interface safer. + * + * \param ctx The generic cipher context. This must be initialized and + * and bound to a key. + * \param iv The IV to use, or NONCE_COUNTER for CTR-mode ciphers. + * This must be a readable buffer of at least \p iv_len + * Bytes. + * \param iv_len The IV length for ciphers with variable-size IV. + * This parameter is discarded by ciphers with fixed-size IV. + * \param ad The additional data to be authenticated. This must be a + * readable buffer of at least \p ad_len Bytes. + * \param ad_len The length of \p ad. + * \param input The buffer holding the input data. This must be a + * readable buffer of at least \p ilen Bytes. + * \param ilen The length of the input data. + * \param output The buffer for the output data. + * This must be able to hold at least \p ilen Bytes. + * \param olen The length of the output data, to be updated with the + * actual number of Bytes written. This must not be + * \c NULL. + * \param tag The buffer holding the authentication tag. This must be + * a readable buffer of at least \p tag_len Bytes. + * \param tag_len The length of the authentication tag. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on + * parameter-verification failure. + * \return #MBEDTLS_ERR_CIPHER_AUTH_FAILED if data is not authentic. + * \return A cipher-specific error code on failure. + */ +int mbedtls_cipher_auth_decrypt( mbedtls_cipher_context_t *ctx, + const unsigned char *iv, size_t iv_len, + const unsigned char *ad, size_t ad_len, + const unsigned char *input, size_t ilen, + unsigned char *output, size_t *olen, + const unsigned char *tag, size_t tag_len ); +#endif /* MBEDTLS_CIPHER_MODE_AEAD */ + +#ifdef __cplusplus +} +#endif + +#endif /* MBEDTLS_CIPHER_H */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/cipher_internal.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/cipher_internal.h new file mode 100644 index 0000000000000000000000000000000000000000..c6def0bef755cf810b4252732488875165839a59 --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/cipher_internal.h @@ -0,0 +1,125 @@ +/** + * \file cipher_internal.h + * + * \brief Cipher wrappers. + * + * \author Adriaan de Jong + */ +/* + * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ +#ifndef MBEDTLS_CIPHER_WRAP_H +#define MBEDTLS_CIPHER_WRAP_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include "cipher.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Base cipher information. The non-mode specific functions and values. + */ +struct mbedtls_cipher_base_t +{ + /** Base Cipher type (e.g. MBEDTLS_CIPHER_ID_AES) */ + mbedtls_cipher_id_t cipher; + + /** Encrypt using ECB */ + int (*ecb_func)( void *ctx, mbedtls_operation_t mode, + const unsigned char *input, unsigned char *output ); + +#if defined(MBEDTLS_CIPHER_MODE_CBC) + /** Encrypt using CBC */ + int (*cbc_func)( void *ctx, mbedtls_operation_t mode, size_t length, + unsigned char *iv, const unsigned char *input, + unsigned char *output ); +#endif + +#if defined(MBEDTLS_CIPHER_MODE_CFB) + /** Encrypt using CFB (Full length) */ + int (*cfb_func)( void *ctx, mbedtls_operation_t mode, size_t length, size_t *iv_off, + unsigned char *iv, const unsigned char *input, + unsigned char *output ); +#endif + +#if defined(MBEDTLS_CIPHER_MODE_OFB) + /** Encrypt using OFB (Full length) */ + int (*ofb_func)( void *ctx, size_t length, size_t *iv_off, + unsigned char *iv, + const unsigned char *input, + unsigned char *output ); +#endif + +#if defined(MBEDTLS_CIPHER_MODE_CTR) + /** Encrypt using CTR */ + int (*ctr_func)( void *ctx, size_t length, size_t *nc_off, + unsigned char *nonce_counter, unsigned char *stream_block, + const unsigned char *input, unsigned char *output ); +#endif + +#if defined(MBEDTLS_CIPHER_MODE_XTS) + /** Encrypt or decrypt using XTS. */ + int (*xts_func)( void *ctx, mbedtls_operation_t mode, size_t length, + const unsigned char data_unit[16], + const unsigned char *input, unsigned char *output ); +#endif + +#if defined(MBEDTLS_CIPHER_MODE_STREAM) + /** Encrypt using STREAM */ + int (*stream_func)( void *ctx, size_t length, + const unsigned char *input, unsigned char *output ); +#endif + + /** Set key for encryption purposes */ + int (*setkey_enc_func)( void *ctx, const unsigned char *key, + unsigned int key_bitlen ); + + /** Set key for decryption purposes */ + int (*setkey_dec_func)( void *ctx, const unsigned char *key, + unsigned int key_bitlen); + + /** Allocate a new context */ + void * (*ctx_alloc_func)( void ); + + /** Free the given context */ + void (*ctx_free_func)( void *ctx ); + +}; + +typedef struct +{ + mbedtls_cipher_type_t type; + const mbedtls_cipher_info_t *info; +} mbedtls_cipher_definition_t; + +extern const mbedtls_cipher_definition_t mbedtls_cipher_definitions[]; + +extern int mbedtls_cipher_supported[]; + +#ifdef __cplusplus +} +#endif + +#endif /* MBEDTLS_CIPHER_WRAP_H */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/cmac.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/cmac.h new file mode 100644 index 0000000000000000000000000000000000000000..9d42b3f209f9c52f0a6a4fcb6d1c0e973d69573c --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/cmac.h @@ -0,0 +1,213 @@ +/** + * \file cmac.h + * + * \brief This file contains CMAC definitions and functions. + * + * The Cipher-based Message Authentication Code (CMAC) Mode for + * Authentication is defined in RFC-4493: The AES-CMAC Algorithm. + */ +/* + * Copyright (C) 2015-2018, Arm Limited (or its affiliates), All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of Mbed TLS (https://tls.mbed.org) + */ + +#ifndef MBEDTLS_CMAC_H +#define MBEDTLS_CMAC_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include "cipher.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* MBEDTLS_ERR_CMAC_HW_ACCEL_FAILED is deprecated and should not be used. */ +#define MBEDTLS_ERR_CMAC_HW_ACCEL_FAILED -0x007A /**< CMAC hardware accelerator failed. */ + +#define MBEDTLS_AES_BLOCK_SIZE 16 +#define MBEDTLS_DES3_BLOCK_SIZE 8 + +#if defined(MBEDTLS_AES_C) +#define MBEDTLS_CIPHER_BLKSIZE_MAX 16 /**< The longest block used by CMAC is that of AES. */ +#else +#define MBEDTLS_CIPHER_BLKSIZE_MAX 8 /**< The longest block used by CMAC is that of 3DES. */ +#endif + +#if !defined(MBEDTLS_CMAC_ALT) + +/** + * The CMAC context structure. + */ +struct mbedtls_cmac_context_t +{ + /** The internal state of the CMAC algorithm. */ + unsigned char state[MBEDTLS_CIPHER_BLKSIZE_MAX]; + + /** Unprocessed data - either data that was not block aligned and is still + * pending processing, or the final block. */ + unsigned char unprocessed_block[MBEDTLS_CIPHER_BLKSIZE_MAX]; + + /** The length of data pending processing. */ + size_t unprocessed_len; +}; + +#else /* !MBEDTLS_CMAC_ALT */ +#include "cmac_alt.h" +#endif /* !MBEDTLS_CMAC_ALT */ + +/** + * \brief This function sets the CMAC key, and prepares to authenticate + * the input data. + * Must be called with an initialized cipher context. + * + * \param ctx The cipher context used for the CMAC operation, initialized + * as one of the following types: MBEDTLS_CIPHER_AES_128_ECB, + * MBEDTLS_CIPHER_AES_192_ECB, MBEDTLS_CIPHER_AES_256_ECB, + * or MBEDTLS_CIPHER_DES_EDE3_ECB. + * \param key The CMAC key. + * \param keybits The length of the CMAC key in bits. + * Must be supported by the cipher. + * + * \return \c 0 on success. + * \return A cipher-specific error code on failure. + */ +int mbedtls_cipher_cmac_starts( mbedtls_cipher_context_t *ctx, + const unsigned char *key, size_t keybits ); + +/** + * \brief This function feeds an input buffer into an ongoing CMAC + * computation. + * + * It is called between mbedtls_cipher_cmac_starts() or + * mbedtls_cipher_cmac_reset(), and mbedtls_cipher_cmac_finish(). + * Can be called repeatedly. + * + * \param ctx The cipher context used for the CMAC operation. + * \param input The buffer holding the input data. + * \param ilen The length of the input data. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA + * if parameter verification fails. + */ +int mbedtls_cipher_cmac_update( mbedtls_cipher_context_t *ctx, + const unsigned char *input, size_t ilen ); + +/** + * \brief This function finishes the CMAC operation, and writes + * the result to the output buffer. + * + * It is called after mbedtls_cipher_cmac_update(). + * It can be followed by mbedtls_cipher_cmac_reset() and + * mbedtls_cipher_cmac_update(), or mbedtls_cipher_free(). + * + * \param ctx The cipher context used for the CMAC operation. + * \param output The output buffer for the CMAC checksum result. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA + * if parameter verification fails. + */ +int mbedtls_cipher_cmac_finish( mbedtls_cipher_context_t *ctx, + unsigned char *output ); + +/** + * \brief This function prepares the authentication of another + * message with the same key as the previous CMAC + * operation. + * + * It is called after mbedtls_cipher_cmac_finish() + * and before mbedtls_cipher_cmac_update(). + * + * \param ctx The cipher context used for the CMAC operation. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA + * if parameter verification fails. + */ +int mbedtls_cipher_cmac_reset( mbedtls_cipher_context_t *ctx ); + +/** + * \brief This function calculates the full generic CMAC + * on the input buffer with the provided key. + * + * The function allocates the context, performs the + * calculation, and frees the context. + * + * The CMAC result is calculated as + * output = generic CMAC(cmac key, input buffer). + * + * + * \param cipher_info The cipher information. + * \param key The CMAC key. + * \param keylen The length of the CMAC key in bits. + * \param input The buffer holding the input data. + * \param ilen The length of the input data. + * \param output The buffer for the generic CMAC result. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA + * if parameter verification fails. + */ +int mbedtls_cipher_cmac( const mbedtls_cipher_info_t *cipher_info, + const unsigned char *key, size_t keylen, + const unsigned char *input, size_t ilen, + unsigned char *output ); + +#if defined(MBEDTLS_AES_C) +/** + * \brief This function implements the AES-CMAC-PRF-128 pseudorandom + * function, as defined in + * RFC-4615: The Advanced Encryption Standard-Cipher-based + * Message Authentication Code-Pseudo-Random Function-128 + * (AES-CMAC-PRF-128) Algorithm for the Internet Key + * Exchange Protocol (IKE). + * + * \param key The key to use. + * \param key_len The key length in Bytes. + * \param input The buffer holding the input data. + * \param in_len The length of the input data in Bytes. + * \param output The buffer holding the generated 16 Bytes of + * pseudorandom output. + * + * \return \c 0 on success. + */ +int mbedtls_aes_cmac_prf_128( const unsigned char *key, size_t key_len, + const unsigned char *input, size_t in_len, + unsigned char output[16] ); +#endif /* MBEDTLS_AES_C */ + +#if defined(MBEDTLS_SELF_TEST) && ( defined(MBEDTLS_AES_C) || defined(MBEDTLS_DES_C) ) +/** + * \brief The CMAC checkup routine. + * + * \return \c 0 on success. + * \return \c 1 on failure. + */ +int mbedtls_cmac_self_test( int verbose ); +#endif /* MBEDTLS_SELF_TEST && ( MBEDTLS_AES_C || MBEDTLS_DES_C ) */ + +#ifdef __cplusplus +} +#endif + +#endif /* MBEDTLS_CMAC_H */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/compat-1.3.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/compat-1.3.h new file mode 100644 index 0000000000000000000000000000000000000000..a58b47243d9c954b494c33ec807e7e0b253a8499 --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/compat-1.3.h @@ -0,0 +1,2531 @@ +/** + * \file compat-1.3.h + * + * \brief Compatibility definitions for using mbed TLS with client code written + * for the PolarSSL naming conventions. + * + * \deprecated Use the new names directly instead + */ +/* + * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#if ! defined(MBEDTLS_DEPRECATED_REMOVED) + +#if defined(MBEDTLS_DEPRECATED_WARNING) +#warning "Including compat-1.3.h is deprecated" +#endif + +#ifndef MBEDTLS_COMPAT13_H +#define MBEDTLS_COMPAT13_H + +/* + * config.h options + */ +#if defined MBEDTLS_AESNI_C +#define POLARSSL_AESNI_C MBEDTLS_AESNI_C +#endif +#if defined MBEDTLS_AES_ALT +#define POLARSSL_AES_ALT MBEDTLS_AES_ALT +#endif +#if defined MBEDTLS_AES_C +#define POLARSSL_AES_C MBEDTLS_AES_C +#endif +#if defined MBEDTLS_AES_ROM_TABLES +#define POLARSSL_AES_ROM_TABLES MBEDTLS_AES_ROM_TABLES +#endif +#if defined MBEDTLS_ARC4_ALT +#define POLARSSL_ARC4_ALT MBEDTLS_ARC4_ALT +#endif +#if defined MBEDTLS_ARC4_C +#define POLARSSL_ARC4_C MBEDTLS_ARC4_C +#endif +#if defined MBEDTLS_ASN1_PARSE_C +#define POLARSSL_ASN1_PARSE_C MBEDTLS_ASN1_PARSE_C +#endif +#if defined MBEDTLS_ASN1_WRITE_C +#define POLARSSL_ASN1_WRITE_C MBEDTLS_ASN1_WRITE_C +#endif +#if defined MBEDTLS_BASE64_C +#define POLARSSL_BASE64_C MBEDTLS_BASE64_C +#endif +#if defined MBEDTLS_BIGNUM_C +#define POLARSSL_BIGNUM_C MBEDTLS_BIGNUM_C +#endif +#if defined MBEDTLS_BLOWFISH_ALT +#define POLARSSL_BLOWFISH_ALT MBEDTLS_BLOWFISH_ALT +#endif +#if defined MBEDTLS_BLOWFISH_C +#define POLARSSL_BLOWFISH_C MBEDTLS_BLOWFISH_C +#endif +#if defined MBEDTLS_CAMELLIA_ALT +#define POLARSSL_CAMELLIA_ALT MBEDTLS_CAMELLIA_ALT +#endif +#if defined MBEDTLS_CAMELLIA_C +#define POLARSSL_CAMELLIA_C MBEDTLS_CAMELLIA_C +#endif +#if defined MBEDTLS_CAMELLIA_SMALL_MEMORY +#define POLARSSL_CAMELLIA_SMALL_MEMORY MBEDTLS_CAMELLIA_SMALL_MEMORY +#endif +#if defined MBEDTLS_CCM_C +#define POLARSSL_CCM_C MBEDTLS_CCM_C +#endif +#if defined MBEDTLS_CERTS_C +#define POLARSSL_CERTS_C MBEDTLS_CERTS_C +#endif +#if defined MBEDTLS_CIPHER_C +#define POLARSSL_CIPHER_C MBEDTLS_CIPHER_C +#endif +#if defined MBEDTLS_CIPHER_MODE_CBC +#define POLARSSL_CIPHER_MODE_CBC MBEDTLS_CIPHER_MODE_CBC +#endif +#if defined MBEDTLS_CIPHER_MODE_CFB +#define POLARSSL_CIPHER_MODE_CFB MBEDTLS_CIPHER_MODE_CFB +#endif +#if defined MBEDTLS_CIPHER_MODE_CTR +#define POLARSSL_CIPHER_MODE_CTR MBEDTLS_CIPHER_MODE_CTR +#endif +#if defined MBEDTLS_CIPHER_NULL_CIPHER +#define POLARSSL_CIPHER_NULL_CIPHER MBEDTLS_CIPHER_NULL_CIPHER +#endif +#if defined MBEDTLS_CIPHER_PADDING_ONE_AND_ZEROS +#define POLARSSL_CIPHER_PADDING_ONE_AND_ZEROS MBEDTLS_CIPHER_PADDING_ONE_AND_ZEROS +#endif +#if defined MBEDTLS_CIPHER_PADDING_PKCS7 +#define POLARSSL_CIPHER_PADDING_PKCS7 MBEDTLS_CIPHER_PADDING_PKCS7 +#endif +#if defined MBEDTLS_CIPHER_PADDING_ZEROS +#define POLARSSL_CIPHER_PADDING_ZEROS MBEDTLS_CIPHER_PADDING_ZEROS +#endif +#if defined MBEDTLS_CIPHER_PADDING_ZEROS_AND_LEN +#define POLARSSL_CIPHER_PADDING_ZEROS_AND_LEN MBEDTLS_CIPHER_PADDING_ZEROS_AND_LEN +#endif +#if defined MBEDTLS_CTR_DRBG_C +#define POLARSSL_CTR_DRBG_C MBEDTLS_CTR_DRBG_C +#endif +#if defined MBEDTLS_DEBUG_C +#define POLARSSL_DEBUG_C MBEDTLS_DEBUG_C +#endif +#if defined MBEDTLS_DEPRECATED_REMOVED +#define POLARSSL_DEPRECATED_REMOVED MBEDTLS_DEPRECATED_REMOVED +#endif +#if defined MBEDTLS_DEPRECATED_WARNING +#define POLARSSL_DEPRECATED_WARNING MBEDTLS_DEPRECATED_WARNING +#endif +#if defined MBEDTLS_DES_ALT +#define POLARSSL_DES_ALT MBEDTLS_DES_ALT +#endif +#if defined MBEDTLS_DES_C +#define POLARSSL_DES_C MBEDTLS_DES_C +#endif +#if defined MBEDTLS_DHM_C +#define POLARSSL_DHM_C MBEDTLS_DHM_C +#endif +#if defined MBEDTLS_ECDH_C +#define POLARSSL_ECDH_C MBEDTLS_ECDH_C +#endif +#if defined MBEDTLS_ECDSA_C +#define POLARSSL_ECDSA_C MBEDTLS_ECDSA_C +#endif +#if defined MBEDTLS_ECDSA_DETERMINISTIC +#define POLARSSL_ECDSA_DETERMINISTIC MBEDTLS_ECDSA_DETERMINISTIC +#endif +#if defined MBEDTLS_ECP_C +#define POLARSSL_ECP_C MBEDTLS_ECP_C +#endif +#if defined MBEDTLS_ECP_DP_BP256R1_ENABLED +#define POLARSSL_ECP_DP_BP256R1_ENABLED MBEDTLS_ECP_DP_BP256R1_ENABLED +#endif +#if defined MBEDTLS_ECP_DP_BP384R1_ENABLED +#define POLARSSL_ECP_DP_BP384R1_ENABLED MBEDTLS_ECP_DP_BP384R1_ENABLED +#endif +#if defined MBEDTLS_ECP_DP_BP512R1_ENABLED +#define POLARSSL_ECP_DP_BP512R1_ENABLED MBEDTLS_ECP_DP_BP512R1_ENABLED +#endif +#if defined MBEDTLS_ECP_DP_CURVE25519_ENABLED +#define POLARSSL_ECP_DP_M255_ENABLED MBEDTLS_ECP_DP_CURVE25519_ENABLED +#endif +#if defined MBEDTLS_ECP_DP_SECP192K1_ENABLED +#define POLARSSL_ECP_DP_SECP192K1_ENABLED MBEDTLS_ECP_DP_SECP192K1_ENABLED +#endif +#if defined MBEDTLS_ECP_DP_SECP192R1_ENABLED +#define POLARSSL_ECP_DP_SECP192R1_ENABLED MBEDTLS_ECP_DP_SECP192R1_ENABLED +#endif +#if defined MBEDTLS_ECP_DP_SECP224K1_ENABLED +#define POLARSSL_ECP_DP_SECP224K1_ENABLED MBEDTLS_ECP_DP_SECP224K1_ENABLED +#endif +#if defined MBEDTLS_ECP_DP_SECP224R1_ENABLED +#define POLARSSL_ECP_DP_SECP224R1_ENABLED MBEDTLS_ECP_DP_SECP224R1_ENABLED +#endif +#if defined MBEDTLS_ECP_DP_SECP256K1_ENABLED +#define POLARSSL_ECP_DP_SECP256K1_ENABLED MBEDTLS_ECP_DP_SECP256K1_ENABLED +#endif +#if defined MBEDTLS_ECP_DP_SECP256R1_ENABLED +#define POLARSSL_ECP_DP_SECP256R1_ENABLED MBEDTLS_ECP_DP_SECP256R1_ENABLED +#endif +#if defined MBEDTLS_ECP_DP_SECP384R1_ENABLED +#define POLARSSL_ECP_DP_SECP384R1_ENABLED MBEDTLS_ECP_DP_SECP384R1_ENABLED +#endif +#if defined MBEDTLS_ECP_DP_SECP521R1_ENABLED +#define POLARSSL_ECP_DP_SECP521R1_ENABLED MBEDTLS_ECP_DP_SECP521R1_ENABLED +#endif +#if defined MBEDTLS_ECP_FIXED_POINT_OPTIM +#define POLARSSL_ECP_FIXED_POINT_OPTIM MBEDTLS_ECP_FIXED_POINT_OPTIM +#endif +#if defined MBEDTLS_ECP_MAX_BITS +#define POLARSSL_ECP_MAX_BITS MBEDTLS_ECP_MAX_BITS +#endif +#if defined MBEDTLS_ECP_NIST_OPTIM +#define POLARSSL_ECP_NIST_OPTIM MBEDTLS_ECP_NIST_OPTIM +#endif +#if defined MBEDTLS_ECP_WINDOW_SIZE +#define POLARSSL_ECP_WINDOW_SIZE MBEDTLS_ECP_WINDOW_SIZE +#endif +#if defined MBEDTLS_ENABLE_WEAK_CIPHERSUITES +#define POLARSSL_ENABLE_WEAK_CIPHERSUITES MBEDTLS_ENABLE_WEAK_CIPHERSUITES +#endif +#if defined MBEDTLS_ENTROPY_C +#define POLARSSL_ENTROPY_C MBEDTLS_ENTROPY_C +#endif +#if defined MBEDTLS_ENTROPY_FORCE_SHA256 +#define POLARSSL_ENTROPY_FORCE_SHA256 MBEDTLS_ENTROPY_FORCE_SHA256 +#endif +#if defined MBEDTLS_ERROR_C +#define POLARSSL_ERROR_C MBEDTLS_ERROR_C +#endif +#if defined MBEDTLS_ERROR_STRERROR_DUMMY +#define POLARSSL_ERROR_STRERROR_DUMMY MBEDTLS_ERROR_STRERROR_DUMMY +#endif +#if defined MBEDTLS_FS_IO +#define POLARSSL_FS_IO MBEDTLS_FS_IO +#endif +#if defined MBEDTLS_GCM_C +#define POLARSSL_GCM_C MBEDTLS_GCM_C +#endif +#if defined MBEDTLS_GENPRIME +#define POLARSSL_GENPRIME MBEDTLS_GENPRIME +#endif +#if defined MBEDTLS_HAVEGE_C +#define POLARSSL_HAVEGE_C MBEDTLS_HAVEGE_C +#endif +#if defined MBEDTLS_HAVE_ASM +#define POLARSSL_HAVE_ASM MBEDTLS_HAVE_ASM +#endif +#if defined MBEDTLS_HAVE_SSE2 +#define POLARSSL_HAVE_SSE2 MBEDTLS_HAVE_SSE2 +#endif +#if defined MBEDTLS_HAVE_TIME +#define POLARSSL_HAVE_TIME MBEDTLS_HAVE_TIME +#endif +#if defined MBEDTLS_HMAC_DRBG_C +#define POLARSSL_HMAC_DRBG_C MBEDTLS_HMAC_DRBG_C +#endif +#if defined MBEDTLS_HMAC_DRBG_MAX_INPUT +#define POLARSSL_HMAC_DRBG_MAX_INPUT MBEDTLS_HMAC_DRBG_MAX_INPUT +#endif +#if defined MBEDTLS_HMAC_DRBG_MAX_REQUEST +#define POLARSSL_HMAC_DRBG_MAX_REQUEST MBEDTLS_HMAC_DRBG_MAX_REQUEST +#endif +#if defined MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT +#define POLARSSL_HMAC_DRBG_MAX_SEED_INPUT MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT +#endif +#if defined MBEDTLS_HMAC_DRBG_RESEED_INTERVAL +#define POLARSSL_HMAC_DRBG_RESEED_INTERVAL MBEDTLS_HMAC_DRBG_RESEED_INTERVAL +#endif +#if defined MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED +#define POLARSSL_KEY_EXCHANGE_DHE_PSK_ENABLED MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED +#endif +#if defined MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED +#define POLARSSL_KEY_EXCHANGE_DHE_RSA_ENABLED MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED +#endif +#if defined MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED +#define POLARSSL_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED +#endif +#if defined MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED +#define POLARSSL_KEY_EXCHANGE_ECDHE_PSK_ENABLED MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED +#endif +#if defined MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED +#define POLARSSL_KEY_EXCHANGE_ECDHE_RSA_ENABLED MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED +#endif +#if defined MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED +#define POLARSSL_KEY_EXCHANGE_ECDH_ECDSA_ENABLED MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED +#endif +#if defined MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED +#define POLARSSL_KEY_EXCHANGE_ECDH_RSA_ENABLED MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED +#endif +#if defined MBEDTLS_KEY_EXCHANGE_PSK_ENABLED +#define POLARSSL_KEY_EXCHANGE_PSK_ENABLED MBEDTLS_KEY_EXCHANGE_PSK_ENABLED +#endif +#if defined MBEDTLS_KEY_EXCHANGE_RSA_ENABLED +#define POLARSSL_KEY_EXCHANGE_RSA_ENABLED MBEDTLS_KEY_EXCHANGE_RSA_ENABLED +#endif +#if defined MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED +#define POLARSSL_KEY_EXCHANGE_RSA_PSK_ENABLED MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED +#endif +#if defined MBEDTLS_MD2_ALT +#define POLARSSL_MD2_ALT MBEDTLS_MD2_ALT +#endif +#if defined MBEDTLS_MD2_C +#define POLARSSL_MD2_C MBEDTLS_MD2_C +#endif +#if defined MBEDTLS_MD2_PROCESS_ALT +#define POLARSSL_MD2_PROCESS_ALT MBEDTLS_MD2_PROCESS_ALT +#endif +#if defined MBEDTLS_MD4_ALT +#define POLARSSL_MD4_ALT MBEDTLS_MD4_ALT +#endif +#if defined MBEDTLS_MD4_C +#define POLARSSL_MD4_C MBEDTLS_MD4_C +#endif +#if defined MBEDTLS_MD4_PROCESS_ALT +#define POLARSSL_MD4_PROCESS_ALT MBEDTLS_MD4_PROCESS_ALT +#endif +#if defined MBEDTLS_MD5_ALT +#define POLARSSL_MD5_ALT MBEDTLS_MD5_ALT +#endif +#if defined MBEDTLS_MD5_C +#define POLARSSL_MD5_C MBEDTLS_MD5_C +#endif +#if defined MBEDTLS_MD5_PROCESS_ALT +#define POLARSSL_MD5_PROCESS_ALT MBEDTLS_MD5_PROCESS_ALT +#endif +#if defined MBEDTLS_MD_C +#define POLARSSL_MD_C MBEDTLS_MD_C +#endif +#if defined MBEDTLS_MEMORY_ALIGN_MULTIPLE +#define POLARSSL_MEMORY_ALIGN_MULTIPLE MBEDTLS_MEMORY_ALIGN_MULTIPLE +#endif +#if defined MBEDTLS_MEMORY_BACKTRACE +#define POLARSSL_MEMORY_BACKTRACE MBEDTLS_MEMORY_BACKTRACE +#endif +#if defined MBEDTLS_MEMORY_BUFFER_ALLOC_C +#define POLARSSL_MEMORY_BUFFER_ALLOC_C MBEDTLS_MEMORY_BUFFER_ALLOC_C +#endif +#if defined MBEDTLS_MEMORY_DEBUG +#define POLARSSL_MEMORY_DEBUG MBEDTLS_MEMORY_DEBUG +#endif +#if defined MBEDTLS_MPI_MAX_SIZE +#define POLARSSL_MPI_MAX_SIZE MBEDTLS_MPI_MAX_SIZE +#endif +#if defined MBEDTLS_MPI_WINDOW_SIZE +#define POLARSSL_MPI_WINDOW_SIZE MBEDTLS_MPI_WINDOW_SIZE +#endif +#if defined MBEDTLS_NET_C +#define POLARSSL_NET_C MBEDTLS_NET_C +#endif +#if defined MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES +#define POLARSSL_NO_DEFAULT_ENTROPY_SOURCES MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES +#endif +#if defined MBEDTLS_NO_PLATFORM_ENTROPY +#define POLARSSL_NO_PLATFORM_ENTROPY MBEDTLS_NO_PLATFORM_ENTROPY +#endif +#if defined MBEDTLS_OID_C +#define POLARSSL_OID_C MBEDTLS_OID_C +#endif +#if defined MBEDTLS_PADLOCK_C +#define POLARSSL_PADLOCK_C MBEDTLS_PADLOCK_C +#endif +#if defined MBEDTLS_PEM_PARSE_C +#define POLARSSL_PEM_PARSE_C MBEDTLS_PEM_PARSE_C +#endif +#if defined MBEDTLS_PEM_WRITE_C +#define POLARSSL_PEM_WRITE_C MBEDTLS_PEM_WRITE_C +#endif +#if defined MBEDTLS_PKCS11_C +#define POLARSSL_PKCS11_C MBEDTLS_PKCS11_C +#endif +#if defined MBEDTLS_PKCS12_C +#define POLARSSL_PKCS12_C MBEDTLS_PKCS12_C +#endif +#if defined MBEDTLS_PKCS1_V15 +#define POLARSSL_PKCS1_V15 MBEDTLS_PKCS1_V15 +#endif +#if defined MBEDTLS_PKCS1_V21 +#define POLARSSL_PKCS1_V21 MBEDTLS_PKCS1_V21 +#endif +#if defined MBEDTLS_PKCS5_C +#define POLARSSL_PKCS5_C MBEDTLS_PKCS5_C +#endif +#if defined MBEDTLS_PK_C +#define POLARSSL_PK_C MBEDTLS_PK_C +#endif +#if defined MBEDTLS_PK_PARSE_C +#define POLARSSL_PK_PARSE_C MBEDTLS_PK_PARSE_C +#endif +#if defined MBEDTLS_PK_PARSE_EC_EXTENDED +#define POLARSSL_PK_PARSE_EC_EXTENDED MBEDTLS_PK_PARSE_EC_EXTENDED +#endif +#if defined MBEDTLS_PK_RSA_ALT_SUPPORT +#define POLARSSL_PK_RSA_ALT_SUPPORT MBEDTLS_PK_RSA_ALT_SUPPORT +#endif +#if defined MBEDTLS_PK_WRITE_C +#define POLARSSL_PK_WRITE_C MBEDTLS_PK_WRITE_C +#endif +#if defined MBEDTLS_PLATFORM_C +#define POLARSSL_PLATFORM_C MBEDTLS_PLATFORM_C +#endif +#if defined MBEDTLS_PLATFORM_EXIT_ALT +#define POLARSSL_PLATFORM_EXIT_ALT MBEDTLS_PLATFORM_EXIT_ALT +#endif +#if defined MBEDTLS_PLATFORM_EXIT_MACRO +#define POLARSSL_PLATFORM_EXIT_MACRO MBEDTLS_PLATFORM_EXIT_MACRO +#endif +#if defined MBEDTLS_PLATFORM_FPRINTF_ALT +#define POLARSSL_PLATFORM_FPRINTF_ALT MBEDTLS_PLATFORM_FPRINTF_ALT +#endif +#if defined MBEDTLS_PLATFORM_FPRINTF_MACRO +#define POLARSSL_PLATFORM_FPRINTF_MACRO MBEDTLS_PLATFORM_FPRINTF_MACRO +#endif +#if defined MBEDTLS_PLATFORM_FREE_MACRO +#define POLARSSL_PLATFORM_FREE_MACRO MBEDTLS_PLATFORM_FREE_MACRO +#endif +#if defined MBEDTLS_PLATFORM_MEMORY +#define POLARSSL_PLATFORM_MEMORY MBEDTLS_PLATFORM_MEMORY +#endif +#if defined MBEDTLS_PLATFORM_NO_STD_FUNCTIONS +#define POLARSSL_PLATFORM_NO_STD_FUNCTIONS MBEDTLS_PLATFORM_NO_STD_FUNCTIONS +#endif +#if defined MBEDTLS_PLATFORM_PRINTF_ALT +#define POLARSSL_PLATFORM_PRINTF_ALT MBEDTLS_PLATFORM_PRINTF_ALT +#endif +#if defined MBEDTLS_PLATFORM_PRINTF_MACRO +#define POLARSSL_PLATFORM_PRINTF_MACRO MBEDTLS_PLATFORM_PRINTF_MACRO +#endif +#if defined MBEDTLS_PLATFORM_SNPRINTF_ALT +#define POLARSSL_PLATFORM_SNPRINTF_ALT MBEDTLS_PLATFORM_SNPRINTF_ALT +#endif +#if defined MBEDTLS_PLATFORM_SNPRINTF_MACRO +#define POLARSSL_PLATFORM_SNPRINTF_MACRO MBEDTLS_PLATFORM_SNPRINTF_MACRO +#endif +#if defined MBEDTLS_PLATFORM_STD_EXIT +#define POLARSSL_PLATFORM_STD_EXIT MBEDTLS_PLATFORM_STD_EXIT +#endif +#if defined MBEDTLS_PLATFORM_STD_FPRINTF +#define POLARSSL_PLATFORM_STD_FPRINTF MBEDTLS_PLATFORM_STD_FPRINTF +#endif +#if defined MBEDTLS_PLATFORM_STD_FREE +#define POLARSSL_PLATFORM_STD_FREE MBEDTLS_PLATFORM_STD_FREE +#endif +#if defined MBEDTLS_PLATFORM_STD_MEM_HDR +#define POLARSSL_PLATFORM_STD_MEM_HDR MBEDTLS_PLATFORM_STD_MEM_HDR +#endif +#if defined MBEDTLS_PLATFORM_STD_PRINTF +#define POLARSSL_PLATFORM_STD_PRINTF MBEDTLS_PLATFORM_STD_PRINTF +#endif +#if defined MBEDTLS_PLATFORM_STD_SNPRINTF +#define POLARSSL_PLATFORM_STD_SNPRINTF MBEDTLS_PLATFORM_STD_SNPRINTF +#endif +#if defined MBEDTLS_PSK_MAX_LEN +#define POLARSSL_PSK_MAX_LEN MBEDTLS_PSK_MAX_LEN +#endif +#if defined MBEDTLS_REMOVE_ARC4_CIPHERSUITES +#define POLARSSL_REMOVE_ARC4_CIPHERSUITES MBEDTLS_REMOVE_ARC4_CIPHERSUITES +#endif +#if defined MBEDTLS_RIPEMD160_ALT +#define POLARSSL_RIPEMD160_ALT MBEDTLS_RIPEMD160_ALT +#endif +#if defined MBEDTLS_RIPEMD160_C +#define POLARSSL_RIPEMD160_C MBEDTLS_RIPEMD160_C +#endif +#if defined MBEDTLS_RIPEMD160_PROCESS_ALT +#define POLARSSL_RIPEMD160_PROCESS_ALT MBEDTLS_RIPEMD160_PROCESS_ALT +#endif +#if defined MBEDTLS_RSA_C +#define POLARSSL_RSA_C MBEDTLS_RSA_C +#endif +#if defined MBEDTLS_RSA_NO_CRT +#define POLARSSL_RSA_NO_CRT MBEDTLS_RSA_NO_CRT +#endif +#if defined MBEDTLS_SELF_TEST +#define POLARSSL_SELF_TEST MBEDTLS_SELF_TEST +#endif +#if defined MBEDTLS_SHA1_ALT +#define POLARSSL_SHA1_ALT MBEDTLS_SHA1_ALT +#endif +#if defined MBEDTLS_SHA1_C +#define POLARSSL_SHA1_C MBEDTLS_SHA1_C +#endif +#if defined MBEDTLS_SHA1_PROCESS_ALT +#define POLARSSL_SHA1_PROCESS_ALT MBEDTLS_SHA1_PROCESS_ALT +#endif +#if defined MBEDTLS_SHA256_ALT +#define POLARSSL_SHA256_ALT MBEDTLS_SHA256_ALT +#endif +#if defined MBEDTLS_SHA256_C +#define POLARSSL_SHA256_C MBEDTLS_SHA256_C +#endif +#if defined MBEDTLS_SHA256_PROCESS_ALT +#define POLARSSL_SHA256_PROCESS_ALT MBEDTLS_SHA256_PROCESS_ALT +#endif +#if defined MBEDTLS_SHA512_ALT +#define POLARSSL_SHA512_ALT MBEDTLS_SHA512_ALT +#endif +#if defined MBEDTLS_SHA512_C +#define POLARSSL_SHA512_C MBEDTLS_SHA512_C +#endif +#if defined MBEDTLS_SHA512_PROCESS_ALT +#define POLARSSL_SHA512_PROCESS_ALT MBEDTLS_SHA512_PROCESS_ALT +#endif +#if defined MBEDTLS_SSL_ALL_ALERT_MESSAGES +#define POLARSSL_SSL_ALL_ALERT_MESSAGES MBEDTLS_SSL_ALL_ALERT_MESSAGES +#endif +#if defined MBEDTLS_SSL_ALPN +#define POLARSSL_SSL_ALPN MBEDTLS_SSL_ALPN +#endif +#if defined MBEDTLS_SSL_CACHE_C +#define POLARSSL_SSL_CACHE_C MBEDTLS_SSL_CACHE_C +#endif +#if defined MBEDTLS_SSL_CBC_RECORD_SPLITTING +#define POLARSSL_SSL_CBC_RECORD_SPLITTING MBEDTLS_SSL_CBC_RECORD_SPLITTING +#endif +#if defined MBEDTLS_SSL_CLI_C +#define POLARSSL_SSL_CLI_C MBEDTLS_SSL_CLI_C +#endif +#if defined MBEDTLS_SSL_COOKIE_C +#define POLARSSL_SSL_COOKIE_C MBEDTLS_SSL_COOKIE_C +#endif +#if defined MBEDTLS_SSL_COOKIE_TIMEOUT +#define POLARSSL_SSL_COOKIE_TIMEOUT MBEDTLS_SSL_COOKIE_TIMEOUT +#endif +#if defined MBEDTLS_SSL_DEBUG_ALL +#define POLARSSL_SSL_DEBUG_ALL MBEDTLS_SSL_DEBUG_ALL +#endif +#if defined MBEDTLS_SSL_DTLS_ANTI_REPLAY +#define POLARSSL_SSL_DTLS_ANTI_REPLAY MBEDTLS_SSL_DTLS_ANTI_REPLAY +#endif +#if defined MBEDTLS_SSL_DTLS_BADMAC_LIMIT +#define POLARSSL_SSL_DTLS_BADMAC_LIMIT MBEDTLS_SSL_DTLS_BADMAC_LIMIT +#endif +#if defined MBEDTLS_SSL_DTLS_HELLO_VERIFY +#define POLARSSL_SSL_DTLS_HELLO_VERIFY MBEDTLS_SSL_DTLS_HELLO_VERIFY +#endif +#if defined MBEDTLS_SSL_ENCRYPT_THEN_MAC +#define POLARSSL_SSL_ENCRYPT_THEN_MAC MBEDTLS_SSL_ENCRYPT_THEN_MAC +#endif +#if defined MBEDTLS_SSL_EXTENDED_MASTER_SECRET +#define POLARSSL_SSL_EXTENDED_MASTER_SECRET MBEDTLS_SSL_EXTENDED_MASTER_SECRET +#endif +#if defined MBEDTLS_SSL_FALLBACK_SCSV +#define POLARSSL_SSL_FALLBACK_SCSV MBEDTLS_SSL_FALLBACK_SCSV +#endif +#if defined MBEDTLS_SSL_HW_RECORD_ACCEL +#define POLARSSL_SSL_HW_RECORD_ACCEL MBEDTLS_SSL_HW_RECORD_ACCEL +#endif +#if defined MBEDTLS_SSL_MAX_FRAGMENT_LENGTH +#define POLARSSL_SSL_MAX_FRAGMENT_LENGTH MBEDTLS_SSL_MAX_FRAGMENT_LENGTH +#endif +#if defined MBEDTLS_SSL_PROTO_DTLS +#define POLARSSL_SSL_PROTO_DTLS MBEDTLS_SSL_PROTO_DTLS +#endif +#if defined MBEDTLS_SSL_PROTO_SSL3 +#define POLARSSL_SSL_PROTO_SSL3 MBEDTLS_SSL_PROTO_SSL3 +#endif +#if defined MBEDTLS_SSL_PROTO_TLS1 +#define POLARSSL_SSL_PROTO_TLS1 MBEDTLS_SSL_PROTO_TLS1 +#endif +#if defined MBEDTLS_SSL_PROTO_TLS1_1 +#define POLARSSL_SSL_PROTO_TLS1_1 MBEDTLS_SSL_PROTO_TLS1_1 +#endif +#if defined MBEDTLS_SSL_PROTO_TLS1_2 +#define POLARSSL_SSL_PROTO_TLS1_2 MBEDTLS_SSL_PROTO_TLS1_2 +#endif +#if defined MBEDTLS_SSL_RENEGOTIATION +#define POLARSSL_SSL_RENEGOTIATION MBEDTLS_SSL_RENEGOTIATION +#endif +#if defined MBEDTLS_SSL_SERVER_NAME_INDICATION +#define POLARSSL_SSL_SERVER_NAME_INDICATION MBEDTLS_SSL_SERVER_NAME_INDICATION +#endif +#if defined MBEDTLS_SSL_SESSION_TICKETS +#define POLARSSL_SSL_SESSION_TICKETS MBEDTLS_SSL_SESSION_TICKETS +#endif +#if defined MBEDTLS_SSL_SRV_C +#define POLARSSL_SSL_SRV_C MBEDTLS_SSL_SRV_C +#endif +#if defined MBEDTLS_SSL_SRV_RESPECT_CLIENT_PREFERENCE +#define POLARSSL_SSL_SRV_RESPECT_CLIENT_PREFERENCE MBEDTLS_SSL_SRV_RESPECT_CLIENT_PREFERENCE +#endif +#if defined MBEDTLS_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO +#define POLARSSL_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO MBEDTLS_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO +#endif +#if defined MBEDTLS_SSL_TLS_C +#define POLARSSL_SSL_TLS_C MBEDTLS_SSL_TLS_C +#endif +#if defined MBEDTLS_SSL_TRUNCATED_HMAC +#define POLARSSL_SSL_TRUNCATED_HMAC MBEDTLS_SSL_TRUNCATED_HMAC +#endif +#if defined MBEDTLS_THREADING_ALT +#define POLARSSL_THREADING_ALT MBEDTLS_THREADING_ALT +#endif +#if defined MBEDTLS_THREADING_C +#define POLARSSL_THREADING_C MBEDTLS_THREADING_C +#endif +#if defined MBEDTLS_THREADING_PTHREAD +#define POLARSSL_THREADING_PTHREAD MBEDTLS_THREADING_PTHREAD +#endif +#if defined MBEDTLS_TIMING_ALT +#define POLARSSL_TIMING_ALT MBEDTLS_TIMING_ALT +#endif +#if defined MBEDTLS_TIMING_C +#define POLARSSL_TIMING_C MBEDTLS_TIMING_C +#endif +#if defined MBEDTLS_VERSION_C +#define POLARSSL_VERSION_C MBEDTLS_VERSION_C +#endif +#if defined MBEDTLS_VERSION_FEATURES +#define POLARSSL_VERSION_FEATURES MBEDTLS_VERSION_FEATURES +#endif +#if defined MBEDTLS_X509_ALLOW_EXTENSIONS_NON_V3 +#define POLARSSL_X509_ALLOW_EXTENSIONS_NON_V3 MBEDTLS_X509_ALLOW_EXTENSIONS_NON_V3 +#endif +#if defined MBEDTLS_X509_ALLOW_UNSUPPORTED_CRITICAL_EXTENSION +#define POLARSSL_X509_ALLOW_UNSUPPORTED_CRITICAL_EXTENSION MBEDTLS_X509_ALLOW_UNSUPPORTED_CRITICAL_EXTENSION +#endif +#if defined MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE +#define POLARSSL_X509_CHECK_EXTENDED_KEY_USAGE MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE +#endif +#if defined MBEDTLS_X509_CHECK_KEY_USAGE +#define POLARSSL_X509_CHECK_KEY_USAGE MBEDTLS_X509_CHECK_KEY_USAGE +#endif +#if defined MBEDTLS_X509_CREATE_C +#define POLARSSL_X509_CREATE_C MBEDTLS_X509_CREATE_C +#endif +#if defined MBEDTLS_X509_CRL_PARSE_C +#define POLARSSL_X509_CRL_PARSE_C MBEDTLS_X509_CRL_PARSE_C +#endif +#if defined MBEDTLS_X509_CRT_PARSE_C +#define POLARSSL_X509_CRT_PARSE_C MBEDTLS_X509_CRT_PARSE_C +#endif +#if defined MBEDTLS_X509_CRT_WRITE_C +#define POLARSSL_X509_CRT_WRITE_C MBEDTLS_X509_CRT_WRITE_C +#endif +#if defined MBEDTLS_X509_CSR_PARSE_C +#define POLARSSL_X509_CSR_PARSE_C MBEDTLS_X509_CSR_PARSE_C +#endif +#if defined MBEDTLS_X509_CSR_WRITE_C +#define POLARSSL_X509_CSR_WRITE_C MBEDTLS_X509_CSR_WRITE_C +#endif +#if defined MBEDTLS_X509_MAX_INTERMEDIATE_CA +#define POLARSSL_X509_MAX_INTERMEDIATE_CA MBEDTLS_X509_MAX_INTERMEDIATE_CA +#endif +#if defined MBEDTLS_X509_RSASSA_PSS_SUPPORT +#define POLARSSL_X509_RSASSA_PSS_SUPPORT MBEDTLS_X509_RSASSA_PSS_SUPPORT +#endif +#if defined MBEDTLS_X509_USE_C +#define POLARSSL_X509_USE_C MBEDTLS_X509_USE_C +#endif +#if defined MBEDTLS_XTEA_ALT +#define POLARSSL_XTEA_ALT MBEDTLS_XTEA_ALT +#endif +#if defined MBEDTLS_XTEA_C +#define POLARSSL_XTEA_C MBEDTLS_XTEA_C +#endif +#if defined MBEDTLS_ZLIB_SUPPORT +#define POLARSSL_ZLIB_SUPPORT MBEDTLS_ZLIB_SUPPORT +#endif + +/* + * Misc names (macros, types, functions, enum constants...) + */ +#define AES_DECRYPT MBEDTLS_AES_DECRYPT +#define AES_ENCRYPT MBEDTLS_AES_ENCRYPT +#define ASN1_BIT_STRING MBEDTLS_ASN1_BIT_STRING +#define ASN1_BMP_STRING MBEDTLS_ASN1_BMP_STRING +#define ASN1_BOOLEAN MBEDTLS_ASN1_BOOLEAN +#define ASN1_CHK_ADD MBEDTLS_ASN1_CHK_ADD +#define ASN1_CONSTRUCTED MBEDTLS_ASN1_CONSTRUCTED +#define ASN1_CONTEXT_SPECIFIC MBEDTLS_ASN1_CONTEXT_SPECIFIC +#define ASN1_GENERALIZED_TIME MBEDTLS_ASN1_GENERALIZED_TIME +#define ASN1_IA5_STRING MBEDTLS_ASN1_IA5_STRING +#define ASN1_INTEGER MBEDTLS_ASN1_INTEGER +#define ASN1_NULL MBEDTLS_ASN1_NULL +#define ASN1_OCTET_STRING MBEDTLS_ASN1_OCTET_STRING +#define ASN1_OID MBEDTLS_ASN1_OID +#define ASN1_PRIMITIVE MBEDTLS_ASN1_PRIMITIVE +#define ASN1_PRINTABLE_STRING MBEDTLS_ASN1_PRINTABLE_STRING +#define ASN1_SEQUENCE MBEDTLS_ASN1_SEQUENCE +#define ASN1_SET MBEDTLS_ASN1_SET +#define ASN1_T61_STRING MBEDTLS_ASN1_T61_STRING +#define ASN1_UNIVERSAL_STRING MBEDTLS_ASN1_UNIVERSAL_STRING +#define ASN1_UTC_TIME MBEDTLS_ASN1_UTC_TIME +#define ASN1_UTF8_STRING MBEDTLS_ASN1_UTF8_STRING +#define BADCERT_CN_MISMATCH MBEDTLS_X509_BADCERT_CN_MISMATCH +#define BADCERT_EXPIRED MBEDTLS_X509_BADCERT_EXPIRED +#define BADCERT_FUTURE MBEDTLS_X509_BADCERT_FUTURE +#define BADCERT_MISSING MBEDTLS_X509_BADCERT_MISSING +#define BADCERT_NOT_TRUSTED MBEDTLS_X509_BADCERT_NOT_TRUSTED +#define BADCERT_OTHER MBEDTLS_X509_BADCERT_OTHER +#define BADCERT_REVOKED MBEDTLS_X509_BADCERT_REVOKED +#define BADCERT_SKIP_VERIFY MBEDTLS_X509_BADCERT_SKIP_VERIFY +#define BADCRL_EXPIRED MBEDTLS_X509_BADCRL_EXPIRED +#define BADCRL_FUTURE MBEDTLS_X509_BADCRL_FUTURE +#define BADCRL_NOT_TRUSTED MBEDTLS_X509_BADCRL_NOT_TRUSTED +#define BLOWFISH_BLOCKSIZE MBEDTLS_BLOWFISH_BLOCKSIZE +#define BLOWFISH_DECRYPT MBEDTLS_BLOWFISH_DECRYPT +#define BLOWFISH_ENCRYPT MBEDTLS_BLOWFISH_ENCRYPT +#define BLOWFISH_MAX_KEY MBEDTLS_BLOWFISH_MAX_KEY_BITS +#define BLOWFISH_MIN_KEY MBEDTLS_BLOWFISH_MIN_KEY_BITS +#define BLOWFISH_ROUNDS MBEDTLS_BLOWFISH_ROUNDS +#define CAMELLIA_DECRYPT MBEDTLS_CAMELLIA_DECRYPT +#define CAMELLIA_ENCRYPT MBEDTLS_CAMELLIA_ENCRYPT +#define COLLECT_SIZE MBEDTLS_HAVEGE_COLLECT_SIZE +#define CTR_DRBG_BLOCKSIZE MBEDTLS_CTR_DRBG_BLOCKSIZE +#define CTR_DRBG_ENTROPY_LEN MBEDTLS_CTR_DRBG_ENTROPY_LEN +#define CTR_DRBG_KEYBITS MBEDTLS_CTR_DRBG_KEYBITS +#define CTR_DRBG_KEYSIZE MBEDTLS_CTR_DRBG_KEYSIZE +#define CTR_DRBG_MAX_INPUT MBEDTLS_CTR_DRBG_MAX_INPUT +#define CTR_DRBG_MAX_REQUEST MBEDTLS_CTR_DRBG_MAX_REQUEST +#define CTR_DRBG_MAX_SEED_INPUT MBEDTLS_CTR_DRBG_MAX_SEED_INPUT +#define CTR_DRBG_PR_OFF MBEDTLS_CTR_DRBG_PR_OFF +#define CTR_DRBG_PR_ON MBEDTLS_CTR_DRBG_PR_ON +#define CTR_DRBG_RESEED_INTERVAL MBEDTLS_CTR_DRBG_RESEED_INTERVAL +#define CTR_DRBG_SEEDLEN MBEDTLS_CTR_DRBG_SEEDLEN +#define DEPRECATED MBEDTLS_DEPRECATED +#define DES_DECRYPT MBEDTLS_DES_DECRYPT +#define DES_ENCRYPT MBEDTLS_DES_ENCRYPT +#define DES_KEY_SIZE MBEDTLS_DES_KEY_SIZE +#define ENTROPY_BLOCK_SIZE MBEDTLS_ENTROPY_BLOCK_SIZE +#define ENTROPY_MAX_GATHER MBEDTLS_ENTROPY_MAX_GATHER +#define ENTROPY_MAX_SEED_SIZE MBEDTLS_ENTROPY_MAX_SEED_SIZE +#define ENTROPY_MAX_SOURCES MBEDTLS_ENTROPY_MAX_SOURCES +#define ENTROPY_MIN_HARDCLOCK MBEDTLS_ENTROPY_MIN_HARDCLOCK +#define ENTROPY_MIN_HAVEGE MBEDTLS_ENTROPY_MIN_HAVEGE +#define ENTROPY_MIN_PLATFORM MBEDTLS_ENTROPY_MIN_PLATFORM +#define ENTROPY_SOURCE_MANUAL MBEDTLS_ENTROPY_SOURCE_MANUAL +#define EXT_AUTHORITY_KEY_IDENTIFIER MBEDTLS_X509_EXT_AUTHORITY_KEY_IDENTIFIER +#define EXT_BASIC_CONSTRAINTS MBEDTLS_X509_EXT_BASIC_CONSTRAINTS +#define EXT_CERTIFICATE_POLICIES MBEDTLS_X509_EXT_CERTIFICATE_POLICIES +#define EXT_CRL_DISTRIBUTION_POINTS MBEDTLS_X509_EXT_CRL_DISTRIBUTION_POINTS +#define EXT_EXTENDED_KEY_USAGE MBEDTLS_X509_EXT_EXTENDED_KEY_USAGE +#define EXT_FRESHEST_CRL MBEDTLS_X509_EXT_FRESHEST_CRL +#define EXT_INIHIBIT_ANYPOLICY MBEDTLS_X509_EXT_INIHIBIT_ANYPOLICY +#define EXT_ISSUER_ALT_NAME MBEDTLS_X509_EXT_ISSUER_ALT_NAME +#define EXT_KEY_USAGE MBEDTLS_X509_EXT_KEY_USAGE +#define EXT_NAME_CONSTRAINTS MBEDTLS_X509_EXT_NAME_CONSTRAINTS +#define EXT_NS_CERT_TYPE MBEDTLS_X509_EXT_NS_CERT_TYPE +#define EXT_POLICY_CONSTRAINTS MBEDTLS_X509_EXT_POLICY_CONSTRAINTS +#define EXT_POLICY_MAPPINGS MBEDTLS_X509_EXT_POLICY_MAPPINGS +#define EXT_SUBJECT_ALT_NAME MBEDTLS_X509_EXT_SUBJECT_ALT_NAME +#define EXT_SUBJECT_DIRECTORY_ATTRS MBEDTLS_X509_EXT_SUBJECT_DIRECTORY_ATTRS +#define EXT_SUBJECT_KEY_IDENTIFIER MBEDTLS_X509_EXT_SUBJECT_KEY_IDENTIFIER +#define GCM_DECRYPT MBEDTLS_GCM_DECRYPT +#define GCM_ENCRYPT MBEDTLS_GCM_ENCRYPT +#define KU_CRL_SIGN MBEDTLS_X509_KU_CRL_SIGN +#define KU_DATA_ENCIPHERMENT MBEDTLS_X509_KU_DATA_ENCIPHERMENT +#define KU_DIGITAL_SIGNATURE MBEDTLS_X509_KU_DIGITAL_SIGNATURE +#define KU_KEY_AGREEMENT MBEDTLS_X509_KU_KEY_AGREEMENT +#define KU_KEY_CERT_SIGN MBEDTLS_X509_KU_KEY_CERT_SIGN +#define KU_KEY_ENCIPHERMENT MBEDTLS_X509_KU_KEY_ENCIPHERMENT +#define KU_NON_REPUDIATION MBEDTLS_X509_KU_NON_REPUDIATION +#define LN_2_DIV_LN_10_SCALE100 MBEDTLS_LN_2_DIV_LN_10_SCALE100 +#define MEMORY_VERIFY_ALLOC MBEDTLS_MEMORY_VERIFY_ALLOC +#define MEMORY_VERIFY_ALWAYS MBEDTLS_MEMORY_VERIFY_ALWAYS +#define MEMORY_VERIFY_FREE MBEDTLS_MEMORY_VERIFY_FREE +#define MEMORY_VERIFY_NONE MBEDTLS_MEMORY_VERIFY_NONE +#define MPI_CHK MBEDTLS_MPI_CHK +#define NET_PROTO_TCP MBEDTLS_NET_PROTO_TCP +#define NET_PROTO_UDP MBEDTLS_NET_PROTO_UDP +#define NS_CERT_TYPE_EMAIL MBEDTLS_X509_NS_CERT_TYPE_EMAIL +#define NS_CERT_TYPE_EMAIL_CA MBEDTLS_X509_NS_CERT_TYPE_EMAIL_CA +#define NS_CERT_TYPE_OBJECT_SIGNING MBEDTLS_X509_NS_CERT_TYPE_OBJECT_SIGNING +#define NS_CERT_TYPE_OBJECT_SIGNING_CA MBEDTLS_X509_NS_CERT_TYPE_OBJECT_SIGNING_CA +#define NS_CERT_TYPE_RESERVED MBEDTLS_X509_NS_CERT_TYPE_RESERVED +#define NS_CERT_TYPE_SSL_CA MBEDTLS_X509_NS_CERT_TYPE_SSL_CA +#define NS_CERT_TYPE_SSL_CLIENT MBEDTLS_X509_NS_CERT_TYPE_SSL_CLIENT +#define NS_CERT_TYPE_SSL_SERVER MBEDTLS_X509_NS_CERT_TYPE_SSL_SERVER +#define OID_ANSI_X9_62 MBEDTLS_OID_ANSI_X9_62 +#define OID_ANSI_X9_62_FIELD_TYPE MBEDTLS_OID_ANSI_X9_62_FIELD_TYPE +#define OID_ANSI_X9_62_PRIME_FIELD MBEDTLS_OID_ANSI_X9_62_PRIME_FIELD +#define OID_ANSI_X9_62_SIG MBEDTLS_OID_ANSI_X9_62_SIG +#define OID_ANSI_X9_62_SIG_SHA2 MBEDTLS_OID_ANSI_X9_62_SIG_SHA2 +#define OID_ANY_EXTENDED_KEY_USAGE MBEDTLS_OID_ANY_EXTENDED_KEY_USAGE +#define OID_AT MBEDTLS_OID_AT +#define OID_AT_CN MBEDTLS_OID_AT_CN +#define OID_AT_COUNTRY MBEDTLS_OID_AT_COUNTRY +#define OID_AT_DN_QUALIFIER MBEDTLS_OID_AT_DN_QUALIFIER +#define OID_AT_GENERATION_QUALIFIER MBEDTLS_OID_AT_GENERATION_QUALIFIER +#define OID_AT_GIVEN_NAME MBEDTLS_OID_AT_GIVEN_NAME +#define OID_AT_INITIALS MBEDTLS_OID_AT_INITIALS +#define OID_AT_LOCALITY MBEDTLS_OID_AT_LOCALITY +#define OID_AT_ORGANIZATION MBEDTLS_OID_AT_ORGANIZATION +#define OID_AT_ORG_UNIT MBEDTLS_OID_AT_ORG_UNIT +#define OID_AT_POSTAL_ADDRESS MBEDTLS_OID_AT_POSTAL_ADDRESS +#define OID_AT_POSTAL_CODE MBEDTLS_OID_AT_POSTAL_CODE +#define OID_AT_PSEUDONYM MBEDTLS_OID_AT_PSEUDONYM +#define OID_AT_SERIAL_NUMBER MBEDTLS_OID_AT_SERIAL_NUMBER +#define OID_AT_STATE MBEDTLS_OID_AT_STATE +#define OID_AT_SUR_NAME MBEDTLS_OID_AT_SUR_NAME +#define OID_AT_TITLE MBEDTLS_OID_AT_TITLE +#define OID_AT_UNIQUE_IDENTIFIER MBEDTLS_OID_AT_UNIQUE_IDENTIFIER +#define OID_AUTHORITY_KEY_IDENTIFIER MBEDTLS_OID_AUTHORITY_KEY_IDENTIFIER +#define OID_BASIC_CONSTRAINTS MBEDTLS_OID_BASIC_CONSTRAINTS +#define OID_CERTICOM MBEDTLS_OID_CERTICOM +#define OID_CERTIFICATE_POLICIES MBEDTLS_OID_CERTIFICATE_POLICIES +#define OID_CLIENT_AUTH MBEDTLS_OID_CLIENT_AUTH +#define OID_CMP MBEDTLS_OID_CMP +#define OID_CODE_SIGNING MBEDTLS_OID_CODE_SIGNING +#define OID_COUNTRY_US MBEDTLS_OID_COUNTRY_US +#define OID_CRL_DISTRIBUTION_POINTS MBEDTLS_OID_CRL_DISTRIBUTION_POINTS +#define OID_CRL_NUMBER MBEDTLS_OID_CRL_NUMBER +#define OID_DES_CBC MBEDTLS_OID_DES_CBC +#define OID_DES_EDE3_CBC MBEDTLS_OID_DES_EDE3_CBC +#define OID_DIGEST_ALG_MD2 MBEDTLS_OID_DIGEST_ALG_MD2 +#define OID_DIGEST_ALG_MD4 MBEDTLS_OID_DIGEST_ALG_MD4 +#define OID_DIGEST_ALG_MD5 MBEDTLS_OID_DIGEST_ALG_MD5 +#define OID_DIGEST_ALG_SHA1 MBEDTLS_OID_DIGEST_ALG_SHA1 +#define OID_DIGEST_ALG_SHA224 MBEDTLS_OID_DIGEST_ALG_SHA224 +#define OID_DIGEST_ALG_SHA256 MBEDTLS_OID_DIGEST_ALG_SHA256 +#define OID_DIGEST_ALG_SHA384 MBEDTLS_OID_DIGEST_ALG_SHA384 +#define OID_DIGEST_ALG_SHA512 MBEDTLS_OID_DIGEST_ALG_SHA512 +#define OID_DOMAIN_COMPONENT MBEDTLS_OID_DOMAIN_COMPONENT +#define OID_ECDSA_SHA1 MBEDTLS_OID_ECDSA_SHA1 +#define OID_ECDSA_SHA224 MBEDTLS_OID_ECDSA_SHA224 +#define OID_ECDSA_SHA256 MBEDTLS_OID_ECDSA_SHA256 +#define OID_ECDSA_SHA384 MBEDTLS_OID_ECDSA_SHA384 +#define OID_ECDSA_SHA512 MBEDTLS_OID_ECDSA_SHA512 +#define OID_EC_ALG_ECDH MBEDTLS_OID_EC_ALG_ECDH +#define OID_EC_ALG_UNRESTRICTED MBEDTLS_OID_EC_ALG_UNRESTRICTED +#define OID_EC_BRAINPOOL_V1 MBEDTLS_OID_EC_BRAINPOOL_V1 +#define OID_EC_GRP_BP256R1 MBEDTLS_OID_EC_GRP_BP256R1 +#define OID_EC_GRP_BP384R1 MBEDTLS_OID_EC_GRP_BP384R1 +#define OID_EC_GRP_BP512R1 MBEDTLS_OID_EC_GRP_BP512R1 +#define OID_EC_GRP_SECP192K1 MBEDTLS_OID_EC_GRP_SECP192K1 +#define OID_EC_GRP_SECP192R1 MBEDTLS_OID_EC_GRP_SECP192R1 +#define OID_EC_GRP_SECP224K1 MBEDTLS_OID_EC_GRP_SECP224K1 +#define OID_EC_GRP_SECP224R1 MBEDTLS_OID_EC_GRP_SECP224R1 +#define OID_EC_GRP_SECP256K1 MBEDTLS_OID_EC_GRP_SECP256K1 +#define OID_EC_GRP_SECP256R1 MBEDTLS_OID_EC_GRP_SECP256R1 +#define OID_EC_GRP_SECP384R1 MBEDTLS_OID_EC_GRP_SECP384R1 +#define OID_EC_GRP_SECP521R1 MBEDTLS_OID_EC_GRP_SECP521R1 +#define OID_EMAIL_PROTECTION MBEDTLS_OID_EMAIL_PROTECTION +#define OID_EXTENDED_KEY_USAGE MBEDTLS_OID_EXTENDED_KEY_USAGE +#define OID_FRESHEST_CRL MBEDTLS_OID_FRESHEST_CRL +#define OID_GOV MBEDTLS_OID_GOV +#define OID_HMAC_SHA1 MBEDTLS_OID_HMAC_SHA1 +#define OID_ID_CE MBEDTLS_OID_ID_CE +#define OID_INIHIBIT_ANYPOLICY MBEDTLS_OID_INIHIBIT_ANYPOLICY +#define OID_ISO_CCITT_DS MBEDTLS_OID_ISO_CCITT_DS +#define OID_ISO_IDENTIFIED_ORG MBEDTLS_OID_ISO_IDENTIFIED_ORG +#define OID_ISO_ITU_COUNTRY MBEDTLS_OID_ISO_ITU_COUNTRY +#define OID_ISO_ITU_US_ORG MBEDTLS_OID_ISO_ITU_US_ORG +#define OID_ISO_MEMBER_BODIES MBEDTLS_OID_ISO_MEMBER_BODIES +#define OID_ISSUER_ALT_NAME MBEDTLS_OID_ISSUER_ALT_NAME +#define OID_KEY_USAGE MBEDTLS_OID_KEY_USAGE +#define OID_KP MBEDTLS_OID_KP +#define OID_MGF1 MBEDTLS_OID_MGF1 +#define OID_NAME_CONSTRAINTS MBEDTLS_OID_NAME_CONSTRAINTS +#define OID_NETSCAPE MBEDTLS_OID_NETSCAPE +#define OID_NS_BASE_URL MBEDTLS_OID_NS_BASE_URL +#define OID_NS_CA_POLICY_URL MBEDTLS_OID_NS_CA_POLICY_URL +#define OID_NS_CA_REVOCATION_URL MBEDTLS_OID_NS_CA_REVOCATION_URL +#define OID_NS_CERT MBEDTLS_OID_NS_CERT +#define OID_NS_CERT_SEQUENCE MBEDTLS_OID_NS_CERT_SEQUENCE +#define OID_NS_CERT_TYPE MBEDTLS_OID_NS_CERT_TYPE +#define OID_NS_COMMENT MBEDTLS_OID_NS_COMMENT +#define OID_NS_DATA_TYPE MBEDTLS_OID_NS_DATA_TYPE +#define OID_NS_RENEWAL_URL MBEDTLS_OID_NS_RENEWAL_URL +#define OID_NS_REVOCATION_URL MBEDTLS_OID_NS_REVOCATION_URL +#define OID_NS_SSL_SERVER_NAME MBEDTLS_OID_NS_SSL_SERVER_NAME +#define OID_OCSP_SIGNING MBEDTLS_OID_OCSP_SIGNING +#define OID_OIW_SECSIG MBEDTLS_OID_OIW_SECSIG +#define OID_OIW_SECSIG_ALG MBEDTLS_OID_OIW_SECSIG_ALG +#define OID_OIW_SECSIG_SHA1 MBEDTLS_OID_OIW_SECSIG_SHA1 +#define OID_ORGANIZATION MBEDTLS_OID_ORGANIZATION +#define OID_ORG_ANSI_X9_62 MBEDTLS_OID_ORG_ANSI_X9_62 +#define OID_ORG_CERTICOM MBEDTLS_OID_ORG_CERTICOM +#define OID_ORG_DOD MBEDTLS_OID_ORG_DOD +#define OID_ORG_GOV MBEDTLS_OID_ORG_GOV +#define OID_ORG_NETSCAPE MBEDTLS_OID_ORG_NETSCAPE +#define OID_ORG_OIW MBEDTLS_OID_ORG_OIW +#define OID_ORG_RSA_DATA_SECURITY MBEDTLS_OID_ORG_RSA_DATA_SECURITY +#define OID_ORG_TELETRUST MBEDTLS_OID_ORG_TELETRUST +#define OID_PKCS MBEDTLS_OID_PKCS +#define OID_PKCS1 MBEDTLS_OID_PKCS1 +#define OID_PKCS12 MBEDTLS_OID_PKCS12 +#define OID_PKCS12_PBE MBEDTLS_OID_PKCS12_PBE +#define OID_PKCS12_PBE_SHA1_DES2_EDE_CBC MBEDTLS_OID_PKCS12_PBE_SHA1_DES2_EDE_CBC +#define OID_PKCS12_PBE_SHA1_DES3_EDE_CBC MBEDTLS_OID_PKCS12_PBE_SHA1_DES3_EDE_CBC +#define OID_PKCS12_PBE_SHA1_RC2_128_CBC MBEDTLS_OID_PKCS12_PBE_SHA1_RC2_128_CBC +#define OID_PKCS12_PBE_SHA1_RC2_40_CBC MBEDTLS_OID_PKCS12_PBE_SHA1_RC2_40_CBC +#define OID_PKCS12_PBE_SHA1_RC4_128 MBEDTLS_OID_PKCS12_PBE_SHA1_RC4_128 +#define OID_PKCS12_PBE_SHA1_RC4_40 MBEDTLS_OID_PKCS12_PBE_SHA1_RC4_40 +#define OID_PKCS1_MD2 MBEDTLS_OID_PKCS1_MD2 +#define OID_PKCS1_MD4 MBEDTLS_OID_PKCS1_MD4 +#define OID_PKCS1_MD5 MBEDTLS_OID_PKCS1_MD5 +#define OID_PKCS1_RSA MBEDTLS_OID_PKCS1_RSA +#define OID_PKCS1_SHA1 MBEDTLS_OID_PKCS1_SHA1 +#define OID_PKCS1_SHA224 MBEDTLS_OID_PKCS1_SHA224 +#define OID_PKCS1_SHA256 MBEDTLS_OID_PKCS1_SHA256 +#define OID_PKCS1_SHA384 MBEDTLS_OID_PKCS1_SHA384 +#define OID_PKCS1_SHA512 MBEDTLS_OID_PKCS1_SHA512 +#define OID_PKCS5 MBEDTLS_OID_PKCS5 +#define OID_PKCS5_PBES2 MBEDTLS_OID_PKCS5_PBES2 +#define OID_PKCS5_PBE_MD2_DES_CBC MBEDTLS_OID_PKCS5_PBE_MD2_DES_CBC +#define OID_PKCS5_PBE_MD2_RC2_CBC MBEDTLS_OID_PKCS5_PBE_MD2_RC2_CBC +#define OID_PKCS5_PBE_MD5_DES_CBC MBEDTLS_OID_PKCS5_PBE_MD5_DES_CBC +#define OID_PKCS5_PBE_MD5_RC2_CBC MBEDTLS_OID_PKCS5_PBE_MD5_RC2_CBC +#define OID_PKCS5_PBE_SHA1_DES_CBC MBEDTLS_OID_PKCS5_PBE_SHA1_DES_CBC +#define OID_PKCS5_PBE_SHA1_RC2_CBC MBEDTLS_OID_PKCS5_PBE_SHA1_RC2_CBC +#define OID_PKCS5_PBKDF2 MBEDTLS_OID_PKCS5_PBKDF2 +#define OID_PKCS5_PBMAC1 MBEDTLS_OID_PKCS5_PBMAC1 +#define OID_PKCS9 MBEDTLS_OID_PKCS9 +#define OID_PKCS9_CSR_EXT_REQ MBEDTLS_OID_PKCS9_CSR_EXT_REQ +#define OID_PKCS9_EMAIL MBEDTLS_OID_PKCS9_EMAIL +#define OID_PKIX MBEDTLS_OID_PKIX +#define OID_POLICY_CONSTRAINTS MBEDTLS_OID_POLICY_CONSTRAINTS +#define OID_POLICY_MAPPINGS MBEDTLS_OID_POLICY_MAPPINGS +#define OID_PRIVATE_KEY_USAGE_PERIOD MBEDTLS_OID_PRIVATE_KEY_USAGE_PERIOD +#define OID_RSASSA_PSS MBEDTLS_OID_RSASSA_PSS +#define OID_RSA_COMPANY MBEDTLS_OID_RSA_COMPANY +#define OID_RSA_SHA_OBS MBEDTLS_OID_RSA_SHA_OBS +#define OID_SERVER_AUTH MBEDTLS_OID_SERVER_AUTH +#define OID_SIZE MBEDTLS_OID_SIZE +#define OID_SUBJECT_ALT_NAME MBEDTLS_OID_SUBJECT_ALT_NAME +#define OID_SUBJECT_DIRECTORY_ATTRS MBEDTLS_OID_SUBJECT_DIRECTORY_ATTRS +#define OID_SUBJECT_KEY_IDENTIFIER MBEDTLS_OID_SUBJECT_KEY_IDENTIFIER +#define OID_TELETRUST MBEDTLS_OID_TELETRUST +#define OID_TIME_STAMPING MBEDTLS_OID_TIME_STAMPING +#define PADLOCK_ACE MBEDTLS_PADLOCK_ACE +#define PADLOCK_ALIGN16 MBEDTLS_PADLOCK_ALIGN16 +#define PADLOCK_PHE MBEDTLS_PADLOCK_PHE +#define PADLOCK_PMM MBEDTLS_PADLOCK_PMM +#define PADLOCK_RNG MBEDTLS_PADLOCK_RNG +#define PKCS12_DERIVE_IV MBEDTLS_PKCS12_DERIVE_IV +#define PKCS12_DERIVE_KEY MBEDTLS_PKCS12_DERIVE_KEY +#define PKCS12_DERIVE_MAC_KEY MBEDTLS_PKCS12_DERIVE_MAC_KEY +#define PKCS12_PBE_DECRYPT MBEDTLS_PKCS12_PBE_DECRYPT +#define PKCS12_PBE_ENCRYPT MBEDTLS_PKCS12_PBE_ENCRYPT +#define PKCS5_DECRYPT MBEDTLS_PKCS5_DECRYPT +#define PKCS5_ENCRYPT MBEDTLS_PKCS5_ENCRYPT +#define POLARSSL_AESNI_AES MBEDTLS_AESNI_AES +#define POLARSSL_AESNI_CLMUL MBEDTLS_AESNI_CLMUL +#define POLARSSL_AESNI_H MBEDTLS_AESNI_H +#define POLARSSL_AES_H MBEDTLS_AES_H +#define POLARSSL_ARC4_H MBEDTLS_ARC4_H +#define POLARSSL_ASN1_H MBEDTLS_ASN1_H +#define POLARSSL_ASN1_WRITE_H MBEDTLS_ASN1_WRITE_H +#define POLARSSL_BASE64_H MBEDTLS_BASE64_H +#define POLARSSL_BIGNUM_H MBEDTLS_BIGNUM_H +#define POLARSSL_BLOWFISH_H MBEDTLS_BLOWFISH_H +#define POLARSSL_BN_MUL_H MBEDTLS_BN_MUL_H +#define POLARSSL_CAMELLIA_H MBEDTLS_CAMELLIA_H +#define POLARSSL_CCM_H MBEDTLS_CCM_H +#define POLARSSL_CERTS_H MBEDTLS_CERTS_H +#define POLARSSL_CHECK_CONFIG_H MBEDTLS_CHECK_CONFIG_H +#define POLARSSL_CIPHERSUITE_NODTLS MBEDTLS_CIPHERSUITE_NODTLS +#define POLARSSL_CIPHERSUITE_SHORT_TAG MBEDTLS_CIPHERSUITE_SHORT_TAG +#define POLARSSL_CIPHERSUITE_WEAK MBEDTLS_CIPHERSUITE_WEAK +#define POLARSSL_CIPHER_AES_128_CBC MBEDTLS_CIPHER_AES_128_CBC +#define POLARSSL_CIPHER_AES_128_CCM MBEDTLS_CIPHER_AES_128_CCM +#define POLARSSL_CIPHER_AES_128_CFB128 MBEDTLS_CIPHER_AES_128_CFB128 +#define POLARSSL_CIPHER_AES_128_CTR MBEDTLS_CIPHER_AES_128_CTR +#define POLARSSL_CIPHER_AES_128_ECB MBEDTLS_CIPHER_AES_128_ECB +#define POLARSSL_CIPHER_AES_128_GCM MBEDTLS_CIPHER_AES_128_GCM +#define POLARSSL_CIPHER_AES_192_CBC MBEDTLS_CIPHER_AES_192_CBC +#define POLARSSL_CIPHER_AES_192_CCM MBEDTLS_CIPHER_AES_192_CCM +#define POLARSSL_CIPHER_AES_192_CFB128 MBEDTLS_CIPHER_AES_192_CFB128 +#define POLARSSL_CIPHER_AES_192_CTR MBEDTLS_CIPHER_AES_192_CTR +#define POLARSSL_CIPHER_AES_192_ECB MBEDTLS_CIPHER_AES_192_ECB +#define POLARSSL_CIPHER_AES_192_GCM MBEDTLS_CIPHER_AES_192_GCM +#define POLARSSL_CIPHER_AES_256_CBC MBEDTLS_CIPHER_AES_256_CBC +#define POLARSSL_CIPHER_AES_256_CCM MBEDTLS_CIPHER_AES_256_CCM +#define POLARSSL_CIPHER_AES_256_CFB128 MBEDTLS_CIPHER_AES_256_CFB128 +#define POLARSSL_CIPHER_AES_256_CTR MBEDTLS_CIPHER_AES_256_CTR +#define POLARSSL_CIPHER_AES_256_ECB MBEDTLS_CIPHER_AES_256_ECB +#define POLARSSL_CIPHER_AES_256_GCM MBEDTLS_CIPHER_AES_256_GCM +#define POLARSSL_CIPHER_ARC4_128 MBEDTLS_CIPHER_ARC4_128 +#define POLARSSL_CIPHER_BLOWFISH_CBC MBEDTLS_CIPHER_BLOWFISH_CBC +#define POLARSSL_CIPHER_BLOWFISH_CFB64 MBEDTLS_CIPHER_BLOWFISH_CFB64 +#define POLARSSL_CIPHER_BLOWFISH_CTR MBEDTLS_CIPHER_BLOWFISH_CTR +#define POLARSSL_CIPHER_BLOWFISH_ECB MBEDTLS_CIPHER_BLOWFISH_ECB +#define POLARSSL_CIPHER_CAMELLIA_128_CBC MBEDTLS_CIPHER_CAMELLIA_128_CBC +#define POLARSSL_CIPHER_CAMELLIA_128_CCM MBEDTLS_CIPHER_CAMELLIA_128_CCM +#define POLARSSL_CIPHER_CAMELLIA_128_CFB128 MBEDTLS_CIPHER_CAMELLIA_128_CFB128 +#define POLARSSL_CIPHER_CAMELLIA_128_CTR MBEDTLS_CIPHER_CAMELLIA_128_CTR +#define POLARSSL_CIPHER_CAMELLIA_128_ECB MBEDTLS_CIPHER_CAMELLIA_128_ECB +#define POLARSSL_CIPHER_CAMELLIA_128_GCM MBEDTLS_CIPHER_CAMELLIA_128_GCM +#define POLARSSL_CIPHER_CAMELLIA_192_CBC MBEDTLS_CIPHER_CAMELLIA_192_CBC +#define POLARSSL_CIPHER_CAMELLIA_192_CCM MBEDTLS_CIPHER_CAMELLIA_192_CCM +#define POLARSSL_CIPHER_CAMELLIA_192_CFB128 MBEDTLS_CIPHER_CAMELLIA_192_CFB128 +#define POLARSSL_CIPHER_CAMELLIA_192_CTR MBEDTLS_CIPHER_CAMELLIA_192_CTR +#define POLARSSL_CIPHER_CAMELLIA_192_ECB MBEDTLS_CIPHER_CAMELLIA_192_ECB +#define POLARSSL_CIPHER_CAMELLIA_192_GCM MBEDTLS_CIPHER_CAMELLIA_192_GCM +#define POLARSSL_CIPHER_CAMELLIA_256_CBC MBEDTLS_CIPHER_CAMELLIA_256_CBC +#define POLARSSL_CIPHER_CAMELLIA_256_CCM MBEDTLS_CIPHER_CAMELLIA_256_CCM +#define POLARSSL_CIPHER_CAMELLIA_256_CFB128 MBEDTLS_CIPHER_CAMELLIA_256_CFB128 +#define POLARSSL_CIPHER_CAMELLIA_256_CTR MBEDTLS_CIPHER_CAMELLIA_256_CTR +#define POLARSSL_CIPHER_CAMELLIA_256_ECB MBEDTLS_CIPHER_CAMELLIA_256_ECB +#define POLARSSL_CIPHER_CAMELLIA_256_GCM MBEDTLS_CIPHER_CAMELLIA_256_GCM +#define POLARSSL_CIPHER_DES_CBC MBEDTLS_CIPHER_DES_CBC +#define POLARSSL_CIPHER_DES_ECB MBEDTLS_CIPHER_DES_ECB +#define POLARSSL_CIPHER_DES_EDE3_CBC MBEDTLS_CIPHER_DES_EDE3_CBC +#define POLARSSL_CIPHER_DES_EDE3_ECB MBEDTLS_CIPHER_DES_EDE3_ECB +#define POLARSSL_CIPHER_DES_EDE_CBC MBEDTLS_CIPHER_DES_EDE_CBC +#define POLARSSL_CIPHER_DES_EDE_ECB MBEDTLS_CIPHER_DES_EDE_ECB +#define POLARSSL_CIPHER_H MBEDTLS_CIPHER_H +#define POLARSSL_CIPHER_ID_3DES MBEDTLS_CIPHER_ID_3DES +#define POLARSSL_CIPHER_ID_AES MBEDTLS_CIPHER_ID_AES +#define POLARSSL_CIPHER_ID_ARC4 MBEDTLS_CIPHER_ID_ARC4 +#define POLARSSL_CIPHER_ID_BLOWFISH MBEDTLS_CIPHER_ID_BLOWFISH +#define POLARSSL_CIPHER_ID_CAMELLIA MBEDTLS_CIPHER_ID_CAMELLIA +#define POLARSSL_CIPHER_ID_DES MBEDTLS_CIPHER_ID_DES +#define POLARSSL_CIPHER_ID_NONE MBEDTLS_CIPHER_ID_NONE +#define POLARSSL_CIPHER_ID_NULL MBEDTLS_CIPHER_ID_NULL +#define POLARSSL_CIPHER_MODE_AEAD MBEDTLS_CIPHER_MODE_AEAD +#define POLARSSL_CIPHER_MODE_STREAM MBEDTLS_CIPHER_MODE_STREAM +#define POLARSSL_CIPHER_MODE_WITH_PADDING MBEDTLS_CIPHER_MODE_WITH_PADDING +#define POLARSSL_CIPHER_NONE MBEDTLS_CIPHER_NONE +#define POLARSSL_CIPHER_NULL MBEDTLS_CIPHER_NULL +#define POLARSSL_CIPHER_VARIABLE_IV_LEN MBEDTLS_CIPHER_VARIABLE_IV_LEN +#define POLARSSL_CIPHER_VARIABLE_KEY_LEN MBEDTLS_CIPHER_VARIABLE_KEY_LEN +#define POLARSSL_CIPHER_WRAP_H MBEDTLS_CIPHER_WRAP_H +#define POLARSSL_CONFIG_H MBEDTLS_CONFIG_H +#define POLARSSL_CTR_DRBG_H MBEDTLS_CTR_DRBG_H +#define POLARSSL_DEBUG_H MBEDTLS_DEBUG_H +#define POLARSSL_DECRYPT MBEDTLS_DECRYPT +#define POLARSSL_DES_H MBEDTLS_DES_H +#define POLARSSL_DHM_H MBEDTLS_DHM_H +#define POLARSSL_DHM_RFC3526_MODP_2048_G MBEDTLS_DHM_RFC3526_MODP_2048_G +#define POLARSSL_DHM_RFC3526_MODP_2048_P MBEDTLS_DHM_RFC3526_MODP_2048_P +#define POLARSSL_DHM_RFC3526_MODP_3072_G MBEDTLS_DHM_RFC3526_MODP_3072_G +#define POLARSSL_DHM_RFC3526_MODP_3072_P MBEDTLS_DHM_RFC3526_MODP_3072_P +#define POLARSSL_DHM_RFC5114_MODP_2048_G MBEDTLS_DHM_RFC5114_MODP_2048_G +#define POLARSSL_DHM_RFC5114_MODP_2048_P MBEDTLS_DHM_RFC5114_MODP_2048_P +#define POLARSSL_ECDH_H MBEDTLS_ECDH_H +#define POLARSSL_ECDH_OURS MBEDTLS_ECDH_OURS +#define POLARSSL_ECDH_THEIRS MBEDTLS_ECDH_THEIRS +#define POLARSSL_ECDSA_H MBEDTLS_ECDSA_H +#define POLARSSL_ECP_DP_BP256R1 MBEDTLS_ECP_DP_BP256R1 +#define POLARSSL_ECP_DP_BP384R1 MBEDTLS_ECP_DP_BP384R1 +#define POLARSSL_ECP_DP_BP512R1 MBEDTLS_ECP_DP_BP512R1 +#define POLARSSL_ECP_DP_M255 MBEDTLS_ECP_DP_CURVE25519 +#define POLARSSL_ECP_DP_MAX MBEDTLS_ECP_DP_MAX +#define POLARSSL_ECP_DP_NONE MBEDTLS_ECP_DP_NONE +#define POLARSSL_ECP_DP_SECP192K1 MBEDTLS_ECP_DP_SECP192K1 +#define POLARSSL_ECP_DP_SECP192R1 MBEDTLS_ECP_DP_SECP192R1 +#define POLARSSL_ECP_DP_SECP224K1 MBEDTLS_ECP_DP_SECP224K1 +#define POLARSSL_ECP_DP_SECP224R1 MBEDTLS_ECP_DP_SECP224R1 +#define POLARSSL_ECP_DP_SECP256K1 MBEDTLS_ECP_DP_SECP256K1 +#define POLARSSL_ECP_DP_SECP256R1 MBEDTLS_ECP_DP_SECP256R1 +#define POLARSSL_ECP_DP_SECP384R1 MBEDTLS_ECP_DP_SECP384R1 +#define POLARSSL_ECP_DP_SECP521R1 MBEDTLS_ECP_DP_SECP521R1 +#define POLARSSL_ECP_H MBEDTLS_ECP_H +#define POLARSSL_ECP_MAX_BYTES MBEDTLS_ECP_MAX_BYTES +#define POLARSSL_ECP_MAX_PT_LEN MBEDTLS_ECP_MAX_PT_LEN +#define POLARSSL_ECP_PF_COMPRESSED MBEDTLS_ECP_PF_COMPRESSED +#define POLARSSL_ECP_PF_UNCOMPRESSED MBEDTLS_ECP_PF_UNCOMPRESSED +#define POLARSSL_ECP_TLS_NAMED_CURVE MBEDTLS_ECP_TLS_NAMED_CURVE +#define POLARSSL_ENCRYPT MBEDTLS_ENCRYPT +#define POLARSSL_ENTROPY_H MBEDTLS_ENTROPY_H +#define POLARSSL_ENTROPY_POLL_H MBEDTLS_ENTROPY_POLL_H +#define POLARSSL_ENTROPY_SHA256_ACCUMULATOR MBEDTLS_ENTROPY_SHA256_ACCUMULATOR +#define POLARSSL_ENTROPY_SHA512_ACCUMULATOR MBEDTLS_ENTROPY_SHA512_ACCUMULATOR +#define POLARSSL_ERROR_H MBEDTLS_ERROR_H +#define POLARSSL_ERR_AES_INVALID_INPUT_LENGTH MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH +#define POLARSSL_ERR_AES_INVALID_KEY_LENGTH MBEDTLS_ERR_AES_INVALID_KEY_LENGTH +#define POLARSSL_ERR_ASN1_BUF_TOO_SMALL MBEDTLS_ERR_ASN1_BUF_TOO_SMALL +#define POLARSSL_ERR_ASN1_INVALID_DATA MBEDTLS_ERR_ASN1_INVALID_DATA +#define POLARSSL_ERR_ASN1_INVALID_LENGTH MBEDTLS_ERR_ASN1_INVALID_LENGTH +#define POLARSSL_ERR_ASN1_LENGTH_MISMATCH MBEDTLS_ERR_ASN1_LENGTH_MISMATCH +#define POLARSSL_ERR_ASN1_MALLOC_FAILED MBEDTLS_ERR_ASN1_ALLOC_FAILED +#define POLARSSL_ERR_ASN1_OUT_OF_DATA MBEDTLS_ERR_ASN1_OUT_OF_DATA +#define POLARSSL_ERR_ASN1_UNEXPECTED_TAG MBEDTLS_ERR_ASN1_UNEXPECTED_TAG +#define POLARSSL_ERR_BASE64_BUFFER_TOO_SMALL MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL +#define POLARSSL_ERR_BASE64_INVALID_CHARACTER MBEDTLS_ERR_BASE64_INVALID_CHARACTER +#define POLARSSL_ERR_BLOWFISH_INVALID_INPUT_LENGTH MBEDTLS_ERR_BLOWFISH_INVALID_INPUT_LENGTH +#define POLARSSL_ERR_BLOWFISH_INVALID_KEY_LENGTH MBEDTLS_ERR_BLOWFISH_INVALID_KEY_LENGTH +#define POLARSSL_ERR_CAMELLIA_INVALID_INPUT_LENGTH MBEDTLS_ERR_CAMELLIA_INVALID_INPUT_LENGTH +#define POLARSSL_ERR_CAMELLIA_INVALID_KEY_LENGTH MBEDTLS_ERR_CAMELLIA_INVALID_KEY_LENGTH +#define POLARSSL_ERR_CCM_AUTH_FAILED MBEDTLS_ERR_CCM_AUTH_FAILED +#define POLARSSL_ERR_CCM_BAD_INPUT MBEDTLS_ERR_CCM_BAD_INPUT +#define POLARSSL_ERR_CIPHER_ALLOC_FAILED MBEDTLS_ERR_CIPHER_ALLOC_FAILED +#define POLARSSL_ERR_CIPHER_AUTH_FAILED MBEDTLS_ERR_CIPHER_AUTH_FAILED +#define POLARSSL_ERR_CIPHER_BAD_INPUT_DATA MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA +#define POLARSSL_ERR_CIPHER_FEATURE_UNAVAILABLE MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE +#define POLARSSL_ERR_CIPHER_FULL_BLOCK_EXPECTED MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED +#define POLARSSL_ERR_CIPHER_INVALID_PADDING MBEDTLS_ERR_CIPHER_INVALID_PADDING +#define POLARSSL_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED +#define POLARSSL_ERR_CTR_DRBG_FILE_IO_ERROR MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR +#define POLARSSL_ERR_CTR_DRBG_INPUT_TOO_BIG MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG +#define POLARSSL_ERR_CTR_DRBG_REQUEST_TOO_BIG MBEDTLS_ERR_CTR_DRBG_REQUEST_TOO_BIG +#define POLARSSL_ERR_DES_INVALID_INPUT_LENGTH MBEDTLS_ERR_DES_INVALID_INPUT_LENGTH +#define POLARSSL_ERR_DHM_BAD_INPUT_DATA MBEDTLS_ERR_DHM_BAD_INPUT_DATA +#define POLARSSL_ERR_DHM_CALC_SECRET_FAILED MBEDTLS_ERR_DHM_CALC_SECRET_FAILED +#define POLARSSL_ERR_DHM_FILE_IO_ERROR MBEDTLS_ERR_DHM_FILE_IO_ERROR +#define POLARSSL_ERR_DHM_INVALID_FORMAT MBEDTLS_ERR_DHM_INVALID_FORMAT +#define POLARSSL_ERR_DHM_MAKE_PARAMS_FAILED MBEDTLS_ERR_DHM_MAKE_PARAMS_FAILED +#define POLARSSL_ERR_DHM_MAKE_PUBLIC_FAILED MBEDTLS_ERR_DHM_MAKE_PUBLIC_FAILED +#define POLARSSL_ERR_DHM_MALLOC_FAILED MBEDTLS_ERR_DHM_ALLOC_FAILED +#define POLARSSL_ERR_DHM_READ_PARAMS_FAILED MBEDTLS_ERR_DHM_READ_PARAMS_FAILED +#define POLARSSL_ERR_DHM_READ_PUBLIC_FAILED MBEDTLS_ERR_DHM_READ_PUBLIC_FAILED +#define POLARSSL_ERR_ECP_BAD_INPUT_DATA MBEDTLS_ERR_ECP_BAD_INPUT_DATA +#define POLARSSL_ERR_ECP_BUFFER_TOO_SMALL MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL +#define POLARSSL_ERR_ECP_FEATURE_UNAVAILABLE MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE +#define POLARSSL_ERR_ECP_INVALID_KEY MBEDTLS_ERR_ECP_INVALID_KEY +#define POLARSSL_ERR_ECP_MALLOC_FAILED MBEDTLS_ERR_ECP_ALLOC_FAILED +#define POLARSSL_ERR_ECP_RANDOM_FAILED MBEDTLS_ERR_ECP_RANDOM_FAILED +#define POLARSSL_ERR_ECP_SIG_LEN_MISMATCH MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH +#define POLARSSL_ERR_ECP_VERIFY_FAILED MBEDTLS_ERR_ECP_VERIFY_FAILED +#define POLARSSL_ERR_ENTROPY_FILE_IO_ERROR MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR +#define POLARSSL_ERR_ENTROPY_MAX_SOURCES MBEDTLS_ERR_ENTROPY_MAX_SOURCES +#define POLARSSL_ERR_ENTROPY_NO_SOURCES_DEFINED MBEDTLS_ERR_ENTROPY_NO_SOURCES_DEFINED +#define POLARSSL_ERR_ENTROPY_SOURCE_FAILED MBEDTLS_ERR_ENTROPY_SOURCE_FAILED +#define POLARSSL_ERR_GCM_AUTH_FAILED MBEDTLS_ERR_GCM_AUTH_FAILED +#define POLARSSL_ERR_GCM_BAD_INPUT MBEDTLS_ERR_GCM_BAD_INPUT +#define POLARSSL_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED +#define POLARSSL_ERR_HMAC_DRBG_FILE_IO_ERROR MBEDTLS_ERR_HMAC_DRBG_FILE_IO_ERROR +#define POLARSSL_ERR_HMAC_DRBG_INPUT_TOO_BIG MBEDTLS_ERR_HMAC_DRBG_INPUT_TOO_BIG +#define POLARSSL_ERR_HMAC_DRBG_REQUEST_TOO_BIG MBEDTLS_ERR_HMAC_DRBG_REQUEST_TOO_BIG +#define POLARSSL_ERR_MD_ALLOC_FAILED MBEDTLS_ERR_MD_ALLOC_FAILED +#define POLARSSL_ERR_MD_BAD_INPUT_DATA MBEDTLS_ERR_MD_BAD_INPUT_DATA +#define POLARSSL_ERR_MD_FEATURE_UNAVAILABLE MBEDTLS_ERR_MD_FEATURE_UNAVAILABLE +#define POLARSSL_ERR_MD_FILE_IO_ERROR MBEDTLS_ERR_MD_FILE_IO_ERROR +#define POLARSSL_ERR_MPI_BAD_INPUT_DATA MBEDTLS_ERR_MPI_BAD_INPUT_DATA +#define POLARSSL_ERR_MPI_BUFFER_TOO_SMALL MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL +#define POLARSSL_ERR_MPI_DIVISION_BY_ZERO MBEDTLS_ERR_MPI_DIVISION_BY_ZERO +#define POLARSSL_ERR_MPI_FILE_IO_ERROR MBEDTLS_ERR_MPI_FILE_IO_ERROR +#define POLARSSL_ERR_MPI_INVALID_CHARACTER MBEDTLS_ERR_MPI_INVALID_CHARACTER +#define POLARSSL_ERR_MPI_MALLOC_FAILED MBEDTLS_ERR_MPI_ALLOC_FAILED +#define POLARSSL_ERR_MPI_NEGATIVE_VALUE MBEDTLS_ERR_MPI_NEGATIVE_VALUE +#define POLARSSL_ERR_MPI_NOT_ACCEPTABLE MBEDTLS_ERR_MPI_NOT_ACCEPTABLE +#define POLARSSL_ERR_NET_ACCEPT_FAILED MBEDTLS_ERR_NET_ACCEPT_FAILED +#define POLARSSL_ERR_NET_BIND_FAILED MBEDTLS_ERR_NET_BIND_FAILED +#define POLARSSL_ERR_NET_CONNECT_FAILED MBEDTLS_ERR_NET_CONNECT_FAILED +#define POLARSSL_ERR_NET_CONN_RESET MBEDTLS_ERR_NET_CONN_RESET +#define POLARSSL_ERR_NET_LISTEN_FAILED MBEDTLS_ERR_NET_LISTEN_FAILED +#define POLARSSL_ERR_NET_RECV_FAILED MBEDTLS_ERR_NET_RECV_FAILED +#define POLARSSL_ERR_NET_SEND_FAILED MBEDTLS_ERR_NET_SEND_FAILED +#define POLARSSL_ERR_NET_SOCKET_FAILED MBEDTLS_ERR_NET_SOCKET_FAILED +#define POLARSSL_ERR_NET_TIMEOUT MBEDTLS_ERR_SSL_TIMEOUT +#define POLARSSL_ERR_NET_UNKNOWN_HOST MBEDTLS_ERR_NET_UNKNOWN_HOST +#define POLARSSL_ERR_NET_WANT_READ MBEDTLS_ERR_SSL_WANT_READ +#define POLARSSL_ERR_NET_WANT_WRITE MBEDTLS_ERR_SSL_WANT_WRITE +#define POLARSSL_ERR_OID_BUF_TOO_SMALL MBEDTLS_ERR_OID_BUF_TOO_SMALL +#define POLARSSL_ERR_OID_NOT_FOUND MBEDTLS_ERR_OID_NOT_FOUND +#define POLARSSL_ERR_PADLOCK_DATA_MISALIGNED MBEDTLS_ERR_PADLOCK_DATA_MISALIGNED +#define POLARSSL_ERR_PEM_BAD_INPUT_DATA MBEDTLS_ERR_PEM_BAD_INPUT_DATA +#define POLARSSL_ERR_PEM_FEATURE_UNAVAILABLE MBEDTLS_ERR_PEM_FEATURE_UNAVAILABLE +#define POLARSSL_ERR_PEM_INVALID_DATA MBEDTLS_ERR_PEM_INVALID_DATA +#define POLARSSL_ERR_PEM_INVALID_ENC_IV MBEDTLS_ERR_PEM_INVALID_ENC_IV +#define POLARSSL_ERR_PEM_MALLOC_FAILED MBEDTLS_ERR_PEM_ALLOC_FAILED +#define POLARSSL_ERR_PEM_NO_HEADER_FOOTER_PRESENT MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT +#define POLARSSL_ERR_PEM_PASSWORD_MISMATCH MBEDTLS_ERR_PEM_PASSWORD_MISMATCH +#define POLARSSL_ERR_PEM_PASSWORD_REQUIRED MBEDTLS_ERR_PEM_PASSWORD_REQUIRED +#define POLARSSL_ERR_PEM_UNKNOWN_ENC_ALG MBEDTLS_ERR_PEM_UNKNOWN_ENC_ALG +#define POLARSSL_ERR_PKCS12_BAD_INPUT_DATA MBEDTLS_ERR_PKCS12_BAD_INPUT_DATA +#define POLARSSL_ERR_PKCS12_FEATURE_UNAVAILABLE MBEDTLS_ERR_PKCS12_FEATURE_UNAVAILABLE +#define POLARSSL_ERR_PKCS12_PASSWORD_MISMATCH MBEDTLS_ERR_PKCS12_PASSWORD_MISMATCH +#define POLARSSL_ERR_PKCS12_PBE_INVALID_FORMAT MBEDTLS_ERR_PKCS12_PBE_INVALID_FORMAT +#define POLARSSL_ERR_PKCS5_BAD_INPUT_DATA MBEDTLS_ERR_PKCS5_BAD_INPUT_DATA +#define POLARSSL_ERR_PKCS5_FEATURE_UNAVAILABLE MBEDTLS_ERR_PKCS5_FEATURE_UNAVAILABLE +#define POLARSSL_ERR_PKCS5_INVALID_FORMAT MBEDTLS_ERR_PKCS5_INVALID_FORMAT +#define POLARSSL_ERR_PKCS5_PASSWORD_MISMATCH MBEDTLS_ERR_PKCS5_PASSWORD_MISMATCH +#define POLARSSL_ERR_PK_BAD_INPUT_DATA MBEDTLS_ERR_PK_BAD_INPUT_DATA +#define POLARSSL_ERR_PK_FEATURE_UNAVAILABLE MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE +#define POLARSSL_ERR_PK_FILE_IO_ERROR MBEDTLS_ERR_PK_FILE_IO_ERROR +#define POLARSSL_ERR_PK_INVALID_ALG MBEDTLS_ERR_PK_INVALID_ALG +#define POLARSSL_ERR_PK_INVALID_PUBKEY MBEDTLS_ERR_PK_INVALID_PUBKEY +#define POLARSSL_ERR_PK_KEY_INVALID_FORMAT MBEDTLS_ERR_PK_KEY_INVALID_FORMAT +#define POLARSSL_ERR_PK_KEY_INVALID_VERSION MBEDTLS_ERR_PK_KEY_INVALID_VERSION +#define POLARSSL_ERR_PK_MALLOC_FAILED MBEDTLS_ERR_PK_ALLOC_FAILED +#define POLARSSL_ERR_PK_PASSWORD_MISMATCH MBEDTLS_ERR_PK_PASSWORD_MISMATCH +#define POLARSSL_ERR_PK_PASSWORD_REQUIRED MBEDTLS_ERR_PK_PASSWORD_REQUIRED +#define POLARSSL_ERR_PK_SIG_LEN_MISMATCH MBEDTLS_ERR_PK_SIG_LEN_MISMATCH +#define POLARSSL_ERR_PK_TYPE_MISMATCH MBEDTLS_ERR_PK_TYPE_MISMATCH +#define POLARSSL_ERR_PK_UNKNOWN_NAMED_CURVE MBEDTLS_ERR_PK_UNKNOWN_NAMED_CURVE +#define POLARSSL_ERR_PK_UNKNOWN_PK_ALG MBEDTLS_ERR_PK_UNKNOWN_PK_ALG +#define POLARSSL_ERR_RSA_BAD_INPUT_DATA MBEDTLS_ERR_RSA_BAD_INPUT_DATA +#define POLARSSL_ERR_RSA_INVALID_PADDING MBEDTLS_ERR_RSA_INVALID_PADDING +#define POLARSSL_ERR_RSA_KEY_CHECK_FAILED MBEDTLS_ERR_RSA_KEY_CHECK_FAILED +#define POLARSSL_ERR_RSA_KEY_GEN_FAILED MBEDTLS_ERR_RSA_KEY_GEN_FAILED +#define POLARSSL_ERR_RSA_OUTPUT_TOO_LARGE MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE +#define POLARSSL_ERR_RSA_PRIVATE_FAILED MBEDTLS_ERR_RSA_PRIVATE_FAILED +#define POLARSSL_ERR_RSA_PUBLIC_FAILED MBEDTLS_ERR_RSA_PUBLIC_FAILED +#define POLARSSL_ERR_RSA_RNG_FAILED MBEDTLS_ERR_RSA_RNG_FAILED +#define POLARSSL_ERR_RSA_VERIFY_FAILED MBEDTLS_ERR_RSA_VERIFY_FAILED +#define POLARSSL_ERR_SSL_BAD_HS_CERTIFICATE MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE +#define POLARSSL_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST +#define POLARSSL_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY +#define POLARSSL_ERR_SSL_BAD_HS_CHANGE_CIPHER_SPEC MBEDTLS_ERR_SSL_BAD_HS_CHANGE_CIPHER_SPEC +#define POLARSSL_ERR_SSL_BAD_HS_CLIENT_HELLO MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO +#define POLARSSL_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE +#define POLARSSL_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_CS MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_CS +#define POLARSSL_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_RP MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_RP +#define POLARSSL_ERR_SSL_BAD_HS_FINISHED MBEDTLS_ERR_SSL_BAD_HS_FINISHED +#define POLARSSL_ERR_SSL_BAD_HS_NEW_SESSION_TICKET MBEDTLS_ERR_SSL_BAD_HS_NEW_SESSION_TICKET +#define POLARSSL_ERR_SSL_BAD_HS_PROTOCOL_VERSION MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION +#define POLARSSL_ERR_SSL_BAD_HS_SERVER_HELLO MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO +#define POLARSSL_ERR_SSL_BAD_HS_SERVER_HELLO_DONE MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO_DONE +#define POLARSSL_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE +#define POLARSSL_ERR_SSL_BAD_INPUT_DATA MBEDTLS_ERR_SSL_BAD_INPUT_DATA +#define POLARSSL_ERR_SSL_BUFFER_TOO_SMALL MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL +#define POLARSSL_ERR_SSL_CA_CHAIN_REQUIRED MBEDTLS_ERR_SSL_CA_CHAIN_REQUIRED +#define POLARSSL_ERR_SSL_CERTIFICATE_REQUIRED MBEDTLS_ERR_SSL_CERTIFICATE_REQUIRED +#define POLARSSL_ERR_SSL_CERTIFICATE_TOO_LARGE MBEDTLS_ERR_SSL_CERTIFICATE_TOO_LARGE +#define POLARSSL_ERR_SSL_COMPRESSION_FAILED MBEDTLS_ERR_SSL_COMPRESSION_FAILED +#define POLARSSL_ERR_SSL_CONN_EOF MBEDTLS_ERR_SSL_CONN_EOF +#define POLARSSL_ERR_SSL_COUNTER_WRAPPING MBEDTLS_ERR_SSL_COUNTER_WRAPPING +#define POLARSSL_ERR_SSL_FATAL_ALERT_MESSAGE MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE +#define POLARSSL_ERR_SSL_FEATURE_UNAVAILABLE MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE +#define POLARSSL_ERR_SSL_HELLO_VERIFY_REQUIRED MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED +#define POLARSSL_ERR_SSL_HW_ACCEL_FAILED MBEDTLS_ERR_SSL_HW_ACCEL_FAILED +#define POLARSSL_ERR_SSL_HW_ACCEL_FALLTHROUGH MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH +#define POLARSSL_ERR_SSL_INTERNAL_ERROR MBEDTLS_ERR_SSL_INTERNAL_ERROR +#define POLARSSL_ERR_SSL_INVALID_MAC MBEDTLS_ERR_SSL_INVALID_MAC +#define POLARSSL_ERR_SSL_INVALID_RECORD MBEDTLS_ERR_SSL_INVALID_RECORD +#define POLARSSL_ERR_SSL_MALLOC_FAILED MBEDTLS_ERR_SSL_ALLOC_FAILED +#define POLARSSL_ERR_SSL_NO_CIPHER_CHOSEN MBEDTLS_ERR_SSL_NO_CIPHER_CHOSEN +#define POLARSSL_ERR_SSL_NO_CLIENT_CERTIFICATE MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE +#define POLARSSL_ERR_SSL_NO_RNG MBEDTLS_ERR_SSL_NO_RNG +#define POLARSSL_ERR_SSL_NO_USABLE_CIPHERSUITE MBEDTLS_ERR_SSL_NO_USABLE_CIPHERSUITE +#define POLARSSL_ERR_SSL_PEER_CLOSE_NOTIFY MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY +#define POLARSSL_ERR_SSL_PEER_VERIFY_FAILED MBEDTLS_ERR_SSL_PEER_VERIFY_FAILED +#define POLARSSL_ERR_SSL_PK_TYPE_MISMATCH MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH +#define POLARSSL_ERR_SSL_PRIVATE_KEY_REQUIRED MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED +#define POLARSSL_ERR_SSL_SESSION_TICKET_EXPIRED MBEDTLS_ERR_SSL_SESSION_TICKET_EXPIRED +#define POLARSSL_ERR_SSL_UNEXPECTED_MESSAGE MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE +#define POLARSSL_ERR_SSL_UNKNOWN_CIPHER MBEDTLS_ERR_SSL_UNKNOWN_CIPHER +#define POLARSSL_ERR_SSL_UNKNOWN_IDENTITY MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY +#define POLARSSL_ERR_SSL_WAITING_SERVER_HELLO_RENEGO MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO +#define POLARSSL_ERR_THREADING_BAD_INPUT_DATA MBEDTLS_ERR_THREADING_BAD_INPUT_DATA +#define POLARSSL_ERR_THREADING_FEATURE_UNAVAILABLE MBEDTLS_ERR_THREADING_FEATURE_UNAVAILABLE +#define POLARSSL_ERR_THREADING_MUTEX_ERROR MBEDTLS_ERR_THREADING_MUTEX_ERROR +#define POLARSSL_ERR_X509_BAD_INPUT_DATA MBEDTLS_ERR_X509_BAD_INPUT_DATA +#define POLARSSL_ERR_X509_CERT_UNKNOWN_FORMAT MBEDTLS_ERR_X509_CERT_UNKNOWN_FORMAT +#define POLARSSL_ERR_X509_CERT_VERIFY_FAILED MBEDTLS_ERR_X509_CERT_VERIFY_FAILED +#define POLARSSL_ERR_X509_FEATURE_UNAVAILABLE MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE +#define POLARSSL_ERR_X509_FILE_IO_ERROR MBEDTLS_ERR_X509_FILE_IO_ERROR +#define POLARSSL_ERR_X509_INVALID_ALG MBEDTLS_ERR_X509_INVALID_ALG +#define POLARSSL_ERR_X509_INVALID_DATE MBEDTLS_ERR_X509_INVALID_DATE +#define POLARSSL_ERR_X509_INVALID_EXTENSIONS MBEDTLS_ERR_X509_INVALID_EXTENSIONS +#define POLARSSL_ERR_X509_INVALID_FORMAT MBEDTLS_ERR_X509_INVALID_FORMAT +#define POLARSSL_ERR_X509_INVALID_NAME MBEDTLS_ERR_X509_INVALID_NAME +#define POLARSSL_ERR_X509_INVALID_SERIAL MBEDTLS_ERR_X509_INVALID_SERIAL +#define POLARSSL_ERR_X509_INVALID_SIGNATURE MBEDTLS_ERR_X509_INVALID_SIGNATURE +#define POLARSSL_ERR_X509_INVALID_VERSION MBEDTLS_ERR_X509_INVALID_VERSION +#define POLARSSL_ERR_X509_MALLOC_FAILED MBEDTLS_ERR_X509_ALLOC_FAILED +#define POLARSSL_ERR_X509_SIG_MISMATCH MBEDTLS_ERR_X509_SIG_MISMATCH +#define POLARSSL_ERR_X509_UNKNOWN_OID MBEDTLS_ERR_X509_UNKNOWN_OID +#define POLARSSL_ERR_X509_UNKNOWN_SIG_ALG MBEDTLS_ERR_X509_UNKNOWN_SIG_ALG +#define POLARSSL_ERR_X509_UNKNOWN_VERSION MBEDTLS_ERR_X509_UNKNOWN_VERSION +#define POLARSSL_ERR_XTEA_INVALID_INPUT_LENGTH MBEDTLS_ERR_XTEA_INVALID_INPUT_LENGTH +#define POLARSSL_GCM_H MBEDTLS_GCM_H +#define POLARSSL_HAVEGE_H MBEDTLS_HAVEGE_H +#define POLARSSL_HAVE_INT32 MBEDTLS_HAVE_INT32 +#define POLARSSL_HAVE_INT64 MBEDTLS_HAVE_INT64 +#define POLARSSL_HAVE_UDBL MBEDTLS_HAVE_UDBL +#define POLARSSL_HAVE_X86 MBEDTLS_HAVE_X86 +#define POLARSSL_HAVE_X86_64 MBEDTLS_HAVE_X86_64 +#define POLARSSL_HMAC_DRBG_H MBEDTLS_HMAC_DRBG_H +#define POLARSSL_HMAC_DRBG_PR_OFF MBEDTLS_HMAC_DRBG_PR_OFF +#define POLARSSL_HMAC_DRBG_PR_ON MBEDTLS_HMAC_DRBG_PR_ON +#define POLARSSL_KEY_EXCHANGE_DHE_PSK MBEDTLS_KEY_EXCHANGE_DHE_PSK +#define POLARSSL_KEY_EXCHANGE_DHE_RSA MBEDTLS_KEY_EXCHANGE_DHE_RSA +#define POLARSSL_KEY_EXCHANGE_ECDHE_ECDSA MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA +#define POLARSSL_KEY_EXCHANGE_ECDHE_PSK MBEDTLS_KEY_EXCHANGE_ECDHE_PSK +#define POLARSSL_KEY_EXCHANGE_ECDHE_RSA MBEDTLS_KEY_EXCHANGE_ECDHE_RSA +#define POLARSSL_KEY_EXCHANGE_ECDH_ECDSA MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA +#define POLARSSL_KEY_EXCHANGE_ECDH_RSA MBEDTLS_KEY_EXCHANGE_ECDH_RSA +#define POLARSSL_KEY_EXCHANGE_NONE MBEDTLS_KEY_EXCHANGE_NONE +#define POLARSSL_KEY_EXCHANGE_PSK MBEDTLS_KEY_EXCHANGE_PSK +#define POLARSSL_KEY_EXCHANGE_RSA MBEDTLS_KEY_EXCHANGE_RSA +#define POLARSSL_KEY_EXCHANGE_RSA_PSK MBEDTLS_KEY_EXCHANGE_RSA_PSK +#define POLARSSL_KEY_EXCHANGE__SOME__ECDHE_ENABLED MBEDTLS_KEY_EXCHANGE__SOME__ECDHE_ENABLED +#define POLARSSL_KEY_EXCHANGE__SOME__PSK_ENABLED MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED +#define POLARSSL_KEY_EXCHANGE__WITH_CERT__ENABLED MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED +#define POLARSSL_KEY_LENGTH_DES MBEDTLS_KEY_LENGTH_DES +#define POLARSSL_KEY_LENGTH_DES_EDE MBEDTLS_KEY_LENGTH_DES_EDE +#define POLARSSL_KEY_LENGTH_DES_EDE3 MBEDTLS_KEY_LENGTH_DES_EDE3 +#define POLARSSL_KEY_LENGTH_NONE MBEDTLS_KEY_LENGTH_NONE +#define POLARSSL_MAX_BLOCK_LENGTH MBEDTLS_MAX_BLOCK_LENGTH +#define POLARSSL_MAX_IV_LENGTH MBEDTLS_MAX_IV_LENGTH +#define POLARSSL_MD2_H MBEDTLS_MD2_H +#define POLARSSL_MD4_H MBEDTLS_MD4_H +#define POLARSSL_MD5_H MBEDTLS_MD5_H +#define POLARSSL_MD_H MBEDTLS_MD_H +#define POLARSSL_MD_MAX_SIZE MBEDTLS_MD_MAX_SIZE +#define POLARSSL_MD_MD2 MBEDTLS_MD_MD2 +#define POLARSSL_MD_MD4 MBEDTLS_MD_MD4 +#define POLARSSL_MD_MD5 MBEDTLS_MD_MD5 +#define POLARSSL_MD_NONE MBEDTLS_MD_NONE +#define POLARSSL_MD_RIPEMD160 MBEDTLS_MD_RIPEMD160 +#define POLARSSL_MD_SHA1 MBEDTLS_MD_SHA1 +#define POLARSSL_MD_SHA224 MBEDTLS_MD_SHA224 +#define POLARSSL_MD_SHA256 MBEDTLS_MD_SHA256 +#define POLARSSL_MD_SHA384 MBEDTLS_MD_SHA384 +#define POLARSSL_MD_SHA512 MBEDTLS_MD_SHA512 +#define POLARSSL_MD_WRAP_H MBEDTLS_MD_WRAP_H +#define POLARSSL_MEMORY_BUFFER_ALLOC_H MBEDTLS_MEMORY_BUFFER_ALLOC_H +#define POLARSSL_MODE_CBC MBEDTLS_MODE_CBC +#define POLARSSL_MODE_CCM MBEDTLS_MODE_CCM +#define POLARSSL_MODE_CFB MBEDTLS_MODE_CFB +#define POLARSSL_MODE_CTR MBEDTLS_MODE_CTR +#define POLARSSL_MODE_ECB MBEDTLS_MODE_ECB +#define POLARSSL_MODE_GCM MBEDTLS_MODE_GCM +#define POLARSSL_MODE_NONE MBEDTLS_MODE_NONE +#define POLARSSL_MODE_OFB MBEDTLS_MODE_OFB +#define POLARSSL_MODE_STREAM MBEDTLS_MODE_STREAM +#define POLARSSL_MPI_MAX_BITS MBEDTLS_MPI_MAX_BITS +#define POLARSSL_MPI_MAX_BITS_SCALE100 MBEDTLS_MPI_MAX_BITS_SCALE100 +#define POLARSSL_MPI_MAX_LIMBS MBEDTLS_MPI_MAX_LIMBS +#define POLARSSL_MPI_RW_BUFFER_SIZE MBEDTLS_MPI_RW_BUFFER_SIZE +#define POLARSSL_NET_H MBEDTLS_NET_SOCKETS_H +#define POLARSSL_NET_LISTEN_BACKLOG MBEDTLS_NET_LISTEN_BACKLOG +#define POLARSSL_OID_H MBEDTLS_OID_H +#define POLARSSL_OPERATION_NONE MBEDTLS_OPERATION_NONE +#define POLARSSL_PADDING_NONE MBEDTLS_PADDING_NONE +#define POLARSSL_PADDING_ONE_AND_ZEROS MBEDTLS_PADDING_ONE_AND_ZEROS +#define POLARSSL_PADDING_PKCS7 MBEDTLS_PADDING_PKCS7 +#define POLARSSL_PADDING_ZEROS MBEDTLS_PADDING_ZEROS +#define POLARSSL_PADDING_ZEROS_AND_LEN MBEDTLS_PADDING_ZEROS_AND_LEN +#define POLARSSL_PADLOCK_H MBEDTLS_PADLOCK_H +#define POLARSSL_PEM_H MBEDTLS_PEM_H +#define POLARSSL_PKCS11_H MBEDTLS_PKCS11_H +#define POLARSSL_PKCS12_H MBEDTLS_PKCS12_H +#define POLARSSL_PKCS5_H MBEDTLS_PKCS5_H +#define POLARSSL_PK_DEBUG_ECP MBEDTLS_PK_DEBUG_ECP +#define POLARSSL_PK_DEBUG_MAX_ITEMS MBEDTLS_PK_DEBUG_MAX_ITEMS +#define POLARSSL_PK_DEBUG_MPI MBEDTLS_PK_DEBUG_MPI +#define POLARSSL_PK_DEBUG_NONE MBEDTLS_PK_DEBUG_NONE +#define POLARSSL_PK_ECDSA MBEDTLS_PK_ECDSA +#define POLARSSL_PK_ECKEY MBEDTLS_PK_ECKEY +#define POLARSSL_PK_ECKEY_DH MBEDTLS_PK_ECKEY_DH +#define POLARSSL_PK_H MBEDTLS_PK_H +#define POLARSSL_PK_NONE MBEDTLS_PK_NONE +#define POLARSSL_PK_RSA MBEDTLS_PK_RSA +#define POLARSSL_PK_RSASSA_PSS MBEDTLS_PK_RSASSA_PSS +#define POLARSSL_PK_RSA_ALT MBEDTLS_PK_RSA_ALT +#define POLARSSL_PK_WRAP_H MBEDTLS_PK_WRAP_H +#define POLARSSL_PLATFORM_H MBEDTLS_PLATFORM_H +#define POLARSSL_PREMASTER_SIZE MBEDTLS_PREMASTER_SIZE +#define POLARSSL_RIPEMD160_H MBEDTLS_RIPEMD160_H +#define POLARSSL_RSA_H MBEDTLS_RSA_H +#define POLARSSL_SHA1_H MBEDTLS_SHA1_H +#define POLARSSL_SHA256_H MBEDTLS_SHA256_H +#define POLARSSL_SHA512_H MBEDTLS_SHA512_H +#define POLARSSL_SSL_CACHE_H MBEDTLS_SSL_CACHE_H +#define POLARSSL_SSL_CIPHERSUITES_H MBEDTLS_SSL_CIPHERSUITES_H +#define POLARSSL_SSL_COOKIE_H MBEDTLS_SSL_COOKIE_H +#define POLARSSL_SSL_H MBEDTLS_SSL_H +#define POLARSSL_THREADING_H MBEDTLS_THREADING_H +#define POLARSSL_THREADING_IMPL MBEDTLS_THREADING_IMPL +#define POLARSSL_TIMING_H MBEDTLS_TIMING_H +#define POLARSSL_VERSION_H MBEDTLS_VERSION_H +#define POLARSSL_VERSION_MAJOR MBEDTLS_VERSION_MAJOR +#define POLARSSL_VERSION_MINOR MBEDTLS_VERSION_MINOR +#define POLARSSL_VERSION_NUMBER MBEDTLS_VERSION_NUMBER +#define POLARSSL_VERSION_PATCH MBEDTLS_VERSION_PATCH +#define POLARSSL_VERSION_STRING MBEDTLS_VERSION_STRING +#define POLARSSL_VERSION_STRING_FULL MBEDTLS_VERSION_STRING_FULL +#define POLARSSL_X509_CRL_H MBEDTLS_X509_CRL_H +#define POLARSSL_X509_CRT_H MBEDTLS_X509_CRT_H +#define POLARSSL_X509_CSR_H MBEDTLS_X509_CSR_H +#define POLARSSL_X509_H MBEDTLS_X509_H +#define POLARSSL_XTEA_H MBEDTLS_XTEA_H +#define RSA_CRYPT MBEDTLS_RSA_CRYPT +#define RSA_PKCS_V15 MBEDTLS_RSA_PKCS_V15 +#define RSA_PKCS_V21 MBEDTLS_RSA_PKCS_V21 +#define RSA_PRIVATE MBEDTLS_RSA_PRIVATE +#define RSA_PUBLIC MBEDTLS_RSA_PUBLIC +#define RSA_SALT_LEN_ANY MBEDTLS_RSA_SALT_LEN_ANY +#define RSA_SIGN MBEDTLS_RSA_SIGN +#define SSL_ALERT_LEVEL_FATAL MBEDTLS_SSL_ALERT_LEVEL_FATAL +#define SSL_ALERT_LEVEL_WARNING MBEDTLS_SSL_ALERT_LEVEL_WARNING +#define SSL_ALERT_MSG_ACCESS_DENIED MBEDTLS_SSL_ALERT_MSG_ACCESS_DENIED +#define SSL_ALERT_MSG_BAD_CERT MBEDTLS_SSL_ALERT_MSG_BAD_CERT +#define SSL_ALERT_MSG_BAD_RECORD_MAC MBEDTLS_SSL_ALERT_MSG_BAD_RECORD_MAC +#define SSL_ALERT_MSG_CERT_EXPIRED MBEDTLS_SSL_ALERT_MSG_CERT_EXPIRED +#define SSL_ALERT_MSG_CERT_REVOKED MBEDTLS_SSL_ALERT_MSG_CERT_REVOKED +#define SSL_ALERT_MSG_CERT_UNKNOWN MBEDTLS_SSL_ALERT_MSG_CERT_UNKNOWN +#define SSL_ALERT_MSG_CLOSE_NOTIFY MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY +#define SSL_ALERT_MSG_DECODE_ERROR MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR +#define SSL_ALERT_MSG_DECOMPRESSION_FAILURE MBEDTLS_SSL_ALERT_MSG_DECOMPRESSION_FAILURE +#define SSL_ALERT_MSG_DECRYPTION_FAILED MBEDTLS_SSL_ALERT_MSG_DECRYPTION_FAILED +#define SSL_ALERT_MSG_DECRYPT_ERROR MBEDTLS_SSL_ALERT_MSG_DECRYPT_ERROR +#define SSL_ALERT_MSG_EXPORT_RESTRICTION MBEDTLS_SSL_ALERT_MSG_EXPORT_RESTRICTION +#define SSL_ALERT_MSG_HANDSHAKE_FAILURE MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE +#define SSL_ALERT_MSG_ILLEGAL_PARAMETER MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER +#define SSL_ALERT_MSG_INAPROPRIATE_FALLBACK MBEDTLS_SSL_ALERT_MSG_INAPROPRIATE_FALLBACK +#define SSL_ALERT_MSG_INSUFFICIENT_SECURITY MBEDTLS_SSL_ALERT_MSG_INSUFFICIENT_SECURITY +#define SSL_ALERT_MSG_INTERNAL_ERROR MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR +#define SSL_ALERT_MSG_NO_APPLICATION_PROTOCOL MBEDTLS_SSL_ALERT_MSG_NO_APPLICATION_PROTOCOL +#define SSL_ALERT_MSG_NO_CERT MBEDTLS_SSL_ALERT_MSG_NO_CERT +#define SSL_ALERT_MSG_NO_RENEGOTIATION MBEDTLS_SSL_ALERT_MSG_NO_RENEGOTIATION +#define SSL_ALERT_MSG_PROTOCOL_VERSION MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION +#define SSL_ALERT_MSG_RECORD_OVERFLOW MBEDTLS_SSL_ALERT_MSG_RECORD_OVERFLOW +#define SSL_ALERT_MSG_UNEXPECTED_MESSAGE MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE +#define SSL_ALERT_MSG_UNKNOWN_CA MBEDTLS_SSL_ALERT_MSG_UNKNOWN_CA +#define SSL_ALERT_MSG_UNKNOWN_PSK_IDENTITY MBEDTLS_SSL_ALERT_MSG_UNKNOWN_PSK_IDENTITY +#define SSL_ALERT_MSG_UNRECOGNIZED_NAME MBEDTLS_SSL_ALERT_MSG_UNRECOGNIZED_NAME +#define SSL_ALERT_MSG_UNSUPPORTED_CERT MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT +#define SSL_ALERT_MSG_UNSUPPORTED_EXT MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_EXT +#define SSL_ALERT_MSG_USER_CANCELED MBEDTLS_SSL_ALERT_MSG_USER_CANCELED +#define SSL_ANTI_REPLAY_DISABLED MBEDTLS_SSL_ANTI_REPLAY_DISABLED +#define SSL_ANTI_REPLAY_ENABLED MBEDTLS_SSL_ANTI_REPLAY_ENABLED +#define SSL_ARC4_DISABLED MBEDTLS_SSL_ARC4_DISABLED +#define SSL_ARC4_ENABLED MBEDTLS_SSL_ARC4_ENABLED +#define SSL_BUFFER_LEN ( ( ( MBEDTLS_SSL_IN_BUFFER_LEN ) < ( MBEDTLS_SSL_OUT_BUFFER_LEN ) ) \ + ? ( MBEDTLS_SSL_IN_BUFFER_LEN ) : ( MBEDTLS_SSL_OUT_BUFFER_LEN ) ) +#define SSL_CACHE_DEFAULT_MAX_ENTRIES MBEDTLS_SSL_CACHE_DEFAULT_MAX_ENTRIES +#define SSL_CACHE_DEFAULT_TIMEOUT MBEDTLS_SSL_CACHE_DEFAULT_TIMEOUT +#define SSL_CBC_RECORD_SPLITTING_DISABLED MBEDTLS_SSL_CBC_RECORD_SPLITTING_DISABLED +#define SSL_CBC_RECORD_SPLITTING_ENABLED MBEDTLS_SSL_CBC_RECORD_SPLITTING_ENABLED +#define SSL_CERTIFICATE_REQUEST MBEDTLS_SSL_CERTIFICATE_REQUEST +#define SSL_CERTIFICATE_VERIFY MBEDTLS_SSL_CERTIFICATE_VERIFY +#define SSL_CERT_TYPE_ECDSA_SIGN MBEDTLS_SSL_CERT_TYPE_ECDSA_SIGN +#define SSL_CERT_TYPE_RSA_SIGN MBEDTLS_SSL_CERT_TYPE_RSA_SIGN +#define SSL_CHANNEL_INBOUND MBEDTLS_SSL_CHANNEL_INBOUND +#define SSL_CHANNEL_OUTBOUND MBEDTLS_SSL_CHANNEL_OUTBOUND +#define SSL_CIPHERSUITES MBEDTLS_SSL_CIPHERSUITES +#define SSL_CLIENT_CERTIFICATE MBEDTLS_SSL_CLIENT_CERTIFICATE +#define SSL_CLIENT_CHANGE_CIPHER_SPEC MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC +#define SSL_CLIENT_FINISHED MBEDTLS_SSL_CLIENT_FINISHED +#define SSL_CLIENT_HELLO MBEDTLS_SSL_CLIENT_HELLO +#define SSL_CLIENT_KEY_EXCHANGE MBEDTLS_SSL_CLIENT_KEY_EXCHANGE +#define SSL_COMPRESSION_ADD MBEDTLS_SSL_COMPRESSION_ADD +#define SSL_COMPRESS_DEFLATE MBEDTLS_SSL_COMPRESS_DEFLATE +#define SSL_COMPRESS_NULL MBEDTLS_SSL_COMPRESS_NULL +#define SSL_DEBUG_BUF MBEDTLS_SSL_DEBUG_BUF +#define SSL_DEBUG_CRT MBEDTLS_SSL_DEBUG_CRT +#define SSL_DEBUG_ECP MBEDTLS_SSL_DEBUG_ECP +#define SSL_DEBUG_MPI MBEDTLS_SSL_DEBUG_MPI +#define SSL_DEBUG_MSG MBEDTLS_SSL_DEBUG_MSG +#define SSL_DEBUG_RET MBEDTLS_SSL_DEBUG_RET +#define SSL_DEFAULT_TICKET_LIFETIME MBEDTLS_SSL_DEFAULT_TICKET_LIFETIME +#define SSL_DTLS_TIMEOUT_DFL_MAX MBEDTLS_SSL_DTLS_TIMEOUT_DFL_MAX +#define SSL_DTLS_TIMEOUT_DFL_MIN MBEDTLS_SSL_DTLS_TIMEOUT_DFL_MIN +#define SSL_EMPTY_RENEGOTIATION_INFO MBEDTLS_SSL_EMPTY_RENEGOTIATION_INFO +#define SSL_ETM_DISABLED MBEDTLS_SSL_ETM_DISABLED +#define SSL_ETM_ENABLED MBEDTLS_SSL_ETM_ENABLED +#define SSL_EXTENDED_MS_DISABLED MBEDTLS_SSL_EXTENDED_MS_DISABLED +#define SSL_EXTENDED_MS_ENABLED MBEDTLS_SSL_EXTENDED_MS_ENABLED +#define SSL_FALLBACK_SCSV MBEDTLS_SSL_FALLBACK_SCSV +#define SSL_FLUSH_BUFFERS MBEDTLS_SSL_FLUSH_BUFFERS +#define SSL_HANDSHAKE_OVER MBEDTLS_SSL_HANDSHAKE_OVER +#define SSL_HANDSHAKE_WRAPUP MBEDTLS_SSL_HANDSHAKE_WRAPUP +#define SSL_HASH_MD5 MBEDTLS_SSL_HASH_MD5 +#define SSL_HASH_NONE MBEDTLS_SSL_HASH_NONE +#define SSL_HASH_SHA1 MBEDTLS_SSL_HASH_SHA1 +#define SSL_HASH_SHA224 MBEDTLS_SSL_HASH_SHA224 +#define SSL_HASH_SHA256 MBEDTLS_SSL_HASH_SHA256 +#define SSL_HASH_SHA384 MBEDTLS_SSL_HASH_SHA384 +#define SSL_HASH_SHA512 MBEDTLS_SSL_HASH_SHA512 +#define SSL_HELLO_REQUEST MBEDTLS_SSL_HELLO_REQUEST +#define SSL_HS_CERTIFICATE MBEDTLS_SSL_HS_CERTIFICATE +#define SSL_HS_CERTIFICATE_REQUEST MBEDTLS_SSL_HS_CERTIFICATE_REQUEST +#define SSL_HS_CERTIFICATE_VERIFY MBEDTLS_SSL_HS_CERTIFICATE_VERIFY +#define SSL_HS_CLIENT_HELLO MBEDTLS_SSL_HS_CLIENT_HELLO +#define SSL_HS_CLIENT_KEY_EXCHANGE MBEDTLS_SSL_HS_CLIENT_KEY_EXCHANGE +#define SSL_HS_FINISHED MBEDTLS_SSL_HS_FINISHED +#define SSL_HS_HELLO_REQUEST MBEDTLS_SSL_HS_HELLO_REQUEST +#define SSL_HS_HELLO_VERIFY_REQUEST MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST +#define SSL_HS_NEW_SESSION_TICKET MBEDTLS_SSL_HS_NEW_SESSION_TICKET +#define SSL_HS_SERVER_HELLO MBEDTLS_SSL_HS_SERVER_HELLO +#define SSL_HS_SERVER_HELLO_DONE MBEDTLS_SSL_HS_SERVER_HELLO_DONE +#define SSL_HS_SERVER_KEY_EXCHANGE MBEDTLS_SSL_HS_SERVER_KEY_EXCHANGE +#define SSL_INITIAL_HANDSHAKE MBEDTLS_SSL_INITIAL_HANDSHAKE +#define SSL_IS_CLIENT MBEDTLS_SSL_IS_CLIENT +#define SSL_IS_FALLBACK MBEDTLS_SSL_IS_FALLBACK +#define SSL_IS_NOT_FALLBACK MBEDTLS_SSL_IS_NOT_FALLBACK +#define SSL_IS_SERVER MBEDTLS_SSL_IS_SERVER +#define SSL_LEGACY_ALLOW_RENEGOTIATION MBEDTLS_SSL_LEGACY_ALLOW_RENEGOTIATION +#define SSL_LEGACY_BREAK_HANDSHAKE MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE +#define SSL_LEGACY_NO_RENEGOTIATION MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION +#define SSL_LEGACY_RENEGOTIATION MBEDTLS_SSL_LEGACY_RENEGOTIATION +#define SSL_MAC_ADD MBEDTLS_SSL_MAC_ADD +#define SSL_MAJOR_VERSION_3 MBEDTLS_SSL_MAJOR_VERSION_3 +#define SSL_MAX_CONTENT_LEN MBEDTLS_SSL_MAX_CONTENT_LEN +#define SSL_MAX_FRAG_LEN_1024 MBEDTLS_SSL_MAX_FRAG_LEN_1024 +#define SSL_MAX_FRAG_LEN_2048 MBEDTLS_SSL_MAX_FRAG_LEN_2048 +#define SSL_MAX_FRAG_LEN_4096 MBEDTLS_SSL_MAX_FRAG_LEN_4096 +#define SSL_MAX_FRAG_LEN_512 MBEDTLS_SSL_MAX_FRAG_LEN_512 +#define SSL_MAX_FRAG_LEN_INVALID MBEDTLS_SSL_MAX_FRAG_LEN_INVALID +#define SSL_MAX_FRAG_LEN_NONE MBEDTLS_SSL_MAX_FRAG_LEN_NONE +#define SSL_MAX_MAJOR_VERSION MBEDTLS_SSL_MAX_MAJOR_VERSION +#define SSL_MAX_MINOR_VERSION MBEDTLS_SSL_MAX_MINOR_VERSION +#define SSL_MINOR_VERSION_0 MBEDTLS_SSL_MINOR_VERSION_0 +#define SSL_MINOR_VERSION_1 MBEDTLS_SSL_MINOR_VERSION_1 +#define SSL_MINOR_VERSION_2 MBEDTLS_SSL_MINOR_VERSION_2 +#define SSL_MINOR_VERSION_3 MBEDTLS_SSL_MINOR_VERSION_3 +#define SSL_MIN_MAJOR_VERSION MBEDTLS_SSL_MIN_MAJOR_VERSION +#define SSL_MIN_MINOR_VERSION MBEDTLS_SSL_MIN_MINOR_VERSION +#define SSL_MSG_ALERT MBEDTLS_SSL_MSG_ALERT +#define SSL_MSG_APPLICATION_DATA MBEDTLS_SSL_MSG_APPLICATION_DATA +#define SSL_MSG_CHANGE_CIPHER_SPEC MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC +#define SSL_MSG_HANDSHAKE MBEDTLS_SSL_MSG_HANDSHAKE +#define SSL_PADDING_ADD MBEDTLS_SSL_PADDING_ADD +#define SSL_RENEGOTIATION MBEDTLS_SSL_RENEGOTIATION +#define SSL_RENEGOTIATION_DISABLED MBEDTLS_SSL_RENEGOTIATION_DISABLED +#define SSL_RENEGOTIATION_DONE MBEDTLS_SSL_RENEGOTIATION_DONE +#define SSL_RENEGOTIATION_ENABLED MBEDTLS_SSL_RENEGOTIATION_ENABLED +#define SSL_RENEGOTIATION_NOT_ENFORCED MBEDTLS_SSL_RENEGOTIATION_NOT_ENFORCED +#define SSL_RENEGOTIATION_PENDING MBEDTLS_SSL_RENEGOTIATION_PENDING +#define SSL_RENEGO_MAX_RECORDS_DEFAULT MBEDTLS_SSL_RENEGO_MAX_RECORDS_DEFAULT +#define SSL_RETRANS_FINISHED MBEDTLS_SSL_RETRANS_FINISHED +#define SSL_RETRANS_PREPARING MBEDTLS_SSL_RETRANS_PREPARING +#define SSL_RETRANS_SENDING MBEDTLS_SSL_RETRANS_SENDING +#define SSL_RETRANS_WAITING MBEDTLS_SSL_RETRANS_WAITING +#define SSL_SECURE_RENEGOTIATION MBEDTLS_SSL_SECURE_RENEGOTIATION +#define SSL_SERVER_CERTIFICATE MBEDTLS_SSL_SERVER_CERTIFICATE +#define SSL_SERVER_CHANGE_CIPHER_SPEC MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC +#define SSL_SERVER_FINISHED MBEDTLS_SSL_SERVER_FINISHED +#define SSL_SERVER_HELLO MBEDTLS_SSL_SERVER_HELLO +#define SSL_SERVER_HELLO_DONE MBEDTLS_SSL_SERVER_HELLO_DONE +#define SSL_SERVER_HELLO_VERIFY_REQUEST_SENT MBEDTLS_SSL_SERVER_HELLO_VERIFY_REQUEST_SENT +#define SSL_SERVER_KEY_EXCHANGE MBEDTLS_SSL_SERVER_KEY_EXCHANGE +#define SSL_SERVER_NEW_SESSION_TICKET MBEDTLS_SSL_SERVER_NEW_SESSION_TICKET +#define SSL_SESSION_TICKETS_DISABLED MBEDTLS_SSL_SESSION_TICKETS_DISABLED +#define SSL_SESSION_TICKETS_ENABLED MBEDTLS_SSL_SESSION_TICKETS_ENABLED +#define SSL_SIG_ANON MBEDTLS_SSL_SIG_ANON +#define SSL_SIG_ECDSA MBEDTLS_SSL_SIG_ECDSA +#define SSL_SIG_RSA MBEDTLS_SSL_SIG_RSA +#define SSL_TRANSPORT_DATAGRAM MBEDTLS_SSL_TRANSPORT_DATAGRAM +#define SSL_TRANSPORT_STREAM MBEDTLS_SSL_TRANSPORT_STREAM +#define SSL_TRUNCATED_HMAC_LEN MBEDTLS_SSL_TRUNCATED_HMAC_LEN +#define SSL_TRUNC_HMAC_DISABLED MBEDTLS_SSL_TRUNC_HMAC_DISABLED +#define SSL_TRUNC_HMAC_ENABLED MBEDTLS_SSL_TRUNC_HMAC_ENABLED +#define SSL_VERIFY_DATA_MAX_LEN MBEDTLS_SSL_VERIFY_DATA_MAX_LEN +#define SSL_VERIFY_NONE MBEDTLS_SSL_VERIFY_NONE +#define SSL_VERIFY_OPTIONAL MBEDTLS_SSL_VERIFY_OPTIONAL +#define SSL_VERIFY_REQUIRED MBEDTLS_SSL_VERIFY_REQUIRED +#define TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA MBEDTLS_TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA +#define TLS_DHE_PSK_WITH_AES_128_CBC_SHA MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CBC_SHA +#define TLS_DHE_PSK_WITH_AES_128_CBC_SHA256 MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CBC_SHA256 +#define TLS_DHE_PSK_WITH_AES_128_CCM MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CCM +#define TLS_DHE_PSK_WITH_AES_128_CCM_8 MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CCM_8 +#define TLS_DHE_PSK_WITH_AES_128_GCM_SHA256 MBEDTLS_TLS_DHE_PSK_WITH_AES_128_GCM_SHA256 +#define TLS_DHE_PSK_WITH_AES_256_CBC_SHA MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CBC_SHA +#define TLS_DHE_PSK_WITH_AES_256_CBC_SHA384 MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CBC_SHA384 +#define TLS_DHE_PSK_WITH_AES_256_CCM MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CCM +#define TLS_DHE_PSK_WITH_AES_256_CCM_8 MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CCM_8 +#define TLS_DHE_PSK_WITH_AES_256_GCM_SHA384 MBEDTLS_TLS_DHE_PSK_WITH_AES_256_GCM_SHA384 +#define TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 +#define TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256 MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256 +#define TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 +#define TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384 MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384 +#define TLS_DHE_PSK_WITH_NULL_SHA MBEDTLS_TLS_DHE_PSK_WITH_NULL_SHA +#define TLS_DHE_PSK_WITH_NULL_SHA256 MBEDTLS_TLS_DHE_PSK_WITH_NULL_SHA256 +#define TLS_DHE_PSK_WITH_NULL_SHA384 MBEDTLS_TLS_DHE_PSK_WITH_NULL_SHA384 +#define TLS_DHE_PSK_WITH_RC4_128_SHA MBEDTLS_TLS_DHE_PSK_WITH_RC4_128_SHA +#define TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA MBEDTLS_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA +#define TLS_DHE_RSA_WITH_AES_128_CBC_SHA MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA +#define TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 +#define TLS_DHE_RSA_WITH_AES_128_CCM MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CCM +#define TLS_DHE_RSA_WITH_AES_128_CCM_8 MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CCM_8 +#define TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 MBEDTLS_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 +#define TLS_DHE_RSA_WITH_AES_256_CBC_SHA MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CBC_SHA +#define TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 +#define TLS_DHE_RSA_WITH_AES_256_CCM MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CCM +#define TLS_DHE_RSA_WITH_AES_256_CCM_8 MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CCM_8 +#define TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 MBEDTLS_TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 +#define TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA +#define TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 +#define TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256 MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256 +#define TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA +#define TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 +#define TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384 MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384 +#define TLS_DHE_RSA_WITH_DES_CBC_SHA MBEDTLS_TLS_DHE_RSA_WITH_DES_CBC_SHA +#define TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA MBEDTLS_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA +#define TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA +#define TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 +#define TLS_ECDHE_ECDSA_WITH_AES_128_CCM MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM +#define TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 +#define TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 +#define TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA +#define TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 +#define TLS_ECDHE_ECDSA_WITH_AES_256_CCM MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CCM +#define TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8 MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8 +#define TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 +#define TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 +#define TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256 MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256 +#define TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 +#define TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384 MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384 +#define TLS_ECDHE_ECDSA_WITH_NULL_SHA MBEDTLS_TLS_ECDHE_ECDSA_WITH_NULL_SHA +#define TLS_ECDHE_ECDSA_WITH_RC4_128_SHA MBEDTLS_TLS_ECDHE_ECDSA_WITH_RC4_128_SHA +#define TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA MBEDTLS_TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA +#define TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA +#define TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 +#define TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA MBEDTLS_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA +#define TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384 MBEDTLS_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384 +#define TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 MBEDTLS_TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 +#define TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 MBEDTLS_TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 +#define TLS_ECDHE_PSK_WITH_NULL_SHA MBEDTLS_TLS_ECDHE_PSK_WITH_NULL_SHA +#define TLS_ECDHE_PSK_WITH_NULL_SHA256 MBEDTLS_TLS_ECDHE_PSK_WITH_NULL_SHA256 +#define TLS_ECDHE_PSK_WITH_NULL_SHA384 MBEDTLS_TLS_ECDHE_PSK_WITH_NULL_SHA384 +#define TLS_ECDHE_PSK_WITH_RC4_128_SHA MBEDTLS_TLS_ECDHE_PSK_WITH_RC4_128_SHA +#define TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA MBEDTLS_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA +#define TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA +#define TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 +#define TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 +#define TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA +#define TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 +#define TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 +#define TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 +#define TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256 MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256 +#define TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384 MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384 +#define TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384 MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384 +#define TLS_ECDHE_RSA_WITH_NULL_SHA MBEDTLS_TLS_ECDHE_RSA_WITH_NULL_SHA +#define TLS_ECDHE_RSA_WITH_RC4_128_SHA MBEDTLS_TLS_ECDHE_RSA_WITH_RC4_128_SHA +#define TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA MBEDTLS_TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA +#define TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA +#define TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 +#define TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 +#define TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA +#define TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 +#define TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 +#define TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 +#define TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256 MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256 +#define TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 +#define TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384 MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384 +#define TLS_ECDH_ECDSA_WITH_NULL_SHA MBEDTLS_TLS_ECDH_ECDSA_WITH_NULL_SHA +#define TLS_ECDH_ECDSA_WITH_RC4_128_SHA MBEDTLS_TLS_ECDH_ECDSA_WITH_RC4_128_SHA +#define TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA MBEDTLS_TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA +#define TLS_ECDH_RSA_WITH_AES_128_CBC_SHA MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA +#define TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 +#define TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 +#define TLS_ECDH_RSA_WITH_AES_256_CBC_SHA MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA +#define TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 +#define TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384 MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384 +#define TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256 MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256 +#define TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256 MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256 +#define TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384 MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384 +#define TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384 MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384 +#define TLS_ECDH_RSA_WITH_NULL_SHA MBEDTLS_TLS_ECDH_RSA_WITH_NULL_SHA +#define TLS_ECDH_RSA_WITH_RC4_128_SHA MBEDTLS_TLS_ECDH_RSA_WITH_RC4_128_SHA +#define TLS_EXT_ALPN MBEDTLS_TLS_EXT_ALPN +#define TLS_EXT_ENCRYPT_THEN_MAC MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC +#define TLS_EXT_EXTENDED_MASTER_SECRET MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET +#define TLS_EXT_MAX_FRAGMENT_LENGTH MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH +#define TLS_EXT_RENEGOTIATION_INFO MBEDTLS_TLS_EXT_RENEGOTIATION_INFO +#define TLS_EXT_SERVERNAME MBEDTLS_TLS_EXT_SERVERNAME +#define TLS_EXT_SERVERNAME_HOSTNAME MBEDTLS_TLS_EXT_SERVERNAME_HOSTNAME +#define TLS_EXT_SESSION_TICKET MBEDTLS_TLS_EXT_SESSION_TICKET +#define TLS_EXT_SIG_ALG MBEDTLS_TLS_EXT_SIG_ALG +#define TLS_EXT_SUPPORTED_ELLIPTIC_CURVES MBEDTLS_TLS_EXT_SUPPORTED_ELLIPTIC_CURVES +#define TLS_EXT_SUPPORTED_POINT_FORMATS MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS +#define TLS_EXT_SUPPORTED_POINT_FORMATS_PRESENT MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS_PRESENT +#define TLS_EXT_TRUNCATED_HMAC MBEDTLS_TLS_EXT_TRUNCATED_HMAC +#define TLS_PSK_WITH_3DES_EDE_CBC_SHA MBEDTLS_TLS_PSK_WITH_3DES_EDE_CBC_SHA +#define TLS_PSK_WITH_AES_128_CBC_SHA MBEDTLS_TLS_PSK_WITH_AES_128_CBC_SHA +#define TLS_PSK_WITH_AES_128_CBC_SHA256 MBEDTLS_TLS_PSK_WITH_AES_128_CBC_SHA256 +#define TLS_PSK_WITH_AES_128_CCM MBEDTLS_TLS_PSK_WITH_AES_128_CCM +#define TLS_PSK_WITH_AES_128_CCM_8 MBEDTLS_TLS_PSK_WITH_AES_128_CCM_8 +#define TLS_PSK_WITH_AES_128_GCM_SHA256 MBEDTLS_TLS_PSK_WITH_AES_128_GCM_SHA256 +#define TLS_PSK_WITH_AES_256_CBC_SHA MBEDTLS_TLS_PSK_WITH_AES_256_CBC_SHA +#define TLS_PSK_WITH_AES_256_CBC_SHA384 MBEDTLS_TLS_PSK_WITH_AES_256_CBC_SHA384 +#define TLS_PSK_WITH_AES_256_CCM MBEDTLS_TLS_PSK_WITH_AES_256_CCM +#define TLS_PSK_WITH_AES_256_CCM_8 MBEDTLS_TLS_PSK_WITH_AES_256_CCM_8 +#define TLS_PSK_WITH_AES_256_GCM_SHA384 MBEDTLS_TLS_PSK_WITH_AES_256_GCM_SHA384 +#define TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256 MBEDTLS_TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256 +#define TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256 MBEDTLS_TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256 +#define TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384 MBEDTLS_TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384 +#define TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384 MBEDTLS_TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384 +#define TLS_PSK_WITH_NULL_SHA MBEDTLS_TLS_PSK_WITH_NULL_SHA +#define TLS_PSK_WITH_NULL_SHA256 MBEDTLS_TLS_PSK_WITH_NULL_SHA256 +#define TLS_PSK_WITH_NULL_SHA384 MBEDTLS_TLS_PSK_WITH_NULL_SHA384 +#define TLS_PSK_WITH_RC4_128_SHA MBEDTLS_TLS_PSK_WITH_RC4_128_SHA +#define TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA MBEDTLS_TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA +#define TLS_RSA_PSK_WITH_AES_128_CBC_SHA MBEDTLS_TLS_RSA_PSK_WITH_AES_128_CBC_SHA +#define TLS_RSA_PSK_WITH_AES_128_CBC_SHA256 MBEDTLS_TLS_RSA_PSK_WITH_AES_128_CBC_SHA256 +#define TLS_RSA_PSK_WITH_AES_128_GCM_SHA256 MBEDTLS_TLS_RSA_PSK_WITH_AES_128_GCM_SHA256 +#define TLS_RSA_PSK_WITH_AES_256_CBC_SHA MBEDTLS_TLS_RSA_PSK_WITH_AES_256_CBC_SHA +#define TLS_RSA_PSK_WITH_AES_256_CBC_SHA384 MBEDTLS_TLS_RSA_PSK_WITH_AES_256_CBC_SHA384 +#define TLS_RSA_PSK_WITH_AES_256_GCM_SHA384 MBEDTLS_TLS_RSA_PSK_WITH_AES_256_GCM_SHA384 +#define TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256 MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256 +#define TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256 MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256 +#define TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384 MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384 +#define TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384 MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384 +#define TLS_RSA_PSK_WITH_NULL_SHA MBEDTLS_TLS_RSA_PSK_WITH_NULL_SHA +#define TLS_RSA_PSK_WITH_NULL_SHA256 MBEDTLS_TLS_RSA_PSK_WITH_NULL_SHA256 +#define TLS_RSA_PSK_WITH_NULL_SHA384 MBEDTLS_TLS_RSA_PSK_WITH_NULL_SHA384 +#define TLS_RSA_PSK_WITH_RC4_128_SHA MBEDTLS_TLS_RSA_PSK_WITH_RC4_128_SHA +#define TLS_RSA_WITH_3DES_EDE_CBC_SHA MBEDTLS_TLS_RSA_WITH_3DES_EDE_CBC_SHA +#define TLS_RSA_WITH_AES_128_CBC_SHA MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA +#define TLS_RSA_WITH_AES_128_CBC_SHA256 MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA256 +#define TLS_RSA_WITH_AES_128_CCM MBEDTLS_TLS_RSA_WITH_AES_128_CCM +#define TLS_RSA_WITH_AES_128_CCM_8 MBEDTLS_TLS_RSA_WITH_AES_128_CCM_8 +#define TLS_RSA_WITH_AES_128_GCM_SHA256 MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256 +#define TLS_RSA_WITH_AES_256_CBC_SHA MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA +#define TLS_RSA_WITH_AES_256_CBC_SHA256 MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA256 +#define TLS_RSA_WITH_AES_256_CCM MBEDTLS_TLS_RSA_WITH_AES_256_CCM +#define TLS_RSA_WITH_AES_256_CCM_8 MBEDTLS_TLS_RSA_WITH_AES_256_CCM_8 +#define TLS_RSA_WITH_AES_256_GCM_SHA384 MBEDTLS_TLS_RSA_WITH_AES_256_GCM_SHA384 +#define TLS_RSA_WITH_CAMELLIA_128_CBC_SHA MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA +#define TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256 MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256 +#define TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256 MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256 +#define TLS_RSA_WITH_CAMELLIA_256_CBC_SHA MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA +#define TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256 MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256 +#define TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384 MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384 +#define TLS_RSA_WITH_DES_CBC_SHA MBEDTLS_TLS_RSA_WITH_DES_CBC_SHA +#define TLS_RSA_WITH_NULL_MD5 MBEDTLS_TLS_RSA_WITH_NULL_MD5 +#define TLS_RSA_WITH_NULL_SHA MBEDTLS_TLS_RSA_WITH_NULL_SHA +#define TLS_RSA_WITH_NULL_SHA256 MBEDTLS_TLS_RSA_WITH_NULL_SHA256 +#define TLS_RSA_WITH_RC4_128_MD5 MBEDTLS_TLS_RSA_WITH_RC4_128_MD5 +#define TLS_RSA_WITH_RC4_128_SHA MBEDTLS_TLS_RSA_WITH_RC4_128_SHA +#define X509_CRT_VERSION_1 MBEDTLS_X509_CRT_VERSION_1 +#define X509_CRT_VERSION_2 MBEDTLS_X509_CRT_VERSION_2 +#define X509_CRT_VERSION_3 MBEDTLS_X509_CRT_VERSION_3 +#define X509_FORMAT_DER MBEDTLS_X509_FORMAT_DER +#define X509_FORMAT_PEM MBEDTLS_X509_FORMAT_PEM +#define X509_MAX_DN_NAME_SIZE MBEDTLS_X509_MAX_DN_NAME_SIZE +#define X509_RFC5280_MAX_SERIAL_LEN MBEDTLS_X509_RFC5280_MAX_SERIAL_LEN +#define X509_RFC5280_UTC_TIME_LEN MBEDTLS_X509_RFC5280_UTC_TIME_LEN +#define XTEA_DECRYPT MBEDTLS_XTEA_DECRYPT +#define XTEA_ENCRYPT MBEDTLS_XTEA_ENCRYPT +#define _asn1_bitstring mbedtls_asn1_bitstring +#define _asn1_buf mbedtls_asn1_buf +#define _asn1_named_data mbedtls_asn1_named_data +#define _asn1_sequence mbedtls_asn1_sequence +#define _ssl_cache_context mbedtls_ssl_cache_context +#define _ssl_cache_entry mbedtls_ssl_cache_entry +#define _ssl_ciphersuite_t mbedtls_ssl_ciphersuite_t +#define _ssl_context mbedtls_ssl_context +#define _ssl_flight_item mbedtls_ssl_flight_item +#define _ssl_handshake_params mbedtls_ssl_handshake_params +#define _ssl_key_cert mbedtls_ssl_key_cert +#define _ssl_premaster_secret mbedtls_ssl_premaster_secret +#define _ssl_session mbedtls_ssl_session +#define _ssl_transform mbedtls_ssl_transform +#define _x509_crl mbedtls_x509_crl +#define _x509_crl_entry mbedtls_x509_crl_entry +#define _x509_crt mbedtls_x509_crt +#define _x509_csr mbedtls_x509_csr +#define _x509_time mbedtls_x509_time +#define _x509write_cert mbedtls_x509write_cert +#define _x509write_csr mbedtls_x509write_csr +#define aes_context mbedtls_aes_context +#define aes_crypt_cbc mbedtls_aes_crypt_cbc +#define aes_crypt_cfb128 mbedtls_aes_crypt_cfb128 +#define aes_crypt_cfb8 mbedtls_aes_crypt_cfb8 +#define aes_crypt_ctr mbedtls_aes_crypt_ctr +#define aes_crypt_ecb mbedtls_aes_crypt_ecb +#define aes_free mbedtls_aes_free +#define aes_init mbedtls_aes_init +#define aes_self_test mbedtls_aes_self_test +#define aes_setkey_dec mbedtls_aes_setkey_dec +#define aes_setkey_enc mbedtls_aes_setkey_enc +#define aesni_crypt_ecb mbedtls_aesni_crypt_ecb +#define aesni_gcm_mult mbedtls_aesni_gcm_mult +#define aesni_inverse_key mbedtls_aesni_inverse_key +#define aesni_setkey_enc mbedtls_aesni_setkey_enc +#define aesni_supports mbedtls_aesni_has_support +#define alarmed mbedtls_timing_alarmed +#define arc4_context mbedtls_arc4_context +#define arc4_crypt mbedtls_arc4_crypt +#define arc4_free mbedtls_arc4_free +#define arc4_init mbedtls_arc4_init +#define arc4_self_test mbedtls_arc4_self_test +#define arc4_setup mbedtls_arc4_setup +#define asn1_bitstring mbedtls_asn1_bitstring +#define asn1_buf mbedtls_asn1_buf +#define asn1_find_named_data mbedtls_asn1_find_named_data +#define asn1_free_named_data mbedtls_asn1_free_named_data +#define asn1_free_named_data_list mbedtls_asn1_free_named_data_list +#define asn1_get_alg mbedtls_asn1_get_alg +#define asn1_get_alg_null mbedtls_asn1_get_alg_null +#define asn1_get_bitstring mbedtls_asn1_get_bitstring +#define asn1_get_bitstring_null mbedtls_asn1_get_bitstring_null +#define asn1_get_bool mbedtls_asn1_get_bool +#define asn1_get_int mbedtls_asn1_get_int +#define asn1_get_len mbedtls_asn1_get_len +#define asn1_get_mpi mbedtls_asn1_get_mpi +#define asn1_get_sequence_of mbedtls_asn1_get_sequence_of +#define asn1_get_tag mbedtls_asn1_get_tag +#define asn1_named_data mbedtls_asn1_named_data +#define asn1_sequence mbedtls_asn1_sequence +#define asn1_store_named_data mbedtls_asn1_store_named_data +#define asn1_write_algorithm_identifier mbedtls_asn1_write_algorithm_identifier +#define asn1_write_bitstring mbedtls_asn1_write_bitstring +#define asn1_write_bool mbedtls_asn1_write_bool +#define asn1_write_ia5_string mbedtls_asn1_write_ia5_string +#define asn1_write_int mbedtls_asn1_write_int +#define asn1_write_len mbedtls_asn1_write_len +#define asn1_write_mpi mbedtls_asn1_write_mpi +#define asn1_write_null mbedtls_asn1_write_null +#define asn1_write_octet_string mbedtls_asn1_write_octet_string +#define asn1_write_oid mbedtls_asn1_write_oid +#define asn1_write_printable_string mbedtls_asn1_write_printable_string +#define asn1_write_raw_buffer mbedtls_asn1_write_raw_buffer +#define asn1_write_tag mbedtls_asn1_write_tag +#define base64_decode mbedtls_base64_decode +#define base64_encode mbedtls_base64_encode +#define base64_self_test mbedtls_base64_self_test +#define blowfish_context mbedtls_blowfish_context +#define blowfish_crypt_cbc mbedtls_blowfish_crypt_cbc +#define blowfish_crypt_cfb64 mbedtls_blowfish_crypt_cfb64 +#define blowfish_crypt_ctr mbedtls_blowfish_crypt_ctr +#define blowfish_crypt_ecb mbedtls_blowfish_crypt_ecb +#define blowfish_free mbedtls_blowfish_free +#define blowfish_init mbedtls_blowfish_init +#define blowfish_setkey mbedtls_blowfish_setkey +#define camellia_context mbedtls_camellia_context +#define camellia_crypt_cbc mbedtls_camellia_crypt_cbc +#define camellia_crypt_cfb128 mbedtls_camellia_crypt_cfb128 +#define camellia_crypt_ctr mbedtls_camellia_crypt_ctr +#define camellia_crypt_ecb mbedtls_camellia_crypt_ecb +#define camellia_free mbedtls_camellia_free +#define camellia_init mbedtls_camellia_init +#define camellia_self_test mbedtls_camellia_self_test +#define camellia_setkey_dec mbedtls_camellia_setkey_dec +#define camellia_setkey_enc mbedtls_camellia_setkey_enc +#define ccm_auth_decrypt mbedtls_ccm_auth_decrypt +#define ccm_context mbedtls_ccm_context +#define ccm_encrypt_and_tag mbedtls_ccm_encrypt_and_tag +#define ccm_free mbedtls_ccm_free +#define ccm_init mbedtls_ccm_init +#define ccm_self_test mbedtls_ccm_self_test +#define cipher_auth_decrypt mbedtls_cipher_auth_decrypt +#define cipher_auth_encrypt mbedtls_cipher_auth_encrypt +#define cipher_base_t mbedtls_cipher_base_t +#define cipher_check_tag mbedtls_cipher_check_tag +#define cipher_context_t mbedtls_cipher_context_t +#define cipher_crypt mbedtls_cipher_crypt +#define cipher_definition_t mbedtls_cipher_definition_t +#define cipher_definitions mbedtls_cipher_definitions +#define cipher_finish mbedtls_cipher_finish +#define cipher_free mbedtls_cipher_free +#define cipher_get_block_size mbedtls_cipher_get_block_size +#define cipher_get_cipher_mode mbedtls_cipher_get_cipher_mode +#define cipher_get_iv_size mbedtls_cipher_get_iv_size +#define cipher_get_key_size mbedtls_cipher_get_key_bitlen +#define cipher_get_name mbedtls_cipher_get_name +#define cipher_get_operation mbedtls_cipher_get_operation +#define cipher_get_type mbedtls_cipher_get_type +#define cipher_id_t mbedtls_cipher_id_t +#define cipher_info_from_string mbedtls_cipher_info_from_string +#define cipher_info_from_type mbedtls_cipher_info_from_type +#define cipher_info_from_values mbedtls_cipher_info_from_values +#define cipher_info_t mbedtls_cipher_info_t +#define cipher_init mbedtls_cipher_init +#define cipher_init_ctx mbedtls_cipher_setup +#define cipher_list mbedtls_cipher_list +#define cipher_mode_t mbedtls_cipher_mode_t +#define cipher_padding_t mbedtls_cipher_padding_t +#define cipher_reset mbedtls_cipher_reset +#define cipher_set_iv mbedtls_cipher_set_iv +#define cipher_set_padding_mode mbedtls_cipher_set_padding_mode +#define cipher_setkey mbedtls_cipher_setkey +#define cipher_type_t mbedtls_cipher_type_t +#define cipher_update mbedtls_cipher_update +#define cipher_update_ad mbedtls_cipher_update_ad +#define cipher_write_tag mbedtls_cipher_write_tag +#define ctr_drbg_context mbedtls_ctr_drbg_context +#define ctr_drbg_free mbedtls_ctr_drbg_free +#define ctr_drbg_init mbedtls_ctr_drbg_init +#define ctr_drbg_random mbedtls_ctr_drbg_random +#define ctr_drbg_random_with_add mbedtls_ctr_drbg_random_with_add +#define ctr_drbg_reseed mbedtls_ctr_drbg_reseed +#define ctr_drbg_self_test mbedtls_ctr_drbg_self_test +#define ctr_drbg_set_entropy_len mbedtls_ctr_drbg_set_entropy_len +#define ctr_drbg_set_prediction_resistance mbedtls_ctr_drbg_set_prediction_resistance +#define ctr_drbg_set_reseed_interval mbedtls_ctr_drbg_set_reseed_interval +#define ctr_drbg_update mbedtls_ctr_drbg_update +#define ctr_drbg_update_seed_file mbedtls_ctr_drbg_update_seed_file +#define ctr_drbg_write_seed_file mbedtls_ctr_drbg_write_seed_file +#define debug_print_buf mbedtls_debug_print_buf +#define debug_print_crt mbedtls_debug_print_crt +#define debug_print_ecp mbedtls_debug_print_ecp +#define debug_print_mpi mbedtls_debug_print_mpi +#define debug_print_msg mbedtls_debug_print_msg +#define debug_print_ret mbedtls_debug_print_ret +#define debug_set_threshold mbedtls_debug_set_threshold +#define des3_context mbedtls_des3_context +#define des3_crypt_cbc mbedtls_des3_crypt_cbc +#define des3_crypt_ecb mbedtls_des3_crypt_ecb +#define des3_free mbedtls_des3_free +#define des3_init mbedtls_des3_init +#define des3_set2key_dec mbedtls_des3_set2key_dec +#define des3_set2key_enc mbedtls_des3_set2key_enc +#define des3_set3key_dec mbedtls_des3_set3key_dec +#define des3_set3key_enc mbedtls_des3_set3key_enc +#define des_context mbedtls_des_context +#define des_crypt_cbc mbedtls_des_crypt_cbc +#define des_crypt_ecb mbedtls_des_crypt_ecb +#define des_free mbedtls_des_free +#define des_init mbedtls_des_init +#define des_key_check_key_parity mbedtls_des_key_check_key_parity +#define des_key_check_weak mbedtls_des_key_check_weak +#define des_key_set_parity mbedtls_des_key_set_parity +#define des_self_test mbedtls_des_self_test +#define des_setkey_dec mbedtls_des_setkey_dec +#define des_setkey_enc mbedtls_des_setkey_enc +#define dhm_calc_secret mbedtls_dhm_calc_secret +#define dhm_context mbedtls_dhm_context +#define dhm_free mbedtls_dhm_free +#define dhm_init mbedtls_dhm_init +#define dhm_make_params mbedtls_dhm_make_params +#define dhm_make_public mbedtls_dhm_make_public +#define dhm_parse_dhm mbedtls_dhm_parse_dhm +#define dhm_parse_dhmfile mbedtls_dhm_parse_dhmfile +#define dhm_read_params mbedtls_dhm_read_params +#define dhm_read_public mbedtls_dhm_read_public +#define dhm_self_test mbedtls_dhm_self_test +#define ecdh_calc_secret mbedtls_ecdh_calc_secret +#define ecdh_compute_shared mbedtls_ecdh_compute_shared +#define ecdh_context mbedtls_ecdh_context +#define ecdh_free mbedtls_ecdh_free +#define ecdh_gen_public mbedtls_ecdh_gen_public +#define ecdh_get_params mbedtls_ecdh_get_params +#define ecdh_init mbedtls_ecdh_init +#define ecdh_make_params mbedtls_ecdh_make_params +#define ecdh_make_public mbedtls_ecdh_make_public +#define ecdh_read_params mbedtls_ecdh_read_params +#define ecdh_read_public mbedtls_ecdh_read_public +#define ecdh_side mbedtls_ecdh_side +#define ecdsa_context mbedtls_ecdsa_context +#define ecdsa_free mbedtls_ecdsa_free +#define ecdsa_from_keypair mbedtls_ecdsa_from_keypair +#define ecdsa_genkey mbedtls_ecdsa_genkey +#define ecdsa_info mbedtls_ecdsa_info +#define ecdsa_init mbedtls_ecdsa_init +#define ecdsa_read_signature mbedtls_ecdsa_read_signature +#define ecdsa_sign mbedtls_ecdsa_sign +#define ecdsa_sign_det mbedtls_ecdsa_sign_det +#define ecdsa_verify mbedtls_ecdsa_verify +#define ecdsa_write_signature mbedtls_ecdsa_write_signature +#define ecdsa_write_signature_det mbedtls_ecdsa_write_signature_det +#define eckey_info mbedtls_eckey_info +#define eckeydh_info mbedtls_eckeydh_info +#define ecp_check_privkey mbedtls_ecp_check_privkey +#define ecp_check_pub_priv mbedtls_ecp_check_pub_priv +#define ecp_check_pubkey mbedtls_ecp_check_pubkey +#define ecp_copy mbedtls_ecp_copy +#define ecp_curve_info mbedtls_ecp_curve_info +#define ecp_curve_info_from_grp_id mbedtls_ecp_curve_info_from_grp_id +#define ecp_curve_info_from_name mbedtls_ecp_curve_info_from_name +#define ecp_curve_info_from_tls_id mbedtls_ecp_curve_info_from_tls_id +#define ecp_curve_list mbedtls_ecp_curve_list +#define ecp_gen_key mbedtls_ecp_gen_key +#define ecp_gen_keypair mbedtls_ecp_gen_keypair +#define ecp_group mbedtls_ecp_group +#define ecp_group_copy mbedtls_ecp_group_copy +#define ecp_group_free mbedtls_ecp_group_free +#define ecp_group_id mbedtls_ecp_group_id +#define ecp_group_init mbedtls_ecp_group_init +#define ecp_grp_id_list mbedtls_ecp_grp_id_list +#define ecp_is_zero mbedtls_ecp_is_zero +#define ecp_keypair mbedtls_ecp_keypair +#define ecp_keypair_free mbedtls_ecp_keypair_free +#define ecp_keypair_init mbedtls_ecp_keypair_init +#define ecp_mul mbedtls_ecp_mul +#define ecp_point mbedtls_ecp_point +#define ecp_point_free mbedtls_ecp_point_free +#define ecp_point_init mbedtls_ecp_point_init +#define ecp_point_read_binary mbedtls_ecp_point_read_binary +#define ecp_point_read_string mbedtls_ecp_point_read_string +#define ecp_point_write_binary mbedtls_ecp_point_write_binary +#define ecp_self_test mbedtls_ecp_self_test +#define ecp_set_zero mbedtls_ecp_set_zero +#define ecp_tls_read_group mbedtls_ecp_tls_read_group +#define ecp_tls_read_point mbedtls_ecp_tls_read_point +#define ecp_tls_write_group mbedtls_ecp_tls_write_group +#define ecp_tls_write_point mbedtls_ecp_tls_write_point +#define ecp_use_known_dp mbedtls_ecp_group_load +#define entropy_add_source mbedtls_entropy_add_source +#define entropy_context mbedtls_entropy_context +#define entropy_free mbedtls_entropy_free +#define entropy_func mbedtls_entropy_func +#define entropy_gather mbedtls_entropy_gather +#define entropy_init mbedtls_entropy_init +#define entropy_self_test mbedtls_entropy_self_test +#define entropy_update_manual mbedtls_entropy_update_manual +#define entropy_update_seed_file mbedtls_entropy_update_seed_file +#define entropy_write_seed_file mbedtls_entropy_write_seed_file +#define error_strerror mbedtls_strerror +#define f_source_ptr mbedtls_entropy_f_source_ptr +#define gcm_auth_decrypt mbedtls_gcm_auth_decrypt +#define gcm_context mbedtls_gcm_context +#define gcm_crypt_and_tag mbedtls_gcm_crypt_and_tag +#define gcm_finish mbedtls_gcm_finish +#define gcm_free mbedtls_gcm_free +#define gcm_init mbedtls_gcm_init +#define gcm_self_test mbedtls_gcm_self_test +#define gcm_starts mbedtls_gcm_starts +#define gcm_update mbedtls_gcm_update +#define get_timer mbedtls_timing_get_timer +#define hardclock mbedtls_timing_hardclock +#define hardclock_poll mbedtls_hardclock_poll +#define havege_free mbedtls_havege_free +#define havege_init mbedtls_havege_init +#define havege_poll mbedtls_havege_poll +#define havege_random mbedtls_havege_random +#define havege_state mbedtls_havege_state +#define hmac_drbg_context mbedtls_hmac_drbg_context +#define hmac_drbg_free mbedtls_hmac_drbg_free +#define hmac_drbg_init mbedtls_hmac_drbg_init +#define hmac_drbg_random mbedtls_hmac_drbg_random +#define hmac_drbg_random_with_add mbedtls_hmac_drbg_random_with_add +#define hmac_drbg_reseed mbedtls_hmac_drbg_reseed +#define hmac_drbg_self_test mbedtls_hmac_drbg_self_test +#define hmac_drbg_set_entropy_len mbedtls_hmac_drbg_set_entropy_len +#define hmac_drbg_set_prediction_resistance mbedtls_hmac_drbg_set_prediction_resistance +#define hmac_drbg_set_reseed_interval mbedtls_hmac_drbg_set_reseed_interval +#define hmac_drbg_update mbedtls_hmac_drbg_update +#define hmac_drbg_update_seed_file mbedtls_hmac_drbg_update_seed_file +#define hmac_drbg_write_seed_file mbedtls_hmac_drbg_write_seed_file +#define hr_time mbedtls_timing_hr_time +#define key_exchange_type_t mbedtls_key_exchange_type_t +#define md mbedtls_md +#define md2 mbedtls_md2 +#define md2_context mbedtls_md2_context +#define md2_finish mbedtls_md2_finish +#define md2_free mbedtls_md2_free +#define md2_info mbedtls_md2_info +#define md2_init mbedtls_md2_init +#define md2_process mbedtls_md2_process +#define md2_self_test mbedtls_md2_self_test +#define md2_starts mbedtls_md2_starts +#define md2_update mbedtls_md2_update +#define md4 mbedtls_md4 +#define md4_context mbedtls_md4_context +#define md4_finish mbedtls_md4_finish +#define md4_free mbedtls_md4_free +#define md4_info mbedtls_md4_info +#define md4_init mbedtls_md4_init +#define md4_process mbedtls_md4_process +#define md4_self_test mbedtls_md4_self_test +#define md4_starts mbedtls_md4_starts +#define md4_update mbedtls_md4_update +#define md5 mbedtls_md5 +#define md5_context mbedtls_md5_context +#define md5_finish mbedtls_md5_finish +#define md5_free mbedtls_md5_free +#define md5_info mbedtls_md5_info +#define md5_init mbedtls_md5_init +#define md5_process mbedtls_md5_process +#define md5_self_test mbedtls_md5_self_test +#define md5_starts mbedtls_md5_starts +#define md5_update mbedtls_md5_update +#define md_context_t mbedtls_md_context_t +#define md_file mbedtls_md_file +#define md_finish mbedtls_md_finish +#define md_free mbedtls_md_free +#define md_get_name mbedtls_md_get_name +#define md_get_size mbedtls_md_get_size +#define md_get_type mbedtls_md_get_type +#define md_hmac mbedtls_md_hmac +#define md_hmac_finish mbedtls_md_hmac_finish +#define md_hmac_reset mbedtls_md_hmac_reset +#define md_hmac_starts mbedtls_md_hmac_starts +#define md_hmac_update mbedtls_md_hmac_update +#define md_info_from_string mbedtls_md_info_from_string +#define md_info_from_type mbedtls_md_info_from_type +#define md_info_t mbedtls_md_info_t +#define md_init mbedtls_md_init +#define md_init_ctx mbedtls_md_init_ctx +#define md_list mbedtls_md_list +#define md_process mbedtls_md_process +#define md_starts mbedtls_md_starts +#define md_type_t mbedtls_md_type_t +#define md_update mbedtls_md_update +#define memory_buffer_alloc_cur_get mbedtls_memory_buffer_alloc_cur_get +#define memory_buffer_alloc_free mbedtls_memory_buffer_alloc_free +#define memory_buffer_alloc_init mbedtls_memory_buffer_alloc_init +#define memory_buffer_alloc_max_get mbedtls_memory_buffer_alloc_max_get +#define memory_buffer_alloc_max_reset mbedtls_memory_buffer_alloc_max_reset +#define memory_buffer_alloc_self_test mbedtls_memory_buffer_alloc_self_test +#define memory_buffer_alloc_status mbedtls_memory_buffer_alloc_status +#define memory_buffer_alloc_verify mbedtls_memory_buffer_alloc_verify +#define memory_buffer_set_verify mbedtls_memory_buffer_set_verify +#define mpi mbedtls_mpi +#define mpi_add_abs mbedtls_mpi_add_abs +#define mpi_add_int mbedtls_mpi_add_int +#define mpi_add_mpi mbedtls_mpi_add_mpi +#define mpi_cmp_abs mbedtls_mpi_cmp_abs +#define mpi_cmp_int mbedtls_mpi_cmp_int +#define mpi_cmp_mpi mbedtls_mpi_cmp_mpi +#define mpi_copy mbedtls_mpi_copy +#define mpi_div_int mbedtls_mpi_div_int +#define mpi_div_mpi mbedtls_mpi_div_mpi +#define mpi_exp_mod mbedtls_mpi_exp_mod +#define mpi_fill_random mbedtls_mpi_fill_random +#define mpi_free mbedtls_mpi_free +#define mpi_gcd mbedtls_mpi_gcd +#define mpi_gen_prime mbedtls_mpi_gen_prime +#define mpi_get_bit mbedtls_mpi_get_bit +#define mpi_grow mbedtls_mpi_grow +#define mpi_init mbedtls_mpi_init +#define mpi_inv_mod mbedtls_mpi_inv_mod +#define mpi_is_prime mbedtls_mpi_is_prime +#define mpi_lsb mbedtls_mpi_lsb +#define mpi_lset mbedtls_mpi_lset +#define mpi_mod_int mbedtls_mpi_mod_int +#define mpi_mod_mpi mbedtls_mpi_mod_mpi +#define mpi_msb mbedtls_mpi_bitlen +#define mpi_mul_int mbedtls_mpi_mul_int +#define mpi_mul_mpi mbedtls_mpi_mul_mpi +#define mpi_read_binary mbedtls_mpi_read_binary +#define mpi_read_file mbedtls_mpi_read_file +#define mpi_read_string mbedtls_mpi_read_string +#define mpi_safe_cond_assign mbedtls_mpi_safe_cond_assign +#define mpi_safe_cond_swap mbedtls_mpi_safe_cond_swap +#define mpi_self_test mbedtls_mpi_self_test +#define mpi_set_bit mbedtls_mpi_set_bit +#define mpi_shift_l mbedtls_mpi_shift_l +#define mpi_shift_r mbedtls_mpi_shift_r +#define mpi_shrink mbedtls_mpi_shrink +#define mpi_size mbedtls_mpi_size +#define mpi_sub_abs mbedtls_mpi_sub_abs +#define mpi_sub_int mbedtls_mpi_sub_int +#define mpi_sub_mpi mbedtls_mpi_sub_mpi +#define mpi_swap mbedtls_mpi_swap +#define mpi_write_binary mbedtls_mpi_write_binary +#define mpi_write_file mbedtls_mpi_write_file +#define mpi_write_string mbedtls_mpi_write_string +#define net_accept mbedtls_net_accept +#define net_bind mbedtls_net_bind +#define net_close mbedtls_net_free +#define net_connect mbedtls_net_connect +#define net_recv mbedtls_net_recv +#define net_recv_timeout mbedtls_net_recv_timeout +#define net_send mbedtls_net_send +#define net_set_block mbedtls_net_set_block +#define net_set_nonblock mbedtls_net_set_nonblock +#define net_usleep mbedtls_net_usleep +#define oid_descriptor_t mbedtls_oid_descriptor_t +#define oid_get_attr_short_name mbedtls_oid_get_attr_short_name +#define oid_get_cipher_alg mbedtls_oid_get_cipher_alg +#define oid_get_ec_grp mbedtls_oid_get_ec_grp +#define oid_get_extended_key_usage mbedtls_oid_get_extended_key_usage +#define oid_get_md_alg mbedtls_oid_get_md_alg +#define oid_get_numeric_string mbedtls_oid_get_numeric_string +#define oid_get_oid_by_ec_grp mbedtls_oid_get_oid_by_ec_grp +#define oid_get_oid_by_md mbedtls_oid_get_oid_by_md +#define oid_get_oid_by_pk_alg mbedtls_oid_get_oid_by_pk_alg +#define oid_get_oid_by_sig_alg mbedtls_oid_get_oid_by_sig_alg +#define oid_get_pk_alg mbedtls_oid_get_pk_alg +#define oid_get_pkcs12_pbe_alg mbedtls_oid_get_pkcs12_pbe_alg +#define oid_get_sig_alg mbedtls_oid_get_sig_alg +#define oid_get_sig_alg_desc mbedtls_oid_get_sig_alg_desc +#define oid_get_x509_ext_type mbedtls_oid_get_x509_ext_type +#define operation_t mbedtls_operation_t +#define padlock_supports mbedtls_padlock_has_support +#define padlock_xcryptcbc mbedtls_padlock_xcryptcbc +#define padlock_xcryptecb mbedtls_padlock_xcryptecb +#define pem_context mbedtls_pem_context +#define pem_free mbedtls_pem_free +#define pem_init mbedtls_pem_init +#define pem_read_buffer mbedtls_pem_read_buffer +#define pem_write_buffer mbedtls_pem_write_buffer +#define pk_can_do mbedtls_pk_can_do +#define pk_check_pair mbedtls_pk_check_pair +#define pk_context mbedtls_pk_context +#define pk_debug mbedtls_pk_debug +#define pk_debug_item mbedtls_pk_debug_item +#define pk_debug_type mbedtls_pk_debug_type +#define pk_decrypt mbedtls_pk_decrypt +#define pk_ec mbedtls_pk_ec +#define pk_encrypt mbedtls_pk_encrypt +#define pk_free mbedtls_pk_free +#define pk_get_len mbedtls_pk_get_len +#define pk_get_name mbedtls_pk_get_name +#define pk_get_size mbedtls_pk_get_bitlen +#define pk_get_type mbedtls_pk_get_type +#define pk_info_from_type mbedtls_pk_info_from_type +#define pk_info_t mbedtls_pk_info_t +#define pk_init mbedtls_pk_init +#define pk_init_ctx mbedtls_pk_setup +#define pk_init_ctx_rsa_alt mbedtls_pk_setup_rsa_alt +#define pk_load_file mbedtls_pk_load_file +#define pk_parse_key mbedtls_pk_parse_key +#define pk_parse_keyfile mbedtls_pk_parse_keyfile +#define pk_parse_public_key mbedtls_pk_parse_public_key +#define pk_parse_public_keyfile mbedtls_pk_parse_public_keyfile +#define pk_parse_subpubkey mbedtls_pk_parse_subpubkey +#define pk_rsa mbedtls_pk_rsa +#define pk_rsa_alt_decrypt_func mbedtls_pk_rsa_alt_decrypt_func +#define pk_rsa_alt_key_len_func mbedtls_pk_rsa_alt_key_len_func +#define pk_rsa_alt_sign_func mbedtls_pk_rsa_alt_sign_func +#define pk_rsassa_pss_options mbedtls_pk_rsassa_pss_options +#define pk_sign mbedtls_pk_sign +#define pk_type_t mbedtls_pk_type_t +#define pk_verify mbedtls_pk_verify +#define pk_verify_ext mbedtls_pk_verify_ext +#define pk_write_key_der mbedtls_pk_write_key_der +#define pk_write_key_pem mbedtls_pk_write_key_pem +#define pk_write_pubkey mbedtls_pk_write_pubkey +#define pk_write_pubkey_der mbedtls_pk_write_pubkey_der +#define pk_write_pubkey_pem mbedtls_pk_write_pubkey_pem +#define pkcs11_context mbedtls_pkcs11_context +#define pkcs11_decrypt mbedtls_pkcs11_decrypt +#define pkcs11_priv_key_free mbedtls_pkcs11_priv_key_free +#define pkcs11_priv_key_init mbedtls_pkcs11_priv_key_bind +#define pkcs11_sign mbedtls_pkcs11_sign +#define pkcs11_x509_cert_init mbedtls_pkcs11_x509_cert_bind +#define pkcs12_derivation mbedtls_pkcs12_derivation +#define pkcs12_pbe mbedtls_pkcs12_pbe +#define pkcs12_pbe_sha1_rc4_128 mbedtls_pkcs12_pbe_sha1_rc4_128 +#define pkcs5_pbes2 mbedtls_pkcs5_pbes2 +#define pkcs5_pbkdf2_hmac mbedtls_pkcs5_pbkdf2_hmac +#define pkcs5_self_test mbedtls_pkcs5_self_test +#define platform_entropy_poll mbedtls_platform_entropy_poll +#define platform_set_exit mbedtls_platform_set_exit +#define platform_set_fprintf mbedtls_platform_set_fprintf +#define platform_set_printf mbedtls_platform_set_printf +#define platform_set_snprintf mbedtls_platform_set_snprintf +#define polarssl_exit mbedtls_exit +#define polarssl_fprintf mbedtls_fprintf +#define polarssl_free mbedtls_free +#define polarssl_mutex_free mbedtls_mutex_free +#define polarssl_mutex_init mbedtls_mutex_init +#define polarssl_mutex_lock mbedtls_mutex_lock +#define polarssl_mutex_unlock mbedtls_mutex_unlock +#define polarssl_printf mbedtls_printf +#define polarssl_snprintf mbedtls_snprintf +#define polarssl_strerror mbedtls_strerror +#define ripemd160 mbedtls_ripemd160 +#define ripemd160_context mbedtls_ripemd160_context +#define ripemd160_finish mbedtls_ripemd160_finish +#define ripemd160_free mbedtls_ripemd160_free +#define ripemd160_info mbedtls_ripemd160_info +#define ripemd160_init mbedtls_ripemd160_init +#define ripemd160_process mbedtls_ripemd160_process +#define ripemd160_self_test mbedtls_ripemd160_self_test +#define ripemd160_starts mbedtls_ripemd160_starts +#define ripemd160_update mbedtls_ripemd160_update +#define rsa_alt_context mbedtls_rsa_alt_context +#define rsa_alt_info mbedtls_rsa_alt_info +#define rsa_check_privkey mbedtls_rsa_check_privkey +#define rsa_check_pub_priv mbedtls_rsa_check_pub_priv +#define rsa_check_pubkey mbedtls_rsa_check_pubkey +#define rsa_context mbedtls_rsa_context +#define rsa_copy mbedtls_rsa_copy +#define rsa_free mbedtls_rsa_free +#define rsa_gen_key mbedtls_rsa_gen_key +#define rsa_info mbedtls_rsa_info +#define rsa_init mbedtls_rsa_init +#define rsa_pkcs1_decrypt mbedtls_rsa_pkcs1_decrypt +#define rsa_pkcs1_encrypt mbedtls_rsa_pkcs1_encrypt +#define rsa_pkcs1_sign mbedtls_rsa_pkcs1_sign +#define rsa_pkcs1_verify mbedtls_rsa_pkcs1_verify +#define rsa_private mbedtls_rsa_private +#define rsa_public mbedtls_rsa_public +#define rsa_rsaes_oaep_decrypt mbedtls_rsa_rsaes_oaep_decrypt +#define rsa_rsaes_oaep_encrypt mbedtls_rsa_rsaes_oaep_encrypt +#define rsa_rsaes_pkcs1_v15_decrypt mbedtls_rsa_rsaes_pkcs1_v15_decrypt +#define rsa_rsaes_pkcs1_v15_encrypt mbedtls_rsa_rsaes_pkcs1_v15_encrypt +#define rsa_rsassa_pkcs1_v15_sign mbedtls_rsa_rsassa_pkcs1_v15_sign +#define rsa_rsassa_pkcs1_v15_verify mbedtls_rsa_rsassa_pkcs1_v15_verify +#define rsa_rsassa_pss_sign mbedtls_rsa_rsassa_pss_sign +#define rsa_rsassa_pss_verify mbedtls_rsa_rsassa_pss_verify +#define rsa_rsassa_pss_verify_ext mbedtls_rsa_rsassa_pss_verify_ext +#define rsa_self_test mbedtls_rsa_self_test +#define rsa_set_padding mbedtls_rsa_set_padding +#define safer_memcmp mbedtls_ssl_safer_memcmp +#define set_alarm mbedtls_set_alarm +#define sha1 mbedtls_sha1 +#define sha1_context mbedtls_sha1_context +#define sha1_finish mbedtls_sha1_finish +#define sha1_free mbedtls_sha1_free +#define sha1_info mbedtls_sha1_info +#define sha1_init mbedtls_sha1_init +#define sha1_process mbedtls_sha1_process +#define sha1_self_test mbedtls_sha1_self_test +#define sha1_starts mbedtls_sha1_starts +#define sha1_update mbedtls_sha1_update +#define sha224_info mbedtls_sha224_info +#define sha256 mbedtls_sha256 +#define sha256_context mbedtls_sha256_context +#define sha256_finish mbedtls_sha256_finish +#define sha256_free mbedtls_sha256_free +#define sha256_info mbedtls_sha256_info +#define sha256_init mbedtls_sha256_init +#define sha256_process mbedtls_sha256_process +#define sha256_self_test mbedtls_sha256_self_test +#define sha256_starts mbedtls_sha256_starts +#define sha256_update mbedtls_sha256_update +#define sha384_info mbedtls_sha384_info +#define sha512 mbedtls_sha512 +#define sha512_context mbedtls_sha512_context +#define sha512_finish mbedtls_sha512_finish +#define sha512_free mbedtls_sha512_free +#define sha512_info mbedtls_sha512_info +#define sha512_init mbedtls_sha512_init +#define sha512_process mbedtls_sha512_process +#define sha512_self_test mbedtls_sha512_self_test +#define sha512_starts mbedtls_sha512_starts +#define sha512_update mbedtls_sha512_update +#define source_state mbedtls_entropy_source_state +#define ssl_cache_context mbedtls_ssl_cache_context +#define ssl_cache_entry mbedtls_ssl_cache_entry +#define ssl_cache_free mbedtls_ssl_cache_free +#define ssl_cache_get mbedtls_ssl_cache_get +#define ssl_cache_init mbedtls_ssl_cache_init +#define ssl_cache_set mbedtls_ssl_cache_set +#define ssl_cache_set_max_entries mbedtls_ssl_cache_set_max_entries +#define ssl_cache_set_timeout mbedtls_ssl_cache_set_timeout +#define ssl_check_cert_usage mbedtls_ssl_check_cert_usage +#define ssl_ciphersuite_from_id mbedtls_ssl_ciphersuite_from_id +#define ssl_ciphersuite_from_string mbedtls_ssl_ciphersuite_from_string +#define ssl_ciphersuite_t mbedtls_ssl_ciphersuite_t +#define ssl_ciphersuite_uses_ec mbedtls_ssl_ciphersuite_uses_ec +#define ssl_ciphersuite_uses_psk mbedtls_ssl_ciphersuite_uses_psk +#define ssl_close_notify mbedtls_ssl_close_notify +#define ssl_context mbedtls_ssl_context +#define ssl_cookie_check mbedtls_ssl_cookie_check +#define ssl_cookie_check_t mbedtls_ssl_cookie_check_t +#define ssl_cookie_ctx mbedtls_ssl_cookie_ctx +#define ssl_cookie_free mbedtls_ssl_cookie_free +#define ssl_cookie_init mbedtls_ssl_cookie_init +#define ssl_cookie_set_timeout mbedtls_ssl_cookie_set_timeout +#define ssl_cookie_setup mbedtls_ssl_cookie_setup +#define ssl_cookie_write mbedtls_ssl_cookie_write +#define ssl_cookie_write_t mbedtls_ssl_cookie_write_t +#define ssl_derive_keys mbedtls_ssl_derive_keys +#define ssl_dtls_replay_check mbedtls_ssl_dtls_replay_check +#define ssl_dtls_replay_update mbedtls_ssl_dtls_replay_update +#define ssl_fetch_input mbedtls_ssl_fetch_input +#define ssl_flight_item mbedtls_ssl_flight_item +#define ssl_flush_output mbedtls_ssl_flush_output +#define ssl_free mbedtls_ssl_free +#define ssl_get_alpn_protocol mbedtls_ssl_get_alpn_protocol +#define ssl_get_bytes_avail mbedtls_ssl_get_bytes_avail +#define ssl_get_ciphersuite mbedtls_ssl_get_ciphersuite +#define ssl_get_ciphersuite_id mbedtls_ssl_get_ciphersuite_id +#define ssl_get_ciphersuite_name mbedtls_ssl_get_ciphersuite_name +#define ssl_get_ciphersuite_sig_pk_alg mbedtls_ssl_get_ciphersuite_sig_pk_alg +#define ssl_get_peer_cert mbedtls_ssl_get_peer_cert +#define ssl_get_record_expansion mbedtls_ssl_get_record_expansion +#define ssl_get_session mbedtls_ssl_get_session +#define ssl_get_verify_result mbedtls_ssl_get_verify_result +#define ssl_get_version mbedtls_ssl_get_version +#define ssl_handshake mbedtls_ssl_handshake +#define ssl_handshake_client_step mbedtls_ssl_handshake_client_step +#define ssl_handshake_free mbedtls_ssl_handshake_free +#define ssl_handshake_params mbedtls_ssl_handshake_params +#define ssl_handshake_server_step mbedtls_ssl_handshake_server_step +#define ssl_handshake_step mbedtls_ssl_handshake_step +#define ssl_handshake_wrapup mbedtls_ssl_handshake_wrapup +#define ssl_hdr_len mbedtls_ssl_hdr_len +#define ssl_hs_hdr_len mbedtls_ssl_hs_hdr_len +#define ssl_hw_record_activate mbedtls_ssl_hw_record_activate +#define ssl_hw_record_finish mbedtls_ssl_hw_record_finish +#define ssl_hw_record_init mbedtls_ssl_hw_record_init +#define ssl_hw_record_read mbedtls_ssl_hw_record_read +#define ssl_hw_record_reset mbedtls_ssl_hw_record_reset +#define ssl_hw_record_write mbedtls_ssl_hw_record_write +#define ssl_init mbedtls_ssl_init +#define ssl_key_cert mbedtls_ssl_key_cert +#define ssl_legacy_renegotiation mbedtls_ssl_conf_legacy_renegotiation +#define ssl_list_ciphersuites mbedtls_ssl_list_ciphersuites +#define ssl_md_alg_from_hash mbedtls_ssl_md_alg_from_hash +#define ssl_optimize_checksum mbedtls_ssl_optimize_checksum +#define ssl_own_cert mbedtls_ssl_own_cert +#define ssl_own_key mbedtls_ssl_own_key +#define ssl_parse_certificate mbedtls_ssl_parse_certificate +#define ssl_parse_change_cipher_spec mbedtls_ssl_parse_change_cipher_spec +#define ssl_parse_finished mbedtls_ssl_parse_finished +#define ssl_pk_alg_from_sig mbedtls_ssl_pk_alg_from_sig +#define ssl_pkcs11_decrypt mbedtls_ssl_pkcs11_decrypt +#define ssl_pkcs11_key_len mbedtls_ssl_pkcs11_key_len +#define ssl_pkcs11_sign mbedtls_ssl_pkcs11_sign +#define ssl_psk_derive_premaster mbedtls_ssl_psk_derive_premaster +#define ssl_read mbedtls_ssl_read +#define ssl_read_record mbedtls_ssl_read_record +#define ssl_read_version mbedtls_ssl_read_version +#define ssl_recv_flight_completed mbedtls_ssl_recv_flight_completed +#define ssl_renegotiate mbedtls_ssl_renegotiate +#define ssl_resend mbedtls_ssl_resend +#define ssl_reset_checksum mbedtls_ssl_reset_checksum +#define ssl_send_alert_message mbedtls_ssl_send_alert_message +#define ssl_send_fatal_handshake_failure mbedtls_ssl_send_fatal_handshake_failure +#define ssl_send_flight_completed mbedtls_ssl_send_flight_completed +#define ssl_session mbedtls_ssl_session +#define ssl_session_free mbedtls_ssl_session_free +#define ssl_session_init mbedtls_ssl_session_init +#define ssl_session_reset mbedtls_ssl_session_reset +#define ssl_set_alpn_protocols mbedtls_ssl_conf_alpn_protocols +#define ssl_set_arc4_support mbedtls_ssl_conf_arc4_support +#define ssl_set_authmode mbedtls_ssl_conf_authmode +#define ssl_set_bio mbedtls_ssl_set_bio +#define ssl_set_ca_chain mbedtls_ssl_conf_ca_chain +#define ssl_set_cbc_record_splitting mbedtls_ssl_conf_cbc_record_splitting +#define ssl_set_ciphersuites mbedtls_ssl_conf_ciphersuites +#define ssl_set_ciphersuites_for_version mbedtls_ssl_conf_ciphersuites_for_version +#define ssl_set_client_transport_id mbedtls_ssl_set_client_transport_id +#define ssl_set_curves mbedtls_ssl_conf_curves +#define ssl_set_dbg mbedtls_ssl_conf_dbg +#define ssl_set_dh_param mbedtls_ssl_conf_dh_param +#define ssl_set_dh_param_ctx mbedtls_ssl_conf_dh_param_ctx +#define ssl_set_dtls_anti_replay mbedtls_ssl_conf_dtls_anti_replay +#define ssl_set_dtls_badmac_limit mbedtls_ssl_conf_dtls_badmac_limit +#define ssl_set_dtls_cookies mbedtls_ssl_conf_dtls_cookies +#define ssl_set_encrypt_then_mac mbedtls_ssl_conf_encrypt_then_mac +#define ssl_set_endpoint mbedtls_ssl_conf_endpoint +#define ssl_set_extended_master_secret mbedtls_ssl_conf_extended_master_secret +#define ssl_set_fallback mbedtls_ssl_conf_fallback +#define ssl_set_handshake_timeout mbedtls_ssl_conf_handshake_timeout +#define ssl_set_hostname mbedtls_ssl_set_hostname +#define ssl_set_max_frag_len mbedtls_ssl_conf_max_frag_len +#define ssl_set_max_version mbedtls_ssl_conf_max_version +#define ssl_set_min_version mbedtls_ssl_conf_min_version +#define ssl_set_own_cert mbedtls_ssl_conf_own_cert +#define ssl_set_psk mbedtls_ssl_conf_psk +#define ssl_set_psk_cb mbedtls_ssl_conf_psk_cb +#define ssl_set_renegotiation mbedtls_ssl_conf_renegotiation +#define ssl_set_renegotiation_enforced mbedtls_ssl_conf_renegotiation_enforced +#define ssl_set_renegotiation_period mbedtls_ssl_conf_renegotiation_period +#define ssl_set_rng mbedtls_ssl_conf_rng +#define ssl_set_session mbedtls_ssl_set_session +#define ssl_set_session_cache mbedtls_ssl_conf_session_cache +#define ssl_set_session_tickets mbedtls_ssl_conf_session_tickets +#define ssl_set_sni mbedtls_ssl_conf_sni +#define ssl_set_transport mbedtls_ssl_conf_transport +#define ssl_set_truncated_hmac mbedtls_ssl_conf_truncated_hmac +#define ssl_set_verify mbedtls_ssl_conf_verify +#define ssl_sig_from_pk mbedtls_ssl_sig_from_pk +#define ssl_states mbedtls_ssl_states +#define ssl_transform mbedtls_ssl_transform +#define ssl_transform_free mbedtls_ssl_transform_free +#define ssl_write mbedtls_ssl_write +#define ssl_write_certificate mbedtls_ssl_write_certificate +#define ssl_write_change_cipher_spec mbedtls_ssl_write_change_cipher_spec +#define ssl_write_finished mbedtls_ssl_write_finished +#define ssl_write_record mbedtls_ssl_write_record +#define ssl_write_version mbedtls_ssl_write_version +#define supported_ciphers mbedtls_cipher_supported +#define t_sint mbedtls_mpi_sint +#define t_udbl mbedtls_t_udbl +#define t_uint mbedtls_mpi_uint +#define test_ca_crt mbedtls_test_ca_crt +#define test_ca_crt_ec mbedtls_test_ca_crt_ec +#define test_ca_crt_rsa mbedtls_test_ca_crt_rsa +#define test_ca_key mbedtls_test_ca_key +#define test_ca_key_ec mbedtls_test_ca_key_ec +#define test_ca_key_rsa mbedtls_test_ca_key_rsa +#define test_ca_list mbedtls_test_cas_pem +#define test_ca_pwd mbedtls_test_ca_pwd +#define test_ca_pwd_ec mbedtls_test_ca_pwd_ec +#define test_ca_pwd_rsa mbedtls_test_ca_pwd_rsa +#define test_cli_crt mbedtls_test_cli_crt +#define test_cli_crt_ec mbedtls_test_cli_crt_ec +#define test_cli_crt_rsa mbedtls_test_cli_crt_rsa +#define test_cli_key mbedtls_test_cli_key +#define test_cli_key_ec mbedtls_test_cli_key_ec +#define test_cli_key_rsa mbedtls_test_cli_key_rsa +#define test_srv_crt mbedtls_test_srv_crt +#define test_srv_crt_ec mbedtls_test_srv_crt_ec +#define test_srv_crt_rsa mbedtls_test_srv_crt_rsa +#define test_srv_key mbedtls_test_srv_key +#define test_srv_key_ec mbedtls_test_srv_key_ec +#define test_srv_key_rsa mbedtls_test_srv_key_rsa +#define threading_mutex_t mbedtls_threading_mutex_t +#define threading_set_alt mbedtls_threading_set_alt +#define timing_self_test mbedtls_timing_self_test +#define version_check_feature mbedtls_version_check_feature +#define version_get_number mbedtls_version_get_number +#define version_get_string mbedtls_version_get_string +#define version_get_string_full mbedtls_version_get_string_full +#define x509_bitstring mbedtls_x509_bitstring +#define x509_buf mbedtls_x509_buf +#define x509_crl mbedtls_x509_crl +#define x509_crl_entry mbedtls_x509_crl_entry +#define x509_crl_free mbedtls_x509_crl_free +#define x509_crl_info mbedtls_x509_crl_info +#define x509_crl_init mbedtls_x509_crl_init +#define x509_crl_parse mbedtls_x509_crl_parse +#define x509_crl_parse_der mbedtls_x509_crl_parse_der +#define x509_crl_parse_file mbedtls_x509_crl_parse_file +#define x509_crt mbedtls_x509_crt +#define x509_crt_check_extended_key_usage mbedtls_x509_crt_check_extended_key_usage +#define x509_crt_check_key_usage mbedtls_x509_crt_check_key_usage +#define x509_crt_free mbedtls_x509_crt_free +#define x509_crt_info mbedtls_x509_crt_info +#define x509_crt_init mbedtls_x509_crt_init +#define x509_crt_parse mbedtls_x509_crt_parse +#define x509_crt_parse_der mbedtls_x509_crt_parse_der +#define x509_crt_parse_file mbedtls_x509_crt_parse_file +#define x509_crt_parse_path mbedtls_x509_crt_parse_path +#define x509_crt_revoked mbedtls_x509_crt_is_revoked +#define x509_crt_verify mbedtls_x509_crt_verify +#define x509_csr mbedtls_x509_csr +#define x509_csr_free mbedtls_x509_csr_free +#define x509_csr_info mbedtls_x509_csr_info +#define x509_csr_init mbedtls_x509_csr_init +#define x509_csr_parse mbedtls_x509_csr_parse +#define x509_csr_parse_der mbedtls_x509_csr_parse_der +#define x509_csr_parse_file mbedtls_x509_csr_parse_file +#define x509_dn_gets mbedtls_x509_dn_gets +#define x509_get_alg mbedtls_x509_get_alg +#define x509_get_alg_null mbedtls_x509_get_alg_null +#define x509_get_ext mbedtls_x509_get_ext +#define x509_get_name mbedtls_x509_get_name +#define x509_get_rsassa_pss_params mbedtls_x509_get_rsassa_pss_params +#define x509_get_serial mbedtls_x509_get_serial +#define x509_get_sig mbedtls_x509_get_sig +#define x509_get_sig_alg mbedtls_x509_get_sig_alg +#define x509_get_time mbedtls_x509_get_time +#define x509_key_size_helper mbedtls_x509_key_size_helper +#define x509_name mbedtls_x509_name +#define x509_self_test mbedtls_x509_self_test +#define x509_sequence mbedtls_x509_sequence +#define x509_serial_gets mbedtls_x509_serial_gets +#define x509_set_extension mbedtls_x509_set_extension +#define x509_sig_alg_gets mbedtls_x509_sig_alg_gets +#define x509_string_to_names mbedtls_x509_string_to_names +#define x509_time mbedtls_x509_time +#define x509_time_expired mbedtls_x509_time_is_past +#define x509_time_future mbedtls_x509_time_is_future +#define x509_write_extensions mbedtls_x509_write_extensions +#define x509_write_names mbedtls_x509_write_names +#define x509_write_sig mbedtls_x509_write_sig +#define x509write_cert mbedtls_x509write_cert +#define x509write_crt_der mbedtls_x509write_crt_der +#define x509write_crt_free mbedtls_x509write_crt_free +#define x509write_crt_init mbedtls_x509write_crt_init +#define x509write_crt_pem mbedtls_x509write_crt_pem +#define x509write_crt_set_authority_key_identifier mbedtls_x509write_crt_set_authority_key_identifier +#define x509write_crt_set_basic_constraints mbedtls_x509write_crt_set_basic_constraints +#define x509write_crt_set_extension mbedtls_x509write_crt_set_extension +#define x509write_crt_set_issuer_key mbedtls_x509write_crt_set_issuer_key +#define x509write_crt_set_issuer_name mbedtls_x509write_crt_set_issuer_name +#define x509write_crt_set_key_usage mbedtls_x509write_crt_set_key_usage +#define x509write_crt_set_md_alg mbedtls_x509write_crt_set_md_alg +#define x509write_crt_set_ns_cert_type mbedtls_x509write_crt_set_ns_cert_type +#define x509write_crt_set_serial mbedtls_x509write_crt_set_serial +#define x509write_crt_set_subject_key mbedtls_x509write_crt_set_subject_key +#define x509write_crt_set_subject_key_identifier mbedtls_x509write_crt_set_subject_key_identifier +#define x509write_crt_set_subject_name mbedtls_x509write_crt_set_subject_name +#define x509write_crt_set_validity mbedtls_x509write_crt_set_validity +#define x509write_crt_set_version mbedtls_x509write_crt_set_version +#define x509write_csr mbedtls_x509write_csr +#define x509write_csr_der mbedtls_x509write_csr_der +#define x509write_csr_free mbedtls_x509write_csr_free +#define x509write_csr_init mbedtls_x509write_csr_init +#define x509write_csr_pem mbedtls_x509write_csr_pem +#define x509write_csr_set_extension mbedtls_x509write_csr_set_extension +#define x509write_csr_set_key mbedtls_x509write_csr_set_key +#define x509write_csr_set_key_usage mbedtls_x509write_csr_set_key_usage +#define x509write_csr_set_md_alg mbedtls_x509write_csr_set_md_alg +#define x509write_csr_set_ns_cert_type mbedtls_x509write_csr_set_ns_cert_type +#define x509write_csr_set_subject_name mbedtls_x509write_csr_set_subject_name +#define xtea_context mbedtls_xtea_context +#define xtea_crypt_cbc mbedtls_xtea_crypt_cbc +#define xtea_crypt_ecb mbedtls_xtea_crypt_ecb +#define xtea_free mbedtls_xtea_free +#define xtea_init mbedtls_xtea_init +#define xtea_self_test mbedtls_xtea_self_test +#define xtea_setup mbedtls_xtea_setup + +#endif /* compat-1.3.h */ +#endif /* MBEDTLS_DEPRECATED_REMOVED */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/config.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/config.h new file mode 100644 index 0000000000000000000000000000000000000000..69a12d9c5ff79c40a65639ebfa5733398894b425 --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/config.h @@ -0,0 +1,3363 @@ +/** + * \file config.h + * + * \brief Configuration options (set of defines) + * + * This set of compile-time options may be used to enable + * or disable features selectively, and reduce the global + * memory footprint. + */ +/* + * Copyright (C) 2006-2018, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ + +#ifndef MBEDTLS_CONFIG_H +#define MBEDTLS_CONFIG_H + +#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE) +#define _CRT_SECURE_NO_DEPRECATE 1 +#endif + +/** + * \name SECTION: System support + * + * This section sets system specific settings. + * \{ + */ + +/** + * \def MBEDTLS_HAVE_ASM + * + * The compiler has support for asm(). + * + * Requires support for asm() in compiler. + * + * Used in: + * library/aria.c + * library/timing.c + * include/mbedtls/bn_mul.h + * + * Required by: + * MBEDTLS_AESNI_C + * MBEDTLS_PADLOCK_C + * + * Comment to disable the use of assembly code. + */ +#define MBEDTLS_HAVE_ASM + +/** + * \def MBEDTLS_NO_UDBL_DIVISION + * + * The platform lacks support for double-width integer division (64-bit + * division on a 32-bit platform, 128-bit division on a 64-bit platform). + * + * Used in: + * include/mbedtls/bignum.h + * library/bignum.c + * + * The bignum code uses double-width division to speed up some operations. + * Double-width division is often implemented in software that needs to + * be linked with the program. The presence of a double-width integer + * type is usually detected automatically through preprocessor macros, + * but the automatic detection cannot know whether the code needs to + * and can be linked with an implementation of division for that type. + * By default division is assumed to be usable if the type is present. + * Uncomment this option to prevent the use of double-width division. + * + * Note that division for the native integer type is always required. + * Furthermore, a 64-bit type is always required even on a 32-bit + * platform, but it need not support multiplication or division. In some + * cases it is also desirable to disable some double-width operations. For + * example, if double-width division is implemented in software, disabling + * it can reduce code size in some embedded targets. + */ +//#define MBEDTLS_NO_UDBL_DIVISION + +/** + * \def MBEDTLS_NO_64BIT_MULTIPLICATION + * + * The platform lacks support for 32x32 -> 64-bit multiplication. + * + * Used in: + * library/poly1305.c + * + * Some parts of the library may use multiplication of two unsigned 32-bit + * operands with a 64-bit result in order to speed up computations. On some + * platforms, this is not available in hardware and has to be implemented in + * software, usually in a library provided by the toolchain. + * + * Sometimes it is not desirable to have to link to that library. This option + * removes the dependency of that library on platforms that lack a hardware + * 64-bit multiplier by embedding a software implementation in Mbed TLS. + * + * Note that depending on the compiler, this may decrease performance compared + * to using the library function provided by the toolchain. + */ +//#define MBEDTLS_NO_64BIT_MULTIPLICATION + +/** + * \def MBEDTLS_HAVE_SSE2 + * + * CPU supports SSE2 instruction set. + * + * Uncomment if the CPU supports SSE2 (IA-32 specific). + */ +//#define MBEDTLS_HAVE_SSE2 + +/** + * \def MBEDTLS_HAVE_TIME + * + * System has time.h and time(). + * The time does not need to be correct, only time differences are used, + * by contrast with MBEDTLS_HAVE_TIME_DATE + * + * Defining MBEDTLS_HAVE_TIME allows you to specify MBEDTLS_PLATFORM_TIME_ALT, + * MBEDTLS_PLATFORM_TIME_MACRO, MBEDTLS_PLATFORM_TIME_TYPE_MACRO and + * MBEDTLS_PLATFORM_STD_TIME. + * + * Comment if your system does not support time functions + */ +#define MBEDTLS_HAVE_TIME + +/** + * \def MBEDTLS_HAVE_TIME_DATE + * + * System has time.h, time(), and an implementation for + * mbedtls_platform_gmtime_r() (see below). + * The time needs to be correct (not necessarily very accurate, but at least + * the date should be correct). This is used to verify the validity period of + * X.509 certificates. + * + * Comment if your system does not have a correct clock. + * + * \note mbedtls_platform_gmtime_r() is an abstraction in platform_util.h that + * behaves similarly to the gmtime_r() function from the C standard. Refer to + * the documentation for mbedtls_platform_gmtime_r() for more information. + * + * \note It is possible to configure an implementation for + * mbedtls_platform_gmtime_r() at compile-time by using the macro + * MBEDTLS_PLATFORM_GMTIME_R_ALT. + */ +// #define MBEDTLS_HAVE_TIME_DATE + +/** + * \def MBEDTLS_PLATFORM_MEMORY + * + * Enable the memory allocation layer. + * + * By default mbed TLS uses the system-provided calloc() and free(). + * This allows different allocators (self-implemented or provided) to be + * provided to the platform abstraction layer. + * + * Enabling MBEDTLS_PLATFORM_MEMORY without the + * MBEDTLS_PLATFORM_{FREE,CALLOC}_MACROs will provide + * "mbedtls_platform_set_calloc_free()" allowing you to set an alternative calloc() and + * free() function pointer at runtime. + * + * Enabling MBEDTLS_PLATFORM_MEMORY and specifying + * MBEDTLS_PLATFORM_{CALLOC,FREE}_MACROs will allow you to specify the + * alternate function at compile time. + * + * Requires: MBEDTLS_PLATFORM_C + * + * Enable this layer to allow use of alternative memory allocators. + */ +#define MBEDTLS_PLATFORM_MEMORY + +/** + * \def MBEDTLS_PLATFORM_NO_STD_FUNCTIONS + * + * Do not assign standard functions in the platform layer (e.g. calloc() to + * MBEDTLS_PLATFORM_STD_CALLOC and printf() to MBEDTLS_PLATFORM_STD_PRINTF) + * + * This makes sure there are no linking errors on platforms that do not support + * these functions. You will HAVE to provide alternatives, either at runtime + * via the platform_set_xxx() functions or at compile time by setting + * the MBEDTLS_PLATFORM_STD_XXX defines, or enabling a + * MBEDTLS_PLATFORM_XXX_MACRO. + * + * Requires: MBEDTLS_PLATFORM_C + * + * Uncomment to prevent default assignment of standard functions in the + * platform layer. + */ +//#define MBEDTLS_PLATFORM_NO_STD_FUNCTIONS + +/** + * \def MBEDTLS_PLATFORM_EXIT_ALT + * + * MBEDTLS_PLATFORM_XXX_ALT: Uncomment a macro to let mbed TLS support the + * function in the platform abstraction layer. + * + * Example: In case you uncomment MBEDTLS_PLATFORM_PRINTF_ALT, mbed TLS will + * provide a function "mbedtls_platform_set_printf()" that allows you to set an + * alternative printf function pointer. + * + * All these define require MBEDTLS_PLATFORM_C to be defined! + * + * \note MBEDTLS_PLATFORM_SNPRINTF_ALT is required on Windows; + * it will be enabled automatically by check_config.h + * + * \warning MBEDTLS_PLATFORM_XXX_ALT cannot be defined at the same time as + * MBEDTLS_PLATFORM_XXX_MACRO! + * + * Requires: MBEDTLS_PLATFORM_TIME_ALT requires MBEDTLS_HAVE_TIME + * + * Uncomment a macro to enable alternate implementation of specific base + * platform function + */ +//#define MBEDTLS_PLATFORM_EXIT_ALT +#define MBEDTLS_PLATFORM_TIME_ALT +//#define MBEDTLS_PLATFORM_FPRINTF_ALT +//#define MBEDTLS_PLATFORM_PRINTF_ALT +//#define MBEDTLS_PLATFORM_SNPRINTF_ALT +//#define MBEDTLS_PLATFORM_NV_SEED_ALT +//#define MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT + +/** + * \def MBEDTLS_DEPRECATED_WARNING + * + * Mark deprecated functions so that they generate a warning if used. + * Functions deprecated in one version will usually be removed in the next + * version. You can enable this to help you prepare the transition to a new + * major version by making sure your code is not using these functions. + * + * This only works with GCC and Clang. With other compilers, you may want to + * use MBEDTLS_DEPRECATED_REMOVED + * + * Uncomment to get warnings on using deprecated functions. + */ +//#define MBEDTLS_DEPRECATED_WARNING + +/** + * \def MBEDTLS_DEPRECATED_REMOVED + * + * Remove deprecated functions so that they generate an error if used. + * Functions deprecated in one version will usually be removed in the next + * version. You can enable this to help you prepare the transition to a new + * major version by making sure your code is not using these functions. + * + * Uncomment to get errors on using deprecated functions. + */ +//#define MBEDTLS_DEPRECATED_REMOVED + +/** + * \def MBEDTLS_CHECK_PARAMS + * + * This configuration option controls whether the library validates more of + * the parameters passed to it. + * + * When this flag is not defined, the library only attempts to validate an + * input parameter if: (1) they may come from the outside world (such as the + * network, the filesystem, etc.) or (2) not validating them could result in + * internal memory errors such as overflowing a buffer controlled by the + * library. On the other hand, it doesn't attempt to validate parameters whose + * values are fully controlled by the application (such as pointers). + * + * When this flag is defined, the library additionally attempts to validate + * parameters that are fully controlled by the application, and should always + * be valid if the application code is fully correct and trusted. + * + * For example, when a function accepts as input a pointer to a buffer that may + * contain untrusted data, and its documentation mentions that this pointer + * must not be NULL: + * - The pointer is checked to be non-NULL only if this option is enabled. + * - The content of the buffer is always validated. + * + * When this flag is defined, if a library function receives a parameter that + * is invalid: + * 1. The function will invoke the macro MBEDTLS_PARAM_FAILED(). + * 2. If MBEDTLS_PARAM_FAILED() did not terminate the program, the function + * will immediately return. If the function returns an Mbed TLS error code, + * the error code in this case is MBEDTLS_ERR_xxx_BAD_INPUT_DATA. + * + * When defining this flag, you also need to arrange a definition for + * MBEDTLS_PARAM_FAILED(). You can do this by any of the following methods: + * - By default, the library defines MBEDTLS_PARAM_FAILED() to call a + * function mbedtls_param_failed(), but the library does not define this + * function. If you do not make any other arrangements, you must provide + * the function mbedtls_param_failed() in your application. + * See `platform_util.h` for its prototype. + * - If you enable the macro #MBEDTLS_CHECK_PARAMS_ASSERT, then the + * library defines #MBEDTLS_PARAM_FAILED(\c cond) to be `assert(cond)`. + * You can still supply an alternative definition of + * MBEDTLS_PARAM_FAILED(), which may call `assert`. + * - If you define a macro MBEDTLS_PARAM_FAILED() before including `config.h` + * or you uncomment the definition of MBEDTLS_PARAM_FAILED() in `config.h`, + * the library will call the macro that you defined and will not supply + * its own version. Note that if MBEDTLS_PARAM_FAILED() calls `assert`, + * you need to enable #MBEDTLS_CHECK_PARAMS_ASSERT so that library source + * files include ``. + * + * Uncomment to enable validation of application-controlled parameters. + */ +//#define MBEDTLS_CHECK_PARAMS + +/** + * \def MBEDTLS_CHECK_PARAMS_ASSERT + * + * Allow MBEDTLS_PARAM_FAILED() to call `assert`, and make it default to + * `assert`. This macro is only used if #MBEDTLS_CHECK_PARAMS is defined. + * + * If this macro is not defined, then MBEDTLS_PARAM_FAILED() defaults to + * calling a function mbedtls_param_failed(). See the documentation of + * #MBEDTLS_CHECK_PARAMS for details. + * + * Uncomment to allow MBEDTLS_PARAM_FAILED() to call `assert`. + */ +//#define MBEDTLS_CHECK_PARAMS_ASSERT + +/* \} name SECTION: System support */ + +/** + * \name SECTION: mbed TLS feature support + * + * This section sets support for features that are or are not needed + * within the modules that are enabled. + * \{ + */ + +/** + * \def MBEDTLS_TIMING_ALT + * + * Uncomment to provide your own alternate implementation for mbedtls_timing_hardclock(), + * mbedtls_timing_get_timer(), mbedtls_set_alarm(), mbedtls_set/get_delay() + * + * Only works if you have MBEDTLS_TIMING_C enabled. + * + * You will need to provide a header "timing_alt.h" and an implementation at + * compile time. + */ +//#define MBEDTLS_TIMING_ALT + +/** + * \def MBEDTLS_AES_ALT + * + * MBEDTLS__MODULE_NAME__ALT: Uncomment a macro to let mbed TLS use your + * alternate core implementation of a symmetric crypto, an arithmetic or hash + * module (e.g. platform specific assembly optimized implementations). Keep + * in mind that the function prototypes should remain the same. + * + * This replaces the whole module. If you only want to replace one of the + * functions, use one of the MBEDTLS__FUNCTION_NAME__ALT flags. + * + * Example: In case you uncomment MBEDTLS_AES_ALT, mbed TLS will no longer + * provide the "struct mbedtls_aes_context" definition and omit the base + * function declarations and implementations. "aes_alt.h" will be included from + * "aes.h" to include the new function definitions. + * + * Uncomment a macro to enable alternate implementation of the corresponding + * module. + * + * \warning MD2, MD4, MD5, ARC4, DES and SHA-1 are considered weak and their + * use constitutes a security risk. If possible, we recommend + * avoiding dependencies on them, and considering stronger message + * digests and ciphers instead. + * + */ +#define MBEDTLS_AES_ALT +//#define MBEDTLS_ARC4_ALT +//#define MBEDTLS_ARIA_ALT +//#define MBEDTLS_BLOWFISH_ALT +//#define MBEDTLS_CAMELLIA_ALT +#define MBEDTLS_CCM_ALT +//#define MBEDTLS_CHACHA20_ALT +//#define MBEDTLS_CHACHAPOLY_ALT +//#define MBEDTLS_CMAC_ALT +//#define MBEDTLS_DES_ALT +//#define MBEDTLS_DHM_ALT +//#define MBEDTLS_ECJPAKE_ALT +#define MBEDTLS_GCM_ALT +//#define MBEDTLS_NIST_KW_ALT +//#define MBEDTLS_MD2_ALT +//#define MBEDTLS_MD4_ALT +#define MBEDTLS_MD5_ALT +//#define MBEDTLS_POLY1305_ALT +//#define MBEDTLS_RIPEMD160_ALT +//#define MBEDTLS_RSA_ALT +//#define MBEDTLS_SHA1_ALT +//#define MBEDTLS_SHA256_ALT +#define MBEDTLS_SHA512_ALT +//#define MBEDTLS_XTEA_ALT + +/* + * accelerate RSA signature and veification by Hisilicon Cipher + * please be aware that only the SHA256RSA2048 and SHA256RSA4096 could be accelerated. + */ +#define MBEDTLS_RSA_HW_ACCEL_BY_HI_CIPHER + +/* + * accelerate ECDSA signature and veification by Hisilicon Cipher + * please be aware that only the SHA256SECP256R1 and SHA256SECP256K1 and SHA256BP256R1 could be accelerated. + */ +#define MBEDTLS_ECDSA_HW_ACCEL_BY_HI_CIPHER + +/* + * When replacing the elliptic curve module, pleace consider, that it is + * implemented with two .c files: + * - ecp.c + * - ecp_curves.c + * You can replace them very much like all the other MBEDTLS__MODULE_NAME__ALT + * macros as described above. The only difference is that you have to make sure + * that you provide functionality for both .c files. + */ +#define MBEDTLS_ECP_ALT + +/** + * \def MBEDTLS_MD2_PROCESS_ALT + * + * MBEDTLS__FUNCTION_NAME__ALT: Uncomment a macro to let mbed TLS use you + * alternate core implementation of symmetric crypto or hash function. Keep in + * mind that function prototypes should remain the same. + * + * This replaces only one function. The header file from mbed TLS is still + * used, in contrast to the MBEDTLS__MODULE_NAME__ALT flags. + * + * Example: In case you uncomment MBEDTLS_SHA256_PROCESS_ALT, mbed TLS will + * no longer provide the mbedtls_sha1_process() function, but it will still provide + * the other function (using your mbedtls_sha1_process() function) and the definition + * of mbedtls_sha1_context, so your implementation of mbedtls_sha1_process must be compatible + * with this definition. + * + * \note Because of a signature change, the core AES encryption and decryption routines are + * currently named mbedtls_aes_internal_encrypt and mbedtls_aes_internal_decrypt, + * respectively. When setting up alternative implementations, these functions should + * be overridden, but the wrapper functions mbedtls_aes_decrypt and mbedtls_aes_encrypt + * must stay untouched. + * + * \note If you use the AES_xxx_ALT macros, then is is recommended to also set + * MBEDTLS_AES_ROM_TABLES in order to help the linker garbage-collect the AES + * tables. + * + * Uncomment a macro to enable alternate implementation of the corresponding + * function. + * + * \warning MD2, MD4, MD5, DES and SHA-1 are considered weak and their use + * constitutes a security risk. If possible, we recommend avoiding + * dependencies on them, and considering stronger message digests + * and ciphers instead. + * + * \warning If both MBEDTLS_ECDSA_SIGN_ALT and MBEDTLS_ECDSA_DETERMINISTIC are + * enabled, then the deterministic ECDH signature functions pass the + * the static HMAC-DRBG as RNG to mbedtls_ecdsa_sign(). Therefore + * alternative implementations should use the RNG only for generating + * the ephemeral key and nothing else. If this is not possible, then + * MBEDTLS_ECDSA_DETERMINISTIC should be disabled and an alternative + * implementation should be provided for mbedtls_ecdsa_sign_det_ext() + * (and for mbedtls_ecdsa_sign_det() too if backward compatibility is + * desirable). + * + */ +//#define MBEDTLS_MD2_PROCESS_ALT +//#define MBEDTLS_MD4_PROCESS_ALT +//#define MBEDTLS_MD5_PROCESS_ALT +//#define MBEDTLS_RIPEMD160_PROCESS_ALT +//#define MBEDTLS_SHA1_PROCESS_ALT +//#define MBEDTLS_SHA256_PROCESS_ALT +//#define MBEDTLS_SHA512_PROCESS_ALT +//#define MBEDTLS_DES_SETKEY_ALT +//#define MBEDTLS_DES_CRYPT_ECB_ALT +//#define MBEDTLS_DES3_CRYPT_ECB_ALT +//#define MBEDTLS_AES_SETKEY_ENC_ALT +//#define MBEDTLS_AES_SETKEY_DEC_ALT +//#define MBEDTLS_AES_ENCRYPT_ALT +//#define MBEDTLS_AES_DECRYPT_ALT +//#define MBEDTLS_ECDH_GEN_PUBLIC_ALT +//#define MBEDTLS_ECDH_COMPUTE_SHARED_ALT +//#define MBEDTLS_ECDSA_VERIFY_ALT +//#define MBEDTLS_ECDSA_SIGN_ALT +//#define MBEDTLS_ECDSA_GENKEY_ALT + +/** + * \def MBEDTLS_ECP_INTERNAL_ALT + * + * Expose a part of the internal interface of the Elliptic Curve Point module. + * + * MBEDTLS_ECP__FUNCTION_NAME__ALT: Uncomment a macro to let mbed TLS use your + * alternative core implementation of elliptic curve arithmetic. Keep in mind + * that function prototypes should remain the same. + * + * This partially replaces one function. The header file from mbed TLS is still + * used, in contrast to the MBEDTLS_ECP_ALT flag. The original implementation + * is still present and it is used for group structures not supported by the + * alternative. + * + * Any of these options become available by defining MBEDTLS_ECP_INTERNAL_ALT + * and implementing the following functions: + * unsigned char mbedtls_internal_ecp_grp_capable( + * const mbedtls_ecp_group *grp ) + * int mbedtls_internal_ecp_init( const mbedtls_ecp_group *grp ) + * void mbedtls_internal_ecp_free( const mbedtls_ecp_group *grp ) + * The mbedtls_internal_ecp_grp_capable function should return 1 if the + * replacement functions implement arithmetic for the given group and 0 + * otherwise. + * The functions mbedtls_internal_ecp_init and mbedtls_internal_ecp_free are + * called before and after each point operation and provide an opportunity to + * implement optimized set up and tear down instructions. + * + * Example: In case you uncomment MBEDTLS_ECP_INTERNAL_ALT and + * MBEDTLS_ECP_DOUBLE_JAC_ALT, mbed TLS will still provide the ecp_double_jac + * function, but will use your mbedtls_internal_ecp_double_jac if the group is + * supported (your mbedtls_internal_ecp_grp_capable function returns 1 when + * receives it as an argument). If the group is not supported then the original + * implementation is used. The other functions and the definition of + * mbedtls_ecp_group and mbedtls_ecp_point will not change, so your + * implementation of mbedtls_internal_ecp_double_jac and + * mbedtls_internal_ecp_grp_capable must be compatible with this definition. + * + * Uncomment a macro to enable alternate implementation of the corresponding + * function. + */ +/* Required for all the functions in this section */ +//#define MBEDTLS_ECP_INTERNAL_ALT +/* Support for Weierstrass curves with Jacobi representation */ +//#define MBEDTLS_ECP_RANDOMIZE_JAC_ALT +//#define MBEDTLS_ECP_ADD_MIXED_ALT +//#define MBEDTLS_ECP_DOUBLE_JAC_ALT +//#define MBEDTLS_ECP_NORMALIZE_JAC_MANY_ALT +//#define MBEDTLS_ECP_NORMALIZE_JAC_ALT +/* Support for curves with Montgomery arithmetic */ +//#define MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT +//#define MBEDTLS_ECP_RANDOMIZE_MXZ_ALT +//#define MBEDTLS_ECP_NORMALIZE_MXZ_ALT + +/** + * \def MBEDTLS_TEST_NULL_ENTROPY + * + * Enables testing and use of mbed TLS without any configured entropy sources. + * This permits use of the library on platforms before an entropy source has + * been integrated (see for example the MBEDTLS_ENTROPY_HARDWARE_ALT or the + * MBEDTLS_ENTROPY_NV_SEED switches). + * + * WARNING! This switch MUST be disabled in production builds, and is suitable + * only for development. + * Enabling the switch negates any security provided by the library. + * + * Requires MBEDTLS_ENTROPY_C, MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES + * + */ +//#define MBEDTLS_TEST_NULL_ENTROPY + +/** + * \def MBEDTLS_ENTROPY_HARDWARE_ALT + * + * Uncomment this macro to let mbed TLS use your own implementation of a + * hardware entropy collector. + * + * Your function must be called \c mbedtls_hardware_poll(), have the same + * prototype as declared in entropy_poll.h, and accept NULL as first argument. + * + * Uncomment to use your own hardware entropy collector. + */ +#define MBEDTLS_ENTROPY_HARDWARE_ALT + +/** + * \def MBEDTLS_AES_ROM_TABLES + * + * Use precomputed AES tables stored in ROM. + * + * Uncomment this macro to use precomputed AES tables stored in ROM. + * Comment this macro to generate AES tables in RAM at runtime. + * + * Tradeoff: Using precomputed ROM tables reduces RAM usage by ~8kb + * (or ~2kb if \c MBEDTLS_AES_FEWER_TABLES is used) and reduces the + * initialization time before the first AES operation can be performed. + * It comes at the cost of additional ~8kb ROM use (resp. ~2kb if \c + * MBEDTLS_AES_FEWER_TABLES below is used), and potentially degraded + * performance if ROM access is slower than RAM access. + * + * This option is independent of \c MBEDTLS_AES_FEWER_TABLES. + * + */ +//#define MBEDTLS_AES_ROM_TABLES + +/** + * \def MBEDTLS_AES_FEWER_TABLES + * + * Use less ROM/RAM for AES tables. + * + * Uncommenting this macro omits 75% of the AES tables from + * ROM / RAM (depending on the value of \c MBEDTLS_AES_ROM_TABLES) + * by computing their values on the fly during operations + * (the tables are entry-wise rotations of one another). + * + * Tradeoff: Uncommenting this reduces the RAM / ROM footprint + * by ~6kb but at the cost of more arithmetic operations during + * runtime. Specifically, one has to compare 4 accesses within + * different tables to 4 accesses with additional arithmetic + * operations within the same table. The performance gain/loss + * depends on the system and memory details. + * + * This option is independent of \c MBEDTLS_AES_ROM_TABLES. + * + */ +//#define MBEDTLS_AES_FEWER_TABLES + +/** + * \def MBEDTLS_CAMELLIA_SMALL_MEMORY + * + * Use less ROM for the Camellia implementation (saves about 768 bytes). + * + * Uncomment this macro to use less memory for Camellia. + */ +//#define MBEDTLS_CAMELLIA_SMALL_MEMORY + +/** + * \def MBEDTLS_CIPHER_MODE_CBC + * + * Enable Cipher Block Chaining mode (CBC) for symmetric ciphers. + */ +#define MBEDTLS_CIPHER_MODE_CBC + +/** + * \def MBEDTLS_CIPHER_MODE_CFB + * + * Enable Cipher Feedback mode (CFB) for symmetric ciphers. + */ +#define MBEDTLS_CIPHER_MODE_CFB + +/** + * \def MBEDTLS_CIPHER_MODE_CTR + * + * Enable Counter Block Cipher mode (CTR) for symmetric ciphers. + */ +#define MBEDTLS_CIPHER_MODE_CTR + +/** + * \def MBEDTLS_CIPHER_MODE_OFB + * + * Enable Output Feedback mode (OFB) for symmetric ciphers. + */ +//#define MBEDTLS_CIPHER_MODE_OFB + +/** + * \def MBEDTLS_CIPHER_MODE_XTS + * + * Enable Xor-encrypt-xor with ciphertext stealing mode (XTS) for AES. + */ +//#define MBEDTLS_CIPHER_MODE_XTS + +/** + * \def MBEDTLS_CIPHER_NULL_CIPHER + * + * Enable NULL cipher. + * Warning: Only do so when you know what you are doing. This allows for + * encryption or channels without any security! + * + * Requires MBEDTLS_ENABLE_WEAK_CIPHERSUITES as well to enable + * the following ciphersuites: + * MBEDTLS_TLS_ECDH_ECDSA_WITH_NULL_SHA + * MBEDTLS_TLS_ECDH_RSA_WITH_NULL_SHA + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_NULL_SHA + * MBEDTLS_TLS_ECDHE_RSA_WITH_NULL_SHA + * MBEDTLS_TLS_ECDHE_PSK_WITH_NULL_SHA384 + * MBEDTLS_TLS_ECDHE_PSK_WITH_NULL_SHA256 + * MBEDTLS_TLS_ECDHE_PSK_WITH_NULL_SHA + * MBEDTLS_TLS_DHE_PSK_WITH_NULL_SHA384 + * MBEDTLS_TLS_DHE_PSK_WITH_NULL_SHA256 + * MBEDTLS_TLS_DHE_PSK_WITH_NULL_SHA + * MBEDTLS_TLS_RSA_WITH_NULL_SHA256 + * MBEDTLS_TLS_RSA_WITH_NULL_SHA + * MBEDTLS_TLS_RSA_WITH_NULL_MD5 + * MBEDTLS_TLS_RSA_PSK_WITH_NULL_SHA384 + * MBEDTLS_TLS_RSA_PSK_WITH_NULL_SHA256 + * MBEDTLS_TLS_RSA_PSK_WITH_NULL_SHA + * MBEDTLS_TLS_PSK_WITH_NULL_SHA384 + * MBEDTLS_TLS_PSK_WITH_NULL_SHA256 + * MBEDTLS_TLS_PSK_WITH_NULL_SHA + * + * Uncomment this macro to enable the NULL cipher and ciphersuites + */ +//#define MBEDTLS_CIPHER_NULL_CIPHER + +/** + * \def MBEDTLS_CIPHER_PADDING_PKCS7 + * + * MBEDTLS_CIPHER_PADDING_XXX: Uncomment or comment macros to add support for + * specific padding modes in the cipher layer with cipher modes that support + * padding (e.g. CBC) + * + * If you disable all padding modes, only full blocks can be used with CBC. + * + * Enable padding modes in the cipher layer. + */ +#define MBEDTLS_CIPHER_PADDING_PKCS7 +#define MBEDTLS_CIPHER_PADDING_ONE_AND_ZEROS +#define MBEDTLS_CIPHER_PADDING_ZEROS_AND_LEN +#define MBEDTLS_CIPHER_PADDING_ZEROS + +/** \def MBEDTLS_CTR_DRBG_USE_128_BIT_KEY + * + * Uncomment this macro to use a 128-bit key in the CTR_DRBG module. + * By default, CTR_DRBG uses a 256-bit key. + */ +//#define MBEDTLS_CTR_DRBG_USE_128_BIT_KEY + +/** + * \def MBEDTLS_ENABLE_WEAK_CIPHERSUITES + * + * Enable weak ciphersuites in SSL / TLS. + * Warning: Only do so when you know what you are doing. This allows for + * channels with virtually no security at all! + * + * This enables the following ciphersuites: + * MBEDTLS_TLS_RSA_WITH_DES_CBC_SHA + * MBEDTLS_TLS_DHE_RSA_WITH_DES_CBC_SHA + * + * Uncomment this macro to enable weak ciphersuites + * + * \warning DES is considered a weak cipher and its use constitutes a + * security risk. We recommend considering stronger ciphers instead. + */ +//#define MBEDTLS_ENABLE_WEAK_CIPHERSUITES + +/** + * \def MBEDTLS_REMOVE_ARC4_CIPHERSUITES + * + * Remove RC4 ciphersuites by default in SSL / TLS. + * This flag removes the ciphersuites based on RC4 from the default list as + * returned by mbedtls_ssl_list_ciphersuites(). However, it is still possible to + * enable (some of) them with mbedtls_ssl_conf_ciphersuites() by including them + * explicitly. + * + * Uncomment this macro to remove RC4 ciphersuites by default. + */ +#define MBEDTLS_REMOVE_ARC4_CIPHERSUITES + +/** + * \def MBEDTLS_REMOVE_3DES_CIPHERSUITES + * + * Remove 3DES ciphersuites by default in SSL / TLS. + * This flag removes the ciphersuites based on 3DES from the default list as + * returned by mbedtls_ssl_list_ciphersuites(). However, it is still possible + * to enable (some of) them with mbedtls_ssl_conf_ciphersuites() by including + * them explicitly. + * + * A man-in-the-browser attacker can recover authentication tokens sent through + * a TLS connection using a 3DES based cipher suite (see "On the Practical + * (In-)Security of 64-bit Block Ciphers" by Karthikeyan Bhargavan and Gaëtan + * Leurent, see https://sweet32.info/SWEET32_CCS16.pdf). If this attack falls + * in your threat model or you are unsure, then you should keep this option + * enabled to remove 3DES based cipher suites. + * + * Comment this macro to keep 3DES in the default ciphersuite list. + */ +#define MBEDTLS_REMOVE_3DES_CIPHERSUITES + +/** + * \def MBEDTLS_ECP_DP_SECP192R1_ENABLED + * + * MBEDTLS_ECP_XXXX_ENABLED: Enables specific curves within the Elliptic Curve + * module. By default all supported curves are enabled. + * + * Comment macros to disable the curve and functions for it + */ +//#define MBEDTLS_ECP_DP_SECP192R1_ENABLED +//#define MBEDTLS_ECP_DP_SECP224R1_ENABLED +#define MBEDTLS_ECP_DP_SECP256R1_ENABLED +/* open ECP_DP_SECP384R1 for PKI certifaction write. */ +#define MBEDTLS_ECP_DP_SECP384R1_ENABLED +//#define MBEDTLS_ECP_DP_SECP521R1_ENABLED +//#define MBEDTLS_ECP_DP_SECP192K1_ENABLED +//#define MBEDTLS_ECP_DP_SECP224K1_ENABLED +//#define MBEDTLS_ECP_DP_SECP256K1_ENABLED +#define MBEDTLS_ECP_DP_BP256R1_ENABLED +//#define MBEDTLS_ECP_DP_BP384R1_ENABLED +//#define MBEDTLS_ECP_DP_BP512R1_ENABLED +#define MBEDTLS_ECP_DP_CURVE25519_ENABLED +//#define MBEDTLS_ECP_DP_CURVE448_ENABLED + +/** + * \def MBEDTLS_ECP_NIST_OPTIM + * + * Enable specific 'modulo p' routines for each NIST prime. + * Depending on the prime and architecture, makes operations 4 to 8 times + * faster on the corresponding curve. + * + * Comment this macro to disable NIST curves optimisation. + */ +#define MBEDTLS_ECP_NIST_OPTIM + +/** + * \def MBEDTLS_ECP_RESTARTABLE + * + * Enable "non-blocking" ECC operations that can return early and be resumed. + * + * This allows various functions to pause by returning + * #MBEDTLS_ERR_ECP_IN_PROGRESS (or, for functions in the SSL module, + * #MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS) and then be called later again in + * order to further progress and eventually complete their operation. This is + * controlled through mbedtls_ecp_set_max_ops() which limits the maximum + * number of ECC operations a function may perform before pausing; see + * mbedtls_ecp_set_max_ops() for more information. + * + * This is useful in non-threaded environments if you want to avoid blocking + * for too long on ECC (and, hence, X.509 or SSL/TLS) operations. + * + * Uncomment this macro to enable restartable ECC computations. + * + * \note This option only works with the default software implementation of + * elliptic curve functionality. It is incompatible with + * MBEDTLS_ECP_ALT, MBEDTLS_ECDH_XXX_ALT and MBEDTLS_ECDSA_XXX_ALT. + */ +//#define MBEDTLS_ECP_RESTARTABLE + +/** + * \def MBEDTLS_ECDSA_DETERMINISTIC + * + * Enable deterministic ECDSA (RFC 6979). + * Standard ECDSA is "fragile" in the sense that lack of entropy when signing + * may result in a compromise of the long-term signing key. This is avoided by + * the deterministic variant. + * + * Requires: MBEDTLS_HMAC_DRBG_C + * + * Comment this macro to disable deterministic ECDSA. + */ +//#define MBEDTLS_ECDSA_DETERMINISTIC + +/** + * \def MBEDTLS_KEY_EXCHANGE_PSK_ENABLED + * + * Enable the PSK based ciphersuite modes in SSL / TLS. + * + * This enables the following ciphersuites (if other requisites are + * enabled as well): + * MBEDTLS_TLS_PSK_WITH_AES_256_GCM_SHA384 + * MBEDTLS_TLS_PSK_WITH_AES_256_CBC_SHA384 + * MBEDTLS_TLS_PSK_WITH_AES_256_CBC_SHA + * MBEDTLS_TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384 + * MBEDTLS_TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384 + * MBEDTLS_TLS_PSK_WITH_AES_128_GCM_SHA256 + * MBEDTLS_TLS_PSK_WITH_AES_128_CBC_SHA256 + * MBEDTLS_TLS_PSK_WITH_AES_128_CBC_SHA + * MBEDTLS_TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256 + * MBEDTLS_TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256 + * MBEDTLS_TLS_PSK_WITH_3DES_EDE_CBC_SHA + * MBEDTLS_TLS_PSK_WITH_RC4_128_SHA + */ +#define MBEDTLS_KEY_EXCHANGE_PSK_ENABLED + +/** + * \def MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED + * + * Enable the DHE-PSK based ciphersuite modes in SSL / TLS. + * + * Requires: MBEDTLS_DHM_C + * + * This enables the following ciphersuites (if other requisites are + * enabled as well): + * MBEDTLS_TLS_DHE_PSK_WITH_AES_256_GCM_SHA384 + * MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CBC_SHA384 + * MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CBC_SHA + * MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384 + * MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 + * MBEDTLS_TLS_DHE_PSK_WITH_AES_128_GCM_SHA256 + * MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CBC_SHA256 + * MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CBC_SHA + * MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256 + * MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 + * MBEDTLS_TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA + * MBEDTLS_TLS_DHE_PSK_WITH_RC4_128_SHA + * + * \warning Using DHE constitutes a security risk as it + * is not possible to validate custom DH parameters. + * If possible, it is recommended users should consider + * preferring other methods of key exchange. + * See dhm.h for more details. + * + */ +#define MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED + +/** + * \def MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED + * + * Enable the ECDHE-PSK based ciphersuite modes in SSL / TLS. + * + * Requires: MBEDTLS_ECDH_C + * + * This enables the following ciphersuites (if other requisites are + * enabled as well): + * MBEDTLS_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384 + * MBEDTLS_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA + * MBEDTLS_TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 + * MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 + * MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA + * MBEDTLS_TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 + * MBEDTLS_TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA + * MBEDTLS_TLS_ECDHE_PSK_WITH_RC4_128_SHA + */ +#define MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED + +/** + * \def MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED + * + * Enable the RSA-PSK based ciphersuite modes in SSL / TLS. + * + * Requires: MBEDTLS_RSA_C, MBEDTLS_PKCS1_V15, + * MBEDTLS_X509_CRT_PARSE_C + * + * This enables the following ciphersuites (if other requisites are + * enabled as well): + * MBEDTLS_TLS_RSA_PSK_WITH_AES_256_GCM_SHA384 + * MBEDTLS_TLS_RSA_PSK_WITH_AES_256_CBC_SHA384 + * MBEDTLS_TLS_RSA_PSK_WITH_AES_256_CBC_SHA + * MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384 + * MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384 + * MBEDTLS_TLS_RSA_PSK_WITH_AES_128_GCM_SHA256 + * MBEDTLS_TLS_RSA_PSK_WITH_AES_128_CBC_SHA256 + * MBEDTLS_TLS_RSA_PSK_WITH_AES_128_CBC_SHA + * MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256 + * MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256 + * MBEDTLS_TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA + * MBEDTLS_TLS_RSA_PSK_WITH_RC4_128_SHA + */ +//#define MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED + +/** + * \def MBEDTLS_KEY_EXCHANGE_RSA_ENABLED + * + * Enable the RSA-only based ciphersuite modes in SSL / TLS. + * + * Requires: MBEDTLS_RSA_C, MBEDTLS_PKCS1_V15, + * MBEDTLS_X509_CRT_PARSE_C + * + * This enables the following ciphersuites (if other requisites are + * enabled as well): + * MBEDTLS_TLS_RSA_WITH_AES_256_GCM_SHA384 + * MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA256 + * MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA + * MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384 + * MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256 + * MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA + * MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256 + * MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA256 + * MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA + * MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256 + * MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256 + * MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA + * MBEDTLS_TLS_RSA_WITH_3DES_EDE_CBC_SHA + * MBEDTLS_TLS_RSA_WITH_RC4_128_SHA + * MBEDTLS_TLS_RSA_WITH_RC4_128_MD5 + */ +//#define MBEDTLS_KEY_EXCHANGE_RSA_ENABLED + +/** + * \def MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED + * + * Enable the DHE-RSA based ciphersuite modes in SSL / TLS. + * + * Requires: MBEDTLS_DHM_C, MBEDTLS_RSA_C, MBEDTLS_PKCS1_V15, + * MBEDTLS_X509_CRT_PARSE_C + * + * This enables the following ciphersuites (if other requisites are + * enabled as well): + * MBEDTLS_TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 + * MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 + * MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CBC_SHA + * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384 + * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 + * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA + * MBEDTLS_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 + * MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 + * MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA + * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256 + * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 + * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA + * MBEDTLS_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA + * + * \warning Using DHE constitutes a security risk as it + * is not possible to validate custom DH parameters. + * If possible, it is recommended users should consider + * preferring other methods of key exchange. + * See dhm.h for more details. + * + */ +//#define MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED + +/** + * \def MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED + * + * Enable the ECDHE-RSA based ciphersuite modes in SSL / TLS. + * + * Requires: MBEDTLS_ECDH_C, MBEDTLS_RSA_C, MBEDTLS_PKCS1_V15, + * MBEDTLS_X509_CRT_PARSE_C + * + * This enables the following ciphersuites (if other requisites are + * enabled as well): + * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 + * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 + * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA + * MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384 + * MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384 + * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 + * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 + * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA + * MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256 + * MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 + * MBEDTLS_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA + * MBEDTLS_TLS_ECDHE_RSA_WITH_RC4_128_SHA + */ +#define MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED + +/** + * \def MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED + * + * Enable the ECDHE-ECDSA based ciphersuite modes in SSL / TLS. + * + * Requires: MBEDTLS_ECDH_C, MBEDTLS_ECDSA_C, MBEDTLS_X509_CRT_PARSE_C, + * + * This enables the following ciphersuites (if other requisites are + * enabled as well): + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_RC4_128_SHA + */ +#define MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED + +/** + * \def MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED + * + * Enable the ECDH-ECDSA based ciphersuite modes in SSL / TLS. + * + * Requires: MBEDTLS_ECDH_C, MBEDTLS_X509_CRT_PARSE_C + * + * This enables the following ciphersuites (if other requisites are + * enabled as well): + * MBEDTLS_TLS_ECDH_ECDSA_WITH_RC4_128_SHA + * MBEDTLS_TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA + * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA + * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA + * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 + * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 + * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 + * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 + * MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 + * MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 + * MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256 + * MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384 + */ +#define MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED + +/** + * \def MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED + * + * Enable the ECDH-RSA based ciphersuite modes in SSL / TLS. + * + * Requires: MBEDTLS_ECDH_C, MBEDTLS_X509_CRT_PARSE_C + * + * This enables the following ciphersuites (if other requisites are + * enabled as well): + * MBEDTLS_TLS_ECDH_RSA_WITH_RC4_128_SHA + * MBEDTLS_TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA + * MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA + * MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA + * MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 + * MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 + * MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 + * MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384 + * MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256 + * MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384 + * MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256 + * MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384 + */ +//#define MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED + +/** + * \def MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED + * + * Enable the ECJPAKE based ciphersuite modes in SSL / TLS. + * + * \warning This is currently experimental. EC J-PAKE support is based on the + * Thread v1.0.0 specification; incompatible changes to the specification + * might still happen. For this reason, this is disabled by default. + * + * Requires: MBEDTLS_ECJPAKE_C + * MBEDTLS_SHA256_C + * MBEDTLS_ECP_DP_SECP256R1_ENABLED + * + * This enables the following ciphersuites (if other requisites are + * enabled as well): + * MBEDTLS_TLS_ECJPAKE_WITH_AES_128_CCM_8 + */ +//#define MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED + +/** + * \def MBEDTLS_PK_PARSE_EC_EXTENDED + * + * Enhance support for reading EC keys using variants of SEC1 not allowed by + * RFC 5915 and RFC 5480. + * + * Currently this means parsing the SpecifiedECDomain choice of EC + * parameters (only known groups are supported, not arbitrary domains, to + * avoid validation issues). + * + * Disable if you only need to support RFC 5915 + 5480 key formats. + */ +#define MBEDTLS_PK_PARSE_EC_EXTENDED + +/** + * \def MBEDTLS_ERROR_STRERROR_DUMMY + * + * Enable a dummy error function to make use of mbedtls_strerror() in + * third party libraries easier when MBEDTLS_ERROR_C is disabled + * (no effect when MBEDTLS_ERROR_C is enabled). + * + * You can safely disable this if MBEDTLS_ERROR_C is enabled, or if you're + * not using mbedtls_strerror() or error_strerror() in your application. + * + * Disable if you run into name conflicts and want to really remove the + * mbedtls_strerror() + */ +#define MBEDTLS_ERROR_STRERROR_DUMMY + +/** + * \def MBEDTLS_GENPRIME + * + * Enable the prime-number generation code. + * + * Requires: MBEDTLS_BIGNUM_C + */ +#define MBEDTLS_GENPRIME + +/** + * \def MBEDTLS_FS_IO + * + * Enable functions that use the filesystem. + */ +//#define MBEDTLS_FS_IO + +/** + * \def MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES + * + * Do not add default entropy sources. These are the platform specific, + * mbedtls_timing_hardclock and HAVEGE based poll functions. + * + * This is useful to have more control over the added entropy sources in an + * application. + * + * Uncomment this macro to prevent loading of default entropy functions. + */ +//#define MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES + +/** + * \def MBEDTLS_NO_PLATFORM_ENTROPY + * + * Do not use built-in platform entropy functions. + * This is useful if your platform does not support + * standards like the /dev/urandom or Windows CryptoAPI. + * + * Uncomment this macro to disable the built-in platform entropy functions. + */ +#define MBEDTLS_NO_PLATFORM_ENTROPY + +/** + * \def MBEDTLS_ENTROPY_FORCE_SHA256 + * + * Force the entropy accumulator to use a SHA-256 accumulator instead of the + * default SHA-512 based one (if both are available). + * + * Requires: MBEDTLS_SHA256_C + * + * On 32-bit systems SHA-256 can be much faster than SHA-512. Use this option + * if you have performance concerns. + * + * This option is only useful if both MBEDTLS_SHA256_C and + * MBEDTLS_SHA512_C are defined. Otherwise the available hash module is used. + */ +//#define MBEDTLS_ENTROPY_FORCE_SHA256 + +/** + * \def MBEDTLS_ENTROPY_NV_SEED + * + * Enable the non-volatile (NV) seed file-based entropy source. + * (Also enables the NV seed read/write functions in the platform layer) + * + * This is crucial (if not required) on systems that do not have a + * cryptographic entropy source (in hardware or kernel) available. + * + * Requires: MBEDTLS_ENTROPY_C, MBEDTLS_PLATFORM_C + * + * \note The read/write functions that are used by the entropy source are + * determined in the platform layer, and can be modified at runtime and/or + * compile-time depending on the flags (MBEDTLS_PLATFORM_NV_SEED_*) used. + * + * \note If you use the default implementation functions that read a seedfile + * with regular fopen(), please make sure you make a seedfile with the + * proper name (defined in MBEDTLS_PLATFORM_STD_NV_SEED_FILE) and at + * least MBEDTLS_ENTROPY_BLOCK_SIZE bytes in size that can be read from + * and written to or you will get an entropy source error! The default + * implementation will only use the first MBEDTLS_ENTROPY_BLOCK_SIZE + * bytes from the file. + * + * \note The entropy collector will write to the seed file before entropy is + * given to an external source, to update it. + */ +//#define MBEDTLS_ENTROPY_NV_SEED + +/** + * \def MBEDTLS_MEMORY_DEBUG + * + * Enable debugging of buffer allocator memory issues. Automatically prints + * (to stderr) all (fatal) messages on memory allocation issues. Enables + * function for 'debug output' of allocated memory. + * + * Requires: MBEDTLS_MEMORY_BUFFER_ALLOC_C + * + * Uncomment this macro to let the buffer allocator print out error messages. + */ +//#define MBEDTLS_MEMORY_DEBUG + +/** + * \def MBEDTLS_MEMORY_BACKTRACE + * + * Include backtrace information with each allocated block. + * + * Requires: MBEDTLS_MEMORY_BUFFER_ALLOC_C + * GLIBC-compatible backtrace() an backtrace_symbols() support + * + * Uncomment this macro to include backtrace information + */ +//#define MBEDTLS_MEMORY_BACKTRACE + +/** + * \def MBEDTLS_PK_RSA_ALT_SUPPORT + * + * Support external private RSA keys (eg from a HSM) in the PK layer. + * + * Comment this macro to disable support for external private RSA keys. + */ +//#define MBEDTLS_PK_RSA_ALT_SUPPORT + +/** + * \def MBEDTLS_PKCS1_V15 + * + * Enable support for PKCS#1 v1.5 encoding. + * + * Requires: MBEDTLS_RSA_C + * + * This enables support for PKCS#1 v1.5 operations. + */ +#define MBEDTLS_PKCS1_V15 + +/** + * \def MBEDTLS_PKCS1_V21 + * + * Enable support for PKCS#1 v2.1 encoding.(hilink BI https use this.) + * + * Requires: MBEDTLS_MD_C, MBEDTLS_RSA_C + * + * This enables support for RSAES-OAEP and RSASSA-PSS operations. + */ +#define MBEDTLS_PKCS1_V21 + +/** + * \def MBEDTLS_RSA_NO_CRT + * + * Do not use the Chinese Remainder Theorem + * for the RSA private operation. + * + * Uncomment this macro to disable the use of CRT in RSA. + * + */ +#define MBEDTLS_RSA_NO_CRT + +/** + * \def MBEDTLS_SELF_TEST + * + * Enable the checkup functions (*_self_test). + */ +//#define MBEDTLS_SELF_TEST + +/** + * \def MBEDTLS_SHA256_SMALLER + * + * Enable an implementation of SHA-256 that has lower ROM footprint but also + * lower performance. + * + * The default implementation is meant to be a reasonnable compromise between + * performance and size. This version optimizes more aggressively for size at + * the expense of performance. Eg on Cortex-M4 it reduces the size of + * mbedtls_sha256_process() from ~2KB to ~0.5KB for a performance hit of about + * 30%. + * + * Uncomment to enable the smaller implementation of SHA256. + */ +#define MBEDTLS_SHA256_SMALLER + +/** + * \def MBEDTLS_SSL_ALL_ALERT_MESSAGES + * + * Enable sending of alert messages in case of encountered errors as per RFC. + * If you choose not to send the alert messages, mbed TLS can still communicate + * with other servers, only debugging of failures is harder. + * + * The advantage of not sending alert messages, is that no information is given + * about reasons for failures thus preventing adversaries of gaining intel. + * + * Enable sending of all alert messages + */ +#define MBEDTLS_SSL_ALL_ALERT_MESSAGES + +/** + * \def MBEDTLS_SSL_ASYNC_PRIVATE + * + * Enable asynchronous external private key operations in SSL. This allows + * you to configure an SSL connection to call an external cryptographic + * module to perform private key operations instead of performing the + * operation inside the library. + * + */ +//#define MBEDTLS_SSL_ASYNC_PRIVATE + +/** + * \def MBEDTLS_SSL_DEBUG_ALL + * + * Enable the debug messages in SSL module for all issues. + * Debug messages have been disabled in some places to prevent timing + * attacks due to (unbalanced) debugging function calls. + * + * If you need all error reporting you should enable this during debugging, + * but remove this for production servers that should log as well. + * + * Uncomment this macro to report all debug messages on errors introducing + * a timing side-channel. + * + */ +//#define MBEDTLS_SSL_DEBUG_ALL + +/** \def MBEDTLS_SSL_ENCRYPT_THEN_MAC + * + * Enable support for Encrypt-then-MAC, RFC 7366. + * + * This allows peers that both support it to use a more robust protection for + * ciphersuites using CBC, providing deep resistance against timing attacks + * on the padding or underlying cipher. + * + * This only affects CBC ciphersuites, and is useless if none is defined. + * + * Requires: MBEDTLS_SSL_PROTO_TLS1 or + * MBEDTLS_SSL_PROTO_TLS1_1 or + * MBEDTLS_SSL_PROTO_TLS1_2 + * + * Comment this macro to disable support for Encrypt-then-MAC + */ +#define MBEDTLS_SSL_ENCRYPT_THEN_MAC + +/** \def MBEDTLS_SSL_EXTENDED_MASTER_SECRET + * + * Enable support for Extended Master Secret, aka Session Hash + * (draft-ietf-tls-session-hash-02). + * + * This was introduced as "the proper fix" to the Triple Handshake familiy of + * attacks, but it is recommended to always use it (even if you disable + * renegotiation), since it actually fixes a more fundamental issue in the + * original SSL/TLS design, and has implications beyond Triple Handshake. + * + * Requires: MBEDTLS_SSL_PROTO_TLS1 or + * MBEDTLS_SSL_PROTO_TLS1_1 or + * MBEDTLS_SSL_PROTO_TLS1_2 + * + * Comment this macro to disable support for Extended Master Secret. + */ +#define MBEDTLS_SSL_EXTENDED_MASTER_SECRET + +/** + * \def MBEDTLS_SSL_FALLBACK_SCSV + * + * Enable support for FALLBACK_SCSV (draft-ietf-tls-downgrade-scsv-00). + * + * For servers, it is recommended to always enable this, unless you support + * only one version of TLS, or know for sure that none of your clients + * implements a fallback strategy. + * + * For clients, you only need this if you're using a fallback strategy, which + * is not recommended in the first place, unless you absolutely need it to + * interoperate with buggy (version-intolerant) servers. + * + * Comment this macro to disable support for FALLBACK_SCSV + */ +#define MBEDTLS_SSL_FALLBACK_SCSV + +/** + * \def MBEDTLS_SSL_HW_RECORD_ACCEL + * + * Enable hooking functions in SSL module for hardware acceleration of + * individual records. + * + * Uncomment this macro to enable hooking functions. + */ +//#define MBEDTLS_SSL_HW_RECORD_ACCEL + +/** + * \def MBEDTLS_SSL_CBC_RECORD_SPLITTING + * + * Enable 1/n-1 record splitting for CBC mode in SSLv3 and TLS 1.0. + * + * This is a countermeasure to the BEAST attack, which also minimizes the risk + * of interoperability issues compared to sending 0-length records. + * + * Comment this macro to disable 1/n-1 record splitting. + */ +//#define MBEDTLS_SSL_CBC_RECORD_SPLITTING + +/** + * \def MBEDTLS_SSL_RENEGOTIATION + * + * Enable support for TLS renegotiation. + * + * The two main uses of renegotiation are (1) refresh keys on long-lived + * connections and (2) client authentication after the initial handshake. + * If you don't need renegotiation, it's probably better to disable it, since + * it has been associated with security issues in the past and is easy to + * misuse/misunderstand. + * + * Comment this to disable support for renegotiation. + * + * \note Even if this option is disabled, both client and server are aware + * of the Renegotiation Indication Extension (RFC 5746) used to + * prevent the SSL renegotiation attack (see RFC 5746 Sect. 1). + * (See \c mbedtls_ssl_conf_legacy_renegotiation for the + * configuration of this extension). + * + */ +#define MBEDTLS_SSL_RENEGOTIATION + +/** + * \def MBEDTLS_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO + * + * Enable support for receiving and parsing SSLv2 Client Hello messages for the + * SSL Server module (MBEDTLS_SSL_SRV_C). + * + * Uncomment this macro to enable support for SSLv2 Client Hello messages. + */ +//#define MBEDTLS_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO + +/** + * \def MBEDTLS_SSL_SRV_RESPECT_CLIENT_PREFERENCE + * + * Pick the ciphersuite according to the client's preferences rather than ours + * in the SSL Server module (MBEDTLS_SSL_SRV_C). + * + * Uncomment this macro to respect client's ciphersuite order + */ +//#define MBEDTLS_SSL_SRV_RESPECT_CLIENT_PREFERENCE + +/** + * \def MBEDTLS_SSL_MAX_FRAGMENT_LENGTH + * + * Enable support for RFC 6066 max_fragment_length extension in SSL. + * + * Comment this macro to disable support for the max_fragment_length extension + */ +#define MBEDTLS_SSL_MAX_FRAGMENT_LENGTH + +/** + * \def MBEDTLS_SSL_PROTO_SSL3 + * + * Enable support for SSL 3.0. + * + * Requires: MBEDTLS_MD5_C + * MBEDTLS_SHA1_C + * + * Comment this macro to disable support for SSL 3.0 + */ +//#define MBEDTLS_SSL_PROTO_SSL3 + +/** + * \def MBEDTLS_SSL_PROTO_TLS1 + * + * Enable support for TLS 1.0. + * + * Requires: MBEDTLS_MD5_C + * MBEDTLS_SHA1_C + * + * Comment this macro to disable support for TLS 1.0 + */ +//#define MBEDTLS_SSL_PROTO_TLS1 + +/** + * \def MBEDTLS_SSL_PROTO_TLS1_1 + * + * Enable support for TLS 1.1 (and DTLS 1.0 if DTLS is enabled). + * + * Requires: MBEDTLS_MD5_C + * MBEDTLS_SHA1_C + * + * Comment this macro to disable support for TLS 1.1 / DTLS 1.0 + */ +//#define MBEDTLS_SSL_PROTO_TLS1_1 + +/** + * \def MBEDTLS_SSL_PROTO_TLS1_2 + * + * Enable support for TLS 1.2 (and DTLS 1.2 if DTLS is enabled). + * + * Requires: MBEDTLS_SHA1_C or MBEDTLS_SHA256_C or MBEDTLS_SHA512_C + * (Depends on ciphersuites) + * + * Comment this macro to disable support for TLS 1.2 / DTLS 1.2 + */ +#define MBEDTLS_SSL_PROTO_TLS1_2 + +/** + * \def MBEDTLS_SSL_PROTO_DTLS + * + * Enable support for DTLS (all available versions). + * + * Enable this and MBEDTLS_SSL_PROTO_TLS1_1 to enable DTLS 1.0, + * and/or this and MBEDTLS_SSL_PROTO_TLS1_2 to enable DTLS 1.2. + * + * Requires: MBEDTLS_SSL_PROTO_TLS1_1 + * or MBEDTLS_SSL_PROTO_TLS1_2 + * + * Comment this macro to disable support for DTLS + */ +//#define MBEDTLS_SSL_PROTO_DTLS + +/** + * \def MBEDTLS_SSL_ALPN + * + * Enable support for RFC 7301 Application Layer Protocol Negotiation. + * + * Comment this macro to disable support for ALPN. + */ +//#define MBEDTLS_SSL_ALPN + +/** + * \def MBEDTLS_SSL_DTLS_ANTI_REPLAY + * + * Enable support for the anti-replay mechanism in DTLS. + * + * Requires: MBEDTLS_SSL_TLS_C + * MBEDTLS_SSL_PROTO_DTLS + * + * \warning Disabling this is often a security risk! + * See mbedtls_ssl_conf_dtls_anti_replay() for details. + * + * Comment this to disable anti-replay in DTLS. + */ +//#define MBEDTLS_SSL_DTLS_ANTI_REPLAY + +/** + * \def MBEDTLS_SSL_DTLS_HELLO_VERIFY + * + * Enable support for HelloVerifyRequest on DTLS servers. + * + * This feature is highly recommended to prevent DTLS servers being used as + * amplifiers in DoS attacks against other hosts. It should always be enabled + * unless you know for sure amplification cannot be a problem in the + * environment in which your server operates. + * + * \warning Disabling this can ba a security risk! (see above) + * + * Requires: MBEDTLS_SSL_PROTO_DTLS + * + * Comment this to disable support for HelloVerifyRequest. + */ +//#define MBEDTLS_SSL_DTLS_HELLO_VERIFY + +/** + * \def MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE + * + * Enable server-side support for clients that reconnect from the same port. + * + * Some clients unexpectedly close the connection and try to reconnect using the + * same source port. This needs special support from the server to handle the + * new connection securely, as described in section 4.2.8 of RFC 6347. This + * flag enables that support. + * + * Requires: MBEDTLS_SSL_DTLS_HELLO_VERIFY + * + * Comment this to disable support for clients reusing the source port. + */ +//#define MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE + +/** + * \def MBEDTLS_SSL_DTLS_BADMAC_LIMIT + * + * Enable support for a limit of records with bad MAC. + * + * See mbedtls_ssl_conf_dtls_badmac_limit(). + * + * Requires: MBEDTLS_SSL_PROTO_DTLS + */ +//#define MBEDTLS_SSL_DTLS_BADMAC_LIMIT + +/** + * \def MBEDTLS_SSL_SESSION_TICKETS + * + * Enable support for RFC 5077 session tickets in SSL. + * Client-side, provides full support for session tickets (maintenance of a + * session store remains the responsibility of the application, though). + * Server-side, you also need to provide callbacks for writing and parsing + * tickets, including authenticated encryption and key management. Example + * callbacks are provided by MBEDTLS_SSL_TICKET_C. + * + * Comment this macro to disable support for SSL session tickets + */ +#define MBEDTLS_SSL_SESSION_TICKETS + +/** + * \def MBEDTLS_SSL_EXPORT_KEYS + * + * Enable support for exporting key block and master secret. + * This is required for certain users of TLS, e.g. EAP-TLS. + * + * Comment this macro to disable support for key export + */ +#define MBEDTLS_SSL_EXPORT_KEYS + +/** + * \def MBEDTLS_SSL_SERVER_NAME_INDICATION + * + * Enable support for RFC 6066 server name indication (SNI) in SSL. + * + * Requires: MBEDTLS_X509_CRT_PARSE_C + * + * Comment this macro to disable support for server name indication in SSL + */ +#define MBEDTLS_SSL_SERVER_NAME_INDICATION + +/** + * \def MBEDTLS_SSL_TRUNCATED_HMAC + * + * Enable support for RFC 6066 truncated HMAC in SSL. + * + * Comment this macro to disable support for truncated HMAC in SSL + */ +#define MBEDTLS_SSL_TRUNCATED_HMAC + +/** + * \def MBEDTLS_SSL_TRUNCATED_HMAC_COMPAT + * + * Fallback to old (pre-2.7), non-conforming implementation of the truncated + * HMAC extension which also truncates the HMAC key. Note that this option is + * only meant for a transitory upgrade period and is likely to be removed in + * a future version of the library. + * + * \warning The old implementation is non-compliant and has a security weakness + * (2^80 brute force attack on the HMAC key used for a single, + * uninterrupted connection). This should only be enabled temporarily + * when (1) the use of truncated HMAC is essential in order to save + * bandwidth, and (2) the peer is an Mbed TLS stack that doesn't use + * the fixed implementation yet (pre-2.7). + * + * \deprecated This option is deprecated and will likely be removed in a + * future version of Mbed TLS. + * + * Uncomment to fallback to old, non-compliant truncated HMAC implementation. + * + * Requires: MBEDTLS_SSL_TRUNCATED_HMAC + */ +//#define MBEDTLS_SSL_TRUNCATED_HMAC_COMPAT + +/** + * \def MBEDTLS_THREADING_ALT + * + * Provide your own alternate threading implementation. + * + * Requires: MBEDTLS_THREADING_C + * + * Uncomment this to allow your own alternate threading implementation. + */ +//#define MBEDTLS_THREADING_ALT + +/** + * \def MBEDTLS_THREADING_PTHREAD + * + * Enable the pthread wrapper layer for the threading layer. + * + * Requires: MBEDTLS_THREADING_C + * + * Uncomment this to enable pthread mutexes. + */ +//#define MBEDTLS_THREADING_PTHREAD + +/** + * \def MBEDTLS_VERSION_FEATURES + * + * Allow run-time checking of compile-time enabled features. Thus allowing users + * to check at run-time if the library is for instance compiled with threading + * support via mbedtls_version_check_feature(). + * + * Requires: MBEDTLS_VERSION_C + * + * Comment this to disable run-time checking and save ROM space + */ +//#define MBEDTLS_VERSION_FEATURES + +/** + * \def MBEDTLS_X509_ALLOW_EXTENSIONS_NON_V3 + * + * If set, the X509 parser will not break-off when parsing an X509 certificate + * and encountering an extension in a v1 or v2 certificate. + * + * Uncomment to prevent an error. + */ +//#define MBEDTLS_X509_ALLOW_EXTENSIONS_NON_V3 + +/** + * \def MBEDTLS_X509_ALLOW_UNSUPPORTED_CRITICAL_EXTENSION + * + * If set, the X509 parser will not break-off when parsing an X509 certificate + * and encountering an unknown critical extension. + * + * \warning Depending on your PKI use, enabling this can be a security risk! + * + * Uncomment to prevent an error. + */ +//#define MBEDTLS_X509_ALLOW_UNSUPPORTED_CRITICAL_EXTENSION + +/** + * \def MBEDTLS_X509_CHECK_KEY_USAGE + * + * Enable verification of the keyUsage extension (CA and leaf certificates). + * + * Disabling this avoids problems with mis-issued and/or misused + * (intermediate) CA and leaf certificates. + * + * \warning Depending on your PKI use, disabling this can be a security risk! + * + * Comment to skip keyUsage checking for both CA and leaf certificates. + */ +#define MBEDTLS_X509_CHECK_KEY_USAGE + +/** + * \def MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE + * + * Enable verification of the extendedKeyUsage extension (leaf certificates). + * + * Disabling this avoids problems with mis-issued and/or misused certificates. + * + * \warning Depending on your PKI use, disabling this can be a security risk! + * + * Comment to skip extendedKeyUsage checking for certificates. + */ +#define MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE + +/** + * \def MBEDTLS_X509_RSASSA_PSS_SUPPORT + * + * Enable parsing and verification of X.509 certificates, CRLs and CSRS + * signed with RSASSA-PSS (aka PKCS#1 v2.1). + * + * Comment this macro to disallow using RSASSA-PSS in certificates. + */ +//#define MBEDTLS_X509_RSASSA_PSS_SUPPORT + +/** + * \def MBEDTLS_ZLIB_SUPPORT + * + * If set, the SSL/TLS module uses ZLIB to support compression and + * decompression of packet data. + * + * \warning TLS-level compression MAY REDUCE SECURITY! See for example the + * CRIME attack. Before enabling this option, you should examine with care if + * CRIME or similar exploits may be applicable to your use case. + * + * \note Currently compression can't be used with DTLS. + * + * \deprecated This feature is deprecated and will be removed + * in the next major revision of the library. + * + * Used in: library/ssl_tls.c + * library/ssl_cli.c + * library/ssl_srv.c + * + * This feature requires zlib library and headers to be present. + * + * Uncomment to enable use of ZLIB + */ +//#define MBEDTLS_ZLIB_SUPPORT +/* \} name SECTION: mbed TLS feature support */ + +/** + * \name SECTION: mbed TLS modules + * + * This section enables or disables entire modules in mbed TLS + * \{ + */ + +/** + * \def MBEDTLS_AESNI_C + * + * Enable AES-NI support on x86-64. + * + * Module: library/aesni.c + * Caller: library/aes.c + * + * Requires: MBEDTLS_HAVE_ASM + * + * This modules adds support for the AES-NI instructions on x86-64 + */ +//#define MBEDTLS_AESNI_C + +/** + * \def MBEDTLS_AES_C + * + * Enable the AES block cipher. + * + * Module: library/aes.c + * Caller: library/cipher.c + * library/pem.c + * library/ctr_drbg.c + * + * This module enables the following ciphersuites (if other requisites are + * enabled as well): + * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA + * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA + * MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA + * MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA + * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 + * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 + * MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 + * MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 + * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 + * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 + * MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 + * MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 + * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 + * MBEDTLS_TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 + * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 + * MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA + * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA + * MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CBC_SHA + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 + * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 + * MBEDTLS_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 + * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 + * MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA + * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA + * MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA + * MBEDTLS_TLS_DHE_PSK_WITH_AES_256_GCM_SHA384 + * MBEDTLS_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384 + * MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CBC_SHA384 + * MBEDTLS_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA + * MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CBC_SHA + * MBEDTLS_TLS_DHE_PSK_WITH_AES_128_GCM_SHA256 + * MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 + * MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CBC_SHA256 + * MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA + * MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CBC_SHA + * MBEDTLS_TLS_RSA_WITH_AES_256_GCM_SHA384 + * MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA256 + * MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA + * MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256 + * MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA256 + * MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA + * MBEDTLS_TLS_RSA_PSK_WITH_AES_256_GCM_SHA384 + * MBEDTLS_TLS_RSA_PSK_WITH_AES_256_CBC_SHA384 + * MBEDTLS_TLS_RSA_PSK_WITH_AES_256_CBC_SHA + * MBEDTLS_TLS_RSA_PSK_WITH_AES_128_GCM_SHA256 + * MBEDTLS_TLS_RSA_PSK_WITH_AES_128_CBC_SHA256 + * MBEDTLS_TLS_RSA_PSK_WITH_AES_128_CBC_SHA + * MBEDTLS_TLS_PSK_WITH_AES_256_GCM_SHA384 + * MBEDTLS_TLS_PSK_WITH_AES_256_CBC_SHA384 + * MBEDTLS_TLS_PSK_WITH_AES_256_CBC_SHA + * MBEDTLS_TLS_PSK_WITH_AES_128_GCM_SHA256 + * MBEDTLS_TLS_PSK_WITH_AES_128_CBC_SHA256 + * MBEDTLS_TLS_PSK_WITH_AES_128_CBC_SHA + * + * PEM_PARSE uses AES for decrypting encrypted keys. + */ +#define MBEDTLS_AES_C + +/** + * \def MBEDTLS_ARC4_C + * + * Enable the ARCFOUR stream cipher. + * + * Module: library/arc4.c + * Caller: library/cipher.c + * + * This module enables the following ciphersuites (if other requisites are + * enabled as well): + * MBEDTLS_TLS_ECDH_ECDSA_WITH_RC4_128_SHA + * MBEDTLS_TLS_ECDH_RSA_WITH_RC4_128_SHA + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_RC4_128_SHA + * MBEDTLS_TLS_ECDHE_RSA_WITH_RC4_128_SHA + * MBEDTLS_TLS_ECDHE_PSK_WITH_RC4_128_SHA + * MBEDTLS_TLS_DHE_PSK_WITH_RC4_128_SHA + * MBEDTLS_TLS_RSA_WITH_RC4_128_SHA + * MBEDTLS_TLS_RSA_WITH_RC4_128_MD5 + * MBEDTLS_TLS_RSA_PSK_WITH_RC4_128_SHA + * MBEDTLS_TLS_PSK_WITH_RC4_128_SHA + * + * \warning ARC4 is considered a weak cipher and its use constitutes a + * security risk. If possible, we recommend avoidng dependencies on + * it, and considering stronger ciphers instead. + * + */ +//#define MBEDTLS_ARC4_C + +/** + * \def MBEDTLS_ASN1_PARSE_C + * + * Enable the generic ASN1 parser. + * + * Module: library/asn1.c + * Caller: library/x509.c + * library/dhm.c + * library/pkcs12.c + * library/pkcs5.c + * library/pkparse.c + */ +#define MBEDTLS_ASN1_PARSE_C + +/** + * \def MBEDTLS_ASN1_WRITE_C + * + * Enable the generic ASN1 writer. + * + * Module: library/asn1write.c + * Caller: library/ecdsa.c + * library/pkwrite.c + * library/x509_create.c + * library/x509write_crt.c + * library/x509write_csr.c + */ +#define MBEDTLS_ASN1_WRITE_C + +/** + * \def MBEDTLS_BASE64_C + * + * Enable the Base64 module. + * + * Module: library/base64.c + * Caller: library/pem.c + * + * This module is required for PEM support (required by X.509). + */ +#define MBEDTLS_BASE64_C + +/** + * \def MBEDTLS_BIGNUM_C + * + * Enable the multi-precision integer library. + * + * Module: library/bignum.c + * Caller: library/dhm.c + * library/ecp.c + * library/ecdsa.c + * library/rsa.c + * library/rsa_internal.c + * library/ssl_tls.c + * + * This module is required for RSA, DHM and ECC (ECDH, ECDSA) support. + */ +#define MBEDTLS_BIGNUM_C + +/** + * \def MBEDTLS_BLOWFISH_C + * + * Enable the Blowfish block cipher. + * + * Module: library/blowfish.c + */ +//#define MBEDTLS_BLOWFISH_C + +/** + * \def MBEDTLS_CAMELLIA_C + * + * Enable the Camellia block cipher. + * + * Module: library/camellia.c + * Caller: library/cipher.c + * + * This module enables the following ciphersuites (if other requisites are + * enabled as well): + * MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 + * MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 + * MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256 + * MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384 + * MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256 + * MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384 + * MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256 + * MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384 + * MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384 + * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 + * MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384 + * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 + * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256 + * MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256 + * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 + * MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 + * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 + * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA + * MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384 + * MBEDTLS_TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 + * MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 + * MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256 + * MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 + * MBEDTLS_TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 + * MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384 + * MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256 + * MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA + * MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256 + * MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256 + * MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA + * MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384 + * MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384 + * MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256 + * MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256 + * MBEDTLS_TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384 + * MBEDTLS_TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384 + * MBEDTLS_TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256 + * MBEDTLS_TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256 + */ +//#define MBEDTLS_CAMELLIA_C + +/** + * \def MBEDTLS_ARIA_C + * + * Enable the ARIA block cipher. + * + * Module: library/aria.c + * Caller: library/cipher.c + * + * This module enables the following ciphersuites (if other requisites are + * enabled as well): + * + * MBEDTLS_TLS_RSA_WITH_ARIA_128_CBC_SHA256 + * MBEDTLS_TLS_RSA_WITH_ARIA_256_CBC_SHA384 + * MBEDTLS_TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256 + * MBEDTLS_TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384 + * MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256 + * MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384 + * MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256 + * MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384 + * MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256 + * MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384 + * MBEDTLS_TLS_RSA_WITH_ARIA_128_GCM_SHA256 + * MBEDTLS_TLS_RSA_WITH_ARIA_256_GCM_SHA384 + * MBEDTLS_TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256 + * MBEDTLS_TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384 + * MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256 + * MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384 + * MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256 + * MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384 + * MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256 + * MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384 + * MBEDTLS_TLS_PSK_WITH_ARIA_128_CBC_SHA256 + * MBEDTLS_TLS_PSK_WITH_ARIA_256_CBC_SHA384 + * MBEDTLS_TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256 + * MBEDTLS_TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384 + * MBEDTLS_TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256 + * MBEDTLS_TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384 + * MBEDTLS_TLS_PSK_WITH_ARIA_128_GCM_SHA256 + * MBEDTLS_TLS_PSK_WITH_ARIA_256_GCM_SHA384 + * MBEDTLS_TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256 + * MBEDTLS_TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384 + * MBEDTLS_TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256 + * MBEDTLS_TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384 + * MBEDTLS_TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256 + * MBEDTLS_TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384 + */ +//#define MBEDTLS_ARIA_C + +/** + * \def MBEDTLS_CCM_C + * + * Enable the Counter with CBC-MAC (CCM) mode for 128-bit block cipher. + * + * Module: library/ccm.c + * + * Requires: MBEDTLS_AES_C or MBEDTLS_CAMELLIA_C + * + * This module enables the AES-CCM ciphersuites, if other requisites are + * enabled as well. + */ +#define MBEDTLS_CCM_C + +/** + * \def MBEDTLS_CERTS_C + * + * Enable the test certificates. + * + * Module: library/certs.c + * Caller: + * + * This module is used for testing (ssl_client/server). + */ +//#define MBEDTLS_CERTS_C + +/** + * \def MBEDTLS_CHACHA20_C + * + * Enable the ChaCha20 stream cipher. + * + * Module: library/chacha20.c + */ +//#define MBEDTLS_CHACHA20_C + +/** + * \def MBEDTLS_CHACHAPOLY_C + * + * Enable the ChaCha20-Poly1305 AEAD algorithm. + * + * Module: library/chachapoly.c + * + * This module requires: MBEDTLS_CHACHA20_C, MBEDTLS_POLY1305_C + */ +//#define MBEDTLS_CHACHAPOLY_C + +/** + * \def MBEDTLS_CIPHER_C + * + * Enable the generic cipher layer. + * + * Module: library/cipher.c + * Caller: library/ssl_tls.c + * + * Uncomment to enable generic cipher wrappers. + */ +#define MBEDTLS_CIPHER_C + +/** + * \def MBEDTLS_CMAC_C + * + * Enable the CMAC (Cipher-based Message Authentication Code) mode for block + * ciphers. + * + * Module: library/cmac.c + * + * Requires: MBEDTLS_AES_C or MBEDTLS_DES_C + * + */ +//#define MBEDTLS_CMAC_C + +/** + * \def MBEDTLS_CTR_DRBG_C + * + * Enable the CTR_DRBG AES-based random generator. + * The CTR_DRBG generator uses AES-256 by default. + * To use AES-128 instead, enable \c MBEDTLS_CTR_DRBG_USE_128_BIT_KEY above. + * + * \note To achieve a 256-bit security strength with CTR_DRBG, + * you must use AES-256 *and* use sufficient entropy. + * See ctr_drbg.h for more details. + * + * Module: library/ctr_drbg.c + * Caller: + * + * Requires: MBEDTLS_AES_C + * + * This module provides the CTR_DRBG AES random number generator. + */ +#define MBEDTLS_CTR_DRBG_C + +/** + * \def MBEDTLS_DEBUG_C + * + * Enable the debug functions. + * + * Module: library/debug.c + * Caller: library/ssl_cli.c + * library/ssl_srv.c + * library/ssl_tls.c + * + * This module provides debugging functions. + */ +//#define MBEDTLS_DEBUG_C + +/** + * \def MBEDTLS_DES_C + * + * Enable the DES block cipher. + * + * Module: library/des.c + * Caller: library/pem.c + * library/cipher.c + * + * This module enables the following ciphersuites (if other requisites are + * enabled as well): + * MBEDTLS_TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA + * MBEDTLS_TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA + * MBEDTLS_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA + * MBEDTLS_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA + * MBEDTLS_TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA + * MBEDTLS_TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA + * MBEDTLS_TLS_RSA_WITH_3DES_EDE_CBC_SHA + * MBEDTLS_TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA + * MBEDTLS_TLS_PSK_WITH_3DES_EDE_CBC_SHA + * + * PEM_PARSE uses DES/3DES for decrypting encrypted keys. + * + * \warning DES is considered a weak cipher and its use constitutes a + * security risk. We recommend considering stronger ciphers instead. + */ +//#define MBEDTLS_DES_C + +/** + * \def MBEDTLS_DHM_C + * + * Enable the Diffie-Hellman-Merkle module. + * + * Module: library/dhm.c + * Caller: library/ssl_cli.c + * library/ssl_srv.c + * + * This module is used by the following key exchanges: + * DHE-RSA, DHE-PSK + * + * \warning Using DHE constitutes a security risk as it + * is not possible to validate custom DH parameters. + * If possible, it is recommended users should consider + * preferring other methods of key exchange. + * See dhm.h for more details. + * + */ +#define MBEDTLS_DHM_C + +/** + * \def MBEDTLS_ECDH_C + * + * Enable the elliptic curve Diffie-Hellman library. + * + * Module: library/ecdh.c + * Caller: library/ssl_cli.c + * library/ssl_srv.c + * + * This module is used by the following key exchanges: + * ECDHE-ECDSA, ECDHE-RSA, DHE-PSK + * + * Requires: MBEDTLS_ECP_C + */ +#define MBEDTLS_ECDH_C + +/** + * \def MBEDTLS_ECDSA_C + * + * Enable the elliptic curve DSA library. + * + * Module: library/ecdsa.c + * Caller: + * + * This module is used by the following key exchanges: + * ECDHE-ECDSA + * + * Requires: MBEDTLS_ECP_C, MBEDTLS_ASN1_WRITE_C, MBEDTLS_ASN1_PARSE_C + */ +#define MBEDTLS_ECDSA_C + +/** + * \def MBEDTLS_ECJPAKE_C + * + * Enable the elliptic curve J-PAKE library. + * + * \warning This is currently experimental. EC J-PAKE support is based on the + * Thread v1.0.0 specification; incompatible changes to the specification + * might still happen. For this reason, this is disabled by default. + * + * Module: library/ecjpake.c + * Caller: + * + * This module is used by the following key exchanges: + * ECJPAKE + * + * Requires: MBEDTLS_ECP_C, MBEDTLS_MD_C + */ +//#define MBEDTLS_ECJPAKE_C + +/** + * \def MBEDTLS_ECP_C + * + * Enable the elliptic curve over GF(p) library. + * + * Module: library/ecp.c + * Caller: library/ecdh.c + * library/ecdsa.c + * library/ecjpake.c + * + * Requires: MBEDTLS_BIGNUM_C and at least one MBEDTLS_ECP_DP_XXX_ENABLED + */ +#define MBEDTLS_ECP_C + +/** + * \def MBEDTLS_ENTROPY_C + * + * Enable the platform-specific entropy code. + * + * Module: library/entropy.c + * Caller: + * + * Requires: MBEDTLS_SHA512_C or MBEDTLS_SHA256_C + * + * This module provides a generic entropy pool + */ +#define MBEDTLS_ENTROPY_C + +/** + * \def MBEDTLS_ERROR_C + * + * Enable error code to error string conversion. + * + * Module: library/error.c + * Caller: + * + * This module enables mbedtls_strerror(). + */ +//#define MBEDTLS_ERROR_C + +/** + * \def MBEDTLS_GCM_C + * + * Enable the Galois/Counter Mode (GCM) for AES. + * + * Module: library/gcm.c + * + * Requires: MBEDTLS_AES_C or MBEDTLS_CAMELLIA_C + * + * This module enables the AES-GCM and CAMELLIA-GCM ciphersuites, if other + * requisites are enabled as well. + */ +#define MBEDTLS_GCM_C + +/** + * \def MBEDTLS_HAVEGE_C + * + * Enable the HAVEGE random generator. + * + * Warning: the HAVEGE random generator is not suitable for virtualized + * environments + * + * Warning: the HAVEGE random generator is dependent on timing and specific + * processor traits. It is therefore not advised to use HAVEGE as + * your applications primary random generator or primary entropy pool + * input. As a secondary input to your entropy pool, it IS able add + * the (limited) extra entropy it provides. + * + * Module: library/havege.c + * Caller: + * + * Requires: MBEDTLS_TIMING_C + * + * Uncomment to enable the HAVEGE random generator. + */ +//#define MBEDTLS_HAVEGE_C + +/** + * \def MBEDTLS_HKDF_C + * + * Enable the HKDF algorithm (RFC 5869). + * + * Module: library/hkdf.c + * Caller: + * + * Requires: MBEDTLS_MD_C + * + * This module adds support for the Hashed Message Authentication Code + * (HMAC)-based key derivation function (HKDF). + */ +#define MBEDTLS_HKDF_C + +/** + * \def MBEDTLS_HMAC_DRBG_C + * + * Enable the HMAC_DRBG random generator. + * + * Module: library/hmac_drbg.c + * Caller: + * + * Requires: MBEDTLS_MD_C + * + * Uncomment to enable the HMAC_DRBG random number geerator. + */ +#define MBEDTLS_HMAC_DRBG_C + +/** + * \def MBEDTLS_NIST_KW_C + * + * Enable the Key Wrapping mode for 128-bit block ciphers, + * as defined in NIST SP 800-38F. Only KW and KWP modes + * are supported. At the moment, only AES is approved by NIST. + * + * Module: library/nist_kw.c + * + * Requires: MBEDTLS_AES_C and MBEDTLS_CIPHER_C + */ +//#define MBEDTLS_NIST_KW_C + +/** + * \def MBEDTLS_MD_C + * + * Enable the generic message digest layer. + * + * Module: library/md.c + * Caller: + * + * Uncomment to enable generic message digest wrappers. + */ +#define MBEDTLS_MD_C + +/** + * \def MBEDTLS_MD2_C + * + * Enable the MD2 hash algorithm. + * + * Module: library/md2.c + * Caller: + * + * Uncomment to enable support for (rare) MD2-signed X.509 certs. + * + * \warning MD2 is considered a weak message digest and its use constitutes a + * security risk. If possible, we recommend avoiding dependencies on + * it, and considering stronger message digests instead. + * + */ +//#define MBEDTLS_MD2_C + +/** + * \def MBEDTLS_MD4_C + * + * Enable the MD4 hash algorithm. + * + * Module: library/md4.c + * Caller: + * + * Uncomment to enable support for (rare) MD4-signed X.509 certs. + * + * \warning MD4 is considered a weak message digest and its use constitutes a + * security risk. If possible, we recommend avoiding dependencies on + * it, and considering stronger message digests instead. + * + */ +//#define MBEDTLS_MD4_C + +/** + * \def MBEDTLS_MD5_C + * + * Enable the MD5 hash algorithm. + * + * Module: library/md5.c + * Caller: library/md.c + * library/pem.c + * library/ssl_tls.c + * + * This module is required for SSL/TLS up to version 1.1, and for TLS 1.2 + * depending on the handshake parameters. Further, it is used for checking + * MD5-signed certificates, and for PBKDF1 when decrypting PEM-encoded + * encrypted keys. + * + * \warning MD5 is considered a weak message digest and its use constitutes a + * security risk. If possible, we recommend avoiding dependencies on + * it, and considering stronger message digests instead. + * + */ +#define MBEDTLS_MD5_C + +/** + * \def MBEDTLS_MEMORY_BUFFER_ALLOC_C + * + * Enable the buffer allocator implementation that makes use of a (stack) + * based buffer to 'allocate' dynamic memory. (replaces calloc() and free() + * calls) + * + * Module: library/memory_buffer_alloc.c + * + * Requires: MBEDTLS_PLATFORM_C + * MBEDTLS_PLATFORM_MEMORY (to use it within mbed TLS) + * + * Enable this module to enable the buffer memory allocator. + */ +#define MBEDTLS_MEMORY_BUFFER_ALLOC_C + +/** + * \def MBEDTLS_NET_C + * + * Enable the TCP and UDP over IPv6/IPv4 networking routines. + * + * \note This module only works on POSIX/Unix (including Linux, BSD and OS X) + * and Windows. For other platforms, you'll want to disable it, and write your + * own networking callbacks to be passed to \c mbedtls_ssl_set_bio(). + * + * \note See also our Knowledge Base article about porting to a new + * environment: + * https://tls.mbed.org/kb/how-to/how-do-i-port-mbed-tls-to-a-new-environment-OS + * + * Module: library/net_sockets.c + * + * This module provides networking routines. + */ +#define MBEDTLS_NET_C + +/** + * \def MBEDTLS_OID_C + * + * Enable the OID database. + * + * Module: library/oid.c + * Caller: library/asn1write.c + * library/pkcs5.c + * library/pkparse.c + * library/pkwrite.c + * library/rsa.c + * library/x509.c + * library/x509_create.c + * library/x509_crl.c + * library/x509_crt.c + * library/x509_csr.c + * library/x509write_crt.c + * library/x509write_csr.c + * + * This modules translates between OIDs and internal values. + */ +#define MBEDTLS_OID_C + +/** + * \def MBEDTLS_PADLOCK_C + * + * Enable VIA Padlock support on x86. + * + * Module: library/padlock.c + * Caller: library/aes.c + * + * Requires: MBEDTLS_HAVE_ASM + * + * This modules adds support for the VIA PadLock on x86. + */ +//#define MBEDTLS_PADLOCK_C + +/** + * \def MBEDTLS_PEM_PARSE_C + * + * Enable PEM decoding / parsing. + * + * Module: library/pem.c + * Caller: library/dhm.c + * library/pkparse.c + * library/x509_crl.c + * library/x509_crt.c + * library/x509_csr.c + * + * Requires: MBEDTLS_BASE64_C + * + * This modules adds support for decoding / parsing PEM files. + */ +#define MBEDTLS_PEM_PARSE_C + +/** + * \def MBEDTLS_PEM_WRITE_C + * + * Enable PEM encoding / writing. + * + * Module: library/pem.c + * Caller: library/pkwrite.c + * library/x509write_crt.c + * library/x509write_csr.c + * + * Requires: MBEDTLS_BASE64_C + * + * This modules adds support for encoding / writing PEM files. + */ +//#define MBEDTLS_PEM_WRITE_C + +/** + * \def MBEDTLS_PK_C + * + * Enable the generic public (asymetric) key layer. + * + * Module: library/pk.c + * Caller: library/ssl_tls.c + * library/ssl_cli.c + * library/ssl_srv.c + * + * Requires: MBEDTLS_RSA_C or MBEDTLS_ECP_C + * + * Uncomment to enable generic public key wrappers. + */ +#define MBEDTLS_PK_C + +/** + * \def MBEDTLS_PK_PARSE_C + * + * Enable the generic public (asymetric) key parser. + * + * Module: library/pkparse.c + * Caller: library/x509_crt.c + * library/x509_csr.c + * + * Requires: MBEDTLS_PK_C + * + * Uncomment to enable generic public key parse functions. + */ +#define MBEDTLS_PK_PARSE_C + +/** + * \def MBEDTLS_PK_WRITE_C + * + * Enable the generic public (asymetric) key writer. + * + * Module: library/pkwrite.c + * Caller: library/x509write.c + * + * Requires: MBEDTLS_PK_C + * + * Uncomment to enable generic public key write functions. + */ +//#define MBEDTLS_PK_WRITE_C + +/** + * \def MBEDTLS_PKCS5_C + * + * Enable PKCS#5 functions. + * + * Module: library/pkcs5.c + * + * Requires: MBEDTLS_MD_C + * + * This module adds support for the PKCS#5 functions. + */ +#define MBEDTLS_PKCS5_C + +/** + * \def MBEDTLS_PKCS11_C + * + * Enable wrapper for PKCS#11 smartcard support. + * + * Module: library/pkcs11.c + * Caller: library/pk.c + * + * Requires: MBEDTLS_PK_C + * + * This module enables SSL/TLS PKCS #11 smartcard support. + * Requires the presence of the PKCS#11 helper library (libpkcs11-helper) + */ +//#define MBEDTLS_PKCS11_C + +/** + * \def MBEDTLS_PKCS12_C + * + * Enable PKCS#12 PBE functions. + * Adds algorithms for parsing PKCS#8 encrypted private keys + * + * Module: library/pkcs12.c + * Caller: library/pkparse.c + * + * Requires: MBEDTLS_ASN1_PARSE_C, MBEDTLS_CIPHER_C, MBEDTLS_MD_C + * Can use: MBEDTLS_ARC4_C + * + * This module enables PKCS#12 functions. + */ +//#define MBEDTLS_PKCS12_C + +/** + * \def MBEDTLS_PLATFORM_C + * + * Enable the platform abstraction layer that allows you to re-assign + * functions like calloc(), free(), snprintf(), printf(), fprintf(), exit(). + * + * Enabling MBEDTLS_PLATFORM_C enables to use of MBEDTLS_PLATFORM_XXX_ALT + * or MBEDTLS_PLATFORM_XXX_MACRO directives, allowing the functions mentioned + * above to be specified at runtime or compile time respectively. + * + * \note This abstraction layer must be enabled on Windows (including MSYS2) + * as other module rely on it for a fixed snprintf implementation. + * + * Module: library/platform.c + * Caller: Most other .c files + * + * This module enables abstraction of common (libc) functions. + */ +#define MBEDTLS_PLATFORM_C + +/** + * \def MBEDTLS_POLY1305_C + * + * Enable the Poly1305 MAC algorithm. + * + * Module: library/poly1305.c + * Caller: library/chachapoly.c + */ +//#define MBEDTLS_POLY1305_C + +/** + * \def MBEDTLS_RIPEMD160_C + * + * Enable the RIPEMD-160 hash algorithm. + * + * Module: library/ripemd160.c + * Caller: library/md.c + * + */ +//#define MBEDTLS_RIPEMD160_C + +/** + * \def MBEDTLS_RSA_C + * + * Enable the RSA public-key cryptosystem. + * + * Module: library/rsa.c + * library/rsa_internal.c + * Caller: library/ssl_cli.c + * library/ssl_srv.c + * library/ssl_tls.c + * library/x509.c + * + * This module is used by the following key exchanges: + * RSA, DHE-RSA, ECDHE-RSA, RSA-PSK + * + * Requires: MBEDTLS_BIGNUM_C, MBEDTLS_OID_C + */ +#define MBEDTLS_RSA_C + +/** + * \def MBEDTLS_SHA1_C + * + * Enable the SHA1 cryptographic hash algorithm. + * + * Module: library/sha1.c + * Caller: library/md.c + * library/ssl_cli.c + * library/ssl_srv.c + * library/ssl_tls.c + * library/x509write_crt.c + * + * This module is required for SSL/TLS up to version 1.1, for TLS 1.2 + * depending on the handshake parameters, and for SHA1-signed certificates. + * + * \warning SHA-1 is considered a weak message digest and its use constitutes + * a security risk. If possible, we recommend avoiding dependencies + * on it, and considering stronger message digests instead. + * + */ +#define MBEDTLS_SHA1_C + +/** + * \def MBEDTLS_SHA256_C + * + * Enable the SHA-224 and SHA-256 cryptographic hash algorithms. + * + * Module: library/sha256.c + * Caller: library/entropy.c + * library/md.c + * library/ssl_cli.c + * library/ssl_srv.c + * library/ssl_tls.c + * + * This module adds support for SHA-224 and SHA-256. + * This module is required for the SSL/TLS 1.2 PRF function. + */ +#define MBEDTLS_SHA256_C + +/** + * \def MBEDTLS_SHA512_C + * + * Enable the SHA-384 and SHA-512 cryptographic hash algorithms. + * + * Module: library/sha512.c + * Caller: library/entropy.c + * library/md.c + * library/ssl_cli.c + * library/ssl_srv.c + * + * This module adds support for SHA-384 and SHA-512. + */ +#define MBEDTLS_SHA512_C + +/** + * \def MBEDTLS_SSL_CACHE_C + * + * Enable simple SSL cache implementation. + * + * Module: library/ssl_cache.c + * Caller: + * + * Requires: MBEDTLS_SSL_CACHE_C + */ +#define MBEDTLS_SSL_CACHE_C + +/** + * \def MBEDTLS_SSL_COOKIE_C + * + * Enable basic implementation of DTLS cookies for hello verification. + * + * Module: library/ssl_cookie.c + * Caller: + */ +#define MBEDTLS_SSL_COOKIE_C + +/** + * \def MBEDTLS_SSL_TICKET_C + * + * Enable an implementation of TLS server-side callbacks for session tickets. + * + * Module: library/ssl_ticket.c + * Caller: + * + * Requires: MBEDTLS_CIPHER_C + */ +#define MBEDTLS_SSL_TICKET_C + +/** + * \def MBEDTLS_SSL_CLI_C + * + * Enable the SSL/TLS client code. + * + * Module: library/ssl_cli.c + * Caller: + * + * Requires: MBEDTLS_SSL_TLS_C + * + * This module is required for SSL/TLS client support. + */ +#define MBEDTLS_SSL_CLI_C + +/** + * \def MBEDTLS_SSL_SRV_C + * + * Enable the SSL/TLS server code. + * + * Module: library/ssl_srv.c + * Caller: + * + * Requires: MBEDTLS_SSL_TLS_C + * + * This module is required for SSL/TLS server support. + */ +//#define MBEDTLS_SSL_SRV_C + +/** + * \def MBEDTLS_SSL_TLS_C + * + * Enable the generic SSL/TLS code. + * + * Module: library/ssl_tls.c + * Caller: library/ssl_cli.c + * library/ssl_srv.c + * + * Requires: MBEDTLS_CIPHER_C, MBEDTLS_MD_C + * and at least one of the MBEDTLS_SSL_PROTO_XXX defines + * + * This module is required for SSL/TLS. + */ +#define MBEDTLS_SSL_TLS_C + +/** + * \def MBEDTLS_THREADING_C + * + * Enable the threading abstraction layer. + * By default mbed TLS assumes it is used in a non-threaded environment or that + * contexts are not shared between threads. If you do intend to use contexts + * between threads, you will need to enable this layer to prevent race + * conditions. See also our Knowledge Base article about threading: + * https://tls.mbed.org/kb/development/thread-safety-and-multi-threading + * + * Module: library/threading.c + * + * This allows different threading implementations (self-implemented or + * provided). + * + * You will have to enable either MBEDTLS_THREADING_ALT or + * MBEDTLS_THREADING_PTHREAD. + * + * Enable this layer to allow use of mutexes within mbed TLS + */ +//#define MBEDTLS_THREADING_C + +/** + * \def MBEDTLS_TIMING_C + * + * Enable the semi-portable timing interface. + * + * \note The provided implementation only works on POSIX/Unix (including Linux, + * BSD and OS X) and Windows. On other platforms, you can either disable that + * module and provide your own implementations of the callbacks needed by + * \c mbedtls_ssl_set_timer_cb() for DTLS, or leave it enabled and provide + * your own implementation of the whole module by setting + * \c MBEDTLS_TIMING_ALT in the current file. + * + * \note See also our Knowledge Base article about porting to a new + * environment: + * https://tls.mbed.org/kb/how-to/how-do-i-port-mbed-tls-to-a-new-environment-OS + * + * Module: library/timing.c + * Caller: library/havege.c + * + * This module is used by the HAVEGE random number generator. + */ +//#define MBEDTLS_TIMING_C + +/** + * \def MBEDTLS_VERSION_C + * + * Enable run-time version information. + * + * Module: library/version.c + * + * This module provides run-time version information. + */ +#define MBEDTLS_VERSION_C + +/** + * \def MBEDTLS_X509_USE_C + * + * Enable X.509 core for using certificates. + * + * Module: library/x509.c + * Caller: library/x509_crl.c + * library/x509_crt.c + * library/x509_csr.c + * + * Requires: MBEDTLS_ASN1_PARSE_C, MBEDTLS_BIGNUM_C, MBEDTLS_OID_C, + * MBEDTLS_PK_PARSE_C + * + * This module is required for the X.509 parsing modules. + */ +#define MBEDTLS_X509_USE_C + +/** + * \def MBEDTLS_X509_CRT_PARSE_C + * + * Enable X.509 certificate parsing. + * + * Module: library/x509_crt.c + * Caller: library/ssl_cli.c + * library/ssl_srv.c + * library/ssl_tls.c + * + * Requires: MBEDTLS_X509_USE_C + * + * This module is required for X.509 certificate parsing. + */ +#define MBEDTLS_X509_CRT_PARSE_C + +/** + * \def MBEDTLS_X509_CRL_PARSE_C + * + * Enable X.509 CRL parsing. + * + * Module: library/x509_crl.c + * Caller: library/x509_crt.c + * + * Requires: MBEDTLS_X509_USE_C + * + * This module is required for X.509 CRL parsing. + */ +//#define MBEDTLS_X509_CRL_PARSE_C + +/** + * \def MBEDTLS_X509_CSR_PARSE_C + * + * Enable X.509 Certificate Signing Request (CSR) parsing. + * + * Module: library/x509_csr.c + * Caller: library/x509_crt_write.c + * + * Requires: MBEDTLS_X509_USE_C + * + * This module is used for reading X.509 certificate request. + */ +//#define MBEDTLS_X509_CSR_PARSE_C + +/** + * \def MBEDTLS_X509_CREATE_C + * + * Enable X.509 core for creating certificates. + * + * Module: library/x509_create.c + * + * Requires: MBEDTLS_BIGNUM_C, MBEDTLS_OID_C, MBEDTLS_PK_WRITE_C + * + * This module is the basis for creating X.509 certificates and CSRs. + */ +//#define MBEDTLS_X509_CREATE_C + +/** + * \def MBEDTLS_X509_CRT_WRITE_C + * + * Enable creating X.509 certificates. + * + * Module: library/x509_crt_write.c + * + * Requires: MBEDTLS_X509_CREATE_C + * + * This module is required for X.509 certificate creation. + */ +//#define MBEDTLS_X509_CRT_WRITE_C + +/** + * \def MBEDTLS_X509_CSR_WRITE_C + * + * Enable creating X.509 Certificate Signing Requests (CSR). + * + * Module: library/x509_csr_write.c + * + * Requires: MBEDTLS_X509_CREATE_C + * + * This module is required for X.509 certificate request writing. + */ +//#define MBEDTLS_X509_CSR_WRITE_C + +/** + * \def MBEDTLS_XTEA_C + * + * Enable the XTEA block cipher. + * + * Module: library/xtea.c + * Caller: + */ +//#define MBEDTLS_XTEA_C + +/* \} name SECTION: mbed TLS modules */ + +/** + * \name SECTION: Module configuration options + * + * This section allows for the setting of module specific sizes and + * configuration options. The default values are already present in the + * relevant header files and should suffice for the regular use cases. + * + * Our advice is to enable options and change their values here + * only if you have a good reason and know the consequences. + * + * Please check the respective header file for documentation on these + * parameters (to prevent duplicate documentation). + * \{ + */ + +/* MPI / BIGNUM options */ +//#define MBEDTLS_MPI_WINDOW_SIZE 6 /**< Maximum windows size used. */ +//#define MBEDTLS_MPI_MAX_SIZE 1024 /**< Maximum number of bytes for usable MPIs. */ + +//#define MBEDTLS_MPI_WINDOW_SIZE 1 /**< Maximum windows size used. */ +//#define MBEDTLS_MPI_MAX_SIZE 384 /**< Maximum number of bytes for usable MPIs. */ + + +/* CTR_DRBG options */ +//#define MBEDTLS_CTR_DRBG_ENTROPY_LEN 48 /**< Amount of entropy used per seed by default (48 with SHA-512, 32 with SHA-256) */ +//#define MBEDTLS_CTR_DRBG_RESEED_INTERVAL 10000 /**< Interval before reseed is performed by default */ +//#define MBEDTLS_CTR_DRBG_MAX_INPUT 256 /**< Maximum number of additional input bytes */ +//#define MBEDTLS_CTR_DRBG_MAX_REQUEST 1024 /**< Maximum number of requested bytes per call */ +//#define MBEDTLS_CTR_DRBG_MAX_SEED_INPUT 384 /**< Maximum size of (re)seed buffer */ +//#define MBEDTLS_CTR_DRBG_USE_128_BIT_KEY /**< Use 128-bit key for CTR_DRBG - may reduce security (see ctr_drbg.h) */ + +/* HMAC_DRBG options */ +//#define MBEDTLS_HMAC_DRBG_RESEED_INTERVAL 10000 /**< Interval before reseed is performed by default */ +//#define MBEDTLS_HMAC_DRBG_MAX_INPUT 256 /**< Maximum number of additional input bytes */ +//#define MBEDTLS_HMAC_DRBG_MAX_REQUEST 1024 /**< Maximum number of requested bytes per call */ +//#define MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT 384 /**< Maximum size of (re)seed buffer */ + +/* ECP options */ +//#define MBEDTLS_ECP_MAX_BITS 521 /**< Maximum bit size of groups */ +//#define MBEDTLS_ECP_WINDOW_SIZE 6 /**< Maximum window size used */ +//#define MBEDTLS_ECP_FIXED_POINT_OPTIM 1 /**< Enable fixed-point speed-up */ + +/* Entropy options */ +#define MBEDTLS_ENTROPY_MAX_SOURCES 3 /**< Maximum number of sources supported */ +//#define MBEDTLS_ENTROPY_MAX_GATHER 128 /**< Maximum amount requested from entropy sources */ +//#define MBEDTLS_ENTROPY_MIN_HARDWARE 32 /**< Default minimum number of bytes required for the hardware entropy source mbedtls_hardware_poll() before entropy is released */ + +/* Memory buffer allocator options */ +//#define MBEDTLS_MEMORY_ALIGN_MULTIPLE 4 /**< Align on multiples of this value */ + +/* Platform options */ +//#define MBEDTLS_PLATFORM_STD_MEM_HDR /**< Header to include if MBEDTLS_PLATFORM_NO_STD_FUNCTIONS is defined. Don't define if no header is needed. */ +//#define MBEDTLS_PLATFORM_STD_CALLOC calloc /**< Default allocator to use, can be undefined */ +//#define MBEDTLS_PLATFORM_STD_FREE free /**< Default free to use, can be undefined */ +//#define MBEDTLS_PLATFORM_STD_EXIT exit /**< Default exit to use, can be undefined */ +//#define MBEDTLS_PLATFORM_STD_TIME time /**< Default time to use, can be undefined. MBEDTLS_HAVE_TIME must be enabled */ +//#define MBEDTLS_PLATFORM_STD_FPRINTF fprintf /**< Default fprintf to use, can be undefined */ +//#define MBEDTLS_PLATFORM_STD_PRINTF printf /**< Default printf to use, can be undefined */ +/* Note: your snprintf must correctly zero-terminate the buffer! */ +//#define MBEDTLS_PLATFORM_STD_SNPRINTF snprintf /**< Default snprintf to use, can be undefined */ +//#define MBEDTLS_PLATFORM_STD_EXIT_SUCCESS 0 /**< Default exit value to use, can be undefined */ +//#define MBEDTLS_PLATFORM_STD_EXIT_FAILURE 1 /**< Default exit value to use, can be undefined */ +//#define MBEDTLS_PLATFORM_STD_NV_SEED_READ mbedtls_platform_std_nv_seed_read /**< Default nv_seed_read function to use, can be undefined */ +//#define MBEDTLS_PLATFORM_STD_NV_SEED_WRITE mbedtls_platform_std_nv_seed_write /**< Default nv_seed_write function to use, can be undefined */ +//#define MBEDTLS_PLATFORM_STD_NV_SEED_FILE "seedfile" /**< Seed file to read/write with default implementation */ + +/* To Use Function Macros MBEDTLS_PLATFORM_C must be enabled */ +/* MBEDTLS_PLATFORM_XXX_MACRO and MBEDTLS_PLATFORM_XXX_ALT cannot both be defined */ +//#define MBEDTLS_PLATFORM_CALLOC_MACRO calloc /**< Default allocator macro to use, can be undefined */ +//#define MBEDTLS_PLATFORM_FREE_MACRO free /**< Default free macro to use, can be undefined */ +//#define MBEDTLS_PLATFORM_EXIT_MACRO exit /**< Default exit macro to use, can be undefined */ +//#define MBEDTLS_PLATFORM_TIME_MACRO time /**< Default time macro to use, can be undefined. MBEDTLS_HAVE_TIME must be enabled */ +//#define MBEDTLS_PLATFORM_TIME_TYPE_MACRO time_t /**< Default time macro to use, can be undefined. MBEDTLS_HAVE_TIME must be enabled */ +//#define MBEDTLS_PLATFORM_FPRINTF_MACRO fprintf /**< Default fprintf macro to use, can be undefined */ +//#define MBEDTLS_PLATFORM_PRINTF_MACRO printf /**< Default printf macro to use, can be undefined */ +/* Note: your snprintf must correctly zero-terminate the buffer! */ +//#define MBEDTLS_PLATFORM_SNPRINTF_MACRO snprintf /**< Default snprintf macro to use, can be undefined */ +//#define MBEDTLS_PLATFORM_NV_SEED_READ_MACRO mbedtls_platform_std_nv_seed_read /**< Default nv_seed_read function to use, can be undefined */ +//#define MBEDTLS_PLATFORM_NV_SEED_WRITE_MACRO mbedtls_platform_std_nv_seed_write /**< Default nv_seed_write function to use, can be undefined */ + +/** + * \brief This macro is invoked by the library when an invalid parameter + * is detected that is only checked with #MBEDTLS_CHECK_PARAMS + * (see the documentation of that option for context). + * + * When you leave this undefined here, the library provides + * a default definition. If the macro #MBEDTLS_CHECK_PARAMS_ASSERT + * is defined, the default definition is `assert(cond)`, + * otherwise the default definition calls a function + * mbedtls_param_failed(). This function is declared in + * `platform_util.h` for the benefit of the library, but + * you need to define in your application. + * + * When you define this here, this replaces the default + * definition in platform_util.h (which no longer declares the + * function mbedtls_param_failed()) and it is your responsibility + * to make sure this macro expands to something suitable (in + * particular, that all the necessary declarations are visible + * from within the library - you can ensure that by providing + * them in this file next to the macro definition). + * If you define this macro to call `assert`, also define + * #MBEDTLS_CHECK_PARAMS_ASSERT so that library source files + * include ``. + * + * Note that you may define this macro to expand to nothing, in + * which case you don't have to worry about declarations or + * definitions. However, you will then be notified about invalid + * parameters only in non-void functions, and void function will + * just silently return early on invalid parameters, which + * partially negates the benefits of enabling + * #MBEDTLS_CHECK_PARAMS in the first place, so is discouraged. + * + * \param cond The expression that should evaluate to true, but doesn't. + */ +//#define MBEDTLS_PARAM_FAILED( cond ) assert( cond ) + +/* SSL Cache options */ +//#define MBEDTLS_SSL_CACHE_DEFAULT_TIMEOUT 86400 /**< 1 day */ +//#define MBEDTLS_SSL_CACHE_DEFAULT_MAX_ENTRIES 50 /**< Maximum entries in cache */ + +/* SSL options */ + +/** \def MBEDTLS_SSL_MAX_CONTENT_LEN + * + * Maximum length (in bytes) of incoming and outgoing plaintext fragments. + * + * This determines the size of both the incoming and outgoing TLS I/O buffers + * in such a way that both are capable of holding the specified amount of + * plaintext data, regardless of the protection mechanism used. + * + * To configure incoming and outgoing I/O buffers separately, use + * #MBEDTLS_SSL_IN_CONTENT_LEN and #MBEDTLS_SSL_OUT_CONTENT_LEN, + * which overwrite the value set by this option. + * + * \note When using a value less than the default of 16KB on the client, it is + * recommended to use the Maximum Fragment Length (MFL) extension to + * inform the server about this limitation. On the server, there + * is no supported, standardized way of informing the client about + * restriction on the maximum size of incoming messages, and unless + * the limitation has been communicated by other means, it is recommended + * to only change the outgoing buffer size #MBEDTLS_SSL_OUT_CONTENT_LEN + * while keeping the default value of 16KB for the incoming buffer. + * + * Uncomment to set the maximum plaintext size of both + * incoming and outgoing I/O buffers. + */ +#define MBEDTLS_SSL_MAX_CONTENT_LEN 16384 + +/** \def MBEDTLS_SSL_IN_CONTENT_LEN + * + * Maximum length (in bytes) of incoming plaintext fragments. + * + * This determines the size of the incoming TLS I/O buffer in such a way + * that it is capable of holding the specified amount of plaintext data, + * regardless of the protection mechanism used. + * + * If this option is undefined, it inherits its value from + * #MBEDTLS_SSL_MAX_CONTENT_LEN. + * + * \note When using a value less than the default of 16KB on the client, it is + * recommended to use the Maximum Fragment Length (MFL) extension to + * inform the server about this limitation. On the server, there + * is no supported, standardized way of informing the client about + * restriction on the maximum size of incoming messages, and unless + * the limitation has been communicated by other means, it is recommended + * to only change the outgoing buffer size #MBEDTLS_SSL_OUT_CONTENT_LEN + * while keeping the default value of 16KB for the incoming buffer. + * + * Uncomment to set the maximum plaintext size of the incoming I/O buffer + * independently of the outgoing I/O buffer. + */ +#define MBEDTLS_SSL_IN_CONTENT_LEN 16384 + +/** \def MBEDTLS_SSL_OUT_CONTENT_LEN + * + * Maximum length (in bytes) of outgoing plaintext fragments. + * + * This determines the size of the outgoing TLS I/O buffer in such a way + * that it is capable of holding the specified amount of plaintext data, + * regardless of the protection mechanism used. + * + * If this option undefined, it inherits its value from + * #MBEDTLS_SSL_MAX_CONTENT_LEN. + * + * It is possible to save RAM by setting a smaller outward buffer, while keeping + * the default inward 16384 byte buffer to conform to the TLS specification. + * + * The minimum required outward buffer size is determined by the handshake + * protocol's usage. Handshaking will fail if the outward buffer is too small. + * The specific size requirement depends on the configured ciphers and any + * certificate data which is sent during the handshake. + * + * Uncomment to set the maximum plaintext size of the outgoing I/O buffer + * independently of the incoming I/O buffer. + */ +//#define MBEDTLS_SSL_OUT_CONTENT_LEN 16384 +#define MBEDTLS_SSL_OUT_CONTENT_LEN 2048 + +/** \def MBEDTLS_SSL_DTLS_MAX_BUFFERING + * + * Maximum number of heap-allocated bytes for the purpose of + * DTLS handshake message reassembly and future message buffering. + * + * This should be at least 9/8 * MBEDTLSSL_IN_CONTENT_LEN + * to account for a reassembled handshake message of maximum size, + * together with its reassembly bitmap. + * + * A value of 2 * MBEDTLS_SSL_IN_CONTENT_LEN (32768 by default) + * should be sufficient for all practical situations as it allows + * to reassembly a large handshake message (such as a certificate) + * while buffering multiple smaller handshake messages. + * + */ +//#define MBEDTLS_SSL_DTLS_MAX_BUFFERING 32768 + +//#define MBEDTLS_SSL_DEFAULT_TICKET_LIFETIME 86400 /**< Lifetime of session tickets (if enabled) */ +//#define MBEDTLS_PSK_MAX_LEN 32 /**< Max size of TLS pre-shared keys, in bytes (default 256 bits) */ +//#define MBEDTLS_SSL_COOKIE_TIMEOUT 60 /**< Default expiration delay of DTLS cookies, in seconds if HAVE_TIME, or in number of cookies issued */ + +/** + * Complete list of ciphersuites to use, in order of preference. + * + * \warning No dependency checking is done on that field! This option can only + * be used to restrict the set of available ciphersuites. It is your + * responsibility to make sure the needed modules are active. + * + * Use this to save a few hundred bytes of ROM (default ordering of all + * available ciphersuites) and a few to a few hundred bytes of RAM. + * + * The value below is only an example, not the default. + */ +//#define MBEDTLS_SSL_CIPHERSUITES MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 + +/* X509 options */ +//#define MBEDTLS_X509_MAX_INTERMEDIATE_CA 8 /**< Maximum number of intermediate CAs in a verification chain. */ +//#define MBEDTLS_X509_MAX_FILE_PATH_LEN 512 /**< Maximum length of a path/filename string in bytes including the null terminator character ('\0'). */ + +/** + * Allow SHA-1 in the default TLS configuration for certificate signing. + * Without this build-time option, SHA-1 support must be activated explicitly + * through mbedtls_ssl_conf_cert_profile. Turning on this option is not + * recommended because of it is possible to generate SHA-1 collisions, however + * this may be safe for legacy infrastructure where additional controls apply. + * + * \warning SHA-1 is considered a weak message digest and its use constitutes + * a security risk. If possible, we recommend avoiding dependencies + * on it, and considering stronger message digests instead. + * + */ +#define MBEDTLS_TLS_DEFAULT_ALLOW_SHA1_IN_CERTIFICATES + +/** + * Allow SHA-1 in the default TLS configuration for TLS 1.2 handshake + * signature and ciphersuite selection. Without this build-time option, SHA-1 + * support must be activated explicitly through mbedtls_ssl_conf_sig_hashes. + * The use of SHA-1 in TLS <= 1.1 and in HMAC-SHA-1 is always allowed by + * default. At the time of writing, there is no practical attack on the use + * of SHA-1 in handshake signatures, hence this option is turned on by default + * to preserve compatibility with existing peers, but the general + * warning applies nonetheless: + * + * \warning SHA-1 is considered a weak message digest and its use constitutes + * a security risk. If possible, we recommend avoiding dependencies + * on it, and considering stronger message digests instead. + * + */ +#define MBEDTLS_TLS_DEFAULT_ALLOW_SHA1_IN_KEY_EXCHANGE + +/** + * Uncomment the macro to let mbed TLS use your alternate implementation of + * mbedtls_platform_zeroize(). This replaces the default implementation in + * platform_util.c. + * + * mbedtls_platform_zeroize() is a widely used function across the library to + * zero a block of memory. The implementation is expected to be secure in the + * sense that it has been written to prevent the compiler from removing calls + * to mbedtls_platform_zeroize() as part of redundant code elimination + * optimizations. However, it is difficult to guarantee that calls to + * mbedtls_platform_zeroize() will not be optimized by the compiler as older + * versions of the C language standards do not provide a secure implementation + * of memset(). Therefore, MBEDTLS_PLATFORM_ZEROIZE_ALT enables users to + * configure their own implementation of mbedtls_platform_zeroize(), for + * example by using directives specific to their compiler, features from newer + * C standards (e.g using memset_s() in C11) or calling a secure memset() from + * their system (e.g explicit_bzero() in BSD). + */ +//#define MBEDTLS_PLATFORM_ZEROIZE_ALT + +/** + * Uncomment the macro to let Mbed TLS use your alternate implementation of + * mbedtls_platform_gmtime_r(). This replaces the default implementation in + * platform_util.c. + * + * gmtime() is not a thread-safe function as defined in the C standard. The + * library will try to use safer implementations of this function, such as + * gmtime_r() when available. However, if Mbed TLS cannot identify the target + * system, the implementation of mbedtls_platform_gmtime_r() will default to + * using the standard gmtime(). In this case, calls from the library to + * gmtime() will be guarded by the global mutex mbedtls_threading_gmtime_mutex + * if MBEDTLS_THREADING_C is enabled. We recommend that calls from outside the + * library are also guarded with this mutex to avoid race conditions. However, + * if the macro MBEDTLS_PLATFORM_GMTIME_R_ALT is defined, Mbed TLS will + * unconditionally use the implementation for mbedtls_platform_gmtime_r() + * supplied at compile time. + */ +//#define MBEDTLS_PLATFORM_GMTIME_R_ALT + +/* \} name SECTION: Customisation configuration options */ + +/* Target and application specific configurations + * + * Allow user to override any previous default. + * + */ +#if defined(MBEDTLS_USER_CONFIG_FILE) +#include MBEDTLS_USER_CONFIG_FILE +#endif + +#include "check_config.h" + +#endif /* MBEDTLS_CONFIG_H */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/ctr_drbg.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/ctr_drbg.h new file mode 100644 index 0000000000000000000000000000000000000000..e0b5ed9c937d76d615c43363783d9edc73ba61f5 --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/ctr_drbg.h @@ -0,0 +1,512 @@ +/** + * \file ctr_drbg.h + * + * \brief This file contains definitions and functions for the + * CTR_DRBG pseudorandom generator. + * + * CTR_DRBG is a standardized way of building a PRNG from a block-cipher + * in counter mode operation, as defined in NIST SP 800-90A: + * Recommendation for Random Number Generation Using Deterministic Random + * Bit Generators. + * + * The Mbed TLS implementation of CTR_DRBG uses AES-256 (default) or AES-128 + * (if \c MBEDTLS_CTR_DRBG_USE_128_BIT_KEY is enabled at compile time) + * as the underlying block cipher, with a derivation function. + * The initial seeding grabs #MBEDTLS_CTR_DRBG_ENTROPY_LEN bytes of entropy. + * See the documentation of mbedtls_ctr_drbg_seed() for more details. + * + * Based on NIST SP 800-90A §10.2.1 table 3 and NIST SP 800-57 part 1 table 2, + * here are the security strengths achieved in typical configuration: + * - 256 bits under the default configuration of the library, with AES-256 + * and with #MBEDTLS_CTR_DRBG_ENTROPY_LEN set to 48 or more. + * - 256 bits if AES-256 is used, #MBEDTLS_CTR_DRBG_ENTROPY_LEN is set + * to 32 or more, and the DRBG is initialized with an explicit + * nonce in the \c custom parameter to mbedtls_ctr_drbg_seed(). + * - 128 bits if AES-256 is used but #MBEDTLS_CTR_DRBG_ENTROPY_LEN is + * between 24 and 47 and the DRBG is not initialized with an explicit + * nonce (see mbedtls_ctr_drbg_seed()). + * - 128 bits if AES-128 is used (\c MBEDTLS_CTR_DRBG_USE_128_BIT_KEY enabled) + * and #MBEDTLS_CTR_DRBG_ENTROPY_LEN is set to 24 or more (which is + * always the case unless it is explicitly set to a different value + * in config.h). + * + * Note that the value of #MBEDTLS_CTR_DRBG_ENTROPY_LEN defaults to: + * - \c 48 if the module \c MBEDTLS_SHA512_C is enabled and the symbol + * \c MBEDTLS_ENTROPY_FORCE_SHA256 is disabled at compile time. + * This is the default configuration of the library. + * - \c 32 if the module \c MBEDTLS_SHA512_C is disabled at compile time. + * - \c 32 if \c MBEDTLS_ENTROPY_FORCE_SHA256 is enabled at compile time. + */ +/* + * Copyright (C) 2006-2019, Arm Limited (or its affiliates), All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of Mbed TLS (https://tls.mbed.org) + */ + +#ifndef MBEDTLS_CTR_DRBG_H +#define MBEDTLS_CTR_DRBG_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include "aes.h" + +#if defined(MBEDTLS_THREADING_C) +#include "threading.h" +#endif + +#define MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED -0x0034 /**< The entropy source failed. */ +#define MBEDTLS_ERR_CTR_DRBG_REQUEST_TOO_BIG -0x0036 /**< The requested random buffer length is too big. */ +#define MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG -0x0038 /**< The input (entropy + additional data) is too large. */ +#define MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR -0x003A /**< Read or write error in file. */ + +#define MBEDTLS_CTR_DRBG_BLOCKSIZE 16 /**< The block size used by the cipher. */ + +#if defined(MBEDTLS_CTR_DRBG_USE_128_BIT_KEY) +#define MBEDTLS_CTR_DRBG_KEYSIZE 16 +/**< The key size in bytes used by the cipher. + * + * Compile-time choice: 16 bytes (128 bits) + * because #MBEDTLS_CTR_DRBG_USE_128_BIT_KEY is enabled. + */ +#else +#define MBEDTLS_CTR_DRBG_KEYSIZE 32 +/**< The key size in bytes used by the cipher. + * + * Compile-time choice: 32 bytes (256 bits) + * because \c MBEDTLS_CTR_DRBG_USE_128_BIT_KEY is disabled. + */ +#endif + +#define MBEDTLS_CTR_DRBG_KEYBITS ( MBEDTLS_CTR_DRBG_KEYSIZE * 8 ) /**< The key size for the DRBG operation, in bits. */ +#define MBEDTLS_CTR_DRBG_SEEDLEN ( MBEDTLS_CTR_DRBG_KEYSIZE + MBEDTLS_CTR_DRBG_BLOCKSIZE ) /**< The seed length, calculated as (counter + AES key). */ + +/** + * \name SECTION: Module settings + * + * The configuration options you can set for this module are in this section. + * Either change them in config.h or define them using the compiler command + * line. + * \{ + */ + +/** \def MBEDTLS_CTR_DRBG_ENTROPY_LEN + * + * \brief The amount of entropy used per seed by default, in bytes. + */ +#if !defined(MBEDTLS_CTR_DRBG_ENTROPY_LEN) +#if defined(MBEDTLS_SHA512_C) && !defined(MBEDTLS_ENTROPY_FORCE_SHA256) +/** This is 48 bytes because the entropy module uses SHA-512 + * (\c MBEDTLS_ENTROPY_FORCE_SHA256 is disabled). + */ +#define MBEDTLS_CTR_DRBG_ENTROPY_LEN 48 + +#else /* defined(MBEDTLS_SHA512_C) && !defined(MBEDTLS_ENTROPY_FORCE_SHA256) */ + +/** This is 32 bytes because the entropy module uses SHA-256 + * (the SHA512 module is disabled or + * \c MBEDTLS_ENTROPY_FORCE_SHA256 is enabled). + */ +#if !defined(MBEDTLS_CTR_DRBG_USE_128_BIT_KEY) +/** \warning To achieve a 256-bit security strength, you must pass a nonce + * to mbedtls_ctr_drbg_seed(). + */ +#endif /* !defined(MBEDTLS_CTR_DRBG_USE_128_BIT_KEY) */ +#define MBEDTLS_CTR_DRBG_ENTROPY_LEN 32 +#endif /* defined(MBEDTLS_SHA512_C) && !defined(MBEDTLS_ENTROPY_FORCE_SHA256) */ +#endif /* !defined(MBEDTLS_CTR_DRBG_ENTROPY_LEN) */ + +#if !defined(MBEDTLS_CTR_DRBG_RESEED_INTERVAL) +#define MBEDTLS_CTR_DRBG_RESEED_INTERVAL 10000 +/**< The interval before reseed is performed by default. */ +#endif + +#if !defined(MBEDTLS_CTR_DRBG_MAX_INPUT) +#define MBEDTLS_CTR_DRBG_MAX_INPUT 256 +/**< The maximum number of additional input Bytes. */ +#endif + +#if !defined(MBEDTLS_CTR_DRBG_MAX_REQUEST) +#define MBEDTLS_CTR_DRBG_MAX_REQUEST 1024 +/**< The maximum number of requested Bytes per call. */ +#endif + +#if !defined(MBEDTLS_CTR_DRBG_MAX_SEED_INPUT) +#define MBEDTLS_CTR_DRBG_MAX_SEED_INPUT 384 +/**< The maximum size of seed or reseed buffer in bytes. */ +#endif + +/* \} name SECTION: Module settings */ + +#define MBEDTLS_CTR_DRBG_PR_OFF 0 +/**< Prediction resistance is disabled. */ +#define MBEDTLS_CTR_DRBG_PR_ON 1 +/**< Prediction resistance is enabled. */ + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \brief The CTR_DRBG context structure. + */ +typedef struct mbedtls_ctr_drbg_context +{ + unsigned char counter[16]; /*!< The counter (V). */ + int reseed_counter; /*!< The reseed counter. */ + int prediction_resistance; /*!< This determines whether prediction + resistance is enabled, that is + whether to systematically reseed before + each random generation. */ + size_t entropy_len; /*!< The amount of entropy grabbed on each + seed or reseed operation. */ + int reseed_interval; /*!< The reseed interval. */ + + mbedtls_aes_context aes_ctx; /*!< The AES context. */ + + /* + * Callbacks (Entropy) + */ + int (*f_entropy)(void *, unsigned char *, size_t); + /*!< The entropy callback function. */ + + void *p_entropy; /*!< The context for the entropy function. */ + +#if defined(MBEDTLS_THREADING_C) + mbedtls_threading_mutex_t mutex; +#endif +} +mbedtls_ctr_drbg_context; + +/** + * \brief This function initializes the CTR_DRBG context, + * and prepares it for mbedtls_ctr_drbg_seed() + * or mbedtls_ctr_drbg_free(). + * + * \param ctx The CTR_DRBG context to initialize. + */ +void mbedtls_ctr_drbg_init( mbedtls_ctr_drbg_context *ctx ); + +/** + * \brief This function seeds and sets up the CTR_DRBG + * entropy source for future reseeds. + * + * A typical choice for the \p f_entropy and \p p_entropy parameters is + * to use the entropy module: + * - \p f_entropy is mbedtls_entropy_func(); + * - \p p_entropy is an instance of ::mbedtls_entropy_context initialized + * with mbedtls_entropy_init() (which registers the platform's default + * entropy sources). + * + * The entropy length is #MBEDTLS_CTR_DRBG_ENTROPY_LEN by default. + * You can override it by calling mbedtls_ctr_drbg_set_entropy_len(). + * + * You can provide a personalization string in addition to the + * entropy source, to make this instantiation as unique as possible. + * + * \note The _seed_material_ value passed to the derivation + * function in the CTR_DRBG Instantiate Process + * described in NIST SP 800-90A §10.2.1.3.2 + * is the concatenation of the string obtained from + * calling \p f_entropy and the \p custom string. + * The origin of the nonce depends on the value of + * the entropy length relative to the security strength. + * - If the entropy length is at least 1.5 times the + * security strength then the nonce is taken from the + * string obtained with \p f_entropy. + * - If the entropy length is less than the security + * strength, then the nonce is taken from \p custom. + * In this case, for compliance with SP 800-90A, + * you must pass a unique value of \p custom at + * each invocation. See SP 800-90A §8.6.7 for more + * details. + */ +#if MBEDTLS_CTR_DRBG_ENTROPY_LEN < MBEDTLS_CTR_DRBG_KEYSIZE * 3 / 2 +/** \warning When #MBEDTLS_CTR_DRBG_ENTROPY_LEN is less than + * #MBEDTLS_CTR_DRBG_KEYSIZE * 3 / 2, to achieve the + * maximum security strength permitted by CTR_DRBG, + * you must pass a value of \p custom that is a nonce: + * this value must never be repeated in subsequent + * runs of the same application or on a different + * device. + */ +#endif +/** + * \param ctx The CTR_DRBG context to seed. + * It must have been initialized with + * mbedtls_ctr_drbg_init(). + * After a successful call to mbedtls_ctr_drbg_seed(), + * you may not call mbedtls_ctr_drbg_seed() again on + * the same context unless you call + * mbedtls_ctr_drbg_free() and mbedtls_ctr_drbg_init() + * again first. + * \param f_entropy The entropy callback, taking as arguments the + * \p p_entropy context, the buffer to fill, and the + * length of the buffer. + * \p f_entropy is always called with a buffer size + * equal to the entropy length. + * \param p_entropy The entropy context to pass to \p f_entropy. + * \param custom The personalization string. + * This can be \c NULL, in which case the personalization + * string is empty regardless of the value of \p len. + * \param len The length of the personalization string. + * This must be at most + * #MBEDTLS_CTR_DRBG_MAX_SEED_INPUT + * - #MBEDTLS_CTR_DRBG_ENTROPY_LEN. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED on failure. + */ +int mbedtls_ctr_drbg_seed( mbedtls_ctr_drbg_context *ctx, + int (*f_entropy)(void *, unsigned char *, size_t), + void *p_entropy, + const unsigned char *custom, + size_t len ); + +/** + * \brief This function clears CTR_CRBG context data. + * + * \param ctx The CTR_DRBG context to clear. + */ +void mbedtls_ctr_drbg_free( mbedtls_ctr_drbg_context *ctx ); + +/** + * \brief This function turns prediction resistance on or off. + * The default value is off. + * + * \note If enabled, entropy is gathered at the beginning of + * every call to mbedtls_ctr_drbg_random_with_add() + * or mbedtls_ctr_drbg_random(). + * Only use this if your entropy source has sufficient + * throughput. + * + * \param ctx The CTR_DRBG context. + * \param resistance #MBEDTLS_CTR_DRBG_PR_ON or #MBEDTLS_CTR_DRBG_PR_OFF. + */ +void mbedtls_ctr_drbg_set_prediction_resistance( mbedtls_ctr_drbg_context *ctx, + int resistance ); + +/** + * \brief This function sets the amount of entropy grabbed on each + * seed or reseed. + * + * The default value is #MBEDTLS_CTR_DRBG_ENTROPY_LEN. + * + * \note The security strength of CTR_DRBG is bounded by the + * entropy length. Thus: + * - When using AES-256 + * (\c MBEDTLS_CTR_DRBG_USE_128_BIT_KEY is disabled, + * which is the default), + * \p len must be at least 32 (in bytes) + * to achieve a 256-bit strength. + * - When using AES-128 + * (\c MBEDTLS_CTR_DRBG_USE_128_BIT_KEY is enabled) + * \p len must be at least 16 (in bytes) + * to achieve a 128-bit strength. + * + * \param ctx The CTR_DRBG context. + * \param len The amount of entropy to grab, in bytes. + * This must be at most #MBEDTLS_CTR_DRBG_MAX_SEED_INPUT. + */ +void mbedtls_ctr_drbg_set_entropy_len( mbedtls_ctr_drbg_context *ctx, + size_t len ); + +/** + * \brief This function sets the reseed interval. + * + * The reseed interval is the number of calls to mbedtls_ctr_drbg_random() + * or mbedtls_ctr_drbg_random_with_add() after which the entropy function + * is called again. + * + * The default value is #MBEDTLS_CTR_DRBG_RESEED_INTERVAL. + * + * \param ctx The CTR_DRBG context. + * \param interval The reseed interval. + */ +void mbedtls_ctr_drbg_set_reseed_interval( mbedtls_ctr_drbg_context *ctx, + int interval ); + +/** + * \brief This function reseeds the CTR_DRBG context, that is + * extracts data from the entropy source. + * + * \param ctx The CTR_DRBG context. + * \param additional Additional data to add to the state. Can be \c NULL. + * \param len The length of the additional data. + * This must be less than + * #MBEDTLS_CTR_DRBG_MAX_SEED_INPUT - \c entropy_len + * where \c entropy_len is the entropy length + * configured for the context. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED on failure. + */ +int mbedtls_ctr_drbg_reseed( mbedtls_ctr_drbg_context *ctx, + const unsigned char *additional, size_t len ); + +/** + * \brief This function updates the state of the CTR_DRBG context. + * + * \param ctx The CTR_DRBG context. + * \param additional The data to update the state with. This must not be + * \c NULL unless \p add_len is \c 0. + * \param add_len Length of \p additional in bytes. This must be at + * most #MBEDTLS_CTR_DRBG_MAX_SEED_INPUT. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG if + * \p add_len is more than + * #MBEDTLS_CTR_DRBG_MAX_SEED_INPUT. + * \return An error from the underlying AES cipher on failure. + */ +int mbedtls_ctr_drbg_update_ret( mbedtls_ctr_drbg_context *ctx, + const unsigned char *additional, + size_t add_len ); + +/** + * \brief This function updates a CTR_DRBG instance with additional + * data and uses it to generate random data. + * + * This function automatically reseeds if the reseed counter is exceeded + * or prediction resistance is enabled. + * + * \param p_rng The CTR_DRBG context. This must be a pointer to a + * #mbedtls_ctr_drbg_context structure. + * \param output The buffer to fill. + * \param output_len The length of the buffer in bytes. + * \param additional Additional data to update. Can be \c NULL, in which + * case the additional data is empty regardless of + * the value of \p add_len. + * \param add_len The length of the additional data + * if \p additional is not \c NULL. + * This must be less than #MBEDTLS_CTR_DRBG_MAX_INPUT + * and less than + * #MBEDTLS_CTR_DRBG_MAX_SEED_INPUT - \c entropy_len + * where \c entropy_len is the entropy length + * configured for the context. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED or + * #MBEDTLS_ERR_CTR_DRBG_REQUEST_TOO_BIG on failure. + */ +int mbedtls_ctr_drbg_random_with_add( void *p_rng, + unsigned char *output, size_t output_len, + const unsigned char *additional, size_t add_len ); + +/** + * \brief This function uses CTR_DRBG to generate random data. + * + * This function automatically reseeds if the reseed counter is exceeded + * or prediction resistance is enabled. + * + * + * \param p_rng The CTR_DRBG context. This must be a pointer to a + * #mbedtls_ctr_drbg_context structure. + * \param output The buffer to fill. + * \param output_len The length of the buffer in bytes. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED or + * #MBEDTLS_ERR_CTR_DRBG_REQUEST_TOO_BIG on failure. + */ +int mbedtls_ctr_drbg_random( void *p_rng, + unsigned char *output, size_t output_len ); + + +#if ! defined(MBEDTLS_DEPRECATED_REMOVED) +#if defined(MBEDTLS_DEPRECATED_WARNING) +#define MBEDTLS_DEPRECATED __attribute__((deprecated)) +#else +#define MBEDTLS_DEPRECATED +#endif +/** + * \brief This function updates the state of the CTR_DRBG context. + * + * \deprecated Superseded by mbedtls_ctr_drbg_update_ret() + * in 2.16.0. + * + * \note If \p add_len is greater than + * #MBEDTLS_CTR_DRBG_MAX_SEED_INPUT, only the first + * #MBEDTLS_CTR_DRBG_MAX_SEED_INPUT Bytes are used. + * The remaining Bytes are silently discarded. + * + * \param ctx The CTR_DRBG context. + * \param additional The data to update the state with. + * \param add_len Length of \p additional data. + */ +MBEDTLS_DEPRECATED void mbedtls_ctr_drbg_update( + mbedtls_ctr_drbg_context *ctx, + const unsigned char *additional, + size_t add_len ); +#undef MBEDTLS_DEPRECATED +#endif /* !MBEDTLS_DEPRECATED_REMOVED */ + +#if defined(MBEDTLS_FS_IO) +/** + * \brief This function writes a seed file. + * + * \param ctx The CTR_DRBG context. + * \param path The name of the file. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR on file error. + * \return #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED on reseed + * failure. + */ +int mbedtls_ctr_drbg_write_seed_file( mbedtls_ctr_drbg_context *ctx, const char *path ); + +/** + * \brief This function reads and updates a seed file. The seed + * is added to this instance. + * + * \param ctx The CTR_DRBG context. + * \param path The name of the file. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR on file error. + * \return #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED on + * reseed failure. + * \return #MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG if the existing + * seed file is too large. + */ +int mbedtls_ctr_drbg_update_seed_file( mbedtls_ctr_drbg_context *ctx, const char *path ); +#endif /* MBEDTLS_FS_IO */ + +#if defined(MBEDTLS_SELF_TEST) + +/** + * \brief The CTR_DRBG checkup routine. + * + * \return \c 0 on success. + * \return \c 1 on failure. + */ +int mbedtls_ctr_drbg_self_test( int verbose ); + +#endif /* MBEDTLS_SELF_TEST */ + +/* Internal functions (do not call directly) */ +int mbedtls_ctr_drbg_seed_entropy_len( mbedtls_ctr_drbg_context *, + int (*)(void *, unsigned char *, size_t), void *, + const unsigned char *, size_t, size_t ); + +#ifdef __cplusplus +} +#endif + +#endif /* ctr_drbg.h */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/debug.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/debug.h new file mode 100644 index 0000000000000000000000000000000000000000..736444bb76a995d9a8e955938f4e60892015d634 --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/debug.h @@ -0,0 +1,265 @@ +/** + * \file debug.h + * + * \brief Functions for controlling and providing debug output from the library. + */ +/* + * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ +#ifndef MBEDTLS_DEBUG_H +#define MBEDTLS_DEBUG_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include "ssl.h" + +#if defined(MBEDTLS_ECP_C) +#include "ecp.h" +#endif + +#if defined(MBEDTLS_DEBUG_C) + +#define MBEDTLS_DEBUG_STRIP_PARENS( ... ) __VA_ARGS__ + +#define MBEDTLS_SSL_DEBUG_MSG( level, args ) \ + mbedtls_debug_print_msg( ssl, level, __FILE__, __LINE__, \ + MBEDTLS_DEBUG_STRIP_PARENS args ) + +#define MBEDTLS_SSL_DEBUG_RET( level, text, ret ) \ + mbedtls_debug_print_ret( ssl, level, __FILE__, __LINE__, text, ret ) + +#define MBEDTLS_SSL_DEBUG_BUF( level, text, buf, len ) \ + mbedtls_debug_print_buf( ssl, level, __FILE__, __LINE__, text, buf, len ) + +#if defined(MBEDTLS_BIGNUM_C) +#define MBEDTLS_SSL_DEBUG_MPI( level, text, X ) \ + mbedtls_debug_print_mpi( ssl, level, __FILE__, __LINE__, text, X ) +#endif + +#if defined(MBEDTLS_ECP_C) +#define MBEDTLS_SSL_DEBUG_ECP( level, text, X ) \ + mbedtls_debug_print_ecp( ssl, level, __FILE__, __LINE__, text, X ) +#endif + +#if defined(MBEDTLS_X509_CRT_PARSE_C) +#define MBEDTLS_SSL_DEBUG_CRT( level, text, crt ) \ + mbedtls_debug_print_crt( ssl, level, __FILE__, __LINE__, text, crt ) +#endif + +#if defined(MBEDTLS_ECDH_C) +#define MBEDTLS_SSL_DEBUG_ECDH( level, ecdh, attr ) \ + mbedtls_debug_printf_ecdh( ssl, level, __FILE__, __LINE__, ecdh, attr ) +#endif + +#else /* MBEDTLS_DEBUG_C */ + +#define MBEDTLS_SSL_DEBUG_MSG( level, args ) do { } while( 0 ) +#define MBEDTLS_SSL_DEBUG_RET( level, text, ret ) do { } while( 0 ) +#define MBEDTLS_SSL_DEBUG_BUF( level, text, buf, len ) do { } while( 0 ) +#define MBEDTLS_SSL_DEBUG_MPI( level, text, X ) do { } while( 0 ) +#define MBEDTLS_SSL_DEBUG_ECP( level, text, X ) do { } while( 0 ) +#define MBEDTLS_SSL_DEBUG_CRT( level, text, crt ) do { } while( 0 ) +#define MBEDTLS_SSL_DEBUG_ECDH( level, ecdh, attr ) do { } while( 0 ) + +#endif /* MBEDTLS_DEBUG_C */ + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \brief Set the threshold error level to handle globally all debug output. + * Debug messages that have a level over the threshold value are + * discarded. + * (Default value: 0 = No debug ) + * + * \param threshold theshold level of messages to filter on. Messages at a + * higher level will be discarded. + * - Debug levels + * - 0 No debug + * - 1 Error + * - 2 State change + * - 3 Informational + * - 4 Verbose + */ +void mbedtls_debug_set_threshold( int threshold ); + +/** + * \brief Print a message to the debug output. This function is always used + * through the MBEDTLS_SSL_DEBUG_MSG() macro, which supplies the ssl + * context, file and line number parameters. + * + * \param ssl SSL context + * \param level error level of the debug message + * \param file file the message has occurred in + * \param line line number the message has occurred at + * \param format format specifier, in printf format + * \param ... variables used by the format specifier + * + * \attention This function is intended for INTERNAL usage within the + * library only. + */ +void mbedtls_debug_print_msg( const mbedtls_ssl_context *ssl, int level, + const char *file, int line, + const char *format, ... ); + +/** + * \brief Print the return value of a function to the debug output. This + * function is always used through the MBEDTLS_SSL_DEBUG_RET() macro, + * which supplies the ssl context, file and line number parameters. + * + * \param ssl SSL context + * \param level error level of the debug message + * \param file file the error has occurred in + * \param line line number the error has occurred in + * \param text the name of the function that returned the error + * \param ret the return code value + * + * \attention This function is intended for INTERNAL usage within the + * library only. + */ +void mbedtls_debug_print_ret( const mbedtls_ssl_context *ssl, int level, + const char *file, int line, + const char *text, int ret ); + +/** + * \brief Output a buffer of size len bytes to the debug output. This function + * is always used through the MBEDTLS_SSL_DEBUG_BUF() macro, + * which supplies the ssl context, file and line number parameters. + * + * \param ssl SSL context + * \param level error level of the debug message + * \param file file the error has occurred in + * \param line line number the error has occurred in + * \param text a name or label for the buffer being dumped. Normally the + * variable or buffer name + * \param buf the buffer to be outputted + * \param len length of the buffer + * + * \attention This function is intended for INTERNAL usage within the + * library only. + */ +void mbedtls_debug_print_buf( const mbedtls_ssl_context *ssl, int level, + const char *file, int line, const char *text, + const unsigned char *buf, size_t len ); + +#if defined(MBEDTLS_BIGNUM_C) +/** + * \brief Print a MPI variable to the debug output. This function is always + * used through the MBEDTLS_SSL_DEBUG_MPI() macro, which supplies the + * ssl context, file and line number parameters. + * + * \param ssl SSL context + * \param level error level of the debug message + * \param file file the error has occurred in + * \param line line number the error has occurred in + * \param text a name or label for the MPI being output. Normally the + * variable name + * \param X the MPI variable + * + * \attention This function is intended for INTERNAL usage within the + * library only. + */ +void mbedtls_debug_print_mpi( const mbedtls_ssl_context *ssl, int level, + const char *file, int line, + const char *text, const mbedtls_mpi *X ); +#endif + +#if defined(MBEDTLS_ECP_C) +/** + * \brief Print an ECP point to the debug output. This function is always + * used through the MBEDTLS_SSL_DEBUG_ECP() macro, which supplies the + * ssl context, file and line number parameters. + * + * \param ssl SSL context + * \param level error level of the debug message + * \param file file the error has occurred in + * \param line line number the error has occurred in + * \param text a name or label for the ECP point being output. Normally the + * variable name + * \param X the ECP point + * + * \attention This function is intended for INTERNAL usage within the + * library only. + */ +void mbedtls_debug_print_ecp( const mbedtls_ssl_context *ssl, int level, + const char *file, int line, + const char *text, const mbedtls_ecp_point *X ); +#endif + +#if defined(MBEDTLS_X509_CRT_PARSE_C) +/** + * \brief Print a X.509 certificate structure to the debug output. This + * function is always used through the MBEDTLS_SSL_DEBUG_CRT() macro, + * which supplies the ssl context, file and line number parameters. + * + * \param ssl SSL context + * \param level error level of the debug message + * \param file file the error has occurred in + * \param line line number the error has occurred in + * \param text a name or label for the certificate being output + * \param crt X.509 certificate structure + * + * \attention This function is intended for INTERNAL usage within the + * library only. + */ +void mbedtls_debug_print_crt( const mbedtls_ssl_context *ssl, int level, + const char *file, int line, + const char *text, const mbedtls_x509_crt *crt ); +#endif + +#if defined(MBEDTLS_ECDH_C) +typedef enum +{ + MBEDTLS_DEBUG_ECDH_Q, + MBEDTLS_DEBUG_ECDH_QP, + MBEDTLS_DEBUG_ECDH_Z, +} mbedtls_debug_ecdh_attr; + +/** + * \brief Print a field of the ECDH structure in the SSL context to the debug + * output. This function is always used through the + * MBEDTLS_SSL_DEBUG_ECDH() macro, which supplies the ssl context, file + * and line number parameters. + * + * \param ssl SSL context + * \param level error level of the debug message + * \param file file the error has occurred in + * \param line line number the error has occurred in + * \param ecdh the ECDH context + * \param attr the identifier of the attribute being output + * + * \attention This function is intended for INTERNAL usage within the + * library only. + */ +void mbedtls_debug_printf_ecdh( const mbedtls_ssl_context *ssl, int level, + const char *file, int line, + const mbedtls_ecdh_context *ecdh, + mbedtls_debug_ecdh_attr attr ); +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* debug.h */ + diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/des.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/des.h new file mode 100644 index 0000000000000000000000000000000000000000..54e6b7894b6f9ec1b3eb5823f16cca347754084d --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/des.h @@ -0,0 +1,356 @@ +/** + * \file des.h + * + * \brief DES block cipher + * + * \warning DES is considered a weak cipher and its use constitutes a + * security risk. We recommend considering stronger ciphers + * instead. + */ +/* + * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + * + */ +#ifndef MBEDTLS_DES_H +#define MBEDTLS_DES_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include +#include + +#define MBEDTLS_DES_ENCRYPT 1 +#define MBEDTLS_DES_DECRYPT 0 + +#define MBEDTLS_ERR_DES_INVALID_INPUT_LENGTH -0x0032 /**< The data input has an invalid length. */ + +/* MBEDTLS_ERR_DES_HW_ACCEL_FAILED is deprecated and should not be used. */ +#define MBEDTLS_ERR_DES_HW_ACCEL_FAILED -0x0033 /**< DES hardware accelerator failed. */ + +#define MBEDTLS_DES_KEY_SIZE 8 + +#ifdef __cplusplus +extern "C" { +#endif + +#if !defined(MBEDTLS_DES_ALT) +// Regular implementation +// + +/** + * \brief DES context structure + * + * \warning DES is considered a weak cipher and its use constitutes a + * security risk. We recommend considering stronger ciphers + * instead. + */ +typedef struct mbedtls_des_context +{ + uint32_t sk[32]; /*!< DES subkeys */ +} +mbedtls_des_context; + +/** + * \brief Triple-DES context structure + */ +typedef struct mbedtls_des3_context +{ + uint32_t sk[96]; /*!< 3DES subkeys */ +} +mbedtls_des3_context; + +#else /* MBEDTLS_DES_ALT */ +#include "des_alt.h" +#endif /* MBEDTLS_DES_ALT */ + +/** + * \brief Initialize DES context + * + * \param ctx DES context to be initialized + * + * \warning DES is considered a weak cipher and its use constitutes a + * security risk. We recommend considering stronger ciphers + * instead. + */ +void mbedtls_des_init( mbedtls_des_context *ctx ); + +/** + * \brief Clear DES context + * + * \param ctx DES context to be cleared + * + * \warning DES is considered a weak cipher and its use constitutes a + * security risk. We recommend considering stronger ciphers + * instead. + */ +void mbedtls_des_free( mbedtls_des_context *ctx ); + +/** + * \brief Initialize Triple-DES context + * + * \param ctx DES3 context to be initialized + */ +void mbedtls_des3_init( mbedtls_des3_context *ctx ); + +/** + * \brief Clear Triple-DES context + * + * \param ctx DES3 context to be cleared + */ +void mbedtls_des3_free( mbedtls_des3_context *ctx ); + +/** + * \brief Set key parity on the given key to odd. + * + * DES keys are 56 bits long, but each byte is padded with + * a parity bit to allow verification. + * + * \param key 8-byte secret key + * + * \warning DES is considered a weak cipher and its use constitutes a + * security risk. We recommend considering stronger ciphers + * instead. + */ +void mbedtls_des_key_set_parity( unsigned char key[MBEDTLS_DES_KEY_SIZE] ); + +/** + * \brief Check that key parity on the given key is odd. + * + * DES keys are 56 bits long, but each byte is padded with + * a parity bit to allow verification. + * + * \param key 8-byte secret key + * + * \return 0 is parity was ok, 1 if parity was not correct. + * + * \warning DES is considered a weak cipher and its use constitutes a + * security risk. We recommend considering stronger ciphers + * instead. + */ +int mbedtls_des_key_check_key_parity( const unsigned char key[MBEDTLS_DES_KEY_SIZE] ); + +/** + * \brief Check that key is not a weak or semi-weak DES key + * + * \param key 8-byte secret key + * + * \return 0 if no weak key was found, 1 if a weak key was identified. + * + * \warning DES is considered a weak cipher and its use constitutes a + * security risk. We recommend considering stronger ciphers + * instead. + */ +int mbedtls_des_key_check_weak( const unsigned char key[MBEDTLS_DES_KEY_SIZE] ); + +/** + * \brief DES key schedule (56-bit, encryption) + * + * \param ctx DES context to be initialized + * \param key 8-byte secret key + * + * \return 0 + * + * \warning DES is considered a weak cipher and its use constitutes a + * security risk. We recommend considering stronger ciphers + * instead. + */ +int mbedtls_des_setkey_enc( mbedtls_des_context *ctx, const unsigned char key[MBEDTLS_DES_KEY_SIZE] ); + +/** + * \brief DES key schedule (56-bit, decryption) + * + * \param ctx DES context to be initialized + * \param key 8-byte secret key + * + * \return 0 + * + * \warning DES is considered a weak cipher and its use constitutes a + * security risk. We recommend considering stronger ciphers + * instead. + */ +int mbedtls_des_setkey_dec( mbedtls_des_context *ctx, const unsigned char key[MBEDTLS_DES_KEY_SIZE] ); + +/** + * \brief Triple-DES key schedule (112-bit, encryption) + * + * \param ctx 3DES context to be initialized + * \param key 16-byte secret key + * + * \return 0 + */ +int mbedtls_des3_set2key_enc( mbedtls_des3_context *ctx, + const unsigned char key[MBEDTLS_DES_KEY_SIZE * 2] ); + +/** + * \brief Triple-DES key schedule (112-bit, decryption) + * + * \param ctx 3DES context to be initialized + * \param key 16-byte secret key + * + * \return 0 + */ +int mbedtls_des3_set2key_dec( mbedtls_des3_context *ctx, + const unsigned char key[MBEDTLS_DES_KEY_SIZE * 2] ); + +/** + * \brief Triple-DES key schedule (168-bit, encryption) + * + * \param ctx 3DES context to be initialized + * \param key 24-byte secret key + * + * \return 0 + */ +int mbedtls_des3_set3key_enc( mbedtls_des3_context *ctx, + const unsigned char key[MBEDTLS_DES_KEY_SIZE * 3] ); + +/** + * \brief Triple-DES key schedule (168-bit, decryption) + * + * \param ctx 3DES context to be initialized + * \param key 24-byte secret key + * + * \return 0 + */ +int mbedtls_des3_set3key_dec( mbedtls_des3_context *ctx, + const unsigned char key[MBEDTLS_DES_KEY_SIZE * 3] ); + +/** + * \brief DES-ECB block encryption/decryption + * + * \param ctx DES context + * \param input 64-bit input block + * \param output 64-bit output block + * + * \return 0 if successful + * + * \warning DES is considered a weak cipher and its use constitutes a + * security risk. We recommend considering stronger ciphers + * instead. + */ +int mbedtls_des_crypt_ecb( mbedtls_des_context *ctx, + const unsigned char input[8], + unsigned char output[8] ); + +#if defined(MBEDTLS_CIPHER_MODE_CBC) +/** + * \brief DES-CBC buffer encryption/decryption + * + * \note Upon exit, the content of the IV is updated so that you can + * call the function same function again on the following + * block(s) of data and get the same result as if it was + * encrypted in one call. This allows a "streaming" usage. + * If on the other hand you need to retain the contents of the + * IV, you should either save it manually or use the cipher + * module instead. + * + * \param ctx DES context + * \param mode MBEDTLS_DES_ENCRYPT or MBEDTLS_DES_DECRYPT + * \param length length of the input data + * \param iv initialization vector (updated after use) + * \param input buffer holding the input data + * \param output buffer holding the output data + * + * \warning DES is considered a weak cipher and its use constitutes a + * security risk. We recommend considering stronger ciphers + * instead. + */ +int mbedtls_des_crypt_cbc( mbedtls_des_context *ctx, + int mode, + size_t length, + unsigned char iv[8], + const unsigned char *input, + unsigned char *output ); +#endif /* MBEDTLS_CIPHER_MODE_CBC */ + +/** + * \brief 3DES-ECB block encryption/decryption + * + * \param ctx 3DES context + * \param input 64-bit input block + * \param output 64-bit output block + * + * \return 0 if successful + */ +int mbedtls_des3_crypt_ecb( mbedtls_des3_context *ctx, + const unsigned char input[8], + unsigned char output[8] ); + +#if defined(MBEDTLS_CIPHER_MODE_CBC) +/** + * \brief 3DES-CBC buffer encryption/decryption + * + * \note Upon exit, the content of the IV is updated so that you can + * call the function same function again on the following + * block(s) of data and get the same result as if it was + * encrypted in one call. This allows a "streaming" usage. + * If on the other hand you need to retain the contents of the + * IV, you should either save it manually or use the cipher + * module instead. + * + * \param ctx 3DES context + * \param mode MBEDTLS_DES_ENCRYPT or MBEDTLS_DES_DECRYPT + * \param length length of the input data + * \param iv initialization vector (updated after use) + * \param input buffer holding the input data + * \param output buffer holding the output data + * + * \return 0 if successful, or MBEDTLS_ERR_DES_INVALID_INPUT_LENGTH + */ +int mbedtls_des3_crypt_cbc( mbedtls_des3_context *ctx, + int mode, + size_t length, + unsigned char iv[8], + const unsigned char *input, + unsigned char *output ); +#endif /* MBEDTLS_CIPHER_MODE_CBC */ + +/** + * \brief Internal function for key expansion. + * (Only exposed to allow overriding it, + * see MBEDTLS_DES_SETKEY_ALT) + * + * \param SK Round keys + * \param key Base key + * + * \warning DES is considered a weak cipher and its use constitutes a + * security risk. We recommend considering stronger ciphers + * instead. + */ +void mbedtls_des_setkey( uint32_t SK[32], + const unsigned char key[MBEDTLS_DES_KEY_SIZE] ); + +#if defined(MBEDTLS_SELF_TEST) + +/** + * \brief Checkup routine + * + * \return 0 if successful, or 1 if the test failed + */ +int mbedtls_des_self_test( int verbose ); + +#endif /* MBEDTLS_SELF_TEST */ + +#ifdef __cplusplus +} +#endif + +#endif /* des.h */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/dhm.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/dhm.h new file mode 100644 index 0000000000000000000000000000000000000000..2909f5fbc8e8aeb46a4811deed9c6d93339c211f --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/dhm.h @@ -0,0 +1,1096 @@ +/** + * \file dhm.h + * + * \brief This file contains Diffie-Hellman-Merkle (DHM) key exchange + * definitions and functions. + * + * Diffie-Hellman-Merkle (DHM) key exchange is defined in + * RFC-2631: Diffie-Hellman Key Agreement Method and + * Public-Key Cryptography Standards (PKCS) #3: Diffie + * Hellman Key Agreement Standard. + * + * RFC-3526: More Modular Exponential (MODP) Diffie-Hellman groups for + * Internet Key Exchange (IKE) defines a number of standardized + * Diffie-Hellman groups for IKE. + * + * RFC-5114: Additional Diffie-Hellman Groups for Use with IETF + * Standards defines a number of standardized Diffie-Hellman + * groups that can be used. + * + * \warning The security of the DHM key exchange relies on the proper choice + * of prime modulus - optimally, it should be a safe prime. The usage + * of non-safe primes both decreases the difficulty of the underlying + * discrete logarithm problem and can lead to small subgroup attacks + * leaking private exponent bits when invalid public keys are used + * and not detected. This is especially relevant if the same DHM + * parameters are reused for multiple key exchanges as in static DHM, + * while the criticality of small-subgroup attacks is lower for + * ephemeral DHM. + * + * \warning For performance reasons, the code does neither perform primality + * nor safe primality tests, nor the expensive checks for invalid + * subgroups. Moreover, even if these were performed, non-standardized + * primes cannot be trusted because of the possibility of backdoors + * that can't be effectively checked for. + * + * \warning Diffie-Hellman-Merkle is therefore a security risk when not using + * standardized primes generated using a trustworthy ("nothing up + * my sleeve") method, such as the RFC 3526 / 7919 primes. In the TLS + * protocol, DH parameters need to be negotiated, so using the default + * primes systematically is not always an option. If possible, use + * Elliptic Curve Diffie-Hellman (ECDH), which has better performance, + * and for which the TLS protocol mandates the use of standard + * parameters. + * + */ +/* + * Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of Mbed TLS (https://tls.mbed.org) + */ + +#ifndef MBEDTLS_DHM_H +#define MBEDTLS_DHM_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif +#include "bignum.h" + +/* + * DHM Error codes + */ +#define MBEDTLS_ERR_DHM_BAD_INPUT_DATA -0x3080 /**< Bad input parameters. */ +#define MBEDTLS_ERR_DHM_READ_PARAMS_FAILED -0x3100 /**< Reading of the DHM parameters failed. */ +#define MBEDTLS_ERR_DHM_MAKE_PARAMS_FAILED -0x3180 /**< Making of the DHM parameters failed. */ +#define MBEDTLS_ERR_DHM_READ_PUBLIC_FAILED -0x3200 /**< Reading of the public values failed. */ +#define MBEDTLS_ERR_DHM_MAKE_PUBLIC_FAILED -0x3280 /**< Making of the public value failed. */ +#define MBEDTLS_ERR_DHM_CALC_SECRET_FAILED -0x3300 /**< Calculation of the DHM secret failed. */ +#define MBEDTLS_ERR_DHM_INVALID_FORMAT -0x3380 /**< The ASN.1 data is not formatted correctly. */ +#define MBEDTLS_ERR_DHM_ALLOC_FAILED -0x3400 /**< Allocation of memory failed. */ +#define MBEDTLS_ERR_DHM_FILE_IO_ERROR -0x3480 /**< Read or write of file failed. */ + +/* MBEDTLS_ERR_DHM_HW_ACCEL_FAILED is deprecated and should not be used. */ +#define MBEDTLS_ERR_DHM_HW_ACCEL_FAILED -0x3500 /**< DHM hardware accelerator failed. */ + +#define MBEDTLS_ERR_DHM_SET_GROUP_FAILED -0x3580 /**< Setting the modulus and generator failed. */ + +#ifdef __cplusplus +extern "C" { +#endif + +#if !defined(MBEDTLS_DHM_ALT) + +/** + * \brief The DHM context structure. + */ +typedef struct mbedtls_dhm_context +{ + size_t len; /*!< The size of \p P in Bytes. */ + mbedtls_mpi P; /*!< The prime modulus. */ + mbedtls_mpi G; /*!< The generator. */ + mbedtls_mpi X; /*!< Our secret value. */ + mbedtls_mpi GX; /*!< Our public key = \c G^X mod \c P. */ + mbedtls_mpi GY; /*!< The public key of the peer = \c G^Y mod \c P. */ + mbedtls_mpi K; /*!< The shared secret = \c G^(XY) mod \c P. */ + mbedtls_mpi RP; /*!< The cached value = \c R^2 mod \c P. */ + mbedtls_mpi Vi; /*!< The blinding value. */ + mbedtls_mpi Vf; /*!< The unblinding value. */ + mbedtls_mpi pX; /*!< The previous \c X. */ +} +mbedtls_dhm_context; + +#else /* MBEDTLS_DHM_ALT */ +#include "dhm_alt.h" +#endif /* MBEDTLS_DHM_ALT */ + +/** + * \brief This function initializes the DHM context. + * + * \param ctx The DHM context to initialize. + */ +void mbedtls_dhm_init( mbedtls_dhm_context *ctx ); + +/** + * \brief This function parses the DHM parameters in a + * TLS ServerKeyExchange handshake message + * (DHM modulus, generator, and public key). + * + * \note In a TLS handshake, this is the how the client + * sets up its DHM context from the server's public + * DHM key material. + * + * \param ctx The DHM context to use. This must be initialized. + * \param p On input, *p must be the start of the input buffer. + * On output, *p is updated to point to the end of the data + * that has been read. On success, this is the first byte + * past the end of the ServerKeyExchange parameters. + * On error, this is the point at which an error has been + * detected, which is usually not useful except to debug + * failures. + * \param end The end of the input buffer. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_DHM_XXX error code on failure. + */ +int mbedtls_dhm_read_params( mbedtls_dhm_context *ctx, + unsigned char **p, + const unsigned char *end ); + +/** + * \brief This function generates a DHM key pair and exports its + * public part together with the DHM parameters in the format + * used in a TLS ServerKeyExchange handshake message. + * + * \note This function assumes that the DHM parameters \c ctx->P + * and \c ctx->G have already been properly set. For that, use + * mbedtls_dhm_set_group() below in conjunction with + * mbedtls_mpi_read_binary() and mbedtls_mpi_read_string(). + * + * \note In a TLS handshake, this is the how the server generates + * and exports its DHM key material. + * + * \param ctx The DHM context to use. This must be initialized + * and have the DHM parameters set. It may or may not + * already have imported the peer's public key. + * \param x_size The private key size in Bytes. + * \param olen The address at which to store the number of Bytes + * written on success. This must not be \c NULL. + * \param output The destination buffer. This must be a writable buffer of + * sufficient size to hold the reduced binary presentation of + * the modulus, the generator and the public key, each wrapped + * with a 2-byte length field. It is the responsibility of the + * caller to ensure that enough space is available. Refer to + * mbedtls_mpi_size() to computing the byte-size of an MPI. + * \param f_rng The RNG function. Must not be \c NULL. + * \param p_rng The RNG context to be passed to \p f_rng. This may be + * \c NULL if \p f_rng doesn't need a context parameter. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_DHM_XXX error code on failure. + */ +int mbedtls_dhm_make_params( mbedtls_dhm_context *ctx, int x_size, + unsigned char *output, size_t *olen, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng ); + +/** + * \brief This function sets the prime modulus and generator. + * + * \note This function can be used to set \c ctx->P, \c ctx->G + * in preparation for mbedtls_dhm_make_params(). + * + * \param ctx The DHM context to configure. This must be initialized. + * \param P The MPI holding the DHM prime modulus. This must be + * an initialized MPI. + * \param G The MPI holding the DHM generator. This must be an + * initialized MPI. + * + * \return \c 0 if successful. + * \return An \c MBEDTLS_ERR_DHM_XXX error code on failure. + */ +int mbedtls_dhm_set_group( mbedtls_dhm_context *ctx, + const mbedtls_mpi *P, + const mbedtls_mpi *G ); + +/** + * \brief This function imports the raw public value of the peer. + * + * \note In a TLS handshake, this is the how the server imports + * the Client's public DHM key. + * + * \param ctx The DHM context to use. This must be initialized and have + * its DHM parameters set, e.g. via mbedtls_dhm_set_group(). + * It may or may not already have generated its own private key. + * \param input The input buffer containing the \c G^Y value of the peer. + * This must be a readable buffer of size \p ilen Bytes. + * \param ilen The size of the input buffer \p input in Bytes. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_DHM_XXX error code on failure. + */ +int mbedtls_dhm_read_public( mbedtls_dhm_context *ctx, + const unsigned char *input, size_t ilen ); + +/** + * \brief This function creates a DHM key pair and exports + * the raw public key in big-endian format. + * + * \note The destination buffer is always fully written + * so as to contain a big-endian representation of G^X mod P. + * If it is larger than \c ctx->len, it is padded accordingly + * with zero-bytes at the beginning. + * + * \param ctx The DHM context to use. This must be initialized and + * have the DHM parameters set. It may or may not already + * have imported the peer's public key. + * \param x_size The private key size in Bytes. + * \param output The destination buffer. This must be a writable buffer of + * size \p olen Bytes. + * \param olen The length of the destination buffer. This must be at least + * equal to `ctx->len` (the size of \c P). + * \param f_rng The RNG function. This must not be \c NULL. + * \param p_rng The RNG context to be passed to \p f_rng. This may be \c NULL + * if \p f_rng doesn't need a context argument. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_DHM_XXX error code on failure. + */ +int mbedtls_dhm_make_public( mbedtls_dhm_context *ctx, int x_size, + unsigned char *output, size_t olen, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng ); + +/** + * \brief This function derives and exports the shared secret + * \c (G^Y)^X mod \c P. + * + * \note If \p f_rng is not \c NULL, it is used to blind the input as + * a countermeasure against timing attacks. Blinding is used + * only if our private key \c X is re-used, and not used + * otherwise. We recommend always passing a non-NULL + * \p f_rng argument. + * + * \param ctx The DHM context to use. This must be initialized + * and have its own private key generated and the peer's + * public key imported. + * \param output The buffer to write the generated shared key to. This + * must be a writable buffer of size \p output_size Bytes. + * \param output_size The size of the destination buffer. This must be at + * least the size of \c ctx->len (the size of \c P). + * \param olen On exit, holds the actual number of Bytes written. + * \param f_rng The RNG function, for blinding purposes. This may + * b \c NULL if blinding isn't needed. + * \param p_rng The RNG context. This may be \c NULL if \p f_rng + * doesn't need a context argument. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_DHM_XXX error code on failure. + */ +int mbedtls_dhm_calc_secret( mbedtls_dhm_context *ctx, + unsigned char *output, size_t output_size, size_t *olen, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng ); + +/** + * \brief This function frees and clears the components + * of a DHM context. + * + * \param ctx The DHM context to free and clear. This may be \c NULL, + * in which case this function is a no-op. If it is not \c NULL, + * it must point to an initialized DHM context. + */ +void mbedtls_dhm_free( mbedtls_dhm_context *ctx ); + +#if defined(MBEDTLS_ASN1_PARSE_C) +/** \ingroup x509_module */ +/** + * \brief This function parses DHM parameters in PEM or DER format. + * + * \param dhm The DHM context to import the DHM parameters into. + * This must be initialized. + * \param dhmin The input buffer. This must be a readable buffer of + * length \p dhminlen Bytes. + * \param dhminlen The size of the input buffer \p dhmin, including the + * terminating \c NULL Byte for PEM data. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_DHM_XXX or \c MBEDTLS_ERR_PEM_XXX error + * code on failure. + */ +int mbedtls_dhm_parse_dhm( mbedtls_dhm_context *dhm, const unsigned char *dhmin, + size_t dhminlen ); + +#if defined(MBEDTLS_FS_IO) +/** \ingroup x509_module */ +/** + * \brief This function loads and parses DHM parameters from a file. + * + * \param dhm The DHM context to load the parameters to. + * This must be initialized. + * \param path The filename to read the DHM parameters from. + * This must not be \c NULL. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_DHM_XXX or \c MBEDTLS_ERR_PEM_XXX + * error code on failure. + */ +int mbedtls_dhm_parse_dhmfile( mbedtls_dhm_context *dhm, const char *path ); +#endif /* MBEDTLS_FS_IO */ +#endif /* MBEDTLS_ASN1_PARSE_C */ + +#if defined(MBEDTLS_SELF_TEST) + +/** + * \brief The DMH checkup routine. + * + * \return \c 0 on success. + * \return \c 1 on failure. + */ +int mbedtls_dhm_self_test( int verbose ); + +#endif /* MBEDTLS_SELF_TEST */ +#ifdef __cplusplus +} +#endif + +/** + * RFC 3526, RFC 5114 and RFC 7919 standardize a number of + * Diffie-Hellman groups, some of which are included here + * for use within the SSL/TLS module and the user's convenience + * when configuring the Diffie-Hellman parameters by hand + * through \c mbedtls_ssl_conf_dh_param. + * + * The following lists the source of the above groups in the standards: + * - RFC 5114 section 2.2: 2048-bit MODP Group with 224-bit Prime Order Subgroup + * - RFC 3526 section 3: 2048-bit MODP Group + * - RFC 3526 section 4: 3072-bit MODP Group + * - RFC 3526 section 5: 4096-bit MODP Group + * - RFC 7919 section A.1: ffdhe2048 + * - RFC 7919 section A.2: ffdhe3072 + * - RFC 7919 section A.3: ffdhe4096 + * - RFC 7919 section A.4: ffdhe6144 + * - RFC 7919 section A.5: ffdhe8192 + * + * The constants with suffix "_p" denote the chosen prime moduli, while + * the constants with suffix "_g" denote the chosen generator + * of the associated prime field. + * + * The constants further suffixed with "_bin" are provided in binary format, + * while all other constants represent null-terminated strings holding the + * hexadecimal presentation of the respective numbers. + * + * The primes from RFC 3526 and RFC 7919 have been generating by the following + * trust-worthy procedure: + * - Fix N in { 2048, 3072, 4096, 6144, 8192 } and consider the N-bit number + * the first and last 64 bits are all 1, and the remaining N - 128 bits of + * which are 0x7ff...ff. + * - Add the smallest multiple of the first N - 129 bits of the binary expansion + * of pi (for RFC 5236) or e (for RFC 7919) to this intermediate bit-string + * such that the resulting integer is a safe-prime. + * - The result is the respective RFC 3526 / 7919 prime, and the corresponding + * generator is always chosen to be 2 (which is a square for these prime, + * hence the corresponding subgroup has order (p-1)/2 and avoids leaking a + * bit in the private exponent). + * + */ + +#if !defined(MBEDTLS_DEPRECATED_REMOVED) + +/** + * \warning The origin of the primes in RFC 5114 is not documented and + * their use therefore constitutes a security risk! + * + * \deprecated The hex-encoded primes from RFC 5114 are deprecated and are + * likely to be removed in a future version of the library without + * replacement. + */ + +/** + * The hexadecimal presentation of the prime underlying the + * 2048-bit MODP Group with 224-bit Prime Order Subgroup, as defined + * in RFC-5114: Additional Diffie-Hellman Groups for Use with + * IETF Standards. + */ +#define MBEDTLS_DHM_RFC5114_MODP_2048_P \ + MBEDTLS_DEPRECATED_STRING_CONSTANT( \ + "AD107E1E9123A9D0D660FAA79559C51FA20D64E5683B9FD1" \ + "B54B1597B61D0A75E6FA141DF95A56DBAF9A3C407BA1DF15" \ + "EB3D688A309C180E1DE6B85A1274A0A66D3F8152AD6AC212" \ + "9037C9EDEFDA4DF8D91E8FEF55B7394B7AD5B7D0B6C12207" \ + "C9F98D11ED34DBF6C6BA0B2C8BBC27BE6A00E0A0B9C49708" \ + "B3BF8A317091883681286130BC8985DB1602E714415D9330" \ + "278273C7DE31EFDC7310F7121FD5A07415987D9ADC0A486D" \ + "CDF93ACC44328387315D75E198C641A480CD86A1B9E587E8" \ + "BE60E69CC928B2B9C52172E413042E9B23F10B0E16E79763" \ + "C9B53DCF4BA80A29E3FB73C16B8E75B97EF363E2FFA31F71" \ + "CF9DE5384E71B81C0AC4DFFE0C10E64F" ) + +/** + * The hexadecimal presentation of the chosen generator of the 2048-bit MODP + * Group with 224-bit Prime Order Subgroup, as defined in RFC-5114: + * Additional Diffie-Hellman Groups for Use with IETF Standards. + */ +#define MBEDTLS_DHM_RFC5114_MODP_2048_G \ + MBEDTLS_DEPRECATED_STRING_CONSTANT( \ + "AC4032EF4F2D9AE39DF30B5C8FFDAC506CDEBE7B89998CAF" \ + "74866A08CFE4FFE3A6824A4E10B9A6F0DD921F01A70C4AFA" \ + "AB739D7700C29F52C57DB17C620A8652BE5E9001A8D66AD7" \ + "C17669101999024AF4D027275AC1348BB8A762D0521BC98A" \ + "E247150422EA1ED409939D54DA7460CDB5F6C6B250717CBE" \ + "F180EB34118E98D119529A45D6F834566E3025E316A330EF" \ + "BB77A86F0C1AB15B051AE3D428C8F8ACB70A8137150B8EEB" \ + "10E183EDD19963DDD9E263E4770589EF6AA21E7F5F2FF381" \ + "B539CCE3409D13CD566AFBB48D6C019181E1BCFE94B30269" \ + "EDFE72FE9B6AA4BD7B5A0F1C71CFFF4C19C418E1F6EC0179" \ + "81BC087F2A7065B384B890D3191F2BFA" ) + +/** + * The hexadecimal presentation of the prime underlying the 2048-bit MODP + * Group, as defined in RFC-3526: More Modular Exponential (MODP) + * Diffie-Hellman groups for Internet Key Exchange (IKE). + * + * \deprecated The hex-encoded primes from RFC 3625 are deprecated and + * superseded by the corresponding macros providing them as + * binary constants. Their hex-encoded constants are likely + * to be removed in a future version of the library. + * + */ +#define MBEDTLS_DHM_RFC3526_MODP_2048_P \ + MBEDTLS_DEPRECATED_STRING_CONSTANT( \ + "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" \ + "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" \ + "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" \ + "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" \ + "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" \ + "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" \ + "83655D23DCA3AD961C62F356208552BB9ED529077096966D" \ + "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" \ + "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" \ + "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" \ + "15728E5A8AACAA68FFFFFFFFFFFFFFFF" ) + +/** + * The hexadecimal presentation of the chosen generator of the 2048-bit MODP + * Group, as defined in RFC-3526: More Modular Exponential (MODP) + * Diffie-Hellman groups for Internet Key Exchange (IKE). + */ +#define MBEDTLS_DHM_RFC3526_MODP_2048_G \ + MBEDTLS_DEPRECATED_STRING_CONSTANT( "02" ) + +/** + * The hexadecimal presentation of the prime underlying the 3072-bit MODP + * Group, as defined in RFC-3072: More Modular Exponential (MODP) + * Diffie-Hellman groups for Internet Key Exchange (IKE). + */ +#define MBEDTLS_DHM_RFC3526_MODP_3072_P \ + MBEDTLS_DEPRECATED_STRING_CONSTANT( \ + "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" \ + "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" \ + "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" \ + "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" \ + "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" \ + "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" \ + "83655D23DCA3AD961C62F356208552BB9ED529077096966D" \ + "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" \ + "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" \ + "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" \ + "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64" \ + "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7" \ + "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B" \ + "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C" \ + "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31" \ + "43DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF" ) + +/** + * The hexadecimal presentation of the chosen generator of the 3072-bit MODP + * Group, as defined in RFC-3526: More Modular Exponential (MODP) + * Diffie-Hellman groups for Internet Key Exchange (IKE). + */ +#define MBEDTLS_DHM_RFC3526_MODP_3072_G \ + MBEDTLS_DEPRECATED_STRING_CONSTANT( "02" ) + +/** + * The hexadecimal presentation of the prime underlying the 4096-bit MODP + * Group, as defined in RFC-3526: More Modular Exponential (MODP) + * Diffie-Hellman groups for Internet Key Exchange (IKE). + */ +#define MBEDTLS_DHM_RFC3526_MODP_4096_P \ + MBEDTLS_DEPRECATED_STRING_CONSTANT( \ + "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" \ + "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" \ + "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" \ + "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" \ + "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" \ + "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" \ + "83655D23DCA3AD961C62F356208552BB9ED529077096966D" \ + "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" \ + "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" \ + "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" \ + "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64" \ + "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7" \ + "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B" \ + "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C" \ + "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31" \ + "43DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D7" \ + "88719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA" \ + "2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6" \ + "287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED" \ + "1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA9" \ + "93B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934063199" \ + "FFFFFFFFFFFFFFFF" ) + +/** + * The hexadecimal presentation of the chosen generator of the 4096-bit MODP + * Group, as defined in RFC-3526: More Modular Exponential (MODP) + * Diffie-Hellman groups for Internet Key Exchange (IKE). + */ +#define MBEDTLS_DHM_RFC3526_MODP_4096_G \ + MBEDTLS_DEPRECATED_STRING_CONSTANT( "02" ) + +#endif /* MBEDTLS_DEPRECATED_REMOVED */ + +/* + * Trustworthy DHM parameters in binary form + */ + +#define MBEDTLS_DHM_RFC3526_MODP_2048_P_BIN { \ + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \ + 0xC9, 0x0F, 0xDA, 0xA2, 0x21, 0x68, 0xC2, 0x34, \ + 0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1, \ + 0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74, \ + 0x02, 0x0B, 0xBE, 0xA6, 0x3B, 0x13, 0x9B, 0x22, \ + 0x51, 0x4A, 0x08, 0x79, 0x8E, 0x34, 0x04, 0xDD, \ + 0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B, \ + 0x30, 0x2B, 0x0A, 0x6D, 0xF2, 0x5F, 0x14, 0x37, \ + 0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45, \ + 0xE4, 0x85, 0xB5, 0x76, 0x62, 0x5E, 0x7E, 0xC6, \ + 0xF4, 0x4C, 0x42, 0xE9, 0xA6, 0x37, 0xED, 0x6B, \ + 0x0B, 0xFF, 0x5C, 0xB6, 0xF4, 0x06, 0xB7, 0xED, \ + 0xEE, 0x38, 0x6B, 0xFB, 0x5A, 0x89, 0x9F, 0xA5, \ + 0xAE, 0x9F, 0x24, 0x11, 0x7C, 0x4B, 0x1F, 0xE6, \ + 0x49, 0x28, 0x66, 0x51, 0xEC, 0xE4, 0x5B, 0x3D, \ + 0xC2, 0x00, 0x7C, 0xB8, 0xA1, 0x63, 0xBF, 0x05, \ + 0x98, 0xDA, 0x48, 0x36, 0x1C, 0x55, 0xD3, 0x9A, \ + 0x69, 0x16, 0x3F, 0xA8, 0xFD, 0x24, 0xCF, 0x5F, \ + 0x83, 0x65, 0x5D, 0x23, 0xDC, 0xA3, 0xAD, 0x96, \ + 0x1C, 0x62, 0xF3, 0x56, 0x20, 0x85, 0x52, 0xBB, \ + 0x9E, 0xD5, 0x29, 0x07, 0x70, 0x96, 0x96, 0x6D, \ + 0x67, 0x0C, 0x35, 0x4E, 0x4A, 0xBC, 0x98, 0x04, \ + 0xF1, 0x74, 0x6C, 0x08, 0xCA, 0x18, 0x21, 0x7C, \ + 0x32, 0x90, 0x5E, 0x46, 0x2E, 0x36, 0xCE, 0x3B, \ + 0xE3, 0x9E, 0x77, 0x2C, 0x18, 0x0E, 0x86, 0x03, \ + 0x9B, 0x27, 0x83, 0xA2, 0xEC, 0x07, 0xA2, 0x8F, \ + 0xB5, 0xC5, 0x5D, 0xF0, 0x6F, 0x4C, 0x52, 0xC9, \ + 0xDE, 0x2B, 0xCB, 0xF6, 0x95, 0x58, 0x17, 0x18, \ + 0x39, 0x95, 0x49, 0x7C, 0xEA, 0x95, 0x6A, 0xE5, \ + 0x15, 0xD2, 0x26, 0x18, 0x98, 0xFA, 0x05, 0x10, \ + 0x15, 0x72, 0x8E, 0x5A, 0x8A, 0xAC, 0xAA, 0x68, \ + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF } + +#define MBEDTLS_DHM_RFC3526_MODP_2048_G_BIN { 0x02 } + +#define MBEDTLS_DHM_RFC3526_MODP_3072_P_BIN { \ + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \ + 0xC9, 0x0F, 0xDA, 0xA2, 0x21, 0x68, 0xC2, 0x34, \ + 0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1, \ + 0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74, \ + 0x02, 0x0B, 0xBE, 0xA6, 0x3B, 0x13, 0x9B, 0x22, \ + 0x51, 0x4A, 0x08, 0x79, 0x8E, 0x34, 0x04, 0xDD, \ + 0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B, \ + 0x30, 0x2B, 0x0A, 0x6D, 0xF2, 0x5F, 0x14, 0x37, \ + 0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45, \ + 0xE4, 0x85, 0xB5, 0x76, 0x62, 0x5E, 0x7E, 0xC6, \ + 0xF4, 0x4C, 0x42, 0xE9, 0xA6, 0x37, 0xED, 0x6B, \ + 0x0B, 0xFF, 0x5C, 0xB6, 0xF4, 0x06, 0xB7, 0xED, \ + 0xEE, 0x38, 0x6B, 0xFB, 0x5A, 0x89, 0x9F, 0xA5, \ + 0xAE, 0x9F, 0x24, 0x11, 0x7C, 0x4B, 0x1F, 0xE6, \ + 0x49, 0x28, 0x66, 0x51, 0xEC, 0xE4, 0x5B, 0x3D, \ + 0xC2, 0x00, 0x7C, 0xB8, 0xA1, 0x63, 0xBF, 0x05, \ + 0x98, 0xDA, 0x48, 0x36, 0x1C, 0x55, 0xD3, 0x9A, \ + 0x69, 0x16, 0x3F, 0xA8, 0xFD, 0x24, 0xCF, 0x5F, \ + 0x83, 0x65, 0x5D, 0x23, 0xDC, 0xA3, 0xAD, 0x96, \ + 0x1C, 0x62, 0xF3, 0x56, 0x20, 0x85, 0x52, 0xBB, \ + 0x9E, 0xD5, 0x29, 0x07, 0x70, 0x96, 0x96, 0x6D, \ + 0x67, 0x0C, 0x35, 0x4E, 0x4A, 0xBC, 0x98, 0x04, \ + 0xF1, 0x74, 0x6C, 0x08, 0xCA, 0x18, 0x21, 0x7C, \ + 0x32, 0x90, 0x5E, 0x46, 0x2E, 0x36, 0xCE, 0x3B, \ + 0xE3, 0x9E, 0x77, 0x2C, 0x18, 0x0E, 0x86, 0x03, \ + 0x9B, 0x27, 0x83, 0xA2, 0xEC, 0x07, 0xA2, 0x8F, \ + 0xB5, 0xC5, 0x5D, 0xF0, 0x6F, 0x4C, 0x52, 0xC9, \ + 0xDE, 0x2B, 0xCB, 0xF6, 0x95, 0x58, 0x17, 0x18, \ + 0x39, 0x95, 0x49, 0x7C, 0xEA, 0x95, 0x6A, 0xE5, \ + 0x15, 0xD2, 0x26, 0x18, 0x98, 0xFA, 0x05, 0x10, \ + 0x15, 0x72, 0x8E, 0x5A, 0x8A, 0xAA, 0xC4, 0x2D, \ + 0xAD, 0x33, 0x17, 0x0D, 0x04, 0x50, 0x7A, 0x33, \ + 0xA8, 0x55, 0x21, 0xAB, 0xDF, 0x1C, 0xBA, 0x64, \ + 0xEC, 0xFB, 0x85, 0x04, 0x58, 0xDB, 0xEF, 0x0A, \ + 0x8A, 0xEA, 0x71, 0x57, 0x5D, 0x06, 0x0C, 0x7D, \ + 0xB3, 0x97, 0x0F, 0x85, 0xA6, 0xE1, 0xE4, 0xC7, \ + 0xAB, 0xF5, 0xAE, 0x8C, 0xDB, 0x09, 0x33, 0xD7, \ + 0x1E, 0x8C, 0x94, 0xE0, 0x4A, 0x25, 0x61, 0x9D, \ + 0xCE, 0xE3, 0xD2, 0x26, 0x1A, 0xD2, 0xEE, 0x6B, \ + 0xF1, 0x2F, 0xFA, 0x06, 0xD9, 0x8A, 0x08, 0x64, \ + 0xD8, 0x76, 0x02, 0x73, 0x3E, 0xC8, 0x6A, 0x64, \ + 0x52, 0x1F, 0x2B, 0x18, 0x17, 0x7B, 0x20, 0x0C, \ + 0xBB, 0xE1, 0x17, 0x57, 0x7A, 0x61, 0x5D, 0x6C, \ + 0x77, 0x09, 0x88, 0xC0, 0xBA, 0xD9, 0x46, 0xE2, \ + 0x08, 0xE2, 0x4F, 0xA0, 0x74, 0xE5, 0xAB, 0x31, \ + 0x43, 0xDB, 0x5B, 0xFC, 0xE0, 0xFD, 0x10, 0x8E, \ + 0x4B, 0x82, 0xD1, 0x20, 0xA9, 0x3A, 0xD2, 0xCA, \ + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF } + +#define MBEDTLS_DHM_RFC3526_MODP_3072_G_BIN { 0x02 } + +#define MBEDTLS_DHM_RFC3526_MODP_4096_P_BIN { \ + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \ + 0xC9, 0x0F, 0xDA, 0xA2, 0x21, 0x68, 0xC2, 0x34, \ + 0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1, \ + 0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74, \ + 0x02, 0x0B, 0xBE, 0xA6, 0x3B, 0x13, 0x9B, 0x22, \ + 0x51, 0x4A, 0x08, 0x79, 0x8E, 0x34, 0x04, 0xDD, \ + 0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B, \ + 0x30, 0x2B, 0x0A, 0x6D, 0xF2, 0x5F, 0x14, 0x37, \ + 0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45, \ + 0xE4, 0x85, 0xB5, 0x76, 0x62, 0x5E, 0x7E, 0xC6, \ + 0xF4, 0x4C, 0x42, 0xE9, 0xA6, 0x37, 0xED, 0x6B, \ + 0x0B, 0xFF, 0x5C, 0xB6, 0xF4, 0x06, 0xB7, 0xED, \ + 0xEE, 0x38, 0x6B, 0xFB, 0x5A, 0x89, 0x9F, 0xA5, \ + 0xAE, 0x9F, 0x24, 0x11, 0x7C, 0x4B, 0x1F, 0xE6, \ + 0x49, 0x28, 0x66, 0x51, 0xEC, 0xE4, 0x5B, 0x3D, \ + 0xC2, 0x00, 0x7C, 0xB8, 0xA1, 0x63, 0xBF, 0x05, \ + 0x98, 0xDA, 0x48, 0x36, 0x1C, 0x55, 0xD3, 0x9A, \ + 0x69, 0x16, 0x3F, 0xA8, 0xFD, 0x24, 0xCF, 0x5F, \ + 0x83, 0x65, 0x5D, 0x23, 0xDC, 0xA3, 0xAD, 0x96, \ + 0x1C, 0x62, 0xF3, 0x56, 0x20, 0x85, 0x52, 0xBB, \ + 0x9E, 0xD5, 0x29, 0x07, 0x70, 0x96, 0x96, 0x6D, \ + 0x67, 0x0C, 0x35, 0x4E, 0x4A, 0xBC, 0x98, 0x04, \ + 0xF1, 0x74, 0x6C, 0x08, 0xCA, 0x18, 0x21, 0x7C, \ + 0x32, 0x90, 0x5E, 0x46, 0x2E, 0x36, 0xCE, 0x3B, \ + 0xE3, 0x9E, 0x77, 0x2C, 0x18, 0x0E, 0x86, 0x03, \ + 0x9B, 0x27, 0x83, 0xA2, 0xEC, 0x07, 0xA2, 0x8F, \ + 0xB5, 0xC5, 0x5D, 0xF0, 0x6F, 0x4C, 0x52, 0xC9, \ + 0xDE, 0x2B, 0xCB, 0xF6, 0x95, 0x58, 0x17, 0x18, \ + 0x39, 0x95, 0x49, 0x7C, 0xEA, 0x95, 0x6A, 0xE5, \ + 0x15, 0xD2, 0x26, 0x18, 0x98, 0xFA, 0x05, 0x10, \ + 0x15, 0x72, 0x8E, 0x5A, 0x8A, 0xAA, 0xC4, 0x2D, \ + 0xAD, 0x33, 0x17, 0x0D, 0x04, 0x50, 0x7A, 0x33, \ + 0xA8, 0x55, 0x21, 0xAB, 0xDF, 0x1C, 0xBA, 0x64, \ + 0xEC, 0xFB, 0x85, 0x04, 0x58, 0xDB, 0xEF, 0x0A, \ + 0x8A, 0xEA, 0x71, 0x57, 0x5D, 0x06, 0x0C, 0x7D, \ + 0xB3, 0x97, 0x0F, 0x85, 0xA6, 0xE1, 0xE4, 0xC7, \ + 0xAB, 0xF5, 0xAE, 0x8C, 0xDB, 0x09, 0x33, 0xD7, \ + 0x1E, 0x8C, 0x94, 0xE0, 0x4A, 0x25, 0x61, 0x9D, \ + 0xCE, 0xE3, 0xD2, 0x26, 0x1A, 0xD2, 0xEE, 0x6B, \ + 0xF1, 0x2F, 0xFA, 0x06, 0xD9, 0x8A, 0x08, 0x64, \ + 0xD8, 0x76, 0x02, 0x73, 0x3E, 0xC8, 0x6A, 0x64, \ + 0x52, 0x1F, 0x2B, 0x18, 0x17, 0x7B, 0x20, 0x0C, \ + 0xBB, 0xE1, 0x17, 0x57, 0x7A, 0x61, 0x5D, 0x6C, \ + 0x77, 0x09, 0x88, 0xC0, 0xBA, 0xD9, 0x46, 0xE2, \ + 0x08, 0xE2, 0x4F, 0xA0, 0x74, 0xE5, 0xAB, 0x31, \ + 0x43, 0xDB, 0x5B, 0xFC, 0xE0, 0xFD, 0x10, 0x8E, \ + 0x4B, 0x82, 0xD1, 0x20, 0xA9, 0x21, 0x08, 0x01, \ + 0x1A, 0x72, 0x3C, 0x12, 0xA7, 0x87, 0xE6, 0xD7, \ + 0x88, 0x71, 0x9A, 0x10, 0xBD, 0xBA, 0x5B, 0x26, \ + 0x99, 0xC3, 0x27, 0x18, 0x6A, 0xF4, 0xE2, 0x3C, \ + 0x1A, 0x94, 0x68, 0x34, 0xB6, 0x15, 0x0B, 0xDA, \ + 0x25, 0x83, 0xE9, 0xCA, 0x2A, 0xD4, 0x4C, 0xE8, \ + 0xDB, 0xBB, 0xC2, 0xDB, 0x04, 0xDE, 0x8E, 0xF9, \ + 0x2E, 0x8E, 0xFC, 0x14, 0x1F, 0xBE, 0xCA, 0xA6, \ + 0x28, 0x7C, 0x59, 0x47, 0x4E, 0x6B, 0xC0, 0x5D, \ + 0x99, 0xB2, 0x96, 0x4F, 0xA0, 0x90, 0xC3, 0xA2, \ + 0x23, 0x3B, 0xA1, 0x86, 0x51, 0x5B, 0xE7, 0xED, \ + 0x1F, 0x61, 0x29, 0x70, 0xCE, 0xE2, 0xD7, 0xAF, \ + 0xB8, 0x1B, 0xDD, 0x76, 0x21, 0x70, 0x48, 0x1C, \ + 0xD0, 0x06, 0x91, 0x27, 0xD5, 0xB0, 0x5A, 0xA9, \ + 0x93, 0xB4, 0xEA, 0x98, 0x8D, 0x8F, 0xDD, 0xC1, \ + 0x86, 0xFF, 0xB7, 0xDC, 0x90, 0xA6, 0xC0, 0x8F, \ + 0x4D, 0xF4, 0x35, 0xC9, 0x34, 0x06, 0x31, 0x99, \ + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF } + +#define MBEDTLS_DHM_RFC3526_MODP_4096_G_BIN { 0x02 } + +#define MBEDTLS_DHM_RFC7919_FFDHE2048_P_BIN { \ + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \ + 0xAD, 0xF8, 0x54, 0x58, 0xA2, 0xBB, 0x4A, 0x9A, \ + 0xAF, 0xDC, 0x56, 0x20, 0x27, 0x3D, 0x3C, 0xF1, \ + 0xD8, 0xB9, 0xC5, 0x83, 0xCE, 0x2D, 0x36, 0x95, \ + 0xA9, 0xE1, 0x36, 0x41, 0x14, 0x64, 0x33, 0xFB, \ + 0xCC, 0x93, 0x9D, 0xCE, 0x24, 0x9B, 0x3E, 0xF9, \ + 0x7D, 0x2F, 0xE3, 0x63, 0x63, 0x0C, 0x75, 0xD8, \ + 0xF6, 0x81, 0xB2, 0x02, 0xAE, 0xC4, 0x61, 0x7A, \ + 0xD3, 0xDF, 0x1E, 0xD5, 0xD5, 0xFD, 0x65, 0x61, \ + 0x24, 0x33, 0xF5, 0x1F, 0x5F, 0x06, 0x6E, 0xD0, \ + 0x85, 0x63, 0x65, 0x55, 0x3D, 0xED, 0x1A, 0xF3, \ + 0xB5, 0x57, 0x13, 0x5E, 0x7F, 0x57, 0xC9, 0x35, \ + 0x98, 0x4F, 0x0C, 0x70, 0xE0, 0xE6, 0x8B, 0x77, \ + 0xE2, 0xA6, 0x89, 0xDA, 0xF3, 0xEF, 0xE8, 0x72, \ + 0x1D, 0xF1, 0x58, 0xA1, 0x36, 0xAD, 0xE7, 0x35, \ + 0x30, 0xAC, 0xCA, 0x4F, 0x48, 0x3A, 0x79, 0x7A, \ + 0xBC, 0x0A, 0xB1, 0x82, 0xB3, 0x24, 0xFB, 0x61, \ + 0xD1, 0x08, 0xA9, 0x4B, 0xB2, 0xC8, 0xE3, 0xFB, \ + 0xB9, 0x6A, 0xDA, 0xB7, 0x60, 0xD7, 0xF4, 0x68, \ + 0x1D, 0x4F, 0x42, 0xA3, 0xDE, 0x39, 0x4D, 0xF4, \ + 0xAE, 0x56, 0xED, 0xE7, 0x63, 0x72, 0xBB, 0x19, \ + 0x0B, 0x07, 0xA7, 0xC8, 0xEE, 0x0A, 0x6D, 0x70, \ + 0x9E, 0x02, 0xFC, 0xE1, 0xCD, 0xF7, 0xE2, 0xEC, \ + 0xC0, 0x34, 0x04, 0xCD, 0x28, 0x34, 0x2F, 0x61, \ + 0x91, 0x72, 0xFE, 0x9C, 0xE9, 0x85, 0x83, 0xFF, \ + 0x8E, 0x4F, 0x12, 0x32, 0xEE, 0xF2, 0x81, 0x83, \ + 0xC3, 0xFE, 0x3B, 0x1B, 0x4C, 0x6F, 0xAD, 0x73, \ + 0x3B, 0xB5, 0xFC, 0xBC, 0x2E, 0xC2, 0x20, 0x05, \ + 0xC5, 0x8E, 0xF1, 0x83, 0x7D, 0x16, 0x83, 0xB2, \ + 0xC6, 0xF3, 0x4A, 0x26, 0xC1, 0xB2, 0xEF, 0xFA, \ + 0x88, 0x6B, 0x42, 0x38, 0x61, 0x28, 0x5C, 0x97, \ + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, } + +#define MBEDTLS_DHM_RFC7919_FFDHE2048_G_BIN { 0x02 } + +#define MBEDTLS_DHM_RFC7919_FFDHE3072_P_BIN { \ + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \ + 0xAD, 0xF8, 0x54, 0x58, 0xA2, 0xBB, 0x4A, 0x9A, \ + 0xAF, 0xDC, 0x56, 0x20, 0x27, 0x3D, 0x3C, 0xF1, \ + 0xD8, 0xB9, 0xC5, 0x83, 0xCE, 0x2D, 0x36, 0x95, \ + 0xA9, 0xE1, 0x36, 0x41, 0x14, 0x64, 0x33, 0xFB, \ + 0xCC, 0x93, 0x9D, 0xCE, 0x24, 0x9B, 0x3E, 0xF9, \ + 0x7D, 0x2F, 0xE3, 0x63, 0x63, 0x0C, 0x75, 0xD8, \ + 0xF6, 0x81, 0xB2, 0x02, 0xAE, 0xC4, 0x61, 0x7A, \ + 0xD3, 0xDF, 0x1E, 0xD5, 0xD5, 0xFD, 0x65, 0x61, \ + 0x24, 0x33, 0xF5, 0x1F, 0x5F, 0x06, 0x6E, 0xD0, \ + 0x85, 0x63, 0x65, 0x55, 0x3D, 0xED, 0x1A, 0xF3, \ + 0xB5, 0x57, 0x13, 0x5E, 0x7F, 0x57, 0xC9, 0x35, \ + 0x98, 0x4F, 0x0C, 0x70, 0xE0, 0xE6, 0x8B, 0x77, \ + 0xE2, 0xA6, 0x89, 0xDA, 0xF3, 0xEF, 0xE8, 0x72, \ + 0x1D, 0xF1, 0x58, 0xA1, 0x36, 0xAD, 0xE7, 0x35, \ + 0x30, 0xAC, 0xCA, 0x4F, 0x48, 0x3A, 0x79, 0x7A, \ + 0xBC, 0x0A, 0xB1, 0x82, 0xB3, 0x24, 0xFB, 0x61, \ + 0xD1, 0x08, 0xA9, 0x4B, 0xB2, 0xC8, 0xE3, 0xFB, \ + 0xB9, 0x6A, 0xDA, 0xB7, 0x60, 0xD7, 0xF4, 0x68, \ + 0x1D, 0x4F, 0x42, 0xA3, 0xDE, 0x39, 0x4D, 0xF4, \ + 0xAE, 0x56, 0xED, 0xE7, 0x63, 0x72, 0xBB, 0x19, \ + 0x0B, 0x07, 0xA7, 0xC8, 0xEE, 0x0A, 0x6D, 0x70, \ + 0x9E, 0x02, 0xFC, 0xE1, 0xCD, 0xF7, 0xE2, 0xEC, \ + 0xC0, 0x34, 0x04, 0xCD, 0x28, 0x34, 0x2F, 0x61, \ + 0x91, 0x72, 0xFE, 0x9C, 0xE9, 0x85, 0x83, 0xFF, \ + 0x8E, 0x4F, 0x12, 0x32, 0xEE, 0xF2, 0x81, 0x83, \ + 0xC3, 0xFE, 0x3B, 0x1B, 0x4C, 0x6F, 0xAD, 0x73, \ + 0x3B, 0xB5, 0xFC, 0xBC, 0x2E, 0xC2, 0x20, 0x05, \ + 0xC5, 0x8E, 0xF1, 0x83, 0x7D, 0x16, 0x83, 0xB2, \ + 0xC6, 0xF3, 0x4A, 0x26, 0xC1, 0xB2, 0xEF, 0xFA, \ + 0x88, 0x6B, 0x42, 0x38, 0x61, 0x1F, 0xCF, 0xDC, \ + 0xDE, 0x35, 0x5B, 0x3B, 0x65, 0x19, 0x03, 0x5B, \ + 0xBC, 0x34, 0xF4, 0xDE, 0xF9, 0x9C, 0x02, 0x38, \ + 0x61, 0xB4, 0x6F, 0xC9, 0xD6, 0xE6, 0xC9, 0x07, \ + 0x7A, 0xD9, 0x1D, 0x26, 0x91, 0xF7, 0xF7, 0xEE, \ + 0x59, 0x8C, 0xB0, 0xFA, 0xC1, 0x86, 0xD9, 0x1C, \ + 0xAE, 0xFE, 0x13, 0x09, 0x85, 0x13, 0x92, 0x70, \ + 0xB4, 0x13, 0x0C, 0x93, 0xBC, 0x43, 0x79, 0x44, \ + 0xF4, 0xFD, 0x44, 0x52, 0xE2, 0xD7, 0x4D, 0xD3, \ + 0x64, 0xF2, 0xE2, 0x1E, 0x71, 0xF5, 0x4B, 0xFF, \ + 0x5C, 0xAE, 0x82, 0xAB, 0x9C, 0x9D, 0xF6, 0x9E, \ + 0xE8, 0x6D, 0x2B, 0xC5, 0x22, 0x36, 0x3A, 0x0D, \ + 0xAB, 0xC5, 0x21, 0x97, 0x9B, 0x0D, 0xEA, 0xDA, \ + 0x1D, 0xBF, 0x9A, 0x42, 0xD5, 0xC4, 0x48, 0x4E, \ + 0x0A, 0xBC, 0xD0, 0x6B, 0xFA, 0x53, 0xDD, 0xEF, \ + 0x3C, 0x1B, 0x20, 0xEE, 0x3F, 0xD5, 0x9D, 0x7C, \ + 0x25, 0xE4, 0x1D, 0x2B, 0x66, 0xC6, 0x2E, 0x37, \ + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF } + +#define MBEDTLS_DHM_RFC7919_FFDHE3072_G_BIN { 0x02 } + +#define MBEDTLS_DHM_RFC7919_FFDHE4096_P_BIN { \ + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \ + 0xAD, 0xF8, 0x54, 0x58, 0xA2, 0xBB, 0x4A, 0x9A, \ + 0xAF, 0xDC, 0x56, 0x20, 0x27, 0x3D, 0x3C, 0xF1, \ + 0xD8, 0xB9, 0xC5, 0x83, 0xCE, 0x2D, 0x36, 0x95, \ + 0xA9, 0xE1, 0x36, 0x41, 0x14, 0x64, 0x33, 0xFB, \ + 0xCC, 0x93, 0x9D, 0xCE, 0x24, 0x9B, 0x3E, 0xF9, \ + 0x7D, 0x2F, 0xE3, 0x63, 0x63, 0x0C, 0x75, 0xD8, \ + 0xF6, 0x81, 0xB2, 0x02, 0xAE, 0xC4, 0x61, 0x7A, \ + 0xD3, 0xDF, 0x1E, 0xD5, 0xD5, 0xFD, 0x65, 0x61, \ + 0x24, 0x33, 0xF5, 0x1F, 0x5F, 0x06, 0x6E, 0xD0, \ + 0x85, 0x63, 0x65, 0x55, 0x3D, 0xED, 0x1A, 0xF3, \ + 0xB5, 0x57, 0x13, 0x5E, 0x7F, 0x57, 0xC9, 0x35, \ + 0x98, 0x4F, 0x0C, 0x70, 0xE0, 0xE6, 0x8B, 0x77, \ + 0xE2, 0xA6, 0x89, 0xDA, 0xF3, 0xEF, 0xE8, 0x72, \ + 0x1D, 0xF1, 0x58, 0xA1, 0x36, 0xAD, 0xE7, 0x35, \ + 0x30, 0xAC, 0xCA, 0x4F, 0x48, 0x3A, 0x79, 0x7A, \ + 0xBC, 0x0A, 0xB1, 0x82, 0xB3, 0x24, 0xFB, 0x61, \ + 0xD1, 0x08, 0xA9, 0x4B, 0xB2, 0xC8, 0xE3, 0xFB, \ + 0xB9, 0x6A, 0xDA, 0xB7, 0x60, 0xD7, 0xF4, 0x68, \ + 0x1D, 0x4F, 0x42, 0xA3, 0xDE, 0x39, 0x4D, 0xF4, \ + 0xAE, 0x56, 0xED, 0xE7, 0x63, 0x72, 0xBB, 0x19, \ + 0x0B, 0x07, 0xA7, 0xC8, 0xEE, 0x0A, 0x6D, 0x70, \ + 0x9E, 0x02, 0xFC, 0xE1, 0xCD, 0xF7, 0xE2, 0xEC, \ + 0xC0, 0x34, 0x04, 0xCD, 0x28, 0x34, 0x2F, 0x61, \ + 0x91, 0x72, 0xFE, 0x9C, 0xE9, 0x85, 0x83, 0xFF, \ + 0x8E, 0x4F, 0x12, 0x32, 0xEE, 0xF2, 0x81, 0x83, \ + 0xC3, 0xFE, 0x3B, 0x1B, 0x4C, 0x6F, 0xAD, 0x73, \ + 0x3B, 0xB5, 0xFC, 0xBC, 0x2E, 0xC2, 0x20, 0x05, \ + 0xC5, 0x8E, 0xF1, 0x83, 0x7D, 0x16, 0x83, 0xB2, \ + 0xC6, 0xF3, 0x4A, 0x26, 0xC1, 0xB2, 0xEF, 0xFA, \ + 0x88, 0x6B, 0x42, 0x38, 0x61, 0x1F, 0xCF, 0xDC, \ + 0xDE, 0x35, 0x5B, 0x3B, 0x65, 0x19, 0x03, 0x5B, \ + 0xBC, 0x34, 0xF4, 0xDE, 0xF9, 0x9C, 0x02, 0x38, \ + 0x61, 0xB4, 0x6F, 0xC9, 0xD6, 0xE6, 0xC9, 0x07, \ + 0x7A, 0xD9, 0x1D, 0x26, 0x91, 0xF7, 0xF7, 0xEE, \ + 0x59, 0x8C, 0xB0, 0xFA, 0xC1, 0x86, 0xD9, 0x1C, \ + 0xAE, 0xFE, 0x13, 0x09, 0x85, 0x13, 0x92, 0x70, \ + 0xB4, 0x13, 0x0C, 0x93, 0xBC, 0x43, 0x79, 0x44, \ + 0xF4, 0xFD, 0x44, 0x52, 0xE2, 0xD7, 0x4D, 0xD3, \ + 0x64, 0xF2, 0xE2, 0x1E, 0x71, 0xF5, 0x4B, 0xFF, \ + 0x5C, 0xAE, 0x82, 0xAB, 0x9C, 0x9D, 0xF6, 0x9E, \ + 0xE8, 0x6D, 0x2B, 0xC5, 0x22, 0x36, 0x3A, 0x0D, \ + 0xAB, 0xC5, 0x21, 0x97, 0x9B, 0x0D, 0xEA, 0xDA, \ + 0x1D, 0xBF, 0x9A, 0x42, 0xD5, 0xC4, 0x48, 0x4E, \ + 0x0A, 0xBC, 0xD0, 0x6B, 0xFA, 0x53, 0xDD, 0xEF, \ + 0x3C, 0x1B, 0x20, 0xEE, 0x3F, 0xD5, 0x9D, 0x7C, \ + 0x25, 0xE4, 0x1D, 0x2B, 0x66, 0x9E, 0x1E, 0xF1, \ + 0x6E, 0x6F, 0x52, 0xC3, 0x16, 0x4D, 0xF4, 0xFB, \ + 0x79, 0x30, 0xE9, 0xE4, 0xE5, 0x88, 0x57, 0xB6, \ + 0xAC, 0x7D, 0x5F, 0x42, 0xD6, 0x9F, 0x6D, 0x18, \ + 0x77, 0x63, 0xCF, 0x1D, 0x55, 0x03, 0x40, 0x04, \ + 0x87, 0xF5, 0x5B, 0xA5, 0x7E, 0x31, 0xCC, 0x7A, \ + 0x71, 0x35, 0xC8, 0x86, 0xEF, 0xB4, 0x31, 0x8A, \ + 0xED, 0x6A, 0x1E, 0x01, 0x2D, 0x9E, 0x68, 0x32, \ + 0xA9, 0x07, 0x60, 0x0A, 0x91, 0x81, 0x30, 0xC4, \ + 0x6D, 0xC7, 0x78, 0xF9, 0x71, 0xAD, 0x00, 0x38, \ + 0x09, 0x29, 0x99, 0xA3, 0x33, 0xCB, 0x8B, 0x7A, \ + 0x1A, 0x1D, 0xB9, 0x3D, 0x71, 0x40, 0x00, 0x3C, \ + 0x2A, 0x4E, 0xCE, 0xA9, 0xF9, 0x8D, 0x0A, 0xCC, \ + 0x0A, 0x82, 0x91, 0xCD, 0xCE, 0xC9, 0x7D, 0xCF, \ + 0x8E, 0xC9, 0xB5, 0x5A, 0x7F, 0x88, 0xA4, 0x6B, \ + 0x4D, 0xB5, 0xA8, 0x51, 0xF4, 0x41, 0x82, 0xE1, \ + 0xC6, 0x8A, 0x00, 0x7E, 0x5E, 0x65, 0x5F, 0x6A, \ + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF } + +#define MBEDTLS_DHM_RFC7919_FFDHE4096_G_BIN { 0x02 } + +#define MBEDTLS_DHM_RFC7919_FFDHE6144_P_BIN { \ + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \ + 0xAD, 0xF8, 0x54, 0x58, 0xA2, 0xBB, 0x4A, 0x9A, \ + 0xAF, 0xDC, 0x56, 0x20, 0x27, 0x3D, 0x3C, 0xF1, \ + 0xD8, 0xB9, 0xC5, 0x83, 0xCE, 0x2D, 0x36, 0x95, \ + 0xA9, 0xE1, 0x36, 0x41, 0x14, 0x64, 0x33, 0xFB, \ + 0xCC, 0x93, 0x9D, 0xCE, 0x24, 0x9B, 0x3E, 0xF9, \ + 0x7D, 0x2F, 0xE3, 0x63, 0x63, 0x0C, 0x75, 0xD8, \ + 0xF6, 0x81, 0xB2, 0x02, 0xAE, 0xC4, 0x61, 0x7A, \ + 0xD3, 0xDF, 0x1E, 0xD5, 0xD5, 0xFD, 0x65, 0x61, \ + 0x24, 0x33, 0xF5, 0x1F, 0x5F, 0x06, 0x6E, 0xD0, \ + 0x85, 0x63, 0x65, 0x55, 0x3D, 0xED, 0x1A, 0xF3, \ + 0xB5, 0x57, 0x13, 0x5E, 0x7F, 0x57, 0xC9, 0x35, \ + 0x98, 0x4F, 0x0C, 0x70, 0xE0, 0xE6, 0x8B, 0x77, \ + 0xE2, 0xA6, 0x89, 0xDA, 0xF3, 0xEF, 0xE8, 0x72, \ + 0x1D, 0xF1, 0x58, 0xA1, 0x36, 0xAD, 0xE7, 0x35, \ + 0x30, 0xAC, 0xCA, 0x4F, 0x48, 0x3A, 0x79, 0x7A, \ + 0xBC, 0x0A, 0xB1, 0x82, 0xB3, 0x24, 0xFB, 0x61, \ + 0xD1, 0x08, 0xA9, 0x4B, 0xB2, 0xC8, 0xE3, 0xFB, \ + 0xB9, 0x6A, 0xDA, 0xB7, 0x60, 0xD7, 0xF4, 0x68, \ + 0x1D, 0x4F, 0x42, 0xA3, 0xDE, 0x39, 0x4D, 0xF4, \ + 0xAE, 0x56, 0xED, 0xE7, 0x63, 0x72, 0xBB, 0x19, \ + 0x0B, 0x07, 0xA7, 0xC8, 0xEE, 0x0A, 0x6D, 0x70, \ + 0x9E, 0x02, 0xFC, 0xE1, 0xCD, 0xF7, 0xE2, 0xEC, \ + 0xC0, 0x34, 0x04, 0xCD, 0x28, 0x34, 0x2F, 0x61, \ + 0x91, 0x72, 0xFE, 0x9C, 0xE9, 0x85, 0x83, 0xFF, \ + 0x8E, 0x4F, 0x12, 0x32, 0xEE, 0xF2, 0x81, 0x83, \ + 0xC3, 0xFE, 0x3B, 0x1B, 0x4C, 0x6F, 0xAD, 0x73, \ + 0x3B, 0xB5, 0xFC, 0xBC, 0x2E, 0xC2, 0x20, 0x05, \ + 0xC5, 0x8E, 0xF1, 0x83, 0x7D, 0x16, 0x83, 0xB2, \ + 0xC6, 0xF3, 0x4A, 0x26, 0xC1, 0xB2, 0xEF, 0xFA, \ + 0x88, 0x6B, 0x42, 0x38, 0x61, 0x1F, 0xCF, 0xDC, \ + 0xDE, 0x35, 0x5B, 0x3B, 0x65, 0x19, 0x03, 0x5B, \ + 0xBC, 0x34, 0xF4, 0xDE, 0xF9, 0x9C, 0x02, 0x38, \ + 0x61, 0xB4, 0x6F, 0xC9, 0xD6, 0xE6, 0xC9, 0x07, \ + 0x7A, 0xD9, 0x1D, 0x26, 0x91, 0xF7, 0xF7, 0xEE, \ + 0x59, 0x8C, 0xB0, 0xFA, 0xC1, 0x86, 0xD9, 0x1C, \ + 0xAE, 0xFE, 0x13, 0x09, 0x85, 0x13, 0x92, 0x70, \ + 0xB4, 0x13, 0x0C, 0x93, 0xBC, 0x43, 0x79, 0x44, \ + 0xF4, 0xFD, 0x44, 0x52, 0xE2, 0xD7, 0x4D, 0xD3, \ + 0x64, 0xF2, 0xE2, 0x1E, 0x71, 0xF5, 0x4B, 0xFF, \ + 0x5C, 0xAE, 0x82, 0xAB, 0x9C, 0x9D, 0xF6, 0x9E, \ + 0xE8, 0x6D, 0x2B, 0xC5, 0x22, 0x36, 0x3A, 0x0D, \ + 0xAB, 0xC5, 0x21, 0x97, 0x9B, 0x0D, 0xEA, 0xDA, \ + 0x1D, 0xBF, 0x9A, 0x42, 0xD5, 0xC4, 0x48, 0x4E, \ + 0x0A, 0xBC, 0xD0, 0x6B, 0xFA, 0x53, 0xDD, 0xEF, \ + 0x3C, 0x1B, 0x20, 0xEE, 0x3F, 0xD5, 0x9D, 0x7C, \ + 0x25, 0xE4, 0x1D, 0x2B, 0x66, 0x9E, 0x1E, 0xF1, \ + 0x6E, 0x6F, 0x52, 0xC3, 0x16, 0x4D, 0xF4, 0xFB, \ + 0x79, 0x30, 0xE9, 0xE4, 0xE5, 0x88, 0x57, 0xB6, \ + 0xAC, 0x7D, 0x5F, 0x42, 0xD6, 0x9F, 0x6D, 0x18, \ + 0x77, 0x63, 0xCF, 0x1D, 0x55, 0x03, 0x40, 0x04, \ + 0x87, 0xF5, 0x5B, 0xA5, 0x7E, 0x31, 0xCC, 0x7A, \ + 0x71, 0x35, 0xC8, 0x86, 0xEF, 0xB4, 0x31, 0x8A, \ + 0xED, 0x6A, 0x1E, 0x01, 0x2D, 0x9E, 0x68, 0x32, \ + 0xA9, 0x07, 0x60, 0x0A, 0x91, 0x81, 0x30, 0xC4, \ + 0x6D, 0xC7, 0x78, 0xF9, 0x71, 0xAD, 0x00, 0x38, \ + 0x09, 0x29, 0x99, 0xA3, 0x33, 0xCB, 0x8B, 0x7A, \ + 0x1A, 0x1D, 0xB9, 0x3D, 0x71, 0x40, 0x00, 0x3C, \ + 0x2A, 0x4E, 0xCE, 0xA9, 0xF9, 0x8D, 0x0A, 0xCC, \ + 0x0A, 0x82, 0x91, 0xCD, 0xCE, 0xC9, 0x7D, 0xCF, \ + 0x8E, 0xC9, 0xB5, 0x5A, 0x7F, 0x88, 0xA4, 0x6B, \ + 0x4D, 0xB5, 0xA8, 0x51, 0xF4, 0x41, 0x82, 0xE1, \ + 0xC6, 0x8A, 0x00, 0x7E, 0x5E, 0x0D, 0xD9, 0x02, \ + 0x0B, 0xFD, 0x64, 0xB6, 0x45, 0x03, 0x6C, 0x7A, \ + 0x4E, 0x67, 0x7D, 0x2C, 0x38, 0x53, 0x2A, 0x3A, \ + 0x23, 0xBA, 0x44, 0x42, 0xCA, 0xF5, 0x3E, 0xA6, \ + 0x3B, 0xB4, 0x54, 0x32, 0x9B, 0x76, 0x24, 0xC8, \ + 0x91, 0x7B, 0xDD, 0x64, 0xB1, 0xC0, 0xFD, 0x4C, \ + 0xB3, 0x8E, 0x8C, 0x33, 0x4C, 0x70, 0x1C, 0x3A, \ + 0xCD, 0xAD, 0x06, 0x57, 0xFC, 0xCF, 0xEC, 0x71, \ + 0x9B, 0x1F, 0x5C, 0x3E, 0x4E, 0x46, 0x04, 0x1F, \ + 0x38, 0x81, 0x47, 0xFB, 0x4C, 0xFD, 0xB4, 0x77, \ + 0xA5, 0x24, 0x71, 0xF7, 0xA9, 0xA9, 0x69, 0x10, \ + 0xB8, 0x55, 0x32, 0x2E, 0xDB, 0x63, 0x40, 0xD8, \ + 0xA0, 0x0E, 0xF0, 0x92, 0x35, 0x05, 0x11, 0xE3, \ + 0x0A, 0xBE, 0xC1, 0xFF, 0xF9, 0xE3, 0xA2, 0x6E, \ + 0x7F, 0xB2, 0x9F, 0x8C, 0x18, 0x30, 0x23, 0xC3, \ + 0x58, 0x7E, 0x38, 0xDA, 0x00, 0x77, 0xD9, 0xB4, \ + 0x76, 0x3E, 0x4E, 0x4B, 0x94, 0xB2, 0xBB, 0xC1, \ + 0x94, 0xC6, 0x65, 0x1E, 0x77, 0xCA, 0xF9, 0x92, \ + 0xEE, 0xAA, 0xC0, 0x23, 0x2A, 0x28, 0x1B, 0xF6, \ + 0xB3, 0xA7, 0x39, 0xC1, 0x22, 0x61, 0x16, 0x82, \ + 0x0A, 0xE8, 0xDB, 0x58, 0x47, 0xA6, 0x7C, 0xBE, \ + 0xF9, 0xC9, 0x09, 0x1B, 0x46, 0x2D, 0x53, 0x8C, \ + 0xD7, 0x2B, 0x03, 0x74, 0x6A, 0xE7, 0x7F, 0x5E, \ + 0x62, 0x29, 0x2C, 0x31, 0x15, 0x62, 0xA8, 0x46, \ + 0x50, 0x5D, 0xC8, 0x2D, 0xB8, 0x54, 0x33, 0x8A, \ + 0xE4, 0x9F, 0x52, 0x35, 0xC9, 0x5B, 0x91, 0x17, \ + 0x8C, 0xCF, 0x2D, 0xD5, 0xCA, 0xCE, 0xF4, 0x03, \ + 0xEC, 0x9D, 0x18, 0x10, 0xC6, 0x27, 0x2B, 0x04, \ + 0x5B, 0x3B, 0x71, 0xF9, 0xDC, 0x6B, 0x80, 0xD6, \ + 0x3F, 0xDD, 0x4A, 0x8E, 0x9A, 0xDB, 0x1E, 0x69, \ + 0x62, 0xA6, 0x95, 0x26, 0xD4, 0x31, 0x61, 0xC1, \ + 0xA4, 0x1D, 0x57, 0x0D, 0x79, 0x38, 0xDA, 0xD4, \ + 0xA4, 0x0E, 0x32, 0x9C, 0xD0, 0xE4, 0x0E, 0x65, \ + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF } + +#define MBEDTLS_DHM_RFC7919_FFDHE6144_G_BIN { 0x02 } + +#define MBEDTLS_DHM_RFC7919_FFDHE8192_P_BIN { \ + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \ + 0xAD, 0xF8, 0x54, 0x58, 0xA2, 0xBB, 0x4A, 0x9A, \ + 0xAF, 0xDC, 0x56, 0x20, 0x27, 0x3D, 0x3C, 0xF1, \ + 0xD8, 0xB9, 0xC5, 0x83, 0xCE, 0x2D, 0x36, 0x95, \ + 0xA9, 0xE1, 0x36, 0x41, 0x14, 0x64, 0x33, 0xFB, \ + 0xCC, 0x93, 0x9D, 0xCE, 0x24, 0x9B, 0x3E, 0xF9, \ + 0x7D, 0x2F, 0xE3, 0x63, 0x63, 0x0C, 0x75, 0xD8, \ + 0xF6, 0x81, 0xB2, 0x02, 0xAE, 0xC4, 0x61, 0x7A, \ + 0xD3, 0xDF, 0x1E, 0xD5, 0xD5, 0xFD, 0x65, 0x61, \ + 0x24, 0x33, 0xF5, 0x1F, 0x5F, 0x06, 0x6E, 0xD0, \ + 0x85, 0x63, 0x65, 0x55, 0x3D, 0xED, 0x1A, 0xF3, \ + 0xB5, 0x57, 0x13, 0x5E, 0x7F, 0x57, 0xC9, 0x35, \ + 0x98, 0x4F, 0x0C, 0x70, 0xE0, 0xE6, 0x8B, 0x77, \ + 0xE2, 0xA6, 0x89, 0xDA, 0xF3, 0xEF, 0xE8, 0x72, \ + 0x1D, 0xF1, 0x58, 0xA1, 0x36, 0xAD, 0xE7, 0x35, \ + 0x30, 0xAC, 0xCA, 0x4F, 0x48, 0x3A, 0x79, 0x7A, \ + 0xBC, 0x0A, 0xB1, 0x82, 0xB3, 0x24, 0xFB, 0x61, \ + 0xD1, 0x08, 0xA9, 0x4B, 0xB2, 0xC8, 0xE3, 0xFB, \ + 0xB9, 0x6A, 0xDA, 0xB7, 0x60, 0xD7, 0xF4, 0x68, \ + 0x1D, 0x4F, 0x42, 0xA3, 0xDE, 0x39, 0x4D, 0xF4, \ + 0xAE, 0x56, 0xED, 0xE7, 0x63, 0x72, 0xBB, 0x19, \ + 0x0B, 0x07, 0xA7, 0xC8, 0xEE, 0x0A, 0x6D, 0x70, \ + 0x9E, 0x02, 0xFC, 0xE1, 0xCD, 0xF7, 0xE2, 0xEC, \ + 0xC0, 0x34, 0x04, 0xCD, 0x28, 0x34, 0x2F, 0x61, \ + 0x91, 0x72, 0xFE, 0x9C, 0xE9, 0x85, 0x83, 0xFF, \ + 0x8E, 0x4F, 0x12, 0x32, 0xEE, 0xF2, 0x81, 0x83, \ + 0xC3, 0xFE, 0x3B, 0x1B, 0x4C, 0x6F, 0xAD, 0x73, \ + 0x3B, 0xB5, 0xFC, 0xBC, 0x2E, 0xC2, 0x20, 0x05, \ + 0xC5, 0x8E, 0xF1, 0x83, 0x7D, 0x16, 0x83, 0xB2, \ + 0xC6, 0xF3, 0x4A, 0x26, 0xC1, 0xB2, 0xEF, 0xFA, \ + 0x88, 0x6B, 0x42, 0x38, 0x61, 0x1F, 0xCF, 0xDC, \ + 0xDE, 0x35, 0x5B, 0x3B, 0x65, 0x19, 0x03, 0x5B, \ + 0xBC, 0x34, 0xF4, 0xDE, 0xF9, 0x9C, 0x02, 0x38, \ + 0x61, 0xB4, 0x6F, 0xC9, 0xD6, 0xE6, 0xC9, 0x07, \ + 0x7A, 0xD9, 0x1D, 0x26, 0x91, 0xF7, 0xF7, 0xEE, \ + 0x59, 0x8C, 0xB0, 0xFA, 0xC1, 0x86, 0xD9, 0x1C, \ + 0xAE, 0xFE, 0x13, 0x09, 0x85, 0x13, 0x92, 0x70, \ + 0xB4, 0x13, 0x0C, 0x93, 0xBC, 0x43, 0x79, 0x44, \ + 0xF4, 0xFD, 0x44, 0x52, 0xE2, 0xD7, 0x4D, 0xD3, \ + 0x64, 0xF2, 0xE2, 0x1E, 0x71, 0xF5, 0x4B, 0xFF, \ + 0x5C, 0xAE, 0x82, 0xAB, 0x9C, 0x9D, 0xF6, 0x9E, \ + 0xE8, 0x6D, 0x2B, 0xC5, 0x22, 0x36, 0x3A, 0x0D, \ + 0xAB, 0xC5, 0x21, 0x97, 0x9B, 0x0D, 0xEA, 0xDA, \ + 0x1D, 0xBF, 0x9A, 0x42, 0xD5, 0xC4, 0x48, 0x4E, \ + 0x0A, 0xBC, 0xD0, 0x6B, 0xFA, 0x53, 0xDD, 0xEF, \ + 0x3C, 0x1B, 0x20, 0xEE, 0x3F, 0xD5, 0x9D, 0x7C, \ + 0x25, 0xE4, 0x1D, 0x2B, 0x66, 0x9E, 0x1E, 0xF1, \ + 0x6E, 0x6F, 0x52, 0xC3, 0x16, 0x4D, 0xF4, 0xFB, \ + 0x79, 0x30, 0xE9, 0xE4, 0xE5, 0x88, 0x57, 0xB6, \ + 0xAC, 0x7D, 0x5F, 0x42, 0xD6, 0x9F, 0x6D, 0x18, \ + 0x77, 0x63, 0xCF, 0x1D, 0x55, 0x03, 0x40, 0x04, \ + 0x87, 0xF5, 0x5B, 0xA5, 0x7E, 0x31, 0xCC, 0x7A, \ + 0x71, 0x35, 0xC8, 0x86, 0xEF, 0xB4, 0x31, 0x8A, \ + 0xED, 0x6A, 0x1E, 0x01, 0x2D, 0x9E, 0x68, 0x32, \ + 0xA9, 0x07, 0x60, 0x0A, 0x91, 0x81, 0x30, 0xC4, \ + 0x6D, 0xC7, 0x78, 0xF9, 0x71, 0xAD, 0x00, 0x38, \ + 0x09, 0x29, 0x99, 0xA3, 0x33, 0xCB, 0x8B, 0x7A, \ + 0x1A, 0x1D, 0xB9, 0x3D, 0x71, 0x40, 0x00, 0x3C, \ + 0x2A, 0x4E, 0xCE, 0xA9, 0xF9, 0x8D, 0x0A, 0xCC, \ + 0x0A, 0x82, 0x91, 0xCD, 0xCE, 0xC9, 0x7D, 0xCF, \ + 0x8E, 0xC9, 0xB5, 0x5A, 0x7F, 0x88, 0xA4, 0x6B, \ + 0x4D, 0xB5, 0xA8, 0x51, 0xF4, 0x41, 0x82, 0xE1, \ + 0xC6, 0x8A, 0x00, 0x7E, 0x5E, 0x0D, 0xD9, 0x02, \ + 0x0B, 0xFD, 0x64, 0xB6, 0x45, 0x03, 0x6C, 0x7A, \ + 0x4E, 0x67, 0x7D, 0x2C, 0x38, 0x53, 0x2A, 0x3A, \ + 0x23, 0xBA, 0x44, 0x42, 0xCA, 0xF5, 0x3E, 0xA6, \ + 0x3B, 0xB4, 0x54, 0x32, 0x9B, 0x76, 0x24, 0xC8, \ + 0x91, 0x7B, 0xDD, 0x64, 0xB1, 0xC0, 0xFD, 0x4C, \ + 0xB3, 0x8E, 0x8C, 0x33, 0x4C, 0x70, 0x1C, 0x3A, \ + 0xCD, 0xAD, 0x06, 0x57, 0xFC, 0xCF, 0xEC, 0x71, \ + 0x9B, 0x1F, 0x5C, 0x3E, 0x4E, 0x46, 0x04, 0x1F, \ + 0x38, 0x81, 0x47, 0xFB, 0x4C, 0xFD, 0xB4, 0x77, \ + 0xA5, 0x24, 0x71, 0xF7, 0xA9, 0xA9, 0x69, 0x10, \ + 0xB8, 0x55, 0x32, 0x2E, 0xDB, 0x63, 0x40, 0xD8, \ + 0xA0, 0x0E, 0xF0, 0x92, 0x35, 0x05, 0x11, 0xE3, \ + 0x0A, 0xBE, 0xC1, 0xFF, 0xF9, 0xE3, 0xA2, 0x6E, \ + 0x7F, 0xB2, 0x9F, 0x8C, 0x18, 0x30, 0x23, 0xC3, \ + 0x58, 0x7E, 0x38, 0xDA, 0x00, 0x77, 0xD9, 0xB4, \ + 0x76, 0x3E, 0x4E, 0x4B, 0x94, 0xB2, 0xBB, 0xC1, \ + 0x94, 0xC6, 0x65, 0x1E, 0x77, 0xCA, 0xF9, 0x92, \ + 0xEE, 0xAA, 0xC0, 0x23, 0x2A, 0x28, 0x1B, 0xF6, \ + 0xB3, 0xA7, 0x39, 0xC1, 0x22, 0x61, 0x16, 0x82, \ + 0x0A, 0xE8, 0xDB, 0x58, 0x47, 0xA6, 0x7C, 0xBE, \ + 0xF9, 0xC9, 0x09, 0x1B, 0x46, 0x2D, 0x53, 0x8C, \ + 0xD7, 0x2B, 0x03, 0x74, 0x6A, 0xE7, 0x7F, 0x5E, \ + 0x62, 0x29, 0x2C, 0x31, 0x15, 0x62, 0xA8, 0x46, \ + 0x50, 0x5D, 0xC8, 0x2D, 0xB8, 0x54, 0x33, 0x8A, \ + 0xE4, 0x9F, 0x52, 0x35, 0xC9, 0x5B, 0x91, 0x17, \ + 0x8C, 0xCF, 0x2D, 0xD5, 0xCA, 0xCE, 0xF4, 0x03, \ + 0xEC, 0x9D, 0x18, 0x10, 0xC6, 0x27, 0x2B, 0x04, \ + 0x5B, 0x3B, 0x71, 0xF9, 0xDC, 0x6B, 0x80, 0xD6, \ + 0x3F, 0xDD, 0x4A, 0x8E, 0x9A, 0xDB, 0x1E, 0x69, \ + 0x62, 0xA6, 0x95, 0x26, 0xD4, 0x31, 0x61, 0xC1, \ + 0xA4, 0x1D, 0x57, 0x0D, 0x79, 0x38, 0xDA, 0xD4, \ + 0xA4, 0x0E, 0x32, 0x9C, 0xCF, 0xF4, 0x6A, 0xAA, \ + 0x36, 0xAD, 0x00, 0x4C, 0xF6, 0x00, 0xC8, 0x38, \ + 0x1E, 0x42, 0x5A, 0x31, 0xD9, 0x51, 0xAE, 0x64, \ + 0xFD, 0xB2, 0x3F, 0xCE, 0xC9, 0x50, 0x9D, 0x43, \ + 0x68, 0x7F, 0xEB, 0x69, 0xED, 0xD1, 0xCC, 0x5E, \ + 0x0B, 0x8C, 0xC3, 0xBD, 0xF6, 0x4B, 0x10, 0xEF, \ + 0x86, 0xB6, 0x31, 0x42, 0xA3, 0xAB, 0x88, 0x29, \ + 0x55, 0x5B, 0x2F, 0x74, 0x7C, 0x93, 0x26, 0x65, \ + 0xCB, 0x2C, 0x0F, 0x1C, 0xC0, 0x1B, 0xD7, 0x02, \ + 0x29, 0x38, 0x88, 0x39, 0xD2, 0xAF, 0x05, 0xE4, \ + 0x54, 0x50, 0x4A, 0xC7, 0x8B, 0x75, 0x82, 0x82, \ + 0x28, 0x46, 0xC0, 0xBA, 0x35, 0xC3, 0x5F, 0x5C, \ + 0x59, 0x16, 0x0C, 0xC0, 0x46, 0xFD, 0x82, 0x51, \ + 0x54, 0x1F, 0xC6, 0x8C, 0x9C, 0x86, 0xB0, 0x22, \ + 0xBB, 0x70, 0x99, 0x87, 0x6A, 0x46, 0x0E, 0x74, \ + 0x51, 0xA8, 0xA9, 0x31, 0x09, 0x70, 0x3F, 0xEE, \ + 0x1C, 0x21, 0x7E, 0x6C, 0x38, 0x26, 0xE5, 0x2C, \ + 0x51, 0xAA, 0x69, 0x1E, 0x0E, 0x42, 0x3C, 0xFC, \ + 0x99, 0xE9, 0xE3, 0x16, 0x50, 0xC1, 0x21, 0x7B, \ + 0x62, 0x48, 0x16, 0xCD, 0xAD, 0x9A, 0x95, 0xF9, \ + 0xD5, 0xB8, 0x01, 0x94, 0x88, 0xD9, 0xC0, 0xA0, \ + 0xA1, 0xFE, 0x30, 0x75, 0xA5, 0x77, 0xE2, 0x31, \ + 0x83, 0xF8, 0x1D, 0x4A, 0x3F, 0x2F, 0xA4, 0x57, \ + 0x1E, 0xFC, 0x8C, 0xE0, 0xBA, 0x8A, 0x4F, 0xE8, \ + 0xB6, 0x85, 0x5D, 0xFE, 0x72, 0xB0, 0xA6, 0x6E, \ + 0xDE, 0xD2, 0xFB, 0xAB, 0xFB, 0xE5, 0x8A, 0x30, \ + 0xFA, 0xFA, 0xBE, 0x1C, 0x5D, 0x71, 0xA8, 0x7E, \ + 0x2F, 0x74, 0x1E, 0xF8, 0xC1, 0xFE, 0x86, 0xFE, \ + 0xA6, 0xBB, 0xFD, 0xE5, 0x30, 0x67, 0x7F, 0x0D, \ + 0x97, 0xD1, 0x1D, 0x49, 0xF7, 0xA8, 0x44, 0x3D, \ + 0x08, 0x22, 0xE5, 0x06, 0xA9, 0xF4, 0x61, 0x4E, \ + 0x01, 0x1E, 0x2A, 0x94, 0x83, 0x8F, 0xF8, 0x8C, \ + 0xD6, 0x8C, 0x8B, 0xB7, 0xC5, 0xC6, 0x42, 0x4C, \ + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF } + +#define MBEDTLS_DHM_RFC7919_FFDHE8192_G_BIN { 0x02 } + +#endif /* dhm.h */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/ecdh.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/ecdh.h new file mode 100644 index 0000000000000000000000000000000000000000..4479a1d46fb3169895c4a3879a4434c19b116c77 --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/ecdh.h @@ -0,0 +1,440 @@ +/** + * \file ecdh.h + * + * \brief This file contains ECDH definitions and functions. + * + * The Elliptic Curve Diffie-Hellman (ECDH) protocol is an anonymous + * key agreement protocol allowing two parties to establish a shared + * secret over an insecure channel. Each party must have an + * elliptic-curve public–private key pair. + * + * For more information, see NIST SP 800-56A Rev. 2: Recommendation for + * Pair-Wise Key Establishment Schemes Using Discrete Logarithm + * Cryptography. + */ +/* + * Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of Mbed TLS (https://tls.mbed.org) + */ + +#ifndef MBEDTLS_ECDH_H +#define MBEDTLS_ECDH_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include "ecp.h" + +/* + * Use a backward compatible ECDH context. + * + * This flag is always enabled for now and future versions might add a + * configuration option that conditionally undefines this flag. + * The configuration option in question may have a different name. + * + * Features undefining this flag, must have a warning in their description in + * config.h stating that the feature breaks backward compatibility. + */ +#define MBEDTLS_ECDH_LEGACY_CONTEXT + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Defines the source of the imported EC key. + */ +typedef enum +{ + MBEDTLS_ECDH_OURS, /**< Our key. */ + MBEDTLS_ECDH_THEIRS, /**< The key of the peer. */ +} mbedtls_ecdh_side; + +#if !defined(MBEDTLS_ECDH_LEGACY_CONTEXT) +/** + * Defines the ECDH implementation used. + * + * Later versions of the library may add new variants, therefore users should + * not make any assumptions about them. + */ +typedef enum +{ + MBEDTLS_ECDH_VARIANT_NONE = 0, /*!< Implementation not defined. */ + MBEDTLS_ECDH_VARIANT_MBEDTLS_2_0,/*!< The default Mbed TLS implementation */ +} mbedtls_ecdh_variant; + +/** + * The context used by the default ECDH implementation. + * + * Later versions might change the structure of this context, therefore users + * should not make any assumptions about the structure of + * mbedtls_ecdh_context_mbed. + */ +typedef struct mbedtls_ecdh_context_mbed +{ + mbedtls_ecp_group grp; /*!< The elliptic curve used. */ + mbedtls_mpi d; /*!< The private key. */ + mbedtls_ecp_point Q; /*!< The public key. */ + mbedtls_ecp_point Qp; /*!< The value of the public key of the peer. */ + mbedtls_mpi z; /*!< The shared secret. */ +#if defined(MBEDTLS_ECP_RESTARTABLE) + mbedtls_ecp_restart_ctx rs; /*!< The restart context for EC computations. */ +#endif +} mbedtls_ecdh_context_mbed; +#endif + +/** + * + * \warning Performing multiple operations concurrently on the same + * ECDSA context is not supported; objects of this type + * should not be shared between multiple threads. + * \brief The ECDH context structure. + */ +typedef struct mbedtls_ecdh_context +{ +#if defined(MBEDTLS_ECDH_LEGACY_CONTEXT) + mbedtls_ecp_group grp; /*!< The elliptic curve used. */ + mbedtls_mpi d; /*!< The private key. */ + mbedtls_ecp_point Q; /*!< The public key. */ + mbedtls_ecp_point Qp; /*!< The value of the public key of the peer. */ + mbedtls_mpi z; /*!< The shared secret. */ + int point_format; /*!< The format of point export in TLS messages. */ + mbedtls_ecp_point Vi; /*!< The blinding value. */ + mbedtls_ecp_point Vf; /*!< The unblinding value. */ + mbedtls_mpi _d; /*!< The previous \p d. */ +#if defined(MBEDTLS_ECP_RESTARTABLE) + int restart_enabled; /*!< The flag for restartable mode. */ + mbedtls_ecp_restart_ctx rs; /*!< The restart context for EC computations. */ +#endif /* MBEDTLS_ECP_RESTARTABLE */ +#else + uint8_t point_format; /*!< The format of point export in TLS messages + as defined in RFC 4492. */ + mbedtls_ecp_group_id grp_id;/*!< The elliptic curve used. */ + mbedtls_ecdh_variant var; /*!< The ECDH implementation/structure used. */ + union + { + mbedtls_ecdh_context_mbed mbed_ecdh; + } ctx; /*!< Implementation-specific context. The + context in use is specified by the \c var + field. */ +#if defined(MBEDTLS_ECP_RESTARTABLE) + uint8_t restart_enabled; /*!< The flag for restartable mode. Functions of + an alternative implementation not supporting + restartable mode must return + MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED error + if this flag is set. */ +#endif /* MBEDTLS_ECP_RESTARTABLE */ +#endif /* MBEDTLS_ECDH_LEGACY_CONTEXT */ +} +mbedtls_ecdh_context; + +/** + * \brief This function generates an ECDH keypair on an elliptic + * curve. + * + * This function performs the first of two core computations + * implemented during the ECDH key exchange. The second core + * computation is performed by mbedtls_ecdh_compute_shared(). + * + * \see ecp.h + * + * \param grp The ECP group to use. This must be initialized and have + * domain parameters loaded, for example through + * mbedtls_ecp_load() or mbedtls_ecp_tls_read_group(). + * \param d The destination MPI (private key). + * This must be initialized. + * \param Q The destination point (public key). + * This must be initialized. + * \param f_rng The RNG function to use. This must not be \c NULL. + * \param p_rng The RNG context to be passed to \p f_rng. This may be + * \c NULL in case \p f_rng doesn't need a context argument. + * + * \return \c 0 on success. + * \return Another \c MBEDTLS_ERR_ECP_XXX or + * \c MBEDTLS_MPI_XXX error code on failure. + */ +int mbedtls_ecdh_gen_public( mbedtls_ecp_group *grp, mbedtls_mpi *d, mbedtls_ecp_point *Q, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng ); + +/** + * \brief This function computes the shared secret. + * + * This function performs the second of two core computations + * implemented during the ECDH key exchange. The first core + * computation is performed by mbedtls_ecdh_gen_public(). + * + * \see ecp.h + * + * \note If \p f_rng is not NULL, it is used to implement + * countermeasures against side-channel attacks. + * For more information, see mbedtls_ecp_mul(). + * + * \param grp The ECP group to use. This must be initialized and have + * domain parameters loaded, for example through + * mbedtls_ecp_load() or mbedtls_ecp_tls_read_group(). + * \param z The destination MPI (shared secret). + * This must be initialized. + * \param Q The public key from another party. + * This must be initialized. + * \param d Our secret exponent (private key). + * This must be initialized. + * \param f_rng The RNG function. This may be \c NULL if randomization + * of intermediate results during the ECP computations is + * not needed (discouraged). See the documentation of + * mbedtls_ecp_mul() for more. + * \param p_rng The RNG context to be passed to \p f_rng. This may be + * \c NULL if \p f_rng is \c NULL or doesn't need a + * context argument. + * + * \return \c 0 on success. + * \return Another \c MBEDTLS_ERR_ECP_XXX or + * \c MBEDTLS_MPI_XXX error code on failure. + */ +int mbedtls_ecdh_compute_shared( mbedtls_ecp_group *grp, mbedtls_mpi *z, + const mbedtls_ecp_point *Q, const mbedtls_mpi *d, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng ); + +/** + * \brief This function initializes an ECDH context. + * + * \param ctx The ECDH context to initialize. This must not be \c NULL. + */ +void mbedtls_ecdh_init( mbedtls_ecdh_context *ctx ); + +/** + * \brief This function sets up the ECDH context with the information + * given. + * + * This function should be called after mbedtls_ecdh_init() but + * before mbedtls_ecdh_make_params(). There is no need to call + * this function before mbedtls_ecdh_read_params(). + * + * This is the first function used by a TLS server for ECDHE + * ciphersuites. + * + * \param ctx The ECDH context to set up. This must be initialized. + * \param grp_id The group id of the group to set up the context for. + * + * \return \c 0 on success. + */ +int mbedtls_ecdh_setup( mbedtls_ecdh_context *ctx, + mbedtls_ecp_group_id grp_id ); + +/** + * \brief This function frees a context. + * + * \param ctx The context to free. This may be \c NULL, in which + * case this function does nothing. If it is not \c NULL, + * it must point to an initialized ECDH context. + */ +void mbedtls_ecdh_free( mbedtls_ecdh_context *ctx ); + +/** + * \brief This function generates an EC key pair and exports its + * in the format used in a TLS ServerKeyExchange handshake + * message. + * + * This is the second function used by a TLS server for ECDHE + * ciphersuites. (It is called after mbedtls_ecdh_setup().) + * + * \see ecp.h + * + * \param ctx The ECDH context to use. This must be initialized + * and bound to a group, for example via mbedtls_ecdh_setup(). + * \param olen The address at which to store the number of Bytes written. + * \param buf The destination buffer. This must be a writable buffer of + * length \p blen Bytes. + * \param blen The length of the destination buffer \p buf in Bytes. + * \param f_rng The RNG function to use. This must not be \c NULL. + * \param p_rng The RNG context to be passed to \p f_rng. This may be + * \c NULL in case \p f_rng doesn't need a context argument. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of + * operations was reached: see \c mbedtls_ecp_set_max_ops(). + * \return Another \c MBEDTLS_ERR_ECP_XXX error code on failure. + */ +int mbedtls_ecdh_make_params( mbedtls_ecdh_context *ctx, size_t *olen, + unsigned char *buf, size_t blen, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng ); + +/** + * \brief This function parses the ECDHE parameters in a + * TLS ServerKeyExchange handshake message. + * + * \note In a TLS handshake, this is the how the client + * sets up its ECDHE context from the server's public + * ECDHE key material. + * + * \see ecp.h + * + * \param ctx The ECDHE context to use. This must be initialized. + * \param buf On input, \c *buf must be the start of the input buffer. + * On output, \c *buf is updated to point to the end of the + * data that has been read. On success, this is the first byte + * past the end of the ServerKeyExchange parameters. + * On error, this is the point at which an error has been + * detected, which is usually not useful except to debug + * failures. + * \param end The end of the input buffer. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_ECP_XXX error code on failure. + * + */ +int mbedtls_ecdh_read_params( mbedtls_ecdh_context *ctx, + const unsigned char **buf, + const unsigned char *end ); + +/** + * \brief This function sets up an ECDH context from an EC key. + * + * It is used by clients and servers in place of the + * ServerKeyEchange for static ECDH, and imports ECDH + * parameters from the EC key information of a certificate. + * + * \see ecp.h + * + * \param ctx The ECDH context to set up. This must be initialized. + * \param key The EC key to use. This must be initialized. + * \param side Defines the source of the key. Possible values are: + * - #MBEDTLS_ECDH_OURS: The key is ours. + * - #MBEDTLS_ECDH_THEIRS: The key is that of the peer. + * + * \return \c 0 on success. + * \return Another \c MBEDTLS_ERR_ECP_XXX error code on failure. + * + */ +int mbedtls_ecdh_get_params( mbedtls_ecdh_context *ctx, + const mbedtls_ecp_keypair *key, + mbedtls_ecdh_side side ); + +/** + * \brief This function generates a public key and exports it + * as a TLS ClientKeyExchange payload. + * + * This is the second function used by a TLS client for ECDH(E) + * ciphersuites. + * + * \see ecp.h + * + * \param ctx The ECDH context to use. This must be initialized + * and bound to a group, the latter usually by + * mbedtls_ecdh_read_params(). + * \param olen The address at which to store the number of Bytes written. + * This must not be \c NULL. + * \param buf The destination buffer. This must be a writable buffer + * of length \p blen Bytes. + * \param blen The size of the destination buffer \p buf in Bytes. + * \param f_rng The RNG function to use. This must not be \c NULL. + * \param p_rng The RNG context to be passed to \p f_rng. This may be + * \c NULL in case \p f_rng doesn't need a context argument. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of + * operations was reached: see \c mbedtls_ecp_set_max_ops(). + * \return Another \c MBEDTLS_ERR_ECP_XXX error code on failure. + */ +int mbedtls_ecdh_make_public( mbedtls_ecdh_context *ctx, size_t *olen, + unsigned char *buf, size_t blen, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng ); + +/** + * \brief This function parses and processes the ECDHE payload of a + * TLS ClientKeyExchange message. + * + * This is the third function used by a TLS server for ECDH(E) + * ciphersuites. (It is called after mbedtls_ecdh_setup() and + * mbedtls_ecdh_make_params().) + * + * \see ecp.h + * + * \param ctx The ECDH context to use. This must be initialized + * and bound to a group, for example via mbedtls_ecdh_setup(). + * \param buf The pointer to the ClientKeyExchange payload. This must + * be a readable buffer of length \p blen Bytes. + * \param blen The length of the input buffer \p buf in Bytes. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_ECP_XXX error code on failure. + */ +int mbedtls_ecdh_read_public( mbedtls_ecdh_context *ctx, + const unsigned char *buf, size_t blen ); + +/** + * \brief This function derives and exports the shared secret. + * + * This is the last function used by both TLS client + * and servers. + * + * \note If \p f_rng is not NULL, it is used to implement + * countermeasures against side-channel attacks. + * For more information, see mbedtls_ecp_mul(). + * + * \see ecp.h + + * \param ctx The ECDH context to use. This must be initialized + * and have its own private key generated and the peer's + * public key imported. + * \param olen The address at which to store the total number of + * Bytes written on success. This must not be \c NULL. + * \param buf The buffer to write the generated shared key to. This + * must be a writable buffer of size \p blen Bytes. + * \param blen The length of the destination buffer \p buf in Bytes. + * \param f_rng The RNG function, for blinding purposes. This may + * b \c NULL if blinding isn't needed. + * \param p_rng The RNG context. This may be \c NULL if \p f_rng + * doesn't need a context argument. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of + * operations was reached: see \c mbedtls_ecp_set_max_ops(). + * \return Another \c MBEDTLS_ERR_ECP_XXX error code on failure. + */ +int mbedtls_ecdh_calc_secret( mbedtls_ecdh_context *ctx, size_t *olen, + unsigned char *buf, size_t blen, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng ); + +#if defined(MBEDTLS_ECP_RESTARTABLE) +/** + * \brief This function enables restartable EC computations for this + * context. (Default: disabled.) + * + * \see \c mbedtls_ecp_set_max_ops() + * + * \note It is not possible to safely disable restartable + * computations once enabled, except by free-ing the context, + * which cancels possible in-progress operations. + * + * \param ctx The ECDH context to use. This must be initialized. + */ +void mbedtls_ecdh_enable_restart( mbedtls_ecdh_context *ctx ); +#endif /* MBEDTLS_ECP_RESTARTABLE */ + +#ifdef __cplusplus +} +#endif + +#endif /* ecdh.h */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/ecdsa.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/ecdsa.h new file mode 100644 index 0000000000000000000000000000000000000000..932acc6d14191ce3882ac634da1bdedd5f3a6454 --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/ecdsa.h @@ -0,0 +1,604 @@ +/** + * \file ecdsa.h + * + * \brief This file contains ECDSA definitions and functions. + * + * The Elliptic Curve Digital Signature Algorithm (ECDSA) is defined in + * Standards for Efficient Cryptography Group (SECG): + * SEC1 Elliptic Curve Cryptography. + * The use of ECDSA for TLS is defined in RFC-4492: Elliptic Curve + * Cryptography (ECC) Cipher Suites for Transport Layer Security (TLS). + * + */ +/* + * Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of Mbed TLS (https://tls.mbed.org) + */ + +#ifndef MBEDTLS_ECDSA_H +#define MBEDTLS_ECDSA_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include "ecp.h" +#include "md.h" + +/* + * RFC-4492 page 20: + * + * Ecdsa-Sig-Value ::= SEQUENCE { + * r INTEGER, + * s INTEGER + * } + * + * Size is at most + * 1 (tag) + 1 (len) + 1 (initial 0) + ECP_MAX_BYTES for each of r and s, + * twice that + 1 (tag) + 2 (len) for the sequence + * (assuming ECP_MAX_BYTES is less than 126 for r and s, + * and less than 124 (total len <= 255) for the sequence) + */ +#if MBEDTLS_ECP_MAX_BYTES > 124 +#error "MBEDTLS_ECP_MAX_BYTES bigger than expected, please fix MBEDTLS_ECDSA_MAX_LEN" +#endif +/** The maximal size of an ECDSA signature in Bytes. */ +#define MBEDTLS_ECDSA_MAX_LEN ( 3 + 2 * ( 3 + MBEDTLS_ECP_MAX_BYTES ) ) + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \brief The ECDSA context structure. + * + * \warning Performing multiple operations concurrently on the same + * ECDSA context is not supported; objects of this type + * should not be shared between multiple threads. + */ +typedef mbedtls_ecp_keypair mbedtls_ecdsa_context; + +#if defined(MBEDTLS_ECP_RESTARTABLE) + +/** + * \brief Internal restart context for ecdsa_verify() + * + * \note Opaque struct, defined in ecdsa.c + */ +typedef struct mbedtls_ecdsa_restart_ver mbedtls_ecdsa_restart_ver_ctx; + +/** + * \brief Internal restart context for ecdsa_sign() + * + * \note Opaque struct, defined in ecdsa.c + */ +typedef struct mbedtls_ecdsa_restart_sig mbedtls_ecdsa_restart_sig_ctx; + +#if defined(MBEDTLS_ECDSA_DETERMINISTIC) +/** + * \brief Internal restart context for ecdsa_sign_det() + * + * \note Opaque struct, defined in ecdsa.c + */ +typedef struct mbedtls_ecdsa_restart_det mbedtls_ecdsa_restart_det_ctx; +#endif + +/** + * \brief General context for resuming ECDSA operations + */ +typedef struct +{ + mbedtls_ecp_restart_ctx ecp; /*!< base context for ECP restart and + shared administrative info */ + mbedtls_ecdsa_restart_ver_ctx *ver; /*!< ecdsa_verify() sub-context */ + mbedtls_ecdsa_restart_sig_ctx *sig; /*!< ecdsa_sign() sub-context */ +#if defined(MBEDTLS_ECDSA_DETERMINISTIC) + mbedtls_ecdsa_restart_det_ctx *det; /*!< ecdsa_sign_det() sub-context */ +#endif +} mbedtls_ecdsa_restart_ctx; + +#else /* MBEDTLS_ECP_RESTARTABLE */ + +/* Now we can declare functions that take a pointer to that */ +typedef void mbedtls_ecdsa_restart_ctx; + +#endif /* MBEDTLS_ECP_RESTARTABLE */ + +/** + * \brief This function computes the ECDSA signature of a + * previously-hashed message. + * + * \note The deterministic version implemented in + * mbedtls_ecdsa_sign_det() is usually preferred. + * + * \note If the bitlength of the message hash is larger than the + * bitlength of the group order, then the hash is truncated + * as defined in Standards for Efficient Cryptography Group + * (SECG): SEC1 Elliptic Curve Cryptography, section + * 4.1.3, step 5. + * + * \see ecp.h + * + * \param grp The context for the elliptic curve to use. + * This must be initialized and have group parameters + * set, for example through mbedtls_ecp_group_load(). + * \param r The MPI context in which to store the first part + * the signature. This must be initialized. + * \param s The MPI context in which to store the second part + * the signature. This must be initialized. + * \param d The private signing key. This must be initialized. + * \param buf The content to be signed. This is usually the hash of + * the original data to be signed. This must be a readable + * buffer of length \p blen Bytes. It may be \c NULL if + * \p blen is zero. + * \param blen The length of \p buf in Bytes. + * \param f_rng The RNG function. This must not be \c NULL. + * \param p_rng The RNG context to be passed to \p f_rng. This may be + * \c NULL if \p f_rng doesn't need a context parameter. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_ECP_XXX + * or \c MBEDTLS_MPI_XXX error code on failure. + */ +int mbedtls_ecdsa_sign( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s, + const mbedtls_mpi *d, const unsigned char *buf, size_t blen, + int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ); + +#if defined(MBEDTLS_ECDSA_DETERMINISTIC) +/** + * \brief This function computes the ECDSA signature of a + * previously-hashed message, deterministic version. + * + * For more information, see RFC-6979: Deterministic + * Usage of the Digital Signature Algorithm (DSA) and Elliptic + * Curve Digital Signature Algorithm (ECDSA). + * + * \note If the bitlength of the message hash is larger than the + * bitlength of the group order, then the hash is truncated as + * defined in Standards for Efficient Cryptography Group + * (SECG): SEC1 Elliptic Curve Cryptography, section + * 4.1.3, step 5. + * + * \warning Since the output of the internal RNG is always the same for + * the same key and message, this limits the efficiency of + * blinding and leaks information through side channels. For + * secure behavior use mbedtls_ecdsa_sign_det_ext() instead. + * + * (Optimally the blinding is a random value that is different + * on every execution. In this case the blinding is still + * random from the attackers perspective, but is the same on + * each execution. This means that this blinding does not + * prevent attackers from recovering secrets by combining + * several measurement traces, but may prevent some attacks + * that exploit relationships between secret data.) + * + * \see ecp.h + * + * \param grp The context for the elliptic curve to use. + * This must be initialized and have group parameters + * set, for example through mbedtls_ecp_group_load(). + * \param r The MPI context in which to store the first part + * the signature. This must be initialized. + * \param s The MPI context in which to store the second part + * the signature. This must be initialized. + * \param d The private signing key. This must be initialized + * and setup, for example through mbedtls_ecp_gen_privkey(). + * \param buf The hashed content to be signed. This must be a readable + * buffer of length \p blen Bytes. It may be \c NULL if + * \p blen is zero. + * \param blen The length of \p buf in Bytes. + * \param md_alg The hash algorithm used to hash the original data. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_ECP_XXX or \c MBEDTLS_MPI_XXX + * error code on failure. + */ +int mbedtls_ecdsa_sign_det( mbedtls_ecp_group *grp, mbedtls_mpi *r, + mbedtls_mpi *s, const mbedtls_mpi *d, + const unsigned char *buf, size_t blen, + mbedtls_md_type_t md_alg ); +/** + * \brief This function computes the ECDSA signature of a + * previously-hashed message, deterministic version. + * + * For more information, see RFC-6979: Deterministic + * Usage of the Digital Signature Algorithm (DSA) and Elliptic + * Curve Digital Signature Algorithm (ECDSA). + * + * \note If the bitlength of the message hash is larger than the + * bitlength of the group order, then the hash is truncated as + * defined in Standards for Efficient Cryptography Group + * (SECG): SEC1 Elliptic Curve Cryptography, section + * 4.1.3, step 5. + * + * \see ecp.h + * + * \param grp The context for the elliptic curve to use. + * This must be initialized and have group parameters + * set, for example through mbedtls_ecp_group_load(). + * \param r The MPI context in which to store the first part + * the signature. This must be initialized. + * \param s The MPI context in which to store the second part + * the signature. This must be initialized. + * \param d The private signing key. This must be initialized + * and setup, for example through mbedtls_ecp_gen_privkey(). + * \param buf The hashed content to be signed. This must be a readable + * buffer of length \p blen Bytes. It may be \c NULL if + * \p blen is zero. + * \param blen The length of \p buf in Bytes. + * \param md_alg The hash algorithm used to hash the original data. + * \param f_rng_blind The RNG function used for blinding. This must not be + * \c NULL. + * \param p_rng_blind The RNG context to be passed to \p f_rng. This may be + * \c NULL if \p f_rng doesn't need a context parameter. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_ECP_XXX or \c MBEDTLS_MPI_XXX + * error code on failure. + */ +int mbedtls_ecdsa_sign_det_ext( mbedtls_ecp_group *grp, mbedtls_mpi *r, + mbedtls_mpi *s, const mbedtls_mpi *d, + const unsigned char *buf, size_t blen, + mbedtls_md_type_t md_alg, + int (*f_rng_blind)(void *, unsigned char *, + size_t), + void *p_rng_blind ); +#endif /* MBEDTLS_ECDSA_DETERMINISTIC */ + +/** + * \brief This function verifies the ECDSA signature of a + * previously-hashed message. + * + * \note If the bitlength of the message hash is larger than the + * bitlength of the group order, then the hash is truncated as + * defined in Standards for Efficient Cryptography Group + * (SECG): SEC1 Elliptic Curve Cryptography, section + * 4.1.4, step 3. + * + * \see ecp.h + * + * \param grp The ECP group to use. + * This must be initialized and have group parameters + * set, for example through mbedtls_ecp_group_load(). + * \param buf The hashed content that was signed. This must be a readable + * buffer of length \p blen Bytes. It may be \c NULL if + * \p blen is zero. + * \param blen The length of \p buf in Bytes. + * \param Q The public key to use for verification. This must be + * initialized and setup. + * \param r The first integer of the signature. + * This must be initialized. + * \param s The second integer of the signature. + * This must be initialized. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if the signature + * is invalid. + * \return An \c MBEDTLS_ERR_ECP_XXX or \c MBEDTLS_MPI_XXX + * error code on failure for any other reason. + */ +int mbedtls_ecdsa_verify( mbedtls_ecp_group *grp, + const unsigned char *buf, size_t blen, + const mbedtls_ecp_point *Q, const mbedtls_mpi *r, + const mbedtls_mpi *s); + +/** + * \brief This function computes the ECDSA signature and writes it + * to a buffer, serialized as defined in RFC-4492: + * Elliptic Curve Cryptography (ECC) Cipher Suites for + * Transport Layer Security (TLS). + * + * \warning It is not thread-safe to use the same context in + * multiple threads. + * + * \note The deterministic version is used if + * #MBEDTLS_ECDSA_DETERMINISTIC is defined. For more + * information, see RFC-6979: Deterministic Usage + * of the Digital Signature Algorithm (DSA) and Elliptic + * Curve Digital Signature Algorithm (ECDSA). + * + * \note If the bitlength of the message hash is larger than the + * bitlength of the group order, then the hash is truncated as + * defined in Standards for Efficient Cryptography Group + * (SECG): SEC1 Elliptic Curve Cryptography, section + * 4.1.3, step 5. + * + * \see ecp.h + * + * \param ctx The ECDSA context to use. This must be initialized + * and have a group and private key bound to it, for example + * via mbedtls_ecdsa_genkey() or mbedtls_ecdsa_from_keypair(). + * \param md_alg The message digest that was used to hash the message. + * \param hash The message hash to be signed. This must be a readable + * buffer of length \p blen Bytes. + * \param hlen The length of the hash \p hash in Bytes. + * \param sig The buffer to which to write the signature. This must be a + * writable buffer of length at least twice as large as the + * size of the curve used, plus 9. For example, 73 Bytes if + * a 256-bit curve is used. A buffer length of + * #MBEDTLS_ECDSA_MAX_LEN is always safe. + * \param slen The address at which to store the actual length of + * the signature written. Must not be \c NULL. + * \param f_rng The RNG function. This must not be \c NULL if + * #MBEDTLS_ECDSA_DETERMINISTIC is unset. Otherwise, + * it is unused and may be set to \c NULL. + * \param p_rng The RNG context to be passed to \p f_rng. This may be + * \c NULL if \p f_rng is \c NULL or doesn't use a context. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_ECP_XXX, \c MBEDTLS_ERR_MPI_XXX or + * \c MBEDTLS_ERR_ASN1_XXX error code on failure. + */ +int mbedtls_ecdsa_write_signature( mbedtls_ecdsa_context *ctx, + mbedtls_md_type_t md_alg, + const unsigned char *hash, size_t hlen, + unsigned char *sig, size_t *slen, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng ); + +/** + * \brief This function computes the ECDSA signature and writes it + * to a buffer, in a restartable way. + * + * \see \c mbedtls_ecdsa_write_signature() + * + * \note This function is like \c mbedtls_ecdsa_write_signature() + * but it can return early and restart according to the limit + * set with \c mbedtls_ecp_set_max_ops() to reduce blocking. + * + * \param ctx The ECDSA context to use. This must be initialized + * and have a group and private key bound to it, for example + * via mbedtls_ecdsa_genkey() or mbedtls_ecdsa_from_keypair(). + * \param md_alg The message digest that was used to hash the message. + * \param hash The message hash to be signed. This must be a readable + * buffer of length \p blen Bytes. + * \param hlen The length of the hash \p hash in Bytes. + * \param sig The buffer to which to write the signature. This must be a + * writable buffer of length at least twice as large as the + * size of the curve used, plus 9. For example, 73 Bytes if + * a 256-bit curve is used. A buffer length of + * #MBEDTLS_ECDSA_MAX_LEN is always safe. + * \param slen The address at which to store the actual length of + * the signature written. Must not be \c NULL. + * \param f_rng The RNG function. This must not be \c NULL if + * #MBEDTLS_ECDSA_DETERMINISTIC is unset. Otherwise, + * it is unused and may be set to \c NULL. + * \param p_rng The RNG context to be passed to \p f_rng. This may be + * \c NULL if \p f_rng is \c NULL or doesn't use a context. + * \param rs_ctx The restart context to use. This may be \c NULL to disable + * restarting. If it is not \c NULL, it must point to an + * initialized restart context. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of + * operations was reached: see \c mbedtls_ecp_set_max_ops(). + * \return Another \c MBEDTLS_ERR_ECP_XXX, \c MBEDTLS_ERR_MPI_XXX or + * \c MBEDTLS_ERR_ASN1_XXX error code on failure. + */ +int mbedtls_ecdsa_write_signature_restartable( mbedtls_ecdsa_context *ctx, + mbedtls_md_type_t md_alg, + const unsigned char *hash, size_t hlen, + unsigned char *sig, size_t *slen, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng, + mbedtls_ecdsa_restart_ctx *rs_ctx ); + +#if defined(MBEDTLS_ECDSA_DETERMINISTIC) +#if ! defined(MBEDTLS_DEPRECATED_REMOVED) +#if defined(MBEDTLS_DEPRECATED_WARNING) +#define MBEDTLS_DEPRECATED __attribute__((deprecated)) +#else +#define MBEDTLS_DEPRECATED +#endif +/** + * \brief This function computes an ECDSA signature and writes + * it to a buffer, serialized as defined in RFC-4492: + * Elliptic Curve Cryptography (ECC) Cipher Suites for + * Transport Layer Security (TLS). + * + * The deterministic version is defined in RFC-6979: + * Deterministic Usage of the Digital Signature Algorithm (DSA) + * and Elliptic Curve Digital Signature Algorithm (ECDSA). + * + * \warning It is not thread-safe to use the same context in + * multiple threads. + * + * \note If the bitlength of the message hash is larger than the + * bitlength of the group order, then the hash is truncated as + * defined in Standards for Efficient Cryptography Group + * (SECG): SEC1 Elliptic Curve Cryptography, section + * 4.1.3, step 5. + * + * \see ecp.h + * + * \deprecated Superseded by mbedtls_ecdsa_write_signature() in + * Mbed TLS version 2.0 and later. + * + * \param ctx The ECDSA context to use. This must be initialized + * and have a group and private key bound to it, for example + * via mbedtls_ecdsa_genkey() or mbedtls_ecdsa_from_keypair(). + * \param hash The message hash to be signed. This must be a readable + * buffer of length \p blen Bytes. + * \param hlen The length of the hash \p hash in Bytes. + * \param sig The buffer to which to write the signature. This must be a + * writable buffer of length at least twice as large as the + * size of the curve used, plus 9. For example, 73 Bytes if + * a 256-bit curve is used. A buffer length of + * #MBEDTLS_ECDSA_MAX_LEN is always safe. + * \param slen The address at which to store the actual length of + * the signature written. Must not be \c NULL. + * \param md_alg The message digest that was used to hash the message. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_ECP_XXX, \c MBEDTLS_ERR_MPI_XXX or + * \c MBEDTLS_ERR_ASN1_XXX error code on failure. + */ +int mbedtls_ecdsa_write_signature_det( mbedtls_ecdsa_context *ctx, + const unsigned char *hash, size_t hlen, + unsigned char *sig, size_t *slen, + mbedtls_md_type_t md_alg ) MBEDTLS_DEPRECATED; +#undef MBEDTLS_DEPRECATED +#endif /* MBEDTLS_DEPRECATED_REMOVED */ +#endif /* MBEDTLS_ECDSA_DETERMINISTIC */ + +/** + * \brief This function reads and verifies an ECDSA signature. + * + * \note If the bitlength of the message hash is larger than the + * bitlength of the group order, then the hash is truncated as + * defined in Standards for Efficient Cryptography Group + * (SECG): SEC1 Elliptic Curve Cryptography, section + * 4.1.4, step 3. + * + * \see ecp.h + * + * \param ctx The ECDSA context to use. This must be initialized + * and have a group and public key bound to it. + * \param hash The message hash that was signed. This must be a readable + * buffer of length \p size Bytes. + * \param hlen The size of the hash \p hash. + * \param sig The signature to read and verify. This must be a readable + * buffer of length \p slen Bytes. + * \param slen The size of \p sig in Bytes. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if signature is invalid. + * \return #MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH if there is a valid + * signature in \p sig, but its length is less than \p siglen. + * \return An \c MBEDTLS_ERR_ECP_XXX or \c MBEDTLS_ERR_MPI_XXX + * error code on failure for any other reason. + */ +int mbedtls_ecdsa_read_signature( mbedtls_ecdsa_context *ctx, + const unsigned char *hash, size_t hlen, + const unsigned char *sig, size_t slen ); + +/** + * \brief This function reads and verifies an ECDSA signature, + * in a restartable way. + * + * \see \c mbedtls_ecdsa_read_signature() + * + * \note This function is like \c mbedtls_ecdsa_read_signature() + * but it can return early and restart according to the limit + * set with \c mbedtls_ecp_set_max_ops() to reduce blocking. + * + * \param ctx The ECDSA context to use. This must be initialized + * and have a group and public key bound to it. + * \param hash The message hash that was signed. This must be a readable + * buffer of length \p size Bytes. + * \param hlen The size of the hash \p hash. + * \param sig The signature to read and verify. This must be a readable + * buffer of length \p slen Bytes. + * \param slen The size of \p sig in Bytes. + * \param rs_ctx The restart context to use. This may be \c NULL to disable + * restarting. If it is not \c NULL, it must point to an + * initialized restart context. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if signature is invalid. + * \return #MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH if there is a valid + * signature in \p sig, but its length is less than \p siglen. + * \return #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of + * operations was reached: see \c mbedtls_ecp_set_max_ops(). + * \return Another \c MBEDTLS_ERR_ECP_XXX or \c MBEDTLS_ERR_MPI_XXX + * error code on failure for any other reason. + */ +int mbedtls_ecdsa_read_signature_restartable( mbedtls_ecdsa_context *ctx, + const unsigned char *hash, size_t hlen, + const unsigned char *sig, size_t slen, + mbedtls_ecdsa_restart_ctx *rs_ctx ); + +/** + * \brief This function generates an ECDSA keypair on the given curve. + * + * \see ecp.h + * + * \param ctx The ECDSA context to store the keypair in. + * This must be initialized. + * \param gid The elliptic curve to use. One of the various + * \c MBEDTLS_ECP_DP_XXX macros depending on configuration. + * \param f_rng The RNG function to use. This must not be \c NULL. + * \param p_rng The RNG context to be passed to \p f_rng. This may be + * \c NULL if \p f_rng doesn't need a context argument. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_ECP_XXX code on failure. + */ +int mbedtls_ecdsa_genkey( mbedtls_ecdsa_context *ctx, mbedtls_ecp_group_id gid, + int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ); + +/** + * \brief This function sets up an ECDSA context from an EC key pair. + * + * \see ecp.h + * + * \param ctx The ECDSA context to setup. This must be initialized. + * \param key The EC key to use. This must be initialized and hold + * a private-public key pair or a public key. In the former + * case, the ECDSA context may be used for signature creation + * and verification after this call. In the latter case, it + * may be used for signature verification. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_ECP_XXX code on failure. + */ +int mbedtls_ecdsa_from_keypair( mbedtls_ecdsa_context *ctx, + const mbedtls_ecp_keypair *key ); + +/** + * \brief This function initializes an ECDSA context. + * + * \param ctx The ECDSA context to initialize. + * This must not be \c NULL. + */ +void mbedtls_ecdsa_init( mbedtls_ecdsa_context *ctx ); + +/** + * \brief This function frees an ECDSA context. + * + * \param ctx The ECDSA context to free. This may be \c NULL, + * in which case this function does nothing. If it + * is not \c NULL, it must be initialized. + */ +void mbedtls_ecdsa_free( mbedtls_ecdsa_context *ctx ); + +#if defined(MBEDTLS_ECP_RESTARTABLE) +/** + * \brief Initialize a restart context. + * + * \param ctx The restart context to initialize. + * This must not be \c NULL. + */ +void mbedtls_ecdsa_restart_init( mbedtls_ecdsa_restart_ctx *ctx ); + +/** + * \brief Free the components of a restart context. + * + * \param ctx The restart context to free. This may be \c NULL, + * in which case this function does nothing. If it + * is not \c NULL, it must be initialized. + */ +void mbedtls_ecdsa_restart_free( mbedtls_ecdsa_restart_ctx *ctx ); +#endif /* MBEDTLS_ECP_RESTARTABLE */ + +#ifdef __cplusplus +} +#endif + +#endif /* ecdsa.h */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/ecjpake.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/ecjpake.h new file mode 100644 index 0000000000000000000000000000000000000000..3d8d02ae6464cbe2feb16a63d626a4bced0ee37e --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/ecjpake.h @@ -0,0 +1,277 @@ +/** + * \file ecjpake.h + * + * \brief Elliptic curve J-PAKE + */ +/* + * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ +#ifndef MBEDTLS_ECJPAKE_H +#define MBEDTLS_ECJPAKE_H + +/* + * J-PAKE is a password-authenticated key exchange that allows deriving a + * strong shared secret from a (potentially low entropy) pre-shared + * passphrase, with forward secrecy and mutual authentication. + * https://en.wikipedia.org/wiki/Password_Authenticated_Key_Exchange_by_Juggling + * + * This file implements the Elliptic Curve variant of J-PAKE, + * as defined in Chapter 7.4 of the Thread v1.0 Specification, + * available to members of the Thread Group http://threadgroup.org/ + * + * As the J-PAKE algorithm is inherently symmetric, so is our API. + * Each party needs to send its first round message, in any order, to the + * other party, then each sends its second round message, in any order. + * The payloads are serialized in a way suitable for use in TLS, but could + * also be use outside TLS. + */ +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include "ecp.h" +#include "md.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Roles in the EC J-PAKE exchange + */ +typedef enum { + MBEDTLS_ECJPAKE_CLIENT = 0, /**< Client */ + MBEDTLS_ECJPAKE_SERVER, /**< Server */ +} mbedtls_ecjpake_role; + +#if !defined(MBEDTLS_ECJPAKE_ALT) +/** + * EC J-PAKE context structure. + * + * J-PAKE is a symmetric protocol, except for the identifiers used in + * Zero-Knowledge Proofs, and the serialization of the second message + * (KeyExchange) as defined by the Thread spec. + * + * In order to benefit from this symmetry, we choose a different naming + * convetion from the Thread v1.0 spec. Correspondance is indicated in the + * description as a pair C: client name, S: server name + */ +typedef struct mbedtls_ecjpake_context +{ + const mbedtls_md_info_t *md_info; /**< Hash to use */ + mbedtls_ecp_group grp; /**< Elliptic curve */ + mbedtls_ecjpake_role role; /**< Are we client or server? */ + int point_format; /**< Format for point export */ + + mbedtls_ecp_point Xm1; /**< My public key 1 C: X1, S: X3 */ + mbedtls_ecp_point Xm2; /**< My public key 2 C: X2, S: X4 */ + mbedtls_ecp_point Xp1; /**< Peer public key 1 C: X3, S: X1 */ + mbedtls_ecp_point Xp2; /**< Peer public key 2 C: X4, S: X2 */ + mbedtls_ecp_point Xp; /**< Peer public key C: Xs, S: Xc */ + + mbedtls_mpi xm1; /**< My private key 1 C: x1, S: x3 */ + mbedtls_mpi xm2; /**< My private key 2 C: x2, S: x4 */ + + mbedtls_mpi s; /**< Pre-shared secret (passphrase) */ +} mbedtls_ecjpake_context; + +#else /* MBEDTLS_ECJPAKE_ALT */ +#include "ecjpake_alt.h" +#endif /* MBEDTLS_ECJPAKE_ALT */ + +/** + * \brief Initialize an ECJPAKE context. + * + * \param ctx The ECJPAKE context to initialize. + * This must not be \c NULL. + */ +void mbedtls_ecjpake_init( mbedtls_ecjpake_context *ctx ); + +/** + * \brief Set up an ECJPAKE context for use. + * + * \note Currently the only values for hash/curve allowed by the + * standard are #MBEDTLS_MD_SHA256/#MBEDTLS_ECP_DP_SECP256R1. + * + * \param ctx The ECJPAKE context to set up. This must be initialized. + * \param role The role of the caller. This must be either + * #MBEDTLS_ECJPAKE_CLIENT or #MBEDTLS_ECJPAKE_SERVER. + * \param hash The identifier of the hash function to use, + * for example #MBEDTLS_MD_SHA256. + * \param curve The identifier of the elliptic curve to use, + * for example #MBEDTLS_ECP_DP_SECP256R1. + * \param secret The pre-shared secret (passphrase). This must be + * a readable buffer of length \p len Bytes. It need + * only be valid for the duration of this call. + * \param len The length of the pre-shared secret \p secret. + * + * \return \c 0 if successful. + * \return A negative error code on failure. + */ +int mbedtls_ecjpake_setup( mbedtls_ecjpake_context *ctx, + mbedtls_ecjpake_role role, + mbedtls_md_type_t hash, + mbedtls_ecp_group_id curve, + const unsigned char *secret, + size_t len ); + +/** + * \brief Check if an ECJPAKE context is ready for use. + * + * \param ctx The ECJPAKE context to check. This must be + * initialized. + * + * \return \c 0 if the context is ready for use. + * \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA otherwise. + */ +int mbedtls_ecjpake_check( const mbedtls_ecjpake_context *ctx ); + +/** + * \brief Generate and write the first round message + * (TLS: contents of the Client/ServerHello extension, + * excluding extension type and length bytes). + * + * \param ctx The ECJPAKE context to use. This must be + * initialized and set up. + * \param buf The buffer to write the contents to. This must be a + * writable buffer of length \p len Bytes. + * \param len The length of \p buf in Bytes. + * \param olen The address at which to store the total number + * of Bytes written to \p buf. This must not be \c NULL. + * \param f_rng The RNG function to use. This must not be \c NULL. + * \param p_rng The RNG parameter to be passed to \p f_rng. This + * may be \c NULL if \p f_rng doesn't use a context. + * + * \return \c 0 if successful. + * \return A negative error code on failure. + */ +int mbedtls_ecjpake_write_round_one( mbedtls_ecjpake_context *ctx, + unsigned char *buf, size_t len, size_t *olen, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng ); + +/** + * \brief Read and process the first round message + * (TLS: contents of the Client/ServerHello extension, + * excluding extension type and length bytes). + * + * \param ctx The ECJPAKE context to use. This must be initialized + * and set up. + * \param buf The buffer holding the first round message. This must + * be a readable buffer of length \p len Bytes. + * \param len The length in Bytes of \p buf. + * + * \return \c 0 if successful. + * \return A negative error code on failure. + */ +int mbedtls_ecjpake_read_round_one( mbedtls_ecjpake_context *ctx, + const unsigned char *buf, + size_t len ); + +/** + * \brief Generate and write the second round message + * (TLS: contents of the Client/ServerKeyExchange). + * + * \param ctx The ECJPAKE context to use. This must be initialized, + * set up, and already have performed round one. + * \param buf The buffer to write the round two contents to. + * This must be a writable buffer of length \p len Bytes. + * \param len The size of \p buf in Bytes. + * \param olen The address at which to store the total number of Bytes + * written to \p buf. This must not be \c NULL. + * \param f_rng The RNG function to use. This must not be \c NULL. + * \param p_rng The RNG parameter to be passed to \p f_rng. This + * may be \c NULL if \p f_rng doesn't use a context. + * + * \return \c 0 if successful. + * \return A negative error code on failure. + */ +int mbedtls_ecjpake_write_round_two( mbedtls_ecjpake_context *ctx, + unsigned char *buf, size_t len, size_t *olen, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng ); + +/** + * \brief Read and process the second round message + * (TLS: contents of the Client/ServerKeyExchange). + * + * \param ctx The ECJPAKE context to use. This must be initialized + * and set up and already have performed round one. + * \param buf The buffer holding the second round message. This must + * be a readable buffer of length \p len Bytes. + * \param len The length in Bytes of \p buf. + * + * \return \c 0 if successful. + * \return A negative error code on failure. + */ +int mbedtls_ecjpake_read_round_two( mbedtls_ecjpake_context *ctx, + const unsigned char *buf, + size_t len ); + +/** + * \brief Derive the shared secret + * (TLS: Pre-Master Secret). + * + * \param ctx The ECJPAKE context to use. This must be initialized, + * set up and have performed both round one and two. + * \param buf The buffer to write the derived secret to. This must + * be a writable buffer of length \p len Bytes. + * \param len The length of \p buf in Bytes. + * \param olen The address at which to store the total number of Bytes + * written to \p buf. This must not be \c NULL. + * \param f_rng The RNG function to use. This must not be \c NULL. + * \param p_rng The RNG parameter to be passed to \p f_rng. This + * may be \c NULL if \p f_rng doesn't use a context. + * + * \return \c 0 if successful. + * \return A negative error code on failure. + */ +int mbedtls_ecjpake_derive_secret( mbedtls_ecjpake_context *ctx, + unsigned char *buf, size_t len, size_t *olen, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng ); + +/** + * \brief This clears an ECJPAKE context and frees any + * embedded data structure. + * + * \param ctx The ECJPAKE context to free. This may be \c NULL, + * in which case this function does nothing. If it is not + * \c NULL, it must point to an initialized ECJPAKE context. + */ +void mbedtls_ecjpake_free( mbedtls_ecjpake_context *ctx ); + +#if defined(MBEDTLS_SELF_TEST) + +/** + * \brief Checkup routine + * + * \return 0 if successful, or 1 if a test failed + */ +int mbedtls_ecjpake_self_test( int verbose ); + +#endif /* MBEDTLS_SELF_TEST */ + +#ifdef __cplusplus +} +#endif + + +#endif /* ecjpake.h */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/ecp.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/ecp.h new file mode 100644 index 0000000000000000000000000000000000000000..065a4cc0b990ff3f799727a59282986eca2cd1db --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/ecp.h @@ -0,0 +1,1132 @@ +/** + * \file ecp.h + * + * \brief This file provides an API for Elliptic Curves over GF(P) (ECP). + * + * The use of ECP in cryptography and TLS is defined in + * Standards for Efficient Cryptography Group (SECG): SEC1 + * Elliptic Curve Cryptography and + * RFC-4492: Elliptic Curve Cryptography (ECC) Cipher Suites + * for Transport Layer Security (TLS). + * + * RFC-2409: The Internet Key Exchange (IKE) defines ECP + * group types. + * + */ + +/* + * Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of Mbed TLS (https://tls.mbed.org) + */ + +#ifndef MBEDTLS_ECP_H +#define MBEDTLS_ECP_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include "bignum.h" + +/* + * ECP error codes + */ +#define MBEDTLS_ERR_ECP_BAD_INPUT_DATA -0x4F80 /**< Bad input parameters to function. */ +#define MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL -0x4F00 /**< The buffer is too small to write to. */ +#define MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE -0x4E80 /**< The requested feature is not available, for example, the requested curve is not supported. */ +#define MBEDTLS_ERR_ECP_VERIFY_FAILED -0x4E00 /**< The signature is not valid. */ +#define MBEDTLS_ERR_ECP_ALLOC_FAILED -0x4D80 /**< Memory allocation failed. */ +#define MBEDTLS_ERR_ECP_RANDOM_FAILED -0x4D00 /**< Generation of random value, such as ephemeral key, failed. */ +#define MBEDTLS_ERR_ECP_INVALID_KEY -0x4C80 /**< Invalid private or public key. */ +#define MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH -0x4C00 /**< The buffer contains a valid signature followed by more data. */ + +/* MBEDTLS_ERR_ECP_HW_ACCEL_FAILED is deprecated and should not be used. */ +#define MBEDTLS_ERR_ECP_HW_ACCEL_FAILED -0x4B80 /**< The ECP hardware accelerator failed. */ + +#define MBEDTLS_ERR_ECP_IN_PROGRESS -0x4B00 /**< Operation in progress, call again with the same parameters to continue. */ + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Domain-parameter identifiers: curve, subgroup, and generator. + * + * \note Only curves over prime fields are supported. + * + * \warning This library does not support validation of arbitrary domain + * parameters. Therefore, only standardized domain parameters from trusted + * sources should be used. See mbedtls_ecp_group_load(). + */ +typedef enum +{ + MBEDTLS_ECP_DP_NONE = 0, /*!< Curve not defined. */ + MBEDTLS_ECP_DP_SECP192R1, /*!< Domain parameters for the 192-bit curve defined by FIPS 186-4 and SEC1. */ + MBEDTLS_ECP_DP_SECP224R1, /*!< Domain parameters for the 224-bit curve defined by FIPS 186-4 and SEC1. */ + MBEDTLS_ECP_DP_SECP256R1, /*!< Domain parameters for the 256-bit curve defined by FIPS 186-4 and SEC1. */ + MBEDTLS_ECP_DP_SECP384R1, /*!< Domain parameters for the 384-bit curve defined by FIPS 186-4 and SEC1. */ + MBEDTLS_ECP_DP_SECP521R1, /*!< Domain parameters for the 521-bit curve defined by FIPS 186-4 and SEC1. */ + MBEDTLS_ECP_DP_BP256R1, /*!< Domain parameters for 256-bit Brainpool curve. */ + MBEDTLS_ECP_DP_BP384R1, /*!< Domain parameters for 384-bit Brainpool curve. */ + MBEDTLS_ECP_DP_BP512R1, /*!< Domain parameters for 512-bit Brainpool curve. */ + MBEDTLS_ECP_DP_CURVE25519, /*!< Domain parameters for Curve25519. */ + MBEDTLS_ECP_DP_SECP192K1, /*!< Domain parameters for 192-bit "Koblitz" curve. */ + MBEDTLS_ECP_DP_SECP224K1, /*!< Domain parameters for 224-bit "Koblitz" curve. */ + MBEDTLS_ECP_DP_SECP256K1, /*!< Domain parameters for 256-bit "Koblitz" curve. */ + MBEDTLS_ECP_DP_CURVE448, /*!< Domain parameters for Curve448. */ +} mbedtls_ecp_group_id; + +/** + * The number of supported curves, plus one for #MBEDTLS_ECP_DP_NONE. + * + * \note Montgomery curves are currently excluded. + */ +#define MBEDTLS_ECP_DP_MAX 12 + +/** + * Curve information, for use by other modules. + */ +typedef struct mbedtls_ecp_curve_info +{ + mbedtls_ecp_group_id grp_id; /*!< An internal identifier. */ + uint16_t tls_id; /*!< The TLS NamedCurve identifier. */ + uint16_t bit_size; /*!< The curve size in bits. */ + const char *name; /*!< A human-friendly name. */ +} mbedtls_ecp_curve_info; + +/** + * \brief The ECP point structure, in Jacobian coordinates. + * + * \note All functions expect and return points satisfying + * the following condition: Z == 0 or + * Z == 1. Other values of \p Z are + * used only by internal functions. + * The point is zero, or "at infinity", if Z == 0. + * Otherwise, \p X and \p Y are its standard (affine) + * coordinates. + */ +typedef struct mbedtls_ecp_point +{ + mbedtls_mpi X; /*!< The X coordinate of the ECP point. */ + mbedtls_mpi Y; /*!< The Y coordinate of the ECP point. */ + mbedtls_mpi Z; /*!< The Z coordinate of the ECP point. */ +} +mbedtls_ecp_point; + +#if !defined(MBEDTLS_ECP_ALT) +/* + * default mbed TLS elliptic curve arithmetic implementation + * + * (in case MBEDTLS_ECP_ALT is defined then the developer has to provide an + * alternative implementation for the whole module and it will replace this + * one.) + */ + +/** + * \brief The ECP group structure. + * + * We consider two types of curve equations: + *
                            • Short Weierstrass: y^2 = x^3 + A x + B mod P + * (SEC1 + RFC-4492)
                            • + *
                            • Montgomery: y^2 = x^3 + A x^2 + x mod P (Curve25519, + * Curve448)
                            + * In both cases, the generator (\p G) for a prime-order subgroup is fixed. + * + * For Short Weierstrass, this subgroup is the whole curve, and its + * cardinality is denoted by \p N. Our code requires that \p N is an + * odd prime as mbedtls_ecp_mul() requires an odd number, and + * mbedtls_ecdsa_sign() requires that it is prime for blinding purposes. + * + * For Montgomery curves, we do not store \p A, but (A + 2) / 4, + * which is the quantity used in the formulas. Additionally, \p nbits is + * not the size of \p N but the required size for private keys. + * + * If \p modp is NULL, reduction modulo \p P is done using a generic algorithm. + * Otherwise, \p modp must point to a function that takes an \p mbedtls_mpi in the + * range of 0..2^(2*pbits)-1, and transforms it in-place to an integer + * which is congruent mod \p P to the given MPI, and is close enough to \p pbits + * in size, so that it may be efficiently brought in the 0..P-1 range by a few + * additions or subtractions. Therefore, it is only an approximative modular + * reduction. It must return 0 on success and non-zero on failure. + * + * \note Alternative implementations must keep the group IDs distinct. If + * two group structures have the same ID, then they must be + * identical. + * + */ +typedef struct mbedtls_ecp_group +{ + mbedtls_ecp_group_id id; /*!< An internal group identifier. */ + mbedtls_mpi P; /*!< The prime modulus of the base field. */ + mbedtls_mpi A; /*!< For Short Weierstrass: \p A in the equation. For + Montgomery curves: (A + 2) / 4. */ + mbedtls_mpi B; /*!< For Short Weierstrass: \p B in the equation. + For Montgomery curves: unused. */ + mbedtls_ecp_point G; /*!< The generator of the subgroup used. */ + mbedtls_mpi N; /*!< The order of \p G. */ + size_t pbits; /*!< The number of bits in \p P.*/ + size_t nbits; /*!< For Short Weierstrass: The number of bits in \p P. + For Montgomery curves: the number of bits in the + private keys. */ + unsigned int h; /*!< \internal 1 if the constants are static. */ + int (*modp)(mbedtls_mpi *); /*!< The function for fast pseudo-reduction + mod \p P (see above).*/ + int (*t_pre)(mbedtls_ecp_point *, void *); /*!< Unused. */ + int (*t_post)(mbedtls_ecp_point *, void *); /*!< Unused. */ + void *t_data; /*!< Unused. */ + mbedtls_ecp_point *T; /*!< Pre-computed points for ecp_mul_comb(). */ + size_t T_size; /*!< The number of pre-computed points. */ +} +mbedtls_ecp_group; + +/** + * \name SECTION: Module settings + * + * The configuration options you can set for this module are in this section. + * Either change them in config.h, or define them using the compiler command line. + * \{ + */ + +#if !defined(MBEDTLS_ECP_MAX_BITS) +/** + * The maximum size of the groups, that is, of \c N and \c P. + */ +#define MBEDTLS_ECP_MAX_BITS 521 /**< The maximum size of groups, in bits. */ +#endif + +#define MBEDTLS_ECP_MAX_BYTES ( ( MBEDTLS_ECP_MAX_BITS + 7 ) / 8 ) +#define MBEDTLS_ECP_MAX_PT_LEN ( 2 * MBEDTLS_ECP_MAX_BYTES + 1 ) + +#if !defined(MBEDTLS_ECP_WINDOW_SIZE) +/* + * Maximum "window" size used for point multiplication. + * Default: 6. + * Minimum value: 2. Maximum value: 7. + * + * Result is an array of at most ( 1 << ( MBEDTLS_ECP_WINDOW_SIZE - 1 ) ) + * points used for point multiplication. This value is directly tied to EC + * peak memory usage, so decreasing it by one should roughly cut memory usage + * by two (if large curves are in use). + * + * Reduction in size may reduce speed, but larger curves are impacted first. + * Sample performances (in ECDHE handshakes/s, with FIXED_POINT_OPTIM = 1): + * w-size: 6 5 4 3 2 + * 521 145 141 135 120 97 + * 384 214 209 198 177 146 + * 256 320 320 303 262 226 + * 224 475 475 453 398 342 + * 192 640 640 633 587 476 + */ +#define MBEDTLS_ECP_WINDOW_SIZE 6 /**< The maximum window size used. */ +#endif /* MBEDTLS_ECP_WINDOW_SIZE */ + +#if !defined(MBEDTLS_ECP_FIXED_POINT_OPTIM) +/* + * Trade memory for speed on fixed-point multiplication. + * + * This speeds up repeated multiplication of the generator (that is, the + * multiplication in ECDSA signatures, and half of the multiplications in + * ECDSA verification and ECDHE) by a factor roughly 3 to 4. + * + * The cost is increasing EC peak memory usage by a factor roughly 2. + * + * Change this value to 0 to reduce peak memory usage. + */ +#define MBEDTLS_ECP_FIXED_POINT_OPTIM 1 /**< Enable fixed-point speed-up. */ +#endif /* MBEDTLS_ECP_FIXED_POINT_OPTIM */ + +/* \} name SECTION: Module settings */ + +#else /* MBEDTLS_ECP_ALT */ +#include "ecp_alt.h" +#endif /* MBEDTLS_ECP_ALT */ + +#if defined(MBEDTLS_ECP_RESTARTABLE) + +/** + * \brief Internal restart context for multiplication + * + * \note Opaque struct + */ +typedef struct mbedtls_ecp_restart_mul mbedtls_ecp_restart_mul_ctx; + +/** + * \brief Internal restart context for ecp_muladd() + * + * \note Opaque struct + */ +typedef struct mbedtls_ecp_restart_muladd mbedtls_ecp_restart_muladd_ctx; + +/** + * \brief General context for resuming ECC operations + */ +typedef struct +{ + unsigned ops_done; /*!< current ops count */ + unsigned depth; /*!< call depth (0 = top-level) */ + mbedtls_ecp_restart_mul_ctx *rsm; /*!< ecp_mul_comb() sub-context */ + mbedtls_ecp_restart_muladd_ctx *ma; /*!< ecp_muladd() sub-context */ +} mbedtls_ecp_restart_ctx; + +/* + * Operation counts for restartable functions + */ +#define MBEDTLS_ECP_OPS_CHK 3 /*!< basic ops count for ecp_check_pubkey() */ +#define MBEDTLS_ECP_OPS_DBL 8 /*!< basic ops count for ecp_double_jac() */ +#define MBEDTLS_ECP_OPS_ADD 11 /*!< basic ops count for see ecp_add_mixed() */ +#define MBEDTLS_ECP_OPS_INV 120 /*!< empirical equivalent for mpi_mod_inv() */ + +/** + * \brief Internal; for restartable functions in other modules. + * Check and update basic ops budget. + * + * \param grp Group structure + * \param rs_ctx Restart context + * \param ops Number of basic ops to do + * + * \return \c 0 if doing \p ops basic ops is still allowed, + * \return #MBEDTLS_ERR_ECP_IN_PROGRESS otherwise. + */ +int mbedtls_ecp_check_budget( const mbedtls_ecp_group *grp, + mbedtls_ecp_restart_ctx *rs_ctx, + unsigned ops ); + +/* Utility macro for checking and updating ops budget */ +#define MBEDTLS_ECP_BUDGET( ops ) \ + MBEDTLS_MPI_CHK( mbedtls_ecp_check_budget( grp, rs_ctx, \ + (unsigned) (ops) ) ); + +#else /* MBEDTLS_ECP_RESTARTABLE */ + +#define MBEDTLS_ECP_BUDGET( ops ) /* no-op; for compatibility */ + +/* We want to declare restartable versions of existing functions anyway */ +typedef void mbedtls_ecp_restart_ctx; + +#endif /* MBEDTLS_ECP_RESTARTABLE */ + +/** + * \brief The ECP key-pair structure. + * + * A generic key-pair that may be used for ECDSA and fixed ECDH, for example. + * + * \note Members are deliberately in the same order as in the + * ::mbedtls_ecdsa_context structure. + */ +typedef struct mbedtls_ecp_keypair +{ + mbedtls_ecp_group grp; /*!< Elliptic curve and base point */ + mbedtls_mpi d; /*!< our secret value */ + mbedtls_ecp_point Q; /*!< our public value */ +} +mbedtls_ecp_keypair; + +/* + * Point formats, from RFC 4492's enum ECPointFormat + */ +#define MBEDTLS_ECP_PF_UNCOMPRESSED 0 /**< Uncompressed point format. */ +#define MBEDTLS_ECP_PF_COMPRESSED 1 /**< Compressed point format. */ + +/* + * Some other constants from RFC 4492 + */ +#define MBEDTLS_ECP_TLS_NAMED_CURVE 3 /**< The named_curve of ECCurveType. */ + +#if defined(MBEDTLS_ECP_RESTARTABLE) +/** + * \brief Set the maximum number of basic operations done in a row. + * + * If more operations are needed to complete a computation, + * #MBEDTLS_ERR_ECP_IN_PROGRESS will be returned by the + * function performing the computation. It is then the + * caller's responsibility to either call again with the same + * parameters until it returns 0 or an error code; or to free + * the restart context if the operation is to be aborted. + * + * It is strictly required that all input parameters and the + * restart context be the same on successive calls for the + * same operation, but output parameters need not be the + * same; they must not be used until the function finally + * returns 0. + * + * This only applies to functions whose documentation + * mentions they may return #MBEDTLS_ERR_ECP_IN_PROGRESS (or + * #MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS for functions in the + * SSL module). For functions that accept a "restart context" + * argument, passing NULL disables restart and makes the + * function equivalent to the function with the same name + * with \c _restartable removed. For functions in the ECDH + * module, restart is disabled unless the function accepts + * an "ECDH context" argument and + * mbedtls_ecdh_enable_restart() was previously called on + * that context. For function in the SSL module, restart is + * only enabled for specific sides and key exchanges + * (currently only for clients and ECDHE-ECDSA). + * + * \param max_ops Maximum number of basic operations done in a row. + * Default: 0 (unlimited). + * Lower (non-zero) values mean ECC functions will block for + * a lesser maximum amount of time. + * + * \note A "basic operation" is defined as a rough equivalent of a + * multiplication in GF(p) for the NIST P-256 curve. + * As an indication, with default settings, a scalar + * multiplication (full run of \c mbedtls_ecp_mul()) is: + * - about 3300 basic operations for P-256 + * - about 9400 basic operations for P-384 + * + * \note Very low values are not always respected: sometimes + * functions need to block for a minimum number of + * operations, and will do so even if max_ops is set to a + * lower value. That minimum depends on the curve size, and + * can be made lower by decreasing the value of + * \c MBEDTLS_ECP_WINDOW_SIZE. As an indication, here is the + * lowest effective value for various curves and values of + * that parameter (w for short): + * w=6 w=5 w=4 w=3 w=2 + * P-256 208 208 160 136 124 + * P-384 682 416 320 272 248 + * P-521 1364 832 640 544 496 + * + * \note This setting is currently ignored by Curve25519. + */ +void mbedtls_ecp_set_max_ops( unsigned max_ops ); + +/** + * \brief Check if restart is enabled (max_ops != 0) + * + * \return \c 0 if \c max_ops == 0 (restart disabled) + * \return \c 1 otherwise (restart enabled) + */ +int mbedtls_ecp_restart_is_enabled( void ); +#endif /* MBEDTLS_ECP_RESTARTABLE */ + +/** + * \brief This function retrieves the information defined in + * mbedtls_ecp_curve_info() for all supported curves in order + * of preference. + * + * \return A statically allocated array. The last entry is 0. + */ +const mbedtls_ecp_curve_info *mbedtls_ecp_curve_list( void ); + +/** + * \brief This function retrieves the list of internal group + * identifiers of all supported curves in the order of + * preference. + * + * \return A statically allocated array, + * terminated with MBEDTLS_ECP_DP_NONE. + */ +const mbedtls_ecp_group_id *mbedtls_ecp_grp_id_list( void ); + +/** + * \brief This function retrieves curve information from an internal + * group identifier. + * + * \param grp_id An \c MBEDTLS_ECP_DP_XXX value. + * + * \return The associated curve information on success. + * \return NULL on failure. + */ +const mbedtls_ecp_curve_info *mbedtls_ecp_curve_info_from_grp_id( mbedtls_ecp_group_id grp_id ); + +/** + * \brief This function retrieves curve information from a TLS + * NamedCurve value. + * + * \param tls_id An \c MBEDTLS_ECP_DP_XXX value. + * + * \return The associated curve information on success. + * \return NULL on failure. + */ +const mbedtls_ecp_curve_info *mbedtls_ecp_curve_info_from_tls_id( uint16_t tls_id ); + +/** + * \brief This function retrieves curve information from a + * human-readable name. + * + * \param name The human-readable name. + * + * \return The associated curve information on success. + * \return NULL on failure. + */ +const mbedtls_ecp_curve_info *mbedtls_ecp_curve_info_from_name( const char *name ); + +/** + * \brief This function initializes a point as zero. + * + * \param pt The point to initialize. + */ +void mbedtls_ecp_point_init( mbedtls_ecp_point *pt ); + +/** + * \brief This function initializes an ECP group context + * without loading any domain parameters. + * + * \note After this function is called, domain parameters + * for various ECP groups can be loaded through the + * mbedtls_ecp_group_load() or mbedtls_ecp_tls_read_group() + * functions. + */ +void mbedtls_ecp_group_init( mbedtls_ecp_group *grp ); + +/** + * \brief This function initializes a key pair as an invalid one. + * + * \param key The key pair to initialize. + */ +void mbedtls_ecp_keypair_init( mbedtls_ecp_keypair *key ); + +/** + * \brief This function frees the components of a point. + * + * \param pt The point to free. + */ +void mbedtls_ecp_point_free( mbedtls_ecp_point *pt ); + +/** + * \brief This function frees the components of an ECP group. + * + * \param grp The group to free. This may be \c NULL, in which + * case this function returns immediately. If it is not + * \c NULL, it must point to an initialized ECP group. + */ +void mbedtls_ecp_group_free( mbedtls_ecp_group *grp ); + +/** + * \brief This function frees the components of a key pair. + * + * \param key The key pair to free. This may be \c NULL, in which + * case this function returns immediately. If it is not + * \c NULL, it must point to an initialized ECP key pair. + */ +void mbedtls_ecp_keypair_free( mbedtls_ecp_keypair *key ); + +#if defined(MBEDTLS_ECP_RESTARTABLE) +/** + * \brief Initialize a restart context. + * + * \param ctx The restart context to initialize. This must + * not be \c NULL. + */ +void mbedtls_ecp_restart_init( mbedtls_ecp_restart_ctx *ctx ); + +/** + * \brief Free the components of a restart context. + * + * \param ctx The restart context to free. This may be \c NULL, in which + * case this function returns immediately. If it is not + * \c NULL, it must point to an initialized restart context. + */ +void mbedtls_ecp_restart_free( mbedtls_ecp_restart_ctx *ctx ); +#endif /* MBEDTLS_ECP_RESTARTABLE */ + +/** + * \brief This function copies the contents of point \p Q into + * point \p P. + * + * \param P The destination point. This must be initialized. + * \param Q The source point. This must be initialized. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory-allocation failure. + * \return Another negative error code for other kinds of failure. + */ +int mbedtls_ecp_copy( mbedtls_ecp_point *P, const mbedtls_ecp_point *Q ); + +/** + * \brief This function copies the contents of group \p src into + * group \p dst. + * + * \param dst The destination group. This must be initialized. + * \param src The source group. This must be initialized. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory-allocation failure. + * \return Another negative error code on other kinds of failure. + */ +int mbedtls_ecp_group_copy( mbedtls_ecp_group *dst, + const mbedtls_ecp_group *src ); + +/** + * \brief This function sets a point to the point at infinity. + * + * \param pt The point to set. This must be initialized. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory-allocation failure. + * \return Another negative error code on other kinds of failure. + */ +int mbedtls_ecp_set_zero( mbedtls_ecp_point *pt ); + +/** + * \brief This function checks if a point is the point at infinity. + * + * \param pt The point to test. This must be initialized. + * + * \return \c 1 if the point is zero. + * \return \c 0 if the point is non-zero. + * \return A negative error code on failure. + */ +int mbedtls_ecp_is_zero( mbedtls_ecp_point *pt ); + +/** + * \brief This function compares two points. + * + * \note This assumes that the points are normalized. Otherwise, + * they may compare as "not equal" even if they are. + * + * \param P The first point to compare. This must be initialized. + * \param Q The second point to compare. This must be initialized. + * + * \return \c 0 if the points are equal. + * \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if the points are not equal. + */ +int mbedtls_ecp_point_cmp( const mbedtls_ecp_point *P, + const mbedtls_ecp_point *Q ); + +/** + * \brief This function imports a non-zero point from two ASCII + * strings. + * + * \param P The destination point. This must be initialized. + * \param radix The numeric base of the input. + * \param x The first affine coordinate, as a null-terminated string. + * \param y The second affine coordinate, as a null-terminated string. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_MPI_XXX error code on failure. + */ +int mbedtls_ecp_point_read_string( mbedtls_ecp_point *P, int radix, + const char *x, const char *y ); + +/** + * \brief This function exports a point into unsigned binary data. + * + * \param grp The group to which the point should belong. + * This must be initialized and have group parameters + * set, for example through mbedtls_ecp_group_load(). + * \param P The point to export. This must be initialized. + * \param format The point format. This must be either + * #MBEDTLS_ECP_PF_COMPRESSED or #MBEDTLS_ECP_PF_UNCOMPRESSED. + * \param olen The address at which to store the length of + * the output in Bytes. This must not be \c NULL. + * \param buf The output buffer. This must be a writable buffer + * of length \p buflen Bytes. + * \param buflen The length of the output buffer \p buf in Bytes. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL if the output buffer + * is too small to hold the point. + * \return Another negative error code on other kinds of failure. + */ +int mbedtls_ecp_point_write_binary( const mbedtls_ecp_group *grp, const mbedtls_ecp_point *P, + int format, size_t *olen, + unsigned char *buf, size_t buflen ); + +/** + * \brief This function imports a point from unsigned binary data. + * + * \note This function does not check that the point actually + * belongs to the given group, see mbedtls_ecp_check_pubkey() + * for that. + * + * \param grp The group to which the point should belong. + * This must be initialized and have group parameters + * set, for example through mbedtls_ecp_group_load(). + * \param P The destination context to import the point to. + * This must be initialized. + * \param buf The input buffer. This must be a readable buffer + * of length \p ilen Bytes. + * \param ilen The length of the input buffer \p buf in Bytes. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if the input is invalid. + * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory-allocation failure. + * \return #MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE if the point format + * is not implemented. + */ +int mbedtls_ecp_point_read_binary( const mbedtls_ecp_group *grp, + mbedtls_ecp_point *P, + const unsigned char *buf, size_t ilen ); + +/** + * \brief This function imports a point from a TLS ECPoint record. + * + * \note On function return, \p *buf is updated to point immediately + * after the ECPoint record. + * + * \param grp The ECP group to use. + * This must be initialized and have group parameters + * set, for example through mbedtls_ecp_group_load(). + * \param pt The destination point. + * \param buf The address of the pointer to the start of the input buffer. + * \param len The length of the buffer. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_MPI_XXX error code on initialization + * failure. + * \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if input is invalid. + */ +int mbedtls_ecp_tls_read_point( const mbedtls_ecp_group *grp, + mbedtls_ecp_point *pt, + const unsigned char **buf, size_t len ); + +/** + * \brief This function exports a point as a TLS ECPoint record + * defined in RFC 4492, Section 5.4. + * + * \param grp The ECP group to use. + * This must be initialized and have group parameters + * set, for example through mbedtls_ecp_group_load(). + * \param pt The point to be exported. This must be initialized. + * \param format The point format to use. This must be either + * #MBEDTLS_ECP_PF_COMPRESSED or #MBEDTLS_ECP_PF_UNCOMPRESSED. + * \param olen The address at which to store the length in Bytes + * of the data written. + * \param buf The target buffer. This must be a writable buffer of + * length \p blen Bytes. + * \param blen The length of the target buffer \p buf in Bytes. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if the input is invalid. + * \return #MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL if the target buffer + * is too small to hold the exported point. + * \return Another negative error code on other kinds of failure. + */ +int mbedtls_ecp_tls_write_point( const mbedtls_ecp_group *grp, + const mbedtls_ecp_point *pt, + int format, size_t *olen, + unsigned char *buf, size_t blen ); + +/** + * \brief This function sets up an ECP group context + * from a standardized set of domain parameters. + * + * \note The index should be a value of the NamedCurve enum, + * as defined in RFC-4492: Elliptic Curve Cryptography + * (ECC) Cipher Suites for Transport Layer Security (TLS), + * usually in the form of an \c MBEDTLS_ECP_DP_XXX macro. + * + * \param grp The group context to setup. This must be initialized. + * \param id The identifier of the domain parameter set to load. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE if \p id doesn't + * correspond to a known group. + * \return Another negative error code on other kinds of failure. + */ +int mbedtls_ecp_group_load( mbedtls_ecp_group *grp, mbedtls_ecp_group_id id ); + +/** + * \brief This function sets up an ECP group context from a TLS + * ECParameters record as defined in RFC 4492, Section 5.4. + * + * \note The read pointer \p buf is updated to point right after + * the ECParameters record on exit. + * + * \param grp The group context to setup. This must be initialized. + * \param buf The address of the pointer to the start of the input buffer. + * \param len The length of the input buffer \c *buf in Bytes. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if input is invalid. + * \return #MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE if the group is not + * recognized. + * \return Another negative error code on other kinds of failure. + */ +int mbedtls_ecp_tls_read_group( mbedtls_ecp_group *grp, + const unsigned char **buf, size_t len ); + +/** + * \brief This function extracts an elliptic curve group ID from a + * TLS ECParameters record as defined in RFC 4492, Section 5.4. + * + * \note The read pointer \p buf is updated to point right after + * the ECParameters record on exit. + * + * \param grp The address at which to store the group id. + * This must not be \c NULL. + * \param buf The address of the pointer to the start of the input buffer. + * \param len The length of the input buffer \c *buf in Bytes. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if input is invalid. + * \return #MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE if the group is not + * recognized. + * \return Another negative error code on other kinds of failure. + */ +int mbedtls_ecp_tls_read_group_id( mbedtls_ecp_group_id *grp, + const unsigned char **buf, + size_t len ); +/** + * \brief This function exports an elliptic curve as a TLS + * ECParameters record as defined in RFC 4492, Section 5.4. + * + * \param grp The ECP group to be exported. + * This must be initialized and have group parameters + * set, for example through mbedtls_ecp_group_load(). + * \param olen The address at which to store the number of Bytes written. + * This must not be \c NULL. + * \param buf The buffer to write to. This must be a writable buffer + * of length \p blen Bytes. + * \param blen The length of the output buffer \p buf in Bytes. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL if the output + * buffer is too small to hold the exported group. + * \return Another negative error code on other kinds of failure. + */ +int mbedtls_ecp_tls_write_group( const mbedtls_ecp_group *grp, + size_t *olen, + unsigned char *buf, size_t blen ); + +/** + * \brief This function performs a scalar multiplication of a point + * by an integer: \p R = \p m * \p P. + * + * It is not thread-safe to use same group in multiple threads. + * + * \note To prevent timing attacks, this function + * executes the exact same sequence of base-field + * operations for any valid \p m. It avoids any if-branch or + * array index depending on the value of \p m. + * + * \note If \p f_rng is not NULL, it is used to randomize + * intermediate results to prevent potential timing attacks + * targeting these results. We recommend always providing + * a non-NULL \p f_rng. The overhead is negligible. + * + * \param grp The ECP group to use. + * This must be initialized and have group parameters + * set, for example through mbedtls_ecp_group_load(). + * \param R The point in which to store the result of the calculation. + * This must be initialized. + * \param m The integer by which to multiply. This must be initialized. + * \param P The point to multiply. This must be initialized. + * \param f_rng The RNG function. This may be \c NULL if randomization + * of intermediate results isn't desired (discouraged). + * \param p_rng The RNG context to be passed to \p p_rng. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_ECP_INVALID_KEY if \p m is not a valid private + * key, or \p P is not a valid public key. + * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory-allocation failure. + * \return Another negative error code on other kinds of failure. + */ +int mbedtls_ecp_mul( mbedtls_ecp_group *grp, mbedtls_ecp_point *R, + const mbedtls_mpi *m, const mbedtls_ecp_point *P, + int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ); + +/** + * \brief This function performs multiplication of a point by + * an integer: \p R = \p m * \p P in a restartable way. + * + * \see mbedtls_ecp_mul() + * + * \note This function does the same as \c mbedtls_ecp_mul(), but + * it can return early and restart according to the limit set + * with \c mbedtls_ecp_set_max_ops() to reduce blocking. + * + * \param grp The ECP group to use. + * This must be initialized and have group parameters + * set, for example through mbedtls_ecp_group_load(). + * \param R The point in which to store the result of the calculation. + * This must be initialized. + * \param m The integer by which to multiply. This must be initialized. + * \param P The point to multiply. This must be initialized. + * \param f_rng The RNG function. This may be \c NULL if randomization + * of intermediate results isn't desired (discouraged). + * \param p_rng The RNG context to be passed to \p p_rng. + * \param rs_ctx The restart context (NULL disables restart). + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_ECP_INVALID_KEY if \p m is not a valid private + * key, or \p P is not a valid public key. + * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory-allocation failure. + * \return #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of + * operations was reached: see \c mbedtls_ecp_set_max_ops(). + * \return Another negative error code on other kinds of failure. + */ +int mbedtls_ecp_mul_restartable( mbedtls_ecp_group *grp, mbedtls_ecp_point *R, + const mbedtls_mpi *m, const mbedtls_ecp_point *P, + int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, + mbedtls_ecp_restart_ctx *rs_ctx ); + +/** + * \brief This function performs multiplication and addition of two + * points by integers: \p R = \p m * \p P + \p n * \p Q + * + * It is not thread-safe to use same group in multiple threads. + * + * \note In contrast to mbedtls_ecp_mul(), this function does not + * guarantee a constant execution flow and timing. + * + * \param grp The ECP group to use. + * This must be initialized and have group parameters + * set, for example through mbedtls_ecp_group_load(). + * \param R The point in which to store the result of the calculation. + * This must be initialized. + * \param m The integer by which to multiply \p P. + * This must be initialized. + * \param P The point to multiply by \p m. This must be initialized. + * \param n The integer by which to multiply \p Q. + * This must be initialized. + * \param Q The point to be multiplied by \p n. + * This must be initialized. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_ECP_INVALID_KEY if \p m or \p n are not + * valid private keys, or \p P or \p Q are not valid public + * keys. + * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory-allocation failure. + * \return Another negative error code on other kinds of failure. + */ +int mbedtls_ecp_muladd( mbedtls_ecp_group *grp, mbedtls_ecp_point *R, + const mbedtls_mpi *m, const mbedtls_ecp_point *P, + const mbedtls_mpi *n, const mbedtls_ecp_point *Q ); + +/** + * \brief This function performs multiplication and addition of two + * points by integers: \p R = \p m * \p P + \p n * \p Q in a + * restartable way. + * + * \see \c mbedtls_ecp_muladd() + * + * \note This function works the same as \c mbedtls_ecp_muladd(), + * but it can return early and restart according to the limit + * set with \c mbedtls_ecp_set_max_ops() to reduce blocking. + * + * \param grp The ECP group to use. + * This must be initialized and have group parameters + * set, for example through mbedtls_ecp_group_load(). + * \param R The point in which to store the result of the calculation. + * This must be initialized. + * \param m The integer by which to multiply \p P. + * This must be initialized. + * \param P The point to multiply by \p m. This must be initialized. + * \param n The integer by which to multiply \p Q. + * This must be initialized. + * \param Q The point to be multiplied by \p n. + * This must be initialized. + * \param rs_ctx The restart context (NULL disables restart). + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_ECP_INVALID_KEY if \p m or \p n are not + * valid private keys, or \p P or \p Q are not valid public + * keys. + * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory-allocation failure. + * \return #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of + * operations was reached: see \c mbedtls_ecp_set_max_ops(). + * \return Another negative error code on other kinds of failure. + */ +int mbedtls_ecp_muladd_restartable( + mbedtls_ecp_group *grp, mbedtls_ecp_point *R, + const mbedtls_mpi *m, const mbedtls_ecp_point *P, + const mbedtls_mpi *n, const mbedtls_ecp_point *Q, + mbedtls_ecp_restart_ctx *rs_ctx ); + +/** + * \brief This function checks that a point is a valid public key + * on this curve. + * + * It only checks that the point is non-zero, has + * valid coordinates and lies on the curve. It does not verify + * that it is indeed a multiple of \p G. This additional + * check is computationally more expensive, is not required + * by standards, and should not be necessary if the group + * used has a small cofactor. In particular, it is useless for + * the NIST groups which all have a cofactor of 1. + * + * \note This function uses bare components rather than an + * ::mbedtls_ecp_keypair structure, to ease use with other + * structures, such as ::mbedtls_ecdh_context or + * ::mbedtls_ecdsa_context. + * + * \param grp The ECP group the point should belong to. + * This must be initialized and have group parameters + * set, for example through mbedtls_ecp_group_load(). + * \param pt The point to check. This must be initialized. + * + * \return \c 0 if the point is a valid public key. + * \return #MBEDTLS_ERR_ECP_INVALID_KEY if the point is not + * a valid public key for the given curve. + * \return Another negative error code on other kinds of failure. + */ +int mbedtls_ecp_check_pubkey( const mbedtls_ecp_group *grp, + const mbedtls_ecp_point *pt ); + +/** + * \brief This function checks that an \p mbedtls_mpi is a + * valid private key for this curve. + * + * \note This function uses bare components rather than an + * ::mbedtls_ecp_keypair structure to ease use with other + * structures, such as ::mbedtls_ecdh_context or + * ::mbedtls_ecdsa_context. + * + * \param grp The ECP group the private key should belong to. + * This must be initialized and have group parameters + * set, for example through mbedtls_ecp_group_load(). + * \param d The integer to check. This must be initialized. + * + * \return \c 0 if the point is a valid private key. + * \return #MBEDTLS_ERR_ECP_INVALID_KEY if the point is not a valid + * private key for the given curve. + * \return Another negative error code on other kinds of failure. + */ +int mbedtls_ecp_check_privkey( const mbedtls_ecp_group *grp, + const mbedtls_mpi *d ); + +/** + * \brief This function generates a private key. + * + * \param grp The ECP group to generate a private key for. + * This must be initialized and have group parameters + * set, for example through mbedtls_ecp_group_load(). + * \param d The destination MPI (secret part). This must be initialized. + * \param f_rng The RNG function. This must not be \c NULL. + * \param p_rng The RNG parameter to be passed to \p f_rng. This may be + * \c NULL if \p f_rng doesn't need a context argument. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_ECP_XXX or \c MBEDTLS_MPI_XXX error code + * on failure. + */ +int mbedtls_ecp_gen_privkey( const mbedtls_ecp_group *grp, + mbedtls_mpi *d, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng ); + +/** + * \brief This function generates a keypair with a configurable base + * point. + * + * \note This function uses bare components rather than an + * ::mbedtls_ecp_keypair structure to ease use with other + * structures, such as ::mbedtls_ecdh_context or + * ::mbedtls_ecdsa_context. + * + * \param grp The ECP group to generate a key pair for. + * This must be initialized and have group parameters + * set, for example through mbedtls_ecp_group_load(). + * \param G The base point to use. This must be initialized + * and belong to \p grp. It replaces the default base + * point \c grp->G used by mbedtls_ecp_gen_keypair(). + * \param d The destination MPI (secret part). + * This must be initialized. + * \param Q The destination point (public part). + * This must be initialized. + * \param f_rng The RNG function. This must not be \c NULL. + * \param p_rng The RNG context to be passed to \p f_rng. This may + * be \c NULL if \p f_rng doesn't need a context argument. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_ECP_XXX or \c MBEDTLS_MPI_XXX error code + * on failure. + */ +int mbedtls_ecp_gen_keypair_base( mbedtls_ecp_group *grp, + const mbedtls_ecp_point *G, + mbedtls_mpi *d, mbedtls_ecp_point *Q, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng ); + +/** + * \brief This function generates an ECP keypair. + * + * \note This function uses bare components rather than an + * ::mbedtls_ecp_keypair structure to ease use with other + * structures, such as ::mbedtls_ecdh_context or + * ::mbedtls_ecdsa_context. + * + * \param grp The ECP group to generate a key pair for. + * This must be initialized and have group parameters + * set, for example through mbedtls_ecp_group_load(). + * \param d The destination MPI (secret part). + * This must be initialized. + * \param Q The destination point (public part). + * This must be initialized. + * \param f_rng The RNG function. This must not be \c NULL. + * \param p_rng The RNG context to be passed to \p f_rng. This may + * be \c NULL if \p f_rng doesn't need a context argument. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_ECP_XXX or \c MBEDTLS_MPI_XXX error code + * on failure. + */ +int mbedtls_ecp_gen_keypair( mbedtls_ecp_group *grp, mbedtls_mpi *d, + mbedtls_ecp_point *Q, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng ); + +/** + * \brief This function generates an ECP key. + * + * \param grp_id The ECP group identifier. + * \param key The destination key. This must be initialized. + * \param f_rng The RNG function to use. This must not be \c NULL. + * \param p_rng The RNG context to be passed to \p f_rng. This may + * be \c NULL if \p f_rng doesn't need a context argument. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_ECP_XXX or \c MBEDTLS_MPI_XXX error code + * on failure. + */ +int mbedtls_ecp_gen_key( mbedtls_ecp_group_id grp_id, mbedtls_ecp_keypair *key, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng ); + +/** + * \brief This function checks that the keypair objects + * \p pub and \p prv have the same group and the + * same public point, and that the private key in + * \p prv is consistent with the public key. + * + * \param pub The keypair structure holding the public key. This + * must be initialized. If it contains a private key, that + * part is ignored. + * \param prv The keypair structure holding the full keypair. + * This must be initialized. + * + * \return \c 0 on success, meaning that the keys are valid and match. + * \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if the keys are invalid or do not match. + * \return An \c MBEDTLS_ERR_ECP_XXX or an \c MBEDTLS_ERR_MPI_XXX + * error code on calculation failure. + */ +int mbedtls_ecp_check_pub_priv( const mbedtls_ecp_keypair *pub, + const mbedtls_ecp_keypair *prv ); + +#if defined(MBEDTLS_SELF_TEST) + +/** + * \brief The ECP checkup routine. + * + * \return \c 0 on success. + * \return \c 1 on failure. + */ +int mbedtls_ecp_self_test( int verbose ); + +#endif /* MBEDTLS_SELF_TEST */ + +#ifdef __cplusplus +} +#endif + +#endif /* ecp.h */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/ecp_alt.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/ecp_alt.h new file mode 100644 index 0000000000000000000000000000000000000000..6bdc481955230c57c4553a0672d8c59f022aa927 --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/ecp_alt.h @@ -0,0 +1,165 @@ +/** + * \file ecp.h + * + * \brief This file provides an API for Elliptic Curves over GF(P) (ECP). + * + * The use of ECP in cryptography and TLS is defined in + * Standards for Efficient Cryptography Group (SECG): SEC1 + * Elliptic Curve Cryptography and + * RFC-4492: Elliptic Curve Cryptography (ECC) Cipher Suites + * for Transport Layer Security (TLS). + * + * RFC-2409: The Internet Key Exchange (IKE) defines ECP + * group types. + * + */ + +/* + * Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of Mbed TLS (https://tls.mbed.org) + */ + +#ifndef MBEDTLS_ECP_ALT_H +#define MBEDTLS_ECP_ALT_H + +#if defined(MBEDTLS_ECP_ALT) +/* + * default mbed TLS elliptic curve arithmetic implementation + * + * (in case MBEDTLS_ECP_ALT is defined then the developer has to provide an + * alternative implementation for the whole module and it will replace this + * one.) + */ + +/** + * \brief The ECP group structure. + * + * We consider two types of curve equations: + *
                            • Short Weierstrass: y^2 = x^3 + A x + B mod P + * (SEC1 + RFC-4492)
                            • + *
                            • Montgomery: y^2 = x^3 + A x^2 + x mod P (Curve25519, + * Curve448)
                            + * In both cases, the generator (\p G) for a prime-order subgroup is fixed. + * + * For Short Weierstrass, this subgroup is the whole curve, and its + * cardinality is denoted by \p N. Our code requires that \p N is an + * odd prime as mbedtls_ecp_mul() requires an odd number, and + * mbedtls_ecdsa_sign() requires that it is prime for blinding purposes. + * + * For Montgomery curves, we do not store \p A, but (A + 2) / 4, + * which is the quantity used in the formulas. Additionally, \p nbits is + * not the size of \p N but the required size for private keys. + * + * If \p modp is NULL, reduction modulo \p P is done using a generic algorithm. + * Otherwise, \p modp must point to a function that takes an \p mbedtls_mpi in the + * range of 0..2^(2*pbits)-1, and transforms it in-place to an integer + * which is congruent mod \p P to the given MPI, and is close enough to \p pbits + * in size, so that it may be efficiently brought in the 0..P-1 range by a few + * additions or subtractions. Therefore, it is only an approximative modular + * reduction. It must return 0 on success and non-zero on failure. + * + * \note Alternative implementations must keep the group IDs distinct. If + * two group structures have the same ID, then they must be + * identical. + * + */ +typedef struct mbedtls_ecp_group +{ + mbedtls_ecp_group_id id; /*!< An internal group identifier. */ + mbedtls_mpi P; /*!< The prime modulus of the base field. */ + mbedtls_mpi A; /*!< For Short Weierstrass: \p A in the equation. For + Montgomery curves: (A + 2) / 4. */ + mbedtls_mpi B; /*!< For Short Weierstrass: \p B in the equation. + For Montgomery curves: unused. */ + mbedtls_ecp_point G; /*!< The generator of the subgroup used. */ + mbedtls_mpi N; /*!< The order of \p G. */ + size_t pbits; /*!< The number of bits in \p P.*/ + size_t nbits; /*!< For Short Weierstrass: The number of bits in \p P. + For Montgomery curves: the number of bits in the + private keys. */ + unsigned int h; /*!< \internal 1 if the constants are static. */ + int (*modp)(mbedtls_mpi *); /*!< The function for fast pseudo-reduction + mod \p P (see above).*/ + int (*t_pre)(mbedtls_ecp_point *, void *); /*!< Unused. */ + int (*t_post)(mbedtls_ecp_point *, void *); /*!< Unused. */ + void *t_data; /*!< Unused. */ + mbedtls_ecp_point *T; /*!< Pre-computed points for ecp_mul_comb(). */ + size_t T_size; /*!< The number of pre-computed points. */ +} +mbedtls_ecp_group; + +/** + * \name SECTION: Module settings + * + * The configuration options you can set for this module are in this section. + * Either change them in config.h, or define them using the compiler command line. + * \{ + */ + +#if !defined(MBEDTLS_ECP_MAX_BITS) +/** + * The maximum size of the groups, that is, of \c N and \c P. + */ +#define MBEDTLS_ECP_MAX_BITS 521 /**< The maximum size of groups, in bits. */ +#endif + +#define MBEDTLS_ECP_MAX_BYTES ( ( MBEDTLS_ECP_MAX_BITS + 7 ) / 8 ) +#define MBEDTLS_ECP_MAX_PT_LEN ( 2 * MBEDTLS_ECP_MAX_BYTES + 1 ) + +#if !defined(MBEDTLS_ECP_WINDOW_SIZE) +/* + * Maximum "window" size used for point multiplication. + * Default: 6. + * Minimum value: 2. Maximum value: 7. + * + * Result is an array of at most ( 1 << ( MBEDTLS_ECP_WINDOW_SIZE - 1 ) ) + * points used for point multiplication. This value is directly tied to EC + * peak memory usage, so decreasing it by one should roughly cut memory usage + * by two (if large curves are in use). + * + * Reduction in size may reduce speed, but larger curves are impacted first. + * Sample performances (in ECDHE handshakes/s, with FIXED_POINT_OPTIM = 1): + * w-size: 6 5 4 3 2 + * 521 145 141 135 120 97 + * 384 214 209 198 177 146 + * 256 320 320 303 262 226 + * 224 475 475 453 398 342 + * 192 640 640 633 587 476 + */ +#define MBEDTLS_ECP_WINDOW_SIZE 6 /**< The maximum window size used. */ +#endif /* MBEDTLS_ECP_WINDOW_SIZE */ + +#if !defined(MBEDTLS_ECP_FIXED_POINT_OPTIM) +/* + * Trade memory for speed on fixed-point multiplication. + * + * This speeds up repeated multiplication of the generator (that is, the + * multiplication in ECDSA signatures, and half of the multiplications in + * ECDSA verification and ECDHE) by a factor roughly 3 to 4. + * + * The cost is increasing EC peak memory usage by a factor roughly 2. + * + * Change this value to 0 to reduce peak memory usage. + */ +#define MBEDTLS_ECP_FIXED_POINT_OPTIM 1 /**< Enable fixed-point speed-up. */ +#endif /* MBEDTLS_ECP_FIXED_POINT_OPTIM */ + +/* \} name SECTION: Module settings */ + +#endif /* MBEDTLS_ECP_ALT */ + +#endif /* ecp_alt.h */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/ecp_internal.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/ecp_internal.h new file mode 100644 index 0000000000000000000000000000000000000000..7625ed48e1afc2ae3c41b15f0ee84db031bcec3d --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/ecp_internal.h @@ -0,0 +1,299 @@ +/** + * \file ecp_internal.h + * + * \brief Function declarations for alternative implementation of elliptic curve + * point arithmetic. + */ +/* + * Copyright (C) 2016, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ + +/* + * References: + * + * [1] BERNSTEIN, Daniel J. Curve25519: new Diffie-Hellman speed records. + * + * + * [2] CORON, Jean-S'ebastien. Resistance against differential power analysis + * for elliptic curve cryptosystems. In : Cryptographic Hardware and + * Embedded Systems. Springer Berlin Heidelberg, 1999. p. 292-302. + * + * + * [3] HEDABOU, Mustapha, PINEL, Pierre, et B'EN'ETEAU, Lucien. A comb method to + * render ECC resistant against Side Channel Attacks. IACR Cryptology + * ePrint Archive, 2004, vol. 2004, p. 342. + * + * + * [4] Certicom Research. SEC 2: Recommended Elliptic Curve Domain Parameters. + * + * + * [5] HANKERSON, Darrel, MENEZES, Alfred J., VANSTONE, Scott. Guide to Elliptic + * Curve Cryptography. + * + * [6] Digital Signature Standard (DSS), FIPS 186-4. + * + * + * [7] Elliptic Curve Cryptography (ECC) Cipher Suites for Transport Layer + * Security (TLS), RFC 4492. + * + * + * [8] + * + * [9] COHEN, Henri. A Course in Computational Algebraic Number Theory. + * Springer Science & Business Media, 1 Aug 2000 + */ + +#ifndef MBEDTLS_ECP_INTERNAL_H +#define MBEDTLS_ECP_INTERNAL_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#if defined(MBEDTLS_ECP_INTERNAL_ALT) + +/** + * \brief Indicate if the Elliptic Curve Point module extension can + * handle the group. + * + * \param grp The pointer to the elliptic curve group that will be the + * basis of the cryptographic computations. + * + * \return Non-zero if successful. + */ +unsigned char mbedtls_internal_ecp_grp_capable( const mbedtls_ecp_group *grp ); + +/** + * \brief Initialise the Elliptic Curve Point module extension. + * + * If mbedtls_internal_ecp_grp_capable returns true for a + * group, this function has to be able to initialise the + * module for it. + * + * This module can be a driver to a crypto hardware + * accelerator, for which this could be an initialise function. + * + * \param grp The pointer to the group the module needs to be + * initialised for. + * + * \return 0 if successful. + */ +int mbedtls_internal_ecp_init( const mbedtls_ecp_group *grp ); + +/** + * \brief Frees and deallocates the Elliptic Curve Point module + * extension. + * + * \param grp The pointer to the group the module was initialised for. + */ +void mbedtls_internal_ecp_free( const mbedtls_ecp_group *grp ); + +#if defined(ECP_SHORTWEIERSTRASS) + +#if defined(MBEDTLS_ECP_RANDOMIZE_JAC_ALT) +/** + * \brief Randomize jacobian coordinates: + * (X, Y, Z) -> (l^2 X, l^3 Y, l Z) for random l. + * + * \param grp Pointer to the group representing the curve. + * + * \param pt The point on the curve to be randomised, given with Jacobian + * coordinates. + * + * \param f_rng A function pointer to the random number generator. + * + * \param p_rng A pointer to the random number generator state. + * + * \return 0 if successful. + */ +int mbedtls_internal_ecp_randomize_jac( const mbedtls_ecp_group *grp, + mbedtls_ecp_point *pt, int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng ); +#endif + +#if defined(MBEDTLS_ECP_ADD_MIXED_ALT) +/** + * \brief Addition: R = P + Q, mixed affine-Jacobian coordinates. + * + * The coordinates of Q must be normalized (= affine), + * but those of P don't need to. R is not normalized. + * + * This function is used only as a subrutine of + * ecp_mul_comb(). + * + * Special cases: (1) P or Q is zero, (2) R is zero, + * (3) P == Q. + * None of these cases can happen as intermediate step in + * ecp_mul_comb(): + * - at each step, P, Q and R are multiples of the base + * point, the factor being less than its order, so none of + * them is zero; + * - Q is an odd multiple of the base point, P an even + * multiple, due to the choice of precomputed points in the + * modified comb method. + * So branches for these cases do not leak secret information. + * + * We accept Q->Z being unset (saving memory in tables) as + * meaning 1. + * + * Cost in field operations if done by [5] 3.22: + * 1A := 8M + 3S + * + * \param grp Pointer to the group representing the curve. + * + * \param R Pointer to a point structure to hold the result. + * + * \param P Pointer to the first summand, given with Jacobian + * coordinates + * + * \param Q Pointer to the second summand, given with affine + * coordinates. + * + * \return 0 if successful. + */ +int mbedtls_internal_ecp_add_mixed( const mbedtls_ecp_group *grp, + mbedtls_ecp_point *R, const mbedtls_ecp_point *P, + const mbedtls_ecp_point *Q ); +#endif + +/** + * \brief Point doubling R = 2 P, Jacobian coordinates. + * + * Cost: 1D := 3M + 4S (A == 0) + * 4M + 4S (A == -3) + * 3M + 6S + 1a otherwise + * when the implementation is based on the "dbl-1998-cmo-2" + * doubling formulas in [8] and standard optimizations are + * applied when curve parameter A is one of { 0, -3 }. + * + * \param grp Pointer to the group representing the curve. + * + * \param R Pointer to a point structure to hold the result. + * + * \param P Pointer to the point that has to be doubled, given with + * Jacobian coordinates. + * + * \return 0 if successful. + */ +#if defined(MBEDTLS_ECP_DOUBLE_JAC_ALT) +int mbedtls_internal_ecp_double_jac( const mbedtls_ecp_group *grp, + mbedtls_ecp_point *R, const mbedtls_ecp_point *P ); +#endif + +/** + * \brief Normalize jacobian coordinates of an array of (pointers to) + * points. + * + * Using Montgomery's trick to perform only one inversion mod P + * the cost is: + * 1N(t) := 1I + (6t - 3)M + 1S + * (See for example Algorithm 10.3.4. in [9]) + * + * This function is used only as a subrutine of + * ecp_mul_comb(). + * + * Warning: fails (returning an error) if one of the points is + * zero! + * This should never happen, see choice of w in ecp_mul_comb(). + * + * \param grp Pointer to the group representing the curve. + * + * \param T Array of pointers to the points to normalise. + * + * \param t_len Number of elements in the array. + * + * \return 0 if successful, + * an error if one of the points is zero. + */ +#if defined(MBEDTLS_ECP_NORMALIZE_JAC_MANY_ALT) +int mbedtls_internal_ecp_normalize_jac_many( const mbedtls_ecp_group *grp, + mbedtls_ecp_point *T[], size_t t_len ); +#endif + +/** + * \brief Normalize jacobian coordinates so that Z == 0 || Z == 1. + * + * Cost in field operations if done by [5] 3.2.1: + * 1N := 1I + 3M + 1S + * + * \param grp Pointer to the group representing the curve. + * + * \param pt pointer to the point to be normalised. This is an + * input/output parameter. + * + * \return 0 if successful. + */ +#if defined(MBEDTLS_ECP_NORMALIZE_JAC_ALT) +int mbedtls_internal_ecp_normalize_jac( const mbedtls_ecp_group *grp, + mbedtls_ecp_point *pt ); +#endif + +#endif /* ECP_SHORTWEIERSTRASS */ + +#if defined(ECP_MONTGOMERY) + +#if defined(MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT) +int mbedtls_internal_ecp_double_add_mxz( const mbedtls_ecp_group *grp, + mbedtls_ecp_point *R, mbedtls_ecp_point *S, const mbedtls_ecp_point *P, + const mbedtls_ecp_point *Q, const mbedtls_mpi *d ); +#endif + +/** + * \brief Randomize projective x/z coordinates: + * (X, Z) -> (l X, l Z) for random l + * + * \param grp pointer to the group representing the curve + * + * \param P the point on the curve to be randomised given with + * projective coordinates. This is an input/output parameter. + * + * \param f_rng a function pointer to the random number generator + * + * \param p_rng a pointer to the random number generator state + * + * \return 0 if successful + */ +#if defined(MBEDTLS_ECP_RANDOMIZE_MXZ_ALT) +int mbedtls_internal_ecp_randomize_mxz( const mbedtls_ecp_group *grp, + mbedtls_ecp_point *P, int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng ); +#endif + +/** + * \brief Normalize Montgomery x/z coordinates: X = X/Z, Z = 1. + * + * \param grp pointer to the group representing the curve + * + * \param P pointer to the point to be normalised. This is an + * input/output parameter. + * + * \return 0 if successful + */ +#if defined(MBEDTLS_ECP_NORMALIZE_MXZ_ALT) +int mbedtls_internal_ecp_normalize_mxz( const mbedtls_ecp_group *grp, + mbedtls_ecp_point *P ); +#endif + +#endif /* ECP_MONTGOMERY */ + +#endif /* MBEDTLS_ECP_INTERNAL_ALT */ + +#endif /* ecp_internal.h */ + diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/entropy.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/entropy.h new file mode 100644 index 0000000000000000000000000000000000000000..ca06dc3c58e8c48043fdf117a900aa9983bc3713 --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/entropy.h @@ -0,0 +1,289 @@ +/** + * \file entropy.h + * + * \brief Entropy accumulator implementation + */ +/* + * Copyright (C) 2006-2016, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ +#ifndef MBEDTLS_ENTROPY_H +#define MBEDTLS_ENTROPY_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include + +#if defined(MBEDTLS_SHA512_C) && !defined(MBEDTLS_ENTROPY_FORCE_SHA256) +#include "sha512.h" +#define MBEDTLS_ENTROPY_SHA512_ACCUMULATOR +#else +#if defined(MBEDTLS_SHA256_C) +#define MBEDTLS_ENTROPY_SHA256_ACCUMULATOR +#include "sha256.h" +#endif +#endif + +#if defined(MBEDTLS_THREADING_C) +#include "threading.h" +#endif + +#if defined(MBEDTLS_HAVEGE_C) +#include "havege.h" +#endif + +#define MBEDTLS_ERR_ENTROPY_SOURCE_FAILED -0x003C /**< Critical entropy source failure. */ +#define MBEDTLS_ERR_ENTROPY_MAX_SOURCES -0x003E /**< No more sources can be added. */ +#define MBEDTLS_ERR_ENTROPY_NO_SOURCES_DEFINED -0x0040 /**< No sources have been added to poll. */ +#define MBEDTLS_ERR_ENTROPY_NO_STRONG_SOURCE -0x003D /**< No strong sources have been added to poll. */ +#define MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR -0x003F /**< Read/write error in file. */ + +/** + * \name SECTION: Module settings + * + * The configuration options you can set for this module are in this section. + * Either change them in config.h or define them on the compiler command line. + * \{ + */ + +#if !defined(MBEDTLS_ENTROPY_MAX_SOURCES) +#define MBEDTLS_ENTROPY_MAX_SOURCES 20 /**< Maximum number of sources supported */ +#endif + +#if !defined(MBEDTLS_ENTROPY_MAX_GATHER) +#define MBEDTLS_ENTROPY_MAX_GATHER 128 /**< Maximum amount requested from entropy sources */ +#endif + +/* \} name SECTION: Module settings */ + +#if defined(MBEDTLS_ENTROPY_SHA512_ACCUMULATOR) +#define MBEDTLS_ENTROPY_BLOCK_SIZE 64 /**< Block size of entropy accumulator (SHA-512) */ +#else +#define MBEDTLS_ENTROPY_BLOCK_SIZE 32 /**< Block size of entropy accumulator (SHA-256) */ +#endif + +#define MBEDTLS_ENTROPY_MAX_SEED_SIZE 1024 /**< Maximum size of seed we read from seed file */ +#define MBEDTLS_ENTROPY_SOURCE_MANUAL MBEDTLS_ENTROPY_MAX_SOURCES + +#define MBEDTLS_ENTROPY_SOURCE_STRONG 1 /**< Entropy source is strong */ +#define MBEDTLS_ENTROPY_SOURCE_WEAK 0 /**< Entropy source is weak */ + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \brief Entropy poll callback pointer + * + * \param data Callback-specific data pointer + * \param output Data to fill + * \param len Maximum size to provide + * \param olen The actual amount of bytes put into the buffer (Can be 0) + * + * \return 0 if no critical failures occurred, + * MBEDTLS_ERR_ENTROPY_SOURCE_FAILED otherwise + */ +typedef int (*mbedtls_entropy_f_source_ptr)(void *data, unsigned char *output, size_t len, + size_t *olen); + +/** + * \brief Entropy source state + */ +typedef struct mbedtls_entropy_source_state +{ + mbedtls_entropy_f_source_ptr f_source; /**< The entropy source callback */ + void * p_source; /**< The callback data pointer */ + size_t size; /**< Amount received in bytes */ + size_t threshold; /**< Minimum bytes required before release */ + int strong; /**< Is the source strong? */ +} +mbedtls_entropy_source_state; + +/** + * \brief Entropy context structure + */ +typedef struct mbedtls_entropy_context +{ + int accumulator_started; +#if defined(MBEDTLS_ENTROPY_SHA512_ACCUMULATOR) + mbedtls_sha512_context accumulator; +#else + mbedtls_sha256_context accumulator; +#endif + int source_count; + mbedtls_entropy_source_state source[MBEDTLS_ENTROPY_MAX_SOURCES]; +#if defined(MBEDTLS_HAVEGE_C) + mbedtls_havege_state havege_data; +#endif +#if defined(MBEDTLS_THREADING_C) + mbedtls_threading_mutex_t mutex; /*!< mutex */ +#endif +#if defined(MBEDTLS_ENTROPY_NV_SEED) + int initial_entropy_run; +#endif +} +mbedtls_entropy_context; + +/** + * \brief Initialize the context + * + * \param ctx Entropy context to initialize + */ +void mbedtls_entropy_init( mbedtls_entropy_context *ctx ); + +/** + * \brief Free the data in the context + * + * \param ctx Entropy context to free + */ +void mbedtls_entropy_free( mbedtls_entropy_context *ctx ); + +/** + * \brief Adds an entropy source to poll + * (Thread-safe if MBEDTLS_THREADING_C is enabled) + * + * \param ctx Entropy context + * \param f_source Entropy function + * \param p_source Function data + * \param threshold Minimum required from source before entropy is released + * ( with mbedtls_entropy_func() ) (in bytes) + * \param strong MBEDTLS_ENTROPY_SOURCE_STRONG or + * MBEDTLS_ENTROPY_SOURCE_WEAK. + * At least one strong source needs to be added. + * Weaker sources (such as the cycle counter) can be used as + * a complement. + * + * \return 0 if successful or MBEDTLS_ERR_ENTROPY_MAX_SOURCES + */ +int mbedtls_entropy_add_source( mbedtls_entropy_context *ctx, + mbedtls_entropy_f_source_ptr f_source, void *p_source, + size_t threshold, int strong ); + +/** + * \brief Trigger an extra gather poll for the accumulator + * (Thread-safe if MBEDTLS_THREADING_C is enabled) + * + * \param ctx Entropy context + * + * \return 0 if successful, or MBEDTLS_ERR_ENTROPY_SOURCE_FAILED + */ +int mbedtls_entropy_gather( mbedtls_entropy_context *ctx ); + +/** + * \brief Retrieve entropy from the accumulator + * (Maximum length: MBEDTLS_ENTROPY_BLOCK_SIZE) + * (Thread-safe if MBEDTLS_THREADING_C is enabled) + * + * \param data Entropy context + * \param output Buffer to fill + * \param len Number of bytes desired, must be at most MBEDTLS_ENTROPY_BLOCK_SIZE + * + * \return 0 if successful, or MBEDTLS_ERR_ENTROPY_SOURCE_FAILED + */ +int mbedtls_entropy_func( void *data, unsigned char *output, size_t len ); + +/** + * \brief Add data to the accumulator manually + * (Thread-safe if MBEDTLS_THREADING_C is enabled) + * + * \param ctx Entropy context + * \param data Data to add + * \param len Length of data + * + * \return 0 if successful + */ +int mbedtls_entropy_update_manual( mbedtls_entropy_context *ctx, + const unsigned char *data, size_t len ); + +#if defined(MBEDTLS_ENTROPY_NV_SEED) +/** + * \brief Trigger an update of the seed file in NV by using the + * current entropy pool. + * + * \param ctx Entropy context + * + * \return 0 if successful + */ +int mbedtls_entropy_update_nv_seed( mbedtls_entropy_context *ctx ); +#endif /* MBEDTLS_ENTROPY_NV_SEED */ + +#if defined(MBEDTLS_FS_IO) +/** + * \brief Write a seed file + * + * \param ctx Entropy context + * \param path Name of the file + * + * \return 0 if successful, + * MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR on file error, or + * MBEDTLS_ERR_ENTROPY_SOURCE_FAILED + */ +int mbedtls_entropy_write_seed_file( mbedtls_entropy_context *ctx, const char *path ); + +/** + * \brief Read and update a seed file. Seed is added to this + * instance. No more than MBEDTLS_ENTROPY_MAX_SEED_SIZE bytes are + * read from the seed file. The rest is ignored. + * + * \param ctx Entropy context + * \param path Name of the file + * + * \return 0 if successful, + * MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR on file error, + * MBEDTLS_ERR_ENTROPY_SOURCE_FAILED + */ +int mbedtls_entropy_update_seed_file( mbedtls_entropy_context *ctx, const char *path ); +#endif /* MBEDTLS_FS_IO */ + +#if defined(MBEDTLS_SELF_TEST) +/** + * \brief Checkup routine + * + * This module self-test also calls the entropy self-test, + * mbedtls_entropy_source_self_test(); + * + * \return 0 if successful, or 1 if a test failed + */ +int mbedtls_entropy_self_test( int verbose ); + +#if defined(MBEDTLS_ENTROPY_HARDWARE_ALT) +/** + * \brief Checkup routine + * + * Verifies the integrity of the hardware entropy source + * provided by the function 'mbedtls_hardware_poll()'. + * + * Note this is the only hardware entropy source that is known + * at link time, and other entropy sources configured + * dynamically at runtime by the function + * mbedtls_entropy_add_source() will not be tested. + * + * \return 0 if successful, or 1 if a test failed + */ +int mbedtls_entropy_source_self_test( int verbose ); +#endif /* MBEDTLS_ENTROPY_HARDWARE_ALT */ +#endif /* MBEDTLS_SELF_TEST */ + +#ifdef __cplusplus +} +#endif + +#endif /* entropy.h */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/entropy_poll.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/entropy_poll.h new file mode 100644 index 0000000000000000000000000000000000000000..94dd657eb9565a857d4303b9793889ce91832b30 --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/entropy_poll.h @@ -0,0 +1,110 @@ +/** + * \file entropy_poll.h + * + * \brief Platform-specific and custom entropy polling functions + */ +/* + * Copyright (C) 2006-2016, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ +#ifndef MBEDTLS_ENTROPY_POLL_H +#define MBEDTLS_ENTROPY_POLL_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * Default thresholds for built-in sources, in bytes + */ +#define MBEDTLS_ENTROPY_MIN_PLATFORM 32 /**< Minimum for platform source */ +#define MBEDTLS_ENTROPY_MIN_HAVEGE 32 /**< Minimum for HAVEGE */ +#define MBEDTLS_ENTROPY_MIN_HARDCLOCK 4 /**< Minimum for mbedtls_timing_hardclock() */ +#if !defined(MBEDTLS_ENTROPY_MIN_HARDWARE) +#define MBEDTLS_ENTROPY_MIN_HARDWARE 32 /**< Minimum for the hardware source */ +#endif + +/** + * \brief Entropy poll callback that provides 0 entropy. + */ +#if defined(MBEDTLS_TEST_NULL_ENTROPY) + int mbedtls_null_entropy_poll( void *data, + unsigned char *output, size_t len, size_t *olen ); +#endif + +#if !defined(MBEDTLS_NO_PLATFORM_ENTROPY) +/** + * \brief Platform-specific entropy poll callback + */ +int mbedtls_platform_entropy_poll( void *data, + unsigned char *output, size_t len, size_t *olen ); +#endif + +#if defined(MBEDTLS_HAVEGE_C) +/** + * \brief HAVEGE based entropy poll callback + * + * Requires an HAVEGE state as its data pointer. + */ +int mbedtls_havege_poll( void *data, + unsigned char *output, size_t len, size_t *olen ); +#endif + +#if defined(MBEDTLS_TIMING_C) +/** + * \brief mbedtls_timing_hardclock-based entropy poll callback + */ +int mbedtls_hardclock_poll( void *data, + unsigned char *output, size_t len, size_t *olen ); +#endif + +#if defined(MBEDTLS_ENTROPY_HARDWARE_ALT) +/** + * \brief Entropy poll callback for a hardware source + * + * \warning This is not provided by mbed TLS! + * See \c MBEDTLS_ENTROPY_HARDWARE_ALT in config.h. + * + * \note This must accept NULL as its first argument. + */ +int mbedtls_hardware_poll( void *data, + unsigned char *output, size_t len, size_t *olen ); +#endif + +#if defined(MBEDTLS_ENTROPY_NV_SEED) +/** + * \brief Entropy poll callback for a non-volatile seed file + * + * \note This must accept NULL as its first argument. + */ +int mbedtls_nv_seed_poll( void *data, + unsigned char *output, size_t len, size_t *olen ); +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* entropy_poll.h */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/error.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/error.h new file mode 100644 index 0000000000000000000000000000000000000000..bee0fe485ac6bb5fa1a4c0d62b161920637bad02 --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/error.h @@ -0,0 +1,129 @@ +/** + * \file error.h + * + * \brief Error to string translation + */ +/* + * Copyright (C) 2006-2018, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ +#ifndef MBEDTLS_ERROR_H +#define MBEDTLS_ERROR_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include + +/** + * Error code layout. + * + * Currently we try to keep all error codes within the negative space of 16 + * bits signed integers to support all platforms (-0x0001 - -0x7FFF). In + * addition we'd like to give two layers of information on the error if + * possible. + * + * For that purpose the error codes are segmented in the following manner: + * + * 16 bit error code bit-segmentation + * + * 1 bit - Unused (sign bit) + * 3 bits - High level module ID + * 5 bits - Module-dependent error code + * 7 bits - Low level module errors + * + * For historical reasons, low-level error codes are divided in even and odd, + * even codes were assigned first, and -1 is reserved for other errors. + * + * Low-level module errors (0x0002-0x007E, 0x0003-0x007F) + * + * Module Nr Codes assigned + * MPI 7 0x0002-0x0010 + * GCM 3 0x0012-0x0014 0x0013-0x0013 + * BLOWFISH 3 0x0016-0x0018 0x0017-0x0017 + * THREADING 3 0x001A-0x001E + * AES 5 0x0020-0x0022 0x0021-0x0025 + * CAMELLIA 3 0x0024-0x0026 0x0027-0x0027 + * XTEA 2 0x0028-0x0028 0x0029-0x0029 + * BASE64 2 0x002A-0x002C + * OID 1 0x002E-0x002E 0x000B-0x000B + * PADLOCK 1 0x0030-0x0030 + * DES 2 0x0032-0x0032 0x0033-0x0033 + * CTR_DBRG 4 0x0034-0x003A + * ENTROPY 3 0x003C-0x0040 0x003D-0x003F + * NET 13 0x0042-0x0052 0x0043-0x0049 + * ARIA 4 0x0058-0x005E + * ASN1 7 0x0060-0x006C + * CMAC 1 0x007A-0x007A + * PBKDF2 1 0x007C-0x007C + * HMAC_DRBG 4 0x0003-0x0009 + * CCM 3 0x000D-0x0011 + * ARC4 1 0x0019-0x0019 + * MD2 1 0x002B-0x002B + * MD4 1 0x002D-0x002D + * MD5 1 0x002F-0x002F + * RIPEMD160 1 0x0031-0x0031 + * SHA1 1 0x0035-0x0035 0x0073-0x0073 + * SHA256 1 0x0037-0x0037 0x0074-0x0074 + * SHA512 1 0x0039-0x0039 0x0075-0x0075 + * CHACHA20 3 0x0051-0x0055 + * POLY1305 3 0x0057-0x005B + * CHACHAPOLY 2 0x0054-0x0056 + * PLATFORM 1 0x0070-0x0072 + * + * High-level module nr (3 bits - 0x0...-0x7...) + * Name ID Nr of Errors + * PEM 1 9 + * PKCS#12 1 4 (Started from top) + * X509 2 20 + * PKCS5 2 4 (Started from top) + * DHM 3 11 + * PK 3 15 (Started from top) + * RSA 4 11 + * ECP 4 10 (Started from top) + * MD 5 5 + * HKDF 5 1 (Started from top) + * CIPHER 6 8 + * SSL 6 23 (Started from top) + * SSL 7 32 + * + * Module dependent error code (5 bits 0x.00.-0x.F8.) + */ + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \brief Translate a mbed TLS error code into a string representation, + * Result is truncated if necessary and always includes a terminating + * null byte. + * + * \param errnum error code + * \param buffer buffer to place representation in + * \param buflen length of the buffer + */ +void mbedtls_strerror( int errnum, char *buffer, size_t buflen ); + +#ifdef __cplusplus +} +#endif + +#endif /* error.h */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/gcm.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/gcm.h new file mode 100644 index 0000000000000000000000000000000000000000..fd130abd7cffe5f6390a01879fabb2f619da36de --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/gcm.h @@ -0,0 +1,326 @@ +/** + * \file gcm.h + * + * \brief This file contains GCM definitions and functions. + * + * The Galois/Counter Mode (GCM) for 128-bit block ciphers is defined + * in D. McGrew, J. Viega, The Galois/Counter Mode of Operation + * (GCM), Natl. Inst. Stand. Technol. + * + * For more information on GCM, see NIST SP 800-38D: Recommendation for + * Block Cipher Modes of Operation: Galois/Counter Mode (GCM) and GMAC. + * + */ +/* + * Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of Mbed TLS (https://tls.mbed.org) + */ + +#ifndef MBEDTLS_GCM_H +#define MBEDTLS_GCM_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include "cipher.h" + +#include + +#define MBEDTLS_GCM_ENCRYPT 1 +#define MBEDTLS_GCM_DECRYPT 0 + +#define MBEDTLS_ERR_GCM_AUTH_FAILED -0x0012 /**< Authenticated decryption failed. */ + +/* MBEDTLS_ERR_GCM_HW_ACCEL_FAILED is deprecated and should not be used. */ +#define MBEDTLS_ERR_GCM_HW_ACCEL_FAILED -0x0013 /**< GCM hardware accelerator failed. */ + +#define MBEDTLS_ERR_GCM_BAD_INPUT -0x0014 /**< Bad input parameters to function. */ + +#ifdef __cplusplus +extern "C" { +#endif + +#if !defined(MBEDTLS_GCM_ALT) + +/** + * \brief The GCM context structure. + */ +typedef struct mbedtls_gcm_context +{ + mbedtls_cipher_context_t cipher_ctx; /*!< The cipher context used. */ + uint64_t HL[16]; /*!< Precalculated HTable low. */ + uint64_t HH[16]; /*!< Precalculated HTable high. */ + uint64_t len; /*!< The total length of the encrypted data. */ + uint64_t add_len; /*!< The total length of the additional data. */ + unsigned char base_ectr[16]; /*!< The first ECTR for tag. */ + unsigned char y[16]; /*!< The Y working value. */ + unsigned char buf[16]; /*!< The buf working value. */ + int mode; /*!< The operation to perform: + #MBEDTLS_GCM_ENCRYPT or + #MBEDTLS_GCM_DECRYPT. */ +} +mbedtls_gcm_context; + +#else /* !MBEDTLS_GCM_ALT */ +#include "gcm_alt.h" +#endif /* !MBEDTLS_GCM_ALT */ + +/** + * \brief This function initializes the specified GCM context, + * to make references valid, and prepares the context + * for mbedtls_gcm_setkey() or mbedtls_gcm_free(). + * + * The function does not bind the GCM context to a particular + * cipher, nor set the key. For this purpose, use + * mbedtls_gcm_setkey(). + * + * \param ctx The GCM context to initialize. This must not be \c NULL. + */ +void mbedtls_gcm_init( mbedtls_gcm_context *ctx ); + +/** + * \brief This function associates a GCM context with a + * cipher algorithm and a key. + * + * \param ctx The GCM context. This must be initialized. + * \param cipher The 128-bit block cipher to use. + * \param key The encryption key. This must be a readable buffer of at + * least \p keybits bits. + * \param keybits The key size in bits. Valid options are: + *
                            • 128 bits
                            • + *
                            • 192 bits
                            • + *
                            • 256 bits
                            + * + * \return \c 0 on success. + * \return A cipher-specific error code on failure. + */ +int mbedtls_gcm_setkey( mbedtls_gcm_context *ctx, + mbedtls_cipher_id_t cipher, + const unsigned char *key, + unsigned int keybits ); + +/** + * \brief This function performs GCM encryption or decryption of a buffer. + * + * \note For encryption, the output buffer can be the same as the + * input buffer. For decryption, the output buffer cannot be + * the same as input buffer. If the buffers overlap, the output + * buffer must trail at least 8 Bytes behind the input buffer. + * + * \warning When this function performs a decryption, it outputs the + * authentication tag and does not verify that the data is + * authentic. You should use this function to perform encryption + * only. For decryption, use mbedtls_gcm_auth_decrypt() instead. + * + * \param ctx The GCM context to use for encryption or decryption. This + * must be initialized. + * \param mode The operation to perform: + * - #MBEDTLS_GCM_ENCRYPT to perform authenticated encryption. + * The ciphertext is written to \p output and the + * authentication tag is written to \p tag. + * - #MBEDTLS_GCM_DECRYPT to perform decryption. + * The plaintext is written to \p output and the + * authentication tag is written to \p tag. + * Note that this mode is not recommended, because it does + * not verify the authenticity of the data. For this reason, + * you should use mbedtls_gcm_auth_decrypt() instead of + * calling this function in decryption mode. + * \param length The length of the input data, which is equal to the length + * of the output data. + * \param iv The initialization vector. This must be a readable buffer of + * at least \p iv_len Bytes. + * \param iv_len The length of the IV. + * \param add The buffer holding the additional data. This must be of at + * least that size in Bytes. + * \param add_len The length of the additional data. + * \param input The buffer holding the input data. If \p length is greater + * than zero, this must be a readable buffer of at least that + * size in Bytes. + * \param output The buffer for holding the output data. If \p length is greater + * than zero, this must be a writable buffer of at least that + * size in Bytes. + * \param tag_len The length of the tag to generate. + * \param tag The buffer for holding the tag. This must be a readable + * buffer of at least \p tag_len Bytes. + * + * \return \c 0 if the encryption or decryption was performed + * successfully. Note that in #MBEDTLS_GCM_DECRYPT mode, + * this does not indicate that the data is authentic. + * \return #MBEDTLS_ERR_GCM_BAD_INPUT if the lengths or pointers are + * not valid or a cipher-specific error code if the encryption + * or decryption failed. + */ +int mbedtls_gcm_crypt_and_tag( mbedtls_gcm_context *ctx, + int mode, + size_t length, + const unsigned char *iv, + size_t iv_len, + const unsigned char *add, + size_t add_len, + const unsigned char *input, + unsigned char *output, + size_t tag_len, + unsigned char *tag ); + +/** + * \brief This function performs a GCM authenticated decryption of a + * buffer. + * + * \note For decryption, the output buffer cannot be the same as + * input buffer. If the buffers overlap, the output buffer + * must trail at least 8 Bytes behind the input buffer. + * + * \param ctx The GCM context. This must be initialized. + * \param length The length of the ciphertext to decrypt, which is also + * the length of the decrypted plaintext. + * \param iv The initialization vector. This must be a readable buffer + * of at least \p iv_len Bytes. + * \param iv_len The length of the IV. + * \param add The buffer holding the additional data. This must be of at + * least that size in Bytes. + * \param add_len The length of the additional data. + * \param tag The buffer holding the tag to verify. This must be a + * readable buffer of at least \p tag_len Bytes. + * \param tag_len The length of the tag to verify. + * \param input The buffer holding the ciphertext. If \p length is greater + * than zero, this must be a readable buffer of at least that + * size. + * \param output The buffer for holding the decrypted plaintext. If \p length + * is greater than zero, this must be a writable buffer of at + * least that size. + * + * \return \c 0 if successful and authenticated. + * \return #MBEDTLS_ERR_GCM_AUTH_FAILED if the tag does not match. + * \return #MBEDTLS_ERR_GCM_BAD_INPUT if the lengths or pointers are + * not valid or a cipher-specific error code if the decryption + * failed. + */ +int mbedtls_gcm_auth_decrypt( mbedtls_gcm_context *ctx, + size_t length, + const unsigned char *iv, + size_t iv_len, + const unsigned char *add, + size_t add_len, + const unsigned char *tag, + size_t tag_len, + const unsigned char *input, + unsigned char *output ); + +/** + * \brief This function starts a GCM encryption or decryption + * operation. + * + * \param ctx The GCM context. This must be initialized. + * \param mode The operation to perform: #MBEDTLS_GCM_ENCRYPT or + * #MBEDTLS_GCM_DECRYPT. + * \param iv The initialization vector. This must be a readable buffer of + * at least \p iv_len Bytes. + * \param iv_len The length of the IV. + * \param add The buffer holding the additional data, or \c NULL + * if \p add_len is \c 0. + * \param add_len The length of the additional data. If \c 0, + * \p add may be \c NULL. + * + * \return \c 0 on success. + */ +int mbedtls_gcm_starts( mbedtls_gcm_context *ctx, + int mode, + const unsigned char *iv, + size_t iv_len, + const unsigned char *add, + size_t add_len ); + +/** + * \brief This function feeds an input buffer into an ongoing GCM + * encryption or decryption operation. + * + * ` The function expects input to be a multiple of 16 + * Bytes. Only the last call before calling + * mbedtls_gcm_finish() can be less than 16 Bytes. + * + * \note For decryption, the output buffer cannot be the same as + * input buffer. If the buffers overlap, the output buffer + * must trail at least 8 Bytes behind the input buffer. + * + * \param ctx The GCM context. This must be initialized. + * \param length The length of the input data. This must be a multiple of + * 16 except in the last call before mbedtls_gcm_finish(). + * \param input The buffer holding the input data. If \p length is greater + * than zero, this must be a readable buffer of at least that + * size in Bytes. + * \param output The buffer for holding the output data. If \p length is + * greater than zero, this must be a writable buffer of at + * least that size in Bytes. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_GCM_BAD_INPUT on failure. + */ +int mbedtls_gcm_update( mbedtls_gcm_context *ctx, + size_t length, + const unsigned char *input, + unsigned char *output ); + +/** + * \brief This function finishes the GCM operation and generates + * the authentication tag. + * + * It wraps up the GCM stream, and generates the + * tag. The tag can have a maximum length of 16 Bytes. + * + * \param ctx The GCM context. This must be initialized. + * \param tag The buffer for holding the tag. This must be a readable + * buffer of at least \p tag_len Bytes. + * \param tag_len The length of the tag to generate. This must be at least + * four. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_GCM_BAD_INPUT on failure. + */ +int mbedtls_gcm_finish( mbedtls_gcm_context *ctx, + unsigned char *tag, + size_t tag_len ); + +/** + * \brief This function clears a GCM context and the underlying + * cipher sub-context. + * + * \param ctx The GCM context to clear. If this is \c NULL, the call has + * no effect. Otherwise, this must be initialized. + */ +void mbedtls_gcm_free( mbedtls_gcm_context *ctx ); + +#if defined(MBEDTLS_SELF_TEST) + +/** + * \brief The GCM checkup routine. + * + * \return \c 0 on success. + * \return \c 1 on failure. + */ +int mbedtls_gcm_self_test( int verbose ); + +#endif /* MBEDTLS_SELF_TEST */ + +#ifdef __cplusplus +} +#endif + + +#endif /* gcm.h */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/gcm_alt.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/gcm_alt.h new file mode 100644 index 0000000000000000000000000000000000000000..bab3b3b458bcd14f09fed000f7b5a526b71ba10f --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/gcm_alt.h @@ -0,0 +1,59 @@ +/** + * \file gcm.h + * + * \brief This file contains GCM definitions and functions. + * + * The Galois/Counter Mode (GCM) for 128-bit block ciphers is defined + * in D. McGrew, J. Viega, The Galois/Counter Mode of Operation + * (GCM), Natl. Inst. Stand. Technol. + * + * For more information on GCM, see NIST SP 800-38D: Recommendation for + * Block Cipher Modes of Operation: Galois/Counter Mode (GCM) and GMAC. + * + */ +/* + * Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of Mbed TLS (https://tls.mbed.org) + */ + +#ifndef MBEDTLS_GCM_ALT_H +#define MBEDTLS_GCM_ALT_H + +#if defined(MBEDTLS_GCM_ALT) + +/** + * \brief The GCM context structure. + */ +typedef struct mbedtls_gcm_context +{ + mbedtls_cipher_context_t cipher_ctx; /*!< The cipher context used. */ + uint64_t HL[16]; /*!< Precalculated HTable low. */ + uint64_t HH[16]; /*!< Precalculated HTable high. */ + uint64_t len; /*!< The total length of the encrypted data. */ + uint64_t add_len; /*!< The total length of the additional data. */ + unsigned char base_ectr[16]; /*!< The first ECTR for tag. */ + unsigned char y[16]; /*!< The Y working value. */ + unsigned char buf[16]; /*!< The buf working value. */ + int mode; /*!< The operation to perform: + #MBEDTLS_GCM_ENCRYPT or + #MBEDTLS_GCM_DECRYPT. */ +} +mbedtls_gcm_context; + +#endif /* !MBEDTLS_GCM_ALT */ + +#endif /* gcm_alt.h */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/havege.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/havege.h new file mode 100644 index 0000000000000000000000000000000000000000..4c1c86087a8c510373272beab7d3c4e58c94d102 --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/havege.h @@ -0,0 +1,81 @@ +/** + * \file havege.h + * + * \brief HAVEGE: HArdware Volatile Entropy Gathering and Expansion + */ +/* + * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ +#ifndef MBEDTLS_HAVEGE_H +#define MBEDTLS_HAVEGE_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include + +#define MBEDTLS_HAVEGE_COLLECT_SIZE 1024 + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \brief HAVEGE state structure + */ +typedef struct mbedtls_havege_state +{ + int PT1, PT2, offset[2]; + int pool[MBEDTLS_HAVEGE_COLLECT_SIZE]; + int WALK[8192]; +} +mbedtls_havege_state; + +/** + * \brief HAVEGE initialization + * + * \param hs HAVEGE state to be initialized + */ +void mbedtls_havege_init( mbedtls_havege_state *hs ); + +/** + * \brief Clear HAVEGE state + * + * \param hs HAVEGE state to be cleared + */ +void mbedtls_havege_free( mbedtls_havege_state *hs ); + +/** + * \brief HAVEGE rand function + * + * \param p_rng A HAVEGE state + * \param output Buffer to fill + * \param len Length of buffer + * + * \return 0 + */ +int mbedtls_havege_random( void *p_rng, unsigned char *output, size_t len ); + +#ifdef __cplusplus +} +#endif + +#endif /* havege.h */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/hkdf.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/hkdf.h new file mode 100644 index 0000000000000000000000000000000000000000..bcafe42513694d58b3828473e36eb0210ca0860c --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/hkdf.h @@ -0,0 +1,141 @@ +/** + * \file hkdf.h + * + * \brief This file contains the HKDF interface. + * + * The HMAC-based Extract-and-Expand Key Derivation Function (HKDF) is + * specified by RFC 5869. + */ +/* + * Copyright (C) 2016-2019, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ +#ifndef MBEDTLS_HKDF_H +#define MBEDTLS_HKDF_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include "md.h" + +/** + * \name HKDF Error codes + * \{ + */ +#define MBEDTLS_ERR_HKDF_BAD_INPUT_DATA -0x5F80 /**< Bad input parameters to function. */ +/* \} name */ + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \brief This is the HMAC-based Extract-and-Expand Key Derivation Function + * (HKDF). + * + * \param md A hash function; md.size denotes the length of the hash + * function output in bytes. + * \param salt An optional salt value (a non-secret random value); + * if the salt is not provided, a string of all zeros of + * md.size length is used as the salt. + * \param salt_len The length in bytes of the optional \p salt. + * \param ikm The input keying material. + * \param ikm_len The length in bytes of \p ikm. + * \param info An optional context and application specific information + * string. This can be a zero-length string. + * \param info_len The length of \p info in bytes. + * \param okm The output keying material of \p okm_len bytes. + * \param okm_len The length of the output keying material in bytes. This + * must be less than or equal to 255 * md.size bytes. + * + * \return 0 on success. + * \return #MBEDTLS_ERR_HKDF_BAD_INPUT_DATA when the parameters are invalid. + * \return An MBEDTLS_ERR_MD_* error for errors returned from the underlying + * MD layer. + */ +int mbedtls_hkdf( const mbedtls_md_info_t *md, const unsigned char *salt, + size_t salt_len, const unsigned char *ikm, size_t ikm_len, + const unsigned char *info, size_t info_len, + unsigned char *okm, size_t okm_len ); + +/** + * \brief Take the input keying material \p ikm and extract from it a + * fixed-length pseudorandom key \p prk. + * + * \warning This function should only be used if the security of it has been + * studied and established in that particular context (eg. TLS 1.3 + * key schedule). For standard HKDF security guarantees use + * \c mbedtls_hkdf instead. + * + * \param md A hash function; md.size denotes the length of the + * hash function output in bytes. + * \param salt An optional salt value (a non-secret random value); + * if the salt is not provided, a string of all zeros + * of md.size length is used as the salt. + * \param salt_len The length in bytes of the optional \p salt. + * \param ikm The input keying material. + * \param ikm_len The length in bytes of \p ikm. + * \param[out] prk A pseudorandom key of at least md.size bytes. + * + * \return 0 on success. + * \return #MBEDTLS_ERR_HKDF_BAD_INPUT_DATA when the parameters are invalid. + * \return An MBEDTLS_ERR_MD_* error for errors returned from the underlying + * MD layer. + */ +int mbedtls_hkdf_extract( const mbedtls_md_info_t *md, + const unsigned char *salt, size_t salt_len, + const unsigned char *ikm, size_t ikm_len, + unsigned char *prk ); + +/** + * \brief Expand the supplied \p prk into several additional pseudorandom + * keys, which is the output of the HKDF. + * + * \warning This function should only be used if the security of it has been + * studied and established in that particular context (eg. TLS 1.3 + * key schedule). For standard HKDF security guarantees use + * \c mbedtls_hkdf instead. + * + * \param md A hash function; md.size denotes the length of the hash + * function output in bytes. + * \param prk A pseudorandom key of at least md.size bytes. \p prk is + * usually the output from the HKDF extract step. + * \param prk_len The length in bytes of \p prk. + * \param info An optional context and application specific information + * string. This can be a zero-length string. + * \param info_len The length of \p info in bytes. + * \param okm The output keying material of \p okm_len bytes. + * \param okm_len The length of the output keying material in bytes. This + * must be less than or equal to 255 * md.size bytes. + * + * \return 0 on success. + * \return #MBEDTLS_ERR_HKDF_BAD_INPUT_DATA when the parameters are invalid. + * \return An MBEDTLS_ERR_MD_* error for errors returned from the underlying + * MD layer. + */ +int mbedtls_hkdf_expand( const mbedtls_md_info_t *md, const unsigned char *prk, + size_t prk_len, const unsigned char *info, + size_t info_len, unsigned char *okm, size_t okm_len ); + +#ifdef __cplusplus +} +#endif + +#endif /* hkdf.h */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/hmac_drbg.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/hmac_drbg.h new file mode 100644 index 0000000000000000000000000000000000000000..7931c2281cf03eeeef45a6b14738dd4e353a823d --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/hmac_drbg.h @@ -0,0 +1,415 @@ +/** + * \file hmac_drbg.h + * + * \brief The HMAC_DRBG pseudorandom generator. + * + * This module implements the HMAC_DRBG pseudorandom generator described + * in NIST SP 800-90A: Recommendation for Random Number Generation Using + * Deterministic Random Bit Generators. + */ +/* + * Copyright (C) 2006-2019, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ +#ifndef MBEDTLS_HMAC_DRBG_H +#define MBEDTLS_HMAC_DRBG_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include "md.h" + +#if defined(MBEDTLS_THREADING_C) +#include "threading.h" +#endif + +/* + * Error codes + */ +#define MBEDTLS_ERR_HMAC_DRBG_REQUEST_TOO_BIG -0x0003 /**< Too many random requested in single call. */ +#define MBEDTLS_ERR_HMAC_DRBG_INPUT_TOO_BIG -0x0005 /**< Input too large (Entropy + additional). */ +#define MBEDTLS_ERR_HMAC_DRBG_FILE_IO_ERROR -0x0007 /**< Read/write error in file. */ +#define MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED -0x0009 /**< The entropy source failed. */ + +/** + * \name SECTION: Module settings + * + * The configuration options you can set for this module are in this section. + * Either change them in config.h or define them on the compiler command line. + * \{ + */ + +#if !defined(MBEDTLS_HMAC_DRBG_RESEED_INTERVAL) +#define MBEDTLS_HMAC_DRBG_RESEED_INTERVAL 10000 /**< Interval before reseed is performed by default */ +#endif + +#if !defined(MBEDTLS_HMAC_DRBG_MAX_INPUT) +#define MBEDTLS_HMAC_DRBG_MAX_INPUT 256 /**< Maximum number of additional input bytes */ +#endif + +#if !defined(MBEDTLS_HMAC_DRBG_MAX_REQUEST) +#define MBEDTLS_HMAC_DRBG_MAX_REQUEST 1024 /**< Maximum number of requested bytes per call */ +#endif + +#if !defined(MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT) +#define MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT 384 /**< Maximum size of (re)seed buffer */ +#endif + +/* \} name SECTION: Module settings */ + +#define MBEDTLS_HMAC_DRBG_PR_OFF 0 /**< No prediction resistance */ +#define MBEDTLS_HMAC_DRBG_PR_ON 1 /**< Prediction resistance enabled */ + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * HMAC_DRBG context. + */ +typedef struct mbedtls_hmac_drbg_context +{ + /* Working state: the key K is not stored explicitly, + * but is implied by the HMAC context */ + mbedtls_md_context_t md_ctx; /*!< HMAC context (inc. K) */ + unsigned char V[MBEDTLS_MD_MAX_SIZE]; /*!< V in the spec */ + int reseed_counter; /*!< reseed counter */ + + /* Administrative state */ + size_t entropy_len; /*!< entropy bytes grabbed on each (re)seed */ + int prediction_resistance; /*!< enable prediction resistance (Automatic + reseed before every random generation) */ + int reseed_interval; /*!< reseed interval */ + + /* Callbacks */ + int (*f_entropy)(void *, unsigned char *, size_t); /*!< entropy function */ + void *p_entropy; /*!< context for the entropy function */ + +#if defined(MBEDTLS_THREADING_C) + mbedtls_threading_mutex_t mutex; +#endif +} mbedtls_hmac_drbg_context; + +/** + * \brief HMAC_DRBG context initialization. + * + * This function makes the context ready for mbedtls_hmac_drbg_seed(), + * mbedtls_hmac_drbg_seed_buf() or mbedtls_hmac_drbg_free(). + * + * \param ctx HMAC_DRBG context to be initialized. + */ +void mbedtls_hmac_drbg_init( mbedtls_hmac_drbg_context *ctx ); + +/** + * \brief HMAC_DRBG initial seeding. + * + * Set the initial seed and set up the entropy source for future reseeds. + * + * A typical choice for the \p f_entropy and \p p_entropy parameters is + * to use the entropy module: + * - \p f_entropy is mbedtls_entropy_func(); + * - \p p_entropy is an instance of ::mbedtls_entropy_context initialized + * with mbedtls_entropy_init() (which registers the platform's default + * entropy sources). + * + * You can provide a personalization string in addition to the + * entropy source, to make this instantiation as unique as possible. + * + * \note By default, the security strength as defined by NIST is: + * - 128 bits if \p md_info is SHA-1; + * - 192 bits if \p md_info is SHA-224; + * - 256 bits if \p md_info is SHA-256, SHA-384 or SHA-512. + * Note that SHA-256 is just as efficient as SHA-224. + * The security strength can be reduced if a smaller + * entropy length is set with + * mbedtls_hmac_drbg_set_entropy_len(). + * + * \note The default entropy length is the security strength + * (converted from bits to bytes). You can override + * it by calling mbedtls_hmac_drbg_set_entropy_len(). + * + * \note During the initial seeding, this function calls + * the entropy source to obtain a nonce + * whose length is half the entropy length. + * + * \param ctx HMAC_DRBG context to be seeded. + * \param md_info MD algorithm to use for HMAC_DRBG. + * \param f_entropy The entropy callback, taking as arguments the + * \p p_entropy context, the buffer to fill, and the + * length of the buffer. + * \p f_entropy is always called with a length that is + * less than or equal to the entropy length. + * \param p_entropy The entropy context to pass to \p f_entropy. + * \param custom The personalization string. + * This can be \c NULL, in which case the personalization + * string is empty regardless of the value of \p len. + * \param len The length of the personalization string. + * This must be at most #MBEDTLS_HMAC_DRBG_MAX_INPUT + * and also at most + * #MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT - \p entropy_len * 3 / 2 + * where \p entropy_len is the entropy length + * described above. + * + * \return \c 0 if successful. + * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA if \p md_info is + * invalid. + * \return #MBEDTLS_ERR_MD_ALLOC_FAILED if there was not enough + * memory to allocate context data. + * \return #MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED + * if the call to \p f_entropy failed. + */ +int mbedtls_hmac_drbg_seed( mbedtls_hmac_drbg_context *ctx, + const mbedtls_md_info_t * md_info, + int (*f_entropy)(void *, unsigned char *, size_t), + void *p_entropy, + const unsigned char *custom, + size_t len ); + +/** + * \brief Initilisation of simpified HMAC_DRBG (never reseeds). + * + * This function is meant for use in algorithms that need a pseudorandom + * input such as deterministic ECDSA. + * + * \param ctx HMAC_DRBG context to be initialised. + * \param md_info MD algorithm to use for HMAC_DRBG. + * \param data Concatenation of the initial entropy string and + * the additional data. + * \param data_len Length of \p data in bytes. + * + * \return \c 0 if successful. or + * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA if \p md_info is + * invalid. + * \return #MBEDTLS_ERR_MD_ALLOC_FAILED if there was not enough + * memory to allocate context data. + */ +int mbedtls_hmac_drbg_seed_buf( mbedtls_hmac_drbg_context *ctx, + const mbedtls_md_info_t * md_info, + const unsigned char *data, size_t data_len ); + +/** + * \brief This function turns prediction resistance on or off. + * The default value is off. + * + * \note If enabled, entropy is gathered at the beginning of + * every call to mbedtls_hmac_drbg_random_with_add() + * or mbedtls_hmac_drbg_random(). + * Only use this if your entropy source has sufficient + * throughput. + * + * \param ctx The HMAC_DRBG context. + * \param resistance #MBEDTLS_HMAC_DRBG_PR_ON or #MBEDTLS_HMAC_DRBG_PR_OFF. + */ +void mbedtls_hmac_drbg_set_prediction_resistance( mbedtls_hmac_drbg_context *ctx, + int resistance ); + +/** + * \brief This function sets the amount of entropy grabbed on each + * seed or reseed. + * + * See the documentation of mbedtls_hmac_drbg_seed() for the default value. + * + * \param ctx The HMAC_DRBG context. + * \param len The amount of entropy to grab, in bytes. + */ +void mbedtls_hmac_drbg_set_entropy_len( mbedtls_hmac_drbg_context *ctx, + size_t len ); + +/** + * \brief Set the reseed interval. + * + * The reseed interval is the number of calls to mbedtls_hmac_drbg_random() + * or mbedtls_hmac_drbg_random_with_add() after which the entropy function + * is called again. + * + * The default value is #MBEDTLS_HMAC_DRBG_RESEED_INTERVAL. + * + * \param ctx The HMAC_DRBG context. + * \param interval The reseed interval. + */ +void mbedtls_hmac_drbg_set_reseed_interval( mbedtls_hmac_drbg_context *ctx, + int interval ); + +/** + * \brief This function updates the state of the HMAC_DRBG context. + * + * \param ctx The HMAC_DRBG context. + * \param additional The data to update the state with. + * If this is \c NULL, there is no additional data. + * \param add_len Length of \p additional in bytes. + * Unused if \p additional is \c NULL. + * + * \return \c 0 on success, or an error from the underlying + * hash calculation. + */ +int mbedtls_hmac_drbg_update_ret( mbedtls_hmac_drbg_context *ctx, + const unsigned char *additional, size_t add_len ); + +/** + * \brief This function reseeds the HMAC_DRBG context, that is + * extracts data from the entropy source. + * + * \param ctx The HMAC_DRBG context. + * \param additional Additional data to add to the state. + * If this is \c NULL, there is no additional data + * and \p len should be \c 0. + * \param len The length of the additional data. + * This must be at most #MBEDTLS_HMAC_DRBG_MAX_INPUT + * and also at most + * #MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT - \p entropy_len + * where \p entropy_len is the entropy length + * (see mbedtls_hmac_drbg_set_entropy_len()). + * + * \return \c 0 if successful. + * \return #MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED + * if a call to the entropy function failed. + */ +int mbedtls_hmac_drbg_reseed( mbedtls_hmac_drbg_context *ctx, + const unsigned char *additional, size_t len ); + +/** + * \brief This function updates an HMAC_DRBG instance with additional + * data and uses it to generate random data. + * + * This function automatically reseeds if the reseed counter is exceeded + * or prediction resistance is enabled. + * + * \param p_rng The HMAC_DRBG context. This must be a pointer to a + * #mbedtls_hmac_drbg_context structure. + * \param output The buffer to fill. + * \param output_len The length of the buffer in bytes. + * This must be at most #MBEDTLS_HMAC_DRBG_MAX_REQUEST. + * \param additional Additional data to update with. + * If this is \c NULL, there is no additional data + * and \p add_len should be \c 0. + * \param add_len The length of the additional data. + * This must be at most #MBEDTLS_HMAC_DRBG_MAX_INPUT. + * + * \return \c 0 if successful. + * \return #MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED + * if a call to the entropy source failed. + * \return #MBEDTLS_ERR_HMAC_DRBG_REQUEST_TOO_BIG if + * \p output_len > #MBEDTLS_HMAC_DRBG_MAX_REQUEST. + * \return #MBEDTLS_ERR_HMAC_DRBG_INPUT_TOO_BIG if + * \p add_len > #MBEDTLS_HMAC_DRBG_MAX_INPUT. + */ +int mbedtls_hmac_drbg_random_with_add( void *p_rng, + unsigned char *output, size_t output_len, + const unsigned char *additional, + size_t add_len ); + +/** + * \brief This function uses HMAC_DRBG to generate random data. + * + * This function automatically reseeds if the reseed counter is exceeded + * or prediction resistance is enabled. + * + * \param p_rng The HMAC_DRBG context. This must be a pointer to a + * #mbedtls_hmac_drbg_context structure. + * \param output The buffer to fill. + * \param out_len The length of the buffer in bytes. + * This must be at most #MBEDTLS_HMAC_DRBG_MAX_REQUEST. + * + * \return \c 0 if successful. + * \return #MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED + * if a call to the entropy source failed. + * \return #MBEDTLS_ERR_HMAC_DRBG_REQUEST_TOO_BIG if + * \p out_len > #MBEDTLS_HMAC_DRBG_MAX_REQUEST. + */ +int mbedtls_hmac_drbg_random( void *p_rng, unsigned char *output, size_t out_len ); + +/** + * \brief Free an HMAC_DRBG context + * + * \param ctx The HMAC_DRBG context to free. + */ +void mbedtls_hmac_drbg_free( mbedtls_hmac_drbg_context *ctx ); + +#if ! defined(MBEDTLS_DEPRECATED_REMOVED) +#if defined(MBEDTLS_DEPRECATED_WARNING) +#define MBEDTLS_DEPRECATED __attribute__((deprecated)) +#else +#define MBEDTLS_DEPRECATED +#endif +/** + * \brief This function updates the state of the HMAC_DRBG context. + * + * \deprecated Superseded by mbedtls_hmac_drbg_update_ret() + * in 2.16.0. + * + * \param ctx The HMAC_DRBG context. + * \param additional The data to update the state with. + * If this is \c NULL, there is no additional data. + * \param add_len Length of \p additional in bytes. + * Unused if \p additional is \c NULL. + */ +MBEDTLS_DEPRECATED void mbedtls_hmac_drbg_update( + mbedtls_hmac_drbg_context *ctx, + const unsigned char *additional, size_t add_len ); +#undef MBEDTLS_DEPRECATED +#endif /* !MBEDTLS_DEPRECATED_REMOVED */ + +#if defined(MBEDTLS_FS_IO) +/** + * \brief This function writes a seed file. + * + * \param ctx The HMAC_DRBG context. + * \param path The name of the file. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_HMAC_DRBG_FILE_IO_ERROR on file error. + * \return #MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED on reseed + * failure. + */ +int mbedtls_hmac_drbg_write_seed_file( mbedtls_hmac_drbg_context *ctx, const char *path ); + +/** + * \brief This function reads and updates a seed file. The seed + * is added to this instance. + * + * \param ctx The HMAC_DRBG context. + * \param path The name of the file. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_HMAC_DRBG_FILE_IO_ERROR on file error. + * \return #MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED on + * reseed failure. + * \return #MBEDTLS_ERR_HMAC_DRBG_INPUT_TOO_BIG if the existing + * seed file is too large. + */ +int mbedtls_hmac_drbg_update_seed_file( mbedtls_hmac_drbg_context *ctx, const char *path ); +#endif /* MBEDTLS_FS_IO */ + + +#if defined(MBEDTLS_SELF_TEST) +/** + * \brief The HMAC_DRBG Checkup routine. + * + * \return \c 0 if successful. + * \return \c 1 if the test failed. + */ +int mbedtls_hmac_drbg_self_test( int verbose ); +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* hmac_drbg.h */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/md.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/md.h new file mode 100644 index 0000000000000000000000000000000000000000..8bcf766a6ca67792b235d9988483c8db55af95de --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/md.h @@ -0,0 +1,468 @@ + /** + * \file md.h + * + * \brief This file contains the generic message-digest wrapper. + * + * \author Adriaan de Jong + */ +/* + * Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of Mbed TLS (https://tls.mbed.org) + */ + +#ifndef MBEDTLS_MD_H +#define MBEDTLS_MD_H + +#include + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#define MBEDTLS_ERR_MD_FEATURE_UNAVAILABLE -0x5080 /**< The selected feature is not available. */ +#define MBEDTLS_ERR_MD_BAD_INPUT_DATA -0x5100 /**< Bad input parameters to function. */ +#define MBEDTLS_ERR_MD_ALLOC_FAILED -0x5180 /**< Failed to allocate memory. */ +#define MBEDTLS_ERR_MD_FILE_IO_ERROR -0x5200 /**< Opening or reading of file failed. */ + +/* MBEDTLS_ERR_MD_HW_ACCEL_FAILED is deprecated and should not be used. */ +#define MBEDTLS_ERR_MD_HW_ACCEL_FAILED -0x5280 /**< MD hardware accelerator failed. */ + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \brief Supported message digests. + * + * \warning MD2, MD4, MD5 and SHA-1 are considered weak message digests and + * their use constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +typedef enum { + MBEDTLS_MD_NONE=0, /**< None. */ + MBEDTLS_MD_MD2, /**< The MD2 message digest. */ + MBEDTLS_MD_MD4, /**< The MD4 message digest. */ + MBEDTLS_MD_MD5, /**< The MD5 message digest. */ + MBEDTLS_MD_SHA1, /**< The SHA-1 message digest. */ + MBEDTLS_MD_SHA224, /**< The SHA-224 message digest. */ + MBEDTLS_MD_SHA256, /**< The SHA-256 message digest. */ + MBEDTLS_MD_SHA384, /**< The SHA-384 message digest. */ + MBEDTLS_MD_SHA512, /**< The SHA-512 message digest. */ + MBEDTLS_MD_RIPEMD160, /**< The RIPEMD-160 message digest. */ +} mbedtls_md_type_t; + +#if defined(MBEDTLS_SHA512_C) +#define MBEDTLS_MD_MAX_SIZE 64 /* longest known is SHA512 */ +#else +#define MBEDTLS_MD_MAX_SIZE 32 /* longest known is SHA256 or less */ +#endif + +/** + * Opaque struct defined in md_internal.h. + */ +typedef struct mbedtls_md_info_t mbedtls_md_info_t; + +/** + * The generic message-digest context. + */ +typedef struct mbedtls_md_context_t +{ + /** Information about the associated message digest. */ + const mbedtls_md_info_t *md_info; + + /** The digest-specific context. */ + void *md_ctx; + + /** The HMAC part of the context. */ + void *hmac_ctx; +} mbedtls_md_context_t; + +/** + * \brief This function returns the list of digests supported by the + * generic digest module. + * + * \return A statically allocated array of digests. Each element + * in the returned list is an integer belonging to the + * message-digest enumeration #mbedtls_md_type_t. + * The last entry is 0. + */ +const int *mbedtls_md_list( void ); + +/** + * \brief This function returns the message-digest information + * associated with the given digest name. + * + * \param md_name The name of the digest to search for. + * + * \return The message-digest information associated with \p md_name. + * \return NULL if the associated message-digest information is not found. + */ +const mbedtls_md_info_t *mbedtls_md_info_from_string( const char *md_name ); + +/** + * \brief This function returns the message-digest information + * associated with the given digest type. + * + * \param md_type The type of digest to search for. + * + * \return The message-digest information associated with \p md_type. + * \return NULL if the associated message-digest information is not found. + */ +const mbedtls_md_info_t *mbedtls_md_info_from_type( mbedtls_md_type_t md_type ); + +/** + * \brief This function initializes a message-digest context without + * binding it to a particular message-digest algorithm. + * + * This function should always be called first. It prepares the + * context for mbedtls_md_setup() for binding it to a + * message-digest algorithm. + */ +void mbedtls_md_init( mbedtls_md_context_t *ctx ); + +/** + * \brief This function clears the internal structure of \p ctx and + * frees any embedded internal structure, but does not free + * \p ctx itself. + * + * If you have called mbedtls_md_setup() on \p ctx, you must + * call mbedtls_md_free() when you are no longer using the + * context. + * Calling this function if you have previously + * called mbedtls_md_init() and nothing else is optional. + * You must not call this function if you have not called + * mbedtls_md_init(). + */ +void mbedtls_md_free( mbedtls_md_context_t *ctx ); + +#if ! defined(MBEDTLS_DEPRECATED_REMOVED) +#if defined(MBEDTLS_DEPRECATED_WARNING) +#define MBEDTLS_DEPRECATED __attribute__((deprecated)) +#else +#define MBEDTLS_DEPRECATED +#endif +/** + * \brief This function selects the message digest algorithm to use, + * and allocates internal structures. + * + * It should be called after mbedtls_md_init() or mbedtls_md_free(). + * Makes it necessary to call mbedtls_md_free() later. + * + * \deprecated Superseded by mbedtls_md_setup() in 2.0.0 + * + * \param ctx The context to set up. + * \param md_info The information structure of the message-digest algorithm + * to use. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification + * failure. + * \return #MBEDTLS_ERR_MD_ALLOC_FAILED on memory-allocation failure. + */ +int mbedtls_md_init_ctx( mbedtls_md_context_t *ctx, const mbedtls_md_info_t *md_info ) MBEDTLS_DEPRECATED; +#undef MBEDTLS_DEPRECATED +#endif /* MBEDTLS_DEPRECATED_REMOVED */ + +/** + * \brief This function selects the message digest algorithm to use, + * and allocates internal structures. + * + * It should be called after mbedtls_md_init() or + * mbedtls_md_free(). Makes it necessary to call + * mbedtls_md_free() later. + * + * \param ctx The context to set up. + * \param md_info The information structure of the message-digest algorithm + * to use. + * \param hmac Defines if HMAC is used. 0: HMAC is not used (saves some memory), + * or non-zero: HMAC is used with this context. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification + * failure. + * \return #MBEDTLS_ERR_MD_ALLOC_FAILED on memory-allocation failure. + */ +int mbedtls_md_setup( mbedtls_md_context_t *ctx, const mbedtls_md_info_t *md_info, int hmac ); + +/** + * \brief This function clones the state of an message-digest + * context. + * + * \note You must call mbedtls_md_setup() on \c dst before calling + * this function. + * + * \note The two contexts must have the same type, + * for example, both are SHA-256. + * + * \warning This function clones the message-digest state, not the + * HMAC state. + * + * \param dst The destination context. + * \param src The context to be cloned. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification failure. + */ +int mbedtls_md_clone( mbedtls_md_context_t *dst, + const mbedtls_md_context_t *src ); + +/** + * \brief This function extracts the message-digest size from the + * message-digest information structure. + * + * \param md_info The information structure of the message-digest algorithm + * to use. + * + * \return The size of the message-digest output in Bytes. + */ +unsigned char mbedtls_md_get_size( const mbedtls_md_info_t *md_info ); + +/** + * \brief This function extracts the message-digest type from the + * message-digest information structure. + * + * \param md_info The information structure of the message-digest algorithm + * to use. + * + * \return The type of the message digest. + */ +mbedtls_md_type_t mbedtls_md_get_type( const mbedtls_md_info_t *md_info ); + +/** + * \brief This function extracts the message-digest name from the + * message-digest information structure. + * + * \param md_info The information structure of the message-digest algorithm + * to use. + * + * \return The name of the message digest. + */ +const char *mbedtls_md_get_name( const mbedtls_md_info_t *md_info ); + +/** + * \brief This function starts a message-digest computation. + * + * You must call this function after setting up the context + * with mbedtls_md_setup(), and before passing data with + * mbedtls_md_update(). + * + * \param ctx The generic message-digest context. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification + * failure. + */ +int mbedtls_md_starts( mbedtls_md_context_t *ctx ); + +/** + * \brief This function feeds an input buffer into an ongoing + * message-digest computation. + * + * You must call mbedtls_md_starts() before calling this + * function. You may call this function multiple times. + * Afterwards, call mbedtls_md_finish(). + * + * \param ctx The generic message-digest context. + * \param input The buffer holding the input data. + * \param ilen The length of the input data. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification + * failure. + */ +int mbedtls_md_update( mbedtls_md_context_t *ctx, const unsigned char *input, size_t ilen ); + +/** + * \brief This function finishes the digest operation, + * and writes the result to the output buffer. + * + * Call this function after a call to mbedtls_md_starts(), + * followed by any number of calls to mbedtls_md_update(). + * Afterwards, you may either clear the context with + * mbedtls_md_free(), or call mbedtls_md_starts() to reuse + * the context for another digest operation with the same + * algorithm. + * + * \param ctx The generic message-digest context. + * \param output The buffer for the generic message-digest checksum result. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification + * failure. + */ +int mbedtls_md_finish( mbedtls_md_context_t *ctx, unsigned char *output ); + +/** + * \brief This function calculates the message-digest of a buffer, + * with respect to a configurable message-digest algorithm + * in a single call. + * + * The result is calculated as + * Output = message_digest(input buffer). + * + * \param md_info The information structure of the message-digest algorithm + * to use. + * \param input The buffer holding the data. + * \param ilen The length of the input data. + * \param output The generic message-digest checksum result. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification + * failure. + */ +int mbedtls_md( const mbedtls_md_info_t *md_info, const unsigned char *input, size_t ilen, + unsigned char *output ); + +#if defined(MBEDTLS_FS_IO) +/** + * \brief This function calculates the message-digest checksum + * result of the contents of the provided file. + * + * The result is calculated as + * Output = message_digest(file contents). + * + * \param md_info The information structure of the message-digest algorithm + * to use. + * \param path The input file name. + * \param output The generic message-digest checksum result. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MD_FILE_IO_ERROR on an I/O error accessing + * the file pointed by \p path. + * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA if \p md_info was NULL. + */ +int mbedtls_md_file( const mbedtls_md_info_t *md_info, const char *path, + unsigned char *output ); +#endif /* MBEDTLS_FS_IO */ + +/** + * \brief This function sets the HMAC key and prepares to + * authenticate a new message. + * + * Call this function after mbedtls_md_setup(), to use + * the MD context for an HMAC calculation, then call + * mbedtls_md_hmac_update() to provide the input data, and + * mbedtls_md_hmac_finish() to get the HMAC value. + * + * \param ctx The message digest context containing an embedded HMAC + * context. + * \param key The HMAC secret key. + * \param keylen The length of the HMAC key in Bytes. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification + * failure. + */ +int mbedtls_md_hmac_starts( mbedtls_md_context_t *ctx, const unsigned char *key, + size_t keylen ); + +/** + * \brief This function feeds an input buffer into an ongoing HMAC + * computation. + * + * Call mbedtls_md_hmac_starts() or mbedtls_md_hmac_reset() + * before calling this function. + * You may call this function multiple times to pass the + * input piecewise. + * Afterwards, call mbedtls_md_hmac_finish(). + * + * \param ctx The message digest context containing an embedded HMAC + * context. + * \param input The buffer holding the input data. + * \param ilen The length of the input data. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification + * failure. + */ +int mbedtls_md_hmac_update( mbedtls_md_context_t *ctx, const unsigned char *input, + size_t ilen ); + +/** + * \brief This function finishes the HMAC operation, and writes + * the result to the output buffer. + * + * Call this function after mbedtls_md_hmac_starts() and + * mbedtls_md_hmac_update() to get the HMAC value. Afterwards + * you may either call mbedtls_md_free() to clear the context, + * or call mbedtls_md_hmac_reset() to reuse the context with + * the same HMAC key. + * + * \param ctx The message digest context containing an embedded HMAC + * context. + * \param output The generic HMAC checksum result. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification + * failure. + */ +int mbedtls_md_hmac_finish( mbedtls_md_context_t *ctx, unsigned char *output); + +/** + * \brief This function prepares to authenticate a new message with + * the same key as the previous HMAC operation. + * + * You may call this function after mbedtls_md_hmac_finish(). + * Afterwards call mbedtls_md_hmac_update() to pass the new + * input. + * + * \param ctx The message digest context containing an embedded HMAC + * context. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification + * failure. + */ +int mbedtls_md_hmac_reset( mbedtls_md_context_t *ctx ); + +/** + * \brief This function calculates the full generic HMAC + * on the input buffer with the provided key. + * + * The function allocates the context, performs the + * calculation, and frees the context. + * + * The HMAC result is calculated as + * output = generic HMAC(hmac key, input buffer). + * + * \param md_info The information structure of the message-digest algorithm + * to use. + * \param key The HMAC secret key. + * \param keylen The length of the HMAC secret key in Bytes. + * \param input The buffer holding the input data. + * \param ilen The length of the input data. + * \param output The generic HMAC result. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification + * failure. + */ +int mbedtls_md_hmac( const mbedtls_md_info_t *md_info, const unsigned char *key, size_t keylen, + const unsigned char *input, size_t ilen, + unsigned char *output ); + +/* Internal use */ +int mbedtls_md_process( mbedtls_md_context_t *ctx, const unsigned char *data ); + +#ifdef __cplusplus +} +#endif + +#endif /* MBEDTLS_MD_H */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/md2.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/md2.h new file mode 100644 index 0000000000000000000000000000000000000000..fe97cf08d409a91b38f7869c4e6228d1a72f2561 --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/md2.h @@ -0,0 +1,306 @@ +/** + * \file md2.h + * + * \brief MD2 message digest algorithm (hash function) + * + * \warning MD2 is considered a weak message digest and its use constitutes a + * security risk. We recommend considering stronger message digests + * instead. + */ +/* + * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + * + */ +#ifndef MBEDTLS_MD2_H +#define MBEDTLS_MD2_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include + +/* MBEDTLS_ERR_MD2_HW_ACCEL_FAILED is deprecated and should not be used. */ +#define MBEDTLS_ERR_MD2_HW_ACCEL_FAILED -0x002B /**< MD2 hardware accelerator failed */ + +#ifdef __cplusplus +extern "C" { +#endif + +#if !defined(MBEDTLS_MD2_ALT) +// Regular implementation +// + +/** + * \brief MD2 context structure + * + * \warning MD2 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +typedef struct mbedtls_md2_context +{ + unsigned char cksum[16]; /*!< checksum of the data block */ + unsigned char state[48]; /*!< intermediate digest state */ + unsigned char buffer[16]; /*!< data block being processed */ + size_t left; /*!< amount of data in buffer */ +} +mbedtls_md2_context; + +#else /* MBEDTLS_MD2_ALT */ +#include "md2_alt.h" +#endif /* MBEDTLS_MD2_ALT */ + +/** + * \brief Initialize MD2 context + * + * \param ctx MD2 context to be initialized + * + * \warning MD2 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +void mbedtls_md2_init( mbedtls_md2_context *ctx ); + +/** + * \brief Clear MD2 context + * + * \param ctx MD2 context to be cleared + * + * \warning MD2 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +void mbedtls_md2_free( mbedtls_md2_context *ctx ); + +/** + * \brief Clone (the state of) an MD2 context + * + * \param dst The destination context + * \param src The context to be cloned + * + * \warning MD2 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +void mbedtls_md2_clone( mbedtls_md2_context *dst, + const mbedtls_md2_context *src ); + +/** + * \brief MD2 context setup + * + * \param ctx context to be initialized + * + * \return 0 if successful + * + * \warning MD2 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +int mbedtls_md2_starts_ret( mbedtls_md2_context *ctx ); + +/** + * \brief MD2 process buffer + * + * \param ctx MD2 context + * \param input buffer holding the data + * \param ilen length of the input data + * + * \return 0 if successful + * + * \warning MD2 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +int mbedtls_md2_update_ret( mbedtls_md2_context *ctx, + const unsigned char *input, + size_t ilen ); + +/** + * \brief MD2 final digest + * + * \param ctx MD2 context + * \param output MD2 checksum result + * + * \return 0 if successful + * + * \warning MD2 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +int mbedtls_md2_finish_ret( mbedtls_md2_context *ctx, + unsigned char output[16] ); + +/** + * \brief MD2 process data block (internal use only) + * + * \param ctx MD2 context + * + * \return 0 if successful + * + * \warning MD2 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +int mbedtls_internal_md2_process( mbedtls_md2_context *ctx ); + +#if !defined(MBEDTLS_DEPRECATED_REMOVED) +#if defined(MBEDTLS_DEPRECATED_WARNING) +#define MBEDTLS_DEPRECATED __attribute__((deprecated)) +#else +#define MBEDTLS_DEPRECATED +#endif +/** + * \brief MD2 context setup + * + * \deprecated Superseded by mbedtls_md2_starts_ret() in 2.7.0 + * + * \param ctx context to be initialized + * + * \warning MD2 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +MBEDTLS_DEPRECATED void mbedtls_md2_starts( mbedtls_md2_context *ctx ); + +/** + * \brief MD2 process buffer + * + * \deprecated Superseded by mbedtls_md2_update_ret() in 2.7.0 + * + * \param ctx MD2 context + * \param input buffer holding the data + * \param ilen length of the input data + * + * \warning MD2 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +MBEDTLS_DEPRECATED void mbedtls_md2_update( mbedtls_md2_context *ctx, + const unsigned char *input, + size_t ilen ); + +/** + * \brief MD2 final digest + * + * \deprecated Superseded by mbedtls_md2_finish_ret() in 2.7.0 + * + * \param ctx MD2 context + * \param output MD2 checksum result + * + * \warning MD2 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +MBEDTLS_DEPRECATED void mbedtls_md2_finish( mbedtls_md2_context *ctx, + unsigned char output[16] ); + +/** + * \brief MD2 process data block (internal use only) + * + * \deprecated Superseded by mbedtls_internal_md2_process() in 2.7.0 + * + * \param ctx MD2 context + * + * \warning MD2 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +MBEDTLS_DEPRECATED void mbedtls_md2_process( mbedtls_md2_context *ctx ); + +#undef MBEDTLS_DEPRECATED +#endif /* !MBEDTLS_DEPRECATED_REMOVED */ + +/** + * \brief Output = MD2( input buffer ) + * + * \param input buffer holding the data + * \param ilen length of the input data + * \param output MD2 checksum result + * + * \warning MD2 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +int mbedtls_md2_ret( const unsigned char *input, + size_t ilen, + unsigned char output[16] ); + +#if !defined(MBEDTLS_DEPRECATED_REMOVED) +#if defined(MBEDTLS_DEPRECATED_WARNING) +#define MBEDTLS_DEPRECATED __attribute__((deprecated)) +#else +#define MBEDTLS_DEPRECATED +#endif +/** + * \brief Output = MD2( input buffer ) + * + * \deprecated Superseded by mbedtls_md2_ret() in 2.7.0 + * + * \param input buffer holding the data + * \param ilen length of the input data + * \param output MD2 checksum result + * + * \warning MD2 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +MBEDTLS_DEPRECATED void mbedtls_md2( const unsigned char *input, + size_t ilen, + unsigned char output[16] ); + +#undef MBEDTLS_DEPRECATED +#endif /* !MBEDTLS_DEPRECATED_REMOVED */ + +#if defined(MBEDTLS_SELF_TEST) + +/** + * \brief Checkup routine + * + * \return 0 if successful, or 1 if the test failed + * + * \warning MD2 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +int mbedtls_md2_self_test( int verbose ); + +#endif /* MBEDTLS_SELF_TEST */ + +#ifdef __cplusplus +} +#endif + +#endif /* mbedtls_md2.h */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/md4.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/md4.h new file mode 100644 index 0000000000000000000000000000000000000000..ce703c0ba4f3fd1ab241272b26b1e3e237f06f3a --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/md4.h @@ -0,0 +1,311 @@ +/** + * \file md4.h + * + * \brief MD4 message digest algorithm (hash function) + * + * \warning MD4 is considered a weak message digest and its use constitutes a + * security risk. We recommend considering stronger message digests + * instead. + */ +/* + * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + * + */ +#ifndef MBEDTLS_MD4_H +#define MBEDTLS_MD4_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include +#include + +/* MBEDTLS_ERR_MD4_HW_ACCEL_FAILED is deprecated and should not be used. */ +#define MBEDTLS_ERR_MD4_HW_ACCEL_FAILED -0x002D /**< MD4 hardware accelerator failed */ + +#ifdef __cplusplus +extern "C" { +#endif + +#if !defined(MBEDTLS_MD4_ALT) +// Regular implementation +// + +/** + * \brief MD4 context structure + * + * \warning MD4 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +typedef struct mbedtls_md4_context +{ + uint32_t total[2]; /*!< number of bytes processed */ + uint32_t state[4]; /*!< intermediate digest state */ + unsigned char buffer[64]; /*!< data block being processed */ +} +mbedtls_md4_context; + +#else /* MBEDTLS_MD4_ALT */ +#include "md4_alt.h" +#endif /* MBEDTLS_MD4_ALT */ + +/** + * \brief Initialize MD4 context + * + * \param ctx MD4 context to be initialized + * + * \warning MD4 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +void mbedtls_md4_init( mbedtls_md4_context *ctx ); + +/** + * \brief Clear MD4 context + * + * \param ctx MD4 context to be cleared + * + * \warning MD4 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +void mbedtls_md4_free( mbedtls_md4_context *ctx ); + +/** + * \brief Clone (the state of) an MD4 context + * + * \param dst The destination context + * \param src The context to be cloned + * + * \warning MD4 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +void mbedtls_md4_clone( mbedtls_md4_context *dst, + const mbedtls_md4_context *src ); + +/** + * \brief MD4 context setup + * + * \param ctx context to be initialized + * + * \return 0 if successful + * + * \warning MD4 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + */ +int mbedtls_md4_starts_ret( mbedtls_md4_context *ctx ); + +/** + * \brief MD4 process buffer + * + * \param ctx MD4 context + * \param input buffer holding the data + * \param ilen length of the input data + * + * \return 0 if successful + * + * \warning MD4 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +int mbedtls_md4_update_ret( mbedtls_md4_context *ctx, + const unsigned char *input, + size_t ilen ); + +/** + * \brief MD4 final digest + * + * \param ctx MD4 context + * \param output MD4 checksum result + * + * \return 0 if successful + * + * \warning MD4 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +int mbedtls_md4_finish_ret( mbedtls_md4_context *ctx, + unsigned char output[16] ); + +/** + * \brief MD4 process data block (internal use only) + * + * \param ctx MD4 context + * \param data buffer holding one block of data + * + * \return 0 if successful + * + * \warning MD4 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +int mbedtls_internal_md4_process( mbedtls_md4_context *ctx, + const unsigned char data[64] ); + +#if !defined(MBEDTLS_DEPRECATED_REMOVED) +#if defined(MBEDTLS_DEPRECATED_WARNING) +#define MBEDTLS_DEPRECATED __attribute__((deprecated)) +#else +#define MBEDTLS_DEPRECATED +#endif +/** + * \brief MD4 context setup + * + * \deprecated Superseded by mbedtls_md4_starts_ret() in 2.7.0 + * + * \param ctx context to be initialized + * + * \warning MD4 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +MBEDTLS_DEPRECATED void mbedtls_md4_starts( mbedtls_md4_context *ctx ); + +/** + * \brief MD4 process buffer + * + * \deprecated Superseded by mbedtls_md4_update_ret() in 2.7.0 + * + * \param ctx MD4 context + * \param input buffer holding the data + * \param ilen length of the input data + * + * \warning MD4 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +MBEDTLS_DEPRECATED void mbedtls_md4_update( mbedtls_md4_context *ctx, + const unsigned char *input, + size_t ilen ); + +/** + * \brief MD4 final digest + * + * \deprecated Superseded by mbedtls_md4_finish_ret() in 2.7.0 + * + * \param ctx MD4 context + * \param output MD4 checksum result + * + * \warning MD4 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +MBEDTLS_DEPRECATED void mbedtls_md4_finish( mbedtls_md4_context *ctx, + unsigned char output[16] ); + +/** + * \brief MD4 process data block (internal use only) + * + * \deprecated Superseded by mbedtls_internal_md4_process() in 2.7.0 + * + * \param ctx MD4 context + * \param data buffer holding one block of data + * + * \warning MD4 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +MBEDTLS_DEPRECATED void mbedtls_md4_process( mbedtls_md4_context *ctx, + const unsigned char data[64] ); + +#undef MBEDTLS_DEPRECATED +#endif /* !MBEDTLS_DEPRECATED_REMOVED */ + +/** + * \brief Output = MD4( input buffer ) + * + * \param input buffer holding the data + * \param ilen length of the input data + * \param output MD4 checksum result + * + * \return 0 if successful + * + * \warning MD4 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +int mbedtls_md4_ret( const unsigned char *input, + size_t ilen, + unsigned char output[16] ); + +#if !defined(MBEDTLS_DEPRECATED_REMOVED) +#if defined(MBEDTLS_DEPRECATED_WARNING) +#define MBEDTLS_DEPRECATED __attribute__((deprecated)) +#else +#define MBEDTLS_DEPRECATED +#endif +/** + * \brief Output = MD4( input buffer ) + * + * \deprecated Superseded by mbedtls_md4_ret() in 2.7.0 + * + * \param input buffer holding the data + * \param ilen length of the input data + * \param output MD4 checksum result + * + * \warning MD4 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +MBEDTLS_DEPRECATED void mbedtls_md4( const unsigned char *input, + size_t ilen, + unsigned char output[16] ); + +#undef MBEDTLS_DEPRECATED +#endif /* !MBEDTLS_DEPRECATED_REMOVED */ + +#if defined(MBEDTLS_SELF_TEST) + +/** + * \brief Checkup routine + * + * \return 0 if successful, or 1 if the test failed + * + * \warning MD4 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +int mbedtls_md4_self_test( int verbose ); + +#endif /* MBEDTLS_SELF_TEST */ + +#ifdef __cplusplus +} +#endif + +#endif /* mbedtls_md4.h */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/md5.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/md5.h new file mode 100644 index 0000000000000000000000000000000000000000..6eed6cc864aae8fb2976ea4bc4c99fcc334788fa --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/md5.h @@ -0,0 +1,311 @@ +/** + * \file md5.h + * + * \brief MD5 message digest algorithm (hash function) + * + * \warning MD5 is considered a weak message digest and its use constitutes a + * security risk. We recommend considering stronger message + * digests instead. + */ +/* + * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ +#ifndef MBEDTLS_MD5_H +#define MBEDTLS_MD5_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include +#include + +/* MBEDTLS_ERR_MD5_HW_ACCEL_FAILED is deprecated and should not be used. */ +#define MBEDTLS_ERR_MD5_HW_ACCEL_FAILED -0x002F /**< MD5 hardware accelerator failed */ + +#ifdef __cplusplus +extern "C" { +#endif + +#if !defined(MBEDTLS_MD5_ALT) +// Regular implementation +// + +/** + * \brief MD5 context structure + * + * \warning MD5 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +typedef struct mbedtls_md5_context +{ + uint32_t total[2]; /*!< number of bytes processed */ + uint32_t state[4]; /*!< intermediate digest state */ + unsigned char buffer[64]; /*!< data block being processed */ +} +mbedtls_md5_context; + +#else /* MBEDTLS_MD5_ALT */ +#include "md5_alt.h" +#endif /* MBEDTLS_MD5_ALT */ + +/** + * \brief Initialize MD5 context + * + * \param ctx MD5 context to be initialized + * + * \warning MD5 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +void mbedtls_md5_init( mbedtls_md5_context *ctx ); + +/** + * \brief Clear MD5 context + * + * \param ctx MD5 context to be cleared + * + * \warning MD5 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +void mbedtls_md5_free( mbedtls_md5_context *ctx ); + +/** + * \brief Clone (the state of) an MD5 context + * + * \param dst The destination context + * \param src The context to be cloned + * + * \warning MD5 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +void mbedtls_md5_clone( mbedtls_md5_context *dst, + const mbedtls_md5_context *src ); + +/** + * \brief MD5 context setup + * + * \param ctx context to be initialized + * + * \return 0 if successful + * + * \warning MD5 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +int mbedtls_md5_starts_ret( mbedtls_md5_context *ctx ); + +/** + * \brief MD5 process buffer + * + * \param ctx MD5 context + * \param input buffer holding the data + * \param ilen length of the input data + * + * \return 0 if successful + * + * \warning MD5 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +int mbedtls_md5_update_ret( mbedtls_md5_context *ctx, + const unsigned char *input, + size_t ilen ); + +/** + * \brief MD5 final digest + * + * \param ctx MD5 context + * \param output MD5 checksum result + * + * \return 0 if successful + * + * \warning MD5 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +int mbedtls_md5_finish_ret( mbedtls_md5_context *ctx, + unsigned char output[16] ); + +/** + * \brief MD5 process data block (internal use only) + * + * \param ctx MD5 context + * \param data buffer holding one block of data + * + * \return 0 if successful + * + * \warning MD5 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +int mbedtls_internal_md5_process( mbedtls_md5_context *ctx, + const unsigned char data[64] ); + +#if !defined(MBEDTLS_DEPRECATED_REMOVED) +#if defined(MBEDTLS_DEPRECATED_WARNING) +#define MBEDTLS_DEPRECATED __attribute__((deprecated)) +#else +#define MBEDTLS_DEPRECATED +#endif +/** + * \brief MD5 context setup + * + * \deprecated Superseded by mbedtls_md5_starts_ret() in 2.7.0 + * + * \param ctx context to be initialized + * + * \warning MD5 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +MBEDTLS_DEPRECATED void mbedtls_md5_starts( mbedtls_md5_context *ctx ); + +/** + * \brief MD5 process buffer + * + * \deprecated Superseded by mbedtls_md5_update_ret() in 2.7.0 + * + * \param ctx MD5 context + * \param input buffer holding the data + * \param ilen length of the input data + * + * \warning MD5 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +MBEDTLS_DEPRECATED void mbedtls_md5_update( mbedtls_md5_context *ctx, + const unsigned char *input, + size_t ilen ); + +/** + * \brief MD5 final digest + * + * \deprecated Superseded by mbedtls_md5_finish_ret() in 2.7.0 + * + * \param ctx MD5 context + * \param output MD5 checksum result + * + * \warning MD5 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +MBEDTLS_DEPRECATED void mbedtls_md5_finish( mbedtls_md5_context *ctx, + unsigned char output[16] ); + +/** + * \brief MD5 process data block (internal use only) + * + * \deprecated Superseded by mbedtls_internal_md5_process() in 2.7.0 + * + * \param ctx MD5 context + * \param data buffer holding one block of data + * + * \warning MD5 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +MBEDTLS_DEPRECATED void mbedtls_md5_process( mbedtls_md5_context *ctx, + const unsigned char data[64] ); + +#undef MBEDTLS_DEPRECATED +#endif /* !MBEDTLS_DEPRECATED_REMOVED */ + +/** + * \brief Output = MD5( input buffer ) + * + * \param input buffer holding the data + * \param ilen length of the input data + * \param output MD5 checksum result + * + * \return 0 if successful + * + * \warning MD5 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +int mbedtls_md5_ret( const unsigned char *input, + size_t ilen, + unsigned char output[16] ); + +#if !defined(MBEDTLS_DEPRECATED_REMOVED) +#if defined(MBEDTLS_DEPRECATED_WARNING) +#define MBEDTLS_DEPRECATED __attribute__((deprecated)) +#else +#define MBEDTLS_DEPRECATED +#endif +/** + * \brief Output = MD5( input buffer ) + * + * \deprecated Superseded by mbedtls_md5_ret() in 2.7.0 + * + * \param input buffer holding the data + * \param ilen length of the input data + * \param output MD5 checksum result + * + * \warning MD5 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +MBEDTLS_DEPRECATED void mbedtls_md5( const unsigned char *input, + size_t ilen, + unsigned char output[16] ); + +#undef MBEDTLS_DEPRECATED +#endif /* !MBEDTLS_DEPRECATED_REMOVED */ + +#if defined(MBEDTLS_SELF_TEST) + +/** + * \brief Checkup routine + * + * \return 0 if successful, or 1 if the test failed + * + * \warning MD5 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +int mbedtls_md5_self_test( int verbose ); + +#endif /* MBEDTLS_SELF_TEST */ + +#ifdef __cplusplus +} +#endif + +#endif /* mbedtls_md5.h */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/md5_alt.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/md5_alt.h new file mode 100644 index 0000000000000000000000000000000000000000..7d84c730289a8410e6648d2795721f5c6b7aad08 --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/md5_alt.h @@ -0,0 +1,51 @@ +/** + * \file md5.h + * + * \brief MD5 message digest algorithm (hash function) + * + * \warning MD5 is considered a weak message digest and its use constitutes a + * security risk. We recommend considering stronger message + * digests instead. + */ +/* + * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ +#ifndef MBEDTLS_MD5_ALT_H +#define MBEDTLS_MD5_ALT_H + +#if defined(MBEDTLS_MD5_ALT) + +/** + * \brief MD5 context structure + * + * \warning MD5 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +typedef struct mbedtls_md5_context +{ + uint32_t total[2]; /*!< number of bytes processed */ + uint32_t state[4]; /*!< intermediate digest state */ + unsigned char buffer[64]; /*!< data block being processed */ +} +mbedtls_md5_context; + +#endif /* MBEDTLS_MD5_ALT */ + +#endif /* mbedtls_md5_alt.h */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/md_internal.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/md_internal.h new file mode 100644 index 0000000000000000000000000000000000000000..04de48291844e0af67107cad1d45a8fcb42c83b5 --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/md_internal.h @@ -0,0 +1,115 @@ +/** + * \file md_internal.h + * + * \brief Message digest wrappers. + * + * \warning This in an internal header. Do not include directly. + * + * \author Adriaan de Jong + */ +/* + * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ +#ifndef MBEDTLS_MD_WRAP_H +#define MBEDTLS_MD_WRAP_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include "md.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Message digest information. + * Allows message digest functions to be called in a generic way. + */ +struct mbedtls_md_info_t +{ + /** Digest identifier */ + mbedtls_md_type_t type; + + /** Name of the message digest */ + const char * name; + + /** Output length of the digest function in bytes */ + int size; + + /** Block length of the digest function in bytes */ + int block_size; + + /** Digest initialisation function */ + int (*starts_func)( void *ctx ); + + /** Digest update function */ + int (*update_func)( void *ctx, const unsigned char *input, size_t ilen ); + + /** Digest finalisation function */ + int (*finish_func)( void *ctx, unsigned char *output ); + + /** Generic digest function */ + int (*digest_func)( const unsigned char *input, size_t ilen, + unsigned char *output ); + + /** Allocate a new context */ + void * (*ctx_alloc_func)( void ); + + /** Free the given context */ + void (*ctx_free_func)( void *ctx ); + + /** Clone state from a context */ + void (*clone_func)( void *dst, const void *src ); + + /** Internal use only */ + int (*process_func)( void *ctx, const unsigned char *input ); +}; + +#if defined(MBEDTLS_MD2_C) +extern const mbedtls_md_info_t mbedtls_md2_info; +#endif +#if defined(MBEDTLS_MD4_C) +extern const mbedtls_md_info_t mbedtls_md4_info; +#endif +#if defined(MBEDTLS_MD5_C) +extern const mbedtls_md_info_t mbedtls_md5_info; +#endif +#if defined(MBEDTLS_RIPEMD160_C) +extern const mbedtls_md_info_t mbedtls_ripemd160_info; +#endif +#if defined(MBEDTLS_SHA1_C) +extern const mbedtls_md_info_t mbedtls_sha1_info; +#endif +#if defined(MBEDTLS_SHA256_C) +extern const mbedtls_md_info_t mbedtls_sha224_info; +extern const mbedtls_md_info_t mbedtls_sha256_info; +#endif +#if defined(MBEDTLS_SHA512_C) +extern const mbedtls_md_info_t mbedtls_sha384_info; +extern const mbedtls_md_info_t mbedtls_sha512_info; +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* MBEDTLS_MD_WRAP_H */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/memory_buffer_alloc.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/memory_buffer_alloc.h new file mode 100644 index 0000000000000000000000000000000000000000..705f9a636900fde07a9e27d56946283b0b3751ed --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/memory_buffer_alloc.h @@ -0,0 +1,151 @@ +/** + * \file memory_buffer_alloc.h + * + * \brief Buffer-based memory allocator + */ +/* + * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ +#ifndef MBEDTLS_MEMORY_BUFFER_ALLOC_H +#define MBEDTLS_MEMORY_BUFFER_ALLOC_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include + +/** + * \name SECTION: Module settings + * + * The configuration options you can set for this module are in this section. + * Either change them in config.h or define them on the compiler command line. + * \{ + */ + +#if !defined(MBEDTLS_MEMORY_ALIGN_MULTIPLE) +#define MBEDTLS_MEMORY_ALIGN_MULTIPLE 4 /**< Align on multiples of this value */ +#endif + +/* \} name SECTION: Module settings */ + +#define MBEDTLS_MEMORY_VERIFY_NONE 0 +#define MBEDTLS_MEMORY_VERIFY_ALLOC (1 << 0) +#define MBEDTLS_MEMORY_VERIFY_FREE (1 << 1) +#define MBEDTLS_MEMORY_VERIFY_ALWAYS (MBEDTLS_MEMORY_VERIFY_ALLOC | MBEDTLS_MEMORY_VERIFY_FREE) + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \brief Initialize use of stack-based memory allocator. + * The stack-based allocator does memory management inside the + * presented buffer and does not call calloc() and free(). + * It sets the global mbedtls_calloc() and mbedtls_free() pointers + * to its own functions. + * (Provided mbedtls_calloc() and mbedtls_free() are thread-safe if + * MBEDTLS_THREADING_C is defined) + * + * \note This code is not optimized and provides a straight-forward + * implementation of a stack-based memory allocator. + * + * \param buf buffer to use as heap + * \param len size of the buffer + */ +void mbedtls_memory_buffer_alloc_init( unsigned char *buf, size_t len ); + +/** + * \brief Free the mutex for thread-safety and clear remaining memory + */ +void mbedtls_memory_buffer_alloc_free( void ); + +/** + * \brief Determine when the allocator should automatically verify the state + * of the entire chain of headers / meta-data. + * (Default: MBEDTLS_MEMORY_VERIFY_NONE) + * + * \param verify One of MBEDTLS_MEMORY_VERIFY_NONE, MBEDTLS_MEMORY_VERIFY_ALLOC, + * MBEDTLS_MEMORY_VERIFY_FREE or MBEDTLS_MEMORY_VERIFY_ALWAYS + */ +void mbedtls_memory_buffer_set_verify( int verify ); + +#if defined(MBEDTLS_MEMORY_DEBUG) +/** + * \brief Print out the status of the allocated memory (primarily for use + * after a program should have de-allocated all memory) + * Prints out a list of 'still allocated' blocks and their stack + * trace if MBEDTLS_MEMORY_BACKTRACE is defined. + */ +void mbedtls_memory_buffer_alloc_status( void ); + +/** + * \brief Get the peak heap usage so far + * + * \param max_used Peak number of bytes in use or committed. This + * includes bytes in allocated blocks too small to split + * into smaller blocks but larger than the requested size. + * \param max_blocks Peak number of blocks in use, including free and used + */ +void mbedtls_memory_buffer_alloc_max_get( size_t *max_used, size_t *max_blocks ); + +/** + * \brief Reset peak statistics + */ +void mbedtls_memory_buffer_alloc_max_reset( void ); + +/** + * \brief Get the current heap usage + * + * \param cur_used Current number of bytes in use or committed. This + * includes bytes in allocated blocks too small to split + * into smaller blocks but larger than the requested size. + * \param cur_blocks Current number of blocks in use, including free and used + */ +void mbedtls_memory_buffer_alloc_cur_get( size_t *cur_used, size_t *cur_blocks ); +#endif /* MBEDTLS_MEMORY_DEBUG */ + +/** + * \brief Verifies that all headers in the memory buffer are correct + * and contain sane values. Helps debug buffer-overflow errors. + * + * Prints out first failure if MBEDTLS_MEMORY_DEBUG is defined. + * Prints out full header information if MBEDTLS_MEMORY_DEBUG + * is defined. (Includes stack trace information for each block if + * MBEDTLS_MEMORY_BACKTRACE is defined as well). + * + * \return 0 if verified, 1 otherwise + */ +int mbedtls_memory_buffer_alloc_verify( void ); + +#if defined(MBEDTLS_SELF_TEST) +/** + * \brief Checkup routine + * + * \return 0 if successful, or 1 if a test failed + */ +int mbedtls_memory_buffer_alloc_self_test( int verbose ); +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* memory_buffer_alloc.h */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/net.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/net.h new file mode 100644 index 0000000000000000000000000000000000000000..8cead58e5df2c9b76252da48ff868d2b16d03fcb --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/net.h @@ -0,0 +1,37 @@ +/** + * \file net.h + * + * \brief Deprecated header file that includes net_sockets.h + * + * \deprecated Superseded by mbedtls/net_sockets.h + */ +/* + * Copyright (C) 2006-2016, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#if !defined(MBEDTLS_DEPRECATED_REMOVED) +#include "net_sockets.h" +#if defined(MBEDTLS_DEPRECATED_WARNING) +#warning "Deprecated header file: Superseded by mbedtls/net_sockets.h" +#endif /* MBEDTLS_DEPRECATED_WARNING */ +#endif /* !MBEDTLS_DEPRECATED_REMOVED */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/net_sockets.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/net_sockets.h new file mode 100644 index 0000000000000000000000000000000000000000..4c7ef00fe667e49b6e7bf1816446492e344d0dce --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/net_sockets.h @@ -0,0 +1,271 @@ +/** + * \file net_sockets.h + * + * \brief Network sockets abstraction layer to integrate Mbed TLS into a + * BSD-style sockets API. + * + * The network sockets module provides an example integration of the + * Mbed TLS library into a BSD sockets implementation. The module is + * intended to be an example of how Mbed TLS can be integrated into a + * networking stack, as well as to be Mbed TLS's network integration + * for its supported platforms. + * + * The module is intended only to be used with the Mbed TLS library and + * is not intended to be used by third party application software + * directly. + * + * The supported platforms are as follows: + * * Microsoft Windows and Windows CE + * * POSIX/Unix platforms including Linux, OS X + * + */ +/* + * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ +#ifndef MBEDTLS_NET_SOCKETS_H +#define MBEDTLS_NET_SOCKETS_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include "ssl.h" + +#include +#include + +#define MBEDTLS_ERR_NET_SOCKET_FAILED -0x0042 /**< Failed to open a socket. */ +#define MBEDTLS_ERR_NET_CONNECT_FAILED -0x0044 /**< The connection to the given server / port failed. */ +#define MBEDTLS_ERR_NET_BIND_FAILED -0x0046 /**< Binding of the socket failed. */ +#define MBEDTLS_ERR_NET_LISTEN_FAILED -0x0048 /**< Could not listen on the socket. */ +#define MBEDTLS_ERR_NET_ACCEPT_FAILED -0x004A /**< Could not accept the incoming connection. */ +#define MBEDTLS_ERR_NET_RECV_FAILED -0x004C /**< Reading information from the socket failed. */ +#define MBEDTLS_ERR_NET_SEND_FAILED -0x004E /**< Sending information through the socket failed. */ +#define MBEDTLS_ERR_NET_CONN_RESET -0x0050 /**< Connection was reset by peer. */ +#define MBEDTLS_ERR_NET_UNKNOWN_HOST -0x0052 /**< Failed to get an IP address for the given hostname. */ +#define MBEDTLS_ERR_NET_BUFFER_TOO_SMALL -0x0043 /**< Buffer is too small to hold the data. */ +#define MBEDTLS_ERR_NET_INVALID_CONTEXT -0x0045 /**< The context is invalid, eg because it was free()ed. */ +#define MBEDTLS_ERR_NET_POLL_FAILED -0x0047 /**< Polling the net context failed. */ +#define MBEDTLS_ERR_NET_BAD_INPUT_DATA -0x0049 /**< Input invalid. */ + +#define MBEDTLS_NET_LISTEN_BACKLOG 10 /**< The backlog that listen() should use. */ + +#define MBEDTLS_NET_PROTO_TCP 0 /**< The TCP transport protocol */ +#define MBEDTLS_NET_PROTO_UDP 1 /**< The UDP transport protocol */ + +#define MBEDTLS_NET_POLL_READ 1 /**< Used in \c mbedtls_net_poll to check for pending data */ +#define MBEDTLS_NET_POLL_WRITE 2 /**< Used in \c mbedtls_net_poll to check if write possible */ + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Wrapper type for sockets. + * + * Currently backed by just a file descriptor, but might be more in the future + * (eg two file descriptors for combined IPv4 + IPv6 support, or additional + * structures for hand-made UDP demultiplexing). + */ +typedef struct mbedtls_net_context +{ + int fd; /**< The underlying file descriptor */ +} +mbedtls_net_context; + +/** + * \brief Initialize a context + * Just makes the context ready to be used or freed safely. + * + * \param ctx Context to initialize + */ +void mbedtls_net_init( mbedtls_net_context *ctx ); + +/** + * \brief Initiate a connection with host:port in the given protocol + * + * \param ctx Socket to use + * \param host Host to connect to + * \param port Port to connect to + * \param proto Protocol: MBEDTLS_NET_PROTO_TCP or MBEDTLS_NET_PROTO_UDP + * + * \return 0 if successful, or one of: + * MBEDTLS_ERR_NET_SOCKET_FAILED, + * MBEDTLS_ERR_NET_UNKNOWN_HOST, + * MBEDTLS_ERR_NET_CONNECT_FAILED + * + * \note Sets the socket in connected mode even with UDP. + */ +int mbedtls_net_connect( mbedtls_net_context *ctx, const char *host, const char *port, int proto ); + +/** + * \brief Create a receiving socket on bind_ip:port in the chosen + * protocol. If bind_ip == NULL, all interfaces are bound. + * + * \param ctx Socket to use + * \param bind_ip IP to bind to, can be NULL + * \param port Port number to use + * \param proto Protocol: MBEDTLS_NET_PROTO_TCP or MBEDTLS_NET_PROTO_UDP + * + * \return 0 if successful, or one of: + * MBEDTLS_ERR_NET_SOCKET_FAILED, + * MBEDTLS_ERR_NET_BIND_FAILED, + * MBEDTLS_ERR_NET_LISTEN_FAILED + * + * \note Regardless of the protocol, opens the sockets and binds it. + * In addition, make the socket listening if protocol is TCP. + */ +int mbedtls_net_bind( mbedtls_net_context *ctx, const char *bind_ip, const char *port, int proto ); + +/** + * \brief Accept a connection from a remote client + * + * \param bind_ctx Relevant socket + * \param client_ctx Will contain the connected client socket + * \param client_ip Will contain the client IP address, can be NULL + * \param buf_size Size of the client_ip buffer + * \param ip_len Will receive the size of the client IP written, + * can be NULL if client_ip is null + * + * \return 0 if successful, or + * MBEDTLS_ERR_NET_ACCEPT_FAILED, or + * MBEDTLS_ERR_NET_BUFFER_TOO_SMALL if buf_size is too small, + * MBEDTLS_ERR_SSL_WANT_READ if bind_fd was set to + * non-blocking and accept() would block. + */ +int mbedtls_net_accept( mbedtls_net_context *bind_ctx, + mbedtls_net_context *client_ctx, + void *client_ip, size_t buf_size, size_t *ip_len ); + +/** + * \brief Check and wait for the context to be ready for read/write + * + * \param ctx Socket to check + * \param rw Bitflag composed of MBEDTLS_NET_POLL_READ and + * MBEDTLS_NET_POLL_WRITE specifying the events + * to wait for: + * - If MBEDTLS_NET_POLL_READ is set, the function + * will return as soon as the net context is available + * for reading. + * - If MBEDTLS_NET_POLL_WRITE is set, the function + * will return as soon as the net context is available + * for writing. + * \param timeout Maximal amount of time to wait before returning, + * in milliseconds. If \c timeout is zero, the + * function returns immediately. If \c timeout is + * -1u, the function blocks potentially indefinitely. + * + * \return Bitmask composed of MBEDTLS_NET_POLL_READ/WRITE + * on success or timeout, or a negative return code otherwise. + */ +int mbedtls_net_poll( mbedtls_net_context *ctx, uint32_t rw, uint32_t timeout ); + +/** + * \brief Set the socket blocking + * + * \param ctx Socket to set + * + * \return 0 if successful, or a non-zero error code + */ +int mbedtls_net_set_block( mbedtls_net_context *ctx ); + +/** + * \brief Set the socket non-blocking + * + * \param ctx Socket to set + * + * \return 0 if successful, or a non-zero error code + */ +int mbedtls_net_set_nonblock( mbedtls_net_context *ctx ); + +/** + * \brief Portable usleep helper + * + * \param usec Amount of microseconds to sleep + * + * \note Real amount of time slept will not be less than + * select()'s timeout granularity (typically, 10ms). + */ +void mbedtls_net_usleep( unsigned long usec ); + +/** + * \brief Read at most 'len' characters. If no error occurs, + * the actual amount read is returned. + * + * \param ctx Socket + * \param buf The buffer to write to + * \param len Maximum length of the buffer + * + * \return the number of bytes received, + * or a non-zero error code; with a non-blocking socket, + * MBEDTLS_ERR_SSL_WANT_READ indicates read() would block. + */ +int mbedtls_net_recv( void *ctx, unsigned char *buf, size_t len ); + +/** + * \brief Write at most 'len' characters. If no error occurs, + * the actual amount read is returned. + * + * \param ctx Socket + * \param buf The buffer to read from + * \param len The length of the buffer + * + * \return the number of bytes sent, + * or a non-zero error code; with a non-blocking socket, + * MBEDTLS_ERR_SSL_WANT_WRITE indicates write() would block. + */ +int mbedtls_net_send( void *ctx, const unsigned char *buf, size_t len ); + +/** + * \brief Read at most 'len' characters, blocking for at most + * 'timeout' seconds. If no error occurs, the actual amount + * read is returned. + * + * \param ctx Socket + * \param buf The buffer to write to + * \param len Maximum length of the buffer + * \param timeout Maximum number of milliseconds to wait for data + * 0 means no timeout (wait forever) + * + * \return the number of bytes received, + * or a non-zero error code: + * MBEDTLS_ERR_SSL_TIMEOUT if the operation timed out, + * MBEDTLS_ERR_SSL_WANT_READ if interrupted by a signal. + * + * \note This function will block (until data becomes available or + * timeout is reached) even if the socket is set to + * non-blocking. Handling timeouts with non-blocking reads + * requires a different strategy. + */ +int mbedtls_net_recv_timeout( void *ctx, unsigned char *buf, size_t len, + uint32_t timeout ); + +/** + * \brief Gracefully shutdown the connection and free associated data + * + * \param ctx The context to free + */ +void mbedtls_net_free( mbedtls_net_context *ctx ); + +#ifdef __cplusplus +} +#endif + +#endif /* net_sockets.h */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/nist_kw.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/nist_kw.h new file mode 100644 index 0000000000000000000000000000000000000000..3b67b59cd2972753928ca7309fdfc9b9a6cd6b13 --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/nist_kw.h @@ -0,0 +1,184 @@ +/** + * \file nist_kw.h + * + * \brief This file provides an API for key wrapping (KW) and key wrapping with + * padding (KWP) as defined in NIST SP 800-38F. + * https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf + * + * Key wrapping specifies a deterministic authenticated-encryption mode + * of operation, according to NIST SP 800-38F: Recommendation for + * Block Cipher Modes of Operation: Methods for Key Wrapping. Its + * purpose is to protect cryptographic keys. + * + * Its equivalent is RFC 3394 for KW, and RFC 5649 for KWP. + * https://tools.ietf.org/html/rfc3394 + * https://tools.ietf.org/html/rfc5649 + * + */ +/* + * Copyright (C) 2018, Arm Limited (or its affiliates), All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of Mbed TLS (https://tls.mbed.org) + */ + +#ifndef MBEDTLS_NIST_KW_H +#define MBEDTLS_NIST_KW_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include "cipher.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum +{ + MBEDTLS_KW_MODE_KW = 0, + MBEDTLS_KW_MODE_KWP = 1 +} mbedtls_nist_kw_mode_t; + +#if !defined(MBEDTLS_NIST_KW_ALT) +// Regular implementation +// + +/** + * \brief The key wrapping context-type definition. The key wrapping context is passed + * to the APIs called. + * + * \note The definition of this type may change in future library versions. + * Don't make any assumptions on this context! + */ +typedef struct { + mbedtls_cipher_context_t cipher_ctx; /*!< The cipher context used. */ +} mbedtls_nist_kw_context; + +#else /* MBEDTLS_NIST_key wrapping_ALT */ +#include "nist_kw_alt.h" +#endif /* MBEDTLS_NIST_KW_ALT */ + +/** + * \brief This function initializes the specified key wrapping context + * to make references valid and prepare the context + * for mbedtls_nist_kw_setkey() or mbedtls_nist_kw_free(). + * + * \param ctx The key wrapping context to initialize. + * + */ +void mbedtls_nist_kw_init( mbedtls_nist_kw_context *ctx ); + +/** + * \brief This function initializes the key wrapping context set in the + * \p ctx parameter and sets the encryption key. + * + * \param ctx The key wrapping context. + * \param cipher The 128-bit block cipher to use. Only AES is supported. + * \param key The Key Encryption Key (KEK). + * \param keybits The KEK size in bits. This must be acceptable by the cipher. + * \param is_wrap Specify whether the operation within the context is wrapping or unwrapping + * + * \return \c 0 on success. + * \return \c MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA for any invalid input. + * \return \c MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE for 128-bit block ciphers + * which are not supported. + * \return cipher-specific error code on failure of the underlying cipher. + */ +int mbedtls_nist_kw_setkey( mbedtls_nist_kw_context *ctx, + mbedtls_cipher_id_t cipher, + const unsigned char *key, + unsigned int keybits, + const int is_wrap ); + +/** + * \brief This function releases and clears the specified key wrapping context + * and underlying cipher sub-context. + * + * \param ctx The key wrapping context to clear. + */ +void mbedtls_nist_kw_free( mbedtls_nist_kw_context *ctx ); + +/** + * \brief This function encrypts a buffer using key wrapping. + * + * \param ctx The key wrapping context to use for encryption. + * \param mode The key wrapping mode to use (MBEDTLS_KW_MODE_KW or MBEDTLS_KW_MODE_KWP) + * \param input The buffer holding the input data. + * \param in_len The length of the input data in Bytes. + * The input uses units of 8 Bytes called semiblocks. + *
                            • For KW mode: a multiple of 8 bytes between 16 and 2^57-8 inclusive.
                            • + *
                            • For KWP mode: any length between 1 and 2^32-1 inclusive.
                            + * \param[out] output The buffer holding the output data. + *
                            • For KW mode: Must be at least 8 bytes larger than \p in_len.
                            • + *
                            • For KWP mode: Must be at least 8 bytes larger rounded up to a multiple of + * 8 bytes for KWP (15 bytes at most).
                            + * \param[out] out_len The number of bytes written to the output buffer. \c 0 on failure. + * \param[in] out_size The capacity of the output buffer. + * + * \return \c 0 on success. + * \return \c MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA for invalid input length. + * \return cipher-specific error code on failure of the underlying cipher. + */ +int mbedtls_nist_kw_wrap( mbedtls_nist_kw_context *ctx, mbedtls_nist_kw_mode_t mode, + const unsigned char *input, size_t in_len, + unsigned char *output, size_t* out_len, size_t out_size ); + +/** + * \brief This function decrypts a buffer using key wrapping. + * + * \param ctx The key wrapping context to use for decryption. + * \param mode The key wrapping mode to use (MBEDTLS_KW_MODE_KW or MBEDTLS_KW_MODE_KWP) + * \param input The buffer holding the input data. + * \param in_len The length of the input data in Bytes. + * The input uses units of 8 Bytes called semiblocks. + * The input must be a multiple of semiblocks. + *
                            • For KW mode: a multiple of 8 bytes between 24 and 2^57 inclusive.
                            • + *
                            • For KWP mode: a multiple of 8 bytes between 16 and 2^32 inclusive.
                            + * \param[out] output The buffer holding the output data. + * The output buffer's minimal length is 8 bytes shorter than \p in_len. + * \param[out] out_len The number of bytes written to the output buffer. \c 0 on failure. + * For KWP mode, the length could be up to 15 bytes shorter than \p in_len, + * depending on how much padding was added to the data. + * \param[in] out_size The capacity of the output buffer. + * + * \return \c 0 on success. + * \return \c MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA for invalid input length. + * \return \c MBEDTLS_ERR_CIPHER_AUTH_FAILED for verification failure of the ciphertext. + * \return cipher-specific error code on failure of the underlying cipher. + */ +int mbedtls_nist_kw_unwrap( mbedtls_nist_kw_context *ctx, mbedtls_nist_kw_mode_t mode, + const unsigned char *input, size_t in_len, + unsigned char *output, size_t* out_len, size_t out_size); + + +#if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_AES_C) +/** + * \brief The key wrapping checkup routine. + * + * \return \c 0 on success. + * \return \c 1 on failure. + */ +int mbedtls_nist_kw_self_test( int verbose ); +#endif /* MBEDTLS_SELF_TEST && MBEDTLS_AES_C */ + +#ifdef __cplusplus +} +#endif + +#endif /* MBEDTLS_NIST_KW_H */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/oid.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/oid.h new file mode 100644 index 0000000000000000000000000000000000000000..6fbd018aaa1a7338f309f731d3e936ca409d00f4 --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/oid.h @@ -0,0 +1,605 @@ +/** + * \file oid.h + * + * \brief Object Identifier (OID) database + */ +/* + * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ +#ifndef MBEDTLS_OID_H +#define MBEDTLS_OID_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include "asn1.h" +#include "pk.h" + +#include + +#if defined(MBEDTLS_CIPHER_C) +#include "cipher.h" +#endif + +#if defined(MBEDTLS_MD_C) +#include "md.h" +#endif + +#if defined(MBEDTLS_X509_USE_C) || defined(MBEDTLS_X509_CREATE_C) +#include "x509.h" +#endif + +#define MBEDTLS_ERR_OID_NOT_FOUND -0x002E /**< OID is not found. */ +#define MBEDTLS_ERR_OID_BUF_TOO_SMALL -0x000B /**< output buffer is too small */ + +/* + * Top level OID tuples + */ +#define MBEDTLS_OID_ISO_MEMBER_BODIES "\x2a" /* {iso(1) member-body(2)} */ +#define MBEDTLS_OID_ISO_IDENTIFIED_ORG "\x2b" /* {iso(1) identified-organization(3)} */ +#define MBEDTLS_OID_ISO_CCITT_DS "\x55" /* {joint-iso-ccitt(2) ds(5)} */ +#define MBEDTLS_OID_ISO_ITU_COUNTRY "\x60" /* {joint-iso-itu-t(2) country(16)} */ + +/* + * ISO Member bodies OID parts + */ +#define MBEDTLS_OID_COUNTRY_US "\x86\x48" /* {us(840)} */ +#define MBEDTLS_OID_ORG_RSA_DATA_SECURITY "\x86\xf7\x0d" /* {rsadsi(113549)} */ +#define MBEDTLS_OID_RSA_COMPANY MBEDTLS_OID_ISO_MEMBER_BODIES MBEDTLS_OID_COUNTRY_US \ + MBEDTLS_OID_ORG_RSA_DATA_SECURITY /* {iso(1) member-body(2) us(840) rsadsi(113549)} */ +#define MBEDTLS_OID_ORG_ANSI_X9_62 "\xce\x3d" /* ansi-X9-62(10045) */ +#define MBEDTLS_OID_ANSI_X9_62 MBEDTLS_OID_ISO_MEMBER_BODIES MBEDTLS_OID_COUNTRY_US \ + MBEDTLS_OID_ORG_ANSI_X9_62 + +/* + * ISO Identified organization OID parts + */ +#define MBEDTLS_OID_ORG_DOD "\x06" /* {dod(6)} */ +#define MBEDTLS_OID_ORG_OIW "\x0e" +#define MBEDTLS_OID_OIW_SECSIG MBEDTLS_OID_ORG_OIW "\x03" +#define MBEDTLS_OID_OIW_SECSIG_ALG MBEDTLS_OID_OIW_SECSIG "\x02" +#define MBEDTLS_OID_OIW_SECSIG_SHA1 MBEDTLS_OID_OIW_SECSIG_ALG "\x1a" +#define MBEDTLS_OID_ORG_CERTICOM "\x81\x04" /* certicom(132) */ +#define MBEDTLS_OID_CERTICOM MBEDTLS_OID_ISO_IDENTIFIED_ORG MBEDTLS_OID_ORG_CERTICOM +#define MBEDTLS_OID_ORG_TELETRUST "\x24" /* teletrust(36) */ +#define MBEDTLS_OID_TELETRUST MBEDTLS_OID_ISO_IDENTIFIED_ORG MBEDTLS_OID_ORG_TELETRUST + +/* + * ISO ITU OID parts + */ +#define MBEDTLS_OID_ORGANIZATION "\x01" /* {organization(1)} */ +#define MBEDTLS_OID_ISO_ITU_US_ORG MBEDTLS_OID_ISO_ITU_COUNTRY MBEDTLS_OID_COUNTRY_US MBEDTLS_OID_ORGANIZATION /* {joint-iso-itu-t(2) country(16) us(840) organization(1)} */ + +#define MBEDTLS_OID_ORG_GOV "\x65" /* {gov(101)} */ +#define MBEDTLS_OID_GOV MBEDTLS_OID_ISO_ITU_US_ORG MBEDTLS_OID_ORG_GOV /* {joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101)} */ + +#define MBEDTLS_OID_ORG_NETSCAPE "\x86\xF8\x42" /* {netscape(113730)} */ +#define MBEDTLS_OID_NETSCAPE MBEDTLS_OID_ISO_ITU_US_ORG MBEDTLS_OID_ORG_NETSCAPE /* Netscape OID {joint-iso-itu-t(2) country(16) us(840) organization(1) netscape(113730)} */ + +/* ISO arc for standard certificate and CRL extensions */ +#define MBEDTLS_OID_ID_CE MBEDTLS_OID_ISO_CCITT_DS "\x1D" /**< id-ce OBJECT IDENTIFIER ::= {joint-iso-ccitt(2) ds(5) 29} */ + +#define MBEDTLS_OID_NIST_ALG MBEDTLS_OID_GOV "\x03\x04" /** { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistAlgorithm(4) */ + +/** + * Private Internet Extensions + * { iso(1) identified-organization(3) dod(6) internet(1) + * security(5) mechanisms(5) pkix(7) } + */ +#define MBEDTLS_OID_PKIX MBEDTLS_OID_ISO_IDENTIFIED_ORG MBEDTLS_OID_ORG_DOD "\x01\x05\x05\x07" + +/* + * Arc for standard naming attributes + */ +#define MBEDTLS_OID_AT MBEDTLS_OID_ISO_CCITT_DS "\x04" /**< id-at OBJECT IDENTIFIER ::= {joint-iso-ccitt(2) ds(5) 4} */ +#define MBEDTLS_OID_AT_CN MBEDTLS_OID_AT "\x03" /**< id-at-commonName AttributeType:= {id-at 3} */ +#define MBEDTLS_OID_AT_SUR_NAME MBEDTLS_OID_AT "\x04" /**< id-at-surName AttributeType:= {id-at 4} */ +#define MBEDTLS_OID_AT_SERIAL_NUMBER MBEDTLS_OID_AT "\x05" /**< id-at-serialNumber AttributeType:= {id-at 5} */ +#define MBEDTLS_OID_AT_COUNTRY MBEDTLS_OID_AT "\x06" /**< id-at-countryName AttributeType:= {id-at 6} */ +#define MBEDTLS_OID_AT_LOCALITY MBEDTLS_OID_AT "\x07" /**< id-at-locality AttributeType:= {id-at 7} */ +#define MBEDTLS_OID_AT_STATE MBEDTLS_OID_AT "\x08" /**< id-at-state AttributeType:= {id-at 8} */ +#define MBEDTLS_OID_AT_ORGANIZATION MBEDTLS_OID_AT "\x0A" /**< id-at-organizationName AttributeType:= {id-at 10} */ +#define MBEDTLS_OID_AT_ORG_UNIT MBEDTLS_OID_AT "\x0B" /**< id-at-organizationalUnitName AttributeType:= {id-at 11} */ +#define MBEDTLS_OID_AT_TITLE MBEDTLS_OID_AT "\x0C" /**< id-at-title AttributeType:= {id-at 12} */ +#define MBEDTLS_OID_AT_POSTAL_ADDRESS MBEDTLS_OID_AT "\x10" /**< id-at-postalAddress AttributeType:= {id-at 16} */ +#define MBEDTLS_OID_AT_POSTAL_CODE MBEDTLS_OID_AT "\x11" /**< id-at-postalCode AttributeType:= {id-at 17} */ +#define MBEDTLS_OID_AT_GIVEN_NAME MBEDTLS_OID_AT "\x2A" /**< id-at-givenName AttributeType:= {id-at 42} */ +#define MBEDTLS_OID_AT_INITIALS MBEDTLS_OID_AT "\x2B" /**< id-at-initials AttributeType:= {id-at 43} */ +#define MBEDTLS_OID_AT_GENERATION_QUALIFIER MBEDTLS_OID_AT "\x2C" /**< id-at-generationQualifier AttributeType:= {id-at 44} */ +#define MBEDTLS_OID_AT_UNIQUE_IDENTIFIER MBEDTLS_OID_AT "\x2D" /**< id-at-uniqueIdentifier AttributType:= {id-at 45} */ +#define MBEDTLS_OID_AT_DN_QUALIFIER MBEDTLS_OID_AT "\x2E" /**< id-at-dnQualifier AttributeType:= {id-at 46} */ +#define MBEDTLS_OID_AT_PSEUDONYM MBEDTLS_OID_AT "\x41" /**< id-at-pseudonym AttributeType:= {id-at 65} */ + +#define MBEDTLS_OID_DOMAIN_COMPONENT "\x09\x92\x26\x89\x93\xF2\x2C\x64\x01\x19" /** id-domainComponent AttributeType:= {itu-t(0) data(9) pss(2342) ucl(19200300) pilot(100) pilotAttributeType(1) domainComponent(25)} */ + +/* + * OIDs for standard certificate extensions + */ +#define MBEDTLS_OID_AUTHORITY_KEY_IDENTIFIER MBEDTLS_OID_ID_CE "\x23" /**< id-ce-authorityKeyIdentifier OBJECT IDENTIFIER ::= { id-ce 35 } */ +#define MBEDTLS_OID_SUBJECT_KEY_IDENTIFIER MBEDTLS_OID_ID_CE "\x0E" /**< id-ce-subjectKeyIdentifier OBJECT IDENTIFIER ::= { id-ce 14 } */ +#define MBEDTLS_OID_KEY_USAGE MBEDTLS_OID_ID_CE "\x0F" /**< id-ce-keyUsage OBJECT IDENTIFIER ::= { id-ce 15 } */ +#define MBEDTLS_OID_CERTIFICATE_POLICIES MBEDTLS_OID_ID_CE "\x20" /**< id-ce-certificatePolicies OBJECT IDENTIFIER ::= { id-ce 32 } */ +#define MBEDTLS_OID_POLICY_MAPPINGS MBEDTLS_OID_ID_CE "\x21" /**< id-ce-policyMappings OBJECT IDENTIFIER ::= { id-ce 33 } */ +#define MBEDTLS_OID_SUBJECT_ALT_NAME MBEDTLS_OID_ID_CE "\x11" /**< id-ce-subjectAltName OBJECT IDENTIFIER ::= { id-ce 17 } */ +#define MBEDTLS_OID_ISSUER_ALT_NAME MBEDTLS_OID_ID_CE "\x12" /**< id-ce-issuerAltName OBJECT IDENTIFIER ::= { id-ce 18 } */ +#define MBEDTLS_OID_SUBJECT_DIRECTORY_ATTRS MBEDTLS_OID_ID_CE "\x09" /**< id-ce-subjectDirectoryAttributes OBJECT IDENTIFIER ::= { id-ce 9 } */ +#define MBEDTLS_OID_BASIC_CONSTRAINTS MBEDTLS_OID_ID_CE "\x13" /**< id-ce-basicConstraints OBJECT IDENTIFIER ::= { id-ce 19 } */ +#define MBEDTLS_OID_NAME_CONSTRAINTS MBEDTLS_OID_ID_CE "\x1E" /**< id-ce-nameConstraints OBJECT IDENTIFIER ::= { id-ce 30 } */ +#define MBEDTLS_OID_POLICY_CONSTRAINTS MBEDTLS_OID_ID_CE "\x24" /**< id-ce-policyConstraints OBJECT IDENTIFIER ::= { id-ce 36 } */ +#define MBEDTLS_OID_EXTENDED_KEY_USAGE MBEDTLS_OID_ID_CE "\x25" /**< id-ce-extKeyUsage OBJECT IDENTIFIER ::= { id-ce 37 } */ +#define MBEDTLS_OID_CRL_DISTRIBUTION_POINTS MBEDTLS_OID_ID_CE "\x1F" /**< id-ce-cRLDistributionPoints OBJECT IDENTIFIER ::= { id-ce 31 } */ +#define MBEDTLS_OID_INIHIBIT_ANYPOLICY MBEDTLS_OID_ID_CE "\x36" /**< id-ce-inhibitAnyPolicy OBJECT IDENTIFIER ::= { id-ce 54 } */ +#define MBEDTLS_OID_FRESHEST_CRL MBEDTLS_OID_ID_CE "\x2E" /**< id-ce-freshestCRL OBJECT IDENTIFIER ::= { id-ce 46 } */ + +/* + * Netscape certificate extensions + */ +#define MBEDTLS_OID_NS_CERT MBEDTLS_OID_NETSCAPE "\x01" +#define MBEDTLS_OID_NS_CERT_TYPE MBEDTLS_OID_NS_CERT "\x01" +#define MBEDTLS_OID_NS_BASE_URL MBEDTLS_OID_NS_CERT "\x02" +#define MBEDTLS_OID_NS_REVOCATION_URL MBEDTLS_OID_NS_CERT "\x03" +#define MBEDTLS_OID_NS_CA_REVOCATION_URL MBEDTLS_OID_NS_CERT "\x04" +#define MBEDTLS_OID_NS_RENEWAL_URL MBEDTLS_OID_NS_CERT "\x07" +#define MBEDTLS_OID_NS_CA_POLICY_URL MBEDTLS_OID_NS_CERT "\x08" +#define MBEDTLS_OID_NS_SSL_SERVER_NAME MBEDTLS_OID_NS_CERT "\x0C" +#define MBEDTLS_OID_NS_COMMENT MBEDTLS_OID_NS_CERT "\x0D" +#define MBEDTLS_OID_NS_DATA_TYPE MBEDTLS_OID_NETSCAPE "\x02" +#define MBEDTLS_OID_NS_CERT_SEQUENCE MBEDTLS_OID_NS_DATA_TYPE "\x05" + +/* + * OIDs for CRL extensions + */ +#define MBEDTLS_OID_PRIVATE_KEY_USAGE_PERIOD MBEDTLS_OID_ID_CE "\x10" +#define MBEDTLS_OID_CRL_NUMBER MBEDTLS_OID_ID_CE "\x14" /**< id-ce-cRLNumber OBJECT IDENTIFIER ::= { id-ce 20 } */ + +/* + * X.509 v3 Extended key usage OIDs + */ +#define MBEDTLS_OID_ANY_EXTENDED_KEY_USAGE MBEDTLS_OID_EXTENDED_KEY_USAGE "\x00" /**< anyExtendedKeyUsage OBJECT IDENTIFIER ::= { id-ce-extKeyUsage 0 } */ + +#define MBEDTLS_OID_KP MBEDTLS_OID_PKIX "\x03" /**< id-kp OBJECT IDENTIFIER ::= { id-pkix 3 } */ +#define MBEDTLS_OID_SERVER_AUTH MBEDTLS_OID_KP "\x01" /**< id-kp-serverAuth OBJECT IDENTIFIER ::= { id-kp 1 } */ +#define MBEDTLS_OID_CLIENT_AUTH MBEDTLS_OID_KP "\x02" /**< id-kp-clientAuth OBJECT IDENTIFIER ::= { id-kp 2 } */ +#define MBEDTLS_OID_CODE_SIGNING MBEDTLS_OID_KP "\x03" /**< id-kp-codeSigning OBJECT IDENTIFIER ::= { id-kp 3 } */ +#define MBEDTLS_OID_EMAIL_PROTECTION MBEDTLS_OID_KP "\x04" /**< id-kp-emailProtection OBJECT IDENTIFIER ::= { id-kp 4 } */ +#define MBEDTLS_OID_TIME_STAMPING MBEDTLS_OID_KP "\x08" /**< id-kp-timeStamping OBJECT IDENTIFIER ::= { id-kp 8 } */ +#define MBEDTLS_OID_OCSP_SIGNING MBEDTLS_OID_KP "\x09" /**< id-kp-OCSPSigning OBJECT IDENTIFIER ::= { id-kp 9 } */ + +/* + * PKCS definition OIDs + */ + +#define MBEDTLS_OID_PKCS MBEDTLS_OID_RSA_COMPANY "\x01" /**< pkcs OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) 1 } */ +#define MBEDTLS_OID_PKCS1 MBEDTLS_OID_PKCS "\x01" /**< pkcs-1 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 1 } */ +#define MBEDTLS_OID_PKCS5 MBEDTLS_OID_PKCS "\x05" /**< pkcs-5 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 5 } */ +#define MBEDTLS_OID_PKCS9 MBEDTLS_OID_PKCS "\x09" /**< pkcs-9 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 9 } */ +#define MBEDTLS_OID_PKCS12 MBEDTLS_OID_PKCS "\x0c" /**< pkcs-12 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 12 } */ + +/* + * PKCS#1 OIDs + */ +#define MBEDTLS_OID_PKCS1_RSA MBEDTLS_OID_PKCS1 "\x01" /**< rsaEncryption OBJECT IDENTIFIER ::= { pkcs-1 1 } */ +#define MBEDTLS_OID_PKCS1_MD2 MBEDTLS_OID_PKCS1 "\x02" /**< md2WithRSAEncryption ::= { pkcs-1 2 } */ +#define MBEDTLS_OID_PKCS1_MD4 MBEDTLS_OID_PKCS1 "\x03" /**< md4WithRSAEncryption ::= { pkcs-1 3 } */ +#define MBEDTLS_OID_PKCS1_MD5 MBEDTLS_OID_PKCS1 "\x04" /**< md5WithRSAEncryption ::= { pkcs-1 4 } */ +#define MBEDTLS_OID_PKCS1_SHA1 MBEDTLS_OID_PKCS1 "\x05" /**< sha1WithRSAEncryption ::= { pkcs-1 5 } */ +#define MBEDTLS_OID_PKCS1_SHA224 MBEDTLS_OID_PKCS1 "\x0e" /**< sha224WithRSAEncryption ::= { pkcs-1 14 } */ +#define MBEDTLS_OID_PKCS1_SHA256 MBEDTLS_OID_PKCS1 "\x0b" /**< sha256WithRSAEncryption ::= { pkcs-1 11 } */ +#define MBEDTLS_OID_PKCS1_SHA384 MBEDTLS_OID_PKCS1 "\x0c" /**< sha384WithRSAEncryption ::= { pkcs-1 12 } */ +#define MBEDTLS_OID_PKCS1_SHA512 MBEDTLS_OID_PKCS1 "\x0d" /**< sha512WithRSAEncryption ::= { pkcs-1 13 } */ + +#define MBEDTLS_OID_RSA_SHA_OBS "\x2B\x0E\x03\x02\x1D" + +#define MBEDTLS_OID_PKCS9_EMAIL MBEDTLS_OID_PKCS9 "\x01" /**< emailAddress AttributeType ::= { pkcs-9 1 } */ + +/* RFC 4055 */ +#define MBEDTLS_OID_RSASSA_PSS MBEDTLS_OID_PKCS1 "\x0a" /**< id-RSASSA-PSS ::= { pkcs-1 10 } */ +#define MBEDTLS_OID_MGF1 MBEDTLS_OID_PKCS1 "\x08" /**< id-mgf1 ::= { pkcs-1 8 } */ + +/* + * Digest algorithms + */ +#define MBEDTLS_OID_DIGEST_ALG_MD2 MBEDTLS_OID_RSA_COMPANY "\x02\x02" /**< id-mbedtls_md2 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 2 } */ +#define MBEDTLS_OID_DIGEST_ALG_MD4 MBEDTLS_OID_RSA_COMPANY "\x02\x04" /**< id-mbedtls_md4 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 4 } */ +#define MBEDTLS_OID_DIGEST_ALG_MD5 MBEDTLS_OID_RSA_COMPANY "\x02\x05" /**< id-mbedtls_md5 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 5 } */ +#define MBEDTLS_OID_DIGEST_ALG_SHA1 MBEDTLS_OID_ISO_IDENTIFIED_ORG MBEDTLS_OID_OIW_SECSIG_SHA1 /**< id-mbedtls_sha1 OBJECT IDENTIFIER ::= { iso(1) identified-organization(3) oiw(14) secsig(3) algorithms(2) 26 } */ +#define MBEDTLS_OID_DIGEST_ALG_SHA224 MBEDTLS_OID_NIST_ALG "\x02\x04" /**< id-sha224 OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistalgorithm(4) hashalgs(2) 4 } */ +#define MBEDTLS_OID_DIGEST_ALG_SHA256 MBEDTLS_OID_NIST_ALG "\x02\x01" /**< id-mbedtls_sha256 OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistalgorithm(4) hashalgs(2) 1 } */ + +#define MBEDTLS_OID_DIGEST_ALG_SHA384 MBEDTLS_OID_NIST_ALG "\x02\x02" /**< id-sha384 OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistalgorithm(4) hashalgs(2) 2 } */ + +#define MBEDTLS_OID_DIGEST_ALG_SHA512 MBEDTLS_OID_NIST_ALG "\x02\x03" /**< id-mbedtls_sha512 OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistalgorithm(4) hashalgs(2) 3 } */ + +#define MBEDTLS_OID_HMAC_SHA1 MBEDTLS_OID_RSA_COMPANY "\x02\x07" /**< id-hmacWithSHA1 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 7 } */ + +#define MBEDTLS_OID_HMAC_SHA224 MBEDTLS_OID_RSA_COMPANY "\x02\x08" /**< id-hmacWithSHA224 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 8 } */ + +#define MBEDTLS_OID_HMAC_SHA256 MBEDTLS_OID_RSA_COMPANY "\x02\x09" /**< id-hmacWithSHA256 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 9 } */ + +#define MBEDTLS_OID_HMAC_SHA384 MBEDTLS_OID_RSA_COMPANY "\x02\x0A" /**< id-hmacWithSHA384 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 10 } */ + +#define MBEDTLS_OID_HMAC_SHA512 MBEDTLS_OID_RSA_COMPANY "\x02\x0B" /**< id-hmacWithSHA512 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 11 } */ + +/* + * Encryption algorithms + */ +#define MBEDTLS_OID_DES_CBC MBEDTLS_OID_ISO_IDENTIFIED_ORG MBEDTLS_OID_OIW_SECSIG_ALG "\x07" /**< desCBC OBJECT IDENTIFIER ::= { iso(1) identified-organization(3) oiw(14) secsig(3) algorithms(2) 7 } */ +#define MBEDTLS_OID_DES_EDE3_CBC MBEDTLS_OID_RSA_COMPANY "\x03\x07" /**< des-ede3-cbc OBJECT IDENTIFIER ::= { iso(1) member-body(2) -- us(840) rsadsi(113549) encryptionAlgorithm(3) 7 } */ +#define MBEDTLS_OID_AES MBEDTLS_OID_NIST_ALG "\x01" /** aes OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistAlgorithm(4) 1 } */ + +/* + * Key Wrapping algorithms + */ +/* + * RFC 5649 + */ +#define MBEDTLS_OID_AES128_KW MBEDTLS_OID_AES "\x05" /** id-aes128-wrap OBJECT IDENTIFIER ::= { aes 5 } */ +#define MBEDTLS_OID_AES128_KWP MBEDTLS_OID_AES "\x08" /** id-aes128-wrap-pad OBJECT IDENTIFIER ::= { aes 8 } */ +#define MBEDTLS_OID_AES192_KW MBEDTLS_OID_AES "\x19" /** id-aes192-wrap OBJECT IDENTIFIER ::= { aes 25 } */ +#define MBEDTLS_OID_AES192_KWP MBEDTLS_OID_AES "\x1c" /** id-aes192-wrap-pad OBJECT IDENTIFIER ::= { aes 28 } */ +#define MBEDTLS_OID_AES256_KW MBEDTLS_OID_AES "\x2d" /** id-aes256-wrap OBJECT IDENTIFIER ::= { aes 45 } */ +#define MBEDTLS_OID_AES256_KWP MBEDTLS_OID_AES "\x30" /** id-aes256-wrap-pad OBJECT IDENTIFIER ::= { aes 48 } */ +/* + * PKCS#5 OIDs + */ +#define MBEDTLS_OID_PKCS5_PBKDF2 MBEDTLS_OID_PKCS5 "\x0c" /**< id-PBKDF2 OBJECT IDENTIFIER ::= {pkcs-5 12} */ +#define MBEDTLS_OID_PKCS5_PBES2 MBEDTLS_OID_PKCS5 "\x0d" /**< id-PBES2 OBJECT IDENTIFIER ::= {pkcs-5 13} */ +#define MBEDTLS_OID_PKCS5_PBMAC1 MBEDTLS_OID_PKCS5 "\x0e" /**< id-PBMAC1 OBJECT IDENTIFIER ::= {pkcs-5 14} */ + +/* + * PKCS#5 PBES1 algorithms + */ +#define MBEDTLS_OID_PKCS5_PBE_MD2_DES_CBC MBEDTLS_OID_PKCS5 "\x01" /**< pbeWithMD2AndDES-CBC OBJECT IDENTIFIER ::= {pkcs-5 1} */ +#define MBEDTLS_OID_PKCS5_PBE_MD2_RC2_CBC MBEDTLS_OID_PKCS5 "\x04" /**< pbeWithMD2AndRC2-CBC OBJECT IDENTIFIER ::= {pkcs-5 4} */ +#define MBEDTLS_OID_PKCS5_PBE_MD5_DES_CBC MBEDTLS_OID_PKCS5 "\x03" /**< pbeWithMD5AndDES-CBC OBJECT IDENTIFIER ::= {pkcs-5 3} */ +#define MBEDTLS_OID_PKCS5_PBE_MD5_RC2_CBC MBEDTLS_OID_PKCS5 "\x06" /**< pbeWithMD5AndRC2-CBC OBJECT IDENTIFIER ::= {pkcs-5 6} */ +#define MBEDTLS_OID_PKCS5_PBE_SHA1_DES_CBC MBEDTLS_OID_PKCS5 "\x0a" /**< pbeWithSHA1AndDES-CBC OBJECT IDENTIFIER ::= {pkcs-5 10} */ +#define MBEDTLS_OID_PKCS5_PBE_SHA1_RC2_CBC MBEDTLS_OID_PKCS5 "\x0b" /**< pbeWithSHA1AndRC2-CBC OBJECT IDENTIFIER ::= {pkcs-5 11} */ + +/* + * PKCS#8 OIDs + */ +#define MBEDTLS_OID_PKCS9_CSR_EXT_REQ MBEDTLS_OID_PKCS9 "\x0e" /**< extensionRequest OBJECT IDENTIFIER ::= {pkcs-9 14} */ + +/* + * PKCS#12 PBE OIDs + */ +#define MBEDTLS_OID_PKCS12_PBE MBEDTLS_OID_PKCS12 "\x01" /**< pkcs-12PbeIds OBJECT IDENTIFIER ::= {pkcs-12 1} */ + +#define MBEDTLS_OID_PKCS12_PBE_SHA1_RC4_128 MBEDTLS_OID_PKCS12_PBE "\x01" /**< pbeWithSHAAnd128BitRC4 OBJECT IDENTIFIER ::= {pkcs-12PbeIds 1} */ +#define MBEDTLS_OID_PKCS12_PBE_SHA1_RC4_40 MBEDTLS_OID_PKCS12_PBE "\x02" /**< pbeWithSHAAnd40BitRC4 OBJECT IDENTIFIER ::= {pkcs-12PbeIds 2} */ +#define MBEDTLS_OID_PKCS12_PBE_SHA1_DES3_EDE_CBC MBEDTLS_OID_PKCS12_PBE "\x03" /**< pbeWithSHAAnd3-KeyTripleDES-CBC OBJECT IDENTIFIER ::= {pkcs-12PbeIds 3} */ +#define MBEDTLS_OID_PKCS12_PBE_SHA1_DES2_EDE_CBC MBEDTLS_OID_PKCS12_PBE "\x04" /**< pbeWithSHAAnd2-KeyTripleDES-CBC OBJECT IDENTIFIER ::= {pkcs-12PbeIds 4} */ +#define MBEDTLS_OID_PKCS12_PBE_SHA1_RC2_128_CBC MBEDTLS_OID_PKCS12_PBE "\x05" /**< pbeWithSHAAnd128BitRC2-CBC OBJECT IDENTIFIER ::= {pkcs-12PbeIds 5} */ +#define MBEDTLS_OID_PKCS12_PBE_SHA1_RC2_40_CBC MBEDTLS_OID_PKCS12_PBE "\x06" /**< pbeWithSHAAnd40BitRC2-CBC OBJECT IDENTIFIER ::= {pkcs-12PbeIds 6} */ + +/* + * EC key algorithms from RFC 5480 + */ + +/* id-ecPublicKey OBJECT IDENTIFIER ::= { + * iso(1) member-body(2) us(840) ansi-X9-62(10045) keyType(2) 1 } */ +#define MBEDTLS_OID_EC_ALG_UNRESTRICTED MBEDTLS_OID_ANSI_X9_62 "\x02\01" + +/* id-ecDH OBJECT IDENTIFIER ::= { + * iso(1) identified-organization(3) certicom(132) + * schemes(1) ecdh(12) } */ +#define MBEDTLS_OID_EC_ALG_ECDH MBEDTLS_OID_CERTICOM "\x01\x0c" + +/* + * ECParameters namedCurve identifiers, from RFC 5480, RFC 5639, and SEC2 + */ + +/* secp192r1 OBJECT IDENTIFIER ::= { + * iso(1) member-body(2) us(840) ansi-X9-62(10045) curves(3) prime(1) 1 } */ +#define MBEDTLS_OID_EC_GRP_SECP192R1 MBEDTLS_OID_ANSI_X9_62 "\x03\x01\x01" + +/* secp224r1 OBJECT IDENTIFIER ::= { + * iso(1) identified-organization(3) certicom(132) curve(0) 33 } */ +#define MBEDTLS_OID_EC_GRP_SECP224R1 MBEDTLS_OID_CERTICOM "\x00\x21" + +/* secp256r1 OBJECT IDENTIFIER ::= { + * iso(1) member-body(2) us(840) ansi-X9-62(10045) curves(3) prime(1) 7 } */ +#define MBEDTLS_OID_EC_GRP_SECP256R1 MBEDTLS_OID_ANSI_X9_62 "\x03\x01\x07" + +/* secp384r1 OBJECT IDENTIFIER ::= { + * iso(1) identified-organization(3) certicom(132) curve(0) 34 } */ +#define MBEDTLS_OID_EC_GRP_SECP384R1 MBEDTLS_OID_CERTICOM "\x00\x22" + +/* secp521r1 OBJECT IDENTIFIER ::= { + * iso(1) identified-organization(3) certicom(132) curve(0) 35 } */ +#define MBEDTLS_OID_EC_GRP_SECP521R1 MBEDTLS_OID_CERTICOM "\x00\x23" + +/* secp192k1 OBJECT IDENTIFIER ::= { + * iso(1) identified-organization(3) certicom(132) curve(0) 31 } */ +#define MBEDTLS_OID_EC_GRP_SECP192K1 MBEDTLS_OID_CERTICOM "\x00\x1f" + +/* secp224k1 OBJECT IDENTIFIER ::= { + * iso(1) identified-organization(3) certicom(132) curve(0) 32 } */ +#define MBEDTLS_OID_EC_GRP_SECP224K1 MBEDTLS_OID_CERTICOM "\x00\x20" + +/* secp256k1 OBJECT IDENTIFIER ::= { + * iso(1) identified-organization(3) certicom(132) curve(0) 10 } */ +#define MBEDTLS_OID_EC_GRP_SECP256K1 MBEDTLS_OID_CERTICOM "\x00\x0a" + +/* RFC 5639 4.1 + * ecStdCurvesAndGeneration OBJECT IDENTIFIER::= {iso(1) + * identified-organization(3) teletrust(36) algorithm(3) signature- + * algorithm(3) ecSign(2) 8} + * ellipticCurve OBJECT IDENTIFIER ::= {ecStdCurvesAndGeneration 1} + * versionOne OBJECT IDENTIFIER ::= {ellipticCurve 1} */ +#define MBEDTLS_OID_EC_BRAINPOOL_V1 MBEDTLS_OID_TELETRUST "\x03\x03\x02\x08\x01\x01" + +/* brainpoolP256r1 OBJECT IDENTIFIER ::= {versionOne 7} */ +#define MBEDTLS_OID_EC_GRP_BP256R1 MBEDTLS_OID_EC_BRAINPOOL_V1 "\x07" + +/* brainpoolP384r1 OBJECT IDENTIFIER ::= {versionOne 11} */ +#define MBEDTLS_OID_EC_GRP_BP384R1 MBEDTLS_OID_EC_BRAINPOOL_V1 "\x0B" + +/* brainpoolP512r1 OBJECT IDENTIFIER ::= {versionOne 13} */ +#define MBEDTLS_OID_EC_GRP_BP512R1 MBEDTLS_OID_EC_BRAINPOOL_V1 "\x0D" + +/* + * SEC1 C.1 + * + * prime-field OBJECT IDENTIFIER ::= { id-fieldType 1 } + * id-fieldType OBJECT IDENTIFIER ::= { ansi-X9-62 fieldType(1)} + */ +#define MBEDTLS_OID_ANSI_X9_62_FIELD_TYPE MBEDTLS_OID_ANSI_X9_62 "\x01" +#define MBEDTLS_OID_ANSI_X9_62_PRIME_FIELD MBEDTLS_OID_ANSI_X9_62_FIELD_TYPE "\x01" + +/* + * ECDSA signature identifiers, from RFC 5480 + */ +#define MBEDTLS_OID_ANSI_X9_62_SIG MBEDTLS_OID_ANSI_X9_62 "\x04" /* signatures(4) */ +#define MBEDTLS_OID_ANSI_X9_62_SIG_SHA2 MBEDTLS_OID_ANSI_X9_62_SIG "\x03" /* ecdsa-with-SHA2(3) */ + +/* ecdsa-with-SHA1 OBJECT IDENTIFIER ::= { + * iso(1) member-body(2) us(840) ansi-X9-62(10045) signatures(4) 1 } */ +#define MBEDTLS_OID_ECDSA_SHA1 MBEDTLS_OID_ANSI_X9_62_SIG "\x01" + +/* ecdsa-with-SHA224 OBJECT IDENTIFIER ::= { + * iso(1) member-body(2) us(840) ansi-X9-62(10045) signatures(4) + * ecdsa-with-SHA2(3) 1 } */ +#define MBEDTLS_OID_ECDSA_SHA224 MBEDTLS_OID_ANSI_X9_62_SIG_SHA2 "\x01" + +/* ecdsa-with-SHA256 OBJECT IDENTIFIER ::= { + * iso(1) member-body(2) us(840) ansi-X9-62(10045) signatures(4) + * ecdsa-with-SHA2(3) 2 } */ +#define MBEDTLS_OID_ECDSA_SHA256 MBEDTLS_OID_ANSI_X9_62_SIG_SHA2 "\x02" + +/* ecdsa-with-SHA384 OBJECT IDENTIFIER ::= { + * iso(1) member-body(2) us(840) ansi-X9-62(10045) signatures(4) + * ecdsa-with-SHA2(3) 3 } */ +#define MBEDTLS_OID_ECDSA_SHA384 MBEDTLS_OID_ANSI_X9_62_SIG_SHA2 "\x03" + +/* ecdsa-with-SHA512 OBJECT IDENTIFIER ::= { + * iso(1) member-body(2) us(840) ansi-X9-62(10045) signatures(4) + * ecdsa-with-SHA2(3) 4 } */ +#define MBEDTLS_OID_ECDSA_SHA512 MBEDTLS_OID_ANSI_X9_62_SIG_SHA2 "\x04" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \brief Base OID descriptor structure + */ +typedef struct mbedtls_oid_descriptor_t +{ + const char *asn1; /*!< OID ASN.1 representation */ + size_t asn1_len; /*!< length of asn1 */ + const char *name; /*!< official name (e.g. from RFC) */ + const char *description; /*!< human friendly description */ +} mbedtls_oid_descriptor_t; + +/** + * \brief Translate an ASN.1 OID into its numeric representation + * (e.g. "\x2A\x86\x48\x86\xF7\x0D" into "1.2.840.113549") + * + * \param buf buffer to put representation in + * \param size size of the buffer + * \param oid OID to translate + * + * \return Length of the string written (excluding final NULL) or + * MBEDTLS_ERR_OID_BUF_TOO_SMALL in case of error + */ +int mbedtls_oid_get_numeric_string( char *buf, size_t size, const mbedtls_asn1_buf *oid ); + +#if defined(MBEDTLS_X509_USE_C) || defined(MBEDTLS_X509_CREATE_C) +/** + * \brief Translate an X.509 extension OID into local values + * + * \param oid OID to use + * \param ext_type place to store the extension type + * + * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND + */ +int mbedtls_oid_get_x509_ext_type( const mbedtls_asn1_buf *oid, int *ext_type ); +#endif + +/** + * \brief Translate an X.509 attribute type OID into the short name + * (e.g. the OID for an X520 Common Name into "CN") + * + * \param oid OID to use + * \param short_name place to store the string pointer + * + * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND + */ +int mbedtls_oid_get_attr_short_name( const mbedtls_asn1_buf *oid, const char **short_name ); + +/** + * \brief Translate PublicKeyAlgorithm OID into pk_type + * + * \param oid OID to use + * \param pk_alg place to store public key algorithm + * + * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND + */ +int mbedtls_oid_get_pk_alg( const mbedtls_asn1_buf *oid, mbedtls_pk_type_t *pk_alg ); + +/** + * \brief Translate pk_type into PublicKeyAlgorithm OID + * + * \param pk_alg Public key type to look for + * \param oid place to store ASN.1 OID string pointer + * \param olen length of the OID + * + * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND + */ +int mbedtls_oid_get_oid_by_pk_alg( mbedtls_pk_type_t pk_alg, + const char **oid, size_t *olen ); + +#if defined(MBEDTLS_ECP_C) +/** + * \brief Translate NamedCurve OID into an EC group identifier + * + * \param oid OID to use + * \param grp_id place to store group id + * + * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND + */ +int mbedtls_oid_get_ec_grp( const mbedtls_asn1_buf *oid, mbedtls_ecp_group_id *grp_id ); + +/** + * \brief Translate EC group identifier into NamedCurve OID + * + * \param grp_id EC group identifier + * \param oid place to store ASN.1 OID string pointer + * \param olen length of the OID + * + * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND + */ +int mbedtls_oid_get_oid_by_ec_grp( mbedtls_ecp_group_id grp_id, + const char **oid, size_t *olen ); +#endif /* MBEDTLS_ECP_C */ + +#if defined(MBEDTLS_MD_C) +/** + * \brief Translate SignatureAlgorithm OID into md_type and pk_type + * + * \param oid OID to use + * \param md_alg place to store message digest algorithm + * \param pk_alg place to store public key algorithm + * + * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND + */ +int mbedtls_oid_get_sig_alg( const mbedtls_asn1_buf *oid, + mbedtls_md_type_t *md_alg, mbedtls_pk_type_t *pk_alg ); + +/** + * \brief Translate SignatureAlgorithm OID into description + * + * \param oid OID to use + * \param desc place to store string pointer + * + * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND + */ +int mbedtls_oid_get_sig_alg_desc( const mbedtls_asn1_buf *oid, const char **desc ); + +/** + * \brief Translate md_type and pk_type into SignatureAlgorithm OID + * + * \param md_alg message digest algorithm + * \param pk_alg public key algorithm + * \param oid place to store ASN.1 OID string pointer + * \param olen length of the OID + * + * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND + */ +int mbedtls_oid_get_oid_by_sig_alg( mbedtls_pk_type_t pk_alg, mbedtls_md_type_t md_alg, + const char **oid, size_t *olen ); + +/** + * \brief Translate hash algorithm OID into md_type + * + * \param oid OID to use + * \param md_alg place to store message digest algorithm + * + * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND + */ +int mbedtls_oid_get_md_alg( const mbedtls_asn1_buf *oid, mbedtls_md_type_t *md_alg ); + +/** + * \brief Translate hmac algorithm OID into md_type + * + * \param oid OID to use + * \param md_hmac place to store message hmac algorithm + * + * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND + */ +int mbedtls_oid_get_md_hmac( const mbedtls_asn1_buf *oid, mbedtls_md_type_t *md_hmac ); +#endif /* MBEDTLS_MD_C */ + +/** + * \brief Translate Extended Key Usage OID into description + * + * \param oid OID to use + * \param desc place to store string pointer + * + * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND + */ +int mbedtls_oid_get_extended_key_usage( const mbedtls_asn1_buf *oid, const char **desc ); + +/** + * \brief Translate md_type into hash algorithm OID + * + * \param md_alg message digest algorithm + * \param oid place to store ASN.1 OID string pointer + * \param olen length of the OID + * + * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND + */ +int mbedtls_oid_get_oid_by_md( mbedtls_md_type_t md_alg, const char **oid, size_t *olen ); + +#if defined(MBEDTLS_CIPHER_C) +/** + * \brief Translate encryption algorithm OID into cipher_type + * + * \param oid OID to use + * \param cipher_alg place to store cipher algorithm + * + * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND + */ +int mbedtls_oid_get_cipher_alg( const mbedtls_asn1_buf *oid, mbedtls_cipher_type_t *cipher_alg ); +#endif /* MBEDTLS_CIPHER_C */ + +#if defined(MBEDTLS_PKCS12_C) +/** + * \brief Translate PKCS#12 PBE algorithm OID into md_type and + * cipher_type + * + * \param oid OID to use + * \param md_alg place to store message digest algorithm + * \param cipher_alg place to store cipher algorithm + * + * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND + */ +int mbedtls_oid_get_pkcs12_pbe_alg( const mbedtls_asn1_buf *oid, mbedtls_md_type_t *md_alg, + mbedtls_cipher_type_t *cipher_alg ); +#endif /* MBEDTLS_PKCS12_C */ + +#ifdef __cplusplus +} +#endif + +#endif /* oid.h */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/padlock.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/padlock.h new file mode 100644 index 0000000000000000000000000000000000000000..721a5d4930e6c71da84f33d74fc740df14f9a8b1 --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/padlock.h @@ -0,0 +1,126 @@ +/** + * \file padlock.h + * + * \brief VIA PadLock ACE for HW encryption/decryption supported by some + * processors + * + * \warning These functions are only for internal use by other library + * functions; you must not call them directly. + */ +/* + * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ +#ifndef MBEDTLS_PADLOCK_H +#define MBEDTLS_PADLOCK_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include "aes.h" + +#define MBEDTLS_ERR_PADLOCK_DATA_MISALIGNED -0x0030 /**< Input data should be aligned. */ + +#if defined(__has_feature) +#if __has_feature(address_sanitizer) +#define MBEDTLS_HAVE_ASAN +#endif +#endif + +/* Some versions of ASan result in errors about not enough registers */ +#if defined(MBEDTLS_HAVE_ASM) && defined(__GNUC__) && defined(__i386__) && \ + !defined(MBEDTLS_HAVE_ASAN) + +#ifndef MBEDTLS_HAVE_X86 +#define MBEDTLS_HAVE_X86 +#endif + +#include + +#define MBEDTLS_PADLOCK_RNG 0x000C +#define MBEDTLS_PADLOCK_ACE 0x00C0 +#define MBEDTLS_PADLOCK_PHE 0x0C00 +#define MBEDTLS_PADLOCK_PMM 0x3000 + +#define MBEDTLS_PADLOCK_ALIGN16(x) (uint32_t *) (16 + ((int32_t) (x) & ~15)) + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \brief Internal PadLock detection routine + * + * \note This function is only for internal use by other library + * functions; you must not call it directly. + * + * \param feature The feature to detect + * + * \return 1 if CPU has support for the feature, 0 otherwise + */ +int mbedtls_padlock_has_support( int feature ); + +/** + * \brief Internal PadLock AES-ECB block en(de)cryption + * + * \note This function is only for internal use by other library + * functions; you must not call it directly. + * + * \param ctx AES context + * \param mode MBEDTLS_AES_ENCRYPT or MBEDTLS_AES_DECRYPT + * \param input 16-byte input block + * \param output 16-byte output block + * + * \return 0 if success, 1 if operation failed + */ +int mbedtls_padlock_xcryptecb( mbedtls_aes_context *ctx, + int mode, + const unsigned char input[16], + unsigned char output[16] ); + +/** + * \brief Internal PadLock AES-CBC buffer en(de)cryption + * + * \note This function is only for internal use by other library + * functions; you must not call it directly. + * + * \param ctx AES context + * \param mode MBEDTLS_AES_ENCRYPT or MBEDTLS_AES_DECRYPT + * \param length length of the input data + * \param iv initialization vector (updated after use) + * \param input buffer holding the input data + * \param output buffer holding the output data + * + * \return 0 if success, 1 if operation failed + */ +int mbedtls_padlock_xcryptcbc( mbedtls_aes_context *ctx, + int mode, + size_t length, + unsigned char iv[16], + const unsigned char *input, + unsigned char *output ); + +#ifdef __cplusplus +} +#endif + +#endif /* HAVE_X86 */ + +#endif /* padlock.h */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/pem.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/pem.h new file mode 100644 index 0000000000000000000000000000000000000000..a29e9ce30024888dd4a04204ab7048c8fa196feb --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/pem.h @@ -0,0 +1,136 @@ +/** + * \file pem.h + * + * \brief Privacy Enhanced Mail (PEM) decoding + */ +/* + * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ +#ifndef MBEDTLS_PEM_H +#define MBEDTLS_PEM_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include + +/** + * \name PEM Error codes + * These error codes are returned in case of errors reading the + * PEM data. + * \{ + */ +#define MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT -0x1080 /**< No PEM header or footer found. */ +#define MBEDTLS_ERR_PEM_INVALID_DATA -0x1100 /**< PEM string is not as expected. */ +#define MBEDTLS_ERR_PEM_ALLOC_FAILED -0x1180 /**< Failed to allocate memory. */ +#define MBEDTLS_ERR_PEM_INVALID_ENC_IV -0x1200 /**< RSA IV is not in hex-format. */ +#define MBEDTLS_ERR_PEM_UNKNOWN_ENC_ALG -0x1280 /**< Unsupported key encryption algorithm. */ +#define MBEDTLS_ERR_PEM_PASSWORD_REQUIRED -0x1300 /**< Private key password can't be empty. */ +#define MBEDTLS_ERR_PEM_PASSWORD_MISMATCH -0x1380 /**< Given private key password does not allow for correct decryption. */ +#define MBEDTLS_ERR_PEM_FEATURE_UNAVAILABLE -0x1400 /**< Unavailable feature, e.g. hashing/encryption combination. */ +#define MBEDTLS_ERR_PEM_BAD_INPUT_DATA -0x1480 /**< Bad input parameters to function. */ +/* \} name */ + +#ifdef __cplusplus +extern "C" { +#endif + +#if defined(MBEDTLS_PEM_PARSE_C) +/** + * \brief PEM context structure + */ +typedef struct mbedtls_pem_context +{ + unsigned char *buf; /*!< buffer for decoded data */ + size_t buflen; /*!< length of the buffer */ + unsigned char *info; /*!< buffer for extra header information */ +} +mbedtls_pem_context; + +/** + * \brief PEM context setup + * + * \param ctx context to be initialized + */ +void mbedtls_pem_init( mbedtls_pem_context *ctx ); + +/** + * \brief Read a buffer for PEM information and store the resulting + * data into the specified context buffers. + * + * \param ctx context to use + * \param header header string to seek and expect + * \param footer footer string to seek and expect + * \param data source data to look in (must be nul-terminated) + * \param pwd password for decryption (can be NULL) + * \param pwdlen length of password + * \param use_len destination for total length used (set after header is + * correctly read, so unless you get + * MBEDTLS_ERR_PEM_BAD_INPUT_DATA or + * MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT, use_len is + * the length to skip) + * + * \note Attempts to check password correctness by verifying if + * the decrypted text starts with an ASN.1 sequence of + * appropriate length + * + * \return 0 on success, or a specific PEM error code + */ +int mbedtls_pem_read_buffer( mbedtls_pem_context *ctx, const char *header, const char *footer, + const unsigned char *data, + const unsigned char *pwd, + size_t pwdlen, size_t *use_len ); + +/** + * \brief PEM context memory freeing + * + * \param ctx context to be freed + */ +void mbedtls_pem_free( mbedtls_pem_context *ctx ); +#endif /* MBEDTLS_PEM_PARSE_C */ + +#if defined(MBEDTLS_PEM_WRITE_C) +/** + * \brief Write a buffer of PEM information from a DER encoded + * buffer. + * + * \param header header string to write + * \param footer footer string to write + * \param der_data DER data to write + * \param der_len length of the DER data + * \param buf buffer to write to + * \param buf_len length of output buffer + * \param olen total length written / required (if buf_len is not enough) + * + * \return 0 on success, or a specific PEM or BASE64 error code. On + * MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL olen is the required + * size. + */ +int mbedtls_pem_write_buffer( const char *header, const char *footer, + const unsigned char *der_data, size_t der_len, + unsigned char *buf, size_t buf_len, size_t *olen ); +#endif /* MBEDTLS_PEM_WRITE_C */ + +#ifdef __cplusplus +} +#endif + +#endif /* pem.h */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/pk.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/pk.h new file mode 100644 index 0000000000000000000000000000000000000000..136427503a0aa9d5390a9c6cf5d979de4008ea55 --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/pk.h @@ -0,0 +1,755 @@ +/** + * \file pk.h + * + * \brief Public Key abstraction layer + */ +/* + * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ + +#ifndef MBEDTLS_PK_H +#define MBEDTLS_PK_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include "md.h" + +#if defined(MBEDTLS_RSA_C) +#include "rsa.h" +#endif + +#if defined(MBEDTLS_ECP_C) +#include "ecp.h" +#endif + +#if defined(MBEDTLS_ECDSA_C) +#include "ecdsa.h" +#endif + +#if ( defined(__ARMCC_VERSION) || defined(_MSC_VER) ) && \ + !defined(inline) && !defined(__cplusplus) +#define inline __inline +#endif + +#define MBEDTLS_ERR_PK_ALLOC_FAILED -0x3F80 /**< Memory allocation failed. */ +#define MBEDTLS_ERR_PK_TYPE_MISMATCH -0x3F00 /**< Type mismatch, eg attempt to encrypt with an ECDSA key */ +#define MBEDTLS_ERR_PK_BAD_INPUT_DATA -0x3E80 /**< Bad input parameters to function. */ +#define MBEDTLS_ERR_PK_FILE_IO_ERROR -0x3E00 /**< Read/write of file failed. */ +#define MBEDTLS_ERR_PK_KEY_INVALID_VERSION -0x3D80 /**< Unsupported key version */ +#define MBEDTLS_ERR_PK_KEY_INVALID_FORMAT -0x3D00 /**< Invalid key tag or value. */ +#define MBEDTLS_ERR_PK_UNKNOWN_PK_ALG -0x3C80 /**< Key algorithm is unsupported (only RSA and EC are supported). */ +#define MBEDTLS_ERR_PK_PASSWORD_REQUIRED -0x3C00 /**< Private key password can't be empty. */ +#define MBEDTLS_ERR_PK_PASSWORD_MISMATCH -0x3B80 /**< Given private key password does not allow for correct decryption. */ +#define MBEDTLS_ERR_PK_INVALID_PUBKEY -0x3B00 /**< The pubkey tag or value is invalid (only RSA and EC are supported). */ +#define MBEDTLS_ERR_PK_INVALID_ALG -0x3A80 /**< The algorithm tag or value is invalid. */ +#define MBEDTLS_ERR_PK_UNKNOWN_NAMED_CURVE -0x3A00 /**< Elliptic curve is unsupported (only NIST curves are supported). */ +#define MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE -0x3980 /**< Unavailable feature, e.g. RSA disabled for RSA key. */ +#define MBEDTLS_ERR_PK_SIG_LEN_MISMATCH -0x3900 /**< The buffer contains a valid signature followed by more data. */ + +/* MBEDTLS_ERR_PK_HW_ACCEL_FAILED is deprecated and should not be used. */ +#define MBEDTLS_ERR_PK_HW_ACCEL_FAILED -0x3880 /**< PK hardware accelerator failed. */ + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \brief Public key types + */ +typedef enum { + MBEDTLS_PK_NONE=0, + MBEDTLS_PK_RSA, + MBEDTLS_PK_ECKEY, + MBEDTLS_PK_ECKEY_DH, + MBEDTLS_PK_ECDSA, + MBEDTLS_PK_RSA_ALT, + MBEDTLS_PK_RSASSA_PSS, +} mbedtls_pk_type_t; + +/** + * \brief Options for RSASSA-PSS signature verification. + * See \c mbedtls_rsa_rsassa_pss_verify_ext() + */ +typedef struct mbedtls_pk_rsassa_pss_options +{ + mbedtls_md_type_t mgf1_hash_id; + int expected_salt_len; + +} mbedtls_pk_rsassa_pss_options; + +/** + * \brief Types for interfacing with the debug module + */ +typedef enum +{ + MBEDTLS_PK_DEBUG_NONE = 0, + MBEDTLS_PK_DEBUG_MPI, + MBEDTLS_PK_DEBUG_ECP, +} mbedtls_pk_debug_type; + +/** + * \brief Item to send to the debug module + */ +typedef struct mbedtls_pk_debug_item +{ + mbedtls_pk_debug_type type; + const char *name; + void *value; +} mbedtls_pk_debug_item; + +/** Maximum number of item send for debugging, plus 1 */ +#define MBEDTLS_PK_DEBUG_MAX_ITEMS 3 + +/** + * \brief Public key information and operations + */ +typedef struct mbedtls_pk_info_t mbedtls_pk_info_t; + +/** + * \brief Public key container + */ +typedef struct mbedtls_pk_context +{ + const mbedtls_pk_info_t * pk_info; /**< Public key information */ + void * pk_ctx; /**< Underlying public key context */ +} mbedtls_pk_context; + +#if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) +/** + * \brief Context for resuming operations + */ +typedef struct +{ + const mbedtls_pk_info_t * pk_info; /**< Public key information */ + void * rs_ctx; /**< Underlying restart context */ +} mbedtls_pk_restart_ctx; +#else /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */ +/* Now we can declare functions that take a pointer to that */ +typedef void mbedtls_pk_restart_ctx; +#endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */ + +#if defined(MBEDTLS_RSA_C) +/** + * Quick access to an RSA context inside a PK context. + * + * \warning You must make sure the PK context actually holds an RSA context + * before using this function! + */ +static inline mbedtls_rsa_context *mbedtls_pk_rsa( const mbedtls_pk_context pk ) +{ + return( (mbedtls_rsa_context *) (pk).pk_ctx ); +} +#endif /* MBEDTLS_RSA_C */ + +#if defined(MBEDTLS_ECP_C) +/** + * Quick access to an EC context inside a PK context. + * + * \warning You must make sure the PK context actually holds an EC context + * before using this function! + */ +static inline mbedtls_ecp_keypair *mbedtls_pk_ec( const mbedtls_pk_context pk ) +{ + return( (mbedtls_ecp_keypair *) (pk).pk_ctx ); +} +#endif /* MBEDTLS_ECP_C */ + +#if defined(MBEDTLS_PK_RSA_ALT_SUPPORT) +/** + * \brief Types for RSA-alt abstraction + */ +typedef int (*mbedtls_pk_rsa_alt_decrypt_func)( void *ctx, int mode, size_t *olen, + const unsigned char *input, unsigned char *output, + size_t output_max_len ); +typedef int (*mbedtls_pk_rsa_alt_sign_func)( void *ctx, + int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, + int mode, mbedtls_md_type_t md_alg, unsigned int hashlen, + const unsigned char *hash, unsigned char *sig ); +typedef size_t (*mbedtls_pk_rsa_alt_key_len_func)( void *ctx ); +#endif /* MBEDTLS_PK_RSA_ALT_SUPPORT */ + +/** + * \brief Return information associated with the given PK type + * + * \param pk_type PK type to search for. + * + * \return The PK info associated with the type or NULL if not found. + */ +const mbedtls_pk_info_t *mbedtls_pk_info_from_type( mbedtls_pk_type_t pk_type ); + +/** + * \brief Initialize a #mbedtls_pk_context (as NONE). + * + * \param ctx The context to initialize. + * This must not be \c NULL. + */ +void mbedtls_pk_init( mbedtls_pk_context *ctx ); + +/** + * \brief Free the components of a #mbedtls_pk_context. + * + * \param ctx The context to clear. It must have been initialized. + * If this is \c NULL, this function does nothing. + */ +void mbedtls_pk_free( mbedtls_pk_context *ctx ); + +#if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) +/** + * \brief Initialize a restart context + * + * \param ctx The context to initialize. + * This must not be \c NULL. + */ +void mbedtls_pk_restart_init( mbedtls_pk_restart_ctx *ctx ); + +/** + * \brief Free the components of a restart context + * + * \param ctx The context to clear. It must have been initialized. + * If this is \c NULL, this function does nothing. + */ +void mbedtls_pk_restart_free( mbedtls_pk_restart_ctx *ctx ); +#endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */ + +/** + * \brief Initialize a PK context with the information given + * and allocates the type-specific PK subcontext. + * + * \param ctx Context to initialize. It must not have been set + * up yet (type #MBEDTLS_PK_NONE). + * \param info Information to use + * + * \return 0 on success, + * MBEDTLS_ERR_PK_BAD_INPUT_DATA on invalid input, + * MBEDTLS_ERR_PK_ALLOC_FAILED on allocation failure. + * + * \note For contexts holding an RSA-alt key, use + * \c mbedtls_pk_setup_rsa_alt() instead. + */ +int mbedtls_pk_setup( mbedtls_pk_context *ctx, const mbedtls_pk_info_t *info ); + +#if defined(MBEDTLS_PK_RSA_ALT_SUPPORT) +/** + * \brief Initialize an RSA-alt context + * + * \param ctx Context to initialize. It must not have been set + * up yet (type #MBEDTLS_PK_NONE). + * \param key RSA key pointer + * \param decrypt_func Decryption function + * \param sign_func Signing function + * \param key_len_func Function returning key length in bytes + * + * \return 0 on success, or MBEDTLS_ERR_PK_BAD_INPUT_DATA if the + * context wasn't already initialized as RSA_ALT. + * + * \note This function replaces \c mbedtls_pk_setup() for RSA-alt. + */ +int mbedtls_pk_setup_rsa_alt( mbedtls_pk_context *ctx, void * key, + mbedtls_pk_rsa_alt_decrypt_func decrypt_func, + mbedtls_pk_rsa_alt_sign_func sign_func, + mbedtls_pk_rsa_alt_key_len_func key_len_func ); +#endif /* MBEDTLS_PK_RSA_ALT_SUPPORT */ + +/** + * \brief Get the size in bits of the underlying key + * + * \param ctx The context to query. It must have been initialized. + * + * \return Key size in bits, or 0 on error + */ +size_t mbedtls_pk_get_bitlen( const mbedtls_pk_context *ctx ); + +/** + * \brief Get the length in bytes of the underlying key + * + * \param ctx The context to query. It must have been initialized. + * + * \return Key length in bytes, or 0 on error + */ +static inline size_t mbedtls_pk_get_len( const mbedtls_pk_context *ctx ) +{ + return( ( mbedtls_pk_get_bitlen( ctx ) + 7 ) / 8 ); +} + +/** + * \brief Tell if a context can do the operation given by type + * + * \param ctx The context to query. It must have been initialized. + * \param type The desired type. + * + * \return 1 if the context can do operations on the given type. + * \return 0 if the context cannot do the operations on the given + * type. This is always the case for a context that has + * been initialized but not set up, or that has been + * cleared with mbedtls_pk_free(). + */ +int mbedtls_pk_can_do( const mbedtls_pk_context *ctx, mbedtls_pk_type_t type ); + +/** + * \brief Verify signature (including padding if relevant). + * + * \param ctx The PK context to use. It must have been set up. + * \param md_alg Hash algorithm used (see notes) + * \param hash Hash of the message to sign + * \param hash_len Hash length or 0 (see notes) + * \param sig Signature to verify + * \param sig_len Signature length + * + * \return 0 on success (signature is valid), + * #MBEDTLS_ERR_PK_SIG_LEN_MISMATCH if there is a valid + * signature in sig but its length is less than \p siglen, + * or a specific error code. + * + * \note For RSA keys, the default padding type is PKCS#1 v1.5. + * Use \c mbedtls_pk_verify_ext( MBEDTLS_PK_RSASSA_PSS, ... ) + * to verify RSASSA_PSS signatures. + * + * \note If hash_len is 0, then the length associated with md_alg + * is used instead, or an error returned if it is invalid. + * + * \note md_alg may be MBEDTLS_MD_NONE, only if hash_len != 0 + */ +int mbedtls_pk_verify( mbedtls_pk_context *ctx, mbedtls_md_type_t md_alg, + const unsigned char *hash, size_t hash_len, + const unsigned char *sig, size_t sig_len ); + +/** + * \brief Restartable version of \c mbedtls_pk_verify() + * + * \note Performs the same job as \c mbedtls_pk_verify(), but can + * return early and restart according to the limit set with + * \c mbedtls_ecp_set_max_ops() to reduce blocking for ECC + * operations. For RSA, same as \c mbedtls_pk_verify(). + * + * \param ctx The PK context to use. It must have been set up. + * \param md_alg Hash algorithm used (see notes) + * \param hash Hash of the message to sign + * \param hash_len Hash length or 0 (see notes) + * \param sig Signature to verify + * \param sig_len Signature length + * \param rs_ctx Restart context (NULL to disable restart) + * + * \return See \c mbedtls_pk_verify(), or + * \return #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of + * operations was reached: see \c mbedtls_ecp_set_max_ops(). + */ +int mbedtls_pk_verify_restartable( mbedtls_pk_context *ctx, + mbedtls_md_type_t md_alg, + const unsigned char *hash, size_t hash_len, + const unsigned char *sig, size_t sig_len, + mbedtls_pk_restart_ctx *rs_ctx ); + +/** + * \brief Verify signature, with options. + * (Includes verification of the padding depending on type.) + * + * \param type Signature type (inc. possible padding type) to verify + * \param options Pointer to type-specific options, or NULL + * \param ctx The PK context to use. It must have been set up. + * \param md_alg Hash algorithm used (see notes) + * \param hash Hash of the message to sign + * \param hash_len Hash length or 0 (see notes) + * \param sig Signature to verify + * \param sig_len Signature length + * + * \return 0 on success (signature is valid), + * #MBEDTLS_ERR_PK_TYPE_MISMATCH if the PK context can't be + * used for this type of signatures, + * #MBEDTLS_ERR_PK_SIG_LEN_MISMATCH if there is a valid + * signature in sig but its length is less than \p siglen, + * or a specific error code. + * + * \note If hash_len is 0, then the length associated with md_alg + * is used instead, or an error returned if it is invalid. + * + * \note md_alg may be MBEDTLS_MD_NONE, only if hash_len != 0 + * + * \note If type is MBEDTLS_PK_RSASSA_PSS, then options must point + * to a mbedtls_pk_rsassa_pss_options structure, + * otherwise it must be NULL. + */ +int mbedtls_pk_verify_ext( mbedtls_pk_type_t type, const void *options, + mbedtls_pk_context *ctx, mbedtls_md_type_t md_alg, + const unsigned char *hash, size_t hash_len, + const unsigned char *sig, size_t sig_len ); + +/** + * \brief Make signature, including padding if relevant. + * + * \param ctx The PK context to use. It must have been set up + * with a private key. + * \param md_alg Hash algorithm used (see notes) + * \param hash Hash of the message to sign + * \param hash_len Hash length or 0 (see notes) + * \param sig Place to write the signature + * \param sig_len Number of bytes written + * \param f_rng RNG function + * \param p_rng RNG parameter + * + * \return 0 on success, or a specific error code. + * + * \note For RSA keys, the default padding type is PKCS#1 v1.5. + * There is no interface in the PK module to make RSASSA-PSS + * signatures yet. + * + * \note If hash_len is 0, then the length associated with md_alg + * is used instead, or an error returned if it is invalid. + * + * \note For RSA, md_alg may be MBEDTLS_MD_NONE if hash_len != 0. + * For ECDSA, md_alg may never be MBEDTLS_MD_NONE. + * + * \note In order to ensure enough space for the signature, the + * \p sig buffer size must be of at least + * `max(MBEDTLS_ECDSA_MAX_LEN, MBEDTLS_MPI_MAX_SIZE)` bytes. + */ +int mbedtls_pk_sign( mbedtls_pk_context *ctx, mbedtls_md_type_t md_alg, + const unsigned char *hash, size_t hash_len, + unsigned char *sig, size_t *sig_len, + int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ); + +/** + * \brief Restartable version of \c mbedtls_pk_sign() + * + * \note Performs the same job as \c mbedtls_pk_sign(), but can + * return early and restart according to the limit set with + * \c mbedtls_ecp_set_max_ops() to reduce blocking for ECC + * operations. For RSA, same as \c mbedtls_pk_sign(). + * + * \note In order to ensure enough space for the signature, the + * \p sig buffer size must be of at least + * `max(MBEDTLS_ECDSA_MAX_LEN, MBEDTLS_MPI_MAX_SIZE)` bytes. + * + * \param ctx The PK context to use. It must have been set up + * with a private key. + * \param md_alg Hash algorithm used (see notes) + * \param hash Hash of the message to sign + * \param hash_len Hash length or 0 (see notes) + * \param sig Place to write the signature + * \param sig_len Number of bytes written + * \param f_rng RNG function + * \param p_rng RNG parameter + * \param rs_ctx Restart context (NULL to disable restart) + * + * \return See \c mbedtls_pk_sign(), or + * \return #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of + * operations was reached: see \c mbedtls_ecp_set_max_ops(). + */ +int mbedtls_pk_sign_restartable( mbedtls_pk_context *ctx, + mbedtls_md_type_t md_alg, + const unsigned char *hash, size_t hash_len, + unsigned char *sig, size_t *sig_len, + int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, + mbedtls_pk_restart_ctx *rs_ctx ); + +/** + * \brief Decrypt message (including padding if relevant). + * + * \param ctx The PK context to use. It must have been set up + * with a private key. + * \param input Input to decrypt + * \param ilen Input size + * \param output Decrypted output + * \param olen Decrypted message length + * \param osize Size of the output buffer + * \param f_rng RNG function + * \param p_rng RNG parameter + * + * \note For RSA keys, the default padding type is PKCS#1 v1.5. + * + * \return 0 on success, or a specific error code. + */ +int mbedtls_pk_decrypt( mbedtls_pk_context *ctx, + const unsigned char *input, size_t ilen, + unsigned char *output, size_t *olen, size_t osize, + int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ); + +/** + * \brief Encrypt message (including padding if relevant). + * + * \param ctx The PK context to use. It must have been set up. + * \param input Message to encrypt + * \param ilen Message size + * \param output Encrypted output + * \param olen Encrypted output length + * \param osize Size of the output buffer + * \param f_rng RNG function + * \param p_rng RNG parameter + * + * \note For RSA keys, the default padding type is PKCS#1 v1.5. + * + * \return 0 on success, or a specific error code. + */ +int mbedtls_pk_encrypt( mbedtls_pk_context *ctx, + const unsigned char *input, size_t ilen, + unsigned char *output, size_t *olen, size_t osize, + int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ); + +/** + * \brief Check if a public-private pair of keys matches. + * + * \param pub Context holding a public key. + * \param prv Context holding a private (and public) key. + * + * \return 0 on success or MBEDTLS_ERR_PK_BAD_INPUT_DATA + */ +int mbedtls_pk_check_pair( const mbedtls_pk_context *pub, const mbedtls_pk_context *prv ); + +/** + * \brief Export debug information + * + * \param ctx The PK context to use. It must have been initialized. + * \param items Place to write debug items + * + * \return 0 on success or MBEDTLS_ERR_PK_BAD_INPUT_DATA + */ +int mbedtls_pk_debug( const mbedtls_pk_context *ctx, mbedtls_pk_debug_item *items ); + +/** + * \brief Access the type name + * + * \param ctx The PK context to use. It must have been initialized. + * + * \return Type name on success, or "invalid PK" + */ +const char * mbedtls_pk_get_name( const mbedtls_pk_context *ctx ); + +/** + * \brief Get the key type + * + * \param ctx The PK context to use. It must have been initialized. + * + * \return Type on success. + * \return #MBEDTLS_PK_NONE for a context that has not been set up. + */ +mbedtls_pk_type_t mbedtls_pk_get_type( const mbedtls_pk_context *ctx ); + +#if defined(MBEDTLS_PK_PARSE_C) +/** \ingroup pk_module */ +/** + * \brief Parse a private key in PEM or DER format + * + * \param ctx The PK context to fill. It must have been initialized + * but not set up. + * \param key Input buffer to parse. + * The buffer must contain the input exactly, with no + * extra trailing material. For PEM, the buffer must + * contain a null-terminated string. + * \param keylen Size of \b key in bytes. + * For PEM data, this includes the terminating null byte, + * so \p keylen must be equal to `strlen(key) + 1`. + * \param pwd Optional password for decryption. + * Pass \c NULL if expecting a non-encrypted key. + * Pass a string of \p pwdlen bytes if expecting an encrypted + * key; a non-encrypted key will also be accepted. + * The empty password is not supported. + * \param pwdlen Size of the password in bytes. + * Ignored if \p pwd is \c NULL. + * + * \note On entry, ctx must be empty, either freshly initialised + * with mbedtls_pk_init() or reset with mbedtls_pk_free(). If you need a + * specific key type, check the result with mbedtls_pk_can_do(). + * + * \note The key is also checked for correctness. + * + * \return 0 if successful, or a specific PK or PEM error code + */ +int mbedtls_pk_parse_key( mbedtls_pk_context *ctx, + const unsigned char *key, size_t keylen, + const unsigned char *pwd, size_t pwdlen ); + +/** \ingroup pk_module */ +/** + * \brief Parse a public key in PEM or DER format + * + * \param ctx The PK context to fill. It must have been initialized + * but not set up. + * \param key Input buffer to parse. + * The buffer must contain the input exactly, with no + * extra trailing material. For PEM, the buffer must + * contain a null-terminated string. + * \param keylen Size of \b key in bytes. + * For PEM data, this includes the terminating null byte, + * so \p keylen must be equal to `strlen(key) + 1`. + * + * \note On entry, ctx must be empty, either freshly initialised + * with mbedtls_pk_init() or reset with mbedtls_pk_free(). If you need a + * specific key type, check the result with mbedtls_pk_can_do(). + * + * \note The key is also checked for correctness. + * + * \return 0 if successful, or a specific PK or PEM error code + */ +int mbedtls_pk_parse_public_key( mbedtls_pk_context *ctx, + const unsigned char *key, size_t keylen ); + +#if defined(MBEDTLS_FS_IO) +/** \ingroup pk_module */ +/** + * \brief Load and parse a private key + * + * \param ctx The PK context to fill. It must have been initialized + * but not set up. + * \param path filename to read the private key from + * \param password Optional password to decrypt the file. + * Pass \c NULL if expecting a non-encrypted key. + * Pass a null-terminated string if expecting an encrypted + * key; a non-encrypted key will also be accepted. + * The empty password is not supported. + * + * \note On entry, ctx must be empty, either freshly initialised + * with mbedtls_pk_init() or reset with mbedtls_pk_free(). If you need a + * specific key type, check the result with mbedtls_pk_can_do(). + * + * \note The key is also checked for correctness. + * + * \return 0 if successful, or a specific PK or PEM error code + */ +int mbedtls_pk_parse_keyfile( mbedtls_pk_context *ctx, + const char *path, const char *password ); + +/** \ingroup pk_module */ +/** + * \brief Load and parse a public key + * + * \param ctx The PK context to fill. It must have been initialized + * but not set up. + * \param path filename to read the public key from + * + * \note On entry, ctx must be empty, either freshly initialised + * with mbedtls_pk_init() or reset with mbedtls_pk_free(). If + * you need a specific key type, check the result with + * mbedtls_pk_can_do(). + * + * \note The key is also checked for correctness. + * + * \return 0 if successful, or a specific PK or PEM error code + */ +int mbedtls_pk_parse_public_keyfile( mbedtls_pk_context *ctx, const char *path ); +#endif /* MBEDTLS_FS_IO */ +#endif /* MBEDTLS_PK_PARSE_C */ + +#if defined(MBEDTLS_PK_WRITE_C) +/** + * \brief Write a private key to a PKCS#1 or SEC1 DER structure + * Note: data is written at the end of the buffer! Use the + * return value to determine where you should start + * using the buffer + * + * \param ctx PK context which must contain a valid private key. + * \param buf buffer to write to + * \param size size of the buffer + * + * \return length of data written if successful, or a specific + * error code + */ +int mbedtls_pk_write_key_der( mbedtls_pk_context *ctx, unsigned char *buf, size_t size ); + +/** + * \brief Write a public key to a SubjectPublicKeyInfo DER structure + * Note: data is written at the end of the buffer! Use the + * return value to determine where you should start + * using the buffer + * + * \param ctx PK context which must contain a valid public or private key. + * \param buf buffer to write to + * \param size size of the buffer + * + * \return length of data written if successful, or a specific + * error code + */ +int mbedtls_pk_write_pubkey_der( mbedtls_pk_context *ctx, unsigned char *buf, size_t size ); + +#if defined(MBEDTLS_PEM_WRITE_C) +/** + * \brief Write a public key to a PEM string + * + * \param ctx PK context which must contain a valid public or private key. + * \param buf Buffer to write to. The output includes a + * terminating null byte. + * \param size Size of the buffer in bytes. + * + * \return 0 if successful, or a specific error code + */ +int mbedtls_pk_write_pubkey_pem( mbedtls_pk_context *ctx, unsigned char *buf, size_t size ); + +/** + * \brief Write a private key to a PKCS#1 or SEC1 PEM string + * + * \param ctx PK context which must contain a valid private key. + * \param buf Buffer to write to. The output includes a + * terminating null byte. + * \param size Size of the buffer in bytes. + * + * \return 0 if successful, or a specific error code + */ +int mbedtls_pk_write_key_pem( mbedtls_pk_context *ctx, unsigned char *buf, size_t size ); +#endif /* MBEDTLS_PEM_WRITE_C */ +#endif /* MBEDTLS_PK_WRITE_C */ + +/* + * WARNING: Low-level functions. You probably do not want to use these unless + * you are certain you do ;) + */ + +#if defined(MBEDTLS_PK_PARSE_C) +/** + * \brief Parse a SubjectPublicKeyInfo DER structure + * + * \param p the position in the ASN.1 data + * \param end end of the buffer + * \param pk The PK context to fill. It must have been initialized + * but not set up. + * + * \return 0 if successful, or a specific PK error code + */ +int mbedtls_pk_parse_subpubkey( unsigned char **p, const unsigned char *end, + mbedtls_pk_context *pk ); +#endif /* MBEDTLS_PK_PARSE_C */ + +#if defined(MBEDTLS_PK_WRITE_C) +/** + * \brief Write a subjectPublicKey to ASN.1 data + * Note: function works backwards in data buffer + * + * \param p reference to current position pointer + * \param start start of the buffer (for bounds-checking) + * \param key PK context which must contain a valid public or private key. + * + * \return the length written or a negative error code + */ +int mbedtls_pk_write_pubkey( unsigned char **p, unsigned char *start, + const mbedtls_pk_context *key ); +#endif /* MBEDTLS_PK_WRITE_C */ + +/* + * Internal module functions. You probably do not want to use these unless you + * know you do. + */ +#if defined(MBEDTLS_FS_IO) +int mbedtls_pk_load_file( const char *path, unsigned char **buf, size_t *n ); +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* MBEDTLS_PK_H */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/pk_internal.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/pk_internal.h new file mode 100644 index 0000000000000000000000000000000000000000..48b7a5f7bf2993402ffd6b5acf9bee8c53eed7e4 --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/pk_internal.h @@ -0,0 +1,138 @@ +/** + * \file pk_internal.h + * + * \brief Public Key abstraction layer: wrapper functions + */ +/* + * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ + +#ifndef MBEDTLS_PK_WRAP_H +#define MBEDTLS_PK_WRAP_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include "pk.h" + +struct mbedtls_pk_info_t +{ + /** Public key type */ + mbedtls_pk_type_t type; + + /** Type name */ + const char *name; + + /** Get key size in bits */ + size_t (*get_bitlen)( const void * ); + + /** Tell if the context implements this type (e.g. ECKEY can do ECDSA) */ + int (*can_do)( mbedtls_pk_type_t type ); + + /** Verify signature */ + int (*verify_func)( void *ctx, mbedtls_md_type_t md_alg, + const unsigned char *hash, size_t hash_len, + const unsigned char *sig, size_t sig_len ); + + /** Make signature */ + int (*sign_func)( void *ctx, mbedtls_md_type_t md_alg, + const unsigned char *hash, size_t hash_len, + unsigned char *sig, size_t *sig_len, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng ); + +#if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) + /** Verify signature (restartable) */ + int (*verify_rs_func)( void *ctx, mbedtls_md_type_t md_alg, + const unsigned char *hash, size_t hash_len, + const unsigned char *sig, size_t sig_len, + void *rs_ctx ); + + /** Make signature (restartable) */ + int (*sign_rs_func)( void *ctx, mbedtls_md_type_t md_alg, + const unsigned char *hash, size_t hash_len, + unsigned char *sig, size_t *sig_len, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng, void *rs_ctx ); +#endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */ + + /** Decrypt message */ + int (*decrypt_func)( void *ctx, const unsigned char *input, size_t ilen, + unsigned char *output, size_t *olen, size_t osize, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng ); + + /** Encrypt message */ + int (*encrypt_func)( void *ctx, const unsigned char *input, size_t ilen, + unsigned char *output, size_t *olen, size_t osize, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng ); + + /** Check public-private key pair */ + int (*check_pair_func)( const void *pub, const void *prv ); + + /** Allocate a new context */ + void * (*ctx_alloc_func)( void ); + + /** Free the given context */ + void (*ctx_free_func)( void *ctx ); + +#if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) + /** Allocate the restart context */ + void * (*rs_alloc_func)( void ); + + /** Free the restart context */ + void (*rs_free_func)( void *rs_ctx ); +#endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */ + + /** Interface with the debug module */ + void (*debug_func)( const void *ctx, mbedtls_pk_debug_item *items ); + +}; +#if defined(MBEDTLS_PK_RSA_ALT_SUPPORT) +/* Container for RSA-alt */ +typedef struct +{ + void *key; + mbedtls_pk_rsa_alt_decrypt_func decrypt_func; + mbedtls_pk_rsa_alt_sign_func sign_func; + mbedtls_pk_rsa_alt_key_len_func key_len_func; +} mbedtls_rsa_alt_context; +#endif + +#if defined(MBEDTLS_RSA_C) +extern const mbedtls_pk_info_t mbedtls_rsa_info; +#endif + +#if defined(MBEDTLS_ECP_C) +extern const mbedtls_pk_info_t mbedtls_eckey_info; +extern const mbedtls_pk_info_t mbedtls_eckeydh_info; +#endif + +#if defined(MBEDTLS_ECDSA_C) +extern const mbedtls_pk_info_t mbedtls_ecdsa_info; +#endif + +#if defined(MBEDTLS_PK_RSA_ALT_SUPPORT) +extern const mbedtls_pk_info_t mbedtls_rsa_alt_info; +#endif + +#endif /* MBEDTLS_PK_WRAP_H */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/pkcs11.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/pkcs11.h new file mode 100644 index 0000000000000000000000000000000000000000..02427ddc1e9ce2980e46b6664326450a1bd48798 --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/pkcs11.h @@ -0,0 +1,175 @@ +/** + * \file pkcs11.h + * + * \brief Wrapper for PKCS#11 library libpkcs11-helper + * + * \author Adriaan de Jong + */ +/* + * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ +#ifndef MBEDTLS_PKCS11_H +#define MBEDTLS_PKCS11_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#if defined(MBEDTLS_PKCS11_C) + +#include "x509_crt.h" + +#include + +#if ( defined(__ARMCC_VERSION) || defined(_MSC_VER) ) && \ + !defined(inline) && !defined(__cplusplus) +#define inline __inline +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Context for PKCS #11 private keys. + */ +typedef struct mbedtls_pkcs11_context +{ + pkcs11h_certificate_t pkcs11h_cert; + int len; +} mbedtls_pkcs11_context; + +/** + * Initialize a mbedtls_pkcs11_context. + * (Just making memory references valid.) + */ +void mbedtls_pkcs11_init( mbedtls_pkcs11_context *ctx ); + +/** + * Fill in a mbed TLS certificate, based on the given PKCS11 helper certificate. + * + * \param cert X.509 certificate to fill + * \param pkcs11h_cert PKCS #11 helper certificate + * + * \return 0 on success. + */ +int mbedtls_pkcs11_x509_cert_bind( mbedtls_x509_crt *cert, pkcs11h_certificate_t pkcs11h_cert ); + +/** + * Set up a mbedtls_pkcs11_context storing the given certificate. Note that the + * mbedtls_pkcs11_context will take over control of the certificate, freeing it when + * done. + * + * \param priv_key Private key structure to fill. + * \param pkcs11_cert PKCS #11 helper certificate + * + * \return 0 on success + */ +int mbedtls_pkcs11_priv_key_bind( mbedtls_pkcs11_context *priv_key, + pkcs11h_certificate_t pkcs11_cert ); + +/** + * Free the contents of the given private key context. Note that the structure + * itself is not freed. + * + * \param priv_key Private key structure to cleanup + */ +void mbedtls_pkcs11_priv_key_free( mbedtls_pkcs11_context *priv_key ); + +/** + * \brief Do an RSA private key decrypt, then remove the message + * padding + * + * \param ctx PKCS #11 context + * \param mode must be MBEDTLS_RSA_PRIVATE, for compatibility with rsa.c's signature + * \param input buffer holding the encrypted data + * \param output buffer that will hold the plaintext + * \param olen will contain the plaintext length + * \param output_max_len maximum length of the output buffer + * + * \return 0 if successful, or an MBEDTLS_ERR_RSA_XXX error code + * + * \note The output buffer must be as large as the size + * of ctx->N (eg. 128 bytes if RSA-1024 is used) otherwise + * an error is thrown. + */ +int mbedtls_pkcs11_decrypt( mbedtls_pkcs11_context *ctx, + int mode, size_t *olen, + const unsigned char *input, + unsigned char *output, + size_t output_max_len ); + +/** + * \brief Do a private RSA to sign a message digest + * + * \param ctx PKCS #11 context + * \param mode must be MBEDTLS_RSA_PRIVATE, for compatibility with rsa.c's signature + * \param md_alg a MBEDTLS_MD_XXX (use MBEDTLS_MD_NONE for signing raw data) + * \param hashlen message digest length (for MBEDTLS_MD_NONE only) + * \param hash buffer holding the message digest + * \param sig buffer that will hold the ciphertext + * + * \return 0 if the signing operation was successful, + * or an MBEDTLS_ERR_RSA_XXX error code + * + * \note The "sig" buffer must be as large as the size + * of ctx->N (eg. 128 bytes if RSA-1024 is used). + */ +int mbedtls_pkcs11_sign( mbedtls_pkcs11_context *ctx, + int mode, + mbedtls_md_type_t md_alg, + unsigned int hashlen, + const unsigned char *hash, + unsigned char *sig ); + +/** + * SSL/TLS wrappers for PKCS#11 functions + */ +static inline int mbedtls_ssl_pkcs11_decrypt( void *ctx, int mode, size_t *olen, + const unsigned char *input, unsigned char *output, + size_t output_max_len ) +{ + return mbedtls_pkcs11_decrypt( (mbedtls_pkcs11_context *) ctx, mode, olen, input, output, + output_max_len ); +} + +static inline int mbedtls_ssl_pkcs11_sign( void *ctx, + int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, + int mode, mbedtls_md_type_t md_alg, unsigned int hashlen, + const unsigned char *hash, unsigned char *sig ) +{ + ((void) f_rng); + ((void) p_rng); + return mbedtls_pkcs11_sign( (mbedtls_pkcs11_context *) ctx, mode, md_alg, + hashlen, hash, sig ); +} + +static inline size_t mbedtls_ssl_pkcs11_key_len( void *ctx ) +{ + return ( (mbedtls_pkcs11_context *) ctx )->len; +} + +#ifdef __cplusplus +} +#endif + +#endif /* MBEDTLS_PKCS11_C */ + +#endif /* MBEDTLS_PKCS11_H */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/pkcs12.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/pkcs12.h new file mode 100644 index 0000000000000000000000000000000000000000..d441357b7f4ff386bb1f7c142eea8cc74f98487e --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/pkcs12.h @@ -0,0 +1,130 @@ +/** + * \file pkcs12.h + * + * \brief PKCS#12 Personal Information Exchange Syntax + */ +/* + * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ +#ifndef MBEDTLS_PKCS12_H +#define MBEDTLS_PKCS12_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include "md.h" +#include "cipher.h" +#include "asn1.h" + +#include + +#define MBEDTLS_ERR_PKCS12_BAD_INPUT_DATA -0x1F80 /**< Bad input parameters to function. */ +#define MBEDTLS_ERR_PKCS12_FEATURE_UNAVAILABLE -0x1F00 /**< Feature not available, e.g. unsupported encryption scheme. */ +#define MBEDTLS_ERR_PKCS12_PBE_INVALID_FORMAT -0x1E80 /**< PBE ASN.1 data not as expected. */ +#define MBEDTLS_ERR_PKCS12_PASSWORD_MISMATCH -0x1E00 /**< Given private key password does not allow for correct decryption. */ + +#define MBEDTLS_PKCS12_DERIVE_KEY 1 /**< encryption/decryption key */ +#define MBEDTLS_PKCS12_DERIVE_IV 2 /**< initialization vector */ +#define MBEDTLS_PKCS12_DERIVE_MAC_KEY 3 /**< integrity / MAC key */ + +#define MBEDTLS_PKCS12_PBE_DECRYPT 0 +#define MBEDTLS_PKCS12_PBE_ENCRYPT 1 + +#ifdef __cplusplus +extern "C" { +#endif + +#if defined(MBEDTLS_ASN1_PARSE_C) + +/** + * \brief PKCS12 Password Based function (encryption / decryption) + * for pbeWithSHAAnd128BitRC4 + * + * \param pbe_params an ASN1 buffer containing the pkcs-12PbeParams structure + * \param mode either MBEDTLS_PKCS12_PBE_ENCRYPT or MBEDTLS_PKCS12_PBE_DECRYPT + * \param pwd the password used (may be NULL if no password is used) + * \param pwdlen length of the password (may be 0) + * \param input the input data + * \param len data length + * \param output the output buffer + * + * \return 0 if successful, or a MBEDTLS_ERR_XXX code + */ +int mbedtls_pkcs12_pbe_sha1_rc4_128( mbedtls_asn1_buf *pbe_params, int mode, + const unsigned char *pwd, size_t pwdlen, + const unsigned char *input, size_t len, + unsigned char *output ); + +/** + * \brief PKCS12 Password Based function (encryption / decryption) + * for cipher-based and mbedtls_md-based PBE's + * + * \param pbe_params an ASN1 buffer containing the pkcs-12PbeParams structure + * \param mode either MBEDTLS_PKCS12_PBE_ENCRYPT or MBEDTLS_PKCS12_PBE_DECRYPT + * \param cipher_type the cipher used + * \param md_type the mbedtls_md used + * \param pwd the password used (may be NULL if no password is used) + * \param pwdlen length of the password (may be 0) + * \param input the input data + * \param len data length + * \param output the output buffer + * + * \return 0 if successful, or a MBEDTLS_ERR_XXX code + */ +int mbedtls_pkcs12_pbe( mbedtls_asn1_buf *pbe_params, int mode, + mbedtls_cipher_type_t cipher_type, mbedtls_md_type_t md_type, + const unsigned char *pwd, size_t pwdlen, + const unsigned char *input, size_t len, + unsigned char *output ); + +#endif /* MBEDTLS_ASN1_PARSE_C */ + +/** + * \brief The PKCS#12 derivation function uses a password and a salt + * to produce pseudo-random bits for a particular "purpose". + * + * Depending on the given id, this function can produce an + * encryption/decryption key, an nitialization vector or an + * integrity key. + * + * \param data buffer to store the derived data in + * \param datalen length to fill + * \param pwd password to use (may be NULL if no password is used) + * \param pwdlen length of the password (may be 0) + * \param salt salt buffer to use + * \param saltlen length of the salt + * \param mbedtls_md mbedtls_md type to use during the derivation + * \param id id that describes the purpose (can be MBEDTLS_PKCS12_DERIVE_KEY, + * MBEDTLS_PKCS12_DERIVE_IV or MBEDTLS_PKCS12_DERIVE_MAC_KEY) + * \param iterations number of iterations + * + * \return 0 if successful, or a MD, BIGNUM type error. + */ +int mbedtls_pkcs12_derivation( unsigned char *data, size_t datalen, + const unsigned char *pwd, size_t pwdlen, + const unsigned char *salt, size_t saltlen, + mbedtls_md_type_t mbedtls_md, int id, int iterations ); + +#ifdef __cplusplus +} +#endif + +#endif /* pkcs12.h */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/pkcs5.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/pkcs5.h new file mode 100644 index 0000000000000000000000000000000000000000..c92185f7a68c9412900f9501e2b49987a5d0a91b --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/pkcs5.h @@ -0,0 +1,109 @@ +/** + * \file pkcs5.h + * + * \brief PKCS#5 functions + * + * \author Mathias Olsson + */ +/* + * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ +#ifndef MBEDTLS_PKCS5_H +#define MBEDTLS_PKCS5_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include "asn1.h" +#include "md.h" + +#include +#include + +#define MBEDTLS_ERR_PKCS5_BAD_INPUT_DATA -0x2f80 /**< Bad input parameters to function. */ +#define MBEDTLS_ERR_PKCS5_INVALID_FORMAT -0x2f00 /**< Unexpected ASN.1 data. */ +#define MBEDTLS_ERR_PKCS5_FEATURE_UNAVAILABLE -0x2e80 /**< Requested encryption or digest alg not available. */ +#define MBEDTLS_ERR_PKCS5_PASSWORD_MISMATCH -0x2e00 /**< Given private key password does not allow for correct decryption. */ + +#define MBEDTLS_PKCS5_DECRYPT 0 +#define MBEDTLS_PKCS5_ENCRYPT 1 + +#ifdef __cplusplus +extern "C" { +#endif + +#if defined(MBEDTLS_ASN1_PARSE_C) + +/** + * \brief PKCS#5 PBES2 function + * + * \param pbe_params the ASN.1 algorithm parameters + * \param mode either MBEDTLS_PKCS5_DECRYPT or MBEDTLS_PKCS5_ENCRYPT + * \param pwd password to use when generating key + * \param pwdlen length of password + * \param data data to process + * \param datalen length of data + * \param output output buffer + * + * \returns 0 on success, or a MBEDTLS_ERR_XXX code if verification fails. + */ +int mbedtls_pkcs5_pbes2( const mbedtls_asn1_buf *pbe_params, int mode, + const unsigned char *pwd, size_t pwdlen, + const unsigned char *data, size_t datalen, + unsigned char *output ); + +#endif /* MBEDTLS_ASN1_PARSE_C */ + +/** + * \brief PKCS#5 PBKDF2 using HMAC + * + * \param ctx Generic HMAC context + * \param password Password to use when generating key + * \param plen Length of password + * \param salt Salt to use when generating key + * \param slen Length of salt + * \param iteration_count Iteration count + * \param key_length Length of generated key in bytes + * \param output Generated key. Must be at least as big as key_length + * + * \returns 0 on success, or a MBEDTLS_ERR_XXX code if verification fails. + */ +int mbedtls_pkcs5_pbkdf2_hmac( mbedtls_md_context_t *ctx, const unsigned char *password, + size_t plen, const unsigned char *salt, size_t slen, + unsigned int iteration_count, + uint32_t key_length, unsigned char *output ); + +#if defined(MBEDTLS_SELF_TEST) + +/** + * \brief Checkup routine + * + * \return 0 if successful, or 1 if the test failed + */ +int mbedtls_pkcs5_self_test( int verbose ); + +#endif /* MBEDTLS_SELF_TEST */ + +#ifdef __cplusplus +} +#endif + +#endif /* pkcs5.h */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/platform.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/platform.h new file mode 100644 index 0000000000000000000000000000000000000000..89fe8a7b197a30942f8b1da62a2c94cb1e4da9dd --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/platform.h @@ -0,0 +1,367 @@ +/** + * \file platform.h + * + * \brief This file contains the definitions and functions of the + * Mbed TLS platform abstraction layer. + * + * The platform abstraction layer removes the need for the library + * to directly link to standard C library functions or operating + * system services, making the library easier to port and embed. + * Application developers and users of the library can provide their own + * implementations of these functions, or implementations specific to + * their platform, which can be statically linked to the library or + * dynamically configured at runtime. + */ +/* + * Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of Mbed TLS (https://tls.mbed.org) + */ +#ifndef MBEDTLS_PLATFORM_H +#define MBEDTLS_PLATFORM_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#if defined(MBEDTLS_HAVE_TIME) +#include "platform_time.h" +#endif + +#define MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED -0x0070 /**< Hardware accelerator failed */ +#define MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED -0x0072 /**< The requested feature is not supported by the platform */ + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \name SECTION: Module settings + * + * The configuration options you can set for this module are in this section. + * Either change them in config.h or define them on the compiler command line. + * \{ + */ + +#if !defined(MBEDTLS_PLATFORM_NO_STD_FUNCTIONS) +#include +#include +#include +#if !defined(MBEDTLS_PLATFORM_STD_SNPRINTF) +#if defined(_WIN32) +#define MBEDTLS_PLATFORM_STD_SNPRINTF mbedtls_platform_win32_snprintf /**< The default \c snprintf function to use. */ +#else +#define MBEDTLS_PLATFORM_STD_SNPRINTF snprintf /**< The default \c snprintf function to use. */ +#endif +#endif +#if !defined(MBEDTLS_PLATFORM_STD_PRINTF) +#define MBEDTLS_PLATFORM_STD_PRINTF printf /**< The default \c printf function to use. */ +#endif +#if !defined(MBEDTLS_PLATFORM_STD_FPRINTF) +#define MBEDTLS_PLATFORM_STD_FPRINTF fprintf /**< The default \c fprintf function to use. */ +#endif +#if !defined(MBEDTLS_PLATFORM_STD_CALLOC) +#define MBEDTLS_PLATFORM_STD_CALLOC calloc /**< The default \c calloc function to use. */ +#endif +#if !defined(MBEDTLS_PLATFORM_STD_FREE) +#define MBEDTLS_PLATFORM_STD_FREE free /**< The default \c free function to use. */ +#endif +#if !defined(MBEDTLS_PLATFORM_STD_EXIT) +#define MBEDTLS_PLATFORM_STD_EXIT exit /**< The default \c exit function to use. */ +#endif +#if !defined(MBEDTLS_PLATFORM_STD_TIME) +#define MBEDTLS_PLATFORM_STD_TIME time /**< The default \c time function to use. */ +#endif +#if !defined(MBEDTLS_PLATFORM_STD_EXIT_SUCCESS) +#define MBEDTLS_PLATFORM_STD_EXIT_SUCCESS EXIT_SUCCESS /**< The default exit value to use. */ +#endif +#if !defined(MBEDTLS_PLATFORM_STD_EXIT_FAILURE) +#define MBEDTLS_PLATFORM_STD_EXIT_FAILURE EXIT_FAILURE /**< The default exit value to use. */ +#endif +#if defined(MBEDTLS_FS_IO) +#if !defined(MBEDTLS_PLATFORM_STD_NV_SEED_READ) +#define MBEDTLS_PLATFORM_STD_NV_SEED_READ mbedtls_platform_std_nv_seed_read +#endif +#if !defined(MBEDTLS_PLATFORM_STD_NV_SEED_WRITE) +#define MBEDTLS_PLATFORM_STD_NV_SEED_WRITE mbedtls_platform_std_nv_seed_write +#endif +#if !defined(MBEDTLS_PLATFORM_STD_NV_SEED_FILE) +#define MBEDTLS_PLATFORM_STD_NV_SEED_FILE "seedfile" +#endif +#endif /* MBEDTLS_FS_IO */ +#else /* MBEDTLS_PLATFORM_NO_STD_FUNCTIONS */ +#if defined(MBEDTLS_PLATFORM_STD_MEM_HDR) +#include MBEDTLS_PLATFORM_STD_MEM_HDR +#endif +#endif /* MBEDTLS_PLATFORM_NO_STD_FUNCTIONS */ + + +/* \} name SECTION: Module settings */ + +/* + * The function pointers for calloc and free. + */ +#if defined(MBEDTLS_PLATFORM_MEMORY) +#if defined(MBEDTLS_PLATFORM_FREE_MACRO) && \ + defined(MBEDTLS_PLATFORM_CALLOC_MACRO) +#define mbedtls_free MBEDTLS_PLATFORM_FREE_MACRO +#define mbedtls_calloc MBEDTLS_PLATFORM_CALLOC_MACRO +#else +/* For size_t */ +#include +extern void *mbedtls_calloc( size_t n, size_t size ); +extern void mbedtls_free( void *ptr ); + +/** + * \brief This function dynamically sets the memory-management + * functions used by the library, during runtime. + * + * \param calloc_func The \c calloc function implementation. + * \param free_func The \c free function implementation. + * + * \return \c 0. + */ +int mbedtls_platform_set_calloc_free( void * (*calloc_func)( size_t, size_t ), + void (*free_func)( void * ) ); +#endif /* MBEDTLS_PLATFORM_FREE_MACRO && MBEDTLS_PLATFORM_CALLOC_MACRO */ +#else /* !MBEDTLS_PLATFORM_MEMORY */ +#define mbedtls_free free +#define mbedtls_calloc calloc +#endif /* MBEDTLS_PLATFORM_MEMORY && !MBEDTLS_PLATFORM_{FREE,CALLOC}_MACRO */ + +/* + * The function pointers for fprintf + */ +#if defined(MBEDTLS_PLATFORM_FPRINTF_ALT) +/* We need FILE * */ +#include +extern int (*mbedtls_fprintf)( FILE *stream, const char *format, ... ); + +/** + * \brief This function dynamically configures the fprintf + * function that is called when the + * mbedtls_fprintf() function is invoked by the library. + * + * \param fprintf_func The \c fprintf function implementation. + * + * \return \c 0. + */ +int mbedtls_platform_set_fprintf( int (*fprintf_func)( FILE *stream, const char *, + ... ) ); +#else +#if defined(MBEDTLS_PLATFORM_FPRINTF_MACRO) +#define mbedtls_fprintf MBEDTLS_PLATFORM_FPRINTF_MACRO +#else +#define mbedtls_fprintf fprintf +#endif /* MBEDTLS_PLATFORM_FPRINTF_MACRO */ +#endif /* MBEDTLS_PLATFORM_FPRINTF_ALT */ + +/* + * The function pointers for printf + */ +#if defined(MBEDTLS_PLATFORM_PRINTF_ALT) +extern int (*mbedtls_printf)( const char *format, ... ); + +/** + * \brief This function dynamically configures the snprintf + * function that is called when the mbedtls_snprintf() + * function is invoked by the library. + * + * \param printf_func The \c printf function implementation. + * + * \return \c 0 on success. + */ +int mbedtls_platform_set_printf( int (*printf_func)( const char *, ... ) ); +#else /* !MBEDTLS_PLATFORM_PRINTF_ALT */ +#if defined(MBEDTLS_PLATFORM_PRINTF_MACRO) +#define mbedtls_printf MBEDTLS_PLATFORM_PRINTF_MACRO +#else +#define mbedtls_printf printf +#endif /* MBEDTLS_PLATFORM_PRINTF_MACRO */ +#endif /* MBEDTLS_PLATFORM_PRINTF_ALT */ + +/* + * The function pointers for snprintf + * + * The snprintf implementation should conform to C99: + * - it *must* always correctly zero-terminate the buffer + * (except when n == 0, then it must leave the buffer untouched) + * - however it is acceptable to return -1 instead of the required length when + * the destination buffer is too short. + */ +#if defined(_WIN32) +/* For Windows (inc. MSYS2), we provide our own fixed implementation */ +int mbedtls_platform_win32_snprintf( char *s, size_t n, const char *fmt, ... ); +#endif + +#if defined(MBEDTLS_PLATFORM_SNPRINTF_ALT) +extern int (*mbedtls_snprintf)( char * s, size_t n, const char * format, ... ); + +/** + * \brief This function allows configuring a custom + * \c snprintf function pointer. + * + * \param snprintf_func The \c snprintf function implementation. + * + * \return \c 0 on success. + */ +int mbedtls_platform_set_snprintf( int (*snprintf_func)( char * s, size_t n, + const char * format, ... ) ); +#else /* MBEDTLS_PLATFORM_SNPRINTF_ALT */ +#if defined(MBEDTLS_PLATFORM_SNPRINTF_MACRO) +#define mbedtls_snprintf MBEDTLS_PLATFORM_SNPRINTF_MACRO +#else +#define mbedtls_snprintf MBEDTLS_PLATFORM_STD_SNPRINTF +#endif /* MBEDTLS_PLATFORM_SNPRINTF_MACRO */ +#endif /* MBEDTLS_PLATFORM_SNPRINTF_ALT */ + +/* + * The function pointers for exit + */ +#if defined(MBEDTLS_PLATFORM_EXIT_ALT) +extern void (*mbedtls_exit)( int status ); + +/** + * \brief This function dynamically configures the exit + * function that is called when the mbedtls_exit() + * function is invoked by the library. + * + * \param exit_func The \c exit function implementation. + * + * \return \c 0 on success. + */ +int mbedtls_platform_set_exit( void (*exit_func)( int status ) ); +#else +#if defined(MBEDTLS_PLATFORM_EXIT_MACRO) +#define mbedtls_exit MBEDTLS_PLATFORM_EXIT_MACRO +#else +#define mbedtls_exit exit +#endif /* MBEDTLS_PLATFORM_EXIT_MACRO */ +#endif /* MBEDTLS_PLATFORM_EXIT_ALT */ + +/* + * The default exit values + */ +#if defined(MBEDTLS_PLATFORM_STD_EXIT_SUCCESS) +#define MBEDTLS_EXIT_SUCCESS MBEDTLS_PLATFORM_STD_EXIT_SUCCESS +#else +#define MBEDTLS_EXIT_SUCCESS 0 +#endif +#if defined(MBEDTLS_PLATFORM_STD_EXIT_FAILURE) +#define MBEDTLS_EXIT_FAILURE MBEDTLS_PLATFORM_STD_EXIT_FAILURE +#else +#define MBEDTLS_EXIT_FAILURE 1 +#endif + +/* + * The function pointers for reading from and writing a seed file to + * Non-Volatile storage (NV) in a platform-independent way + * + * Only enabled when the NV seed entropy source is enabled + */ +#if defined(MBEDTLS_ENTROPY_NV_SEED) +#if !defined(MBEDTLS_PLATFORM_NO_STD_FUNCTIONS) && defined(MBEDTLS_FS_IO) +/* Internal standard platform definitions */ +int mbedtls_platform_std_nv_seed_read( unsigned char *buf, size_t buf_len ); +int mbedtls_platform_std_nv_seed_write( unsigned char *buf, size_t buf_len ); +#endif + +#if defined(MBEDTLS_PLATFORM_NV_SEED_ALT) +extern int (*mbedtls_nv_seed_read)( unsigned char *buf, size_t buf_len ); +extern int (*mbedtls_nv_seed_write)( unsigned char *buf, size_t buf_len ); + +/** + * \brief This function allows configuring custom seed file writing and + * reading functions. + * + * \param nv_seed_read_func The seed reading function implementation. + * \param nv_seed_write_func The seed writing function implementation. + * + * \return \c 0 on success. + */ +int mbedtls_platform_set_nv_seed( + int (*nv_seed_read_func)( unsigned char *buf, size_t buf_len ), + int (*nv_seed_write_func)( unsigned char *buf, size_t buf_len ) + ); +#else +#if defined(MBEDTLS_PLATFORM_NV_SEED_READ_MACRO) && \ + defined(MBEDTLS_PLATFORM_NV_SEED_WRITE_MACRO) +#define mbedtls_nv_seed_read MBEDTLS_PLATFORM_NV_SEED_READ_MACRO +#define mbedtls_nv_seed_write MBEDTLS_PLATFORM_NV_SEED_WRITE_MACRO +#else +#define mbedtls_nv_seed_read mbedtls_platform_std_nv_seed_read +#define mbedtls_nv_seed_write mbedtls_platform_std_nv_seed_write +#endif +#endif /* MBEDTLS_PLATFORM_NV_SEED_ALT */ +#endif /* MBEDTLS_ENTROPY_NV_SEED */ + +#if !defined(MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT) + +/** + * \brief The platform context structure. + * + * \note This structure may be used to assist platform-specific + * setup or teardown operations. + */ +typedef struct mbedtls_platform_context +{ + char dummy; /**< A placeholder member, as empty structs are not portable. */ +} +mbedtls_platform_context; + +#else +#include "platform_alt.h" +#endif /* !MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT */ + +/** + * \brief This function performs any platform-specific initialization + * operations. + * + * \note This function should be called before any other library functions. + * + * Its implementation is platform-specific, and unless + * platform-specific code is provided, it does nothing. + * + * \note The usage and necessity of this function is dependent on the platform. + * + * \param ctx The platform context. + * + * \return \c 0 on success. + */ +int mbedtls_platform_setup( mbedtls_platform_context *ctx ); +/** + * \brief This function performs any platform teardown operations. + * + * \note This function should be called after every other Mbed TLS module + * has been correctly freed using the appropriate free function. + * + * Its implementation is platform-specific, and unless + * platform-specific code is provided, it does nothing. + * + * \note The usage and necessity of this function is dependent on the platform. + * + * \param ctx The platform context. + * + */ +void mbedtls_platform_teardown( mbedtls_platform_context *ctx ); + +#ifdef __cplusplus +} +#endif + +#endif /* platform.h */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/platform_time.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/platform_time.h new file mode 100644 index 0000000000000000000000000000000000000000..2ed36f56c9ee8f357908ce4ef7cfc3811ac02661 --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/platform_time.h @@ -0,0 +1,82 @@ +/** + * \file platform_time.h + * + * \brief mbed TLS Platform time abstraction + */ +/* + * Copyright (C) 2006-2016, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ +#ifndef MBEDTLS_PLATFORM_TIME_H +#define MBEDTLS_PLATFORM_TIME_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \name SECTION: Module settings + * + * The configuration options you can set for this module are in this section. + * Either change them in config.h or define them on the compiler command line. + * \{ + */ + +/* + * The time_t datatype + */ +#if defined(MBEDTLS_PLATFORM_TIME_TYPE_MACRO) +typedef MBEDTLS_PLATFORM_TIME_TYPE_MACRO mbedtls_time_t; +#else +/* For time_t */ +#include +typedef time_t mbedtls_time_t; +#endif /* MBEDTLS_PLATFORM_TIME_TYPE_MACRO */ + +/* + * The function pointers for time + */ +#if defined(MBEDTLS_PLATFORM_TIME_ALT) +extern mbedtls_time_t (*mbedtls_time)( mbedtls_time_t* time ); + +/** + * \brief Set your own time function pointer + * + * \param time_func the time function implementation + * + * \return 0 + */ +int mbedtls_platform_set_time( mbedtls_time_t (*time_func)( mbedtls_time_t* time ) ); +#else +#if defined(MBEDTLS_PLATFORM_TIME_MACRO) +#define mbedtls_time MBEDTLS_PLATFORM_TIME_MACRO +#else +#define mbedtls_time time +#endif /* MBEDTLS_PLATFORM_TIME_MACRO */ +#endif /* MBEDTLS_PLATFORM_TIME_ALT */ + +#ifdef __cplusplus +} +#endif + +#endif /* platform_time.h */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/platform_util.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/platform_util.h new file mode 100644 index 0000000000000000000000000000000000000000..09d09651829546adec10f1127e1b2f30686292c2 --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/platform_util.h @@ -0,0 +1,196 @@ +/** + * \file platform_util.h + * + * \brief Common and shared functions used by multiple modules in the Mbed TLS + * library. + */ +/* + * Copyright (C) 2018, Arm Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of Mbed TLS (https://tls.mbed.org) + */ +#ifndef MBEDTLS_PLATFORM_UTIL_H +#define MBEDTLS_PLATFORM_UTIL_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include +#if defined(MBEDTLS_HAVE_TIME_DATE) +#include "platform_time.h" +#include +#endif /* MBEDTLS_HAVE_TIME_DATE */ + +#ifdef __cplusplus +extern "C" { +#endif + +#if defined(MBEDTLS_CHECK_PARAMS) + +#if defined(MBEDTLS_CHECK_PARAMS_ASSERT) +/* Allow the user to define MBEDTLS_PARAM_FAILED to something like assert + * (which is what our config.h suggests). */ +#include +#endif /* MBEDTLS_CHECK_PARAMS_ASSERT */ + +#if defined(MBEDTLS_PARAM_FAILED) +/** An alternative definition of MBEDTLS_PARAM_FAILED has been set in config.h. + * + * This flag can be used to check whether it is safe to assume that + * MBEDTLS_PARAM_FAILED() will expand to a call to mbedtls_param_failed(). + */ +#define MBEDTLS_PARAM_FAILED_ALT + +#elif defined(MBEDTLS_CHECK_PARAMS_ASSERT) +#define MBEDTLS_PARAM_FAILED( cond ) assert( cond ) +#define MBEDTLS_PARAM_FAILED_ALT + +#else /* MBEDTLS_PARAM_FAILED */ +#define MBEDTLS_PARAM_FAILED( cond ) \ + mbedtls_param_failed( #cond, __FILE__, __LINE__ ) + +/** + * \brief User supplied callback function for parameter validation failure. + * See #MBEDTLS_CHECK_PARAMS for context. + * + * This function will be called unless an alternative treatement + * is defined through the #MBEDTLS_PARAM_FAILED macro. + * + * This function can return, and the operation will be aborted, or + * alternatively, through use of setjmp()/longjmp() can resume + * execution in the application code. + * + * \param failure_condition The assertion that didn't hold. + * \param file The file where the assertion failed. + * \param line The line in the file where the assertion failed. + */ +void mbedtls_param_failed( const char *failure_condition, + const char *file, + int line ); +#endif /* MBEDTLS_PARAM_FAILED */ + +/* Internal macro meant to be called only from within the library. */ +#define MBEDTLS_INTERNAL_VALIDATE_RET( cond, ret ) \ + do { \ + if( !(cond) ) \ + { \ + MBEDTLS_PARAM_FAILED( cond ); \ + return( ret ); \ + } \ + } while( 0 ) + +/* Internal macro meant to be called only from within the library. */ +#define MBEDTLS_INTERNAL_VALIDATE( cond ) \ + do { \ + if( !(cond) ) \ + { \ + MBEDTLS_PARAM_FAILED( cond ); \ + return; \ + } \ + } while( 0 ) + +#else /* MBEDTLS_CHECK_PARAMS */ + +/* Internal macros meant to be called only from within the library. */ +#define MBEDTLS_INTERNAL_VALIDATE_RET( cond, ret ) do { } while( 0 ) +#define MBEDTLS_INTERNAL_VALIDATE( cond ) do { } while( 0 ) + +#endif /* MBEDTLS_CHECK_PARAMS */ + +/* Internal helper macros for deprecating API constants. */ +#if !defined(MBEDTLS_DEPRECATED_REMOVED) +#if defined(MBEDTLS_DEPRECATED_WARNING) +/* Deliberately don't (yet) export MBEDTLS_DEPRECATED here + * to avoid conflict with other headers which define and use + * it, too. We might want to move all these definitions here at + * some point for uniformity. */ +#define MBEDTLS_DEPRECATED __attribute__((deprecated)) +MBEDTLS_DEPRECATED typedef char const * mbedtls_deprecated_string_constant_t; +#define MBEDTLS_DEPRECATED_STRING_CONSTANT( VAL ) \ + ( (mbedtls_deprecated_string_constant_t) ( VAL ) ) +MBEDTLS_DEPRECATED typedef int mbedtls_deprecated_numeric_constant_t; +#define MBEDTLS_DEPRECATED_NUMERIC_CONSTANT( VAL ) \ + ( (mbedtls_deprecated_numeric_constant_t) ( VAL ) ) +#undef MBEDTLS_DEPRECATED +#else /* MBEDTLS_DEPRECATED_WARNING */ +#define MBEDTLS_DEPRECATED_STRING_CONSTANT( VAL ) VAL +#define MBEDTLS_DEPRECATED_NUMERIC_CONSTANT( VAL ) VAL +#endif /* MBEDTLS_DEPRECATED_WARNING */ +#endif /* MBEDTLS_DEPRECATED_REMOVED */ + +/** + * \brief Securely zeroize a buffer + * + * The function is meant to wipe the data contained in a buffer so + * that it can no longer be recovered even if the program memory + * is later compromised. Call this function on sensitive data + * stored on the stack before returning from a function, and on + * sensitive data stored on the heap before freeing the heap + * object. + * + * It is extremely difficult to guarantee that calls to + * mbedtls_platform_zeroize() are not removed by aggressive + * compiler optimizations in a portable way. For this reason, Mbed + * TLS provides the configuration option + * MBEDTLS_PLATFORM_ZEROIZE_ALT, which allows users to configure + * mbedtls_platform_zeroize() to use a suitable implementation for + * their platform and needs + * + * \param buf Buffer to be zeroized + * \param len Length of the buffer in bytes + * + */ +void mbedtls_platform_zeroize( void *buf, size_t len ); + +#if defined(MBEDTLS_HAVE_TIME_DATE) +/** + * \brief Platform-specific implementation of gmtime_r() + * + * The function is a thread-safe abstraction that behaves + * similarly to the gmtime_r() function from Unix/POSIX. + * + * Mbed TLS will try to identify the underlying platform and + * make use of an appropriate underlying implementation (e.g. + * gmtime_r() for POSIX and gmtime_s() for Windows). If this is + * not possible, then gmtime() will be used. In this case, calls + * from the library to gmtime() will be guarded by the mutex + * mbedtls_threading_gmtime_mutex if MBEDTLS_THREADING_C is + * enabled. It is recommended that calls from outside the library + * are also guarded by this mutex. + * + * If MBEDTLS_PLATFORM_GMTIME_R_ALT is defined, then Mbed TLS will + * unconditionally use the alternative implementation for + * mbedtls_platform_gmtime_r() supplied by the user at compile time. + * + * \param tt Pointer to an object containing time (in seconds) since the + * epoch to be converted + * \param tm_buf Pointer to an object where the results will be stored + * + * \return Pointer to an object of type struct tm on success, otherwise + * NULL + */ +struct tm *mbedtls_platform_gmtime_r( const mbedtls_time_t *tt, + struct tm *tm_buf ); +#endif /* MBEDTLS_HAVE_TIME_DATE */ + +#ifdef __cplusplus +} +#endif + +#endif /* MBEDTLS_PLATFORM_UTIL_H */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/poly1305.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/poly1305.h new file mode 100644 index 0000000000000000000000000000000000000000..f0ec44c96833a66e575dc8719314dbf8abbb7e97 --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/poly1305.h @@ -0,0 +1,192 @@ +/** + * \file poly1305.h + * + * \brief This file contains Poly1305 definitions and functions. + * + * Poly1305 is a one-time message authenticator that can be used to + * authenticate messages. Poly1305-AES was created by Daniel + * Bernstein https://cr.yp.to/mac/poly1305-20050329.pdf The generic + * Poly1305 algorithm (not tied to AES) was also standardized in RFC + * 7539. + * + * \author Daniel King + */ + +/* Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of Mbed TLS (https://tls.mbed.org) + */ + +#ifndef MBEDTLS_POLY1305_H +#define MBEDTLS_POLY1305_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include +#include + +#define MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA -0x0057 /**< Invalid input parameter(s). */ + +/* MBEDTLS_ERR_POLY1305_FEATURE_UNAVAILABLE is deprecated and should not be + * used. */ +#define MBEDTLS_ERR_POLY1305_FEATURE_UNAVAILABLE -0x0059 /**< Feature not available. For example, s part of the API is not implemented. */ + +/* MBEDTLS_ERR_POLY1305_HW_ACCEL_FAILED is deprecated and should not be used. + */ +#define MBEDTLS_ERR_POLY1305_HW_ACCEL_FAILED -0x005B /**< Poly1305 hardware accelerator failed. */ + +#ifdef __cplusplus +extern "C" { +#endif + +#if !defined(MBEDTLS_POLY1305_ALT) + +typedef struct mbedtls_poly1305_context +{ + uint32_t r[4]; /** The value for 'r' (low 128 bits of the key). */ + uint32_t s[4]; /** The value for 's' (high 128 bits of the key). */ + uint32_t acc[5]; /** The accumulator number. */ + uint8_t queue[16]; /** The current partial block of data. */ + size_t queue_len; /** The number of bytes stored in 'queue'. */ +} +mbedtls_poly1305_context; + +#else /* MBEDTLS_POLY1305_ALT */ +#include "poly1305_alt.h" +#endif /* MBEDTLS_POLY1305_ALT */ + +/** + * \brief This function initializes the specified Poly1305 context. + * + * It must be the first API called before using + * the context. + * + * It is usually followed by a call to + * \c mbedtls_poly1305_starts(), then one or more calls to + * \c mbedtls_poly1305_update(), then one call to + * \c mbedtls_poly1305_finish(), then finally + * \c mbedtls_poly1305_free(). + * + * \param ctx The Poly1305 context to initialize. This must + * not be \c NULL. + */ +void mbedtls_poly1305_init( mbedtls_poly1305_context *ctx ); + +/** + * \brief This function releases and clears the specified + * Poly1305 context. + * + * \param ctx The Poly1305 context to clear. This may be \c NULL, in which + * case this function is a no-op. If it is not \c NULL, it must + * point to an initialized Poly1305 context. + */ +void mbedtls_poly1305_free( mbedtls_poly1305_context *ctx ); + +/** + * \brief This function sets the one-time authentication key. + * + * \warning The key must be unique and unpredictable for each + * invocation of Poly1305. + * + * \param ctx The Poly1305 context to which the key should be bound. + * This must be initialized. + * \param key The buffer containing the \c 32 Byte (\c 256 Bit) key. + * + * \return \c 0 on success. + * \return A negative error code on failure. + */ +int mbedtls_poly1305_starts( mbedtls_poly1305_context *ctx, + const unsigned char key[32] ); + +/** + * \brief This functions feeds an input buffer into an ongoing + * Poly1305 computation. + * + * It is called between \c mbedtls_cipher_poly1305_starts() and + * \c mbedtls_cipher_poly1305_finish(). + * It can be called repeatedly to process a stream of data. + * + * \param ctx The Poly1305 context to use for the Poly1305 operation. + * This must be initialized and bound to a key. + * \param ilen The length of the input data in Bytes. + * Any value is accepted. + * \param input The buffer holding the input data. + * This pointer can be \c NULL if `ilen == 0`. + * + * \return \c 0 on success. + * \return A negative error code on failure. + */ +int mbedtls_poly1305_update( mbedtls_poly1305_context *ctx, + const unsigned char *input, + size_t ilen ); + +/** + * \brief This function generates the Poly1305 Message + * Authentication Code (MAC). + * + * \param ctx The Poly1305 context to use for the Poly1305 operation. + * This must be initialized and bound to a key. + * \param mac The buffer to where the MAC is written. This must + * be a writable buffer of length \c 16 Bytes. + * + * \return \c 0 on success. + * \return A negative error code on failure. + */ +int mbedtls_poly1305_finish( mbedtls_poly1305_context *ctx, + unsigned char mac[16] ); + +/** + * \brief This function calculates the Poly1305 MAC of the input + * buffer with the provided key. + * + * \warning The key must be unique and unpredictable for each + * invocation of Poly1305. + * + * \param key The buffer containing the \c 32 Byte (\c 256 Bit) key. + * \param ilen The length of the input data in Bytes. + * Any value is accepted. + * \param input The buffer holding the input data. + * This pointer can be \c NULL if `ilen == 0`. + * \param mac The buffer to where the MAC is written. This must be + * a writable buffer of length \c 16 Bytes. + * + * \return \c 0 on success. + * \return A negative error code on failure. + */ +int mbedtls_poly1305_mac( const unsigned char key[32], + const unsigned char *input, + size_t ilen, + unsigned char mac[16] ); + +#if defined(MBEDTLS_SELF_TEST) +/** + * \brief The Poly1305 checkup routine. + * + * \return \c 0 on success. + * \return \c 1 on failure. + */ +int mbedtls_poly1305_self_test( int verbose ); +#endif /* MBEDTLS_SELF_TEST */ + +#ifdef __cplusplus +} +#endif + +#endif /* MBEDTLS_POLY1305_H */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/ripemd160.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/ripemd160.h new file mode 100644 index 0000000000000000000000000000000000000000..b42f6d2a9597ede9ec13bc67d93ee2b6ae1a1bbb --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/ripemd160.h @@ -0,0 +1,237 @@ +/** + * \file ripemd160.h + * + * \brief RIPE MD-160 message digest + */ +/* + * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ +#ifndef MBEDTLS_RIPEMD160_H +#define MBEDTLS_RIPEMD160_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include +#include + +/* MBEDTLS_ERR_RIPEMD160_HW_ACCEL_FAILED is deprecated and should not be used. + */ +#define MBEDTLS_ERR_RIPEMD160_HW_ACCEL_FAILED -0x0031 /**< RIPEMD160 hardware accelerator failed */ + +#ifdef __cplusplus +extern "C" { +#endif + +#if !defined(MBEDTLS_RIPEMD160_ALT) +// Regular implementation +// + +/** + * \brief RIPEMD-160 context structure + */ +typedef struct mbedtls_ripemd160_context +{ + uint32_t total[2]; /*!< number of bytes processed */ + uint32_t state[5]; /*!< intermediate digest state */ + unsigned char buffer[64]; /*!< data block being processed */ +} +mbedtls_ripemd160_context; + +#else /* MBEDTLS_RIPEMD160_ALT */ +#include "ripemd160.h" +#endif /* MBEDTLS_RIPEMD160_ALT */ + +/** + * \brief Initialize RIPEMD-160 context + * + * \param ctx RIPEMD-160 context to be initialized + */ +void mbedtls_ripemd160_init( mbedtls_ripemd160_context *ctx ); + +/** + * \brief Clear RIPEMD-160 context + * + * \param ctx RIPEMD-160 context to be cleared + */ +void mbedtls_ripemd160_free( mbedtls_ripemd160_context *ctx ); + +/** + * \brief Clone (the state of) an RIPEMD-160 context + * + * \param dst The destination context + * \param src The context to be cloned + */ +void mbedtls_ripemd160_clone( mbedtls_ripemd160_context *dst, + const mbedtls_ripemd160_context *src ); + +/** + * \brief RIPEMD-160 context setup + * + * \param ctx context to be initialized + * + * \return 0 if successful + */ +int mbedtls_ripemd160_starts_ret( mbedtls_ripemd160_context *ctx ); + +/** + * \brief RIPEMD-160 process buffer + * + * \param ctx RIPEMD-160 context + * \param input buffer holding the data + * \param ilen length of the input data + * + * \return 0 if successful + */ +int mbedtls_ripemd160_update_ret( mbedtls_ripemd160_context *ctx, + const unsigned char *input, + size_t ilen ); + +/** + * \brief RIPEMD-160 final digest + * + * \param ctx RIPEMD-160 context + * \param output RIPEMD-160 checksum result + * + * \return 0 if successful + */ +int mbedtls_ripemd160_finish_ret( mbedtls_ripemd160_context *ctx, + unsigned char output[20] ); + +/** + * \brief RIPEMD-160 process data block (internal use only) + * + * \param ctx RIPEMD-160 context + * \param data buffer holding one block of data + * + * \return 0 if successful + */ +int mbedtls_internal_ripemd160_process( mbedtls_ripemd160_context *ctx, + const unsigned char data[64] ); + +#if !defined(MBEDTLS_DEPRECATED_REMOVED) +#if defined(MBEDTLS_DEPRECATED_WARNING) +#define MBEDTLS_DEPRECATED __attribute__((deprecated)) +#else +#define MBEDTLS_DEPRECATED +#endif +/** + * \brief RIPEMD-160 context setup + * + * \deprecated Superseded by mbedtls_ripemd160_starts_ret() in 2.7.0 + * + * \param ctx context to be initialized + */ +MBEDTLS_DEPRECATED void mbedtls_ripemd160_starts( + mbedtls_ripemd160_context *ctx ); + +/** + * \brief RIPEMD-160 process buffer + * + * \deprecated Superseded by mbedtls_ripemd160_update_ret() in 2.7.0 + * + * \param ctx RIPEMD-160 context + * \param input buffer holding the data + * \param ilen length of the input data + */ +MBEDTLS_DEPRECATED void mbedtls_ripemd160_update( + mbedtls_ripemd160_context *ctx, + const unsigned char *input, + size_t ilen ); + +/** + * \brief RIPEMD-160 final digest + * + * \deprecated Superseded by mbedtls_ripemd160_finish_ret() in 2.7.0 + * + * \param ctx RIPEMD-160 context + * \param output RIPEMD-160 checksum result + */ +MBEDTLS_DEPRECATED void mbedtls_ripemd160_finish( + mbedtls_ripemd160_context *ctx, + unsigned char output[20] ); + +/** + * \brief RIPEMD-160 process data block (internal use only) + * + * \deprecated Superseded by mbedtls_internal_ripemd160_process() in 2.7.0 + * + * \param ctx RIPEMD-160 context + * \param data buffer holding one block of data + */ +MBEDTLS_DEPRECATED void mbedtls_ripemd160_process( + mbedtls_ripemd160_context *ctx, + const unsigned char data[64] ); + +#undef MBEDTLS_DEPRECATED +#endif /* !MBEDTLS_DEPRECATED_REMOVED */ + +/** + * \brief Output = RIPEMD-160( input buffer ) + * + * \param input buffer holding the data + * \param ilen length of the input data + * \param output RIPEMD-160 checksum result + * + * \return 0 if successful + */ +int mbedtls_ripemd160_ret( const unsigned char *input, + size_t ilen, + unsigned char output[20] ); + +#if !defined(MBEDTLS_DEPRECATED_REMOVED) +#if defined(MBEDTLS_DEPRECATED_WARNING) +#define MBEDTLS_DEPRECATED __attribute__((deprecated)) +#else +#define MBEDTLS_DEPRECATED +#endif +/** + * \brief Output = RIPEMD-160( input buffer ) + * + * \deprecated Superseded by mbedtls_ripemd160_ret() in 2.7.0 + * + * \param input buffer holding the data + * \param ilen length of the input data + * \param output RIPEMD-160 checksum result + */ +MBEDTLS_DEPRECATED void mbedtls_ripemd160( const unsigned char *input, + size_t ilen, + unsigned char output[20] ); + +#undef MBEDTLS_DEPRECATED +#endif /* !MBEDTLS_DEPRECATED_REMOVED */ + +#if defined(MBEDTLS_SELF_TEST) + +/** + * \brief Checkup routine + * + * \return 0 if successful, or 1 if the test failed + */ +int mbedtls_ripemd160_self_test( int verbose ); + +#endif /* MBEDTLS_SELF_TEST */ + +#ifdef __cplusplus +} +#endif + +#endif /* mbedtls_ripemd160.h */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/rsa.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/rsa.h new file mode 100644 index 0000000000000000000000000000000000000000..35bacd8763c6f6d0246bb939403d82fb638645bb --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/rsa.h @@ -0,0 +1,1274 @@ +/** + * \file rsa.h + * + * \brief This file provides an API for the RSA public-key cryptosystem. + * + * The RSA public-key cryptosystem is defined in Public-Key + * Cryptography Standards (PKCS) #1 v1.5: RSA Encryption + * and Public-Key Cryptography Standards (PKCS) #1 v2.1: + * RSA Cryptography Specifications. + * + */ +/* + * Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of Mbed TLS (https://tls.mbed.org) + */ +#ifndef MBEDTLS_RSA_H +#define MBEDTLS_RSA_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include "bignum.h" +#include "md.h" + +#if defined(MBEDTLS_THREADING_C) +#include "threading.h" +#endif + +/* + * RSA Error codes + */ +#define MBEDTLS_ERR_RSA_BAD_INPUT_DATA -0x4080 /**< Bad input parameters to function. */ +#define MBEDTLS_ERR_RSA_INVALID_PADDING -0x4100 /**< Input data contains invalid padding and is rejected. */ +#define MBEDTLS_ERR_RSA_KEY_GEN_FAILED -0x4180 /**< Something failed during generation of a key. */ +#define MBEDTLS_ERR_RSA_KEY_CHECK_FAILED -0x4200 /**< Key failed to pass the validity check of the library. */ +#define MBEDTLS_ERR_RSA_PUBLIC_FAILED -0x4280 /**< The public key operation failed. */ +#define MBEDTLS_ERR_RSA_PRIVATE_FAILED -0x4300 /**< The private key operation failed. */ +#define MBEDTLS_ERR_RSA_VERIFY_FAILED -0x4380 /**< The PKCS#1 verification failed. */ +#define MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE -0x4400 /**< The output buffer for decryption is not large enough. */ +#define MBEDTLS_ERR_RSA_RNG_FAILED -0x4480 /**< The random generator failed to generate non-zeros. */ + +/* MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION is deprecated and should not be used. + */ +#define MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION -0x4500 /**< The implementation does not offer the requested operation, for example, because of security violations or lack of functionality. */ + +/* MBEDTLS_ERR_RSA_HW_ACCEL_FAILED is deprecated and should not be used. */ +#define MBEDTLS_ERR_RSA_HW_ACCEL_FAILED -0x4580 /**< RSA hardware accelerator failed. */ + +/* + * RSA constants + */ +#define MBEDTLS_RSA_PUBLIC 0 /**< Request private key operation. */ +#define MBEDTLS_RSA_PRIVATE 1 /**< Request public key operation. */ + +#define MBEDTLS_RSA_PKCS_V15 0 /**< Use PKCS#1 v1.5 encoding. */ +#define MBEDTLS_RSA_PKCS_V21 1 /**< Use PKCS#1 v2.1 encoding. */ + +#define MBEDTLS_RSA_SIGN 1 /**< Identifier for RSA signature operations. */ +#define MBEDTLS_RSA_CRYPT 2 /**< Identifier for RSA encryption and decryption operations. */ + +#define MBEDTLS_RSA_SALT_LEN_ANY -1 + +/* + * The above constants may be used even if the RSA module is compile out, + * eg for alternative (PKCS#11) RSA implemenations in the PK layers. + */ + +#ifdef __cplusplus +extern "C" { +#endif + +#if !defined(MBEDTLS_RSA_ALT) +// Regular implementation +// + +/** + * \brief The RSA context structure. + * + * \note Direct manipulation of the members of this structure + * is deprecated. All manipulation should instead be done through + * the public interface functions. + */ +typedef struct mbedtls_rsa_context +{ + int ver; /*!< Always 0.*/ + size_t len; /*!< The size of \p N in Bytes. */ + + mbedtls_mpi N; /*!< The public modulus. */ + mbedtls_mpi E; /*!< The public exponent. */ + + mbedtls_mpi D; /*!< The private exponent. */ + mbedtls_mpi P; /*!< The first prime factor. */ + mbedtls_mpi Q; /*!< The second prime factor. */ + + mbedtls_mpi DP; /*!< D % (P - 1). */ + mbedtls_mpi DQ; /*!< D % (Q - 1). */ + mbedtls_mpi QP; /*!< 1 / (Q % P). */ + + mbedtls_mpi RN; /*!< cached R^2 mod N. */ + + mbedtls_mpi RP; /*!< cached R^2 mod P. */ + mbedtls_mpi RQ; /*!< cached R^2 mod Q. */ + + mbedtls_mpi Vi; /*!< The cached blinding value. */ + mbedtls_mpi Vf; /*!< The cached un-blinding value. */ + + int padding; /*!< Selects padding mode: + #MBEDTLS_RSA_PKCS_V15 for 1.5 padding and + #MBEDTLS_RSA_PKCS_V21 for OAEP or PSS. */ + int hash_id; /*!< Hash identifier of mbedtls_md_type_t type, + as specified in md.h for use in the MGF + mask generating function used in the + EME-OAEP and EMSA-PSS encodings. */ +#if defined(MBEDTLS_THREADING_C) + mbedtls_threading_mutex_t mutex; /*!< Thread-safety mutex. */ +#endif +} +mbedtls_rsa_context; + +#else /* MBEDTLS_RSA_ALT */ +#include "rsa_alt.h" +#endif /* MBEDTLS_RSA_ALT */ + +/** + * \brief This function initializes an RSA context. + * + * \note Set padding to #MBEDTLS_RSA_PKCS_V21 for the RSAES-OAEP + * encryption scheme and the RSASSA-PSS signature scheme. + * + * \note The \p hash_id parameter is ignored when using + * #MBEDTLS_RSA_PKCS_V15 padding. + * + * \note The choice of padding mode is strictly enforced for private key + * operations, since there might be security concerns in + * mixing padding modes. For public key operations it is + * a default value, which can be overridden by calling specific + * \c rsa_rsaes_xxx or \c rsa_rsassa_xxx functions. + * + * \note The hash selected in \p hash_id is always used for OEAP + * encryption. For PSS signatures, it is always used for + * making signatures, but can be overridden for verifying them. + * If set to #MBEDTLS_MD_NONE, it is always overridden. + * + * \param ctx The RSA context to initialize. This must not be \c NULL. + * \param padding The padding mode to use. This must be either + * #MBEDTLS_RSA_PKCS_V15 or #MBEDTLS_RSA_PKCS_V21. + * \param hash_id The hash identifier of ::mbedtls_md_type_t type, if + * \p padding is #MBEDTLS_RSA_PKCS_V21. It is unused + * otherwise. + */ +void mbedtls_rsa_init( mbedtls_rsa_context *ctx, + int padding, + int hash_id ); + +/** + * \brief This function imports a set of core parameters into an + * RSA context. + * + * \note This function can be called multiple times for successive + * imports, if the parameters are not simultaneously present. + * + * Any sequence of calls to this function should be followed + * by a call to mbedtls_rsa_complete(), which checks and + * completes the provided information to a ready-for-use + * public or private RSA key. + * + * \note See mbedtls_rsa_complete() for more information on which + * parameters are necessary to set up a private or public + * RSA key. + * + * \note The imported parameters are copied and need not be preserved + * for the lifetime of the RSA context being set up. + * + * \param ctx The initialized RSA context to store the parameters in. + * \param N The RSA modulus. This may be \c NULL. + * \param P The first prime factor of \p N. This may be \c NULL. + * \param Q The second prime factor of \p N. This may be \c NULL. + * \param D The private exponent. This may be \c NULL. + * \param E The public exponent. This may be \c NULL. + * + * \return \c 0 on success. + * \return A non-zero error code on failure. + */ +int mbedtls_rsa_import( mbedtls_rsa_context *ctx, + const mbedtls_mpi *N, + const mbedtls_mpi *P, const mbedtls_mpi *Q, + const mbedtls_mpi *D, const mbedtls_mpi *E ); + +/** + * \brief This function imports core RSA parameters, in raw big-endian + * binary format, into an RSA context. + * + * \note This function can be called multiple times for successive + * imports, if the parameters are not simultaneously present. + * + * Any sequence of calls to this function should be followed + * by a call to mbedtls_rsa_complete(), which checks and + * completes the provided information to a ready-for-use + * public or private RSA key. + * + * \note See mbedtls_rsa_complete() for more information on which + * parameters are necessary to set up a private or public + * RSA key. + * + * \note The imported parameters are copied and need not be preserved + * for the lifetime of the RSA context being set up. + * + * \param ctx The initialized RSA context to store the parameters in. + * \param N The RSA modulus. This may be \c NULL. + * \param N_len The Byte length of \p N; it is ignored if \p N == NULL. + * \param P The first prime factor of \p N. This may be \c NULL. + * \param P_len The Byte length of \p P; it ns ignored if \p P == NULL. + * \param Q The second prime factor of \p N. This may be \c NULL. + * \param Q_len The Byte length of \p Q; it is ignored if \p Q == NULL. + * \param D The private exponent. This may be \c NULL. + * \param D_len The Byte length of \p D; it is ignored if \p D == NULL. + * \param E The public exponent. This may be \c NULL. + * \param E_len The Byte length of \p E; it is ignored if \p E == NULL. + * + * \return \c 0 on success. + * \return A non-zero error code on failure. + */ +int mbedtls_rsa_import_raw( mbedtls_rsa_context *ctx, + unsigned char const *N, size_t N_len, + unsigned char const *P, size_t P_len, + unsigned char const *Q, size_t Q_len, + unsigned char const *D, size_t D_len, + unsigned char const *E, size_t E_len ); + +/** + * \brief This function completes an RSA context from + * a set of imported core parameters. + * + * To setup an RSA public key, precisely \p N and \p E + * must have been imported. + * + * To setup an RSA private key, sufficient information must + * be present for the other parameters to be derivable. + * + * The default implementation supports the following: + *
                            • Derive \p P, \p Q from \p N, \p D, \p E.
                            • + *
                            • Derive \p N, \p D from \p P, \p Q, \p E.
                            + * Alternative implementations need not support these. + * + * If this function runs successfully, it guarantees that + * the RSA context can be used for RSA operations without + * the risk of failure or crash. + * + * \warning This function need not perform consistency checks + * for the imported parameters. In particular, parameters that + * are not needed by the implementation might be silently + * discarded and left unchecked. To check the consistency + * of the key material, see mbedtls_rsa_check_privkey(). + * + * \param ctx The initialized RSA context holding imported parameters. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_RSA_BAD_INPUT_DATA if the attempted derivations + * failed. + * + */ +int mbedtls_rsa_complete( mbedtls_rsa_context *ctx ); + +/** + * \brief This function exports the core parameters of an RSA key. + * + * If this function runs successfully, the non-NULL buffers + * pointed to by \p N, \p P, \p Q, \p D, and \p E are fully + * written, with additional unused space filled leading by + * zero Bytes. + * + * Possible reasons for returning + * #MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED:
                              + *
                            • An alternative RSA implementation is in use, which + * stores the key externally, and either cannot or should + * not export it into RAM.
                            • + *
                            • A SW or HW implementation might not support a certain + * deduction. For example, \p P, \p Q from \p N, \p D, + * and \p E if the former are not part of the + * implementation.
                            + * + * If the function fails due to an unsupported operation, + * the RSA context stays intact and remains usable. + * + * \param ctx The initialized RSA context. + * \param N The MPI to hold the RSA modulus. + * This may be \c NULL if this field need not be exported. + * \param P The MPI to hold the first prime factor of \p N. + * This may be \c NULL if this field need not be exported. + * \param Q The MPI to hold the second prime factor of \p N. + * This may be \c NULL if this field need not be exported. + * \param D The MPI to hold the private exponent. + * This may be \c NULL if this field need not be exported. + * \param E The MPI to hold the public exponent. + * This may be \c NULL if this field need not be exported. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED if exporting the + * requested parameters cannot be done due to missing + * functionality or because of security policies. + * \return A non-zero return code on any other failure. + * + */ +int mbedtls_rsa_export( const mbedtls_rsa_context *ctx, + mbedtls_mpi *N, mbedtls_mpi *P, mbedtls_mpi *Q, + mbedtls_mpi *D, mbedtls_mpi *E ); + +/** + * \brief This function exports core parameters of an RSA key + * in raw big-endian binary format. + * + * If this function runs successfully, the non-NULL buffers + * pointed to by \p N, \p P, \p Q, \p D, and \p E are fully + * written, with additional unused space filled leading by + * zero Bytes. + * + * Possible reasons for returning + * #MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED:
                              + *
                            • An alternative RSA implementation is in use, which + * stores the key externally, and either cannot or should + * not export it into RAM.
                            • + *
                            • A SW or HW implementation might not support a certain + * deduction. For example, \p P, \p Q from \p N, \p D, + * and \p E if the former are not part of the + * implementation.
                            + * If the function fails due to an unsupported operation, + * the RSA context stays intact and remains usable. + * + * \note The length parameters are ignored if the corresponding + * buffer pointers are NULL. + * + * \param ctx The initialized RSA context. + * \param N The Byte array to store the RSA modulus, + * or \c NULL if this field need not be exported. + * \param N_len The size of the buffer for the modulus. + * \param P The Byte array to hold the first prime factor of \p N, + * or \c NULL if this field need not be exported. + * \param P_len The size of the buffer for the first prime factor. + * \param Q The Byte array to hold the second prime factor of \p N, + * or \c NULL if this field need not be exported. + * \param Q_len The size of the buffer for the second prime factor. + * \param D The Byte array to hold the private exponent, + * or \c NULL if this field need not be exported. + * \param D_len The size of the buffer for the private exponent. + * \param E The Byte array to hold the public exponent, + * or \c NULL if this field need not be exported. + * \param E_len The size of the buffer for the public exponent. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED if exporting the + * requested parameters cannot be done due to missing + * functionality or because of security policies. + * \return A non-zero return code on any other failure. + */ +int mbedtls_rsa_export_raw( const mbedtls_rsa_context *ctx, + unsigned char *N, size_t N_len, + unsigned char *P, size_t P_len, + unsigned char *Q, size_t Q_len, + unsigned char *D, size_t D_len, + unsigned char *E, size_t E_len ); + +/** + * \brief This function exports CRT parameters of a private RSA key. + * + * \note Alternative RSA implementations not using CRT-parameters + * internally can implement this function based on + * mbedtls_rsa_deduce_opt(). + * + * \param ctx The initialized RSA context. + * \param DP The MPI to hold \c D modulo `P-1`, + * or \c NULL if it need not be exported. + * \param DQ The MPI to hold \c D modulo `Q-1`, + * or \c NULL if it need not be exported. + * \param QP The MPI to hold modular inverse of \c Q modulo \c P, + * or \c NULL if it need not be exported. + * + * \return \c 0 on success. + * \return A non-zero error code on failure. + * + */ +int mbedtls_rsa_export_crt( const mbedtls_rsa_context *ctx, + mbedtls_mpi *DP, mbedtls_mpi *DQ, mbedtls_mpi *QP ); + +/** + * \brief This function sets padding for an already initialized RSA + * context. See mbedtls_rsa_init() for details. + * + * \param ctx The initialized RSA context to be configured. + * \param padding The padding mode to use. This must be either + * #MBEDTLS_RSA_PKCS_V15 or #MBEDTLS_RSA_PKCS_V21. + * \param hash_id The #MBEDTLS_RSA_PKCS_V21 hash identifier. + */ +void mbedtls_rsa_set_padding( mbedtls_rsa_context *ctx, int padding, + int hash_id ); + +/** + * \brief This function retrieves the length of RSA modulus in Bytes. + * + * \param ctx The initialized RSA context. + * + * \return The length of the RSA modulus in Bytes. + * + */ +size_t mbedtls_rsa_get_len( const mbedtls_rsa_context *ctx ); + +/** + * \brief This function generates an RSA keypair. + * + * \note mbedtls_rsa_init() must be called before this function, + * to set up the RSA context. + * + * \param ctx The initialized RSA context used to hold the key. + * \param f_rng The RNG function to be used for key generation. + * This must not be \c NULL. + * \param p_rng The RNG context to be passed to \p f_rng. + * This may be \c NULL if \p f_rng doesn't need a context. + * \param nbits The size of the public key in bits. + * \param exponent The public exponent to use. For example, \c 65537. + * This must be odd and greater than \c 1. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. + */ +int mbedtls_rsa_gen_key( mbedtls_rsa_context *ctx, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng, + unsigned int nbits, int exponent ); + +/** + * \brief This function checks if a context contains at least an RSA + * public key. + * + * If the function runs successfully, it is guaranteed that + * enough information is present to perform an RSA public key + * operation using mbedtls_rsa_public(). + * + * \param ctx The initialized RSA context to check. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. + * + */ +int mbedtls_rsa_check_pubkey( const mbedtls_rsa_context *ctx ); + +/** + * \brief This function checks if a context contains an RSA private key + * and perform basic consistency checks. + * + * \note The consistency checks performed by this function not only + * ensure that mbedtls_rsa_private() can be called successfully + * on the given context, but that the various parameters are + * mutually consistent with high probability, in the sense that + * mbedtls_rsa_public() and mbedtls_rsa_private() are inverses. + * + * \warning This function should catch accidental misconfigurations + * like swapping of parameters, but it cannot establish full + * trust in neither the quality nor the consistency of the key + * material that was used to setup the given RSA context: + *
                            • Consistency: Imported parameters that are irrelevant + * for the implementation might be silently dropped. If dropped, + * the current function does not have access to them, + * and therefore cannot check them. See mbedtls_rsa_complete(). + * If you want to check the consistency of the entire + * content of an PKCS1-encoded RSA private key, for example, you + * should use mbedtls_rsa_validate_params() before setting + * up the RSA context. + * Additionally, if the implementation performs empirical checks, + * these checks substantiate but do not guarantee consistency.
                            • + *
                            • Quality: This function is not expected to perform + * extended quality assessments like checking that the prime + * factors are safe. Additionally, it is the responsibility of the + * user to ensure the trustworthiness of the source of his RSA + * parameters, which goes beyond what is effectively checkable + * by the library.
                            + * + * \param ctx The initialized RSA context to check. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. + */ +int mbedtls_rsa_check_privkey( const mbedtls_rsa_context *ctx ); + +/** + * \brief This function checks a public-private RSA key pair. + * + * It checks each of the contexts, and makes sure they match. + * + * \param pub The initialized RSA context holding the public key. + * \param prv The initialized RSA context holding the private key. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. + */ +int mbedtls_rsa_check_pub_priv( const mbedtls_rsa_context *pub, + const mbedtls_rsa_context *prv ); + +/** + * \brief This function performs an RSA public key operation. + * + * \param ctx The initialized RSA context to use. + * \param input The input buffer. This must be a readable buffer + * of length \c ctx->len Bytes. For example, \c 256 Bytes + * for an 2048-bit RSA modulus. + * \param output The output buffer. This must be a writable buffer + * of length \c ctx->len Bytes. For example, \c 256 Bytes + * for an 2048-bit RSA modulus. + * + * \note This function does not handle message padding. + * + * \note Make sure to set \p input[0] = 0 or ensure that + * input is smaller than \p N. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. + */ +int mbedtls_rsa_public( mbedtls_rsa_context *ctx, + const unsigned char *input, + unsigned char *output ); + +/** + * \brief This function performs an RSA private key operation. + * + * \note Blinding is used if and only if a PRNG is provided. + * + * \note If blinding is used, both the base of exponentation + * and the exponent are blinded, providing protection + * against some side-channel attacks. + * + * \warning It is deprecated and a security risk to not provide + * a PRNG here and thereby prevent the use of blinding. + * Future versions of the library may enforce the presence + * of a PRNG. + * + * \param ctx The initialized RSA context to use. + * \param f_rng The RNG function, used for blinding. It is discouraged + * and deprecated to pass \c NULL here, in which case + * blinding will be omitted. + * \param p_rng The RNG context to pass to \p f_rng. This may be \c NULL + * if \p f_rng is \c NULL or if \p f_rng doesn't need a context. + * \param input The input buffer. This must be a readable buffer + * of length \c ctx->len Bytes. For example, \c 256 Bytes + * for an 2048-bit RSA modulus. + * \param output The output buffer. This must be a writable buffer + * of length \c ctx->len Bytes. For example, \c 256 Bytes + * for an 2048-bit RSA modulus. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. + * + */ +int mbedtls_rsa_private( mbedtls_rsa_context *ctx, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng, + const unsigned char *input, + unsigned char *output ); + +/** + * \brief This function adds the message padding, then performs an RSA + * operation. + * + * It is the generic wrapper for performing a PKCS#1 encryption + * operation using the \p mode from the context. + * + * \deprecated It is deprecated and discouraged to call this function + * in #MBEDTLS_RSA_PRIVATE mode. Future versions of the library + * are likely to remove the \p mode argument and have it + * implicitly set to #MBEDTLS_RSA_PUBLIC. + * + * \note Alternative implementations of RSA need not support + * mode being set to #MBEDTLS_RSA_PRIVATE and might instead + * return #MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED. + * + * \param ctx The initialized RSA context to use. + * \param f_rng The RNG to use. It is mandatory for PKCS#1 v2.1 padding + * encoding, and for PKCS#1 v1.5 padding encoding when used + * with \p mode set to #MBEDTLS_RSA_PUBLIC. For PKCS#1 v1.5 + * padding encoding and \p mode set to #MBEDTLS_RSA_PRIVATE, + * it is used for blinding and should be provided in this + * case; see mbedtls_rsa_private() for more. + * \param p_rng The RNG context to be passed to \p f_rng. May be + * \c NULL if \p f_rng is \c NULL or if \p f_rng doesn't + * need a context argument. + * \param mode The mode of operation. This must be either + * #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE (deprecated). + * \param ilen The length of the plaintext in Bytes. + * \param input The input data to encrypt. This must be a readable + * buffer of size \p ilen Bytes. This must not be \c NULL. + * \param output The output buffer. This must be a writable buffer + * of length \c ctx->len Bytes. For example, \c 256 Bytes + * for an 2048-bit RSA modulus. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. + */ +int mbedtls_rsa_pkcs1_encrypt( mbedtls_rsa_context *ctx, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng, + int mode, size_t ilen, + const unsigned char *input, + unsigned char *output ); + +/** + * \brief This function performs a PKCS#1 v1.5 encryption operation + * (RSAES-PKCS1-v1_5-ENCRYPT). + * + * \deprecated It is deprecated and discouraged to call this function + * in #MBEDTLS_RSA_PRIVATE mode. Future versions of the library + * are likely to remove the \p mode argument and have it + * implicitly set to #MBEDTLS_RSA_PUBLIC. + * + * \note Alternative implementations of RSA need not support + * mode being set to #MBEDTLS_RSA_PRIVATE and might instead + * return #MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED. + * + * \param ctx The initialized RSA context to use. + * \param f_rng The RNG function to use. It is needed for padding generation + * if \p mode is #MBEDTLS_RSA_PUBLIC. If \p mode is + * #MBEDTLS_RSA_PRIVATE (discouraged), it is used for + * blinding and should be provided; see mbedtls_rsa_private(). + * \param p_rng The RNG context to be passed to \p f_rng. This may + * be \c NULL if \p f_rng is \c NULL or if \p f_rng + * doesn't need a context argument. + * \param mode The mode of operation. This must be either + * #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE (deprecated). + * \param ilen The length of the plaintext in Bytes. + * \param input The input data to encrypt. This must be a readable + * buffer of size \p ilen Bytes. This must not be \c NULL. + * \param output The output buffer. This must be a writable buffer + * of length \c ctx->len Bytes. For example, \c 256 Bytes + * for an 2048-bit RSA modulus. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. + */ +int mbedtls_rsa_rsaes_pkcs1_v15_encrypt( mbedtls_rsa_context *ctx, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng, + int mode, size_t ilen, + const unsigned char *input, + unsigned char *output ); + +/** + * \brief This function performs a PKCS#1 v2.1 OAEP encryption + * operation (RSAES-OAEP-ENCRYPT). + * + * \note The output buffer must be as large as the size + * of ctx->N. For example, 128 Bytes if RSA-1024 is used. + * + * \deprecated It is deprecated and discouraged to call this function + * in #MBEDTLS_RSA_PRIVATE mode. Future versions of the library + * are likely to remove the \p mode argument and have it + * implicitly set to #MBEDTLS_RSA_PUBLIC. + * + * \note Alternative implementations of RSA need not support + * mode being set to #MBEDTLS_RSA_PRIVATE and might instead + * return #MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED. + * + * \param ctx The initnialized RSA context to use. + * \param f_rng The RNG function to use. This is needed for padding + * generation and must be provided. + * \param p_rng The RNG context to be passed to \p f_rng. This may + * be \c NULL if \p f_rng doesn't need a context argument. + * \param mode The mode of operation. This must be either + * #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE (deprecated). + * \param label The buffer holding the custom label to use. + * This must be a readable buffer of length \p label_len + * Bytes. It may be \c NULL if \p label_len is \c 0. + * \param label_len The length of the label in Bytes. + * \param ilen The length of the plaintext buffer \p input in Bytes. + * \param input The input data to encrypt. This must be a readable + * buffer of size \p ilen Bytes. This must not be \c NULL. + * \param output The output buffer. This must be a writable buffer + * of length \c ctx->len Bytes. For example, \c 256 Bytes + * for an 2048-bit RSA modulus. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. + */ +int mbedtls_rsa_rsaes_oaep_encrypt( mbedtls_rsa_context *ctx, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng, + int mode, + const unsigned char *label, size_t label_len, + size_t ilen, + const unsigned char *input, + unsigned char *output ); + +/** + * \brief This function performs an RSA operation, then removes the + * message padding. + * + * It is the generic wrapper for performing a PKCS#1 decryption + * operation using the \p mode from the context. + * + * \note The output buffer length \c output_max_len should be + * as large as the size \p ctx->len of \p ctx->N (for example, + * 128 Bytes if RSA-1024 is used) to be able to hold an + * arbitrary decrypted message. If it is not large enough to + * hold the decryption of the particular ciphertext provided, + * the function returns \c MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE. + * + * \deprecated It is deprecated and discouraged to call this function + * in #MBEDTLS_RSA_PUBLIC mode. Future versions of the library + * are likely to remove the \p mode argument and have it + * implicitly set to #MBEDTLS_RSA_PRIVATE. + * + * \note Alternative implementations of RSA need not support + * mode being set to #MBEDTLS_RSA_PUBLIC and might instead + * return #MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED. + * + * \param ctx The initialized RSA context to use. + * \param f_rng The RNG function. If \p mode is #MBEDTLS_RSA_PRIVATE, + * this is used for blinding and should be provided; see + * mbedtls_rsa_private() for more. If \p mode is + * #MBEDTLS_RSA_PUBLIC, it is ignored. + * \param p_rng The RNG context to be passed to \p f_rng. This may be + * \c NULL if \p f_rng is \c NULL or doesn't need a context. + * \param mode The mode of operation. This must be either + * #MBEDTLS_RSA_PRIVATE or #MBEDTLS_RSA_PUBLIC (deprecated). + * \param olen The address at which to store the length of + * the plaintext. This must not be \c NULL. + * \param input The ciphertext buffer. This must be a readable buffer + * of length \c ctx->len Bytes. For example, \c 256 Bytes + * for an 2048-bit RSA modulus. + * \param output The buffer used to hold the plaintext. This must + * be a writable buffer of length \p output_max_len Bytes. + * \param output_max_len The length in Bytes of the output buffer \p output. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. + */ +int mbedtls_rsa_pkcs1_decrypt( mbedtls_rsa_context *ctx, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng, + int mode, size_t *olen, + const unsigned char *input, + unsigned char *output, + size_t output_max_len ); + +/** + * \brief This function performs a PKCS#1 v1.5 decryption + * operation (RSAES-PKCS1-v1_5-DECRYPT). + * + * \note The output buffer length \c output_max_len should be + * as large as the size \p ctx->len of \p ctx->N, for example, + * 128 Bytes if RSA-1024 is used, to be able to hold an + * arbitrary decrypted message. If it is not large enough to + * hold the decryption of the particular ciphertext provided, + * the function returns #MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE. + * + * \deprecated It is deprecated and discouraged to call this function + * in #MBEDTLS_RSA_PUBLIC mode. Future versions of the library + * are likely to remove the \p mode argument and have it + * implicitly set to #MBEDTLS_RSA_PRIVATE. + * + * \note Alternative implementations of RSA need not support + * mode being set to #MBEDTLS_RSA_PUBLIC and might instead + * return #MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED. + * + * \param ctx The initialized RSA context to use. + * \param f_rng The RNG function. If \p mode is #MBEDTLS_RSA_PRIVATE, + * this is used for blinding and should be provided; see + * mbedtls_rsa_private() for more. If \p mode is + * #MBEDTLS_RSA_PUBLIC, it is ignored. + * \param p_rng The RNG context to be passed to \p f_rng. This may be + * \c NULL if \p f_rng is \c NULL or doesn't need a context. + * \param mode The mode of operation. This must be either + * #MBEDTLS_RSA_PRIVATE or #MBEDTLS_RSA_PUBLIC (deprecated). + * \param olen The address at which to store the length of + * the plaintext. This must not be \c NULL. + * \param input The ciphertext buffer. This must be a readable buffer + * of length \c ctx->len Bytes. For example, \c 256 Bytes + * for an 2048-bit RSA modulus. + * \param output The buffer used to hold the plaintext. This must + * be a writable buffer of length \p output_max_len Bytes. + * \param output_max_len The length in Bytes of the output buffer \p output. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. + * + */ +int mbedtls_rsa_rsaes_pkcs1_v15_decrypt( mbedtls_rsa_context *ctx, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng, + int mode, size_t *olen, + const unsigned char *input, + unsigned char *output, + size_t output_max_len ); + +/** + * \brief This function performs a PKCS#1 v2.1 OAEP decryption + * operation (RSAES-OAEP-DECRYPT). + * + * \note The output buffer length \c output_max_len should be + * as large as the size \p ctx->len of \p ctx->N, for + * example, 128 Bytes if RSA-1024 is used, to be able to + * hold an arbitrary decrypted message. If it is not + * large enough to hold the decryption of the particular + * ciphertext provided, the function returns + * #MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE. + * + * \deprecated It is deprecated and discouraged to call this function + * in #MBEDTLS_RSA_PUBLIC mode. Future versions of the library + * are likely to remove the \p mode argument and have it + * implicitly set to #MBEDTLS_RSA_PRIVATE. + * + * \note Alternative implementations of RSA need not support + * mode being set to #MBEDTLS_RSA_PUBLIC and might instead + * return #MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED. + * + * \param ctx The initialized RSA context to use. + * \param f_rng The RNG function. If \p mode is #MBEDTLS_RSA_PRIVATE, + * this is used for blinding and should be provided; see + * mbedtls_rsa_private() for more. If \p mode is + * #MBEDTLS_RSA_PUBLIC, it is ignored. + * \param p_rng The RNG context to be passed to \p f_rng. This may be + * \c NULL if \p f_rng is \c NULL or doesn't need a context. + * \param mode The mode of operation. This must be either + * #MBEDTLS_RSA_PRIVATE or #MBEDTLS_RSA_PUBLIC (deprecated). + * \param label The buffer holding the custom label to use. + * This must be a readable buffer of length \p label_len + * Bytes. It may be \c NULL if \p label_len is \c 0. + * \param label_len The length of the label in Bytes. + * \param olen The address at which to store the length of + * the plaintext. This must not be \c NULL. + * \param input The ciphertext buffer. This must be a readable buffer + * of length \c ctx->len Bytes. For example, \c 256 Bytes + * for an 2048-bit RSA modulus. + * \param output The buffer used to hold the plaintext. This must + * be a writable buffer of length \p output_max_len Bytes. + * \param output_max_len The length in Bytes of the output buffer \p output. + * + * \return \c 0 on success. + * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. + */ +int mbedtls_rsa_rsaes_oaep_decrypt( mbedtls_rsa_context *ctx, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng, + int mode, + const unsigned char *label, size_t label_len, + size_t *olen, + const unsigned char *input, + unsigned char *output, + size_t output_max_len ); + +/** + * \brief This function performs a private RSA operation to sign + * a message digest using PKCS#1. + * + * It is the generic wrapper for performing a PKCS#1 + * signature using the \p mode from the context. + * + * \note The \p sig buffer must be as large as the size + * of \p ctx->N. For example, 128 Bytes if RSA-1024 is used. + * + * \note For PKCS#1 v2.1 encoding, see comments on + * mbedtls_rsa_rsassa_pss_sign() for details on + * \p md_alg and \p hash_id. + * + * \deprecated It is deprecated and discouraged to call this function + * in #MBEDTLS_RSA_PUBLIC mode. Future versions of the library + * are likely to remove the \p mode argument and have it + * implicitly set to #MBEDTLS_RSA_PRIVATE. + * + * \note Alternative implementations of RSA need not support + * mode being set to #MBEDTLS_RSA_PUBLIC and might instead + * return #MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED. + * + * \param ctx The initialized RSA context to use. + * \param f_rng The RNG function to use. If the padding mode is PKCS#1 v2.1, + * this must be provided. If the padding mode is PKCS#1 v1.5 and + * \p mode is #MBEDTLS_RSA_PRIVATE, it is used for blinding + * and should be provided; see mbedtls_rsa_private() for more + * more. It is ignored otherwise. + * \param p_rng The RNG context to be passed to \p f_rng. This may be \c NULL + * if \p f_rng is \c NULL or doesn't need a context argument. + * \param mode The mode of operation. This must be either + * #MBEDTLS_RSA_PRIVATE or #MBEDTLS_RSA_PUBLIC (deprecated). + * \param md_alg The message-digest algorithm used to hash the original data. + * Use #MBEDTLS_MD_NONE for signing raw data. + * \param hashlen The length of the message digest. + * Ths is only used if \p md_alg is #MBEDTLS_MD_NONE. + * \param hash The buffer holding the message digest or raw data. + * If \p md_alg is #MBEDTLS_MD_NONE, this must be a readable + * buffer of length \p hashlen Bytes. If \p md_alg is not + * #MBEDTLS_MD_NONE, it must be a readable buffer of length + * the size of the hash corresponding to \p md_alg. + * \param sig The buffer to hold the signature. This must be a writable + * buffer of length \c ctx->len Bytes. For example, \c 256 Bytes + * for an 2048-bit RSA modulus. A buffer length of + * #MBEDTLS_MPI_MAX_SIZE is always safe. + * + * \return \c 0 if the signing operation was successful. + * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. + */ +int mbedtls_rsa_pkcs1_sign( mbedtls_rsa_context *ctx, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng, + int mode, + mbedtls_md_type_t md_alg, + unsigned int hashlen, + const unsigned char *hash, + unsigned char *sig ); + +/** + * \brief This function performs a PKCS#1 v1.5 signature + * operation (RSASSA-PKCS1-v1_5-SIGN). + * + * \deprecated It is deprecated and discouraged to call this function + * in #MBEDTLS_RSA_PUBLIC mode. Future versions of the library + * are likely to remove the \p mode argument and have it + * implicitly set to #MBEDTLS_RSA_PRIVATE. + * + * \note Alternative implementations of RSA need not support + * mode being set to #MBEDTLS_RSA_PUBLIC and might instead + * return #MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED. + * + * \param ctx The initialized RSA context to use. + * \param f_rng The RNG function. If \p mode is #MBEDTLS_RSA_PRIVATE, + * this is used for blinding and should be provided; see + * mbedtls_rsa_private() for more. If \p mode is + * #MBEDTLS_RSA_PUBLIC, it is ignored. + * \param p_rng The RNG context to be passed to \p f_rng. This may be \c NULL + * if \p f_rng is \c NULL or doesn't need a context argument. + * \param mode The mode of operation. This must be either + * #MBEDTLS_RSA_PRIVATE or #MBEDTLS_RSA_PUBLIC (deprecated). + * \param md_alg The message-digest algorithm used to hash the original data. + * Use #MBEDTLS_MD_NONE for signing raw data. + * \param hashlen The length of the message digest. + * Ths is only used if \p md_alg is #MBEDTLS_MD_NONE. + * \param hash The buffer holding the message digest or raw data. + * If \p md_alg is #MBEDTLS_MD_NONE, this must be a readable + * buffer of length \p hashlen Bytes. If \p md_alg is not + * #MBEDTLS_MD_NONE, it must be a readable buffer of length + * the size of the hash corresponding to \p md_alg. + * \param sig The buffer to hold the signature. This must be a writable + * buffer of length \c ctx->len Bytes. For example, \c 256 Bytes + * for an 2048-bit RSA modulus. A buffer length of + * #MBEDTLS_MPI_MAX_SIZE is always safe. + * + * \return \c 0 if the signing operation was successful. + * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. + */ +int mbedtls_rsa_rsassa_pkcs1_v15_sign( mbedtls_rsa_context *ctx, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng, + int mode, + mbedtls_md_type_t md_alg, + unsigned int hashlen, + const unsigned char *hash, + unsigned char *sig ); + +/** + * \brief This function performs a PKCS#1 v2.1 PSS signature + * operation (RSASSA-PSS-SIGN). + * + * \note The \p hash_id in the RSA context is the one used for the + * encoding. \p md_alg in the function call is the type of hash + * that is encoded. According to RFC-3447: Public-Key + * Cryptography Standards (PKCS) #1 v2.1: RSA Cryptography + * Specifications it is advised to keep both hashes the + * same. + * + * \note This function always uses the maximum possible salt size, + * up to the length of the payload hash. This choice of salt + * size complies with FIPS 186-4 §5.5 (e) and RFC 8017 (PKCS#1 + * v2.2) §9.1.1 step 3. Furthermore this function enforces a + * minimum salt size which is the hash size minus 2 bytes. If + * this minimum size is too large given the key size (the salt + * size, plus the hash size, plus 2 bytes must be no more than + * the key size in bytes), this function returns + * #MBEDTLS_ERR_RSA_BAD_INPUT_DATA. + * + * \deprecated It is deprecated and discouraged to call this function + * in #MBEDTLS_RSA_PUBLIC mode. Future versions of the library + * are likely to remove the \p mode argument and have it + * implicitly set to #MBEDTLS_RSA_PRIVATE. + * + * \note Alternative implementations of RSA need not support + * mode being set to #MBEDTLS_RSA_PUBLIC and might instead + * return #MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED. + * + * \param ctx The initialized RSA context to use. + * \param f_rng The RNG function. It must not be \c NULL. + * \param p_rng The RNG context to be passed to \p f_rng. This may be \c NULL + * if \p f_rng doesn't need a context argument. + * \param mode The mode of operation. This must be either + * #MBEDTLS_RSA_PRIVATE or #MBEDTLS_RSA_PUBLIC (deprecated). + * \param md_alg The message-digest algorithm used to hash the original data. + * Use #MBEDTLS_MD_NONE for signing raw data. + * \param hashlen The length of the message digest. + * Ths is only used if \p md_alg is #MBEDTLS_MD_NONE. + * \param hash The buffer holding the message digest or raw data. + * If \p md_alg is #MBEDTLS_MD_NONE, this must be a readable + * buffer of length \p hashlen Bytes. If \p md_alg is not + * #MBEDTLS_MD_NONE, it must be a readable buffer of length + * the size of the hash corresponding to \p md_alg. + * \param sig The buffer to hold the signature. This must be a writable + * buffer of length \c ctx->len Bytes. For example, \c 256 Bytes + * for an 2048-bit RSA modulus. A buffer length of + * #MBEDTLS_MPI_MAX_SIZE is always safe. + * + * \return \c 0 if the signing operation was successful. + * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. + */ +int mbedtls_rsa_rsassa_pss_sign( mbedtls_rsa_context *ctx, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng, + int mode, + mbedtls_md_type_t md_alg, + unsigned int hashlen, + const unsigned char *hash, + unsigned char *sig ); + +/** + * \brief This function performs a public RSA operation and checks + * the message digest. + * + * This is the generic wrapper for performing a PKCS#1 + * verification using the mode from the context. + * + * \note For PKCS#1 v2.1 encoding, see comments on + * mbedtls_rsa_rsassa_pss_verify() about \p md_alg and + * \p hash_id. + * + * \deprecated It is deprecated and discouraged to call this function + * in #MBEDTLS_RSA_PRIVATE mode. Future versions of the library + * are likely to remove the \p mode argument and have it + * set to #MBEDTLS_RSA_PUBLIC. + * + * \note Alternative implementations of RSA need not support + * mode being set to #MBEDTLS_RSA_PRIVATE and might instead + * return #MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED. + * + * \param ctx The initialized RSA public key context to use. + * \param f_rng The RNG function to use. If \p mode is #MBEDTLS_RSA_PRIVATE, + * this is used for blinding and should be provided; see + * mbedtls_rsa_private() for more. Otherwise, it is ignored. + * \param p_rng The RNG context to be passed to \p f_rng. This may be + * \c NULL if \p f_rng is \c NULL or doesn't need a context. + * \param mode The mode of operation. This must be either + * #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE (deprecated). + * \param md_alg The message-digest algorithm used to hash the original data. + * Use #MBEDTLS_MD_NONE for signing raw data. + * \param hashlen The length of the message digest. + * This is only used if \p md_alg is #MBEDTLS_MD_NONE. + * \param hash The buffer holding the message digest or raw data. + * If \p md_alg is #MBEDTLS_MD_NONE, this must be a readable + * buffer of length \p hashlen Bytes. If \p md_alg is not + * #MBEDTLS_MD_NONE, it must be a readable buffer of length + * the size of the hash corresponding to \p md_alg. + * \param sig The buffer holding the signature. This must be a readable + * buffer of length \c ctx->len Bytes. For example, \c 256 Bytes + * for an 2048-bit RSA modulus. + * + * \return \c 0 if the verify operation was successful. + * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. + */ +int mbedtls_rsa_pkcs1_verify( mbedtls_rsa_context *ctx, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng, + int mode, + mbedtls_md_type_t md_alg, + unsigned int hashlen, + const unsigned char *hash, + const unsigned char *sig ); + +/** + * \brief This function performs a PKCS#1 v1.5 verification + * operation (RSASSA-PKCS1-v1_5-VERIFY). + * + * \deprecated It is deprecated and discouraged to call this function + * in #MBEDTLS_RSA_PRIVATE mode. Future versions of the library + * are likely to remove the \p mode argument and have it + * set to #MBEDTLS_RSA_PUBLIC. + * + * \note Alternative implementations of RSA need not support + * mode being set to #MBEDTLS_RSA_PRIVATE and might instead + * return #MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED. + * + * \param ctx The initialized RSA public key context to use. + * \param f_rng The RNG function to use. If \p mode is #MBEDTLS_RSA_PRIVATE, + * this is used for blinding and should be provided; see + * mbedtls_rsa_private() for more. Otherwise, it is ignored. + * \param p_rng The RNG context to be passed to \p f_rng. This may be + * \c NULL if \p f_rng is \c NULL or doesn't need a context. + * \param mode The mode of operation. This must be either + * #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE (deprecated). + * \param md_alg The message-digest algorithm used to hash the original data. + * Use #MBEDTLS_MD_NONE for signing raw data. + * \param hashlen The length of the message digest. + * This is only used if \p md_alg is #MBEDTLS_MD_NONE. + * \param hash The buffer holding the message digest or raw data. + * If \p md_alg is #MBEDTLS_MD_NONE, this must be a readable + * buffer of length \p hashlen Bytes. If \p md_alg is not + * #MBEDTLS_MD_NONE, it must be a readable buffer of length + * the size of the hash corresponding to \p md_alg. + * \param sig The buffer holding the signature. This must be a readable + * buffer of length \c ctx->len Bytes. For example, \c 256 Bytes + * for an 2048-bit RSA modulus. + * + * \return \c 0 if the verify operation was successful. + * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. + */ +int mbedtls_rsa_rsassa_pkcs1_v15_verify( mbedtls_rsa_context *ctx, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng, + int mode, + mbedtls_md_type_t md_alg, + unsigned int hashlen, + const unsigned char *hash, + const unsigned char *sig ); + +/** + * \brief This function performs a PKCS#1 v2.1 PSS verification + * operation (RSASSA-PSS-VERIFY). + * + * The hash function for the MGF mask generating function + * is that specified in the RSA context. + * + * \note The \p hash_id in the RSA context is the one used for the + * verification. \p md_alg in the function call is the type of + * hash that is verified. According to RFC-3447: Public-Key + * Cryptography Standards (PKCS) #1 v2.1: RSA Cryptography + * Specifications it is advised to keep both hashes the + * same. If \p hash_id in the RSA context is unset, + * the \p md_alg from the function call is used. + * + * \deprecated It is deprecated and discouraged to call this function + * in #MBEDTLS_RSA_PRIVATE mode. Future versions of the library + * are likely to remove the \p mode argument and have it + * implicitly set to #MBEDTLS_RSA_PUBLIC. + * + * \note Alternative implementations of RSA need not support + * mode being set to #MBEDTLS_RSA_PRIVATE and might instead + * return #MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED. + * + * \param ctx The initialized RSA public key context to use. + * \param f_rng The RNG function to use. If \p mode is #MBEDTLS_RSA_PRIVATE, + * this is used for blinding and should be provided; see + * mbedtls_rsa_private() for more. Otherwise, it is ignored. + * \param p_rng The RNG context to be passed to \p f_rng. This may be + * \c NULL if \p f_rng is \c NULL or doesn't need a context. + * \param mode The mode of operation. This must be either + * #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE (deprecated). + * \param md_alg The message-digest algorithm used to hash the original data. + * Use #MBEDTLS_MD_NONE for signing raw data. + * \param hashlen The length of the message digest. + * This is only used if \p md_alg is #MBEDTLS_MD_NONE. + * \param hash The buffer holding the message digest or raw data. + * If \p md_alg is #MBEDTLS_MD_NONE, this must be a readable + * buffer of length \p hashlen Bytes. If \p md_alg is not + * #MBEDTLS_MD_NONE, it must be a readable buffer of length + * the size of the hash corresponding to \p md_alg. + * \param sig The buffer holding the signature. This must be a readable + * buffer of length \c ctx->len Bytes. For example, \c 256 Bytes + * for an 2048-bit RSA modulus. + * + * \return \c 0 if the verify operation was successful. + * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. + */ +int mbedtls_rsa_rsassa_pss_verify( mbedtls_rsa_context *ctx, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng, + int mode, + mbedtls_md_type_t md_alg, + unsigned int hashlen, + const unsigned char *hash, + const unsigned char *sig ); + +/** + * \brief This function performs a PKCS#1 v2.1 PSS verification + * operation (RSASSA-PSS-VERIFY). + * + * The hash function for the MGF mask generating function + * is that specified in \p mgf1_hash_id. + * + * \note The \p sig buffer must be as large as the size + * of \p ctx->N. For example, 128 Bytes if RSA-1024 is used. + * + * \note The \p hash_id in the RSA context is ignored. + * + * \param ctx The initialized RSA public key context to use. + * \param f_rng The RNG function to use. If \p mode is #MBEDTLS_RSA_PRIVATE, + * this is used for blinding and should be provided; see + * mbedtls_rsa_private() for more. Otherwise, it is ignored. + * \param p_rng The RNG context to be passed to \p f_rng. This may be + * \c NULL if \p f_rng is \c NULL or doesn't need a context. + * \param mode The mode of operation. This must be either + * #MBEDTLS_RSA_PUBLIC or #MBEDTLS_RSA_PRIVATE. + * \param md_alg The message-digest algorithm used to hash the original data. + * Use #MBEDTLS_MD_NONE for signing raw data. + * \param hashlen The length of the message digest. + * This is only used if \p md_alg is #MBEDTLS_MD_NONE. + * \param hash The buffer holding the message digest or raw data. + * If \p md_alg is #MBEDTLS_MD_NONE, this must be a readable + * buffer of length \p hashlen Bytes. If \p md_alg is not + * #MBEDTLS_MD_NONE, it must be a readable buffer of length + * the size of the hash corresponding to \p md_alg. + * \param mgf1_hash_id The message digest used for mask generation. + * \param expected_salt_len The length of the salt used in padding. Use + * #MBEDTLS_RSA_SALT_LEN_ANY to accept any salt length. + * \param sig The buffer holding the signature. This must be a readable + * buffer of length \c ctx->len Bytes. For example, \c 256 Bytes + * for an 2048-bit RSA modulus. + * + * \return \c 0 if the verify operation was successful. + * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. + */ +int mbedtls_rsa_rsassa_pss_verify_ext( mbedtls_rsa_context *ctx, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng, + int mode, + mbedtls_md_type_t md_alg, + unsigned int hashlen, + const unsigned char *hash, + mbedtls_md_type_t mgf1_hash_id, + int expected_salt_len, + const unsigned char *sig ); + +/** + * \brief This function copies the components of an RSA context. + * + * \param dst The destination context. This must be initialized. + * \param src The source context. This must be initialized. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory allocation failure. + */ +int mbedtls_rsa_copy( mbedtls_rsa_context *dst, const mbedtls_rsa_context *src ); + +/** + * \brief This function frees the components of an RSA key. + * + * \param ctx The RSA context to free. May be \c NULL, in which case + * this function is a no-op. If it is not \c NULL, it must + * point to an initialized RSA context. + */ +void mbedtls_rsa_free( mbedtls_rsa_context *ctx ); + +#if defined(MBEDTLS_SELF_TEST) + +/** + * \brief The RSA checkup routine. + * + * \return \c 0 on success. + * \return \c 1 on failure. + */ +int mbedtls_rsa_self_test( int verbose ); + +#endif /* MBEDTLS_SELF_TEST */ + +#ifdef __cplusplus +} +#endif + +#endif /* rsa.h */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/rsa_internal.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/rsa_internal.h new file mode 100644 index 0000000000000000000000000000000000000000..53abd3c5b0eeeafdfe73bd95174bd7a45929a0d0 --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/rsa_internal.h @@ -0,0 +1,226 @@ +/** + * \file rsa_internal.h + * + * \brief Context-independent RSA helper functions + * + * This module declares some RSA-related helper functions useful when + * implementing the RSA interface. These functions are provided in a separate + * compilation unit in order to make it easy for designers of alternative RSA + * implementations to use them in their own code, as it is conceived that the + * functionality they provide will be necessary for most complete + * implementations. + * + * End-users of Mbed TLS who are not providing their own alternative RSA + * implementations should not use these functions directly, and should instead + * use only the functions declared in rsa.h. + * + * The interface provided by this module will be maintained through LTS (Long + * Term Support) branches of Mbed TLS, but may otherwise be subject to change, + * and must be considered an internal interface of the library. + * + * There are two classes of helper functions: + * + * (1) Parameter-generating helpers. These are: + * - mbedtls_rsa_deduce_primes + * - mbedtls_rsa_deduce_private_exponent + * - mbedtls_rsa_deduce_crt + * Each of these functions takes a set of core RSA parameters and + * generates some other, or CRT related parameters. + * + * (2) Parameter-checking helpers. These are: + * - mbedtls_rsa_validate_params + * - mbedtls_rsa_validate_crt + * They take a set of core or CRT related RSA parameters and check their + * validity. + * + */ +/* + * Copyright (C) 2006-2017, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + * + */ + +#ifndef MBEDTLS_RSA_INTERNAL_H +#define MBEDTLS_RSA_INTERNAL_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include "bignum.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/** + * \brief Compute RSA prime moduli P, Q from public modulus N=PQ + * and a pair of private and public key. + * + * \note This is a 'static' helper function not operating on + * an RSA context. Alternative implementations need not + * overwrite it. + * + * \param N RSA modulus N = PQ, with P, Q to be found + * \param E RSA public exponent + * \param D RSA private exponent + * \param P Pointer to MPI holding first prime factor of N on success + * \param Q Pointer to MPI holding second prime factor of N on success + * + * \return + * - 0 if successful. In this case, P and Q constitute a + * factorization of N. + * - A non-zero error code otherwise. + * + * \note It is neither checked that P, Q are prime nor that + * D, E are modular inverses wrt. P-1 and Q-1. For that, + * use the helper function \c mbedtls_rsa_validate_params. + * + */ +int mbedtls_rsa_deduce_primes( mbedtls_mpi const *N, mbedtls_mpi const *E, + mbedtls_mpi const *D, + mbedtls_mpi *P, mbedtls_mpi *Q ); + +/** + * \brief Compute RSA private exponent from + * prime moduli and public key. + * + * \note This is a 'static' helper function not operating on + * an RSA context. Alternative implementations need not + * overwrite it. + * + * \param P First prime factor of RSA modulus + * \param Q Second prime factor of RSA modulus + * \param E RSA public exponent + * \param D Pointer to MPI holding the private exponent on success. + * + * \return + * - 0 if successful. In this case, D is set to a simultaneous + * modular inverse of E modulo both P-1 and Q-1. + * - A non-zero error code otherwise. + * + * \note This function does not check whether P and Q are primes. + * + */ +int mbedtls_rsa_deduce_private_exponent( mbedtls_mpi const *P, + mbedtls_mpi const *Q, + mbedtls_mpi const *E, + mbedtls_mpi *D ); + + +/** + * \brief Generate RSA-CRT parameters + * + * \note This is a 'static' helper function not operating on + * an RSA context. Alternative implementations need not + * overwrite it. + * + * \param P First prime factor of N + * \param Q Second prime factor of N + * \param D RSA private exponent + * \param DP Output variable for D modulo P-1 + * \param DQ Output variable for D modulo Q-1 + * \param QP Output variable for the modular inverse of Q modulo P. + * + * \return 0 on success, non-zero error code otherwise. + * + * \note This function does not check whether P, Q are + * prime and whether D is a valid private exponent. + * + */ +int mbedtls_rsa_deduce_crt( const mbedtls_mpi *P, const mbedtls_mpi *Q, + const mbedtls_mpi *D, mbedtls_mpi *DP, + mbedtls_mpi *DQ, mbedtls_mpi *QP ); + + +/** + * \brief Check validity of core RSA parameters + * + * \note This is a 'static' helper function not operating on + * an RSA context. Alternative implementations need not + * overwrite it. + * + * \param N RSA modulus N = PQ + * \param P First prime factor of N + * \param Q Second prime factor of N + * \param D RSA private exponent + * \param E RSA public exponent + * \param f_rng PRNG to be used for primality check, or NULL + * \param p_rng PRNG context for f_rng, or NULL + * + * \return + * - 0 if the following conditions are satisfied + * if all relevant parameters are provided: + * - P prime if f_rng != NULL (%) + * - Q prime if f_rng != NULL (%) + * - 1 < N = P * Q + * - 1 < D, E < N + * - D and E are modular inverses modulo P-1 and Q-1 + * (%) This is only done if MBEDTLS_GENPRIME is defined. + * - A non-zero error code otherwise. + * + * \note The function can be used with a restricted set of arguments + * to perform specific checks only. E.g., calling it with + * (-,P,-,-,-) and a PRNG amounts to a primality check for P. + */ +int mbedtls_rsa_validate_params( const mbedtls_mpi *N, const mbedtls_mpi *P, + const mbedtls_mpi *Q, const mbedtls_mpi *D, + const mbedtls_mpi *E, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng ); + +/** + * \brief Check validity of RSA CRT parameters + * + * \note This is a 'static' helper function not operating on + * an RSA context. Alternative implementations need not + * overwrite it. + * + * \param P First prime factor of RSA modulus + * \param Q Second prime factor of RSA modulus + * \param D RSA private exponent + * \param DP MPI to check for D modulo P-1 + * \param DQ MPI to check for D modulo P-1 + * \param QP MPI to check for the modular inverse of Q modulo P. + * + * \return + * - 0 if the following conditions are satisfied: + * - D = DP mod P-1 if P, D, DP != NULL + * - Q = DQ mod P-1 if P, D, DQ != NULL + * - QP = Q^-1 mod P if P, Q, QP != NULL + * - \c MBEDTLS_ERR_RSA_KEY_CHECK_FAILED if check failed, + * potentially including \c MBEDTLS_ERR_MPI_XXX if some + * MPI calculations failed. + * - \c MBEDTLS_ERR_RSA_BAD_INPUT_DATA if insufficient + * data was provided to check DP, DQ or QP. + * + * \note The function can be used with a restricted set of arguments + * to perform specific checks only. E.g., calling it with the + * parameters (P, -, D, DP, -, -) will check DP = D mod P-1. + */ +int mbedtls_rsa_validate_crt( const mbedtls_mpi *P, const mbedtls_mpi *Q, + const mbedtls_mpi *D, const mbedtls_mpi *DP, + const mbedtls_mpi *DQ, const mbedtls_mpi *QP ); + +#ifdef __cplusplus +} +#endif + +#endif /* rsa_internal.h */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/sha1.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/sha1.h new file mode 100644 index 0000000000000000000000000000000000000000..bb6ecf05a4a8a93a496ab245243e1bf97983cace --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/sha1.h @@ -0,0 +1,352 @@ +/** + * \file sha1.h + * + * \brief This file contains SHA-1 definitions and functions. + * + * The Secure Hash Algorithm 1 (SHA-1) cryptographic hash function is defined in + * FIPS 180-4: Secure Hash Standard (SHS). + * + * \warning SHA-1 is considered a weak message digest and its use constitutes + * a security risk. We recommend considering stronger message + * digests instead. + */ +/* + * Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of Mbed TLS (https://tls.mbed.org) + */ +#ifndef MBEDTLS_SHA1_H +#define MBEDTLS_SHA1_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include +#include + +/* MBEDTLS_ERR_SHA1_HW_ACCEL_FAILED is deprecated and should not be used. */ +#define MBEDTLS_ERR_SHA1_HW_ACCEL_FAILED -0x0035 /**< SHA-1 hardware accelerator failed */ +#define MBEDTLS_ERR_SHA1_BAD_INPUT_DATA -0x0073 /**< SHA-1 input data was malformed. */ + +#ifdef __cplusplus +extern "C" { +#endif + +#if !defined(MBEDTLS_SHA1_ALT) +// Regular implementation +// + +/** + * \brief The SHA-1 context structure. + * + * \warning SHA-1 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + */ +typedef struct mbedtls_sha1_context +{ + uint32_t total[2]; /*!< The number of Bytes processed. */ + uint32_t state[5]; /*!< The intermediate digest state. */ + unsigned char buffer[64]; /*!< The data block being processed. */ +} +mbedtls_sha1_context; + +#else /* MBEDTLS_SHA1_ALT */ +#include "sha1_alt.h" +#endif /* MBEDTLS_SHA1_ALT */ + +/** + * \brief This function initializes a SHA-1 context. + * + * \warning SHA-1 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + * \param ctx The SHA-1 context to initialize. + * This must not be \c NULL. + * + */ +void mbedtls_sha1_init( mbedtls_sha1_context *ctx ); + +/** + * \brief This function clears a SHA-1 context. + * + * \warning SHA-1 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + * \param ctx The SHA-1 context to clear. This may be \c NULL, + * in which case this function does nothing. If it is + * not \c NULL, it must point to an initialized + * SHA-1 context. + * + */ +void mbedtls_sha1_free( mbedtls_sha1_context *ctx ); + +/** + * \brief This function clones the state of a SHA-1 context. + * + * \warning SHA-1 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + * \param dst The SHA-1 context to clone to. This must be initialized. + * \param src The SHA-1 context to clone from. This must be initialized. + * + */ +void mbedtls_sha1_clone( mbedtls_sha1_context *dst, + const mbedtls_sha1_context *src ); + +/** + * \brief This function starts a SHA-1 checksum calculation. + * + * \warning SHA-1 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + * \param ctx The SHA-1 context to initialize. This must be initialized. + * + * \return \c 0 on success. + * \return A negative error code on failure. + * + */ +int mbedtls_sha1_starts_ret( mbedtls_sha1_context *ctx ); + +/** + * \brief This function feeds an input buffer into an ongoing SHA-1 + * checksum calculation. + * + * \warning SHA-1 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + * \param ctx The SHA-1 context. This must be initialized + * and have a hash operation started. + * \param input The buffer holding the input data. + * This must be a readable buffer of length \p ilen Bytes. + * \param ilen The length of the input data \p input in Bytes. + * + * \return \c 0 on success. + * \return A negative error code on failure. + */ +int mbedtls_sha1_update_ret( mbedtls_sha1_context *ctx, + const unsigned char *input, + size_t ilen ); + +/** + * \brief This function finishes the SHA-1 operation, and writes + * the result to the output buffer. + * + * \warning SHA-1 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + * \param ctx The SHA-1 context to use. This must be initialized and + * have a hash operation started. + * \param output The SHA-1 checksum result. This must be a writable + * buffer of length \c 20 Bytes. + * + * \return \c 0 on success. + * \return A negative error code on failure. + */ +int mbedtls_sha1_finish_ret( mbedtls_sha1_context *ctx, + unsigned char output[20] ); + +/** + * \brief SHA-1 process data block (internal use only). + * + * \warning SHA-1 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + * \param ctx The SHA-1 context to use. This must be initialized. + * \param data The data block being processed. This must be a + * readable buffer of length \c 64 Bytes. + * + * \return \c 0 on success. + * \return A negative error code on failure. + * + */ +int mbedtls_internal_sha1_process( mbedtls_sha1_context *ctx, + const unsigned char data[64] ); + +#if !defined(MBEDTLS_DEPRECATED_REMOVED) +#if defined(MBEDTLS_DEPRECATED_WARNING) +#define MBEDTLS_DEPRECATED __attribute__((deprecated)) +#else +#define MBEDTLS_DEPRECATED +#endif +/** + * \brief This function starts a SHA-1 checksum calculation. + * + * \warning SHA-1 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + * \deprecated Superseded by mbedtls_sha1_starts_ret() in 2.7.0. + * + * \param ctx The SHA-1 context to initialize. This must be initialized. + * + */ +MBEDTLS_DEPRECATED void mbedtls_sha1_starts( mbedtls_sha1_context *ctx ); + +/** + * \brief This function feeds an input buffer into an ongoing SHA-1 + * checksum calculation. + * + * \warning SHA-1 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + * \deprecated Superseded by mbedtls_sha1_update_ret() in 2.7.0. + * + * \param ctx The SHA-1 context. This must be initialized and + * have a hash operation started. + * \param input The buffer holding the input data. + * This must be a readable buffer of length \p ilen Bytes. + * \param ilen The length of the input data \p input in Bytes. + * + */ +MBEDTLS_DEPRECATED void mbedtls_sha1_update( mbedtls_sha1_context *ctx, + const unsigned char *input, + size_t ilen ); + +/** + * \brief This function finishes the SHA-1 operation, and writes + * the result to the output buffer. + * + * \warning SHA-1 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + * \deprecated Superseded by mbedtls_sha1_finish_ret() in 2.7.0. + * + * \param ctx The SHA-1 context. This must be initialized and + * have a hash operation started. + * \param output The SHA-1 checksum result. + * This must be a writable buffer of length \c 20 Bytes. + */ +MBEDTLS_DEPRECATED void mbedtls_sha1_finish( mbedtls_sha1_context *ctx, + unsigned char output[20] ); + +/** + * \brief SHA-1 process data block (internal use only). + * + * \warning SHA-1 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + * \deprecated Superseded by mbedtls_internal_sha1_process() in 2.7.0. + * + * \param ctx The SHA-1 context. This must be initialized. + * \param data The data block being processed. + * This must be a readable buffer of length \c 64 bytes. + * + */ +MBEDTLS_DEPRECATED void mbedtls_sha1_process( mbedtls_sha1_context *ctx, + const unsigned char data[64] ); + +#undef MBEDTLS_DEPRECATED +#endif /* !MBEDTLS_DEPRECATED_REMOVED */ + +/** + * \brief This function calculates the SHA-1 checksum of a buffer. + * + * The function allocates the context, performs the + * calculation, and frees the context. + * + * The SHA-1 result is calculated as + * output = SHA-1(input buffer). + * + * \warning SHA-1 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + * \param input The buffer holding the input data. + * This must be a readable buffer of length \p ilen Bytes. + * \param ilen The length of the input data \p input in Bytes. + * \param output The SHA-1 checksum result. + * This must be a writable buffer of length \c 20 Bytes. + * + * \return \c 0 on success. + * \return A negative error code on failure. + * + */ +int mbedtls_sha1_ret( const unsigned char *input, + size_t ilen, + unsigned char output[20] ); + +#if !defined(MBEDTLS_DEPRECATED_REMOVED) +#if defined(MBEDTLS_DEPRECATED_WARNING) +#define MBEDTLS_DEPRECATED __attribute__((deprecated)) +#else +#define MBEDTLS_DEPRECATED +#endif +/** + * \brief This function calculates the SHA-1 checksum of a buffer. + * + * The function allocates the context, performs the + * calculation, and frees the context. + * + * The SHA-1 result is calculated as + * output = SHA-1(input buffer). + * + * \warning SHA-1 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + * \deprecated Superseded by mbedtls_sha1_ret() in 2.7.0 + * + * \param input The buffer holding the input data. + * This must be a readable buffer of length \p ilen Bytes. + * \param ilen The length of the input data \p input in Bytes. + * \param output The SHA-1 checksum result. This must be a writable + * buffer of size \c 20 Bytes. + * + */ +MBEDTLS_DEPRECATED void mbedtls_sha1( const unsigned char *input, + size_t ilen, + unsigned char output[20] ); + +#undef MBEDTLS_DEPRECATED +#endif /* !MBEDTLS_DEPRECATED_REMOVED */ + +#if defined(MBEDTLS_SELF_TEST) + +/** + * \brief The SHA-1 checkup routine. + * + * \warning SHA-1 is considered a weak message digest and its use + * constitutes a security risk. We recommend considering + * stronger message digests instead. + * + * \return \c 0 on success. + * \return \c 1 on failure. + * + */ +int mbedtls_sha1_self_test( int verbose ); + +#endif /* MBEDTLS_SELF_TEST */ + +#ifdef __cplusplus +} +#endif + +#endif /* mbedtls_sha1.h */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/sha256.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/sha256.h new file mode 100644 index 0000000000000000000000000000000000000000..d64739820c6d32ab993bb2d1cf701e1148ec4af1 --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/sha256.h @@ -0,0 +1,297 @@ +/** + * \file sha256.h + * + * \brief This file contains SHA-224 and SHA-256 definitions and functions. + * + * The Secure Hash Algorithms 224 and 256 (SHA-224 and SHA-256) cryptographic + * hash functions are defined in FIPS 180-4: Secure Hash Standard (SHS). + */ +/* + * Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of Mbed TLS (https://tls.mbed.org) + */ +#ifndef MBEDTLS_SHA256_H +#define MBEDTLS_SHA256_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include +#include + +/* MBEDTLS_ERR_SHA256_HW_ACCEL_FAILED is deprecated and should not be used. */ +#define MBEDTLS_ERR_SHA256_HW_ACCEL_FAILED -0x0037 /**< SHA-256 hardware accelerator failed */ +#define MBEDTLS_ERR_SHA256_BAD_INPUT_DATA -0x0074 /**< SHA-256 input data was malformed. */ + +#ifdef __cplusplus +extern "C" { +#endif + +#if !defined(MBEDTLS_SHA256_ALT) +// Regular implementation +// + +/** + * \brief The SHA-256 context structure. + * + * The structure is used both for SHA-256 and for SHA-224 + * checksum calculations. The choice between these two is + * made in the call to mbedtls_sha256_starts_ret(). + */ +typedef struct mbedtls_sha256_context +{ + uint32_t total[2]; /*!< The number of Bytes processed. */ + uint32_t state[8]; /*!< The intermediate digest state. */ + unsigned char buffer[64]; /*!< The data block being processed. */ + int is224; /*!< Determines which function to use: + 0: Use SHA-256, or 1: Use SHA-224. */ +} +mbedtls_sha256_context; + +#else /* MBEDTLS_SHA256_ALT */ +#include "sha256_alt.h" +#endif /* MBEDTLS_SHA256_ALT */ + +/** + * \brief This function initializes a SHA-256 context. + * + * \param ctx The SHA-256 context to initialize. This must not be \c NULL. + */ +void mbedtls_sha256_init( mbedtls_sha256_context *ctx ); + +/** + * \brief This function clears a SHA-256 context. + * + * \param ctx The SHA-256 context to clear. This may be \c NULL, in which + * case this function returns immediately. If it is not \c NULL, + * it must point to an initialized SHA-256 context. + */ +void mbedtls_sha256_free( mbedtls_sha256_context *ctx ); + +/** + * \brief This function clones the state of a SHA-256 context. + * + * \param dst The destination context. This must be initialized. + * \param src The context to clone. This must be initialized. + */ +void mbedtls_sha256_clone( mbedtls_sha256_context *dst, + const mbedtls_sha256_context *src ); + +/** + * \brief This function starts a SHA-224 or SHA-256 checksum + * calculation. + * + * \param ctx The context to use. This must be initialized. + * \param is224 This determines which function to use. This must be + * either \c 0 for SHA-256, or \c 1 for SHA-224. + * + * \return \c 0 on success. + * \return A negative error code on failure. + */ +int mbedtls_sha256_starts_ret( mbedtls_sha256_context *ctx, int is224 ); + +/** + * \brief This function feeds an input buffer into an ongoing + * SHA-256 checksum calculation. + * + * \param ctx The SHA-256 context. This must be initialized + * and have a hash operation started. + * \param input The buffer holding the data. This must be a readable + * buffer of length \p ilen Bytes. + * \param ilen The length of the input data in Bytes. + * + * \return \c 0 on success. + * \return A negative error code on failure. + */ +int mbedtls_sha256_update_ret( mbedtls_sha256_context *ctx, + const unsigned char *input, + size_t ilen ); + +/** + * \brief This function finishes the SHA-256 operation, and writes + * the result to the output buffer. + * + * \param ctx The SHA-256 context. This must be initialized + * and have a hash operation started. + * \param output The SHA-224 or SHA-256 checksum result. + * This must be a writable buffer of length \c 32 Bytes. + * + * \return \c 0 on success. + * \return A negative error code on failure. + */ +int mbedtls_sha256_finish_ret( mbedtls_sha256_context *ctx, + unsigned char output[32] ); + +/** + * \brief This function processes a single data block within + * the ongoing SHA-256 computation. This function is for + * internal use only. + * + * \param ctx The SHA-256 context. This must be initialized. + * \param data The buffer holding one block of data. This must + * be a readable buffer of length \c 64 Bytes. + * + * \return \c 0 on success. + * \return A negative error code on failure. + */ +int mbedtls_internal_sha256_process( mbedtls_sha256_context *ctx, + const unsigned char data[64] ); + +#if !defined(MBEDTLS_DEPRECATED_REMOVED) +#if defined(MBEDTLS_DEPRECATED_WARNING) +#define MBEDTLS_DEPRECATED __attribute__((deprecated)) +#else +#define MBEDTLS_DEPRECATED +#endif +/** + * \brief This function starts a SHA-224 or SHA-256 checksum + * calculation. + * + * \deprecated Superseded by mbedtls_sha256_starts_ret() in 2.7.0. + * + * \param ctx The context to use. This must be initialized. + * \param is224 Determines which function to use. This must be + * either \c 0 for SHA-256, or \c 1 for SHA-224. + */ +MBEDTLS_DEPRECATED void mbedtls_sha256_starts( mbedtls_sha256_context *ctx, + int is224 ); + +/** + * \brief This function feeds an input buffer into an ongoing + * SHA-256 checksum calculation. + * + * \deprecated Superseded by mbedtls_sha256_update_ret() in 2.7.0. + * + * \param ctx The SHA-256 context to use. This must be + * initialized and have a hash operation started. + * \param input The buffer holding the data. This must be a readable + * buffer of length \p ilen Bytes. + * \param ilen The length of the input data in Bytes. + */ +MBEDTLS_DEPRECATED void mbedtls_sha256_update( mbedtls_sha256_context *ctx, + const unsigned char *input, + size_t ilen ); + +/** + * \brief This function finishes the SHA-256 operation, and writes + * the result to the output buffer. + * + * \deprecated Superseded by mbedtls_sha256_finish_ret() in 2.7.0. + * + * \param ctx The SHA-256 context. This must be initialized and + * have a hash operation started. + * \param output The SHA-224 or SHA-256 checksum result. This must be + * a writable buffer of length \c 32 Bytes. + */ +MBEDTLS_DEPRECATED void mbedtls_sha256_finish( mbedtls_sha256_context *ctx, + unsigned char output[32] ); + +/** + * \brief This function processes a single data block within + * the ongoing SHA-256 computation. This function is for + * internal use only. + * + * \deprecated Superseded by mbedtls_internal_sha256_process() in 2.7.0. + * + * \param ctx The SHA-256 context. This must be initialized. + * \param data The buffer holding one block of data. This must be + * a readable buffer of size \c 64 Bytes. + */ +MBEDTLS_DEPRECATED void mbedtls_sha256_process( mbedtls_sha256_context *ctx, + const unsigned char data[64] ); + +#undef MBEDTLS_DEPRECATED +#endif /* !MBEDTLS_DEPRECATED_REMOVED */ + +/** + * \brief This function calculates the SHA-224 or SHA-256 + * checksum of a buffer. + * + * The function allocates the context, performs the + * calculation, and frees the context. + * + * The SHA-256 result is calculated as + * output = SHA-256(input buffer). + * + * \param input The buffer holding the data. This must be a readable + * buffer of length \p ilen Bytes. + * \param ilen The length of the input data in Bytes. + * \param output The SHA-224 or SHA-256 checksum result. This must + * be a writable buffer of length \c 32 Bytes. + * \param is224 Determines which function to use. This must be + * either \c 0 for SHA-256, or \c 1 for SHA-224. + */ +int mbedtls_sha256_ret( const unsigned char *input, + size_t ilen, + unsigned char output[32], + int is224 ); + +#if !defined(MBEDTLS_DEPRECATED_REMOVED) +#if defined(MBEDTLS_DEPRECATED_WARNING) +#define MBEDTLS_DEPRECATED __attribute__((deprecated)) +#else +#define MBEDTLS_DEPRECATED +#endif + +/** + * \brief This function calculates the SHA-224 or SHA-256 checksum + * of a buffer. + * + * The function allocates the context, performs the + * calculation, and frees the context. + * + * The SHA-256 result is calculated as + * output = SHA-256(input buffer). + * + * \deprecated Superseded by mbedtls_sha256_ret() in 2.7.0. + * + * \param input The buffer holding the data. This must be a readable + * buffer of length \p ilen Bytes. + * \param ilen The length of the input data in Bytes. + * \param output The SHA-224 or SHA-256 checksum result. This must be + * a writable buffer of length \c 32 Bytes. + * \param is224 Determines which function to use. This must be either + * \c 0 for SHA-256, or \c 1 for SHA-224. + */ +MBEDTLS_DEPRECATED void mbedtls_sha256( const unsigned char *input, + size_t ilen, + unsigned char output[32], + int is224 ); + +#undef MBEDTLS_DEPRECATED +#endif /* !MBEDTLS_DEPRECATED_REMOVED */ + +#if defined(MBEDTLS_SELF_TEST) + +/** + * \brief The SHA-224 and SHA-256 checkup routine. + * + * \return \c 0 on success. + * \return \c 1 on failure. + */ +int mbedtls_sha256_self_test( int verbose ); + +#endif /* MBEDTLS_SELF_TEST */ + +#ifdef __cplusplus +} +#endif + +#endif /* mbedtls_sha256.h */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/sha256_alt.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/sha256_alt.h new file mode 100644 index 0000000000000000000000000000000000000000..9e8e5750e1802dd923806fdb45d80f6685f1960a --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/sha256_alt.h @@ -0,0 +1,41 @@ +/** + * \file sha256.h + * + * \brief This file contains SHA-224 and SHA-256 definitions and functions. + * + * The Secure Hash Algorithms 224 and 256 (SHA-224 and SHA-256) cryptographic + * hash functions are defined in FIPS 180-4: Secure Hash Standard (SHS). + */ +/* + * Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of Mbed TLS (https://tls.mbed.org) + */ +#ifndef MBEDTLS_SHA256_ALT_H +#define MBEDTLS_SHA256_ALT_H +#include "hi_cipher.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define mbedtls_sha256_context hi_cipher_hash_atts + +#ifdef __cplusplus +} +#endif + +#endif /* mbedtls_sha256_alt.h */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/sha512.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/sha512.h new file mode 100644 index 0000000000000000000000000000000000000000..c06ceed1d13c2e5acce3cebb22d1955f05444605 --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/sha512.h @@ -0,0 +1,300 @@ +/** + * \file sha512.h + * \brief This file contains SHA-384 and SHA-512 definitions and functions. + * + * The Secure Hash Algorithms 384 and 512 (SHA-384 and SHA-512) cryptographic + * hash functions are defined in FIPS 180-4: Secure Hash Standard (SHS). + */ +/* + * Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of Mbed TLS (https://tls.mbed.org) + */ +#ifndef MBEDTLS_SHA512_H +#define MBEDTLS_SHA512_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include +#include + +/* MBEDTLS_ERR_SHA512_HW_ACCEL_FAILED is deprecated and should not be used. */ +#define MBEDTLS_ERR_SHA512_HW_ACCEL_FAILED -0x0039 /**< SHA-512 hardware accelerator failed */ +#define MBEDTLS_ERR_SHA512_BAD_INPUT_DATA -0x0075 /**< SHA-512 input data was malformed. */ + +#ifdef __cplusplus +extern "C" { +#endif + +#if !defined(MBEDTLS_SHA512_ALT) +// Regular implementation +// + +/** + * \brief The SHA-512 context structure. + * + * The structure is used both for SHA-384 and for SHA-512 + * checksum calculations. The choice between these two is + * made in the call to mbedtls_sha512_starts_ret(). + */ +typedef struct mbedtls_sha512_context +{ + uint64_t total[2]; /*!< The number of Bytes processed. */ + uint64_t state[8]; /*!< The intermediate digest state. */ + unsigned char buffer[128]; /*!< The data block being processed. */ + int is384; /*!< Determines which function to use: + 0: Use SHA-512, or 1: Use SHA-384. */ +} +mbedtls_sha512_context; + +#else /* MBEDTLS_SHA512_ALT */ +#include "sha512_alt.h" +#endif /* MBEDTLS_SHA512_ALT */ + +/** + * \brief This function initializes a SHA-512 context. + * + * \param ctx The SHA-512 context to initialize. This must + * not be \c NULL. + */ +void mbedtls_sha512_init( mbedtls_sha512_context *ctx ); + +/** + * \brief This function clears a SHA-512 context. + * + * \param ctx The SHA-512 context to clear. This may be \c NULL, + * in which case this function does nothing. If it + * is not \c NULL, it must point to an initialized + * SHA-512 context. + */ +void mbedtls_sha512_free( mbedtls_sha512_context *ctx ); + +/** + * \brief This function clones the state of a SHA-512 context. + * + * \param dst The destination context. This must be initialized. + * \param src The context to clone. This must be initialized. + */ +void mbedtls_sha512_clone( mbedtls_sha512_context *dst, + const mbedtls_sha512_context *src ); + +/** + * \brief This function starts a SHA-384 or SHA-512 checksum + * calculation. + * + * \param ctx The SHA-512 context to use. This must be initialized. + * \param is384 Determines which function to use. This must be + * either \c for SHA-512, or \c 1 for SHA-384. + * + * \return \c 0 on success. + * \return A negative error code on failure. + */ +int mbedtls_sha512_starts_ret( mbedtls_sha512_context *ctx, int is384 ); + +/** + * \brief This function feeds an input buffer into an ongoing + * SHA-512 checksum calculation. + * + * \param ctx The SHA-512 context. This must be initialized + * and have a hash operation started. + * \param input The buffer holding the input data. This must + * be a readable buffer of length \p ilen Bytes. + * \param ilen The length of the input data in Bytes. + * + * \return \c 0 on success. + * \return A negative error code on failure. + */ +int mbedtls_sha512_update_ret( mbedtls_sha512_context *ctx, + const unsigned char *input, + size_t ilen ); + +/** + * \brief This function finishes the SHA-512 operation, and writes + * the result to the output buffer. This function is for + * internal use only. + * + * \param ctx The SHA-512 context. This must be initialized + * and have a hash operation started. + * \param output The SHA-384 or SHA-512 checksum result. + * This must be a writable buffer of length \c 64 Bytes. + * + * \return \c 0 on success. + * \return A negative error code on failure. + */ +int mbedtls_sha512_finish_ret( mbedtls_sha512_context *ctx, + unsigned char output[64] ); + +/** + * \brief This function processes a single data block within + * the ongoing SHA-512 computation. + * + * \param ctx The SHA-512 context. This must be initialized. + * \param data The buffer holding one block of data. This + * must be a readable buffer of length \c 128 Bytes. + * + * \return \c 0 on success. + * \return A negative error code on failure. + */ +int mbedtls_internal_sha512_process( mbedtls_sha512_context *ctx, + const unsigned char data[128] ); +#if !defined(MBEDTLS_DEPRECATED_REMOVED) +#if defined(MBEDTLS_DEPRECATED_WARNING) +#define MBEDTLS_DEPRECATED __attribute__((deprecated)) +#else +#define MBEDTLS_DEPRECATED +#endif +/** + * \brief This function starts a SHA-384 or SHA-512 checksum + * calculation. + * + * \deprecated Superseded by mbedtls_sha512_starts_ret() in 2.7.0 + * + * \param ctx The SHA-512 context to use. This must be initialized. + * \param is384 Determines which function to use. This must be either + * \c 0 for SHA-512 or \c 1 for SHA-384. + */ +MBEDTLS_DEPRECATED void mbedtls_sha512_starts( mbedtls_sha512_context *ctx, + int is384 ); + +/** + * \brief This function feeds an input buffer into an ongoing + * SHA-512 checksum calculation. + * + * \deprecated Superseded by mbedtls_sha512_update_ret() in 2.7.0. + * + * \param ctx The SHA-512 context. This must be initialized + * and have a hash operation started. + * \param input The buffer holding the data. This must be a readable + * buffer of length \p ilen Bytes. + * \param ilen The length of the input data in Bytes. + */ +MBEDTLS_DEPRECATED void mbedtls_sha512_update( mbedtls_sha512_context *ctx, + const unsigned char *input, + size_t ilen ); + +/** + * \brief This function finishes the SHA-512 operation, and writes + * the result to the output buffer. + * + * \deprecated Superseded by mbedtls_sha512_finish_ret() in 2.7.0. + * + * \param ctx The SHA-512 context. This must be initialized + * and have a hash operation started. + * \param output The SHA-384 or SHA-512 checksum result. This must + * be a writable buffer of size \c 64 Bytes. + */ +MBEDTLS_DEPRECATED void mbedtls_sha512_finish( mbedtls_sha512_context *ctx, + unsigned char output[64] ); + +/** + * \brief This function processes a single data block within + * the ongoing SHA-512 computation. This function is for + * internal use only. + * + * \deprecated Superseded by mbedtls_internal_sha512_process() in 2.7.0. + * + * \param ctx The SHA-512 context. This must be initialized. + * \param data The buffer holding one block of data. This must be + * a readable buffer of length \c 128 Bytes. + */ +MBEDTLS_DEPRECATED void mbedtls_sha512_process( + mbedtls_sha512_context *ctx, + const unsigned char data[128] ); + +#undef MBEDTLS_DEPRECATED +#endif /* !MBEDTLS_DEPRECATED_REMOVED */ + +/** + * \brief This function calculates the SHA-512 or SHA-384 + * checksum of a buffer. + * + * The function allocates the context, performs the + * calculation, and frees the context. + * + * The SHA-512 result is calculated as + * output = SHA-512(input buffer). + * + * \param input The buffer holding the input data. This must be + * a readable buffer of length \p ilen Bytes. + * \param ilen The length of the input data in Bytes. + * \param output The SHA-384 or SHA-512 checksum result. + * This must be a writable buffer of length \c 64 Bytes. + * \param is384 Determines which function to use. This must be either + * \c 0 for SHA-512, or \c 1 for SHA-384. + * + * \return \c 0 on success. + * \return A negative error code on failure. + */ +int mbedtls_sha512_ret( const unsigned char *input, + size_t ilen, + unsigned char output[64], + int is384 ); + +#if !defined(MBEDTLS_DEPRECATED_REMOVED) +#if defined(MBEDTLS_DEPRECATED_WARNING) +#define MBEDTLS_DEPRECATED __attribute__((deprecated)) +#else +#define MBEDTLS_DEPRECATED +#endif + +/** + * \brief This function calculates the SHA-512 or SHA-384 + * checksum of a buffer. + * + * The function allocates the context, performs the + * calculation, and frees the context. + * + * The SHA-512 result is calculated as + * output = SHA-512(input buffer). + * + * \deprecated Superseded by mbedtls_sha512_ret() in 2.7.0 + * + * \param input The buffer holding the data. This must be a + * readable buffer of length \p ilen Bytes. + * \param ilen The length of the input data in Bytes. + * \param output The SHA-384 or SHA-512 checksum result. This must + * be a writable buffer of length \c 64 Bytes. + * \param is384 Determines which function to use. This must be either + * \c 0 for SHA-512, or \c 1 for SHA-384. + */ +MBEDTLS_DEPRECATED void mbedtls_sha512( const unsigned char *input, + size_t ilen, + unsigned char output[64], + int is384 ); + +#undef MBEDTLS_DEPRECATED +#endif /* !MBEDTLS_DEPRECATED_REMOVED */ + +#if defined(MBEDTLS_SELF_TEST) + + /** + * \brief The SHA-384 or SHA-512 checkup routine. + * + * \return \c 0 on success. + * \return \c 1 on failure. + */ +int mbedtls_sha512_self_test( int verbose ); +#endif /* MBEDTLS_SELF_TEST */ + +#ifdef __cplusplus +} +#endif + +#endif /* mbedtls_sha512.h */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/sha512_alt.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/sha512_alt.h new file mode 100644 index 0000000000000000000000000000000000000000..a1e11af33860c9717272afb00a1f3c00e1ce49f3 --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/sha512_alt.h @@ -0,0 +1,49 @@ +/** + * \file sha512.h + * \brief This file contains SHA-384 and SHA-512 definitions and functions. + * + * The Secure Hash Algorithms 384 and 512 (SHA-384 and SHA-512) cryptographic + * hash functions are defined in FIPS 180-4: Secure Hash Standard (SHS). + */ +/* + * Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of Mbed TLS (https://tls.mbed.org) + */ +#ifndef MBEDTLS_SHA512_ALT_H +#define MBEDTLS_SHA512_ALT_H + +#if defined(MBEDTLS_SHA512_ALT) +/** + * \brief The SHA-512 context structure. + * + * The structure is used both for SHA-384 and for SHA-512 + * checksum calculations. The choice between these two is + * made in the call to mbedtls_sha512_starts_ret(). + */ +typedef struct mbedtls_sha512_context +{ + uint64_t total[2]; /*!< The number of Bytes processed. */ + uint64_t state[8]; /*!< The intermediate digest state. */ + unsigned char buffer[128]; /*!< The data block being processed. */ + int is384; /*!< Determines which function to use: + 0: Use SHA-512, or 1: Use SHA-384. */ +} +mbedtls_sha512_context; + +#endif /* MBEDTLS_SHA512_ALT */ + +#endif /* mbedtls_sha512_alt.h */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/ssl.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/ssl.h new file mode 100644 index 0000000000000000000000000000000000000000..44364aa4ac558cc659f2cb0f2ddb47dabca48b69 --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/ssl.h @@ -0,0 +1,3264 @@ +/** + * \file ssl.h + * + * \brief SSL/TLS functions. + */ +/* + * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ +#ifndef MBEDTLS_SSL_H +#define MBEDTLS_SSL_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include "bignum.h" +#include "ecp.h" + +#include "ssl_ciphersuites.h" + +#if defined(MBEDTLS_X509_CRT_PARSE_C) +#include "x509_crt.h" +#include "x509_crl.h" +#endif + +#if defined(MBEDTLS_DHM_C) +#include "dhm.h" +#endif + +#if defined(MBEDTLS_ECDH_C) +#include "ecdh.h" +#endif + +#if defined(MBEDTLS_ZLIB_SUPPORT) + +#if defined(MBEDTLS_DEPRECATED_WARNING) +#warning "Record compression support via MBEDTLS_ZLIB_SUPPORT is deprecated and will be removed in the next major revision of the library" +#endif + +#if defined(MBEDTLS_DEPRECATED_REMOVED) +#error "Record compression support via MBEDTLS_ZLIB_SUPPORT is deprecated and cannot be used if MBEDTLS_DEPRECATED_REMOVED is set" +#endif + +#include "zlib.h" +#endif + +#if defined(MBEDTLS_HAVE_TIME) +#include "platform_time.h" +#endif + +/* + * SSL Error codes + */ +#define MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE -0x7080 /**< The requested feature is not available. */ +#define MBEDTLS_ERR_SSL_BAD_INPUT_DATA -0x7100 /**< Bad input parameters to function. */ +#define MBEDTLS_ERR_SSL_INVALID_MAC -0x7180 /**< Verification of the message MAC failed. */ +#define MBEDTLS_ERR_SSL_INVALID_RECORD -0x7200 /**< An invalid SSL record was received. */ +#define MBEDTLS_ERR_SSL_MSG_TOO_LONG -0x7240 /**< SSL record was too long to be filled in in_buf. */ +#define MBEDTLS_ERR_SSL_CONN_EOF -0x7280 /**< The connection indicated an EOF. */ +#define MBEDTLS_ERR_SSL_UNKNOWN_CIPHER -0x7300 /**< An unknown cipher was received. */ +#define MBEDTLS_ERR_SSL_NO_CIPHER_CHOSEN -0x7380 /**< The server has no ciphersuites in common with the client. */ +#define MBEDTLS_ERR_SSL_NO_RNG -0x7400 /**< No RNG was provided to the SSL module. */ +#define MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE -0x7480 /**< No client certification received from the client, but required by the authentication mode. */ +#define MBEDTLS_ERR_SSL_CERTIFICATE_TOO_LARGE -0x7500 /**< Our own certificate(s) is/are too large to send in an SSL message. */ +#define MBEDTLS_ERR_SSL_CERTIFICATE_REQUIRED -0x7580 /**< The own certificate is not set, but needed by the server. */ +#define MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED -0x7600 /**< The own private key or pre-shared key is not set, but needed. */ +#define MBEDTLS_ERR_SSL_CA_CHAIN_REQUIRED -0x7680 /**< No CA Chain is set, but required to operate. */ +#define MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE -0x7700 /**< An unexpected message was received from our peer. */ +#define MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE -0x7780 /**< A fatal alert message was received from our peer. */ +#define MBEDTLS_ERR_SSL_PEER_VERIFY_FAILED -0x7800 /**< Verification of our peer failed. */ +#define MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY -0x7880 /**< The peer notified us that the connection is going to be closed. */ +#define MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO -0x7900 /**< Processing of the ClientHello handshake message failed. */ +#define MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO -0x7980 /**< Processing of the ServerHello handshake message failed. */ +#define MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE -0x7A00 /**< Processing of the Certificate handshake message failed. */ +#define MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST -0x7A80 /**< Processing of the CertificateRequest handshake message failed. */ +#define MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE -0x7B00 /**< Processing of the ServerKeyExchange handshake message failed. */ +#define MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO_DONE -0x7B80 /**< Processing of the ServerHelloDone handshake message failed. */ +#define MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE -0x7C00 /**< Processing of the ClientKeyExchange handshake message failed. */ +#define MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_RP -0x7C80 /**< Processing of the ClientKeyExchange handshake message failed in DHM / ECDH Read Public. */ +#define MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_CS -0x7D00 /**< Processing of the ClientKeyExchange handshake message failed in DHM / ECDH Calculate Secret. */ +#define MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY -0x7D80 /**< Processing of the CertificateVerify handshake message failed. */ +#define MBEDTLS_ERR_SSL_BAD_HS_CHANGE_CIPHER_SPEC -0x7E00 /**< Processing of the ChangeCipherSpec handshake message failed. */ +#define MBEDTLS_ERR_SSL_BAD_HS_FINISHED -0x7E80 /**< Processing of the Finished handshake message failed. */ +#define MBEDTLS_ERR_SSL_ALLOC_FAILED -0x7F00 /**< Memory allocation failed */ +#define MBEDTLS_ERR_SSL_HW_ACCEL_FAILED -0x7F80 /**< Hardware acceleration function returned with error */ +#define MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH -0x6F80 /**< Hardware acceleration function skipped / left alone data */ +#define MBEDTLS_ERR_SSL_COMPRESSION_FAILED -0x6F00 /**< Processing of the compression / decompression failed */ +#define MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION -0x6E80 /**< Handshake protocol not within min/max boundaries */ +#define MBEDTLS_ERR_SSL_BAD_HS_NEW_SESSION_TICKET -0x6E00 /**< Processing of the NewSessionTicket handshake message failed. */ +#define MBEDTLS_ERR_SSL_SESSION_TICKET_EXPIRED -0x6D80 /**< Session ticket has expired. */ +#define MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH -0x6D00 /**< Public key type mismatch (eg, asked for RSA key exchange and presented EC key) */ +#define MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY -0x6C80 /**< Unknown identity received (eg, PSK identity) */ +#define MBEDTLS_ERR_SSL_INTERNAL_ERROR -0x6C00 /**< Internal error (eg, unexpected failure in lower-level module) */ +#define MBEDTLS_ERR_SSL_COUNTER_WRAPPING -0x6B80 /**< A counter would wrap (eg, too many messages exchanged). */ +#define MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO -0x6B00 /**< Unexpected message at ServerHello in renegotiation. */ +#define MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED -0x6A80 /**< DTLS client must retry for hello verification */ +#define MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL -0x6A00 /**< A buffer is too small to receive or write a message */ +#define MBEDTLS_ERR_SSL_NO_USABLE_CIPHERSUITE -0x6980 /**< None of the common ciphersuites is usable (eg, no suitable certificate, see debug messages). */ +#define MBEDTLS_ERR_SSL_WANT_READ -0x6900 /**< No data of requested type currently available on underlying transport. */ +#define MBEDTLS_ERR_SSL_WANT_WRITE -0x6880 /**< Connection requires a write call. */ +#define MBEDTLS_ERR_SSL_TIMEOUT -0x6800 /**< The operation timed out. */ +#define MBEDTLS_ERR_SSL_CLIENT_RECONNECT -0x6780 /**< The client initiated a reconnect from the same port. */ +#define MBEDTLS_ERR_SSL_UNEXPECTED_RECORD -0x6700 /**< Record header looks valid but is not expected. */ +#define MBEDTLS_ERR_SSL_NON_FATAL -0x6680 /**< The alert message received indicates a non-fatal error. */ +#define MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH -0x6600 /**< Couldn't set the hash for verifying CertificateVerify */ +#define MBEDTLS_ERR_SSL_CONTINUE_PROCESSING -0x6580 /**< Internal-only message signaling that further message-processing should be done */ +#define MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS -0x6500 /**< The asynchronous operation is not completed yet. */ +#define MBEDTLS_ERR_SSL_EARLY_MESSAGE -0x6480 /**< Internal-only message signaling that a message arrived early. */ +#define MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS -0x7000 /**< A cryptographic operation is in progress. Try again later. */ + +/* + * Various constants + */ +#define MBEDTLS_SSL_MAJOR_VERSION_3 3 +#define MBEDTLS_SSL_MINOR_VERSION_0 0 /*!< SSL v3.0 */ +#define MBEDTLS_SSL_MINOR_VERSION_1 1 /*!< TLS v1.0 */ +#define MBEDTLS_SSL_MINOR_VERSION_2 2 /*!< TLS v1.1 */ +#define MBEDTLS_SSL_MINOR_VERSION_3 3 /*!< TLS v1.2 */ + +#define MBEDTLS_SSL_TRANSPORT_STREAM 0 /*!< TLS */ +#define MBEDTLS_SSL_TRANSPORT_DATAGRAM 1 /*!< DTLS */ + +#define MBEDTLS_SSL_MAX_HOST_NAME_LEN 255 /*!< Maximum host name defined in RFC 1035 */ + +/* RFC 6066 section 4, see also mfl_code_to_length in ssl_tls.c + * NONE must be zero so that memset()ing structure to zero works */ +#define MBEDTLS_SSL_MAX_FRAG_LEN_NONE 0 /*!< don't use this extension */ +#define MBEDTLS_SSL_MAX_FRAG_LEN_512 1 /*!< MaxFragmentLength 2^9 */ +#define MBEDTLS_SSL_MAX_FRAG_LEN_1024 2 /*!< MaxFragmentLength 2^10 */ +#define MBEDTLS_SSL_MAX_FRAG_LEN_2048 3 /*!< MaxFragmentLength 2^11 */ +#define MBEDTLS_SSL_MAX_FRAG_LEN_4096 4 /*!< MaxFragmentLength 2^12 */ +#define MBEDTLS_SSL_MAX_FRAG_LEN_INVALID 5 /*!< first invalid value */ + +#define MBEDTLS_SSL_IS_CLIENT 0 +#define MBEDTLS_SSL_IS_SERVER 1 + +#define MBEDTLS_SSL_IS_NOT_FALLBACK 0 +#define MBEDTLS_SSL_IS_FALLBACK 1 + +#define MBEDTLS_SSL_EXTENDED_MS_DISABLED 0 +#define MBEDTLS_SSL_EXTENDED_MS_ENABLED 1 + +#define MBEDTLS_SSL_ETM_DISABLED 0 +#define MBEDTLS_SSL_ETM_ENABLED 1 + +#define MBEDTLS_SSL_COMPRESS_NULL 0 +#define MBEDTLS_SSL_COMPRESS_DEFLATE 1 + +#define MBEDTLS_SSL_VERIFY_NONE 0 +#define MBEDTLS_SSL_VERIFY_OPTIONAL 1 +#define MBEDTLS_SSL_VERIFY_REQUIRED 2 +#define MBEDTLS_SSL_VERIFY_UNSET 3 /* Used only for sni_authmode */ + +#define MBEDTLS_SSL_LEGACY_RENEGOTIATION 0 +#define MBEDTLS_SSL_SECURE_RENEGOTIATION 1 + +#define MBEDTLS_SSL_RENEGOTIATION_DISABLED 0 +#define MBEDTLS_SSL_RENEGOTIATION_ENABLED 1 + +#define MBEDTLS_SSL_ANTI_REPLAY_DISABLED 0 +#define MBEDTLS_SSL_ANTI_REPLAY_ENABLED 1 + +#define MBEDTLS_SSL_RENEGOTIATION_NOT_ENFORCED -1 +#define MBEDTLS_SSL_RENEGO_MAX_RECORDS_DEFAULT 16 + +#define MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION 0 +#define MBEDTLS_SSL_LEGACY_ALLOW_RENEGOTIATION 1 +#define MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE 2 + +#define MBEDTLS_SSL_TRUNC_HMAC_DISABLED 0 +#define MBEDTLS_SSL_TRUNC_HMAC_ENABLED 1 +#define MBEDTLS_SSL_TRUNCATED_HMAC_LEN 10 /* 80 bits, rfc 6066 section 7 */ + +#define MBEDTLS_SSL_SESSION_TICKETS_DISABLED 0 +#define MBEDTLS_SSL_SESSION_TICKETS_ENABLED 1 + +#define MBEDTLS_SSL_CBC_RECORD_SPLITTING_DISABLED 0 +#define MBEDTLS_SSL_CBC_RECORD_SPLITTING_ENABLED 1 + +#define MBEDTLS_SSL_ARC4_ENABLED 0 +#define MBEDTLS_SSL_ARC4_DISABLED 1 + +#define MBEDTLS_SSL_PRESET_DEFAULT 0 +#define MBEDTLS_SSL_PRESET_SUITEB 2 + +#define MBEDTLS_SSL_CERT_REQ_CA_LIST_ENABLED 1 +#define MBEDTLS_SSL_CERT_REQ_CA_LIST_DISABLED 0 + +/* + * Default range for DTLS retransmission timer value, in milliseconds. + * RFC 6347 4.2.4.1 says from 1 second to 60 seconds. + */ +#define MBEDTLS_SSL_DTLS_TIMEOUT_DFL_MIN 1000 +#define MBEDTLS_SSL_DTLS_TIMEOUT_DFL_MAX 60000 + +/** + * \name SECTION: Module settings + * + * The configuration options you can set for this module are in this section. + * Either change them in config.h or define them on the compiler command line. + * \{ + */ + +#if !defined(MBEDTLS_SSL_DEFAULT_TICKET_LIFETIME) +#define MBEDTLS_SSL_DEFAULT_TICKET_LIFETIME 86400 /**< Lifetime of session tickets (if enabled) */ +#endif + +/* + * Maximum fragment length in bytes, + * determines the size of each of the two internal I/O buffers. + * + * Note: the RFC defines the default size of SSL / TLS messages. If you + * change the value here, other clients / servers may not be able to + * communicate with you anymore. Only change this value if you control + * both sides of the connection and have it reduced at both sides, or + * if you're using the Max Fragment Length extension and you know all your + * peers are using it too! + */ +#if !defined(MBEDTLS_SSL_MAX_CONTENT_LEN) +#define MBEDTLS_SSL_MAX_CONTENT_LEN 16384 /**< Size of the input / output buffer */ +#endif + +#if !defined(MBEDTLS_SSL_IN_CONTENT_LEN) +#define MBEDTLS_SSL_IN_CONTENT_LEN MBEDTLS_SSL_MAX_CONTENT_LEN +#endif + +#if !defined(MBEDTLS_SSL_OUT_CONTENT_LEN) +#define MBEDTLS_SSL_OUT_CONTENT_LEN MBEDTLS_SSL_MAX_CONTENT_LEN +#endif + +/* + * Maximum number of heap-allocated bytes for the purpose of + * DTLS handshake message reassembly and future message buffering. + */ +#if !defined(MBEDTLS_SSL_DTLS_MAX_BUFFERING) +#define MBEDTLS_SSL_DTLS_MAX_BUFFERING 32768 +#endif + +/* \} name SECTION: Module settings */ + +/* + * Length of the verify data for secure renegotiation + */ +#if defined(MBEDTLS_SSL_PROTO_SSL3) +#define MBEDTLS_SSL_VERIFY_DATA_MAX_LEN 36 +#else +#define MBEDTLS_SSL_VERIFY_DATA_MAX_LEN 12 +#endif + +/* + * Signaling ciphersuite values (SCSV) + */ +#define MBEDTLS_SSL_EMPTY_RENEGOTIATION_INFO 0xFF /**< renegotiation info ext */ +#define MBEDTLS_SSL_FALLBACK_SCSV_VALUE 0x5600 /**< RFC 7507 section 2 */ + +/* + * Supported Signature and Hash algorithms (For TLS 1.2) + * RFC 5246 section 7.4.1.4.1 + */ +#define MBEDTLS_SSL_HASH_NONE 0 +#define MBEDTLS_SSL_HASH_MD5 1 +#define MBEDTLS_SSL_HASH_SHA1 2 +#define MBEDTLS_SSL_HASH_SHA224 3 +#define MBEDTLS_SSL_HASH_SHA256 4 +#define MBEDTLS_SSL_HASH_SHA384 5 +#define MBEDTLS_SSL_HASH_SHA512 6 + +#define MBEDTLS_SSL_SIG_ANON 0 +#define MBEDTLS_SSL_SIG_RSA 1 +#define MBEDTLS_SSL_SIG_ECDSA 3 + +/* + * Client Certificate Types + * RFC 5246 section 7.4.4 plus RFC 4492 section 5.5 + */ +#define MBEDTLS_SSL_CERT_TYPE_RSA_SIGN 1 +#define MBEDTLS_SSL_CERT_TYPE_ECDSA_SIGN 64 + +/* + * Message, alert and handshake types + */ +#define MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC 20 +#define MBEDTLS_SSL_MSG_ALERT 21 +#define MBEDTLS_SSL_MSG_HANDSHAKE 22 +#define MBEDTLS_SSL_MSG_APPLICATION_DATA 23 + +#define MBEDTLS_SSL_ALERT_LEVEL_WARNING 1 +#define MBEDTLS_SSL_ALERT_LEVEL_FATAL 2 + +#define MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY 0 /* 0x00 */ +#define MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE 10 /* 0x0A */ +#define MBEDTLS_SSL_ALERT_MSG_BAD_RECORD_MAC 20 /* 0x14 */ +#define MBEDTLS_SSL_ALERT_MSG_DECRYPTION_FAILED 21 /* 0x15 */ +#define MBEDTLS_SSL_ALERT_MSG_RECORD_OVERFLOW 22 /* 0x16 */ +#define MBEDTLS_SSL_ALERT_MSG_DECOMPRESSION_FAILURE 30 /* 0x1E */ +#define MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE 40 /* 0x28 */ +#define MBEDTLS_SSL_ALERT_MSG_NO_CERT 41 /* 0x29 */ +#define MBEDTLS_SSL_ALERT_MSG_BAD_CERT 42 /* 0x2A */ +#define MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT 43 /* 0x2B */ +#define MBEDTLS_SSL_ALERT_MSG_CERT_REVOKED 44 /* 0x2C */ +#define MBEDTLS_SSL_ALERT_MSG_CERT_EXPIRED 45 /* 0x2D */ +#define MBEDTLS_SSL_ALERT_MSG_CERT_UNKNOWN 46 /* 0x2E */ +#define MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER 47 /* 0x2F */ +#define MBEDTLS_SSL_ALERT_MSG_UNKNOWN_CA 48 /* 0x30 */ +#define MBEDTLS_SSL_ALERT_MSG_ACCESS_DENIED 49 /* 0x31 */ +#define MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR 50 /* 0x32 */ +#define MBEDTLS_SSL_ALERT_MSG_DECRYPT_ERROR 51 /* 0x33 */ +#define MBEDTLS_SSL_ALERT_MSG_EXPORT_RESTRICTION 60 /* 0x3C */ +#define MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION 70 /* 0x46 */ +#define MBEDTLS_SSL_ALERT_MSG_INSUFFICIENT_SECURITY 71 /* 0x47 */ +#define MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR 80 /* 0x50 */ +#define MBEDTLS_SSL_ALERT_MSG_INAPROPRIATE_FALLBACK 86 /* 0x56 */ +#define MBEDTLS_SSL_ALERT_MSG_USER_CANCELED 90 /* 0x5A */ +#define MBEDTLS_SSL_ALERT_MSG_NO_RENEGOTIATION 100 /* 0x64 */ +#define MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_EXT 110 /* 0x6E */ +#define MBEDTLS_SSL_ALERT_MSG_UNRECOGNIZED_NAME 112 /* 0x70 */ +#define MBEDTLS_SSL_ALERT_MSG_UNKNOWN_PSK_IDENTITY 115 /* 0x73 */ +#define MBEDTLS_SSL_ALERT_MSG_NO_APPLICATION_PROTOCOL 120 /* 0x78 */ + +#define MBEDTLS_SSL_HS_HELLO_REQUEST 0 +#define MBEDTLS_SSL_HS_CLIENT_HELLO 1 +#define MBEDTLS_SSL_HS_SERVER_HELLO 2 +#define MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST 3 +#define MBEDTLS_SSL_HS_NEW_SESSION_TICKET 4 +#define MBEDTLS_SSL_HS_CERTIFICATE 11 +#define MBEDTLS_SSL_HS_SERVER_KEY_EXCHANGE 12 +#define MBEDTLS_SSL_HS_CERTIFICATE_REQUEST 13 +#define MBEDTLS_SSL_HS_SERVER_HELLO_DONE 14 +#define MBEDTLS_SSL_HS_CERTIFICATE_VERIFY 15 +#define MBEDTLS_SSL_HS_CLIENT_KEY_EXCHANGE 16 +#define MBEDTLS_SSL_HS_FINISHED 20 + +/* + * TLS extensions + */ +#define MBEDTLS_TLS_EXT_SERVERNAME 0 +#define MBEDTLS_TLS_EXT_SERVERNAME_HOSTNAME 0 + +#define MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH 1 + +#define MBEDTLS_TLS_EXT_TRUNCATED_HMAC 4 + +#define MBEDTLS_TLS_EXT_SUPPORTED_ELLIPTIC_CURVES 10 +#define MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS 11 + +#define MBEDTLS_TLS_EXT_SIG_ALG 13 + +#define MBEDTLS_TLS_EXT_ALPN 16 + +#define MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC 22 /* 0x16 */ +#define MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET 0x0017 /* 23 */ + +#define MBEDTLS_TLS_EXT_SESSION_TICKET 35 + +#define MBEDTLS_TLS_EXT_ECJPAKE_KKPP 256 /* experimental */ + +#define MBEDTLS_TLS_EXT_RENEGOTIATION_INFO 0xFF01 + +/* + * Size defines + */ +#if !defined(MBEDTLS_PSK_MAX_LEN) +#define MBEDTLS_PSK_MAX_LEN 32 /* 256 bits */ +#endif + +/* Dummy type used only for its size */ +union mbedtls_ssl_premaster_secret +{ +#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) + unsigned char _pms_rsa[48]; /* RFC 5246 8.1.1 */ +#endif +#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) + unsigned char _pms_dhm[MBEDTLS_MPI_MAX_SIZE]; /* RFC 5246 8.1.2 */ +#endif +#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \ + defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) || \ + defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \ + defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED) + unsigned char _pms_ecdh[MBEDTLS_ECP_MAX_BYTES]; /* RFC 4492 5.10 */ +#endif +#if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) + unsigned char _pms_psk[4 + 2 * MBEDTLS_PSK_MAX_LEN]; /* RFC 4279 2 */ +#endif +#if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED) + unsigned char _pms_dhe_psk[4 + MBEDTLS_MPI_MAX_SIZE + + MBEDTLS_PSK_MAX_LEN]; /* RFC 4279 3 */ +#endif +#if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) + unsigned char _pms_rsa_psk[52 + MBEDTLS_PSK_MAX_LEN]; /* RFC 4279 4 */ +#endif +#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) + unsigned char _pms_ecdhe_psk[4 + MBEDTLS_ECP_MAX_BYTES + + MBEDTLS_PSK_MAX_LEN]; /* RFC 5489 2 */ +#endif +#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) + unsigned char _pms_ecjpake[32]; /* Thread spec: SHA-256 output */ +#endif +}; + +#define MBEDTLS_PREMASTER_SIZE sizeof( union mbedtls_ssl_premaster_secret ) + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * SSL state machine + */ +typedef enum +{ + MBEDTLS_SSL_HELLO_REQUEST, + MBEDTLS_SSL_CLIENT_HELLO, + MBEDTLS_SSL_SERVER_HELLO, + MBEDTLS_SSL_SERVER_CERTIFICATE, + MBEDTLS_SSL_SERVER_KEY_EXCHANGE, + MBEDTLS_SSL_CERTIFICATE_REQUEST, + MBEDTLS_SSL_SERVER_HELLO_DONE, + MBEDTLS_SSL_CLIENT_CERTIFICATE, + MBEDTLS_SSL_CLIENT_KEY_EXCHANGE, + MBEDTLS_SSL_CERTIFICATE_VERIFY, + MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC, + MBEDTLS_SSL_CLIENT_FINISHED, + MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC, + MBEDTLS_SSL_SERVER_FINISHED, + MBEDTLS_SSL_FLUSH_BUFFERS, + MBEDTLS_SSL_HANDSHAKE_WRAPUP, + MBEDTLS_SSL_HANDSHAKE_OVER, + MBEDTLS_SSL_SERVER_NEW_SESSION_TICKET, + MBEDTLS_SSL_SERVER_HELLO_VERIFY_REQUEST_SENT, +} +mbedtls_ssl_states; + +/** + * \brief Callback type: send data on the network. + * + * \note That callback may be either blocking or non-blocking. + * + * \param ctx Context for the send callback (typically a file descriptor) + * \param buf Buffer holding the data to send + * \param len Length of the data to send + * + * \return The callback must return the number of bytes sent if any, + * or a non-zero error code. + * If performing non-blocking I/O, \c MBEDTLS_ERR_SSL_WANT_WRITE + * must be returned when the operation would block. + * + * \note The callback is allowed to send fewer bytes than requested. + * It must always return the number of bytes actually sent. + */ +typedef int mbedtls_ssl_send_t( void *ctx, + const unsigned char *buf, + size_t len ); + +/** + * \brief Callback type: receive data from the network. + * + * \note That callback may be either blocking or non-blocking. + * + * \param ctx Context for the receive callback (typically a file + * descriptor) + * \param buf Buffer to write the received data to + * \param len Length of the receive buffer + * + * \return The callback must return the number of bytes received, + * or a non-zero error code. + * If performing non-blocking I/O, \c MBEDTLS_ERR_SSL_WANT_READ + * must be returned when the operation would block. + * + * \note The callback may receive fewer bytes than the length of the + * buffer. It must always return the number of bytes actually + * received and written to the buffer. + */ +typedef int mbedtls_ssl_recv_t( void *ctx, + unsigned char *buf, + size_t len ); + +/** + * \brief Callback type: receive data from the network, with timeout + * + * \note That callback must block until data is received, or the + * timeout delay expires, or the operation is interrupted by a + * signal. + * + * \param ctx Context for the receive callback (typically a file descriptor) + * \param buf Buffer to write the received data to + * \param len Length of the receive buffer + * \param timeout Maximum nomber of millisecondes to wait for data + * 0 means no timeout (potentially waiting forever) + * + * \return The callback must return the number of bytes received, + * or a non-zero error code: + * \c MBEDTLS_ERR_SSL_TIMEOUT if the operation timed out, + * \c MBEDTLS_ERR_SSL_WANT_READ if interrupted by a signal. + * + * \note The callback may receive fewer bytes than the length of the + * buffer. It must always return the number of bytes actually + * received and written to the buffer. + */ +typedef int mbedtls_ssl_recv_timeout_t( void *ctx, + unsigned char *buf, + size_t len, + uint32_t timeout ); +/** + * \brief Callback type: set a pair of timers/delays to watch + * + * \param ctx Context pointer + * \param int_ms Intermediate delay in milliseconds + * \param fin_ms Final delay in milliseconds + * 0 cancels the current timer. + * + * \note This callback must at least store the necessary information + * for the associated \c mbedtls_ssl_get_timer_t callback to + * return correct information. + * + * \note If using a event-driven style of programming, an event must + * be generated when the final delay is passed. The event must + * cause a call to \c mbedtls_ssl_handshake() with the proper + * SSL context to be scheduled. Care must be taken to ensure + * that at most one such call happens at a time. + * + * \note Only one timer at a time must be running. Calling this + * function while a timer is running must cancel it. Cancelled + * timers must not generate any event. + */ +typedef void mbedtls_ssl_set_timer_t( void * ctx, + uint32_t int_ms, + uint32_t fin_ms ); + +/** + * \brief Callback type: get status of timers/delays + * + * \param ctx Context pointer + * + * \return This callback must return: + * -1 if cancelled (fin_ms == 0), + * 0 if none of the delays have passed, + * 1 if only the intermediate delay has passed, + * 2 if the final delay has passed. + */ +typedef int mbedtls_ssl_get_timer_t( void * ctx ); + +/* Defined below */ +typedef struct mbedtls_ssl_session mbedtls_ssl_session; +typedef struct mbedtls_ssl_context mbedtls_ssl_context; +typedef struct mbedtls_ssl_config mbedtls_ssl_config; + +/* Defined in ssl_internal.h */ +typedef struct mbedtls_ssl_transform mbedtls_ssl_transform; +typedef struct mbedtls_ssl_handshake_params mbedtls_ssl_handshake_params; +typedef struct mbedtls_ssl_sig_hash_set_t mbedtls_ssl_sig_hash_set_t; +#if defined(MBEDTLS_X509_CRT_PARSE_C) +typedef struct mbedtls_ssl_key_cert mbedtls_ssl_key_cert; +#endif +#if defined(MBEDTLS_SSL_PROTO_DTLS) +typedef struct mbedtls_ssl_flight_item mbedtls_ssl_flight_item; +#endif + +#if defined(MBEDTLS_SSL_ASYNC_PRIVATE) +#if defined(MBEDTLS_X509_CRT_PARSE_C) +/** + * \brief Callback type: start external signature operation. + * + * This callback is called during an SSL handshake to start + * a signature decryption operation using an + * external processor. The parameter \p cert contains + * the public key; it is up to the callback function to + * determine how to access the associated private key. + * + * This function typically sends or enqueues a request, and + * does not wait for the operation to complete. This allows + * the handshake step to be non-blocking. + * + * The parameters \p ssl and \p cert are guaranteed to remain + * valid throughout the handshake. On the other hand, this + * function must save the contents of \p hash if the value + * is needed for later processing, because the \p hash buffer + * is no longer valid after this function returns. + * + * This function may call mbedtls_ssl_set_async_operation_data() + * to store an operation context for later retrieval + * by the resume or cancel callback. + * + * \note For RSA signatures, this function must produce output + * that is consistent with PKCS#1 v1.5 in the same way as + * mbedtls_rsa_pkcs1_sign(). Before the private key operation, + * apply the padding steps described in RFC 8017, section 9.2 + * "EMSA-PKCS1-v1_5" as follows. + * - If \p md_alg is #MBEDTLS_MD_NONE, apply the PKCS#1 v1.5 + * encoding, treating \p hash as the DigestInfo to be + * padded. In other words, apply EMSA-PKCS1-v1_5 starting + * from step 3, with `T = hash` and `tLen = hash_len`. + * - If `md_alg != MBEDTLS_MD_NONE`, apply the PKCS#1 v1.5 + * encoding, treating \p hash as the hash to be encoded and + * padded. In other words, apply EMSA-PKCS1-v1_5 starting + * from step 2, with `digestAlgorithm` obtained by calling + * mbedtls_oid_get_oid_by_md() on \p md_alg. + * + * \note For ECDSA signatures, the output format is the DER encoding + * `Ecdsa-Sig-Value` defined in + * [RFC 4492 section 5.4](https://tools.ietf.org/html/rfc4492#section-5.4). + * + * \param ssl The SSL connection instance. It should not be + * modified other than via + * mbedtls_ssl_set_async_operation_data(). + * \param cert Certificate containing the public key. + * In simple cases, this is one of the pointers passed to + * mbedtls_ssl_conf_own_cert() when configuring the SSL + * connection. However, if other callbacks are used, this + * property may not hold. For example, if an SNI callback + * is registered with mbedtls_ssl_conf_sni(), then + * this callback determines what certificate is used. + * \param md_alg Hash algorithm. + * \param hash Buffer containing the hash. This buffer is + * no longer valid when the function returns. + * \param hash_len Size of the \c hash buffer in bytes. + * + * \return 0 if the operation was started successfully and the SSL + * stack should call the resume callback immediately. + * \return #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS if the operation + * was started successfully and the SSL stack should return + * immediately without calling the resume callback yet. + * \return #MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH if the external + * processor does not support this key. The SSL stack will + * use the private key object instead. + * \return Any other error indicates a fatal failure and is + * propagated up the call chain. The callback should + * use \c MBEDTLS_ERR_PK_xxx error codes, and must not + * use \c MBEDTLS_ERR_SSL_xxx error codes except as + * directed in the documentation of this callback. + */ +typedef int mbedtls_ssl_async_sign_t( mbedtls_ssl_context *ssl, + mbedtls_x509_crt *cert, + mbedtls_md_type_t md_alg, + const unsigned char *hash, + size_t hash_len ); + +/** + * \brief Callback type: start external decryption operation. + * + * This callback is called during an SSL handshake to start + * an RSA decryption operation using an + * external processor. The parameter \p cert contains + * the public key; it is up to the callback function to + * determine how to access the associated private key. + * + * This function typically sends or enqueues a request, and + * does not wait for the operation to complete. This allows + * the handshake step to be non-blocking. + * + * The parameters \p ssl and \p cert are guaranteed to remain + * valid throughout the handshake. On the other hand, this + * function must save the contents of \p input if the value + * is needed for later processing, because the \p input buffer + * is no longer valid after this function returns. + * + * This function may call mbedtls_ssl_set_async_operation_data() + * to store an operation context for later retrieval + * by the resume or cancel callback. + * + * \warning RSA decryption as used in TLS is subject to a potential + * timing side channel attack first discovered by Bleichenbacher + * in 1998. This attack can be remotely exploitable + * in practice. To avoid this attack, you must ensure that + * if the callback performs an RSA decryption, the time it + * takes to execute and return the result does not depend + * on whether the RSA decryption succeeded or reported + * invalid padding. + * + * \param ssl The SSL connection instance. It should not be + * modified other than via + * mbedtls_ssl_set_async_operation_data(). + * \param cert Certificate containing the public key. + * In simple cases, this is one of the pointers passed to + * mbedtls_ssl_conf_own_cert() when configuring the SSL + * connection. However, if other callbacks are used, this + * property may not hold. For example, if an SNI callback + * is registered with mbedtls_ssl_conf_sni(), then + * this callback determines what certificate is used. + * \param input Buffer containing the input ciphertext. This buffer + * is no longer valid when the function returns. + * \param input_len Size of the \p input buffer in bytes. + * + * \return 0 if the operation was started successfully and the SSL + * stack should call the resume callback immediately. + * \return #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS if the operation + * was started successfully and the SSL stack should return + * immediately without calling the resume callback yet. + * \return #MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH if the external + * processor does not support this key. The SSL stack will + * use the private key object instead. + * \return Any other error indicates a fatal failure and is + * propagated up the call chain. The callback should + * use \c MBEDTLS_ERR_PK_xxx error codes, and must not + * use \c MBEDTLS_ERR_SSL_xxx error codes except as + * directed in the documentation of this callback. + */ +typedef int mbedtls_ssl_async_decrypt_t( mbedtls_ssl_context *ssl, + mbedtls_x509_crt *cert, + const unsigned char *input, + size_t input_len ); +#endif /* MBEDTLS_X509_CRT_PARSE_C */ + +/** + * \brief Callback type: resume external operation. + * + * This callback is called during an SSL handshake to resume + * an external operation started by the + * ::mbedtls_ssl_async_sign_t or + * ::mbedtls_ssl_async_decrypt_t callback. + * + * This function typically checks the status of a pending + * request or causes the request queue to make progress, and + * does not wait for the operation to complete. This allows + * the handshake step to be non-blocking. + * + * This function may call mbedtls_ssl_get_async_operation_data() + * to retrieve an operation context set by the start callback. + * It may call mbedtls_ssl_set_async_operation_data() to modify + * this context. + * + * Note that when this function returns a status other than + * #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS, it must free any + * resources associated with the operation. + * + * \param ssl The SSL connection instance. It should not be + * modified other than via + * mbedtls_ssl_set_async_operation_data(). + * \param output Buffer containing the output (signature or decrypted + * data) on success. + * \param output_len On success, number of bytes written to \p output. + * \param output_size Size of the \p output buffer in bytes. + * + * \return 0 if output of the operation is available in the + * \p output buffer. + * \return #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS if the operation + * is still in progress. Subsequent requests for progress + * on the SSL connection will call the resume callback + * again. + * \return Any other error means that the operation is aborted. + * The SSL handshake is aborted. The callback should + * use \c MBEDTLS_ERR_PK_xxx error codes, and must not + * use \c MBEDTLS_ERR_SSL_xxx error codes except as + * directed in the documentation of this callback. + */ +typedef int mbedtls_ssl_async_resume_t( mbedtls_ssl_context *ssl, + unsigned char *output, + size_t *output_len, + size_t output_size ); + +/** + * \brief Callback type: cancel external operation. + * + * This callback is called if an SSL connection is closed + * while an asynchronous operation is in progress. Note that + * this callback is not called if the + * ::mbedtls_ssl_async_resume_t callback has run and has + * returned a value other than + * #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS, since in that case + * the asynchronous operation has already completed. + * + * This function may call mbedtls_ssl_get_async_operation_data() + * to retrieve an operation context set by the start callback. + * + * \param ssl The SSL connection instance. It should not be + * modified. + */ +typedef void mbedtls_ssl_async_cancel_t( mbedtls_ssl_context *ssl ); +#endif /* MBEDTLS_SSL_ASYNC_PRIVATE */ + +/* + * This structure is used for storing current session data. + */ +struct mbedtls_ssl_session +{ +#if defined(MBEDTLS_HAVE_TIME) + mbedtls_time_t start; /*!< starting time */ +#endif + int ciphersuite; /*!< chosen ciphersuite */ + int compression; /*!< chosen compression */ + size_t id_len; /*!< session id length */ + unsigned char id[32]; /*!< session identifier */ + unsigned char master[48]; /*!< the master secret */ + +#if defined(MBEDTLS_X509_CRT_PARSE_C) + mbedtls_x509_crt *peer_cert; /*!< peer X.509 cert chain */ +#endif /* MBEDTLS_X509_CRT_PARSE_C */ + uint32_t verify_result; /*!< verification result */ + +#if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C) + unsigned char *ticket; /*!< RFC 5077 session ticket */ + size_t ticket_len; /*!< session ticket length */ + uint32_t ticket_lifetime; /*!< ticket lifetime hint */ +#endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_CLI_C */ + +#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) + unsigned char mfl_code; /*!< MaxFragmentLength negotiated by peer */ +#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */ + +#if defined(MBEDTLS_SSL_TRUNCATED_HMAC) + int trunc_hmac; /*!< flag for truncated hmac activation */ +#endif /* MBEDTLS_SSL_TRUNCATED_HMAC */ + +#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) + int encrypt_then_mac; /*!< flag for EtM activation */ +#endif +}; + +/** + * SSL/TLS configuration to be shared between mbedtls_ssl_context structures. + */ +struct mbedtls_ssl_config +{ + /* Group items by size (largest first) to minimize padding overhead */ + + /* + * Pointers + */ + + const int *ciphersuite_list[4]; /*!< allowed ciphersuites per version */ + + /** Callback for printing debug output */ + void (*f_dbg)(void *, int, const char *, int, const char *); + void *p_dbg; /*!< context for the debug function */ + + /** Callback for getting (pseudo-)random numbers */ + int (*f_rng)(void *, unsigned char *, size_t); + void *p_rng; /*!< context for the RNG function */ + + /** Callback to retrieve a session from the cache */ + int (*f_get_cache)(void *, mbedtls_ssl_session *); + /** Callback to store a session into the cache */ + int (*f_set_cache)(void *, const mbedtls_ssl_session *); + void *p_cache; /*!< context for cache callbacks */ + +#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) + /** Callback for setting cert according to SNI extension */ + int (*f_sni)(void *, mbedtls_ssl_context *, const unsigned char *, size_t); + void *p_sni; /*!< context for SNI callback */ +#endif + +#if defined(MBEDTLS_X509_CRT_PARSE_C) + /** Callback to customize X.509 certificate chain verification */ + int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *); + void *p_vrfy; /*!< context for X.509 verify calllback */ +#endif + +#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED) + /** Callback to retrieve PSK key from identity */ + int (*f_psk)(void *, mbedtls_ssl_context *, const unsigned char *, size_t); + void *p_psk; /*!< context for PSK callback */ +#endif + +#if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C) + /** Callback to create & write a cookie for ClientHello veirifcation */ + int (*f_cookie_write)( void *, unsigned char **, unsigned char *, + const unsigned char *, size_t ); + /** Callback to verify validity of a ClientHello cookie */ + int (*f_cookie_check)( void *, const unsigned char *, size_t, + const unsigned char *, size_t ); + void *p_cookie; /*!< context for the cookie callbacks */ +#endif + +#if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_SRV_C) + /** Callback to create & write a session ticket */ + int (*f_ticket_write)( void *, const mbedtls_ssl_session *, + unsigned char *, const unsigned char *, size_t *, uint32_t * ); + /** Callback to parse a session ticket into a session structure */ + int (*f_ticket_parse)( void *, mbedtls_ssl_session *, unsigned char *, size_t); + void *p_ticket; /*!< context for the ticket callbacks */ +#endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_SRV_C */ + +#if defined(MBEDTLS_SSL_EXPORT_KEYS) + /** Callback to export key block and master secret */ + int (*f_export_keys)( void *, const unsigned char *, + const unsigned char *, size_t, size_t, size_t ); + void *p_export_keys; /*!< context for key export callback */ +#endif + +#if defined(MBEDTLS_X509_CRT_PARSE_C) + const mbedtls_x509_crt_profile *cert_profile; /*!< verification profile */ + mbedtls_ssl_key_cert *key_cert; /*!< own certificate/key pair(s) */ + mbedtls_x509_crt *ca_chain; /*!< trusted CAs */ + mbedtls_x509_crl *ca_crl; /*!< trusted CAs CRLs */ +#endif /* MBEDTLS_X509_CRT_PARSE_C */ + +#if defined(MBEDTLS_SSL_ASYNC_PRIVATE) +#if defined(MBEDTLS_X509_CRT_PARSE_C) + mbedtls_ssl_async_sign_t *f_async_sign_start; /*!< start asynchronous signature operation */ + mbedtls_ssl_async_decrypt_t *f_async_decrypt_start; /*!< start asynchronous decryption operation */ +#endif /* MBEDTLS_X509_CRT_PARSE_C */ + mbedtls_ssl_async_resume_t *f_async_resume; /*!< resume asynchronous operation */ + mbedtls_ssl_async_cancel_t *f_async_cancel; /*!< cancel asynchronous operation */ + void *p_async_config_data; /*!< Configuration data set by mbedtls_ssl_conf_async_private_cb(). */ +#endif /* MBEDTLS_SSL_ASYNC_PRIVATE */ + +#if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED) + const int *sig_hashes; /*!< allowed signature hashes */ +#endif + +#if defined(MBEDTLS_ECP_C) + const mbedtls_ecp_group_id *curve_list; /*!< allowed curves */ +#endif + +#if defined(MBEDTLS_DHM_C) + mbedtls_mpi dhm_P; /*!< prime modulus for DHM */ + mbedtls_mpi dhm_G; /*!< generator for DHM */ +#endif + +#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED) + unsigned char *psk; /*!< pre-shared key. This field should + only be set via + mbedtls_ssl_conf_psk() */ + size_t psk_len; /*!< length of the pre-shared key. This + field should only be set via + mbedtls_ssl_conf_psk() */ + unsigned char *psk_identity; /*!< identity for PSK negotiation. This + field should only be set via + mbedtls_ssl_conf_psk() */ + size_t psk_identity_len;/*!< length of identity. This field should + only be set via + mbedtls_ssl_conf_psk() */ +#endif + +#if defined(MBEDTLS_SSL_ALPN) + const char **alpn_list; /*!< ordered list of protocols */ +#endif + + /* + * Numerical settings (int then char) + */ + + uint32_t read_timeout; /*!< timeout for mbedtls_ssl_read (ms) */ + +#if defined(MBEDTLS_SSL_PROTO_DTLS) + uint32_t hs_timeout_min; /*!< initial value of the handshake + retransmission timeout (ms) */ + uint32_t hs_timeout_max; /*!< maximum value of the handshake + retransmission timeout (ms) */ +#endif + +#if defined(MBEDTLS_SSL_RENEGOTIATION) + int renego_max_records; /*!< grace period for renegotiation */ + unsigned char renego_period[8]; /*!< value of the record counters + that triggers renegotiation */ +#endif + +#if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT) + unsigned int badmac_limit; /*!< limit of records with a bad MAC */ +#endif + +#if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_CLI_C) + unsigned int dhm_min_bitlen; /*!< min. bit length of the DHM prime */ +#endif + + unsigned char max_major_ver; /*!< max. major version used */ + unsigned char max_minor_ver; /*!< max. minor version used */ + unsigned char min_major_ver; /*!< min. major version used */ + unsigned char min_minor_ver; /*!< min. minor version used */ + + /* + * Flags (bitfields) + */ + + unsigned int endpoint : 1; /*!< 0: client, 1: server */ + unsigned int transport : 1; /*!< stream (TLS) or datagram (DTLS) */ + unsigned int authmode : 2; /*!< MBEDTLS_SSL_VERIFY_XXX */ + /* needed even with renego disabled for LEGACY_BREAK_HANDSHAKE */ + unsigned int allow_legacy_renegotiation : 2 ; /*!< MBEDTLS_LEGACY_XXX */ +#if defined(MBEDTLS_ARC4_C) + unsigned int arc4_disabled : 1; /*!< blacklist RC4 ciphersuites? */ +#endif +#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) + unsigned int mfl_code : 3; /*!< desired fragment length */ +#endif +#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) + unsigned int encrypt_then_mac : 1 ; /*!< negotiate encrypt-then-mac? */ +#endif +#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET) + unsigned int extended_ms : 1; /*!< negotiate extended master secret? */ +#endif +#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) + unsigned int anti_replay : 1; /*!< detect and prevent replay? */ +#endif +#if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING) + unsigned int cbc_record_splitting : 1; /*!< do cbc record splitting */ +#endif +#if defined(MBEDTLS_SSL_RENEGOTIATION) + unsigned int disable_renegotiation : 1; /*!< disable renegotiation? */ +#endif +#if defined(MBEDTLS_SSL_TRUNCATED_HMAC) + unsigned int trunc_hmac : 1; /*!< negotiate truncated hmac? */ +#endif +#if defined(MBEDTLS_SSL_SESSION_TICKETS) + unsigned int session_tickets : 1; /*!< use session tickets? */ +#endif +#if defined(MBEDTLS_SSL_FALLBACK_SCSV) && defined(MBEDTLS_SSL_CLI_C) + unsigned int fallback : 1; /*!< is this a fallback? */ +#endif +#if defined(MBEDTLS_SSL_SRV_C) + unsigned int cert_req_ca_list : 1; /*!< enable sending CA list in + Certificate Request messages? */ +#endif +}; + + +struct mbedtls_ssl_context +{ + const mbedtls_ssl_config *conf; /*!< configuration information */ + + /* + * Miscellaneous + */ + int state; /*!< SSL handshake: current state */ +#if defined(MBEDTLS_SSL_RENEGOTIATION) + int renego_status; /*!< Initial, in progress, pending? */ + int renego_records_seen; /*!< Records since renego request, or with DTLS, + number of retransmissions of request if + renego_max_records is < 0 */ +#endif /* MBEDTLS_SSL_RENEGOTIATION */ + + int major_ver; /*!< equal to MBEDTLS_SSL_MAJOR_VERSION_3 */ + int minor_ver; /*!< either 0 (SSL3) or 1 (TLS1.0) */ + +#if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT) + unsigned badmac_seen; /*!< records with a bad MAC received */ +#endif /* MBEDTLS_SSL_DTLS_BADMAC_LIMIT */ + + mbedtls_ssl_send_t *f_send; /*!< Callback for network send */ + mbedtls_ssl_recv_t *f_recv; /*!< Callback for network receive */ + mbedtls_ssl_recv_timeout_t *f_recv_timeout; + /*!< Callback for network receive with timeout */ + + void *p_bio; /*!< context for I/O operations */ + + /* + * Session layer + */ + mbedtls_ssl_session *session_in; /*!< current session data (in) */ + mbedtls_ssl_session *session_out; /*!< current session data (out) */ + mbedtls_ssl_session *session; /*!< negotiated session data */ + mbedtls_ssl_session *session_negotiate; /*!< session data in negotiation */ + + mbedtls_ssl_handshake_params *handshake; /*!< params required only during + the handshake process */ + + /* + * Record layer transformations + */ + mbedtls_ssl_transform *transform_in; /*!< current transform params (in) */ + mbedtls_ssl_transform *transform_out; /*!< current transform params (in) */ + mbedtls_ssl_transform *transform; /*!< negotiated transform params */ + mbedtls_ssl_transform *transform_negotiate; /*!< transform params in negotiation */ + + /* + * Timers + */ + void *p_timer; /*!< context for the timer callbacks */ + + mbedtls_ssl_set_timer_t *f_set_timer; /*!< set timer callback */ + mbedtls_ssl_get_timer_t *f_get_timer; /*!< get timer callback */ + + /* + * Record layer (incoming data) + */ + unsigned char *in_buf; /*!< input buffer */ + size_t in_buf_len; /*!< input buffer length */ + unsigned char *in_ctr; /*!< 64-bit incoming message counter + TLS: maintained by us + DTLS: read from peer */ + unsigned char *in_hdr; /*!< start of record header */ + unsigned char *in_len; /*!< two-bytes message length field */ + unsigned char *in_iv; /*!< ivlen-byte IV */ + unsigned char *in_msg; /*!< message contents (in_iv+ivlen) */ + unsigned char *in_offt; /*!< read offset in application data */ + + int in_msgtype; /*!< record header: message type */ + size_t in_msglen; /*!< record header: message length */ + size_t in_left; /*!< amount of data read so far */ +#if defined(MBEDTLS_SSL_PROTO_DTLS) + uint16_t in_epoch; /*!< DTLS epoch for incoming records */ + size_t next_record_offset; /*!< offset of the next record in datagram + (equal to in_left if none) */ +#endif /* MBEDTLS_SSL_PROTO_DTLS */ +#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) + uint64_t in_window_top; /*!< last validated record seq_num */ + uint64_t in_window; /*!< bitmask for replay detection */ +#endif /* MBEDTLS_SSL_DTLS_ANTI_REPLAY */ + + size_t in_hslen; /*!< current handshake message length, + including the handshake header */ + int nb_zero; /*!< # of 0-length encrypted messages */ + + int keep_current_message; /*!< drop or reuse current message + on next call to record layer? */ + +#if defined(MBEDTLS_SSL_PROTO_DTLS) + uint8_t disable_datagram_packing; /*!< Disable packing multiple records + * within a single datagram. */ +#endif /* MBEDTLS_SSL_PROTO_DTLS */ + + /* + * Record layer (outgoing data) + */ + unsigned char *out_buf; /*!< output buffer */ + unsigned char *out_ctr; /*!< 64-bit outgoing message counter */ + unsigned char *out_hdr; /*!< start of record header */ + unsigned char *out_len; /*!< two-bytes message length field */ + unsigned char *out_iv; /*!< ivlen-byte IV */ + unsigned char *out_msg; /*!< message contents (out_iv+ivlen) */ + + int out_msgtype; /*!< record header: message type */ + size_t out_msglen; /*!< record header: message length */ + size_t out_left; /*!< amount of data not yet written */ + + unsigned char cur_out_ctr[8]; /*!< Outgoing record sequence number. */ + +#if defined(MBEDTLS_SSL_PROTO_DTLS) + uint16_t mtu; /*!< path mtu, used to fragment outgoing messages */ +#endif /* MBEDTLS_SSL_PROTO_DTLS */ + +#if defined(MBEDTLS_ZLIB_SUPPORT) + unsigned char *compress_buf; /*!< zlib data buffer */ +#endif /* MBEDTLS_ZLIB_SUPPORT */ +#if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING) + signed char split_done; /*!< current record already splitted? */ +#endif /* MBEDTLS_SSL_CBC_RECORD_SPLITTING */ + + /* + * PKI layer + */ + int client_auth; /*!< flag for client auth. */ + + /* + * User settings + */ +#if defined(MBEDTLS_X509_CRT_PARSE_C) + char *hostname; /*!< expected peer CN for verification + (and SNI if available) */ +#endif /* MBEDTLS_X509_CRT_PARSE_C */ + +#if defined(MBEDTLS_SSL_ALPN) + const char *alpn_chosen; /*!< negotiated protocol */ +#endif /* MBEDTLS_SSL_ALPN */ + + /* + * Information for DTLS hello verify + */ +#if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C) + unsigned char *cli_id; /*!< transport-level ID of the client */ + size_t cli_id_len; /*!< length of cli_id */ +#endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY && MBEDTLS_SSL_SRV_C */ + + /* + * Secure renegotiation + */ + /* needed to know when to send extension on server */ + int secure_renegotiation; /*!< does peer support legacy or + secure renegotiation */ +#if defined(MBEDTLS_SSL_RENEGOTIATION) + size_t verify_data_len; /*!< length of verify data stored */ + char own_verify_data[MBEDTLS_SSL_VERIFY_DATA_MAX_LEN]; /*!< previous handshake verify data */ + char peer_verify_data[MBEDTLS_SSL_VERIFY_DATA_MAX_LEN]; /*!< previous handshake verify data */ +#endif /* MBEDTLS_SSL_RENEGOTIATION */ +}; + +#if defined(MBEDTLS_SSL_HW_RECORD_ACCEL) + +#define MBEDTLS_SSL_CHANNEL_OUTBOUND 0 +#define MBEDTLS_SSL_CHANNEL_INBOUND 1 + +extern int (*mbedtls_ssl_hw_record_init)(mbedtls_ssl_context *ssl, + const unsigned char *key_enc, const unsigned char *key_dec, + size_t keylen, + const unsigned char *iv_enc, const unsigned char *iv_dec, + size_t ivlen, + const unsigned char *mac_enc, const unsigned char *mac_dec, + size_t maclen); +extern int (*mbedtls_ssl_hw_record_activate)(mbedtls_ssl_context *ssl, int direction); +extern int (*mbedtls_ssl_hw_record_reset)(mbedtls_ssl_context *ssl); +extern int (*mbedtls_ssl_hw_record_write)(mbedtls_ssl_context *ssl); +extern int (*mbedtls_ssl_hw_record_read)(mbedtls_ssl_context *ssl); +extern int (*mbedtls_ssl_hw_record_finish)(mbedtls_ssl_context *ssl); +#endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */ + +/** + * \brief Return the name of the ciphersuite associated with the + * given ID + * + * \param ciphersuite_id SSL ciphersuite ID + * + * \return a string containing the ciphersuite name + */ +const char *mbedtls_ssl_get_ciphersuite_name( const int ciphersuite_id ); + +/** + * \brief Return the ID of the ciphersuite associated with the + * given name + * + * \param ciphersuite_name SSL ciphersuite name + * + * \return the ID with the ciphersuite or 0 if not found + */ +int mbedtls_ssl_get_ciphersuite_id( const char *ciphersuite_name ); + +/** + * \brief Initialize an SSL context + * Just makes the context ready for mbedtls_ssl_setup() or + * mbedtls_ssl_free() + * + * \param ssl SSL context + */ +void mbedtls_ssl_init( mbedtls_ssl_context *ssl ); + +/** + * \brief Set up an SSL context for use + * + * \note No copy of the configuration context is made, it can be + * shared by many mbedtls_ssl_context structures. + * + * \warning The conf structure will be accessed during the session. + * It must not be modified or freed as long as the session + * is active. + * + * \warning This function must be called exactly once per context. + * Calling mbedtls_ssl_setup again is not supported, even + * if no session is active. + * + * \param ssl SSL context + * \param conf SSL configuration to use + * + * \return 0 if successful, or MBEDTLS_ERR_SSL_ALLOC_FAILED if + * memory allocation failed + */ +int mbedtls_ssl_setup( mbedtls_ssl_context *ssl, + const mbedtls_ssl_config *conf ); + +/** + * \brief Reset an already initialized SSL context for re-use + * while retaining application-set variables, function + * pointers and data. + * + * \param ssl SSL context + * \return 0 if successful, or MBEDTLS_ERR_SSL_ALLOC_FAILED, + MBEDTLS_ERR_SSL_HW_ACCEL_FAILED or + * MBEDTLS_ERR_SSL_COMPRESSION_FAILED + */ +int mbedtls_ssl_session_reset( mbedtls_ssl_context *ssl ); + +/** + * \brief Set the current endpoint type + * + * \param conf SSL configuration + * \param endpoint must be MBEDTLS_SSL_IS_CLIENT or MBEDTLS_SSL_IS_SERVER + */ +void mbedtls_ssl_conf_endpoint( mbedtls_ssl_config *conf, int endpoint ); + +/** + * \brief Set the transport type (TLS or DTLS). + * Default: TLS + * + * \note For DTLS, you must either provide a recv callback that + * doesn't block, or one that handles timeouts, see + * \c mbedtls_ssl_set_bio(). You also need to provide timer + * callbacks with \c mbedtls_ssl_set_timer_cb(). + * + * \param conf SSL configuration + * \param transport transport type: + * MBEDTLS_SSL_TRANSPORT_STREAM for TLS, + * MBEDTLS_SSL_TRANSPORT_DATAGRAM for DTLS. + */ +void mbedtls_ssl_conf_transport( mbedtls_ssl_config *conf, int transport ); + +/** + * \brief Set the certificate verification mode + * Default: NONE on server, REQUIRED on client + * + * \param conf SSL configuration + * \param authmode can be: + * + * MBEDTLS_SSL_VERIFY_NONE: peer certificate is not checked + * (default on server) + * (insecure on client) + * + * MBEDTLS_SSL_VERIFY_OPTIONAL: peer certificate is checked, however the + * handshake continues even if verification failed; + * mbedtls_ssl_get_verify_result() can be called after the + * handshake is complete. + * + * MBEDTLS_SSL_VERIFY_REQUIRED: peer *must* present a valid certificate, + * handshake is aborted if verification failed. + * (default on client) + * + * \note On client, MBEDTLS_SSL_VERIFY_REQUIRED is the recommended mode. + * With MBEDTLS_SSL_VERIFY_OPTIONAL, the user needs to call mbedtls_ssl_get_verify_result() at + * the right time(s), which may not be obvious, while REQUIRED always perform + * the verification as soon as possible. For example, REQUIRED was protecting + * against the "triple handshake" attack even before it was found. + */ +void mbedtls_ssl_conf_authmode( mbedtls_ssl_config *conf, int authmode ); + +#if defined(MBEDTLS_X509_CRT_PARSE_C) +/** + * \brief Set the verification callback (Optional). + * + * If set, the verify callback is called for each + * certificate in the chain. For implementation + * information, please see \c mbedtls_x509_crt_verify() + * + * \param conf SSL configuration + * \param f_vrfy verification function + * \param p_vrfy verification parameter + */ +void mbedtls_ssl_conf_verify( mbedtls_ssl_config *conf, + int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *), + void *p_vrfy ); +#endif /* MBEDTLS_X509_CRT_PARSE_C */ + +/** + * \brief Set the random number generator callback + * + * \param conf SSL configuration + * \param f_rng RNG function + * \param p_rng RNG parameter + */ +void mbedtls_ssl_conf_rng( mbedtls_ssl_config *conf, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng ); + +/** + * \brief Set the debug callback + * + * The callback has the following argument: + * void * opaque context for the callback + * int debug level + * const char * file name + * int line number + * const char * message + * + * \param conf SSL configuration + * \param f_dbg debug function + * \param p_dbg debug parameter + */ +void mbedtls_ssl_conf_dbg( mbedtls_ssl_config *conf, + void (*f_dbg)(void *, int, const char *, int, const char *), + void *p_dbg ); + +/** + * \brief Set the underlying BIO callbacks for write, read and + * read-with-timeout. + * + * \param ssl SSL context + * \param p_bio parameter (context) shared by BIO callbacks + * \param f_send write callback + * \param f_recv read callback + * \param f_recv_timeout blocking read callback with timeout. + * + * \note One of f_recv or f_recv_timeout can be NULL, in which case + * the other is used. If both are non-NULL, f_recv_timeout is + * used and f_recv is ignored (as if it were NULL). + * + * \note The two most common use cases are: + * - non-blocking I/O, f_recv != NULL, f_recv_timeout == NULL + * - blocking I/O, f_recv == NULL, f_recv_timout != NULL + * + * \note For DTLS, you need to provide either a non-NULL + * f_recv_timeout callback, or a f_recv that doesn't block. + * + * \note See the documentations of \c mbedtls_ssl_sent_t, + * \c mbedtls_ssl_recv_t and \c mbedtls_ssl_recv_timeout_t for + * the conventions those callbacks must follow. + * + * \note On some platforms, net_sockets.c provides + * \c mbedtls_net_send(), \c mbedtls_net_recv() and + * \c mbedtls_net_recv_timeout() that are suitable to be used + * here. + */ +void mbedtls_ssl_set_bio( mbedtls_ssl_context *ssl, + void *p_bio, + mbedtls_ssl_send_t *f_send, + mbedtls_ssl_recv_t *f_recv, + mbedtls_ssl_recv_timeout_t *f_recv_timeout ); + +#if defined(MBEDTLS_SSL_PROTO_DTLS) +/** + * \brief Set the Maximum Tranport Unit (MTU). + * Special value: 0 means unset (no limit). + * This represents the maximum size of a datagram payload + * handled by the transport layer (usually UDP) as determined + * by the network link and stack. In practice, this controls + * the maximum size datagram the DTLS layer will pass to the + * \c f_send() callback set using \c mbedtls_ssl_set_bio(). + * + * \note The limit on datagram size is converted to a limit on + * record payload by subtracting the current overhead of + * encapsulation and encryption/authentication if any. + * + * \note This can be called at any point during the connection, for + * example when a Path Maximum Transfer Unit (PMTU) + * estimate becomes available from other sources, + * such as lower (or higher) protocol layers. + * + * \note This setting only controls the size of the packets we send, + * and does not restrict the size of the datagrams we're + * willing to receive. Client-side, you can request the + * server to use smaller records with \c + * mbedtls_ssl_conf_max_frag_len(). + * + * \note If both a MTU and a maximum fragment length have been + * configured (or negotiated with the peer), the resulting + * lower limit on record payload (see first note) is used. + * + * \note This can only be used to decrease the maximum size + * of datagrams (hence records, see first note) sent. It + * cannot be used to increase the maximum size of records over + * the limit set by #MBEDTLS_SSL_OUT_CONTENT_LEN. + * + * \note Values lower than the current record layer expansion will + * result in an error when trying to send data. + * + * \note Using record compression together with a non-zero MTU value + * will result in an error when trying to send data. + * + * \param ssl SSL context + * \param mtu Value of the path MTU in bytes + */ +void mbedtls_ssl_set_mtu( mbedtls_ssl_context *ssl, uint16_t mtu ); +#endif /* MBEDTLS_SSL_PROTO_DTLS */ + +/** + * \brief Set the timeout period for mbedtls_ssl_read() + * (Default: no timeout.) + * + * \param conf SSL configuration context + * \param timeout Timeout value in milliseconds. + * Use 0 for no timeout (default). + * + * \note With blocking I/O, this will only work if a non-NULL + * \c f_recv_timeout was set with \c mbedtls_ssl_set_bio(). + * With non-blocking I/O, this will only work if timer + * callbacks were set with \c mbedtls_ssl_set_timer_cb(). + * + * \note With non-blocking I/O, you may also skip this function + * altogether and handle timeouts at the application layer. + */ +void mbedtls_ssl_conf_read_timeout( mbedtls_ssl_config *conf, uint32_t timeout ); + +/** + * \brief Set the timer callbacks (Mandatory for DTLS.) + * + * \param ssl SSL context + * \param p_timer parameter (context) shared by timer callbacks + * \param f_set_timer set timer callback + * \param f_get_timer get timer callback. Must return: + * + * \note See the documentation of \c mbedtls_ssl_set_timer_t and + * \c mbedtls_ssl_get_timer_t for the conventions this pair of + * callbacks must follow. + * + * \note On some platforms, timing.c provides + * \c mbedtls_timing_set_delay() and + * \c mbedtls_timing_get_delay() that are suitable for using + * here, except if using an event-driven style. + * + * \note See also the "DTLS tutorial" article in our knowledge base. + * https://tls.mbed.org/kb/how-to/dtls-tutorial + */ +void mbedtls_ssl_set_timer_cb( mbedtls_ssl_context *ssl, + void *p_timer, + mbedtls_ssl_set_timer_t *f_set_timer, + mbedtls_ssl_get_timer_t *f_get_timer ); + +/** + * \brief Callback type: generate and write session ticket + * + * \note This describes what a callback implementation should do. + * This callback should generate an encrypted and + * authenticated ticket for the session and write it to the + * output buffer. Here, ticket means the opaque ticket part + * of the NewSessionTicket structure of RFC 5077. + * + * \param p_ticket Context for the callback + * \param session SSL session to be written in the ticket + * \param start Start of the output buffer + * \param end End of the output buffer + * \param tlen On exit, holds the length written + * \param lifetime On exit, holds the lifetime of the ticket in seconds + * + * \return 0 if successful, or + * a specific MBEDTLS_ERR_XXX code. + */ +typedef int mbedtls_ssl_ticket_write_t( void *p_ticket, + const mbedtls_ssl_session *session, + unsigned char *start, + const unsigned char *end, + size_t *tlen, + uint32_t *lifetime ); + +#if defined(MBEDTLS_SSL_EXPORT_KEYS) +/** + * \brief Callback type: Export key block and master secret + * + * \note This is required for certain uses of TLS, e.g. EAP-TLS + * (RFC 5216) and Thread. The key pointers are ephemeral and + * therefore must not be stored. The master secret and keys + * should not be used directly except as an input to a key + * derivation function. + * + * \param p_expkey Context for the callback + * \param ms Pointer to master secret (fixed length: 48 bytes) + * \param kb Pointer to key block, see RFC 5246 section 6.3 + * (variable length: 2 * maclen + 2 * keylen + 2 * ivlen). + * \param maclen MAC length + * \param keylen Key length + * \param ivlen IV length + * + * \return 0 if successful, or + * a specific MBEDTLS_ERR_XXX code. + */ +typedef int mbedtls_ssl_export_keys_t( void *p_expkey, + const unsigned char *ms, + const unsigned char *kb, + size_t maclen, + size_t keylen, + size_t ivlen ); +#endif /* MBEDTLS_SSL_EXPORT_KEYS */ + +/** + * \brief Callback type: parse and load session ticket + * + * \note This describes what a callback implementation should do. + * This callback should parse a session ticket as generated + * by the corresponding mbedtls_ssl_ticket_write_t function, + * and, if the ticket is authentic and valid, load the + * session. + * + * \note The implementation is allowed to modify the first len + * bytes of the input buffer, eg to use it as a temporary + * area for the decrypted ticket contents. + * + * \param p_ticket Context for the callback + * \param session SSL session to be loaded + * \param buf Start of the buffer containing the ticket + * \param len Length of the ticket. + * + * \return 0 if successful, or + * MBEDTLS_ERR_SSL_INVALID_MAC if not authentic, or + * MBEDTLS_ERR_SSL_SESSION_TICKET_EXPIRED if expired, or + * any other non-zero code for other failures. + */ +typedef int mbedtls_ssl_ticket_parse_t( void *p_ticket, + mbedtls_ssl_session *session, + unsigned char *buf, + size_t len ); + +#if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_SRV_C) +/** + * \brief Configure SSL session ticket callbacks (server only). + * (Default: none.) + * + * \note On server, session tickets are enabled by providing + * non-NULL callbacks. + * + * \note On client, use \c mbedtls_ssl_conf_session_tickets(). + * + * \param conf SSL configuration context + * \param f_ticket_write Callback for writing a ticket + * \param f_ticket_parse Callback for parsing a ticket + * \param p_ticket Context shared by the two callbacks + */ +void mbedtls_ssl_conf_session_tickets_cb( mbedtls_ssl_config *conf, + mbedtls_ssl_ticket_write_t *f_ticket_write, + mbedtls_ssl_ticket_parse_t *f_ticket_parse, + void *p_ticket ); +#endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_SRV_C */ + +#if defined(MBEDTLS_SSL_EXPORT_KEYS) +/** + * \brief Configure key export callback. + * (Default: none.) + * + * \note See \c mbedtls_ssl_export_keys_t. + * + * \param conf SSL configuration context + * \param f_export_keys Callback for exporting keys + * \param p_export_keys Context for the callback + */ +void mbedtls_ssl_conf_export_keys_cb( mbedtls_ssl_config *conf, + mbedtls_ssl_export_keys_t *f_export_keys, + void *p_export_keys ); +#endif /* MBEDTLS_SSL_EXPORT_KEYS */ + +#if defined(MBEDTLS_SSL_ASYNC_PRIVATE) +/** + * \brief Configure asynchronous private key operation callbacks. + * + * \param conf SSL configuration context + * \param f_async_sign Callback to start a signature operation. See + * the description of ::mbedtls_ssl_async_sign_t + * for more information. This may be \c NULL if the + * external processor does not support any signature + * operation; in this case the private key object + * associated with the certificate will be used. + * \param f_async_decrypt Callback to start a decryption operation. See + * the description of ::mbedtls_ssl_async_decrypt_t + * for more information. This may be \c NULL if the + * external processor does not support any decryption + * operation; in this case the private key object + * associated with the certificate will be used. + * \param f_async_resume Callback to resume an asynchronous operation. See + * the description of ::mbedtls_ssl_async_resume_t + * for more information. This may not be \c NULL unless + * \p f_async_sign and \p f_async_decrypt are both + * \c NULL. + * \param f_async_cancel Callback to cancel an asynchronous operation. See + * the description of ::mbedtls_ssl_async_cancel_t + * for more information. This may be \c NULL if + * no cleanup is needed. + * \param config_data A pointer to configuration data which can be + * retrieved with + * mbedtls_ssl_conf_get_async_config_data(). The + * library stores this value without dereferencing it. + */ +void mbedtls_ssl_conf_async_private_cb( mbedtls_ssl_config *conf, + mbedtls_ssl_async_sign_t *f_async_sign, + mbedtls_ssl_async_decrypt_t *f_async_decrypt, + mbedtls_ssl_async_resume_t *f_async_resume, + mbedtls_ssl_async_cancel_t *f_async_cancel, + void *config_data ); + +/** + * \brief Retrieve the configuration data set by + * mbedtls_ssl_conf_async_private_cb(). + * + * \param conf SSL configuration context + * \return The configuration data set by + * mbedtls_ssl_conf_async_private_cb(). + */ +void *mbedtls_ssl_conf_get_async_config_data( const mbedtls_ssl_config *conf ); + +/** + * \brief Retrieve the asynchronous operation user context. + * + * \note This function may only be called while a handshake + * is in progress. + * + * \param ssl The SSL context to access. + * + * \return The asynchronous operation user context that was last + * set during the current handshake. If + * mbedtls_ssl_set_async_operation_data() has not yet been + * called during the current handshake, this function returns + * \c NULL. + */ +void *mbedtls_ssl_get_async_operation_data( const mbedtls_ssl_context *ssl ); + +/** + * \brief Retrieve the asynchronous operation user context. + * + * \note This function may only be called while a handshake + * is in progress. + * + * \param ssl The SSL context to access. + * \param ctx The new value of the asynchronous operation user context. + * Call mbedtls_ssl_get_async_operation_data() later during the + * same handshake to retrieve this value. + */ +void mbedtls_ssl_set_async_operation_data( mbedtls_ssl_context *ssl, + void *ctx ); +#endif /* MBEDTLS_SSL_ASYNC_PRIVATE */ + +/** + * \brief Callback type: generate a cookie + * + * \param ctx Context for the callback + * \param p Buffer to write to, + * must be updated to point right after the cookie + * \param end Pointer to one past the end of the output buffer + * \param info Client ID info that was passed to + * \c mbedtls_ssl_set_client_transport_id() + * \param ilen Length of info in bytes + * + * \return The callback must return 0 on success, + * or a negative error code. + */ +typedef int mbedtls_ssl_cookie_write_t( void *ctx, + unsigned char **p, unsigned char *end, + const unsigned char *info, size_t ilen ); + +/** + * \brief Callback type: verify a cookie + * + * \param ctx Context for the callback + * \param cookie Cookie to verify + * \param clen Length of cookie + * \param info Client ID info that was passed to + * \c mbedtls_ssl_set_client_transport_id() + * \param ilen Length of info in bytes + * + * \return The callback must return 0 if cookie is valid, + * or a negative error code. + */ +typedef int mbedtls_ssl_cookie_check_t( void *ctx, + const unsigned char *cookie, size_t clen, + const unsigned char *info, size_t ilen ); + +#if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C) +/** + * \brief Register callbacks for DTLS cookies + * (Server only. DTLS only.) + * + * Default: dummy callbacks that fail, in order to force you to + * register working callbacks (and initialize their context). + * + * To disable HelloVerifyRequest, register NULL callbacks. + * + * \warning Disabling hello verification allows your server to be used + * for amplification in DoS attacks against other hosts. + * Only disable if you known this can't happen in your + * particular environment. + * + * \note See comments on \c mbedtls_ssl_handshake() about handling + * the MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED that is expected + * on the first handshake attempt when this is enabled. + * + * \note This is also necessary to handle client reconnection from + * the same port as described in RFC 6347 section 4.2.8 (only + * the variant with cookies is supported currently). See + * comments on \c mbedtls_ssl_read() for details. + * + * \param conf SSL configuration + * \param f_cookie_write Cookie write callback + * \param f_cookie_check Cookie check callback + * \param p_cookie Context for both callbacks + */ +void mbedtls_ssl_conf_dtls_cookies( mbedtls_ssl_config *conf, + mbedtls_ssl_cookie_write_t *f_cookie_write, + mbedtls_ssl_cookie_check_t *f_cookie_check, + void *p_cookie ); + +/** + * \brief Set client's transport-level identification info. + * (Server only. DTLS only.) + * + * This is usually the IP address (and port), but could be + * anything identify the client depending on the underlying + * network stack. Used for HelloVerifyRequest with DTLS. + * This is *not* used to route the actual packets. + * + * \param ssl SSL context + * \param info Transport-level info identifying the client (eg IP + port) + * \param ilen Length of info in bytes + * + * \note An internal copy is made, so the info buffer can be reused. + * + * \return 0 on success, + * MBEDTLS_ERR_SSL_BAD_INPUT_DATA if used on client, + * MBEDTLS_ERR_SSL_ALLOC_FAILED if out of memory. + */ +int mbedtls_ssl_set_client_transport_id( mbedtls_ssl_context *ssl, + const unsigned char *info, + size_t ilen ); + +#endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY && MBEDTLS_SSL_SRV_C */ + +#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) +/** + * \brief Enable or disable anti-replay protection for DTLS. + * (DTLS only, no effect on TLS.) + * Default: enabled. + * + * \param conf SSL configuration + * \param mode MBEDTLS_SSL_ANTI_REPLAY_ENABLED or MBEDTLS_SSL_ANTI_REPLAY_DISABLED. + * + * \warning Disabling this is a security risk unless the application + * protocol handles duplicated packets in a safe way. You + * should not disable this without careful consideration. + * However, if your application already detects duplicated + * packets and needs information about them to adjust its + * transmission strategy, then you'll want to disable this. + */ +void mbedtls_ssl_conf_dtls_anti_replay( mbedtls_ssl_config *conf, char mode ); +#endif /* MBEDTLS_SSL_DTLS_ANTI_REPLAY */ + +#if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT) +/** + * \brief Set a limit on the number of records with a bad MAC + * before terminating the connection. + * (DTLS only, no effect on TLS.) + * Default: 0 (disabled). + * + * \param conf SSL configuration + * \param limit Limit, or 0 to disable. + * + * \note If the limit is N, then the connection is terminated when + * the Nth non-authentic record is seen. + * + * \note Records with an invalid header are not counted, only the + * ones going through the authentication-decryption phase. + * + * \note This is a security trade-off related to the fact that it's + * often relatively easy for an active attacker ot inject UDP + * datagrams. On one hand, setting a low limit here makes it + * easier for such an attacker to forcibly terminated a + * connection. On the other hand, a high limit or no limit + * might make us waste resources checking authentication on + * many bogus packets. + */ +void mbedtls_ssl_conf_dtls_badmac_limit( mbedtls_ssl_config *conf, unsigned limit ); +#endif /* MBEDTLS_SSL_DTLS_BADMAC_LIMIT */ + +#if defined(MBEDTLS_SSL_PROTO_DTLS) + +/** + * \brief Allow or disallow packing of multiple handshake records + * within a single datagram. + * + * \param ssl The SSL context to configure. + * \param allow_packing This determines whether datagram packing may + * be used or not. A value of \c 0 means that every + * record will be sent in a separate datagram; a + * value of \c 1 means that, if space permits, + * multiple handshake messages (including CCS) belonging to + * a single flight may be packed within a single datagram. + * + * \note This is enabled by default and should only be disabled + * for test purposes, or if datagram packing causes + * interoperability issues with peers that don't support it. + * + * \note Allowing datagram packing reduces the network load since + * there's less overhead if multiple messages share the same + * datagram. Also, it increases the handshake efficiency + * since messages belonging to a single datagram will not + * be reordered in transit, and so future message buffering + * or flight retransmission (if no buffering is used) as + * means to deal with reordering are needed less frequently. + * + * \note Application records are not affected by this option and + * are currently always sent in separate datagrams. + * + */ +void mbedtls_ssl_set_datagram_packing( mbedtls_ssl_context *ssl, + unsigned allow_packing ); + +/** + * \brief Set retransmit timeout values for the DTLS handshake. + * (DTLS only, no effect on TLS.) + * + * \param conf SSL configuration + * \param min Initial timeout value in milliseconds. + * Default: 1000 (1 second). + * \param max Maximum timeout value in milliseconds. + * Default: 60000 (60 seconds). + * + * \note Default values are from RFC 6347 section 4.2.4.1. + * + * \note The 'min' value should typically be slightly above the + * expected round-trip time to your peer, plus whatever time + * it takes for the peer to process the message. For example, + * if your RTT is about 600ms and you peer needs up to 1s to + * do the cryptographic operations in the handshake, then you + * should set 'min' slightly above 1600. Lower values of 'min' + * might cause spurious resends which waste network resources, + * while larger value of 'min' will increase overall latency + * on unreliable network links. + * + * \note The more unreliable your network connection is, the larger + * your max / min ratio needs to be in order to achieve + * reliable handshakes. + * + * \note Messages are retransmitted up to log2(ceil(max/min)) times. + * For example, if min = 1s and max = 5s, the retransmit plan + * goes: send ... 1s -> resend ... 2s -> resend ... 4s -> + * resend ... 5s -> give up and return a timeout error. + */ +void mbedtls_ssl_conf_handshake_timeout( mbedtls_ssl_config *conf, uint32_t min, uint32_t max ); +#endif /* MBEDTLS_SSL_PROTO_DTLS */ + +#if defined(MBEDTLS_SSL_SRV_C) +/** + * \brief Set the session cache callbacks (server-side only) + * If not set, no session resuming is done (except if session + * tickets are enabled too). + * + * The session cache has the responsibility to check for stale + * entries based on timeout. See RFC 5246 for recommendations. + * + * Warning: session.peer_cert is cleared by the SSL/TLS layer on + * connection shutdown, so do not cache the pointer! Either set + * it to NULL or make a full copy of the certificate. + * + * The get callback is called once during the initial handshake + * to enable session resuming. The get function has the + * following parameters: (void *parameter, mbedtls_ssl_session *session) + * If a valid entry is found, it should fill the master of + * the session object with the cached values and return 0, + * return 1 otherwise. Optionally peer_cert can be set as well + * if it is properly present in cache entry. + * + * The set callback is called once during the initial handshake + * to enable session resuming after the entire handshake has + * been finished. The set function has the following parameters: + * (void *parameter, const mbedtls_ssl_session *session). The function + * should create a cache entry for future retrieval based on + * the data in the session structure and should keep in mind + * that the mbedtls_ssl_session object presented (and all its referenced + * data) is cleared by the SSL/TLS layer when the connection is + * terminated. It is recommended to add metadata to determine if + * an entry is still valid in the future. Return 0 if + * successfully cached, return 1 otherwise. + * + * \param conf SSL configuration + * \param p_cache parmater (context) for both callbacks + * \param f_get_cache session get callback + * \param f_set_cache session set callback + */ +void mbedtls_ssl_conf_session_cache( mbedtls_ssl_config *conf, + void *p_cache, + int (*f_get_cache)(void *, mbedtls_ssl_session *), + int (*f_set_cache)(void *, const mbedtls_ssl_session *) ); +#endif /* MBEDTLS_SSL_SRV_C */ + +#if defined(MBEDTLS_SSL_CLI_C) +/** + * \brief Request resumption of session (client-side only) + * Session data is copied from presented session structure. + * + * \param ssl SSL context + * \param session session context + * + * \return 0 if successful, + * MBEDTLS_ERR_SSL_ALLOC_FAILED if memory allocation failed, + * MBEDTLS_ERR_SSL_BAD_INPUT_DATA if used server-side or + * arguments are otherwise invalid + * + * \sa mbedtls_ssl_get_session() + */ +int mbedtls_ssl_set_session( mbedtls_ssl_context *ssl, const mbedtls_ssl_session *session ); +#endif /* MBEDTLS_SSL_CLI_C */ + +/** + * \brief Set the list of allowed ciphersuites and the preference + * order. First in the list has the highest preference. + * (Overrides all version-specific lists) + * + * The ciphersuites array is not copied, and must remain + * valid for the lifetime of the ssl_config. + * + * Note: The server uses its own preferences + * over the preference of the client unless + * MBEDTLS_SSL_SRV_RESPECT_CLIENT_PREFERENCE is defined! + * + * \param conf SSL configuration + * \param ciphersuites 0-terminated list of allowed ciphersuites + */ +void mbedtls_ssl_conf_ciphersuites( mbedtls_ssl_config *conf, + const int *ciphersuites ); + +/** + * \brief Set the list of allowed ciphersuites and the + * preference order for a specific version of the protocol. + * (Only useful on the server side) + * + * The ciphersuites array is not copied, and must remain + * valid for the lifetime of the ssl_config. + * + * \param conf SSL configuration + * \param ciphersuites 0-terminated list of allowed ciphersuites + * \param major Major version number (only MBEDTLS_SSL_MAJOR_VERSION_3 + * supported) + * \param minor Minor version number (MBEDTLS_SSL_MINOR_VERSION_0, + * MBEDTLS_SSL_MINOR_VERSION_1 and MBEDTLS_SSL_MINOR_VERSION_2, + * MBEDTLS_SSL_MINOR_VERSION_3 supported) + * + * \note With DTLS, use MBEDTLS_SSL_MINOR_VERSION_2 for DTLS 1.0 + * and MBEDTLS_SSL_MINOR_VERSION_3 for DTLS 1.2 + */ +void mbedtls_ssl_conf_ciphersuites_for_version( mbedtls_ssl_config *conf, + const int *ciphersuites, + int major, int minor ); + +#if defined(MBEDTLS_X509_CRT_PARSE_C) +/** + * \brief Set the X.509 security profile used for verification + * + * \note The restrictions are enforced for all certificates in the + * chain. However, signatures in the handshake are not covered + * by this setting but by \b mbedtls_ssl_conf_sig_hashes(). + * + * \param conf SSL configuration + * \param profile Profile to use + */ +void mbedtls_ssl_conf_cert_profile( mbedtls_ssl_config *conf, + const mbedtls_x509_crt_profile *profile ); + +/** + * \brief Set the data required to verify peer certificate + * + * \note See \c mbedtls_x509_crt_verify() for notes regarding the + * parameters ca_chain (maps to trust_ca for that function) + * and ca_crl. + * + * \param conf SSL configuration + * \param ca_chain trusted CA chain (meaning all fully trusted top-level CAs) + * \param ca_crl trusted CA CRLs + */ +void mbedtls_ssl_conf_ca_chain( mbedtls_ssl_config *conf, + mbedtls_x509_crt *ca_chain, + mbedtls_x509_crl *ca_crl ); + +/** + * \brief Set own certificate chain and private key + * + * \note own_cert should contain in order from the bottom up your + * certificate chain. The top certificate (self-signed) + * can be omitted. + * + * \note On server, this function can be called multiple times to + * provision more than one cert/key pair (eg one ECDSA, one + * RSA with SHA-256, one RSA with SHA-1). An adequate + * certificate will be selected according to the client's + * advertised capabilities. In case multiple certificates are + * adequate, preference is given to the one set by the first + * call to this function, then second, etc. + * + * \note On client, only the first call has any effect. That is, + * only one client certificate can be provisioned. The + * server's preferences in its CertficateRequest message will + * be ignored and our only cert will be sent regardless of + * whether it matches those preferences - the server can then + * decide what it wants to do with it. + * + * \note The provided \p pk_key needs to match the public key in the + * first certificate in \p own_cert, or all handshakes using + * that certificate will fail. It is your responsibility + * to ensure that; this function will not perform any check. + * You may use mbedtls_pk_check_pair() in order to perform + * this check yourself, but be aware that this function can + * be computationally expensive on some key types. + * + * \param conf SSL configuration + * \param own_cert own public certificate chain + * \param pk_key own private key + * + * \return 0 on success or MBEDTLS_ERR_SSL_ALLOC_FAILED + */ +int mbedtls_ssl_conf_own_cert( mbedtls_ssl_config *conf, + mbedtls_x509_crt *own_cert, + mbedtls_pk_context *pk_key ); +#endif /* MBEDTLS_X509_CRT_PARSE_C */ + +#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED) +/** + * \brief Set the Pre Shared Key (PSK) and the expected identity name + * + * \note This is mainly useful for clients. Servers will usually + * want to use \c mbedtls_ssl_conf_psk_cb() instead. + * + * \note Currently clients can only register one pre-shared key. + * In other words, the servers' identity hint is ignored. + * Support for setting multiple PSKs on clients and selecting + * one based on the identity hint is not a planned feature but + * feedback is welcomed. + * + * \param conf SSL configuration + * \param psk pointer to the pre-shared key + * \param psk_len pre-shared key length + * \param psk_identity pointer to the pre-shared key identity + * \param psk_identity_len identity key length + * + * \return 0 if successful or MBEDTLS_ERR_SSL_ALLOC_FAILED + */ +int mbedtls_ssl_conf_psk( mbedtls_ssl_config *conf, + const unsigned char *psk, size_t psk_len, + const unsigned char *psk_identity, size_t psk_identity_len ); + + +/** + * \brief Set the Pre Shared Key (PSK) for the current handshake + * + * \note This should only be called inside the PSK callback, + * ie the function passed to \c mbedtls_ssl_conf_psk_cb(). + * + * \param ssl SSL context + * \param psk pointer to the pre-shared key + * \param psk_len pre-shared key length + * + * \return 0 if successful or MBEDTLS_ERR_SSL_ALLOC_FAILED + */ +int mbedtls_ssl_set_hs_psk( mbedtls_ssl_context *ssl, + const unsigned char *psk, size_t psk_len ); + +/** + * \brief Set the PSK callback (server-side only). + * + * If set, the PSK callback is called for each + * handshake where a PSK ciphersuite was negotiated. + * The caller provides the identity received and wants to + * receive the actual PSK data and length. + * + * The callback has the following parameters: (void *parameter, + * mbedtls_ssl_context *ssl, const unsigned char *psk_identity, + * size_t identity_len) + * If a valid PSK identity is found, the callback should use + * \c mbedtls_ssl_set_hs_psk() on the ssl context to set the + * correct PSK and return 0. + * Any other return value will result in a denied PSK identity. + * + * \note If you set a PSK callback using this function, then you + * don't need to set a PSK key and identity using + * \c mbedtls_ssl_conf_psk(). + * + * \param conf SSL configuration + * \param f_psk PSK identity function + * \param p_psk PSK identity parameter + */ +void mbedtls_ssl_conf_psk_cb( mbedtls_ssl_config *conf, + int (*f_psk)(void *, mbedtls_ssl_context *, const unsigned char *, + size_t), + void *p_psk ); +#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */ + +#if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_SRV_C) + +#if !defined(MBEDTLS_DEPRECATED_REMOVED) + +#if defined(MBEDTLS_DEPRECATED_WARNING) +#define MBEDTLS_DEPRECATED __attribute__((deprecated)) +#else +#define MBEDTLS_DEPRECATED +#endif + +/** + * \brief Set the Diffie-Hellman public P and G values, + * read as hexadecimal strings (server-side only) + * (Default values: MBEDTLS_DHM_RFC3526_MODP_2048_[PG]) + * + * \param conf SSL configuration + * \param dhm_P Diffie-Hellman-Merkle modulus + * \param dhm_G Diffie-Hellman-Merkle generator + * + * \deprecated Superseded by \c mbedtls_ssl_conf_dh_param_bin. + * + * \return 0 if successful + */ +MBEDTLS_DEPRECATED int mbedtls_ssl_conf_dh_param( mbedtls_ssl_config *conf, + const char *dhm_P, + const char *dhm_G ); + +#endif /* MBEDTLS_DEPRECATED_REMOVED */ + +/** + * \brief Set the Diffie-Hellman public P and G values + * from big-endian binary presentations. + * (Default values: MBEDTLS_DHM_RFC3526_MODP_2048_[PG]_BIN) + * + * \param conf SSL configuration + * \param dhm_P Diffie-Hellman-Merkle modulus in big-endian binary form + * \param P_len Length of DHM modulus + * \param dhm_G Diffie-Hellman-Merkle generator in big-endian binary form + * \param G_len Length of DHM generator + * + * \return 0 if successful + */ +int mbedtls_ssl_conf_dh_param_bin( mbedtls_ssl_config *conf, + const unsigned char *dhm_P, size_t P_len, + const unsigned char *dhm_G, size_t G_len ); + +/** + * \brief Set the Diffie-Hellman public P and G values, + * read from existing context (server-side only) + * + * \param conf SSL configuration + * \param dhm_ctx Diffie-Hellman-Merkle context + * + * \return 0 if successful + */ +int mbedtls_ssl_conf_dh_param_ctx( mbedtls_ssl_config *conf, mbedtls_dhm_context *dhm_ctx ); +#endif /* MBEDTLS_DHM_C && defined(MBEDTLS_SSL_SRV_C) */ + +#if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_CLI_C) +/** + * \brief Set the minimum length for Diffie-Hellman parameters. + * (Client-side only.) + * (Default: 1024 bits.) + * + * \param conf SSL configuration + * \param bitlen Minimum bit length of the DHM prime + */ +void mbedtls_ssl_conf_dhm_min_bitlen( mbedtls_ssl_config *conf, + unsigned int bitlen ); +#endif /* MBEDTLS_DHM_C && MBEDTLS_SSL_CLI_C */ + +#if defined(MBEDTLS_ECP_C) +/** + * \brief Set the allowed curves in order of preference. + * (Default: all defined curves.) + * + * On server: this only affects selection of the ECDHE curve; + * the curves used for ECDH and ECDSA are determined by the + * list of available certificates instead. + * + * On client: this affects the list of curves offered for any + * use. The server can override our preference order. + * + * Both sides: limits the set of curves accepted for use in + * ECDHE and in the peer's end-entity certificate. + * + * \note This has no influence on which curves are allowed inside the + * certificate chains, see \c mbedtls_ssl_conf_cert_profile() + * for that. For the end-entity certificate however, the key + * will be accepted only if it is allowed both by this list + * and by the cert profile. + * + * \note This list should be ordered by decreasing preference + * (preferred curve first). + * + * \param conf SSL configuration + * \param curves Ordered list of allowed curves, + * terminated by MBEDTLS_ECP_DP_NONE. + */ +void mbedtls_ssl_conf_curves( mbedtls_ssl_config *conf, + const mbedtls_ecp_group_id *curves ); +#endif /* MBEDTLS_ECP_C */ + +#if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED) +/** + * \brief Set the allowed hashes for signatures during the handshake. + * (Default: all available hashes except MD5.) + * + * \note This only affects which hashes are offered and can be used + * for signatures during the handshake. Hashes for message + * authentication and the TLS PRF are controlled by the + * ciphersuite, see \c mbedtls_ssl_conf_ciphersuites(). Hashes + * used for certificate signature are controlled by the + * verification profile, see \c mbedtls_ssl_conf_cert_profile(). + * + * \note This list should be ordered by decreasing preference + * (preferred hash first). + * + * \param conf SSL configuration + * \param hashes Ordered list of allowed signature hashes, + * terminated by \c MBEDTLS_MD_NONE. + */ +void mbedtls_ssl_conf_sig_hashes( mbedtls_ssl_config *conf, + const int *hashes ); +#endif /* MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */ + +#if defined(MBEDTLS_X509_CRT_PARSE_C) +/** + * \brief Set or reset the hostname to check against the received + * server certificate. It sets the ServerName TLS extension, + * too, if that extension is enabled. (client-side only) + * + * \param ssl SSL context + * \param hostname the server hostname, may be NULL to clear hostname + + * \note Maximum hostname length MBEDTLS_SSL_MAX_HOST_NAME_LEN. + * + * \return 0 if successful, MBEDTLS_ERR_SSL_ALLOC_FAILED on + * allocation failure, MBEDTLS_ERR_SSL_BAD_INPUT_DATA on + * too long input hostname. + * + * Hostname set to the one provided on success (cleared + * when NULL). On allocation failure hostname is cleared. + * On too long input failure, old hostname is unchanged. + */ +int mbedtls_ssl_set_hostname( mbedtls_ssl_context *ssl, const char *hostname ); +#endif /* MBEDTLS_X509_CRT_PARSE_C */ + +#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) +/** + * \brief Set own certificate and key for the current handshake + * + * \note Same as \c mbedtls_ssl_conf_own_cert() but for use within + * the SNI callback. + * + * \param ssl SSL context + * \param own_cert own public certificate chain + * \param pk_key own private key + * + * \return 0 on success or MBEDTLS_ERR_SSL_ALLOC_FAILED + */ +int mbedtls_ssl_set_hs_own_cert( mbedtls_ssl_context *ssl, + mbedtls_x509_crt *own_cert, + mbedtls_pk_context *pk_key ); + +/** + * \brief Set the data required to verify peer certificate for the + * current handshake + * + * \note Same as \c mbedtls_ssl_conf_ca_chain() but for use within + * the SNI callback. + * + * \param ssl SSL context + * \param ca_chain trusted CA chain (meaning all fully trusted top-level CAs) + * \param ca_crl trusted CA CRLs + */ +void mbedtls_ssl_set_hs_ca_chain( mbedtls_ssl_context *ssl, + mbedtls_x509_crt *ca_chain, + mbedtls_x509_crl *ca_crl ); + +/** + * \brief Set authmode for the current handshake. + * + * \note Same as \c mbedtls_ssl_conf_authmode() but for use within + * the SNI callback. + * + * \param ssl SSL context + * \param authmode MBEDTLS_SSL_VERIFY_NONE, MBEDTLS_SSL_VERIFY_OPTIONAL or + * MBEDTLS_SSL_VERIFY_REQUIRED + */ +void mbedtls_ssl_set_hs_authmode( mbedtls_ssl_context *ssl, + int authmode ); + +/** + * \brief Set server side ServerName TLS extension callback + * (optional, server-side only). + * + * If set, the ServerName callback is called whenever the + * server receives a ServerName TLS extension from the client + * during a handshake. The ServerName callback has the + * following parameters: (void *parameter, mbedtls_ssl_context *ssl, + * const unsigned char *hostname, size_t len). If a suitable + * certificate is found, the callback must set the + * certificate(s) and key(s) to use with \c + * mbedtls_ssl_set_hs_own_cert() (can be called repeatedly), + * and may optionally adjust the CA and associated CRL with \c + * mbedtls_ssl_set_hs_ca_chain() as well as the client + * authentication mode with \c mbedtls_ssl_set_hs_authmode(), + * then must return 0. If no matching name is found, the + * callback must either set a default cert, or + * return non-zero to abort the handshake at this point. + * + * \param conf SSL configuration + * \param f_sni verification function + * \param p_sni verification parameter + */ +void mbedtls_ssl_conf_sni( mbedtls_ssl_config *conf, + int (*f_sni)(void *, mbedtls_ssl_context *, const unsigned char *, + size_t), + void *p_sni ); +#endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */ + +#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) +/** + * \brief Set the EC J-PAKE password for current handshake. + * + * \note An internal copy is made, and destroyed as soon as the + * handshake is completed, or when the SSL context is reset or + * freed. + * + * \note The SSL context needs to be already set up. The right place + * to call this function is between \c mbedtls_ssl_setup() or + * \c mbedtls_ssl_reset() and \c mbedtls_ssl_handshake(). + * + * \param ssl SSL context + * \param pw EC J-PAKE password (pre-shared secret) + * \param pw_len length of pw in bytes + * + * \return 0 on success, or a negative error code. + */ +int mbedtls_ssl_set_hs_ecjpake_password( mbedtls_ssl_context *ssl, + const unsigned char *pw, + size_t pw_len ); +#endif /*MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */ + +#if defined(MBEDTLS_SSL_ALPN) +/** + * \brief Set the supported Application Layer Protocols. + * + * \param conf SSL configuration + * \param protos Pointer to a NULL-terminated list of supported protocols, + * in decreasing preference order. The pointer to the list is + * recorded by the library for later reference as required, so + * the lifetime of the table must be atleast as long as the + * lifetime of the SSL configuration structure. + * + * \return 0 on success, or MBEDTLS_ERR_SSL_BAD_INPUT_DATA. + */ +int mbedtls_ssl_conf_alpn_protocols( mbedtls_ssl_config *conf, const char **protos ); + +/** + * \brief Get the name of the negotiated Application Layer Protocol. + * This function should be called after the handshake is + * completed. + * + * \param ssl SSL context + * + * \return Protcol name, or NULL if no protocol was negotiated. + */ +const char *mbedtls_ssl_get_alpn_protocol( const mbedtls_ssl_context *ssl ); +#endif /* MBEDTLS_SSL_ALPN */ + +/** + * \brief Set the maximum supported version sent from the client side + * and/or accepted at the server side + * (Default: MBEDTLS_SSL_MAX_MAJOR_VERSION, MBEDTLS_SSL_MAX_MINOR_VERSION) + * + * \note This ignores ciphersuites from higher versions. + * + * \note With DTLS, use MBEDTLS_SSL_MINOR_VERSION_2 for DTLS 1.0 and + * MBEDTLS_SSL_MINOR_VERSION_3 for DTLS 1.2 + * + * \param conf SSL configuration + * \param major Major version number (only MBEDTLS_SSL_MAJOR_VERSION_3 supported) + * \param minor Minor version number (MBEDTLS_SSL_MINOR_VERSION_0, + * MBEDTLS_SSL_MINOR_VERSION_1 and MBEDTLS_SSL_MINOR_VERSION_2, + * MBEDTLS_SSL_MINOR_VERSION_3 supported) + */ +void mbedtls_ssl_conf_max_version( mbedtls_ssl_config *conf, int major, int minor ); + +/** + * \brief Set the minimum accepted SSL/TLS protocol version + * (Default: TLS 1.0) + * + * \note Input outside of the SSL_MAX_XXXXX_VERSION and + * SSL_MIN_XXXXX_VERSION range is ignored. + * + * \note MBEDTLS_SSL_MINOR_VERSION_0 (SSL v3) should be avoided. + * + * \note With DTLS, use MBEDTLS_SSL_MINOR_VERSION_2 for DTLS 1.0 and + * MBEDTLS_SSL_MINOR_VERSION_3 for DTLS 1.2 + * + * \param conf SSL configuration + * \param major Major version number (only MBEDTLS_SSL_MAJOR_VERSION_3 supported) + * \param minor Minor version number (MBEDTLS_SSL_MINOR_VERSION_0, + * MBEDTLS_SSL_MINOR_VERSION_1 and MBEDTLS_SSL_MINOR_VERSION_2, + * MBEDTLS_SSL_MINOR_VERSION_3 supported) + */ +void mbedtls_ssl_conf_min_version( mbedtls_ssl_config *conf, int major, int minor ); + +#if defined(MBEDTLS_SSL_FALLBACK_SCSV) && defined(MBEDTLS_SSL_CLI_C) +/** + * \brief Set the fallback flag (client-side only). + * (Default: MBEDTLS_SSL_IS_NOT_FALLBACK). + * + * \note Set to MBEDTLS_SSL_IS_FALLBACK when preparing a fallback + * connection, that is a connection with max_version set to a + * lower value than the value you're willing to use. Such + * fallback connections are not recommended but are sometimes + * necessary to interoperate with buggy (version-intolerant) + * servers. + * + * \warning You should NOT set this to MBEDTLS_SSL_IS_FALLBACK for + * non-fallback connections! This would appear to work for a + * while, then cause failures when the server is upgraded to + * support a newer TLS version. + * + * \param conf SSL configuration + * \param fallback MBEDTLS_SSL_IS_NOT_FALLBACK or MBEDTLS_SSL_IS_FALLBACK + */ +void mbedtls_ssl_conf_fallback( mbedtls_ssl_config *conf, char fallback ); +#endif /* MBEDTLS_SSL_FALLBACK_SCSV && MBEDTLS_SSL_CLI_C */ + +#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) +/** + * \brief Enable or disable Encrypt-then-MAC + * (Default: MBEDTLS_SSL_ETM_ENABLED) + * + * \note This should always be enabled, it is a security + * improvement, and should not cause any interoperability + * issue (used only if the peer supports it too). + * + * \param conf SSL configuration + * \param etm MBEDTLS_SSL_ETM_ENABLED or MBEDTLS_SSL_ETM_DISABLED + */ +void mbedtls_ssl_conf_encrypt_then_mac( mbedtls_ssl_config *conf, char etm ); +#endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */ + +#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET) +/** + * \brief Enable or disable Extended Master Secret negotiation. + * (Default: MBEDTLS_SSL_EXTENDED_MS_ENABLED) + * + * \note This should always be enabled, it is a security fix to the + * protocol, and should not cause any interoperability issue + * (used only if the peer supports it too). + * + * \param conf SSL configuration + * \param ems MBEDTLS_SSL_EXTENDED_MS_ENABLED or MBEDTLS_SSL_EXTENDED_MS_DISABLED + */ +void mbedtls_ssl_conf_extended_master_secret( mbedtls_ssl_config *conf, char ems ); +#endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */ + +#if defined(MBEDTLS_ARC4_C) +/** + * \brief Disable or enable support for RC4 + * (Default: MBEDTLS_SSL_ARC4_DISABLED) + * + * \warning Use of RC4 in DTLS/TLS has been prohibited by RFC 7465 + * for security reasons. Use at your own risk. + * + * \note This function is deprecated and will likely be removed in + * a future version of the library. + * RC4 is disabled by default at compile time and needs to be + * actively enabled for use with legacy systems. + * + * \param conf SSL configuration + * \param arc4 MBEDTLS_SSL_ARC4_ENABLED or MBEDTLS_SSL_ARC4_DISABLED + */ +void mbedtls_ssl_conf_arc4_support( mbedtls_ssl_config *conf, char arc4 ); +#endif /* MBEDTLS_ARC4_C */ + +#if defined(MBEDTLS_SSL_SRV_C) +/** + * \brief Whether to send a list of acceptable CAs in + * CertificateRequest messages. + * (Default: do send) + * + * \param conf SSL configuration + * \param cert_req_ca_list MBEDTLS_SSL_CERT_REQ_CA_LIST_ENABLED or + * MBEDTLS_SSL_CERT_REQ_CA_LIST_DISABLED + */ +void mbedtls_ssl_conf_cert_req_ca_list( mbedtls_ssl_config *conf, + char cert_req_ca_list ); +#endif /* MBEDTLS_SSL_SRV_C */ + +#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) +/** + * \brief Set the maximum fragment length to emit and/or negotiate. + * (Typical: the smaller of #MBEDTLS_SSL_IN_CONTENT_LEN and + * #MBEDTLS_SSL_OUT_CONTENT_LEN, usually `2^14` bytes) + * (Server: set maximum fragment length to emit, + * usually negotiated by the client during handshake) + * (Client: set maximum fragment length to emit *and* + * negotiate with the server during handshake) + * (Default: #MBEDTLS_SSL_MAX_FRAG_LEN_NONE) + * + * \note On the client side, the maximum fragment length extension + * *will not* be used, unless the maximum fragment length has + * been set via this function to a value different than + * #MBEDTLS_SSL_MAX_FRAG_LEN_NONE. + * + * \note This sets the maximum length for a record's payload, + * excluding record overhead that will be added to it, see + * \c mbedtls_ssl_get_record_expansion(). + * + * \note With TLS, this currently only affects ApplicationData (sent + * with \c mbedtls_ssl_read()), not handshake messages. + * With DTLS, this affects both ApplicationData and handshake. + * + * \note For DTLS, it is also possible to set a limit for the total + * size of daragrams passed to the transport layer, including + * record overhead, see \c mbedtls_ssl_set_mtu(). + * + * \param conf SSL configuration + * \param mfl_code Code for maximum fragment length (allowed values: + * MBEDTLS_SSL_MAX_FRAG_LEN_512, MBEDTLS_SSL_MAX_FRAG_LEN_1024, + * MBEDTLS_SSL_MAX_FRAG_LEN_2048, MBEDTLS_SSL_MAX_FRAG_LEN_4096) + * + * \return 0 if successful or MBEDTLS_ERR_SSL_BAD_INPUT_DATA + */ +int mbedtls_ssl_conf_max_frag_len( mbedtls_ssl_config *conf, unsigned char mfl_code ); +#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */ + +#if defined(MBEDTLS_SSL_TRUNCATED_HMAC) +/** + * \brief Activate negotiation of truncated HMAC + * (Default: MBEDTLS_SSL_TRUNC_HMAC_DISABLED) + * + * \param conf SSL configuration + * \param truncate Enable or disable (MBEDTLS_SSL_TRUNC_HMAC_ENABLED or + * MBEDTLS_SSL_TRUNC_HMAC_DISABLED) + */ +void mbedtls_ssl_conf_truncated_hmac( mbedtls_ssl_config *conf, int truncate ); +#endif /* MBEDTLS_SSL_TRUNCATED_HMAC */ + +#if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING) +/** + * \brief Enable / Disable 1/n-1 record splitting + * (Default: MBEDTLS_SSL_CBC_RECORD_SPLITTING_ENABLED) + * + * \note Only affects SSLv3 and TLS 1.0, not higher versions. + * Does not affect non-CBC ciphersuites in any version. + * + * \param conf SSL configuration + * \param split MBEDTLS_SSL_CBC_RECORD_SPLITTING_ENABLED or + * MBEDTLS_SSL_CBC_RECORD_SPLITTING_DISABLED + */ +void mbedtls_ssl_conf_cbc_record_splitting( mbedtls_ssl_config *conf, char split ); +#endif /* MBEDTLS_SSL_CBC_RECORD_SPLITTING */ + +#if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C) +/** + * \brief Enable / Disable session tickets (client only). + * (Default: MBEDTLS_SSL_SESSION_TICKETS_ENABLED.) + * + * \note On server, use \c mbedtls_ssl_conf_session_tickets_cb(). + * + * \param conf SSL configuration + * \param use_tickets Enable or disable (MBEDTLS_SSL_SESSION_TICKETS_ENABLED or + * MBEDTLS_SSL_SESSION_TICKETS_DISABLED) + */ +void mbedtls_ssl_conf_session_tickets( mbedtls_ssl_config *conf, int use_tickets ); +#endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_CLI_C */ + +#if defined(MBEDTLS_SSL_RENEGOTIATION) +/** + * \brief Enable / Disable renegotiation support for connection when + * initiated by peer + * (Default: MBEDTLS_SSL_RENEGOTIATION_DISABLED) + * + * \warning It is recommended to always disable renegotation unless you + * know you need it and you know what you're doing. In the + * past, there have been several issues associated with + * renegotiation or a poor understanding of its properties. + * + * \note Server-side, enabling renegotiation also makes the server + * susceptible to a resource DoS by a malicious client. + * + * \param conf SSL configuration + * \param renegotiation Enable or disable (MBEDTLS_SSL_RENEGOTIATION_ENABLED or + * MBEDTLS_SSL_RENEGOTIATION_DISABLED) + */ +void mbedtls_ssl_conf_renegotiation( mbedtls_ssl_config *conf, int renegotiation ); +#endif /* MBEDTLS_SSL_RENEGOTIATION */ + +/** + * \brief Prevent or allow legacy renegotiation. + * (Default: MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION) + * + * MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION allows connections to + * be established even if the peer does not support + * secure renegotiation, but does not allow renegotiation + * to take place if not secure. + * (Interoperable and secure option) + * + * MBEDTLS_SSL_LEGACY_ALLOW_RENEGOTIATION allows renegotiations + * with non-upgraded peers. Allowing legacy renegotiation + * makes the connection vulnerable to specific man in the + * middle attacks. (See RFC 5746) + * (Most interoperable and least secure option) + * + * MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE breaks off connections + * if peer does not support secure renegotiation. Results + * in interoperability issues with non-upgraded peers + * that do not support renegotiation altogether. + * (Most secure option, interoperability issues) + * + * \param conf SSL configuration + * \param allow_legacy Prevent or allow (SSL_NO_LEGACY_RENEGOTIATION, + * SSL_ALLOW_LEGACY_RENEGOTIATION or + * MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE) + */ +void mbedtls_ssl_conf_legacy_renegotiation( mbedtls_ssl_config *conf, int allow_legacy ); + +#if defined(MBEDTLS_SSL_RENEGOTIATION) +/** + * \brief Enforce renegotiation requests. + * (Default: enforced, max_records = 16) + * + * When we request a renegotiation, the peer can comply or + * ignore the request. This function allows us to decide + * whether to enforce our renegotiation requests by closing + * the connection if the peer doesn't comply. + * + * However, records could already be in transit from the peer + * when the request is emitted. In order to increase + * reliability, we can accept a number of records before the + * expected handshake records. + * + * The optimal value is highly dependent on the specific usage + * scenario. + * + * \note With DTLS and server-initiated renegotiation, the + * HelloRequest is retransmited every time mbedtls_ssl_read() times + * out or receives Application Data, until: + * - max_records records have beens seen, if it is >= 0, or + * - the number of retransmits that would happen during an + * actual handshake has been reached. + * Please remember the request might be lost a few times + * if you consider setting max_records to a really low value. + * + * \warning On client, the grace period can only happen during + * mbedtls_ssl_read(), as opposed to mbedtls_ssl_write() and mbedtls_ssl_renegotiate() + * which always behave as if max_record was 0. The reason is, + * if we receive application data from the server, we need a + * place to write it, which only happens during mbedtls_ssl_read(). + * + * \param conf SSL configuration + * \param max_records Use MBEDTLS_SSL_RENEGOTIATION_NOT_ENFORCED if you don't want to + * enforce renegotiation, or a non-negative value to enforce + * it but allow for a grace period of max_records records. + */ +void mbedtls_ssl_conf_renegotiation_enforced( mbedtls_ssl_config *conf, int max_records ); + +/** + * \brief Set record counter threshold for periodic renegotiation. + * (Default: 2^48 - 1) + * + * Renegotiation is automatically triggered when a record + * counter (outgoing or ingoing) crosses the defined + * threshold. The default value is meant to prevent the + * connection from being closed when the counter is about to + * reached its maximal value (it is not allowed to wrap). + * + * Lower values can be used to enforce policies such as "keys + * must be refreshed every N packets with cipher X". + * + * The renegotiation period can be disabled by setting + * conf->disable_renegotiation to + * MBEDTLS_SSL_RENEGOTIATION_DISABLED. + * + * \note When the configured transport is + * MBEDTLS_SSL_TRANSPORT_DATAGRAM the maximum renegotiation + * period is 2^48 - 1, and for MBEDTLS_SSL_TRANSPORT_STREAM, + * the maximum renegotiation period is 2^64 - 1. + * + * \param conf SSL configuration + * \param period The threshold value: a big-endian 64-bit number. + */ +void mbedtls_ssl_conf_renegotiation_period( mbedtls_ssl_config *conf, + const unsigned char period[8] ); +#endif /* MBEDTLS_SSL_RENEGOTIATION */ + +/** + * \brief Check if there is data already read from the + * underlying transport but not yet processed. + * + * \param ssl SSL context + * + * \return 0 if nothing's pending, 1 otherwise. + * + * \note This is different in purpose and behaviour from + * \c mbedtls_ssl_get_bytes_avail in that it considers + * any kind of unprocessed data, not only unread + * application data. If \c mbedtls_ssl_get_bytes + * returns a non-zero value, this function will + * also signal pending data, but the converse does + * not hold. For example, in DTLS there might be + * further records waiting to be processed from + * the current underlying transport's datagram. + * + * \note If this function returns 1 (data pending), this + * does not imply that a subsequent call to + * \c mbedtls_ssl_read will provide any data; + * e.g., the unprocessed data might turn out + * to be an alert or a handshake message. + * + * \note This function is useful in the following situation: + * If the SSL/TLS module successfully returns from an + * operation - e.g. a handshake or an application record + * read - and you're awaiting incoming data next, you + * must not immediately idle on the underlying transport + * to have data ready, but you need to check the value + * of this function first. The reason is that the desired + * data might already be read but not yet processed. + * If, in contrast, a previous call to the SSL/TLS module + * returned MBEDTLS_ERR_SSL_WANT_READ, it is not necessary + * to call this function, as the latter error code entails + * that all internal data has been processed. + * + */ +int mbedtls_ssl_check_pending( const mbedtls_ssl_context *ssl ); + +/** + * \brief Return the number of application data bytes + * remaining to be read from the current record. + * + * \param ssl SSL context + * + * \return How many bytes are available in the application + * data record read buffer. + * + * \note When working over a datagram transport, this is + * useful to detect the current datagram's boundary + * in case \c mbedtls_ssl_read has written the maximal + * amount of data fitting into the input buffer. + * + */ +size_t mbedtls_ssl_get_bytes_avail( const mbedtls_ssl_context *ssl ); + +/** + * \brief Return the result of the certificate verification + * + * \param ssl The SSL context to use. + * + * \return \c 0 if the certificate verification was successful. + * \return \c -1u if the result is not available. This may happen + * e.g. if the handshake aborts early, or a verification + * callback returned a fatal error. + * \return A bitwise combination of \c MBEDTLS_X509_BADCERT_XXX + * and \c MBEDTLS_X509_BADCRL_XXX failure flags; see x509.h. + */ +uint32_t mbedtls_ssl_get_verify_result( const mbedtls_ssl_context *ssl ); + +/** + * \brief Return the name of the current ciphersuite + * + * \param ssl SSL context + * + * \return a string containing the ciphersuite name + */ +const char *mbedtls_ssl_get_ciphersuite( const mbedtls_ssl_context *ssl ); + +/** + * \brief Return the current SSL version (SSLv3/TLSv1/etc) + * + * \param ssl SSL context + * + * \return a string containing the SSL version + */ +const char *mbedtls_ssl_get_version( const mbedtls_ssl_context *ssl ); + +/** + * \brief Return the (maximum) number of bytes added by the record + * layer: header + encryption/MAC overhead (inc. padding) + * + * \note This function is not available (always returns an error) + * when record compression is enabled. + * + * \param ssl SSL context + * + * \return Current maximum record expansion in bytes, or + * MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE if compression is + * enabled, which makes expansion much less predictable + */ +int mbedtls_ssl_get_record_expansion( const mbedtls_ssl_context *ssl ); + +#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) +/** + * \brief Return the maximum fragment length (payload, in bytes). + * This is the value negotiated with peer if any, + * or the locally configured value. + * + * \sa mbedtls_ssl_conf_max_frag_len() + * \sa mbedtls_ssl_get_max_record_payload() + * + * \param ssl SSL context + * + * \return Current maximum fragment length. + */ +size_t mbedtls_ssl_get_max_frag_len( const mbedtls_ssl_context *ssl ); +#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */ + +/** + * \brief Return the current maximum outgoing record payload in bytes. + * This takes into account the config.h setting \c + * MBEDTLS_SSL_OUT_CONTENT_LEN, the configured and negotiated + * max fragment length extension if used, and for DTLS the + * path MTU as configured and current record expansion. + * + * \note With DTLS, \c mbedtls_ssl_write() will return an error if + * called with a larger length value. + * With TLS, \c mbedtls_ssl_write() will fragment the input if + * necessary and return the number of bytes written; it is up + * to the caller to call \c mbedtls_ssl_write() again in + * order to send the remaining bytes if any. + * + * \note This function is not available (always returns an error) + * when record compression is enabled. + * + * \sa mbedtls_ssl_set_mtu() + * \sa mbedtls_ssl_get_max_frag_len() + * \sa mbedtls_ssl_get_record_expansion() + * + * \param ssl SSL context + * + * \return Current maximum payload for an outgoing record, + * or a negative error code. + */ +int mbedtls_ssl_get_max_out_record_payload( const mbedtls_ssl_context *ssl ); + +#if defined(MBEDTLS_X509_CRT_PARSE_C) +/** + * \brief Return the peer certificate from the current connection + * + * Note: Can be NULL in case no certificate was sent during + * the handshake. Different calls for the same connection can + * return the same or different pointers for the same + * certificate and even a different certificate altogether. + * The peer cert CAN change in a single connection if + * renegotiation is performed. + * + * \param ssl SSL context + * + * \return the current peer certificate + */ +const mbedtls_x509_crt *mbedtls_ssl_get_peer_cert( const mbedtls_ssl_context *ssl ); +#endif /* MBEDTLS_X509_CRT_PARSE_C */ + +#if defined(MBEDTLS_SSL_CLI_C) +/** + * \brief Save session in order to resume it later (client-side only) + * Session data is copied to presented session structure. + * + * + * \param ssl SSL context + * \param session session context + * + * \return 0 if successful, + * MBEDTLS_ERR_SSL_ALLOC_FAILED if memory allocation failed, + * MBEDTLS_ERR_SSL_BAD_INPUT_DATA if used server-side or + * arguments are otherwise invalid. + * + * \note Only the server certificate is copied, and not the full chain, + * so you should not attempt to validate the certificate again + * by calling \c mbedtls_x509_crt_verify() on it. + * Instead, you should use the results from the verification + * in the original handshake by calling \c mbedtls_ssl_get_verify_result() + * after loading the session again into a new SSL context + * using \c mbedtls_ssl_set_session(). + * + * \note Once the session object is not needed anymore, you should + * free it by calling \c mbedtls_ssl_session_free(). + * + * \sa mbedtls_ssl_set_session() + */ +int mbedtls_ssl_get_session( const mbedtls_ssl_context *ssl, mbedtls_ssl_session *session ); +#endif /* MBEDTLS_SSL_CLI_C */ + +/** + * \brief Perform the SSL handshake + * + * \param ssl SSL context + * + * \return \c 0 if successful. + * \return #MBEDTLS_ERR_SSL_WANT_READ or #MBEDTLS_ERR_SSL_WANT_WRITE + * if the handshake is incomplete and waiting for data to + * be available for reading from or writing to the underlying + * transport - in this case you must call this function again + * when the underlying transport is ready for the operation. + * \return #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS if an asynchronous + * operation is in progress (see + * mbedtls_ssl_conf_async_private_cb()) - in this case you + * must call this function again when the operation is ready. + * \return #MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS if a cryptographic + * operation is in progress (see mbedtls_ecp_set_max_ops()) - + * in this case you must call this function again to complete + * the handshake when you're done attending other tasks. + * \return #MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED if DTLS is in use + * and the client did not demonstrate reachability yet - in + * this case you must stop using the context (see below). + * \return Another SSL error code - in this case you must stop using + * the context (see below). + * + * \warning If this function returns something other than + * \c 0, + * #MBEDTLS_ERR_SSL_WANT_READ, + * #MBEDTLS_ERR_SSL_WANT_WRITE, + * #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS or + * #MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS, + * you must stop using the SSL context for reading or writing, + * and either free it or call \c mbedtls_ssl_session_reset() + * on it before re-using it for a new connection; the current + * connection must be closed. + * + * \note If DTLS is in use, then you may choose to handle + * #MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED specially for logging + * purposes, as it is an expected return value rather than an + * actual error, but you still need to reset/free the context. + * + * \note Remarks regarding event-driven DTLS: + * If the function returns #MBEDTLS_ERR_SSL_WANT_READ, no datagram + * from the underlying transport layer is currently being processed, + * and it is safe to idle until the timer or the underlying transport + * signal a new event. This is not true for a successful handshake, + * in which case the datagram of the underlying transport that is + * currently being processed might or might not contain further + * DTLS records. + */ +int mbedtls_ssl_handshake( mbedtls_ssl_context *ssl ); + +/** + * \brief Perform a single step of the SSL handshake + * + * \note The state of the context (ssl->state) will be at + * the next state after this function returns \c 0. Do not + * call this function if state is MBEDTLS_SSL_HANDSHAKE_OVER. + * + * \param ssl SSL context + * + * \return See mbedtls_ssl_handshake(). + * + * \warning If this function returns something other than \c 0, + * #MBEDTLS_ERR_SSL_WANT_READ, #MBEDTLS_ERR_SSL_WANT_WRITE, + * #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS or + * #MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS, you must stop using + * the SSL context for reading or writing, and either free it + * or call \c mbedtls_ssl_session_reset() on it before + * re-using it for a new connection; the current connection + * must be closed. + */ +int mbedtls_ssl_handshake_step( mbedtls_ssl_context *ssl ); + +#if defined(MBEDTLS_SSL_RENEGOTIATION) +/** + * \brief Initiate an SSL renegotiation on the running connection. + * Client: perform the renegotiation right now. + * Server: request renegotiation, which will be performed + * during the next call to mbedtls_ssl_read() if honored by + * client. + * + * \param ssl SSL context + * + * \return 0 if successful, or any mbedtls_ssl_handshake() return + * value except #MBEDTLS_ERR_SSL_CLIENT_RECONNECT that can't + * happen during a renegotiation. + * + * \warning If this function returns something other than \c 0, + * #MBEDTLS_ERR_SSL_WANT_READ, #MBEDTLS_ERR_SSL_WANT_WRITE, + * #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS or + * #MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS, you must stop using + * the SSL context for reading or writing, and either free it + * or call \c mbedtls_ssl_session_reset() on it before + * re-using it for a new connection; the current connection + * must be closed. + * + */ +int mbedtls_ssl_renegotiate( mbedtls_ssl_context *ssl ); +#endif /* MBEDTLS_SSL_RENEGOTIATION */ + +/** + * \brief Read at most 'len' application data bytes + * + * \param ssl SSL context + * \param buf buffer that will hold the data + * \param len maximum number of bytes to read + * + * \return The (positive) number of bytes read if successful. + * \return \c 0 if the read end of the underlying transport was closed + * - in this case you must stop using the context (see below). + * \return #MBEDTLS_ERR_SSL_WANT_READ or #MBEDTLS_ERR_SSL_WANT_WRITE + * if the handshake is incomplete and waiting for data to + * be available for reading from or writing to the underlying + * transport - in this case you must call this function again + * when the underlying transport is ready for the operation. + * \return #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS if an asynchronous + * operation is in progress (see + * mbedtls_ssl_conf_async_private_cb()) - in this case you + * must call this function again when the operation is ready. + * \return #MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS if a cryptographic + * operation is in progress (see mbedtls_ecp_set_max_ops()) - + * in this case you must call this function again to complete + * the handshake when you're done attending other tasks. + * \return #MBEDTLS_ERR_SSL_CLIENT_RECONNECT if we're at the server + * side of a DTLS connection and the client is initiating a + * new connection using the same source port. See below. + * \return Another SSL error code - in this case you must stop using + * the context (see below). + * + * \warning If this function returns something other than + * a positive value, + * #MBEDTLS_ERR_SSL_WANT_READ, + * #MBEDTLS_ERR_SSL_WANT_WRITE, + * #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS, + * #MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS or + * #MBEDTLS_ERR_SSL_CLIENT_RECONNECT, + * you must stop using the SSL context for reading or writing, + * and either free it or call \c mbedtls_ssl_session_reset() + * on it before re-using it for a new connection; the current + * connection must be closed. + * + * \note When this function returns #MBEDTLS_ERR_SSL_CLIENT_RECONNECT + * (which can only happen server-side), it means that a client + * is initiating a new connection using the same source port. + * You can either treat that as a connection close and wait + * for the client to resend a ClientHello, or directly + * continue with \c mbedtls_ssl_handshake() with the same + * context (as it has been reset internally). Either way, you + * must make sure this is seen by the application as a new + * connection: application state, if any, should be reset, and + * most importantly the identity of the client must be checked + * again. WARNING: not validating the identity of the client + * again, or not transmitting the new identity to the + * application layer, would allow authentication bypass! + * + * \note Remarks regarding event-driven DTLS: + * - If the function returns #MBEDTLS_ERR_SSL_WANT_READ, no datagram + * from the underlying transport layer is currently being processed, + * and it is safe to idle until the timer or the underlying transport + * signal a new event. + * - This function may return MBEDTLS_ERR_SSL_WANT_READ even if data was + * initially available on the underlying transport, as this data may have + * been only e.g. duplicated messages or a renegotiation request. + * Therefore, you must be prepared to receive MBEDTLS_ERR_SSL_WANT_READ even + * when reacting to an incoming-data event from the underlying transport. + * - On success, the datagram of the underlying transport that is currently + * being processed may contain further DTLS records. You should call + * \c mbedtls_ssl_check_pending to check for remaining records. + * + */ +int mbedtls_ssl_read( mbedtls_ssl_context *ssl, unsigned char *buf, size_t len ); + +/** + * \brief Try to write exactly 'len' application data bytes + * + * \warning This function will do partial writes in some cases. If the + * return value is non-negative but less than length, the + * function must be called again with updated arguments: + * buf + ret, len - ret (if ret is the return value) until + * it returns a value equal to the last 'len' argument. + * + * \param ssl SSL context + * \param buf buffer holding the data + * \param len how many bytes must be written + * + * \return The (non-negative) number of bytes actually written if + * successful (may be less than \p len). + * \return #MBEDTLS_ERR_SSL_WANT_READ or #MBEDTLS_ERR_SSL_WANT_WRITE + * if the handshake is incomplete and waiting for data to + * be available for reading from or writing to the underlying + * transport - in this case you must call this function again + * when the underlying transport is ready for the operation. + * \return #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS if an asynchronous + * operation is in progress (see + * mbedtls_ssl_conf_async_private_cb()) - in this case you + * must call this function again when the operation is ready. + * \return #MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS if a cryptographic + * operation is in progress (see mbedtls_ecp_set_max_ops()) - + * in this case you must call this function again to complete + * the handshake when you're done attending other tasks. + * \return Another SSL error code - in this case you must stop using + * the context (see below). + * + * \warning If this function returns something other than + * a non-negative value, + * #MBEDTLS_ERR_SSL_WANT_READ, + * #MBEDTLS_ERR_SSL_WANT_WRITE, + * #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS or + * #MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS, + * you must stop using the SSL context for reading or writing, + * and either free it or call \c mbedtls_ssl_session_reset() + * on it before re-using it for a new connection; the current + * connection must be closed. + * + * \note When this function returns #MBEDTLS_ERR_SSL_WANT_WRITE/READ, + * it must be called later with the *same* arguments, + * until it returns a value greater that or equal to 0. When + * the function returns #MBEDTLS_ERR_SSL_WANT_WRITE there may be + * some partial data in the output buffer, however this is not + * yet sent. + * + * \note If the requested length is greater than the maximum + * fragment length (either the built-in limit or the one set + * or negotiated with the peer), then: + * - with TLS, less bytes than requested are written. + * - with DTLS, MBEDTLS_ERR_SSL_BAD_INPUT_DATA is returned. + * \c mbedtls_ssl_get_max_frag_len() may be used to query the + * active maximum fragment length. + * + * \note Attempting to write 0 bytes will result in an empty TLS + * application record being sent. + */ +int mbedtls_ssl_write( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ); + +/** + * \brief Send an alert message + * + * \param ssl SSL context + * \param level The alert level of the message + * (MBEDTLS_SSL_ALERT_LEVEL_WARNING or MBEDTLS_SSL_ALERT_LEVEL_FATAL) + * \param message The alert message (SSL_ALERT_MSG_*) + * + * \return 0 if successful, or a specific SSL error code. + * + * \note If this function returns something other than 0 or + * MBEDTLS_ERR_SSL_WANT_READ/WRITE, you must stop using + * the SSL context for reading or writing, and either free it or + * call \c mbedtls_ssl_session_reset() on it before re-using it + * for a new connection; the current connection must be closed. + */ +int mbedtls_ssl_send_alert_message( mbedtls_ssl_context *ssl, + unsigned char level, + unsigned char message ); +/** + * \brief Notify the peer that the connection is being closed + * + * \param ssl SSL context + * + * \return 0 if successful, or a specific SSL error code. + * + * \note If this function returns something other than 0 or + * MBEDTLS_ERR_SSL_WANT_READ/WRITE, you must stop using + * the SSL context for reading or writing, and either free it or + * call \c mbedtls_ssl_session_reset() on it before re-using it + * for a new connection; the current connection must be closed. + */ +int mbedtls_ssl_close_notify( mbedtls_ssl_context *ssl ); + +/** + * \brief Free referenced items in an SSL context and clear memory + * + * \param ssl SSL context + */ +void mbedtls_ssl_free( mbedtls_ssl_context *ssl ); + +/** + * \brief Initialize an SSL configuration context + * Just makes the context ready for + * mbedtls_ssl_config_defaults() or mbedtls_ssl_config_free(). + * + * \note You need to call mbedtls_ssl_config_defaults() unless you + * manually set all of the relevant fields yourself. + * + * \param conf SSL configuration context + */ +void mbedtls_ssl_config_init( mbedtls_ssl_config *conf ); + +/** + * \brief Load reasonnable default SSL configuration values. + * (You need to call mbedtls_ssl_config_init() first.) + * + * \param conf SSL configuration context + * \param endpoint MBEDTLS_SSL_IS_CLIENT or MBEDTLS_SSL_IS_SERVER + * \param transport MBEDTLS_SSL_TRANSPORT_STREAM for TLS, or + * MBEDTLS_SSL_TRANSPORT_DATAGRAM for DTLS + * \param preset a MBEDTLS_SSL_PRESET_XXX value + * + * \note See \c mbedtls_ssl_conf_transport() for notes on DTLS. + * + * \return 0 if successful, or + * MBEDTLS_ERR_XXX_ALLOC_FAILED on memory allocation error. + */ +int mbedtls_ssl_config_defaults( mbedtls_ssl_config *conf, + int endpoint, int transport, int preset ); + +/** + * \brief Free an SSL configuration context + * + * \param conf SSL configuration context + */ +void mbedtls_ssl_config_free( mbedtls_ssl_config *conf ); + +/** + * \brief Initialize SSL session structure + * + * \param session SSL session + */ +void mbedtls_ssl_session_init( mbedtls_ssl_session *session ); + +/** + * \brief Free referenced items in an SSL session including the + * peer certificate and clear memory + * + * \note A session object can be freed even if the SSL context + * that was used to retrieve the session is still in use. + * + * \param session SSL session + */ +void mbedtls_ssl_session_free( mbedtls_ssl_session *session ); + +#ifdef __cplusplus +} +#endif + +#endif /* ssl.h */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/ssl_cache.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/ssl_cache.h new file mode 100644 index 0000000000000000000000000000000000000000..52ba0948c55d70bbc3e79e1a65a3e0756008fe1e --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/ssl_cache.h @@ -0,0 +1,150 @@ +/** + * \file ssl_cache.h + * + * \brief SSL session cache implementation + */ +/* + * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ +#ifndef MBEDTLS_SSL_CACHE_H +#define MBEDTLS_SSL_CACHE_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include "ssl.h" + +#if defined(MBEDTLS_THREADING_C) +#include "threading.h" +#endif + +/** + * \name SECTION: Module settings + * + * The configuration options you can set for this module are in this section. + * Either change them in config.h or define them on the compiler command line. + * \{ + */ + +#if !defined(MBEDTLS_SSL_CACHE_DEFAULT_TIMEOUT) +#define MBEDTLS_SSL_CACHE_DEFAULT_TIMEOUT 86400 /*!< 1 day */ +#endif + +#if !defined(MBEDTLS_SSL_CACHE_DEFAULT_MAX_ENTRIES) +#define MBEDTLS_SSL_CACHE_DEFAULT_MAX_ENTRIES 50 /*!< Maximum entries in cache */ +#endif + +/* \} name SECTION: Module settings */ + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct mbedtls_ssl_cache_context mbedtls_ssl_cache_context; +typedef struct mbedtls_ssl_cache_entry mbedtls_ssl_cache_entry; + +/** + * \brief This structure is used for storing cache entries + */ +struct mbedtls_ssl_cache_entry +{ +#if defined(MBEDTLS_HAVE_TIME) + mbedtls_time_t timestamp; /*!< entry timestamp */ +#endif + mbedtls_ssl_session session; /*!< entry session */ +#if defined(MBEDTLS_X509_CRT_PARSE_C) + mbedtls_x509_buf peer_cert; /*!< entry peer_cert */ +#endif + mbedtls_ssl_cache_entry *next; /*!< chain pointer */ +}; + +/** + * \brief Cache context + */ +struct mbedtls_ssl_cache_context +{ + mbedtls_ssl_cache_entry *chain; /*!< start of the chain */ + int timeout; /*!< cache entry timeout */ + int max_entries; /*!< maximum entries */ +#if defined(MBEDTLS_THREADING_C) + mbedtls_threading_mutex_t mutex; /*!< mutex */ +#endif +}; + +/** + * \brief Initialize an SSL cache context + * + * \param cache SSL cache context + */ +void mbedtls_ssl_cache_init( mbedtls_ssl_cache_context *cache ); + +/** + * \brief Cache get callback implementation + * (Thread-safe if MBEDTLS_THREADING_C is enabled) + * + * \param data SSL cache context + * \param session session to retrieve entry for + */ +int mbedtls_ssl_cache_get( void *data, mbedtls_ssl_session *session ); + +/** + * \brief Cache set callback implementation + * (Thread-safe if MBEDTLS_THREADING_C is enabled) + * + * \param data SSL cache context + * \param session session to store entry for + */ +int mbedtls_ssl_cache_set( void *data, const mbedtls_ssl_session *session ); + +#if defined(MBEDTLS_HAVE_TIME) +/** + * \brief Set the cache timeout + * (Default: MBEDTLS_SSL_CACHE_DEFAULT_TIMEOUT (1 day)) + * + * A timeout of 0 indicates no timeout. + * + * \param cache SSL cache context + * \param timeout cache entry timeout in seconds + */ +void mbedtls_ssl_cache_set_timeout( mbedtls_ssl_cache_context *cache, int timeout ); +#endif /* MBEDTLS_HAVE_TIME */ + +/** + * \brief Set the maximum number of cache entries + * (Default: MBEDTLS_SSL_CACHE_DEFAULT_MAX_ENTRIES (50)) + * + * \param cache SSL cache context + * \param max cache entry maximum + */ +void mbedtls_ssl_cache_set_max_entries( mbedtls_ssl_cache_context *cache, int max ); + +/** + * \brief Free referenced items in a cache context and clear memory + * + * \param cache SSL cache context + */ +void mbedtls_ssl_cache_free( mbedtls_ssl_cache_context *cache ); + +#ifdef __cplusplus +} +#endif + +#endif /* ssl_cache.h */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/ssl_ciphersuites.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/ssl_ciphersuites.h new file mode 100644 index 0000000000000000000000000000000000000000..71053e5ba71ccec1358f00be6b313285829e5507 --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/ssl_ciphersuites.h @@ -0,0 +1,540 @@ +/** + * \file ssl_ciphersuites.h + * + * \brief SSL Ciphersuites for mbed TLS + */ +/* + * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ +#ifndef MBEDTLS_SSL_CIPHERSUITES_H +#define MBEDTLS_SSL_CIPHERSUITES_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include "pk.h" +#include "cipher.h" +#include "md.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * Supported ciphersuites (Official IANA names) + */ +#define MBEDTLS_TLS_RSA_WITH_NULL_MD5 0x01 /**< Weak! */ +#define MBEDTLS_TLS_RSA_WITH_NULL_SHA 0x02 /**< Weak! */ + +#define MBEDTLS_TLS_RSA_WITH_RC4_128_MD5 0x04 +#define MBEDTLS_TLS_RSA_WITH_RC4_128_SHA 0x05 +#define MBEDTLS_TLS_RSA_WITH_DES_CBC_SHA 0x09 /**< Weak! Not in TLS 1.2 */ + +#define MBEDTLS_TLS_RSA_WITH_3DES_EDE_CBC_SHA 0x0A + +#define MBEDTLS_TLS_DHE_RSA_WITH_DES_CBC_SHA 0x15 /**< Weak! Not in TLS 1.2 */ +#define MBEDTLS_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA 0x16 + +#define MBEDTLS_TLS_PSK_WITH_NULL_SHA 0x2C /**< Weak! */ +#define MBEDTLS_TLS_DHE_PSK_WITH_NULL_SHA 0x2D /**< Weak! */ +#define MBEDTLS_TLS_RSA_PSK_WITH_NULL_SHA 0x2E /**< Weak! */ +#define MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA 0x2F + +#define MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA 0x33 +#define MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA 0x35 +#define MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CBC_SHA 0x39 + +#define MBEDTLS_TLS_RSA_WITH_NULL_SHA256 0x3B /**< Weak! */ +#define MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA256 0x3C /**< TLS 1.2 */ +#define MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA256 0x3D /**< TLS 1.2 */ + +#define MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA 0x41 +#define MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA 0x45 + +#define MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 0x67 /**< TLS 1.2 */ +#define MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 0x6B /**< TLS 1.2 */ + +#define MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA 0x84 +#define MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA 0x88 + +#define MBEDTLS_TLS_PSK_WITH_RC4_128_SHA 0x8A +#define MBEDTLS_TLS_PSK_WITH_3DES_EDE_CBC_SHA 0x8B +#define MBEDTLS_TLS_PSK_WITH_AES_128_CBC_SHA 0x8C +#define MBEDTLS_TLS_PSK_WITH_AES_256_CBC_SHA 0x8D + +#define MBEDTLS_TLS_DHE_PSK_WITH_RC4_128_SHA 0x8E +#define MBEDTLS_TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA 0x8F +#define MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CBC_SHA 0x90 +#define MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CBC_SHA 0x91 + +#define MBEDTLS_TLS_RSA_PSK_WITH_RC4_128_SHA 0x92 +#define MBEDTLS_TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA 0x93 +#define MBEDTLS_TLS_RSA_PSK_WITH_AES_128_CBC_SHA 0x94 +#define MBEDTLS_TLS_RSA_PSK_WITH_AES_256_CBC_SHA 0x95 + +#define MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256 0x9C /**< TLS 1.2 */ +#define MBEDTLS_TLS_RSA_WITH_AES_256_GCM_SHA384 0x9D /**< TLS 1.2 */ +#define MBEDTLS_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 0x9E /**< TLS 1.2 */ +#define MBEDTLS_TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 0x9F /**< TLS 1.2 */ + +#define MBEDTLS_TLS_PSK_WITH_AES_128_GCM_SHA256 0xA8 /**< TLS 1.2 */ +#define MBEDTLS_TLS_PSK_WITH_AES_256_GCM_SHA384 0xA9 /**< TLS 1.2 */ +#define MBEDTLS_TLS_DHE_PSK_WITH_AES_128_GCM_SHA256 0xAA /**< TLS 1.2 */ +#define MBEDTLS_TLS_DHE_PSK_WITH_AES_256_GCM_SHA384 0xAB /**< TLS 1.2 */ +#define MBEDTLS_TLS_RSA_PSK_WITH_AES_128_GCM_SHA256 0xAC /**< TLS 1.2 */ +#define MBEDTLS_TLS_RSA_PSK_WITH_AES_256_GCM_SHA384 0xAD /**< TLS 1.2 */ + +#define MBEDTLS_TLS_PSK_WITH_AES_128_CBC_SHA256 0xAE +#define MBEDTLS_TLS_PSK_WITH_AES_256_CBC_SHA384 0xAF +#define MBEDTLS_TLS_PSK_WITH_NULL_SHA256 0xB0 /**< Weak! */ +#define MBEDTLS_TLS_PSK_WITH_NULL_SHA384 0xB1 /**< Weak! */ + +#define MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CBC_SHA256 0xB2 +#define MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CBC_SHA384 0xB3 +#define MBEDTLS_TLS_DHE_PSK_WITH_NULL_SHA256 0xB4 /**< Weak! */ +#define MBEDTLS_TLS_DHE_PSK_WITH_NULL_SHA384 0xB5 /**< Weak! */ + +#define MBEDTLS_TLS_RSA_PSK_WITH_AES_128_CBC_SHA256 0xB6 +#define MBEDTLS_TLS_RSA_PSK_WITH_AES_256_CBC_SHA384 0xB7 +#define MBEDTLS_TLS_RSA_PSK_WITH_NULL_SHA256 0xB8 /**< Weak! */ +#define MBEDTLS_TLS_RSA_PSK_WITH_NULL_SHA384 0xB9 /**< Weak! */ + +#define MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256 0xBA /**< TLS 1.2 */ +#define MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 0xBE /**< TLS 1.2 */ + +#define MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256 0xC0 /**< TLS 1.2 */ +#define MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 0xC4 /**< TLS 1.2 */ + +#define MBEDTLS_TLS_ECDH_ECDSA_WITH_NULL_SHA 0xC001 /**< Weak! */ +#define MBEDTLS_TLS_ECDH_ECDSA_WITH_RC4_128_SHA 0xC002 /**< Not in SSL3! */ +#define MBEDTLS_TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA 0xC003 /**< Not in SSL3! */ +#define MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA 0xC004 /**< Not in SSL3! */ +#define MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA 0xC005 /**< Not in SSL3! */ + +#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_NULL_SHA 0xC006 /**< Weak! */ +#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_RC4_128_SHA 0xC007 /**< Not in SSL3! */ +#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA 0xC008 /**< Not in SSL3! */ +#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA 0xC009 /**< Not in SSL3! */ +#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA 0xC00A /**< Not in SSL3! */ + +#define MBEDTLS_TLS_ECDH_RSA_WITH_NULL_SHA 0xC00B /**< Weak! */ +#define MBEDTLS_TLS_ECDH_RSA_WITH_RC4_128_SHA 0xC00C /**< Not in SSL3! */ +#define MBEDTLS_TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA 0xC00D /**< Not in SSL3! */ +#define MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA 0xC00E /**< Not in SSL3! */ +#define MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA 0xC00F /**< Not in SSL3! */ + +#define MBEDTLS_TLS_ECDHE_RSA_WITH_NULL_SHA 0xC010 /**< Weak! */ +#define MBEDTLS_TLS_ECDHE_RSA_WITH_RC4_128_SHA 0xC011 /**< Not in SSL3! */ +#define MBEDTLS_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA 0xC012 /**< Not in SSL3! */ +#define MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA 0xC013 /**< Not in SSL3! */ +#define MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA 0xC014 /**< Not in SSL3! */ + +#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 0xC023 /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 0xC024 /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 0xC025 /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 0xC026 /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 0xC027 /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 0xC028 /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 0xC029 /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 0xC02A /**< TLS 1.2 */ + +#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 0xC02B /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 0xC02C /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 0xC02D /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 0xC02E /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 0xC02F /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 0xC030 /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 0xC031 /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384 0xC032 /**< TLS 1.2 */ + +#define MBEDTLS_TLS_ECDHE_PSK_WITH_RC4_128_SHA 0xC033 /**< Not in SSL3! */ +#define MBEDTLS_TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA 0xC034 /**< Not in SSL3! */ +#define MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA 0xC035 /**< Not in SSL3! */ +#define MBEDTLS_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA 0xC036 /**< Not in SSL3! */ +#define MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 0xC037 /**< Not in SSL3! */ +#define MBEDTLS_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384 0xC038 /**< Not in SSL3! */ +#define MBEDTLS_TLS_ECDHE_PSK_WITH_NULL_SHA 0xC039 /**< Weak! No SSL3! */ +#define MBEDTLS_TLS_ECDHE_PSK_WITH_NULL_SHA256 0xC03A /**< Weak! No SSL3! */ +#define MBEDTLS_TLS_ECDHE_PSK_WITH_NULL_SHA384 0xC03B /**< Weak! No SSL3! */ + +#define MBEDTLS_TLS_RSA_WITH_ARIA_128_CBC_SHA256 0xC03C /**< TLS 1.2 */ +#define MBEDTLS_TLS_RSA_WITH_ARIA_256_CBC_SHA384 0xC03D /**< TLS 1.2 */ +#define MBEDTLS_TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256 0xC044 /**< TLS 1.2 */ +#define MBEDTLS_TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384 0xC045 /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256 0xC048 /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384 0xC049 /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256 0xC04A /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384 0xC04B /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256 0xC04C /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384 0xC04D /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256 0xC04E /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384 0xC04F /**< TLS 1.2 */ +#define MBEDTLS_TLS_RSA_WITH_ARIA_128_GCM_SHA256 0xC050 /**< TLS 1.2 */ +#define MBEDTLS_TLS_RSA_WITH_ARIA_256_GCM_SHA384 0xC051 /**< TLS 1.2 */ +#define MBEDTLS_TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256 0xC052 /**< TLS 1.2 */ +#define MBEDTLS_TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384 0xC053 /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256 0xC05C /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384 0xC05D /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256 0xC05E /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384 0xC05F /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256 0xC060 /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384 0xC061 /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256 0xC062 /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384 0xC063 /**< TLS 1.2 */ +#define MBEDTLS_TLS_PSK_WITH_ARIA_128_CBC_SHA256 0xC064 /**< TLS 1.2 */ +#define MBEDTLS_TLS_PSK_WITH_ARIA_256_CBC_SHA384 0xC065 /**< TLS 1.2 */ +#define MBEDTLS_TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256 0xC066 /**< TLS 1.2 */ +#define MBEDTLS_TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384 0xC067 /**< TLS 1.2 */ +#define MBEDTLS_TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256 0xC068 /**< TLS 1.2 */ +#define MBEDTLS_TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384 0xC069 /**< TLS 1.2 */ +#define MBEDTLS_TLS_PSK_WITH_ARIA_128_GCM_SHA256 0xC06A /**< TLS 1.2 */ +#define MBEDTLS_TLS_PSK_WITH_ARIA_256_GCM_SHA384 0xC06B /**< TLS 1.2 */ +#define MBEDTLS_TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256 0xC06C /**< TLS 1.2 */ +#define MBEDTLS_TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384 0xC06D /**< TLS 1.2 */ +#define MBEDTLS_TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256 0xC06E /**< TLS 1.2 */ +#define MBEDTLS_TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384 0xC06F /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256 0xC070 /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384 0xC071 /**< TLS 1.2 */ + +#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 0xC072 /**< Not in SSL3! */ +#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 0xC073 /**< Not in SSL3! */ +#define MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 0xC074 /**< Not in SSL3! */ +#define MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 0xC075 /**< Not in SSL3! */ +#define MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 0xC076 /**< Not in SSL3! */ +#define MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384 0xC077 /**< Not in SSL3! */ +#define MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256 0xC078 /**< Not in SSL3! */ +#define MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384 0xC079 /**< Not in SSL3! */ + +#define MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256 0xC07A /**< TLS 1.2 */ +#define MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384 0xC07B /**< TLS 1.2 */ +#define MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256 0xC07C /**< TLS 1.2 */ +#define MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384 0xC07D /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256 0xC086 /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384 0xC087 /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256 0xC088 /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384 0xC089 /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256 0xC08A /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384 0xC08B /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256 0xC08C /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384 0xC08D /**< TLS 1.2 */ + +#define MBEDTLS_TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256 0xC08E /**< TLS 1.2 */ +#define MBEDTLS_TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384 0xC08F /**< TLS 1.2 */ +#define MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256 0xC090 /**< TLS 1.2 */ +#define MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384 0xC091 /**< TLS 1.2 */ +#define MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256 0xC092 /**< TLS 1.2 */ +#define MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384 0xC093 /**< TLS 1.2 */ + +#define MBEDTLS_TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256 0xC094 +#define MBEDTLS_TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384 0xC095 +#define MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 0xC096 +#define MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 0xC097 +#define MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256 0xC098 +#define MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384 0xC099 +#define MBEDTLS_TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 0xC09A /**< Not in SSL3! */ +#define MBEDTLS_TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 0xC09B /**< Not in SSL3! */ + +#define MBEDTLS_TLS_RSA_WITH_AES_128_CCM 0xC09C /**< TLS 1.2 */ +#define MBEDTLS_TLS_RSA_WITH_AES_256_CCM 0xC09D /**< TLS 1.2 */ +#define MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CCM 0xC09E /**< TLS 1.2 */ +#define MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CCM 0xC09F /**< TLS 1.2 */ +#define MBEDTLS_TLS_RSA_WITH_AES_128_CCM_8 0xC0A0 /**< TLS 1.2 */ +#define MBEDTLS_TLS_RSA_WITH_AES_256_CCM_8 0xC0A1 /**< TLS 1.2 */ +#define MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CCM_8 0xC0A2 /**< TLS 1.2 */ +#define MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CCM_8 0xC0A3 /**< TLS 1.2 */ +#define MBEDTLS_TLS_PSK_WITH_AES_128_CCM 0xC0A4 /**< TLS 1.2 */ +#define MBEDTLS_TLS_PSK_WITH_AES_256_CCM 0xC0A5 /**< TLS 1.2 */ +#define MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CCM 0xC0A6 /**< TLS 1.2 */ +#define MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CCM 0xC0A7 /**< TLS 1.2 */ +#define MBEDTLS_TLS_PSK_WITH_AES_128_CCM_8 0xC0A8 /**< TLS 1.2 */ +#define MBEDTLS_TLS_PSK_WITH_AES_256_CCM_8 0xC0A9 /**< TLS 1.2 */ +#define MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CCM_8 0xC0AA /**< TLS 1.2 */ +#define MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CCM_8 0xC0AB /**< TLS 1.2 */ +/* The last two are named with PSK_DHE in the RFC, which looks like a typo */ + +#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM 0xC0AC /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CCM 0xC0AD /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 0xC0AE /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8 0xC0AF /**< TLS 1.2 */ + +#define MBEDTLS_TLS_ECJPAKE_WITH_AES_128_CCM_8 0xC0FF /**< experimental */ + +/* RFC 7905 */ +#define MBEDTLS_TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 0xCCA8 /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 0xCCA9 /**< TLS 1.2 */ +#define MBEDTLS_TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256 0xCCAA /**< TLS 1.2 */ +#define MBEDTLS_TLS_PSK_WITH_CHACHA20_POLY1305_SHA256 0xCCAB /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256 0xCCAC /**< TLS 1.2 */ +#define MBEDTLS_TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256 0xCCAD /**< TLS 1.2 */ +#define MBEDTLS_TLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256 0xCCAE /**< TLS 1.2 */ + +/* Reminder: update mbedtls_ssl_premaster_secret when adding a new key exchange. + * Reminder: update MBEDTLS_KEY_EXCHANGE__xxx below + */ +typedef enum { + MBEDTLS_KEY_EXCHANGE_NONE = 0, + MBEDTLS_KEY_EXCHANGE_RSA, + MBEDTLS_KEY_EXCHANGE_DHE_RSA, + MBEDTLS_KEY_EXCHANGE_ECDHE_RSA, + MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA, + MBEDTLS_KEY_EXCHANGE_PSK, + MBEDTLS_KEY_EXCHANGE_DHE_PSK, + MBEDTLS_KEY_EXCHANGE_RSA_PSK, + MBEDTLS_KEY_EXCHANGE_ECDHE_PSK, + MBEDTLS_KEY_EXCHANGE_ECDH_RSA, + MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA, + MBEDTLS_KEY_EXCHANGE_ECJPAKE, +} mbedtls_key_exchange_type_t; + +/* Key exchanges using a certificate */ +#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) || \ + defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \ + defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \ + defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) || \ + defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) || \ + defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \ + defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED) +#define MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED +#endif + +/* Key exchanges allowing client certificate requests */ +#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) || \ + defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \ + defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \ + defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \ + defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED) || \ + defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) +#define MBEDTLS_KEY_EXCHANGE__CERT_REQ_ALLOWED__ENABLED +#endif + +/* Key exchanges involving server signature in ServerKeyExchange */ +#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \ + defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \ + defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) +#define MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED +#endif + +/* Key exchanges using ECDH */ +#if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \ + defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED) +#define MBEDTLS_KEY_EXCHANGE__SOME__ECDH_ENABLED +#endif + +/* Key exchanges that don't involve ephemeral keys */ +#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) || \ + defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) || \ + defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) || \ + defined(MBEDTLS_KEY_EXCHANGE__SOME__ECDH_ENABLED) +#define MBEDTLS_KEY_EXCHANGE__SOME_NON_PFS__ENABLED +#endif + +/* Key exchanges that involve ephemeral keys */ +#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \ + defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED) || \ + defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \ + defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) || \ + defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) || \ + defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) +#define MBEDTLS_KEY_EXCHANGE__SOME_PFS__ENABLED +#endif + +/* Key exchanges using a PSK */ +#if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) || \ + defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) || \ + defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED) || \ + defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) +#define MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED +#endif + +/* Key exchanges using DHE */ +#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \ + defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED) +#define MBEDTLS_KEY_EXCHANGE__SOME__DHE_ENABLED +#endif + +/* Key exchanges using ECDHE */ +#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \ + defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) || \ + defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) +#define MBEDTLS_KEY_EXCHANGE__SOME__ECDHE_ENABLED +#endif + +typedef struct mbedtls_ssl_ciphersuite_t mbedtls_ssl_ciphersuite_t; + +#define MBEDTLS_CIPHERSUITE_WEAK 0x01 /**< Weak ciphersuite flag */ +#define MBEDTLS_CIPHERSUITE_SHORT_TAG 0x02 /**< Short authentication tag, + eg for CCM_8 */ +#define MBEDTLS_CIPHERSUITE_NODTLS 0x04 /**< Can't be used with DTLS */ + +/** + * \brief This structure is used for storing ciphersuite information + */ +struct mbedtls_ssl_ciphersuite_t +{ + int id; + const char * name; + + mbedtls_cipher_type_t cipher; + mbedtls_md_type_t mac; + mbedtls_key_exchange_type_t key_exchange; + + int min_major_ver; + int min_minor_ver; + int max_major_ver; + int max_minor_ver; + + unsigned char flags; +}; + +const int *mbedtls_ssl_list_ciphersuites( void ); + +const mbedtls_ssl_ciphersuite_t *mbedtls_ssl_ciphersuite_from_string( const char *ciphersuite_name ); +const mbedtls_ssl_ciphersuite_t *mbedtls_ssl_ciphersuite_from_id( int ciphersuite_id ); + +#if defined(MBEDTLS_PK_C) +mbedtls_pk_type_t mbedtls_ssl_get_ciphersuite_sig_pk_alg( const mbedtls_ssl_ciphersuite_t *info ); +mbedtls_pk_type_t mbedtls_ssl_get_ciphersuite_sig_alg( const mbedtls_ssl_ciphersuite_t *info ); +#endif + +int mbedtls_ssl_ciphersuite_uses_ec( const mbedtls_ssl_ciphersuite_t *info ); +int mbedtls_ssl_ciphersuite_uses_psk( const mbedtls_ssl_ciphersuite_t *info ); + +#if defined(MBEDTLS_KEY_EXCHANGE__SOME_PFS__ENABLED) +static inline int mbedtls_ssl_ciphersuite_has_pfs( const mbedtls_ssl_ciphersuite_t *info ) +{ + switch( info->key_exchange ) + { + case MBEDTLS_KEY_EXCHANGE_DHE_RSA: + case MBEDTLS_KEY_EXCHANGE_DHE_PSK: + case MBEDTLS_KEY_EXCHANGE_ECDHE_RSA: + case MBEDTLS_KEY_EXCHANGE_ECDHE_PSK: + case MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA: + case MBEDTLS_KEY_EXCHANGE_ECJPAKE: + return( 1 ); + + default: + return( 0 ); + } +} +#endif /* MBEDTLS_KEY_EXCHANGE__SOME_PFS__ENABLED */ + +#if defined(MBEDTLS_KEY_EXCHANGE__SOME_NON_PFS__ENABLED) +static inline int mbedtls_ssl_ciphersuite_no_pfs( const mbedtls_ssl_ciphersuite_t *info ) +{ + switch( info->key_exchange ) + { + case MBEDTLS_KEY_EXCHANGE_ECDH_RSA: + case MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA: + case MBEDTLS_KEY_EXCHANGE_RSA: + case MBEDTLS_KEY_EXCHANGE_PSK: + case MBEDTLS_KEY_EXCHANGE_RSA_PSK: + return( 1 ); + + default: + return( 0 ); + } +} +#endif /* MBEDTLS_KEY_EXCHANGE__SOME_NON_PFS__ENABLED */ + +#if defined(MBEDTLS_KEY_EXCHANGE__SOME__ECDH_ENABLED) +static inline int mbedtls_ssl_ciphersuite_uses_ecdh( const mbedtls_ssl_ciphersuite_t *info ) +{ + switch( info->key_exchange ) + { + case MBEDTLS_KEY_EXCHANGE_ECDH_RSA: + case MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA: + return( 1 ); + + default: + return( 0 ); + } +} +#endif /* MBEDTLS_KEY_EXCHANGE__SOME__ECDH_ENABLED */ + +static inline int mbedtls_ssl_ciphersuite_cert_req_allowed( const mbedtls_ssl_ciphersuite_t *info ) +{ + switch( info->key_exchange ) + { + case MBEDTLS_KEY_EXCHANGE_RSA: + case MBEDTLS_KEY_EXCHANGE_DHE_RSA: + case MBEDTLS_KEY_EXCHANGE_ECDH_RSA: + case MBEDTLS_KEY_EXCHANGE_ECDHE_RSA: + case MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA: + case MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA: + return( 1 ); + + default: + return( 0 ); + } +} + +#if defined(MBEDTLS_KEY_EXCHANGE__SOME__DHE_ENABLED) +static inline int mbedtls_ssl_ciphersuite_uses_dhe( const mbedtls_ssl_ciphersuite_t *info ) +{ + switch( info->key_exchange ) + { + case MBEDTLS_KEY_EXCHANGE_DHE_RSA: + case MBEDTLS_KEY_EXCHANGE_DHE_PSK: + return( 1 ); + + default: + return( 0 ); + } +} +#endif /* MBEDTLS_KEY_EXCHANGE__SOME__DHE_ENABLED) */ + +#if defined(MBEDTLS_KEY_EXCHANGE__SOME__ECDHE_ENABLED) +static inline int mbedtls_ssl_ciphersuite_uses_ecdhe( const mbedtls_ssl_ciphersuite_t *info ) +{ + switch( info->key_exchange ) + { + case MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA: + case MBEDTLS_KEY_EXCHANGE_ECDHE_RSA: + case MBEDTLS_KEY_EXCHANGE_ECDHE_PSK: + return( 1 ); + + default: + return( 0 ); + } +} +#endif /* MBEDTLS_KEY_EXCHANGE__SOME__ECDHE_ENABLED) */ + +#if defined(MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED) +static inline int mbedtls_ssl_ciphersuite_uses_server_signature( const mbedtls_ssl_ciphersuite_t *info ) +{ + switch( info->key_exchange ) + { + case MBEDTLS_KEY_EXCHANGE_DHE_RSA: + case MBEDTLS_KEY_EXCHANGE_ECDHE_RSA: + case MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA: + return( 1 ); + + default: + return( 0 ); + } +} +#endif /* MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED */ + +#ifdef __cplusplus +} +#endif + +#endif /* ssl_ciphersuites.h */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/ssl_cookie.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/ssl_cookie.h new file mode 100644 index 0000000000000000000000000000000000000000..e34760ae85ea86bebb22a7c6ac88912ef8d94e14 --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/ssl_cookie.h @@ -0,0 +1,115 @@ +/** + * \file ssl_cookie.h + * + * \brief DTLS cookie callbacks implementation + */ +/* + * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ +#ifndef MBEDTLS_SSL_COOKIE_H +#define MBEDTLS_SSL_COOKIE_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include "ssl.h" + +#if defined(MBEDTLS_THREADING_C) +#include "threading.h" +#endif + +/** + * \name SECTION: Module settings + * + * The configuration options you can set for this module are in this section. + * Either change them in config.h or define them on the compiler command line. + * \{ + */ +#ifndef MBEDTLS_SSL_COOKIE_TIMEOUT +#define MBEDTLS_SSL_COOKIE_TIMEOUT 60 /**< Default expiration delay of DTLS cookies, in seconds if HAVE_TIME, or in number of cookies issued */ +#endif + +/* \} name SECTION: Module settings */ + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \brief Context for the default cookie functions. + */ +typedef struct mbedtls_ssl_cookie_ctx +{ + mbedtls_md_context_t hmac_ctx; /*!< context for the HMAC portion */ +#if !defined(MBEDTLS_HAVE_TIME) + unsigned long serial; /*!< serial number for expiration */ +#endif + unsigned long timeout; /*!< timeout delay, in seconds if HAVE_TIME, + or in number of tickets issued */ + +#if defined(MBEDTLS_THREADING_C) + mbedtls_threading_mutex_t mutex; +#endif +} mbedtls_ssl_cookie_ctx; + +/** + * \brief Initialize cookie context + */ +void mbedtls_ssl_cookie_init( mbedtls_ssl_cookie_ctx *ctx ); + +/** + * \brief Setup cookie context (generate keys) + */ +int mbedtls_ssl_cookie_setup( mbedtls_ssl_cookie_ctx *ctx, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng ); + +/** + * \brief Set expiration delay for cookies + * (Default MBEDTLS_SSL_COOKIE_TIMEOUT) + * + * \param ctx Cookie contex + * \param delay Delay, in seconds if HAVE_TIME, or in number of cookies + * issued in the meantime. + * 0 to disable expiration (NOT recommended) + */ +void mbedtls_ssl_cookie_set_timeout( mbedtls_ssl_cookie_ctx *ctx, unsigned long delay ); + +/** + * \brief Free cookie context + */ +void mbedtls_ssl_cookie_free( mbedtls_ssl_cookie_ctx *ctx ); + +/** + * \brief Generate cookie, see \c mbedtls_ssl_cookie_write_t + */ +mbedtls_ssl_cookie_write_t mbedtls_ssl_cookie_write; + +/** + * \brief Verify cookie, see \c mbedtls_ssl_cookie_write_t + */ +mbedtls_ssl_cookie_check_t mbedtls_ssl_cookie_check; + +#ifdef __cplusplus +} +#endif + +#endif /* ssl_cookie.h */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/ssl_internal.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/ssl_internal.h new file mode 100644 index 0000000000000000000000000000000000000000..f58da95d0f6cdbe4ae59718dcbfb6d4699bc0ade --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/ssl_internal.h @@ -0,0 +1,778 @@ +/** + * \file ssl_internal.h + * + * \brief Internal functions shared by the SSL modules + */ +/* + * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ +#ifndef MBEDTLS_SSL_INTERNAL_H +#define MBEDTLS_SSL_INTERNAL_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include "ssl.h" +#include "cipher.h" + +#if defined(MBEDTLS_MD5_C) +#include "md5.h" +#endif + +#if defined(MBEDTLS_SHA1_C) +#include "sha1.h" +#endif + +#if defined(MBEDTLS_SHA256_C) +#include "sha256.h" +#endif + +#if defined(MBEDTLS_SHA512_C) +#include "sha512.h" +#endif + +#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) +#include "ecjpake.h" +#endif + +#if ( defined(__ARMCC_VERSION) || defined(_MSC_VER) ) && \ + !defined(inline) && !defined(__cplusplus) +#define inline __inline +#endif + +/* Determine minimum supported version */ +#define MBEDTLS_SSL_MIN_MAJOR_VERSION MBEDTLS_SSL_MAJOR_VERSION_3 + +#if defined(MBEDTLS_SSL_PROTO_SSL3) +#define MBEDTLS_SSL_MIN_MINOR_VERSION MBEDTLS_SSL_MINOR_VERSION_0 +#else +#if defined(MBEDTLS_SSL_PROTO_TLS1) +#define MBEDTLS_SSL_MIN_MINOR_VERSION MBEDTLS_SSL_MINOR_VERSION_1 +#else +#if defined(MBEDTLS_SSL_PROTO_TLS1_1) +#define MBEDTLS_SSL_MIN_MINOR_VERSION MBEDTLS_SSL_MINOR_VERSION_2 +#else +#if defined(MBEDTLS_SSL_PROTO_TLS1_2) +#define MBEDTLS_SSL_MIN_MINOR_VERSION MBEDTLS_SSL_MINOR_VERSION_3 +#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ +#endif /* MBEDTLS_SSL_PROTO_TLS1_1 */ +#endif /* MBEDTLS_SSL_PROTO_TLS1 */ +#endif /* MBEDTLS_SSL_PROTO_SSL3 */ + +#define MBEDTLS_SSL_MIN_VALID_MINOR_VERSION MBEDTLS_SSL_MINOR_VERSION_1 +#define MBEDTLS_SSL_MIN_VALID_MAJOR_VERSION MBEDTLS_SSL_MAJOR_VERSION_3 + +/* Determine maximum supported version */ +#define MBEDTLS_SSL_MAX_MAJOR_VERSION MBEDTLS_SSL_MAJOR_VERSION_3 + +#if defined(MBEDTLS_SSL_PROTO_TLS1_2) +#define MBEDTLS_SSL_MAX_MINOR_VERSION MBEDTLS_SSL_MINOR_VERSION_3 +#else +#if defined(MBEDTLS_SSL_PROTO_TLS1_1) +#define MBEDTLS_SSL_MAX_MINOR_VERSION MBEDTLS_SSL_MINOR_VERSION_2 +#else +#if defined(MBEDTLS_SSL_PROTO_TLS1) +#define MBEDTLS_SSL_MAX_MINOR_VERSION MBEDTLS_SSL_MINOR_VERSION_1 +#else +#if defined(MBEDTLS_SSL_PROTO_SSL3) +#define MBEDTLS_SSL_MAX_MINOR_VERSION MBEDTLS_SSL_MINOR_VERSION_0 +#endif /* MBEDTLS_SSL_PROTO_SSL3 */ +#endif /* MBEDTLS_SSL_PROTO_TLS1 */ +#endif /* MBEDTLS_SSL_PROTO_TLS1_1 */ +#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ + +/* Shorthand for restartable ECC */ +#if defined(MBEDTLS_ECP_RESTARTABLE) && \ + defined(MBEDTLS_SSL_CLI_C) && \ + defined(MBEDTLS_SSL_PROTO_TLS1_2) && \ + defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) +#define MBEDTLS_SSL__ECP_RESTARTABLE +#endif + +#define MBEDTLS_SSL_INITIAL_HANDSHAKE 0 +#define MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS 1 /* In progress */ +#define MBEDTLS_SSL_RENEGOTIATION_DONE 2 /* Done or aborted */ +#define MBEDTLS_SSL_RENEGOTIATION_PENDING 3 /* Requested (server only) */ + +/* + * DTLS retransmission states, see RFC 6347 4.2.4 + * + * The SENDING state is merged in PREPARING for initial sends, + * but is distinct for resends. + * + * Note: initial state is wrong for server, but is not used anyway. + */ +#define MBEDTLS_SSL_RETRANS_PREPARING 0 +#define MBEDTLS_SSL_RETRANS_SENDING 1 +#define MBEDTLS_SSL_RETRANS_WAITING 2 +#define MBEDTLS_SSL_RETRANS_FINISHED 3 + +/* + * Allow extra bytes for record, authentication and encryption overhead: + * counter (8) + header (5) + IV(16) + MAC (16-48) + padding (0-256) + * and allow for a maximum of 1024 of compression expansion if + * enabled. + */ +#if defined(MBEDTLS_ZLIB_SUPPORT) +#define MBEDTLS_SSL_COMPRESSION_ADD 1024 +#else +#define MBEDTLS_SSL_COMPRESSION_ADD 0 +#endif + +#if defined(MBEDTLS_ARC4_C) || defined(MBEDTLS_CIPHER_MODE_CBC) +/* Ciphersuites using HMAC */ +#if defined(MBEDTLS_SHA512_C) +#define MBEDTLS_SSL_MAC_ADD 48 /* SHA-384 used for HMAC */ +#elif defined(MBEDTLS_SHA256_C) +#define MBEDTLS_SSL_MAC_ADD 32 /* SHA-256 used for HMAC */ +#else +#define MBEDTLS_SSL_MAC_ADD 20 /* SHA-1 used for HMAC */ +#endif +#else +/* AEAD ciphersuites: GCM and CCM use a 128 bits tag */ +#define MBEDTLS_SSL_MAC_ADD 16 +#endif + +#if defined(MBEDTLS_CIPHER_MODE_CBC) +#define MBEDTLS_SSL_PADDING_ADD 256 +#else +#define MBEDTLS_SSL_PADDING_ADD 0 +#endif + +#define MBEDTLS_SSL_PAYLOAD_OVERHEAD ( MBEDTLS_SSL_COMPRESSION_ADD + \ + MBEDTLS_MAX_IV_LENGTH + \ + MBEDTLS_SSL_MAC_ADD + \ + MBEDTLS_SSL_PADDING_ADD \ + ) + +#define MBEDTLS_SSL_IN_PAYLOAD_LEN ( MBEDTLS_SSL_PAYLOAD_OVERHEAD + \ + ( MBEDTLS_SSL_IN_CONTENT_LEN ) ) + +#define MBEDTLS_SSL_OUT_PAYLOAD_LEN ( MBEDTLS_SSL_PAYLOAD_OVERHEAD + \ + ( MBEDTLS_SSL_OUT_CONTENT_LEN ) ) + +/* The maximum number of buffered handshake messages. */ +#define MBEDTLS_SSL_MAX_BUFFERED_HS 4 + +/* Maximum length we can advertise as our max content length for + RFC 6066 max_fragment_length extension negotiation purposes + (the lesser of both sizes, if they are unequal.) + */ +#define MBEDTLS_TLS_EXT_ADV_CONTENT_LEN MBEDTLS_SSL_IN_CONTENT_LEN + +/* + * Check that we obey the standard's message size bounds + */ + +#if MBEDTLS_SSL_MAX_CONTENT_LEN > 16384 +#error "Bad configuration - record content too large." +#endif + +#if MBEDTLS_SSL_IN_CONTENT_LEN > MBEDTLS_SSL_MAX_CONTENT_LEN +#error "Bad configuration - incoming record content should not be larger than MBEDTLS_SSL_MAX_CONTENT_LEN." +#endif + +#if MBEDTLS_SSL_OUT_CONTENT_LEN > MBEDTLS_SSL_MAX_CONTENT_LEN +#error "Bad configuration - outgoing record content should not be larger than MBEDTLS_SSL_MAX_CONTENT_LEN." +#endif + +#if MBEDTLS_SSL_IN_PAYLOAD_LEN > MBEDTLS_SSL_MAX_CONTENT_LEN + 2048 +#error "Bad configuration - incoming protected record payload too large." +#endif + +#if MBEDTLS_SSL_OUT_PAYLOAD_LEN > MBEDTLS_SSL_MAX_CONTENT_LEN + 2048 +#error "Bad configuration - outgoing protected record payload too large." +#endif + +/* Calculate buffer sizes */ + +/* Note: Even though the TLS record header is only 5 bytes + long, we're internally using 8 bytes to store the + implicit sequence number. */ +#define MBEDTLS_SSL_HEADER_LEN 13 + +#define MBEDTLS_SSL_IN_BUFFER_LEN \ + ( ( MBEDTLS_SSL_HEADER_LEN ) + ( MBEDTLS_SSL_IN_PAYLOAD_LEN ) ) + +#define MBEDTLS_SSL_OUT_BUFFER_LEN \ + ( ( MBEDTLS_SSL_HEADER_LEN ) + ( MBEDTLS_SSL_OUT_PAYLOAD_LEN ) ) + +#ifdef MBEDTLS_ZLIB_SUPPORT +/* Compression buffer holds both IN and OUT buffers, so should be size of the larger */ +#define MBEDTLS_SSL_COMPRESS_BUFFER_LEN ( \ + ( MBEDTLS_SSL_IN_BUFFER_LEN > MBEDTLS_SSL_OUT_BUFFER_LEN ) \ + ? MBEDTLS_SSL_IN_BUFFER_LEN \ + : MBEDTLS_SSL_OUT_BUFFER_LEN \ + ) +#endif + +/* + * TLS extension flags (for extensions with outgoing ServerHello content + * that need it (e.g. for RENEGOTIATION_INFO the server already knows because + * of state of the renegotiation flag, so no indicator is required) + */ +#define MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS_PRESENT (1 << 0) +#define MBEDTLS_TLS_EXT_ECJPAKE_KKPP_OK (1 << 1) + +#ifdef __cplusplus +extern "C" { +#endif + +#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \ + defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED) +/* + * Abstraction for a grid of allowed signature-hash-algorithm pairs. + */ +struct mbedtls_ssl_sig_hash_set_t +{ + /* At the moment, we only need to remember a single suitable + * hash algorithm per signature algorithm. As long as that's + * the case - and we don't need a general lookup function - + * we can implement the sig-hash-set as a map from signatures + * to hash algorithms. */ + mbedtls_md_type_t rsa; + mbedtls_md_type_t ecdsa; +}; +#endif /* MBEDTLS_SSL_PROTO_TLS1_2 && + MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */ + +/* + * This structure contains the parameters only needed during handshake. + */ +struct mbedtls_ssl_handshake_params +{ + /* + * Handshake specific crypto variables + */ + +#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \ + defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED) + mbedtls_ssl_sig_hash_set_t hash_algs; /*!< Set of suitable sig-hash pairs */ +#endif +#if defined(MBEDTLS_DHM_C) + mbedtls_dhm_context dhm_ctx; /*!< DHM key exchange */ +#endif +#if defined(MBEDTLS_ECDH_C) + mbedtls_ecdh_context ecdh_ctx; /*!< ECDH key exchange */ +#endif +#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) + mbedtls_ecjpake_context ecjpake_ctx; /*!< EC J-PAKE key exchange */ +#if defined(MBEDTLS_SSL_CLI_C) + unsigned char *ecjpake_cache; /*!< Cache for ClientHello ext */ + size_t ecjpake_cache_len; /*!< Length of cached data */ +#endif +#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */ +#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \ + defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) + const mbedtls_ecp_curve_info **curves; /*!< Supported elliptic curves */ +#endif +#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED) + unsigned char *psk; /*!< PSK from the callback */ + size_t psk_len; /*!< Length of PSK from callback */ +#endif +#if defined(MBEDTLS_X509_CRT_PARSE_C) + mbedtls_ssl_key_cert *key_cert; /*!< chosen key/cert pair (server) */ +#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) + int sni_authmode; /*!< authmode from SNI callback */ + mbedtls_ssl_key_cert *sni_key_cert; /*!< key/cert list from SNI */ + mbedtls_x509_crt *sni_ca_chain; /*!< trusted CAs from SNI callback */ + mbedtls_x509_crl *sni_ca_crl; /*!< trusted CAs CRLs from SNI */ +#endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */ +#endif /* MBEDTLS_X509_CRT_PARSE_C */ +#if defined(MBEDTLS_SSL__ECP_RESTARTABLE) + int ecrs_enabled; /*!< Handshake supports EC restart? */ + mbedtls_x509_crt_restart_ctx ecrs_ctx; /*!< restart context */ + enum { /* this complements ssl->state with info on intra-state operations */ + ssl_ecrs_none = 0, /*!< nothing going on (yet) */ + ssl_ecrs_crt_verify, /*!< Certificate: crt_verify() */ + ssl_ecrs_ske_start_processing, /*!< ServerKeyExchange: pk_verify() */ + ssl_ecrs_cke_ecdh_calc_secret, /*!< ClientKeyExchange: ECDH step 2 */ + ssl_ecrs_crt_vrfy_sign, /*!< CertificateVerify: pk_sign() */ + } ecrs_state; /*!< current (or last) operation */ + size_t ecrs_n; /*!< place for saving a length */ +#endif +#if defined(MBEDTLS_SSL_PROTO_DTLS) + unsigned int out_msg_seq; /*!< Outgoing handshake sequence number */ + unsigned int in_msg_seq; /*!< Incoming handshake sequence number */ + + unsigned char *verify_cookie; /*!< Cli: HelloVerifyRequest cookie + Srv: unused */ + unsigned char verify_cookie_len; /*!< Cli: cookie length + Srv: flag for sending a cookie */ + + uint32_t retransmit_timeout; /*!< Current value of timeout */ + unsigned char retransmit_state; /*!< Retransmission state */ + mbedtls_ssl_flight_item *flight; /*!< Current outgoing flight */ + mbedtls_ssl_flight_item *cur_msg; /*!< Current message in flight */ + unsigned char *cur_msg_p; /*!< Position in current message */ + unsigned int in_flight_start_seq; /*!< Minimum message sequence in the + flight being received */ + mbedtls_ssl_transform *alt_transform_out; /*!< Alternative transform for + resending messages */ + unsigned char alt_out_ctr[8]; /*!< Alternative record epoch/counter + for resending messages */ + + struct + { + size_t total_bytes_buffered; /*!< Cumulative size of heap allocated + * buffers used for message buffering. */ + + uint8_t seen_ccs; /*!< Indicates if a CCS message has + * been seen in the current flight. */ + + struct mbedtls_ssl_hs_buffer + { + unsigned is_valid : 1; + unsigned is_fragmented : 1; + unsigned is_complete : 1; + unsigned char *data; + size_t data_len; + } hs[MBEDTLS_SSL_MAX_BUFFERED_HS]; + + struct + { + unsigned char *data; + size_t len; + unsigned epoch; + } future_record; + + } buffering; + + uint16_t mtu; /*!< Handshake mtu, used to fragment outgoing messages */ +#endif /* MBEDTLS_SSL_PROTO_DTLS */ + + /* + * Checksum contexts + */ +#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \ + defined(MBEDTLS_SSL_PROTO_TLS1_1) + mbedtls_md5_context fin_md5; + mbedtls_sha1_context fin_sha1; +#endif +#if defined(MBEDTLS_SSL_PROTO_TLS1_2) +#if defined(MBEDTLS_SHA256_C) + mbedtls_sha256_context fin_sha256; +#endif +#if defined(MBEDTLS_SHA512_C) + mbedtls_sha512_context fin_sha512; +#endif +#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ + + void (*update_checksum)(mbedtls_ssl_context *, const unsigned char *, size_t); + void (*calc_verify)(mbedtls_ssl_context *, unsigned char *); + void (*calc_finished)(mbedtls_ssl_context *, unsigned char *, int); + int (*tls_prf)(const unsigned char *, size_t, const char *, + const unsigned char *, size_t, + unsigned char *, size_t); + + size_t pmslen; /*!< premaster length */ + + unsigned char randbytes[64]; /*!< random bytes */ + unsigned char premaster[MBEDTLS_PREMASTER_SIZE]; + /*!< premaster secret */ + + int resume; /*!< session resume indicator*/ + int max_major_ver; /*!< max. major version client*/ + int max_minor_ver; /*!< max. minor version client*/ + int cli_exts; /*!< client extension presence*/ + +#if defined(MBEDTLS_SSL_SESSION_TICKETS) + int new_session_ticket; /*!< use NewSessionTicket? */ +#endif /* MBEDTLS_SSL_SESSION_TICKETS */ +#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET) + int extended_ms; /*!< use Extended Master Secret? */ +#endif + +#if defined(MBEDTLS_SSL_ASYNC_PRIVATE) + unsigned int async_in_progress : 1; /*!< an asynchronous operation is in progress */ +#endif /* MBEDTLS_SSL_ASYNC_PRIVATE */ + +#if defined(MBEDTLS_SSL_ASYNC_PRIVATE) + /** Asynchronous operation context. This field is meant for use by the + * asynchronous operation callbacks (mbedtls_ssl_config::f_async_sign_start, + * mbedtls_ssl_config::f_async_decrypt_start, + * mbedtls_ssl_config::f_async_resume, mbedtls_ssl_config::f_async_cancel). + * The library does not use it internally. */ + void *user_async_ctx; +#endif /* MBEDTLS_SSL_ASYNC_PRIVATE */ +}; + +typedef struct mbedtls_ssl_hs_buffer mbedtls_ssl_hs_buffer; + +/* + * This structure contains a full set of runtime transform parameters + * either in negotiation or active. + */ +struct mbedtls_ssl_transform +{ + /* + * Session specific crypto layer + */ + const mbedtls_ssl_ciphersuite_t *ciphersuite_info; + /*!< Chosen cipersuite_info */ + unsigned int keylen; /*!< symmetric key length (bytes) */ + size_t minlen; /*!< min. ciphertext length */ + size_t ivlen; /*!< IV length */ + size_t fixed_ivlen; /*!< Fixed part of IV (AEAD) */ + size_t maclen; /*!< MAC length */ + + unsigned char iv_enc[16]; /*!< IV (encryption) */ + unsigned char iv_dec[16]; /*!< IV (decryption) */ + +#if defined(MBEDTLS_SSL_PROTO_SSL3) + /* Needed only for SSL v3.0 secret */ + unsigned char mac_enc[20]; /*!< SSL v3.0 secret (enc) */ + unsigned char mac_dec[20]; /*!< SSL v3.0 secret (dec) */ +#endif /* MBEDTLS_SSL_PROTO_SSL3 */ + + mbedtls_md_context_t md_ctx_enc; /*!< MAC (encryption) */ + mbedtls_md_context_t md_ctx_dec; /*!< MAC (decryption) */ + + mbedtls_cipher_context_t cipher_ctx_enc; /*!< encryption context */ + mbedtls_cipher_context_t cipher_ctx_dec; /*!< decryption context */ + + /* + * Session specific compression layer + */ +#if defined(MBEDTLS_ZLIB_SUPPORT) + z_stream ctx_deflate; /*!< compression context */ + z_stream ctx_inflate; /*!< decompression context */ +#endif +}; + +#if defined(MBEDTLS_X509_CRT_PARSE_C) +/* + * List of certificate + private key pairs + */ +struct mbedtls_ssl_key_cert +{ + mbedtls_x509_crt *cert; /*!< cert */ + mbedtls_pk_context *key; /*!< private key */ + mbedtls_ssl_key_cert *next; /*!< next key/cert pair */ +}; +#endif /* MBEDTLS_X509_CRT_PARSE_C */ + +#if defined(MBEDTLS_SSL_PROTO_DTLS) +/* + * List of handshake messages kept around for resending + */ +struct mbedtls_ssl_flight_item +{ + unsigned char *p; /*!< message, including handshake headers */ + size_t len; /*!< length of p */ + unsigned char type; /*!< type of the message: handshake or CCS */ + mbedtls_ssl_flight_item *next; /*!< next handshake message(s) */ +}; +#endif /* MBEDTLS_SSL_PROTO_DTLS */ + +#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \ + defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED) + +/* Find an entry in a signature-hash set matching a given hash algorithm. */ +mbedtls_md_type_t mbedtls_ssl_sig_hash_set_find( mbedtls_ssl_sig_hash_set_t *set, + mbedtls_pk_type_t sig_alg ); +/* Add a signature-hash-pair to a signature-hash set */ +void mbedtls_ssl_sig_hash_set_add( mbedtls_ssl_sig_hash_set_t *set, + mbedtls_pk_type_t sig_alg, + mbedtls_md_type_t md_alg ); +/* Allow exactly one hash algorithm for each signature. */ +void mbedtls_ssl_sig_hash_set_const_hash( mbedtls_ssl_sig_hash_set_t *set, + mbedtls_md_type_t md_alg ); + +/* Setup an empty signature-hash set */ +static inline void mbedtls_ssl_sig_hash_set_init( mbedtls_ssl_sig_hash_set_t *set ) +{ + mbedtls_ssl_sig_hash_set_const_hash( set, MBEDTLS_MD_NONE ); +} + +#endif /* MBEDTLS_SSL_PROTO_TLS1_2) && + MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */ + +/** + * \brief Free referenced items in an SSL transform context and clear + * memory + * + * \param transform SSL transform context + */ +void mbedtls_ssl_transform_free( mbedtls_ssl_transform *transform ); + +/** + * \brief Free referenced items in an SSL handshake context and clear + * memory + * + * \param ssl SSL context + */ +void mbedtls_ssl_handshake_free( mbedtls_ssl_context *ssl ); + +int mbedtls_ssl_handshake_client_step( mbedtls_ssl_context *ssl ); +int mbedtls_ssl_handshake_server_step( mbedtls_ssl_context *ssl ); +void mbedtls_ssl_handshake_wrapup( mbedtls_ssl_context *ssl ); + +int mbedtls_ssl_send_fatal_handshake_failure( mbedtls_ssl_context *ssl ); + +void mbedtls_ssl_reset_checksum( mbedtls_ssl_context *ssl ); +int mbedtls_ssl_derive_keys( mbedtls_ssl_context *ssl ); + +int mbedtls_ssl_handle_message_type( mbedtls_ssl_context *ssl ); +int mbedtls_ssl_prepare_handshake_record( mbedtls_ssl_context *ssl ); +void mbedtls_ssl_update_handshake_status( mbedtls_ssl_context *ssl ); + +/** + * \brief Update record layer + * + * This function roughly separates the implementation + * of the logic of (D)TLS from the implementation + * of the secure transport. + * + * \param ssl The SSL context to use. + * \param update_hs_digest This indicates if the handshake digest + * should be automatically updated in case + * a handshake message is found. + * + * \return 0 or non-zero error code. + * + * \note A clarification on what is called 'record layer' here + * is in order, as many sensible definitions are possible: + * + * The record layer takes as input an untrusted underlying + * transport (stream or datagram) and transforms it into + * a serially multiplexed, secure transport, which + * conceptually provides the following: + * + * (1) Three datagram based, content-agnostic transports + * for handshake, alert and CCS messages. + * (2) One stream- or datagram-based transport + * for application data. + * (3) Functionality for changing the underlying transform + * securing the contents. + * + * The interface to this functionality is given as follows: + * + * a Updating + * [Currently implemented by mbedtls_ssl_read_record] + * + * Check if and on which of the four 'ports' data is pending: + * Nothing, a controlling datagram of type (1), or application + * data (2). In any case data is present, internal buffers + * provide access to the data for the user to process it. + * Consumption of type (1) datagrams is done automatically + * on the next update, invalidating that the internal buffers + * for previous datagrams, while consumption of application + * data (2) is user-controlled. + * + * b Reading of application data + * [Currently manual adaption of ssl->in_offt pointer] + * + * As mentioned in the last paragraph, consumption of data + * is different from the automatic consumption of control + * datagrams (1) because application data is treated as a stream. + * + * c Tracking availability of application data + * [Currently manually through decreasing ssl->in_msglen] + * + * For efficiency and to retain datagram semantics for + * application data in case of DTLS, the record layer + * provides functionality for checking how much application + * data is still available in the internal buffer. + * + * d Changing the transformation securing the communication. + * + * Given an opaque implementation of the record layer in the + * above sense, it should be possible to implement the logic + * of (D)TLS on top of it without the need to know anything + * about the record layer's internals. This is done e.g. + * in all the handshake handling functions, and in the + * application data reading function mbedtls_ssl_read. + * + * \note The above tries to give a conceptual picture of the + * record layer, but the current implementation deviates + * from it in some places. For example, our implementation of + * the update functionality through mbedtls_ssl_read_record + * discards datagrams depending on the current state, which + * wouldn't fall under the record layer's responsibility + * following the above definition. + * + */ +int mbedtls_ssl_read_record( mbedtls_ssl_context *ssl, + unsigned update_hs_digest ); +int mbedtls_ssl_fetch_input( mbedtls_ssl_context *ssl, size_t nb_want ); + +int mbedtls_ssl_write_handshake_msg( mbedtls_ssl_context *ssl ); +int mbedtls_ssl_write_record( mbedtls_ssl_context *ssl, uint8_t force_flush ); +int mbedtls_ssl_flush_output( mbedtls_ssl_context *ssl ); + +int mbedtls_ssl_parse_certificate( mbedtls_ssl_context *ssl ); +int mbedtls_ssl_write_certificate( mbedtls_ssl_context *ssl ); + +int mbedtls_ssl_parse_change_cipher_spec( mbedtls_ssl_context *ssl ); +int mbedtls_ssl_write_change_cipher_spec( mbedtls_ssl_context *ssl ); + +int mbedtls_ssl_parse_finished( mbedtls_ssl_context *ssl ); +int mbedtls_ssl_write_finished( mbedtls_ssl_context *ssl ); + +void mbedtls_ssl_optimize_checksum( mbedtls_ssl_context *ssl, + const mbedtls_ssl_ciphersuite_t *ciphersuite_info ); + +#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED) +int mbedtls_ssl_psk_derive_premaster( mbedtls_ssl_context *ssl, mbedtls_key_exchange_type_t key_ex ); +#endif + +#if defined(MBEDTLS_PK_C) +unsigned char mbedtls_ssl_sig_from_pk( mbedtls_pk_context *pk ); +unsigned char mbedtls_ssl_sig_from_pk_alg( mbedtls_pk_type_t type ); +mbedtls_pk_type_t mbedtls_ssl_pk_alg_from_sig( unsigned char sig ); +#endif + +mbedtls_md_type_t mbedtls_ssl_md_alg_from_hash( unsigned char hash ); +unsigned char mbedtls_ssl_hash_from_md_alg( int md ); +int mbedtls_ssl_set_calc_verify_md( mbedtls_ssl_context *ssl, int md ); + +#if defined(MBEDTLS_ECP_C) +int mbedtls_ssl_check_curve( const mbedtls_ssl_context *ssl, mbedtls_ecp_group_id grp_id ); +#endif + +#if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED) +int mbedtls_ssl_check_sig_hash( const mbedtls_ssl_context *ssl, + mbedtls_md_type_t md ); +#endif + +#if defined(MBEDTLS_X509_CRT_PARSE_C) +static inline mbedtls_pk_context *mbedtls_ssl_own_key( mbedtls_ssl_context *ssl ) +{ + mbedtls_ssl_key_cert *key_cert; + + if( ssl->handshake != NULL && ssl->handshake->key_cert != NULL ) + key_cert = ssl->handshake->key_cert; + else + key_cert = ssl->conf->key_cert; + + return( key_cert == NULL ? NULL : key_cert->key ); +} + +static inline mbedtls_x509_crt *mbedtls_ssl_own_cert( mbedtls_ssl_context *ssl ) +{ + mbedtls_ssl_key_cert *key_cert; + + if( ssl->handshake != NULL && ssl->handshake->key_cert != NULL ) + key_cert = ssl->handshake->key_cert; + else + key_cert = ssl->conf->key_cert; + + return( key_cert == NULL ? NULL : key_cert->cert ); +} + +/* + * Check usage of a certificate wrt extensions: + * keyUsage, extendedKeyUsage (later), and nSCertType (later). + * + * Warning: cert_endpoint is the endpoint of the cert (ie, of our peer when we + * check a cert we received from them)! + * + * Return 0 if everything is OK, -1 if not. + */ +int mbedtls_ssl_check_cert_usage( const mbedtls_x509_crt *cert, + const mbedtls_ssl_ciphersuite_t *ciphersuite, + int cert_endpoint, + uint32_t *flags ); +#endif /* MBEDTLS_X509_CRT_PARSE_C */ + +void mbedtls_ssl_write_version( int major, int minor, int transport, + unsigned char ver[2] ); +void mbedtls_ssl_read_version( int *major, int *minor, int transport, + const unsigned char ver[2] ); + +static inline size_t mbedtls_ssl_hdr_len( const mbedtls_ssl_context *ssl ) +{ +#if defined(MBEDTLS_SSL_PROTO_DTLS) + if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) + return( 13 ); +#else + ((void) ssl); +#endif + return( 5 ); +} + +static inline size_t mbedtls_ssl_hs_hdr_len( const mbedtls_ssl_context *ssl ) +{ +#if defined(MBEDTLS_SSL_PROTO_DTLS) + if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) + return( 12 ); +#else + ((void) ssl); +#endif + return( 4 ); +} + +#if defined(MBEDTLS_SSL_PROTO_DTLS) +void mbedtls_ssl_send_flight_completed( mbedtls_ssl_context *ssl ); +void mbedtls_ssl_recv_flight_completed( mbedtls_ssl_context *ssl ); +int mbedtls_ssl_resend( mbedtls_ssl_context *ssl ); +int mbedtls_ssl_flight_transmit( mbedtls_ssl_context *ssl ); +#endif + +/* Visible for testing purposes only */ +#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) +int mbedtls_ssl_dtls_replay_check( mbedtls_ssl_context *ssl ); +void mbedtls_ssl_dtls_replay_update( mbedtls_ssl_context *ssl ); +#endif + +/* constant-time buffer comparison */ +static inline int mbedtls_ssl_safer_memcmp( const void *a, const void *b, size_t n ) +{ + size_t i; + volatile const unsigned char *A = (volatile const unsigned char *) a; + volatile const unsigned char *B = (volatile const unsigned char *) b; + volatile unsigned char diff = 0; + + for( i = 0; i < n; i++ ) + { + /* Read volatile data in order before computing diff. + * This avoids IAR compiler warning: + * 'the order of volatile accesses is undefined ..' */ + unsigned char x = A[i], y = B[i]; + diff |= x ^ y; + } + + return( diff ); +} + +#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \ + defined(MBEDTLS_SSL_PROTO_TLS1_1) +int mbedtls_ssl_get_key_exchange_md_ssl_tls( mbedtls_ssl_context *ssl, + unsigned char *output, + unsigned char *data, size_t data_len ); +#endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \ + MBEDTLS_SSL_PROTO_TLS1_1 */ + +#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \ + defined(MBEDTLS_SSL_PROTO_TLS1_2) +int mbedtls_ssl_get_key_exchange_md_tls1_2( mbedtls_ssl_context *ssl, + unsigned char *hash, size_t *hashlen, + unsigned char *data, size_t data_len, + mbedtls_md_type_t md_alg ); +#endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \ + MBEDTLS_SSL_PROTO_TLS1_2 */ + +#ifdef __cplusplus +} +#endif + +#endif /* ssl_internal.h */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/ssl_ticket.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/ssl_ticket.h new file mode 100644 index 0000000000000000000000000000000000000000..774a007a9f3b8e15977c0108fb22c638dd682462 --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/ssl_ticket.h @@ -0,0 +1,142 @@ +/** + * \file ssl_ticket.h + * + * \brief TLS server ticket callbacks implementation + */ +/* + * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ +#ifndef MBEDTLS_SSL_TICKET_H +#define MBEDTLS_SSL_TICKET_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +/* + * This implementation of the session ticket callbacks includes key + * management, rotating the keys periodically in order to preserve forward + * secrecy, when MBEDTLS_HAVE_TIME is defined. + */ + +#include "ssl.h" +#include "cipher.h" + +#if defined(MBEDTLS_THREADING_C) +#include "threading.h" +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \brief Information for session ticket protection + */ +typedef struct mbedtls_ssl_ticket_key +{ + unsigned char name[4]; /*!< random key identifier */ + uint32_t generation_time; /*!< key generation timestamp (seconds) */ + mbedtls_cipher_context_t ctx; /*!< context for auth enc/decryption */ +} +mbedtls_ssl_ticket_key; + +/** + * \brief Context for session ticket handling functions + */ +typedef struct mbedtls_ssl_ticket_context +{ + mbedtls_ssl_ticket_key keys[2]; /*!< ticket protection keys */ + unsigned char active; /*!< index of the currently active key */ + + uint32_t ticket_lifetime; /*!< lifetime of tickets in seconds */ + + /** Callback for getting (pseudo-)random numbers */ + int (*f_rng)(void *, unsigned char *, size_t); + void *p_rng; /*!< context for the RNG function */ + +#if defined(MBEDTLS_THREADING_C) + mbedtls_threading_mutex_t mutex; +#endif +} +mbedtls_ssl_ticket_context; + +/** + * \brief Initialize a ticket context. + * (Just make it ready for mbedtls_ssl_ticket_setup() + * or mbedtls_ssl_ticket_free().) + * + * \param ctx Context to be initialized + */ +void mbedtls_ssl_ticket_init( mbedtls_ssl_ticket_context *ctx ); + +/** + * \brief Prepare context to be actually used + * + * \param ctx Context to be set up + * \param f_rng RNG callback function + * \param p_rng RNG callback context + * \param cipher AEAD cipher to use for ticket protection. + * Recommended value: MBEDTLS_CIPHER_AES_256_GCM. + * \param lifetime Tickets lifetime in seconds + * Recommended value: 86400 (one day). + * + * \note It is highly recommended to select a cipher that is at + * least as strong as the the strongest ciphersuite + * supported. Usually that means a 256-bit key. + * + * \note The lifetime of the keys is twice the lifetime of tickets. + * It is recommended to pick a reasonnable lifetime so as not + * to negate the benefits of forward secrecy. + * + * \return 0 if successful, + * or a specific MBEDTLS_ERR_XXX error code + */ +int mbedtls_ssl_ticket_setup( mbedtls_ssl_ticket_context *ctx, + int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, + mbedtls_cipher_type_t cipher, + uint32_t lifetime ); + +/** + * \brief Implementation of the ticket write callback + * + * \note See \c mbedtls_ssl_ticket_write_t for description + */ +mbedtls_ssl_ticket_write_t mbedtls_ssl_ticket_write; + +/** + * \brief Implementation of the ticket parse callback + * + * \note See \c mbedtls_ssl_ticket_parse_t for description + */ +mbedtls_ssl_ticket_parse_t mbedtls_ssl_ticket_parse; + +/** + * \brief Free a context's content and zeroize it. + * + * \param ctx Context to be cleaned up + */ +void mbedtls_ssl_ticket_free( mbedtls_ssl_ticket_context *ctx ); + +#ifdef __cplusplus +} +#endif + +#endif /* ssl_ticket.h */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/threading.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/threading.h new file mode 100644 index 0000000000000000000000000000000000000000..92e6e6b987e7fd8486761bc5147ccc89c7b62a19 --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/threading.h @@ -0,0 +1,122 @@ +/** + * \file threading.h + * + * \brief Threading abstraction layer + */ +/* + * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ +#ifndef MBEDTLS_THREADING_H +#define MBEDTLS_THREADING_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* MBEDTLS_ERR_THREADING_FEATURE_UNAVAILABLE is deprecated and should not be + * used. */ +#define MBEDTLS_ERR_THREADING_FEATURE_UNAVAILABLE -0x001A /**< The selected feature is not available. */ + +#define MBEDTLS_ERR_THREADING_BAD_INPUT_DATA -0x001C /**< Bad input parameters to function. */ +#define MBEDTLS_ERR_THREADING_MUTEX_ERROR -0x001E /**< Locking / unlocking / free failed with error code. */ + +#if defined(MBEDTLS_THREADING_PTHREAD) +#include +typedef struct mbedtls_threading_mutex_t +{ + pthread_mutex_t mutex; + char is_valid; +} mbedtls_threading_mutex_t; +#endif + +#if defined(MBEDTLS_THREADING_ALT) +/* You should define the mbedtls_threading_mutex_t type in your header */ +#include "threading_alt.h" + +/** + * \brief Set your alternate threading implementation function + * pointers and initialize global mutexes. If used, this + * function must be called once in the main thread before any + * other mbed TLS function is called, and + * mbedtls_threading_free_alt() must be called once in the main + * thread after all other mbed TLS functions. + * + * \note mutex_init() and mutex_free() don't return a status code. + * If mutex_init() fails, it should leave its argument (the + * mutex) in a state such that mutex_lock() will fail when + * called with this argument. + * + * \param mutex_init the init function implementation + * \param mutex_free the free function implementation + * \param mutex_lock the lock function implementation + * \param mutex_unlock the unlock function implementation + */ +void mbedtls_threading_set_alt( void (*mutex_init)( mbedtls_threading_mutex_t * ), + void (*mutex_free)( mbedtls_threading_mutex_t * ), + int (*mutex_lock)( mbedtls_threading_mutex_t * ), + int (*mutex_unlock)( mbedtls_threading_mutex_t * ) ); + +/** + * \brief Free global mutexes. + */ +void mbedtls_threading_free_alt( void ); +#endif /* MBEDTLS_THREADING_ALT */ + +#if defined(MBEDTLS_THREADING_C) +/* + * The function pointers for mutex_init, mutex_free, mutex_ and mutex_unlock + * + * All these functions are expected to work or the result will be undefined. + */ +extern void (*mbedtls_mutex_init)( mbedtls_threading_mutex_t *mutex ); +extern void (*mbedtls_mutex_free)( mbedtls_threading_mutex_t *mutex ); +extern int (*mbedtls_mutex_lock)( mbedtls_threading_mutex_t *mutex ); +extern int (*mbedtls_mutex_unlock)( mbedtls_threading_mutex_t *mutex ); + +/* + * Global mutexes + */ +#if defined(MBEDTLS_FS_IO) +extern mbedtls_threading_mutex_t mbedtls_threading_readdir_mutex; +#endif + +#if defined(MBEDTLS_HAVE_TIME_DATE) && !defined(MBEDTLS_PLATFORM_GMTIME_R_ALT) +/* This mutex may or may not be used in the default definition of + * mbedtls_platform_gmtime_r(), but in order to determine that, + * we need to check POSIX features, hence modify _POSIX_C_SOURCE. + * With the current approach, this declaration is orphaned, lacking + * an accompanying definition, in case mbedtls_platform_gmtime_r() + * doesn't need it, but that's not a problem. */ +extern mbedtls_threading_mutex_t mbedtls_threading_gmtime_mutex; +#endif /* MBEDTLS_HAVE_TIME_DATE && !MBEDTLS_PLATFORM_GMTIME_R_ALT */ + +#endif /* MBEDTLS_THREADING_C */ + +#ifdef __cplusplus +} +#endif + +#endif /* threading.h */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/timing.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/timing.h new file mode 100644 index 0000000000000000000000000000000000000000..a965fe0d355a68bd9997dedc5cced8eebb2c3787 --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/timing.h @@ -0,0 +1,153 @@ +/** + * \file timing.h + * + * \brief Portable interface to timeouts and to the CPU cycle counter + */ +/* + * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ +#ifndef MBEDTLS_TIMING_H +#define MBEDTLS_TIMING_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#if !defined(MBEDTLS_TIMING_ALT) +// Regular implementation +// + +/** + * \brief timer structure + */ +struct mbedtls_timing_hr_time +{ + unsigned char opaque[32]; +}; + +/** + * \brief Context for mbedtls_timing_set/get_delay() + */ +typedef struct mbedtls_timing_delay_context +{ + struct mbedtls_timing_hr_time timer; + uint32_t int_ms; + uint32_t fin_ms; +} mbedtls_timing_delay_context; + +#else /* MBEDTLS_TIMING_ALT */ +#include "timing_alt.h" +#endif /* MBEDTLS_TIMING_ALT */ + +extern volatile int mbedtls_timing_alarmed; + +/** + * \brief Return the CPU cycle counter value + * + * \warning This is only a best effort! Do not rely on this! + * In particular, it is known to be unreliable on virtual + * machines. + * + * \note This value starts at an unspecified origin and + * may wrap around. + */ +unsigned long mbedtls_timing_hardclock( void ); + +/** + * \brief Return the elapsed time in milliseconds + * + * \param val points to a timer structure + * \param reset If 0, query the elapsed time. Otherwise (re)start the timer. + * + * \return Elapsed time since the previous reset in ms. When + * restarting, this is always 0. + * + * \note To initialize a timer, call this function with reset=1. + * + * Determining the elapsed time and resetting the timer is not + * atomic on all platforms, so after the sequence + * `{ get_timer(1); ...; time1 = get_timer(1); ...; time2 = + * get_timer(0) }` the value time1+time2 is only approximately + * the delay since the first reset. + */ +unsigned long mbedtls_timing_get_timer( struct mbedtls_timing_hr_time *val, int reset ); + +/** + * \brief Setup an alarm clock + * + * \param seconds delay before the "mbedtls_timing_alarmed" flag is set + * (must be >=0) + * + * \warning Only one alarm at a time is supported. In a threaded + * context, this means one for the whole process, not one per + * thread. + */ +void mbedtls_set_alarm( int seconds ); + +/** + * \brief Set a pair of delays to watch + * (See \c mbedtls_timing_get_delay().) + * + * \param data Pointer to timing data. + * Must point to a valid \c mbedtls_timing_delay_context struct. + * \param int_ms First (intermediate) delay in milliseconds. + * The effect if int_ms > fin_ms is unspecified. + * \param fin_ms Second (final) delay in milliseconds. + * Pass 0 to cancel the current delay. + * + * \note To set a single delay, either use \c mbedtls_timing_set_timer + * directly or use this function with int_ms == fin_ms. + */ +void mbedtls_timing_set_delay( void *data, uint32_t int_ms, uint32_t fin_ms ); + +/** + * \brief Get the status of delays + * (Memory helper: number of delays passed.) + * + * \param data Pointer to timing data + * Must point to a valid \c mbedtls_timing_delay_context struct. + * + * \return -1 if cancelled (fin_ms = 0), + * 0 if none of the delays are passed, + * 1 if only the intermediate delay is passed, + * 2 if the final delay is passed. + */ +int mbedtls_timing_get_delay( void *data ); + +#if defined(MBEDTLS_SELF_TEST) +/** + * \brief Checkup routine + * + * \return 0 if successful, or 1 if a test failed + */ +int mbedtls_timing_self_test( int verbose ); +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* timing.h */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/version.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/version.h new file mode 100644 index 0000000000000000000000000000000000000000..e0a2e7f6d6c6daa893065d9cdb41283a3fe3385d --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/version.h @@ -0,0 +1,112 @@ +/** + * \file version.h + * + * \brief Run-time version information + */ +/* + * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ +/* + * This set of compile-time defines and run-time variables can be used to + * determine the version number of the mbed TLS library used. + */ +#ifndef MBEDTLS_VERSION_H +#define MBEDTLS_VERSION_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +/** + * The version number x.y.z is split into three parts. + * Major, Minor, Patchlevel + */ +#define MBEDTLS_VERSION_MAJOR 2 +#define MBEDTLS_VERSION_MINOR 16 +#define MBEDTLS_VERSION_PATCH 6 + +/** + * The single version number has the following structure: + * MMNNPP00 + * Major version | Minor version | Patch version + */ +#define MBEDTLS_VERSION_NUMBER 0x02100600 +#define MBEDTLS_VERSION_STRING "2.16.6" +#define MBEDTLS_VERSION_STRING_FULL "mbed TLS 2.16.6" + +#if defined(MBEDTLS_VERSION_C) + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Get the version number. + * + * \return The constructed version number in the format + * MMNNPP00 (Major, Minor, Patch). + */ +unsigned int mbedtls_version_get_number( void ); + +/** + * Get the version string ("x.y.z"). + * + * \param string The string that will receive the value. + * (Should be at least 9 bytes in size) + */ +void mbedtls_version_get_string( char *string ); + +/** + * Get the full version string ("mbed TLS x.y.z"). + * + * \param string The string that will receive the value. The mbed TLS version + * string will use 18 bytes AT MOST including a terminating + * null byte. + * (So the buffer should be at least 18 bytes to receive this + * version string). + */ +void mbedtls_version_get_string_full( char *string ); + +/** + * \brief Check if support for a feature was compiled into this + * mbed TLS binary. This allows you to see at runtime if the + * library was for instance compiled with or without + * Multi-threading support. + * + * \note only checks against defines in the sections "System + * support", "mbed TLS modules" and "mbed TLS feature + * support" in config.h + * + * \param feature The string for the define to check (e.g. "MBEDTLS_AES_C") + * + * \return 0 if the feature is present, + * -1 if the feature is not present and + * -2 if support for feature checking as a whole was not + * compiled in. + */ +int mbedtls_version_check_feature( const char *feature ); + +#ifdef __cplusplus +} +#endif + +#endif /* MBEDTLS_VERSION_C */ + +#endif /* version.h */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/x509.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/x509.h new file mode 100644 index 0000000000000000000000000000000000000000..63aae32d870ec2c84bfe56b13f70cf1130abbfb9 --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/x509.h @@ -0,0 +1,337 @@ +/** + * \file x509.h + * + * \brief X.509 generic defines and structures + */ +/* + * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ +#ifndef MBEDTLS_X509_H +#define MBEDTLS_X509_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include "asn1.h" +#include "pk.h" + +#if defined(MBEDTLS_RSA_C) +#include "rsa.h" +#endif + +/** + * \addtogroup x509_module + * \{ + */ + +#if !defined(MBEDTLS_X509_MAX_INTERMEDIATE_CA) +/** + * Maximum number of intermediate CAs in a verification chain. + * That is, maximum length of the chain, excluding the end-entity certificate + * and the trusted root certificate. + * + * Set this to a low value to prevent an adversary from making you waste + * resources verifying an overlong certificate chain. + */ +#define MBEDTLS_X509_MAX_INTERMEDIATE_CA 8 +#endif + +/** + * \name X509 Error codes + * \{ + */ +#define MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE -0x2080 /**< Unavailable feature, e.g. RSA hashing/encryption combination. */ +#define MBEDTLS_ERR_X509_UNKNOWN_OID -0x2100 /**< Requested OID is unknown. */ +#define MBEDTLS_ERR_X509_INVALID_FORMAT -0x2180 /**< The CRT/CRL/CSR format is invalid, e.g. different type expected. */ +#define MBEDTLS_ERR_X509_INVALID_VERSION -0x2200 /**< The CRT/CRL/CSR version element is invalid. */ +#define MBEDTLS_ERR_X509_INVALID_SERIAL -0x2280 /**< The serial tag or value is invalid. */ +#define MBEDTLS_ERR_X509_INVALID_ALG -0x2300 /**< The algorithm tag or value is invalid. */ +#define MBEDTLS_ERR_X509_INVALID_NAME -0x2380 /**< The name tag or value is invalid. */ +#define MBEDTLS_ERR_X509_INVALID_DATE -0x2400 /**< The date tag or value is invalid. */ +#define MBEDTLS_ERR_X509_INVALID_SIGNATURE -0x2480 /**< The signature tag or value invalid. */ +#define MBEDTLS_ERR_X509_INVALID_EXTENSIONS -0x2500 /**< The extension tag or value is invalid. */ +#define MBEDTLS_ERR_X509_UNKNOWN_VERSION -0x2580 /**< CRT/CRL/CSR has an unsupported version number. */ +#define MBEDTLS_ERR_X509_UNKNOWN_SIG_ALG -0x2600 /**< Signature algorithm (oid) is unsupported. */ +#define MBEDTLS_ERR_X509_SIG_MISMATCH -0x2680 /**< Signature algorithms do not match. (see \c ::mbedtls_x509_crt sig_oid) */ +#define MBEDTLS_ERR_X509_CERT_VERIFY_FAILED -0x2700 /**< Certificate verification failed, e.g. CRL, CA or signature check failed. */ +#define MBEDTLS_ERR_X509_CERT_UNKNOWN_FORMAT -0x2780 /**< Format not recognized as DER or PEM. */ +#define MBEDTLS_ERR_X509_BAD_INPUT_DATA -0x2800 /**< Input invalid. */ +#define MBEDTLS_ERR_X509_ALLOC_FAILED -0x2880 /**< Allocation of memory failed. */ +#define MBEDTLS_ERR_X509_FILE_IO_ERROR -0x2900 /**< Read/write of file failed. */ +#define MBEDTLS_ERR_X509_BUFFER_TOO_SMALL -0x2980 /**< Destination buffer is too small. */ +#define MBEDTLS_ERR_X509_FATAL_ERROR -0x3000 /**< A fatal error occurred, eg the chain is too long or the vrfy callback failed. */ +/* \} name */ + +/** + * \name X509 Verify codes + * \{ + */ +/* Reminder: update x509_crt_verify_strings[] in library/x509_crt.c */ +#define MBEDTLS_X509_BADCERT_EXPIRED 0x01 /**< The certificate validity has expired. */ +#define MBEDTLS_X509_BADCERT_REVOKED 0x02 /**< The certificate has been revoked (is on a CRL). */ +#define MBEDTLS_X509_BADCERT_CN_MISMATCH 0x04 /**< The certificate Common Name (CN) does not match with the expected CN. */ +#define MBEDTLS_X509_BADCERT_NOT_TRUSTED 0x08 /**< The certificate is not correctly signed by the trusted CA. */ +#define MBEDTLS_X509_BADCRL_NOT_TRUSTED 0x10 /**< The CRL is not correctly signed by the trusted CA. */ +#define MBEDTLS_X509_BADCRL_EXPIRED 0x20 /**< The CRL is expired. */ +#define MBEDTLS_X509_BADCERT_MISSING 0x40 /**< Certificate was missing. */ +#define MBEDTLS_X509_BADCERT_SKIP_VERIFY 0x80 /**< Certificate verification was skipped. */ +#define MBEDTLS_X509_BADCERT_OTHER 0x0100 /**< Other reason (can be used by verify callback) */ +#define MBEDTLS_X509_BADCERT_FUTURE 0x0200 /**< The certificate validity starts in the future. */ +#define MBEDTLS_X509_BADCRL_FUTURE 0x0400 /**< The CRL is from the future */ +#define MBEDTLS_X509_BADCERT_KEY_USAGE 0x0800 /**< Usage does not match the keyUsage extension. */ +#define MBEDTLS_X509_BADCERT_EXT_KEY_USAGE 0x1000 /**< Usage does not match the extendedKeyUsage extension. */ +#define MBEDTLS_X509_BADCERT_NS_CERT_TYPE 0x2000 /**< Usage does not match the nsCertType extension. */ +#define MBEDTLS_X509_BADCERT_BAD_MD 0x4000 /**< The certificate is signed with an unacceptable hash. */ +#define MBEDTLS_X509_BADCERT_BAD_PK 0x8000 /**< The certificate is signed with an unacceptable PK alg (eg RSA vs ECDSA). */ +#define MBEDTLS_X509_BADCERT_BAD_KEY 0x010000 /**< The certificate is signed with an unacceptable key (eg bad curve, RSA too short). */ +#define MBEDTLS_X509_BADCRL_BAD_MD 0x020000 /**< The CRL is signed with an unacceptable hash. */ +#define MBEDTLS_X509_BADCRL_BAD_PK 0x040000 /**< The CRL is signed with an unacceptable PK alg (eg RSA vs ECDSA). */ +#define MBEDTLS_X509_BADCRL_BAD_KEY 0x080000 /**< The CRL is signed with an unacceptable key (eg bad curve, RSA too short). */ + +/* \} name */ +/* \} addtogroup x509_module */ + +/* + * X.509 v3 Key Usage Extension flags + * Reminder: update x509_info_key_usage() when adding new flags. + */ +#define MBEDTLS_X509_KU_DIGITAL_SIGNATURE (0x80) /* bit 0 */ +#define MBEDTLS_X509_KU_NON_REPUDIATION (0x40) /* bit 1 */ +#define MBEDTLS_X509_KU_KEY_ENCIPHERMENT (0x20) /* bit 2 */ +#define MBEDTLS_X509_KU_DATA_ENCIPHERMENT (0x10) /* bit 3 */ +#define MBEDTLS_X509_KU_KEY_AGREEMENT (0x08) /* bit 4 */ +#define MBEDTLS_X509_KU_KEY_CERT_SIGN (0x04) /* bit 5 */ +#define MBEDTLS_X509_KU_CRL_SIGN (0x02) /* bit 6 */ +#define MBEDTLS_X509_KU_ENCIPHER_ONLY (0x01) /* bit 7 */ +#define MBEDTLS_X509_KU_DECIPHER_ONLY (0x8000) /* bit 8 */ + +/* + * Netscape certificate types + * (http://www.mozilla.org/projects/security/pki/nss/tech-notes/tn3.html) + */ + +#define MBEDTLS_X509_NS_CERT_TYPE_SSL_CLIENT (0x80) /* bit 0 */ +#define MBEDTLS_X509_NS_CERT_TYPE_SSL_SERVER (0x40) /* bit 1 */ +#define MBEDTLS_X509_NS_CERT_TYPE_EMAIL (0x20) /* bit 2 */ +#define MBEDTLS_X509_NS_CERT_TYPE_OBJECT_SIGNING (0x10) /* bit 3 */ +#define MBEDTLS_X509_NS_CERT_TYPE_RESERVED (0x08) /* bit 4 */ +#define MBEDTLS_X509_NS_CERT_TYPE_SSL_CA (0x04) /* bit 5 */ +#define MBEDTLS_X509_NS_CERT_TYPE_EMAIL_CA (0x02) /* bit 6 */ +#define MBEDTLS_X509_NS_CERT_TYPE_OBJECT_SIGNING_CA (0x01) /* bit 7 */ + +/* + * X.509 extension types + * + * Comments refer to the status for using certificates. Status can be + * different for writing certificates or reading CRLs or CSRs. + */ +#define MBEDTLS_X509_EXT_AUTHORITY_KEY_IDENTIFIER (1 << 0) +#define MBEDTLS_X509_EXT_SUBJECT_KEY_IDENTIFIER (1 << 1) +#define MBEDTLS_X509_EXT_KEY_USAGE (1 << 2) +#define MBEDTLS_X509_EXT_CERTIFICATE_POLICIES (1 << 3) +#define MBEDTLS_X509_EXT_POLICY_MAPPINGS (1 << 4) +#define MBEDTLS_X509_EXT_SUBJECT_ALT_NAME (1 << 5) /* Supported (DNS) */ +#define MBEDTLS_X509_EXT_ISSUER_ALT_NAME (1 << 6) +#define MBEDTLS_X509_EXT_SUBJECT_DIRECTORY_ATTRS (1 << 7) +#define MBEDTLS_X509_EXT_BASIC_CONSTRAINTS (1 << 8) /* Supported */ +#define MBEDTLS_X509_EXT_NAME_CONSTRAINTS (1 << 9) +#define MBEDTLS_X509_EXT_POLICY_CONSTRAINTS (1 << 10) +#define MBEDTLS_X509_EXT_EXTENDED_KEY_USAGE (1 << 11) +#define MBEDTLS_X509_EXT_CRL_DISTRIBUTION_POINTS (1 << 12) +#define MBEDTLS_X509_EXT_INIHIBIT_ANYPOLICY (1 << 13) +#define MBEDTLS_X509_EXT_FRESHEST_CRL (1 << 14) + +#define MBEDTLS_X509_EXT_NS_CERT_TYPE (1 << 16) + +/* + * Storage format identifiers + * Recognized formats: PEM and DER + */ +#define MBEDTLS_X509_FORMAT_DER 1 +#define MBEDTLS_X509_FORMAT_PEM 2 + +#define MBEDTLS_X509_MAX_DN_NAME_SIZE 256 /**< Maximum value size of a DN entry */ + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \addtogroup x509_module + * \{ */ + +/** + * \name Structures for parsing X.509 certificates, CRLs and CSRs + * \{ + */ + +/** + * Type-length-value structure that allows for ASN1 using DER. + */ +typedef mbedtls_asn1_buf mbedtls_x509_buf; + +/** + * Container for ASN1 bit strings. + */ +typedef mbedtls_asn1_bitstring mbedtls_x509_bitstring; + +/** + * Container for ASN1 named information objects. + * It allows for Relative Distinguished Names (e.g. cn=localhost,ou=code,etc.). + */ +typedef mbedtls_asn1_named_data mbedtls_x509_name; + +/** + * Container for a sequence of ASN.1 items + */ +typedef mbedtls_asn1_sequence mbedtls_x509_sequence; + +/** Container for date and time (precision in seconds). */ +typedef struct mbedtls_x509_time +{ + int year, mon, day; /**< Date. */ + int hour, min, sec; /**< Time. */ +} +mbedtls_x509_time; + +/** \} name Structures for parsing X.509 certificates, CRLs and CSRs */ +/** \} addtogroup x509_module */ + +/** + * \brief Store the certificate DN in printable form into buf; + * no more than size characters will be written. + * + * \param buf Buffer to write to + * \param size Maximum size of buffer + * \param dn The X509 name to represent + * + * \return The length of the string written (not including the + * terminated nul byte), or a negative error code. + */ +int mbedtls_x509_dn_gets( char *buf, size_t size, const mbedtls_x509_name *dn ); + +/** + * \brief Store the certificate serial in printable form into buf; + * no more than size characters will be written. + * + * \param buf Buffer to write to + * \param size Maximum size of buffer + * \param serial The X509 serial to represent + * + * \return The length of the string written (not including the + * terminated nul byte), or a negative error code. + */ +int mbedtls_x509_serial_gets( char *buf, size_t size, const mbedtls_x509_buf *serial ); + +/** + * \brief Check a given mbedtls_x509_time against the system time + * and tell if it's in the past. + * + * \note Intended usage is "if( is_past( valid_to ) ) ERROR". + * Hence the return value of 1 if on internal errors. + * + * \param to mbedtls_x509_time to check + * + * \return 1 if the given time is in the past or an error occurred, + * 0 otherwise. + */ +int mbedtls_x509_time_is_past( const mbedtls_x509_time *to ); + +/** + * \brief Check a given mbedtls_x509_time against the system time + * and tell if it's in the future. + * + * \note Intended usage is "if( is_future( valid_from ) ) ERROR". + * Hence the return value of 1 if on internal errors. + * + * \param from mbedtls_x509_time to check + * + * \return 1 if the given time is in the future or an error occurred, + * 0 otherwise. + */ +int mbedtls_x509_time_is_future( const mbedtls_x509_time *from ); + +#if defined(MBEDTLS_SELF_TEST) + +/** + * \brief Checkup routine + * + * \return 0 if successful, or 1 if the test failed + */ +int mbedtls_x509_self_test( int verbose ); + +#endif /* MBEDTLS_SELF_TEST */ + +/* + * Internal module functions. You probably do not want to use these unless you + * know you do. + */ +int mbedtls_x509_get_name( unsigned char **p, const unsigned char *end, + mbedtls_x509_name *cur ); +int mbedtls_x509_get_alg_null( unsigned char **p, const unsigned char *end, + mbedtls_x509_buf *alg ); +int mbedtls_x509_get_alg( unsigned char **p, const unsigned char *end, + mbedtls_x509_buf *alg, mbedtls_x509_buf *params ); +#if defined(MBEDTLS_X509_RSASSA_PSS_SUPPORT) +int mbedtls_x509_get_rsassa_pss_params( const mbedtls_x509_buf *params, + mbedtls_md_type_t *md_alg, mbedtls_md_type_t *mgf_md, + int *salt_len ); +#endif +int mbedtls_x509_get_sig( unsigned char **p, const unsigned char *end, mbedtls_x509_buf *sig ); +int mbedtls_x509_get_sig_alg( const mbedtls_x509_buf *sig_oid, const mbedtls_x509_buf *sig_params, + mbedtls_md_type_t *md_alg, mbedtls_pk_type_t *pk_alg, + void **sig_opts ); +int mbedtls_x509_get_time( unsigned char **p, const unsigned char *end, + mbedtls_x509_time *t ); +int mbedtls_x509_get_serial( unsigned char **p, const unsigned char *end, + mbedtls_x509_buf *serial ); +int mbedtls_x509_get_ext( unsigned char **p, const unsigned char *end, + mbedtls_x509_buf *ext, int tag ); +int mbedtls_x509_sig_alg_gets( char *buf, size_t size, const mbedtls_x509_buf *sig_oid, + mbedtls_pk_type_t pk_alg, mbedtls_md_type_t md_alg, + const void *sig_opts ); +int mbedtls_x509_key_size_helper( char *buf, size_t buf_size, const char *name ); +int mbedtls_x509_string_to_names( mbedtls_asn1_named_data **head, const char *name ); +int mbedtls_x509_set_extension( mbedtls_asn1_named_data **head, const char *oid, size_t oid_len, + int critical, const unsigned char *val, + size_t val_len ); +int mbedtls_x509_write_extensions( unsigned char **p, unsigned char *start, + mbedtls_asn1_named_data *first ); +int mbedtls_x509_write_names( unsigned char **p, unsigned char *start, + mbedtls_asn1_named_data *first ); +int mbedtls_x509_write_sig( unsigned char **p, unsigned char *start, + const char *oid, size_t oid_len, + unsigned char *sig, size_t size ); + +#define MBEDTLS_X509_SAFE_SNPRINTF \ + do { \ + if( ret < 0 || (size_t) ret >= n ) \ + return( MBEDTLS_ERR_X509_BUFFER_TOO_SMALL ); \ + \ + n -= (size_t) ret; \ + p += (size_t) ret; \ + } while( 0 ) + +#ifdef __cplusplus +} +#endif + +#endif /* x509.h */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/x509_crl.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/x509_crl.h new file mode 100644 index 0000000000000000000000000000000000000000..fa838d68cbfebdb984deb801b36ba13ab1ea39c6 --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/x509_crl.h @@ -0,0 +1,174 @@ +/** + * \file x509_crl.h + * + * \brief X.509 certificate revocation list parsing + */ +/* + * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ +#ifndef MBEDTLS_X509_CRL_H +#define MBEDTLS_X509_CRL_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include "x509.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \addtogroup x509_module + * \{ */ + +/** + * \name Structures and functions for parsing CRLs + * \{ + */ + +/** + * Certificate revocation list entry. + * Contains the CA-specific serial numbers and revocation dates. + */ +typedef struct mbedtls_x509_crl_entry +{ + mbedtls_x509_buf raw; + + mbedtls_x509_buf serial; + + mbedtls_x509_time revocation_date; + + mbedtls_x509_buf entry_ext; + + struct mbedtls_x509_crl_entry *next; +} +mbedtls_x509_crl_entry; + +/** + * Certificate revocation list structure. + * Every CRL may have multiple entries. + */ +typedef struct mbedtls_x509_crl +{ + mbedtls_x509_buf raw; /**< The raw certificate data (DER). */ + mbedtls_x509_buf tbs; /**< The raw certificate body (DER). The part that is To Be Signed. */ + + int version; /**< CRL version (1=v1, 2=v2) */ + mbedtls_x509_buf sig_oid; /**< CRL signature type identifier */ + + mbedtls_x509_buf issuer_raw; /**< The raw issuer data (DER). */ + + mbedtls_x509_name issuer; /**< The parsed issuer data (named information object). */ + + mbedtls_x509_time this_update; + mbedtls_x509_time next_update; + + mbedtls_x509_crl_entry entry; /**< The CRL entries containing the certificate revocation times for this CA. */ + + mbedtls_x509_buf crl_ext; + + mbedtls_x509_buf sig_oid2; + mbedtls_x509_buf sig; + mbedtls_md_type_t sig_md; /**< Internal representation of the MD algorithm of the signature algorithm, e.g. MBEDTLS_MD_SHA256 */ + mbedtls_pk_type_t sig_pk; /**< Internal representation of the Public Key algorithm of the signature algorithm, e.g. MBEDTLS_PK_RSA */ + void *sig_opts; /**< Signature options to be passed to mbedtls_pk_verify_ext(), e.g. for RSASSA-PSS */ + + struct mbedtls_x509_crl *next; +} +mbedtls_x509_crl; + +/** + * \brief Parse a DER-encoded CRL and append it to the chained list + * + * \param chain points to the start of the chain + * \param buf buffer holding the CRL data in DER format + * \param buflen size of the buffer + * (including the terminating null byte for PEM data) + * + * \return 0 if successful, or a specific X509 or PEM error code + */ +int mbedtls_x509_crl_parse_der( mbedtls_x509_crl *chain, + const unsigned char *buf, size_t buflen ); +/** + * \brief Parse one or more CRLs and append them to the chained list + * + * \note Multiple CRLs are accepted only if using PEM format + * + * \param chain points to the start of the chain + * \param buf buffer holding the CRL data in PEM or DER format + * \param buflen size of the buffer + * (including the terminating null byte for PEM data) + * + * \return 0 if successful, or a specific X509 or PEM error code + */ +int mbedtls_x509_crl_parse( mbedtls_x509_crl *chain, const unsigned char *buf, size_t buflen ); + +#if defined(MBEDTLS_FS_IO) +/** + * \brief Load one or more CRLs and append them to the chained list + * + * \note Multiple CRLs are accepted only if using PEM format + * + * \param chain points to the start of the chain + * \param path filename to read the CRLs from (in PEM or DER encoding) + * + * \return 0 if successful, or a specific X509 or PEM error code + */ +int mbedtls_x509_crl_parse_file( mbedtls_x509_crl *chain, const char *path ); +#endif /* MBEDTLS_FS_IO */ + +/** + * \brief Returns an informational string about the CRL. + * + * \param buf Buffer to write to + * \param size Maximum size of buffer + * \param prefix A line prefix + * \param crl The X509 CRL to represent + * + * \return The length of the string written (not including the + * terminated nul byte), or a negative error code. + */ +int mbedtls_x509_crl_info( char *buf, size_t size, const char *prefix, + const mbedtls_x509_crl *crl ); + +/** + * \brief Initialize a CRL (chain) + * + * \param crl CRL chain to initialize + */ +void mbedtls_x509_crl_init( mbedtls_x509_crl *crl ); + +/** + * \brief Unallocate all CRL data + * + * \param crl CRL chain to free + */ +void mbedtls_x509_crl_free( mbedtls_x509_crl *crl ); + +/* \} name */ +/* \} addtogroup x509_module */ + +#ifdef __cplusplus +} +#endif + +#endif /* mbedtls_x509_crl.h */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/x509_crt.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/x509_crt.h new file mode 100644 index 0000000000000000000000000000000000000000..670bd10d8910d111f54c0598e0f97f8fef6d7a63 --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/x509_crt.h @@ -0,0 +1,785 @@ +/** + * \file x509_crt.h + * + * \brief X.509 certificate parsing and writing + */ +/* + * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ +#ifndef MBEDTLS_X509_CRT_H +#define MBEDTLS_X509_CRT_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include "x509.h" +#include "x509_crl.h" + +/** + * \addtogroup x509_module + * \{ + */ + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \name Structures and functions for parsing and writing X.509 certificates + * \{ + */ + +/** + * Container for an X.509 certificate. The certificate may be chained. + */ +typedef struct mbedtls_x509_crt +{ + mbedtls_x509_buf raw; /**< The raw certificate data (DER). */ + mbedtls_x509_buf tbs; /**< The raw certificate body (DER). The part that is To Be Signed. */ + + int version; /**< The X.509 version. (1=v1, 2=v2, 3=v3) */ + mbedtls_x509_buf serial; /**< Unique id for certificate issued by a specific CA. */ + mbedtls_x509_buf sig_oid; /**< Signature algorithm, e.g. sha1RSA */ + + mbedtls_x509_buf issuer_raw; /**< The raw issuer data (DER). Used for quick comparison. */ + mbedtls_x509_buf subject_raw; /**< The raw subject data (DER). Used for quick comparison. */ + + mbedtls_x509_name issuer; /**< The parsed issuer data (named information object). */ + mbedtls_x509_name subject; /**< The parsed subject data (named information object). */ + + mbedtls_x509_time valid_from; /**< Start time of certificate validity. */ + mbedtls_x509_time valid_to; /**< End time of certificate validity. */ + + mbedtls_pk_context pk; /**< Container for the public key context. */ + + mbedtls_x509_buf issuer_id; /**< Optional X.509 v2/v3 issuer unique identifier. */ + mbedtls_x509_buf subject_id; /**< Optional X.509 v2/v3 subject unique identifier. */ + mbedtls_x509_buf v3_ext; /**< Optional X.509 v3 extensions. */ + mbedtls_x509_sequence subject_alt_names; /**< Optional list of Subject Alternative Names (Only dNSName supported). */ + + int ext_types; /**< Bit string containing detected and parsed extensions */ + int ca_istrue; /**< Optional Basic Constraint extension value: 1 if this certificate belongs to a CA, 0 otherwise. */ + int max_pathlen; /**< Optional Basic Constraint extension value: The maximum path length to the root certificate. Path length is 1 higher than RFC 5280 'meaning', so 1+ */ + + unsigned int key_usage; /**< Optional key usage extension value: See the values in x509.h */ + + mbedtls_x509_sequence ext_key_usage; /**< Optional list of extended key usage OIDs. */ + + unsigned char ns_cert_type; /**< Optional Netscape certificate type extension value: See the values in x509.h */ + + mbedtls_x509_buf sig; /**< Signature: hash of the tbs part signed with the private key. */ + mbedtls_md_type_t sig_md; /**< Internal representation of the MD algorithm of the signature algorithm, e.g. MBEDTLS_MD_SHA256 */ + mbedtls_pk_type_t sig_pk; /**< Internal representation of the Public Key algorithm of the signature algorithm, e.g. MBEDTLS_PK_RSA */ + void *sig_opts; /**< Signature options to be passed to mbedtls_pk_verify_ext(), e.g. for RSASSA-PSS */ + + struct mbedtls_x509_crt *next; /**< Next certificate in the CA-chain. */ +} +mbedtls_x509_crt; + +/** + * Build flag from an algorithm/curve identifier (pk, md, ecp) + * Since 0 is always XXX_NONE, ignore it. + */ +#define MBEDTLS_X509_ID_FLAG( id ) ( 1 << ( (id) - 1 ) ) + +/** + * Security profile for certificate verification. + * + * All lists are bitfields, built by ORing flags from MBEDTLS_X509_ID_FLAG(). + */ +typedef struct mbedtls_x509_crt_profile +{ + uint32_t allowed_mds; /**< MDs for signatures */ + uint32_t allowed_pks; /**< PK algs for signatures */ + uint32_t allowed_curves; /**< Elliptic curves for ECDSA */ + uint32_t rsa_min_bitlen; /**< Minimum size for RSA keys */ +} +mbedtls_x509_crt_profile; + +#define MBEDTLS_X509_CRT_VERSION_1 0 +#define MBEDTLS_X509_CRT_VERSION_2 1 +#define MBEDTLS_X509_CRT_VERSION_3 2 + +#define MBEDTLS_X509_RFC5280_MAX_SERIAL_LEN 32 +#define MBEDTLS_X509_RFC5280_UTC_TIME_LEN 15 + +#if !defined( MBEDTLS_X509_MAX_FILE_PATH_LEN ) +#define MBEDTLS_X509_MAX_FILE_PATH_LEN 512 +#endif + +/** + * Container for writing a certificate (CRT) + */ +typedef struct mbedtls_x509write_cert +{ + int version; + mbedtls_mpi serial; + mbedtls_pk_context *subject_key; + mbedtls_pk_context *issuer_key; + mbedtls_asn1_named_data *subject; + mbedtls_asn1_named_data *issuer; + mbedtls_md_type_t md_alg; + char not_before[MBEDTLS_X509_RFC5280_UTC_TIME_LEN + 1]; + char not_after[MBEDTLS_X509_RFC5280_UTC_TIME_LEN + 1]; + mbedtls_asn1_named_data *extensions; +} +mbedtls_x509write_cert; + +/** + * Item in a verification chain: cert and flags for it + */ +typedef struct { + mbedtls_x509_crt *crt; + uint32_t flags; +} mbedtls_x509_crt_verify_chain_item; + +/** + * Max size of verification chain: end-entity + intermediates + trusted root + */ +#define MBEDTLS_X509_MAX_VERIFY_CHAIN_SIZE ( MBEDTLS_X509_MAX_INTERMEDIATE_CA + 2 ) + +/** + * Verification chain as built by \c mbedtls_crt_verify_chain() + */ +typedef struct +{ + mbedtls_x509_crt_verify_chain_item items[MBEDTLS_X509_MAX_VERIFY_CHAIN_SIZE]; + unsigned len; +} mbedtls_x509_crt_verify_chain; + +#if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) + +/** + * \brief Context for resuming X.509 verify operations + */ +typedef struct +{ + /* for check_signature() */ + mbedtls_pk_restart_ctx pk; + + /* for find_parent_in() */ + mbedtls_x509_crt *parent; /* non-null iff parent_in in progress */ + mbedtls_x509_crt *fallback_parent; + int fallback_signature_is_good; + + /* for find_parent() */ + int parent_is_trusted; /* -1 if find_parent is not in progress */ + + /* for verify_chain() */ + enum { + x509_crt_rs_none, + x509_crt_rs_find_parent, + } in_progress; /* none if no operation is in progress */ + int self_cnt; + mbedtls_x509_crt_verify_chain ver_chain; + +} mbedtls_x509_crt_restart_ctx; + +#else /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */ + +/* Now we can declare functions that take a pointer to that */ +typedef void mbedtls_x509_crt_restart_ctx; + +#endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */ + +#if defined(MBEDTLS_X509_CRT_PARSE_C) +/** + * Default security profile. Should provide a good balance between security + * and compatibility with current deployments. + */ +extern const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_default; + +/** + * Expected next default profile. Recommended for new deployments. + * Currently targets a 128-bit security level, except for RSA-2048. + */ +extern const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_next; + +/** + * NSA Suite B profile. + */ +extern const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_suiteb; + +/** + * \brief Parse a single DER formatted certificate and add it + * to the chained list. + * + * \param chain points to the start of the chain + * \param buf buffer holding the certificate DER data + * \param buflen size of the buffer + * + * \return 0 if successful, or a specific X509 or PEM error code + */ +int mbedtls_x509_crt_parse_der( mbedtls_x509_crt *chain, const unsigned char *buf, + size_t buflen ); + +/** + * \brief Parse one DER-encoded or one or more concatenated PEM-encoded + * certificates and add them to the chained list. + * + * For CRTs in PEM encoding, the function parses permissively: + * if at least one certificate can be parsed, the function + * returns the number of certificates for which parsing failed + * (hence \c 0 if all certificates were parsed successfully). + * If no certificate could be parsed, the function returns + * the first (negative) error encountered during parsing. + * + * PEM encoded certificates may be interleaved by other data + * such as human readable descriptions of their content, as + * long as the certificates are enclosed in the PEM specific + * '-----{BEGIN/END} CERTIFICATE-----' delimiters. + * + * \param chain The chain to which to add the parsed certificates. + * \param buf The buffer holding the certificate data in PEM or DER format. + * For certificates in PEM encoding, this may be a concatenation + * of multiple certificates; for DER encoding, the buffer must + * comprise exactly one certificate. + * \param buflen The size of \p buf, including the terminating \c NULL byte + * in case of PEM encoded data. + * + * \return \c 0 if all certificates were parsed successfully. + * \return The (positive) number of certificates that couldn't + * be parsed if parsing was partly successful (see above). + * \return A negative X509 or PEM error code otherwise. + * + */ +int mbedtls_x509_crt_parse( mbedtls_x509_crt *chain, const unsigned char *buf, size_t buflen ); + +#if defined(MBEDTLS_FS_IO) +/** + * \brief Load one or more certificates and add them + * to the chained list. Parses permissively. If some + * certificates can be parsed, the result is the number + * of failed certificates it encountered. If none complete + * correctly, the first error is returned. + * + * \param chain points to the start of the chain + * \param path filename to read the certificates from + * + * \return 0 if all certificates parsed successfully, a positive number + * if partly successful or a specific X509 or PEM error code + */ +int mbedtls_x509_crt_parse_file( mbedtls_x509_crt *chain, const char *path ); + +/** + * \brief Load one or more certificate files from a path and add them + * to the chained list. Parses permissively. If some + * certificates can be parsed, the result is the number + * of failed certificates it encountered. If none complete + * correctly, the first error is returned. + * + * \param chain points to the start of the chain + * \param path directory / folder to read the certificate files from + * + * \return 0 if all certificates parsed successfully, a positive number + * if partly successful or a specific X509 or PEM error code + */ +int mbedtls_x509_crt_parse_path( mbedtls_x509_crt *chain, const char *path ); +#endif /* MBEDTLS_FS_IO */ + +/** + * \brief Returns an informational string about the + * certificate. + * + * \param buf Buffer to write to + * \param size Maximum size of buffer + * \param prefix A line prefix + * \param crt The X509 certificate to represent + * + * \return The length of the string written (not including the + * terminated nul byte), or a negative error code. + */ +int mbedtls_x509_crt_info( char *buf, size_t size, const char *prefix, + const mbedtls_x509_crt *crt ); + +/** + * \brief Returns an informational string about the + * verification status of a certificate. + * + * \param buf Buffer to write to + * \param size Maximum size of buffer + * \param prefix A line prefix + * \param flags Verification flags created by mbedtls_x509_crt_verify() + * + * \return The length of the string written (not including the + * terminated nul byte), or a negative error code. + */ +int mbedtls_x509_crt_verify_info( char *buf, size_t size, const char *prefix, + uint32_t flags ); + +/** + * \brief Verify the certificate signature + * + * The verify callback is a user-supplied callback that + * can clear / modify / add flags for a certificate. If set, + * the verification callback is called for each + * certificate in the chain (from the trust-ca down to the + * presented crt). The parameters for the callback are: + * (void *parameter, mbedtls_x509_crt *crt, int certificate_depth, + * int *flags). With the flags representing current flags for + * that specific certificate and the certificate depth from + * the bottom (Peer cert depth = 0). + * + * All flags left after returning from the callback + * are also returned to the application. The function should + * return 0 for anything (including invalid certificates) + * other than fatal error, as a non-zero return code + * immediately aborts the verification process. For fatal + * errors, a specific error code should be used (different + * from MBEDTLS_ERR_X509_CERT_VERIFY_FAILED which should not + * be returned at this point), or MBEDTLS_ERR_X509_FATAL_ERROR + * can be used if no better code is available. + * + * \note In case verification failed, the results can be displayed + * using \c mbedtls_x509_crt_verify_info() + * + * \note Same as \c mbedtls_x509_crt_verify_with_profile() with the + * default security profile. + * + * \note It is your responsibility to provide up-to-date CRLs for + * all trusted CAs. If no CRL is provided for the CA that was + * used to sign the certificate, CRL verification is skipped + * silently, that is *without* setting any flag. + * + * \note The \c trust_ca list can contain two types of certificates: + * (1) those of trusted root CAs, so that certificates + * chaining up to those CAs will be trusted, and (2) + * self-signed end-entity certificates to be trusted (for + * specific peers you know) - in that case, the self-signed + * certificate doesn't need to have the CA bit set. + * + * \param crt a certificate (chain) to be verified + * \param trust_ca the list of trusted CAs (see note above) + * \param ca_crl the list of CRLs for trusted CAs (see note above) + * \param cn expected Common Name (can be set to + * NULL if the CN must not be verified) + * \param flags result of the verification + * \param f_vrfy verification function + * \param p_vrfy verification parameter + * + * \return 0 (and flags set to 0) if the chain was verified and valid, + * MBEDTLS_ERR_X509_CERT_VERIFY_FAILED if the chain was verified + * but found to be invalid, in which case *flags will have one + * or more MBEDTLS_X509_BADCERT_XXX or MBEDTLS_X509_BADCRL_XXX + * flags set, or another error (and flags set to 0xffffffff) + * in case of a fatal error encountered during the + * verification process. + */ +int mbedtls_x509_crt_verify( mbedtls_x509_crt *crt, + mbedtls_x509_crt *trust_ca, + mbedtls_x509_crl *ca_crl, + const char *cn, uint32_t *flags, + int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *), + void *p_vrfy ); + +/** + * \brief Verify the certificate signature according to profile + * + * \note Same as \c mbedtls_x509_crt_verify(), but with explicit + * security profile. + * + * \note The restrictions on keys (RSA minimum size, allowed curves + * for ECDSA) apply to all certificates: trusted root, + * intermediate CAs if any, and end entity certificate. + * + * \param crt a certificate (chain) to be verified + * \param trust_ca the list of trusted CAs + * \param ca_crl the list of CRLs for trusted CAs + * \param profile security profile for verification + * \param cn expected Common Name (can be set to + * NULL if the CN must not be verified) + * \param flags result of the verification + * \param f_vrfy verification function + * \param p_vrfy verification parameter + * + * \return 0 if successful or MBEDTLS_ERR_X509_CERT_VERIFY_FAILED + * in which case *flags will have one or more + * MBEDTLS_X509_BADCERT_XXX or MBEDTLS_X509_BADCRL_XXX flags + * set, + * or another error in case of a fatal error encountered + * during the verification process. + */ +int mbedtls_x509_crt_verify_with_profile( mbedtls_x509_crt *crt, + mbedtls_x509_crt *trust_ca, + mbedtls_x509_crl *ca_crl, + const mbedtls_x509_crt_profile *profile, + const char *cn, uint32_t *flags, + int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *), + void *p_vrfy ); + +/** + * \brief Restartable version of \c mbedtls_crt_verify_with_profile() + * + * \note Performs the same job as \c mbedtls_crt_verify_with_profile() + * but can return early and restart according to the limit + * set with \c mbedtls_ecp_set_max_ops() to reduce blocking. + * + * \param crt a certificate (chain) to be verified + * \param trust_ca the list of trusted CAs + * \param ca_crl the list of CRLs for trusted CAs + * \param profile security profile for verification + * \param cn expected Common Name (can be set to + * NULL if the CN must not be verified) + * \param flags result of the verification + * \param f_vrfy verification function + * \param p_vrfy verification parameter + * \param rs_ctx restart context (NULL to disable restart) + * + * \return See \c mbedtls_crt_verify_with_profile(), or + * \return #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of + * operations was reached: see \c mbedtls_ecp_set_max_ops(). + */ +int mbedtls_x509_crt_verify_restartable( mbedtls_x509_crt *crt, + mbedtls_x509_crt *trust_ca, + mbedtls_x509_crl *ca_crl, + const mbedtls_x509_crt_profile *profile, + const char *cn, uint32_t *flags, + int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *), + void *p_vrfy, + mbedtls_x509_crt_restart_ctx *rs_ctx ); + +#if defined(MBEDTLS_X509_CHECK_KEY_USAGE) +/** + * \brief Check usage of certificate against keyUsage extension. + * + * \param crt Leaf certificate used. + * \param usage Intended usage(s) (eg MBEDTLS_X509_KU_KEY_ENCIPHERMENT + * before using the certificate to perform an RSA key + * exchange). + * + * \note Except for decipherOnly and encipherOnly, a bit set in the + * usage argument means this bit MUST be set in the + * certificate. For decipherOnly and encipherOnly, it means + * that bit MAY be set. + * + * \return 0 is these uses of the certificate are allowed, + * MBEDTLS_ERR_X509_BAD_INPUT_DATA if the keyUsage extension + * is present but does not match the usage argument. + * + * \note You should only call this function on leaf certificates, on + * (intermediate) CAs the keyUsage extension is automatically + * checked by \c mbedtls_x509_crt_verify(). + */ +int mbedtls_x509_crt_check_key_usage( const mbedtls_x509_crt *crt, + unsigned int usage ); +#endif /* MBEDTLS_X509_CHECK_KEY_USAGE) */ + +#if defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE) +/** + * \brief Check usage of certificate against extendedKeyUsage. + * + * \param crt Leaf certificate used. + * \param usage_oid Intended usage (eg MBEDTLS_OID_SERVER_AUTH or + * MBEDTLS_OID_CLIENT_AUTH). + * \param usage_len Length of usage_oid (eg given by MBEDTLS_OID_SIZE()). + * + * \return 0 if this use of the certificate is allowed, + * MBEDTLS_ERR_X509_BAD_INPUT_DATA if not. + * + * \note Usually only makes sense on leaf certificates. + */ +int mbedtls_x509_crt_check_extended_key_usage( const mbedtls_x509_crt *crt, + const char *usage_oid, + size_t usage_len ); +#endif /* MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE */ + +#if defined(MBEDTLS_X509_CRL_PARSE_C) +/** + * \brief Verify the certificate revocation status + * + * \param crt a certificate to be verified + * \param crl the CRL to verify against + * + * \return 1 if the certificate is revoked, 0 otherwise + * + */ +int mbedtls_x509_crt_is_revoked( const mbedtls_x509_crt *crt, const mbedtls_x509_crl *crl ); +#endif /* MBEDTLS_X509_CRL_PARSE_C */ + +/** + * \brief Initialize a certificate (chain) + * + * \param crt Certificate chain to initialize + */ +void mbedtls_x509_crt_init( mbedtls_x509_crt *crt ); + +/** + * \brief Unallocate all certificate data + * + * \param crt Certificate chain to free + */ +void mbedtls_x509_crt_free( mbedtls_x509_crt *crt ); + +#if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE) +/** + * \brief Initialize a restart context + */ +void mbedtls_x509_crt_restart_init( mbedtls_x509_crt_restart_ctx *ctx ); + +/** + * \brief Free the components of a restart context + */ +void mbedtls_x509_crt_restart_free( mbedtls_x509_crt_restart_ctx *ctx ); +#endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */ +#endif /* MBEDTLS_X509_CRT_PARSE_C */ + +/* \} name */ +/* \} addtogroup x509_module */ + +#if defined(MBEDTLS_X509_CRT_WRITE_C) +/** + * \brief Initialize a CRT writing context + * + * \param ctx CRT context to initialize + */ +void mbedtls_x509write_crt_init( mbedtls_x509write_cert *ctx ); + +/** + * \brief Set the verion for a Certificate + * Default: MBEDTLS_X509_CRT_VERSION_3 + * + * \param ctx CRT context to use + * \param version version to set (MBEDTLS_X509_CRT_VERSION_1, MBEDTLS_X509_CRT_VERSION_2 or + * MBEDTLS_X509_CRT_VERSION_3) + */ +void mbedtls_x509write_crt_set_version( mbedtls_x509write_cert *ctx, int version ); + +/** + * \brief Set the serial number for a Certificate. + * + * \param ctx CRT context to use + * \param serial serial number to set + * + * \return 0 if successful + */ +int mbedtls_x509write_crt_set_serial( mbedtls_x509write_cert *ctx, const mbedtls_mpi *serial ); + +/** + * \brief Set the validity period for a Certificate + * Timestamps should be in string format for UTC timezone + * i.e. "YYYYMMDDhhmmss" + * e.g. "20131231235959" for December 31st 2013 + * at 23:59:59 + * + * \param ctx CRT context to use + * \param not_before not_before timestamp + * \param not_after not_after timestamp + * + * \return 0 if timestamp was parsed successfully, or + * a specific error code + */ +int mbedtls_x509write_crt_set_validity( mbedtls_x509write_cert *ctx, const char *not_before, + const char *not_after ); + +/** + * \brief Set the issuer name for a Certificate + * Issuer names should contain a comma-separated list + * of OID types and values: + * e.g. "C=UK,O=ARM,CN=mbed TLS CA" + * + * \param ctx CRT context to use + * \param issuer_name issuer name to set + * + * \return 0 if issuer name was parsed successfully, or + * a specific error code + */ +int mbedtls_x509write_crt_set_issuer_name( mbedtls_x509write_cert *ctx, + const char *issuer_name ); + +/** + * \brief Set the subject name for a Certificate + * Subject names should contain a comma-separated list + * of OID types and values: + * e.g. "C=UK,O=ARM,CN=mbed TLS Server 1" + * + * \param ctx CRT context to use + * \param subject_name subject name to set + * + * \return 0 if subject name was parsed successfully, or + * a specific error code + */ +int mbedtls_x509write_crt_set_subject_name( mbedtls_x509write_cert *ctx, + const char *subject_name ); + +/** + * \brief Set the subject public key for the certificate + * + * \param ctx CRT context to use + * \param key public key to include + */ +void mbedtls_x509write_crt_set_subject_key( mbedtls_x509write_cert *ctx, mbedtls_pk_context *key ); + +/** + * \brief Set the issuer key used for signing the certificate + * + * \param ctx CRT context to use + * \param key private key to sign with + */ +void mbedtls_x509write_crt_set_issuer_key( mbedtls_x509write_cert *ctx, mbedtls_pk_context *key ); + +/** + * \brief Set the MD algorithm to use for the signature + * (e.g. MBEDTLS_MD_SHA1) + * + * \param ctx CRT context to use + * \param md_alg MD algorithm to use + */ +void mbedtls_x509write_crt_set_md_alg( mbedtls_x509write_cert *ctx, mbedtls_md_type_t md_alg ); + +/** + * \brief Generic function to add to or replace an extension in the + * CRT + * + * \param ctx CRT context to use + * \param oid OID of the extension + * \param oid_len length of the OID + * \param critical if the extension is critical (per the RFC's definition) + * \param val value of the extension OCTET STRING + * \param val_len length of the value data + * + * \return 0 if successful, or a MBEDTLS_ERR_X509_ALLOC_FAILED + */ +int mbedtls_x509write_crt_set_extension( mbedtls_x509write_cert *ctx, + const char *oid, size_t oid_len, + int critical, + const unsigned char *val, size_t val_len ); + +/** + * \brief Set the basicConstraints extension for a CRT + * + * \param ctx CRT context to use + * \param is_ca is this a CA certificate + * \param max_pathlen maximum length of certificate chains below this + * certificate (only for CA certificates, -1 is + * inlimited) + * + * \return 0 if successful, or a MBEDTLS_ERR_X509_ALLOC_FAILED + */ +int mbedtls_x509write_crt_set_basic_constraints( mbedtls_x509write_cert *ctx, + int is_ca, int max_pathlen ); + +#if defined(MBEDTLS_SHA1_C) +/** + * \brief Set the subjectKeyIdentifier extension for a CRT + * Requires that mbedtls_x509write_crt_set_subject_key() has been + * called before + * + * \param ctx CRT context to use + * + * \return 0 if successful, or a MBEDTLS_ERR_X509_ALLOC_FAILED + */ +int mbedtls_x509write_crt_set_subject_key_identifier( mbedtls_x509write_cert *ctx ); + +/** + * \brief Set the authorityKeyIdentifier extension for a CRT + * Requires that mbedtls_x509write_crt_set_issuer_key() has been + * called before + * + * \param ctx CRT context to use + * + * \return 0 if successful, or a MBEDTLS_ERR_X509_ALLOC_FAILED + */ +int mbedtls_x509write_crt_set_authority_key_identifier( mbedtls_x509write_cert *ctx ); +#endif /* MBEDTLS_SHA1_C */ + +/** + * \brief Set the Key Usage Extension flags + * (e.g. MBEDTLS_X509_KU_DIGITAL_SIGNATURE | MBEDTLS_X509_KU_KEY_CERT_SIGN) + * + * \param ctx CRT context to use + * \param key_usage key usage flags to set + * + * \return 0 if successful, or MBEDTLS_ERR_X509_ALLOC_FAILED + */ +int mbedtls_x509write_crt_set_key_usage( mbedtls_x509write_cert *ctx, + unsigned int key_usage ); + +/** + * \brief Set the Netscape Cert Type flags + * (e.g. MBEDTLS_X509_NS_CERT_TYPE_SSL_CLIENT | MBEDTLS_X509_NS_CERT_TYPE_EMAIL) + * + * \param ctx CRT context to use + * \param ns_cert_type Netscape Cert Type flags to set + * + * \return 0 if successful, or MBEDTLS_ERR_X509_ALLOC_FAILED + */ +int mbedtls_x509write_crt_set_ns_cert_type( mbedtls_x509write_cert *ctx, + unsigned char ns_cert_type ); + +/** + * \brief Free the contents of a CRT write context + * + * \param ctx CRT context to free + */ +void mbedtls_x509write_crt_free( mbedtls_x509write_cert *ctx ); + +/** + * \brief Write a built up certificate to a X509 DER structure + * Note: data is written at the end of the buffer! Use the + * return value to determine where you should start + * using the buffer + * + * \param ctx certificate to write away + * \param buf buffer to write to + * \param size size of the buffer + * \param f_rng RNG function (for signature, see note) + * \param p_rng RNG parameter + * + * \return length of data written if successful, or a specific + * error code + * + * \note f_rng may be NULL if RSA is used for signature and the + * signature is made offline (otherwise f_rng is desirable + * for countermeasures against timing attacks). + * ECDSA signatures always require a non-NULL f_rng. + */ +int mbedtls_x509write_crt_der( mbedtls_x509write_cert *ctx, unsigned char *buf, size_t size, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng ); + +#if defined(MBEDTLS_PEM_WRITE_C) +/** + * \brief Write a built up certificate to a X509 PEM string + * + * \param ctx certificate to write away + * \param buf buffer to write to + * \param size size of the buffer + * \param f_rng RNG function (for signature, see note) + * \param p_rng RNG parameter + * + * \return 0 if successful, or a specific error code + * + * \note f_rng may be NULL if RSA is used for signature and the + * signature is made offline (otherwise f_rng is desirable + * for countermeasures against timing attacks). + * ECDSA signatures always require a non-NULL f_rng. + */ +int mbedtls_x509write_crt_pem( mbedtls_x509write_cert *ctx, unsigned char *buf, size_t size, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng ); +#endif /* MBEDTLS_PEM_WRITE_C */ +#endif /* MBEDTLS_X509_CRT_WRITE_C */ + +#ifdef __cplusplus +} +#endif + +#endif /* mbedtls_x509_crt.h */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/x509_csr.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/x509_csr.h new file mode 100644 index 0000000000000000000000000000000000000000..a3c28048e011e9f8d5346ca022983709c5efb301 --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/x509_csr.h @@ -0,0 +1,307 @@ +/** + * \file x509_csr.h + * + * \brief X.509 certificate signing request parsing and writing + */ +/* + * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ +#ifndef MBEDTLS_X509_CSR_H +#define MBEDTLS_X509_CSR_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include "x509.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \addtogroup x509_module + * \{ */ + +/** + * \name Structures and functions for X.509 Certificate Signing Requests (CSR) + * \{ + */ + +/** + * Certificate Signing Request (CSR) structure. + */ +typedef struct mbedtls_x509_csr +{ + mbedtls_x509_buf raw; /**< The raw CSR data (DER). */ + mbedtls_x509_buf cri; /**< The raw CertificateRequestInfo body (DER). */ + + int version; /**< CSR version (1=v1). */ + + mbedtls_x509_buf subject_raw; /**< The raw subject data (DER). */ + mbedtls_x509_name subject; /**< The parsed subject data (named information object). */ + + mbedtls_pk_context pk; /**< Container for the public key context. */ + + mbedtls_x509_buf sig_oid; + mbedtls_x509_buf sig; + mbedtls_md_type_t sig_md; /**< Internal representation of the MD algorithm of the signature algorithm, e.g. MBEDTLS_MD_SHA256 */ + mbedtls_pk_type_t sig_pk; /**< Internal representation of the Public Key algorithm of the signature algorithm, e.g. MBEDTLS_PK_RSA */ + void *sig_opts; /**< Signature options to be passed to mbedtls_pk_verify_ext(), e.g. for RSASSA-PSS */ +} +mbedtls_x509_csr; + +/** + * Container for writing a CSR + */ +typedef struct mbedtls_x509write_csr +{ + mbedtls_pk_context *key; + mbedtls_asn1_named_data *subject; + mbedtls_md_type_t md_alg; + mbedtls_asn1_named_data *extensions; +} +mbedtls_x509write_csr; + +#if defined(MBEDTLS_X509_CSR_PARSE_C) +/** + * \brief Load a Certificate Signing Request (CSR) in DER format + * + * \note CSR attributes (if any) are currently silently ignored. + * + * \param csr CSR context to fill + * \param buf buffer holding the CRL data + * \param buflen size of the buffer + * + * \return 0 if successful, or a specific X509 error code + */ +int mbedtls_x509_csr_parse_der( mbedtls_x509_csr *csr, + const unsigned char *buf, size_t buflen ); + +/** + * \brief Load a Certificate Signing Request (CSR), DER or PEM format + * + * \note See notes for \c mbedtls_x509_csr_parse_der() + * + * \param csr CSR context to fill + * \param buf buffer holding the CRL data + * \param buflen size of the buffer + * (including the terminating null byte for PEM data) + * + * \return 0 if successful, or a specific X509 or PEM error code + */ +int mbedtls_x509_csr_parse( mbedtls_x509_csr *csr, const unsigned char *buf, size_t buflen ); + +#if defined(MBEDTLS_FS_IO) +/** + * \brief Load a Certificate Signing Request (CSR) + * + * \note See notes for \c mbedtls_x509_csr_parse() + * + * \param csr CSR context to fill + * \param path filename to read the CSR from + * + * \return 0 if successful, or a specific X509 or PEM error code + */ +int mbedtls_x509_csr_parse_file( mbedtls_x509_csr *csr, const char *path ); +#endif /* MBEDTLS_FS_IO */ + +/** + * \brief Returns an informational string about the + * CSR. + * + * \param buf Buffer to write to + * \param size Maximum size of buffer + * \param prefix A line prefix + * \param csr The X509 CSR to represent + * + * \return The length of the string written (not including the + * terminated nul byte), or a negative error code. + */ +int mbedtls_x509_csr_info( char *buf, size_t size, const char *prefix, + const mbedtls_x509_csr *csr ); + +/** + * \brief Initialize a CSR + * + * \param csr CSR to initialize + */ +void mbedtls_x509_csr_init( mbedtls_x509_csr *csr ); + +/** + * \brief Unallocate all CSR data + * + * \param csr CSR to free + */ +void mbedtls_x509_csr_free( mbedtls_x509_csr *csr ); +#endif /* MBEDTLS_X509_CSR_PARSE_C */ + +/* \} name */ +/* \} addtogroup x509_module */ + +#if defined(MBEDTLS_X509_CSR_WRITE_C) +/** + * \brief Initialize a CSR context + * + * \param ctx CSR context to initialize + */ +void mbedtls_x509write_csr_init( mbedtls_x509write_csr *ctx ); + +/** + * \brief Set the subject name for a CSR + * Subject names should contain a comma-separated list + * of OID types and values: + * e.g. "C=UK,O=ARM,CN=mbed TLS Server 1" + * + * \param ctx CSR context to use + * \param subject_name subject name to set + * + * \return 0 if subject name was parsed successfully, or + * a specific error code + */ +int mbedtls_x509write_csr_set_subject_name( mbedtls_x509write_csr *ctx, + const char *subject_name ); + +/** + * \brief Set the key for a CSR (public key will be included, + * private key used to sign the CSR when writing it) + * + * \param ctx CSR context to use + * \param key Asymetric key to include + */ +void mbedtls_x509write_csr_set_key( mbedtls_x509write_csr *ctx, mbedtls_pk_context *key ); + +/** + * \brief Set the MD algorithm to use for the signature + * (e.g. MBEDTLS_MD_SHA1) + * + * \param ctx CSR context to use + * \param md_alg MD algorithm to use + */ +void mbedtls_x509write_csr_set_md_alg( mbedtls_x509write_csr *ctx, mbedtls_md_type_t md_alg ); + +/** + * \brief Set the Key Usage Extension flags + * (e.g. MBEDTLS_X509_KU_DIGITAL_SIGNATURE | MBEDTLS_X509_KU_KEY_CERT_SIGN) + * + * \param ctx CSR context to use + * \param key_usage key usage flags to set + * + * \return 0 if successful, or MBEDTLS_ERR_X509_ALLOC_FAILED + * + * \note The decipherOnly flag from the Key Usage + * extension is represented by bit 8 (i.e. + * 0x8000), which cannot typically be represented + * in an unsigned char. Therefore, the flag + * decipherOnly (i.e. + * #MBEDTLS_X509_KU_DECIPHER_ONLY) cannot be set using this + * function. + */ +int mbedtls_x509write_csr_set_key_usage( mbedtls_x509write_csr *ctx, unsigned char key_usage ); + +/** + * \brief Set the Netscape Cert Type flags + * (e.g. MBEDTLS_X509_NS_CERT_TYPE_SSL_CLIENT | MBEDTLS_X509_NS_CERT_TYPE_EMAIL) + * + * \param ctx CSR context to use + * \param ns_cert_type Netscape Cert Type flags to set + * + * \return 0 if successful, or MBEDTLS_ERR_X509_ALLOC_FAILED + */ +int mbedtls_x509write_csr_set_ns_cert_type( mbedtls_x509write_csr *ctx, + unsigned char ns_cert_type ); + +/** + * \brief Generic function to add to or replace an extension in the + * CSR + * + * \param ctx CSR context to use + * \param oid OID of the extension + * \param oid_len length of the OID + * \param val value of the extension OCTET STRING + * \param val_len length of the value data + * + * \return 0 if successful, or a MBEDTLS_ERR_X509_ALLOC_FAILED + */ +int mbedtls_x509write_csr_set_extension( mbedtls_x509write_csr *ctx, + const char *oid, size_t oid_len, + const unsigned char *val, size_t val_len ); + +/** + * \brief Free the contents of a CSR context + * + * \param ctx CSR context to free + */ +void mbedtls_x509write_csr_free( mbedtls_x509write_csr *ctx ); + +/** + * \brief Write a CSR (Certificate Signing Request) to a + * DER structure + * Note: data is written at the end of the buffer! Use the + * return value to determine where you should start + * using the buffer + * + * \param ctx CSR to write away + * \param buf buffer to write to + * \param size size of the buffer + * \param f_rng RNG function (for signature, see note) + * \param p_rng RNG parameter + * + * \return length of data written if successful, or a specific + * error code + * + * \note f_rng may be NULL if RSA is used for signature and the + * signature is made offline (otherwise f_rng is desirable + * for countermeasures against timing attacks). + * ECDSA signatures always require a non-NULL f_rng. + */ +int mbedtls_x509write_csr_der( mbedtls_x509write_csr *ctx, unsigned char *buf, size_t size, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng ); + +#if defined(MBEDTLS_PEM_WRITE_C) +/** + * \brief Write a CSR (Certificate Signing Request) to a + * PEM string + * + * \param ctx CSR to write away + * \param buf buffer to write to + * \param size size of the buffer + * \param f_rng RNG function (for signature, see note) + * \param p_rng RNG parameter + * + * \return 0 if successful, or a specific error code + * + * \note f_rng may be NULL if RSA is used for signature and the + * signature is made offline (otherwise f_rng is desirable + * for countermeasures against timing attacks). + * ECDSA signatures always require a non-NULL f_rng. + */ +int mbedtls_x509write_csr_pem( mbedtls_x509write_csr *ctx, unsigned char *buf, size_t size, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng ); +#endif /* MBEDTLS_PEM_WRITE_C */ +#endif /* MBEDTLS_X509_CSR_WRITE_C */ + +#ifdef __cplusplus +} +#endif + +#endif /* mbedtls_x509_csr.h */ diff --git a/sdk_liteos/third_party/mbedtls/include/mbedtls/xtea.h b/sdk_liteos/third_party/mbedtls/include/mbedtls/xtea.h new file mode 100644 index 0000000000000000000000000000000000000000..b47f5535085e028f8a31025cdd3af45aba7b40d6 --- /dev/null +++ b/sdk_liteos/third_party/mbedtls/include/mbedtls/xtea.h @@ -0,0 +1,139 @@ +/** + * \file xtea.h + * + * \brief XTEA block cipher (32-bit) + */ +/* + * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ +#ifndef MBEDTLS_XTEA_H +#define MBEDTLS_XTEA_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include +#include + +#define MBEDTLS_XTEA_ENCRYPT 1 +#define MBEDTLS_XTEA_DECRYPT 0 + +#define MBEDTLS_ERR_XTEA_INVALID_INPUT_LENGTH -0x0028 /**< The data input has an invalid length. */ + +/* MBEDTLS_ERR_XTEA_HW_ACCEL_FAILED is deprecated and should not be used. */ +#define MBEDTLS_ERR_XTEA_HW_ACCEL_FAILED -0x0029 /**< XTEA hardware accelerator failed. */ + +#ifdef __cplusplus +extern "C" { +#endif + +#if !defined(MBEDTLS_XTEA_ALT) +// Regular implementation +// + +/** + * \brief XTEA context structure + */ +typedef struct mbedtls_xtea_context +{ + uint32_t k[4]; /*!< key */ +} +mbedtls_xtea_context; + +#else /* MBEDTLS_XTEA_ALT */ +#include "xtea_alt.h" +#endif /* MBEDTLS_XTEA_ALT */ + +/** + * \brief Initialize XTEA context + * + * \param ctx XTEA context to be initialized + */ +void mbedtls_xtea_init( mbedtls_xtea_context *ctx ); + +/** + * \brief Clear XTEA context + * + * \param ctx XTEA context to be cleared + */ +void mbedtls_xtea_free( mbedtls_xtea_context *ctx ); + +/** + * \brief XTEA key schedule + * + * \param ctx XTEA context to be initialized + * \param key the secret key + */ +void mbedtls_xtea_setup( mbedtls_xtea_context *ctx, const unsigned char key[16] ); + +/** + * \brief XTEA cipher function + * + * \param ctx XTEA context + * \param mode MBEDTLS_XTEA_ENCRYPT or MBEDTLS_XTEA_DECRYPT + * \param input 8-byte input block + * \param output 8-byte output block + * + * \return 0 if successful + */ +int mbedtls_xtea_crypt_ecb( mbedtls_xtea_context *ctx, + int mode, + const unsigned char input[8], + unsigned char output[8] ); + +#if defined(MBEDTLS_CIPHER_MODE_CBC) +/** + * \brief XTEA CBC cipher function + * + * \param ctx XTEA context + * \param mode MBEDTLS_XTEA_ENCRYPT or MBEDTLS_XTEA_DECRYPT + * \param length the length of input, multiple of 8 + * \param iv initialization vector for CBC mode + * \param input input block + * \param output output block + * + * \return 0 if successful, + * MBEDTLS_ERR_XTEA_INVALID_INPUT_LENGTH if the length % 8 != 0 + */ +int mbedtls_xtea_crypt_cbc( mbedtls_xtea_context *ctx, + int mode, + size_t length, + unsigned char iv[8], + const unsigned char *input, + unsigned char *output); +#endif /* MBEDTLS_CIPHER_MODE_CBC */ + +#if defined(MBEDTLS_SELF_TEST) + +/** + * \brief Checkup routine + * + * \return 0 if successful, or 1 if the test failed + */ +int mbedtls_xtea_self_test( int verbose ); + +#endif /* MBEDTLS_SELF_TEST */ + +#ifdef __cplusplus +} +#endif + +#endif /* xtea.h */ diff --git a/sdk_liteos/third_party/u-boot-v2019.07/hisilicon_patch/hisilicon-u-boot-v2019.07.patch b/sdk_liteos/third_party/u-boot-v2019.07/hisilicon_patch/hisilicon-u-boot-v2019.07.patch new file mode 100755 index 0000000000000000000000000000000000000000..7014944a0ea369b64221d891721a0d3d6d95360b --- /dev/null +++ b/sdk_liteos/third_party/u-boot-v2019.07/hisilicon_patch/hisilicon-u-boot-v2019.07.patch @@ -0,0 +1,1328 @@ +diff -Nur u-boot-v2019.07/lib/crc32.c u-boot-v2019.07_ok/lib/crc32.c +--- u-boot-v2019.07/lib/crc32.c 2020-05-30 23:14:30.908000000 +0800 ++++ u-boot-v2019.07_ok/lib/crc32.c 2020-05-30 12:06:17.000000000 +0800 +@@ -8,259 +8,139 @@ + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +-#ifdef USE_HOSTCC +-#include +-#else +-#include +-#include +-#endif +-#include +-#include ++#define ZEXPORT /* empty */ ++#define cpu_to_le32(x) (x) ++#define le32_to_cpu(x) (x) ++#define tole(x) cpu_to_le32(x) ++typedef unsigned char uint8_t; ++typedef unsigned short uint16_t; ++typedef unsigned int uint32_t; ++typedef unsigned int uint; ++typedef unsigned char bytef; ++typedef unsigned int size_t; ++typedef unsigned int uintptr_t; + +-#if defined(CONFIG_HW_WATCHDOG) || defined(CONFIG_WATCHDOG) +-#include +-#endif +-#include "u-boot/zlib.h" +- +-#ifdef USE_HOSTCC +-#define __efi_runtime +-#define __efi_runtime_data +-#endif +- +-#define tole(x) cpu_to_le32(x) +- +-#ifdef CONFIG_DYNAMIC_CRC_TABLE +- +-static int __efi_runtime_data crc_table_empty = 1; +-static uint32_t __efi_runtime_data crc_table[256]; +-static void __efi_runtime make_crc_table OF((void)); +- +-/* +- Generate a table for a byte-wise 32-bit CRC calculation on the polynomial: +- x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1. +- +- Polynomials over GF(2) are represented in binary, one bit per coefficient, +- with the lowest powers in the most significant bit. Then adding polynomials +- is just exclusive-or, and multiplying a polynomial by x is a right shift by +- one. If we call the above polynomial p, and represent a byte as the +- polynomial q, also with the lowest power in the most significant bit (so the +- byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p, +- where a mod b means the remainder after dividing a by b. +- +- This calculation is done using the shift-register method of multiplying and +- taking the remainder. The register is initialized to zero, and for each +- incoming bit, x^32 is added mod p to the register if the bit is a one (where +- x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by +- x (which is shifting right by one and adding x^32 mod p if the bit shifted +- out is a one). We start with the highest power (least significant bit) of +- q and repeat for all eight bits of q. +- +- The table is simply the CRC of all possible eight bit values. This is all +- the information needed to generate CRC's on data a byte at a time for all +- combinations of CRC register values and incoming bytes. +-*/ +-static void __efi_runtime make_crc_table(void) +-{ +- uint32_t c; +- int n, k; +- uLong poly; /* polynomial exclusive-or pattern */ +- /* terms of polynomial defining this crc (except x^32): */ +- static Byte __efi_runtime_data p[] = { +- 0, 1, 2, 4, 5, 7, 8, 10, 11, 12, 16, 22, 23, 26}; +- +- /* make exclusive-or pattern from polynomial (0xedb88320L) */ +- poly = 0L; +- for (n = 0; n < sizeof(p)/sizeof(Byte); n++) +- poly |= 1L << (31 - p[n]); +- +- for (n = 0; n < 256; n++) +- { +- c = (uLong)n; +- for (k = 0; k < 8; k++) +- c = c & 1 ? poly ^ (c >> 1) : c >> 1; +- crc_table[n] = tole(c); +- } +- crc_table_empty = 0; +-} +-#else + /* ======================================================================== + * Table of CRC-32's of all single-byte values (made by make_crc_table) + */ +- +-static const uint32_t __efi_runtime_data crc_table[256] = { +-tole(0x00000000L), tole(0x77073096L), tole(0xee0e612cL), tole(0x990951baL), +-tole(0x076dc419L), tole(0x706af48fL), tole(0xe963a535L), tole(0x9e6495a3L), +-tole(0x0edb8832L), tole(0x79dcb8a4L), tole(0xe0d5e91eL), tole(0x97d2d988L), +-tole(0x09b64c2bL), tole(0x7eb17cbdL), tole(0xe7b82d07L), tole(0x90bf1d91L), +-tole(0x1db71064L), tole(0x6ab020f2L), tole(0xf3b97148L), tole(0x84be41deL), +-tole(0x1adad47dL), tole(0x6ddde4ebL), tole(0xf4d4b551L), tole(0x83d385c7L), +-tole(0x136c9856L), tole(0x646ba8c0L), tole(0xfd62f97aL), tole(0x8a65c9ecL), +-tole(0x14015c4fL), tole(0x63066cd9L), tole(0xfa0f3d63L), tole(0x8d080df5L), +-tole(0x3b6e20c8L), tole(0x4c69105eL), tole(0xd56041e4L), tole(0xa2677172L), +-tole(0x3c03e4d1L), tole(0x4b04d447L), tole(0xd20d85fdL), tole(0xa50ab56bL), +-tole(0x35b5a8faL), tole(0x42b2986cL), tole(0xdbbbc9d6L), tole(0xacbcf940L), +-tole(0x32d86ce3L), tole(0x45df5c75L), tole(0xdcd60dcfL), tole(0xabd13d59L), +-tole(0x26d930acL), tole(0x51de003aL), tole(0xc8d75180L), tole(0xbfd06116L), +-tole(0x21b4f4b5L), tole(0x56b3c423L), tole(0xcfba9599L), tole(0xb8bda50fL), +-tole(0x2802b89eL), tole(0x5f058808L), tole(0xc60cd9b2L), tole(0xb10be924L), +-tole(0x2f6f7c87L), tole(0x58684c11L), tole(0xc1611dabL), tole(0xb6662d3dL), +-tole(0x76dc4190L), tole(0x01db7106L), tole(0x98d220bcL), tole(0xefd5102aL), +-tole(0x71b18589L), tole(0x06b6b51fL), tole(0x9fbfe4a5L), tole(0xe8b8d433L), +-tole(0x7807c9a2L), tole(0x0f00f934L), tole(0x9609a88eL), tole(0xe10e9818L), +-tole(0x7f6a0dbbL), tole(0x086d3d2dL), tole(0x91646c97L), tole(0xe6635c01L), +-tole(0x6b6b51f4L), tole(0x1c6c6162L), tole(0x856530d8L), tole(0xf262004eL), +-tole(0x6c0695edL), tole(0x1b01a57bL), tole(0x8208f4c1L), tole(0xf50fc457L), +-tole(0x65b0d9c6L), tole(0x12b7e950L), tole(0x8bbeb8eaL), tole(0xfcb9887cL), +-tole(0x62dd1ddfL), tole(0x15da2d49L), tole(0x8cd37cf3L), tole(0xfbd44c65L), +-tole(0x4db26158L), tole(0x3ab551ceL), tole(0xa3bc0074L), tole(0xd4bb30e2L), +-tole(0x4adfa541L), tole(0x3dd895d7L), tole(0xa4d1c46dL), tole(0xd3d6f4fbL), +-tole(0x4369e96aL), tole(0x346ed9fcL), tole(0xad678846L), tole(0xda60b8d0L), +-tole(0x44042d73L), tole(0x33031de5L), tole(0xaa0a4c5fL), tole(0xdd0d7cc9L), +-tole(0x5005713cL), tole(0x270241aaL), tole(0xbe0b1010L), tole(0xc90c2086L), +-tole(0x5768b525L), tole(0x206f85b3L), tole(0xb966d409L), tole(0xce61e49fL), +-tole(0x5edef90eL), tole(0x29d9c998L), tole(0xb0d09822L), tole(0xc7d7a8b4L), +-tole(0x59b33d17L), tole(0x2eb40d81L), tole(0xb7bd5c3bL), tole(0xc0ba6cadL), +-tole(0xedb88320L), tole(0x9abfb3b6L), tole(0x03b6e20cL), tole(0x74b1d29aL), +-tole(0xead54739L), tole(0x9dd277afL), tole(0x04db2615L), tole(0x73dc1683L), +-tole(0xe3630b12L), tole(0x94643b84L), tole(0x0d6d6a3eL), tole(0x7a6a5aa8L), +-tole(0xe40ecf0bL), tole(0x9309ff9dL), tole(0x0a00ae27L), tole(0x7d079eb1L), +-tole(0xf00f9344L), tole(0x8708a3d2L), tole(0x1e01f268L), tole(0x6906c2feL), +-tole(0xf762575dL), tole(0x806567cbL), tole(0x196c3671L), tole(0x6e6b06e7L), +-tole(0xfed41b76L), tole(0x89d32be0L), tole(0x10da7a5aL), tole(0x67dd4accL), +-tole(0xf9b9df6fL), tole(0x8ebeeff9L), tole(0x17b7be43L), tole(0x60b08ed5L), +-tole(0xd6d6a3e8L), tole(0xa1d1937eL), tole(0x38d8c2c4L), tole(0x4fdff252L), +-tole(0xd1bb67f1L), tole(0xa6bc5767L), tole(0x3fb506ddL), tole(0x48b2364bL), +-tole(0xd80d2bdaL), tole(0xaf0a1b4cL), tole(0x36034af6L), tole(0x41047a60L), +-tole(0xdf60efc3L), tole(0xa867df55L), tole(0x316e8eefL), tole(0x4669be79L), +-tole(0xcb61b38cL), tole(0xbc66831aL), tole(0x256fd2a0L), tole(0x5268e236L), +-tole(0xcc0c7795L), tole(0xbb0b4703L), tole(0x220216b9L), tole(0x5505262fL), +-tole(0xc5ba3bbeL), tole(0xb2bd0b28L), tole(0x2bb45a92L), tole(0x5cb36a04L), +-tole(0xc2d7ffa7L), tole(0xb5d0cf31L), tole(0x2cd99e8bL), tole(0x5bdeae1dL), +-tole(0x9b64c2b0L), tole(0xec63f226L), tole(0x756aa39cL), tole(0x026d930aL), +-tole(0x9c0906a9L), tole(0xeb0e363fL), tole(0x72076785L), tole(0x05005713L), +-tole(0x95bf4a82L), tole(0xe2b87a14L), tole(0x7bb12baeL), tole(0x0cb61b38L), +-tole(0x92d28e9bL), tole(0xe5d5be0dL), tole(0x7cdcefb7L), tole(0x0bdbdf21L), +-tole(0x86d3d2d4L), tole(0xf1d4e242L), tole(0x68ddb3f8L), tole(0x1fda836eL), +-tole(0x81be16cdL), tole(0xf6b9265bL), tole(0x6fb077e1L), tole(0x18b74777L), +-tole(0x88085ae6L), tole(0xff0f6a70L), tole(0x66063bcaL), tole(0x11010b5cL), +-tole(0x8f659effL), tole(0xf862ae69L), tole(0x616bffd3L), tole(0x166ccf45L), +-tole(0xa00ae278L), tole(0xd70dd2eeL), tole(0x4e048354L), tole(0x3903b3c2L), +-tole(0xa7672661L), tole(0xd06016f7L), tole(0x4969474dL), tole(0x3e6e77dbL), +-tole(0xaed16a4aL), tole(0xd9d65adcL), tole(0x40df0b66L), tole(0x37d83bf0L), +-tole(0xa9bcae53L), tole(0xdebb9ec5L), tole(0x47b2cf7fL), tole(0x30b5ffe9L), +-tole(0xbdbdf21cL), tole(0xcabac28aL), tole(0x53b39330L), tole(0x24b4a3a6L), +-tole(0xbad03605L), tole(0xcdd70693L), tole(0x54de5729L), tole(0x23d967bfL), +-tole(0xb3667a2eL), tole(0xc4614ab8L), tole(0x5d681b02L), tole(0x2a6f2b94L), +-tole(0xb40bbe37L), tole(0xc30c8ea1L), tole(0x5a05df1bL), tole(0x2d02ef8dL) ++const unsigned int g_crc_table[256] = { /* 256:С */ ++ tole(0x00000000L), tole(0x77073096L), tole(0xee0e612cL), tole(0x990951baL), ++ tole(0x076dc419L), tole(0x706af48fL), tole(0xe963a535L), tole(0x9e6495a3L), ++ tole(0x0edb8832L), tole(0x79dcb8a4L), tole(0xe0d5e91eL), tole(0x97d2d988L), ++ tole(0x09b64c2bL), tole(0x7eb17cbdL), tole(0xe7b82d07L), tole(0x90bf1d91L), ++ tole(0x1db71064L), tole(0x6ab020f2L), tole(0xf3b97148L), tole(0x84be41deL), ++ tole(0x1adad47dL), tole(0x6ddde4ebL), tole(0xf4d4b551L), tole(0x83d385c7L), ++ tole(0x136c9856L), tole(0x646ba8c0L), tole(0xfd62f97aL), tole(0x8a65c9ecL), ++ tole(0x14015c4fL), tole(0x63066cd9L), tole(0xfa0f3d63L), tole(0x8d080df5L), ++ tole(0x3b6e20c8L), tole(0x4c69105eL), tole(0xd56041e4L), tole(0xa2677172L), ++ tole(0x3c03e4d1L), tole(0x4b04d447L), tole(0xd20d85fdL), tole(0xa50ab56bL), ++ tole(0x35b5a8faL), tole(0x42b2986cL), tole(0xdbbbc9d6L), tole(0xacbcf940L), ++ tole(0x32d86ce3L), tole(0x45df5c75L), tole(0xdcd60dcfL), tole(0xabd13d59L), ++ tole(0x26d930acL), tole(0x51de003aL), tole(0xc8d75180L), tole(0xbfd06116L), ++ tole(0x21b4f4b5L), tole(0x56b3c423L), tole(0xcfba9599L), tole(0xb8bda50fL), ++ tole(0x2802b89eL), tole(0x5f058808L), tole(0xc60cd9b2L), tole(0xb10be924L), ++ tole(0x2f6f7c87L), tole(0x58684c11L), tole(0xc1611dabL), tole(0xb6662d3dL), ++ tole(0x76dc4190L), tole(0x01db7106L), tole(0x98d220bcL), tole(0xefd5102aL), ++ tole(0x71b18589L), tole(0x06b6b51fL), tole(0x9fbfe4a5L), tole(0xe8b8d433L), ++ tole(0x7807c9a2L), tole(0x0f00f934L), tole(0x9609a88eL), tole(0xe10e9818L), ++ tole(0x7f6a0dbbL), tole(0x086d3d2dL), tole(0x91646c97L), tole(0xe6635c01L), ++ tole(0x6b6b51f4L), tole(0x1c6c6162L), tole(0x856530d8L), tole(0xf262004eL), ++ tole(0x6c0695edL), tole(0x1b01a57bL), tole(0x8208f4c1L), tole(0xf50fc457L), ++ tole(0x65b0d9c6L), tole(0x12b7e950L), tole(0x8bbeb8eaL), tole(0xfcb9887cL), ++ tole(0x62dd1ddfL), tole(0x15da2d49L), tole(0x8cd37cf3L), tole(0xfbd44c65L), ++ tole(0x4db26158L), tole(0x3ab551ceL), tole(0xa3bc0074L), tole(0xd4bb30e2L), ++ tole(0x4adfa541L), tole(0x3dd895d7L), tole(0xa4d1c46dL), tole(0xd3d6f4fbL), ++ tole(0x4369e96aL), tole(0x346ed9fcL), tole(0xad678846L), tole(0xda60b8d0L), ++ tole(0x44042d73L), tole(0x33031de5L), tole(0xaa0a4c5fL), tole(0xdd0d7cc9L), ++ tole(0x5005713cL), tole(0x270241aaL), tole(0xbe0b1010L), tole(0xc90c2086L), ++ tole(0x5768b525L), tole(0x206f85b3L), tole(0xb966d409L), tole(0xce61e49fL), ++ tole(0x5edef90eL), tole(0x29d9c998L), tole(0xb0d09822L), tole(0xc7d7a8b4L), ++ tole(0x59b33d17L), tole(0x2eb40d81L), tole(0xb7bd5c3bL), tole(0xc0ba6cadL), ++ tole(0xedb88320L), tole(0x9abfb3b6L), tole(0x03b6e20cL), tole(0x74b1d29aL), ++ tole(0xead54739L), tole(0x9dd277afL), tole(0x04db2615L), tole(0x73dc1683L), ++ tole(0xe3630b12L), tole(0x94643b84L), tole(0x0d6d6a3eL), tole(0x7a6a5aa8L), ++ tole(0xe40ecf0bL), tole(0x9309ff9dL), tole(0x0a00ae27L), tole(0x7d079eb1L), ++ tole(0xf00f9344L), tole(0x8708a3d2L), tole(0x1e01f268L), tole(0x6906c2feL), ++ tole(0xf762575dL), tole(0x806567cbL), tole(0x196c3671L), tole(0x6e6b06e7L), ++ tole(0xfed41b76L), tole(0x89d32be0L), tole(0x10da7a5aL), tole(0x67dd4accL), ++ tole(0xf9b9df6fL), tole(0x8ebeeff9L), tole(0x17b7be43L), tole(0x60b08ed5L), ++ tole(0xd6d6a3e8L), tole(0xa1d1937eL), tole(0x38d8c2c4L), tole(0x4fdff252L), ++ tole(0xd1bb67f1L), tole(0xa6bc5767L), tole(0x3fb506ddL), tole(0x48b2364bL), ++ tole(0xd80d2bdaL), tole(0xaf0a1b4cL), tole(0x36034af6L), tole(0x41047a60L), ++ tole(0xdf60efc3L), tole(0xa867df55L), tole(0x316e8eefL), tole(0x4669be79L), ++ tole(0xcb61b38cL), tole(0xbc66831aL), tole(0x256fd2a0L), tole(0x5268e236L), ++ tole(0xcc0c7795L), tole(0xbb0b4703L), tole(0x220216b9L), tole(0x5505262fL), ++ tole(0xc5ba3bbeL), tole(0xb2bd0b28L), tole(0x2bb45a92L), tole(0x5cb36a04L), ++ tole(0xc2d7ffa7L), tole(0xb5d0cf31L), tole(0x2cd99e8bL), tole(0x5bdeae1dL), ++ tole(0x9b64c2b0L), tole(0xec63f226L), tole(0x756aa39cL), tole(0x026d930aL), ++ tole(0x9c0906a9L), tole(0xeb0e363fL), tole(0x72076785L), tole(0x05005713L), ++ tole(0x95bf4a82L), tole(0xe2b87a14L), tole(0x7bb12baeL), tole(0x0cb61b38L), ++ tole(0x92d28e9bL), tole(0xe5d5be0dL), tole(0x7cdcefb7L), tole(0x0bdbdf21L), ++ tole(0x86d3d2d4L), tole(0xf1d4e242L), tole(0x68ddb3f8L), tole(0x1fda836eL), ++ tole(0x81be16cdL), tole(0xf6b9265bL), tole(0x6fb077e1L), tole(0x18b74777L), ++ tole(0x88085ae6L), tole(0xff0f6a70L), tole(0x66063bcaL), tole(0x11010b5cL), ++ tole(0x8f659effL), tole(0xf862ae69L), tole(0x616bffd3L), tole(0x166ccf45L), ++ tole(0xa00ae278L), tole(0xd70dd2eeL), tole(0x4e048354L), tole(0x3903b3c2L), ++ tole(0xa7672661L), tole(0xd06016f7L), tole(0x4969474dL), tole(0x3e6e77dbL), ++ tole(0xaed16a4aL), tole(0xd9d65adcL), tole(0x40df0b66L), tole(0x37d83bf0L), ++ tole(0xa9bcae53L), tole(0xdebb9ec5L), tole(0x47b2cf7fL), tole(0x30b5ffe9L), ++ tole(0xbdbdf21cL), tole(0xcabac28aL), tole(0x53b39330L), tole(0x24b4a3a6L), ++ tole(0xbad03605L), tole(0xcdd70693L), tole(0x54de5729L), tole(0x23d967bfL), ++ tole(0xb3667a2eL), tole(0xc4614ab8L), tole(0x5d681b02L), tole(0x2a6f2b94L), ++ tole(0xb40bbe37L), tole(0xc30c8ea1L), tole(0x5a05df1bL), tole(0x2d02ef8dL) + }; +-#endif +- +-#if 0 +-/* ========================================================================= +- * This function can be used by asm versions of crc32() +- */ +-const uint32_t * ZEXPORT get_crc_table() +-{ +-#ifdef CONFIG_DYNAMIC_CRC_TABLE +- if (crc_table_empty) make_crc_table(); +-#endif +- return (const uint32_t *)crc_table; +-} +-#endif + + /* ========================================================================= */ +-# if __BYTE_ORDER == __LITTLE_ENDIAN +-# define DO_CRC(x) crc = tab[(crc ^ (x)) & 255] ^ (crc >> 8) +-# else +-# define DO_CRC(x) crc = tab[((crc >> 24) ^ (x)) & 255] ^ (crc << 8) +-# endif +- ++#define do_crc(x) (crc = tab[(crc ^ (x)) & 255] ^ (crc >> 8)) /* 255 8 */ + /* ========================================================================= */ +- + /* No ones complement version. JFFS2 (and other things ?) + * don't use ones compliment in their CRC calculations. + */ +-uint32_t __efi_runtime crc32_no_comp(uint32_t crc, const Bytef *buf, uInt len) ++unsigned int crc32_no_comp(unsigned int crc, const bytef *buf, uint len) + { +- const uint32_t *tab = crc_table; +- const uint32_t *b =(const uint32_t *)buf; ++ const unsigned int *tab = g_crc_table; ++ const unsigned int *b = (const unsigned int *)buf; + size_t rem_len; +-#ifdef CONFIG_DYNAMIC_CRC_TABLE +- if (crc_table_empty) +- make_crc_table(); +-#endif +- crc = cpu_to_le32(crc); ++ + /* Align it */ +- if (((long)b) & 3 && len) { +- uint8_t *p = (uint8_t *)b; +- do { +- DO_CRC(*p++); +- } while ((--len) && ((long)p)&3); +- b = (uint32_t *)p; ++ if ((((uintptr_t)b) & 3) && len) { /* 3 */ ++ uint8_t *p = (uint8_t *)b; ++ do { ++ do_crc(*p++); ++ } while ((--len) && (((uintptr_t)p) & 3)); /* 3 */ ++ b = (unsigned int *)p; + } + +- rem_len = len & 3; +- len = len >> 2; ++ rem_len = len & 3; /* 3 */ ++ len = len >> 2; /* 2 */ + for (--b; len; --len) { +- /* load data 32 bits wide, xor data 32 bits wide. */ +- crc ^= *++b; /* use pre increment for speed */ +- DO_CRC(0); +- DO_CRC(0); +- DO_CRC(0); +- DO_CRC(0); ++ /* load data 32 bits wide, xor data 32 bits wide. */ ++ crc ^= *++b; /* use pre increment for speed */ ++ do_crc(0); ++ do_crc(0); ++ do_crc(0); ++ do_crc(0); + } + len = rem_len; + /* And the last few bytes */ + if (len) { +- uint8_t *p = (uint8_t *)(b + 1) - 1; +- do { +- DO_CRC(*++p); /* use pre increment for speed */ +- } while (--len); ++ uint8_t *p = (uint8_t *)(b + 1) - 1; ++ do { ++ do_crc(*++p); /* use pre increment for speed */ ++ } while (--len); + } + + return le32_to_cpu(crc); + } +-#undef DO_CRC +- +-uint32_t __efi_runtime crc32(uint32_t crc, const Bytef *p, uInt len) +-{ +- return crc32_no_comp(crc ^ 0xffffffffL, p, len) ^ 0xffffffffL; +-} ++#undef do_crc + +-/* +- * Calculate the crc32 checksum triggering the watchdog every 'chunk_sz' bytes +- * of input. +- */ +-uint32_t crc32_wd(uint32_t crc, const unsigned char *buf, uInt len, +- uInt chunk_sz) ++unsigned int hi_crc32 (unsigned int crc, const bytef *p, uint len) + { +-#if defined(CONFIG_HW_WATCHDOG) || defined(CONFIG_WATCHDOG) +- const unsigned char *end, *curr; +- int chunk; +- +- curr = buf; +- end = buf + len; +- while (curr < end) { +- chunk = end - curr; +- if (chunk > chunk_sz) +- chunk = chunk_sz; +- crc = crc32 (crc, curr, chunk); +- curr += chunk; +- WATCHDOG_RESET (); +- } +-#else +- crc = crc32 (crc, buf, len); +-#endif ++ if (!p || !len) { ++ return 0; ++ } + +- return crc; ++ return crc32_no_comp(crc ^ 0xffffffffL, p, len) ^ 0xffffffffL; + } + +-void crc32_wd_buf(const unsigned char *input, unsigned int ilen, +- unsigned char *output, unsigned int chunk_sz) +-{ +- uint32_t crc; + +- crc = crc32_wd(0, input, ilen, chunk_sz); +- crc = htonl(crc); +- memcpy(output, &crc, sizeof(crc)); +-} +Binary files u-boot-v2019.07/lib/crc32.o and u-boot-v2019.07_ok/lib/crc32.o differ +diff -Nur u-boot-v2019.07/lib/lzma/LzmaDec.c u-boot-v2019.07_ok/lib/lzma/LzmaDec.c +--- u-boot-v2019.07/lib/lzma/LzmaDec.c 2020-05-30 23:14:30.920000000 +0800 ++++ u-boot-v2019.07_ok/lib/lzma/LzmaDec.c 2020-05-30 12:06:17.000000000 +0800 +@@ -1,13 +1,9 @@ + /* LzmaDec.c -- LZMA Decoder + 2009-09-20 : Igor Pavlov : Public domain */ ++#include + +-#include +-#include +-#include + #include "LzmaDec.h" + +-#include +- + #define kNumTopBits 24 + #define kTopValue ((UInt32)1 << kNumTopBits) + +@@ -47,9 +43,10 @@ + i -= 0x40; } + #endif + +-#define NORMALIZE_CHECK if (range < kTopValue) { if (buf >= bufLimit) return DUMMY_ERROR; range <<= 8; code = (code << 8) | (*buf++); } ++#define NORMALIZE_CHECK if (range < kTopValue) { if (buf >= bufLimit) return DUMMY_ERROR;} ++#define NORMALIZE_CHECK_MODIFY if (range < kTopValue) { if (buf >= bufLimit) return DUMMY_ERROR; range <<= 8; code = (code << 8) | (*buf++); } + +-#define IF_BIT_0_CHECK(p) ttt = *(p); NORMALIZE_CHECK; bound = (range >> kNumBitModelTotalBits) * ttt; if (code < bound) ++#define IF_BIT_0_CHECK(p) ttt = *(p); NORMALIZE_CHECK_MODIFY; bound = (range >> kNumBitModelTotalBits) * ttt; if (code < bound) + #define UPDATE_0_CHECK range = bound; + #define UPDATE_1_CHECK range -= bound; code -= bound; + #define GET_BIT2_CHECK(p, i, A0, A1) IF_BIT_0_CHECK(p) \ +@@ -131,7 +128,7 @@ + = kMatchSpecLenStart + 2 : State Init Marker + */ + +-static int MY_FAST_CALL LzmaDec_DecodeReal(CLzmaDec *p, SizeT limit, const Byte *bufLimit) ++unsigned int MY_FAST_CALL LzmaDec_DecodeReal(CLzmaDec* p, SizeT limit, const Byte* bufLimit) + { + CLzmaProb *probs = p->probs; + +@@ -153,7 +150,7 @@ + UInt32 range = p->range; + UInt32 code = p->code; + +- WATCHDOG_RESET(); ++ hi_watchdog_feed(); + + do + { +@@ -177,9 +174,10 @@ + state -= (state < 4) ? state : 3; + symbol = 1; + +- WATCHDOG_RESET(); ++ hi_watchdog_feed(); + +- do { GET_BIT(prob + symbol, symbol) } while (symbol < 0x100); ++ do { GET_BIT(prob + symbol, symbol) } ++ while (symbol < 0x100); + } + else + { +@@ -188,7 +186,7 @@ + state -= (state < 10) ? 3 : 6; + symbol = 1; + +- WATCHDOG_RESET(); ++ hi_watchdog_feed(); + + do + { +@@ -270,14 +268,14 @@ + prob = probs + RepLenCoder; + } + { +- unsigned limit, offset; ++ unsigned int inner_limit, offset; + CLzmaProb *probLen = prob + LenChoice; + IF_BIT_0(probLen) + { + UPDATE_0(probLen); + probLen = prob + LenLow + (posState << kLenNumLowBits); + offset = 0; +- limit = (1 << kLenNumLowBits); ++ inner_limit = (1 << kLenNumLowBits); + } + else + { +@@ -288,17 +286,17 @@ + UPDATE_0(probLen); + probLen = prob + LenMid + (posState << kLenNumMidBits); + offset = kLenNumLowSymbols; +- limit = (1 << kLenNumMidBits); ++ inner_limit = (1 << kLenNumMidBits); + } + else + { + UPDATE_1(probLen); + probLen = prob + LenHigh; + offset = kLenNumLowSymbols + kLenNumMidSymbols; +- limit = (1 << kLenNumHighBits); ++ inner_limit = (1 << kLenNumHighBits); + } + } +- TREE_DECODE(probLen, limit, len); ++ TREE_DECODE(probLen, inner_limit, len); + len += offset; + } + +@@ -312,16 +310,17 @@ + { + unsigned posSlot = (unsigned)distance; + int numDirectBits = (int)(((distance >> 1) - 1)); ++ unsigned int numDirectBitsTemp = (unsigned int)numDirectBits; + distance = (2 | (distance & 1)); + if (posSlot < kEndPosModelIndex) + { +- distance <<= numDirectBits; ++ distance <<= numDirectBitsTemp; + prob = probs + SpecPos + distance - posSlot - 1; + { + UInt32 mask = 1; + unsigned i = 1; + +- WATCHDOG_RESET(); ++ hi_watchdog_feed(); + + do + { +@@ -335,7 +334,7 @@ + { + numDirectBits -= kNumAlignBits; + +- WATCHDOG_RESET(); ++ hi_watchdog_feed(); + + do + { +@@ -409,7 +408,7 @@ + const Byte *lim = dest + curLen; + dicPos += curLen; + +- WATCHDOG_RESET(); ++ hi_watchdog_feed(); + + do + *(dest) = (Byte)*(dest + src); +@@ -418,7 +417,7 @@ + else + { + +- WATCHDOG_RESET(); ++ hi_watchdog_feed(); + + do + { +@@ -433,7 +432,7 @@ + } + while (dicPos < limit && buf < bufLimit); + +- WATCHDOG_RESET(); ++ hi_watchdog_feed(); + + NORMALIZE; + p->buf = buf; +@@ -451,7 +450,7 @@ + return SZ_OK; + } + +-static void MY_FAST_CALL LzmaDec_WriteRem(CLzmaDec *p, SizeT limit) ++void MY_FAST_CALL LzmaDec_WriteRem(CLzmaDec* p, SizeT limit) + { + if (p->remainLen != 0 && p->remainLen < kMatchSpecLenStart) + { +@@ -477,7 +476,7 @@ + } + } + +-static int MY_FAST_CALL LzmaDec_DecodeReal2(CLzmaDec *p, SizeT limit, const Byte *bufLimit) ++unsigned int MY_FAST_CALL LzmaDec_DecodeReal2(CLzmaDec* p, SizeT limit, const Byte* bufLimit) + { + do + { +@@ -510,7 +509,7 @@ + DUMMY_REP + } ELzmaDummy; + +-static ELzmaDummy LzmaDec_TryDummy(const CLzmaDec *p, const Byte *buf, SizeT inSize) ++ ELzmaDummy LzmaDec_TryDummy(const CLzmaDec* p, const Byte* buf, SizeT inSize) + { + UInt32 range = p->range; + UInt32 code = p->code; +@@ -541,7 +540,8 @@ + if (state < kNumLitStates) + { + unsigned symbol = 1; +- do { GET_BIT_CHECK(prob + symbol, symbol) } while (symbol < 0x100); ++ do { GET_BIT_CHECK(prob + symbol, symbol) } ++ while (symbol < 0x100); + } + else + { +@@ -668,14 +668,14 @@ + + if (posSlot < kEndPosModelIndex) + { +- prob = probs + SpecPos + ((2 | (posSlot & 1)) << numDirectBits) - posSlot - 1; ++ prob = probs + SpecPos + ((2 | (posSlot & 1)) << (unsigned int)numDirectBits) - posSlot - 1; + } + else + { + numDirectBits -= kNumAlignBits; + do + { +- NORMALIZE_CHECK ++ NORMALIZE_CHECK_MODIFY + range >>= 1; + code -= range & (((code - range) >> 31) - 1); + /* if (code >= range) code -= range; */ +@@ -701,7 +701,7 @@ + } + + +-static void LzmaDec_InitRc(CLzmaDec *p, const Byte *data) ++ void LzmaDec_InitRc(CLzmaDec* p, const Byte* data) + { + p->code = ((UInt32)data[1] << 24) | ((UInt32)data[2] << 16) | ((UInt32)data[3] << 8) | ((UInt32)data[4]); + p->range = 0xFFFFFFFF; +@@ -730,7 +730,7 @@ + LzmaDec_InitDicAndState(p, True, True); + } + +-static void LzmaDec_InitStateReal(CLzmaDec *p) ++ void LzmaDec_InitStateReal(CLzmaDec* p) + { + UInt32 numProbs = Literal + ((UInt32)LZMA_LIT_SIZE << (p->prop.lc + p->prop.lp)); + UInt32 i; +@@ -804,63 +804,79 @@ + int dummyRes = LzmaDec_TryDummy(p, src, inSize); + if (dummyRes == DUMMY_ERROR) + { +- memcpy(p->tempBuf, src, inSize); +- p->tempBufSize = (unsigned)inSize; +- (*srcLen) += inSize; +- *status = LZMA_STATUS_NEEDS_MORE_INPUT; +- return SZ_OK; +- } +- if (checkEndMarkNow && dummyRes != DUMMY_MATCH) +- { +- *status = LZMA_STATUS_NOT_FINISHED; +- return SZ_ERROR_DATA; +- } +- bufLimit = src; ++ unsigned int cs = (uintptr_t)p->tempBuf ^ inSize ^ (uintptr_t)src ^ inSize; ++ (hi_void)memcpy_s(p->tempBuf,inSize ,src, inSize, cs); ++ p->tempBufSize = (unsigned)inSize; ++ (*srcLen) += inSize; ++ *status = LZMA_STATUS_NEEDS_MORE_INPUT; ++ return SZ_OK; ++ } ++ ++ if (checkEndMarkNow && dummyRes != DUMMY_MATCH) ++ { ++ *status = LZMA_STATUS_NOT_FINISHED; ++ return SZ_ERROR_DATA; ++ } ++ ++ bufLimit = src; ++ } ++ else ++ { bufLimit = src + inSize - LZMA_REQUIRED_INPUT_MAX; } ++ ++ p->buf = src; ++ ++ if (LzmaDec_DecodeReal2(p, dicLimit, bufLimit) != 0) ++ { return SZ_ERROR_DATA; } ++ ++ processed = (SizeT)(p->buf - src); ++ (*srcLen) += processed; ++ src += processed; ++ inSize -= processed; + } + else +- bufLimit = src + inSize - LZMA_REQUIRED_INPUT_MAX; +- p->buf = src; +- if (LzmaDec_DecodeReal2(p, dicLimit, bufLimit) != 0) +- return SZ_ERROR_DATA; +- processed = (SizeT)(p->buf - src); +- (*srcLen) += processed; +- src += processed; +- inSize -= processed; +- } +- else +- { +- unsigned rem = p->tempBufSize, lookAhead = 0; +- while (rem < LZMA_REQUIRED_INPUT_MAX && lookAhead < inSize) +- p->tempBuf[rem++] = src[lookAhead++]; +- p->tempBufSize = rem; +- if (rem < LZMA_REQUIRED_INPUT_MAX || checkEndMarkNow) + { +- int dummyRes = LzmaDec_TryDummy(p, p->tempBuf, rem); +- if (dummyRes == DUMMY_ERROR) +- { ++ unsigned rem = p->tempBufSize, lookAhead = 0; ++ ++ while (rem < LZMA_REQUIRED_INPUT_MAX && lookAhead < inSize) ++ { p->tempBuf[rem++] = src[lookAhead++]; } ++ ++ p->tempBufSize = rem; ++ ++ if (rem < LZMA_REQUIRED_INPUT_MAX || checkEndMarkNow) ++ { ++ int dummyRes = LzmaDec_TryDummy(p, p->tempBuf, rem); ++ ++ if (dummyRes == DUMMY_ERROR) ++ { ++ (*srcLen) += lookAhead; ++ *status = LZMA_STATUS_NEEDS_MORE_INPUT; ++ return SZ_OK; ++ } ++ ++ if (checkEndMarkNow && dummyRes != DUMMY_MATCH) ++ { ++ *status = LZMA_STATUS_NOT_FINISHED; ++ return SZ_ERROR_DATA; ++ } ++ } ++ ++ p->buf = p->tempBuf; ++ ++ if (LzmaDec_DecodeReal2(p, dicLimit, p->buf) != 0) ++ { return SZ_ERROR_DATA; } ++ ++ lookAhead -= (rem - (unsigned)(p->buf - p->tempBuf)); + (*srcLen) += lookAhead; +- *status = LZMA_STATUS_NEEDS_MORE_INPUT; +- return SZ_OK; +- } +- if (checkEndMarkNow && dummyRes != DUMMY_MATCH) +- { +- *status = LZMA_STATUS_NOT_FINISHED; +- return SZ_ERROR_DATA; +- } ++ src += lookAhead; ++ inSize -= lookAhead; ++ p->tempBufSize = 0; + } +- p->buf = p->tempBuf; +- if (LzmaDec_DecodeReal2(p, dicLimit, p->buf) != 0) +- return SZ_ERROR_DATA; +- lookAhead -= (rem - (unsigned)(p->buf - p->tempBuf)); +- (*srcLen) += lookAhead; +- src += lookAhead; +- inSize -= lookAhead; +- p->tempBufSize = 0; +- } +- } +- if (p->code == 0) +- *status = LZMA_STATUS_FINISHED_WITH_MARK; +- return (p->code == 0) ? SZ_OK : SZ_ERROR_DATA; ++ } ++ ++ if (p->code == 0) ++ { *status = LZMA_STATUS_FINISHED_WITH_MARK; } ++ ++ return (p->code == 0) ? (SRes)SZ_OK : (SRes)SZ_ERROR_DATA; + } + + SRes LzmaDec_DecodeToBuf(CLzmaDec *p, Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen, ELzmaFinishMode finishMode, ELzmaStatus *status) +@@ -887,20 +903,23 @@ + curFinishMode = finishMode; + } + +- res = LzmaDec_DecodeToDic(p, outSizeCur, src, &inSizeCur, curFinishMode, status); +- src += inSizeCur; +- inSize -= inSizeCur; +- *srcLen += inSizeCur; +- outSizeCur = p->dicPos - dicPos; +- memcpy(dest, p->dic + dicPos, outSizeCur); +- dest += outSizeCur; +- outSize -= outSizeCur; +- *destLen += outSizeCur; +- if (res != 0) +- return res; +- if (outSizeCur == 0 || outSize == 0) +- return SZ_OK; +- } ++ res = LzmaDec_DecodeToDic(p, outSizeCur, src, &inSizeCur, curFinishMode, status); ++ src += inSizeCur; ++ inSize -= inSizeCur; ++ *srcLen += inSizeCur; ++ outSizeCur = p->dicPos - dicPos; ++ unsigned int cs = (uintptr_t)dest ^ outSizeCur ^ (uintptr_t)(p->dic + dicPos) ^ outSizeCur; ++ (hi_void)memcpy_s(dest,outSizeCur,p->dic + dicPos, outSizeCur, cs); ++ dest += outSizeCur; ++ outSize -= outSizeCur; ++ *destLen += outSizeCur; ++ ++ if (res != 0) ++ { return res; } ++ ++ if (outSizeCur == 0 || outSize == 0) ++ { return SZ_OK; } ++ } + } + + void LzmaDec_FreeProbs(CLzmaDec *p, ISzAlloc *alloc) +@@ -909,7 +928,7 @@ + p->probs = 0; + } + +-static void LzmaDec_FreeDict(CLzmaDec *p, ISzAlloc *alloc) ++ void LzmaDec_FreeDict(CLzmaDec* p, ISzAlloc* alloc) + { + alloc->Free(alloc, p->dic); + p->dic = 0; +@@ -947,7 +966,7 @@ + return SZ_OK; + } + +-static SRes LzmaDec_AllocateProbs2(CLzmaDec *p, const CLzmaProps *propNew, ISzAlloc *alloc) ++ SRes LzmaDec_AllocateProbs2(CLzmaDec* p, const CLzmaProps* propNew, ISzAlloc* alloc) + { + UInt32 numProbs = LzmaProps_GetNumProbs(propNew); + if (p->probs == 0 || numProbs != p->numProbs) +Binary files u-boot-v2019.07/lib/lzma/LzmaDec.o and u-boot-v2019.07_ok/lib/lzma/LzmaDec.o differ +diff -Nur u-boot-v2019.07/lib/lzma/LzmaTools.c u-boot-v2019.07_ok/lib/lzma/LzmaTools.c +--- u-boot-v2019.07/lib/lzma/LzmaTools.c 2020-05-30 23:14:30.920000000 +0800 ++++ u-boot-v2019.07_ok/lib/lzma/LzmaTools.c 2020-05-30 12:06:17.000000000 +0800 +@@ -17,31 +17,29 @@ + * + */ + +-#include +-#include +-#include ++#include + +-#ifdef CONFIG_LZMA + + #define LZMA_PROPERTIES_OFFSET 0 + #define LZMA_SIZE_OFFSET LZMA_PROPS_SIZE + #define LZMA_DATA_OFFSET LZMA_SIZE_OFFSET+sizeof(uint64_t) + +-#include "LzmaTools.h" + #include "LzmaDec.h" ++#include "LzmaTools.h" ++ ++#define IN_BUF_SIZE (0x1000) ++#define OUT_BUF_SIZE (0x1000) ++ + +-#include +-#include ++SRes Decode2(CLzmaDec* state, Byte* in_buf, LZMA_STREAM_S* in_stream, Byte* out_buf, LZMA_STREAM_S* out_stream, ++ unsigned int uncompress_len, unsigned int compress_len, ELzmaStatus* status); + +-static void *SzAlloc(void *p, size_t size) { return malloc(size); } +-static void SzFree(void *p, void *address) { free(address); } + +-int lzmaBuffToBuffDecompress (unsigned char *outStream, SizeT *uncompressedSize, +- unsigned char *inStream, SizeT length) ++int lzmaBuffToBuffDecompress (unsigned char* outStream, SizeT* uncompressedSize, ++ unsigned char* inStream, SizeT length, ISzAlloc* alloc) + { + int res = SZ_ERROR_DATA; + int i; +- ISzAlloc g_Alloc; + + SizeT outSizeFull = 0xFFFFFFFF; /* 4GBytes limit */ + SizeT outProcessed; +@@ -50,34 +48,37 @@ + ELzmaStatus state; + SizeT compressedSize = (SizeT)(length - LZMA_PROPS_SIZE); + +- debug ("LZMA: Image address............... 0x%p\n", inStream); +- debug ("LZMA: Properties address.......... 0x%p\n", inStream + LZMA_PROPERTIES_OFFSET); +- debug ("LZMA: Uncompressed size address... 0x%p\n", inStream + LZMA_SIZE_OFFSET); +- debug ("LZMA: Compressed data address..... 0x%p\n", inStream + LZMA_DATA_OFFSET); +- debug ("LZMA: Destination address......... 0x%p\n", outStream); +- +- memset(&state, 0, sizeof(state)); ++ (hi_void)memset_s(&state,sizeof(state), 0, sizeof(state), (uintptr_t)(&state) ^ sizeof(state) ^ 0 ^ sizeof(state)); + + outSize = 0; + outSizeHigh = 0; + /* Read the uncompressed size */ +- for (i = 0; i < 8; i++) { ++ for (i = 0; i < 8; i++) ++ { + unsigned char b = inStream[LZMA_SIZE_OFFSET + i]; +- if (i < 4) { +- outSize += (UInt32)(b) << (i * 8); +- } else { +- outSizeHigh += (UInt32)(b) << ((i - 4) * 8); ++ ++ if (i < 4) ++ { ++ outSize += (UInt32)(b) << ((unsigned int)i * 8); ++ } ++ else ++ { ++ outSizeHigh += (UInt32)(b) << (((unsigned int)i - 4) * 8); + } + } + + outSizeFull = (SizeT)outSize; +- if (sizeof(SizeT) >= 8) { ++ ++ if (sizeof(SizeT) >= 8) ++ { + /* + * SizeT is a 64 bit uint => We can manage files larger than 4GB! + * + */ +- outSizeFull |= (((SizeT)outSizeHigh << 16) << 16); +- } else if (outSizeHigh != 0 || (UInt32)(SizeT)outSize != outSize) { ++ outSizeFull |= (((SizeT)outSizeHigh << 16) << 16); ++ } ++ else if (outSizeHigh != 0 || (UInt32)(SizeT)outSize != outSize) ++ { + /* + * SizeT is a 32 bit uint => We cannot manage files larger than + * 4GB! Assume however that all 0xf values is "unknown size" and +@@ -85,39 +86,185 @@ + * + */ + if (outSizeHigh != (SizeT)-1 || outSize != (SizeT)-1) { +- debug ("LZMA: 64bit support not enabled.\n"); ++ boot_msg0 ("LZMA: 64bit support not enabled.\n"); + return SZ_ERROR_DATA; + } + } + +- debug("LZMA: Uncompresed size............ 0x%zx\n", outSizeFull); +- debug("LZMA: Compresed size.............. 0x%zx\n", compressedSize); +- +- g_Alloc.Alloc = SzAlloc; +- g_Alloc.Free = SzFree; ++ boot_msg1("Uncompresed size: ", outSizeFull); ++ boot_msg1("Compresed size: ", compressedSize); + + /* Short-circuit early if we know the buffer can't hold the results. */ +- if (outSizeFull != (SizeT)-1 && *uncompressedSize < outSizeFull) +- return SZ_ERROR_OUTPUT_EOF; ++ if (outSizeFull != (SizeT) - 1 && *uncompressedSize < outSizeFull) ++ { return SZ_ERROR_OUTPUT_EOF; } + + /* Decompress */ +- outProcessed = min(outSizeFull, *uncompressedSize); +- +- WATCHDOG_RESET(); ++ outProcessed = (outSizeFull > *uncompressedSize) ? (*uncompressedSize) : outSizeFull; + ++ hi_watchdog_feed(); + res = LzmaDecode( +- outStream, &outProcessed, +- inStream + LZMA_DATA_OFFSET, &compressedSize, +- inStream, LZMA_PROPS_SIZE, LZMA_FINISH_END, &state, &g_Alloc); ++ outStream, &outProcessed, ++ inStream + LZMA_DATA_OFFSET, &compressedSize, ++ inStream, LZMA_PROPS_SIZE, LZMA_FINISH_END, &state, alloc); + *uncompressedSize = outProcessed; + +- debug("LZMA: Uncompressed ............... 0x%zx\n", outProcessed); +- +- if (res != SZ_OK) { ++ if (res != SZ_OK) ++ { + return res; + } + + return res; + } + +-#endif ++ ++unsigned int LzmaDecode2(const Byte* prop_data, unsigned int prop_size, ELzmaStatus* status, ISzAlloc* alloc, ++ LZMA_STREAM_S* in_stream, LZMA_STREAM_S* out_stream, unsigned int uncompress_len, unsigned int compress_len) ++{ ++ CLzmaDec p; ++ SRes res; ++ Byte* in_buf = HI_NULL; ++ Byte* out_buf = HI_NULL; ++ unsigned int dic_size = compress_len; ++ ++ LzmaDec_Construct(&p); ++ ++ res = LzmaDec_AllocateProbs(&p, prop_data, prop_size, alloc); ++ ++ if (0 != res) ++ { ++ return SZ_ERROR_MEM; ++ } ++ ++ LzmaDec_Init(&p); ++ ++ in_buf = IAlloc_Alloc(alloc, IN_BUF_SIZE); ++ ++ if (HI_NULL == in_buf) ++ { ++ return SZ_ERROR_MEM; ++ } ++ ++ out_buf = IAlloc_Alloc(alloc, OUT_BUF_SIZE); ++ ++ if (HI_NULL == out_buf) ++ { ++ IAlloc_Free(alloc, in_buf); ++ in_buf = HI_NULL; ++ return SZ_ERROR_MEM; ++ } ++ ++ (hi_void)memset_s(in_buf, IN_BUF_SIZE, 0, IN_BUF_SIZE, (uintptr_t)in_buf ^ IN_BUF_SIZE ^ 0 ^ IN_BUF_SIZE); ++ (hi_void)memset_s(out_buf, OUT_BUF_SIZE, 0, OUT_BUF_SIZE, (uintptr_t)out_buf ^ OUT_BUF_SIZE ^ 0 ^ OUT_BUF_SIZE); ++ ++ if (p.prop.dicSize <= compress_len) ++ { ++ dic_size = p.prop.dicSize; ++ } ++ ++ p.dic = IAlloc_Alloc(alloc, dic_size); ++ ++ if (HI_NULL == p.dic) ++ { ++ IAlloc_Free(alloc, in_buf); ++ in_buf = HI_NULL; ++ ++ IAlloc_Free(alloc, out_buf); ++ out_buf = HI_NULL; ++ ++ return SZ_ERROR_MEM; ++ } ++ ++ p.dicBufSize = dic_size; ++ ++ res = Decode2(&p, in_buf, in_stream, out_buf, out_stream, uncompress_len, compress_len, status); ++ ++ if ((res == SZ_OK) && (*status == LZMA_STATUS_NEEDS_MORE_INPUT)) ++ { ++ res = SZ_ERROR_INPUT_EOF; ++ } ++ ++ IAlloc_Free(alloc, in_buf); ++ in_buf = HI_NULL; ++ ++ IAlloc_Free(alloc, out_buf); ++ out_buf = HI_NULL; ++ ++ IAlloc_Free(alloc, p.dic); ++ p.dic = HI_NULL; ++ ++ LzmaDec_FreeProbs(&p, alloc); ++ ++ return res; ++} ++ ++ ++SRes Decode2(CLzmaDec* state, Byte* in_buf, LZMA_STREAM_S* in_stream, Byte* out_buf, LZMA_STREAM_S* out_stream, ++ unsigned int uncompress_len, unsigned int compress_len, ELzmaStatus* status) ++{ ++ int there_is_size = (compress_len != (unsigned int) - 1); ++ size_t in_pos = 0, in_size = 0, out_pos = 0; ++ unsigned int in_offset = in_stream->offset; ++ unsigned int out_offset = out_stream->offset; ++ ++ LzmaDec_Init(state); ++ ++ for (;;) ++ { ++ if (in_pos == in_size) ++ { ++ in_size = (uncompress_len > IN_BUF_SIZE) ? IN_BUF_SIZE : uncompress_len; ++ RINOK(in_stream->func(in_offset, in_buf, in_size)); ++ RINOK(in_stream->func(in_offset, in_buf, 1)); /* Make sure the readings are correct. */ ++ uncompress_len -= in_size; ++ in_pos = 0; ++ } ++ ++ { ++ SRes res; ++ size_t in_processed = in_size - in_pos; ++ size_t out_processed = OUT_BUF_SIZE - out_pos; ++ ++ ELzmaFinishMode finish_mode = LZMA_FINISH_ANY; ++ ++ if (there_is_size && out_processed > compress_len) ++ { ++ out_processed = (size_t)compress_len; ++ finish_mode = LZMA_FINISH_END; ++ } ++ ++ res = LzmaDec_DecodeToBuf(state, out_buf + out_pos, &out_processed, ++ in_buf + in_pos, &in_processed, finish_mode, status); ++ ++ in_pos += in_processed; ++ out_pos += out_processed; ++ compress_len -= out_processed; ++ ++ /* Misjudgment is required. */ ++ if (out_stream->func(out_offset, out_buf, out_processed) != out_processed) ++ { ++ return SZ_ERROR_WRITE; ++ } ++ ++ in_offset += in_processed; ++ out_offset += out_processed; ++ ++ out_pos = 0; ++ ++ if (res != SZ_OK || (there_is_size && compress_len == 0)) ++ { ++ return res; ++ } ++ ++ if (in_processed == 0 && out_processed == 0) ++ { ++ if (there_is_size || *status != LZMA_STATUS_FINISHED_WITH_MARK) ++ { ++ return SZ_ERROR_DATA; ++ } ++ ++ return res; ++ } ++ } ++ } ++} ++ +diff -Nur u-boot-v2019.07/lib/lzma/LzmaTools.h u-boot-v2019.07_ok/lib/lzma/LzmaTools.h +--- u-boot-v2019.07/lib/lzma/LzmaTools.h 2020-05-30 23:14:30.920000000 +0800 ++++ u-boot-v2019.07_ok/lib/lzma/LzmaTools.h 2020-05-30 12:06:17.000000000 +0800 +@@ -11,8 +11,22 @@ + #ifndef __LZMA_TOOL_H__ + #define __LZMA_TOOL_H__ + +-#include + +-extern int lzmaBuffToBuffDecompress (unsigned char *outStream, SizeT *uncompressedSize, +- unsigned char *inStream, SizeT length); ++/* The return value of the function is the actual read/write length. Note that the return value is not success/fail */ ++typedef unsigned int (*LZMA_STREAM_FCT)(unsigned int offset, unsigned char* buffer, unsigned int size); ++ ++typedef struct ++{ ++ unsigned int offset; ++ LZMA_STREAM_FCT func; ++} LZMA_STREAM_S; ++ ++extern int lzmaBuffToBuffDecompress (unsigned char* outStream, unsigned int* uncompressedSize, ++ unsigned char* inStream, unsigned int length, ISzAlloc* alloc); ++ ++extern unsigned int LzmaDecode2(const Byte* prop_data, unsigned int prop_size, ELzmaStatus* status, ++ ISzAlloc* alloc, LZMA_STREAM_S* in_stream, LZMA_STREAM_S* out_stream, ++ unsigned int uncompress_len, unsigned int compress_len); ++ + #endif ++ +Binary files u-boot-v2019.07/lib/lzma/LzmaTools.o and u-boot-v2019.07_ok/lib/lzma/LzmaTools.o differ +diff -Nur u-boot-v2019.07/lib/lzma/Types.h u-boot-v2019.07_ok/lib/lzma/Types.h +--- u-boot-v2019.07/lib/lzma/Types.h 2020-05-30 23:14:30.920000000 +0800 ++++ u-boot-v2019.07_ok/lib/lzma/Types.h 2020-05-30 12:06:17.000000000 +0800 +@@ -4,12 +4,6 @@ + #ifndef __7Z_TYPES_H + #define __7Z_TYPES_H + +-#include +- +-#ifdef _WIN32 +-#include +-#endif +- + #define SZ_OK 0 + + #define SZ_ERROR_DATA 1 +@@ -28,16 +22,13 @@ + #define SZ_ERROR_ARCHIVE 16 + #define SZ_ERROR_NO_ARCHIVE 17 + +-typedef int SRes; ++typedef unsigned int SRes; ++typedef int ptrdiff_t; + +-#ifdef _WIN32 +-typedef DWORD WRes; +-#else + typedef int WRes; +-#endif + + #ifndef RINOK +-#define RINOK(x) { int __result__ = (x); if (__result__ != 0) return __result__; } ++#define RINOK(x) {unsigned int __result__ = (x); if (__result__ != 0) return __result__; } + #endif + + typedef unsigned char Byte; +@@ -74,6 +65,10 @@ + + #endif + ++#ifdef USE_FOTA ++typedef unsigned int size_t; ++#endif ++ + #ifdef _LZMA_NO_SYSTEM_SIZE_T + typedef UInt32 SizeT; + #else +@@ -118,19 +113,19 @@ + + typedef struct + { +- SRes (*Read)(void *p, void *buf, size_t *size); ++ SRes (*Read)(void* p, void* buf, size_t* size); + /* if (input(*size) != 0 && output(*size) == 0) means end_of_stream. + (output(*size) < input(*size)) is allowed */ + } ISeqInStream; + + /* it can return SZ_ERROR_INPUT_EOF */ +-SRes SeqInStream_Read(ISeqInStream *stream, void *buf, size_t size); +-SRes SeqInStream_Read2(ISeqInStream *stream, void *buf, size_t size, SRes errorType); ++SRes SeqInStream_Read(ISeqInStream* stream, void* buf, size_t size); ++SRes SeqInStream_Read2(ISeqInStream* stream, void* buf, size_t size, SRes errorType); + SRes SeqInStream_ReadByte(ISeqInStream *stream, Byte *buf); + + typedef struct + { +- size_t (*Write)(void *p, const void *buf, size_t size); ++ size_t (*Write)(void* p, const void* buf, size_t size); + /* Returns: result - the number of actually written bytes. + (result < size) means error */ + } ISeqOutStream; +@@ -144,30 +139,30 @@ + + typedef struct + { +- SRes (*Read)(void *p, void *buf, size_t *size); /* same as ISeqInStream::Read */ ++ SRes (*Read)(void* p, void* buf, size_t* size); /* same as ISeqInStream::Read */ + SRes (*Seek)(void *p, Int64 *pos, ESzSeek origin); + } ISeekInStream; + + typedef struct + { +- SRes (*Look)(void *p, const void **buf, size_t *size); ++ SRes (*Look)(void* p, const void** buf, size_t* size); + /* if (input(*size) != 0 && output(*size) == 0) means end_of_stream. + (output(*size) > input(*size)) is not allowed + (output(*size) < input(*size)) is allowed */ +- SRes (*Skip)(void *p, size_t offset); ++ SRes (*Skip)(void* p, size_t offset); + /* offset must be <= output(*size) of Look */ + +- SRes (*Read)(void *p, void *buf, size_t *size); ++ SRes (*Read)(void* p, void* buf, size_t* size); + /* reads directly (without buffer). It's same as ISeqInStream::Read */ + SRes (*Seek)(void *p, Int64 *pos, ESzSeek origin); + } ILookInStream; + +-SRes LookInStream_LookRead(ILookInStream *stream, void *buf, size_t *size); ++SRes LookInStream_LookRead(ILookInStream* stream, void* buf, size_t* size); + SRes LookInStream_SeekTo(ILookInStream *stream, UInt64 offset); + + /* reads via ILookInStream::Read */ +-SRes LookInStream_Read2(ILookInStream *stream, void *buf, size_t size, SRes errorType); +-SRes LookInStream_Read(ILookInStream *stream, void *buf, size_t size); ++SRes LookInStream_Read2(ILookInStream* stream, void* buf, size_t size, SRes errorType); ++SRes LookInStream_Read(ILookInStream* stream, void* buf, size_t size); + + #define LookToRead_BUF_SIZE (1 << 14) + +@@ -175,8 +170,8 @@ + { + ILookInStream s; + ISeekInStream *realStream; +- size_t pos; +- size_t size; ++ size_t pos; ++ size_t size; + Byte buf[LookToRead_BUF_SIZE]; + } CLookToRead; + +@@ -208,27 +203,16 @@ + + typedef struct + { +- void *(*Alloc)(void *p, size_t size); ++ void* (*Alloc)(void* p, size_t size); + void (*Free)(void *p, void *address); /* address can be 0 */ + } ISzAlloc; + + #define IAlloc_Alloc(p, size) (p)->Alloc((p), size) + #define IAlloc_Free(p, a) (p)->Free((p), a) + +-#ifdef _WIN32 +- +-#define CHAR_PATH_SEPARATOR '\\' +-#define WCHAR_PATH_SEPARATOR L'\\' +-#define STRING_PATH_SEPARATOR "\\" +-#define WSTRING_PATH_SEPARATOR L"\\" +- +-#else +- + #define CHAR_PATH_SEPARATOR '/' + #define WCHAR_PATH_SEPARATOR L'/' + #define STRING_PATH_SEPARATOR "/" + #define WSTRING_PATH_SEPARATOR L"/" + + #endif +- +-#endif +diff -Nur u-boot-v2019.07/lib/SConscript u-boot-v2019.07_ok/lib/SConscript +--- u-boot-v2019.07/lib/SConscript 1970-01-01 08:00:00.000000000 +0800 ++++ u-boot-v2019.07_ok/lib/SConscript 2020-05-30 23:05:15.608442200 +0800 +@@ -0,0 +1,9 @@ ++import os ++Import('env') ++ ++env = env.Clone() ++ ++src = [os.path.join('crc32.c'), os.path.join('lzma', 'LzmaDec.c'), os.path.join('lzma', 'LzmaTools.c')] ++objs = env.Object(src) ++objs.sort() ++Return('objs') +\ No newline at end of file +diff -Nur u-boot-v2019.07/SConscript u-boot-v2019.07_ok/SConscript +--- u-boot-v2019.07/SConscript 1970-01-01 08:00:00.000000000 +0800 ++++ u-boot-v2019.07_ok/SConscript 2020-05-29 16:04:52.676000000 +0800 +@@ -0,0 +1,34 @@ ++#!/usr/bin/env python3 ++# coding=utf-8 ++ ++import os ++from scripts import common_env ++from scripts.mk_prim_xml_step1 import create_file_id_dic ++Import('env') ++Import('env_cfg') ++Import('module') ++ ++module_path = env_cfg.get_module_dir(module) ++obj_path = env_cfg.obj_path ++module_libs = env_cfg.get_module_libs(module) ++libs = [] ++ ++env = env.Clone() ++env_cfg.append_environs(env, module) ++common_env.print_log_env(env, env_cfg.get_module_dir(module)) ++ ++file_id_dict = None ++file = os.path.join(env_cfg.root, module_path, 'file_id.cfg') ++if not os.path.exists(file): ++ file_id_dict = None ++else: ++ file_id_dict = create_file_id_dic(file) ++ ++for lib in module_libs: ++ print('lib_name:',lib) ++ src_path = module_libs[lib] ++ objs = [] ++ for src in src_path: ++ objs += env.SConscript(os.path.join(src, 'SConscript'), {'env':env, 'id_dict':file_id_dict}, variant_dir = os.path.join('#', obj_path, module_path, src), duplicate = 0) ++ libs += env.Library(lib,sorted(objs)) ++Return('libs') diff --git a/sdk_liteos/third_party/u-boot-v2019.07/patch/CVE-2019-13103.patch b/sdk_liteos/third_party/u-boot-v2019.07/patch/CVE-2019-13103.patch new file mode 100755 index 0000000000000000000000000000000000000000..e0d69117ce34e1a1f622ee59da7db9198948fbf1 --- /dev/null +++ b/sdk_liteos/third_party/u-boot-v2019.07/patch/CVE-2019-13103.patch @@ -0,0 +1,62 @@ +From 232e2f4fd9a24bf08215ddc8c53ccadffc841fb5 Mon Sep 17 00:00:00 2001 +From: Paul Emge +Date: Mon, 8 Jul 2019 16:37:03 -0700 +Subject: [PATCH] CVE-2019-13103: disk: stop infinite recursion in DOS + Partitions + +part_get_info_extended and print_partition_extended can recurse infinitely +while parsing a self-referential filesystem or one with a silly number of +extended partitions. This patch adds a limit to the number of recursive +partitions. + +Signed-off-by: Paul Emge +--- + disk/part_dos.c | 18 ++++++++++++++++++ + 1 file changed, 18 insertions(+) + +diff --git a/disk/part_dos.c b/disk/part_dos.c +index 936cee0..aae9d95 100644 +--- a/disk/part_dos.c ++++ b/disk/part_dos.c +@@ -23,6 +23,10 @@ + + #define DOS_PART_DEFAULT_SECTOR 512 + ++/* should this be configurable? It looks like it's not very common at all ++ * to use large numbers of partitions */ ++#define MAX_EXT_PARTS 256 ++ + /* Convert char[4] in little endian format to the host format integer + */ + static inline unsigned int le32_to_int(unsigned char *le32) +@@ -126,6 +130,13 @@ static void print_partition_extended(struct blk_desc *dev_desc, + dos_partition_t *pt; + int i; + ++ /* set a maximum recursion level */ ++ if (part_num > MAX_EXT_PARTS) ++ { ++ printf("** Nested DOS partitions detected, stopping **\n"); ++ return; ++ } ++ + if (blk_dread(dev_desc, ext_part_sector, 1, (ulong *)buffer) != 1) { + printf ("** Can't read partition table on %d:" LBAFU " **\n", + dev_desc->devnum, ext_part_sector); +@@ -191,6 +202,13 @@ static int part_get_info_extended(struct blk_desc *dev_desc, + int i; + int dos_type; + ++ /* set a maximum recursion level */ ++ if (part_num > MAX_EXT_PARTS) ++ { ++ printf("** Nested DOS partitions detected, stopping **\n"); ++ return -1; ++ } ++ + if (blk_dread(dev_desc, ext_part_sector, 1, (ulong *)buffer) != 1) { + printf ("** Can't read partition table on %d:" LBAFU " **\n", + dev_desc->devnum, ext_part_sector); +-- +1.9.1 + diff --git a/sdk_liteos/third_party/u-boot-v2019.07/patch/CVE-2019-13104.patch b/sdk_liteos/third_party/u-boot-v2019.07/patch/CVE-2019-13104.patch new file mode 100755 index 0000000000000000000000000000000000000000..98d87213d94acbb97aba57299b1fd88c940531a1 --- /dev/null +++ b/sdk_liteos/third_party/u-boot-v2019.07/patch/CVE-2019-13104.patch @@ -0,0 +1,41 @@ +From 878269dbe74229005dd7f27aca66c554e31dad8e Mon Sep 17 00:00:00 2001 +From: Paul Emge +Date: Mon, 8 Jul 2019 16:37:05 -0700 +Subject: [PATCH] CVE-2019-13104: ext4: check for underflow in ext4fs_read_file + +in ext4fs_read_file, it is possible for a broken/malicious file +system to cause a memcpy of a negative number of bytes, which +overflows all memory. This patch fixes the issue by checking for +a negative length. + +Signed-off-by: Paul Emge +--- + fs/ext4/ext4fs.c | 8 +++++--- + 1 file changed, 5 insertions(+), 3 deletions(-) + +diff --git a/fs/ext4/ext4fs.c b/fs/ext4/ext4fs.c +index 85dc122..e2b740c 100644 +--- a/fs/ext4/ext4fs.c ++++ b/fs/ext4/ext4fs.c +@@ -66,13 +66,15 @@ int ext4fs_read_file(struct ext2fs_node *node, loff_t pos, + + ext_cache_init(&cache); + +- if (blocksize <= 0) +- return -1; +- + /* Adjust len so it we can't read past the end of the file. */ + if (len + pos > filesize) + len = (filesize - pos); + ++ if (blocksize <= 0 || len <= 0) { ++ ext_cache_fini(&cache); ++ return -1; ++ } ++ + blockcnt = lldiv(((len + pos) + blocksize - 1), blocksize); + + for (i = lldiv(pos, blocksize); i < blockcnt; i++) { +-- +1.9.1 + diff --git a/sdk_liteos/third_party/u-boot-v2019.07/patch/CVE-2019-13105.patch b/sdk_liteos/third_party/u-boot-v2019.07/patch/CVE-2019-13105.patch new file mode 100755 index 0000000000000000000000000000000000000000..023fa0074e70c1adecc295d5d9f1b7ce8041cee4 --- /dev/null +++ b/sdk_liteos/third_party/u-boot-v2019.07/patch/CVE-2019-13105.patch @@ -0,0 +1,30 @@ +From 6e5a79de658cb1c8012c86e0837379aa6eabd024 Mon Sep 17 00:00:00 2001 +From: Paul Emge +Date: Mon, 8 Jul 2019 16:37:04 -0700 +Subject: [PATCH] CVE-2019-13105: ext4: fix double-free in ext4_cache_read + +ext_cache_read doesn't null cache->buf, after freeing, which results +in a later function double-freeing it. This patch fixes +ext_cache_read to call ext_cache_fini instead of free. + +Signed-off-by: Paul Emge +--- + fs/ext4/ext4fs.c | 2 +- + 1 file changed, 1 insertion(+), 1 deletion(-) + +diff --git a/fs/ext4/ext4fs.c b/fs/ext4/ext4fs.c +index 26db677..85dc122 100644 +--- a/fs/ext4/ext4fs.c ++++ b/fs/ext4/ext4fs.c +@@ -286,7 +286,7 @@ int ext_cache_read(struct ext_block_cache *cache, lbaint_t block, int size) + if (!cache->buf) + return 0; + if (!ext4fs_devread(block, 0, size, cache->buf)) { +- free(cache->buf); ++ ext_cache_fini(cache); + return 0; + } + cache->block = block; +-- +1.9.1 + diff --git a/sdk_liteos/third_party/u-boot-v2019.07/patch/CVE-2019-13106.patch b/sdk_liteos/third_party/u-boot-v2019.07/patch/CVE-2019-13106.patch new file mode 100755 index 0000000000000000000000000000000000000000..fb81570ccea52142e7d7a153aaa3aed79c9f5446 --- /dev/null +++ b/sdk_liteos/third_party/u-boot-v2019.07/patch/CVE-2019-13106.patch @@ -0,0 +1,49 @@ +From e205896c5383c938274262524adceb2775fb03ba Mon Sep 17 00:00:00 2001 +From: Paul Emge +Date: Mon, 8 Jul 2019 16:37:07 -0700 +Subject: [PATCH] CVE-2019-13106: ext4: fix out-of-bounds memset + +In ext4fs_read_file in ext4fs.c, a memset can overwrite the bounds of +the destination memory region. This patch adds a check to disallow +this. + +Signed-off-by: Paul Emge +--- + fs/ext4/ext4fs.c | 7 +++++-- + 1 file changed, 5 insertions(+), 2 deletions(-) + +diff --git a/fs/ext4/ext4fs.c b/fs/ext4/ext4fs.c +index e2b740c..37b31d9 100644 +--- a/fs/ext4/ext4fs.c ++++ b/fs/ext4/ext4fs.c +@@ -61,6 +61,7 @@ int ext4fs_read_file(struct ext2fs_node *node, loff_t pos, + lbaint_t delayed_skipfirst = 0; + lbaint_t delayed_next = 0; + char *delayed_buf = NULL; ++ char *start_buf = buf; + short status; + struct ext_block_cache cache; + +@@ -139,6 +140,7 @@ int ext4fs_read_file(struct ext2fs_node *node, loff_t pos, + } + } else { + int n; ++ int n_left; + if (previous_block_number != -1) { + /* spill */ + status = ext4fs_devread(delayed_start, +@@ -153,8 +155,9 @@ int ext4fs_read_file(struct ext2fs_node *node, loff_t pos, + } + /* Zero no more than `len' bytes. */ + n = blocksize - skipfirst; +- if (n > len) +- n = len; ++ n_left = len - ( buf - start_buf ); ++ if (n > n_left) ++ n = n_left; + memset(buf, 0, n); + } + buf += blocksize - skipfirst; +-- +1.9.1 + diff --git a/sdk_liteos/third_party/u-boot-v2019.07/patch/CVE-2019-14192-14193-14199.patch b/sdk_liteos/third_party/u-boot-v2019.07/patch/CVE-2019-14192-14193-14199.patch new file mode 100755 index 0000000000000000000000000000000000000000..e4f6ed8f3e58086848b5e8e9f59571e1441384f9 --- /dev/null +++ b/sdk_liteos/third_party/u-boot-v2019.07/patch/CVE-2019-14192-14193-14199.patch @@ -0,0 +1,36 @@ +From fe7288069d2e6659117049f7d27e261b550bb725 Mon Sep 17 00:00:00 2001 +From: "liucheng (G)" +Date: Thu, 29 Aug 2019 13:47:33 +0000 +Subject: [PATCH] CVE: net: fix unbounded memcpy of UDP packet +MIME-Version: 1.0 +Content-Type: text/plain; charset=utf8 +Content-Transfer-Encoding: 8bit + +This patch adds a check to udp_len to fix unbounded memcpy for +CVE-2019-14192, CVE-2019-14193 and CVE-2019-14199. + +Signed-off-by: Cheng Liu +Reviewed-by: Simon Goldschmidt +Reported-by: Fermín Serna +Acked-by: Joe Hershberger +--- + net/net.c | 3 +++ + 1 file changed, 3 insertions(+) + +diff --git a/net/net.c b/net/net.c +index 74a8a36..ded86e7 100644 +--- a/net/net.c ++++ b/net/net.c +@@ -1264,6 +1264,9 @@ void net_process_received_packet(uchar *in_packet, int len) + return; + } + ++ if (ntohs(ip->udp_len) < UDP_HDR_SIZE || ntohs(ip->udp_len) > ntohs(ip->ip_len)) ++ return; ++ + debug_cond(DEBUG_DEV_PKT, + "received UDP (to=%pI4, from=%pI4, len=%d)\n", + &dst_ip, &src_ip, len); +-- +1.9.1 + diff --git a/sdk_liteos/third_party/u-boot-v2019.07/patch/CVE-2019-14194-14198.patch b/sdk_liteos/third_party/u-boot-v2019.07/patch/CVE-2019-14194-14198.patch new file mode 100755 index 0000000000000000000000000000000000000000..10735703766b7ddbcd35a1f99be65d5ef514b5dd --- /dev/null +++ b/sdk_liteos/third_party/u-boot-v2019.07/patch/CVE-2019-14194-14198.patch @@ -0,0 +1,35 @@ +From aa207cf3a6d68f39d64cd29057a4fb63943e9078 Mon Sep 17 00:00:00 2001 +From: "liucheng (G)" +Date: Thu, 29 Aug 2019 13:47:48 +0000 +Subject: [PATCH] CVE-2019-14194/CVE-2019-14198: nfs: fix unbounded memcpy with + a failed length check at nfs_read_reply +MIME-Version: 1.0 +Content-Type: text/plain; charset=utf8 +Content-Transfer-Encoding: 8bit + +This patch adds a check to rpc_pkt.u.reply.data at nfs_read_reply. + +Signed-off-by: Cheng Liu +Reported-by: Fermín Serna +Acked-by: Joe Hershberger +--- + net/nfs.c | 3 +++ + 1 file changed, 3 insertions(+) + +diff --git a/net/nfs.c b/net/nfs.c +index b7cf3b3..11941fa 100644 +--- a/net/nfs.c ++++ b/net/nfs.c +@@ -701,6 +701,9 @@ static int nfs_read_reply(uchar *pkt, unsigned len) + &(rpc_pkt.u.reply.data[4 + nfsv3_data_offset]); + } + ++ if (((uchar *)&(rpc_pkt.u.reply.data[0]) - (uchar *)(&rpc_pkt) + rlen) > len) ++ return -9999; ++ + if (store_block(data_ptr, nfs_offset, rlen)) + return -9999; + +-- +1.9.1 + diff --git a/sdk_liteos/third_party/u-boot-v2019.07/patch/CVE-2019-14195.patch b/sdk_liteos/third_party/u-boot-v2019.07/patch/CVE-2019-14195.patch new file mode 100755 index 0000000000000000000000000000000000000000..42565c787e3e1de145fa4c333ff0ed86a3458914 --- /dev/null +++ b/sdk_liteos/third_party/u-boot-v2019.07/patch/CVE-2019-14195.patch @@ -0,0 +1,35 @@ +From cf3a4f1e86ecdd24f87b615051b49d8e1968c230 Mon Sep 17 00:00:00 2001 +From: "liucheng (G)" +Date: Thu, 29 Aug 2019 13:47:54 +0000 +Subject: [PATCH] CVE-2019-14195: nfs: fix unbounded memcpy with unvalidated + length at nfs_readlink_reply +MIME-Version: 1.0 +Content-Type: text/plain; charset=utf8 +Content-Transfer-Encoding: 8bit + +This patch adds a check to rpc_pkt.u.reply.data at nfs_readlink_reply. + +Signed-off-by: Cheng Liu +Reported-by: Fermín Serna +Acked-by: Joe Hershberger +--- + net/nfs.c | 3 +++ + 1 file changed, 3 insertions(+) + +diff --git a/net/nfs.c b/net/nfs.c +index 11941fa..915acd9 100644 +--- a/net/nfs.c ++++ b/net/nfs.c +@@ -634,6 +634,9 @@ static int nfs_readlink_reply(uchar *pkt, unsigned len) + /* new path length */ + rlen = ntohl(rpc_pkt.u.reply.data[1 + nfsv3_data_offset]); + ++ if (((uchar *)&(rpc_pkt.u.reply.data[0]) - (uchar *)(&rpc_pkt) + rlen) > len) ++ return -NFS_RPC_DROP; ++ + if (*((char *)&(rpc_pkt.u.reply.data[2 + nfsv3_data_offset])) != '/') { + int pathlen; + +-- +1.9.1 + diff --git a/sdk_liteos/third_party/u-boot-v2019.07/patch/CVE-2019-14196.patch b/sdk_liteos/third_party/u-boot-v2019.07/patch/CVE-2019-14196.patch new file mode 100755 index 0000000000000000000000000000000000000000..0d16b4d5a9f916340269901100c9ab63395d52fc --- /dev/null +++ b/sdk_liteos/third_party/u-boot-v2019.07/patch/CVE-2019-14196.patch @@ -0,0 +1,41 @@ +From 5d14ee4e53a81055d34ba280cb8fd90330f22a96 Mon Sep 17 00:00:00 2001 +From: "liucheng (G)" +Date: Thu, 29 Aug 2019 13:48:02 +0000 +Subject: [PATCH] CVE-2019-14196: nfs: fix unbounded memcpy with a failed + length check at nfs_lookup_reply +MIME-Version: 1.0 +Content-Type: text/plain; charset=utf8 +Content-Transfer-Encoding: 8bit + +This patch adds a check to rpc_pkt.u.reply.data at nfs_lookup_reply. + +Signed-off-by: Cheng Liu +Reported-by: Fermín Serna +Acked-by: Joe Hershberger +--- + net/nfs.c | 4 ++++ + 1 file changed, 4 insertions(+) + +diff --git a/net/nfs.c b/net/nfs.c +index 915acd9..89952ae 100644 +--- a/net/nfs.c ++++ b/net/nfs.c +@@ -566,11 +566,15 @@ static int nfs_lookup_reply(uchar *pkt, unsigned len) + } + + if (supported_nfs_versions & NFSV2_FLAG) { ++ if (((uchar *)&(rpc_pkt.u.reply.data[0]) - (uchar *)(&rpc_pkt) + NFS_FHSIZE) > len) ++ return -NFS_RPC_DROP; + memcpy(filefh, rpc_pkt.u.reply.data + 1, NFS_FHSIZE); + } else { /* NFSV3_FLAG */ + filefh3_length = ntohl(rpc_pkt.u.reply.data[1]); + if (filefh3_length > NFS3_FHSIZE) + filefh3_length = NFS3_FHSIZE; ++ if (((uchar *)&(rpc_pkt.u.reply.data[0]) - (uchar *)(&rpc_pkt) + filefh3_length) > len) ++ return -NFS_RPC_DROP; + memcpy(filefh, rpc_pkt.u.reply.data + 2, filefh3_length); + } + +-- +1.9.1 + diff --git a/sdk_liteos/third_party/u-boot-v2019.07/patch/CVE-2019-14197-14200-14201-14202-14203-14204.patch b/sdk_liteos/third_party/u-boot-v2019.07/patch/CVE-2019-14197-14200-14201-14202-14203-14204.patch new file mode 100755 index 0000000000000000000000000000000000000000..473cc50babe650cccf8e64f21c7aaf49996e6e83 --- /dev/null +++ b/sdk_liteos/third_party/u-boot-v2019.07/patch/CVE-2019-14197-14200-14201-14202-14203-14204.patch @@ -0,0 +1,36 @@ +From 741a8a08ebe5bc3ccfe3cde6c2b44ee53891af21 Mon Sep 17 00:00:00 2001 +From: "liucheng (G)" +Date: Thu, 29 Aug 2019 13:47:40 +0000 +Subject: [PATCH] CVE: nfs: fix stack-based buffer overflow in some nfs_handler + reply helper functions +MIME-Version: 1.0 +Content-Type: text/plain; charset=utf8 +Content-Transfer-Encoding: 8bit + +This patch adds a check to nfs_handler to fix buffer overflow for CVE-2019-14197, +CVE-2019-14200, CVE-2019-14201, CVE-2019-14202, CVE-2019-14203 and CVE-2019-14204. + +Signed-off-by: Cheng Liu +Reported-by: Fermín Serna +Acked-by: Joe Hershberger +--- + net/nfs.c | 3 +++ + 1 file changed, 3 insertions(+) + +diff --git a/net/nfs.c b/net/nfs.c +index d6a7f8e..b7cf3b3 100644 +--- a/net/nfs.c ++++ b/net/nfs.c +@@ -732,6 +732,9 @@ static void nfs_handler(uchar *pkt, unsigned dest, struct in_addr sip, + + debug("%s\n", __func__); + ++ if (len > sizeof(struct rpc_t)) ++ return; ++ + if (dest != nfs_our_port) + return; + +-- +1.9.1 + diff --git a/sdk_liteos/third_party/u-boot-v2019.07/u-boot-v2019.07.tar.gz b/sdk_liteos/third_party/u-boot-v2019.07/u-boot-v2019.07.tar.gz new file mode 100755 index 0000000000000000000000000000000000000000..2906c507150bc4271407d0608e352a2122065898 Binary files /dev/null and b/sdk_liteos/third_party/u-boot-v2019.07/u-boot-v2019.07.tar.gz differ diff --git a/sdk_liteos/tools/efuse_tool/Efuse.ini b/sdk_liteos/tools/efuse_tool/Efuse.ini new file mode 100755 index 0000000000000000000000000000000000000000..52672c03efdb92cfc4de8bed1bdac0c238b3ec34 --- /dev/null +++ b/sdk_liteos/tools/efuse_tool/Efuse.ini @@ -0,0 +1,283 @@ +[EFUSE_CONFIG] +EFUSE_NAME1=CHIP_ID +EFUSE_START_BIT1=0 +EFUSE_BIT_WIDTH1=8 +EFUSE_NAME2=DIE_ID +EFUSE_START_BIT2=8 +EFUSE_BIT_WIDTH2=192 +EFUSE_NAME3=PMU_FUSE1 +EFUSE_START_BIT3=200 +EFUSE_BIT_WIDTH3=10 +EFUSE_NAME4=PMU_FUSE2 +EFUSE_START_BIT4=210 +EFUSE_BIT_WIDTH4=10 +EFUSE_NAME5=FLASH_ENCPY_CNT3 +EFUSE_START_BIT5=220 +EFUSE_BIT_WIDTH5=2 +EFUSE_NAME6=FLASH_ENCPY_CNT4 +EFUSE_START_BIT6=222 +EFUSE_BIT_WIDTH6=2 +EFUSE_NAME7=FLASH_ENCPY_CNT5 +EFUSE_START_BIT7=224 +EFUSE_BIT_WIDTH7=2 +EFUSE_NAME8=SEC_BOOT +EFUSE_START_BIT8=226 +EFUSE_BIT_WIDTH8=8 +EFUSE_NAME9=DSLEEP_FLAG +EFUSE_START_BIT9=234 +EFUSE_BIT_WIDTH9=1 +EFUSE_NAME10=LOCK_FLASH_ENCPY_CNT3 +EFUSE_START_BIT10=235 +EFUSE_BIT_WIDTH10=1 +EFUSE_NAME11=LOCK_FLASH_ENCPY_CNT4 +EFUSE_START_BIT11=236 +EFUSE_BIT_WIDTH11=1 +EFUSE_NAME12=LOCK_FLASH_ENCPY_CNT5 +EFUSE_START_BIT12=237 +EFUSE_BIT_WIDTH12=1 +EFUSE_NAME13=LOCK_SEC_BOOT +EFUSE_START_BIT13=238 +EFUSE_BIT_WIDTH13=1 +EFUSE_NAME14=LOCK_DSLEEP_FLAG +EFUSE_START_BIT14=239 +EFUSE_BIT_WIDTH14=1 +EFUSE_NAME15=ROOT_PUBKEY +EFUSE_START_BIT15=240 +EFUSE_BIT_WIDTH15=256 +EFUSE_NAME16=ROOT_KEY +EFUSE_START_BIT16=496 +EFUSE_BIT_WIDTH16=256 +EFUSE_NAME17=CUSTOMER_RSVD0_RW_ID +EFUSE_START_BIT17=752 +EFUSE_BIT_WIDTH17=256 +EFUSE_NAME18=SUBKEY_CAT +EFUSE_START_BIT18=1008 +EFUSE_BIT_WIDTH18=32 +EFUSE_NAME19=ENCRYPT_FLAG +EFUSE_START_BIT19=1040 +EFUSE_BIT_WIDTH19=8 +EFUSE_NAME20=SUBKEY_RSIM +EFUSE_START_BIT20=1048 +EFUSE_BIT_WIDTH20=24 +EFUSE_NAME21=START_TYPE +EFUSE_START_BIT21=1072 +EFUSE_BIT_WIDTH21=1 +EFUSE_NAME22=JTM +EFUSE_START_BIT22=1073 +EFUSE_BIT_WIDTH22=1 +EFUSE_NAME23=UTM0 +EFUSE_START_BIT23=1074 +EFUSE_BIT_WIDTH23=1 +EFUSE_NAME24=UTM1 +EFUSE_START_BIT24=1075 +EFUSE_BIT_WIDTH24=1 +EFUSE_NAME25=UTM2 +EFUSE_START_BIT25=1076 +EFUSE_BIT_WIDTH25=1 +EFUSE_NAME26=SDC +EFUSE_START_BIT26=1077 +EFUSE_BIT_WIDTH26=1 +EFUSE_NAME27=RSVD0 +EFUSE_START_BIT27=1078 +EFUSE_BIT_WIDTH27=1 +EFUSE_NAME28=KDF2ECC_HUK_DISABLE +EFUSE_START_BIT28=1079 +EFUSE_BIT_WIDTH28=1 +EFUSE_NAME29=SSS_CORNER_RW_ID +EFUSE_START_BIT29=1080 +EFUSE_BIT_WIDTH29=2 +EFUSE_NAME30=UART_HALT_INTERVAL +EFUSE_START_BIT30=1082 +EFUSE_BIT_WIDTH30=2 +EFUSE_NAME31=TSENSOR_RIM +EFUSE_START_BIT31=1084 +EFUSE_BIT_WIDTH31=4 +EFUSE_NAME32=CHIP_BK_RW_ID +EFUSE_START_BIT32=1088 +EFUSE_BIT_WIDTH32=8 +EFUSE_NAME33=IPV4_MAC_ADDR +EFUSE_START_BIT33=1096 +EFUSE_BIT_WIDTH33=48 +EFUSE_NAME34=IPV6_MAC_ADDR +EFUSE_START_BIT34=1144 +EFUSE_BIT_WIDTH34=128 +EFUSE_NAME35=PG2GCCKA0_TRIM0 +EFUSE_START_BIT35=1272 +EFUSE_BIT_WIDTH35=32 +EFUSE_NAME36=PG2GCCKA1_TRIM0 +EFUSE_START_BIT36=1304 +EFUSE_BIT_WIDTH36=32 +EFUSE_NAME37=NVRAM_PA2GA0_TRIM0 +EFUSE_START_BIT37=1336 +EFUSE_BIT_WIDTH37=32 +EFUSE_NAME38=NVRAM_PA2GA1_TRIM0 +EFUSE_START_BIT38=1368 +EFUSE_BIT_WIDTH38=32 +EFUSE_NAME39=PG2GCCKA0_TRIM1 +EFUSE_START_BIT39=1400 +EFUSE_BIT_WIDTH39=32 +EFUSE_NAME40=PG2GCCKA1_TRIM1 +EFUSE_START_BIT40=1432 +EFUSE_BIT_WIDTH40=32 +EFUSE_NAME41=NVRAM_PA2GA0_TRIM1 +EFUSE_START_BIT41=1464 +EFUSE_BIT_WIDTH41=32 +EFUSE_NAME42=NVRAM_PA2GA1_TRIM1 +EFUSE_START_BIT42=1496 +EFUSE_BIT_WIDTH42=32 +EFUSE_NAME43=PG2GCCKA0_TRIM2 +EFUSE_START_BIT43=1528 +EFUSE_BIT_WIDTH43=32 +EFUSE_NAME44=PG2GCCKA1_TRIM2 +EFUSE_START_BIT44=1560 +EFUSE_BIT_WIDTH44=32 +EFUSE_NAME45=NVRAM_PA2GA0_TRIM2 +EFUSE_START_BIT45=1592 +EFUSE_BIT_WIDTH45=32 +EFUSE_NAME46=NVRAM_PA2GA1_TRIM2 +EFUSE_START_BIT46=1624 +EFUSE_BIT_WIDTH46=32 +EFUSE_NAME47=TEE_BOOT_VER +EFUSE_START_BIT47=1656 +EFUSE_BIT_WIDTH47=16 +EFUSE_NAME48=TEE_KERNEL_VER +EFUSE_START_BIT48=1672 +EFUSE_BIT_WIDTH48=48 +EFUSE_NAME49=TEE_SALT +EFUSE_START_BIT49=1720 +EFUSE_BIT_WIDTH49=128 +EFUSE_NAME50=FLASH_ENCPY_CNT0 +EFUSE_START_BIT50=1848 +EFUSE_BIT_WIDTH50=2 +EFUSE_NAME51=FLASH_ENCPY_CNT1 +EFUSE_START_BIT51=1850 +EFUSE_BIT_WIDTH51=2 +EFUSE_NAME52=FLASH_ENCPY_CNT2 +EFUSE_START_BIT52=1852 +EFUSE_BIT_WIDTH52=2 +EFUSE_NAME53=FLASH_ENCPY_CFG +EFUSE_START_BIT53=1854 +EFUSE_BIT_WIDTH53=1 +EFUSE_NAME54=FLASH_SCRAMBLE_EN +EFUSE_START_BIT54=1855 +EFUSE_BIT_WIDTH54=1 +EFUSE_NAME55=USER_FLASH_IND +EFUSE_START_BIT55=1856 +EFUSE_BIT_WIDTH55=10 +EFUSE_NAME56=RF_PDBUFFER_GCAL +EFUSE_START_BIT56=1866 +EFUSE_BIT_WIDTH56=18 +EFUSE_NAME57=CUSTOMER_RSVD1 +EFUSE_START_BIT57=1884 +EFUSE_BIT_WIDTH57=64 +EFUSE_NAME58=DIE_2_RW_ID +EFUSE_START_BIT58=1948 +EFUSE_BIT_WIDTH58=64 +EFUSE_NAME59=LOCK_CHIP_ID +EFUSE_START_BIT59=2012 +EFUSE_BIT_WIDTH59=1 +EFUSE_NAME60=LOCK_DIE_ID +EFUSE_START_BIT60=2013 +EFUSE_BIT_WIDTH60=1 +EFUSE_NAME61=LOCK_PMU_FUSE1_FUSE2_START_TYPE_TSENSOR +EFUSE_START_BIT61=2014 +EFUSE_BIT_WIDTH61=1 +EFUSE_NAME62=LOCK_ROOT_PUBKEY +EFUSE_START_BIT62=2015 +EFUSE_BIT_WIDTH62=1 +EFUSE_NAME63=LOCK_ROOT_KEY +EFUSE_START_BIT63=2016 +EFUSE_BIT_WIDTH63=1 +EFUSE_NAME64=LOCK_CUSTOMER_RSVD0_ID +EFUSE_START_BIT64=2017 +EFUSE_BIT_WIDTH64=1 +EFUSE_NAME65=LOCK_SUBKEY_CAT +EFUSE_START_BIT65=2018 +EFUSE_BIT_WIDTH65=1 +EFUSE_NAME66=LOCK_ENCRYPT_RSIM +EFUSE_START_BIT66=2019 +EFUSE_BIT_WIDTH66=1 +EFUSE_NAME67=LOCK_JTM +EFUSE_START_BIT67=2020 +EFUSE_BIT_WIDTH67=1 +EFUSE_NAME68=LOCK_UTM0 +EFUSE_START_BIT68=2021 +EFUSE_BIT_WIDTH68=1 +EFUSE_NAME69=LOCK_UTM1 +EFUSE_START_BIT69=2022 +EFUSE_BIT_WIDTH69=1 +EFUSE_NAME70=LOCK_UTM2 +EFUSE_START_BIT70=2023 +EFUSE_BIT_WIDTH70=1 +EFUSE_NAME71=LOCK_SDC +EFUSE_START_BIT71=2024 +EFUSE_BIT_WIDTH71=1 +EFUSE_NAME72=LOCK_RSVD0 +EFUSE_START_BIT72=2025 +EFUSE_BIT_WIDTH72=1 +EFUSE_NAME73=LOCK_SSS_CORNER_ID +EFUSE_START_BIT73=2026 +EFUSE_BIT_WIDTH73=1 +EFUSE_NAME74=LOCK_UART_HALT_INTERVAL +EFUSE_START_BIT74=2027 +EFUSE_BIT_WIDTH74=1 +EFUSE_NAME75=LOCK_CHIP_BK_ID +EFUSE_START_BIT75=2028 +EFUSE_BIT_WIDTH75=1 +EFUSE_NAME76=LOCK_IPV4_IPV6_MAC_ADDR +EFUSE_START_BIT76=2029 +EFUSE_BIT_WIDTH76=1 +EFUSE_NAME77=LOCK_PG2GCCKA0_PG2GCCKA1_TRIM0 +EFUSE_START_BIT77=2030 +EFUSE_BIT_WIDTH77=1 +EFUSE_NAME78=LOCK_NVRAM_PA2GA0_PA2GA1_TRIM0 +EFUSE_START_BIT78=2031 +EFUSE_BIT_WIDTH78=1 +EFUSE_NAME79=LOCK_PG2GCCKA0_PG2GCCKA1_TRIM1 +EFUSE_START_BIT79=2032 +EFUSE_BIT_WIDTH79=1 +EFUSE_NAME80=LOCK_NVRAM_PA2GA0_PA2GA1_TRIM1 +EFUSE_START_BIT80=2033 +EFUSE_BIT_WIDTH80=1 +EFUSE_NAME81=LOCK_PG2GCCKA0_PG2GCCKA1_TRIM2 +EFUSE_START_BIT81=2034 +EFUSE_BIT_WIDTH81=1 +EFUSE_NAME82=LOCK_NVRAM_PA2GA0_PA2GA1_TRIM2 +EFUSE_START_BIT82=2035 +EFUSE_BIT_WIDTH82=1 +EFUSE_NAME83=LOCK_TEE_BOOT_VER +EFUSE_START_BIT83=2036 +EFUSE_BIT_WIDTH83=1 +EFUSE_NAME84=LOCK_TEE_KERNEL_VER +EFUSE_START_BIT84=2037 +EFUSE_BIT_WIDTH84=1 +EFUSE_NAME85=LOCK_TEE_SALT +EFUSE_START_BIT85=2038 +EFUSE_BIT_WIDTH85=1 +EFUSE_NAME86=LOCK_FLASH_ENCPY_CNT0 +EFUSE_START_BIT86=2039 +EFUSE_BIT_WIDTH86=1 +EFUSE_NAME87=LOCK_FLASH_ENCPY_CNT1 +EFUSE_START_BIT87=2040 +EFUSE_BIT_WIDTH87=1 +EFUSE_NAME88=LOCK_FLASH_ENCPY_CNT2 +EFUSE_START_BIT88=2041 +EFUSE_BIT_WIDTH88=1 +EFUSE_NAME89=LOCK_FLASH_ENCPY_CFG +EFUSE_START_BIT89=2042 +EFUSE_BIT_WIDTH89=1 +EFUSE_NAME90=LOCK_FLASH_SCRAMBLE_EN_FLASH_IND +EFUSE_START_BIT90=2043 +EFUSE_BIT_WIDTH90=1 +EFUSE_NAME91=LOCK_RF_PDBUFFER_GCAL +EFUSE_START_BIT91=2044 +EFUSE_BIT_WIDTH91=1 +EFUSE_NAME92=LOCK_CUSTOMER_RSVD1 +EFUSE_START_BIT92=2045 +EFUSE_BIT_WIDTH92=1 +EFUSE_NAME93=LOCK_LOCK_DIE_2_ID +EFUSE_START_BIT93=2046 +EFUSE_BIT_WIDTH93=1 +EFUSE_NAME94=LOCK_KDF2ECC_HUK_DISABLE +EFUSE_START_BIT94=2047 +EFUSE_BIT_WIDTH94=1 diff --git a/sdk_liteos/tools/efuse_tool/efuse.csv b/sdk_liteos/tools/efuse_tool/efuse.csv new file mode 100755 index 0000000000000000000000000000000000000000..d79c165b30e8fc5185b4e10ac03892dcf9e58b4e --- /dev/null +++ b/sdk_liteos/tools/efuse_tool/efuse.csv @@ -0,0 +1,95 @@ +burn,name,start_bit,bit_width,value,lock +0,CHIP_ID,0,8,0x00000000,PG0 +0,DIE_ID,8,192,0x00000000 0x00000000 0x00000000 0x00000000 0x00000000 0x00000000,PG1 +0,PMU_FUSE1,200,10,0x00000000,PG2 +0,PMU_FUSE2,210,10,0x00000000,PG2 +0,FLASH_ENCPY_CNT3,220,2,0x00000000,PG36 +0,FLASH_ENCPY_CNT4,222,2,0x00000000,PG37 +0,FLASH_ENCPY_CNT5,224,2,0x00000000,PG38 +0,SEC_BOOT,226,8,0x00000042,PG39 +0,DSLEEP_FLAG,234,1,0x00000000,PG40 +0,LOCK_FLASH_ENCPY_CNT3,235,1,0x00000000, +0,LOCK_FLASH_ENCPY_CNT4,236,1,0x00000000, +0,LOCK_FLASH_ENCPY_CNT5,237,1,0x00000000, +0,LOCK_SEC_BOOT,238,1,0x00000000, +0,LOCK_DSLEEP_FLAG,239,1,0x00000000, +0,ROOT_PUBKEY,240,256,0x00000000 0x00000000 0x00000000 0x00000000 0x00000000 0x00000000 0x00000000 0x00000000,PG3 +0,ROOT_KEY,496,256,0x00000000 0x00000000 0x00000000 0x00000000 0x00000000 0x00000000 0x00000000 0x00000000,PG4 +0,CUSTOMER_RSVD0_RW_ID,752,256,0x00000000 0x00000000 0x00000000 0x00000000 0x00000000 0x00000000 0x00000000 0x00000000,PG5 +0,SUBKEY_CAT,1008,32,0x00000000,PG6 +0,ENCRYPT_FLAG,1040,8,0x00000042,PG7 +0,SUBKEY_RSIM,1048,24,0x00000000,PG7 +0,START_TYPE,1072,1,0x00000001,PG2 +0,JTM,1073,1,0x00000000,PG8 +0,UTM0,1074,1,0x00000000,PG9 +0,UTM1,1075,1,0x00000000,PG10 +0,UTM2,1076,1,0x00000000,PG11 +0,SDC,1077,1,0x00000000,PG12 +0,RSVD0,1078,1,0x00000000,PG13 +0,KDF2ECC_HUK_DISABLE,1079,1,0x00000000,PG35 +0,SSS_CORNER_RW_ID,1080,2,0x00000000,PG14 +0,UART_HALT_INTERVAL,1082,2,0x00000000,PG15 +0,TSENSOR_RIM,1084,4,0x00000000,PG2 +0,CHIP_BK_RW_ID,1088,8,0x00000000,PG16 +0,IPV4_MAC_ADDR,1096,48,0x00000000 0x00000000,PG17 +0,IPV6_MAC_ADDR,1144,128,0x00000000 0x00000000 0x00000000 0x00000000,PG17 +0,PG2GCCKA0_TRIM0,1272,32,0x00000000,PG18 +0,PG2GCCKA1_TRIM0,1304,32,0x00000000,PG18 +0,NVRAM_PA2GA0_TRIM0,1336,32,0x00000000,PG19 +0,NVRAM_PA2GA1_TRIM0,1368,32,0x00000000,PG19 +0,PG2GCCKA0_TRIM1,1400,32,0x00000000,PG20 +0,PG2GCCKA1_TRIM1,1432,32,0x00000000,PG20 +0,NVRAM_PA2GA0_TRIM1,1464,32,0x00000000,PG21 +0,NVRAM_PA2GA1_TRIM1,1496,32,0x00000000,PG21 +0,PG2GCCKA0_TRIM2,1528,32,0x00000000,PG22 +0,PG2GCCKA1_TRIM2,1560,32,0x00000000,PG22 +0,NVRAM_PA2GA0_TRIM2,1592,32,0x00000000,PG23 +0,NVRAM_PA2GA1_TRIM2,1624,32,0x00000000,PG23 +0,TEE_BOOT_VER,1656,16,0x00000000,PG24 +0,TEE_KERNEL_VER,1672,48,0x00000000 0x00000000,PG25 +0,TEE_SALT,1720,128,0x00000000 0x00000000 0x00000000 0x00000000,PG26 +0,FLASH_ENCPY_CNT0,1848,2,0x00000000,PG27 +0,FLASH_ENCPY_CNT1,1850,2,0x00000000,PG28 +0,FLASH_ENCPY_CNT2,1852,2,0x00000000,PG29 +0,FLASH_ENCPY_CFG,1854,1,0x00000000,PG30 +0,FLASH_SCRAMBLE_EN,1855,1,0x00000000,PG31 +0,USER_FLASH_IND,1856,10,0x00000000,PG31 +0,RF_PDBUFFER_GCAL,1866,18,0x00000000,PG32 +0,CUSTOMER_RSVD1,1884,64,0x00000000 0x00000000,PG33 +0,DIE_2_RW_ID,1948,64,0x00000000 0x00000000,PG34 +0,LOCK_CHIP_ID,2012,1,0x00000000, +0,LOCK_DIE_ID,2013,1,0x00000000, +0,LOCK_PMU_FUSE1_FUSE2_START_TYPE_TSENSOR,2014,1,0x00000000, +0,LOCK_ROOT_PUBKEY,2015,1,0x00000000, +0,LOCK_ROOT_KEY,2016,1,0x00000000, +0,LOCK_CUSTOMER_RSVD0_ID,2017,1,0x00000000, +0,LOCK_SUBKEY_CAT,2018,1,0x00000000, +0,LOCK_ENCRYPT_RSIM,2019,1,0x00000000, +0,LOCK_JTM,2020,1,0x00000000, +0,LOCK_UTM0,2021,1,0x00000000, +0,LOCK_UTM1,2022,1,0x00000000, +0,LOCK_UTM2,2023,1,0x00000000, +0,LOCK_SDC,2024,1,0x00000000, +0,LOCK_RSVD0,2025,1,0x00000000, +0,LOCK_SSS_CORNER_ID,2026,1,0x00000000, +0,LOCK_UART_HALT_INTERVAL,2027,1,0x00000000, +0,LOCK_CHIP_BK_ID,2028,1,0x00000000, +0,LOCK_IPV4_IPV6_MAC_ADDR,2029,1,0x00000000, +0,LOCK_PG2GCCKA0_PG2GCCKA1_TRIM0,2030,1,0x00000000, +0,LOCK_NVRAM_PA2GA0_PA2GA1_TRIM0,2031,1,0x00000000, +0,LOCK_PG2GCCKA0_PG2GCCKA1_TRIM1,2032,1,0x00000000, +0,LOCK_NVRAM_PA2GA0_PA2GA1_TRIM1,2033,1,0x00000000, +0,LOCK_PG2GCCKA0_PG2GCCKA1_TRIM2,2034,1,0x00000000, +0,LOCK_NVRAM_PA2GA0_PA2GA1_TRIM2,2035,1,0x00000000, +0,LOCK_TEE_BOOT_VER,2036,1,0x00000000, +0,LOCK_TEE_KERNEL_VER,2037,1,0x00000000, +0,LOCK_TEE_SALT,2038,1,0x00000000, +0,LOCK_FLASH_ENCPY_CNT0,2039,1,0x00000000, +0,LOCK_FLASH_ENCPY_CNT1,2040,1,0x00000000, +0,LOCK_FLASH_ENCPY_CNT2,2041,1,0x00000000, +0,LOCK_FLASH_ENCPY_CFG,2042,1,0x00000000, +0,LOCK_FLASH_SCRAMBLE_EN_FLASH_IND,2043,1,0x00000000, +0,LOCK_RF_PDBUFFER_GCAL,2044,1,0x00000000, +0,LOCK_CUSTOMER_RSVD1,2045,1,0x00000000, +0,LOCK_DIE_2_ID,2046,1,0x00000000, +0,LOCK_KDF2ECC_HUK_DISABLE,2047,1,0x00000000, diff --git a/sdk_liteos/tools/efuse_tool/efuse_cfg_gen.py b/sdk_liteos/tools/efuse_tool/efuse_cfg_gen.py new file mode 100755 index 0000000000000000000000000000000000000000..57b84a710d4aa489dc438ed0857e61ae0a064aad --- /dev/null +++ b/sdk_liteos/tools/efuse_tool/efuse_cfg_gen.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python3 +# coding=utf-8 + +''' +* Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +* Description: efuse too scripts. +''' + +import csv +import struct +import hashlib +import os +from sys import version_info + +def str_to_hex(s): + return ' '.join([hex(ord(c)).replace('0x', '') for c in s]) + +def print_bytes(bytes): + if version_info.major == 3: + c = bytes.hex() + print(c) + else: + c = bytes.encode('hex') + print(c) + +number = 0 +value_len = 0 +buf = b'' +csv_dir = os.path.split(os.path.realpath(__file__))[0] +csv_path = os.path.join(csv_dir, 'efuse.csv') +#print('csv_path:', csv_path) +bin_path = os.path.join(csv_dir, 'efuse_cfg.bin') +#print('bin_path:', bin_path) + +# 用reader读取csv文件 +with open(csv_path, 'r') as csvFile: + reader = csv.reader(csvFile) + for line in reader: + if(line[0] == "1"): + size = int(line[3]) + if (size <= 32): + value_len = 4 + elif (size <= 64): + value_len = 8 + else: + value_len = size // 8 + result = struct.pack('BBHHH', 0, 8, int(line[2]), size, value_len) + value_str = line[4] + value_list = value_str.split(" ") + value_struct = b'' + for i in range(value_len // 4): + value = int(value_list[i], 16) + value_struct = value_struct + struct.pack('I', value) + print_bytes(value_struct) + buf = buf + result + value_struct + number = number + 1 +header = struct.pack('BBHIII', 0, 48, number, len(buf) + 48, 0, 0) +data = header + buf +hash = hashlib.sha256(data).digest() +bin_data = hash + data +#print(bin_data) + +with open(bin_path, 'wb') as f: + f.write(bin_data) diff --git a/sdk_liteos/tools/lzma_tool/lzma_tool b/sdk_liteos/tools/lzma_tool/lzma_tool new file mode 100755 index 0000000000000000000000000000000000000000..a35ec1314c1a1c91750589c36b8ec238ea58c6db Binary files /dev/null and b/sdk_liteos/tools/lzma_tool/lzma_tool differ diff --git a/sdk_liteos/tools/menuconfig/Kconfig b/sdk_liteos/tools/menuconfig/Kconfig new file mode 100644 index 0000000000000000000000000000000000000000..9cadf33871d41cd3a7372678429cabbae646ea38 --- /dev/null +++ b/sdk_liteos/tools/menuconfig/Kconfig @@ -0,0 +1,201 @@ + menu "Target Chip" + choice TARGET_CHIP + prompt "Hi3861" + default TARGET_CHIP_HI3861 + config TARGET_CHIP_HI3861 + bool "Hi3861" + help + Set Target Chip as Hi3861. + endchoice + endmenu + + menu "Security Settings" + choice TARGET_SIGNATURE_MOD + prompt "Signature Algorithm for bootloader and upgrade file" + default TARGET_SIG_SHA256 + config TARGET_SIG_RSA_V15 + bool "RSA_V15" + help + RSA_V15 Signature Algorithm of bootloader and upgrade file. + + config TARGET_SIG_RSA_PSS + bool "RSA_PSS" + help + RSA_PSS Signature Algorithm of bootloader and upgrade file. + + config TARGET_SIG_ECC + bool "ECC" + help + ECC Signature Algorithm of bootloader and upgrade file. + + config TARGET_SIG_SHA256 + bool "SHA256" + help + SHA256 Signature Algorithm of bootloader and upgrade file. + endchoice + + config BOOT_ENCRYPT + depends on TARGET_SIG_RSA_PSS || TARGET_SIG_ECC || TARGET_SIG_RSA_V15 + bool "Enable bootloader encryption" + help + Enable Bootloader encryption. + config TARGET_BOOT_VER + int "boot ver(value form 0 to 16)" + default 0 + help + Set boot version. + config TARGET_KERNEL_VER + int "kernel ver(value form 0 to 48)" + default 0 + help + Set kernel version. + config TEE_HUKS_SUPPORT + bool "TEE HUKS support" + default n + select FILE_SYSTEM_SUPPORT + help + Support TEE HUKS interface. + config TEE_HUKS_DEMO_SUPPORT + bool "TEE HUKS demo support" + default n + select FILE_SYSTEM_SUPPORT + select TEE_HUKS_SUPPORT + help + Support TEE HUKS DEMO interface. + config FLASH_ENCRYPT_SUPPORT + bool "FLASH ENCRYPT support(only apply in WIFI CHIP_PKT_32K)" + default n + help + Support encrypt code and data. + endmenu + + menu "Factory Test Settings" + config FACTORY_TEST_SUPPORT + bool "factory test enable" + default n + help + enable factory test in flashboot. + endmenu + + menu "BSP Settings" + config I2C_SUPPORT + bool "i2c driver support" + default n + help + i2c driver support. + + config I2S_SUPPORT + bool "i2s driver support" + default n + help + i2s driver support. + + config SPI_SUPPORT + bool "SPI driver support" + default n + help + spi driver support. + + config DMA_SUPPORT + bool "DMA driver support" + default n + help + dma driver support. + + config SDIO_SUPPORT + bool "SDIO driver support" + default n + help + sdio driver support. + + config SPI_DMA_SUPPORT + bool "SPI support DMA" + default n + help + spi driver support DMA transfer. + + config UART_DMA_SUPPORT + bool "UART support DMA" + default n + help + uart driver support DMA transfer. + + config PWM_SUPPORT + bool "PWM driver support" + default n + help + pwm driver support. + + config PWM_HOLD_AFTER_REBOOT + bool "PWM hold after reboot" + default n + help + pwm hold after reboot. + + config AT_SUPPORT + bool "Enable AT command" + default y + help + enable at command. + config FILE_SYSTEM_SUPPORT + bool "Enable file system" + default n + help + enable file system. + config UART0_SUPPORT + bool "Enable uart0 IO mux config" + default y + help + Enable uart0 IO mux config. + config UART1_SUPPORT + bool "Enable uart1 IO mux config" + default y + help + Enable uart1 IO mux config. + config UART2_SUPPORT + bool "Enable uart2 IO mux config" + default n + help + Enable uart2 IO mux config. + endmenu + + menu "WiFi Settings" + choice + prompt "Authentication Option of Radio Parameters" + default CE_SUPPORT + + config CE_SUPPORT + bool "CE Authentication" + + config FCC_SUPPORT + bool "FCC Authentication" + + config MAX_POWER_SUPPORT + bool "Max Power" + endchoice + endmenu + + menu "OTA Settings" + choice + prompt "OTA upgrade method" + default COMPRESSION_OTA_SUPPORT + config COMPRESSION_OTA_SUPPORT + bool "compression ota support" + help + compression ota upgrade method. + + config DUAL_PARTITION_OTA_SUPPORT + bool "dual-partition ota support" + help + dual-patition upgrade method. + endchoice + endmenu + + menu "Link Settings" + config HILINK + bool "HiLink support" + default n + help + Enable the option to compile hilink module. + endmenu + diff --git a/sdk_liteos/tools/menuconfig/usr_config.mk b/sdk_liteos/tools/menuconfig/usr_config.mk new file mode 100644 index 0000000000000000000000000000000000000000..85bce720fe7338dafa7075eea48a96635053de86 --- /dev/null +++ b/sdk_liteos/tools/menuconfig/usr_config.mk @@ -0,0 +1,100 @@ +# Generated by Kconfiglib (https://github.com/ulfalizer/Kconfiglib) + +# +# Target Chip +# +CONFIG_TARGET_CHIP_HI3861=y +# CONFIG_TARGET_CHIP_HI3861L is not set +# end of Target Chip + +# +# Security Settings +# +# CONFIG_TARGET_SIG_RSA_V15 is not set +# CONFIG_TARGET_SIG_RSA_PSS is not set +# CONFIG_TARGET_SIG_ECC is not set +CONFIG_TARGET_SIG_SHA256=y +# CONFIG_BOOT_ENCRYPT is not set +CONFIG_TARGET_KERNEL_VER=0 +CONFIG_TARGET_BOOT_VER=0 +# CONFIG_TEE_HUKS_SUPPORT is not set +# CONFIG_TEE_HUKS_DEMO_SUPPORT is not set +# CONFIG_FLASH_ENCRYPT_SUPPORT is not set +# end of Security Settings + +# +# Factory Test Settings +# +# CONFIG_FACTORY_TEST_SUPPORT is not set +# end of Factory Test Settings + +# +# BSP Settings +# +# CONFIG_I2C_SUPPORT is not set +# CONFIG_I2S_SUPPORT is not set +# CONFIG_SPI_SUPPORT is not set +# CONFIG_DMA_SUPPORT is not set +# CONFIG_SDIO_SUPPORT is not set +# CONFIG_SPI_DMA_SUPPORT is not set +# CONFIG_UART_DMA_SUPPORT is not set +# CONFIG_PWM_SUPPORT is not set +# CONFIG_PWM_HOLD_AFTER_REBOOT is not set +CONFIG_I2C_SUPPORT=y +CONFIG_PWM_SUPPORT=y +CONFIG_SPI_SUPPORT=y +CONFIG_AT_SUPPORT=y +# CONFIG_FILE_SYSTEM_SUPPORT is not set +CONFIG_UART0_SUPPORT=y +CONFIG_UART1_SUPPORT=y +# CONFIG_UART2_SUPPORT is not set +# end of BSP Settings + +# +# WiFi Settings +# +# CONFIG_WPS_SUPPORT is not set +CONFIG_CE_SUPPORT=y +# CONFIG_FCC_SUPPORT is not set +# CONFIG_MAX_POWER_SUPPORT is not set +# CONFIG_MESH_SUPPORT is not set +# CONFIG_QUICK_SEND is not set +# end of WiFi Settings + +# +# Third Party library +# +# CONFIG_CJSON is not set +# CONFIG_CJSON_NESTING_LIMIT=1000 +# CONFIG_LIBCOAP is not set +# CONFIG_MQTT is not set +CONFIG_IPERF=y +# end of Third Party library + +# +# Lwip Settings +# +CONFIG_DHCPS_GW=y +# CONFIG_NETIF_HOSTNAME is not set +# CONFIG_DHCP_VENDOR_CLASS_IDENTIFIER is not set +# CONFIG_LWIP_LOWPOWER is not set +# end of Lwip Settings + +# +# OTA Settings +# +CONFIG_COMPRESSION_OTA_SUPPORT=y +# CONFIG_DUAL_PARTITION_OTA_SUPPORT is not set +# end of OTA Settings + +# +# Link Settings +# +# CONFIG_HILINK is not set +# end of Link Settings + +# +# Debug Log Settings +# +# CONFIG_DIAG_SUPPORT is not set +# end of Debug Log Settings diff --git a/sdk_liteos/tools/menuconfig/usr_config.py b/sdk_liteos/tools/menuconfig/usr_config.py new file mode 100644 index 0000000000000000000000000000000000000000..416ad70f817335cac75518eb60c819d07a4c1ce4 --- /dev/null +++ b/sdk_liteos/tools/menuconfig/usr_config.py @@ -0,0 +1,43 @@ +#!/usr/bin/env python3 +#coding=utf-8 + +''' +* Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +* Description: Menuconfig entry +''' + +import os +from kconfiglib import Kconfig +from menuconfig import menuconfig + +def mconf_set_env(style, conf, header): + """ + These parameters would not be effect unless kconflib supported these. + """ + os.environ["MENUCONFIG_STYLE"] = style + os.environ["KCONFIG_CONFIG"] = conf + os.environ["KCONFIG_CONFIG_HEADER"] = header + +def hi_mconfig(): + kconfig = os.path.join("tools", "menuconfig", "Kconfig") + display_style = "default selection=fg:white,bg:red" + target_conf = os.path.join("build", "config", "usr_config.mk") + header = "# Generated by HiSilicon menuconfig tool" + mconf_set_env(display_style, target_conf, header) + kconf = Kconfig(filename=kconfig) + menuconfig(kconf) + +if __name__ == "__main__": + hi_mconfig() diff --git a/sdk_liteos/tools/nvtool/build_nv.py b/sdk_liteos/tools/nvtool/build_nv.py new file mode 100755 index 0000000000000000000000000000000000000000..849023517b3e99408c74215a8162a00c99499df4 --- /dev/null +++ b/sdk_liteos/tools/nvtool/build_nv.py @@ -0,0 +1,678 @@ +#!/usr/bin/env python3 +# coding=utf-8 + +''' +* Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +* Description: nv build scripts. +''' + +import os +import sys +import re +import subprocess +import configparser +import shutil +import sys +import xml.etree.ElementTree as ET +import copy +from ctypes import * +import time +import hashlib +import binascii +import datetime +from zlib import crc32 +import struct +sys.path.append("'..', '..', 'build'") +#from scripts.analyze_dependence import user_pannel_config + +#-----------------------------------基本错误定义----------------------------------- +HI_ERR_SUCCESS = 0 +#-----------------------------------基本类型定义----------------------------------- +HI_CHAR = c_char +HI_S8 = c_byte +HI_U8 = c_ubyte +HI_S16 = c_short +HI_U16 = c_ushort +HI_S32 = c_int +HI_U32 = c_uint +#-----------------------------------NV结构体定义----------------------------------- +class NV_FILE_STRU(Structure): + _fields_ = [ + ("magic", HI_U32), + ("crc", HI_U32), + ("ver", HI_U8), + ("head_len", HI_U8), + ("total_num", HI_U16), + ("seq", HI_U32), + ("ver_magic", HI_U32), + ("flash_size", HI_U32), + ("keep_id_range", HI_U8*2), + ("reserve", HI_U8*2), + ("nv_item_index", HI_U8*0), + ] + +class NV_ITEM_INDEX_STRU(Structure): + _fields_ = [ + ("nv_id", HI_U8), + ("nv_len", HI_U8), + ("nv_offset", HI_U16), + ] +NV_ITEM_INDEX_LEN = 4 +NV_ITEM_CRC_LEN = 4 + +HNV_MAGIC = 0x24564E48 +FNV_MAGIC = 0x23564E46 + +#SEC_CONN_SALT = '"sec conn salt"' +#SEC_NV_ID = 0x8c + +###############################NV 分区头格式 ############################################### +#Hi3921不再在NV中体现Factory/Modem/APP等不同分区头 + +###############################NV项头信息############################################### +#Hi3921各个NV项(条目)没有头信息. + +#-----------------------------------生成HNV文件流程----------------------------------- +def nv_process_mk_section(element_root, src_bin_dic, is_factory): + nv_id_list = [] + nv_keep_id_list = [] + nv_item_bin_list = [] + nv_item_index_bin_list = [] + nv_total_size = 0 + nv_offset = 0 + nv_len = 0 + nv_total_num = 0 + + #1.遍历,取出工厂区或非工厂区的所有NV ID,并排序 + for element_grp in element_root: +# print("element_grp: ", element_grp) +# print("NAME: ", element_grp.attrib['NAME']) + if True == is_factory: + if element_grp.attrib['NAME'] == 'Factory': + for nv_element in element_grp: + nv_id_list.append(int(nv_element.attrib['ID'], 16)) + break; + else: + if element_grp.attrib['NAME'] != 'Factory': + for nv_element in element_grp: + nv_id_list.append(int(nv_element.attrib['ID'], 16)) + if element_grp.attrib['NAME'] == 'Keep': + nv_keep_id_list.append(int(nv_element.attrib['ID'], 16)) + + nv_id_list.sort() + nv_keep_id_list.sort() + nv_total_num = len(nv_id_list) + nv_offset = sizeof(NV_FILE_STRU)+nv_total_num*4#NV相对本区的偏移初始化在索引区之后 + + #print(nv_id_list) + + #2.按照ID顺序生成nv_item_bin(含nv_item头和nv_item内容),添加到nv_item_bin_list中 + for nv_id in nv_id_list: + #申请nv_item_bin空间并转换成nv_item_st + src_bin = src_bin_dic[hex(nv_id)] + nv_len = len(src_bin) + nv_item_bin = bytearray(nv_len+NV_ITEM_CRC_LEN)#申请空间 + + #填充nv_item_bin,并将nv_item_bin添加到nv_item_bin_list中 + nv_item_bin[0:] = src_bin#拷贝bin + nv_item_bin[nv_len:] = struct.pack(' g_nv_env.flash_size: + print("Error: NV is larger than flash_size:%d"%(g_nv_env.flash_size)) + exit(-1) + + #将nv_flash空闲区域置为F + for i in range(offset, g_nv_env.flash_size): + nv_file_Bin[i] = 0xFF + + #计算整区的crc32 + nv_file_st.crc = crc32(nv_file_Bin[8:g_nv_env.flash_size]) + + return (HI_ERR_SUCCESS, nv_file_Bin) + +class NvEnv: + def __init__(self): + self.app_name = []#app名称 + self.root_dir = []#编译根目录 + self.mdm_xml = []#mdm_xml全路径 + self.app_xml = []#app_xml全路径 + self.app_sdk_level = []#app sdk等级 + self.app_cfg_dir = []#客制化文件夹路径,带产品形态路径 + self.src_bin_dir = []#原bin路径,带产品形态路径 + + self.product_type = []#产品形态名称 + self.temp_dir = []#临时文件夹路径,带产品形态 + self.combin_xml = []#合并后xml全路径,带or不带产品形态 + self.nv_tool_dir = []# + self.nv_h_dir = []# + self.nv_bin_max_size = 0 + self.flash_size = 0 + self.ver_magic = 0 + +g_nv_env = NvEnv() + +def hi_str_to_int(line, num): + if num is not None: + return int(line, num) + match1 = re.match(r'\s*0x', line) + match2 = re.match(r'\s*0X', line) + if match1 or match2: + return int(line, 16) + else: + return int(line, 10) + +''' ''' +def hi_nv_set_cfg(root_dir, product_lib_out, xml_hfile_dir, product_name, app_name, hnv_dir, flash_size, ver_magic, hnv_file_name): + global g_nv_env + subver = g_subver_name + if subver =='common': + subver = app_name + + if hnv_dir is None:#hnv存放位置 + g_nv_env.hnv_dir=product_lib_out + else: + g_nv_env.hnv_dir=hnv_dir + + g_nv_env.nv_h_dir=xml_hfile_dir#存放结构体txt文件存放位置 + g_nv_env.app_name=app_name#app名称 + g_nv_env.product_type=product_name#产品形态名称 + g_nv_env.root_dir=root_dir#根目录 + g_nv_env.temp_dir=os.path.join(product_lib_out, app_name, '%s%s'%(g_common_ver, g_subver_name))#临时文件目录 + print('root_dir:', root_dir) + g_nv_env.mdm_xml=os.path.join(root_dir, 'xml_file', hnv_file_name) + print('mdm_xml:', g_nv_env.mdm_xml) + g_nv_env.app_xml=os.path.join(root_dir, 'xml_file', 'app_nvi_db.xml') + g_nv_env.app_cfg_dir=os.path.join(root_dir, 'xml_file')#区分不同产品形态 + print('HNV NAME:' + hnv_file_name) + g_nv_env.combin_xml=os.path.join(product_lib_out, app_name, hnv_file_name)#合并后combin.xml路径 + g_nv_env.combin_product_xml=os.path.join(g_nv_env.temp_dir, 'mss_nvi_db_%s.xml'%(g_nv_env.product_type))#合并分割后combin_coo.xml路径 + g_nv_env.combin_product_security_xml=os.path.join(g_nv_env.temp_dir, 'combin_%s_security.xml'%(g_nv_env.product_type))#合并分割后combin_coo.xml路径 + + g_nv_env.src_bin_dir=os.path.join(root_dir, 'app', g_nv_env.app_name, 'nv', 'src_bin', g_nv_env.product_type)#存放必源src bin文件路径 + g_nv_env.nv_tool=os.path.join(root_dir, 'tools', 'nv', 'cdbm')#nv工具路径 + print('nv_tool:', g_nv_env.nv_tool) + #g_nv_env.pwd_nv_tool=os.path.join(root_dir, 'tools', 'nv', 'pwd_nv_tool.exe')#pwd nv 制作工具路径 + g_nv_env.nv_bin_max_size=65536#暂定最大支持64K flash + + g_nv_env.flash_size=flash_size + g_nv_env.ver_magic=ver_magic + return 0 + +def hi_nv_fomat_nv_id(root): + ret = 0 + for grp in root: + for nv in grp: + if 'ID' in nv.attrib.keys(): + str_id=nv.attrib['ID'] + int_id=hi_str_to_int(str_id, None) + str_id=hex(int_id) + nv.attrib['ID']=str_id + return 0 + +""" +合并xml;nv id标准化;nv 按组号进行排序 +""" +def HI_NV_XmlCombineXml(src_xml_list, combin_xml): + root_list=[] + group_dics={} + exist_item_id_list=[] + global g_nv_env + + for src_xml in src_xml_list: + tree = ET.parse(src_xml) + root = tree.getroot() + hi_nv_fomat_nv_id(root)#标准化NVID + root_list.append(root) + + new_root=ET.Element('HISTUDIO') + print('root_list', root_list) + + #判断是否有重复的ID + for root in root_list: + grp_list=root.findall('GROUP')#找到所有的grp + for grp in grp_list: + item_list=grp.findall('NV') + for item in item_list: + str_id=item.attrib['ID'] + int_id=hi_str_to_int(str_id, None) + if int_id in exist_item_id_list: + print(exist_item_id_list) + return -1 + exist_item_id_list.append(int_id) + + #合并xml + for root in root_list: + grp_list=root.findall('GROUP')#找到所有的grp + for grp in grp_list: + grp_name=grp.attrib['NAME'] + if not grp_name in group_dics.keys(): + new_root.append(grp) + group_dics[grp_name]=grp + else: + old_grp=group_dics[grp_name] + sub_elements=grp.findall('NV') + old_grp.extend(sub_elements) + + #对新xml进行排序 + element_grp_list=[] + for element_grp in new_root: + element_grp_list.append(element_grp) + + element_grp_list.sort(key=lambda x:int(x.attrib['ID'], 16)) + i=0 + while i< len(element_grp_list): + new_root[i]=element_grp_list[i] + i=i+1 + + #回写xml + new_tree=ET.ElementTree(new_root) + new_tree.write(combin_xml, encoding="utf-8") + +def hi_nv_mk_temp_dir(temp_dir, hnv_dir): + global g_nv_env + if os.path.exists(temp_dir): + shutil.rmtree(temp_dir) + os.makedirs(temp_dir) + else: + os.makedirs(temp_dir) + + if hnv_dir is None: + pass + elif not os.path.exists(hnv_dir): + os.makedirs(hnv_dir) + else: + pass + +""" +合并mss和app xml +""" +def hi_nv_combine_mss_and_app_xml(): + global g_nv_env + src_xml_list=[] + src_xml_list.append(g_nv_env.mdm_xml) + print('mdmxml:'+g_nv_env.mdm_xml) + if os.path.exists(g_nv_env.app_xml): + src_xml_list.append(g_nv_env.app_xml) + print('appxml:'+g_nv_env.app_xml) + print('src_xml_list:', src_xml_list) + print('combin_xml:%s'%g_nv_env.combin_xml) + HI_NV_XmlCombineXml(src_xml_list, g_nv_env.combin_xml) + +def HI_NV_XmlSplitByProductType(src_xml, product_list, dst_xml_list): + new_root_list=[] + tree = ET.parse(src_xml) + root = tree.getroot() + i=0 + #print('src_xml', src_xml) + #print('product_list', product_list) + #print('dst_xml_list', dst_xml_list) + while i= g_nv_env.nv_bin_max_size:#检测NV文件大小,边界也有问题 + print(factory_hnv, "error nv size large than nv_bin_max_size(%u)"%(g_nv_env.nv_bin_max_size)) + exit(-1) + if ret == HI_ERR_SUCCESS: + with open(factory_hnv, 'wb+') as hnvfp: + hnvfp.write(bytearray_hnv) + g_target_hnv.append(factory_hnv) + + #生成非工厂区NV文件_normal.hnv + (ret, bytearray_hnv) = hi_nv_process_mk_hnv(root, src_bin_dic, os.path.basename(dst_hnv), False) + normal_hnv = dst_hnv.replace('.hnv', '_normal.hnv') + if len(bytearray_hnv) >= g_nv_env.nv_bin_max_size:#检测NV文件大小,边界也有问题 + print(normal_hnv, "error nv size large than nv_bin_max_size(%u)"%(g_nv_env.nv_bin_max_size)) + exit(-1) + if ret == HI_ERR_SUCCESS: + with open(normal_hnv, 'wb+') as hnvfp: + hnvfp.write(bytearray_hnv) + g_target_hnv.append(normal_hnv) + +#def generate_pwd_nv(nv_bin_dir): + #cmd_line = (os.path.join(nv_bin_dir, ''.join([hex(SEC_NV_ID),'.bin']))) + #print('conn pwd: ', g_diag_auth_pwd) + #ret = os.system(cmd_line) + #ret = subprocess.run(cmd_line).returncode + #if ret!=0: + # print('error:', cmd_line) + # sys.exit(ret) + +def check_hnv_result(file_name): + if os.path.exists(file_name.replace('.hnv', '_factory.hnv')): + if os.path.exists(file_name.replace('.hnv', '_normal.hnv')): + return 0 + return -1 + +def hi_nv_modify_by_cfg(): + print('hi_nv_modify_by_cfg') + global g_nv_env + if os.path.exists(g_nv_env.app_cfg_dir): + cfg_file_list = os.listdir(g_nv_env.app_cfg_dir) + else: + return 0 + for cfg_file in cfg_file_list: + if cfg_file.endswith(".cfg"): + cfg_file = cfg_file[:-len('.cfg')] + print('cfg_file:', cfg_file) + cfg_file_full_name = os.path.join(g_nv_env.app_cfg_dir, '%s.cfg'%cfg_file) + cfg_xml_full_name = os.path.join(g_nv_env.temp_dir, '%s.xml'%cfg_file) + cfg_hnv_full_name = os.path.join(g_nv_env.hnv_dir, '%s.hnv'%g_nv_env.app_name) + cfg_bin_dir = os.path.join(g_nv_env.temp_dir, cfg_file) + if os.path.exists(cfg_bin_dir): + shutil.rmtree(cfg_bin_dir) + os.makedirs(cfg_bin_dir) + else: + os.makedirs(cfg_bin_dir) + + HI_NV_XmlModifyByCfg(cfg_file_full_name, g_nv_env.combin_product_xml, cfg_xml_full_name) + + HI_NV_Xml2Bin(g_nv_env.nv_tool, cfg_xml_full_name, cfg_bin_dir, g_nv_env.nv_h_dir) + #替换0x90安全连接NV + #generate_pwd_nv(cfg_bin_dir) + #将xml和bin文件合成hnv文件 + HI_NV_HNV_Build(cfg_xml_full_name, cfg_hnv_full_name, cfg_bin_dir) + ret = check_hnv_result(cfg_hnv_full_name) + if ret!=0: + print('Build hnv ERROR:%s'%cfg_hnv_full_name) + sys.exit(ret) + print('build hnv OK:%s'%cfg_hnv_full_name) + print('ENDING') + +g_common_ver = 'bbit_' +g_subver_name = 'common' +def hi_nv_mk_app_subtemp_dir(product_lib_out, app_name): + app_subver_temp_dir = os.path.join(product_lib_out, app_name, '%s%s'%(g_common_ver, g_subver_name)) + print('app_subver_temp_dir:%s'%app_subver_temp_dir) + + if os.path.exists(product_lib_out): + if os.path.exists(app_subver_temp_dir): + shutil.rmtree(app_subver_temp_dir) + else: + os.makedirs(app_subver_temp_dir) + print('make app_subver_temp_dir') + +def hi_app_subver_list_filter(app_name, subver_list): + app_subver_list = [] + for sub_name in subver_list: + if sub_name == app_name: + app_subver_list.append('common') + else: + app_subver_list.append(sub_name) + return app_subver_list + +g_root_dir = os.path.abspath(os.path.dirname(__file__)) +g_out_dir = os.path.join(g_root_dir, 'out_nv_bin')#sys.argv[2] #nv编译结果根目录,v1r1/build_tmp/HiMDL_release(该名称可变) +g_flash_size = 4096#int(sys.argv[3]) +#g_diag_auth_pwd = 'cih518@AMR'#(sys.argv[4]) +g_ver_magic = 0#ver_magic在制作hupg的时候会重新写入,此处默认0即可,可用于单独升级NV场景下(正常无此场景),固定赋值。 +#g_user_pannel_config = user_pannel_config() +#g_project_name = g_user_pannel_config.get_project_name() +g_project_name = 'himdl' +g_target_hnv = [] + +def HI_NV_MakeMain(root_dir, product_lib_out, xml_hfile_dir, product_name, app_name, app_subver_list, hnv_dir, + flash_size, ver_magic, hnv_file_name): + global g_common_ver + global g_subver_name + #common_ver_list = ['bbit_', 'outside_'] + common_ver_list = ['outside_'] + if app_subver_list == []: + print(app_name.upper(), 'selected 0 nv config!!!please select at least one!!!') + sys.exit(1) + for common_ver in common_ver_list: + g_common_ver = common_ver + for subver_name in app_subver_list: + print('current subver_name:%s'%subver_name) + g_subver_name = subver_name + ret = hi_nv_set_cfg(root_dir, product_lib_out, xml_hfile_dir, product_name, app_name, hnv_dir, flash_size, + ver_magic, hnv_file_name) + if ret != 0: + continue + hi_nv_mk_app_subtemp_dir(product_lib_out, app_name) + hi_nv_combine_mss_and_app_xml() + hi_nv_split_by_product_type() + hi_nv_modify_by_cfg() + +def make_nv_bin(target_path = '.', target_name = 'hi3861', hnv_file_name = ''): + product_name_list = ['sta'] + ''' analyse begin ''' + app_name_list = [target_name] + print('product_name_list:', product_name_list) + for product_name in product_name_list: + product_out_dir = os.path.join(g_out_dir, product_name) + product_lib_out = os.path.join(product_out_dir, 'nv') + xml_hfile_dir = os.path.join(g_root_dir, 'h_file', 'nv') + print('xml h file:', xml_hfile_dir) + hnv_dir = os.path.join(product_out_dir, 'nv', 'hnv') + hi_nv_mk_temp_dir(product_lib_out, hnv_dir) + print(product_out_dir) + for app_name in app_name_list: + nv_total_list = ['demo'] + app_subver_list = hi_app_subver_list_filter(app_name, nv_total_list) + print('app_subver_list:', app_subver_list) + HI_NV_MakeMain(g_root_dir, product_lib_out, xml_hfile_dir, product_name, app_name, app_subver_list, hnv_dir, + g_flash_size, g_ver_magic, hnv_file_name) + + if len(g_target_hnv) > 0: + for hnv in g_target_hnv: + shutil.copy(hnv, target_path) + +if __name__ == '__main__': + if len(sys.argv) == 4: + make_nv_bin(sys.argv[1], sys.argv[2], sys.argv[3]) + else: + filename = sys.argv[1] + target_name = sys.argv[2] + default_target_path = os.path.join(g_root_dir, '..', '..', 'build', 'build_tmp', 'nv') + if os.path.exists(default_target_path) is False: + os.makedirs(default_target_path) + make_nv_bin(default_target_path, target_name, filename) + diff --git a/sdk_liteos/tools/nvtool/h_file/nv/base_datatype_def.txt b/sdk_liteos/tools/nvtool/h_file/nv/base_datatype_def.txt new file mode 100644 index 0000000000000000000000000000000000000000..58b8f1eb9c9f8a407523ce546fca0fcb578c9b98 --- /dev/null +++ b/sdk_liteos/tools/nvtool/h_file/nv/base_datatype_def.txt @@ -0,0 +1,38 @@ +UINT32 32 0 +UINT16 16 0 +UINT8 8 0 + +INT32 32 1 +INT16 16 1 +INT8 8 1 + +enum 32 0 +HSO_ENUM 32 0 + +u32 32 0 +u16 16 0 +u8 8 0 + +s32 32 1 +s16 16 1 +s8 8 1 +BOOL 8 0 + +HI_U8A 8 0 +HI_U16A 16 0 +HI_CHARTA 8 1 1 + +hi_u32 32 0 +hi_u16 16 0 +hi_u8 8 0 +hi_s32 32 1 +hi_s16 16 1 +hi_s8 8 1 +hi_bool 8 0 +hi_char 8 1 1 +char 8 1 1 + +long 32 1 +hi_pvoid 32 0 +hi_pbyte 32 0 + diff --git a/sdk_liteos/tools/nvtool/h_file/nv/nv_app_struct_def.txt b/sdk_liteos/tools/nvtool/h_file/nv/nv_app_struct_def.txt new file mode 100644 index 0000000000000000000000000000000000000000..967f83a368f4053b793fb5047dd1de18f3667d08 --- /dev/null +++ b/sdk_liteos/tools/nvtool/h_file/nv/nv_app_struct_def.txt @@ -0,0 +1 @@ +#include "base_datatype_def.txt" diff --git a/sdk_liteos/tools/nvtool/h_file/nv/nv_factory_struct_def.txt b/sdk_liteos/tools/nvtool/h_file/nv/nv_factory_struct_def.txt new file mode 100644 index 0000000000000000000000000000000000000000..8aa6b71b727dbdef4919cab847ccbce1d25019f4 --- /dev/null +++ b/sdk_liteos/tools/nvtool/h_file/nv/nv_factory_struct_def.txt @@ -0,0 +1,58 @@ +#include "base_datatype_def.txt" + +typedef struct { + hi_s32 init_cfg_rf_high_temp_threshold; + hi_s32 init_cfg_rf_low_temp_threshold; + hi_s32 init_cfg_rf_ppm_compesation; +} rf_cfg_xtal_compesation; + +typedef struct { + hi_u32 addr:24; + hi_u32 id:7; + hi_u32 dir:1; + hi_u32 size:24; + hi_u32 reserve:8; + hi_u32 addition; +} hi_flash_partition_info; +typedef struct { + hi_flash_partition_info table[12]; +} hi_flash_partition_table; + +typedef struct { + hi_u32 addr_start; + hi_u16 mode; + hi_u8 file_type; + hi_u8 refresh_nv; + hi_u8 reset_cnt; + hi_u8 cnt_max; + hi_u16 reserved1; + hi_u32 addr_write; + hi_u32 reserved2; +} hi_nv_ftm_startup_cfg; + +typedef struct { + hi_u8 root_salt[32]; + hi_u8 iv_nv[16]; + hi_u8 iv_content[16]; + hi_u8 work_text[32]; + hi_u8 content_sh256[32]; +} hi_flash_crypto_content; + +typedef struct { + hi_u32 flash_crypt_cnt; +} hi_flash_crypto_cnt; + +typedef struct { + hi_u32 factory_mode; + hi_u32 factory_addr_start; + hi_u32 factory_size; + hi_u32 factory_valid; +}hi_nv_ftm_factory_mode; + +typedef struct { + hi_u32 file_addr; + hi_u8 file_type; + hi_u8 boot_version; + hi_u8 is_upg_process; + hi_u8 trans_finish_flag; +} hi_nv_ftm_upg_wait_mode; \ No newline at end of file diff --git a/sdk_liteos/tools/nvtool/h_file/nv/nv_modem_struct_def.txt b/sdk_liteos/tools/nvtool/h_file/nv/nv_modem_struct_def.txt new file mode 100644 index 0000000000000000000000000000000000000000..7762d90bc36fb771f18ce524eae07080cc7bda7a --- /dev/null +++ b/sdk_liteos/tools/nvtool/h_file/nv/nv_modem_struct_def.txt @@ -0,0 +1,221 @@ +#include "base_datatype_def.txt" + +typedef struct +{ + hi_u32 init_cfg_country_code; + hi_u32 init_cfg_ampdu_tx_max_num; + hi_u32 init_cfg_rx_ack_limit; + hi_u32 init_cfg_int_unit_ctrl; + hi_u32 init_cfg_powermgmt_switch; + hi_u32 init_cfg_sta_dtim_setting; + hi_u32 init_cfg_loglevel; + hi_u32 init_cfg_phy_scaling_value_11b; + hi_u32 init_cfg_phy_u1_scaling_value_11g; + hi_u32 init_cfg_phy_u2_scaling_value_11g; + hi_u32 init_cfg_phy_u1_scaling_value_11n_2d4g; + hi_u32 init_cfg_phy_u2_scaling_value_11n_2d4g; + hi_u32 init_cfg_phy_u1_scaling_value_11n40m_2d4g; + hi_u32 init_cfg_phy_u2_scaling_value_11n40m_2d4g; + hi_u32 init_cfg_phy_u0_scaling_value_11n_5g; + hi_u32 init_cfg_phy_u3_scaling_value_11n40m_5g; + hi_u32 init_cfg_rts_clk_freq; + hi_u32 init_cfg_clk_type; + hi_s32 init_cfg_rf_line_txrx_gain_db_2g_band1; + hi_s32 init_cfg_rf_line_txrx_gain_db_2g_band2; + hi_s32 init_cfg_rf_line_txrx_gain_db_2g_band3; + hi_u32 init_cfg_rf_txpwr_cali_ref_2g_val_band1; + hi_u32 init_cfg_rf_txpwr_cali_ref_2g_val_band2; + hi_u32 init_cfg_rf_txpwr_cali_ref_2g_val_band3; + hi_u32 init_cfg_tx_ratio_level_0; + hi_u32 init_cfg_tx_pwr_comp_val_level_0; + hi_u32 init_cfg_tx_ratio_level_1; + hi_u32 init_cfg_tx_pwr_comp_val_level_1; + hi_u32 init_cfg_tx_ratio_level_2; + hi_u32 init_cfg_tx_pwr_comp_val_level_2; + hi_u32 init_cfg_more_pwr; + hi_u32 init_cfg_random_mac_addr_scan; + hi_u32 init_cfg_band_edge_limit_2g_11g_txpwr; + hi_u32 init_cfg_band_edge_limit_2g_11n_ht20_txpwr; + hi_u32 init_cfg_band_edge_limit_2g_11n_ht40_txpwr; + hi_u32 init_cfg_band_edge_limit_2g_11g_dbb_scaling; + hi_u32 init_cfg_band_edge_limit_2g_11n_ht20_dbb_scaling; + hi_u32 init_cfg_band_edge_limit_2g_11n_ht40_dbb_scaling; + hi_u32 init_cfg_cali_tone_amp_grade; +}wal_cfg_params; + + +typedef struct +{ + hi_u32 init_cfg_dyn_cali_dscr_interval; + + hi_u32 init_cfg_nvram_pa2gccka0; + hi_u32 init_cfg_nvram_pa2ga0; + hi_u32 init_cfg_nvram_pa2gcwa0; + + hi_u32 init_cfg_dpn24g_ch1_core0; + hi_u32 init_cfg_dpn24g_ch2_core0; + hi_u32 init_cfg_dpn24g_ch3_core0; + hi_u32 init_cfg_dpn24g_ch4_core0; + hi_u32 init_cfg_dpn24g_ch5_core0; + hi_u32 init_cfg_dpn24g_ch6_core0; + hi_u32 init_cfg_dpn24g_ch7_core0; + hi_u32 init_cfg_dpn24g_ch8_core0; + hi_u32 init_cfg_dpn24g_ch9_core0; + hi_u32 init_cfg_dpn24g_ch10_core0; + hi_u32 init_cfg_dpn24g_ch11_core0; + hi_u32 init_cfg_dpn24g_ch12_core0; + hi_u32 init_cfg_dpn24g_ch13_core0; + + hi_u32 init_cfg_dsss2ofdm_dbb_pwr_bo_val; + + hi_u32 init_cfg_cali_data_mask; + hi_u32 init_cfg_cali_mask; +}wal_cfg_calibration; + +typedef struct +{ + hi_u32 init_cfg_rf_rx_insertion_loss_2g_b1; + hi_u32 init_cfg_rf_rx_insertion_loss_2g_b2; + hi_u32 init_cfg_rf_rx_insertion_loss_2g_b3; + hi_u32 init_cfg_rf_line_rf_pwr_ref_rssi_db_2g_c0_mult4; +}wal_cfg_rf_rx_insertion; + +typedef struct +{ + hi_u32 init_cfg_sar_txpwr_ctrl_2g; +}wal_cfg_sar_txpwr; + +typedef struct { + hi_u32 init_cfg_nvram_max_txpwr_base_2p4g; + + hi_u32 init_cfg_nvram_params0; + hi_u32 init_cfg_nvram_params1; + hi_u32 init_cfg_nvram_params2; + hi_u32 init_cfg_nvram_params3; +}wal_cfg_base_delta_power; + +typedef struct +{ + hi_u32 init_cfg_side_band_txpwr_limit_24g_ch1; + hi_u32 init_cfg_side_band_txpwr_limit_24g_ch2; + hi_u32 init_cfg_side_band_txpwr_limit_24g_ch3; + hi_u32 init_cfg_side_band_txpwr_limit_24g_ch4; + hi_u32 init_cfg_side_band_txpwr_limit_24g_ch5; + hi_u32 init_cfg_side_band_txpwr_limit_24g_ch6; + hi_u32 init_cfg_side_band_txpwr_limit_24g_ch7; + hi_u32 init_cfg_side_band_txpwr_limit_24g_ch8; + hi_u32 init_cfg_side_band_txpwr_limit_24g_ch9; + hi_u32 init_cfg_side_band_txpwr_limit_24g_ch10; + hi_u32 init_cfg_side_band_txpwr_limit_24g_ch11; + hi_u32 init_cfg_side_band_txpwr_limit_24g_ch12; + hi_u32 init_cfg_side_band_txpwr_limit_24g_ch13; +}wal_cfg_band_txpwr; + +typedef struct +{ + hi_u32 init_cfg_rf_pa_vdd_reg_100_mode_1and2; + hi_u32 init_cfg_rf_pa_vdd_reg_101_mode_1and2; + hi_u32 init_cfg_rf_pa_vdd_reg_102_mode_1and2; + hi_u32 init_cfg_rf_pa_vdd_reg_103_mode_1and2; + hi_u32 init_cfg_rf_pa_vdd_reg_104_mode_1and2; + hi_u32 init_cfg_rf_pa_vdd_reg_105_mode_1and2; + hi_u32 init_cfg_rf_pa_vdd_reg_106_mode_1and2; + hi_u32 init_cfg_rf_pa_vdd_reg_107_mode_1and2; + hi_u32 init_cfg_rf_pa_vdd_reg_108_mode_1and2; + hi_u32 init_cfg_rf_pa_vdd_reg_109_mode_1and2; + hi_u32 init_cfg_rf_pa_vdd_reg_110_mode_1and2; + hi_u32 init_cfg_rf_pa_vdd_reg_111_mode_1and2; + hi_u32 init_cfg_rf_pa_vdd_reg_112_mode_1and2; + hi_u32 init_cfg_rf_pa_vdd_reg_113_mode_1and2; + hi_u32 init_cfg_rf_pa_vdd_reg_114_mode_1and2; + hi_u32 init_cfg_rf_pa_vdd_reg_115_mode_1and2; + hi_u32 init_cfg_rf_pa_vdd_reg_100_mode_3and4; + hi_u32 init_cfg_rf_pa_vdd_reg_101_mode_3and4; + hi_u32 init_cfg_rf_pa_vdd_reg_102_mode_3and4; + hi_u32 init_cfg_rf_pa_vdd_reg_103_mode_3and4; + hi_u32 init_cfg_rf_pa_vdd_reg_104_mode_3and4; + hi_u32 init_cfg_rf_pa_vdd_reg_105_mode_3and4; + hi_u32 init_cfg_rf_pa_vdd_reg_106_mode_3and4; + hi_u32 init_cfg_rf_pa_vdd_reg_107_mode_3and4; + hi_u32 init_cfg_rf_pa_vdd_reg_108_mode_3and4; + hi_u32 init_cfg_rf_pa_vdd_reg_109_mode_3and4; + hi_u32 init_cfg_rf_pa_vdd_reg_110_mode_3and4; + hi_u32 init_cfg_rf_pa_vdd_reg_111_mode_3and4; + hi_u32 init_cfg_rf_pa_vdd_reg_112_mode_3and4; + hi_u32 init_cfg_rf_pa_vdd_reg_113_mode_3and4; + hi_u32 init_cfg_rf_pa_vdd_reg_114_mode_3and4; + hi_u32 init_cfg_rf_pa_vdd_reg_115_mode_3and4; +}wal_cfg_rf_reg1; + +typedef struct +{ + hi_u32 init_cfg_rf_pa_vdd_reg_100_mode_5and6; + hi_u32 init_cfg_rf_pa_vdd_reg_101_mode_5and6; + hi_u32 init_cfg_rf_pa_vdd_reg_102_mode_5and6; + hi_u32 init_cfg_rf_pa_vdd_reg_103_mode_5and6; + hi_u32 init_cfg_rf_pa_vdd_reg_104_mode_5and6; + hi_u32 init_cfg_rf_pa_vdd_reg_105_mode_5and6; + hi_u32 init_cfg_rf_pa_vdd_reg_106_mode_5and6; + hi_u32 init_cfg_rf_pa_vdd_reg_107_mode_5and6; + hi_u32 init_cfg_rf_pa_vdd_reg_108_mode_5and6; + hi_u32 init_cfg_rf_pa_vdd_reg_109_mode_5and6; + hi_u32 init_cfg_rf_pa_vdd_reg_110_mode_5and6; + hi_u32 init_cfg_rf_pa_vdd_reg_111_mode_5and6; + hi_u32 init_cfg_rf_pa_vdd_reg_112_mode_5and6; + hi_u32 init_cfg_rf_pa_vdd_reg_113_mode_5and6; + hi_u32 init_cfg_rf_pa_vdd_reg_114_mode_5and6; + hi_u32 init_cfg_rf_pa_vdd_reg_115_mode_5and6; + hi_u32 init_cfg_rf_pa_vdd_reg_100_mode_7and8; + hi_u32 init_cfg_rf_pa_vdd_reg_101_mode_7and8; + hi_u32 init_cfg_rf_pa_vdd_reg_102_mode_7and8; + hi_u32 init_cfg_rf_pa_vdd_reg_103_mode_7and8; + hi_u32 init_cfg_rf_pa_vdd_reg_104_mode_7and8; + hi_u32 init_cfg_rf_pa_vdd_reg_105_mode_7and8; + hi_u32 init_cfg_rf_pa_vdd_reg_106_mode_7and8; + hi_u32 init_cfg_rf_pa_vdd_reg_107_mode_7and8; + hi_u32 init_cfg_rf_pa_vdd_reg_108_mode_7and8; + hi_u32 init_cfg_rf_pa_vdd_reg_109_mode_7and8; + hi_u32 init_cfg_rf_pa_vdd_reg_110_mode_7and8; + hi_u32 init_cfg_rf_pa_vdd_reg_111_mode_7and8; + hi_u32 init_cfg_rf_pa_vdd_reg_112_mode_7and8; + hi_u32 init_cfg_rf_pa_vdd_reg_113_mode_7and8; + hi_u32 init_cfg_rf_pa_vdd_reg_114_mode_7and8; + hi_u32 init_cfg_rf_pa_vdd_reg_115_mode_7and8; +}wal_cfg_rf_reg2; + +typedef struct { + hi_u8 mac[6]; +} wal_cfg_mac_addr; + +typedef struct +{ + hi_u32 init_cfg_dpd_cali_ch_core0; + hi_u32 init_cfg_dpd_use_cail_ch_idx0_core0; + hi_u32 init_cfg_dpd_use_cail_ch_idx1_core0; + hi_u32 init_cfg_dpd_amp_t0_t3; + hi_u32 init_cfg_dpd_amp_t4_t7; + hi_u32 init_cfg_dpd_comp_tpc_temp; +}wal_cfg_dpd_calibration; + +typedef struct { + UINT8 ver; + UINT8 flag; + UINT8 dtsn; + UINT8 dodagVerNum; + UINT8 pathSeq; + UINT8 daoSeq; + UINT8 dcoSeq; + UINT8 pad; +} rplStore; + +typedef struct { + hi_u32 rst_times; + hi_u32 enable_save; +} hi_sys_reset_times; + +typedef struct { + hi_u8 uart_port_at; + hi_u8 uart_port_debug; + hi_u8 uart_port_sigma; + hi_u8 uart_port_reserved; +} hi_nv_uart_port_alloc; \ No newline at end of file diff --git a/sdk_liteos/tools/nvtool/nv_builder b/sdk_liteos/tools/nvtool/nv_builder new file mode 100755 index 0000000000000000000000000000000000000000..cebaf755a9853e9647a385caa199e33368692e3f Binary files /dev/null and b/sdk_liteos/tools/nvtool/nv_builder differ diff --git a/sdk_liteos/tools/nvtool/tools/nv/cdbm b/sdk_liteos/tools/nvtool/tools/nv/cdbm new file mode 100755 index 0000000000000000000000000000000000000000..a9f955b58c998452fb16bc99146f95d4a5d4bf91 Binary files /dev/null and b/sdk_liteos/tools/nvtool/tools/nv/cdbm differ diff --git a/sdk_liteos/tools/nvtool/xml_file/mss_nvi_db.xml b/sdk_liteos/tools/nvtool/xml_file/mss_nvi_db.xml new file mode 100755 index 0000000000000000000000000000000000000000..e5be69b563562592cc1b6919827320b2f75e3043 --- /dev/null +++ b/sdk_liteos/tools/nvtool/xml_file/mss_nvi_db.xml @@ -0,0 +1,44 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/sdk_liteos/tools/nvtool/xml_file/mss_nvi_db_fcc.xml b/sdk_liteos/tools/nvtool/xml_file/mss_nvi_db_fcc.xml new file mode 100755 index 0000000000000000000000000000000000000000..83539e652991fd3b341f48cefc022c76d9e0ec08 --- /dev/null +++ b/sdk_liteos/tools/nvtool/xml_file/mss_nvi_db_fcc.xml @@ -0,0 +1,44 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/sdk_liteos/tools/nvtool/xml_file/mss_nvi_db_max.xml b/sdk_liteos/tools/nvtool/xml_file/mss_nvi_db_max.xml new file mode 100755 index 0000000000000000000000000000000000000000..e3441dbcf3db6358ad0b5fb2787cb80ca0e68623 --- /dev/null +++ b/sdk_liteos/tools/nvtool/xml_file/mss_nvi_db_max.xml @@ -0,0 +1,44 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/sdk_liteos/tools/nvtool/xml_file/nv.cfg b/sdk_liteos/tools/nvtool/xml_file/nv.cfg new file mode 100755 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/sdk_liteos/tools/packet_tool/packet_tool.py b/sdk_liteos/tools/packet_tool/packet_tool.py new file mode 100644 index 0000000000000000000000000000000000000000..c188783c32cef2ae9bc5eed6b905472c7bd861cc --- /dev/null +++ b/sdk_liteos/tools/packet_tool/packet_tool.py @@ -0,0 +1,469 @@ +#!/usr/bin/env python3 +# coding=utf-8 + +''' +* Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +* Description: allinone.bin packet too scripts. +''' + +import struct +import sys +import os + +class crc16: + POLYNOMIAL = 0x1021 + PRESET = 0x0000 + _tab = [] + def __init__(self): + self._tab = [self._initial(i) for i in range(256)] + + def _initial(self, c): + crc = 0 + c = c << 8 + for j in range(8): + if (crc ^ c) & 0x8000: + crc = (crc << 1) ^ self.POLYNOMIAL + else: + crc = crc << 1 + c = c << 1 + return crc + + def _update_crc(self, crc, c): + cc = 0xff & int(c) + + tmp = (crc >> 8) ^ cc + crc = (crc << 8) ^ self._tab[tmp & 0xff] + crc = crc & 0xffff + + return crc + + def crc(self, str): + crc = self.PRESET + for c in str: + crc = self._update_crc(crc, ord(c)) + return crc + + def crcb(self, i): + crc = self.PRESET + for c in i: + crc = self._update_crc(crc, c) + return crc + +t = crc16() +def packet_bin(outputPath, inputList): + pathList = [] + burnAddrList = [] + burnSizeList = [] + imageSizeList = [] + typeList = [] + for item in inputList: + path, burnAddr, burnSize, type = item.split("|") + imageSize = os.path.getsize(path) + pathList.append(path) + burnAddrList.append(int(burnAddr)) + burnSizeList.append(int(burnSize)) + imageSizeList.append(imageSize) + typeList.append(int(type)) + + print(pathList) + print(burnAddrList) + print(burnSizeList) + print(imageSizeList) + print(typeList) + + flag = 0xefbeaddf + print(flag) + crc = 0 + imageNum = len(pathList) + #sizeof(IMAGE_INFO) is 52, sizeof(FWPKG_HEAD) is 12 + headLen = imageNum * 52 + 12 + #each image has 16byte 0 in the end + padLen = 16 * imageNum + totalFileSize = sum(imageSizeList) + headLen + padLen + with open(outputPath, 'wb+') as file: + file.write(struct.pack('IHHI', flag, crc, imageNum, totalFileSize)) + startIndex = headLen + times = 0 + for path in pathList: + pathName = os.path.basename(path) + file.write( + struct.pack('32sIIIII', bytes(pathName, 'ascii'), startIndex, imageSizeList[times], burnAddrList[times], + burnSizeList[times], typeList[times])) + #separate each image with 16 bytes 0 + startIndex = startIndex + imageSizeList[times] + 16 + times += 1 + + for path in pathList: + subfile = open(path, 'rb+') + data = subfile.read() + file.write(data) + file.write(struct.pack('IIII', 0, 0, 0, 0)) + + file.flush() + #crc range is FWPKG_HEAD.imageNum to end, begin index is 6bytes + file.seek(6) + newdata = file.read(headLen - 6) + crc16 = t.crcb(newdata) + file.seek(4) + file.write(struct.pack('H', crc16)) + file.close() +def update_bin(packet_path, inputList): + pathNameList = [] + burnAddrList = [] + burnSizeList = [] + imageSizeList = [] + typeList = [] + startIndexList = [] + fileInfoList = [] + + pathNameListNew = [] + burnAddrListNew = [] + burnSizeListNew = [] + imageSizeListNew = [] + typeListNew = [] + for item in inputList: + path, burnAddr, burnSize, type = item.split("|") + imageSize = os.path.getsize(path) + pathNameListNew.append(path) + burnAddrListNew.append(int(burnAddr)) + burnSizeListNew.append(int(burnSize)) + imageSizeListNew.append(imageSize) + typeListNew.append(int(type)) + + with open(packet_path, 'rb+') as file: + info = file.read(struct.calcsize('IHHI')) + flag, crc, imageNum, totalFileSize = struct.unpack('IHHI', info) + times = 0 + for index in range(0, imageNum): + info = file.read(struct.calcsize('32sIIIII')) + pathName, startIndex, imageSize, burnAddr, burnSize, type2 = struct.unpack('32sIIIII', info) + #separate each image with 16 bytes 0 + pathName = str(pathName, encoding="utf-8") + pathNameNew = '' + for char in pathName: + if char != '\x00': + pathNameNew += char + print(pathNameNew) + pathNameList.append(pathNameNew) + startIndexList.append(startIndex) + burnAddrList.append(burnAddr) + burnSizeList.append(burnSize) + imageSizeList.append(imageSize) + typeList.append(type2) + + for index in range(0, imageNum): + file.seek(startIndexList[index]) + fileInfoList.append(file.read(imageSizeList[index])) + + for index in range(0, len(pathNameListNew)): + pathNew = pathNameListNew[index] + print(os.path.basename(pathNew)) + pathIn32Byte = os.path.basename(pathNew) + if len(pathIn32Byte) > 32: + pathIn32Byte = pathIn32Byte[0:32] + if pathIn32Byte in pathNameList: + for index2 in range(0, imageNum): + path = pathNameList[index2] + if path == pathIn32Byte: + subfile = open(pathNew, 'rb+') + fileInfoList[index2] = subfile.read() + subfile.close() + pathNameList[index2] = os.path.basename(pathNew) + burnAddrList[index2] = burnAddrListNew[index] + burnSizeList[index2] = burnSizeListNew[index] + imageSizeList[index2] = imageSizeListNew[index] + typeList[index2] = typeListNew[index] + break + else: + pathNameList.append(pathNameListNew[index]) + burnAddrList.append(burnAddrListNew[index]) + burnSizeList.append(burnSizeListNew[index]) + imageSizeList.append(imageSizeListNew[index]) + typeList.append(typeListNew[index]) + subfile = open(pathNew, 'rb+') + fileInfoList.append(subfile.read()) + subfile.close() + file.close() + print(pathNameList) + print(burnAddrList) + print(burnSizeList) + print(imageSizeList) + print(typeList) + + flag = 0xefbeaddf + print(flag) + crc = 0 + imageNum = len(pathNameList) + #sizeof(IMAGE_INFO) is 52, sizeof(FWPKG_HEAD) is 12 + headLen = imageNum * 52 + 12 + #each image has 16byte 0 in the end + padLen = 16 * imageNum + totalFileSize = sum(imageSizeList) + headLen + padLen + with open(outputPath, 'wb+') as file: + file.write(struct.pack('IHHI', flag, crc, imageNum, totalFileSize)) + startIndex = headLen + times = 0 + for path in pathNameList: + pathName = os.path.basename(path) + file.write( + struct.pack('32sIIIII', bytes(pathName, 'ascii'), startIndex, imageSizeList[times], burnAddrList[times], + burnSizeList[times], typeList[times])) + #separate each image with 16 bytes 0 + startIndex = startIndex + imageSizeList[times] + 16 + times += 1 + + for info in fileInfoList: + file.write(info) + file.write(struct.pack('IIII', 0, 0, 0, 0)) + + file.flush() + #crc range is FWPKG_HEAD.imageNum to end, begin index is 6bytes + file.seek(6) + newdata = file.read(headLen - 6) + crc16 = t.crcb(newdata) + file.seek(4) + file.write(struct.pack('H', crc16)) + file.close() +def delete_bin(packet_path, name_list): + pathNameList = [] + burnAddrList = [] + burnSizeList = [] + imageSizeList = [] + typeList = [] + startIndexList = [] + fileInfoList = [] + + pathNameListNew = name_list + + with open(packet_path, 'rb+') as file: + info = file.read(struct.calcsize('IHHI')) + flag, crc, imageNum, totalFileSize = struct.unpack('IHHI', info) + times = 0 + for index in range(0, imageNum): + info = file.read(struct.calcsize('32sIIIII')) + pathName, startIndex, imageSize, burnAddr, burnSize, type2 = struct.unpack('32sIIIII', info) + #separate each image with 16 bytes 0 + pathName = str(pathName, encoding="utf-8") + pathNameNew = '' + for char in pathName: + if char != '\x00': + pathNameNew += char + print(pathNameNew) + pathNameList.append(pathNameNew) + startIndexList.append(startIndex) + burnAddrList.append(burnAddr) + burnSizeList.append(burnSize) + imageSizeList.append(imageSize) + typeList.append(type2) + + for index in range(0, imageNum): + file.seek(startIndexList[index]) + fileInfoList.append(file.read(imageSizeList[index])) + + for pathNew in pathNameListNew: + print(os.path.basename(pathNew)) + pathIn32Byte = os.path.basename(pathNew) + if len(pathIn32Byte) > 32: + pathIn32Byte = pathIn32Byte[0:32] + if pathIn32Byte in pathNameList: + for index2 in range(0, imageNum): + path = pathNameList[index2] + if path == pathIn32Byte: + del fileInfoList[index2] + del pathNameList[index2] + del burnAddrList[index2] + del burnSizeList[index2] + del imageSizeList[index2] + del typeList[index2] + break + file.close() + print(pathNameList) + print(burnAddrList) + print(burnSizeList) + print(imageSizeList) + print(typeList) + + flag = 0xefbeaddf + print(flag) + crc = 0 + imageNum = len(pathNameList) + #sizeof(IMAGE_INFO) is 52, sizeof(FWPKG_HEAD) is 12 + headLen = imageNum * 52 + 12 + #each image has 16byte 0 in the end + padLen = 16 * imageNum + totalFileSize = sum(imageSizeList) + headLen + padLen + with open(outputPath, 'wb+') as file: + file.write(struct.pack('IHHI', flag, crc, imageNum, totalFileSize)) + startIndex = headLen + times = 0 + for path in pathNameList: + pathName = os.path.basename(path) + file.write( + struct.pack('32sIIIII', bytes(pathName, 'ascii'), startIndex, imageSizeList[times], burnAddrList[times], + burnSizeList[times], typeList[times])) + #separate each image with 16 bytes 0 + startIndex = startIndex + imageSizeList[times] + 16 + times += 1 + + for info in fileInfoList: + file.write(info) + file.write(struct.pack('IIII', 0, 0, 0, 0)) + + file.flush() + #crc range is FWPKG_HEAD.imageNum to end, begin index is 6bytes + file.seek(6) + newdata = file.read(headLen - 6) + crc16 = t.crcb(newdata) + file.seek(4) + file.write(struct.pack('H', crc16)) + file.close() +def split_bin(packet_path, output_path): + pathNameList = [] + burnAddrList = [] + burnSizeList = [] + imageSizeList = [] + typeList = [] + startIndexList = [] + fileInfoList = [] + + pathNameListNew = [] + burnAddrListNew = [] + burnSizeListNew = [] + imageSizeListNew = [] + typeListNew = [] + with open(packet_path, 'rb+') as file: + info = file.read(struct.calcsize('IHHI')) + flag, crc, imageNum, totalFileSize = struct.unpack('IHHI', info) + times = 0 + for index in range(0, imageNum): + info = file.read(struct.calcsize('32sIIIII')) + pathName, startIndex, imageSize, burnAddr, burnSize, type2 = struct.unpack('32sIIIII', info) + #separate each image with 16 bytes 0 + pathName = str(pathName, encoding="utf-8") + pathNameNew = '' + for char in pathName: + if char != '\x00': + pathNameNew += char + print(pathNameNew) + pathNameList.append(pathNameNew) + startIndexList.append(startIndex) + burnAddrList.append(burnAddr) + burnSizeList.append(burnSize) + imageSizeList.append(imageSize) + typeList.append(type2) + + for index in range(0, imageNum): + file.seek(startIndexList[index]) + fileInfoList.append(file.read(imageSizeList[index])) + + file.close() + print(pathNameList) + print(burnAddrList) + print(burnSizeList) + print(imageSizeList) + print(typeList) + + imageNum = len(pathNameList) + for index in range(0, imageNum): + pathName = os.path.join(output_path, pathNameList[index]) + print(pathName) + with open(pathName, 'wb+') as file: + file.write(fileInfoList[index]) + file.close() +def show_bin(packet_path): + pathNameList = [] + burnAddrList = [] + burnSizeList = [] + imageSizeList = [] + typeList = [] + startIndexList = [] + fileInfoList = [] + + with open(packet_path, 'rb+') as file: + info = file.read(struct.calcsize('IHHI')) + flag, crc, imageNum, totalFileSize = struct.unpack('IHHI', info) + times = 0 + for index in range(0, imageNum): + info = file.read(struct.calcsize('32sIIIII')) + pathName, startIndex, imageSize, burnAddr, burnSize, type2 = struct.unpack('32sIIIII', info) + #separate each image with 16 bytes 0 + pathName = str(pathName, encoding="utf-8") + pathNameNew = '' + for char in pathName: + if char != '\x00': + pathNameNew += char + print(pathNameNew) + pathNameList.append(pathNameNew) + startIndexList.append(startIndex) + burnAddrList.append(burnAddr) + burnSizeList.append(burnSize) + imageSizeList.append(imageSize) + typeList.append(type2) + + for index in range(0, imageNum): + file.seek(startIndexList[index]) + fileInfoList.append(file.read(imageSizeList[index])) + + file.close() + print(pathNameList) + print(burnAddrList) + print(burnSizeList) + print(imageSizeList) + print(typeList) + +if __name__=="__main__": + args = len(sys.argv) + argv = sys.argv + if(args <= 1): + print("parma error, please use -help for usage") + sys.exit() + if (argv[1] == '-packet'): + outputPath = argv[2] + print(outputPath) + del argv[2] + del argv[1] + del argv[0] + packet_bin(outputPath, argv) + elif (argv[1] == '-update'): + outputPath = argv[2] + print(outputPath) + del argv[2] + del argv[1] + del argv[0] + update_bin(outputPath, argv) + elif (argv[1] == '-split'): + input_file = argv[2] + outputPath = argv[3] + split_bin(input_file, outputPath) + elif (argv[1] == '-show'): + input_file = argv[2] + show_bin(input_file) + elif (argv[1] == '-delete'): + outputPath = argv[2] + print(outputPath) + del argv[2] + del argv[1] + del argv[0] + delete_bin(outputPath, argv) + elif (argv[1] == '-help'): + print("\ + -packet,param should be : python packet_create.py -packet \"outputPath\" \"name|burnAddr|burnSize|type\"...\r\n\ + -split,param should be : python packet_create.py -split \"inputefile\" \"outputPath\"\r\n\ + -update,param should be : python packet_create.py -update \"outputPath\" \"name|burnAddr|burnSize|type\"...\r\n\ + -delete,param should be : python packet_create.py -delete \"inputefile\" \"name1\"...\r\n\ + -show\r\n\ + -help\r\n") + else: + print("parma error, please use -help for usage") diff --git a/sdk_liteos/tools/sign_tool/sign_tool b/sdk_liteos/tools/sign_tool/sign_tool new file mode 100755 index 0000000000000000000000000000000000000000..c1d506e9b5964c9328960476694ad2d5e2095cd2 Binary files /dev/null and b/sdk_liteos/tools/sign_tool/sign_tool differ