diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/.gitee/ISSUE_TEMPLATE.zh-CN.md b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/.gitee/ISSUE_TEMPLATE.zh-CN.md
new file mode 100644
index 00000000..651e02ce
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/.gitee/ISSUE_TEMPLATE.zh-CN.md
@@ -0,0 +1,11 @@
+### 该问题是怎么引起的?
+
+
+
+### 重现步骤
+
+
+
+### 报错信息
+
+
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md
new file mode 100644
index 00000000..2e36464c
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md
@@ -0,0 +1,21 @@
+### 相关的Issue
+
+
+### 原因(目的、解决的问题等)
+
+
+### 描述(做了什么,变更了什么)
+
+
+### 测试用例(新增、改动、可能影响的功能)
+
+
+### 是否需要同步至release(如:3.0LTS ... )分支?
+
+必须选择一项(在MarkDown模式下用[x]替换[ ]即可勾选对应选项):
+- [ ] 是,需要同步的分支:
+- [ ] 否
+
+理由:
+
+
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/.gitignore b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/.gitignore
new file mode 100644
index 00000000..c796d20f
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/.gitignore
@@ -0,0 +1,24 @@
+# General ignored file types
+*.o
+*.a
+*.so
+*.swp
+
+# IDE settings
+.vscode
+.idea
+.settings
+.cproject
+.project
+
+# VIM files
+cscope*
+tags
+
+# Menuconfig temp files
+/config.h
+/.config
+/.config.old
+
+# Build temp files
+/out
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/BUILD.gn b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/BUILD.gn
new file mode 100644
index 00000000..ed823066
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/BUILD.gn
@@ -0,0 +1,395 @@
+# 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")
+
+LITEOS_MENUCONFIG_H = rebase_path("$root_out_dir/config.h")
+
+declare_args() {
+ tee_enable = false
+ liteos_name = "OHOS_Image"
+ liteos_skip_make = false
+}
+
+tee = ""
+if (tee_enable) {
+ tee = "_tee"
+}
+
+declare_args() {
+ liteos_config_file = "${ohos_build_type}${tee}.config"
+}
+
+liteos_config_file =
+ rebase_path(liteos_config_file, "", "$product_path/kernel_configs")
+print("liteos_config_file:", liteos_config_file)
+
+exec_script("//build/lite/run_shell_cmd.py",
+ [ "env" + " CONFIG_=LOSCFG_" + " KCONFIG_CONFIG_HEADER='y=true'" +
+ " KCONFIG_CONFIG=$liteos_config_file" +
+ " DEVICE_PATH=$device_path" + " srctree=" + rebase_path(".") +
+ " genconfig" + " --header-path $LITEOS_MENUCONFIG_H" +
+ " --file-list kconfig_files.txt" +
+ " --env-list kconfig_env.txt" + " --config-out config.gni" ],
+ "",
+ [ liteos_config_file ])
+
+import("liteos.gni")
+
+assert(ARCH != "", "ARCH not set!")
+assert(ARCH == arch, "ARCH not match! details: $ARCH != $arch")
+assert(tee_enable == defined(LOSCFG_TEE_ENABLE), "TEE switch not match!")
+assert(ohos_build_compiler == "clang" == defined(LOSCFG_COMPILER_CLANG_LLVM),
+ "compiler not match!")
+
+generate_notice_file("kernel_notice_file") {
+ module_name = "kernel"
+ module_source_dir_list = [
+ "$LITEOSTHIRDPARTY/FreeBSD",
+ "$LITEOSTHIRDPARTY/musl",
+ "$LITEOSTHIRDPARTY/zlib",
+ "$LITEOSTHIRDPARTY/FatFs",
+ "$LITEOSTHIRDPARTY/lwip",
+ "$LITEOSTHIRDPARTY/NuttX",
+ "$LITEOSTHIRDPARTY/mtd-utils",
+ ]
+}
+
+liteos_arch_cflags = []
+if (defined(LOSCFG_ARCH_ARM)) {
+ mcpu = LOSCFG_ARCH_CPU
+ if (defined(LOSCFG_ARCH_ARM_AARCH64) && defined(LOSCFG_ARCH_FPU_DISABLE)) {
+ mcpu += "+nofp"
+ }
+ liteos_arch_cflags += [ "-mcpu=$mcpu" ]
+ if (defined(LOSCFG_ARCH_ARM_AARCH32)) {
+ liteos_arch_cflags += [
+ "-mfloat-abi=softfp",
+ "-mfpu=$LOSCFG_ARCH_FPU",
+ ]
+ }
+}
+
+cc = "$ohos_current_cc_command " + string_join(" ", liteos_arch_cflags)
+if (ohos_build_compiler == "clang") {
+ cc += " --target=$target_triple"
+}
+
+config("arch_config") {
+ cflags = liteos_arch_cflags
+ asmflags = cflags
+ ldflags = cflags
+ if (defined(LOSCFG_ARCH_ARM_AARCH32)) {
+ if (!defined(LOSCFG_COMPILER_CLANG_LLVM)) {
+ cflags += [ "-mthumb-interwork" ]
+ }
+ }
+ if (defined(LOSCFG_THUMB)) {
+ cflags += [ "-mthumb" ]
+ if (defined(LOSCFG_COMPILER_CLANG_LLVM)) {
+ cflags += [ "-mimplicit-it=thumb" ]
+ } else {
+ cflags += [ "-Wa,-mimplicit-it=thumb" ]
+ }
+ }
+}
+
+config("stdinc_config") {
+ std_include = exec_script("//build/lite/run_shell_cmd.py",
+ [ "$cc -print-file-name=include" ],
+ "trim string")
+ cflags = [
+ "-isystem",
+ std_include,
+ ]
+ cflags += [ "-nostdinc" ]
+ asmflags = cflags
+}
+
+config("ssp_config") {
+ cflags = []
+ if (defined(LOSCFG_CC_STACKPROTECTOR_ALL)) {
+ cflags += [ "-fstack-protector-all" ]
+ } else if (defined(LOSCFG_CC_STACKPROTECTOR_STRONG)) {
+ cflags += [ "-fstack-protector-strong" ]
+ } else if (defined(LOSCFG_CC_STACKPROTECTOR)) {
+ cflags += [
+ "-fstack-protector",
+ "--param",
+ "ssp-buffer-size=4",
+ ]
+ } else {
+ cflags += [ "-fno-stack-protector" ]
+ }
+ asmflags = cflags
+}
+
+config("optimize_config") {
+ cflags = []
+ if (defined(LOSCFG_COMPILE_DEBUG)) {
+ cflags += [
+ "-g",
+ "-gdwarf-2",
+ ]
+ optimization_cflag = "-O0"
+ }
+ if (defined(LOSCFG_COMPILE_OPTIMIZE)) {
+ optimization_cflag = "-O2"
+ }
+ if (defined(LOSCFG_COMPILE_OPTIMIZE_SIZE)) {
+ if (defined(LOSCFG_COMPILER_CLANG_LLVM)) {
+ optimization_cflag = "-Oz"
+ } else {
+ optimization_cflag = "-Os"
+ }
+ }
+ if (defined(LOSCFG_COMPILE_LTO)) {
+ if (defined(LOSCFG_COMPILER_CLANG_LLVM)) {
+ cflags += [ "-flto=thin" ]
+ } else {
+ #cflags += [ "-flto" ]
+ }
+ }
+ cflags += [ optimization_cflag ]
+ asmflags = cflags
+}
+
+config("kconfig_config") {
+ cflags = [
+ "-imacros",
+ "$LITEOS_MENUCONFIG_H",
+ ]
+ asmflags = cflags
+}
+
+config("warn_config") {
+ cflags = [
+ "-Wall",
+ "-Werror",
+ "-Wpointer-arith",
+ "-Wstrict-prototypes",
+ "-Winvalid-pch",
+ ]
+ if (defined(LOSCFG_COMPILER_CLANG_LLVM)) {
+ cflags += [ "-Wno-address-of-packed-member" ]
+ }
+ asmflags = cflags
+}
+
+config("dialect_config") {
+ cflags_c = [ "-std=c99" ]
+ cflags_cc = [ "-std=c++11" ]
+}
+
+config("misc_config") {
+ defines = [ "__LITEOS__" ]
+ defines += [ "__LITEOS_A__" ]
+ if (!defined(LOSCFG_DEBUG_VERSION)) {
+ defines += [ "NDEBUG" ]
+ }
+
+ cflags = [
+ "-fno-pic",
+ "-fno-builtin",
+ "-fms-extensions",
+ "-fno-strict-aliasing",
+ "-fno-common",
+ "-fsigned-char",
+ "-ffunction-sections",
+ "-fdata-sections",
+ "-fno-exceptions",
+ "-fno-omit-frame-pointer",
+ "-fno-short-enums",
+ "-mno-unaligned-access",
+ ]
+
+ if (!defined(LOSCFG_COMPILER_CLANG_LLVM)) {
+ cflags += [ "-fno-aggressive-loop-optimizations" ]
+ }
+
+ asmflags = cflags
+}
+
+config("los_config") {
+ configs = [
+ ":arch_config",
+ ":kconfig_config",
+ ":stdinc_config",
+ ":dialect_config",
+ ":optimize_config",
+ ":ssp_config",
+ ":warn_config",
+ ":misc_config",
+ ]
+}
+
+cmd = "if [ -f $device_path/BUILD.gn ]; then echo true; else echo false; fi"
+HAVE_DEVICE_SDK = exec_script("//build/lite/run_shell_cmd.py", [ cmd ], "value")
+
+config("public") {
+ configs = [
+ "arch:public",
+ "kernel:public",
+ "compat:public",
+ "bsd:public",
+ "fs:public",
+ "drivers:public",
+ "security:public",
+ "net:public",
+ "shell:public",
+ "lib:public",
+ ]
+
+ configs += [
+ "$HDFTOPDIR:public",
+ "//drivers/liteos:public",
+ ]
+
+ if (HAVE_DEVICE_SDK) {
+ configs += [ "$device_path:public" ]
+ }
+}
+
+group("modules") {
+ deps = [
+ "arch",
+ "bsd",
+ "compat",
+ "drivers",
+ "fs",
+ "kernel",
+ "lib",
+ "net",
+ "security",
+ "shell",
+ "syscall",
+ ]
+
+ deps += [
+ "//drivers/liteos",
+ HDFTOPDIR,
+ ]
+
+ if (HAVE_DEVICE_SDK) {
+ deps += [ device_path ]
+ }
+}
+
+group("apps") {
+ deps = [ "apps" ]
+}
+
+group("tests") {
+ deps = [ "testsuites" ]
+}
+
+group("kernel") {
+ deps = [ ":build_kernel_image" ]
+}
+
+group("liteos_a") {
+ deps = [
+ ":apps",
+ ":kernel",
+ ":make",
+ ":tests",
+ "//prebuilts/lite/sysroot/build:strip",
+ ]
+}
+
+executable("liteos") {
+ configs = [] # clear default configs
+ configs += [ ":arch_config" ]
+ configs += [ ":public" ]
+
+ ldflags = [
+ "-static",
+ "-nostdlib",
+ "-Wl,--gc-sections",
+ "-Wl,-Map=$liteos_name.map",
+ "-Wl,--no-eh-frame-hdr",
+ ]
+
+ libgcc = exec_script("//build/lite/run_shell_cmd.py",
+ [ "$cc -print-libgcc-file-name" ],
+ "trim string")
+ libs = [ libgcc ]
+ if (defined(LOSCFG_COMPILER_CLANG_LLVM)) {
+ ldflags +=
+ [ "-Wl,-T" + rebase_path("tools/build/liteos_llvm.ld", root_build_dir) ]
+ inputs = [ "tools/build/liteos_llvm.ld" ]
+ } else {
+ ldflags +=
+ [ "-Wl,-T" + rebase_path("tools/build/liteos.ld", root_build_dir) ]
+ ldflags += [ "-Wl,-nostartfiles" ]
+ inputs = [ "tools/build/liteos.ld" ]
+ }
+
+ inputs += [ "$root_out_dir/board.ld" ]
+
+ output_dir = target_out_dir
+
+ deps = [
+ ":modules",
+ "platform:copy_board.ld",
+ ]
+}
+
+copy("copy_liteos") {
+ deps = [ ":liteos" ]
+ sources = [ "$target_out_dir/unstripped/bin/liteos" ]
+ outputs = [ "$root_out_dir/$liteos_name" ]
+}
+
+build_ext_component("build_kernel_image") {
+ deps = [ ":copy_liteos" ]
+ exec_path = rebase_path(root_out_dir)
+
+ objcopy = "${compile_prefix}objcopy$toolchain_cmd_suffix"
+ objdump = "${compile_prefix}objdump$toolchain_cmd_suffix"
+
+ command = "$objcopy -O binary $liteos_name $liteos_name.bin"
+ command +=
+ " && sh -c '$objdump -t $liteos_name | sort >$liteos_name.sym.sorted'"
+ command += " && sh -c '$objdump -d $liteos_name >$liteos_name.asm'"
+}
+
+build_ext_component("make") {
+ exec_path = rebase_path(".", root_build_dir)
+ outdir = rebase_path("$target_out_dir/${target_name}_out")
+ sysroot_path = rebase_path(ohos_current_sysroot)
+ arch_cflags = string_join(" ", target_arch_cflags)
+ command = "./build.sh \"$board_name\" \"$ohos_build_compiler\" \"$root_build_dir\" \"$ohos_build_type\" \"$tee_enable\""
+ command += " \"$device_company\" \"$product_path\" \"$outdir\" \"$ohos_version\" \"$sysroot_path\" \"$arch_cflags\""
+ command += " \"$device_path\" \"$compile_prefix\" \"$liteos_config_file\""
+ if (liteos_skip_make) {
+ print("build_ext_component \"$target_name\" skipped:", command)
+ command = "true"
+ }
+}
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/Kconfig b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/Kconfig
new file mode 100644
index 00000000..8041b61d
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/Kconfig
@@ -0,0 +1,336 @@
+# 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.
+
+mainmenu "Huawei LiteOS Configuration"
+
+menu "Compiler"
+choice
+ prompt "Compiler type"
+ default COMPILER_CLANG_LLVM
+ help
+ Choose compiler type.
+
+config COMPILER_GCC
+ bool "GCC"
+
+config CROSS_COMPILE
+ string "GCC cross-compile toolchain prefix"
+ depends on COMPILER_GCC
+ default "arm-linux-ohoseabi-" if ARCH_ARM_AARCH32
+
+config COMPILER_CLANG_LLVM
+ bool "Clang"
+
+config LLVM_TARGET
+ string "Clang LLVM target"
+ depends on COMPILER_CLANG_LLVM
+ default "arm-liteos-ohos" if ARCH_ARM_AARCH32
+
+endchoice
+
+config COMPILE_DEBUG
+ bool "Enable debug options"
+ default n
+ help
+ Answer Y to add -g option in compile command.
+
+config COMPILE_OPTIMIZE
+ bool "Enable code optimization options"
+ default y
+ help
+ Answer Y to add optimization options for efficient code.
+ The final binary size will be smaller and execute faster.
+ But the debugging experience may be worst somehow.
+
+config COMPILE_OPTIMIZE_SIZE
+ bool "Enable code size optimization options" if COMPILE_OPTIMIZE
+ default y
+ help
+ Answer Y to add optimization options for small code size.
+ The final binary size will be smaller.
+ But the compile time may be a bit longer.
+
+config COMPILE_LTO
+ bool "Enable link time optimization (LTO)" if COMPILE_OPTIMIZE_SIZE
+ default y
+ help
+ Answer Y to add lto options for more smaller code size.
+ The final binary size will be smaller.
+ But the compile time may be much longer.
+
+endmenu
+
+menu "Platform"
+
+######################### config options of bsp #####################
+source "platform/Kconfig"
+
+######################### config options of cpu arch ################
+source "arch/Kconfig"
+
+config QUICK_START
+ bool "Enable QUICK_START"
+ default n
+ depends on DRIVERS && FS_VFS
+ help
+ Answer Y to enable LiteOS support quick start.
+endmenu
+
+######################### config options of kernel #####################
+source "kernel/Kconfig"
+######################### config options of lib ########################
+source "lib/Kconfig"
+######################### config options of compatibility ##############
+menu "Compat"
+source "compat/posix/Kconfig"
+source "bsd/Kconfig"
+endmenu
+
+######################## config options of filesystem ##################
+menu "FileSystem"
+source "fs/Kconfig"
+endmenu
+
+######################## config options of net ############################
+source "net/Kconfig"
+
+######################## config options of debug ########################
+menu "Debug"
+config GDB
+ bool "Enable gdb functions"
+ default n
+ help
+ Answer Y to enable gdb functions.
+
+config PLATFORM_ADAPT
+ bool "Enable Os_adapt"
+ default y
+ help
+ Answer Y to add os_adapt.c to LiteOS.
+
+config ENABLE_OOM_LOOP_TASK
+ bool "Enable Oom loop task"
+ default n
+ depends on KERNEL_VM
+ help
+ Answer Y to enable oom loop kthread to check system out of memory.
+
+config DO_ALIGN
+ bool "Enable do align for hi3518e"
+ default y
+ depends on PLATFORM_HI3518EV200
+ help
+ Answer Y to enable do align for hi3518e.
+
+
+config ENABLE_MAGICKEY
+ bool "Enable MAGIC KEY"
+ default y
+ help
+ Answer Y to enable LiteOS Magic key.
+ ctrl + r : Magic key check switch;
+ ctrl + z : Show all magic op key;
+ ctrl + t : Show task information;
+ ctrl + p : System panic;
+ ctrl + e : Check system memory pool.
+
+config THUMB
+ bool "Enable Thumb"
+ default n
+ depends on ARCH_ARM
+ help
+ Answer Y to build thumb version. This will make LiteOS smaller.
+
+config PLATFORM_DVFS
+ bool "Enable Dvfs"
+ default n
+ depends on COMPAT_LINUXKPI
+ help
+ Answer Y to enable LiteOS support dynamic voltage and frequency scaling feature for
+ low power consumption.
+
+config SAVE_EXCINFO
+ bool "Enable Saving Exception Information"
+ default n
+ help
+ Answer Y to enable LiteOS support saving exception information to storage medium.
+
+config DEBUG_VERSION
+ bool "Enable a Debug Version"
+ default n
+ help
+ If you do not select this option that means you enable a release version for LiteOS.
+ It also means you do not want to use debug modules, like shell,telnet,tftp,nfs and
+ memory check, etc.
+ If you select this option that means you enable a debug version for LiteOS.
+ That means you want an opposite behaviour compared to release version.
+
+config DEBUG_KERNEL
+ bool "Enable Debug LiteOS Kernel Resource"
+ default n
+ depends on DEBUG_VERSION
+ help
+ If you select this option that means you enable debugging kernel resource.
+ It also means you want to get queue, mutex, semaphore, memory debug information.
+ That means you want an opposite behaviour compared to release version.
+
+config DEBUG_QUEUE
+ bool "Enable Queue Debugging"
+ default n
+ depends on DEBUG_KERNEL
+ help
+ Answer Y to enable debug queue.
+
+config DEBUG_DEADLOCK
+ bool "Enable Mutex Deadlock Debugging"
+ default n
+ depends on DEBUG_KERNEL
+ help
+ Answer Y to enable debug mutex deadlock.
+
+config DEBUG_SEMAPHORE
+ bool "Enable Semaphore Debugging"
+ default n
+ depends on DEBUG_KERNEL
+ help
+ Answer Y to enable debug semaphore.
+
+source "shell/Kconfig"
+config NET_LWIP_SACK_TFTP
+ bool "Enable Tftp"
+ default y
+ depends on SHELL && NET_LWIP_SACK && DEBUG_VERSION
+ help
+ Answer Y to enable LiteOS support tftp cmd and tftp tool.
+source "net/telnet/Kconfig"
+config SCHED_DEBUG
+ bool "Enable sched debug Feature"
+ default n
+ depends on DEBUG_VERSION
+ help
+ If you wish to build LiteOS with support for sched debug.
+
+config USER_INIT_DEBUG
+ bool "Enable user init Debug"
+ default n
+ depends on DEBUG_VERSION
+
+config SHELL_CMD_DEBUG
+ bool "Enable shell cmd Debug"
+ default n
+ depends on DEBUG_VERSION && SHELL
+
+config USB_DEBUG
+ bool "Enable USB Debug"
+ default n
+ depends on SHELL && DRIVERS_USB && DEBUG_VERSION
+ help
+ Answer Y to enable LiteOS support usb debug.
+ use shell command to open the specified debug level print.
+config MEM_DEBUG
+ bool "Enable MEM Debug"
+ default n
+ depends on DEBUG_VERSION
+ help
+ Answer Y to enable LiteOS support mem debug.
+
+config MEM_LEAKCHECK
+ bool "Enable Function call stack of Mem operation recorded"
+ default n
+ depends on DEBUG_VERSION && MEM_DEBUG
+ help
+ Answer Y to enable record the LR of Function call stack of Mem operation, it can check the mem leak through the informations of mem node.
+config BASE_MEM_NODE_INTEGRITY_CHECK
+ bool "Enable integrity check or not"
+ default n
+ depends on DEBUG_VERSION && MEM_DEBUG
+config MEM_WATERLINE
+ bool "Enable memory pool waterline or not"
+ default n
+ depends on DEBUG_VERSION && MEM_DEBUG
+
+config VM_OVERLAP_CHECK
+ bool "Enable VM overlap check or not"
+ default n
+ depends on DEBUG_VERSION && MEM_DEBUG
+ help
+ Answer Y to enable vm overlap check.
+
+endmenu
+
+######################## config options os drivers ########################
+menu "Driver"
+source "drivers/Kconfig"
+endmenu
+
+######################## config options os security #######################
+menu "Security"
+source "security/Kconfig"
+endmenu
+
+menu "Test"
+config ENABLE_KERNEL_TEST
+ bool "Enable Kernel Test"
+ default n
+endmenu
+
+menu "Stack Smashing Protector (SSP) Compiler Feature"
+
+choice
+ prompt "Enable stack buffer overflow detection"
+ default CC_STACKPROTECTOR_STRONG
+ ---help---
+ This option turns on the -fstack-protector GCC feature. This
+ feature puts, at the beginning of functions, a canary value on
+ the stack just before the return address, and validates
+ the value just before actually returning. Stack based buffer
+ overflows (that need to overwrite this return address) now also
+ overwrite the canary, which gets detected and the attack is then
+ neutralized via a kernel panic.
+
+ This feature requires gcc version 4.2 or above, or a distribution
+ gcc with the feature backported. Older versions are automatically
+ detected and for those versions, this configuration option is
+ ignored. (and a warning is printed during bootup)
+
+config CC_NO_STACKPROTECTOR
+ bool "-fno-stack-protector"
+
+config CC_STACKPROTECTOR
+ bool "-fstack-protector"
+
+config CC_STACKPROTECTOR_STRONG
+ bool "-fstack-protector-strong"
+
+config CC_STACKPROTECTOR_ALL
+ bool "-fstack-protector-all"
+
+endchoice
+
+endmenu
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/LICENSE b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/LICENSE
new file mode 100644
index 00000000..b6ffd6e6
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/LICENSE
@@ -0,0 +1,28 @@
+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.
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/Makefile b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/Makefile
new file mode 100644
index 00000000..8122156f
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/Makefile
@@ -0,0 +1,201 @@
+# 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.
+
+LITEOSTOPDIR := $(realpath $(dir $(lastword $(MAKEFILE_LIST))))
+export LITEOSTOPDIR
+
+APPS = apps
+ROOTFS = rootfs
+LITEOS_TARGET = liteos
+LITEOS_LIBS_TARGET = libs
+KCONFIG_CMDS := $(notdir $(wildcard $(dir $(shell which menuconfig))*config))
+
+ohos_kernel ?= liteos_a
+$(foreach line,$(shell hb env | sed 's/\[OHOS INFO\]/ohos/g;s/ /_/g;s/:_/=/g' || true),$(eval $(line)))
+ifneq ($(ohos_kernel),liteos_a)
+$(error The selected product ($(ohos_product)) is not a liteos_a kernel type product)
+endif
+
+ifeq ($(PRODUCT_PATH),)
+PRODUCT_PATH:=$(ohos_product_path)
+endif
+
+ifeq ($(DEVICE_PATH),)
+DEVICE_PATH:=$(ohos_device_path)
+endif
+
+ifeq ($(TEE:1=y),y)
+tee = _tee
+endif
+ifeq ($(RELEASE:1=y),y)
+CONFIG ?= $(PRODUCT_PATH)/kernel_configs/release$(tee).config
+else
+CONFIG ?= $(PRODUCT_PATH)/kernel_configs/debug$(tee).config
+endif
+
+KCONFIG_CONFIG ?= $(CONFIG)
+SYSROOT_PATH ?= $(OUT)/sysroot
+
+# export subdir Makefile related environment variables
+export SYSROOT_PATH
+export PRODUCT_PATH
+export DEVICE_PATH
+
+# export kconfig related environment variables
+export CONFIG_=LOSCFG_
+export srctree=$(LITEOSTOPDIR)
+
+include $(LITEOSTOPDIR)/config.mk
+
+ifeq ($(LOSCFG_STORAGE_SPINOR), y)
+FSTYPE = jffs2
+endif
+ifeq ($(LOSCFG_STORAGE_EMMC), y)
+FSTYPE = vfat
+endif
+ifeq ($(LOSCFG_STORAGE_SPINAND), y)
+FSTYPE = yaffs2
+endif
+ifeq ($(LOSCFG_PLATFORM_QEMU_ARM_VIRT_CA7), y)
+FSTYPE = jffs2
+endif
+ROOTFS_DIR = $(OUT)/rootfs
+ROOTFS_ZIP = $(OUT)/rootfs.zip
+
+define HELP =
+Usage: make [TARGET]... [PARAMETER=VALUE]...
+
+Targets:
+ help: display this help and exit
+ clean: clean compiled objects
+ cleanall: clean all build outputs
+ all: make liteos kernel image and rootfs image (Default target)
+ $(APPS): build all apps
+ $(ROOTFS): make an original rootfs image
+ $(LITEOS_LIBS_TARGET): compile all kernel modules (libraries)
+ $(LITEOS_TARGET): make liteos kernel image
+ update_config: update product kernel config (use menuconfig)
+ xxconfig: invoke xxconfig command of kconfiglib (xxconfig is one of $(KCONFIG_CMDS))
+
+Parameters:
+ FSTYPE: value should be one of (jffs2 vfat yaffs2)
+ TEE: boolean value(1 or y for true), enable tee
+ RELEASE: boolean value(1 or y for true), build release version
+ CONFIG: kernel config file to be use
+ args: arguments for xxconfig command
+endef
+export HELP
+
+all: $(LITEOS_TARGET) $(ROOTFS)
+
+help:
+ $(HIDE)echo "$$HELP"
+
+sysroot:
+ $(HIDE)echo "sysroot:" $(abspath $(SYSROOT_PATH))
+ifeq ($(origin SYSROOT_PATH),file)
+ $(HIDE)mkdir -p $(SYSROOT_PATH)/build && cd $(SYSROOT_PATH)/build && \
+ ln -snf $(LITEOSTOPDIR)/../../prebuilts/lite/sysroot/build/Makefile && \
+ $(MAKE) TARGETS=liteos_a_user \
+ ARCH=$(ARCH) \
+ TARGET=$(LOSCFG_LLVM_TARGET) \
+ ARCH_CFLAGS="$(LITEOS_CORE_COPTS) -w" \
+ TOPDIR="$(LITEOSTOPDIR)/../.." \
+ SYSROOTDIR="$(SYSROOT_PATH)" \
+ $(if $(LOSCFG_COMPILER_CLANG_LLVM),CLANG="$(LITEOS_COMPILER_PATH)clang",GCC="$(CC)") \
+ BUILD_DEBUG=$(if $(patsubst y,,$(or $(RELEASE:1=y),n)),true,false)
+endif
+
+$(filter-out menuconfig,$(KCONFIG_CMDS)):
+ $(HIDE)$@ $(args)
+
+$(LITEOS_CONFIG_FILE): $(KCONFIG_CONFIG)
+ $(HIDE)env KCONFIG_CONFIG=$< genconfig --config-out $@ --header-path $(LITEOS_MENUCONFIG_H)
+
+update_config menuconfig:
+ $(HIDE)test -f "$(CONFIG)" && cp -v "$(CONFIG)" .config && menuconfig $(args) && savedefconfig --out "$(CONFIG)"
+
+$(LITEOS_LIBS_TARGET): sysroot
+ $(HIDE)for dir in $(LIB_SUBDIRS); do $(MAKE) -C $$dir all || exit 1; done
+
+$(LITEOS_TARGET): $(OUT)/$(LITEOS_TARGET)
+$(LITEOS_TARGET): $(OUT)/$(LITEOS_TARGET).map
+#$(LITEOS_TARGET): $(OUT)/$(LITEOS_TARGET).objsize
+$(LITEOS_TARGET): $(OUT)/$(LITEOS_TARGET).bin
+$(LITEOS_TARGET): $(OUT)/$(LITEOS_TARGET).sym.sorted
+$(LITEOS_TARGET): $(OUT)/$(LITEOS_TARGET).asm
+#$(LITEOS_TARGET): $(OUT)/$(LITEOS_TARGET).size
+
+$(OUT)/$(LITEOS_TARGET): $(LITEOS_LIBS_TARGET)
+ $(LD) $(LITEOS_LDFLAGS) $(LITEOS_TABLES_LDFLAGS) -Map=$@.map -o $@ --start-group $(LITEOS_LIBDEP) --end-group
+$(OUT)/$(LITEOS_TARGET).map: $(OUT)/$(LITEOS_TARGET)
+$(OUT)/$(LITEOS_TARGET).objsize: $(LITEOS_LIBS_TARGET)
+ $(SIZE) -t --common $(OUT)/lib/*.a >$@
+$(OUT)/$(LITEOS_TARGET).bin: $(OUT)/$(LITEOS_TARGET)
+ $(OBJCOPY) -O binary $< $@
+$(OUT)/$(LITEOS_TARGET).sym.sorted: $(OUT)/$(LITEOS_TARGET)
+ $(OBJDUMP) -t $< |sort >$@
+$(OUT)/$(LITEOS_TARGET).asm: $(OUT)/$(LITEOS_TARGET)
+ $(OBJDUMP) -d $< >$@
+$(OUT)/$(LITEOS_TARGET).size: $(OUT)/$(LITEOS_TARGET)
+ $(NM) -S --size-sort $< >$@
+
+$(APPS): sysroot
+ $(HIDE)$(MAKE) -C apps all
+
+$(ROOTFS): $(APPS)
+ $(HIDE)mkdir -p $(OUT)/musl
+ifeq ($(LOSCFG_COMPILER_CLANG_LLVM), y)
+ $(HIDE)cp -fp $$($(CC) $(LITEOS_CFLAGS) -print-file-name=libc.so) $(OUT)/musl
+ $(HIDE)cp -fp $$($(GPP) $(LITEOS_CXXFLAGS) -print-file-name=libc++.so) $(OUT)/musl
+else
+ $(HIDE)cp -fp $$($(CC) $(LITEOS_CFLAGS) -print-file-name=libc.so) $(OUT)/musl
+ $(HIDE)cp -fp $$($(CC) $(LITEOS_CFLAGS) -print-file-name=libgcc_s.so.1) $(OUT)/musl
+ $(HIDE)cp -fp $$($(GPP) $(LITEOS_CXXFLAGS) -print-file-name=libstdc++.so.6) $(OUT)/musl
+endif
+ $(HIDE)$(LITEOS_SCRIPTPATH)/make_rootfs/rootfsdir.sh $(OUT) $(ROOTFS_DIR)
+ $(HIDE)shopt -s nullglob && $(STRIP) $(ROOTFS_DIR)/bin/* $(ROOTFS_DIR)/lib/*
+ifneq ($(VERSION),)
+ $(HIDE)$(LITEOS_SCRIPTPATH)/make_rootfs/releaseinfo.sh "$(VERSION)" $(ROOTFS_DIR)
+endif
+ $(HIDE)$(LITEOS_SCRIPTPATH)/make_rootfs/rootfsimg.sh $(ROOTFS_DIR) $(FSTYPE)
+ $(HIDE)cd $(ROOTFS_DIR)/.. && zip -r $(ROOTFS_ZIP) $(ROOTFS)
+
+clean:
+ $(HIDE)if [ -d $(SYSROOT_PATH)/build ]; then $(MAKE) -C $(SYSROOT_PATH)/build clean; fi
+ $(HIDE)for dir in $(LIB_SUBDIRS) apps; do $(MAKE) -C $$dir clean || exit 1; done
+ $(HIDE)$(RM) $(LITEOS_MENUCONFIG_H)
+ $(HIDE)echo "clean $(LOSCFG_PLATFORM) finish"
+
+cleanall: clean
+ $(HIDE)$(RM) $(LITEOSTOPDIR)/out $(LITEOS_CONFIG_FILE)
+ $(HIDE)echo "clean all done"
+
+.PHONY: all clean cleanall sysroot help update_config
+.PHONY: $(LITEOS_TARGET) $(ROOTFS) $(APPS) $(KCONFIG_CMDS) $(LITEOS_LIBS_TARGET) $(KCONFIG_CONFIG)
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/OAT.xml b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/OAT.xml
new file mode 100644
index 00000000..3ffb98a8
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/OAT.xml
@@ -0,0 +1,84 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/README.md b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/README.md
new file mode 100644
index 00000000..63f37f9f
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/README.md
@@ -0,0 +1,96 @@
+# LiteOS Cortex-A
+
+- [Introduction](#section11660541593)
+- [Directory Structure](#section161941989596)
+- [Constraints](#section119744591305)
+- [Usage](#section741617511812)
+ - [Preparations](#section1579912573329)
+ - [Source Code Acquisition](#section11443189655)
+ - [Compilation and Building](#section2081013992812)
+
+- [Repositories Involved](#section1371113476307)
+
+## Introduction
+
+The OpenHarmony LiteOS Cortex-A is a new-generation kernel developed based on the Huawei LiteOS kernel. Huawei LiteOS is a lightweight operating system \(OS\) built for the Internet of Things \(IoT\) field. With the rapid development of the IoT industry, OpenHarmony LiteOS Cortex-A brings small-sized, low-power, and high-performance experience and builds a unified and open ecosystem for developers. In addition, it provides rich kernel mechanisms, more comprehensive Portable Operating System Interface \(POSIX\), and a unified driver framework, Hardware Driver Foundation \(HDF\), which offers unified access for device developers and friendly development experience for application developers. [Figure 1](#fig27311582210) shows the architecture of the OpenHarmony LiteOS Cortex-A kernel.
+
+**Figure 1** Architecture of the OpenHarmony LiteOS Cortex-A kernel
+
+
+## Directory Structure
+
+```
+/kernel/liteos_a
+├── apps # User-space init and shell application programs
+├── arch # System architecture, such as ARM
+│ └── arm # Code for ARM architecture
+├── bsd # Code of the driver and adaptation layer module related to the FreeBSD, such as the USB module
+├── compat # Kernel API compatibility
+│ └── posix # POSIX APIs
+├── drivers # Kernel drivers
+│ └── char # Character device
+│ ├── mem # Driver for accessing physical input/output (I/O) devices
+│ ├── quickstart # APIs for quick start of the system
+│ ├── random # Driver for random number generators
+│ └── video # Framework of the framebuffer driver
+├── fs # File system module, which mainly derives from the NuttX open-source project
+│ ├── fat # FAT file system
+│ ├── jffs2 # JFFS2 file system
+│ ├── include # Header files exposed externally
+│ ├── nfs # NFS file system
+│ ├── proc # proc file system
+│ ├── ramfs # RAMFS file system
+│ └── vfs # VFS layer
+├── kernel # Kernel modules including the process, memory, and IPC modules
+│ ├── base # Basic kernel modules including the scheduling and memory modules
+│ ├── common # Common components used by the kernel
+│ ├── extended # Extended kernel modules including the dynamic loading, vDSO, and LiteIPC modules
+│ ├── include # Header files exposed externally
+│ └── user # Init process loading
+├── lib # Kernel library
+├── net # Network module, which mainly derives from the lwIP open-source project
+├── platform # Code for supporting different systems on a chip (SOCs), such as Hi3516D V300
+│ ├── hw # Logic code related to clocks and interrupts
+│ ├── include # Header files exposed externally
+│ └── uart # Logic code related to the serial port
+├── platform # Code for supporting different systems on a chip (SOCs), such as Hi3516D V300
+├── security # Code related to security features, including process permission management and virtual ID mapping management
+├── syscall # System calling
+└── tools # Building tools as well as related configuration and code
+```
+
+## Constraints
+
+- Programming languages: C and C++
+- Applicable development boards: Hi3516D V300
+- Hi3516D V300 uses the FAT file system by default.
+
+## Usage
+
+OpenHarmony LiteOS Cortex-A supports the [Hi3516D V300](https://gitee.com/openharmony/docs/blob/master/en/device-dev/quick-start/quickstart-lite-introduction-hi3516.md). You can develop and run your applications based on this development board.
+
+### Preparations
+
+You need to set up the compilation environment on Linux.
+
+- [Setting Up Ubuntu Development Environment](https://gitee.com/openharmony/docs/blob/master/en/device-dev/quick-start/quickstart-lite-env-setup.md)
+- For Hi3516D V300, see [Setting Up the Hi3516 Development Environment](https://gitee.com/openharmony/docs/blob/master/en/device-dev/quick-start/quickstart-lite-steps-hi3516-setting.md).
+
+### Source Code Acquisition
+
+Download and decompress a set of source code on a Linux server to acquire the [source code](https://gitee.com/openharmony/docs/blob/master/en/device-dev/get-code/sourcecode-acquire.md).
+
+### Compilation and Building
+
+For details about how to develop the first application, see:
+
+- [Developing the First Example Program Running on Hi3516](https://gitee.com/openharmony/docs/blob/master/en/device-dev/quick-start/quickstart-lite-steps-hi3516-running.md)
+
+## Repositories Involved
+
+[Kernel subsystem](https://gitee.com/openharmony/docs/blob/master/en/readme/kernel.md)
+
+[drivers\_liteos](https://gitee.com/openharmony/drivers_liteos/blob/master/README.md)
+
+[kernel\_liteos\_a](https://gitee.com/openharmony/kernel_liteos_a/blob/master/README.md)
+
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/README_zh-HK.md b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/README_zh-HK.md
new file mode 100644
index 00000000..46bc25c2
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/README_zh-HK.md
@@ -0,0 +1,95 @@
+# LiteOS-A內核
+
+- [簡介](#section11660541593)
+- [目錄](#section161941989596)
+- [約束](#section119744591305)
+- [使用說明](#section741617511812)
+ - [準備](#section1579912573329)
+ - [獲取源碼](#section11443189655)
+ - [編譯構建](#section2081013992812)
+
+- [相關倉](#section1371113476307)
+
+## 簡介
+
+OpenHarmony LiteOS-A內核是基於Huawei LiteOS內核演進發展的新一代內核,Huawei LiteOS是面向IoT領域構建的輕量級物聯網操作系統。在IoT產業高速發展的潮流中,OpenHarmony LiteOS-A內核能夠帶給用戶小體積、低功耗、高性能的體驗以及統一開放的生態系統能力,新增了豐富的內核機制、更加全面的POSIX標準接口以及統一驅動框架**HDF**(OpenHarmony Driver Foundation)等,為設備廠商提供了更統一的接入方式,為OpenHarmony的應用開發者提供了更友好的開發體驗。圖1為OpenHarmony LiteOS-A內核架構圖:
+
+**圖 1** OpenHarmony LiteOS-A內核架構圖
+
+
+
+## 目錄
+
+```
+/kernel/liteos_a
+├── apps # 用戶態的init和shell應用程序
+├── arch # 體系架構的目錄,如arm等
+│ └── arm # arm架構代碼
+├── bsd # freebsd相關的驅動和適配層模塊代碼引入,例如USB等
+├── compat # 內核接口兼容性目錄
+│ └── posix # posix相關接口
+├── drivers # 內核驅動
+│ └── char # 字符設備
+│ ├── mem # 訪問物理IO設備驅動
+│ ├── quickstart # 系統快速啟動接口目錄
+│ ├── random # 隨機數設備驅動
+│ └── video # framebuffer驅動框架
+├── fs # 文件系統模塊,主要來源於NuttX開源項目
+│ ├── fat # fat文件系統
+│ ├── jffs2 # jffs2文件系統
+│ ├── include # 對外暴露頭文件存放目錄
+│ ├── nfs # nfs文件系統
+│ ├── proc # proc文件系統
+│ ├── ramfs # ramfs文件系統
+│ └── vfs # vfs層
+├── kernel # 進程、內存、IPC等模塊
+│ ├── base # 基礎內核,包括調度、內存等模塊
+│ ├── common # 內核通用組件
+│ ├── extended # 擴展內核,包括動態加載、vdso、liteipc等模塊
+│ ├── include # 對外暴露頭文件存放目錄
+│ └── user # 加載init進程
+├── lib # 內核的lib庫
+├── net # 網絡模塊,主要來源於lwip開源項目
+├── platform # 支持不同的芯片平台代碼,如Hi3516DV300等
+│ ├── hw # 時鐘與中斷相關邏輯代碼
+│ ├── include # 對外暴露頭文件存放目錄
+│ └── uart # 串口相關邏輯代碼
+├── security # 安全特性相關的代碼,包括進程權限管理和虛擬id映射管理
+├── syscall # 系統調用
+└── tools # 構建工具及相關配置和代碼
+```
+
+## 約束
+
+- 開發語言:C/C++;
+- 適用於Hi3516DV300單板;
+- Hi3516DV300默認使用FAT文件系統。
+
+## 使用說明
+
+OpenHarmony LiteOS-A內核支持Hi3516DV300([介紹](https://gitee.com/openharmony/docs/blob/master/zh-cn/device-dev/quick-start/quickstart-lite-introduction-hi3516.md))單板,開發者可基於此單板開發運行自己的應用程序。
+
+### 準備
+
+開發者需要在Linux上搭建編譯環境:
+
+- [編譯環境凖備](https://gitee.com/openharmony/docs/blob/master/zh-cn/device-dev/quick-start/quickstart-lite-env-setup.md);
+- Hi3516DV300單板:參考[環境搭建](https://gitee.com/openharmony/docs/blob/master/zh-cn/device-dev/quick-start/quickstart-lite-steps-hi3516-setting.md)。
+
+### 獲取源碼
+
+在Linux服務器上下載並解壓一套源代碼,源碼獲取方式參考[源碼獲取](https://gitee.com/openharmony/docs/blob/master/zh-cn/device-dev/get-code/sourcecode-acquire.md)。
+
+### 編譯構建
+
+開發者開發第一個應用程序可參考:
+
+- [helloworld for Hi3516DV300](https://gitee.com/openharmony/docs/blob/master/zh-cn/device-dev/quick-start/quickstart-lite-steps-hi3516-running.md)。
+
+## 相關倉
+
+[內核子系統](https://gitee.com/openharmony/docs/blob/master/zh-cn/readme/%E5%86%85%E6%A0%B8%E5%AD%90%E7%B3%BB%E7%BB%9F.md)
+
+[drivers\_liteos](https://gitee.com/openharmony/drivers_liteos/blob/master/README_zh.md)
+
+[kernel\_liteos\_a](https://gitee.com/openharmony/kernel_liteos_a/blob/master/README_zh-HK.md)
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/README_zh.md b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/README_zh.md
new file mode 100644
index 00000000..c62c0449
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/README_zh.md
@@ -0,0 +1,95 @@
+# LiteOS-A内核
+
+- [简介](#section11660541593)
+- [目录](#section161941989596)
+- [约束](#section119744591305)
+- [使用说明](#section741617511812)
+ - [准备](#section1579912573329)
+ - [获取源码](#section11443189655)
+ - [编译构建](#section2081013992812)
+
+- [相关仓](#section1371113476307)
+
+## 简介
+
+OpenHarmony LiteOS-A内核是基于Huawei LiteOS内核演进发展的新一代内核,Huawei LiteOS是面向IoT领域构建的轻量级物联网操作系统。在IoT产业高速发展的潮流中,OpenHarmony LiteOS-A内核能够带给用户小体积、低功耗、高性能的体验以及统一开放的生态系统能力,新增了丰富的内核机制、更加全面的POSIX标准接口以及统一驱动框架**HDF**(OpenHarmony Driver Foundation)等,为设备厂商提供了更统一的接入方式,为OpenHarmony的应用开发者提供了更友好的开发体验。图1为OpenHarmony LiteOS-A内核架构图:
+
+**图 1** OpenHarmony LiteOS-A内核架构图
+
+
+## 目录
+
+```
+/kernel/liteos_a
+├── apps # 用户态的init和shell应用程序
+├── arch # 体系架构的目录,如arm等
+│ └── arm # arm架构代码
+├── bsd # freebsd相关的驱动和适配层模块代码引入,例如USB等
+├── compat # 内核接口兼容性目录
+│ └── posix # posix相关接口
+├── drivers # 内核驱动
+│ └── char # 字符设备
+│ ├── mem # 访问物理IO设备驱动
+│ ├── quickstart # 系统快速启动接口目录
+│ ├── random # 随机数设备驱动
+│ └── video # framebuffer驱动框架
+├── fs # 文件系统模块,主要来源于NuttX开源项目
+│ ├── fat # fat文件系统
+│ ├── jffs2 # jffs2文件系统
+│ ├── include # 对外暴露头文件存放目录
+│ ├── nfs # nfs文件系统
+│ ├── proc # proc文件系统
+│ ├── ramfs # ramfs文件系统
+│ └── vfs # vfs层
+├── kernel # 进程、内存、IPC等模块
+│ ├── base # 基础内核,包括调度、内存等模块
+│ ├── common # 内核通用组件
+│ ├── extended # 扩展内核,包括动态加载、vdso、liteipc等模块
+│ ├── include # 对外暴露头文件存放目录
+│ └── user # 加载init进程
+├── lib # 内核的lib库
+├── net # 网络模块,主要来源于lwip开源项目
+├── platform # 支持不同的芯片平台代码,如Hi3516DV300等
+│ ├── hw # 时钟与中断相关逻辑代码
+│ ├── include # 对外暴露头文件存放目录
+│ └── uart # 串口相关逻辑代码
+├── security # 安全特性相关的代码,包括进程权限管理和虚拟id映射管理
+├── syscall # 系统调用
+└── tools # 构建工具及相关配置和代码
+```
+
+## 约束
+
+- 开发语言:C/C++;
+- 适用于Hi3516DV300单板;
+- Hi3516DV300默认使用FAT文件系统。
+
+## 使用说明
+
+OpenHarmony LiteOS-A内核支持[Hi3516DV300](https://gitee.com/openharmony/docs/blob/master/zh-cn/device-dev/quick-start/quickstart-lite-introduction-hi3516.md)单板。开发者可基于此单板开发运行自己的应用程序。
+
+### 准备
+
+开发者需要在Linux上搭建编译环境:
+
+- [编译环境准备](https://gitee.com/openharmony/docs/blob/master/zh-cn/device-dev/quick-start/quickstart-lite-env-setup.md);
+- Hi3516DV300单板:参考[环境搭建](https://gitee.com/openharmony/docs/blob/master/zh-cn/device-dev/quick-start/quickstart-lite-steps-hi3516-setting.md)。
+
+### 获取源码
+
+在Linux服务器上下载并解压一套源代码,源码获取方式参考[源码获取](https://gitee.com/openharmony/docs/blob/master/zh-cn/device-dev/get-code/sourcecode-acquire.md)。
+
+### 编译构建
+
+开发者开发第一个应用程序可参考:
+
+- [helloworld for Hi3516DV300](https://gitee.com/openharmony/docs/blob/master/zh-cn/device-dev/quick-start/quickstart-lite-steps-hi3516-running.md)。
+
+## 相关仓
+
+[内核子系统](https://gitee.com/openharmony/docs/blob/master/zh-cn/readme/%E5%86%85%E6%A0%B8%E5%AD%90%E7%B3%BB%E7%BB%9F.md)
+
+[drivers\_liteos](https://gitee.com/openharmony/drivers_liteos/blob/master/README_zh.md)
+
+[kernel\_liteos\_a](https://gitee.com/openharmony/kernel_liteos_a/blob/master/README_zh.md)
+
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/BUILD.gn b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/BUILD.gn
new file mode 100644
index 00000000..bf35c91a
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/BUILD.gn
@@ -0,0 +1,62 @@
+# 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("//kernel/liteos_a/liteos.gni")
+
+group("apps") {
+ deps = []
+
+ if (defined(LOSCFG_SHELL)) {
+ deps += [
+ "mksh",
+ "shell",
+ "toybox",
+ ]
+ }
+
+ if (defined(LOSCFG_USER_INIT_DEBUG)) {
+ deps += [ "init" ]
+ }
+
+ if (defined(LOSCFG_NET_LWIP_SACK_TFTP)) {
+ deps += [ "tftp" ]
+ }
+
+ if (defined(LOSCFG_DRIVERS_TRACE)) {
+ deps += [ "trace" ]
+ }
+
+ if (defined(LOSCFG_DRIVERS_PERF)) {
+ deps += [ "perf" ]
+ }
+
+ if (defined(LOSCFG_KERNEL_LMS)) {
+ deps += [ "lms:sample_usr_lms" ]
+ }
+}
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/Makefile b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/Makefile
new file mode 100644
index 00000000..490a6cb3
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/Makefile
@@ -0,0 +1,40 @@
+# 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.
+
+APPSTOPDIR := $(shell pwd)
+LITEOSTOPDIR ?= $(APPSTOPDIR)/..
+export LITEOSTOPDIR
+export APPSTOPDIR
+
+include $(APPSTOPDIR)/config.mk
+
+all clean:
+ $(HIDE) for dir in $(APP_SUBDIRS); do $(MAKE) -C $$dir $@ || exit 1; done
+
+.PHONY: all clean
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/app.mk b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/app.mk
new file mode 100644
index 00000000..3531c266
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/app.mk
@@ -0,0 +1,32 @@
+# 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.
+
+override TARGET = $(OUT)/bin/$(APP_NAME)
+
+include $(MODULE)
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/config.mk b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/config.mk
new file mode 100644
index 00000000..51e9e219
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/config.mk
@@ -0,0 +1,75 @@
+# 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 $(LITEOSTOPDIR)/config.mk
+
+# common flags config
+BASE_OPTS := -D_FORTIFY_SOURCE=2 -D_XOPEN_SOURCE=700
+
+ASFLAGS :=
+CFLAGS := $(LITEOS_COPTS) $(BASE_OPTS) -fPIE
+CXXFLAGS := $(LITEOS_CXXOPTS) $(BASE_OPTS) -fPIE
+LDFLAGS := $(LITEOS_CORE_COPTS) -pie -Wl,-z,relro,-z,now -O2
+
+CFLAGS := $(filter-out -fno-pic -fno-builtin -nostdinc -nostdlib,$(CFLAGS))
+CXXFLAGS := $(filter-out -fno-pic -fno-builtin -nostdinc -nostdlib -nostdinc++,$(CXXFLAGS))
+
+# alias variable config
+HIDE := @
+MAKE := make
+RM := rm -rf
+CP := cp -rf
+MV := mv -f
+
+APP := $(APPSTOPDIR)/app.mk
+
+##build modules config##
+APP_SUBDIRS :=
+
+ifeq ($(LOSCFG_SHELL), y)
+APP_SUBDIRS += shell
+APP_SUBDIRS += mksh
+APP_SUBDIRS += toybox
+endif
+
+ifeq ($(LOSCFG_USER_INIT_DEBUG), y)
+APP_SUBDIRS += init
+endif
+
+ifeq ($(LOSCFG_NET_LWIP_SACK_TFTP), y)
+APP_SUBDIRS += tftp
+endif
+
+ifeq ($(LOSCFG_DRIVERS_TRACE), y)
+APP_SUBDIRS += trace
+endif
+
+ifeq ($(LOSCFG_DRIVERS_PERF), y)
+APP_SUBDIRS += perf
+endif
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/init/BUILD.gn b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/init/BUILD.gn
new file mode 100644
index 00000000..a69e257e
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/init/BUILD.gn
@@ -0,0 +1,39 @@
+# 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("//kernel/liteos_a/liteos.gni")
+
+executable("init") {
+ sources = [ "src/init.c" ]
+
+ if (defined(LOSCFG_QUICK_START)) {
+ ldflags = [ "--static" ]
+ defines = [ "LOSCFG_QUICK_START" ]
+ }
+}
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/init/Makefile b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/init/Makefile
new file mode 100644
index 00000000..bd254e65
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/init/Makefile
@@ -0,0 +1,41 @@
+# 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 $(APPSTOPDIR)/config.mk
+
+APP_NAME := $(notdir $(shell pwd))
+
+LOCAL_SRCS := src/init.c
+
+ifeq ($(LOSCFG_QUICK_START), y)
+LDFLAGS += --static
+CFLAGS += -DLOSCFG_QUICK_START
+endif
+
+include $(APP)
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/init/src/init.c b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/init/src/init.c
new file mode 100644
index 00000000..a0420394
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/init/src/init.c
@@ -0,0 +1,99 @@
+/*
+ * 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
+
+#ifdef LOSCFG_QUICK_START
+#include
+#include
+#include
+#include
+#include
+
+#define QUICKSTART_IOC_MAGIC 'T'
+#define QUICKSTART_INITSTEP2 _IO(QUICKSTART_IOC_MAGIC, 0)
+#define WAIT_FOR_SAMPLE 300000 // wait 300ms for sample
+#endif
+int main(int argc, char * const *argv)
+{
+ (void)argv;
+ int ret;
+ pid_t gid;
+ const char *shellPath = "/bin/mksh";
+
+#ifdef LOSCFG_QUICK_START
+ const char *samplePath = "/dev/shm/sample_quickstart";
+
+ ret = fork();
+ if (ret < 0) {
+ printf("Failed to fork for sample_quickstart\n");
+ } else if (ret == 0) {
+ (void)execve(samplePath, NULL, NULL);
+ exit(0);
+ }
+
+ usleep(WAIT_FOR_SAMPLE);
+
+ int fd = open("/dev/quickstart", O_RDONLY);
+ if (fd != -1) {
+ ioctl(fd, QUICKSTART_INITSTEP2);
+ close(fd);
+ }
+#endif
+ ret = fork();
+ if (ret < 0) {
+ printf("Failed to fork for shell\n");
+ } else if (ret == 0) {
+ gid = getpgrp();
+ if (gid < 0) {
+ printf("get group id failed, pgrpid %d, errno %d\n", gid, errno);
+ exit(0);
+ }
+ ret = tcsetpgrp(STDIN_FILENO, gid);
+ if (ret != 0) {
+ printf("tcsetpgrp failed, errno %d\n", errno);
+ exit(0);
+ }
+ (void)execve(shellPath, NULL, NULL);
+ exit(0);
+ }
+
+ while (1) {
+ ret = waitpid(-1, 0, WNOHANG);
+ if (ret == 0) {
+ sleep(1);
+ }
+ };
+}
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/lms/BUILD.gn b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/lms/BUILD.gn
new file mode 100644
index 00000000..f90f6363
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/lms/BUILD.gn
@@ -0,0 +1,77 @@
+# 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("LMS-Sample") {
+ features = [ ":sample_usr_lms" ]
+}
+executable("sample_usr_lms") {
+ output_name = "sample_usr_lms"
+ sources = [ "src/sample_usr_lms.c" ]
+ include_dirs = []
+ defines = []
+ if (ohos_build_compiler == "gcc") {
+ cflags_c = [
+ "-O0",
+ "-fsanitize=kernel-address",
+ "-funwind-tables",
+ "-fasynchronous-unwind-tables",
+ ]
+ } else {
+ cflags_c = [
+ "-O0",
+ "-fsanitize=kernel-address",
+ "-mllvm",
+ "-asan-instrumentation-with-call-threshold=0",
+ "-mllvm",
+ "-asan-stack=0",
+ "-mllvm",
+ "-asan-globals=0",
+ "-funwind-tables",
+ "-fasynchronous-unwind-tables",
+ ]
+ }
+ ldflags = [
+ "-rdynamic",
+ "-lunwind",
+ "-lusrlms",
+ "-Wl,--wrap=realloc",
+ "-Wl,--wrap=calloc",
+ "-Wl,--wrap=malloc",
+ "-Wl,--wrap=free",
+ "-Wl,--wrap=valloc",
+ "-Wl,--wrap=aligned_alloc",
+ "-Wl,--wrap=memset",
+ "-Wl,--wrap=memcpy",
+ "-Wl,--wrap=memmove",
+ "-Wl,--wrap=strcpy",
+ "-Wl,--wrap=strcat",
+ ]
+ deps = [ "//kernel/liteos_a/kernel/extended/lms/usr:usrlmslib" ]
+}
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/lms/src/sample_usr_lms.c b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/lms/src/sample_usr_lms.c
new file mode 100644
index 00000000..de5425f0
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/lms/src/sample_usr_lms.c
@@ -0,0 +1,248 @@
+/*
+ * 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
+
+static void BufWriteTest(void *buf, int start, int end)
+{
+ for (int i = start; i <= end; i++) {
+ ((char *)buf)[i] = 'a';
+ }
+}
+
+static void BufReadTest(void *buf, int start, int end)
+{
+ char tmp;
+ for (int i = start; i <= end; i++) {
+ tmp = ((char *)buf)[i];
+ }
+}
+
+static void LmsMallocTest(void)
+{
+#define TEST_SIZE 16
+ printf("\n-------- LmsMallocTest Start --------\n");
+ char *buf = (char *)malloc(TEST_SIZE);
+ if (buf == NULL) {
+ return;
+ }
+ printf("[LmsMallocTest] read overflow & underflow error should be triggered, read range[-1, TEST_SIZE]\n");
+ BufReadTest(buf, -1, TEST_SIZE);
+ printf("[LmsMallocTest] write overflow error should be triggered, write range[0, TEST_SIZE]\n");
+ BufWriteTest(buf, 0, TEST_SIZE);
+
+ free(buf);
+ printf("\n-------- LmsMallocTest End --------\n");
+}
+
+static void LmsReallocTest(void)
+{
+#define TEST_SIZE 64
+#define TEST_SIZE_MIN 32
+ printf("\n-------- LmsReallocTest Start --------\n");
+ char *buf = (char *)malloc(TEST_SIZE);
+ printf("[LmsReallocTest] read overflow & underflow error should be triggered, read range[-1, TEST_SIZE]\n");
+ BufReadTest(buf, -1, TEST_SIZE);
+ char *buf1 = (char *)realloc(buf, TEST_SIZE_MIN);
+ if (buf1 == NULL) {
+ free(buf);
+ return;
+ }
+ buf = NULL;
+ printf("[LmsReallocTest] read overflow & underflow error should be triggered, read range[-1, TEST_SIZE_MIN]\n");
+ BufReadTest(buf1, -1, TEST_SIZE_MIN);
+ free(buf1);
+ printf("\n-------- LmsReallocTest End --------\n");
+}
+
+static void LmsCallocTest(void)
+{
+#define TEST_SIZE 16
+ printf("\n-------- LmsCallocTest Start --------\n");
+ char *buf = (char *)calloc(4, 4); /* 4: test size */
+ if (buf == NULL) {
+ return;
+ }
+ printf("[LmsCallocTest] read overflow & underflow error should be triggered, read range[-1, TEST_SIZE]\n");
+ BufReadTest(buf, -1, TEST_SIZE);
+ free(buf);
+ printf("\n-------- LmsCallocTest End --------\n");
+}
+
+static void LmsVallocTest(void)
+{
+#define TEST_SIZE 4096
+ printf("\n-------- LmsVallocTest Start --------\n");
+ char *buf = (char *)valloc(TEST_SIZE);
+ if (buf == NULL) {
+ return;
+ }
+ printf("[LmsVallocTest] read overflow & underflow error should be triggered, read range[-1, TEST_SIZE]\n");
+ BufReadTest(buf, -1, TEST_SIZE);
+ free(buf);
+ printf("\n-------- LmsVallocTest End --------\n");
+}
+
+static void LmsAlignedAllocTest(void)
+{
+#define TEST_ALIGN_SIZE 64
+#define TEST_SIZE 128
+ printf("\n-------- LmsAlignedAllocTest Start --------\n");
+ char *buf = (char *)aligned_alloc(TEST_ALIGN_SIZE, TEST_SIZE);
+ if (buf == NULL) {
+ return;
+ }
+ printf("[LmsAlignedAllocTest] read overflow & underflow error should be triggered, read range[-1,128]\n");
+ BufReadTest(buf, -1, 128);
+ free(buf);
+ printf("\n-------- LmsAlignedAllocTest End --------\n");
+}
+
+static void LmsMemsetTest(void)
+{
+#define TEST_SIZE 32
+ printf("\n-------- LmsMemsetTest Start --------\n");
+ char *buf = (char *)malloc(TEST_SIZE);
+ if (buf == NULL) {
+ return;
+ }
+ printf("[LmsMemsetTest] memset overflow & underflow error should be triggered, memset size:%d\n", TEST_SIZE + 1);
+ memset(buf, 0, TEST_SIZE + 1);
+ free(buf);
+ printf("\n-------- LmsMemsetTest End --------\n");
+}
+
+static void LmsMemcpyTest(void)
+{
+#define TEST_SIZE 20
+ printf("\n-------- LmsMemcpyTest Start --------\n");
+ char *buf = (char *)malloc(TEST_SIZE);
+ if (buf == NULL) {
+ return;
+ }
+ char localBuf[32] = {0}; /* 32: test size */
+ printf("[LmsMemcpyTest] memcpy overflow error should be triggered, memcpy size:%d\n", TEST_SIZE + 1);
+ memcpy(buf, localBuf, TEST_SIZE + 1);
+ free(buf);
+ printf("\n-------- LmsMemcpyTest End --------\n");
+}
+
+static void LmsMemmoveTest(void)
+{
+#define TEST_SIZE 20
+ printf("\n-------- LmsMemmoveTest Start --------\n");
+ char *buf = (char *)malloc(TEST_SIZE);
+ if (buf == NULL) {
+ return;
+ }
+ printf("[LmsMemmoveTest] memmove overflow error should be triggered\n");
+ memmove(buf + 12, buf, 10); /* 12 and 10: test size */
+ free(buf);
+ printf("\n-------- LmsMemmoveTest End --------\n");
+}
+
+static void LmsStrcpyTest(void)
+{
+#define TEST_SIZE 16
+ printf("\n-------- LmsStrcpyTest Start --------\n");
+ char *buf = (char *)malloc(TEST_SIZE);
+ if (buf == NULL) {
+ return;
+ }
+ char *testStr = "bbbbbbbbbbbbbbbbb";
+ printf("[LmsStrcpyTest] strcpy overflow error should be triggered, src string buf size:%d\n", strlen(testStr) + 1);
+ strcpy(buf, testStr);
+ free(buf);
+ printf("\n-------- LmsStrcpyTest End --------\n");
+}
+
+static void LmsStrcatTest(void)
+{
+#define TEST_SIZE 16
+ printf("\n-------- LmsStrcatTest Start --------\n");
+ char *buf = (char *)malloc(TEST_SIZE);
+ if (buf == NULL) {
+ return;
+ }
+ buf[0] = 'a';
+ buf[1] = 'b';
+ buf[2] = 0;
+ char *testStr = "cccccccccccccc";
+ printf("[LmsStrcatTest] strcat overflow error should be triggered, src string:%s dest string:%s"
+ "total buf size:%d\n",
+ testStr, buf, strlen(testStr) + strlen(buf) + 1);
+ strcat(buf, testStr);
+ free(buf);
+ printf("\n-------- LmsStrcatTest End --------\n");
+}
+
+static void LmsFreeTest(void)
+{
+#define TEST_SIZE 16
+ printf("\n-------- LmsFreeTest Start --------\n");
+ char *buf = (char *)malloc(TEST_SIZE);
+ if (buf == NULL) {
+ return;
+ }
+ printf("[LmsFreeTest] free size:%d\n", TEST_SIZE);
+ free(buf);
+ printf("[LmsFreeTest] Use after free error should be triggered, read range[1,1]\n");
+ BufReadTest(buf, 1, 1);
+ printf("[LmsFreeTest] double free error should be triggered\n");
+ free(buf);
+ printf("\n-------- LmsFreeTest End --------\n");
+}
+
+int main(int argc, char * const *argv)
+{
+ (void)argc;
+ (void)argv;
+ printf("\n############### Lms Test start ###############\n");
+ char *tmp = (char *)malloc(5000); /* 5000: test mem size */
+ if (tmp == NULL) {
+ return;
+ }
+ LmsMallocTest();
+ LmsReallocTest();
+ LmsCallocTest();
+ LmsVallocTest();
+ LmsAlignedAllocTest();
+ LmsMemsetTest();
+ LmsMemcpyTest();
+ LmsMemmoveTest();
+ LmsStrcpyTest();
+ LmsStrcatTest();
+ LmsFreeTest();
+ free(tmp);
+ printf("\n############### Lms Test End ###############\n");
+}
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/mksh/BUILD.gn b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/mksh/BUILD.gn
new file mode 100644
index 00000000..379d78f0
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/mksh/BUILD.gn
@@ -0,0 +1,100 @@
+# 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")
+import("//kernel/liteos_a/liteos.gni")
+import("//third_party/mksh/mksh.gni")
+
+group("mksh") {
+ deps = [ ":build_mksh" ]
+}
+
+copy("copy_mksh_src") {
+ sources = MKSH_SRC_DIR
+ outputs = [ "$target_out_dir/mksh_build" ]
+}
+
+build_ext_component("build_mksh") {
+ deps = [ ":copy_mksh_src" ]
+ deps += [ "//prebuilts/lite/sysroot" ]
+ exec_path = rebase_path("$target_out_dir/mksh_build")
+
+ cflags = [
+ "-flto",
+ "-fdata-sections",
+ "-ffunction-sections",
+ "-fstack-protector-strong",
+ "-D_FORTIFY_SOURCE=2",
+ "-DMKSH_DISABLE_TTY_WARNING",
+ "-DMKSH_SMALL=1",
+ "-DMKSH_ASSUME_UTF8=1",
+ "-DMKSH_SMALL_BUT_FAST=0",
+ "-DMKSH_S_NOVI=1",
+ "-DHAVE_CAN_FSTACKPROTECTORSTRONG=1",
+ "-DMKSH_LESS_CMDLINE_EDITING",
+ "-DMKSH_LESS_BUILDINS",
+ "-DMKSH_NO_INITCOMS",
+ "-DADAPT_FOR_LITEOS_A",
+ ]
+ if (defined(LOSCFG_COMPILER_CLANG_LLVM)) {
+ cflags += [ "-Oz" ]
+ } else {
+ cflags += [ "-O2" ]
+ }
+ cflags = string_join(" ", cflags)
+
+ extra_flags = string_join(" ", target_arch_cflags)
+ if (ohos_build_compiler == "clang") {
+ extra_flags += " --target=$target_triple"
+ extra_flags += " --sysroot=" + rebase_path(ohos_current_sysroot)
+ }
+
+ command = "rm -rf .git && env"
+ command += " CC=\"$ohos_current_cc_command\""
+ command += " TARGET_OS=OpenHarmony"
+ command += " CFLAGS=\"$cflags $extra_flags\""
+ command += " LDFLAGS=\"-Wl,--gc-sections -flto -O2\""
+ command += " sh ./Build.sh -r"
+
+ # copy mksh and .mkshrc to out dir
+ command += " && mkdir -p "
+ command += rebase_path("$root_out_dir/bin", exec_path)
+ command += " && install -D mksh "
+ command += rebase_path("$root_out_dir/unstripped/bin/mksh", exec_path)
+ command += " && $ohos_current_strip_command mksh -o "
+ command += rebase_path("$root_out_dir/bin/mksh", exec_path)
+ command += " && install -D .mkshrc "
+ command += rebase_path("$root_out_dir/etc/.mkshrc", exec_path)
+
+ outputs = [
+ "$root_out_dir/unstripped/bin/mksh",
+ "$root_out_dir/bin/mksh",
+ "$root_out_dir/etc/.mkshrc",
+ ]
+}
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/mksh/Makefile b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/mksh/Makefile
new file mode 100644
index 00000000..9bb177c9
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/mksh/Makefile
@@ -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.
+
+include $(APPSTOPDIR)/config.mk
+
+BUILD_DIR := $(OUT)/mksh_build
+BUILD_LOG := $(BUILD_DIR)/build.log
+
+CFLAGS += -DMKSH_DISABLE_TTY_WARNING -DMKSH_SMALL=1 -DMKSH_ASSUME_UTF8=1 -DMKSH_SMALL_BUT_FAST=0 -DMKSH_S_NOVI=1 -DHAVE_CAN_FSTACKPROTECTORSTRONG=1
+CFLAGS += -DMKSH_LESS_CMDLINE_EDITING -DMKSH_LESS_BUILDINS -DMKSH_NO_INITCOMS -DADAPT_FOR_LITEOS_A
+CFLAGS += -Wno-error
+LDFLAGS += -Wl,--gc-sections
+
+all:
+ifneq ($(wildcard $(BUILD_DIR)/Rebuild.sh),)
+ $(HIDE)echo "not clean, rebuilding now"
+ $(HIDE)cd $(BUILD_DIR) && sh ./Rebuild.sh > $(BUILD_LOG) 2>&1
+else
+ $(HIDE)mkdir -p $(BUILD_DIR)
+ $(HIDE)$(CP) $(LITEOSTHIRDPARTY)/mksh/. $(BUILD_DIR)
+ $(HIDE)cd $(BUILD_DIR) && CC="$(CC)" TARGET_OS=OpenHarmony CFLAGS="$(CFLAGS)" LDFLAGS="$(LDFLAGS)" sh ./Build.sh -r > $(BUILD_LOG) 2>&1
+endif
+ $(HIDE)mkdir -p $(OUT)/bin/ $(OUT)/etc/
+ $(HIDE)$(STRIP) $(BUILD_DIR)/mksh -o $(OUT)/bin/mksh
+ $(HIDE)$(CP) $(BUILD_DIR)/.mkshrc $(OUT)/etc/
+
+clean:
+ $(HIDE)$(RM) $(BUILD_DIR)
+
+.PHONY: all clean
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/perf/BUILD.gn b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/perf/BUILD.gn
new file mode 100644
index 00000000..c195375b
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/perf/BUILD.gn
@@ -0,0 +1,63 @@
+# 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("//kernel/liteos_a/liteos.gni")
+
+executable("perf") {
+ sources = [
+ "src/main.c",
+ "src/option.c",
+ "src/perf.c",
+ "src/perf_list.c",
+ "src/perf_record.c",
+ "src/perf_stat.c",
+ ]
+ include_dirs = [ "include" ]
+ defines = []
+
+ if (defined(LOSCFG_PERF_HW_PMU)) {
+ defines += [ "LOSCFG_PERF_HW_PMU" ]
+ }
+
+ if (defined(LOSCFG_PERF_TIMED_PMU)) {
+ defines += [ "LOSCFG_PERF_TIMED_PMU" ]
+ }
+
+ if (defined(LOSCFG_PERF_SW_PMU)) {
+ defines += [ "LOSCFG_PERF_SW_PMU" ]
+ }
+
+ if (defined(LOSCFG_FS_VFS)) {
+ defines += [ "LOSCFG_FS_VFS" ]
+ }
+
+ defines += [ "LOSCFG_PERF_BUFFER_SIZE=$LOSCFG_PERF_BUFFER_SIZE" ]
+
+ deps = [ "$LITEOSTHIRDPARTY/bounds_checking_function:libsec_static" ]
+}
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/perf/Makefile b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/perf/Makefile
new file mode 100644
index 00000000..dcaadb8a
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/perf/Makefile
@@ -0,0 +1,62 @@
+# 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 $(APPSTOPDIR)/config.mk
+
+APP_NAME := $(notdir $(shell pwd))
+
+SECUREC_DIR := $(LITEOSTHIRDPARTY)/bounds_checking_function
+
+LOCAL_SRCS = $(wildcard src/*.c)
+LOCAL_SRCS += $(wildcard $(SECUREC_DIR)/src/*.c)
+
+LOCAL_INCLUDE := \
+ -I include \
+ -I $(SECUREC_DIR)/include
+
+LOCAL_FLAGS += $(LOCAL_INCLUDE)
+
+ifeq ($(LOSCFG_PERF_HW_PMU), y)
+CFLAGS += -DLOSCFG_PERF_HW_PMU
+endif
+
+ifeq ($(LOSCFG_PERF_TIMED_PMU), y)
+CFLAGS += -DLOSCFG_PERF_TIMED_PMU
+endif
+
+ifeq ($(LOSCFG_PERF_SW_PMU), y)
+CFLAGS += -DLOSCFG_PERF_SW_PMU
+endif
+
+ifeq ($(LOSCFG_FS_VFS), y)
+CFLAGS += -DLOSCFG_FS_VFS
+endif
+
+CFLAGS += -DLOSCFG_PERF_BUFFER_SIZE=$(LOSCFG_PERF_BUFFER_SIZE)
+include $(APP)
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/perf/include/option.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/perf/include/option.h
new file mode 100644
index 00000000..e745bebf
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/perf/include/option.h
@@ -0,0 +1,81 @@
+/*
+ * 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 _OPTION_H
+#define _OPTION_H
+
+#include "perf.h"
+
+#ifdef __cplusplus
+#if __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+#define CMD_MAX_PARAMS 10
+typedef int (*CALL_BACK)(const char *argv);
+
+enum OptionType {
+ OPTION_TYPE_UINT,
+ OPTION_TYPE_STRING,
+ OPTION_TYPE_CALLBACK,
+};
+
+typedef struct {
+ int type;
+ const char *name;
+ const char **str;
+ unsigned int *value;
+ CALL_BACK cb;
+} PerfOption;
+
+typedef struct {
+ const char *path;
+ char *params[CMD_MAX_PARAMS];
+} SubCmd;
+
+#define OPTION_END() {.name = ""}
+#define OPTION_UINT(n, v) {.type = OPTION_TYPE_UINT, .name = (n), .value = (v)}
+#define OPTION_STRING(n, s) {.type = OPTION_TYPE_STRING, .name = (n), .str = (s)}
+#define OPTION_CALLBACK(n, c) {.type = OPTION_TYPE_CALLBACK, .name = (n), .cb = (c)}
+
+int ParseOptions(int argc, char **argv, PerfOption *opt, SubCmd *cmd);
+int ParseEvents(const char *argv, PerfEventConfig *eventsCfg, unsigned int *len);
+int ParseIds(const char *argv, int *arr, unsigned int *len);
+
+#ifdef __cplusplus
+#if __cplusplus
+}
+#endif
+#endif
+
+#endif /* _OPTION_H */
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/perf/include/perf.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/perf/include/perf.h
new file mode 100644
index 00000000..2eccb5e1
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/perf/include/perf.h
@@ -0,0 +1,163 @@
+/*
+ * 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 _PERF_H
+#define _PERF_H
+
+#include
+
+#ifdef __cplusplus
+#if __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+#define PERF_MAX_EVENT 7
+#define PERF_MAX_FILTER_TSKS 32
+
+#ifdef PERF_DEBUG
+#define printf_debug(fmt, ...) printf(fmt, ##__VA_ARGS__)
+#else
+#define printf_debug(fmt, ...)
+#endif
+
+/*
+ * Perf types
+ */
+enum PerfEventType {
+ PERF_EVENT_TYPE_HW, /* boards common hw events */
+ PERF_EVENT_TYPE_TIMED, /* hrtimer timed events */
+ PERF_EVENT_TYPE_SW, /* software trace events */
+ PERF_EVENT_TYPE_RAW, /* boards special hw events, see enum PmuEventType in corresponding arch headfile */
+
+ PERF_EVENT_TYPE_MAX
+};
+
+/*
+ * Common hardware pmu events
+ */
+enum PmuHwId {
+ PERF_COUNT_HW_CPU_CYCLES = 0, /* cpu cycle event */
+ PERF_COUNT_HW_INSTRUCTIONS, /* instruction event */
+ PERF_COUNT_HW_DCACHE_REFERENCES, /* dcache access event */
+ PERF_COUNT_HW_DCACHE_MISSES, /* dcache miss event */
+ PERF_COUNT_HW_ICACHE_REFERENCES, /* icache access event */
+ PERF_COUNT_HW_ICACHE_MISSES, /* icache miss event */
+ PERF_COUNT_HW_BRANCH_INSTRUCTIONS, /* software change of pc event */
+ PERF_COUNT_HW_BRANCH_MISSES, /* branch miss event */
+
+ PERF_COUNT_HW_MAX,
+};
+
+/*
+ * Common hrtimer timed events
+ */
+enum PmuTimedId {
+ PERF_COUNT_CPU_CLOCK = 0, /* hrtimer timed event */
+};
+
+/*
+ * Common software pmu events
+ */
+enum PmuSwId {
+ PERF_COUNT_SW_TASK_SWITCH = 1, /* task switch event */
+ PERF_COUNT_SW_IRQ_RESPONSE, /* irq response event */
+ PERF_COUNT_SW_MEM_ALLOC, /* memory alloc event */
+ PERF_COUNT_SW_MUX_PEND, /* mutex pend event */
+
+ PERF_COUNT_SW_MAX,
+};
+
+/*
+ * perf sample data types
+ * Config it through PerfConfigAttr->sampleType.
+ */
+enum PerfSampleType {
+ PERF_RECORD_CPU = 1U << 0, /* record current cpuid */
+ PERF_RECORD_TID = 1U << 1, /* record current task id */
+ PERF_RECORD_TYPE = 1U << 2, /* record event type */
+ PERF_RECORD_PERIOD = 1U << 3, /* record event period */
+ PERF_RECORD_TIMESTAMP = 1U << 4, /* record timestamp */
+ PERF_RECORD_IP = 1U << 5, /* record instruction pointer */
+ PERF_RECORD_CALLCHAIN = 1U << 6, /* record backtrace */
+ PERF_RECORD_PID = 1U << 7, /* record current process id */
+};
+
+/*
+ * perf configuration sub event information
+ *
+ * This structure is used to config specific events attributes.
+ */
+typedef struct {
+ unsigned int type; /* enum PerfEventType */
+ struct {
+ unsigned int eventId; /* the specific event corresponds to the PerfEventType */
+ unsigned int period; /* event period, for every "period"th occurrence of the event a
+ sample will be recorded */
+ } events[PERF_MAX_EVENT]; /* perf event list */
+ unsigned int eventsNr; /* total perf event number */
+ size_t predivided; /* whether to prescaler (once every 64 counts),
+ which only take effect on cpu cycle hardware event */
+} PerfEventConfig;
+
+/*
+ * perf configuration main information
+ *
+ * This structure is used to set perf sampling attributes, including events, tasks and other information.
+ */
+typedef struct {
+ PerfEventConfig eventsCfg; /* perf event config */
+ unsigned int taskIds[PERF_MAX_FILTER_TSKS]; /* perf task filter list (allowlist) */
+ unsigned int taskIdsNr; /* task numbers of task filter allowlist,
+ if set 0 perf will sample all tasks */
+ unsigned int processIds[PERF_MAX_FILTER_TSKS]; /* perf process filter list (allowlist) */
+ unsigned int processIdsNr; /* process numbers of process filter allowlist,
+ if set 0 perf will sample all processes */
+ unsigned int sampleType; /* type of data to sample defined in PerfSampleType */
+ size_t needSample; /* whether to sample data */
+} PerfConfigAttr;
+
+void PerfUsage(void);
+void PerfDumpAttr(PerfConfigAttr *attr);
+int PerfConfig(int fd, PerfConfigAttr *attr);
+void PerfStart(int fd, size_t sectionId);
+void PerfStop(int fd);
+ssize_t PerfRead(int fd, char *buf, size_t size);
+void PerfPrintBuffer(const char *buf, ssize_t num);
+
+#ifdef __cplusplus
+#if __cplusplus
+}
+#endif
+#endif
+
+#endif /* _PERF_H */
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/perf/include/perf_list.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/perf/include/perf_list.h
new file mode 100644
index 00000000..a65e9d70
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/perf/include/perf_list.h
@@ -0,0 +1,57 @@
+/*
+ * 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 _PERF_LIST_H
+#define _PERF_LIST_H
+
+#ifdef __cplusplus
+#if __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+typedef struct {
+ const char *name;
+ int event;
+ int type;
+} PerfEvent;
+
+extern const PerfEvent g_events[];
+void PerfList(void);
+
+#ifdef __cplusplus
+#if __cplusplus
+}
+#endif
+#endif
+
+#endif /* _PERF_LIST_H */
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/perf/include/perf_record.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/perf/include/perf_record.h
new file mode 100644
index 00000000..b218eb75
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/perf/include/perf_record.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 _PERF_RECORD_H
+#define _PERF_RECORD_H
+
+#ifdef __cplusplus
+#if __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+void PerfRecord(int fd, int argc, char **argv);
+
+#ifdef __cplusplus
+#if __cplusplus
+}
+#endif
+#endif
+
+#endif /* _PERF_RECORD_H */
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/perf/include/perf_stat.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/perf/include/perf_stat.h
new file mode 100644
index 00000000..ad2a456c
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/perf/include/perf_stat.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 _PERF_STAT_H
+#define _PERF_STAT_H
+
+#ifdef __cplusplus
+#if __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+void PerfStat(int fd, int argc, char **argv);
+
+#ifdef __cplusplus
+#if __cplusplus
+}
+#endif
+#endif
+
+#endif /* _PERF_STAT_H */
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/perf/src/main.c b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/perf/src/main.c
new file mode 100644
index 00000000..8fb841fa
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/perf/src/main.c
@@ -0,0 +1,90 @@
+/*
+ * 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
+#include "perf.h"
+#include "perf_list.h"
+#include "perf_stat.h"
+#include "perf_record.h"
+
+int main(int argc, char **argv)
+{
+#define TWO_ARGS 2
+#define THREE_ARGS 3
+ int fd = open("/dev/perf", O_RDWR);
+ if (fd == -1) {
+ printf("Perf open failed.\n");
+ exit(EXIT_FAILURE);
+ }
+
+ if (argc == 1) {
+ PerfUsage();
+ } else if ((argc == TWO_ARGS) && strcmp(argv[1], "start") == 0) {
+ PerfStart(fd, 0);
+ } else if ((argc == THREE_ARGS) && strcmp(argv[1], "start") == 0) {
+ size_t id = strtoul(argv[THREE_ARGS - 1], NULL, 0);
+ PerfStart(fd, id);
+ } else if ((argc == TWO_ARGS) && strcmp(argv[1], "stop") == 0) {
+ PerfStop(fd);
+ } else if ((argc == THREE_ARGS) && strcmp(argv[1], "read") == 0) {
+ size_t size = strtoul(argv[THREE_ARGS - 1], NULL, 0);
+ if (size <= 0) {
+ goto EXIT:
+ }
+
+ char *buf = (char *)malloc(size);
+ if (buf != NULL) {
+ int len = PerfRead(fd, buf, size);
+ PerfPrintBuffer(buf, len);
+ free(buf);
+ buf = NULL;
+ }
+ } else if ((argc == TWO_ARGS) && strcmp(argv[1], "list") == 0) {
+ PerfList();
+ } else if ((argc >= THREE_ARGS) && strcmp(argv[1], "stat") == 0) {
+ PerfStat(fd, argc, argv);
+ } else if ((argc >= THREE_ARGS) && strcmp(argv[1], "record") == 0) {
+ PerfRecord(fd, argc, argv);
+ } else {
+ printf("Unsupported perf command.\n");
+ PerfUsage();
+ }
+
+EXIT:
+ close(fd);
+ return 0;
+}
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/perf/src/option.c b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/perf/src/option.c
new file mode 100644
index 00000000..40ef3430
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/perf/src/option.c
@@ -0,0 +1,182 @@
+/*
+ * 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 "option.h"
+#include "perf_list.h"
+
+static int ParseOption(char **argv, int *index, PerfOption *opts)
+{
+ int ret = 0;
+ const char *str = NULL;
+
+ while ((opts->name != NULL) && (*opts->name != 0)) {
+ if (strcmp(argv[*index], opts->name) == 0) {
+ switch (opts->type) {
+ case OPTION_TYPE_UINT:
+ *opts->value = strtoul(argv[++(*index)], NULL, 0);
+ break;
+ case OPTION_TYPE_STRING:
+ *opts->str = argv[++(*index)];
+ break;
+ case OPTION_TYPE_CALLBACK:
+ str = argv[++(*index)];
+ if ((*opts->cb)(str) != 0) {
+ printf("parse error\n");
+ ret = -1;
+ }
+ break;
+ default:
+ printf("invalid option\n");
+ ret = -1;
+ break;
+ }
+ return ret;
+ }
+ opts++;
+ }
+
+ return -1;
+}
+
+int ParseOptions(int argc, char **argv, PerfOption *opts, SubCmd *cmd)
+{
+ int i;
+ int index = 0;
+
+ while ((index < argc) && (argv[index] != NULL) && (*argv[index] == '-')) {
+ if (ParseOption(argv, &index, opts) != 0) {
+ return -1;
+ }
+ index++;
+ }
+
+ if ((index < argc) && (argv[index] != NULL)) {
+ cmd->path = argv[index];
+ cmd->params[0] = argv[index];
+ index++;
+ } else {
+ printf("no subcmd to execute\n");
+ return -1;
+ }
+
+ for (i = 1; (index < argc) && (i < CMD_MAX_PARAMS); index++, i++) {
+ cmd->params[i] = argv[index];
+ }
+ printf_debug("subcmd = %s\n", cmd->path);
+ for (int j = 0; j < i; j++) {
+ printf_debug("paras[%d]:%s\n", j, cmd->params[j]);
+ }
+ return 0;
+}
+
+int ParseIds(const char *argv, int *arr, unsigned int *len)
+{
+ int res, ret;
+ unsigned int index = 0;
+ char *sp = NULL;
+ char *this = NULL;
+ char *list = strdup(argv);
+
+ if (list == NULL) {
+ printf("no memory for ParseIds\n");
+ return -1;
+ }
+
+ sp = strtok_r(list, ",", &this);
+ while (sp) {
+ res = strtoul(sp, NULL, 0);
+ if (res < 0) {
+ ret = -1;
+ goto EXIT;
+ }
+ arr[index++] = res;
+ sp = strtok_r(NULL, ",", &this);
+ }
+ *len = index;
+ ret = 0;
+EXIT:
+ free(list);
+ return ret;
+}
+
+static inline const PerfEvent *StrToEvent(const char *str)
+{
+ const PerfEvent *evt = &g_events[0];
+
+ for (; evt->event != -1; evt++) {
+ if (strcmp(str, evt->name) == 0) {
+ return evt;
+ }
+ }
+ return NULL;
+}
+
+int ParseEvents(const char *argv, PerfEventConfig *eventsCfg, unsigned int *len)
+{
+ int ret;
+ unsigned int index = 0;
+ const PerfEvent *event = NULL;
+ char *sp = NULL;
+ char *this = NULL;
+ char *list = strdup(argv);
+
+ if (list == NULL) {
+ printf("no memory for ParseEvents\n");
+ return -1;
+ }
+
+ sp = strtok_r(list, ",", &this);
+ while (sp) {
+ event = StrToEvent(sp);
+ if (event == NULL) {
+ ret = -1;
+ goto EXIT;
+ }
+
+ if (index == 0) {
+ eventsCfg->type = event->type;
+ } else if (eventsCfg->type != event->type) {
+ printf("events type must be same\n");
+ ret = -1;
+ goto EXIT;
+ }
+ eventsCfg->events[index].eventId = event->event;
+ sp = strtok_r(NULL, ",", &this);
+ index++;
+ }
+ *len = index;
+ ret = 0;
+EXIT:
+ free(list);
+ return ret;
+}
\ No newline at end of file
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/perf/src/perf.c b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/perf/src/perf.c
new file mode 100644
index 00000000..aeafec0e
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/perf/src/perf.c
@@ -0,0 +1,136 @@
+/*
+ * 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 "perf.h"
+
+#define PERF_IOC_MAGIC 'T'
+#define PERF_START _IO(PERF_IOC_MAGIC, 1)
+#define PERF_STOP _IO(PERF_IOC_MAGIC, 2)
+
+void PerfUsage(void)
+{
+ printf("\nUsage: ./perf start [id]. Start perf.\n");
+ printf("\nUsage: ./perf stop. Stop perf.\n");
+ printf("\nUsage: ./perf read . Read nBytes raw data from perf buffer and print out.\n");
+ printf("\nUsage: ./perf list. List events to be used in -e.\n");
+ printf("\nUsage: ./perf stat/record [option] . \n"
+ "-e, event selector. use './perf list' to list available events.\n"
+ "-p, event period.\n"
+ "-o, perf data output filename.\n"
+ "-t, taskId filter(allowlist), if not set perf will sample all tasks.\n"
+ "-s, type of data to sample defined in PerfSampleType los_perf.h.\n"
+ "-P, processId filter(allowlist), if not set perf will sample all processes.\n"
+ "-d, whether to prescaler (once every 64 counts),"
+ "which only take effect on cpu cycle hardware event.\n"
+ );
+}
+
+static void PerfSetPeriod(PerfConfigAttr *attr)
+{
+ int i;
+ for (i = 1; i < attr->eventsCfg.eventsNr; i++) {
+ attr->eventsCfg.events[i].period = attr->eventsCfg.events[0].period;
+ }
+}
+
+void PerfPrintBuffer(const char *buf, ssize_t num)
+{
+#define BYTES_PER_LINE 4
+ ssize_t i;
+ for (i = 0; i < num; i++) {
+ printf(" %02x", (unsigned char)buf[i]);
+ if (((i + 1) % BYTES_PER_LINE) == 0) {
+ printf("\n");
+ }
+ }
+ printf("\n");
+}
+
+void PerfDumpAttr(PerfConfigAttr *attr)
+{
+ int i;
+ printf_debug("attr->type: %d\n", attr->eventsCfg.type);
+ for (i = 0; i < attr->eventsCfg.eventsNr; i++) {
+ printf_debug("attr->events[%d]: %d, 0x%x\n", i, attr->eventsCfg.events[i].eventId,
+ attr->eventsCfg.events[i].period);
+ }
+ printf_debug("attr->predivided: %d\n", attr->eventsCfg.predivided);
+ printf_debug("attr->sampleType: 0x%x\n", attr->sampleType);
+
+ for (i = 0; i < attr->taskIdsNr; i++) {
+ printf_debug("attr->taskIds[%d]: %d\n", i, attr->taskIds[i]);
+ }
+
+ for (i = 0; i < attr->processIdsNr; i++) {
+ printf_debug("attr->processIds[%d]: %d\n", i, attr->processIds[i]);
+ }
+
+ printf_debug("attr->needSample: %d\n", attr->needSample);
+}
+
+
+void PerfStart(int fd, size_t sectionId)
+{
+ (void)ioctl(fd, PERF_START, sectionId);
+}
+
+void PerfStop(int fd)
+{
+ (void)ioctl(fd, PERF_STOP, NULL);
+}
+
+int PerfConfig(int fd, PerfConfigAttr *attr)
+{
+ if (attr == NULL) {
+ return -1;
+ }
+ PerfSetPeriod(attr);
+ PerfDumpAttr(attr);
+ return write(fd, attr, sizeof(PerfConfigAttr));
+}
+
+ssize_t PerfRead(int fd, char *buf, size_t size)
+{
+ ssize_t len;
+ if (buf == NULL) {
+ printf("Read buffer is null.\n");
+ return 0;
+ }
+
+ len = read(fd, buf, size);
+ return len;
+}
\ No newline at end of file
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/perf/src/perf_list.c b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/perf/src/perf_list.c
new file mode 100644
index 00000000..73e6a6e8
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/perf/src/perf_list.c
@@ -0,0 +1,129 @@
+/*
+ * 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 "perf.h"
+#include "perf_list.h"
+
+static const char *g_eventTypeStr[] = {
+ "[Hardware event]",
+ "[Timed event]",
+ "[Software event]",
+};
+
+const PerfEvent g_events[] = {
+#ifdef LOSCFG_PERF_HW_PMU
+ {
+ .name = "cycles",
+ .event = PERF_COUNT_HW_CPU_CYCLES,
+ .type = PERF_EVENT_TYPE_HW,
+ },
+ {
+ .name = "instruction",
+ .event = PERF_COUNT_HW_INSTRUCTIONS,
+ .type = PERF_EVENT_TYPE_HW,
+ },
+ {
+ .name = "dcache",
+ .event = PERF_COUNT_HW_DCACHE_REFERENCES,
+ .type = PERF_EVENT_TYPE_HW,
+ },
+ {
+ .name = "dcache-miss",
+ .event = PERF_COUNT_HW_DCACHE_MISSES,
+ .type = PERF_EVENT_TYPE_HW,
+ },
+ {
+ .name = "icache",
+ .event = PERF_COUNT_HW_ICACHE_REFERENCES,
+ .type = PERF_EVENT_TYPE_HW,
+ },
+ {
+ .name = "icache-miss",
+ .event = PERF_COUNT_HW_ICACHE_MISSES,
+ .type = PERF_EVENT_TYPE_HW,
+ },
+ {
+ .name = "branch",
+ .event = PERF_COUNT_HW_BRANCH_INSTRUCTIONS,
+ .type = PERF_EVENT_TYPE_HW,
+ },
+ {
+ .name = "branch-miss",
+ .event = PERF_COUNT_HW_BRANCH_MISSES,
+ .type = PERF_EVENT_TYPE_HW,
+ },
+#endif
+#ifdef LOSCFG_PERF_TIMED_PMU
+ {
+ .name = "clock",
+ .event = PERF_COUNT_CPU_CLOCK,
+ .type = PERF_EVENT_TYPE_TIMED,
+ },
+#endif
+#ifdef LOSCFG_PERF_SW_PMU
+ {
+ .name = "task-switch",
+ .event = PERF_COUNT_SW_TASK_SWITCH,
+ .type = PERF_EVENT_TYPE_SW,
+ },
+ {
+ .name = "irq-in",
+ .event = PERF_COUNT_SW_IRQ_RESPONSE,
+ .type = PERF_EVENT_TYPE_SW,
+ },
+ {
+ .name = "mem-alloc",
+ .event = PERF_COUNT_SW_MEM_ALLOC,
+ .type = PERF_EVENT_TYPE_SW,
+ },
+ {
+ .name = "mux-pend",
+ .event = PERF_COUNT_SW_MUX_PEND,
+ .type = PERF_EVENT_TYPE_SW,
+ },
+#endif
+ {
+ .name = "",
+ .event = -1,
+ .type = PERF_EVENT_TYPE_MAX,
+ }
+};
+
+void PerfList(void)
+{
+ const PerfEvent *evt = &g_events[0];
+ printf("\n");
+ for (; evt->event != -1; evt++) {
+ printf("\t %-25s%30s\n", evt->name, g_eventTypeStr[evt->type]);
+ }
+ printf("\n");
+}
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/perf/src/perf_record.c b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/perf/src/perf_record.c
new file mode 100644
index 00000000..98a64155
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/perf/src/perf_record.c
@@ -0,0 +1,203 @@
+/*
+ * 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
+
+#ifdef LOSCFG_FS_VFS
+#include
+#include
+#endif
+
+#include "perf.h"
+#include "option.h"
+#include "perf_record.h"
+
+#define PERF_FILE_MODE 0644
+static PerfConfigAttr g_recordAttr;
+static const char *g_savePath = "/storage/data/perf.data";
+
+static inline int GetEvents(const char *argv)
+{
+ return ParseEvents(argv, &g_recordAttr.eventsCfg, &g_recordAttr.eventsCfg.eventsNr);
+}
+
+static inline int GetTids(const char *argv)
+{
+ return ParseIds(argv, (int *)g_recordAttr.taskIds, &g_recordAttr.taskIdsNr);
+}
+
+static inline int GetPids(const char *argv)
+{
+ return ParseIds(argv, (int *)g_recordAttr.processIds, &g_recordAttr.processIdsNr);
+}
+
+static PerfOption g_recordOpts[] = {
+ OPTION_CALLBACK("-e", GetEvents),
+ OPTION_CALLBACK("-t", GetTids),
+ OPTION_CALLBACK("-P", GetPids),
+ OPTION_STRING("-o", &g_savePath),
+ OPTION_UINT("-p", &g_recordAttr.eventsCfg.events[0].period),
+ OPTION_UINT("-s", &g_recordAttr.sampleType),
+ OPTION_UINT("-d", &g_recordAttr.eventsCfg.predivided),
+};
+
+static int PerfRecordAttrInit(void)
+{
+ PerfConfigAttr attr = {
+ .eventsCfg = {
+#ifdef LOSCFG_PERF_HW_PMU
+ .type = PERF_EVENT_TYPE_HW,
+ .events = {
+ [0] = {PERF_COUNT_HW_CPU_CYCLES, 0xFFFF},
+ },
+#elif defined LOSCFG_PERF_TIMED_PMU
+ .type = PERF_EVENT_TYPE_TIMED,
+ .events = {
+ [0] = {PERF_COUNT_CPU_CLOCK, 100},
+ },
+#elif defined LOSCFG_PERF_SW_PMU
+ .type = PERF_EVENT_TYPE_SW,
+ .events = {
+ [0] = {PERF_COUNT_SW_TASK_SWITCH, 1},
+ },
+#endif
+ .eventsNr = 1, /* 1 event */
+ .predivided = 0,
+ },
+ .taskIds = {0},
+ .taskIdsNr = 0,
+ .processIds = {0},
+ .processIdsNr = 0,
+ .needSample = 1,
+ .sampleType = PERF_RECORD_IP | PERF_RECORD_CALLCHAIN,
+ };
+
+ return memcpy_s(&g_recordAttr, sizeof(PerfConfigAttr), &attr, sizeof(PerfConfigAttr)) != EOK ? -1 : 0;
+}
+
+ssize_t PerfWriteFile(const char *filePath, const char *buf, ssize_t bufSize)
+{
+#ifdef LOSCFG_FS_VFS
+ int fd = -1;
+ ssize_t totalToWrite = bufSize;
+ ssize_t totalWrite = 0;
+
+ if (filePath == NULL || buf == NULL || bufSize == 0) {
+ return -1;
+ }
+
+ fd = open(filePath, O_CREAT | O_RDWR | O_TRUNC, PERF_FILE_MODE);
+ if (fd < 0) {
+ printf("create file [%s] failed, fd: %d, %s!\n", filePath, fd, strerror(errno));
+ return -1;
+ }
+ while (totalToWrite > 0) {
+ ssize_t writeThisTime = write(fd, buf, totalToWrite);
+ if (writeThisTime < 0) {
+ printf("failed to write file [%s], %s!\n", filePath, strerror(errno));
+ (void)close(fd);
+ return -1;
+ }
+ buf += writeThisTime;
+ totalToWrite -= writeThisTime;
+ totalWrite += writeThisTime;
+ }
+ (void)fsync(fd);
+ (void)close(fd);
+
+ return (totalWrite == bufSize) ? 0 : -1;
+#else
+ (void)filePath;
+ PerfPrintBuffer(buf, bufSize);
+ return 0;
+#endif
+}
+
+void PerfRecord(int fd, int argc, char **argv)
+{
+ int ret;
+ int child;
+ char *buf;
+ ssize_t len;
+ SubCmd cmd = {0};
+
+ if (argc < 3) { /* perf record argc is at least 3 */
+ return;
+ }
+
+ ret = PerfRecordAttrInit();
+ if (ret != 0) {
+ printf("perf record attr init failed\n");
+ return;
+ }
+
+ ret = ParseOptions(argc - 2, &argv[2], g_recordOpts, &cmd); /* parse option and cmd begin at index 2 */
+ if (ret != 0) {
+ printf("parse error\n");
+ return;
+ }
+
+ ret = PerfConfig(fd, &g_recordAttr);
+ if (ret != 0) {
+ printf("perf config failed\n");
+ return;
+ }
+
+ PerfStart(fd, 0);
+ child = fork();
+ if (child < 0) {
+ printf("fork error\n");
+ PerfStop(fd);
+ return;
+ } else if (child == 0) {
+ (void)execve(cmd.path, cmd.params, NULL);
+ exit(0);
+ }
+
+ waitpid(child, 0, 0);
+ PerfStop(fd);
+
+ buf = (char *)malloc(LOSCFG_PERF_BUFFER_SIZE);
+ if (buf == NULL) {
+ printf("no memory for read perf 0x%x\n", LOSCFG_PERF_BUFFER_SIZE);
+ return;
+ }
+ len = PerfRead(fd, buf, LOSCFG_PERF_BUFFER_SIZE);
+ ret = PerfWriteFile(g_savePath, buf, len);
+ if (ret == 0) {
+ printf("save perf data success at %s\n", g_savePath);
+ } else {
+ printf("save perf data failed at %s\n", g_savePath);
+ }
+ free(buf);
+}
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/perf/src/perf_stat.c b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/perf/src/perf_stat.c
new file mode 100644
index 00000000..a1155048
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/perf/src/perf_stat.c
@@ -0,0 +1,149 @@
+/*
+ * 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 "perf.h"
+#include "option.h"
+#include "perf_stat.h"
+
+static PerfConfigAttr g_statAttr;
+
+static inline int GetEvents(const char *argv)
+{
+ return ParseEvents(argv, &g_statAttr.eventsCfg, &g_statAttr.eventsCfg.eventsNr);
+}
+
+static inline int GetTids(const char *argv)
+{
+ return ParseIds(argv, (int *)g_statAttr.taskIds, &g_statAttr.taskIdsNr);
+}
+
+static inline int GetPids(const char *argv)
+{
+ return ParseIds(argv, (int *)g_statAttr.processIds, &g_statAttr.processIdsNr);
+}
+
+static PerfOption g_statOpts[] = {
+ OPTION_CALLBACK("-e", GetEvents),
+ OPTION_CALLBACK("-t", GetTids),
+ OPTION_CALLBACK("-P", GetPids),
+ OPTION_UINT("-p", &g_statAttr.eventsCfg.events[0].period),
+ OPTION_UINT("-s", &g_statAttr.sampleType),
+ OPTION_UINT("-d", &g_statAttr.eventsCfg.predivided),
+};
+
+static int PerfStatAttrInit(void)
+{
+ PerfConfigAttr attr = {
+ .eventsCfg = {
+#ifdef LOSCFG_PERF_HW_PMU
+ .type = PERF_EVENT_TYPE_HW,
+ .events = {
+ [0] = {PERF_COUNT_HW_CPU_CYCLES, 0xFFFF},
+ [1] = {PERF_COUNT_HW_INSTRUCTIONS, 0xFFFFFF00},
+ [2] = {PERF_COUNT_HW_ICACHE_REFERENCES, 0xFFFF},
+ [3] = {PERF_COUNT_HW_DCACHE_REFERENCES, 0xFFFF},
+ },
+ .eventsNr = 4, /* 4 events */
+#elif defined LOSCFG_PERF_TIMED_PMU
+ .type = PERF_EVENT_TYPE_TIMED,
+ .events = {
+ [0] = {PERF_COUNT_CPU_CLOCK, 100},
+ },
+ .eventsNr = 1, /* 1 event */
+#elif defined LOSCFG_PERF_SW_PMU
+ .type = PERF_EVENT_TYPE_SW,
+ .events = {
+ [0] = {PERF_COUNT_SW_TASK_SWITCH, 1},
+ [1] = {PERF_COUNT_SW_IRQ_RESPONSE, 1},
+ [2] = {PERF_COUNT_SW_MEM_ALLOC, 1},
+ [3] = {PERF_COUNT_SW_MUX_PEND, 1},
+ },
+ .eventsNr = 4, /* 4 events */
+#endif
+ .predivided = 0,
+ },
+ .taskIds = {0},
+ .taskIdsNr = 0,
+ .processIds = {0},
+ .processIdsNr = 0,
+ .needSample = 0,
+ .sampleType = 0,
+ };
+
+ return memcpy_s(&g_statAttr, sizeof(PerfConfigAttr), &attr, sizeof(PerfConfigAttr)) != EOK ? -1 : 0;
+}
+
+void PerfStat(int fd, int argc, char **argv)
+{
+ int ret;
+ int child;
+ SubCmd cmd = {0};
+
+ if (argc < 3) { /* perf stat argc is at least 3 */
+ return;
+ }
+
+ ret = PerfStatAttrInit();
+ if (ret != 0) {
+ printf("perf stat attr init failed\n");
+ return;
+ }
+
+ ret = ParseOptions(argc - 2, &argv[2], g_statOpts, &cmd); /* parse option and cmd begin at index 2 */
+ if (ret != 0) {
+ printf("parse error\n");
+ return;
+ }
+
+ ret = PerfConfig(fd, &g_statAttr);
+ if (ret != 0) {
+ printf("perf config failed\n");
+ return;
+ }
+
+ PerfStart(fd, 0);
+ child = fork();
+ if (child < 0) {
+ printf("fork error\n");
+ goto EXIT;
+ } else if (child == 0) {
+ (void)execve(cmd.path, cmd.params, NULL);
+ exit(0);
+ }
+
+ (void)waitpid(child, 0, 0);
+EXIT:
+ PerfStop(fd);
+}
+
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/shell/BUILD.gn b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/shell/BUILD.gn
new file mode 100644
index 00000000..d7052575
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/shell/BUILD.gn
@@ -0,0 +1,44 @@
+# 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("//kernel/liteos_a/liteos.gni")
+
+executable("shell") {
+ sources = [
+ "builtin/cd.c",
+ "src/main.c",
+ "src/shcmd.c",
+ "src/shcmdparse.c",
+ "src/shmsg.c",
+ ]
+
+ deps = [ "$LITEOSTHIRDPARTY/bounds_checking_function:libsec_static" ]
+
+ include_dirs = [ "include" ]
+}
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/shell/Makefile b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/shell/Makefile
new file mode 100644
index 00000000..16737994
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/shell/Makefile
@@ -0,0 +1,45 @@
+# 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 $(APPSTOPDIR)/config.mk
+
+APP_NAME := $(notdir $(shell pwd))
+
+SECUREC_DIR := $(LITEOSTHIRDPARTY)/bounds_checking_function
+
+LOCAL_SRCS = $(wildcard src/*.c builtin/*.c)
+LOCAL_SRCS += $(wildcard $(SECUREC_DIR)/src/*.c)
+
+LOCAL_INCLUDE := \
+ -I include \
+ -I $(SECUREC_DIR)/include
+
+LOCAL_FLAGS += $(LOCAL_INCLUDE)
+
+include $(APP)
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/shell/builtin/cd.c b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/shell/builtin/cd.c
new file mode 100644
index 00000000..88e3eb93
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/shell/builtin/cd.c
@@ -0,0 +1,54 @@
+/*
+ * 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.
+ */
+
+#define _GNU_SOURCE
+
+#include "unistd.h"
+#include "shcmd.h"
+#include "sherr.h"
+
+
+int Chdir(const char *tgtDir)
+{
+ int ret;
+
+ if (!tgtDir) {
+ return SH_ERROR;
+ }
+
+ ret = chdir(tgtDir);
+ if (ret == 0) {
+ ret = OsShellSetWorkingDirectory(tgtDir, strlen(tgtDir) + 1); /* 1: the length of '\0' */
+ }
+
+ return ret;
+}
+
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/shell/include/shcmd.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/shell/include/shcmd.h
new file mode 100644
index 00000000..d1ab8b1c
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/shell/include/shcmd.h
@@ -0,0 +1,73 @@
+/*
+ * 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 _SHCMD_H
+#define _SHCMD_H
+
+#include "string.h"
+#include "stdlib.h"
+#include "shell_list.h"
+#include "shcmdparse.h"
+#include "sherr.h"
+#include "show.h"
+
+#ifdef __cplusplus
+#if __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+typedef struct {
+ unsigned int count;
+ SH_List list;
+ char cmdString[0];
+} CmdKeyLink;
+
+#define NEED_NEW_LINE(timesPrint, lineCap) ((timesPrint) % (lineCap) == 0)
+#define SCREEN_IS_FULL(timesPrint, lineCap) ((timesPrint) >= ((lineCap) * DEFAULT_SCREEN_HEIGHT))
+
+extern unsigned int OsCmdExec(CmdParsed *cmdParsed, char *cmdStr);
+extern unsigned int OsCmdKeyShift(const char *cmdKey, char *cmdOut, unsigned int size);
+extern int OsTabCompletion(char *cmdKey, unsigned int *len);
+extern void OsShellCmdPush(const char *string, CmdKeyLink *cmdKeyLink);
+extern void OsShellHistoryShow(unsigned int value, ShellCB *shellCB);
+extern unsigned int OsShellKeyInit(ShellCB *shellCB);
+extern void OsShellKeyDeInit(CmdKeyLink *cmdKeyLink);
+extern int OsShellSetWorkingDirectory(const char *dir, size_t len);
+
+#ifdef __cplusplus
+#if __cplusplus
+}
+#endif
+#endif
+
+#endif /* _SHCMD_H */
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/shell/include/shcmdparse.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/shell/include/shcmdparse.h
new file mode 100644
index 00000000..94e8f89d
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/shell/include/shcmdparse.h
@@ -0,0 +1,65 @@
+/*
+ * 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 _SHCMDPARSE_H
+#define _SHCMDPARSE_H
+
+#include "string.h"
+#include "show.h"
+
+#ifdef __cplusplus
+#if __cplusplus
+extern "C" {
+#endif
+#endif
+
+/*
+ * Description: the info struct after cmd parser
+ */
+typedef struct {
+ unsigned int paramCnt; /* count of para */
+ CmdType cmdType; /* cmd type, judge cmd keyword */
+ char cmdKeyword[CMD_KEY_LEN]; /* cmd keyword str */
+ char *paramArray[CMD_MAX_PARAS];
+} CmdParsed;
+
+extern unsigned int OsCmdParse(char *cmdStr, CmdParsed *cmdParsed);
+extern char *OsCmdParseStrdup(const char *str);
+extern unsigned int OsCmdParseOneToken(CmdParsed *cmdParsed, unsigned int index, const char *token);
+extern unsigned int OsCmdTokenSplit(char *cmdStr, char split, CmdParsed *cmdParsed);
+
+#ifdef __cplusplus
+#if __cplusplus
+}
+#endif
+#endif
+
+#endif /* _SHCMDPARSE_H */
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/shell/include/shell.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/shell/include/shell.h
new file mode 100644
index 00000000..ebc94e0d
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/shell/include/shell.h
@@ -0,0 +1,109 @@
+/*
+ * 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 _SHELL_H
+#define _SHELL_H
+
+#include "pthread.h"
+#include "semaphore.h"
+
+#ifdef __cplusplus
+#if __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+/* Max len of show str */
+#define SHOW_MAX_LEN CMD_MAX_LEN
+
+#define SHELL_PROCESS_PRIORITY_INIT 15
+
+#define PATH_MAX 256
+#define CMD_MAX_PARAS 32
+#define CMD_KEY_LEN 16U
+#define CMD_MAX_LEN (256U + CMD_KEY_LEN)
+#define CMD_KEY_NUM 32
+#define CMD_HISTORY_LEN 10
+#define CMD_MAX_PATH 256
+#define DEFAULT_SCREEN_WIDTH 80
+#define DEFAULT_SCREEN_HEIGHT 24
+
+#define SWITCH_QUOTES_STATUS(qu) do { \
+ if ((qu) == TRUE) { \
+ (qu) = FALSE; \
+ } else { \
+ (qu) = TRUE; \
+ } \
+} while (0)
+
+#define QUOTES_STATUS_CLOSE(qu) ((qu) == FALSE)
+#define QUOTES_STATUS_OPEN(qu) ((qu) == TRUE)
+
+
+typedef struct {
+ unsigned int consoleID;
+ pthread_t shellTaskHandle;
+ pthread_t shellEntryHandle;
+ void *cmdKeyLink;
+ void *cmdHistoryKeyLink;
+ void *cmdMaskKeyLink;
+ unsigned int shellBufOffset;
+ unsigned int shellKeyType;
+ sem_t shellSem;
+ pthread_mutex_t keyMutex;
+ pthread_mutex_t historyMutex;
+ char shellBuf[SHOW_MAX_LEN];
+ char shellWorkingDirectory[PATH_MAX];
+} ShellCB;
+
+/* All support cmd types */
+typedef enum {
+ CMD_TYPE_SHOW = 0,
+ CMD_TYPE_STD = 1,
+ CMD_TYPE_EX = 2,
+ CMD_TYPE_BUTT
+} CmdType;
+
+typedef enum {
+ CMD_KEY_UP = 0,
+ CMD_KEY_DOWN = 1,
+ CMD_KEY_RIGHT = 2,
+ CMD_KEY_LEFT = 4,
+ CMD_KEY_BUTT
+} CmdKeyDirection;
+
+#ifdef __cplusplus
+#if __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+#endif /* _SHELL_H */
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/shell/include/shell_list.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/shell/include/shell_list.h
new file mode 100644
index 00000000..25030234
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/shell/include/shell_list.h
@@ -0,0 +1,574 @@
+/*
+ * 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 _SHELL_LIST_H
+#define _SHELL_LIST_H
+
+#include "sherr.h"
+#include "stdint.h"
+
+#ifdef __cplusplus
+#if __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+typedef size_t bool;
+
+/**
+ * @ingroup shell_list
+ * Structure of a node in a doubly linked list.
+ */
+typedef struct SH_List {
+ struct SH_List *pstPrev; /**< Current node's pointer to the previous node */
+ struct SH_List *pstNext; /**< Current node's pointer to the next node */
+} SH_List;
+
+/**
+ * @ingroup shell_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:
+ *
shell_list.h: the header file that contains the API declaration.
+ * @see
+ */
+static inline void SH_ListInit(SH_List *list)
+{
+ list->pstNext = list;
+ list->pstPrev = list;
+}
+
+/**
+ * @ingroup shell_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.
shell_list.h: the header file that contains the API declaration.
+ * @see
+ */
+#define SH_LIST_LAST(object) ((object)->pstPrev)
+
+/**
+ * @ingroup shell_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:
+ *
shell_list.h: the header file that contains the API declaration.
+ * @see SH_ListDelete
+ */
+static inline void SH_ListAdd(SH_List *list, SH_List *node)
+{
+ node->pstNext = list->pstNext;
+ node->pstPrev = list;
+ list->pstNext->pstPrev = node;
+ list->pstNext = node;
+}
+
+/**
+ * @ingroup shell_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:
+ *
shell_list.h: the header file that contains the API declaration.
+ * @see SH_ListAdd | SH_ListHeadInsert
+ */
+static inline void SH_ListTailInsert(SH_List *list, SH_List *node)
+{
+ if ((list == NULL) || (node == NULL)) {
+ return;
+ }
+
+ SH_ListAdd(list->pstPrev, node);
+}
+
+/**
+ * @ingroup shell_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:
+ *
shell_list.h: the header file that contains the API declaration.
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 list.
+ *
+ * @retval TRUE The doubly linked list is empty.
+ * @retval FALSE The doubly linked list is not empty.
+ * @par Dependency:
+ *
shell_list.h: the header file that contains the API declaration.
+ * @see
+ */
+static inline bool SH_ListEmpty(SH_List *list)
+{
+ if (list == NULL) {
+ return FALSE;
+ }
+
+ return (bool)(list->pstNext == list);
+}
+
+/**
+ * @ingroup shell_list
+ * @brief Insert a new list to a doubly linked list.
+ *
+ * @par Description:
+ * This API is used to insert a new list to a doubly linked list.
+ * @attention
+ *
+ *
The parameters passed in should be ensured to be legal pointers.
+ *
+ *
+ * @param oldList [IN] Doubly linked list where the new list is inserted.
+ * @param newList [IN] New list to be inserted.
+ *
+ * @retval None
+ * @par Dependency:
+ *
shell_list.h: the header file that contains the API declaration.
+ * @see SH_ListDelete
+ */
+static inline void SH_ListAddList(SH_List *oldList, SH_List *newList)
+{
+ SH_List *oldListHead = oldList->pstNext;
+ SH_List *oldListTail = oldList;
+ SH_List *newListHead = newList;
+ SH_List *newListTail = newList->pstPrev;
+
+ oldListTail->pstNext = newListHead;
+ newListHead->pstPrev = oldListTail;
+ oldListHead->pstPrev = newListTail;
+ newListTail->pstNext = oldListHead;
+}
+
+/**
+ * @ingroup shell_list
+ * @brief Insert a doubly list to the tail of a doubly linked list.
+ *
+ * @par Description:
+ * This API is used to insert a new doubly list to the tail of a doubly linked list.
+ * @attention
+ *
+ *
The parameters passed in should be ensured to be legal pointers.
+ *
+ *
+ * @param oldList [IN] Doubly linked list where the new list is inserted.
+ * @param newList [IN] New list to be inserted.
+ *
+ * @retval None.
+ * @par Dependency:
+ *
shell_list.h: the header file that contains the API declaration.
+ * @see SH_ListAddList | SH_ListHeadInsertList
+ */
+static inline void SH_ListTailInsertList(SH_List *oldList, SH_List *newList)
+{
+ SH_ListAddList(oldList->pstPrev, newList);
+}
+
+/**
+ * @ingroup shell_list
+ * @brief Insert a doubly list to the head of a doubly linked list.
+ *
+ * @par Description:
+ * This API is used to insert a new doubly list to the head of a doubly linked list.
+ * @attention
+ *
+ *
The parameters passed in should be ensured to be legal pointers.
+ *
+ *
+ * @param oldList [IN] Doubly linked list where the new list is inserted.
+ * @param newList [IN] New list to be inserted.
+ *
+ * @retval None.
+ * @par Dependency:
+ *
shell_list.h: the header file that contains the API declaration.
+ * @see SH_ListAddList | SH_ListTailInsertList
+ */
+static inline void SH_ListHeadInsertList(SH_List *oldList, SH_List *newList)
+{
+ SH_ListAddList(oldList, newList);
+}
+
+/**
+ * @ingroup shell_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 member [IN] Name of the member of which the offset is to be measured.
+ *
+ * @retval Offset of the field to the structure address.
+ * @par Dependency:
+ *
shell_list.h: the header file that contains the API declaration.
+ * @see
+ */
+#define LOS_OFF_SET_OF(type, member) ((uintptr_t)&((type *)0)->member)
+
+/**
+ * @ingroup shell_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:
+ *
shell_list.h: the header file that contains the API declaration.
+ * @see
+ */
+#define SH_LIST_ENTRY(item, type, member) \
+ ((type *)(void *)((char *)(item) - LOS_OFF_SET_OF(type, member)))
+
+/**
+ * @ingroup shell_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:
+ *
shell_list.h: the header file that contains the API declaration.
+ * @see
+ */
+#define SH_LIST_FOR_EACH_ENTRY(item, list, type, member) \
+ for (item = SH_LIST_ENTRY((list)->pstNext, type, member); \
+ &(item)->member != (list); \
+ item = SH_LIST_ENTRY((item)->member.pstNext, type, member))
+
+/**
+ * @ingroup shell_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:
+ *
shell_list.h: the header file that contains the API declaration.
+ * @see
+ */
+#define SH_LIST_FOR_EACH_ENTRY_SAFE(item, next, list, type, member) \
+ for (item = SH_LIST_ENTRY((list)->pstNext, type, member), \
+ next = SH_LIST_ENTRY((item)->member.pstNext, type, member); \
+ &(item)->member != (list); \
+ item = next, next = SH_LIST_ENTRY((item)->member.pstNext, type, member))
+
+/**
+ * @ingroup shell_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.
shell_list.h: the header file that contains the API declaration.
+ * @see
+ */
+static inline void SH_ListDelInit(SH_List *list)
+{
+ list->pstNext->pstPrev = list->pstPrev;
+ list->pstPrev->pstNext = list->pstNext;
+ SH_ListInit(list);
+}
+
+/**
+ * @ingroup shell_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:
+ *
shell_list.h: the header file that contains the API declaration.
+ * @see
+ */
+#define SH_LIST_FOR_EACH(item, list) \
+ for (item = (list)->pstNext; \
+ (item) != (list); \
+ item = (item)->pstNext)
+
+/**
+ * @ingroup shell_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:
+ *
shell_list.h: the header file that contains the API declaration.
+ * @see
+ */
+#define SH_LIST_FOR_EACH_SAFE(item, next, list) \
+ for (item = (list)->pstNext, next = (item)->pstNext; \
+ (item) != (list); \
+ item = next, next = (item)->pstNext)
+
+/**
+ * @ingroup shell_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:
+ *
shell_list.h: the header file that contains the API declaration.
+ * @see
+ */
+#define SH_LIST_HEAD(list) SH_List list = { &(list), &(list) }
+
+#define SH_ListPeekHeadType(list, type, element) do { \
+ type *__t; \
+ if ((list)->pstNext == list) { \
+ __t = NULL; \
+ } else { \
+ __t = SH_LIST_ENTRY((list)->pstNext, type, element); \
+ } \
+ __t; \
+} while (0)
+
+#define SH_ListRemoveHeadType(list, type, element) do { \
+ type *__t; \
+ if ((list)->pstNext == list) { \
+ __t = NULL; \
+ } else { \
+ __t = SH_LIST_ENTRY((list)->pstNext, type, element); \
+ SH_ListDelete((list)->pstNext); \
+ } \
+ __t; \
+} while (0)
+
+#define SH_ListNextType(list, item, type, element) do { \
+ type *__t; \
+ if ((item)->pstNext == list) { \
+ __t = NULL; \
+ } else { \
+ __t = SH_LIST_ENTRY((item)->pstNext, type, element); \
+ } \
+ __t; \
+} while (0)
+
+#ifdef __cplusplus
+#if __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+#endif /* _SHELL_LIST_H */
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/shell/include/shell_pri.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/shell/include/shell_pri.h
new file mode 100644
index 00000000..e1a47f1d
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/shell/include/shell_pri.h
@@ -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.
+ */
+
+#ifndef _SHELL_PRI_H
+#define _SHELL_PRI_H
+
+#ifdef __cplusplus
+#if __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+extern void *ShellEntry(void *argv);
+extern void *ShellTask(void *argv);
+
+#ifdef __cplusplus
+#if __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+#endif /* _SHELL_PRI_H */
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/shell/include/sherr.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/shell/include/sherr.h
new file mode 100644
index 00000000..9645a97b
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/shell/include/sherr.h
@@ -0,0 +1,59 @@
+/*
+ * 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 _SHERR_H
+#define _SHERR_H
+
+#ifdef __cplusplus
+#if __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+#define SH_ERROR -1
+#define SH_OK 0
+#define SH_NOK -1
+
+#ifndef TRUE
+# define TRUE 1
+#endif
+#ifndef FALSE
+# define FALSE 0
+#endif
+
+#ifdef __cplusplus
+#if __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+#endif /* _SHERR_H */
+
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/shell/include/shmsg.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/shell/include/shmsg.h
new file mode 100644
index 00000000..71d7da96
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/shell/include/shmsg.h
@@ -0,0 +1,75 @@
+/*
+ * 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 _SHMSG_H
+#define _SHMSG_H
+
+#include "shell.h"
+
+#ifdef __cplusplus
+#if __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+#define SHELL_ENTRY_STACKSIZE 0x1000
+#define SHELL_TASK_STACKSIZE 0x3000
+
+#define SHELL_EXEC_COMMAND "exec"
+#define SHELL_EXEC_COMMAND_BYTES 4
+#define CMD_EXEC_COMMAND SHELL_EXEC_COMMAND" "
+#define CMD_EXEC_COMMAND_BYTES (SHELL_EXEC_COMMAND_BYTES + 1)
+#define CMD_EXIT_COMMAND "exit"
+#define CMD_EXIT_COMMAND_BYTES 4
+#define CMD_EXIT_CODE_BASE_DEC 10
+
+#define CONSOLE_IOC_MAGIC 'c'
+#define CONSOLE_CONTROL_REG_USERTASK _IO(CONSOLE_IOC_MAGIC, 7)
+
+#define COLOR_NONE "\e[0m"
+#define COLOR_RED "\e[0;31m"
+#define COLOR_L_RED "\e[1;31m"
+#define SHELL_PROMPT COLOR_L_RED"OHOS # "COLOR_NONE
+
+typedef void (* OutputFunc)(const char *fmt, ...);
+extern int ShellTaskInit(ShellCB *shellCB);
+extern int ShellEntryInit(ShellCB *shellCB);
+extern void ChildExec(const char *cmdName, char *const paramArray[]);
+extern void ShellCmdLineParse(char c, OutputFunc outputFunc, ShellCB *shellCB);
+extern int ShellNotify(ShellCB *shellCB);
+
+#ifdef __cplusplus
+#if __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+#endif /* _SHMSG_H */
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/shell/include/show.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/shell/include/show.h
new file mode 100644
index 00000000..542f27ac
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/shell/include/show.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 _SHOW_H
+#define _SHOW_H
+
+#include "stdarg.h"
+
+#include "shell.h"
+
+#ifdef __cplusplus
+#if __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+extern char *OsShellGetWorkingDirectory(void);
+extern unsigned int OsShellInit(void);
+extern int OsShellDeinit(ShellCB *shellCB);
+extern ShellCB *OsGetShellCb(void);
+
+#ifdef __cplusplus
+#if __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+#endif /* _SHOW_H */
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/shell/src/main.c b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/shell/src/main.c
new file mode 100644
index 00000000..3cdfc803
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/shell/src/main.c
@@ -0,0 +1,178 @@
+/*
+ * 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.
+ */
+
+#define _GNU_SOURCE
+
+#include "show.h"
+#include "shmsg.h"
+#include "shcmd.h"
+#include "semaphore.h"
+#include "securec.h"
+#include "unistd.h"
+#include
+
+ShellCB *g_shellCB = NULL;
+
+ShellCB *OsGetShellCb()
+{
+ return g_shellCB;
+}
+
+void ShellDeinit(ShellCB *shellCB)
+{
+ (void)pthread_mutex_destroy(&shellCB->historyMutex);
+ (void)pthread_mutex_destroy(&shellCB->keyMutex);
+ OsShellKeyDeInit((CmdKeyLink *)shellCB->cmdKeyLink);
+ OsShellKeyDeInit((CmdKeyLink *)shellCB->cmdHistoryKeyLink);
+ (void)free(shellCB);
+}
+
+static int OsShellCreateTask(ShellCB *shellCB)
+{
+ struct sched_param param = { 0 };
+ int ret;
+
+ ret = sched_getparam(getpid(), ¶m);
+ if (ret != SH_OK) {
+ goto OUT;
+ }
+
+ param.sched_priority = SHELL_PROCESS_PRIORITY_INIT;
+
+ ret = sched_setparam(getpid(), ¶m);
+ if (ret != SH_OK) {
+ goto OUT;
+ }
+
+ ret = ShellTaskInit(shellCB);
+ if (ret != SH_OK) {
+ goto OUT;
+ }
+
+ ret = ShellEntryInit(shellCB);
+ if (ret != SH_OK) {
+ goto OUT;
+ }
+
+ (void)pthread_join(shellCB->shellTaskHandle, NULL);
+ (void)pthread_join(shellCB->shellEntryHandle, NULL);
+
+OUT:
+ ShellDeinit(shellCB);
+ return ret;
+}
+
+static int DoShellExec(char **argv)
+{
+ int i, j;
+ int len = 0;
+ int ret = SH_NOK;
+ char *cmdLine = NULL;
+
+ if (strncmp(argv[0], SHELL_EXEC_COMMAND, SHELL_EXEC_COMMAND_BYTES) == 0) {
+ ChildExec(argv[1], argv + 1);
+ }
+ for (i = 0; argv[i]; i++) {
+ len += strlen(argv[i]);
+ }
+ len += i + 1;
+ cmdLine = (char *)malloc(len);
+ if (!cmdLine) {
+ return ret;
+ }
+ errno_t ret1 = memset_s(cmdLine, len, 0, len);
+ if (ret1 != EOK) {
+ free(cmdLine);
+ return ret1;
+ }
+
+ for (j = 0; j < i; j++) {
+ (void)strcat_s(cmdLine, len, argv[j]);
+ (void)strcat_s(cmdLine, len, " ");
+ }
+
+ cmdLine[len - 2] = '\0'; /* 2, (len - 2) is the end of cmdline buf */
+ ret = syscall(__NR_shellexec, argv[0], cmdLine);
+ free(cmdLine);
+ return ret;
+}
+
+int main(int argc, char **argv)
+{
+ int ret = SH_NOK;
+ ShellCB *shellCB = NULL;
+
+ if (argc > 1) {
+ ret = DoShellExec(argv + 1);
+ return ret;
+ }
+
+ setbuf(stdout, NULL);
+
+ shellCB = (ShellCB *)malloc(sizeof(ShellCB));
+ if (shellCB == NULL) {
+ goto ERR_OUT1;
+ }
+ ret = memset_s(shellCB, sizeof(ShellCB), 0, sizeof(ShellCB));
+ if (ret != SH_OK) {
+ goto ERR_OUT1;
+ }
+
+ ret = pthread_mutex_init(&shellCB->keyMutex, NULL);
+ if (ret != SH_OK) {
+ goto ERR_OUT1;
+ }
+
+ ret = pthread_mutex_init(&shellCB->historyMutex, NULL);
+ if (ret != SH_OK) {
+ goto ERR_OUT2;
+ }
+
+ ret = (int)OsShellKeyInit(shellCB);
+ if (ret != SH_OK) {
+ goto ERR_OUT3;
+ }
+ (void)strncpy_s(shellCB->shellWorkingDirectory, PATH_MAX, "/", 2); /* 2:space for "/" */
+
+ sem_init(&shellCB->shellSem, 0, 0);
+
+ g_shellCB = shellCB;
+ return OsShellCreateTask(shellCB);
+
+ERR_OUT3:
+ (void)pthread_mutex_destroy(&shellCB->historyMutex);
+ERR_OUT2:
+ (void)pthread_mutex_destroy(&shellCB->keyMutex);
+ERR_OUT1:
+ (void)free(shellCB);
+ return ret;
+}
+
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/shell/src/shcmd.c b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/shell/src/shcmd.c
new file mode 100644
index 00000000..e51dee3d
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/shell/src/shcmd.c
@@ -0,0 +1,594 @@
+/*
+ * 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 "shcmd.h"
+#include "show.h"
+#include "stdlib.h"
+#include "unistd.h"
+#include "dirent.h"
+#include "securec.h"
+
+#define SHELL_INIT_MAGIC_FLAG 0xABABABAB
+#define CTRL_C 0x03 /* 0x03: ctrl+c ASCII */
+
+static void OsFreeCmdPara(CmdParsed *cmdParsed)
+{
+ unsigned int i;
+ for (i = 0; i < cmdParsed->paramCnt; i++) {
+ if ((cmdParsed->paramArray[i]) != NULL) {
+ free((cmdParsed->paramArray[i]));
+ cmdParsed->paramArray[i] = NULL;
+ }
+ }
+}
+
+static int OsStrSeparateTabStrGet(const char **tabStr, CmdParsed *parsed, unsigned int tabStrLen)
+{
+ char *shiftStr = NULL;
+ char *tempStr = (char *)malloc(SHOW_MAX_LEN << 1);
+ if (tempStr == NULL) {
+ return (int)SH_ERROR;
+ }
+
+ (void)memset_s(tempStr, SHOW_MAX_LEN << 1, 0, SHOW_MAX_LEN << 1);
+ shiftStr = tempStr + SHOW_MAX_LEN;
+
+ if (strncpy_s(tempStr, SHOW_MAX_LEN - 1, *tabStr, tabStrLen)) {
+ free(tempStr);
+ return (int)SH_ERROR;
+ }
+
+ parsed->cmdType = CMD_TYPE_STD;
+
+ /* cut useless or repeat space */
+ if (OsCmdKeyShift(tempStr, shiftStr, SHOW_MAX_LEN - 1)) {
+ free(tempStr);
+ return (int)SH_ERROR;
+ }
+
+ /* get exact position of string to complete */
+ /* situation different if end space lost or still exist */
+ if ((strlen(shiftStr) == 0) || (tempStr[strlen(tempStr) - 1] != shiftStr[strlen(shiftStr) - 1])) {
+ *tabStr = "";
+ } else {
+ if (OsCmdParse(shiftStr, parsed)) {
+ free(tempStr);
+ return (int)SH_ERROR;
+ }
+ *tabStr = parsed->paramArray[parsed->paramCnt - 1];
+ }
+
+ free(tempStr);
+ return SH_OK;
+}
+
+char *OsShellGetWorkingDirectory(void)
+{
+ return OsGetShellCb()->shellWorkingDirectory;
+}
+
+int OsShellSetWorkingDirectory(const char *dir, size_t len)
+{
+ if (dir == NULL) {
+ return SH_NOK;
+ }
+
+ int ret = strncpy_s(OsGetShellCb()->shellWorkingDirectory, sizeof(OsGetShellCb()->shellWorkingDirectory),
+ dir, len);
+ if (ret != SH_OK) {
+ return SH_NOK;
+ }
+ return SH_OK;
+}
+
+static int OsStrSeparate(const char *tabStr, char *strPath, char *nameLooking, unsigned int tabStrLen)
+{
+ char *strEnd = NULL;
+ char *cutPos = NULL;
+ CmdParsed parsed = {0};
+ char *shellWorkingDirectory = OsShellGetWorkingDirectory();
+ int ret;
+
+ ret = OsStrSeparateTabStrGet(&tabStr, &parsed, tabStrLen);
+ if (ret != SH_OK) {
+ return ret;
+ }
+
+ /* get fullpath str */
+ if (*tabStr != '/') {
+ if (strncpy_s(strPath, CMD_MAX_PATH, shellWorkingDirectory, CMD_MAX_PATH - 1)) {
+ OsFreeCmdPara(&parsed);
+ return (int)SH_ERROR;
+ }
+ if (strcmp(shellWorkingDirectory, "/")) {
+ if (strncat_s(strPath, CMD_MAX_PATH - 1, "/", CMD_MAX_PATH - strlen(strPath) - 1)) {
+ OsFreeCmdPara(&parsed);
+ return (int)SH_ERROR;
+ }
+ }
+ }
+
+ if (strncat_s(strPath, CMD_MAX_PATH - 1, tabStr, CMD_MAX_PATH - strlen(strPath) - 1)) {
+ OsFreeCmdPara(&parsed);
+ return (int)SH_ERROR;
+ }
+
+ /* split str by last '/' */
+ strEnd = strrchr(strPath, '/');
+ if (strEnd != NULL) {
+ if (strncpy_s(nameLooking, CMD_MAX_PATH, strEnd + 1, CMD_MAX_PATH - 1)) { /* get cmp str */
+ OsFreeCmdPara(&parsed);
+ return (int)SH_ERROR;
+ }
+ }
+
+ cutPos = strrchr(strPath, '/');
+ if (cutPos != NULL) {
+ *(cutPos + 1) = '\0';
+ }
+
+ OsFreeCmdPara(&parsed);
+ return SH_OK;
+}
+
+static int OsShowPageInputControl(void)
+{
+ char readChar;
+
+ while (1) {
+ if (read(STDIN_FILENO, &readChar, 1) != 1) { /* get one char from stdin */
+ printf("\n");
+ return (int)SH_ERROR;
+ }
+ if ((readChar == 'q') || (readChar == 'Q') || (readChar == CTRL_C)) {
+ printf("\n");
+ return 0;
+ } else if (readChar == '\r') {
+ printf("\b \b\b \b\b \b\b \b\b \b\b \b\b \b\b \b");
+ return 1;
+ }
+ }
+}
+
+static int OsShowPageControl(unsigned int timesPrint, unsigned int lineCap, unsigned int count)
+{
+ if (NEED_NEW_LINE(timesPrint, lineCap)) {
+ printf("\n");
+ if (SCREEN_IS_FULL(timesPrint, lineCap) && (timesPrint < count)) {
+ printf("--More--");
+ return OsShowPageInputControl();
+ }
+ }
+ return 1;
+}
+
+static int OsSurePrintAll(unsigned int count)
+{
+ char readChar = 0;
+ printf("\nDisplay all %u possibilities?(y/n)", count);
+ while (1) {
+ if (read(STDIN_FILENO, &readChar, 1) != 1) {
+ return (int)SH_ERROR;
+ }
+ if ((readChar == 'n') || (readChar == 'N') || (readChar == CTRL_C)) {
+ printf("\n");
+ return 0;
+ } else if ((readChar == 'y') || (readChar == 'Y') || (readChar == '\r')) {
+ return 1;
+ }
+ }
+}
+
+static int OsPrintMatchList(unsigned int count, const char *strPath, const char *nameLooking, unsigned int printLen)
+{
+ unsigned int timesPrint = 0;
+ unsigned int lineCap;
+ int ret;
+ DIR *openDir = NULL;
+ struct dirent *readDir = NULL;
+ char formatChar[10] = {0}; /* 10:for formatChar length */
+
+ printLen = (printLen > (DEFAULT_SCREEN_WIDTH - 2)) ? (DEFAULT_SCREEN_WIDTH - 2) : printLen; /* 2:revered 2 bytes */
+ lineCap = DEFAULT_SCREEN_WIDTH / (printLen + 2); /* 2:DEFAULT_SCREEN_WIDTH revered 2 bytes */
+ if (snprintf_s(formatChar, sizeof(formatChar) - 1, 7, "%%-%us ", printLen) < 0) { /* 7:format-len */
+ return (int)SH_ERROR;
+ }
+
+ if (count > (lineCap * DEFAULT_SCREEN_HEIGHT)) {
+ ret = OsSurePrintAll(count);
+ if (ret != 1) {
+ return ret;
+ }
+ }
+ openDir = opendir(strPath);
+ if (openDir == NULL) {
+ return (int)SH_ERROR;
+ }
+
+ printf("\n");
+ for (readDir = readdir(openDir); readDir != NULL; readDir = readdir(openDir)) {
+ if (strncmp(nameLooking, readDir->d_name, strlen(nameLooking)) != 0) {
+ continue;
+ }
+ printf(formatChar, readDir->d_name);
+ timesPrint++;
+ ret = OsShowPageControl(timesPrint, lineCap, count);
+ if (ret != 1) {
+ if (closedir(openDir) < 0) {
+ return (int)SH_ERROR;
+ }
+ return ret;
+ }
+ }
+
+ printf("\n");
+ if (closedir(openDir) < 0) {
+ return (int)SH_ERROR;
+ }
+
+ return SH_OK;
+}
+
+static void StrncmpCut(const char *s1, char *s2, size_t n)
+{
+ if ((n == 0) || (s1 == NULL) || (s2 == NULL)) {
+ return;
+ }
+ do {
+ if (*s1 && *s2 && (*s1 == *s2)) {
+ s1++;
+ s2++;
+ } else {
+ break;
+ }
+ } while (--n != 0);
+ if (n > 0) {
+ /* NULL pad the remaining n-1 bytes */
+ while (n-- != 0) {
+ *s2++ = 0;
+ }
+ }
+ return;
+}
+
+static void OsCompleteStr(char *result, const char *target, char *cmdKey, unsigned int *len)
+{
+ unsigned int size = strlen(result) - strlen(target);
+ char *des = cmdKey + *len;
+ char *src = result + strlen(target);
+
+ while (size-- > 0) {
+ printf("%c", *src);
+ if (*len == (SHOW_MAX_LEN - 1)) {
+ *des = '\0';
+ break;
+ }
+ *des++ = *src++;
+ (*len)++;
+ }
+}
+
+static int OsExecNameMatch(const char *strPath, const char *nameLooking, char *strObj, unsigned int *maxLen)
+{
+ int count = 0;
+ DIR *openDir = NULL;
+ struct dirent *readDir = NULL;
+
+ openDir = opendir(strPath);
+ if (openDir == NULL) {
+ return (int)SH_ERROR;
+ }
+
+ for (readDir = readdir(openDir); readDir != NULL; readDir = readdir(openDir)) {
+ if (strncmp(nameLooking, readDir->d_name, strlen(nameLooking)) != 0) {
+ continue;
+ }
+ if (count == 0) {
+ if (strncpy_s(strObj, CMD_MAX_PATH, readDir->d_name, CMD_MAX_PATH - 1)) {
+ (void)closedir(openDir);
+ return (int)SH_ERROR;
+ }
+ *maxLen = strlen(readDir->d_name);
+ } else {
+ /* strncmp&cut the same strings of name matched */
+ StrncmpCut(readDir->d_name, strObj, strlen(strObj));
+ if (strlen(readDir->d_name) > *maxLen) {
+ *maxLen = strlen(readDir->d_name);
+ }
+ }
+ count++;
+ }
+
+ if (closedir(openDir) < 0) {
+ return (int)SH_ERROR;
+ }
+
+ return count;
+}
+
+static int OsTabMatchFile(char *cmdKey, unsigned int *len)
+{
+ unsigned int maxLen = 0;
+ int count;
+ char *strOutput = NULL;
+ char *strCmp = NULL;
+ char *dirOpen = (char *)malloc(CMD_MAX_PATH * 3); /* 3:dirOpen\strOutput\strCmp */
+ if (dirOpen == NULL) {
+ return (int)SH_ERROR;
+ }
+
+ (void)memset_s(dirOpen, CMD_MAX_PATH * 3, 0, CMD_MAX_PATH * 3); /* 3:dirOpen\strOutput\strCmp */
+ strOutput = dirOpen + CMD_MAX_PATH;
+ strCmp = strOutput + CMD_MAX_PATH;
+
+ if (OsStrSeparate(cmdKey, dirOpen, strCmp, *len)) {
+ free(dirOpen);
+ return (int)SH_ERROR;
+ }
+
+ count = OsExecNameMatch(dirOpen, strCmp, strOutput, &maxLen);
+ /* one or more matched */
+ if (count >= 1) {
+ OsCompleteStr(strOutput, strCmp, cmdKey, len);
+
+ if (count == 1) {
+ free(dirOpen);
+ return 1;
+ }
+ if (OsPrintMatchList((unsigned int)count, dirOpen, strCmp, maxLen) == -1) {
+ free(dirOpen);
+ return (int)SH_ERROR;
+ }
+ }
+
+ free(dirOpen);
+ return count;
+}
+
+/*
+ * Description: Pass in the string and clear useless space ,which include:
+ * 1) The overmatch space which is not be marked by Quote's area
+ * Squeeze the overmatch space into one space
+ * 2) Clear all space before first valid character
+ * Input: cmdKey : Pass in the buff string, which is ready to be operated
+ * cmdOut : Pass out the buffer string ,which has already been operated
+ * size : cmdKey length
+ */
+unsigned int OsCmdKeyShift(const char *cmdKey, char *cmdOut, unsigned int size)
+{
+ char *output = NULL;
+ char *outputBak = NULL;
+ unsigned int len;
+ int ret;
+ bool quotes = FALSE;
+
+ if ((cmdKey == NULL) || (cmdOut == NULL)) {
+ return (unsigned int)SH_ERROR;
+ }
+
+ len = strlen(cmdKey);
+ if ((*cmdKey == '\n') || (len >= size)) {
+ return (unsigned int)SH_ERROR;
+ }
+ output = (char *)malloc(len + 1);
+ if (output == NULL) {
+ printf("malloc failure in %s[%d]\n", __FUNCTION__, __LINE__);
+ return (unsigned int)SH_ERROR;
+ }
+
+ /* Backup the 'output' start address */
+ outputBak = output;
+ /* Scan each character in 'cmdKey',and squeeze the overmuch space and ignore invalid character */
+ for (; *cmdKey != '\0'; cmdKey++) {
+ /* Detected a Double Quotes, switch the matching status */
+ if (*(cmdKey) == '\"') {
+ SWITCH_QUOTES_STATUS(quotes);
+ }
+ /* Ignore the current character in following situation */
+ /* 1) Quotes matching status is FALSE (which said that the space is not been marked by double quotes) */
+ /* 2) Current character is a space */
+ /* 3) Next character is a space too, or the string is been seeked to the end already(\0) */
+ /* 4) Invalid character, such as single quotes */
+ if ((*cmdKey == ' ') && ((*(cmdKey + 1) == ' ') || (*(cmdKey + 1) == '\0')) && QUOTES_STATUS_CLOSE(quotes)) {
+ continue;
+ }
+ if (*cmdKey == '\'') {
+ continue;
+ }
+ *output = *cmdKey;
+ output++;
+ }
+ *output = '\0';
+ /* Restore the 'output' start address */
+ output = outputBak;
+ len = strlen(output);
+ /* Clear the space which is located at the first character in buffer */
+ if (*output == ' ') {
+ output++;
+ len--;
+ }
+ /* Copy out the buffer which is been operated already */
+ ret = strncpy_s(cmdOut, size, output, len);
+ if (ret != SH_OK) {
+ printf("%s,%d strncpy_s failed, err:%d!\n", __FUNCTION__, __LINE__, ret);
+ free(outputBak);
+ return SH_ERROR;
+ }
+ cmdOut[len] = '\0';
+
+ free(outputBak);
+ return SH_OK;
+}
+
+int OsTabCompletion(char *cmdKey, unsigned int *len)
+{
+ int count;
+
+ if ((cmdKey == NULL) || (len == NULL)) {
+ return (int)SH_ERROR;
+ }
+
+ count = OsTabMatchFile(cmdKey, len);
+
+ return count;
+}
+
+unsigned int OsShellKeyInit(ShellCB *shellCB)
+{
+ CmdKeyLink *cmdKeyLink = NULL;
+ CmdKeyLink *cmdHistoryLink = NULL;
+
+ if (shellCB == NULL) {
+ return SH_ERROR;
+ }
+
+ cmdKeyLink = (CmdKeyLink *)malloc(sizeof(CmdKeyLink));
+ if (cmdKeyLink == NULL) {
+ printf("Shell CmdKeyLink memory alloc error!\n");
+ return SH_ERROR;
+ }
+ cmdHistoryLink = (CmdKeyLink *)malloc(sizeof(CmdKeyLink));
+ if (cmdHistoryLink == NULL) {
+ free(cmdKeyLink);
+ printf("Shell CmdHistoryLink memory alloc error!\n");
+ return SH_ERROR;
+ }
+
+ cmdKeyLink->count = 0;
+ SH_ListInit(&(cmdKeyLink->list));
+ shellCB->cmdKeyLink = (void *)cmdKeyLink;
+
+ cmdHistoryLink->count = 0;
+ SH_ListInit(&(cmdHistoryLink->list));
+ shellCB->cmdHistoryKeyLink = (void *)cmdHistoryLink;
+ shellCB->cmdMaskKeyLink = (void *)cmdHistoryLink;
+ return SH_OK;
+}
+
+void OsShellKeyDeInit(CmdKeyLink *cmdKeyLink)
+{
+ CmdKeyLink *cmdtmp = NULL;
+ if (cmdKeyLink == NULL) {
+ return;
+ }
+
+ while (!SH_ListEmpty(&(cmdKeyLink->list))) {
+ cmdtmp = SH_LIST_ENTRY(cmdKeyLink->list.pstNext, CmdKeyLink, list);
+ SH_ListDelete(&cmdtmp->list);
+ free(cmdtmp);
+ }
+
+ cmdKeyLink->count = 0;
+ free(cmdKeyLink);
+}
+
+void OsShellCmdPush(const char *string, CmdKeyLink *cmdKeyLink)
+{
+ CmdKeyLink *cmdNewNode = NULL;
+ unsigned int len;
+
+ if ((string == NULL) || (strlen(string) == 0)) {
+ return;
+ }
+
+ len = strlen(string);
+ cmdNewNode = (CmdKeyLink *)malloc(sizeof(CmdKeyLink) + len + 1);
+ if (cmdNewNode == NULL) {
+ return;
+ }
+
+ (void)memset_s(cmdNewNode, sizeof(CmdKeyLink) + len + 1, 0, sizeof(CmdKeyLink) + len + 1);
+ if (strncpy_s(cmdNewNode->cmdString, len + 1, string, len)) {
+ free(cmdNewNode);
+ return;
+ }
+
+ SH_ListTailInsert(&(cmdKeyLink->list), &(cmdNewNode->list));
+
+ return;
+}
+
+void OsShellHistoryShow(unsigned int value, ShellCB *shellCB)
+{
+ CmdKeyLink *cmdtmp = NULL;
+ CmdKeyLink *cmdNode = shellCB->cmdHistoryKeyLink;
+ CmdKeyLink *cmdMask = shellCB->cmdMaskKeyLink;
+ int ret;
+
+ (void)pthread_mutex_lock(&shellCB->historyMutex);
+ if (value == CMD_KEY_DOWN) {
+ if (cmdMask == cmdNode) {
+ goto END;
+ }
+
+ cmdtmp = SH_LIST_ENTRY(cmdMask->list.pstNext, CmdKeyLink, list);
+ if (cmdtmp != cmdNode) {
+ cmdMask = cmdtmp;
+ } else {
+ goto END;
+ }
+ } else if (value == CMD_KEY_UP) {
+ cmdtmp = SH_LIST_ENTRY(cmdMask->list.pstPrev, CmdKeyLink, list);
+ if (cmdtmp != cmdNode) {
+ cmdMask = cmdtmp;
+ } else {
+ goto END;
+ }
+ }
+
+ while (shellCB->shellBufOffset--) {
+ printf("\b \b");
+ }
+ printf("%s", cmdMask->cmdString);
+ shellCB->shellBufOffset = strlen(cmdMask->cmdString);
+ (void)memset_s(shellCB->shellBuf, SHOW_MAX_LEN, 0, SHOW_MAX_LEN);
+ ret = memcpy_s(shellCB->shellBuf, SHOW_MAX_LEN, cmdMask->cmdString, shellCB->shellBufOffset);
+ if (ret != SH_OK) {
+ printf("%s, %d memcpy failed!\n", __FUNCTION__, __LINE__);
+ goto END;
+ }
+ shellCB->cmdMaskKeyLink = (void *)cmdMask;
+
+END:
+ (void)pthread_mutex_unlock(&shellCB->historyMutex);
+ return;
+}
+
+unsigned int OsCmdExec(CmdParsed *cmdParsed, char *cmdStr)
+{
+ unsigned int ret = SH_OK;
+ if (cmdParsed && cmdStr) {
+ ret = SH_NOK;
+ }
+
+ return ret;
+}
+
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/shell/src/shcmdparse.c b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/shell/src/shcmdparse.c
new file mode 100644
index 00000000..269b4193
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/shell/src/shcmdparse.c
@@ -0,0 +1,154 @@
+/*
+ * 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 "shcmd.h"
+#include "sherr.h"
+
+
+/*
+ * Filter out double quote or single-quoted strings at both ends
+ */
+char *OsCmdParseStrdup(const char *str)
+{
+ char *tempStr = NULL;
+ char *newStr = NULL;
+
+ newStr = (char *)malloc(strlen(str) + 1);
+ if (newStr == NULL) {
+ return NULL;
+ }
+
+ tempStr = newStr;
+ for (; *str != '\0'; str++) {
+ if ((*str == '\"') || (*str == '\'')) {
+ continue;
+ }
+ *newStr = *str;
+ newStr++;
+ }
+ *newStr = '\0';
+ return tempStr;
+}
+
+unsigned int OsCmdParseParaGet(char **value, const char *paraTokenStr)
+{
+ if ((paraTokenStr == NULL) || (value == NULL)) {
+ return (unsigned int)SH_ERROR;
+ }
+ *value = OsCmdParseStrdup(paraTokenStr);
+ if (*value == NULL) {
+ return SH_NOK;
+ }
+ return SH_OK;
+}
+
+unsigned int OsCmdParseOneToken(CmdParsed *cmdParsed, unsigned int index, const char *token)
+{
+ unsigned int ret = SH_OK;
+ unsigned int tempLen;
+
+ if (cmdParsed == NULL) {
+ return (unsigned int)SH_ERROR;
+ }
+
+ if (index == 0) {
+ if (cmdParsed->cmdType != CMD_TYPE_STD) {
+ return ret;
+ }
+ }
+
+ if ((token != NULL) && (cmdParsed->paramCnt < CMD_MAX_PARAS)) {
+ tempLen = cmdParsed->paramCnt;
+ ret = OsCmdParseParaGet(&(cmdParsed->paramArray[tempLen]), token);
+ if (ret != SH_OK) {
+ return ret;
+ }
+ cmdParsed->paramCnt++;
+ }
+ return ret;
+}
+
+unsigned int OsCmdTokenSplit(char *cmdStr, char split, CmdParsed *cmdParsed)
+{
+ enum {
+ STAT_INIT,
+ STAT_TOKEN_IN,
+ STAT_TOKEN_OUT
+ } state = STAT_INIT;
+ unsigned int count = 0;
+ char *p = NULL;
+ char *token = cmdStr;
+ unsigned int ret = SH_OK;
+ bool quotes = FALSE;
+
+ if (cmdStr == NULL) {
+ return (unsigned int)SH_ERROR;
+ }
+
+ for (p = cmdStr; (*p != '\0') && (ret == SH_OK); p++) {
+ if (*p == '\"') {
+ SWITCH_QUOTES_STATUS(quotes);
+ }
+ switch (state) {
+ case STAT_INIT:
+ case STAT_TOKEN_IN:
+ if ((*p == split) && QUOTES_STATUS_CLOSE(quotes)) {
+ *p = '\0';
+ ret = OsCmdParseOneToken(cmdParsed, count++, token);
+ state = STAT_TOKEN_OUT;
+ }
+ break;
+ case STAT_TOKEN_OUT:
+ if (*p != split) {
+ token = p;
+ state = STAT_TOKEN_IN;
+ }
+ break;
+ default:
+ break;
+ }
+ }
+
+ if (((ret == SH_OK) && (state == STAT_TOKEN_IN)) || (state == STAT_INIT)) {
+ ret = OsCmdParseOneToken(cmdParsed, count, token);
+ }
+
+ return ret;
+}
+
+unsigned int OsCmdParse(char *cmdStr, CmdParsed *cmdParsed)
+{
+ if ((cmdStr == NULL) || (cmdParsed == NULL) || (strlen(cmdStr) == 0)) {
+ return (unsigned int)SH_ERROR;
+ }
+ return OsCmdTokenSplit(cmdStr, ' ', cmdParsed);
+}
+
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/shell/src/shmsg.c b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/shell/src/shmsg.c
new file mode 100644
index 00000000..0fb2b69d
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/shell/src/shmsg.c
@@ -0,0 +1,716 @@
+/*
+ * 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.
+ */
+
+#define _GNU_SOURCE
+
+#include "stdlib.h"
+#include "stdio.h"
+#include "unistd.h"
+#include "sys/prctl.h"
+#include "sys/ioctl.h"
+#include "syscall.h"
+#include "sys/wait.h"
+#include "pthread.h"
+#include "securec.h"
+#include "shmsg.h"
+#include "shell_pri.h"
+#include "shcmd.h"
+
+#define CHAR_CTRL_C '\x03'
+#define CHAR_CTRL_DEL '\x7F'
+
+#define VISIABLE_CHAR(ch) ((ch) > 0x1F && (ch) < 0x7F)
+
+char *GetCmdline(ShellCB *shellCB)
+{
+ CmdKeyLink *cmdkey = shellCB->cmdKeyLink;
+ CmdKeyLink *cmdNode = NULL;
+
+ (void)pthread_mutex_lock(&shellCB->keyMutex);
+ if ((cmdkey == NULL) || SH_ListEmpty(&cmdkey->list)) {
+ (void)pthread_mutex_unlock(&shellCB->keyMutex);
+ return NULL;
+ }
+
+ cmdNode = SH_LIST_ENTRY(cmdkey->list.pstNext, CmdKeyLink, list);
+ if (cmdNode == NULL) {
+ (void)pthread_mutex_unlock(&shellCB->keyMutex);
+ return NULL;
+ }
+
+ SH_ListDelete(&(cmdNode->list));
+ (void)pthread_mutex_unlock(&shellCB->keyMutex);
+
+ if (strlen(cmdNode->cmdString) == 0) {
+ free(cmdNode);
+ return NULL;
+ }
+
+ return cmdNode->cmdString;
+}
+
+static void ShellSaveHistoryCmd(char *string, ShellCB *shellCB)
+{
+ CmdKeyLink *cmdHistory = shellCB->cmdHistoryKeyLink;
+ CmdKeyLink *cmdkey = SH_LIST_ENTRY(string, CmdKeyLink, cmdString);
+ CmdKeyLink *cmdNxt = NULL;
+
+ if (*string == '\n') {
+ free(cmdkey);
+ return;
+ }
+
+ (void)pthread_mutex_lock(&shellCB->historyMutex);
+ if (cmdHistory->count != 0) {
+ cmdNxt = SH_LIST_ENTRY(cmdHistory->list.pstPrev, CmdKeyLink, list);
+ if (strcmp(string, cmdNxt->cmdString) == 0) {
+ free((void *)cmdkey);
+ (void)pthread_mutex_unlock(&shellCB->historyMutex);
+ return;
+ }
+ }
+
+ if (cmdHistory->count >= CMD_HISTORY_LEN) {
+ cmdNxt = SH_LIST_ENTRY(cmdHistory->list.pstNext, CmdKeyLink, list);
+ SH_ListDelete(&(cmdNxt->list));
+ SH_ListTailInsert(&(cmdHistory->list), &(cmdkey->list));
+ free((void *)cmdNxt);
+ (void)pthread_mutex_unlock(&shellCB->historyMutex);
+ return;
+ }
+
+ SH_ListTailInsert(&(cmdHistory->list), &(cmdkey->list));
+ cmdHistory->count++;
+
+ (void)pthread_mutex_unlock(&shellCB->historyMutex);
+ return;
+}
+
+int ShellPend(ShellCB *shellCB)
+{
+ if (shellCB == NULL) {
+ return SH_NOK;
+ }
+
+ return sem_wait(&shellCB->shellSem);
+}
+
+int ShellNotify(ShellCB *shellCB)
+{
+ if (shellCB == NULL) {
+ return SH_NOK;
+ }
+
+ return sem_post(&shellCB->shellSem);
+}
+
+enum {
+ STAT_NORMAL_KEY,
+ STAT_ESC_KEY,
+ STAT_MULTI_KEY
+};
+
+static int ShellCmdLineCheckUDRL(const char ch, ShellCB *shellCB)
+{
+ int ret = SH_OK;
+ if (ch == 0x1b) { /* 0x1b: ESC */
+ shellCB->shellKeyType = STAT_ESC_KEY;
+ return ret;
+ } else if (ch == 0x5b) { /* 0x5b: first Key combination */
+ if (shellCB->shellKeyType == STAT_ESC_KEY) {
+ shellCB->shellKeyType = STAT_MULTI_KEY;
+ return ret;
+ }
+ } else if (ch == 0x41) { /* up */
+ if (shellCB->shellKeyType == STAT_MULTI_KEY) {
+ OsShellHistoryShow(CMD_KEY_UP, shellCB);
+ shellCB->shellKeyType = STAT_NORMAL_KEY;
+ return ret;
+ }
+ } else if (ch == 0x42) { /* down */
+ if (shellCB->shellKeyType == STAT_MULTI_KEY) {
+ shellCB->shellKeyType = STAT_NORMAL_KEY;
+ OsShellHistoryShow(CMD_KEY_DOWN, shellCB);
+ return ret;
+ }
+ } else if (ch == 0x43) { /* right */
+ if (shellCB->shellKeyType == STAT_MULTI_KEY) {
+ shellCB->shellKeyType = STAT_NORMAL_KEY;
+ return ret;
+ }
+ } else if (ch == 0x44) { /* left */
+ if (shellCB->shellKeyType == STAT_MULTI_KEY) {
+ shellCB->shellKeyType = STAT_NORMAL_KEY;
+ return ret;
+ }
+ }
+ return SH_NOK;
+}
+
+void ShellTaskNotify(ShellCB *shellCB)
+{
+ int ret;
+
+ (void)pthread_mutex_lock(&shellCB->keyMutex);
+ OsShellCmdPush(shellCB->shellBuf, shellCB->cmdKeyLink);
+ (void)pthread_mutex_unlock(&shellCB->keyMutex);
+
+ ret = ShellNotify(shellCB);
+ if (ret != SH_OK) {
+ printf("command execute failed, \"%s\"", shellCB->shellBuf);
+ }
+}
+
+void ParseEnterKey(OutputFunc outputFunc, ShellCB *shellCB)
+{
+ if ((shellCB == NULL) || (outputFunc == NULL)) {
+ return;
+ }
+
+ if (shellCB->shellBufOffset == 0) {
+ shellCB->shellBuf[shellCB->shellBufOffset] = '\n';
+ shellCB->shellBuf[shellCB->shellBufOffset + 1] = '\0';
+ goto NOTIFY;
+ }
+
+ if (shellCB->shellBufOffset <= (SHOW_MAX_LEN - 1)) {
+ shellCB->shellBuf[shellCB->shellBufOffset] = '\0';
+ }
+NOTIFY:
+ shellCB->shellBufOffset = 0;
+ ShellTaskNotify(shellCB);
+}
+
+void ParseCancelKey(OutputFunc outputFunc, ShellCB *shellCB)
+{
+ if ((shellCB == NULL) || (outputFunc == NULL)) {
+ return;
+ }
+
+ if (shellCB->shellBufOffset <= (SHOW_MAX_LEN - 1)) {
+ shellCB->shellBuf[0] = CHAR_CTRL_C;
+ shellCB->shellBuf[1] = '\0';
+ }
+
+ shellCB->shellBufOffset = 0;
+ ShellTaskNotify(shellCB);
+}
+
+void ParseDeleteKey(OutputFunc outputFunc, ShellCB *shellCB)
+{
+ if ((shellCB == NULL) || (outputFunc == NULL)) {
+ return;
+ }
+
+ if ((shellCB->shellBufOffset > 0) && (shellCB->shellBufOffset <= (SHOW_MAX_LEN - 1))) {
+ shellCB->shellBuf[shellCB->shellBufOffset - 1] = '\0';
+ shellCB->shellBufOffset--;
+ outputFunc("\b \b");
+ }
+}
+
+void ParseTabKey(OutputFunc outputFunc, ShellCB *shellCB)
+{
+ int ret;
+
+ if ((shellCB == NULL) || (outputFunc == NULL)) {
+ return;
+ }
+
+ if ((shellCB->shellBufOffset > 0) && (shellCB->shellBufOffset < (SHOW_MAX_LEN - 1))) {
+ ret = OsTabCompletion(shellCB->shellBuf, &shellCB->shellBufOffset);
+ if (ret > 1) {
+ outputFunc(SHELL_PROMPT"%s", shellCB->shellBuf);
+ }
+ }
+}
+
+void ParseNormalChar(char ch, OutputFunc outputFunc, ShellCB *shellCB)
+{
+ if ((shellCB == NULL) || (outputFunc == NULL) || !VISIABLE_CHAR(ch)) {
+ return;
+ }
+
+ if ((ch != '\0') && (shellCB->shellBufOffset < (SHOW_MAX_LEN - 1))) {
+ shellCB->shellBuf[shellCB->shellBufOffset] = ch;
+ shellCB->shellBufOffset++;
+ outputFunc("%c", ch);
+ }
+
+ shellCB->shellKeyType = STAT_NORMAL_KEY;
+}
+
+void ShellCmdLineParse(char c, OutputFunc outputFunc, ShellCB *shellCB)
+{
+ const char ch = c;
+ int ret;
+
+ if ((shellCB->shellBufOffset == 0) && (ch != '\n') && (ch != CHAR_CTRL_C) && (ch != '\0')) {
+ (void)memset_s(shellCB->shellBuf, SHOW_MAX_LEN, 0, SHOW_MAX_LEN);
+ }
+
+ switch (ch) {
+ case '\r':
+ case '\n': /* enter */
+ ParseEnterKey(outputFunc, shellCB);
+ break;
+ case CHAR_CTRL_C: /* ctrl + c */
+ ParseCancelKey(outputFunc, shellCB);
+ break;
+ case '\b': /* backspace */
+ case CHAR_CTRL_DEL: /* delete(0x7F) */
+ ParseDeleteKey(outputFunc, shellCB);
+ break;
+ case '\t': /* tab */
+ ParseTabKey(outputFunc, shellCB);
+ break;
+ default:
+ /* parse the up/down/right/left key */
+ ret = ShellCmdLineCheckUDRL(ch, shellCB);
+ if (ret == SH_OK) {
+ return;
+ }
+ ParseNormalChar(ch, outputFunc, shellCB);
+ break;
+ }
+
+ return;
+}
+
+unsigned int ShellMsgNameGet(CmdParsed *cmdParsed, const char *cmdType)
+{
+ (void)cmdParsed;
+ (void)cmdType;
+ return SH_ERROR;
+}
+
+char *GetCmdName(const char *cmdline, unsigned int len)
+{
+ unsigned int loop;
+ const char *tmpStr = NULL;
+ bool quotes = FALSE;
+ char *cmdName = NULL;
+ if (cmdline == NULL) {
+ return NULL;
+ }
+
+ cmdName = (char *)malloc(len + 1);
+ if (cmdName == NULL) {
+ printf("malloc failure in %s[%d]\n", __FUNCTION__, __LINE__);
+ return NULL;
+ }
+
+ /* Scan the 'cmdline' string for command */
+ /* Notice: Command string must not have any special name */
+ for (tmpStr = cmdline, loop = 0; (*tmpStr != '\0') && (loop < len); ) {
+ /* If reach a double quotes, switch the quotes matching status */
+ if (*tmpStr == '\"') {
+ SWITCH_QUOTES_STATUS(quotes);
+ /* Ignore the double quote character itself */
+ tmpStr++;
+ continue;
+ }
+ /* If detected a space which the quotes matching status is false */
+ /* which said has detected the first space for separator, finish this scan operation */
+ if ((*tmpStr == ' ') && (QUOTES_STATUS_CLOSE(quotes))) {
+ break;
+ }
+ cmdName[loop] = *tmpStr++;
+ loop++;
+ }
+ cmdName[loop] = '\0';
+
+ return cmdName;
+}
+
+void ChildExec(const char *cmdName, char *const paramArray[])
+{
+ int ret;
+ pid_t gid;
+
+ ret = setpgrp();
+ if (ret == -1) {
+ exit(1);
+ }
+
+ gid = getpgrp();
+ if (gid < 0) {
+ printf("get group id failed, pgrpid %d, errno %d\n", gid, errno);
+ exit(1);
+ }
+
+ ret = tcsetpgrp(STDIN_FILENO, gid);
+ if (ret != 0) {
+ printf("tcsetpgrp failed, errno %d\n", errno);
+ exit(1);
+ }
+
+ ret = execve(cmdName, paramArray, NULL);
+ if (ret == -1) {
+ perror("execve");
+ exit(-1);
+ }
+}
+
+int CheckExit(const char *cmdName, const CmdParsed *cmdParsed)
+{
+ int ret = 0;
+
+ if (strlen(cmdName) != CMD_EXIT_COMMAND_BYTES || strncmp(cmdName, CMD_EXIT_COMMAND, CMD_EXIT_COMMAND_BYTES) != 0) {
+ return 0;
+ }
+
+ if (cmdParsed->paramCnt > 1) {
+ printf("exit: too many arguments\n");
+ return -1;
+ }
+ if (cmdParsed->paramCnt == 1) {
+ char *p = NULL;
+ ret = strtol(cmdParsed->paramArray[0], &p, CMD_EXIT_CODE_BASE_DEC);
+ if (*p != '\0') {
+ printf("exit: bad number: %s\n", cmdParsed->paramArray[0]);
+ return -1;
+ }
+ }
+
+ exit(ret);
+}
+
+static void DoCmdExec(const char *cmdName, const char *cmdline, unsigned int len, const CmdParsed *cmdParsed)
+{
+ int ret;
+ pid_t forkPid;
+
+ if (strncmp(cmdline, CMD_EXEC_COMMAND, CMD_EXEC_COMMAND_BYTES) == 0) {
+ forkPid = fork();
+ if (forkPid < 0) {
+ printf("Faild to fork from shell\n");
+ return;
+ } else if (forkPid == 0) {
+ ChildExec(cmdParsed->paramArray[0], cmdParsed->paramArray);
+ } else {
+ waitpid(forkPid, 0, 0);
+ ret = tcsetpgrp(STDIN_FILENO, getpid());
+ if (ret != 0) {
+ printf("tcsetpgrp failed, errno %d\n", errno);
+ }
+ }
+ } else {
+ if (CheckExit(cmdName, cmdParsed) < 0) {
+ return;
+ }
+ (void)syscall(__NR_shellexec, cmdName, cmdline);
+ }
+}
+
+static void ParseAndExecCmdline(CmdParsed *cmdParsed, const char *cmdline, unsigned int len)
+{
+ int i;
+ unsigned int ret;
+ char shellWorkingDirectory[PATH_MAX + 1] = { 0 };
+ char *cmdlineOrigin = NULL;
+ char *cmdName = NULL;
+
+ cmdlineOrigin = strdup(cmdline);
+ if (cmdlineOrigin == NULL) {
+ printf("malloc failure in %s[%d]\n", __FUNCTION__, __LINE__);
+ return;
+ }
+
+ cmdName = GetCmdName(cmdline, len);
+ if (cmdName == NULL) {
+ free(cmdlineOrigin);
+ printf("malloc failure in %s[%d]\n", __FUNCTION__, __LINE__);
+ return;
+ }
+
+ ret = OsCmdParse((char *)cmdline, cmdParsed);
+ if (ret != SH_OK) {
+ printf("cmd parse failure in %s[%d]\n", __FUNCTION__, __LINE__);
+ goto OUT;
+ }
+
+ DoCmdExec(cmdName, cmdlineOrigin, len, cmdParsed);
+
+ if (getcwd(shellWorkingDirectory, PATH_MAX) != NULL) {
+ (void)OsShellSetWorkingDirectory(shellWorkingDirectory, (PATH_MAX + 1));
+ }
+
+OUT:
+ for (i = 0; i < cmdParsed->paramCnt; i++) {
+ if (cmdParsed->paramArray[i] != NULL) {
+ free(cmdParsed->paramArray[i]);
+ cmdParsed->paramArray[i] = NULL;
+ }
+ }
+ free(cmdName);
+ free(cmdlineOrigin);
+}
+
+unsigned int PreHandleCmdline(const char *input, char **output, unsigned int *outputlen)
+{
+ unsigned int shiftLen, execLen, newLen;
+ unsigned int removeLen = strlen("./"); /* "./" needs to be removed if it exists */
+ unsigned int ret;
+ char *newCmd = NULL;
+ char *execCmd = CMD_EXEC_COMMAND;
+ const char *cmdBuf = input;
+ unsigned int cmdBufLen = strlen(cmdBuf);
+ char *shiftStr = (char *)malloc(cmdBufLen + 1);
+ errno_t err;
+
+ if (shiftStr == NULL) {
+ printf("malloc failure in %s[%d]\n", __FUNCTION__, __LINE__);
+ return SH_NOK;
+ }
+ (void)memset_s(shiftStr, cmdBufLen + 1, 0, cmdBufLen + 1);
+
+ /* Call function 'OsCmdKeyShift' to squeeze and clear useless or overmuch space if string buffer */
+ ret = OsCmdKeyShift(cmdBuf, shiftStr, cmdBufLen + 1);
+ shiftLen = strlen(shiftStr);
+ if ((ret != SH_OK) || (shiftLen == 0)) {
+ ret = SH_NOK;
+ goto END_FREE_SHIFTSTR;
+ }
+ *output = shiftStr;
+ *outputlen = shiftLen;
+
+ /* Check and parse "./", located at the first two characters of the cmd */
+ if ((shiftLen > removeLen) && (shiftStr[0] == '.') && (shiftStr[1] == '/')) {
+ execLen = strlen(execCmd);
+ newLen = execLen + shiftLen - removeLen; /* i.e., newLen - execLen == shiftLen - removeLen */
+ newCmd = (char *)malloc(newLen + 1);
+ if (newCmd == NULL) {
+ ret = SH_NOK;
+ printf("malloc failure in %s[%d]\n", __FUNCTION__, __LINE__);
+ goto END_FREE_SHIFTSTR;
+ }
+
+ err = memcpy_s(newCmd, newLen, execCmd, execLen);
+ if (err != EOK) {
+ printf("memcpy_s failure in %s[%d]\n", __FUNCTION__, __LINE__);
+ ret = SH_NOK;
+ goto END_FREE_NEWCMD;
+ }
+
+ err = memcpy_s(newCmd + execLen, newLen - execLen, shiftStr + removeLen, shiftLen - removeLen);
+ if (err != EOK) {
+ printf("memcpy_s failure in %s[%d]\n", __FUNCTION__, __LINE__);
+ ret = SH_NOK;
+ goto END_FREE_NEWCMD;
+ }
+ newCmd[newLen] = '\0';
+
+ *output = newCmd;
+ *outputlen = newLen;
+ ret = SH_OK;
+ goto END_FREE_SHIFTSTR;
+ } else {
+ ret = SH_OK;
+ goto END;
+ }
+END_FREE_NEWCMD:
+ free(newCmd);
+END_FREE_SHIFTSTR:
+ free(shiftStr);
+END:
+ return ret;
+}
+
+static void ExecCmdline(const char *cmdline)
+{
+ unsigned int ret;
+ char *output = NULL;
+ unsigned int outputlen;
+ CmdParsed cmdParsed;
+
+ if (cmdline == NULL) {
+ return;
+ }
+
+ /* strip out unnecessary characters */
+ ret = PreHandleCmdline(cmdline, &output, &outputlen);
+ if (ret == SH_NOK) {
+ return;
+ }
+
+ (void)memset_s(&cmdParsed, sizeof(CmdParsed), 0, sizeof(CmdParsed));
+ ParseAndExecCmdline(&cmdParsed, output, outputlen);
+ free(output);
+}
+
+void RecycleZombieChild(void)
+{
+ while (waitpid(-1, NULL, WNOHANG) > 0) {
+ continue;
+ }
+}
+
+static void ShellCmdProcess(ShellCB *shellCB)
+{
+ char *buf = NULL;
+ while (1) {
+ /* recycle zombine child process */
+ RecycleZombieChild();
+ buf = GetCmdline(shellCB);
+ if (buf == NULL) {
+ break;
+ }
+ if (buf[0] == CHAR_CTRL_C) {
+ printf("^C");
+ buf[0] = '\n';
+ }
+ printf("\n");
+ ExecCmdline(buf);
+ ShellSaveHistoryCmd(buf, shellCB);
+ shellCB->cmdMaskKeyLink = shellCB->cmdHistoryKeyLink;
+ printf(SHELL_PROMPT);
+ }
+}
+
+void *ShellTask(void *argv)
+{
+ int ret;
+ ShellCB *shellCB = (ShellCB *)argv;
+
+ if (shellCB == NULL) {
+ return NULL;
+ }
+
+ ret = prctl(PR_SET_NAME, "ShellTask");
+ if (ret != SH_OK) {
+ return NULL;
+ }
+
+ printf(SHELL_PROMPT);
+ while (1) {
+ ret = ShellPend(shellCB);
+ if (ret == SH_OK) {
+ ShellCmdProcess(shellCB);
+ } else if (ret != SH_OK) {
+ break;
+ }
+ }
+
+ return NULL;
+}
+
+int ShellTaskInit(ShellCB *shellCB)
+{
+ unsigned int ret;
+ size_t stackSize = SHELL_TASK_STACKSIZE;
+ void *arg = NULL;
+ pthread_attr_t attr;
+
+ if (shellCB == NULL) {
+ return SH_NOK;
+ }
+
+ ret = pthread_attr_init(&attr);
+ if (ret != SH_OK) {
+ return SH_NOK;
+ }
+
+ pthread_attr_setstacksize(&attr, stackSize);
+ arg = (void *)shellCB;
+ ret = pthread_create(&shellCB->shellTaskHandle, &attr, &ShellTask, arg);
+ if (ret != SH_OK) {
+ return SH_NOK;
+ }
+
+ return ret;
+}
+
+static int ShellKernelReg(unsigned int shellHandle)
+{
+ return ioctl(STDIN_FILENO, CONSOLE_CONTROL_REG_USERTASK, shellHandle);
+}
+
+void *ShellEntry(void *argv)
+{
+ char ch;
+ int ret;
+ int n;
+ pid_t tid = syscall(__NR_gettid);
+ ShellCB *shellCB = (ShellCB *)argv;
+
+ if (shellCB == NULL) {
+ return NULL;
+ }
+
+ (void)memset_s(shellCB->shellBuf, SHOW_MAX_LEN, 0, SHOW_MAX_LEN);
+
+ ret = prctl(PR_SET_NAME, "ShellEntry");
+ if (ret != SH_OK) {
+ return NULL;
+ }
+
+ ret = ShellKernelReg((int)tid);
+ if (ret != 0) {
+ printf("another shell is already running!\n");
+ exit(-1);
+ }
+
+ while (1) {
+ n = read(0, &ch, 1);
+ if (n == 1) {
+ ShellCmdLineParse(ch, (OutputFunc)printf, shellCB);
+ }
+ }
+ return NULL;
+}
+
+int ShellEntryInit(ShellCB *shellCB)
+{
+ int ret;
+ size_t stackSize = SHELL_ENTRY_STACKSIZE;
+ void *arg = NULL;
+ pthread_attr_t attr;
+
+ if (shellCB == NULL) {
+ return SH_NOK;
+ }
+
+ ret = pthread_attr_init(&attr);
+ if (ret != SH_OK) {
+ return SH_NOK;
+ }
+
+ pthread_attr_setstacksize(&attr, stackSize);
+ arg = (void *)shellCB;
+ ret = pthread_create(&shellCB->shellEntryHandle, &attr, &ShellEntry, arg);
+ if (ret != SH_OK) {
+ return SH_NOK;
+ }
+
+ return ret;
+}
+
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/tftp/BUILD.gn b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/tftp/BUILD.gn
new file mode 100644
index 00000000..2c00ec02
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/tftp/BUILD.gn
@@ -0,0 +1,41 @@
+# 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("//kernel/liteos_a/liteos.gni")
+
+executable("tftp") {
+ sources = [
+ "src/main.c",
+ "src/tftpc.c",
+ ]
+
+ deps = [ "$LITEOSTHIRDPARTY/bounds_checking_function:libsec_static" ]
+
+ include_dirs = [ "include" ]
+}
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/tftp/Makefile b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/tftp/Makefile
new file mode 100644
index 00000000..5e12e7dd
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/tftp/Makefile
@@ -0,0 +1,45 @@
+# 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 $(APPSTOPDIR)/config.mk
+
+APP_NAME := $(notdir $(shell pwd))
+
+SECUREC_DIR := $(LITEOSTHIRDPARTY)/bounds_checking_function
+
+LOCAL_SRCS = $(wildcard src/*.c)
+LOCAL_SRCS += $(wildcard $(SECUREC_DIR)/src/*.c)
+
+LOCAL_INCLUDE := \
+ -I include \
+ -I $(SECUREC_DIR)/include
+
+LOCAL_FLAGS += $(LOCAL_INCLUDE)
+
+include $(APP)
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/tftp/include/tftpc.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/tftp/include/tftpc.h
new file mode 100644
index 00000000..1ada9b43
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/tftp/include/tftpc.h
@@ -0,0 +1,309 @@
+/*
+ * 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 TFTPC_H
+#define TFTPC_H
+
+#include "types_adapt.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)
+
+/** @cond liteos
+* @defgroup TFTP_Interfaces
+* @ingroup Enums
+* * This section contains the TFTP enums.
+*/
+/**
+*
+* This Enum is used to specify the transfer mode of the file to be handled by TFTP client.
+*/
+typedef enum tagTFTPC_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 tagTFTPC_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. */
+
+ /**< This is the error sent by the server when host name cannot be resolved. */
+ TFTPC_CANNOT_RESOLVE_HOSTNAME = 7,
+ TFTPC_INVALID_PARAVALUE = 8, /**< Input parameters passed to TFTP interfaces are invalid. */
+
+ /**< Error detected in TFTP packet or the error received from the TFTP server. */
+ TFTPC_PROTO_ERROR = 9,
+ /**< Error during packet synchronization while sending or unexpected packet is received. */
+ TFTPC_SYNC_FAILURE = 10,
+ /**< File size limit crossed, Max block can be 0xFFFF, each block containing 512 bytes. */
+ TFTPC_FILE_TOO_BIG = 11,
+ 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. */
+
+ /**< TFTP server returned error signifying that the DISK is full to write. */
+ TFTPC_DISK_FULL = 15,
+ TFTPC_FILE_EXISTS = 16, /**< TFTP server returned error signifying that the file exists. */
+
+ /**< tftp_put_file_by_filename returned error signifying that the source file name do not exist. */
+ TFTPC_FILE_NOT_EXIST = 17,
+ 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. */
+
+ /**< Error when the received packet is less than 4 bytes (error length) or greater than 512 bytes. */
+ TFTPC_PKT_SIZE_ERROR = 24,
+ 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. */
+
+ /**< IOCTL function failed at TFTP client while setting the socket to non-block. */
+ TFTPC_IOCTLSOCKET_FAILURE = 28,
+ TFTPC_MEMCPY_FAILURE = 29 /**< TFTP memcpy failure. */
+} TFTPC_ERR_CODE_E;
+
+typedef enum tagTFTPC_OpCode {
+ TFTPC_OP_RRQ = 1, /* read request */
+ TFTPC_OP_WRQ, /* write request */
+ TFTPC_OP_DATA, /* data packet */
+ TFTPC_OP_ACK, /* acknowledgment */
+ 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 usBlknum; /* block number */
+ u8_t ucDataBuf[TFTP_BLKSIZE]; /* Actual data */
+} TFTPC_DATA_S;
+
+
+/* TFTP error packet */
+typedef struct tagTFTPC_ERROR {
+ u16_t usErrNum; /* error number */
+ u8_t ucErrMesg[TFTP_MAXERRSTRSIZE]; /* error message */
+} TFTPC_ERROR_S;
+
+
+/* TFTP packet format */
+typedef struct tagTFTPC_PACKET {
+ u16_t usOpcode; /* Opcode value */
+ union {
+ /* it contains mode and filename */
+ s8_t ucName_Mode[TFTP_MAX_PATH_LENGTH + TFTP_MAX_MODE_SIZE];
+ u16_t usBlknum; /* 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] ulHostAddr IP address of Host. This is the TFTP server IP. [NA]
+* @param[in] usTftpServPort TFTP server port. If the value is passed as 0 then the default TFTP
+* PORT 69 is used. [NA]
+* @param[in] ucTftpTransMode File transfer mode, either TRANSFER_MODE_BINARY or TRANSFER_MODE_ASCII. [NA]
+* @param[in] szSrcFileName Source file in the tftp server. [NA]
+* @param[in] szDestDirPath 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 ulHostAddr,
+ u16_t usTftpServPort,
+ u8_t ucTftpTransMode,
+ s8_t *szSrcFileName,
+ s8_t *szDestDirPath);
+
+
+/* @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] ulHostAddr Indicates the IP address of Host. This is the TFTP server IP.
+* @param[in] usTftpServPort Indicates the TFTP server port. If the value is passed as 0 then the default TFTP
+* PORT 69 is used.
+* @param[in] ucTftpTransMode Indicates the file transfer mode, either TRANSFER_MODE_BINARY or TRANSFER_MODE_ASCII.
+* @param[in] szSrcFileName Indicates the source file in the client.
+* @param[in] szDestDirPath 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 ulHostAddr,
+ u16_t usTftpServPort,
+ u8_t cTftpTransMode,
+ s8_t *szSrcFileName,
+ s8_t *szDestDirPath);
+
+#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] ulHostAddr Indicates the IP address of the Host. This is the TFTP server IP.
+* @param[in] usTftpServPort Indicates the TFTP server port. If the value is passed as 0 then the default TFTP
+* PORT 69 is used.
+* @param[in] ucTftpTransMode Indicates the File transfer mode, either TRANSFER_MODE_BINARY or TRANSFER_MODE_ASCII.
+* @param[in] szSrcFileName Indicates the Source file in the TFTP server.
+* @param[in] szDestMemAddr Indicates the target memory address in the client.
+* @param[in/out] ulFileLength 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 ulHostAddr,
+ u16_t usTftpServPort,
+ u8_t ucTftpTransMode,
+ s8_t *szSrcFileName,
+ s8_t *szDestMemAddr,
+ u32_t *ulFileLength);
+#endif
+
+#if defined (__cplusplus) && __cplusplus
+}
+#endif
+
+#endif /* LWIP_TFTP */
+
+#endif /* TFTPC_H */
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/tftp/include/types_adapt.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/tftp/include/types_adapt.h
new file mode 100644
index 00000000..5634495f
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/tftp/include/types_adapt.h
@@ -0,0 +1,88 @@
+/*
+ * 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 TYPES_ADAPT_H
+#define TYPES_ADAPT_H
+
+#include
+#include
+#include
+
+#define LWIP_TFTP 1
+#define LOSCFG_NET_LWIP_SACK_TFTP 1
+#define LOSCFG_SHELL_CMD_DEBUG 1
+
+#define u8_t uint8_t
+#define s8_t int8_t
+#define u16_t uint16_t
+#define s16_t int16_t
+#define u32_t uint32_t
+#define s32_t int32_t
+
+#define X8_F "02" PRIx8
+#define U16_F PRIu16
+#define S16_F PRId16
+#define X16_F PRIx16
+#define U32_F PRIu32
+#define S32_F PRId32
+#define X32_F PRIx32
+#define SZT_F PRIuPTR
+
+#define PRINTK(fmt, ...) printf(fmt, ##__VA_ARGS__)
+#define LWIP_ASSERT(msg, expr) assert(expr)
+#define LWIP_DEBUGF(module, msg) PRINTK msg
+
+#define LOS_OK 0
+#define LOS_NOK 1
+#define ERR_OK 0
+#define EOK 0
+
+#define mem_malloc malloc
+#define mem_free free
+#define lwip_socket socket
+#define lwip_ioctl ioctl
+#define lwip_close close
+#define lwip_bind bind
+#define lwip_sendto sendto
+#define lwip_recvfrom recvfrom
+
+#define IPADDR_NONE INADDR_NONE
+#define DEFFILEMODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)
+
+#define SHELLCMD_ENTRY(l, cmdType, cmdKey, paraNum, cmdHook) \
+int main(int argc, const char **argv) \
+{ \
+ return (int)cmdHook(argc, argv); \
+}
+
+typedef u32_t (*CmdCallBackFunc)(u32_t argc, const char **argv);
+
+#endif /* TYPES_ADAPT_H */
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/tftp/src/main.c b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/tftp/src/main.c
new file mode 100644
index 00000000..6a989f3c
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/tftp/src/main.c
@@ -0,0 +1,160 @@
+/*
+ * 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
+#include
+#include "tftpc.h"
+
+#ifdef LOSCFG_NET_LWIP_SACK_TFTP
+static int tcpip_init_finish = 1;
+static char *TftpError[] = {
+ "TFTP transfer finish\n",
+ "Error while creating UDP socket\n",
+ "Error while binding to the UDP socket\n",
+ "Error returned by select() system call\n",
+ "Error while receiving data from the peer\n",
+ "Error while sending data to the peer\n",
+ "Requested file is not found\n",
+ "This is the error sent by the server when hostname cannot be resolved\n",
+ "Input parameters passed to TFTP interfaces are invalid\n",
+ "Error detected in TFTP packet or the error received from the TFTP server\n",
+ "Error during packet synhronization while sending or unexpected packet is received\n",
+ "File size limit crossed, Max block can be 0xFFFF, each block containing 512 bytes\n",
+ "File name length greater than 256\n",
+ "Hostname IP is not valid\n",
+ "TFTP server returned file access error\n",
+ "TFTP server returned error signifying that the DISK is full to write\n",
+ "TFTP server returned error signifying that the file exist\n",
+ "The source file name do not exisits\n",
+ "Memory allocaion failed in TFTP client\n",
+ "File open failed\n",
+ "File read error\n",
+ "File create error\n",
+ "File write error\n",
+ "Max time expired while waiting for file to be recived\n",
+ "Error when the received packet is less than 4bytes(error length) or greater than 512bytes\n",
+ "Returned by TFTP server for protocol user error\n",
+ "The destination file path length greater than 256\n",
+ "Returned by TFTP server for undefined transfer ID\n",
+ "IOCTL function failed at TFTP client while setting the socket to non-block\n",
+};
+
+#ifndef ARRAY_SIZE
+#define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
+#endif
+
+u32_t osShellTftp(int argc, const char **argv)
+{
+ u32_t ulRemoteAddr = IPADDR_NONE;
+ const u16_t usTftpServPort = 69;
+ u8_t ucTftpGet = 0;
+ s8_t *szLocalFileName = NULL;
+ s8_t *szRemoteFileName = NULL;
+ u32_t ret;
+
+ int i = 1;
+ if (argc < 1 || argv == NULL) {
+ goto usage;
+ }
+
+ if (!tcpip_init_finish) {
+ PRINTK("%s: tcpip_init have not been called\n", __FUNCTION__);
+ return LOS_NOK;
+ }
+
+ while (i < argc) {
+ if (strcmp(argv[i], "-p") == 0) {
+ ucTftpGet = 0;
+ i++;
+ continue;
+ }
+
+ if (strcmp(argv[i], "-g") == 0) {
+ ucTftpGet = 1;
+ i++;
+ continue;
+ }
+
+ if (strcmp(argv[i], "-l") == 0 && ((i + 1) < argc)) {
+ szLocalFileName = (s8_t *)argv[i + 1];
+ i += 2;
+ continue;
+ }
+
+ if (strcmp(argv[i], "-r") == 0 && ((i + 1) < argc)) {
+ szRemoteFileName = (s8_t *)argv[i + 1];
+ i += 2;
+ continue;
+ }
+
+ if ((i + 1) == argc) {
+ ulRemoteAddr = inet_addr(argv[i]);
+ break;
+ }
+
+ goto usage;
+ }
+
+ if (ulRemoteAddr == IPADDR_NONE || szLocalFileName == NULL || szRemoteFileName == NULL) {
+ goto usage;
+ }
+
+ if (ucTftpGet) {
+ ret = lwip_tftp_get_file_by_filename(ntohl(ulRemoteAddr), usTftpServPort,
+ TRANSFER_MODE_BINARY, szRemoteFileName, szLocalFileName);
+ } else {
+ ret = lwip_tftp_put_file_by_filename(ntohl(ulRemoteAddr), usTftpServPort,
+ TRANSFER_MODE_BINARY, szLocalFileName, szRemoteFileName);
+ }
+
+ LWIP_ASSERT("TFTP UNKNOW ERROR!", ret < ARRAY_SIZE(TftpError));
+ PRINTK("%s", TftpError[ret]);
+ if (ret) {
+ return LOS_NOK;
+ } else {
+ return LOS_OK;
+ }
+usage:
+ PRINTK("usage:\nTransfer a file from/to tftp server\n");
+ PRINTK("tftp <-g/-p> -l FullPathLocalFile -r RemoteFile Host\n");
+ return LOS_NOK;
+}
+
+#ifdef LOSCFG_SHELL_CMD_DEBUG
+SHELLCMD_ENTRY(tftp_shellcmd, CMD_TYPE_EX, "tftp", XARGS, (CmdCallBackFunc)(uintptr_t)osShellTftp);
+#endif /* LOSCFG_SHELL_CMD_DEBUG */
+#endif /* LOSCFG_NET_LWIP_SACK_TFTP */
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/tftp/src/tftpc.c b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/tftp/src/tftpc.c
new file mode 100644
index 00000000..a1ab6f34
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/tftp/src/tftpc.c
@@ -0,0 +1,1720 @@
+/*
+ * 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.
+ */
+
+/* TFTP Client utility */
+
+#include "tftpc.h"
+
+#if LWIP_TFTP /* don't build if not configured for use in lwipopts.h */
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+/* Function Declarations */
+#ifdef LOSCFG_NET_LWIP_SACK_TFTP
+static u32_t lwip_tftp_create_bind_socket(s32_t *piSocketID);
+
+static s32_t lwip_tftp_make_tftp_packet(u16_t usOpcode, s8_t *szFileName,
+ u32_t ulMode, TFTPC_PACKET_S *pstPacket);
+
+static u32_t lwip_tftp_recv_from_server(s32_t iSockNum,
+ u32_t *pulSize,
+ TFTPC_PACKET_S *pstRecvBuf,
+ u32_t *pulIgnorePkt,
+ struct sockaddr_in *pstServerAddr,
+ TFTPC_PACKET_S *pstSendBuf);
+
+static u32_t lwip_tftp_send_to_server(s32_t iSockNum, u32_t ulSize,
+ TFTPC_PACKET_S *pstSendBuf,
+ struct sockaddr_in *pstServerAddr);
+
+static u32_t lwip_tftp_validate_data_pkt(s32_t iSockNum,
+ u32_t *pulSize,
+ TFTPC_PACKET_S *pstRecvBuf,
+ u16_t usCurrBlk, u32_t *pulResendPkt,
+ struct sockaddr_in *pstServerAddr);
+
+static u32_t lwip_tftp_inner_put_file(s32_t iSockNum, TFTPC_PACKET_S *pstSendBuf,
+ u32_t ulSendSize, u16_t usCurrBlk,
+ struct sockaddr_in *pstServerAddr);
+
+static void lwip_tftp_send_error(s32_t iSockNum, u32_t ulError, const char *szErrMsg,
+ struct sockaddr_in *pstServerAddr, TFTPC_PACKET_S *pstSendBuf);
+
+
+/* Create and bind a UDP socket. */
+u32_t lwip_tftp_create_bind_socket(s32_t *piSocketID)
+{
+ int retval;
+ struct sockaddr_in stClientAddr;
+ u32_t ulTempClientIp;
+ u32_t set_non_block_socket = 1;
+
+ /* create a socket */
+ *piSocketID = lwip_socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
+ if (*piSocketID == -1) {
+ LWIP_DEBUGF(TFTP_DEBUG, ("lwip_tftp_create_bind_socket : lwip_socket create socket failed\n"));
+ return TFTPC_SOCKET_FAILURE;
+ }
+
+ /* Make the socket as NON-BLOCKING. */
+ retval = lwip_ioctl(*piSocketID, (long)FIONBIO, &set_non_block_socket);
+ if (retval != 0) {
+ (void)lwip_close(*piSocketID);
+ *piSocketID = TFTP_NULL_INT32;
+ return TFTPC_IOCTLSOCKET_FAILURE;
+ }
+
+ ulTempClientIp = INADDR_ANY;
+
+ /* specify a local address for this socket */
+ (void)memset_s(&stClientAddr, sizeof(stClientAddr), 0, sizeof(stClientAddr));
+ stClientAddr.sin_family = AF_INET;
+ stClientAddr.sin_port = 0;
+ stClientAddr.sin_addr.s_addr = htonl(ulTempClientIp);
+
+ retval = lwip_bind(*piSocketID, (struct sockaddr *)&stClientAddr, sizeof(stClientAddr));
+ if (retval != 0) {
+ (void)lwip_close(*piSocketID);
+ *piSocketID = TFTP_NULL_INT32;
+
+ return TFTPC_BIND_FAILURE;
+ }
+
+ return ERR_OK;
+}
+
+
+/* Function to create TFTP packet.
+ usOpcode - indiacting the nature of the operation
+ pFileName -filename on which the operation needs to done
+ ulMode -mode in which the operation needs to done
+ pstPacket - packet generated
+ Returns packet address on success
+*/
+static s32_t lwip_tftp_make_tftp_packet(u16_t usOpcode, s8_t *szFileName, u32_t ulMode, TFTPC_PACKET_S *pstPacket)
+{
+ s8_t *pcCp = NULL;
+
+ pstPacket->usOpcode = htons(usOpcode);
+ pcCp = pstPacket->u.ucName_Mode;
+
+ /* Request packet format is:
+ | Opcode | Filename | 0 | Mode | 0 |
+ */
+ (void)strncpy_s((char *)pcCp, TFTP_MAX_PATH_LENGTH, (char *)szFileName, (TFTP_MAX_PATH_LENGTH - 1));
+ pcCp[(TFTP_MAX_PATH_LENGTH - 1)] = '\0';
+
+ pcCp += (strlen((char *)szFileName) + 1);
+ if (ulMode == TRANSFER_MODE_BINARY) {
+ (void)strncpy_s((char *)pcCp, TFTP_MAX_MODE_SIZE, "octet", (TFTP_MAX_MODE_SIZE - 1));
+ pcCp[(TFTP_MAX_MODE_SIZE - 1)] = '\0';
+ } else if (ulMode == TRANSFER_MODE_ASCII) {
+ (void)strncpy_s((char *)pcCp, TFTP_MAX_MODE_SIZE, "netascii", (TFTP_MAX_MODE_SIZE - 1));
+ pcCp[(TFTP_MAX_MODE_SIZE - 1)] = '\0';
+ }
+
+ pcCp += (strlen((char *)pcCp) + 1);
+
+ return (pcCp - (s8_t *)pstPacket);
+}
+
+/* Function to recv a packet from server
+ iSockNum - Socket Number
+ pstServerAddr - Server address
+ pulIgnorePkt - Ignore packet flag
+ pstRecvBuf - received packet
+ pulSize - Size of the packet
+*/
+u32_t lwip_tftp_recv_from_server(s32_t iSockNum, u32_t *pulSize, TFTPC_PACKET_S *pstRecvBuf, u32_t *pulIgnorePkt,
+ struct sockaddr_in *pstServerAddr, TFTPC_PACKET_S *pstSendBuf)
+{
+ u32_t ulError;
+ socklen_t slFromAddrLen;
+ struct sockaddr_in stFromAddr;
+ fd_set stReadfds;
+ struct timeval stTimeout;
+ u16_t usOpcode; /* Opcode value */
+ s32_t iRet;
+
+ slFromAddrLen = sizeof(stFromAddr);
+ stTimeout.tv_sec = TFTPC_TIMEOUT_PERIOD;
+ stTimeout.tv_usec = 0;
+
+ /* wait for DATA packet */
+ FD_ZERO(&stReadfds);
+ FD_SET(iSockNum, &stReadfds);
+
+ iRet = select((s32_t)(iSockNum + 1), &stReadfds, 0, 0, &stTimeout);
+ if (iRet == -1) {
+ return TFTPC_SELECT_ERROR;
+ } else if (iRet == 0) {
+ return TFTPC_TIMEOUT_ERROR; /* Select timeout occurred */
+ }
+
+ if (!FD_ISSET(iSockNum, &stReadfds)) {
+ return TFTPC_TIMEOUT_ERROR; /* FD not set*/
+ }
+
+ /* receive a packet from server */
+ iRet = lwip_recvfrom(iSockNum, (s8_t *)pstRecvBuf, TFTP_PKTSIZE, 0,
+ (struct sockaddr *)&stFromAddr, &slFromAddrLen);
+ if (iRet <= 0) {
+ return TFTPC_RECVFROM_ERROR;
+ }
+
+ /* If received packet size < minimum packet size */
+ if (iRet < TFTPC_FOUR) {
+ /* Send Error packet to server */
+ lwip_tftp_send_error(iSockNum,
+ TFTPC_PROTOCOL_PROTO_ERROR,
+ "Packet size < min size",
+ pstServerAddr, pstSendBuf);
+
+ return TFTPC_PKT_SIZE_ERROR;
+ }
+
+ /* convert network opcode to host format after receive. */
+ usOpcode = ntohs(pstRecvBuf->usOpcode);
+ /* if this packet is ERROR packet */
+ if (usOpcode == TFTPC_OP_ERROR) {
+ ulError = ntohs(pstRecvBuf->u.stTFTP_Err.usErrNum);
+
+ /*If the error is according to RFC,then convert to lwip error codes.
+ Constant values are used in the cases as these error codes are as per
+ the RFC, these are constant values returned by many standard TFTP
+ serevrs.*/
+ switch (ulError) {
+ case TFTPC_PROTOCOL_USER_DEFINED:
+ ulError = TFTPC_ERROR_NOT_DEFINED;
+ break;
+ case TFTPC_PROTOCOL_FILE_NOT_FOUND:
+ ulError = TFTPC_FILE_NOT_FOUND;
+ break;
+ case TFTPC_PROTOCOL_ACCESS_ERROR:
+ ulError = TFTPC_ACCESS_ERROR;
+ break;
+ case TFTPC_PROTOCOL_DISK_FULL:
+ ulError = TFTPC_DISK_FULL;
+ break;
+ case TFTPC_PROTOCOL_PROTO_ERROR:
+ ulError = TFTPC_PROTO_ERROR;
+ break;
+ case TFTPC_PROTOCOL_UNKNOWN_TRANSFER_ID:
+ ulError = TFTPC_UNKNOWN_TRANSFER_ID;
+ break;
+ case TFTPC_PROTOCOL_FILE_EXISTS:
+ ulError = TFTPC_FILE_EXISTS;
+ break;
+ case TFTPC_PROTOCOL_CANNOT_RESOLVE_HOSTNAME:
+ ulError = TFTPC_CANNOT_RESOLVE_HOSTNAME;
+ break;
+ default:
+ ulError = TFTPC_ERROR_NOT_DEFINED;
+ break;
+ }
+
+ /* If length of error msg > 100 chars */
+ pstRecvBuf->u.stTFTP_Err.ucErrMesg[TFTP_MAXERRSTRSIZE - 1] = '\0';
+
+ LWIP_DEBUGF(TFTP_DEBUG, ("lwip_tftp_recv_from_server : ERROR pkt received: %s\n",
+ pstRecvBuf->u.stTFTP_Err.ucErrMesg));
+
+ /* Now we get error block, so return. */
+ return ulError;
+ }
+
+ /* Store the size of received block */
+ *pulSize = (u32_t)iRet;
+
+ /* If received packet is first block of data(for get operation) or if
+ received packet is acknowledgment for write request (put operation)
+ store the received port number */
+ if (((usOpcode == TFTPC_OP_DATA) &&
+ (ntohs(pstRecvBuf->u.stTFTP_Data.usBlknum) == 1)) ||
+ ((usOpcode == TFTPC_OP_ACK) &&
+ (ntohs(pstRecvBuf->u.usBlknum) == 0))) {
+ /* If received packet from correct server */
+ if (stFromAddr.sin_addr.s_addr == pstServerAddr->sin_addr.s_addr) {
+ /* set the server port to received port */
+ pstServerAddr->sin_port = stFromAddr.sin_port;
+ } else {
+ /* Received packet form wrong server. */
+ LWIP_DEBUGF(TFTP_DEBUG,
+ ("lwip_tftp_recv_from_server : Received 1st packet from wrong Server or unknown server\n"));
+
+ /* Set ignore packet flag */
+ *pulIgnorePkt = 1;
+ }
+ } else {
+ /* If not first packet, check if the received packet is from correct
+ server and from correct port */
+ if ((stFromAddr.sin_addr.s_addr != pstServerAddr->sin_addr.s_addr) ||
+ (pstServerAddr->sin_port != stFromAddr.sin_port)) {
+ /* Received packet form wrong server or wrong port.Ignore packet. */
+ LWIP_DEBUGF(TFTP_DEBUG,
+ ("lwip_tftp_recv_from_server : Received a packet from wrong Server or unknown server\n"));
+
+ /* Set ignore packet flag */
+ *pulIgnorePkt = 1;
+ }
+ }
+
+ return ERR_OK;
+}
+
+/* Function to send a packet to server
+ iSockNum: Socket Number
+ ulSize: Size of the packet
+ pstSendBuf: Packet to send
+ pstServerAddr: Server address
+*/
+u32_t lwip_tftp_send_to_server(s32_t iSockNum,
+ u32_t ulSize,
+ TFTPC_PACKET_S *pstSendBuf,
+ struct sockaddr_in *pstServerAddr)
+{
+ s32_t iRet;
+
+ /* Send packet to server */
+ iRet = lwip_sendto(iSockNum, (s8_t *)pstSendBuf,
+ (size_t)ulSize, 0,
+ (struct sockaddr *)pstServerAddr,
+ sizeof(struct sockaddr_in));
+ /* Size of data sent not equal to size of packet */
+ if ((iRet == TFTP_NULL_INT32) || ((u32_t)iRet != ulSize)) {
+ return TFTPC_SENDTO_ERROR;
+ }
+
+ return ERR_OK;
+}
+
+/* lwip_tftp_validate_data_pkt
+* Get the data block from the received packet
+* @param Input iSockNum Socket Number
+* pulSize: Size of received packet,
+ pstRecvBuf - received packet
+ usCurrBlk - Current block number
+ * @param Output pulResendPkt - Resend packet flag
+ * @return VOS_OK on success.else error code*/
+
+u32_t lwip_tftp_validate_data_pkt(s32_t iSockNum,
+ u32_t *pulSize,
+ TFTPC_PACKET_S *pstRecvBuf,
+ u16_t usCurrBlk,
+ u32_t *pulResendPkt,
+ struct sockaddr_in *pstServerAddr)
+{
+ fd_set stReadfds;
+ struct timeval stTimeout;
+ struct sockaddr_in stFromAddr;
+ socklen_t ulFromAddrLen;
+ s32_t iRecvLen = (s32_t)*pulSize;
+ s32_t iError;
+ u16_t usBlknum;
+ u32_t ulLoopCnt = 0;
+
+ ulFromAddrLen = sizeof(stFromAddr);
+
+ /* Initialize from address to the server address at first */
+ if (memcpy_s((void *)&stFromAddr, sizeof(struct sockaddr_in), (void *)pstServerAddr, sizeof(stFromAddr)) != 0) {
+ LWIP_DEBUGF(TFTP_DEBUG, ("lwip_tftp_validate_data_pkt : memcpy_s error\n"));
+ return TFTPC_MEMCPY_FAILURE;
+ }
+
+ /* Get Block Number */
+ usBlknum = ntohs(pstRecvBuf->u.stTFTP_Data.usBlknum);
+ /* Now data blocks are not in sync. */
+ if (usBlknum != usCurrBlk) {
+ /* Set timeout value */
+ stTimeout.tv_sec = 1;
+ stTimeout.tv_usec = 0;
+
+ /* Reset any stored packets. */
+ FD_ZERO(&stReadfds);
+ FD_SET(iSockNum, &stReadfds);
+
+ iError = select((s32_t)(iSockNum + 1),
+ &stReadfds, 0, 0, &stTimeout);
+
+ /* Loop to get the last data packet from the receive buffer */
+ while ((iError != TFTP_NULL_INT32) && (iError != 0)) {
+ ulLoopCnt++;
+
+ /* 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.
+ */
+ if (ulLoopCnt > TFTPC_MAX_WAIT_IN_LOOP) {
+ LWIP_DEBUGF(TFTP_DEBUG, ("lwip_tftp_validate_data_pkt : unexpected packets are received repeatedly\n"));
+ *pulSize = TFTP_NULL_UINT32;
+ return TFTPC_PKT_SIZE_ERROR;
+ }
+
+ FD_ZERO(&stReadfds);
+ FD_SET(iSockNum, &stReadfds);
+
+ iRecvLen = lwip_recvfrom(iSockNum,
+ (s8_t *)pstRecvBuf,
+ TFTP_PKTSIZE, 0,
+ (struct sockaddr *)&stFromAddr,
+ &ulFromAddrLen);
+ if (iRecvLen == -1) {
+ *pulSize = TFTP_NULL_UINT32;
+
+ /* return from the function, recvfrom operation failed */
+ return TFTPC_RECVFROM_ERROR;
+ }
+
+ stTimeout.tv_sec = 1;
+ stTimeout.tv_usec = 0;
+ iError = select((s32_t)(iSockNum + 1), &stReadfds, 0, 0, &stTimeout);
+ }
+
+ /* If received packet size < minimum packet size */
+ if (iRecvLen < TFTPC_FOUR) {
+ return TFTPC_PKT_SIZE_ERROR;
+ }
+
+ /* Check if the received packet is from correct server and from
+ correct port
+ */
+ if ((stFromAddr.sin_addr.s_addr != pstServerAddr->sin_addr.s_addr) ||
+ (pstServerAddr->sin_port != stFromAddr.sin_port)) {
+ /* resend ack packet */
+ *pulResendPkt = 1;
+ LWIP_DEBUGF(TFTP_DEBUG, ("lwip_tftp_validate_data_pkt : Received pkt from unknown server\n"));
+
+ return ERR_OK;
+ }
+
+ /* if this packet is not DATA packet */
+ if (TFTPC_OP_DATA != ntohs(pstRecvBuf->usOpcode)) {
+ LWIP_DEBUGF(TFTP_DEBUG, ("lwip_tftp_validate_data_pkt : Received pkt not a DATA pkt\n"));
+
+ /* return from the function, incorrect packet received,
+ expected packet is data packet */
+ return TFTPC_PROTO_ERROR;
+ }
+
+ usBlknum = ntohs(pstRecvBuf->u.stTFTP_Data.usBlknum);
+ /* if we now have the earlier data packet, then the host probably
+ never got our acknowledge packet, now we will send it again. */
+ if (usBlknum == (usCurrBlk - 1)) {
+ /* resend ack packet */
+ *pulResendPkt = 1;
+ LWIP_DEBUGF(TFTP_DEBUG, ("lwip_tftp_validate_data_pkt : Received previous DATA pkt\n"));
+
+ return ERR_OK;
+ }
+
+ /* If the block of data received is not current block or also
+ previous block, then it is abnormal case. */
+ if (usBlknum != usCurrBlk) {
+ LWIP_DEBUGF(TFTP_DEBUG,
+ ("lwip_tftp_validate_data_pkt : Received DATA pkt no. %"S32_F" instead of pkt no.%"S32_F"\n",
+ usBlknum, usCurrBlk));
+
+ return TFTPC_SYNC_FAILURE;
+ }
+ }
+
+ *pulSize = (u32_t)iRecvLen;
+ return ERR_OK;
+}
+
+/* Send an error packet to the server
+ iSockNum : Socket Number
+ ulError: Error code
+ szErrMsg - Error message
+ pstServerAddr - Server address
+*/
+static void lwip_tftp_send_error(s32_t iSockNum, u32_t ulError, const char *szErrMsg,
+ struct sockaddr_in *pstServerAddr, TFTPC_PACKET_S *pstSendBuf)
+{
+ u16_t usOpCode = TFTPC_OP_ERROR;
+
+ if (memset_s((void *)pstSendBuf, sizeof(TFTPC_PACKET_S), 0, sizeof(TFTPC_PACKET_S)) != 0) {
+ LWIP_DEBUGF(TFTP_DEBUG, ("lwip_tftp_send_error : memset_s error\n"));
+ return;
+ }
+
+ /* Set up the send buffer */
+ pstSendBuf->usOpcode = htons(usOpCode);
+ pstSendBuf->u.stTFTP_Err.usErrNum = htons((u16_t)ulError);
+
+ if (strncpy_s((char *)(pstSendBuf->u.stTFTP_Err.ucErrMesg), TFTP_MAXERRSTRSIZE,
+ (char *)szErrMsg, (TFTP_MAXERRSTRSIZE - 1)) != EOK) {
+ LWIP_DEBUGF(TFTP_DEBUG, ("lwip_tftp_send_error : strncpy_s error\n"));
+ return;
+ }
+ pstSendBuf->u.stTFTP_Err.ucErrMesg[(TFTP_MAXERRSTRSIZE - 1)] = '\0';
+
+ /* Send to server */
+ if (lwip_tftp_send_to_server(iSockNum,
+ sizeof(TFTPC_PACKET_S),
+ pstSendBuf,
+ pstServerAddr) != ERR_OK) {
+ LWIP_DEBUGF(TFTP_DEBUG, ("lwip_tftp_send_to_server error."));
+ return;
+ }
+}
+
+/* INTEFACE to get a file using filename
+ ulHostAddr - IP address of Host
+ szSrcFileName - Source file
+ szDestDirPath - Destination file path
+*/
+u32_t lwip_tftp_get_file_by_filename(u32_t ulHostAddr,
+ u16_t usTftpServPort,
+ u8_t ucTftpTransMode,
+ s8_t *szSrcFileName,
+ s8_t *szDestDirPath)
+{
+ s32_t iSockNum = TFTP_NULL_INT32;
+ u32_t ulSrcStrLen;
+ u32_t ulDestStrLen;
+ u32_t ulSize;
+ u32_t ulRecvSize = TFTP_NULL_UINT32;
+ s32_t iErrCode;
+ u32_t ulErrCode;
+ u16_t usReadReq;
+ u16_t usTempServPort;
+ s8_t *pszTempDestName = NULL;
+ s8_t *szTempSrcName = NULL;
+ u32_t ulCurrBlk = 1;
+ u32_t ulResendPkt = 0; /*Resend the previous packet*/
+ u32_t ulIgnorePkt = 0; /*Ignore received packet*/
+ u32_t ulTotalTime = 0;
+ u32_t isLocalFileOpened = false;
+
+ TFTPC_PACKET_S *pstSendBuf = NULL;
+ TFTPC_PACKET_S *pstRecvBuf = NULL;
+ struct sockaddr_in stServerAddr;
+ struct stat sb;
+ u32_t IsDirExist = 0;
+ s32_t fp = -1;
+
+ /*Validate the parameters*/
+ if ((szSrcFileName == NULL) || (szDestDirPath == NULL)) {
+ return TFTPC_INVALID_PARAVALUE;
+ }
+
+ if ((ucTftpTransMode != TRANSFER_MODE_BINARY) && (ucTftpTransMode != TRANSFER_MODE_ASCII)) {
+ return TFTPC_INVALID_PARAVALUE;
+ }
+
+ /*check IP address not within ( 1.0.0.0 - 126.255.255.255 )
+ and ( 128.0.0.0 - 223.255.255.255 ) range.*/
+ if (!(((ulHostAddr >= TFTPC_IP_ADDR_MIN) &&
+ (ulHostAddr <= TFTPC_IP_ADDR_EX_RESV)) ||
+ ((ulHostAddr >= TFTPC_IP_ADDR_CLASS_B) &&
+ (ulHostAddr <= TFTPC_IP_ADDR_EX_CLASS_DE)))) {
+ return TFTPC_IP_NOT_WITHIN_RANGE;
+ }
+
+ /*Check validity of source filename*/
+ ulSrcStrLen = strlen((char *)szSrcFileName);
+ if ((ulSrcStrLen == 0) || (ulSrcStrLen >= TFTP_MAX_PATH_LENGTH)) {
+ return TFTPC_SRC_FILENAME_LENGTH_ERROR;
+ }
+
+ /*Check validity of destination path*/
+ ulDestStrLen = strlen((char *)szDestDirPath);
+ if ((ulDestStrLen >= TFTP_MAX_PATH_LENGTH) || (ulDestStrLen == 0)) {
+ return TFTPC_DEST_PATH_LENGTH_ERROR;
+ }
+
+ pstSendBuf = (TFTPC_PACKET_S *)mem_malloc(sizeof(TFTPC_PACKET_S));
+ if (pstSendBuf == NULL) {
+ return TFTPC_MEMALLOC_ERROR;
+ }
+
+ pstRecvBuf = (TFTPC_PACKET_S *)mem_malloc(sizeof(TFTPC_PACKET_S));
+ if (pstRecvBuf == NULL) {
+ mem_free(pstSendBuf);
+ return TFTPC_MEMALLOC_ERROR;
+ }
+
+ pszTempDestName = (s8_t *)mem_malloc(TFTP_MAX_PATH_LENGTH);
+ if (pszTempDestName == NULL) {
+ mem_free(pstSendBuf);
+ mem_free(pstRecvBuf);
+ return TFTPC_MEMALLOC_ERROR;
+ }
+
+ /* First time initialize the buffers */
+ (void)memset_s((void *)pstSendBuf, sizeof(TFTPC_PACKET_S), 0, sizeof(TFTPC_PACKET_S));
+ (void)memset_s((void *)pstRecvBuf, sizeof(TFTPC_PACKET_S), 0, sizeof(TFTPC_PACKET_S));
+
+ /*If given src filename is a relative path extract
+ the file name from the path*/
+ if ((0 != strchr((char *)szSrcFileName, '/')) || (0 != strchr((char *)szSrcFileName, '\\'))) {
+ /*Move to the end of the src file path*/
+ szTempSrcName = szSrcFileName + (ulSrcStrLen - 1);
+
+ while (((*(szTempSrcName - 1) != '/') &&
+ (*(szTempSrcName - 1) != '\\')) &&
+ (szTempSrcName != szSrcFileName)) {
+ szTempSrcName--;
+ }
+
+ /*Get length of the extracted src filename*/
+ ulSrcStrLen = strlen((char *)szTempSrcName);
+ } else {
+ /*If not a relative src path use the given src filename*/
+ szTempSrcName = szSrcFileName;
+ }
+
+ (void)memset_s(pszTempDestName, TFTP_MAX_PATH_LENGTH, 0, TFTP_MAX_PATH_LENGTH);
+ if (strncpy_s((char *)pszTempDestName, TFTP_MAX_PATH_LENGTH, (char *)szDestDirPath, TFTP_MAX_PATH_LENGTH - 1) !=
+ 0) {
+ ulErrCode = TFTPC_MEMCPY_FAILURE;
+ goto err_handler;
+ }
+ pszTempDestName[TFTP_MAX_PATH_LENGTH - 1] = '\0';
+
+ if (stat((char *)pszTempDestName, &sb) == 0 && S_ISDIR(sb.st_mode)) {
+ IsDirExist = 1;
+ }
+
+ if (IsDirExist == 1) {
+ /*The filename is not present concat source filename and try*/
+ if ((ulDestStrLen + ulSrcStrLen) >= TFTP_MAX_PATH_LENGTH) {
+ /*If concatenating src filename exceeds 256 bytes*/
+ ulErrCode = TFTPC_DEST_PATH_LENGTH_ERROR;
+ goto err_handler;
+ }
+
+ /*Check if / present at end of string*/
+ if ((pszTempDestName[ulDestStrLen - 1] != '/') &&
+ (pszTempDestName[ulDestStrLen - 1] != '\\')) {
+ if ((ulDestStrLen + ulSrcStrLen + 1) >= TFTP_MAX_PATH_LENGTH) {
+ /*If concatenating src filename exceeds 256 bytes*/
+ ulErrCode = TFTPC_DEST_PATH_LENGTH_ERROR;
+ goto err_handler;
+ }
+
+ /*If not present concat / to the path*/
+ if (strncat_s((char *)pszTempDestName, (TFTP_MAX_PATH_LENGTH - strlen((char *)pszTempDestName)),
+ "/", TFTP_MAX_PATH_LENGTH - strlen((char *)pszTempDestName) - 1) != 0) {
+ ulErrCode = TFTPC_ERROR_NOT_DEFINED;
+ goto err_handler;
+ }
+ }
+
+ /*Concatenate src filename to destination path*/
+ if (strncat_s((char *)pszTempDestName, (TFTP_MAX_PATH_LENGTH - strlen((char *)pszTempDestName)),
+ (char *)szTempSrcName, TFTP_MAX_PATH_LENGTH - strlen((char *)pszTempDestName) - 1) != 0) {
+ ulErrCode = TFTPC_ERROR_NOT_DEFINED;
+ goto err_handler;
+ }
+ }
+
+ ulErrCode = lwip_tftp_create_bind_socket(&iSockNum);
+ if (ulErrCode != ERR_OK) {
+ goto err_handler;
+ }
+
+ if (usTftpServPort == 0) {
+ usTftpServPort = TFTPC_SERVER_PORT;
+ }
+
+ usTempServPort = usTftpServPort;
+
+ /* set server IP address */
+ (void)memset_s(&stServerAddr, sizeof(stServerAddr), 0, sizeof(stServerAddr));
+ stServerAddr.sin_family = AF_INET;
+ stServerAddr.sin_port = htons(usTempServPort);
+ stServerAddr.sin_addr.s_addr = htonl(ulHostAddr);
+
+ /* Make a request packet - TFTPC_OP_RRQ */
+ ulSize = (u32_t)lwip_tftp_make_tftp_packet(TFTPC_OP_RRQ, szSrcFileName,
+ (u32_t)ucTftpTransMode,
+ pstSendBuf);
+ ulErrCode = lwip_tftp_send_to_server(iSockNum, ulSize,
+ pstSendBuf, &stServerAddr);
+ if (ulErrCode != ERR_OK) {
+ /* send to server failed */
+ (void)lwip_close(iSockNum);
+ goto err_handler;
+ }
+
+ for (;;) {
+ if (ulIgnorePkt > 0) {
+ ulIgnorePkt = 0;
+ }
+
+ ulErrCode = lwip_tftp_recv_from_server(iSockNum, &ulRecvSize, pstRecvBuf,
+ &ulIgnorePkt, &stServerAddr, pstSendBuf);
+ /* If select timeout occurred */
+ if (ulErrCode == TFTPC_TIMEOUT_ERROR) {
+ ulTotalTime++;
+ if (ulTotalTime < TFTPC_MAX_SEND_REQ_ATTEMPTS) {
+ /* Max attempts not reached. Resend packet */
+ ulErrCode = lwip_tftp_send_to_server(iSockNum, ulSize,
+ pstSendBuf, &stServerAddr);
+ if (ulErrCode != ERR_OK) {
+ (void)lwip_close(iSockNum);
+ if (isLocalFileOpened == true) {
+ close(fp);
+ }
+ goto err_handler;
+ }
+
+ continue;
+ } else {
+ /* return from the function, max attempts limit reached */
+ (void)lwip_close(iSockNum);
+ if (isLocalFileOpened == true) {
+ close(fp);
+ }
+ ulErrCode = TFTPC_TIMEOUT_ERROR;
+ goto err_handler;
+ }
+ } else if (ulErrCode != ERR_OK) {
+ (void)lwip_close(iSockNum);
+ if (isLocalFileOpened == true) {
+ close(fp);
+ }
+ goto err_handler;
+ }
+
+ /* Now we have receive block from different server. */
+ if (ulIgnorePkt > 0) {
+ /*Continue without processing this block. */
+ continue;
+ }
+
+ /* if this packet is unkonwn or incorrect packet */
+ if (ntohs(pstRecvBuf->usOpcode) != TFTPC_OP_DATA) {
+ /* Send error packet to server */
+ lwip_tftp_send_error(iSockNum,
+ TFTPC_PROTOCOL_PROTO_ERROR,
+ "Protocol error.",
+ &stServerAddr, pstSendBuf);
+
+ (void)lwip_close(iSockNum);
+ if (isLocalFileOpened == true) {
+ close(fp);
+ }
+
+ LWIP_DEBUGF(TFTP_DEBUG, ("lwip_tftp_get_file_by_filename : Received pkt not DATA pkt\n"));
+
+ ulErrCode = TFTPC_PROTO_ERROR;
+ goto err_handler;
+ }
+
+ /* Now the number of tries will be reset. */
+ ulTotalTime = 0;
+
+ /* Validate received DATA packet. */
+ ulErrCode = lwip_tftp_validate_data_pkt(iSockNum, &ulRecvSize,
+ pstRecvBuf, (u16_t)ulCurrBlk,
+ &ulResendPkt,
+ &stServerAddr);
+ if (ulErrCode != ERR_OK) {
+ /* Send Error packet to server */
+ if (ulErrCode != TFTPC_RECVFROM_ERROR) {
+ lwip_tftp_send_error(iSockNum,
+ TFTPC_PROTOCOL_PROTO_ERROR,
+ "Received unexpected packet",
+ &stServerAddr, pstSendBuf);
+ }
+
+ (void)lwip_close(iSockNum);
+ if (isLocalFileOpened == true) {
+ close(fp);
+ }
+
+ goto err_handler;
+ }
+
+ /* Received previous data block again. Resend last packet */
+ if (ulResendPkt > 0) {
+ /* Now set ulResendPkt to 0 to send the last packet. */
+ ulResendPkt = 0;
+ ulErrCode = lwip_tftp_send_to_server(iSockNum, ulSize,
+ pstSendBuf, &stServerAddr);
+ if (ulErrCode != ERR_OK) {
+ (void)lwip_close(iSockNum);
+ if (isLocalFileOpened == true) {
+ close(fp);
+ }
+
+ goto err_handler;
+ }
+
+ /* Continue in loop to send last packet again. */
+ continue;
+ }
+
+ /* Get the size of the data block received */
+ ulRecvSize -= TFTP_HDRSIZE;
+
+ /* Check if the size of the received data block > max size */
+ if (ulRecvSize > TFTP_BLKSIZE) {
+ /* Send Error packet to server */
+ lwip_tftp_send_error(iSockNum,
+ TFTPC_PROTOCOL_PROTO_ERROR,
+ "Packet size > max size",
+ &stServerAddr, pstSendBuf);
+
+ (void)lwip_close(iSockNum);
+ if (isLocalFileOpened == true) {
+ close(fp);
+ }
+
+ LWIP_DEBUGF(TFTP_DEBUG, ("lwip_tftp_get_file_by_filename : Packet size > max size\n"));
+
+ ulErrCode = TFTPC_PKT_SIZE_ERROR;
+ goto err_handler;
+ }
+
+ usReadReq = (u16_t)TFTPC_OP_ACK;
+ pstSendBuf->usOpcode = htons(usReadReq);
+ pstSendBuf->u.usBlknum = htons((u16_t)ulCurrBlk);
+ ulSize = TFTP_HDRSIZE;
+
+ if (isLocalFileOpened == false) {
+ fp = open((char *)pszTempDestName, (O_WRONLY | O_CREAT | O_TRUNC), DEFFILEMODE);
+ if (fp == TFTP_NULL_INT32) {
+ ulErrCode = TFTPC_FILECREATE_ERROR;
+ (void)lwip_close(iSockNum);
+ goto err_handler;
+ }
+ isLocalFileOpened = true;
+ }
+
+ if (ulRecvSize != TFTP_BLKSIZE) {
+ (void)lwip_tftp_send_to_server(iSockNum, ulSize, pstSendBuf, &stServerAddr);
+
+ /* If the received packet has only header and do not have payload, the return failure */
+ if (ulRecvSize != 0) {
+ /* Write the last packet to the file */
+ iErrCode = write(fp, (void *)pstRecvBuf->u.stTFTP_Data.ucDataBuf, (size_t)ulRecvSize);
+ if (ulRecvSize != (u32_t)iErrCode) {
+ /* Write to file failed. */
+ lwip_tftp_send_error(iSockNum,
+ TFTPC_PROTOCOL_USER_DEFINED,
+ "Write to file failed",
+ &stServerAddr, pstSendBuf);
+
+ (void)lwip_close(iSockNum);
+ close(fp);
+
+ /* return from the function, file write failed */
+ ulErrCode = TFTPC_FILEWRITE_ERROR;
+ goto err_handler;
+ }
+ }
+
+ /* Now free allocated resourdes and return,
+ data block receiving is already completed */
+ (void)lwip_close(iSockNum);
+ close(fp);
+ ulErrCode = ERR_OK;
+ goto err_handler;
+ }
+
+ ulErrCode = lwip_tftp_send_to_server(iSockNum, ulSize,
+ pstSendBuf, &stServerAddr);
+ if (ulErrCode != ERR_OK) {
+ (void)lwip_close(iSockNum);
+ close(fp);
+ goto err_handler;
+ }
+
+ iErrCode = write(fp, (void *)pstRecvBuf->u.stTFTP_Data.ucDataBuf, (size_t)ulRecvSize);
+ if (ulRecvSize != (u32_t)iErrCode) {
+ /* Write to file failed. */
+ lwip_tftp_send_error(iSockNum,
+ TFTPC_PROTOCOL_USER_DEFINED,
+ "Write to file failed",
+ &stServerAddr, pstSendBuf);
+
+ (void)lwip_close(iSockNum);
+ close(fp);
+
+ /* return from the function, file write failed */
+ ulErrCode = TFTPC_FILEWRITE_ERROR;
+ goto err_handler;
+ }
+
+ /* form the ACK packet for the DATA packet received */
+ /* Go to the next packet no. */
+ ulCurrBlk++;
+
+ /* if the file is too big, exit */
+ if (ulCurrBlk > TFTP_MAX_BLK_NUM) {
+ /* Send error packet to server */
+ lwip_tftp_send_error(iSockNum,
+ TFTPC_PROTOCOL_USER_DEFINED,
+ "File is too big.",
+ &stServerAddr, pstSendBuf);
+
+ (void)lwip_close(iSockNum);
+ close(fp);
+ LWIP_DEBUGF(TFTP_DEBUG, ("lwip_tftp_get_file_by_filename : Data block number exceeded max value\n"));
+
+ ulErrCode = TFTPC_FILE_TOO_BIG;
+ goto err_handler;
+ }
+ }
+
+err_handler:
+ mem_free(pstSendBuf);
+ mem_free(pstRecvBuf);
+ mem_free(pszTempDestName);
+ return ulErrCode;
+}
+
+
+/* INTERFACE Function to put a file using filename
+ ulHostAddr: IP address of Host
+ szSrcFileName: Source file
+ szDestDirPath: Destination file path
+*/
+u32_t lwip_tftp_put_file_by_filename(u32_t ulHostAddr, u16_t usTftpServPort, u8_t ucTftpTransMode,
+ s8_t *szSrcFileName, s8_t *szDestDirPath)
+{
+ u32_t ulSrcStrLen;
+ u32_t ulDestStrLen;
+ s32_t iSockNum = TFTP_NULL_INT32;
+ s32_t iErrCode;
+ u32_t ulErrCode;
+ u16_t usTempServPort;
+ TFTPC_PACKET_S *pstSendBuf = NULL;
+ u16_t usReadReq;
+ u32_t ulSize;
+ s8_t *pucBuffer = 0;
+ s8_t *szTempDestName = NULL;
+
+ /*Initialize the block number*/
+ u16_t usCurrBlk = 0;
+ struct sockaddr_in stServerAddr;
+ struct stat buffer;
+ s32_t fp = -1;
+
+ /* Validate parameters */
+ if ((szSrcFileName == NULL) || (szDestDirPath == NULL)) {
+ return TFTPC_INVALID_PARAVALUE;
+ }
+
+ if ((ucTftpTransMode != TRANSFER_MODE_BINARY) && (ucTftpTransMode != TRANSFER_MODE_ASCII)) {
+ return TFTPC_INVALID_PARAVALUE;
+ }
+
+ /*check IP address not within ( 1.0.0.0 - 126.255.255.255 )
+ and ( 128.0.0.0 - 223.255.255.255 ) range.*/
+ if (!(((ulHostAddr >= TFTPC_IP_ADDR_MIN) &&
+ (ulHostAddr <= TFTPC_IP_ADDR_EX_RESV)) ||
+ ((ulHostAddr >= TFTPC_IP_ADDR_CLASS_B) &&
+ (ulHostAddr <= TFTPC_IP_ADDR_EX_CLASS_DE)))) {
+ return TFTPC_IP_NOT_WITHIN_RANGE;
+ }
+
+ /* If Src filename is empty or exceeded max length */
+ ulSrcStrLen = strlen((char *)szSrcFileName);
+ if ((ulSrcStrLen == 0) || (ulSrcStrLen >= TFTP_MAX_PATH_LENGTH)) {
+ return TFTPC_SRC_FILENAME_LENGTH_ERROR;
+ }
+
+ /* Check if source file exists */
+ if (stat((char *)szSrcFileName, &buffer) != 0) {
+ return TFTPC_FILE_NOT_EXIST;
+ }
+
+ /* Check if the file is too big */
+ if (buffer.st_size >= (off_t)(TFTP_MAX_BLK_NUM * TFTP_BLKSIZE)) {
+ return TFTPC_FILE_TOO_BIG;
+ }
+
+ /* Check validity of destination path */
+ ulDestStrLen = strlen((char *)szDestDirPath);
+ /* If dest path length exceeded max value */
+ if (ulDestStrLen >= TFTP_MAX_PATH_LENGTH) {
+ return TFTPC_DEST_PATH_LENGTH_ERROR;
+ }
+
+ pstSendBuf = (TFTPC_PACKET_S *)mem_malloc(sizeof(TFTPC_PACKET_S));
+ if (pstSendBuf == NULL) {
+ return TFTPC_MEMALLOC_ERROR;
+ }
+
+ /* First time initialize the buffer */
+ (void)memset_s((void *)pstSendBuf, sizeof(TFTPC_PACKET_S), 0, sizeof(TFTPC_PACKET_S));
+
+ /* The destination path can only be one of the following:
+ 1. Only filename
+ 2. Relative path WITH filename
+ 3. Empty string
+ */
+ if (ulDestStrLen != 0) {
+ /* If not empty string use the Destination path name */
+ szTempDestName = szDestDirPath;
+ } else {
+ /* If destination directory is empty string use source filename
+ If given src filename is a relative path extract the file name
+ from the path */
+ if ((strchr((char *)szSrcFileName, '/') != 0) ||
+ (strchr((char *)szSrcFileName, '\\') != 0)) {
+ /* Move to the end of the src file path */
+ szTempDestName = szSrcFileName + (ulSrcStrLen - 1);
+
+ while (((*(szTempDestName - 1) != '/') && (*(szTempDestName - 1) != '\\')) &&
+ (szTempDestName != szSrcFileName)) {
+ szTempDestName--;
+ }
+ } else {
+ /* If not a relative src path use the given src filename */
+ szTempDestName = szSrcFileName;
+ }
+ }
+
+ /* Create a socket and bind it to an available port number */
+ ulErrCode = lwip_tftp_create_bind_socket(&iSockNum);
+ if (ulErrCode != EOK) {
+ /* Create and Bind socket failed */
+ goto err_handler;
+ }
+
+ if (usTftpServPort == 0) {
+ usTftpServPort = TFTPC_SERVER_PORT;
+ }
+
+ usTempServPort = usTftpServPort;
+
+ /* set server internet address */
+ (void)memset_s(&stServerAddr, sizeof(stServerAddr), 0, sizeof(stServerAddr));
+ stServerAddr.sin_family = AF_INET;
+ stServerAddr.sin_port = htons(usTempServPort);
+ stServerAddr.sin_addr.s_addr = htonl(ulHostAddr);
+
+ /* Make request packet - TFTPC_OP_WRQ */
+ ulSize = (u32_t)lwip_tftp_make_tftp_packet(TFTPC_OP_WRQ,
+ szTempDestName,
+ ucTftpTransMode,
+ pstSendBuf);
+
+ ulErrCode = lwip_tftp_send_to_server(iSockNum, ulSize,
+ pstSendBuf, &stServerAddr);
+ if (ulErrCode != ERR_OK) {
+ /* Send to server error */
+ (void)lwip_close(iSockNum);
+
+ goto err_handler;
+ }
+
+ /* Send the request packet */
+ ulErrCode = lwip_tftp_inner_put_file(iSockNum, pstSendBuf, ulSize,
+ usCurrBlk, &stServerAddr);
+ if (ulErrCode != ERR_OK) {
+ /* Send request packet failed */
+ (void)lwip_close(iSockNum);
+
+ LWIP_DEBUGF(TFTP_DEBUG, ("lwip_tftp_put_file_by_filename : Failed to send request packet\n"));
+
+ goto err_handler;
+ }
+
+ /* Create buffer block size */
+ pucBuffer = mem_malloc(TFTP_BLKSIZE);
+ if (pucBuffer == NULL) {
+ /* Memory allocation failed */
+ lwip_tftp_send_error(iSockNum,
+ TFTPC_PROTOCOL_USER_DEFINED,
+ "Memory allocation failed.",
+ &stServerAddr, pstSendBuf);
+
+ (void)lwip_close(iSockNum);
+ ulErrCode = TFTPC_MEMALLOC_ERROR;
+ goto err_handler;
+ }
+
+ (void)memset_s((void *)pucBuffer, TFTP_BLKSIZE, 0, TFTP_BLKSIZE);
+
+ fp = open((char *)szSrcFileName, O_RDONLY);
+ if (TFTP_NULL_INT32 == fp) {
+ /* If file could not be opened send error to server */
+ lwip_tftp_send_error(iSockNum,
+ TFTPC_PROTOCOL_USER_DEFINED,
+ "File open error.",
+ &stServerAddr, pstSendBuf);
+
+ (void)lwip_close(iSockNum);
+ mem_free(pucBuffer);
+
+ ulErrCode = TFTPC_FILEOPEN_ERROR;
+ goto err_handler;
+ }
+
+ iErrCode = read(fp, pucBuffer, TFTP_BLKSIZE);
+ if (iErrCode < 0) {
+ /* If failed to read from file */
+ lwip_tftp_send_error(iSockNum,
+ TFTPC_PROTOCOL_USER_DEFINED,
+ "File read error.",
+ &stServerAddr, pstSendBuf);
+
+ (void)lwip_close(iSockNum);
+ close(fp);
+ mem_free(pucBuffer);
+
+ ulErrCode = TFTPC_FILEREAD_ERROR;
+ goto err_handler;
+ }
+
+ /* Read from source file and send to server */
+ /* To send empty packet to server when file is a 0 byte file */
+ do {
+ if (((u32_t)usCurrBlk + 1) > TFTP_MAX_BLK_NUM) {
+ lwip_tftp_send_error(iSockNum,
+ TFTPC_PROTOCOL_USER_DEFINED,
+ "File is too big.",
+ &stServerAddr, pstSendBuf);
+
+ (void)lwip_close(iSockNum);
+ close(fp);
+ mem_free(pucBuffer);
+ LWIP_DEBUGF(TFTP_DEBUG, ("lwip_tftp_put_file_by_filename : Data block number exceeded max value\n"));
+
+ ulErrCode = TFTPC_FILE_TOO_BIG;
+ goto err_handler;
+ }
+
+ /* Increment block number */
+ usCurrBlk++;
+
+ ulSize = (u32_t)iErrCode + TFTP_HDRSIZE;
+
+ /* Form the DATA packet */
+ usReadReq = (u16_t)TFTPC_OP_DATA;
+ pstSendBuf->usOpcode = htons(usReadReq);
+ pstSendBuf->u.stTFTP_Data.usBlknum = htons(usCurrBlk);
+ if (memcpy_s((void *)pstSendBuf->u.stTFTP_Data.ucDataBuf, TFTP_BLKSIZE,
+ (void *)pucBuffer, (u32_t)iErrCode) != EOK) {
+ (void)lwip_close(iSockNum);
+ close(fp);
+ mem_free(pucBuffer);
+ goto err_handler;
+ }
+
+ ulErrCode = lwip_tftp_send_to_server(iSockNum, ulSize,
+ pstSendBuf, &stServerAddr);
+ if ((ulErrCode != ERR_OK) || (memset_s((void *)pucBuffer, TFTP_BLKSIZE, 0, TFTP_BLKSIZE) != 0)) {
+ (void)lwip_close(iSockNum);
+ close(fp);
+ mem_free(pucBuffer);
+ goto err_handler;
+ }
+
+ /* Read a block from the file to buffer */
+ iErrCode = read(fp, pucBuffer, TFTP_BLKSIZE);
+ if (iErrCode < 0) {
+ /*If failed to read from file*/
+ lwip_tftp_send_error(iSockNum, TFTPC_PROTOCOL_USER_DEFINED, "File read error.",
+ &stServerAddr, pstSendBuf);
+
+ (void)lwip_close(iSockNum);
+ close(fp);
+ mem_free(pucBuffer);
+ ulErrCode = TFTPC_FILEREAD_ERROR;
+ goto err_handler;
+ }
+
+ /* Send the request packet */
+ ulErrCode = lwip_tftp_inner_put_file(iSockNum, pstSendBuf, ulSize,
+ usCurrBlk, &stServerAddr);
+ if (ulErrCode != ERR_OK) {
+ /* Sending buffer contents failed */
+ (void)lwip_close(iSockNum);
+ close(fp);
+ mem_free(pucBuffer);
+ LWIP_DEBUGF(TFTP_DEBUG, ("lwip_tftp_put_file_by_filename : Sending file to server failed\n"));
+ goto err_handler;
+ }
+ } while (ulSize == (TFTP_BLKSIZE + TFTP_HDRSIZE));
+
+ /* Transfer of data is finished */
+ (void)lwip_close(iSockNum);
+ close(fp);
+ mem_free(pucBuffer);
+
+ ulErrCode = ERR_OK;
+err_handler:
+ mem_free(pstSendBuf);
+ return ulErrCode;
+}
+
+/* Put file function
+ iSockNum: Socket ID
+ pstSendBuf: Packet to send to server
+ ulSendSize: Packet length
+ usCurrBlk: Current block number
+ pstServerAddr: Server address
+*/
+u32_t lwip_tftp_inner_put_file(s32_t iSockNum,
+ TFTPC_PACKET_S *pstSendBuf,
+ u32_t ulSendSize,
+ u16_t usCurrBlk,
+ struct sockaddr_in *pstServerAddr)
+{
+ u32_t ulPktSize;
+ u32_t ulError;
+ s32_t iError;
+ int iRecvLen = 0;
+ socklen_t iFromAddrLen;
+ u32_t ulTotalTime = 0;
+ fd_set stReadfds;
+ struct sockaddr_in stFromAddr;
+ struct timeval stTimeout;
+ TFTPC_PACKET_S *pstRecvBuf = NULL;
+ u32_t ulIgnorePkt = 0;
+ u16_t usBlknum;
+ u32_t ulLoopCnt = 0;
+
+ iFromAddrLen = sizeof(stFromAddr);
+
+ pstRecvBuf = (TFTPC_PACKET_S *)mem_malloc(sizeof(TFTPC_PACKET_S));
+ if (pstRecvBuf == NULL) {
+ return TFTPC_MEMALLOC_ERROR;
+ }
+
+ /* First time initialize the buffer */
+ (void)memset_s((void *)pstRecvBuf, sizeof(TFTPC_PACKET_S), 0, sizeof(TFTPC_PACKET_S));
+
+ /* Initialize from address to the server address at first */
+ if (memcpy_s((void *)&stFromAddr, sizeof(struct sockaddr_in),
+ (void *)pstServerAddr, sizeof(stFromAddr)) != EOK) {
+ ulError = TFTPC_MEMCPY_FAILURE;
+ goto err_handler;
+ }
+
+ for (;;) {
+ ulError = lwip_tftp_recv_from_server(iSockNum, &ulPktSize,
+ pstRecvBuf, &ulIgnorePkt,
+ pstServerAddr, pstSendBuf);
+ /* If select timeout occurred */
+ if (ulError == TFTPC_TIMEOUT_ERROR) {
+ ulTotalTime++;
+ if (ulTotalTime < TFTPC_MAX_SEND_REQ_ATTEMPTS) {
+ /*Max attempts not reached. Resend packet*/
+ ulError = lwip_tftp_send_to_server(iSockNum, ulSendSize,
+ pstSendBuf, pstServerAddr);
+ if (ulError != ERR_OK) {
+ goto err_handler;
+ }
+
+ continue;
+ } else {
+ /* return from the function, max attempts limit reached */
+ ulError = TFTPC_TIMEOUT_ERROR;
+ goto err_handler;
+ }
+ } else if (ulError != ERR_OK) {
+ /* return from the function, RecvFromServer failed */
+ goto err_handler;
+ }
+
+ /* If Received packet from another server */
+ if (ulIgnorePkt > 0) {
+ /* The packet that is received is to be ignored.
+ So continue without processing it. */
+ ulIgnorePkt = 0;
+ continue;
+ }
+
+ /* if this packet is unknown or incorrect packet */
+ if (TFTPC_OP_ACK != ntohs(pstRecvBuf->usOpcode)) {
+ lwip_tftp_send_error(iSockNum,
+ TFTPC_PROTOCOL_PROTO_ERROR,
+ "Protocol error.",
+ pstServerAddr, pstSendBuf);
+
+ LWIP_DEBUGF(TFTP_DEBUG, ("lwip_tftp_inner_put_file : Received pkt not Ack pkt\n"));
+
+ ulError = TFTPC_PROTO_ERROR;
+ goto err_handler;
+ }
+
+ ulTotalTime = 0;
+
+ /* if the packet is acknowledge packet */
+ usBlknum = ntohs(pstRecvBuf->u.usBlknum);
+ iRecvLen = (int)ulPktSize;
+
+ /* If not correct block no. */
+ if (usBlknum != usCurrBlk) {
+ /* we are not in sync now */
+ /* reset any collected packets. */
+ stTimeout.tv_sec = 1;
+ stTimeout.tv_usec = 0;
+
+ FD_ZERO(&stReadfds);
+ FD_SET(iSockNum, &stReadfds);
+
+ /*
+ Need to take care of timeout scenario in Select call.
+ Since the socket used is blocking, if select timeout occurs,
+ the following recvfrom will block indefinitely.
+ */
+ iError = select((s32_t)(iSockNum + 1), &stReadfds, 0, 0, &stTimeout);
+
+ /* Loop to get the last data packet from the receive buffer */
+ while ((iError != -1) && (iError != 0)) {
+ ulLoopCnt++;
+
+ /* MAX file size in TFTP is 32 MB.
+ Reason for keeping 75 here , is ((75*512=38400bytes)/1024) = 37MB. So the recv/Snd
+ Loop can receive the complete MAX message from the network.
+ */
+ if (ulLoopCnt > TFTPC_MAX_WAIT_IN_LOOP) {
+ LWIP_DEBUGF(TFTP_DEBUG,
+ ("lwip_tftp_inner_put_file : unexpected packets are received repeatedly\n"));
+ ulError = TFTPC_PKT_SIZE_ERROR;
+ goto err_handler;
+ }
+
+ FD_ZERO(&stReadfds);
+ FD_SET(iSockNum, &stReadfds);
+ iRecvLen = lwip_recvfrom(iSockNum,
+ (s8_t *)pstRecvBuf,
+ TFTP_PKTSIZE, 0,
+ (struct sockaddr *)&stFromAddr,
+ &iFromAddrLen);
+ if (TFTP_NULL_INT32 == iRecvLen) {
+ ulError = TFTPC_RECVFROM_ERROR;
+ goto err_handler;
+ }
+
+ stTimeout.tv_sec = 1;
+ stTimeout.tv_usec = 0;
+ iError = select((s32_t)(iSockNum + 1),
+ &stReadfds, 0, 0, &stTimeout);
+ }
+
+ /* If a new packet is not received then donot change the byte order
+ * as it has already been done
+ */
+ /* If received packet size < minimum packet size */
+ if (iRecvLen < TFTPC_FOUR) {
+ lwip_tftp_send_error(iSockNum,
+ TFTPC_PROTOCOL_PROTO_ERROR,
+ "Packet size < min packet size",
+ pstServerAddr, pstSendBuf);
+
+ LWIP_DEBUGF(TFTP_DEBUG, ("lwip_tftp_inner_put_file : Received pkt not Ack pkt\n"));
+
+ ulError = TFTPC_PKT_SIZE_ERROR;
+ goto err_handler;
+ }
+
+ /* Check if the received packet is from correct server and from
+ correct port
+ */
+ if ((stFromAddr.sin_addr.s_addr != pstServerAddr->sin_addr.s_addr) ||
+ (pstServerAddr->sin_port != stFromAddr.sin_port)) {
+ /* This ACK packet is invalid. Just ignore it. */
+ LWIP_DEBUGF(TFTP_DEBUG, ("lwip_tftp_inner_put_file : Received pkt from unknown server\n"));
+ continue;
+ }
+
+ /* if this packet is not ACK packet */
+ if (TFTPC_OP_ACK != ntohs(pstRecvBuf->usOpcode)) {
+ lwip_tftp_send_error(iSockNum,
+ TFTPC_PROTOCOL_PROTO_ERROR,
+ "Protocol error.",
+ pstServerAddr, pstSendBuf);
+
+ LWIP_DEBUGF(TFTP_DEBUG, ("lwip_tftp_inner_put_file : Received pkt not Ack pkt\n"));
+
+ ulError = TFTPC_PROTO_ERROR;
+ goto err_handler;
+ }
+
+ usBlknum = ntohs(pstRecvBuf->u.usBlknum);
+ /*
+ * In this case we have received a duplicate ACK for data block.
+ * (ACK for this data block was aready received earlier)
+ * In this case we have usRecvBlkNum == (usNextBlkNum - 1).
+ * This could mean that:
+ * (i) last data packet that was sent was not received at server side
+ * (ii) Acknowledgement of peer side is delayed.
+ *
+ * In this case, this duplicate ACK will be ignored and return to the
+ * state machine to initiate a receive of this data packet.
+ */
+ if ((usCurrBlk - 1) == usBlknum) {
+ /* This ACK packet is invalid. Just ignore it. */
+ continue;
+ }
+
+ /* Now check the block number with current block.
+ * If it is not the previous block and the current block,
+ * then it is an unexpected packet.
+ */
+ if (usBlknum != usCurrBlk) {
+ lwip_tftp_send_error(iSockNum,
+ TFTPC_PROTOCOL_PROTO_ERROR,
+ "Received unexpected packet",
+ pstServerAddr, pstSendBuf);
+
+ LWIP_DEBUGF(TFTP_DEBUG,
+ ("lwip_tftp_inner_put_file : Received DATA pkt no. %"S32_F"instead of pkt no. %"S32_F"\n",
+ usBlknum, usCurrBlk));
+
+ ulError = TFTPC_SYNC_FAILURE;
+ goto err_handler;
+ }
+ }
+
+ ulError = ERR_OK;
+ goto err_handler;
+ }
+
+err_handler:
+ mem_free(pstRecvBuf);
+ return ulError;
+}
+
+#ifdef TFTP_TO_RAWMEM
+/* INTEFACE to get a file using filename
+ ulHostAddr - IP address of Host
+ szSrcFileName - Source file
+ szDestMemAddr - The target memory address in the client
+
+ Example :
+ ulHostAddr = ntohl(inet_addr ("192.168.1.3"));
+ lwip_tftp_get_file_by_filename_to_rawmem(ulHostAddr, "/ramfs/vs_server.bin", memaddr, &filelen);
+*/
+u32_t lwip_tftp_get_file_by_filename_to_rawmem(u32_t ulHostAddr,
+ u16_t usTftpServPort,
+ u8_t ucTftpTransMode,
+ s8_t *szSrcFileName,
+ s8_t *szDestMemAddr,
+ u32_t *ulFileLength)
+{
+ s32_t iSockNum = TFTP_NULL_INT32;
+ u32_t ulSrcStrLen;
+ u32_t lDestStrLen;
+ u32_t ulSize;
+ u32_t ulRecvSize = TFTP_NULL_UINT32;
+ s32_t iErrCode;
+ u32_t ulErrCode;
+ u16_t usReadReq;
+ u16_t usTempServPort;
+ u32_t ulCurrBlk = 1;
+ u32_t ulResendPkt = 0; /* Resend the previous packet */
+ u32_t ulIgnorePkt = 0; /* Ignore received packet */
+ u32_t ulTotalTime = 0;
+
+ TFTPC_PACKET_S *pstSendBuf = NULL;
+ TFTPC_PACKET_S *pstRecvBuf = NULL;
+ struct sockaddr_in stServerAddr;
+ u32_t ulMemOffset = 0;
+
+ /* Validate the parameters */
+ if ((szSrcFileName == NULL) || (szDestMemAddr == NULL) || (*ulFileLength == 0)) {
+ return TFTPC_INVALID_PARAVALUE;
+ }
+
+ if ((ucTftpTransMode != TRANSFER_MODE_BINARY) && (ucTftpTransMode != TRANSFER_MODE_ASCII)) {
+ return TFTPC_INVALID_PARAVALUE;
+ }
+
+ /* check IP address not within ( 1.0.0.0 - 126.255.255.255 )
+ and ( 128.0.0.0 - 223.255.255.255 ) range. */
+ if (!(((ulHostAddr >= TFTPC_IP_ADDR_MIN) &&
+ (ulHostAddr <= TFTPC_IP_ADDR_EX_RESV)) ||
+ ((ulHostAddr >= TFTPC_IP_ADDR_CLASS_B) &&
+ (ulHostAddr <= TFTPC_IP_ADDR_EX_CLASS_DE)))) {
+ return TFTPC_IP_NOT_WITHIN_RANGE;
+ }
+
+ /*Check validity of source filename*/
+ ulSrcStrLen = strlen(szSrcFileName);
+ if ((ulSrcStrLen == 0) || (ulSrcStrLen >= TFTP_MAX_PATH_LENGTH)) {
+ return TFTPC_SRC_FILENAME_LENGTH_ERROR;
+ }
+
+ pstSendBuf = (TFTPC_PACKET_S *)mem_malloc(sizeof(TFTPC_PACKET_S));
+ if (pstSendBuf == NULL) {
+ return TFTPC_MEMALLOC_ERROR;
+ }
+
+ pstRecvBuf = (TFTPC_PACKET_S *)mem_malloc(sizeof(TFTPC_PACKET_S));
+ if (pstRecvBuf == NULL) {
+ mem_free(pstSendBuf);
+ return TFTPC_MEMALLOC_ERROR;
+ }
+
+ /* First time initialize the buffers */
+ (void)memset_s((void *)pstSendBuf, sizeof(TFTPC_PACKET_S), 0, sizeof(TFTPC_PACKET_S));
+ (void)memset_s((void *)pstRecvBuf, sizeof(TFTPC_PACKET_S), 0, sizeof(TFTPC_PACKET_S));
+
+ ulErrCode = lwip_tftp_create_bind_socket(&iSockNum);
+ if (ulErrCode != EOK) {
+ goto err_handler;
+ }
+
+ if (usTftpServPort == 0) {
+ usTftpServPort = TFTPC_SERVER_PORT;
+ }
+
+ usTempServPort = usTftpServPort;
+
+ /* set server IP address */
+ (void)memset_s(&stServerAddr, sizeof(stServerAddr), 0, sizeof(stServerAddr));
+ stServerAddr.sin_family = AF_INET;
+ stServerAddr.sin_port = htons(usTempServPort);
+ stServerAddr.sin_addr.s_addr = htonl(ulHostAddr);
+
+ /* Make a request packet - TFTPC_OP_RRQ */
+ ulSize = (u32_t)lwip_tftp_make_tftp_packet(TFTPC_OP_RRQ, szSrcFileName, (u32_t)ucTftpTransMode, pstSendBuf);
+ ulErrCode = lwip_tftp_send_to_server(iSockNum, ulSize, pstSendBuf, &stServerAddr);
+ if (ulErrCode != ERR_OK) {
+ /* send to server failed */
+ (void)lwip_close(iSockNum);
+ goto err_handler;
+ }
+
+ for (;;) {
+ if (ulIgnorePkt > 0) {
+ ulIgnorePkt = 0;
+ }
+
+ ulErrCode = lwip_tftp_recv_from_server(iSockNum, &ulRecvSize, pstRecvBuf, &ulIgnorePkt,
+ &stServerAddr, pstSendBuf);
+ /* If select timeout occurred */
+ if (ulErrCode == TFTPC_TIMEOUT_ERROR) {
+ ulTotalTime++;
+ if (ulTotalTime < TFTPC_MAX_SEND_REQ_ATTEMPTS) {
+ /* Max attempts not reached. Resend packet */
+ ulErrCode = lwip_tftp_send_to_server(iSockNum, ulSize,
+ pstSendBuf, &stServerAddr);
+ if (ulErrCode != ERR_OK) {
+ (void)lwip_close(iSockNum);
+ goto err_handler;
+ }
+
+ continue;
+ } else {
+ /* return from the function, max attempts limit reached */
+ (void)lwip_close(iSockNum);
+ ulErrCode = TFTPC_TIMEOUT_ERROR;
+ goto err_handler;
+ }
+ } else if (ulErrCode != ERR_OK) {
+ (void)lwip_close(iSockNum);
+ goto err_handler;
+ }
+
+ /* Now we have receive block from different server. */
+ if (ulIgnorePkt > 0) {
+ /*Continue without processing this block. */
+ continue;
+ }
+
+ /* if this packet is unkonwn or incorrect packet */
+ if (ntohs(pstRecvBuf->usOpcode) != TFTPC_OP_DATA) {
+ /* Send error packet to server */
+ lwip_tftp_send_error(iSockNum,
+ TFTPC_PROTOCOL_PROTO_ERROR,
+ "Protocol error.",
+ &stServerAddr, pstSendBuf);
+
+ (void)lwip_close(iSockNum);
+
+ LWIP_DEBUGF(TFTP_DEBUG, ("lwip_tftp_get_file_by_filename : Received pkt not DATA pkt\n"));
+
+ ulErrCode = TFTPC_PROTO_ERROR;
+ goto err_handler;
+ }
+
+ /* Now the number of tries will be reset. */
+ ulTotalTime = 0;
+
+ /* Validate received DATA packet. */
+ ulErrCode = lwip_tftp_validate_data_pkt(iSockNum, &ulRecvSize,
+ pstRecvBuf, (u16_t)ulCurrBlk,
+ &ulResendPkt,
+ &stServerAddr);
+ if (ulErrCode != ERR_OK) {
+ /* Send Error packet to server */
+ if (ulErrCode != TFTPC_RECVFROM_ERROR) {
+ lwip_tftp_send_error(iSockNum,
+ TFTPC_PROTOCOL_PROTO_ERROR,
+ "Received unexpected packet",
+ &stServerAddr, pstSendBuf);
+ }
+
+ (void)lwip_close(iSockNum);
+
+ goto err_handler;
+ }
+
+ /* Received previous data block again. Resend last packet */
+ if (ulResendPkt > 0) {
+ /* Now set ulResendPkt to 0 to send the last packet. */
+ ulResendPkt = 0;
+ ulErrCode = lwip_tftp_send_to_server(iSockNum, ulSize,
+ pstSendBuf, &stServerAddr);
+ if (ulErrCode != ERR_OK) {
+ (void)lwip_close(iSockNum);
+
+ goto err_handler;
+ }
+
+ /* Continue in loop to send last packet again. */
+ continue;
+ }
+
+ /* Get the size of the data block received */
+ ulRecvSize -= TFTP_HDRSIZE;
+
+ /* Check if the size of the received data block > max size */
+ if (ulRecvSize > TFTP_BLKSIZE) {
+ /* Send Error packet to server */
+ lwip_tftp_send_error(iSockNum,
+ TFTPC_PROTOCOL_PROTO_ERROR,
+ "Packet size > max size",
+ &stServerAddr, pstSendBuf);
+
+ (void)lwip_close(iSockNum);
+
+ LWIP_DEBUGF(TFTP_DEBUG, ("lwip_tftp_get_file_by_filename : Packet size > max size\n"));
+
+ ulErrCode = TFTPC_PKT_SIZE_ERROR;
+ goto err_handler;
+ }
+
+ usReadReq = (u16_t)TFTPC_OP_ACK;
+ pstSendBuf->usOpcode = htons(usReadReq);
+ pstSendBuf->u.usBlknum = htons((u16_t)ulCurrBlk);
+ ulSize = TFTP_HDRSIZE;
+
+ if (ulRecvSize != TFTP_BLKSIZE) {
+ (void)lwip_tftp_send_to_server(iSockNum, ulSize,
+ pstSendBuf, &stServerAddr);
+
+ /* If the received packet has only header and do not have payload, the return failure */
+ if (ulRecvSize != 0) {
+ /* memcopy filed */
+ if (*ulFileLength < (ulMemOffset + ulRecvSize)) {
+ ulErrCode = TFTPC_MEMCPY_FAILURE;
+ (void)lwip_close(iSockNum);
+ *ulFileLength = ulMemOffset;
+ goto err_handler;
+ }
+ /* copy the last packet to the memory */
+ if (memcpy_s(szDestMemAddr + ulMemOffset, TFTP_MAX_BLK_NUM * TFTP_BLKSIZE,
+ (void *)pstRecvBuf->u.stTFTP_Data.ucDataBuf, (size_t)ulRecvSize) != EOK) {
+ ulErrCode = TFTPC_MEMCPY_FAILURE;
+ (void)lwip_close(iSockNum);
+ *ulFileLength = ulMemOffset;
+ goto err_handler;
+ }
+ ulMemOffset += ulRecvSize;
+ }
+
+ /* Now free allocated resourdes and return,
+ data block receiving is already completed */
+ (void)lwip_close(iSockNum);
+ ulErrCode = ERR_OK;
+ *ulFileLength = ulMemOffset;
+ goto err_handler;
+ }
+
+ ulErrCode = lwip_tftp_send_to_server(iSockNum, ulSize,
+ pstSendBuf, &stServerAddr);
+ if (ulErrCode != ERR_OK) {
+ (void)lwip_close(iSockNum);
+ goto err_handler;
+ }
+
+ /* memcopy filed */
+ if (*ulFileLength < ulRecvSize * ulCurrBlk) {
+ ulErrCode = TFTPC_MEMCPY_FAILURE;
+ (void)lwip_close(iSockNum);
+ *ulFileLength = ulMemOffset;
+ goto err_handler;
+ }
+ if (memcpy_s(szDestMemAddr + ulMemOffset, TFTP_MAX_BLK_NUM * TFTP_BLKSIZE,
+ (void *)pstRecvBuf->u.stTFTP_Data.ucDataBuf, (size_t)ulRecvSize) != EOK) {
+ ulErrCode = TFTPC_MEMCPY_FAILURE;
+ (void)lwip_close(iSockNum);
+ *ulFileLength = ulMemOffset;
+ goto err_handler;
+ }
+
+ ulMemOffset += ulRecvSize;
+ /* form the ACK packet for the DATA packet received */
+ /* Go to the next packet no. */
+ ulCurrBlk++;
+ /* if the file is too big, exit */
+ if (ulCurrBlk > TFTP_MAX_BLK_NUM) {
+ /* Send error packet to server */
+ lwip_tftp_send_error(iSockNum,
+ TFTPC_PROTOCOL_USER_DEFINED,
+ "File is too big.",
+ &stServerAddr, pstSendBuf);
+
+ (void)lwip_close(iSockNum);
+
+ LWIP_DEBUGF(TFTP_DEBUG, ("lwip_tftp_get_file_by_filename : Data block number exceeded max value\n"));
+
+ ulErrCode = TFTPC_FILE_TOO_BIG;
+ goto err_handler;
+ }
+ }
+
+err_handler:
+ mem_free(pstSendBuf);
+ mem_free(pstRecvBuf);
+ return ulErrCode;
+}
+#endif
+
+#endif /* LOSCFG_NET_LWIP_SACK_TFTP */
+#endif /* LWIP_TFTP */
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/toybox/BUILD.gn b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/toybox/BUILD.gn
new file mode 100644
index 00000000..a6d74a10
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/toybox/BUILD.gn
@@ -0,0 +1,84 @@
+# 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")
+import("//kernel/liteos_a/liteos.gni")
+import("//third_party/toybox/toybox.gni")
+
+group("toybox") {
+ deps = [ ":build_toybox" ]
+}
+
+copy("copy_toybox_src") {
+ sources = TOYBOX_SRC_DIR
+ outputs = [ "$target_out_dir/toybox_build" ]
+}
+
+copy("copy_toybox_config") {
+ deps = [ ":copy_toybox_src" ]
+ sources = [ "liteos_a_custom.config" ]
+ outputs = [ "$target_out_dir/{{source_file_part}}" ]
+}
+
+build_ext_component("build_toybox") {
+ deps = [
+ ":copy_toybox_config",
+ ":copy_toybox_src",
+ ]
+ deps += [ "//prebuilts/lite/sysroot" ]
+ exec_path = rebase_path("$target_out_dir/toybox_build")
+
+ cflags = [
+ "-fstack-protector-strong",
+ "-D_FORTIFY_SOURCE=2",
+ ]
+ cflags = string_join(" ", cflags)
+
+ extra_flags = string_join(" ", target_arch_cflags)
+ if (ohos_build_compiler == "clang") {
+ extra_flags += " --target=$target_triple"
+ extra_flags += " --sysroot=" + rebase_path(ohos_current_sysroot)
+ }
+
+ command = "rm -rf .git && cp -rfp porting/liteos_a/. . && env"
+ command += " CC=\"$ohos_current_cc_command\""
+ command += " STRIP=\"$ohos_current_strip_command\""
+ command += " OUTNAME=toybox"
+ command += " CFLAGS=\"$cflags $extra_flags\""
+ command += " make toybox"
+ command += " && install -D toybox "
+ command += rebase_path("$root_out_dir/bin/toybox", exec_path)
+ command += " && install -D generated/unstripped/toybox "
+ command += rebase_path("$root_out_dir/unstripped/bin/toybox", exec_path)
+
+ outputs = [
+ "$root_out_dir/unstripped/bin/toybox",
+ "$root_out_dir/bin/toybox",
+ ]
+}
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/toybox/Makefile b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/toybox/Makefile
new file mode 100644
index 00000000..6fd3d005
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/toybox/Makefile
@@ -0,0 +1,53 @@
+# 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 $(APPSTOPDIR)/config.mk
+
+BUILD_DIR := $(OUT)/toybox_build
+BUILD_LOG := $(BUILD_DIR)/build.log
+
+CFLAGS += -Wno-error
+
+all:
+ifneq ($(wildcard $(BUILD_DIR)),)
+ $(HIDE)echo "not clean, rebuilding now"
+else
+ $(HIDE)mkdir -p $(BUILD_DIR)
+ $(HIDE)$(CP) $(LITEOSTHIRDPARTY)/toybox/. $(BUILD_DIR)
+ $(HIDE)$(CP) $(LITEOSTHIRDPARTY)/toybox/porting/liteos_a/. $(BUILD_DIR)
+ $(HIDE)$(CP) liteos_a_custom.config $(BUILD_DIR)/../
+endif
+ $(HIDE)unset KCONFIG_CONFIG CROSS_COMPILE && \
+ env CC="$(CC)" OUTNAME="$(OUT)/bin/toybox" CFLAGS="$(CFLAGS)" LDFLAGS="$(LDFLAGS)" STRIP="$(STRIP)" \
+ make -C $(BUILD_DIR) toybox -j> $(BUILD_LOG) 2>&1
+
+clean:
+ $(HIDE)$(RM) $(BUILD_DIR)
+
+.PHONY: all clean
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/toybox/liteos_a_custom.config b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/toybox/liteos_a_custom.config
new file mode 100644
index 00000000..7628c2fa
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/toybox/liteos_a_custom.config
@@ -0,0 +1,186 @@
+# CONFIG_BASENAME is not set
+# CONFIG_CAL is not set
+# CONFIG_CAT is not set
+# CONFIG_CATV is not set
+# CONFIG_CKSUM is not set
+# CONFIG_CRC32 is not set
+# CONFIG_CMP is not set
+# CONFIG_COMM is not set
+# CONFIG_CP_PRESERVE is not set
+# CONFIG_INSTALL is not set
+# CONFIG_CPIO is not set
+# CONFIG_CUT is not set
+# CONFIG_DF is not set
+# CONFIG_DIRNAME is not set
+# CONFIG_ECHO is not set
+# CONFIG_ENV is not set
+# CONFIG_EXPAND is not set
+# CONFIG_FALSE is not set
+# CONFIG_FILE is not set
+# CONFIG_FIND is not set
+# CONFIG_GETCONF is not set
+# CONFIG_GREP is not set
+# CONFIG_EGREP is not set
+# CONFIG_FGREP is not set
+# CONFIG_HEAD is not set
+# CONFIG_ICONV is not set
+# CONFIG_ID is not set
+# CONFIG_GROUPS is not set
+# CONFIG_LOGNAME is not set
+# CONFIG_WHOAMI is not set
+# CONFIG_LINK is not set
+# CONFIG_LN is not set
+# CONFIG_LOGGER is not set
+# CONFIG_MKFIFO is not set
+# CONFIG_NICE is not set
+# CONFIG_NL is not set
+# CONFIG_NOHUP is not set
+# CONFIG_OD is not set
+# CONFIG_PASTE is not set
+# CONFIG_PATCH is not set
+# CONFIG_PRINTF is not set
+# CONFIG_IOTOP is not set
+# CONFIG_PGREP is not set
+# CONFIG_PKILL is not set
+# CONFIG_PWD is not set
+# CONFIG_RENICE is not set
+# CONFIG_SED is not set
+# CONFIG_SLEEP is not set
+# CONFIG_SORT is not set
+# CONFIG_SORT_FLOAT is not set
+# CONFIG_SPLIT is not set
+# CONFIG_STRINGS is not set
+# CONFIG_TAIL is not set
+# CONFIG_TAR is not set
+# CONFIG_TEE is not set
+# CONFIG_TEST is not set
+# CONFIG_TIME is not set
+# CONFIG_TRUE is not set
+# CONFIG_TTY is not set
+# CONFIG_ULIMIT is not set
+# CONFIG_ARCH is not set
+# CONFIG_UNIQ is not set
+# CONFIG_UNLINK is not set
+# CONFIG_UUDECODE is not set
+# CONFIG_UUENCODE is not set
+# CONFIG_WC is not set
+# CONFIG_WHO is not set
+# CONFIG_XARGS is not set
+# CONFIG_ACPI is not set
+# CONFIG_ASCII is not set
+# CONFIG_BASE64 is not set
+# CONFIG_BLKID is not set
+# CONFIG_FSTYPE is not set
+# CONFIG_BLOCKDEV is not set
+# CONFIG_BUNZIP2 is not set
+# CONFIG_BZCAT is not set
+# CONFIG_CHROOT is not set
+# CONFIG_CHRT is not set
+# CONFIG_CHVT is not set
+# CONFIG_CLEAR is not set
+# CONFIG_COUNT is not set
+# CONFIG_DEVMEM is not set
+# CONFIG_DOS2UNIX is not set
+# CONFIG_UNIX2DOS is not set
+# CONFIG_EJECT is not set
+# CONFIG_FACTOR is not set
+# CONFIG_FALLOCATE is not set
+# CONFIG_FLOCK is not set
+# CONFIG_FMT is not set
+# CONFIG_FREERAMDISK is not set
+# CONFIG_FSFREEZE is not set
+# CONFIG_FSYNC is not set
+# CONFIG_HELP_EXTRAS is not set
+# CONFIG_HEXEDIT is not set
+# CONFIG_HWCLOCK is not set
+# CONFIG_I2CDETECT is not set
+# CONFIG_I2CDUMP is not set
+# CONFIG_I2CGET is not set
+# CONFIG_I2CSET is not set
+# CONFIG_INOTIFYD is not set
+# CONFIG_INSMOD is not set
+# CONFIG_IONICE is not set
+# CONFIG_IORENICE is not set
+# CONFIG_LOGIN is not set
+# CONFIG_LOSETUP is not set
+# CONFIG_LSATTR is not set
+# CONFIG_CHATTR is not set
+# CONFIG_LSMOD is not set
+# CONFIG_LSPCI is not set
+# CONFIG_LSPCI_TEXT is not set
+# CONFIG_LSUSB is not set
+# CONFIG_MAKEDEVS is not set
+# CONFIG_MCOOKIE is not set
+# CONFIG_MIX is not set
+# CONFIG_MKPASSWD is not set
+# CONFIG_MKSWAP is not set
+# CONFIG_MODINFO is not set
+# CONFIG_MOUNTPOINT is not set
+# CONFIG_NBD_CLIENT is not set
+# CONFIG_UNSHARE is not set
+# CONFIG_NSENTER is not set
+# CONFIG_ONEIT is not set
+# CONFIG_PARTPROBE is not set
+# CONFIG_PIVOT_ROOT is not set
+# CONFIG_PMAP is not set
+# CONFIG_PRINTENV is not set
+# CONFIG_PWDX is not set
+# CONFIG_READAHEAD is not set
+# CONFIG_READLINK is not set
+# CONFIG_REALPATH is not set
+# CONFIG_RESET is not set
+# CONFIG_REV is not set
+# CONFIG_RMMOD is not set
+# CONFIG_SETFATTR is not set
+# CONFIG_SETSID is not set
+# CONFIG_SHRED is not set
+# CONFIG_STAT is not set
+# CONFIG_SWAPOFF is not set
+# CONFIG_SWAPON is not set
+# CONFIG_SWITCH_ROOT is not set
+# CONFIG_SYSCTL is not set
+# CONFIG_TAC is not set
+# CONFIG_NPROC is not set
+# CONFIG_TASKSET is not set
+# CONFIG_TIMEOUT is not set
+# CONFIG_TRUNCATE is not set
+# CONFIG_UPTIME is not set
+# CONFIG_USLEEP is not set
+# CONFIG_UUIDGEN is not set
+# CONFIG_VCONFIG is not set
+# CONFIG_VMSTAT is not set
+# CONFIG_W is not set
+# CONFIG_WATCH is not set
+# CONFIG_WHICH is not set
+# CONFIG_XXD is not set
+# CONFIG_YES is not set
+# CONFIG_FTPGET is not set
+# CONFIG_FTPPUT is not set
+# CONFIG_MICROCOM is not set
+# CONFIG_NETCAT is not set
+# CONFIG_NETCAT_LISTEN is not set
+# CONFIG_NETSTAT is not set
+# CONFIG_RFKILL is not set
+# CONFIG_SNTP is not set
+# CONFIG_TUNCTL is not set
+# CONFIG_DMESG is not set
+# CONFIG_GUNZIP is not set
+# CONFIG_ZCAT is not set
+# CONFIG_HOSTNAME is not set
+# CONFIG_DNSDOMAINNAME is not set
+# CONFIG_KILLALL is not set
+# CONFIG_MD5SUM is not set
+# CONFIG_SHA1SUM is not set
+# CONFIG_MKNOD is not set
+# CONFIG_MKTEMP is not set
+# CONFIG_PASSWD is not set
+# CONFIG_PIDOF is not set
+# CONFIG_SEQ is not set
+# CONFIG_SU is not set
+# CONFIG_SYNC is not set
+#
+# pending (see toys/pending/README)
+#
+# CONFIG_GETTY is not set
+# CONFIG_MDEV is not set
+# CONFIG_MDEV_CONF is not set
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/trace/BUILD.gn b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/trace/BUILD.gn
new file mode 100644
index 00000000..e8afff91
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/trace/BUILD.gn
@@ -0,0 +1,34 @@
+# 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("//kernel/liteos_a/liteos.gni")
+
+executable("trace") {
+ sources = [ "src/trace.c" ]
+}
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/trace/Makefile b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/trace/Makefile
new file mode 100644
index 00000000..787ca20f
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/trace/Makefile
@@ -0,0 +1,36 @@
+# 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 $(APPSTOPDIR)/config.mk
+
+APP_NAME := $(notdir $(shell pwd))
+
+LOCAL_SRCS := src/trace.c
+
+include $(APP)
\ No newline at end of file
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/trace/src/trace.c b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/trace/src/trace.c
new file mode 100644
index 00000000..ddcb5553
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/apps/trace/src/trace.c
@@ -0,0 +1,141 @@
+/*
+ * 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
+#include
+#include
+#include
+
+#define TRACE_IOC_MAGIC 'T'
+#define TRACE_START _IO(TRACE_IOC_MAGIC, 1)
+#define TRACE_STOP _IO(TRACE_IOC_MAGIC, 2)
+#define TRACE_RESET _IO(TRACE_IOC_MAGIC, 3)
+#define TRACE_DUMP _IO(TRACE_IOC_MAGIC, 4)
+#define TRACE_SET_MASK _IO(TRACE_IOC_MAGIC, 5)
+
+#define TRACE_USR_MAX_PARAMS 3
+typedef struct {
+ unsigned int eventType;
+ uintptr_t identity;
+ uintptr_t params[TRACE_USR_MAX_PARAMS];
+} UsrEventInfo;
+
+static void TraceUsage(void)
+{
+ printf("\nUsage: ./trace [start] Start to trace events.\n");
+ printf("\nUsage: ./trace [stop] Stop trace.\n");
+ printf("\nUsage: ./trace [reset] Clear the trace record buffer.\n");
+ printf("\nUsage: ./trace [dump 0/1] Format printf trace data,"
+ "0/1 stands for whether to send data to studio for analysis.\n");
+ printf("\nUsage: ./trace [mask num] Set trace filter event mask.\n");
+ printf("\nUsage: ./trace [read nBytes] Read nBytes raw data from trace buffer.\n");
+ printf("\nUsage: ./trace [write type id params..] Write a user event, no more than 3 parameters.\n");
+}
+
+static void TraceRead(int fd, size_t size)
+{
+ ssize_t i;
+ ssize_t len;
+ if (size <= 0) {
+ return;
+ }
+
+ char *buffer = (char *)malloc(size);
+ if (buffer == NULL) {
+ printf("Read buffer malloc failed.\n");
+ return;
+ }
+
+ len = read(fd, buffer, size);
+ for (i = 0; i < len; i++) {
+ printf("%02x ", buffer[i] & 0xFF);
+ }
+ printf("\n");
+ free(buffer);
+}
+
+static void TraceWrite(int fd, int argc, char **argv)
+{
+ int i;
+ UsrEventInfo info = {0};
+ info.eventType = strtoul(argv[2], NULL, 0); /* 2, argv number */
+ info.identity = strtoul(argv[3], NULL, 0); /* 3, argv number */
+ /* 4, argc -4 means user argv that does not contain argv[0]~argv[3] */
+ int paramNum = (argc - 4) > TRACE_USR_MAX_PARAMS ? TRACE_USR_MAX_PARAMS : (argc - 4);
+
+ for (i = 0; i < paramNum; i++) {
+ /* 4, argc -4 means user argv that does not contain argv[0]~argv[3] */
+ info.params[i] = strtoul(argv[4 + i], NULL, 0);
+ }
+ (void)write(fd, &info, sizeof(UsrEventInfo));
+}
+
+int main(int argc, char **argv)
+{
+ int fd = open("/dev/trace", O_RDWR);
+ if (fd == -1) {
+ printf("Trace open failed.\n");
+ exit(EXIT_FAILURE);
+ }
+
+ if (argc == 1) {
+ TraceUsage();
+ } else if (argc == 2 && strcmp(argv[1], "start") == 0) { /* 2, argv num, no special meaning */
+ ioctl(fd, TRACE_START, NULL);
+ } else if (argc == 2 && strcmp(argv[1], "stop") == 0) { /* 2, argv num, no special meaning */
+ ioctl(fd, TRACE_STOP, NULL);
+ } else if (argc == 2 && strcmp(argv[1], "reset") == 0) { /* 2, argv num, no special meaning */
+ ioctl(fd, TRACE_RESET, NULL);
+ } else if (argc == 3 && strcmp(argv[1], "mask") == 0) { /* 3, argv num, no special meaning */
+ size_t mask = strtoul(argv[2], NULL, 0);
+ ioctl(fd, TRACE_SET_MASK, mask);
+ } else if (argc == 3 && strcmp(argv[1], "dump") == 0) { /* 3, argv num, no special meaning */
+ size_t flag = strtoul(argv[2], NULL, 0);
+ ioctl(fd, TRACE_DUMP, flag);
+ } else if (argc == 3 && strcmp(argv[1], "read") == 0) { /* 3, argv num, no special meaning */
+ size_t size = strtoul(argv[2], NULL, 0);
+ TraceRead(fd, size);
+ } else if (argc >= 4 && strcmp(argv[1], "write") == 0) { /* 4, argv num, no special meaning */
+ TraceWrite(fd, argc, argv);
+ } else {
+ printf("Unsupported trace command.\n");
+ TraceUsage();
+ }
+
+ close(fd);
+ return 0;
+}
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/BUILD.gn b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/BUILD.gn
new file mode 100644
index 00000000..75517815
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/BUILD.gn
@@ -0,0 +1,44 @@
+# 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("//kernel/liteos_a/liteos.gni")
+
+group("arch") {
+ deps = []
+ if (defined(LOSCFG_ARCH_ARM)) {
+ deps += [ "arm" ]
+ }
+}
+
+config("public") {
+ configs = []
+ if (defined(LOSCFG_ARCH_ARM)) {
+ configs += [ "arm:public" ]
+ }
+}
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/Kconfig b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/Kconfig
new file mode 100644
index 00000000..9e58fe4a
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/Kconfig
@@ -0,0 +1,33 @@
+config ARCH_ARM
+ bool
+
+source "arch/arm/Kconfig"
+
+comment "Extra Configurations"
+
+config ARCH_FPU_DISABLE
+ bool "Disable Floating Pointer Unit"
+ default n
+ help
+ This option will bypass floating procedure in system.
+
+config ARCH_SECURE_MONITOR_MODE
+ bool "Run On Secure Monitor Mode"
+ default n
+ depends on ARCH_ARM_AARCH64
+ help
+ This option will make the system run on EL3.
+
+config ARCH_INTERRUPT_PREEMPTION
+ bool "Enable Interrupt Preemption"
+ default n
+ depends on ARCH_ARM_AARCH64
+ help
+ This option will support high priority interrupt preemption.
+
+config IRQ_USE_STANDALONE_STACK
+ bool "Use Interrupt Stack"
+ default y
+ depends on ARCH_ARM_AARCH64 || ARCH_ARM_AARCH32
+ help
+ This option will support using standalone interrupt stack.
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/BUILD.gn b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/BUILD.gn
new file mode 100644
index 00000000..257b1830
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/BUILD.gn
@@ -0,0 +1,40 @@
+# 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("//kernel/liteos_a/liteos.gni")
+
+group("arm") {
+ deps = [ "gic" ]
+ deps += [ ARCH ]
+}
+
+config("public") {
+ include_dirs = [ "include" ]
+ configs = [ "$ARCH:public" ]
+}
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/Kconfig b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/Kconfig
new file mode 100644
index 00000000..f87fa49c
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/Kconfig
@@ -0,0 +1,103 @@
+# ARM Architecture
+
+#
+# ARM has 32-bit(Aarch32) and 64-bit(Aarch64) implementations
+#
+config ARCH_ARM_AARCH32
+ bool
+ select ARCH_ARM
+ help
+ 32-bit ARM architecture implementations, Except the M-profile.
+ It is not limited to ARMv7-A but also ARMv7-R, ARMv8-A 32-bit and etc.
+
+#
+# Architecture Versions
+#
+config ARCH_ARM_V7A
+ bool
+
+config ARCH_ARM_VER
+ string
+ default "armv7-a" if ARCH_ARM_V7A
+
+#
+# VFP Hardware
+#
+config ARCH_FPU_VFP_V3
+ bool
+ help
+ An optional extension to the Arm, Thumb, and ThumbEE instruction sets in the ARMv7-A and ARMv7-R profiles.
+ VFPv3U is a variant of VFPv3 that supports the trapping of floating-point exceptions to support code.
+
+config ARCH_FPU_VFP_V4
+ bool
+ help
+ An optional extension to the Arm, Thumb, and ThumbEE instruction sets in the ARMv7-A and ARMv7-R profiles.
+ VFPv4U is a variant of VFPv4 that supports the trapping of floating-point exceptions to support code.
+ VFPv4 and VFPv4U add both the Half-precision Extension and the fused multiply-add instructions to the features of VFPv3.
+
+config ARCH_FPU_VFP_D16
+ bool
+ depends on ARCH_ARM_AARCH32
+ help
+ VPU implemented with 16 doubleword registers (16 x 64-bit).
+
+config ARCH_FPU_VFP_D32
+ bool
+ depends on ARCH_ARM_AARCH32
+ help
+ VPU implemented with 32 doubleword registers (32 x 64-bit).
+
+config ARCH_FPU_VFP_NEON
+ bool
+ help
+ Advanced SIMD extension (NEON) support.
+
+config ARCH_FPU
+ string
+ default "vfpv3" if ARCH_FPU_VFP_V3 && ARCH_FPU_VFP_D32
+ default "vfpv3-d16" if ARCH_FPU_VFP_V3 && ARCH_FPU_VFP_D16
+ default "neon-vfpv4" if ARCH_FPU_VFP_V4 && ARCH_FPU_VFP_D32 && ARCH_FPU_VFP_NEON
+ default "vfpv4" if ARCH_FPU_VFP_V4 && ARCH_FPU_VFP_D32
+ default "vfpv4-d16" if ARCH_FPU_VFP_V4 && ARCH_FPU_VFP_D16
+
+#
+# Supported Processor Cores
+#
+config ARCH_CORTEX_A7
+ bool
+ select ARCH_ARM_V7A
+ select ARCH_ARM_AARCH32
+ select ARCH_FPU_VFP_V4
+ select ARCH_FPU_VFP_D32
+ select ARCH_FPU_VFP_NEON
+
+config ARCH_CPU
+ string
+ default "cortex-a7" if ARCH_CORTEX_A7
+
+#
+# Supported GIC version
+#
+
+choice
+ prompt "GIC version"
+ default ARCH_GIC_V2
+ help
+ Interrupt Controller.
+
+config ARCH_GIC_V2
+ bool "GIC Version 2"
+ help
+ This GIC(General Interrupt Controller) version 2 driver is compatatble with
+ GIC version 1 and version 2.
+
+config ARCH_GIC_V3
+ bool "GIC Version 3"
+ depends on ARCH_ARM_V8A || ARCH_ARM_V8R
+ help
+ General Interrupt Controller version 3.
+
+endchoice
+
+
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm.mk b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm.mk
new file mode 100644
index 00000000..248ef5ee
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm.mk
@@ -0,0 +1,76 @@
+# 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.
+
+# strip quotation mark in configuration
+
+LOSCFG_ARCH_CPU_STRIP := $(subst $\",,$(LOSCFG_ARCH_CPU))
+LOSCFG_ARCH_CPU = $(LOSCFG_ARCH_CPU_STRIP)
+
+LOSCFG_ARCH_FPU_STRIP := $(subst $\",,$(LOSCFG_ARCH_FPU))
+LOSCFG_ARCH_FPU = $(LOSCFG_ARCH_FPU_STRIP)
+
+ifeq ($(LOSCFG_ARCH_ARM_AARCH32), y)
+ARCH := arm
+else ifeq ($(LOSCFG_ARCH_ARM_AARCH64), y)
+ARCH := aarch64
+endif
+
+LITEOS_BASELIB += -l$(LOSCFG_ARCH_CPU)
+LITEOS_BASELIB += -lgic
+
+LIB_SUBDIRS += arch/arm/$(ARCH)
+LIB_SUBDIRS += arch/arm/gic
+
+# CPU compile options
+ifeq ($(LOSCFG_ARCH_ARM_AARCH64), y)
+ifeq ($(LOSCFG_ARCH_FPU_DISABLE), y)
+EXTENSION := +nofp
+endif
+endif
+LITEOS_CPU_OPTS := -mcpu=$(LOSCFG_ARCH_CPU)$(EXTENSION)
+
+# FPU compile options
+# -mfloat and -mfpu is ignored with AArch64 targets
+ifeq ($(LOSCFG_ARCH_ARM_AARCH32), y)
+LITEOS_FLOAT_OPTS := -mfloat-abi=softfp
+LITEOS_FPU_OPTS := -mfpu=$(LOSCFG_ARCH_FPU)
+# gcc libc folder style is combine with core and fpu
+# for example, cortex-a7 with softfp abi and neon vfp4 is: a7_softfp_neon_vfp4
+LITEOS_GCCLIB := $(subst cortex-,,$(LOSCFG_ARCH_CPU))_softfp_$(LOSCFG_ARCH_FPU)
+endif
+
+LITEOS_CORE_COPTS = $(or $(ARCH_CFLAGS),$(LITEOS_CPU_OPTS) $(LITEOS_FLOAT_OPTS) $(LITEOS_FPU_OPTS))
+LITEOS_ASOPTS += $(LITEOS_CPU_OPTS)
+LITEOS_CXXOPTS_BASE += $(LITEOS_CORE_COPTS)
+
+ARCH_INCLUDE := -I $(LITEOSTOPDIR)/arch/arm/include \
+ -I $(LITEOSTOPDIR)/arch/arm/$(ARCH)/include \
+ -I $(LITEOSTOPDIR)/arch/arm/$(ARCH)/src/include
+
+LITEOS_PLATFORM_INCLUDE += $(ARCH_INCLUDE)
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/BUILD.gn b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/BUILD.gn
new file mode 100644
index 00000000..260544f6
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/BUILD.gn
@@ -0,0 +1,96 @@
+# 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("//kernel/liteos_a/liteos.gni")
+
+module_name = LOSCFG_ARCH_CPU
+kernel_module(module_name) {
+ sources = [
+ "src/arm_generic_timer.c",
+ "src/clear_user.S",
+ "src/hw_user_get.S",
+ "src/hw_user_put.S",
+ "src/jmp.S",
+ "src/los_arch_mmu.c",
+ "src/los_asid.c",
+ "src/los_dispatch.S",
+ "src/los_exc.c",
+ "src/los_hw.c",
+ "src/los_hw_exc.S",
+ "src/los_hw_runstop.S",
+ "src/los_hw_tick.c",
+ "src/los_hwi.c",
+ "src/smp.c",
+ "src/strncpy_from_user.c",
+ "src/strnlen_user.c",
+ "src/user_copy.c",
+ ]
+
+ if (LOSCFG_ARCH_ARM_VER == "armv7-a") {
+ sources += [ "src/armv7a/cache.S" ]
+ }
+
+ if (defined(LOSCFG_KERNEL_SMP)) {
+ sources += [ "src/startup/reset_vector_mp.S" ]
+ } else {
+ sources += [ "src/startup/reset_vector_up.S" ]
+ }
+
+ include_dirs = [ "src/include" ]
+
+ if (defined(LOSCFG_PERF_HW_PMU)) {
+ sources += [ "src/pmu/armv7_pmu.c" ]
+ }
+
+ if (defined(LOSCFG_GDB)) {
+ configs += [ ":as_objs_libc_flags" ]
+ }
+
+ public_configs = [ ":public" ]
+}
+
+config("public") {
+ include_dirs = [
+ "include",
+ "src/include",
+ ]
+}
+
+config("as_objs_libc_flags") {
+ defines = [ "__ASSEMBLY__" ]
+
+ # linux style macros
+ if (defined(LOSCFG_ARCH_ARM_V7A) || defined(LOSCFG_ARCH_ARM_V7R) ||
+ defined(LOSCFG_ARCH_ARM_V7M)) {
+ defines += [ "__LINUX_ARM_ARCH__=7" ]
+ } else if (defined(LOSCFG_ARCH_ARM_V8A) || defined(LOSCFG_ARCH_ARM_V8R) ||
+ defined(LOSCFG_ARCH_ARM_V8M)) {
+ defines += [ "__LINUX_ARM_ARCH__=8" ]
+ }
+}
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/Makefile b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/Makefile
new file mode 100644
index 00000000..52f8b55b
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/Makefile
@@ -0,0 +1,65 @@
+# 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 $(LITEOSTOPDIR)/config.mk
+
+MODULE_NAME := $(LOSCFG_ARCH_CPU)
+
+LOCAL_SRCS := $(wildcard src/*.c) $(wildcard src/*.S)
+
+ifeq ($(LOSCFG_ARCH_ARM_VER), "armv7-a")
+LOCAL_SRCS += $(wildcard src/armv7a/*.S)
+endif
+
+ifeq ($(LOSCFG_KERNEL_SMP), y)
+LOCAL_SRCS += src/startup/reset_vector_mp.S
+else
+LOCAL_SRCS += src/startup/reset_vector_up.S
+endif
+
+ifeq ($(LOSCFG_PERF_HW_PMU), y)
+LOCAL_SRCS += src/pmu/armv7_pmu.c
+endif
+
+LOCAL_FLAGS := $(LOCAL_INCLUDE)
+
+AS_OBJS_LIBC_FLAGS = -D__ASSEMBLY__
+# linux style macros
+LINUX_ARCH_$(LOSCFG_ARCH_ARM_V7A) = -D__LINUX_ARM_ARCH__=7
+LINUX_ARCH_$(LOSCFG_ARCH_ARM_V7R) = -D__LINUX_ARM_ARCH__=7
+LINUX_ARCH_$(LOSCFG_ARCH_ARM_V7M) = -D__LINUX_ARM_ARCH__=7
+LINUX_ARCH_$(LOSCFG_ARCH_ARM_V8A) = -D__LINUX_ARM_ARCH__=8
+LINUX_ARCH_$(LOSCFG_ARCH_ARM_V8R) = -D__LINUX_ARM_ARCH__=8
+LINUX_ARCH_$(LOSCFG_ARCH_ARM_V8M) = -D__LINUX_ARM_ARCH__=8
+AS_OBJS_LIBC_FLAGS += $(LINUX_ARCH_y)
+
+ifeq ($(LOSCFG_GDB), y)
+LOCAL_FLAGS += $(AS_OBJS_LIBC_FLAGS)
+endif
+include $(MODULE)
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/include/arch_config.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/include/arch_config.h
new file mode 100644
index 00000000..56aa7558
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/include/arch_config.h
@@ -0,0 +1,102 @@
+/*
+ * 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 _ARCH_CONFIG_H
+#define _ARCH_CONFIG_H
+
+
+#define CPSR_INT_DISABLE 0xC0 /* Disable both FIQ and IRQ */
+#define CPSR_IRQ_DISABLE 0x80 /* IRQ disabled when =1 */
+#define CPSR_FIQ_DISABLE 0x40 /* FIQ disabled when =1 */
+#define CPSR_THUMB_ENABLE 0x20 /* Thumb mode when =1 */
+#define CPSR_USER_MODE 0x10
+#define CPSR_FIQ_MODE 0x11
+#define CPSR_IRQ_MODE 0x12
+#define CPSR_SVC_MODE 0x13
+#define CPSR_ABT_MODE 0x17
+#define CPSR_UNDEF_MODE 0x1B
+#define CPSR_MASK_MODE 0x1F
+
+/* Define exception type ID */
+#define OS_EXCEPT_RESET 0x00
+#define OS_EXCEPT_UNDEF_INSTR 0x01
+#define OS_EXCEPT_SWI 0x02
+#define OS_EXCEPT_PREFETCH_ABORT 0x03
+#define OS_EXCEPT_DATA_ABORT 0x04
+#define OS_EXCEPT_FIQ 0x05
+#define OS_EXCEPT_ADDR_ABORT 0x06
+#define OS_EXCEPT_IRQ 0x07
+
+/* Define core num */
+#ifdef LOSCFG_KERNEL_SMP
+#define CORE_NUM LOSCFG_KERNEL_SMP_CORE_NUM
+#else
+#define CORE_NUM 1
+#endif
+
+/* Initial bit32 stack value. */
+#define OS_STACK_INIT 0xCACACACA
+/* Bit32 stack top magic number. */
+#define OS_STACK_MAGIC_WORD 0xCCCCCCCC
+
+#ifdef LOSCFG_GDB
+#define OS_EXC_UNDEF_STACK_SIZE 512
+#define OS_EXC_ABT_STACK_SIZE 512
+#else
+#define OS_EXC_UNDEF_STACK_SIZE 40
+#define OS_EXC_ABT_STACK_SIZE 40
+#endif
+#define OS_EXC_FIQ_STACK_SIZE 64
+#define OS_EXC_IRQ_STACK_SIZE 64
+#define OS_EXC_SVC_STACK_SIZE 0x2000
+#define OS_EXC_STACK_SIZE 0x1000
+
+#define REG_R0 0
+#define REG_R1 1
+#define REG_R2 2
+#define REG_R3 3
+#define REG_R4 4
+#define REG_R5 5
+#define REG_R6 6
+#define REG_R7 7
+#define REG_R8 8
+#define REG_R9 9
+#define REG_R10 10
+#define REG_R11 11
+#define REG_R12 12
+#define REG_R13 13
+#define REG_R14 14
+#define REG_R15 15
+#define REG_CPSR 16
+#define REG_SP REG_R13
+#define REG_LR REG_R14
+#define REG_PC REG_R15
+#endif
\ No newline at end of file
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/include/arm.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/include/arm.h
new file mode 100644
index 00000000..9d8aeb6a
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/include/arm.h
@@ -0,0 +1,1131 @@
+/*
+ * 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 __LOS_ARM_H__
+#define __LOS_ARM_H__
+
+#define CPSR_MODE_USR 0x10
+#define CPSR_MODE_MASK 0x1f
+
+STATIC INLINE UINT32 OsArmReadSctlr(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p15, 0, %0, c1,c0,0" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteSctlr(UINT32 val)
+{
+ __asm__ volatile("mcr p15, 0, %0, c1,c0,0" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadActlr(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p15, 0, %0, c1,c0,1" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteActlr(UINT32 val)
+{
+ __asm__ volatile("mcr p15, 0, %0, c1,c0,1" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadCpacr(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p15, 0, %0, c1,c0,2" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteCpacr(UINT32 val)
+{
+ __asm__ volatile("mcr p15, 0, %0, c1,c0,2" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadTtbr(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p15, 0, %0, c2,c0,0" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteTtbr(UINT32 val)
+{
+ __asm__ volatile("mcr p15, 0, %0, c2,c0,0" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadTtbr0(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p15, 0, %0, c2,c0,0" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteTtbr0(UINT32 val)
+{
+ __asm__ volatile("mcr p15, 0, %0, c2,c0,0" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadTtbr1(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p15, 0, %0, c2,c0,1" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteTtbr1(UINT32 val)
+{
+ __asm__ volatile("mcr p15, 0, %0, c2,c0,1" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadTtbcr(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p15, 0, %0, c2,c0,2" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteTtbcr(UINT32 val)
+{
+ __asm__ volatile("mcr p15, 0, %0, c2,c0,2" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadDacr(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p15, 0, %0, c3,c0,0" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteDacr(UINT32 val)
+{
+ __asm__ volatile("mcr p15, 0, %0, c3,c0,0" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadDfsr(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p15, 0, %0, c5,c0,0" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteDfsr(UINT32 val)
+{
+ __asm__ volatile("mcr p15, 0, %0, c5,c0,0" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadIfsr(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p15, 0, %0, c5,c0,1" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteIfsr(UINT32 val)
+{
+ __asm__ volatile("mcr p15, 0, %0, c5,c0,1" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadDfar(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p15, 0, %0, c6,c0,0" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteDfar(UINT32 val)
+{
+ __asm__ volatile("mcr p15, 0, %0, c6,c0,0" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadWfar(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p15, 0, %0, c6,c0,1" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteWfar(UINT32 val)
+{
+ __asm__ volatile("mcr p15, 0, %0, c6,c0,1" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadIfar(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p15, 0, %0, c6,c0,2" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteIfar(UINT32 val)
+{
+ __asm__ volatile("mcr p15, 0, %0, c6,c0,2" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadFcseidr(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p15, 0, %0, c13,c0,0" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteFcseidr(UINT32 val)
+{
+ __asm__ volatile("mcr p15, 0, %0, c13,c0,0" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadContextidr(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p15, 0, %0, c13,c0,1" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteContextidr(UINT32 val)
+{
+ __asm__ volatile("mcr p15, 0, %0, c13,c0,1" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadTpidrurw(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p15, 0, %0, c13,c0,2" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteTpidrurw(UINT32 val)
+{
+ __asm__ volatile("mcr p15, 0, %0, c13,c0,2" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadTpidruro(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p15, 0, %0, c13,c0,3" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteTpidruro(UINT32 val)
+{
+ __asm__ volatile("mcr p15, 0, %0, c13,c0,3" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadTpidrprw(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p15, 0, %0, c13,c0,4" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteTpidrprw(UINT32 val)
+{
+ __asm__ volatile("mcr p15, 0, %0, c13,c0,4" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadMidr(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p15, 0, %0, c0,c0,0" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteMidr(UINT32 val)
+{
+ __asm__ volatile("mcr p15, 0, %0, c0,c0,0" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadMpidr(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p15, 0, %0, c0,c0,5" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteMpidr(UINT32 val)
+{
+ __asm__ volatile("mcr p15, 0, %0, c0,c0,5" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadVbar(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p15, 0, %0, c12,c0,0" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteVbar(UINT32 val)
+{
+ __asm__ volatile("mcr p15, 0, %0, c12,c0,0" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadCbar(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p15, 4, %0, c15,c0,0" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteCbar(UINT32 val)
+{
+ __asm__ volatile("mcr p15, 4, %0, c15,c0,0" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadAts1cpr(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p15, 0, %0, c7,c8,0" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteAts1cpr(UINT32 val)
+{
+ __asm__ volatile("mcr p15, 0, %0, c7,c8,0" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadAts1cpw(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p15, 0, %0, c7,c8,1" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteAts1cpw(UINT32 val)
+{
+ __asm__ volatile("mcr p15, 0, %0, c7,c8,1" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadAts1cur(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p15, 0, %0, c7,c8,2" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteAts1cur(UINT32 val)
+{
+ __asm__ volatile("mcr p15, 0, %0, c7,c8,2" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadAts1cuw(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p15, 0, %0, c7,c8,3" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteAts1cuw(UINT32 val)
+{
+ __asm__ volatile("mcr p15, 0, %0, c7,c8,3" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadAts12nsopr(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p15, 0, %0, c7,c8,4" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteAts12nsopr(UINT32 val)
+{
+ __asm__ volatile("mcr p15, 0, %0, c7,c8,4" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadAts12nsopw(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p15, 0, %0, c7,c8,5" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteAts12nsopw(UINT32 val)
+{
+ __asm__ volatile("mcr p15, 0, %0, c7,c8,5" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadAts12nsour(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p15, 0, %0, c7,c8,6" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteAts12nsour(UINT32 val)
+{
+ __asm__ volatile("mcr p15, 0, %0, c7,c8,6" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadAts12nsouw(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p15, 0, %0, c7,c8,7" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteAts12nsouw(UINT32 val)
+{
+ __asm__ volatile("mcr p15, 0, %0, c7,c8,7" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadPar(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p15, 0, %0, c7,c4,0" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWritePar(UINT32 val)
+{
+ __asm__ volatile("mcr p15, 0, %0, c7,c4,0" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadBpiall(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p15, 0, %0, c7,c5,6" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteBpiall(UINT32 val)
+{
+ __asm__ volatile("mcr p15, 0, %0, c7,c5,6" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadBpimva(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p15, 0, %0, c7,c5,7" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteBpimva(UINT32 val)
+{
+ __asm__ volatile("mcr p15, 0, %0, c7,c5,7" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadBpiallis(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p15, 0, %0, c7,c1,6" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteBpiallis(UINT32 val)
+{
+ __asm__ volatile("mcr p15, 0, %0, c7,c1,6" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadTlbiallis(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p15, 0, %0, c8,c3,0" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteTlbiallis(UINT32 val)
+{
+ __asm__ volatile("mcr p15, 0, %0, c8,c3,0" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadTlbimvais(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p15, 0, %0, c8,c3,1" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteTlbimvais(UINT32 val)
+{
+ __asm__ volatile("mcr p15, 0, %0, c8,c3,1" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadTlbiasidis(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p15, 0, %0, c8,c3,2" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteTlbiasidis(UINT32 val)
+{
+ __asm__ volatile("mcr p15, 0, %0, c8,c3,2" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadTlbimvaais(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p15, 0, %0, c8,c3,3" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteTlbimvaais(UINT32 val)
+{
+ __asm__ volatile("mcr p15, 0, %0, c8,c3,3" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadItlbiall(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p15, 0, %0, c8,c5,0" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteItlbiall(UINT32 val)
+{
+ __asm__ volatile("mcr p15, 0, %0, c8,c5,0" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadItlbimva(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p15, 0, %0, c8,c5,1" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteItlbimva(UINT32 val)
+{
+ __asm__ volatile("mcr p15, 0, %0, c8,c5,1" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadItlbiasid(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p15, 0, %0, c8,c5,2" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteItlbiasid(UINT32 val)
+{
+ __asm__ volatile("mcr p15, 0, %0, c8,c5,2" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadDtlbiall(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p15, 0, %0, c8,c6,0" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteDtlbiall(UINT32 val)
+{
+ __asm__ volatile("mcr p15, 0, %0, c8,c6,0" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadDtlbimva(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p15, 0, %0, c8,c6,1" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteDtlbimva(UINT32 val)
+{
+ __asm__ volatile("mcr p15, 0, %0, c8,c6,1" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadDtlbiasid(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p15, 0, %0, c8,c6,2" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteDtlbiasid(UINT32 val)
+{
+ __asm__ volatile("mcr p15, 0, %0, c8,c6,2" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadTlbiall(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p15, 0, %0, c8,c7,0" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteTlbiall(UINT32 val)
+{
+ __asm__ volatile("mcr p15, 0, %0, c8,c7,0" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadTlbimva(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p15, 0, %0, c8,c7,1" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteTlbimva(UINT32 val)
+{
+ __asm__ volatile("mcr p15, 0, %0, c8,c7,1" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadTlbiasid(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p15, 0, %0, c8,c7,2" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteTlbiasid(UINT32 val)
+{
+ __asm__ volatile("mcr p15, 0, %0, c8,c7,2" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadTlbimvaa(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p15, 0, %0, c8,c7,3" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteTlbimvaa(UINT32 val)
+{
+ __asm__ volatile("mcr p15, 0, %0, c8,c7,3" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadL2ctlr(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p15, 1, %0, c9,c0,2" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteL2ctlr(UINT32 val)
+{
+ __asm__ volatile("mcr p15, 1, %0, c9,c0,2" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadL2ectlr(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p15, 1, %0, c9,c0,3" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteL2ectlr(UINT32 val)
+{
+ __asm__ volatile("mcr p15, 1, %0, c9,c0,3" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadDbddidr(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p14, 0, %0, c0,c0,0" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteDbddidr(UINT32 val)
+{
+ __asm__ volatile("mcr p14, 0, %0, c0,c0,0" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadDbgdrar(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p14, 0, %0, c1,c0,0" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteDbgdrar(UINT32 val)
+{
+ __asm__ volatile("mcr p14, 0, %0, c1,c0,0" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadDbgdsar(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p14, 0, %0, c2,c0,0" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteDbgdsar(UINT32 val)
+{
+ __asm__ volatile("mcr p14, 0, %0, c2,c0,0" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadDbgdscr(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p14, 0, %0, c0,c1,0" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteDbgdscr(UINT32 val)
+{
+ __asm__ volatile("mcr p14, 0, %0, c0,c1,0" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadDbgdtrtxint(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p14, 0, %0, c0,c5,0" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteDbgdtrtxint(UINT32 val)
+{
+ __asm__ volatile("mcr p14, 0, %0, c0,c5,0" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadDbgdtrrxint(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p14, 0, %0, c0,c5,0" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteDbgdtrrxint(UINT32 val)
+{
+ __asm__ volatile("mcr p14, 0, %0, c0,c5,0" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadDbgwfar(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p14, 0, %0, c0,c6,0" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteDbgwfar(UINT32 val)
+{
+ __asm__ volatile("mcr p14, 0, %0, c0,c6,0" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadDbgvcr(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p14, 0, %0, c0,c7,0" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteDbgvcr(UINT32 val)
+{
+ __asm__ volatile("mcr p14, 0, %0, c0,c7,0" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadDbgecr(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p14, 0, %0, c0,c9,0" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteDbgecr(UINT32 val)
+{
+ __asm__ volatile("mcr p14, 0, %0, c0,c9,0" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadDbgdsccr(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p14, 0, %0, c0,c10,0" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteDbgdsccr(UINT32 val)
+{
+ __asm__ volatile("mcr p14, 0, %0, c0,c10,0" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadDbgdsmcr(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p14, 0, %0, c0,c11,0" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteDbgdsmcr(UINT32 val)
+{
+ __asm__ volatile("mcr p14, 0, %0, c0,c11,0" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadDbgdtrrxext(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p14, 0, %0, c0,c0,2" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteDbgdtrrxext(UINT32 val)
+{
+ __asm__ volatile("mcr p14, 0, %0, c0,c0,2" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadDbgdscrext(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p14, 0, %0, c0,c2,2" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteDbgdscrext(UINT32 val)
+{
+ __asm__ volatile("mcr p14, 0, %0, c0,c2,2" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadDbgdtrtxext(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p14, 0, %0, c0,c3,2" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteDbgdtrtxext(UINT32 val)
+{
+ __asm__ volatile("mcr p14, 0, %0, c0,c3,2" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadDbgdrcr(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p14, 0, %0, c0,c4,2" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteDbgdrcr(UINT32 val)
+{
+ __asm__ volatile("mcr p14, 0, %0, c0,c4,2" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadDbgvr0(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p14, 0, %0, c0,c0,4" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteDbgvr0(UINT32 val)
+{
+ __asm__ volatile("mcr p14, 0, %0, c0,c0,4" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadDbgvr1(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p14, 0, %0, c0,c1,4" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteDbgvr1(UINT32 val)
+{
+ __asm__ volatile("mcr p14, 0, %0, c0,c1,4" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadDbgvr2(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p14, 0, %0, c0,c2,4" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteDbgvr2(UINT32 val)
+{
+ __asm__ volatile("mcr p14, 0, %0, c0,c2,4" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadDbgbcr0(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p14, 0, %0, c0,c0,5" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteDbgbcr0(UINT32 val)
+{
+ __asm__ volatile("mcr p14, 0, %0, c0,c0,5" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadDbgbcr1(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p14, 0, %0, c0,c1,5" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteDbgbcr1(UINT32 val)
+{
+ __asm__ volatile("mcr p14, 0, %0, c0,c1,5" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadDbgbcr2(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p14, 0, %0, c0,c2,5" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteDbgbcr2(UINT32 val)
+{
+ __asm__ volatile("mcr p14, 0, %0, c0,c2,5" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadDbgwvr0(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p14, 0, %0, c0,c0,6" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteDbgwvr0(UINT32 val)
+{
+ __asm__ volatile("mcr p14, 0, %0, c0,c0,6" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadDbgwvr1(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p14, 0, %0, c0,c1,6" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteDbgwvr1(UINT32 val)
+{
+ __asm__ volatile("mcr p14, 0, %0, c0,c1,6" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadDbgwcr0(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p14, 0, %0, c0,c0,7" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteDbgwcr0(UINT32 val)
+{
+ __asm__ volatile("mcr p14, 0, %0, c0,c0,7" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadDbgwcr1(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p14, 0, %0, c0,c1,7" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteDbgwcr1(UINT32 val)
+{
+ __asm__ volatile("mcr p14, 0, %0, c0,c1,7" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadDbgoslar(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p14, 0, %0, c1,c0,4" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteDbgoslar(UINT32 val)
+{
+ __asm__ volatile("mcr p14, 0, %0, c1,c0,4" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadDbgoslsr(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p14, 0, %0, c1,c1,4" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteDbgoslsr(UINT32 val)
+{
+ __asm__ volatile("mcr p14, 0, %0, c1,c1,4" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadDbgossrr(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p14, 0, %0, c1,c2,4" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteDbgossrr(UINT32 val)
+{
+ __asm__ volatile("mcr p14, 0, %0, c1,c2,4" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadDbgprcr(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p14, 0, %0, c1,c4,4" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteDbgprcr(UINT32 val)
+{
+ __asm__ volatile("mcr p14, 0, %0, c1,c4,4" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadDbgprsr(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p14, 0, %0, c1,c5,4" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteDbgprsr(UINT32 val)
+{
+ __asm__ volatile("mcr p14, 0, %0, c1,c5,4" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadDbgclaimset(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p14, 0, %0, c7,c8,6" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteDbgclaimset(UINT32 val)
+{
+ __asm__ volatile("mcr p14, 0, %0, c7,c8,6" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadDbgclaimclr(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p14, 0, %0, c7,c9,6" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteDbgclaimclr(UINT32 val)
+{
+ __asm__ volatile("mcr p14, 0, %0, c7,c9,6" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadDbgauthstatus(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p14, 0, %0, c7,c14,6" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteDbgauthstatus(UINT32 val)
+{
+ __asm__ volatile("mcr p14, 0, %0, c7,c14,6" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+STATIC INLINE UINT32 OsArmReadDbgdevid(VOID)
+{
+ UINT32 val;
+ __asm__ volatile("mrc p14, 0, %0, c7,c2,7" : "=r"(val));
+ return val;
+}
+
+STATIC INLINE VOID OsArmWriteDbgdevid(UINT32 val)
+{
+ __asm__ volatile("mcr p14, 0, %0, c7,c2,7" ::"r"(val));
+ __asm__ volatile("isb" ::: "memory");
+}
+
+#endif /* __LOS_ARM_H__ */
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/include/arm_user_clear.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/include/arm_user_clear.h
new file mode 100644
index 00000000..d808208a
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/include/arm_user_clear.h
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 2021-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 _ARM_USER_CLEAR_H
+#define _ARM_USER_CLEAR_H
+
+#include "los_typedef.h"
+
+#ifdef __cplusplus
+#if __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+size_t _arm_clear_user(void *addr, size_t bytes);
+
+#ifdef __cplusplus
+#if __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+#endif /* _ARM_USER_CLEAR_H */
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/include/arm_user_copy.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/include/arm_user_copy.h
new file mode 100644
index 00000000..b86e37c4
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/include/arm_user_copy.h
@@ -0,0 +1,36 @@
+/*
+ * 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_typedef.h"
+#pragma once
+
+size_t _arm_user_copy(void *dst, const void *src, size_t len);
+
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/include/arm_user_get.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/include/arm_user_get.h
new file mode 100644
index 00000000..2f4a67ef
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/include/arm_user_get.h
@@ -0,0 +1,52 @@
+/*
+ * 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 _ARM_USER_GET_H
+#define _ARM_USER_GET_H
+
+#include "los_typedef.h"
+#include "securec.h"
+
+#ifdef __cplusplus
+#if __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+errno_t _arm_get_user(void *dst, const void *src, size_t dstTypeLen, size_t srcTypeLen);
+
+#ifdef __cplusplus
+#if __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+#endif /* _ARM_USER_GET_H */
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/include/arm_user_put.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/include/arm_user_put.h
new file mode 100644
index 00000000..28b04f46
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/include/arm_user_put.h
@@ -0,0 +1,52 @@
+/*
+ * 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 _ARM_USER_PUT_H
+#define _ARM_USER_PUT_H
+
+#include "los_typedef.h"
+#include "securec.h"
+
+#ifdef __cplusplus
+#if __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+errno_t _arm_put_user(void *dst, const void *src, size_t dstTypeLen, size_t srcTypeLen);
+
+#ifdef __cplusplus
+#if __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+#endif /* _ARM_USER_PUT_H */
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/include/hal_timer.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/include/hal_timer.h
new file mode 100644
index 00000000..667188bc
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/include/hal_timer.h
@@ -0,0 +1,64 @@
+/*
+ * 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 _LOS_TIMER_H
+#define _LOS_TIMER_H
+
+#ifdef __cplusplus
+#if __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+extern UINT32 HalClockFreqRead(VOID);
+extern VOID HalClockFreqWrite(UINT32 freq);
+extern VOID HalClockStart(VOID);
+extern VOID HalClockIrqClear(VOID);
+extern VOID HalClockInit(VOID);
+extern UINT64 HalClockGetCycles(VOID);
+extern VOID HalDelayUs(UINT32 usecs);
+extern UINT32 HalClockGetTickTimerCycles(VOID);
+extern UINT64 HalClockTickTimerReload(UINT64 cycles);
+
+extern UINT32 HrtimersInit(VOID);
+extern VOID HrtimerClockIrqClear(VOID);
+extern VOID HrtimerClockStart(UINT32 period);
+extern VOID HrtimerClockStop(VOID);
+extern UINT32 HrtimerClockValueGet(VOID);
+extern VOID HrtimerClockInit(VOID);
+
+#ifdef __cplusplus
+#if __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+#endif /* _LOS_TIMER_H */
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/include/los_arch_mmu.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/include/los_arch_mmu.h
new file mode 100644
index 00000000..afb0ab93
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/include/los_arch_mmu.h
@@ -0,0 +1,80 @@
+/*
+ * 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.
+ */
+
+/**
+ * @defgroup los_arch_mmu architecture mmu
+ * @ingroup kernel
+ */
+
+#ifndef __LOS_ARCH_MMU_H__
+#define __LOS_ARCH_MMU_H__
+
+#include "los_typedef.h"
+#include "los_vm_phys.h"
+#ifndef LOSCFG_PAGE_TABLE_FINE_LOCK
+#include "los_spinlock.h"
+#endif
+
+#ifdef __cplusplus
+#if __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+typedef struct ArchMmu {
+#ifndef LOSCFG_PAGE_TABLE_FINE_LOCK
+ SPIN_LOCK_S lock; /**< arch mmu page table entry modification spin lock */
+#endif
+ VADDR_T *virtTtb; /**< translation table base virtual addr */
+ PADDR_T physTtb; /**< translation table base phys addr */
+ UINT32 asid; /**< TLB asid */
+ LOS_DL_LIST ptList; /**< page table vm page list */
+} LosArchMmu;
+
+BOOL OsArchMmuInit(LosArchMmu *archMmu, VADDR_T *virtTtb);
+STATUS_T LOS_ArchMmuQuery(const LosArchMmu *archMmu, VADDR_T vaddr, PADDR_T *paddr, UINT32 *flags);
+STATUS_T LOS_ArchMmuUnmap(LosArchMmu *archMmu, VADDR_T vaddr, size_t count);
+STATUS_T LOS_ArchMmuMap(LosArchMmu *archMmu, VADDR_T vaddr, PADDR_T paddr, size_t count, UINT32 flags);
+STATUS_T LOS_ArchMmuChangeProt(LosArchMmu *archMmu, VADDR_T vaddr, size_t count, UINT32 flags);
+STATUS_T LOS_ArchMmuMove(LosArchMmu *archMmu, VADDR_T oldVaddr, VADDR_T newVaddr, size_t count, UINT32 flags);
+VOID LOS_ArchMmuContextSwitch(LosArchMmu *archMmu);
+STATUS_T LOS_ArchMmuDestroy(LosArchMmu *archMmu);
+VOID OsArchMmuInitPerCPU(VOID);
+VADDR_T *OsGFirstTableGet(VOID);
+
+#ifdef __cplusplus
+#if __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+#endif /* __LOS_ARCH_MMU_H__ */
+
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/include/los_asid.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/include/los_asid.h
new file mode 100644
index 00000000..613982db
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/include/los_asid.h
@@ -0,0 +1,61 @@
+/*
+ * 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.
+ */
+
+/**
+ * @defgroup los_asid mmu address space id
+ * @ingroup kernel
+ */
+
+#ifndef __LOS_ASID_H__
+#define __LOS_ASID_H__
+
+#include "los_typedef.h"
+
+#ifdef __cplusplus
+#if __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+#define MMU_ARM_ASID_BITS 8
+
+/* allocate and free asid */
+STATUS_T OsAllocAsid(UINT32 *asid);
+VOID OsFreeAsid(UINT32 asid);
+
+#ifdef __cplusplus
+#if __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+#endif /* __LOS_VM_PAGE_H__ */
+
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/include/los_atomic.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/include/los_atomic.h
new file mode 100644
index 00000000..6d79cf94
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/include/los_atomic.h
@@ -0,0 +1,892 @@
+/*
+ * 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.
+ */
+
+/**
+ * @defgroup los_atomic Atomic
+ * @ingroup kernel
+ */
+
+#ifndef __LOS_ATOMIC_H__
+#define __LOS_ATOMIC_H__
+
+#include "los_typedef.h"
+
+#ifdef __cplusplus
+#if __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+typedef volatile INT32 Atomic;
+typedef volatile INT64 Atomic64;
+
+/**
+ * @ingroup los_atomic
+ * @brief Atomic read.
+ *
+ * @par Description:
+ * This API is used to implement the atomic read and return the result value of the read.
+ * @attention
+ *
+ *
The pointer v must not be NULL.
+ *
+ *
+ * @param v [IN] The reading pointer.
+ *
+ * @retval #INT32 The result value of the read.
+ * @par Dependency:
+ *
los_atomic.h: the header file that contains the API declaration.
+ * @see
+ */
+STATIC INLINE INT32 LOS_AtomicRead(const Atomic *v)
+{
+ return *(volatile INT32 *)v;
+}
+
+/**
+ * @ingroup los_atomic
+ * @brief Atomic setting.
+ *
+ * @par Description:
+ * This API is used to implement the atomic setting operation.
+ * @attention
+ *
+ *
The pointer v must not be NULL.
+ *
+ *
+ * @param v [IN] The variable pointer to be setting.
+ * @param setVal [IN] The value to be setting.
+ *
+ * @retval none.
+ * @par Dependency:
+ *
los_atomic.h: the header file that contains the API declaration.
+ * @see
+ */
+STATIC INLINE VOID LOS_AtomicSet(Atomic *v, INT32 setVal)
+{
+ *(volatile INT32 *)v = setVal;
+}
+
+/**
+ * @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 v 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 v [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(Atomic *v, INT32 addVal)
+{
+ INT32 val;
+ UINT32 status;
+
+ do {
+ __asm__ __volatile__("ldrex %1, [%2]\n"
+ "add %1, %1, %3\n"
+ "strex %0, %1, [%2]"
+ : "=&r"(status), "=&r"(val)
+ : "r"(v), "r"(addVal)
+ : "cc");
+ } while (__builtin_expect(status != 0, 0));
+
+ return val;
+}
+
+/**
+ * @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 v 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 v [IN] The minuend pointer.
+ * @param subVal [IN] The subtrahend.
+ *
+ * @retval #INT32 The result value of the minuend.
+ * @par Dependency:
+ *
los_atomic.h: the header file that contains the API declaration.
los_atomic.h: the header file that contains the API declaration.
+ * @see
+ */
+STATIC INLINE VOID LOS_AtomicDec(Atomic *v)
+{
+ INT32 val;
+ UINT32 status;
+
+ do {
+ __asm__ __volatile__("ldrex %0, [%3]\n"
+ "sub %0, %0, #1\n"
+ "strex %1, %0, [%3]"
+ : "=&r"(val), "=&r"(status), "+m"(*v)
+ : "r"(v)
+ : "cc");
+ } while (__builtin_expect(status != 0, 0));
+}
+
+/**
+ * @ingroup los_atomic
+ * @brief Atomic auto-decrement.
+ *
+ * @par Description:
+ * This API is used to implement the atomic auto-decrement and return the result of auto-decrement.
+ * @attention
+ *
+ *
The pointer v must not be NULL.
+ *
The value which v point to must not be INT_MIN to avoid overflow after reducing 1.
+ *
+ *
+ * @param v [IN] The auto-decrement 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(Atomic *v)
+{
+ INT32 val;
+ UINT32 status;
+
+ do {
+ __asm__ __volatile__("ldrex %0, [%3]\n"
+ "sub %0, %0, #1\n"
+ "strex %1, %0, [%3]"
+ : "=&r"(val), "=&r"(status), "+m"(*v)
+ : "r"(v)
+ : "cc");
+ } while (__builtin_expect(status != 0, 0));
+
+ return val;
+}
+
+/**
+ * @ingroup los_atomic
+ * @brief Atomic64 read.
+ *
+ * @par Description:
+ * This API is used to implement the atomic64 read and return the result value of the read.
+ * @attention
+ *
+ *
The pointer v must not be NULL.
+ *
+ *
+ * @param v [IN] The reading pointer.
+ *
+ * @retval #INT64 The result value of the read.
+ * @par Dependency:
+ *
los_atomic.h: the header file that contains the API declaration.
+ * @see
+ */
+STATIC INLINE INT64 LOS_Atomic64Read(const Atomic64 *v)
+{
+ INT64 val;
+
+ do {
+ __asm__ __volatile__("ldrexd %0, %H0, [%1]"
+ : "=&r"(val)
+ : "r"(v)
+ : "cc");
+ } while (0);
+
+ return val;
+}
+
+/**
+ * @ingroup los_atomic
+ * @brief Atomic64 setting.
+ *
+ * @par Description:
+ * This API is used to implement the atomic64 setting operation.
+ * @attention
+ *
+ *
The pointer v must not be NULL.
+ *
+ *
+ * @param v [IN] The variable pointer to be setting.
+ * @param setVal [IN] The value to be setting.
+ *
+ * @retval none.
+ * @par Dependency:
+ *
los_atomic.h: the header file that contains the API declaration.
+ * @see
+ */
+STATIC INLINE VOID LOS_Atomic64Set(Atomic64 *v, INT64 setVal)
+{
+ INT64 tmp;
+ UINT32 status;
+
+ do {
+ __asm__ __volatile__("ldrexd %1, %H1, [%2]\n"
+ "strexd %0, %3, %H3, [%2]"
+ : "=&r"(status), "=&r"(tmp)
+ : "r"(v), "r"(setVal)
+ : "cc");
+ } while (__builtin_expect(status != 0, 0));
+}
+
+/**
+ * @ingroup los_atomic
+ * @brief Atomic64 addition.
+ *
+ * @par Description:
+ * This API is used to implement the atomic64 addition and return the result value of the augend.
+ * @attention
+ *
+ *
The pointer v must not be NULL.
+ *
If the addtion result is not in the range of representable values for 64-bit signed integer,
+ * an int integer overflow may occur to the return value
+ *
+ *
+ * @param v [IN] The augend pointer.
+ * @param addVal [IN] The addend.
+ *
+ * @retval #INT64 The result value of the augend.
+ * @par Dependency:
+ *
los_atomic.h: the header file that contains the API declaration.
+ * @see
+ */
+STATIC INLINE INT64 LOS_Atomic64Add(Atomic64 *v, INT64 addVal)
+{
+ INT64 val;
+ UINT32 status;
+
+ do {
+ __asm__ __volatile__("ldrexd %1, %H1, [%2]\n"
+ "adds %Q1, %Q1, %Q3\n"
+ "adc %R1, %R1, %R3\n"
+ "strexd %0, %1, %H1, [%2]"
+ : "=&r"(status), "=&r"(val)
+ : "r"(v), "r"(addVal)
+ : "cc");
+ } while (__builtin_expect(status != 0, 0));
+
+ return val;
+}
+
+/**
+ * @ingroup los_atomic
+ * @brief Atomic64 subtraction.
+ *
+ * @par Description:
+ * This API is used to implement the atomic64 subtraction and return the result value of the minuend.
+ * @attention
+ *
+ *
The pointer v must not be NULL.
+ *
If the subtraction result is not in the range of representable values for 64-bit signed integer,
+ * an int integer overflow may occur to the return value
+ *
+ *
+ * @param v [IN] The minuend pointer.
+ * @param subVal [IN] The subtrahend.
+ *
+ * @retval #INT64 The result value of the minuend.
+ * @par Dependency:
+ *
los_atomic.h: the header file that contains the API declaration.
los_atomic.h: the header file that contains the API declaration.
+ * @see
+ */
+STATIC INLINE VOID LOS_Atomic64Dec(Atomic64 *v)
+{
+ INT64 val;
+ UINT32 status;
+
+ do {
+ __asm__ __volatile__("ldrexd %0, %H0, [%3]\n"
+ "subs %Q0, %Q0, #1\n"
+ "sbc %R0, %R0, #0\n"
+ "strexd %1, %0, %H0, [%3]"
+ : "=&r"(val), "=&r"(status), "+m"(*v)
+ : "r"(v)
+ : "cc");
+ } while (__builtin_expect(status != 0, 0));
+}
+
+/**
+ * @ingroup los_atomic
+ * @brief Atomic64 auto-decrement.
+ *
+ * @par Description:
+ * This API is used to implement the atomic64 auto-decrement and return the result of auto-decrement.
+ * @attention
+ *
+ *
The pointer v must not be NULL.
+ *
The value which v point to must not be INT64_MIN to avoid overflow after reducing 1.
+ *
+ *
+ * @param v [IN] The auto-decrement variable pointer.
+ *
+ * @retval #INT64 The return value of variable auto-decrement.
+ * @par Dependency:
+ *
los_atomic.h: the header file that contains the API declaration.
+ * @see
+ */
+STATIC INLINE INT64 LOS_Atomic64DecRet(Atomic64 *v)
+{
+ INT64 val;
+ UINT32 status;
+
+ do {
+ __asm__ __volatile__("ldrexd %0, %H0, [%3]\n"
+ "subs %Q0, %Q0, #1\n"
+ "sbc %R0, %R0, #0\n"
+ "strexd %1, %0, %H0, [%3]"
+ : "=&r"(val), "=&r"(status), "+m"(*v)
+ : "r"(v)
+ : "cc");
+ } while (__builtin_expect(status != 0, 0));
+
+ return val;
+}
+
+/**
+ * @ingroup los_atomic
+ * @brief Atomic exchange for 8-bit variable.
+ *
+ * @par Description:
+ * This API is used to implement the atomic exchange for 8-bit variable and
+ * return the previous value of the atomic variable.
+ * @attention
+ *
The pointer v must not be NULL.
+ *
+ * @param v [IN] The variable pointer.
+ * @param val [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_AtomicXchgByte(volatile INT8 *v, INT32 val)
+{
+ INT32 prevVal;
+ UINT32 status;
+
+ do {
+ __asm__ __volatile__("ldrexb %0, [%3]\n"
+ "strexb %1, %4, [%3]"
+ : "=&r"(prevVal), "=&r"(status), "+m"(*v)
+ : "r"(v), "r"(val)
+ : "cc");
+ } while (__builtin_expect(status != 0, 0));
+
+ return prevVal;
+}
+
+/**
+ * @ingroup los_atomic
+ * @brief Atomic exchange for 16-bit variable.
+ *
+ * @par Description:
+ * This API is used to implement the atomic exchange for 16-bit variable and
+ * return the previous value of the atomic variable.
+ * @attention
+ *
The pointer v must not be NULL.
+ *
+ * @param v [IN] The variable pointer.
+ * @param val [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_AtomicXchg16bits(volatile INT16 *v, INT32 val)
+{
+ INT32 prevVal;
+ UINT32 status;
+
+ do {
+ __asm__ __volatile__("ldrexh %0, [%3]\n"
+ "strexh %1, %4, [%3]"
+ : "=&r"(prevVal), "=&r"(status), "+m"(*v)
+ : "r"(v), "r"(val)
+ : "cc");
+ } while (__builtin_expect(status != 0, 0));
+
+ return prevVal;
+}
+
+/**
+ * @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 v must not be NULL.
+ *
+ * @param v [IN] The variable pointer.
+ * @param val [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(Atomic *v, INT32 val)
+{
+ INT32 prevVal;
+ UINT32 status;
+
+ do {
+ __asm__ __volatile__("ldrex %0, [%3]\n"
+ "strex %1, %4, [%3]"
+ : "=&r"(prevVal), "=&r"(status), "+m"(*v)
+ : "r"(v), "r"(val)
+ : "cc");
+ } while (__builtin_expect(status != 0, 0));
+
+ return prevVal;
+}
+
+/**
+ * @ingroup los_atomic
+ * @brief Atomic exchange for 64-bit variable.
+ *
+ * @par Description:
+ * This API is used to implement the atomic exchange for 64-bit variable
+ * and return the previous value of the atomic variable.
+ * @attention
+ *
The pointer v must not be NULL.
+ *
+ * @param v [IN] The variable pointer.
+ * @param val [IN] The exchange value.
+ *
+ * @retval #INT64 The previous value of the atomic variable
+ * @par Dependency:
+ *
los_atomic.h: the header file that contains the API declaration.
+ * @see
+ */
+STATIC INLINE INT64 LOS_AtomicXchg64bits(Atomic64 *v, INT64 val)
+{
+ INT64 prevVal;
+ UINT32 status;
+
+ do {
+ __asm__ __volatile__("ldrexd %0, %H0, [%3]\n"
+ "strexd %1, %4, %H4, [%3]"
+ : "=&r"(prevVal), "=&r"(status), "+m"(*v)
+ : "r"(v), "r"(val)
+ : "cc");
+ } while (__builtin_expect(status != 0, 0));
+
+ return prevVal;
+}
+
+/**
+ * @ingroup los_atomic
+ * @brief Atomic exchange for 8-bit variable with compare.
+ *
+ * @par Description:
+ * This API is used to implement the atomic exchange for 8-bit variable, if the value of variable is equal to oldVal.
+ * @attention
+ *
The pointer v must not be NULL.
+ *
+ * @param v [IN] The variable pointer.
+ * @param val [IN] The new value.
+ * @param oldVal [IN] The old value.
+ *
+ * @retval TRUE The previous value of the atomic variable is not equal to oldVal.
+ * @retval FALSE The previous value of the atomic variable is equal to oldVal.
+ * @par Dependency:
+ *
los_atomic.h: the header file that contains the API declaration.
+ * @see
+ */
+STATIC INLINE BOOL LOS_AtomicCmpXchgByte(volatile INT8 *v, INT32 val, INT32 oldVal)
+{
+ INT32 prevVal;
+ UINT32 status;
+
+ do {
+ __asm__ __volatile__("ldrexb %0, [%3]\n"
+ "mov %1, #0\n"
+ "teq %0, %4\n"
+ "strexbeq %1, %5, [%3]"
+ : "=&r"(prevVal), "=&r"(status), "+m"(*v)
+ : "r"(v), "r"(oldVal), "r"(val)
+ : "cc");
+ } while (__builtin_expect(status != 0, 0));
+
+ return prevVal != oldVal;
+}
+
+/**
+ * @ingroup los_atomic
+ * @brief Atomic exchange for 16-bit variable with compare.
+ *
+ * @par Description:
+ * This API is used to implement the atomic exchange for 16-bit variable, if the value of variable is equal to oldVal.
+ * @attention
+ *
The pointer v must not be NULL.
+ *
+ * @param v [IN] The variable pointer.
+ * @param val [IN] The new value.
+ * @param oldVal [IN] The old value.
+ *
+ * @retval TRUE The previous value of the atomic variable is not equal to oldVal.
+ * @retval FALSE The previous value of the atomic variable is equal to oldVal.
+ * @par Dependency:
+ *
los_atomic.h: the header file that contains the API declaration.
+ * @see
+ */
+STATIC INLINE BOOL LOS_AtomicCmpXchg16bits(volatile INT16 *v, INT32 val, INT32 oldVal)
+{
+ INT32 prevVal;
+ UINT32 status;
+
+ do {
+ __asm__ __volatile__("ldrexh %0, [%3]\n"
+ "mov %1, #0\n"
+ "teq %0, %4\n"
+ "strexheq %1, %5, [%3]"
+ : "=&r"(prevVal), "=&r"(status), "+m"(*v)
+ : "r"(v), "r"(oldVal), "r"(val)
+ : "cc");
+ } while (__builtin_expect(status != 0, 0));
+
+ return prevVal != oldVal;
+}
+
+/**
+ * @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 oldVal.
+ * @attention
+ *
The pointer v must not be NULL.
+ *
+ * @param v [IN] The variable pointer.
+ * @param val [IN] The new value.
+ * @param oldVal [IN] The old value.
+ *
+ * @retval TRUE The previous value of the atomic variable is not equal to oldVal.
+ * @retval FALSE The previous value of the atomic variable is equal to oldVal.
+ * @par Dependency:
+ *
los_atomic.h: the header file that contains the API declaration.
+ * @see
+ */
+STATIC INLINE BOOL LOS_AtomicCmpXchg32bits(Atomic *v, INT32 val, INT32 oldVal)
+{
+ INT32 prevVal;
+ UINT32 status;
+
+ do {
+ __asm__ __volatile__("ldrex %0, [%3]\n"
+ "mov %1, #0\n"
+ "teq %0, %4\n"
+ "strexeq %1, %5, [%3]"
+ : "=&r"(prevVal), "=&r"(status), "+m"(*v)
+ : "r"(v), "r"(oldVal), "r"(val)
+ : "cc");
+ } while (__builtin_expect(status != 0, 0));
+
+ return prevVal != oldVal;
+}
+
+/**
+ * @ingroup los_atomic
+ * @brief Atomic exchange for 64-bit variable with compare.
+ *
+ * @par Description:
+ * This API is used to implement the atomic exchange for 64-bit variable, if the value of variable is equal to oldVal.
+ * @attention
+ *
The pointer v must not be NULL.
+ *
+ * @param v [IN] The variable pointer.
+ * @param val [IN] The new value.
+ * @param oldVal [IN] The old value.
+ *
+ * @retval TRUE The previous value of the atomic variable is not equal to oldVal.
+ * @retval FALSE The previous value of the atomic variable is equal to oldVal.
+ * @par Dependency:
+ *
los_atomic.h: the header file that contains the API declaration.
+ * @see
+ */
+STATIC INLINE BOOL LOS_AtomicCmpXchg64bits(Atomic64 *v, INT64 val, INT64 oldVal)
+{
+ INT64 prevVal;
+ UINT32 status;
+
+ do {
+ __asm__ __volatile__("ldrexd %0, %H0, [%3]\n"
+ "mov %1, #0\n"
+ "teq %0, %4\n"
+ "teqeq %H0, %H4\n"
+ "strexdeq %1, %5, %H5, [%3]"
+ : "=&r"(prevVal), "=&r"(status), "+m"(*v)
+ : "r"(v), "r"(oldVal), "r"(val)
+ : "cc");
+ } while (__builtin_expect(status != 0, 0));
+
+ return prevVal != oldVal;
+}
+
+#ifdef __cplusplus
+#if __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+#endif /* __LOS_ATOMIC_H__ */
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/include/los_hw_cpu.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/include/los_hw_cpu.h
new file mode 100644
index 00000000..0234052f
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/include/los_hw_cpu.h
@@ -0,0 +1,277 @@
+/*
+ * 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.
+ */
+
+/**
+ * @defgroup los_hw Hardware
+ * @ingroup kernel
+ */
+
+#ifndef _LOS_HW_CPU_H
+#define _LOS_HW_CPU_H
+
+#include "los_typedef.h"
+#include "los_toolchain.h"
+#include "los_hw_arch.h"
+
+#ifdef __cplusplus
+#if __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+/* ARM System Registers */
+#define DSB __asm__ volatile("dsb" ::: "memory")
+#define DMB __asm__ volatile("dmb" ::: "memory")
+#define ISB __asm__ volatile("isb" ::: "memory")
+#define WFI __asm__ volatile("wfi" ::: "memory")
+#define BARRIER __asm__ volatile("":::"memory")
+#define WFE __asm__ volatile("wfe" ::: "memory")
+#define SEV __asm__ volatile("sev" ::: "memory")
+
+#define ARM_SYSREG_READ(REG) \
+({ \
+ UINT32 _val; \
+ __asm__ volatile("mrc " REG : "=r" (_val)); \
+ _val; \
+})
+
+#define ARM_SYSREG_WRITE(REG, val) \
+({ \
+ __asm__ volatile("mcr " REG :: "r" (val)); \
+ ISB; \
+})
+
+#define ARM_SYSREG64_READ(REG) \
+({ \
+ UINT64 _val; \
+ __asm__ volatile("mrrc " REG : "=r" (_val)); \
+ _val; \
+})
+
+#define ARM_SYSREG64_WRITE(REG, val) \
+({ \
+ __asm__ volatile("mcrr " REG :: "r" (val)); \
+ ISB; \
+})
+
+#define CP14_REG(CRn, Op1, CRm, Op2) "p14, "#Op1", %0, "#CRn","#CRm","#Op2
+#define CP15_REG(CRn, Op1, CRm, Op2) "p15, "#Op1", %0, "#CRn","#CRm","#Op2
+#define CP15_REG64(CRn, Op1) "p15, "#Op1", %0, %H0,"#CRn
+
+/*
+ * Identification registers (c0)
+ */
+#define MIDR CP15_REG(c0, 0, c0, 0) /* Main ID Register */
+#define MPIDR CP15_REG(c0, 0, c0, 5) /* Multiprocessor Affinity Register */
+#define CCSIDR CP15_REG(c0, 1, c0, 0) /* Cache Size ID Registers */
+#define CLIDR CP15_REG(c0, 1, c0, 1) /* Cache Level ID Register */
+#define VPIDR CP15_REG(c0, 4, c0, 0) /* Virtualization Processor ID Register */
+#define VMPIDR CP15_REG(c0, 4, c0, 5) /* Virtualization Multiprocessor ID Register */
+
+/*
+ * System control registers (c1)
+ */
+#define SCTLR CP15_REG(c1, 0, c0, 0) /* System Control Register */
+#define ACTLR CP15_REG(c1, 0, c0, 1) /* Auxiliary Control Register */
+#define CPACR CP15_REG(c1, 0, c0, 2) /* Coprocessor Access Control Register */
+
+/*
+ * Memory protection and control registers (c2 & c3)
+ */
+#define TTBR0 CP15_REG(c2, 0, c0, 0) /* Translation Table Base Register 0 */
+#define TTBR1 CP15_REG(c2, 0, c0, 1) /* Translation Table Base Register 1 */
+#define TTBCR CP15_REG(c2, 0, c0, 2) /* Translation Table Base Control Register */
+#define DACR CP15_REG(c3, 0, c0, 0) /* Domain Access Control Register */
+
+/*
+ * Memory system fault registers (c5 & c6)
+ */
+#define DFSR CP15_REG(c5, 0, c0, 0) /* Data Fault Status Register */
+#define IFSR CP15_REG(c5, 0, c0, 1) /* Instruction Fault Status Register */
+#define DFAR CP15_REG(c6, 0, c0, 0) /* Data Fault Address Register */
+#define IFAR CP15_REG(c6, 0, c0, 2) /* Instruction Fault Address Register */
+
+/*
+ * Process, context and thread ID registers (c13)
+ */
+#define FCSEIDR CP15_REG(c13, 0, c0, 0) /* FCSE Process ID Register */
+#define CONTEXTIDR CP15_REG(c13, 0, c0, 1) /* Context ID Register */
+#define TPIDRURW CP15_REG(c13, 0, c0, 2) /* User Read/Write Thread ID Register */
+#define TPIDRURO CP15_REG(c13, 0, c0, 3) /* User Read-Only Thread ID Register */
+#define TPIDRPRW CP15_REG(c13, 0, c0, 4) /* PL1 only Thread ID Register */
+
+#define MPIDR_CPUID_MASK (0xffU)
+
+STATIC INLINE VOID *ArchCurrTaskGet(VOID)
+{
+ return (VOID *)(UINTPTR)ARM_SYSREG_READ(TPIDRPRW);
+}
+
+STATIC INLINE VOID ArchCurrTaskSet(VOID *val)
+{
+ ARM_SYSREG_WRITE(TPIDRPRW, (UINT32)(UINTPTR)val);
+}
+
+STATIC INLINE VOID ArchCurrUserTaskSet(UINTPTR val)
+{
+ ARM_SYSREG_WRITE(TPIDRURO, (UINT32)val);
+}
+
+STATIC INLINE UINT32 ArchCurrCpuid(VOID)
+{
+#ifdef LOSCFG_KERNEL_SMP
+ return ARM_SYSREG_READ(MPIDR) & MPIDR_CPUID_MASK;
+#else
+ return 0;
+#endif
+}
+
+STATIC INLINE UINT64 OsHwIDGet(VOID)
+{
+ return ARM_SYSREG_READ(MPIDR);
+}
+
+STATIC INLINE UINT32 OsMainIDGet(VOID)
+{
+ return ARM_SYSREG_READ(MIDR);
+}
+
+/* CPU interrupt mask handle implementation */
+#if LOSCFG_ARM_ARCH >= 6
+
+STATIC INLINE UINT32 ArchIntLock(VOID)
+{
+ UINT32 intSave;
+ __asm__ __volatile__(
+ "mrs %0, cpsr \n"
+ "cpsid if "
+ : "=r"(intSave)
+ :
+ : "memory");
+ return intSave;
+}
+
+STATIC INLINE UINT32 ArchIntUnlock(VOID)
+{
+ UINT32 intSave;
+ __asm__ __volatile__(
+ "mrs %0, cpsr \n"
+ "cpsie if "
+ : "=r"(intSave)
+ :
+ : "memory");
+ return intSave;
+}
+
+STATIC INLINE VOID ArchIrqDisable(VOID)
+{
+ __asm__ __volatile__(
+ "cpsid i "
+ :
+ :
+ : "memory", "cc");
+}
+
+STATIC INLINE VOID ArchIrqEnable(VOID)
+{
+ __asm__ __volatile__(
+ "cpsie i "
+ :
+ :
+ : "memory", "cc");
+}
+
+#else
+
+STATIC INLINE UINT32 ArchIntLock(VOID)
+{
+ UINT32 intSave, temp;
+ __asm__ __volatile__(
+ "mrs %0, cpsr \n"
+ "orr %1, %0, #0xc0 \n"
+ "msr cpsr_c, %1 "
+ :"=r"(intSave), "=r"(temp)
+ : :"memory");
+ return intSave;
+}
+
+STATIC INLINE UINT32 ArchIntUnlock(VOID)
+{
+ UINT32 intSave;
+ __asm__ __volatile__(
+ "mrs %0, cpsr \n"
+ "bic %0, %0, #0xc0 \n"
+ "msr cpsr_c, %0 "
+ : "=r"(intSave)
+ : : "memory");
+ return intSave;
+}
+
+#endif
+
+STATIC INLINE VOID ArchIntRestore(UINT32 intSave)
+{
+ __asm__ __volatile__(
+ "msr cpsr_c, %0 "
+ :
+ : "r"(intSave)
+ : "memory");
+}
+
+#define PSR_I_BIT 0x00000080U
+
+STATIC INLINE UINT32 OsIntLocked(VOID)
+{
+ UINT32 intSave;
+
+ asm volatile(
+ "mrs %0, cpsr "
+ : "=r" (intSave)
+ :
+ : "memory", "cc");
+
+ return intSave & PSR_I_BIT;
+}
+
+STATIC INLINE UINT32 ArchSPGet(VOID)
+{
+ UINT32 val;
+ __asm__ __volatile__("mov %0, sp" : "=r"(val));
+ return val;
+}
+
+#ifdef __cplusplus
+#if __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+#endif /* _LOS_HW_CPU_H */
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/include/los_mmu_descriptor_v6.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/include/los_mmu_descriptor_v6.h
new file mode 100644
index 00000000..6f93de03
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/include/los_mmu_descriptor_v6.h
@@ -0,0 +1,234 @@
+/*
+ * 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.
+ */
+
+/**
+ * @defgroup los_mmu_descriptor_v6 MMU Descriptor v6
+ * @ingroup kernel
+ */
+
+#ifndef __LOS_MMU_DESCRIPTOR_V6_H__
+#define __LOS_MMU_DESCRIPTOR_V6_H__
+
+#include "los_vm_common.h"
+
+#ifdef __cplusplus
+#if __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+#define __iomem
+#ifndef IS_ALIGNED
+#define IS_ALIGNED(a, b) (!(((UINTPTR)(a)) & (((UINTPTR)(b))-1)))
+#endif
+
+#define MMU_DESCRIPTOR_TEX_0 0
+#define MMU_DESCRIPTOR_TEX_1 1
+#define MMU_DESCRIPTOR_TEX_2 2
+#define MMU_DESCRIPTOR_TEX_MASK 7
+
+#define MMU_DESCRIPTOR_CACHE_BUFFER_SHIFT 2
+#define MMU_DESCRIPTOR_CACHE_BUFFER(x) ((x) << MMU_DESCRIPTOR_CACHE_BUFFER_SHIFT)
+#define MMU_DESCRIPTOR_NON_CACHEABLE MMU_DESCRIPTOR_CACHE_BUFFER(0)
+#define MMU_DESCRIPTOR_WRITE_BACK_ALLOCATE MMU_DESCRIPTOR_CACHE_BUFFER(1)
+#define MMU_DESCRIPTOR_WRITE_THROUGH_NO_ALLOCATE MMU_DESCRIPTOR_CACHE_BUFFER(2)
+#define MMU_DESCRIPTOR_WRITE_BACK_NO_ALLOCATE MMU_DESCRIPTOR_CACHE_BUFFER(3)
+
+/* user space mmu access permission define begin */
+#define MMU_DESCRIPTOR_DOMAIN_MANAGER 0
+#define MMU_DESCRIPTOR_DOMAIN_CLIENT 1
+#define MMU_DESCRIPTOR_DOMAIN_NA 2
+
+/* L1 descriptor type */
+#define MMU_DESCRIPTOR_L1_TYPE_INVALID (0x0 << 0)
+#define MMU_DESCRIPTOR_L1_TYPE_PAGE_TABLE (0x1 << 0)
+#define MMU_DESCRIPTOR_L1_TYPE_SECTION (0x2 << 0)
+#define MMU_DESCRIPTOR_L1_TYPE_MASK (0x3 << 0)
+
+/* L2 descriptor type */
+#define MMU_DESCRIPTOR_L2_TYPE_INVALID (0x0 << 0)
+#define MMU_DESCRIPTOR_L2_TYPE_LARGE_PAGE (0x1 << 0)
+#define MMU_DESCRIPTOR_L2_TYPE_SMALL_PAGE (0x2 << 0)
+#define MMU_DESCRIPTOR_L2_TYPE_SMALL_PAGE_XN (0x3 << 0)
+#define MMU_DESCRIPTOR_L2_TYPE_MASK (0x3 << 0)
+
+#define MMU_DESCRIPTOR_IS_L1_SIZE_ALIGNED(x) IS_ALIGNED(x, MMU_DESCRIPTOR_L1_SMALL_SIZE)
+#define MMU_DESCRIPTOR_L1_SMALL_SIZE 0x100000
+#define MMU_DESCRIPTOR_L1_SMALL_MASK (MMU_DESCRIPTOR_L1_SMALL_SIZE - 1)
+#define MMU_DESCRIPTOR_L1_SMALL_FRAME (~MMU_DESCRIPTOR_L1_SMALL_MASK)
+#define MMU_DESCRIPTOR_L1_SMALL_SHIFT 20
+#define MMU_DESCRIPTOR_L1_SECTION_ADDR(x) ((x) & MMU_DESCRIPTOR_L1_SMALL_FRAME)
+#define MMU_DESCRIPTOR_L1_PAGE_TABLE_ADDR(x) ((x) & ~((1 << 10)-1))
+#define MMU_DESCRIPTOR_L1_SMALL_L2_TABLES_PER_PAGE 4
+#define MMU_DESCRIPTOR_L1_SMALL_ENTRY_NUMBERS 0x4000U
+#define MMU_DESCRIPTOR_L1_SMALL_DOMAIN_MASK (~(0x0f << 5)) /* 4k page section domain mask */
+#define MMU_DESCRIPTOR_L1_SMALL_DOMAIN_CLIENT (MMU_DESCRIPTOR_DOMAIN_CLIENT << 5)
+
+#define MMU_DESCRIPTOR_L1_PAGETABLE_NON_SECURE (1 << 3)
+#define MMU_DESCRIPTOR_L1_SECTION_NON_SECURE (1 << 19)
+#define MMU_DESCRIPTOR_L1_SECTION_SHAREABLE (1 << 16)
+#define MMU_DESCRIPTOR_L1_SECTION_NON_GLOBAL (1 << 17)
+#define MMU_DESCRIPTOR_L1_SECTION_XN (1 << 4)
+
+/* TEX CB */
+#define MMU_DESCRIPTOR_L1_TEX_SHIFT 12 /* type extension field shift */
+#define MMU_DESCRIPTOR_L1_TEX(x) \
+ ((x) << MMU_DESCRIPTOR_L1_TEX_SHIFT) /* type extension */
+#define MMU_DESCRIPTOR_L1_TYPE_STRONGLY_ORDERED \
+ (MMU_DESCRIPTOR_L1_TEX(MMU_DESCRIPTOR_TEX_0) | MMU_DESCRIPTOR_NON_CACHEABLE)
+#define MMU_DESCRIPTOR_L1_TYPE_NORMAL_NOCACHE \
+ (MMU_DESCRIPTOR_L1_TEX(MMU_DESCRIPTOR_TEX_1) | MMU_DESCRIPTOR_NON_CACHEABLE)
+#define MMU_DESCRIPTOR_L1_TYPE_DEVICE_SHARED \
+ (MMU_DESCRIPTOR_L1_TEX(MMU_DESCRIPTOR_TEX_0) | MMU_DESCRIPTOR_WRITE_BACK_ALLOCATE)
+#define MMU_DESCRIPTOR_L1_TYPE_DEVICE_NON_SHARED \
+ (MMU_DESCRIPTOR_L1_TEX(MMU_DESCRIPTOR_TEX_2) | MMU_DESCRIPTOR_NON_CACHEABLE)
+#define MMU_DESCRIPTOR_L1_TYPE_NORMAL_WRITE_BACK_ALLOCATE \
+ (MMU_DESCRIPTOR_L1_TEX(MMU_DESCRIPTOR_TEX_1) | MMU_DESCRIPTOR_WRITE_BACK_NO_ALLOCATE)
+#define MMU_DESCRIPTOR_L1_TEX_TYPE_MASK \
+ (MMU_DESCRIPTOR_L1_TEX(MMU_DESCRIPTOR_TEX_MASK) | MMU_DESCRIPTOR_WRITE_BACK_NO_ALLOCATE)
+
+#define MMU_DESCRIPTOR_L1_AP2_SHIFT 15
+#define MMU_DESCRIPTOR_L1_AP2(x) ((x) << MMU_DESCRIPTOR_L1_AP2_SHIFT)
+#define MMU_DESCRIPTOR_L1_AP2_0 (MMU_DESCRIPTOR_L1_AP2(0))
+#define MMU_DESCRIPTOR_L1_AP2_1 (MMU_DESCRIPTOR_L1_AP2(1))
+#define MMU_DESCRIPTOR_L1_AP01_SHIFT 10
+#define MMU_DESCRIPTOR_L1_AP01(x) ((x) << MMU_DESCRIPTOR_L1_AP01_SHIFT)
+#define MMU_DESCRIPTOR_L1_AP01_0 (MMU_DESCRIPTOR_L1_AP01(0))
+#define MMU_DESCRIPTOR_L1_AP01_1 (MMU_DESCRIPTOR_L1_AP01(1))
+#define MMU_DESCRIPTOR_L1_AP01_3 (MMU_DESCRIPTOR_L1_AP01(3))
+#define MMU_DESCRIPTOR_L1_AP_P_NA_U_NA (MMU_DESCRIPTOR_L1_AP2_0 | MMU_DESCRIPTOR_L1_AP01_0)
+#define MMU_DESCRIPTOR_L1_AP_P_RW_U_RW (MMU_DESCRIPTOR_L1_AP2_0 | MMU_DESCRIPTOR_L1_AP01_3)
+#define MMU_DESCRIPTOR_L1_AP_P_RW_U_NA (MMU_DESCRIPTOR_L1_AP2_0 | MMU_DESCRIPTOR_L1_AP01_1)
+#define MMU_DESCRIPTOR_L1_AP_P_RO_U_RO (MMU_DESCRIPTOR_L1_AP2_1 | MMU_DESCRIPTOR_L1_AP01_3)
+#define MMU_DESCRIPTOR_L1_AP_P_RO_U_NA (MMU_DESCRIPTOR_L1_AP2_1 | MMU_DESCRIPTOR_L1_AP01_1)
+#define MMU_DESCRIPTOR_L1_AP_MASK (MMU_DESCRIPTOR_L1_AP2_1 | MMU_DESCRIPTOR_L1_AP01_3)
+
+#define MMU_DESCRIPTOR_L2_SMALL_SIZE 0x1000
+#define MMU_DESCRIPTOR_L2_SMALL_MASK (MMU_DESCRIPTOR_L2_SMALL_SIZE - 1)
+#define MMU_DESCRIPTOR_L2_SMALL_FRAME (~MMU_DESCRIPTOR_L2_SMALL_MASK)
+#define MMU_DESCRIPTOR_L2_SMALL_SHIFT 12
+#define MMU_DESCRIPTOR_L2_NUMBERS_PER_L1 \
+ (MMU_DESCRIPTOR_L1_SMALL_SIZE >> MMU_DESCRIPTOR_L2_SMALL_SHIFT)
+#define MMU_DESCRIPTOR_IS_L2_SIZE_ALIGNED(x) IS_ALIGNED(x, MMU_DESCRIPTOR_L2_SMALL_SIZE)
+#define MMU_DESCRIPTOR_L2_TEX_SHIFT 6 /* type extension field shift */
+#define MMU_DESCRIPTOR_L2_TEX(x) \
+ ((x) << MMU_DESCRIPTOR_L2_TEX_SHIFT) /* type extension */
+#define MMU_DESCRIPTOR_L2_TYPE_STRONGLY_ORDERED \
+ (MMU_DESCRIPTOR_L2_TEX(MMU_DESCRIPTOR_TEX_0) | MMU_DESCRIPTOR_NON_CACHEABLE)
+#define MMU_DESCRIPTOR_L2_TYPE_NORMAL_NOCACHE \
+ (MMU_DESCRIPTOR_L2_TEX(MMU_DESCRIPTOR_TEX_1) | MMU_DESCRIPTOR_NON_CACHEABLE)
+#define MMU_DESCRIPTOR_L2_TYPE_DEVICE_SHARED \
+ (MMU_DESCRIPTOR_L2_TEX(MMU_DESCRIPTOR_TEX_0) | MMU_DESCRIPTOR_WRITE_BACK_ALLOCATE)
+#define MMU_DESCRIPTOR_L2_TYPE_DEVICE_NON_SHARED \
+ (MMU_DESCRIPTOR_L2_TEX(MMU_DESCRIPTOR_TEX_2) | MMU_DESCRIPTOR_NON_CACHEABLE)
+#define MMU_DESCRIPTOR_L2_TYPE_NORMAL_WRITE_BACK_ALLOCATE \
+ (MMU_DESCRIPTOR_L2_TEX(MMU_DESCRIPTOR_TEX_1) | MMU_DESCRIPTOR_WRITE_BACK_NO_ALLOCATE)
+#define MMU_DESCRIPTOR_L2_TEX_TYPE_MASK \
+ (MMU_DESCRIPTOR_L2_TEX(MMU_DESCRIPTOR_TEX_MASK) | MMU_DESCRIPTOR_WRITE_BACK_NO_ALLOCATE)
+#define MMU_DESCRIPTOR_L2_AP2_SHIFT 9
+#define MMU_DESCRIPTOR_L2_AP2(x) ((x) << MMU_DESCRIPTOR_L2_AP2_SHIFT)
+#define MMU_DESCRIPTOR_L2_AP2_0 (MMU_DESCRIPTOR_L2_AP2(0))
+#define MMU_DESCRIPTOR_L2_AP2_1 (MMU_DESCRIPTOR_L2_AP2(1))
+#define MMU_DESCRIPTOR_L2_AP01_SHIFT 4
+#define MMU_DESCRIPTOR_L2_AP01(x) ((x) << MMU_DESCRIPTOR_L2_AP01_SHIFT)
+#define MMU_DESCRIPTOR_L2_AP01_0 (MMU_DESCRIPTOR_L2_AP01(0))
+#define MMU_DESCRIPTOR_L2_AP01_1 (MMU_DESCRIPTOR_L2_AP01(1))
+#define MMU_DESCRIPTOR_L2_AP01_3 (MMU_DESCRIPTOR_L2_AP01(3))
+#define MMU_DESCRIPTOR_L2_AP_P_NA_U_NA (MMU_DESCRIPTOR_L2_AP2_0 | MMU_DESCRIPTOR_L2_AP01_0)
+#define MMU_DESCRIPTOR_L2_AP_P_RW_U_RW (MMU_DESCRIPTOR_L2_AP2_0 | MMU_DESCRIPTOR_L2_AP01_3)
+#define MMU_DESCRIPTOR_L2_AP_P_RW_U_NA (MMU_DESCRIPTOR_L2_AP2_0 | MMU_DESCRIPTOR_L2_AP01_1)
+#define MMU_DESCRIPTOR_L2_AP_P_RO_U_RO (MMU_DESCRIPTOR_L2_AP2_1 | MMU_DESCRIPTOR_L2_AP01_3)
+#define MMU_DESCRIPTOR_L2_AP_P_RO_U_NA (MMU_DESCRIPTOR_L2_AP2_1 | MMU_DESCRIPTOR_L2_AP01_1)
+#define MMU_DESCRIPTOR_L2_AP_MASK (MMU_DESCRIPTOR_L2_AP2_1 | MMU_DESCRIPTOR_L2_AP01_3)
+
+#define MMU_DESCRIPTOR_L2_SHAREABLE (1 << 10)
+#define MMU_DESCRIPTOR_L2_NON_GLOBAL (1 << 11)
+#define MMU_DESCRIPTOR_L2_SMALL_PAGE_ADDR(x) ((x) & MMU_DESCRIPTOR_L2_SMALL_FRAME)
+
+#define MMU_DESCRIPTOR_TTBCR_PD0 (1 << 4)
+#define MMU_DESCRIPTOR_TTBR_WRITE_BACK_ALLOCATE 1
+#define MMU_DESCRIPTOR_TTBR_RGN(x) (((x) & 0x3) << 3)
+#define MMU_DESCRIPTOR_TTBR_IRGN(x) ((((x) & 0x1) << 6) | ((((x) >> 1) & 0x1) << 0))
+#define MMU_DESCRIPTOR_TTBR_S (1 << 1)
+#define MMU_DESCRIPTOR_TTBR_NOS (1 << 5)
+
+#ifdef LOSCFG_KERNEL_SMP
+#define MMU_TTBRx_SHARABLE_FLAGS (MMU_DESCRIPTOR_TTBR_S | MMU_DESCRIPTOR_TTBR_NOS)
+#else
+#define MMU_TTBRx_SHARABLE_FLAGS 0
+#endif
+
+#define MMU_TTBRx_FLAGS \
+ (MMU_DESCRIPTOR_TTBR_RGN(MMU_DESCRIPTOR_TTBR_WRITE_BACK_ALLOCATE) | \
+ MMU_DESCRIPTOR_TTBR_IRGN(MMU_DESCRIPTOR_TTBR_WRITE_BACK_ALLOCATE) | \
+ MMU_TTBRx_SHARABLE_FLAGS)
+
+#ifdef LOSCFG_KERNEL_SMP
+#define MMU_DESCRIPTOR_KERNEL_L1_PTE_FLAGS \
+ (MMU_DESCRIPTOR_L1_TYPE_SECTION | \
+ MMU_DESCRIPTOR_L1_TYPE_NORMAL_WRITE_BACK_ALLOCATE | \
+ MMU_DESCRIPTOR_L1_AP_P_RW_U_NA | \
+ MMU_DESCRIPTOR_L1_SMALL_DOMAIN_CLIENT | \
+ MMU_DESCRIPTOR_L1_SECTION_SHAREABLE)
+#else
+#define MMU_DESCRIPTOR_KERNEL_L1_PTE_FLAGS \
+ (MMU_DESCRIPTOR_L1_TYPE_SECTION | \
+ MMU_DESCRIPTOR_L1_TYPE_NORMAL_WRITE_BACK_ALLOCATE | \
+ MMU_DESCRIPTOR_L1_SMALL_DOMAIN_CLIENT | \
+ MMU_DESCRIPTOR_L1_AP_P_RW_U_NA)
+#endif
+
+#define MMU_INITIAL_MAP_STRONGLY_ORDERED \
+ (MMU_DESCRIPTOR_L1_TYPE_SECTION | \
+ MMU_DESCRIPTOR_L1_TYPE_STRONGLY_ORDERED | \
+ MMU_DESCRIPTOR_L1_SMALL_DOMAIN_CLIENT | \
+ MMU_DESCRIPTOR_L1_AP_P_RW_U_NA)
+
+#define MMU_INITIAL_MAP_NORMAL_NOCACHE \
+ (MMU_DESCRIPTOR_L1_TYPE_SECTION | \
+ MMU_DESCRIPTOR_L1_TYPE_NORMAL_NOCACHE | \
+ MMU_DESCRIPTOR_L1_SMALL_DOMAIN_CLIENT | \
+ MMU_DESCRIPTOR_L1_AP_P_RW_U_NA)
+
+#define MMU_INITIAL_MAP_DEVICE \
+ (MMU_DESCRIPTOR_L1_TYPE_SECTION | \
+ MMU_DESCRIPTOR_L1_TYPE_DEVICE_SHARED | \
+ MMU_DESCRIPTOR_L1_SMALL_DOMAIN_CLIENT | \
+ MMU_DESCRIPTOR_L1_AP_P_RW_U_NA)
+
+#ifdef __cplusplus
+#if __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+#endif /* __LOS_MMU_DESCRIPTOR_V6_H__ */
+
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/include/los_pte_ops.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/include/los_pte_ops.h
new file mode 100644
index 00000000..e47b4d65
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/include/los_pte_ops.h
@@ -0,0 +1,181 @@
+/*
+ * 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.
+ */
+
+/**
+ * @defgroup los_pte_ops page table entry operations
+ * @ingroup kernel
+ */
+
+#ifndef __LOS_PTE_OPS_H__
+#define __LOS_PTE_OPS_H__
+
+#include "los_typedef.h"
+#include "arm.h"
+#include "los_mmu_descriptor_v6.h"
+
+#ifdef __cplusplus
+#if __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+STATIC INLINE VOID OsSavePte1(PTE_T *pte1Ptr, PTE_T pte1)
+{
+ DMB;
+ *pte1Ptr = pte1;
+ DSB;
+}
+
+STATIC INLINE ADDR_T OsTruncPte1(ADDR_T addr)
+{
+ return MMU_DESCRIPTOR_L1_SECTION_ADDR(addr);
+}
+
+STATIC INLINE UINT32 OsGetPte1Index(vaddr_t va)
+{
+ return va >> MMU_DESCRIPTOR_L1_SMALL_SHIFT;
+}
+
+STATIC INLINE VOID OsClearPte1(PTE_T *pte1Ptr)
+{
+ OsSavePte1(pte1Ptr, 0);
+}
+
+STATIC INLINE PADDR_T OsGetPte1Paddr(PADDR_T PhysTtb, vaddr_t va)
+{
+ return (PhysTtb + (OsGetPte1Index(va) * sizeof(PADDR_T)));
+}
+
+STATIC INLINE PTE_T *OsGetPte1Ptr(PTE_T *pte1BasePtr, vaddr_t va)
+{
+ return (pte1BasePtr + OsGetPte1Index(va));
+}
+
+STATIC INLINE PTE_T OsGetPte1(PTE_T *pte1BasePtr, vaddr_t va)
+{
+ return *OsGetPte1Ptr(pte1BasePtr, va);
+}
+
+STATIC INLINE BOOL OsIsPte1PageTable(PTE_T pte1)
+{
+ return (pte1 & MMU_DESCRIPTOR_L1_TYPE_MASK) == MMU_DESCRIPTOR_L1_TYPE_PAGE_TABLE;
+}
+
+STATIC INLINE BOOL OsIsPte1Invalid(PTE_T pte1)
+{
+ return (pte1 & MMU_DESCRIPTOR_L1_TYPE_MASK) == MMU_DESCRIPTOR_L1_TYPE_INVALID;
+}
+
+STATIC INLINE BOOL OsIsPte1Section(PTE_T pte1)
+{
+ return (pte1 & MMU_DESCRIPTOR_L1_TYPE_MASK) == MMU_DESCRIPTOR_L1_TYPE_SECTION;
+}
+
+STATIC INLINE UINT32 OsGetPte2Index(vaddr_t va)
+{
+ return (va % MMU_DESCRIPTOR_L1_SMALL_SIZE) >> MMU_DESCRIPTOR_L2_SMALL_SHIFT;
+}
+
+STATIC INLINE PTE_T *OsGetPte2Ptr(PTE_T *pte2BasePtr, vaddr_t va)
+{
+ return (pte2BasePtr + OsGetPte2Index(va));
+}
+
+STATIC INLINE PTE_T OsGetPte2(PTE_T *pte2BasePtr, vaddr_t va)
+{
+ return *(pte2BasePtr + OsGetPte2Index(va));
+}
+
+STATIC INLINE VOID OsSavePte2(PTE_T *pte2Ptr, PTE_T pte2)
+{
+ DMB;
+ *pte2Ptr = pte2;
+ DSB;
+}
+
+STATIC INLINE UINT32 OsSavePte2Continuous(PTE_T *pte2BasePtr, UINT32 index, PTE_T pte2, UINT32 count)
+{
+ UINT32 saveCounts = 0;
+ if (count == 0) {
+ return 0;
+ }
+
+ DMB;
+ do {
+ pte2BasePtr[index++] = pte2;
+ count--;
+ pte2 += MMU_DESCRIPTOR_L2_SMALL_SIZE;
+ saveCounts++;
+ } while ((count != 0) && (index != MMU_DESCRIPTOR_L2_NUMBERS_PER_L1));
+ DSB;
+
+ return saveCounts;
+}
+
+STATIC INLINE VOID OsClearPte2Continuous(PTE_T *pte2Ptr, UINT32 count)
+{
+ UINT32 index = 0;
+
+ DMB;
+ while (count > 0) {
+ pte2Ptr[index++] = 0;
+ count--;
+ }
+ DSB;
+}
+
+STATIC INLINE BOOL OsIsPte2SmallPage(PTE_T pte2)
+{
+ return (pte2 & MMU_DESCRIPTOR_L2_TYPE_MASK) == MMU_DESCRIPTOR_L2_TYPE_SMALL_PAGE;
+}
+
+STATIC INLINE BOOL OsIsPte2SmallPageXN(PTE_T pte2)
+{
+ return (pte2 & MMU_DESCRIPTOR_L2_TYPE_MASK) == MMU_DESCRIPTOR_L2_TYPE_SMALL_PAGE_XN;
+}
+
+STATIC INLINE BOOL OsIsPte2LargePage(PTE_T pte2)
+{
+ return (pte2 & MMU_DESCRIPTOR_L2_TYPE_MASK) == MMU_DESCRIPTOR_L2_TYPE_LARGE_PAGE;
+}
+
+STATIC INLINE BOOL OsIsPte2Invalid(PTE_T pte2)
+{
+ return (pte2 & MMU_DESCRIPTOR_L2_TYPE_MASK) == MMU_DESCRIPTOR_L2_TYPE_INVALID;
+}
+
+#ifdef __cplusplus
+#if __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+#endif /* __LOS_PTE_OPS_H__ */
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/include/los_tlb_v6.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/include/los_tlb_v6.h
new file mode 100644
index 00000000..cdfa7971
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/include/los_tlb_v6.h
@@ -0,0 +1,92 @@
+/*
+ * 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.
+ */
+
+/**
+ * @defgroup los_tlb_v6 MMU TLB v6
+ * @ingroup kernel
+ */
+#ifndef __LOS_TLB_V6_H__
+#define __LOS_TLB_V6_H__
+
+#include "los_typedef.h"
+#include "arm.h"
+
+#ifdef __cplusplus
+#if __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+STATIC INLINE VOID OsArmInvalidateTlbBarrier(VOID)
+{
+#ifdef LOSCFG_KERNEL_SMP
+ OsArmWriteBpiallis(0);
+#else
+ OsArmWriteBpiall(0);
+#endif
+ DSB;
+ ISB;
+}
+
+STATIC INLINE VOID OsArmInvalidateTlbMvaNoBarrier(VADDR_T va)
+{
+#ifdef LOSCFG_KERNEL_SMP
+ OsArmWriteTlbimvaais(va & 0xfffff000);
+#else
+ OsArmWriteTlbimvaa(va & 0xfffff000);
+#endif
+}
+
+STATIC INLINE VOID OsArmInvalidateTlbMvaRangeNoBarrier(VADDR_T start, UINT32 count)
+{
+ UINT32 index = 0;
+
+ while (count > 0) {
+ OsArmInvalidateTlbMvaNoBarrier(start + (index << MMU_DESCRIPTOR_L2_SMALL_SHIFT));
+ index++;
+ count--;
+ }
+}
+
+STATIC INLINE VOID OsCleanTLB(VOID)
+{
+ UINT32 val = 0;
+ __asm volatile("mcr p15, 0, %0, c8, c7, 0" : : "r"(val));
+}
+
+#ifdef __cplusplus
+#if __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+#endif /* __LOS_TLB_V6_H__ */
+
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/include/smp.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/include/smp.h
new file mode 100644
index 00000000..bc3b335d
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/include/smp.h
@@ -0,0 +1,58 @@
+/*
+ * 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 _ARCH_SMP_H
+#define _ARCH_SMP_H
+
+#include "los_config.h"
+
+#ifdef __cplusplus
+#if __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+struct SmpOps {
+ INT32 (*SmpCpuOn)(UINT32 cpuNum, UINTPTR startEntry); /* The startEntry is physical addr. */
+};
+
+typedef VOID (*ArchCpuStartFunc)(VOID *arg);
+
+VOID HalArchCpuOn(UINT32 cpuNum, ArchCpuStartFunc func, struct SmpOps *ops, VOID *arg);
+
+#ifdef __cplusplus
+#if __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+#endif /* _ARCH_SMP_H */
+
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/arm_generic_timer.c b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/arm_generic_timer.c
new file mode 100644
index 00000000..4e8a655c
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/arm_generic_timer.c
@@ -0,0 +1,183 @@
+/*
+ * 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_hw_pri.h"
+#include "los_tick_pri.h"
+#include "los_sys_pri.h"
+#include "gic_common.h"
+
+#define STRING_COMB(x, y, z) x ## y ## z
+
+#ifdef LOSCFG_ARCH_SECURE_MONITOR_MODE
+#define TIMER_REG(reg) STRING_COMB(TIMER_REG_, CNTPS, reg)
+#else
+#define TIMER_REG(reg) STRING_COMB(TIMER_REG_, CNTP, reg)
+#endif
+#define TIMER_REG_CTL TIMER_REG(_CTL) /* 32 bits */
+#define TIMER_REG_TVAL TIMER_REG(_TVAL) /* 32 bits */
+#define TIMER_REG_CVAL TIMER_REG(_CVAL) /* 64 bits */
+#define TIMER_REG_CT TIMER_REG(CT) /* 64 bits */
+
+#ifdef __LP64__
+
+#define TIMER_REG_CNTFRQ cntfrq_el0
+
+/* CNTP AArch64 registers */
+#define TIMER_REG_CNTP_CTL cntp_ctl_el0
+#define TIMER_REG_CNTP_TVAL cntp_tval_el0
+#define TIMER_REG_CNTP_CVAL cntp_cval_el0
+#define TIMER_REG_CNTPCT cntpct_el0
+
+/* CNTPS AArch64 registers */
+#define TIMER_REG_CNTPS_CTL cntps_ctl_el1
+#define TIMER_REG_CNTPS_TVAL cntps_tval_el1
+#define TIMER_REG_CNTPS_CVAL cntps_cval_el1
+#define TIMER_REG_CNTPSCT cntpct_el0
+
+#define READ_TIMER_REG32(reg) AARCH64_SYSREG_READ(reg)
+#define READ_TIMER_REG64(reg) AARCH64_SYSREG_READ(reg)
+#define WRITE_TIMER_REG32(reg, val) AARCH64_SYSREG_WRITE(reg, (UINT64)(val))
+#define WRITE_TIMER_REG64(reg, val) AARCH64_SYSREG_WRITE(reg, val)
+
+#else /* Aarch32 */
+
+#define TIMER_REG_CNTFRQ CP15_REG(c14, 0, c0, 0)
+
+/* CNTP AArch32 registers */
+#define TIMER_REG_CNTP_CTL CP15_REG(c14, 0, c2, 1)
+#define TIMER_REG_CNTP_TVAL CP15_REG(c14, 0, c2, 0)
+#define TIMER_REG_CNTP_CVAL CP15_REG64(c14, 2)
+#define TIMER_REG_CNTPCT CP15_REG64(c14, 0)
+
+/* CNTPS AArch32 registers are banked and accessed though CNTP */
+#define CNTPS CNTP
+
+#define READ_TIMER_REG32(reg) ARM_SYSREG_READ(reg)
+#define READ_TIMER_REG64(reg) ARM_SYSREG64_READ(reg)
+#define WRITE_TIMER_REG32(reg, val) ARM_SYSREG_WRITE(reg, val)
+#define WRITE_TIMER_REG64(reg, val) ARM_SYSREG64_WRITE(reg, val)
+
+#endif
+
+UINT32 HalClockFreqRead(VOID)
+{
+ return READ_TIMER_REG32(TIMER_REG_CNTFRQ);
+}
+
+VOID HalClockFreqWrite(UINT32 freq)
+{
+ WRITE_TIMER_REG32(TIMER_REG_CNTFRQ, freq);
+}
+
+STATIC_INLINE VOID TimerCtlWrite(UINT32 cntpCtl)
+{
+ WRITE_TIMER_REG32(TIMER_REG_CTL, cntpCtl);
+}
+
+STATIC_INLINE UINT64 TimerCvalRead(VOID)
+{
+ return READ_TIMER_REG64(TIMER_REG_CVAL);
+}
+
+STATIC_INLINE VOID TimerCvalWrite(UINT64 cval)
+{
+ WRITE_TIMER_REG64(TIMER_REG_CVAL, cval);
+}
+
+STATIC_INLINE VOID TimerTvalWrite(UINT32 tval)
+{
+ WRITE_TIMER_REG32(TIMER_REG_TVAL, tval);
+}
+
+UINT64 HalClockGetCycles(VOID)
+{
+ UINT64 cntpct;
+
+ cntpct = READ_TIMER_REG64(TIMER_REG_CT);
+ return cntpct;
+}
+
+LITE_OS_SEC_TEXT_INIT VOID HalClockInit(VOID)
+{
+ UINT32 ret;
+
+ g_sysClock = HalClockFreqRead();
+ ret = LOS_HwiCreate(OS_TICK_INT_NUM, MIN_INTERRUPT_PRIORITY, 0, OsTickHandler, 0);
+ if (ret != LOS_OK) {
+ PRINT_ERR("%s, %d create tick irq failed, ret:0x%x\n", __FUNCTION__, __LINE__, ret);
+ }
+}
+
+LITE_OS_SEC_TEXT_INIT VOID HalClockStart(VOID)
+{
+ HalIrqUnmask(OS_TICK_INT_NUM);
+
+ /* triggle the first tick */
+ TimerCtlWrite(0);
+ TimerTvalWrite(OS_CYCLE_PER_TICK);
+ TimerCtlWrite(1);
+}
+
+VOID HalDelayUs(UINT32 usecs)
+{
+ UINT64 cycles = (UINT64)usecs * g_sysClock / OS_SYS_US_PER_SECOND;
+ UINT64 deadline = HalClockGetCycles() + cycles;
+
+ while (HalClockGetCycles() < deadline) {
+ __asm__ volatile ("nop");
+ }
+}
+
+DEPRECATED UINT64 hi_sched_clock(VOID)
+{
+ return LOS_CurrNanosec();
+}
+
+UINT32 HalClockGetTickTimerCycles(VOID)
+{
+ UINT64 cval = TimerCvalRead();
+ UINT64 cycles = HalClockGetCycles();
+
+ return (UINT32)((cval > cycles) ? (cval - cycles) : 0);
+}
+
+UINT64 HalClockTickTimerReload(UINT64 cycles)
+{
+ HalIrqMask(OS_TICK_INT_NUM);
+ HalIrqClear(OS_TICK_INT_NUM);
+
+ TimerCtlWrite(0);
+ TimerCvalWrite(HalClockGetCycles() + cycles);
+ TimerCtlWrite(1);
+
+ HalIrqUnmask(OS_TICK_INT_NUM);
+ return cycles;
+}
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/armv7a/cache.S b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/armv7a/cache.S
new file mode 100644
index 00000000..0970d453
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/armv7a/cache.S
@@ -0,0 +1,80 @@
+/*
+ * 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 "asm.h"
+
+ .fpu vfpv4
+ .arch armv7a
+.macro DCACHE_LINE_SIZE, reg, tmp
+ mrc p15, 0, \tmp, c0, c0, 1
+ lsr \tmp, \tmp, #16
+ and \tmp, \tmp, #0xf
+ mov \reg, #4
+ mov \reg, \reg, lsl \tmp
+.endm
+
+
+FUNCTION(arm_inv_cache_range)
+ push {r2, r3}
+ DCACHE_LINE_SIZE r2, r3
+ sub r3, r2, #1
+ tst r0, r3
+ bic r0, r0, r3
+
+ mcrne p15, 0, r0, c7, c14, 1
+
+ tst r1, r3
+ bic r1, r1, r3
+ mcrne p15, 0, r1, c7, c14, 1
+1:
+ mcr p15, 0, r0, c7, c6, 1
+ add r0, r0, r2
+ cmp r0, r1
+ blo 1b
+ dsb
+ pop {r2, r3}
+ mov pc, lr
+
+FUNCTION(arm_clean_cache_range)
+ push {r2, r3}
+ DCACHE_LINE_SIZE r2, r3
+ sub r3, r2, #1
+ bic r0, r0, r3
+
+1:
+ mcr p15, 0, r0, c7, c10, 1
+ add r0, r0, r2
+ cmp r0, r1
+ blo 1b
+ dsb
+ pop {r2, r3}
+ mov pc, lr
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/clear_user.S b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/clear_user.S
new file mode 100644
index 00000000..907a5041
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/clear_user.S
@@ -0,0 +1,100 @@
+/*
+ * Copyright (c) 2021-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 "asm.h"
+
+.syntax unified
+.arm
+
+// size_t _arm_clear_user(void *addr, size_t bytes)
+FUNCTION(_arm_clear_user)
+ push {r0-r6, lr}
+ cmp r1, #0
+ beq .Lclear_user_return
+ tst r0, #7
+ beq .Lclear_user_aligned
+
+.Lclear_user_byte:
+ mov r2, #0
+0: strb r2, [r0], #1
+ subs r1, r1, #1
+ beq .Lclear_user_return
+ tst r0, #7
+ bne 0b
+
+.Lclear_user_aligned:
+ eor r3, r3
+ eor r4, r4
+ bics r2, r1, #15
+ bne .Lclear_user_16bytes
+ bics r2, r1, #7
+ bne .Lclear_user_8bytes
+ b .Lclear_user_remaining
+
+.Lclear_user_16bytes:
+ eor r5, r5
+ eor r6, r6
+1: stmia r0!, {r3, r4, r5, r6}
+ subs r2, r2, #16
+ bne 1b
+ ands r1, r1, #15
+ beq .Lclear_user_return
+ bics r2, r1, #7
+ beq .Lclear_user_remaining
+
+.Lclear_user_8bytes:
+2: stmia r0!, {r3, r4}
+ ands r1, r1, #7
+ beq .Lclear_user_return
+
+.Lclear_user_remaining:
+ mov r2, #0
+3: strb r2, [r0], #1
+ subs r1, r1, #1
+ bne 3b
+
+.Lclear_user_return:
+ pop {r0-r6, lr}
+ mov r0, #0
+ bx lr
+
+.Lclear_user_err:
+ pop {r0, r1}
+ sub r0, r2, r0
+ sub r0, r1, r0
+ pop {r2-r6, lr}
+ bx lr
+
+.pushsection __exc_table, "a"
+ .long 0b, .Lclear_user_err
+ .long 1b, .Lclear_user_err
+ .long 2b, .Lclear_user_err
+ .long 3b, .Lclear_user_err
+.popsection
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/hw_user_get.S b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/hw_user_get.S
new file mode 100644
index 00000000..169cbf9e
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/hw_user_get.S
@@ -0,0 +1,77 @@
+/*
+ * 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 "asm.h"
+
+.syntax unified
+.arm
+
+// errno_t _arm_get_user(void *dst, const void *src, size_t dstTypeLen, size_t srcTypeLen)
+FUNCTION(_arm_get_user)
+ stmdb sp!, {r0, r1, r2, r3, lr}
+ cmp r2, #0
+ beq .Lget_user_return
+ cmp r2, r3
+ bne .Lget_user_err
+ cmp r2, #1
+ bhi .Lget_user_half
+.Lget_user_byte:
+0: ldrbt r3, [r1], #0
+1: strb r3, [r0], #0
+ b .Lget_user_return
+.Lget_user_half:
+ cmp r2, #2
+ bhi .Lget_user_word
+2: ldrht r3, [r1], #0
+3: strh r3, [r0], #0
+ b .Lget_user_return
+.Lget_user_word:
+ cmp r2, #4
+ bhi .Lget_user_err
+4: ldrt r3, [r1], #0
+5: str r3, [r0], #0
+.Lget_user_return:
+ ldmia sp!, {r0, r1, r2, r3, lr}
+ mov r0, 0
+ bx lr
+.Lget_user_err:
+ ldmia sp!, {r0, r1, r2, r3, lr}
+ mov r0, #-14
+ bx lr
+
+.pushsection __exc_table, "a"
+ .long 0b, .Lget_user_err
+ .long 1b, .Lget_user_err
+ .long 2b, .Lget_user_err
+ .long 3b, .Lget_user_err
+ .long 4b, .Lget_user_err
+ .long 5b, .Lget_user_err
+.popsection
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/hw_user_put.S b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/hw_user_put.S
new file mode 100644
index 00000000..e463addd
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/hw_user_put.S
@@ -0,0 +1,77 @@
+/*
+ * 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 "asm.h"
+
+.syntax unified
+.arm
+
+// errno_t _arm_put_user(void *dst, const void *src, size_t dstTypeLen, size_t srcTypeLen)
+FUNCTION(_arm_put_user)
+ stmdb sp!, {r0, r1, r2, r3, lr}
+ cmp r2, #0
+ beq .Lget_user_return
+ cmp r2, r3
+ bne .Lget_user_err
+ cmp r2, #1
+ bhi .Lget_user_half
+.Lget_user_byte:
+0: ldrb r3, [r1], #0
+1: strbt r3, [r0], #0
+ b .Lget_user_return
+.Lget_user_half:
+ cmp r2, #2
+ bhi .Lget_user_word
+2: ldrh r3, [r1], #0
+3: strht r3, [r0], #0
+ b .Lget_user_return
+.Lget_user_word:
+ cmp r2, #4
+ bhi .Lget_user_err
+4: ldr r3, [r1], #0
+5: strt r3, [r0], #0
+.Lget_user_return:
+ ldmia sp!, {r0, r1, r2, r3, lr}
+ mov r0, 0
+ bx lr
+.Lget_user_err:
+ ldmia sp!, {r0, r1, r2, r3, lr}
+ mov r0, #-14
+ bx lr
+
+.pushsection __exc_table, "a"
+ .long 0b, .Lget_user_err
+ .long 1b, .Lget_user_err
+ .long 2b, .Lget_user_err
+ .long 3b, .Lget_user_err
+ .long 4b, .Lget_user_err
+ .long 5b, .Lget_user_err
+.popsection
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/include/armv7_pmu_pri.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/include/armv7_pmu_pri.h
new file mode 100644
index 00000000..cb712f45
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/include/armv7_pmu_pri.h
@@ -0,0 +1,108 @@
+/*
+ * 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 _ARMV7_PMU_PRI_H
+#define _ARMV7_PMU_PRI_H
+
+#include "los_typedef.h"
+
+#ifdef __cplusplus
+#if __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+/* counters overflow flag status reg */
+#define ARMV7_FLAG_MASK 0xffffffff /* Mask for writable bits */
+#define ARMV7_OVERFLOWED_MASK ARMV7_FLAG_MASK /* Mask for pmu overflowed */
+
+/* pmnc config reg */
+#define ARMV7_PMNC_E (1U << 0) /* Enable all counters */
+#define ARMV7_PMNC_P (1U << 1) /* Reset all counters */
+#define ARMV7_PMNC_C (1U << 2) /* Cycle counter reset */
+#define ARMV7_PMNC_D (1U << 3) /* CCNT counts every 64th cpu cycle */
+#define ARMV7_PMNC_X (1U << 4) /* Export to ETM */
+#define ARMV7_PMNC_DP (1U << 5) /* Disable CCNT if non-invasive debug */
+#define ARMV7_PMNC_MASK 0x3f /* Mask for writable bits */
+
+/* pmxevtyper event selection reg */
+#define ARMV7_EVTYPE_MASK 0xc80000ff /* Mask for writable bits */
+
+/* armv7 counters index */
+#define ARMV7_IDX_COUNTER0 1
+#define ARMV7_IDX_CYCLE_COUNTER 0
+#define ARMV7_IDX_MAX_COUNTER 9
+
+#define ARMV7_MAX_COUNTERS 32
+#define ARMV7_IDX_COUNTER_LAST (ARMV7_IDX_CYCLE_COUNTER + ARMV7_MAX_COUNTERS - 1)
+#define ARMV7_COUNTER_MASK (ARMV7_MAX_COUNTERS - 1)
+
+/* armv7 event counter index mapping */
+#define ARMV7_CNT2BIT(x) (1UL << (x))
+#define ARMV7_IDX2CNT(x) (((x) - ARMV7_IDX_COUNTER0) & ARMV7_COUNTER_MASK)
+
+enum PmuEventType {
+ ARMV7_PERF_HW_CYCLES = 0xFF, /* cycles */
+ ARMV7_PERF_HW_INSTRUCTIONS = 0x08, /* instructions */
+ ARMV7_PERF_HW_DCACHES = 0x04, /* dcache */
+ ARMV7_PERF_HW_DCACHE_MISSES = 0x03, /* dcache-misses */
+ ARMV7_PERF_HW_ICACHES = 0x14, /* icache */
+ ARMV7_PERF_HW_ICACHE_MISSES = 0x01, /* icache-misses */
+ ARMV7_PERF_HW_BRANCHES = 0x0C, /* software change of pc */
+ ARMV7_PERF_HW_BRANCE_MISSES = 0x10, /* branch-misses */
+ ARMV7_PERF_HW_PRED_BRANCH = 0x12, /* predictable branches */
+ ARMV7_PERF_HW_NUM_CYC_IRQ = 0x50, /* number of cycles Irqs are interrupted */
+ ARMV7_PERF_HW_EXC_TAKEN = 0x09, /* exception_taken */
+ ARMV7_PERF_HW_DATA_READ = 0x06, /* data read */
+ ARMV7_PERF_HW_DATA_WRITE = 0x07, /* data write */
+ ARMV7_PERF_HW_STREX_PASSED = 0x80, /* strex passed */
+ ARMV7_PERF_HW_STREX_FAILED = 0x81, /* strex failed */
+ ARMV7_PERF_HW_LP_IN_TCM = 0x82, /* literal pool in TCM region */
+ ARMV7_PERF_HW_DMB_STALL = 0x90, /* DMB stall */
+ ARMV7_PERF_HW_ITCM_ACCESS = 0x91, /* ITCM access */
+ ARMV7_PERF_HW_DTCM_ACCESS = 0x92, /* DTCM access */
+ ARMV7_PERF_HW_DATA_EVICTION = 0x93, /* data eviction */
+ ARMV7_PERF_HW_SCU = 0x94, /* SCU coherency operation */
+ ARMV7_PERF_HW_INSCACHE_DEP_DW = 0x95, /* instruction cache dependent stall */
+ ARMV7_PERF_HW_DATA_CACHE_DEP_STALL = 0x96, /* data cache dependent stall */
+ ARMV7_PERF_HW_NOCACHE_NO_PER_DEP_STALL = 0x97, /* non-cacheable no peripheral dependent stall */
+ ARMV7_PERF_HW_NOCACHE_PER_DEP_STALL = 0x98, /* non-Cacheable peripheral dependent stall */
+ ARMV7_PERF_HW_DATA_CACHE_HP_DEP_STALL = 0x99, /* data cache high priority dependent stall */
+ ARMV7_PERF_HW_AXI_FAST_PERIPHERAL = 0x9A, /* Accesses_to_AXI_fast_peripheral_port(reads_and_writes) */
+};
+
+#ifdef __cplusplus
+#if __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+#endif /* _ARMV7_PMU_PRI_H */
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/include/asm.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/include/asm.h
new file mode 100644
index 00000000..b58871f8
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/include/asm.h
@@ -0,0 +1,66 @@
+/*
+ * 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 __ASM_H
+#define __ASM_H
+
+#ifdef __cplusplus
+#if __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+#define FUNCTION(x) .global x; .text; .code 32; x:
+#define MPIDR_CPUID_MASK 0xFFU
+
+/*
+ * ------------------------------------------
+ * stackTop | cpu n | ... | cpu 1 | cpu 0 | stackBottom
+ * ------------------------------------------
+ * | stackSize | ... | stackSize | stackSize |
+ */
+.macro EXC_SP_SET stackBottom, stackSize, reg0, reg1
+ mrc p15, 0, \reg0, c0, c0, 5
+ and \reg0, \reg0, #MPIDR_CPUID_MASK /* get cpu id */
+ mov \reg1, #\stackSize
+ mul \reg1, \reg1, \reg0 /* calculate current cpu stack offset */
+ ldr \reg0, =\stackBottom
+ sub \reg0, \reg0, \reg1 /* calculate current cpu stack bottom */
+ mov sp, \reg0 /* set sp */
+.endm
+
+#ifdef __cplusplus
+#if __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+#endif /* __ASM_H */
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/include/los_exc_pri.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/include/los_exc_pri.h
new file mode 100644
index 00000000..da9796da
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/include/los_exc_pri.h
@@ -0,0 +1,72 @@
+/*
+ * 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 _LOS_EXC_PRI_H
+#define _LOS_EXC_PRI_H
+
+#include "los_typedef.h"
+
+#ifdef __cplusplus
+#if __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+#define OS_SYSTEM_NORMAL 0
+#define OS_SYSTEM_EXC_CURR_CPU 1
+#define OS_SYSTEM_EXC_OTHER_CPU 2
+
+#define REGION_PATH_MAX 32
+
+typedef struct {
+#ifdef LOSCFG_KERNEL_VM
+ UINTPTR ip;
+ UINT32 len; /* f_path length */
+ CHAR f_path[REGION_PATH_MAX];
+#else
+ UINTPTR ip;
+#endif
+} IpInfo;
+
+extern UINT32 OsGetSystemStatus(VOID);
+extern VOID BackTraceSub(UINTPTR regFP);
+extern VOID OsExcInit(VOID);
+extern BOOL OsSystemExcIsReset(VOID);
+extern UINT32 BackTraceGet(UINTPTR regFP, IpInfo *callChain, UINT32 maxDepth);
+extern BOOL OsGetUsrIpInfo(UINTPTR ip, IpInfo *info);
+
+#ifdef __cplusplus
+#if __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+#endif /* _LOS_EXC_PRI_H */
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/include/los_hw_pri.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/include/los_hw_pri.h
new file mode 100644
index 00000000..d764cc9b
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/include/los_hw_pri.h
@@ -0,0 +1,117 @@
+/*
+ * 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 _LOS_HW_PRI_H
+#define _LOS_HW_PRI_H
+
+#include "los_base.h"
+#include "los_hw.h"
+
+#ifdef __cplusplus
+#if __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+#if defined(LOSCFG_ARCH_FPU_VFP_D16)
+#define FP_REGS_NUM 16
+#elif defined (LOSCFG_ARCH_FPU_VFP_D32)
+#define FP_REGS_NUM 32
+#endif
+#define GEN_REGS_NUM 13
+
+/* The size of this structure must be smaller than or equal to the size specified by OS_TSK_STACK_ALIGN (16 bytes). */
+typedef struct {
+#if !defined(LOSCFG_ARCH_FPU_DISABLE)
+ UINT64 D[FP_REGS_NUM]; /* D0-D31 */
+ UINT32 regFPSCR; /* FPSCR */
+ UINT32 regFPEXC; /* FPEXC */
+#endif
+ UINT32 R4;
+ UINT32 R5;
+ UINT32 R6;
+ UINT32 R7;
+ UINT32 R8;
+ UINT32 R9;
+ UINT32 R10;
+ UINT32 R11;
+
+ /* It has the same structure as IrqContext */
+ UINT32 reserved2; /**< Multiplexing registers, used in interrupts and system calls but with different meanings */
+ UINT32 reserved1; /**< Multiplexing registers, used in interrupts and system calls but with different meanings */
+ UINT32 USP; /**< User mode sp register */
+ UINT32 ULR; /**< User mode lr register */
+ UINT32 R0;
+ UINT32 R1;
+ UINT32 R2;
+ UINT32 R3;
+ UINT32 R12;
+ UINT32 LR;
+ UINT32 PC;
+ UINT32 regCPSR;
+} TaskContext;
+
+typedef struct {
+ UINT32 reserved2; /**< Multiplexing registers, used in interrupts and system calls but with different meanings */
+ UINT32 reserved1; /**< Multiplexing registers, used in interrupts and system calls but with different meanings */
+ UINT32 USP; /**< User mode sp register */
+ UINT32 ULR; /**< User mode lr register */
+ UINT32 R0;
+ UINT32 R1;
+ UINT32 R2;
+ UINT32 R3;
+ UINT32 R12;
+ UINT32 LR;
+ UINT32 PC;
+ UINT32 regCPSR;
+} IrqContext;
+
+/*
+ * Description : task stack initialization
+ * Input : taskID -- task ID
+ * stackSize -- task stack size
+ * topStack -- stack top of task (low address)
+ * Return : pointer to the task context
+ */
+extern VOID *OsTaskStackInit(UINT32 taskID, UINT32 stackSize, VOID *topStack, BOOL initFlag);
+extern VOID OsUserCloneParentStack(VOID *childStack, UINTPTR parentTopOfStask, UINT32 parentStackSize);
+extern VOID OsUserTaskStackInit(TaskContext *context, UINTPTR taskEntry, UINTPTR stack);
+extern VOID OsInitSignalContext(const VOID *sp, VOID *signalContext, UINTPTR sigHandler, UINT32 signo, UINT32 param);
+extern void arm_clean_cache_range(UINTPTR start, UINTPTR end);
+extern void arm_inv_cache_range(UINTPTR start, UINTPTR end);
+
+#ifdef __cplusplus
+#if __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+#endif /* _LOS_HW_PRI_H */
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/include/los_hwi_pri.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/include/los_hwi_pri.h
new file mode 100644
index 00000000..174b0189
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/include/los_hwi_pri.h
@@ -0,0 +1,69 @@
+/*
+ * 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 _LOS_HWI_PRI_H
+#define _LOS_HWI_PRI_H
+
+#include "los_hwi.h"
+
+#ifdef __cplusplus
+#if __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+/**
+ * @ingroup los_hwi
+ * The hwi form does not contain exceptions for Aarch32
+ */
+#define OS_HWI_FORM_EXC_NUM 0
+#if OS_HWI_FORM_EXC_NUM != 0
+#error "OS_HWI_FORM_EXC_NUM must be zero"
+#endif
+
+#ifdef LOSCFG_NO_SHARED_IRQ
+#define HWI_IS_REGISTED(num) ((&g_hwiForm[num])->pfnHook != NULL)
+#else
+#define HWI_IS_REGISTED(num) ((&g_hwiForm[num])->pstNext != NULL)
+#endif
+extern VOID OsHwiInit(VOID);
+extern VOID OsIncHwiFormCnt(UINT32 index);
+extern UINT32 OsGetHwiFormCnt(UINT32 index);
+extern CHAR *OsGetHwiFormName(UINT32 index);
+extern VOID OsInterrupt(UINT32 intNum);
+extern VOID OsSyscallHandleInit(VOID);
+
+#ifdef __cplusplus
+#if __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+#endif /* _LOS_HWI_PRI_H */
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/jmp.S b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/jmp.S
new file mode 100644
index 00000000..14dd05a3
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/jmp.S
@@ -0,0 +1,52 @@
+/*
+ * 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 "asm.h"
+
+FUNCTION(longjmp)
+ ldmfd r0,{r4-r12}
+ add r0,#(4 * 9)
+ ldr r13,[r0]
+ add r0,#4
+ ldr r14,[r0]
+ cmp r1,#0
+ moveq r1,#1
+ mov r0,r1
+ mov pc,lr
+
+FUNCTION(setjmp)
+ stmea r0,{r4-r12}
+ add r0,#(4 * 9)
+ str r13,[r0]
+ add r0,#4
+ str r14,[r0]
+ mov r0,#0
+ mov pc,lr
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/los_arch_mmu.c b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/los_arch_mmu.c
new file mode 100644
index 00000000..04f58204
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/los_arch_mmu.c
@@ -0,0 +1,1139 @@
+/*
+ * 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.
+ */
+
+/**
+ * @defgroup los_arch_mmu architecture mmu
+ * @ingroup kernel
+ */
+
+#include "los_arch_mmu.h"
+#include "los_asid.h"
+#include "los_pte_ops.h"
+#include "los_tlb_v6.h"
+#include "los_printf.h"
+#include "los_vm_common.h"
+#include "los_vm_map.h"
+#include "los_vm_boot.h"
+#include "los_mmu_descriptor_v6.h"
+#include "los_process_pri.h"
+
+#ifdef LOSCFG_KERNEL_MMU
+typedef struct {
+ LosArchMmu *archMmu;
+ VADDR_T *vaddr;
+ PADDR_T *paddr;
+ UINT32 *flags;
+} MmuMapInfo;
+
+#define TRY_MAX_TIMES 10
+
+__attribute__((aligned(MMU_DESCRIPTOR_L1_SMALL_ENTRY_NUMBERS))) \
+ __attribute__((section(".bss.prebss.translation_table"))) UINT8 \
+ g_firstPageTable[MMU_DESCRIPTOR_L1_SMALL_ENTRY_NUMBERS];
+#ifdef LOSCFG_KERNEL_SMP
+__attribute__((aligned(MMU_DESCRIPTOR_L1_SMALL_ENTRY_NUMBERS))) \
+ __attribute__((section(".bss.prebss.translation_table"))) UINT8 \
+ g_tempPageTable[MMU_DESCRIPTOR_L1_SMALL_ENTRY_NUMBERS];
+UINT8 *g_mmuJumpPageTable = g_tempPageTable;
+#else
+extern CHAR __mmu_ttlb_begin; /* defined in .ld script */
+UINT8 *g_mmuJumpPageTable = (UINT8 *)&__mmu_ttlb_begin; /* temp page table, this is only used when system power up */
+#endif
+
+STATIC SPIN_LOCK_S *OsGetPteLock(LosArchMmu *archMmu, PADDR_T paddr, UINT32 *intSave)
+{
+ SPIN_LOCK_S *lock = NULL;
+#ifdef LOSCFG_PAGE_TABLE_FINE_LOCK
+ LosVmPage *vmPage = NULL;
+
+ vmPage = OsVmPaddrToPage(paddr);
+ if (vmPage == NULL) {
+ return NULL;
+ }
+ lock = &vmPage->lock;
+#else
+ lock = &archMmu->lock;
+#endif
+
+ LOS_SpinLockSave(lock, intSave);
+ return lock;
+}
+
+STATIC SPIN_LOCK_S *OsGetPte1Lock(LosArchMmu *archMmu, PADDR_T paddr, UINT32 *intSave)
+{
+ return OsGetPteLock(archMmu, paddr, intSave);
+}
+
+STATIC INLINE VOID OsUnlockPte1(SPIN_LOCK_S *lock, UINT32 intSave)
+{
+ if (lock == NULL) {
+ return;
+ }
+ LOS_SpinUnlockRestore(lock, intSave);
+}
+
+STATIC SPIN_LOCK_S *OsGetPte1LockTmp(LosArchMmu *archMmu, PADDR_T paddr, UINT32 *intSave)
+{
+ SPIN_LOCK_S *spinLock = NULL;
+#ifdef LOSCFG_PAGE_TABLE_FINE_LOCK
+ spinLock = OsGetPteLock(archMmu, paddr, intSave);
+#else
+ (VOID)archMmu;
+ (VOID)paddr;
+ (VOID)intSave;
+#endif
+ return spinLock;
+}
+
+STATIC INLINE VOID OsUnlockPte1Tmp(SPIN_LOCK_S *lock, UINT32 intSave)
+{
+#ifdef LOSCFG_PAGE_TABLE_FINE_LOCK
+ if (lock == NULL) {
+ return;
+ }
+ LOS_SpinUnlockRestore(lock, intSave);
+#else
+ (VOID)lock;
+ (VOID)intSave;
+#endif
+}
+
+STATIC INLINE SPIN_LOCK_S *OsGetPte2Lock(LosArchMmu *archMmu, PTE_T pte1, UINT32 *intSave)
+{
+ PADDR_T pa = MMU_DESCRIPTOR_L1_PAGE_TABLE_ADDR(pte1);
+ return OsGetPteLock(archMmu, pa, intSave);
+}
+
+STATIC INLINE VOID OsUnlockPte2(SPIN_LOCK_S *lock, UINT32 intSave)
+{
+ return OsUnlockPte1(lock, intSave);
+}
+
+STATIC INLINE PTE_T *OsGetPte2BasePtr(PTE_T pte1)
+{
+ PADDR_T pa = MMU_DESCRIPTOR_L1_PAGE_TABLE_ADDR(pte1);
+ return LOS_PaddrToKVaddr(pa);
+}
+
+VADDR_T *OsGFirstTableGet(VOID)
+{
+ return (VADDR_T *)g_firstPageTable;
+}
+
+STATIC INLINE UINT32 OsUnmapL1Invalid(vaddr_t *vaddr, UINT32 *count)
+{
+ UINT32 unmapCount;
+
+ unmapCount = MIN2((MMU_DESCRIPTOR_L1_SMALL_SIZE - (*vaddr % MMU_DESCRIPTOR_L1_SMALL_SIZE)) >>
+ MMU_DESCRIPTOR_L2_SMALL_SHIFT, *count);
+ *vaddr += unmapCount << MMU_DESCRIPTOR_L2_SMALL_SHIFT;
+ *count -= unmapCount;
+
+ return unmapCount;
+}
+
+STATIC INT32 OsMapParamCheck(UINT32 flags, VADDR_T vaddr, PADDR_T paddr)
+{
+#if !WITH_ARCH_MMU_PICK_SPOT
+ if (flags & VM_MAP_REGION_FLAG_NS) {
+ /* WITH_ARCH_MMU_PICK_SPOT is required to support NS memory */
+ LOS_Panic("NS mem is not supported\n");
+ }
+#endif
+
+ /* paddr and vaddr must be aligned */
+ if (!MMU_DESCRIPTOR_IS_L2_SIZE_ALIGNED(vaddr) || !MMU_DESCRIPTOR_IS_L2_SIZE_ALIGNED(paddr)) {
+ return LOS_ERRNO_VM_INVALID_ARGS;
+ }
+
+ return 0;
+}
+
+STATIC VOID OsCvtPte2AttsToFlags(PTE_T l1Entry, PTE_T l2Entry, UINT32 *flags)
+{
+ *flags = 0;
+ /* NS flag is only present on L1 entry */
+ if (l1Entry & MMU_DESCRIPTOR_L1_PAGETABLE_NON_SECURE) {
+ *flags |= VM_MAP_REGION_FLAG_NS;
+ }
+
+ switch (l2Entry & MMU_DESCRIPTOR_L2_TEX_TYPE_MASK) {
+ case MMU_DESCRIPTOR_L2_TYPE_STRONGLY_ORDERED:
+ *flags |= VM_MAP_REGION_FLAG_STRONGLY_ORDERED;
+ break;
+ case MMU_DESCRIPTOR_L2_TYPE_NORMAL_NOCACHE:
+ *flags |= VM_MAP_REGION_FLAG_UNCACHED;
+ break;
+ case MMU_DESCRIPTOR_L2_TYPE_DEVICE_SHARED:
+ case MMU_DESCRIPTOR_L2_TYPE_DEVICE_NON_SHARED:
+ *flags |= VM_MAP_REGION_FLAG_UNCACHED_DEVICE;
+ break;
+ default:
+ break;
+ }
+
+ *flags |= VM_MAP_REGION_FLAG_PERM_READ;
+
+ switch (l2Entry & MMU_DESCRIPTOR_L2_AP_MASK) {
+ case MMU_DESCRIPTOR_L2_AP_P_RO_U_NA:
+ break;
+ case MMU_DESCRIPTOR_L2_AP_P_RW_U_NA:
+ *flags |= VM_MAP_REGION_FLAG_PERM_WRITE;
+ break;
+ case MMU_DESCRIPTOR_L2_AP_P_RO_U_RO:
+ *flags |= VM_MAP_REGION_FLAG_PERM_USER;
+ break;
+ case MMU_DESCRIPTOR_L2_AP_P_RW_U_RW:
+ *flags |= VM_MAP_REGION_FLAG_PERM_USER | VM_MAP_REGION_FLAG_PERM_WRITE;
+ break;
+ default:
+ break;
+ }
+ if ((l2Entry & MMU_DESCRIPTOR_L2_TYPE_MASK) != MMU_DESCRIPTOR_L2_TYPE_SMALL_PAGE_XN) {
+ *flags |= VM_MAP_REGION_FLAG_PERM_EXECUTE;
+ }
+}
+
+STATIC VOID OsPutL2Table(const LosArchMmu *archMmu, UINT32 l1Index, paddr_t l2Paddr)
+{
+ UINT32 index;
+ PTE_T ttEntry;
+ /* check if any l1 entry points to this l2 table */
+ for (index = 0; index < MMU_DESCRIPTOR_L1_SMALL_L2_TABLES_PER_PAGE; index++) {
+ ttEntry = archMmu->virtTtb[ROUNDDOWN(l1Index, MMU_DESCRIPTOR_L1_SMALL_L2_TABLES_PER_PAGE) + index];
+ if ((ttEntry & MMU_DESCRIPTOR_L1_TYPE_MASK) == MMU_DESCRIPTOR_L1_TYPE_PAGE_TABLE) {
+ return;
+ }
+ }
+#ifdef LOSCFG_KERNEL_VM
+ /* we can free this l2 table */
+ LosVmPage *vmPage = LOS_VmPageGet(l2Paddr);
+ if (vmPage == NULL) {
+ LOS_Panic("bad page table paddr %#x\n", l2Paddr);
+ return;
+ }
+
+ LOS_ListDelete(&vmPage->node);
+ LOS_PhysPageFree(vmPage);
+#else
+ (VOID)LOS_MemFree(OS_SYS_MEM_ADDR, LOS_PaddrToKVaddr(l2Paddr));
+#endif
+}
+
+STATIC VOID OsTryUnmapL1PTE(LosArchMmu *archMmu, PTE_T *l1Entry, vaddr_t vaddr, UINT32 scanIndex, UINT32 scanCount)
+{
+ /*
+ * Check if all pages related to this l1 entry are deallocated.
+ * We only need to check pages that we did not clear above starting
+ * from scanIndex and wrapped around SECTION.
+ */
+ UINT32 l1Index;
+ PTE_T *pte2BasePtr = NULL;
+ SPIN_LOCK_S *pte1Lock = NULL;
+ SPIN_LOCK_S *pte2Lock = NULL;
+ UINT32 pte1IntSave;
+ UINT32 pte2IntSave;
+ PTE_T pte1Val;
+ PADDR_T pte1Paddr;
+
+ pte1Paddr = OsGetPte1Paddr(archMmu->physTtb, vaddr);
+ pte2Lock = OsGetPte2Lock(archMmu, *l1Entry, &pte2IntSave);
+ if (pte2Lock == NULL) {
+ return;
+ }
+ pte2BasePtr = OsGetPte2BasePtr(*l1Entry);
+ if (pte2BasePtr == NULL) {
+ OsUnlockPte2(pte2Lock, pte2IntSave);
+ return;
+ }
+
+ while (scanCount) {
+ if (scanIndex == MMU_DESCRIPTOR_L2_NUMBERS_PER_L1) {
+ scanIndex = 0;
+ }
+ if (pte2BasePtr[scanIndex++]) {
+ break;
+ }
+ scanCount--;
+ }
+
+ if (!scanCount) {
+ /*
+ * The pte1 of kprocess is placed in kernel image when compiled. So the pte1Lock will be null.
+ * There is no situation to simultaneous access the pte1 of kprocess.
+ */
+ pte1Lock = OsGetPte1LockTmp(archMmu, pte1Paddr, &pte1IntSave);
+ if (!OsIsPte1PageTable(*l1Entry)) {
+ OsUnlockPte1Tmp(pte1Lock, pte1IntSave);
+ OsUnlockPte2(pte2Lock, pte2IntSave);
+ return;
+ }
+ pte1Val = *l1Entry;
+ /* we can kill l1 entry */
+ OsClearPte1(l1Entry);
+ l1Index = OsGetPte1Index(vaddr);
+ OsArmInvalidateTlbMvaNoBarrier(l1Index << MMU_DESCRIPTOR_L1_SMALL_SHIFT);
+
+ /* try to free l2 page itself */
+ OsPutL2Table(archMmu, l1Index, MMU_DESCRIPTOR_L1_PAGE_TABLE_ADDR(pte1Val));
+ OsUnlockPte1Tmp(pte1Lock, pte1IntSave);
+ }
+ OsUnlockPte2(pte2Lock, pte2IntSave);
+}
+
+STATIC UINT32 OsCvtSecCacheFlagsToMMUFlags(UINT32 flags)
+{
+ UINT32 mmuFlags = 0;
+
+ switch (flags & VM_MAP_REGION_FLAG_CACHE_MASK) {
+ case VM_MAP_REGION_FLAG_CACHED:
+ mmuFlags |= MMU_DESCRIPTOR_L1_TYPE_NORMAL_WRITE_BACK_ALLOCATE;
+#ifdef LOSCFG_KERNEL_SMP
+ mmuFlags |= MMU_DESCRIPTOR_L1_SECTION_SHAREABLE;
+#endif
+ break;
+ case VM_MAP_REGION_FLAG_STRONGLY_ORDERED:
+ mmuFlags |= MMU_DESCRIPTOR_L1_TYPE_STRONGLY_ORDERED;
+ break;
+ case VM_MAP_REGION_FLAG_UNCACHED:
+ mmuFlags |= MMU_DESCRIPTOR_L1_TYPE_NORMAL_NOCACHE;
+ break;
+ case VM_MAP_REGION_FLAG_UNCACHED_DEVICE:
+ mmuFlags |= MMU_DESCRIPTOR_L1_TYPE_DEVICE_SHARED;
+ break;
+ default:
+ return LOS_ERRNO_VM_INVALID_ARGS;
+ }
+ return mmuFlags;
+}
+
+STATIC UINT32 OsCvtSecAccessFlagsToMMUFlags(UINT32 flags)
+{
+ UINT32 mmuFlags = 0;
+
+ switch (flags & (VM_MAP_REGION_FLAG_PERM_USER | VM_MAP_REGION_FLAG_PERM_READ | VM_MAP_REGION_FLAG_PERM_WRITE)) {
+ case 0:
+ mmuFlags |= MMU_DESCRIPTOR_L1_AP_P_NA_U_NA;
+ break;
+ case VM_MAP_REGION_FLAG_PERM_READ:
+ case VM_MAP_REGION_FLAG_PERM_USER:
+ mmuFlags |= MMU_DESCRIPTOR_L1_AP_P_RO_U_NA;
+ break;
+ case VM_MAP_REGION_FLAG_PERM_USER | VM_MAP_REGION_FLAG_PERM_READ:
+ mmuFlags |= MMU_DESCRIPTOR_L1_AP_P_RO_U_RO;
+ break;
+ case VM_MAP_REGION_FLAG_PERM_WRITE:
+ case VM_MAP_REGION_FLAG_PERM_READ | VM_MAP_REGION_FLAG_PERM_WRITE:
+ mmuFlags |= MMU_DESCRIPTOR_L1_AP_P_RW_U_NA;
+ break;
+ case VM_MAP_REGION_FLAG_PERM_USER | VM_MAP_REGION_FLAG_PERM_WRITE:
+ case VM_MAP_REGION_FLAG_PERM_USER | VM_MAP_REGION_FLAG_PERM_READ | VM_MAP_REGION_FLAG_PERM_WRITE:
+ mmuFlags |= MMU_DESCRIPTOR_L1_AP_P_RW_U_RW;
+ break;
+ default:
+ break;
+ }
+ return mmuFlags;
+}
+
+/* convert user level mmu flags to L1 descriptors flags */
+STATIC UINT32 OsCvtSecFlagsToAttrs(UINT32 flags)
+{
+ UINT32 mmuFlags;
+
+ mmuFlags = OsCvtSecCacheFlagsToMMUFlags(flags);
+ if (mmuFlags == LOS_ERRNO_VM_INVALID_ARGS) {
+ return mmuFlags;
+ }
+
+ mmuFlags |= MMU_DESCRIPTOR_L1_SMALL_DOMAIN_CLIENT;
+
+ mmuFlags |= OsCvtSecAccessFlagsToMMUFlags(flags);
+
+ if (!(flags & VM_MAP_REGION_FLAG_PERM_EXECUTE)) {
+ mmuFlags |= MMU_DESCRIPTOR_L1_SECTION_XN;
+ }
+
+ if (flags & VM_MAP_REGION_FLAG_NS) {
+ mmuFlags |= MMU_DESCRIPTOR_L1_SECTION_NON_SECURE;
+ }
+
+ if (flags & VM_MAP_REGION_FLAG_PERM_USER) {
+ mmuFlags |= MMU_DESCRIPTOR_L1_SECTION_NON_GLOBAL;
+ }
+
+ return mmuFlags;
+}
+
+STATIC VOID OsCvtSecAttsToFlags(PTE_T l1Entry, UINT32 *flags)
+{
+ *flags = 0;
+ if (l1Entry & MMU_DESCRIPTOR_L1_SECTION_NON_SECURE) {
+ *flags |= VM_MAP_REGION_FLAG_NS;
+ }
+
+ switch (l1Entry & MMU_DESCRIPTOR_L1_TEX_TYPE_MASK) {
+ case MMU_DESCRIPTOR_L1_TYPE_STRONGLY_ORDERED:
+ *flags |= VM_MAP_REGION_FLAG_STRONGLY_ORDERED;
+ break;
+ case MMU_DESCRIPTOR_L1_TYPE_NORMAL_NOCACHE:
+ *flags |= VM_MAP_REGION_FLAG_UNCACHED;
+ break;
+ case MMU_DESCRIPTOR_L1_TYPE_DEVICE_SHARED:
+ case MMU_DESCRIPTOR_L1_TYPE_DEVICE_NON_SHARED:
+ *flags |= VM_MAP_REGION_FLAG_UNCACHED_DEVICE;
+ break;
+ default:
+ break;
+ }
+
+ *flags |= VM_MAP_REGION_FLAG_PERM_READ;
+
+ switch (l1Entry & MMU_DESCRIPTOR_L1_AP_MASK) {
+ case MMU_DESCRIPTOR_L1_AP_P_RO_U_NA:
+ break;
+ case MMU_DESCRIPTOR_L1_AP_P_RW_U_NA:
+ *flags |= VM_MAP_REGION_FLAG_PERM_WRITE;
+ break;
+ case MMU_DESCRIPTOR_L1_AP_P_RO_U_RO:
+ *flags |= VM_MAP_REGION_FLAG_PERM_USER;
+ break;
+ case MMU_DESCRIPTOR_L1_AP_P_RW_U_RW:
+ *flags |= VM_MAP_REGION_FLAG_PERM_USER | VM_MAP_REGION_FLAG_PERM_WRITE;
+ break;
+ default:
+ break;
+ }
+
+ if (!(l1Entry & MMU_DESCRIPTOR_L1_SECTION_XN)) {
+ *flags |= VM_MAP_REGION_FLAG_PERM_EXECUTE;
+ }
+}
+
+STATIC UINT32 OsUnmapL2PTE(LosArchMmu *archMmu, PTE_T *pte1, vaddr_t vaddr, UINT32 *count)
+{
+ UINT32 unmapCount;
+ UINT32 pte2Index;
+ UINT32 intSave;
+ PTE_T *pte2BasePtr = NULL;
+ SPIN_LOCK_S *lock = NULL;
+
+ pte2Index = OsGetPte2Index(vaddr);
+ unmapCount = MIN2(MMU_DESCRIPTOR_L2_NUMBERS_PER_L1 - pte2Index, *count);
+
+ lock = OsGetPte2Lock(archMmu, *pte1, &intSave);
+ if (lock == NULL) {
+ return unmapCount;
+ }
+
+ pte2BasePtr = OsGetPte2BasePtr(*pte1);
+ if (pte2BasePtr == NULL) {
+ OsUnlockPte2(lock, intSave);
+ return unmapCount;
+ }
+
+ /* unmap page run */
+ OsClearPte2Continuous(&pte2BasePtr[pte2Index], unmapCount);
+
+ /* invalidate tlb */
+ OsArmInvalidateTlbMvaRangeNoBarrier(vaddr, unmapCount);
+ OsUnlockPte2(lock, intSave);
+
+ *count -= unmapCount;
+ return unmapCount;
+}
+
+STATIC UINT32 OsUnmapSection(LosArchMmu *archMmu, PTE_T *l1Entry, vaddr_t *vaddr, UINT32 *count)
+{
+ UINT32 intSave;
+ PADDR_T pte1Paddr;
+ SPIN_LOCK_S *lock = NULL;
+
+ pte1Paddr = OsGetPte1Paddr(archMmu->physTtb, *vaddr);
+ lock = OsGetPte1Lock(archMmu, pte1Paddr, &intSave);
+ if (!OsIsPte1Section(*l1Entry)) {
+ OsUnlockPte1(lock, intSave);
+ return 0;
+ }
+ OsClearPte1(OsGetPte1Ptr((PTE_T *)archMmu->virtTtb, *vaddr));
+ OsArmInvalidateTlbMvaNoBarrier(*vaddr);
+ OsUnlockPte1(lock, intSave);
+
+ *vaddr += MMU_DESCRIPTOR_L1_SMALL_SIZE;
+ *count -= MMU_DESCRIPTOR_L2_NUMBERS_PER_L1;
+
+ return MMU_DESCRIPTOR_L2_NUMBERS_PER_L1;
+}
+
+BOOL OsArchMmuInit(LosArchMmu *archMmu, VADDR_T *virtTtb)
+{
+#ifdef LOSCFG_KERNEL_VM
+ if (OsAllocAsid(&archMmu->asid) != LOS_OK) {
+ VM_ERR("alloc arch mmu asid failed");
+ return FALSE;
+ }
+#endif
+
+#ifndef LOSCFG_PAGE_TABLE_FINE_LOCK
+ LOS_SpinInit(&archMmu->lock);
+#endif
+ LOS_ListInit(&archMmu->ptList);
+ archMmu->virtTtb = virtTtb;
+ archMmu->physTtb = (VADDR_T)(UINTPTR)virtTtb - KERNEL_ASPACE_BASE + SYS_MEM_BASE;
+ return TRUE;
+}
+
+STATUS_T LOS_ArchMmuQuery(const LosArchMmu *archMmu, VADDR_T vaddr, PADDR_T *paddr, UINT32 *flags)
+{
+ PTE_T l1Entry = OsGetPte1(archMmu->virtTtb, vaddr);
+ PTE_T l2Entry;
+ PTE_T* l2Base = NULL;
+
+ if (OsIsPte1Invalid(l1Entry)) {
+ return LOS_ERRNO_VM_NOT_FOUND;
+ } else if (OsIsPte1Section(l1Entry)) {
+ if (paddr != NULL) {
+ *paddr = MMU_DESCRIPTOR_L1_SECTION_ADDR(l1Entry) + (vaddr & (MMU_DESCRIPTOR_L1_SMALL_SIZE - 1));
+ }
+
+ if (flags != NULL) {
+ OsCvtSecAttsToFlags(l1Entry, flags);
+ }
+ } else if (OsIsPte1PageTable(l1Entry)) {
+ l2Base = OsGetPte2BasePtr(l1Entry);
+ if (l2Base == NULL) {
+ return LOS_ERRNO_VM_NOT_FOUND;
+ }
+ l2Entry = OsGetPte2(l2Base, vaddr);
+ if (OsIsPte2SmallPage(l2Entry) || OsIsPte2SmallPageXN(l2Entry)) {
+ if (paddr != NULL) {
+ *paddr = MMU_DESCRIPTOR_L2_SMALL_PAGE_ADDR(l2Entry) + (vaddr & (MMU_DESCRIPTOR_L2_SMALL_SIZE - 1));
+ }
+
+ if (flags != NULL) {
+ OsCvtPte2AttsToFlags(l1Entry, l2Entry, flags);
+ }
+ } else if (OsIsPte2LargePage(l2Entry)) {
+ LOS_Panic("%s %d, large page unimplemented\n", __FUNCTION__, __LINE__);
+ } else {
+ return LOS_ERRNO_VM_NOT_FOUND;
+ }
+ }
+
+ return LOS_OK;
+}
+
+STATUS_T LOS_ArchMmuUnmap(LosArchMmu *archMmu, VADDR_T vaddr, size_t count)
+{
+ PTE_T *l1Entry = NULL;
+ INT32 unmapped = 0;
+ UINT32 unmapCount = 0;
+ INT32 tryTime = TRY_MAX_TIMES;
+
+ while (count > 0) {
+ l1Entry = OsGetPte1Ptr(archMmu->virtTtb, vaddr);
+ if (OsIsPte1Invalid(*l1Entry)) {
+ unmapCount = OsUnmapL1Invalid(&vaddr, &count);
+ } else if (OsIsPte1Section(*l1Entry)) {
+ if (MMU_DESCRIPTOR_IS_L1_SIZE_ALIGNED(vaddr) && count >= MMU_DESCRIPTOR_L2_NUMBERS_PER_L1) {
+ unmapCount = OsUnmapSection(archMmu, l1Entry, &vaddr, &count);
+ } else {
+ LOS_Panic("%s %d, unimplemented\n", __FUNCTION__, __LINE__);
+ }
+ } else if (OsIsPte1PageTable(*l1Entry)) {
+ unmapCount = OsUnmapL2PTE(archMmu, l1Entry, vaddr, &count);
+ OsTryUnmapL1PTE(archMmu, l1Entry, vaddr, OsGetPte2Index(vaddr) + unmapCount,
+ MMU_DESCRIPTOR_L2_NUMBERS_PER_L1);
+ vaddr += unmapCount << MMU_DESCRIPTOR_L2_SMALL_SHIFT;
+ } else {
+ LOS_Panic("%s %d, unimplemented\n", __FUNCTION__, __LINE__);
+ }
+ tryTime = (unmapCount == 0) ? (tryTime - 1) : tryTime;
+ if (tryTime == 0) {
+ return LOS_ERRNO_VM_FAULT;
+ }
+ unmapped += unmapCount;
+ }
+ OsArmInvalidateTlbBarrier();
+ return unmapped;
+}
+
+STATIC UINT32 OsMapSection(MmuMapInfo *mmuMapInfo, UINT32 *count)
+{
+ UINT32 mmuFlags = 0;
+ UINT32 intSave;
+ PADDR_T pte1Paddr;
+ SPIN_LOCK_S *lock = NULL;
+
+ mmuFlags |= OsCvtSecFlagsToAttrs(*mmuMapInfo->flags);
+ pte1Paddr = OsGetPte1Paddr(mmuMapInfo->archMmu->physTtb, *mmuMapInfo->vaddr);
+ lock = OsGetPte1Lock(mmuMapInfo->archMmu, pte1Paddr, &intSave);
+ OsSavePte1(OsGetPte1Ptr(mmuMapInfo->archMmu->virtTtb, *mmuMapInfo->vaddr),
+ OsTruncPte1(*mmuMapInfo->paddr) | mmuFlags | MMU_DESCRIPTOR_L1_TYPE_SECTION);
+ OsUnlockPte1(lock, intSave);
+ *count -= MMU_DESCRIPTOR_L2_NUMBERS_PER_L1;
+ *mmuMapInfo->vaddr += MMU_DESCRIPTOR_L1_SMALL_SIZE;
+ *mmuMapInfo->paddr += MMU_DESCRIPTOR_L1_SMALL_SIZE;
+
+ return MMU_DESCRIPTOR_L2_NUMBERS_PER_L1;
+}
+
+STATIC STATUS_T OsGetL2Table(LosArchMmu *archMmu, UINT32 l1Index, paddr_t *ppa)
+{
+ UINT32 index;
+ PTE_T ttEntry;
+ VADDR_T *kvaddr = NULL;
+ UINT32 l2Offset = (MMU_DESCRIPTOR_L2_SMALL_SIZE / MMU_DESCRIPTOR_L1_SMALL_L2_TABLES_PER_PAGE) *
+ (l1Index & (MMU_DESCRIPTOR_L1_SMALL_L2_TABLES_PER_PAGE - 1));
+ /* lookup an existing l2 page table */
+ for (index = 0; index < MMU_DESCRIPTOR_L1_SMALL_L2_TABLES_PER_PAGE; index++) {
+ ttEntry = archMmu->virtTtb[ROUNDDOWN(l1Index, MMU_DESCRIPTOR_L1_SMALL_L2_TABLES_PER_PAGE) + index];
+ if ((ttEntry & MMU_DESCRIPTOR_L1_TYPE_MASK) == MMU_DESCRIPTOR_L1_TYPE_PAGE_TABLE) {
+ *ppa = (PADDR_T)ROUNDDOWN(MMU_DESCRIPTOR_L1_PAGE_TABLE_ADDR(ttEntry), MMU_DESCRIPTOR_L2_SMALL_SIZE) +
+ l2Offset;
+ return LOS_OK;
+ }
+ }
+
+#ifdef LOSCFG_KERNEL_VM
+ /* not found: allocate one (paddr) */
+ LosVmPage *vmPage = LOS_PhysPageAlloc();
+ if (vmPage == NULL) {
+ VM_ERR("have no memory to save l2 page");
+ return LOS_ERRNO_VM_NO_MEMORY;
+ }
+ LOS_ListAdd(&archMmu->ptList, &vmPage->node);
+ kvaddr = OsVmPageToVaddr(vmPage);
+#else
+ kvaddr = LOS_MemAlloc(OS_SYS_MEM_ADDR, MMU_DESCRIPTOR_L2_SMALL_SIZE);
+ if (kvaddr == NULL) {
+ VM_ERR("have no memory to save l2 page");
+ return LOS_ERRNO_VM_NO_MEMORY;
+ }
+#endif
+ (VOID)memset_s(kvaddr, MMU_DESCRIPTOR_L2_SMALL_SIZE, 0, MMU_DESCRIPTOR_L2_SMALL_SIZE);
+
+ /* get physical address */
+ *ppa = OsKVaddrToPaddr((VADDR_T)kvaddr) + l2Offset;
+ return LOS_OK;
+}
+
+STATIC UINT32 OsCvtPte2CacheFlagsToMMUFlags(UINT32 flags)
+{
+ UINT32 mmuFlags = 0;
+
+ switch (flags & VM_MAP_REGION_FLAG_CACHE_MASK) {
+ case VM_MAP_REGION_FLAG_CACHED:
+#ifdef LOSCFG_KERNEL_SMP
+ mmuFlags |= MMU_DESCRIPTOR_L2_SHAREABLE;
+#endif
+ mmuFlags |= MMU_DESCRIPTOR_L2_TYPE_NORMAL_WRITE_BACK_ALLOCATE;
+ break;
+ case VM_MAP_REGION_FLAG_STRONGLY_ORDERED:
+ mmuFlags |= MMU_DESCRIPTOR_L2_TYPE_STRONGLY_ORDERED;
+ break;
+ case VM_MAP_REGION_FLAG_UNCACHED:
+ mmuFlags |= MMU_DESCRIPTOR_L2_TYPE_NORMAL_NOCACHE;
+ break;
+ case VM_MAP_REGION_FLAG_UNCACHED_DEVICE:
+ mmuFlags |= MMU_DESCRIPTOR_L2_TYPE_DEVICE_SHARED;
+ break;
+ default:
+ return LOS_ERRNO_VM_INVALID_ARGS;
+ }
+ return mmuFlags;
+}
+
+STATIC UINT32 OsCvtPte2AccessFlagsToMMUFlags(UINT32 flags)
+{
+ UINT32 mmuFlags = 0;
+
+ switch (flags & (VM_MAP_REGION_FLAG_PERM_USER | VM_MAP_REGION_FLAG_PERM_READ | VM_MAP_REGION_FLAG_PERM_WRITE)) {
+ case 0:
+ mmuFlags |= MMU_DESCRIPTOR_L1_AP_P_NA_U_NA;
+ break;
+ case VM_MAP_REGION_FLAG_PERM_READ:
+ case VM_MAP_REGION_FLAG_PERM_USER:
+ mmuFlags |= MMU_DESCRIPTOR_L2_AP_P_RO_U_NA;
+ break;
+ case VM_MAP_REGION_FLAG_PERM_USER | VM_MAP_REGION_FLAG_PERM_READ:
+ mmuFlags |= MMU_DESCRIPTOR_L2_AP_P_RO_U_RO;
+ break;
+ case VM_MAP_REGION_FLAG_PERM_WRITE:
+ case VM_MAP_REGION_FLAG_PERM_READ | VM_MAP_REGION_FLAG_PERM_WRITE:
+ mmuFlags |= MMU_DESCRIPTOR_L2_AP_P_RW_U_NA;
+ break;
+ case VM_MAP_REGION_FLAG_PERM_USER | VM_MAP_REGION_FLAG_PERM_WRITE:
+ case VM_MAP_REGION_FLAG_PERM_USER | VM_MAP_REGION_FLAG_PERM_READ | VM_MAP_REGION_FLAG_PERM_WRITE:
+ mmuFlags |= MMU_DESCRIPTOR_L2_AP_P_RW_U_RW;
+ break;
+ default:
+ break;
+ }
+ return mmuFlags;
+}
+
+/* convert user level mmu flags to L2 descriptors flags */
+STATIC UINT32 OsCvtPte2FlagsToAttrs(UINT32 flags)
+{
+ UINT32 mmuFlags;
+
+ mmuFlags = OsCvtPte2CacheFlagsToMMUFlags(flags);
+ if (mmuFlags == LOS_ERRNO_VM_INVALID_ARGS) {
+ return mmuFlags;
+ }
+
+ mmuFlags |= OsCvtPte2AccessFlagsToMMUFlags(flags);
+
+ if (!(flags & VM_MAP_REGION_FLAG_PERM_EXECUTE)) {
+ mmuFlags |= MMU_DESCRIPTOR_L2_TYPE_SMALL_PAGE_XN;
+ } else {
+ mmuFlags |= MMU_DESCRIPTOR_L2_TYPE_SMALL_PAGE;
+ }
+
+ if (flags & VM_MAP_REGION_FLAG_PERM_USER) {
+ mmuFlags |= MMU_DESCRIPTOR_L2_NON_GLOBAL;
+ }
+
+ return mmuFlags;
+}
+
+STATIC UINT32 OsMapL1PTE(MmuMapInfo *mmuMapInfo, PTE_T *l1Entry, UINT32 *count)
+{
+ PADDR_T pte2Base = 0;
+ PADDR_T pte1Paddr;
+ SPIN_LOCK_S *pte1Lock = NULL;
+ SPIN_LOCK_S *pte2Lock = NULL;
+ PTE_T *pte2BasePtr = NULL;
+ UINT32 saveCounts, archFlags, pte1IntSave, pte2IntSave;
+
+ pte1Paddr = OsGetPte1Paddr(mmuMapInfo->archMmu->physTtb, *mmuMapInfo->vaddr);
+ pte1Lock = OsGetPte1Lock(mmuMapInfo->archMmu, pte1Paddr, &pte1IntSave);
+ if (!OsIsPte1Invalid(*l1Entry)) {
+ OsUnlockPte1(pte1Lock, pte1IntSave);
+ return 0;
+ }
+ if (OsGetL2Table(mmuMapInfo->archMmu, OsGetPte1Index(*mmuMapInfo->vaddr), &pte2Base) != LOS_OK) {
+ LOS_Panic("%s %d, failed to allocate pagetable\n", __FUNCTION__, __LINE__);
+ }
+
+ *l1Entry = pte2Base | MMU_DESCRIPTOR_L1_TYPE_PAGE_TABLE;
+ if (*mmuMapInfo->flags & VM_MAP_REGION_FLAG_NS) {
+ *l1Entry |= MMU_DESCRIPTOR_L1_PAGETABLE_NON_SECURE;
+ }
+ *l1Entry &= MMU_DESCRIPTOR_L1_SMALL_DOMAIN_MASK;
+ *l1Entry |= MMU_DESCRIPTOR_L1_SMALL_DOMAIN_CLIENT; // use client AP
+ OsSavePte1(OsGetPte1Ptr(mmuMapInfo->archMmu->virtTtb, *mmuMapInfo->vaddr), *l1Entry);
+ OsUnlockPte1(pte1Lock, pte1IntSave);
+
+ pte2Lock = OsGetPte2Lock(mmuMapInfo->archMmu, *l1Entry, &pte2IntSave);
+ if (pte2Lock == NULL) {
+ LOS_Panic("pte2 should not be null!\n");
+ }
+ pte2BasePtr = (PTE_T *)LOS_PaddrToKVaddr(pte2Base);
+
+ /* compute the arch flags for L2 4K pages */
+ archFlags = OsCvtPte2FlagsToAttrs(*mmuMapInfo->flags);
+ saveCounts = OsSavePte2Continuous(pte2BasePtr, OsGetPte2Index(*mmuMapInfo->vaddr), *mmuMapInfo->paddr | archFlags,
+ *count);
+ OsUnlockPte2(pte2Lock, pte2IntSave);
+ *mmuMapInfo->paddr += (saveCounts << MMU_DESCRIPTOR_L2_SMALL_SHIFT);
+ *mmuMapInfo->vaddr += (saveCounts << MMU_DESCRIPTOR_L2_SMALL_SHIFT);
+ *count -= saveCounts;
+ return saveCounts;
+}
+
+STATIC UINT32 OsMapL2PageContinous(MmuMapInfo *mmuMapInfo, PTE_T *pte1, UINT32 *count)
+{
+ PTE_T *pte2BasePtr = NULL;
+ UINT32 archFlags;
+ UINT32 saveCounts;
+ UINT32 intSave;
+ SPIN_LOCK_S *lock = NULL;
+
+ lock = OsGetPte2Lock(mmuMapInfo->archMmu, *pte1, &intSave);
+ if (lock == NULL) {
+ return 0;
+ }
+ pte2BasePtr = OsGetPte2BasePtr(*pte1);
+ if (pte2BasePtr == NULL) {
+ OsUnlockPte2(lock, intSave);
+ return 0;
+ }
+
+ /* compute the arch flags for L2 4K pages */
+ archFlags = OsCvtPte2FlagsToAttrs(*mmuMapInfo->flags);
+ saveCounts = OsSavePte2Continuous(pte2BasePtr, OsGetPte2Index(*mmuMapInfo->vaddr), *mmuMapInfo->paddr | archFlags,
+ *count);
+ OsUnlockPte2(lock, intSave);
+ *mmuMapInfo->paddr += (saveCounts << MMU_DESCRIPTOR_L2_SMALL_SHIFT);
+ *mmuMapInfo->vaddr += (saveCounts << MMU_DESCRIPTOR_L2_SMALL_SHIFT);
+ *count -= saveCounts;
+ return saveCounts;
+}
+
+status_t LOS_ArchMmuMap(LosArchMmu *archMmu, VADDR_T vaddr, PADDR_T paddr, size_t count, UINT32 flags)
+{
+ PTE_T *l1Entry = NULL;
+ UINT32 saveCounts = 0;
+ INT32 mapped = 0;
+ INT32 tryTime = TRY_MAX_TIMES;
+ INT32 checkRst;
+ MmuMapInfo mmuMapInfo = {
+ .archMmu = archMmu,
+ .vaddr = &vaddr,
+ .paddr = &paddr,
+ .flags = &flags,
+ };
+
+ checkRst = OsMapParamCheck(flags, vaddr, paddr);
+ if (checkRst < 0) {
+ return checkRst;
+ }
+
+ /* see what kind of mapping we can use */
+ while (count > 0) {
+ if (MMU_DESCRIPTOR_IS_L1_SIZE_ALIGNED(*mmuMapInfo.vaddr) &&
+ MMU_DESCRIPTOR_IS_L1_SIZE_ALIGNED(*mmuMapInfo.paddr) &&
+ count >= MMU_DESCRIPTOR_L2_NUMBERS_PER_L1) {
+ /* compute the arch flags for L1 sections cache, r ,w ,x, domain and type */
+ saveCounts = OsMapSection(&mmuMapInfo, &count);
+ } else {
+ /* have to use a L2 mapping, we only allocate 4KB for L1, support 0 ~ 1GB */
+ l1Entry = OsGetPte1Ptr(archMmu->virtTtb, *mmuMapInfo.vaddr);
+ if (OsIsPte1Invalid(*l1Entry)) {
+ saveCounts = OsMapL1PTE(&mmuMapInfo, l1Entry, &count);
+ } else if (OsIsPte1PageTable(*l1Entry)) {
+ saveCounts = OsMapL2PageContinous(&mmuMapInfo, l1Entry, &count);
+ } else {
+ LOS_Panic("%s %d, unimplemented tt_entry %x\n", __FUNCTION__, __LINE__, l1Entry);
+ }
+ }
+ mapped += saveCounts;
+ tryTime = (saveCounts == 0) ? (tryTime - 1) : tryTime;
+ if (tryTime == 0) {
+ return LOS_ERRNO_VM_TIMED_OUT;
+ }
+ }
+
+ return mapped;
+}
+
+STATUS_T LOS_ArchMmuChangeProt(LosArchMmu *archMmu, VADDR_T vaddr, size_t count, UINT32 flags)
+{
+ STATUS_T status;
+ PADDR_T paddr = 0;
+
+ if ((archMmu == NULL) || (vaddr == 0) || (count == 0)) {
+ VM_ERR("invalid args: archMmu %p, vaddr %p, count %d", archMmu, vaddr, count);
+ return LOS_NOK;
+ }
+
+ while (count > 0) {
+ count--;
+ status = LOS_ArchMmuQuery(archMmu, vaddr, &paddr, NULL);
+ if (status != LOS_OK) {
+ vaddr += MMU_DESCRIPTOR_L2_SMALL_SIZE;
+ continue;
+ }
+
+ status = LOS_ArchMmuUnmap(archMmu, vaddr, 1);
+ if (status < 0) {
+ VM_ERR("invalid args:aspace %p, vaddr %p, count %d", archMmu, vaddr, count);
+ return LOS_NOK;
+ }
+
+ status = LOS_ArchMmuMap(archMmu, vaddr, paddr, 1, flags);
+ if (status < 0) {
+ VM_ERR("invalid args:aspace %p, vaddr %p, count %d",
+ archMmu, vaddr, count);
+ return LOS_NOK;
+ }
+ vaddr += MMU_DESCRIPTOR_L2_SMALL_SIZE;
+ }
+ return LOS_OK;
+}
+
+STATUS_T LOS_ArchMmuMove(LosArchMmu *archMmu, VADDR_T oldVaddr, VADDR_T newVaddr, size_t count, UINT32 flags)
+{
+ STATUS_T status;
+ PADDR_T paddr = 0;
+
+ if ((archMmu == NULL) || (oldVaddr == 0) || (newVaddr == 0) || (count == 0)) {
+ VM_ERR("invalid args: archMmu %p, oldVaddr %p, newVaddr %p, count %d",
+ archMmu, oldVaddr, newVaddr, count);
+ return LOS_NOK;
+ }
+
+ while (count > 0) {
+ count--;
+ status = LOS_ArchMmuQuery(archMmu, oldVaddr, &paddr, NULL);
+ if (status != LOS_OK) {
+ oldVaddr += MMU_DESCRIPTOR_L2_SMALL_SIZE;
+ newVaddr += MMU_DESCRIPTOR_L2_SMALL_SIZE;
+ continue;
+ }
+ // we need to clear the mapping here and remain the phy page.
+ status = LOS_ArchMmuUnmap(archMmu, oldVaddr, 1);
+ if (status < 0) {
+ VM_ERR("invalid args: archMmu %p, vaddr %p, count %d",
+ archMmu, oldVaddr, count);
+ return LOS_NOK;
+ }
+
+ status = LOS_ArchMmuMap(archMmu, newVaddr, paddr, 1, flags);
+ if (status < 0) {
+ VM_ERR("invalid args:archMmu %p, old_vaddr %p, new_addr %p, count %d",
+ archMmu, oldVaddr, newVaddr, count);
+ return LOS_NOK;
+ }
+ oldVaddr += MMU_DESCRIPTOR_L2_SMALL_SIZE;
+ newVaddr += MMU_DESCRIPTOR_L2_SMALL_SIZE;
+ }
+
+ return LOS_OK;
+}
+
+VOID LOS_ArchMmuContextSwitch(LosArchMmu *archMmu)
+{
+ UINT32 ttbr;
+ UINT32 ttbcr = OsArmReadTtbcr();
+ if (archMmu) {
+ ttbr = MMU_TTBRx_FLAGS | (archMmu->physTtb);
+ /* enable TTBR0 */
+ ttbcr &= ~MMU_DESCRIPTOR_TTBCR_PD0;
+ } else {
+ ttbr = 0;
+ /* disable TTBR0 */
+ ttbcr |= MMU_DESCRIPTOR_TTBCR_PD0;
+ }
+
+#ifdef LOSCFG_KERNEL_VM
+ /* from armv7a arm B3.10.4, we should do synchronization changes of ASID and TTBR. */
+ OsArmWriteContextidr(LOS_GetKVmSpace()->archMmu.asid);
+ ISB;
+#endif
+ OsArmWriteTtbr0(ttbr);
+ ISB;
+ OsArmWriteTtbcr(ttbcr);
+ ISB;
+#ifdef LOSCFG_KERNEL_VM
+ if (archMmu) {
+ OsArmWriteContextidr(archMmu->asid);
+ ISB;
+ }
+#endif
+}
+
+STATUS_T LOS_ArchMmuDestroy(LosArchMmu *archMmu)
+{
+#ifdef LOSCFG_KERNEL_VM
+ LosVmPage *page = NULL;
+ /* free all of the pages allocated in archMmu->ptList */
+ while ((page = LOS_ListRemoveHeadType(&archMmu->ptList, LosVmPage, node)) != NULL) {
+ LOS_PhysPageFree(page);
+ }
+
+ OsArmWriteTlbiasidis(archMmu->asid);
+ OsFreeAsid(archMmu->asid);
+#endif
+ return LOS_OK;
+}
+
+STATIC VOID OsSwitchTmpTTB(VOID)
+{
+ PTE_T *tmpTtbase = NULL;
+ errno_t err;
+ LosVmSpace *kSpace = LOS_GetKVmSpace();
+
+ /* ttbr address should be 16KByte align */
+ tmpTtbase = LOS_MemAllocAlign(m_aucSysMem0, MMU_DESCRIPTOR_L1_SMALL_ENTRY_NUMBERS,
+ MMU_DESCRIPTOR_L1_SMALL_ENTRY_NUMBERS);
+ if (tmpTtbase == NULL) {
+ VM_ERR("memory alloc failed");
+ return;
+ }
+
+ kSpace->archMmu.virtTtb = tmpTtbase;
+ err = memcpy_s(kSpace->archMmu.virtTtb, MMU_DESCRIPTOR_L1_SMALL_ENTRY_NUMBERS,
+ g_firstPageTable, MMU_DESCRIPTOR_L1_SMALL_ENTRY_NUMBERS);
+ if (err != EOK) {
+ (VOID)LOS_MemFree(m_aucSysMem0, tmpTtbase);
+ kSpace->archMmu.virtTtb = (VADDR_T *)g_firstPageTable;
+ VM_ERR("memcpy failed, errno: %d", err);
+ return;
+ }
+ kSpace->archMmu.physTtb = LOS_PaddrQuery(kSpace->archMmu.virtTtb);
+ OsArmWriteTtbr0(kSpace->archMmu.physTtb | MMU_TTBRx_FLAGS);
+ ISB;
+}
+
+STATIC VOID OsSetKSectionAttr(UINTPTR virtAddr, BOOL uncached)
+{
+ UINT32 offset = virtAddr - KERNEL_VMM_BASE;
+ /* every section should be page aligned */
+ UINTPTR textStart = (UINTPTR)&__text_start + offset;
+ UINTPTR textEnd = (UINTPTR)&__text_end + offset;
+ UINTPTR rodataStart = (UINTPTR)&__rodata_start + offset;
+ UINTPTR rodataEnd = (UINTPTR)&__rodata_end + offset;
+ UINTPTR ramDataStart = (UINTPTR)&__ram_data_start + offset;
+ UINTPTR bssEnd = (UINTPTR)&__bss_end + offset;
+ UINT32 bssEndBoundary = ROUNDUP(bssEnd, MB);
+ LosArchMmuInitMapping mmuKernelMappings[] = {
+ {
+ .phys = SYS_MEM_BASE + textStart - virtAddr,
+ .virt = textStart,
+ .size = ROUNDUP(textEnd - textStart, MMU_DESCRIPTOR_L2_SMALL_SIZE),
+ .flags = VM_MAP_REGION_FLAG_PERM_READ | VM_MAP_REGION_FLAG_PERM_EXECUTE,
+ .name = "kernel_text"
+ },
+ {
+ .phys = SYS_MEM_BASE + rodataStart - virtAddr,
+ .virt = rodataStart,
+ .size = ROUNDUP(rodataEnd - rodataStart, MMU_DESCRIPTOR_L2_SMALL_SIZE),
+ .flags = VM_MAP_REGION_FLAG_PERM_READ,
+ .name = "kernel_rodata"
+ },
+ {
+ .phys = SYS_MEM_BASE + ramDataStart - virtAddr,
+ .virt = ramDataStart,
+ .size = ROUNDUP(bssEndBoundary - ramDataStart, MMU_DESCRIPTOR_L2_SMALL_SIZE),
+ .flags = VM_MAP_REGION_FLAG_PERM_READ | VM_MAP_REGION_FLAG_PERM_WRITE,
+ .name = "kernel_data_bss"
+ }
+ };
+ LosVmSpace *kSpace = LOS_GetKVmSpace();
+ status_t status;
+ UINT32 length;
+ INT32 i;
+ LosArchMmuInitMapping *kernelMap = NULL;
+ UINT32 kmallocLength;
+ UINT32 flags;
+
+ /* use second-level mapping of default READ and WRITE */
+ kSpace->archMmu.virtTtb = (PTE_T *)g_firstPageTable;
+ kSpace->archMmu.physTtb = LOS_PaddrQuery(kSpace->archMmu.virtTtb);
+ status = LOS_ArchMmuUnmap(&kSpace->archMmu, virtAddr,
+ (bssEndBoundary - virtAddr) >> MMU_DESCRIPTOR_L2_SMALL_SHIFT);
+ if (status != ((bssEndBoundary - virtAddr) >> MMU_DESCRIPTOR_L2_SMALL_SHIFT)) {
+ VM_ERR("unmap failed, status: %d", status);
+ return;
+ }
+
+ flags = VM_MAP_REGION_FLAG_PERM_READ | VM_MAP_REGION_FLAG_PERM_WRITE | VM_MAP_REGION_FLAG_PERM_EXECUTE;
+ if (uncached) {
+ flags |= VM_MAP_REGION_FLAG_UNCACHED;
+ }
+ status = LOS_ArchMmuMap(&kSpace->archMmu, virtAddr, SYS_MEM_BASE,
+ (textStart - virtAddr) >> MMU_DESCRIPTOR_L2_SMALL_SHIFT,
+ flags);
+ if (status != ((textStart - virtAddr) >> MMU_DESCRIPTOR_L2_SMALL_SHIFT)) {
+ VM_ERR("mmap failed, status: %d", status);
+ return;
+ }
+
+ length = sizeof(mmuKernelMappings) / sizeof(LosArchMmuInitMapping);
+ for (i = 0; i < length; i++) {
+ kernelMap = &mmuKernelMappings[i];
+ if (uncached) {
+ kernelMap->flags |= VM_MAP_REGION_FLAG_UNCACHED;
+ }
+ status = LOS_ArchMmuMap(&kSpace->archMmu, kernelMap->virt, kernelMap->phys,
+ kernelMap->size >> MMU_DESCRIPTOR_L2_SMALL_SHIFT, kernelMap->flags);
+ if (status != (kernelMap->size >> MMU_DESCRIPTOR_L2_SMALL_SHIFT)) {
+ VM_ERR("mmap failed, status: %d", status);
+ return;
+ }
+ LOS_VmSpaceReserve(kSpace, kernelMap->size, kernelMap->virt);
+ }
+
+ kmallocLength = virtAddr + SYS_MEM_SIZE_DEFAULT - bssEndBoundary;
+ flags = VM_MAP_REGION_FLAG_PERM_READ | VM_MAP_REGION_FLAG_PERM_WRITE;
+ if (uncached) {
+ flags |= VM_MAP_REGION_FLAG_UNCACHED;
+ }
+ status = LOS_ArchMmuMap(&kSpace->archMmu, bssEndBoundary,
+ SYS_MEM_BASE + bssEndBoundary - virtAddr,
+ kmallocLength >> MMU_DESCRIPTOR_L2_SMALL_SHIFT,
+ flags);
+ if (status != (kmallocLength >> MMU_DESCRIPTOR_L2_SMALL_SHIFT)) {
+ VM_ERR("mmap failed, status: %d", status);
+ return;
+ }
+ LOS_VmSpaceReserve(kSpace, kmallocLength, bssEndBoundary);
+}
+
+STATIC VOID OsKSectionNewAttrEnable(VOID)
+{
+ LosVmSpace *kSpace = LOS_GetKVmSpace();
+ paddr_t oldTtPhyBase;
+
+ kSpace->archMmu.virtTtb = (PTE_T *)g_firstPageTable;
+ kSpace->archMmu.physTtb = LOS_PaddrQuery(kSpace->archMmu.virtTtb);
+
+ /* we need free tmp ttbase */
+ oldTtPhyBase = OsArmReadTtbr0();
+ oldTtPhyBase = oldTtPhyBase & MMU_DESCRIPTOR_L2_SMALL_FRAME;
+ OsArmWriteTtbr0(kSpace->archMmu.physTtb | MMU_TTBRx_FLAGS);
+ ISB;
+
+ /* we changed page table entry, so we need to clean TLB here */
+ OsCleanTLB();
+
+ (VOID)LOS_MemFree(m_aucSysMem0, (VOID *)(UINTPTR)(oldTtPhyBase - SYS_MEM_BASE + KERNEL_VMM_BASE));
+}
+
+/* disable TTBCR0 and set the split between TTBR0 and TTBR1 */
+VOID OsArchMmuInitPerCPU(VOID)
+{
+ UINT32 n = __builtin_clz(KERNEL_ASPACE_BASE) + 1;
+ UINT32 ttbcr = MMU_DESCRIPTOR_TTBCR_PD0 | n;
+
+ OsArmWriteTtbr1(OsArmReadTtbr0());
+ ISB;
+ OsArmWriteTtbcr(ttbcr);
+ ISB;
+ OsArmWriteTtbr0(0);
+ ISB;
+}
+
+VOID OsInitMappingStartUp(VOID)
+{
+ OsArmInvalidateTlbBarrier();
+
+ OsSwitchTmpTTB();
+
+ OsSetKSectionAttr(KERNEL_VMM_BASE, FALSE);
+ OsSetKSectionAttr(UNCACHED_VMM_BASE, TRUE);
+ OsKSectionNewAttrEnable();
+}
+#endif
+
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/los_asid.c b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/los_asid.c
new file mode 100644
index 00000000..30fd6331
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/los_asid.c
@@ -0,0 +1,73 @@
+/*
+ * 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.
+ */
+
+/**
+ * @defgroup los_asid mmu address space id
+ * @ingroup kernel
+ */
+
+#include "los_asid.h"
+#include "los_bitmap.h"
+#include "los_spinlock.h"
+#include "los_mmu_descriptor_v6.h"
+
+
+#ifdef LOSCFG_KERNEL_VM
+
+STATIC SPIN_LOCK_INIT(g_cpuAsidLock);
+STATIC UINTPTR g_asidPool[BITMAP_NUM_WORDS(1UL << MMU_ARM_ASID_BITS)];
+
+/* allocate and free asid */
+status_t OsAllocAsid(UINT32 *asid)
+{
+ UINT32 flags;
+ LOS_SpinLockSave(&g_cpuAsidLock, &flags);
+ UINT32 firstZeroBit = LOS_BitmapFfz(g_asidPool, 1UL << MMU_ARM_ASID_BITS);
+ if (firstZeroBit >= 0 && firstZeroBit < (1UL << MMU_ARM_ASID_BITS)) {
+ LOS_BitmapSetNBits(g_asidPool, firstZeroBit, 1);
+ *asid = firstZeroBit;
+ LOS_SpinUnlockRestore(&g_cpuAsidLock, flags);
+ return LOS_OK;
+ }
+
+ LOS_SpinUnlockRestore(&g_cpuAsidLock, flags);
+ return firstZeroBit;
+}
+
+VOID OsFreeAsid(UINT32 asid)
+{
+ UINT32 flags;
+ LOS_SpinLockSave(&g_cpuAsidLock, &flags);
+ LOS_BitmapClrNBits(g_asidPool, asid, 1);
+ LOS_SpinUnlockRestore(&g_cpuAsidLock, flags);
+}
+#endif
+
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/los_dispatch.S b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/los_dispatch.S
new file mode 100644
index 00000000..797d1677
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/los_dispatch.S
@@ -0,0 +1,234 @@
+/*
+ * 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 "asm.h"
+#include "arch_config.h"
+
+ .extern OsSaveSignalContext
+ .extern OsSchedToUserReleaseLock
+ .global OsTaskSchedule
+ .global OsTaskContextLoad
+ .global OsIrqHandler
+
+ .fpu vfpv4
+
+/* macros to align and unalign the stack on 8 byte boundary for ABI compliance */
+.macro STACK_ALIGN, reg
+ MOV \reg, sp
+ TST SP, #4
+ SUBEQ SP, #4
+ PUSH { \reg }
+.endm
+
+.macro STACK_RESTORE, reg
+ POP { \reg }
+ MOV sp, \reg
+.endm
+
+/* macros to save and restore fpu regs */
+.macro PUSH_FPU_REGS reg1
+#if !defined(LOSCFG_ARCH_FPU_DISABLE)
+ VMRS \reg1, FPEXC
+ PUSH {\reg1}
+ VMRS \reg1, FPSCR
+ PUSH {\reg1}
+#if defined(LOSCFG_ARCH_FPU_VFP_D32)
+ VPUSH {D16-D31}
+#endif
+ VPUSH {D0-D15}
+#endif
+.endm
+
+.macro POP_FPU_REGS reg1
+#if !defined(LOSCFG_ARCH_FPU_DISABLE)
+ VPOP {D0-D15}
+#if defined(LOSCFG_ARCH_FPU_VFP_D32)
+ VPOP {D16-D31}
+#endif
+ POP {\reg1}
+ VMSR FPSCR, \reg1
+ POP {\reg1}
+ VMSR FPEXC, \reg1
+#endif
+.endm
+
+/*
+ * R0: new task
+ * R1: run task
+ */
+OsTaskSchedule:
+ MRS R2, CPSR
+ STMFD SP!, {R2}
+ STMFD SP!, {LR}
+ STMFD SP!, {LR}
+ STMFD SP!, {R12}
+
+ /* jump R0 - R3 USP, ULR reserved */
+ SUB SP, SP, #(8 * 4)
+
+ /* push R4 - R11*/
+ STMFD SP!, {R4-R11}
+
+ /* save fpu registers */
+ PUSH_FPU_REGS R2
+
+ /* store sp on running task */
+ STR SP, [R1]
+
+OsTaskContextLoad:
+ /* clear the flag of ldrex */
+ CLREX
+
+ /* switch to new task's sp */
+ LDR SP, [R0]
+
+ /* restore fpu registers */
+ POP_FPU_REGS R2
+
+ LDMFD SP!, {R4-R11}
+ LDR R3, [SP, #(11 * 4)]
+ AND R0, R3, #CPSR_MASK_MODE
+ CMP R0, #CPSR_USER_MODE
+ BNE OsKernelTaskLoad
+
+ MVN R2, #CPSR_INT_DISABLE
+ AND R3, R3, R2
+ STR R3, [SP, #(11 * 4)]
+
+#ifdef LOSCFG_KERNEL_SMP
+ BL OsSchedToUserReleaseLock
+#endif
+
+ /* jump sp, reserved */
+ ADD SP, SP, #(2 * 4)
+ LDMFD SP, {R13, R14}^
+ ADD SP, SP, #(2 * 4)
+ LDMFD SP!, {R0-R3, R12, LR}
+ RFEIA SP!
+
+OsKernelTaskLoad:
+ ADD SP, SP, #(4 * 4)
+ LDMFD SP!, {R0-R3, R12, LR}
+ RFEIA SP!
+
+OsIrqHandler:
+ SUB LR, LR, #4
+
+ /* Save pc and cpsr to svc sp, ARMv6 and above support */
+ SRSFD #0x13!
+ /* disable irq, switch to svc mode */
+ CPSID i, #0x13
+
+#ifdef LOSCFG_KERNEL_PERF
+ PUSH {R0-R3, R12, LR}
+ MOV R0, LR
+ MOV R1, FP
+ BL OsPerfSetIrqRegs
+ POP {R0-R3, R12, LR}
+#endif
+
+ STMFD SP!, {R0-R3, R12, LR}
+ STMFD SP, {R13, R14}^
+ SUB SP, SP, #(4 * 4)
+ STR R4, [SP, #0]
+
+ /*
+ * save fpu regs in case in case those been
+ * altered in interrupt handlers.
+ */
+ PUSH_FPU_REGS R0
+
+ MOV R4, SP
+ EXC_SP_SET __svc_stack_top, OS_EXC_SVC_STACK_SIZE, R1, R2
+
+ BLX HalIrqHandler
+
+ MOV SP, R4
+
+ /* process pending signals */
+ BLX OsTaskProcSignal
+ BLX OsSchedIrqEndCheckNeedSched
+
+ /* restore fpu regs */
+ POP_FPU_REGS R0
+ LDR R4, [SP, #0]
+
+#ifdef LOSCFG_KERNEL_VM
+ /* Obtain the CPSR to determine the mode the system is in when the interrupt is triggered */
+ LDR R3, [SP, #(11 * 4)]
+ AND R1, R3, #CPSR_MASK_MODE
+ CMP R1, #CPSR_USER_MODE
+ BNE 1f
+
+ MOV R0, SP
+ STR R7, [SP, #0]
+ /* sp - sizeof(IrqContext) */
+ SUB SP, SP, #(12 * 4)
+ MOV R1, SP
+ BLX OsSaveSignalContext
+ MOV SP, R0
+1:
+#endif
+ ADD SP, SP, #(2 * 4)
+ /* load user sp and lr, and jump cpsr */
+ LDMFD SP, {R13, R14}^
+ ADD SP, SP, #(2 * 4)
+ LDMFD SP!, {R0-R3, R12, LR}
+ RFEIA SP!
+
+FUNCTION(ArchSpinLock)
+ mov r1, #1
+1:
+ ldrex r2, [r0]
+ cmp r2, #0
+ wfene
+ strexeq r2, r1, [r0]
+ cmpeq r2, #0
+ bne 1b
+ dmb
+ bx lr
+
+FUNCTION(ArchSpinTrylock)
+ mov r1, #1
+ mov r2, r0
+ ldrex r0, [r2]
+ cmp r0, #0
+ strexeq r0, r1, [r2]
+ dmb
+ bx lr
+
+FUNCTION(ArchSpinUnlock)
+ mov r1, #0
+ dmb
+ str r1, [r0]
+ dsb
+ sev
+ bx lr
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/los_exc.c b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/los_exc.c
new file mode 100644
index 00000000..672e9396
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/los_exc.c
@@ -0,0 +1,1284 @@
+/*
+ * 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_exc.h"
+#include "los_memory_pri.h"
+#include "los_printf_pri.h"
+#include "los_task_pri.h"
+#include "los_percpu_pri.h"
+#include "los_hw_pri.h"
+#ifdef LOSCFG_SAVE_EXCINFO
+#include "los_excinfo_pri.h"
+#endif
+#include "los_sys_stack_pri.h"
+#ifdef LOSCFG_COREDUMP
+#include "los_coredump.h"
+#endif
+#ifdef LOSCFG_GDB
+#include "gdb_int.h"
+#endif
+#include "los_mp.h"
+#include "los_vm_map.h"
+#include "los_vm_dump.h"
+#include "los_arch_mmu.h"
+#include "los_vm_phys.h"
+#include "los_vm_fault.h"
+#include "los_vm_common.h"
+#ifdef LOSCFG_KERNEL_DYNLOAD
+#include "los_load_elf.h"
+#endif
+#include "arm.h"
+#include "los_bitmap.h"
+#include "los_process_pri.h"
+#include "los_exc_pri.h"
+#include "los_sched_pri.h"
+#ifdef LOSCFG_FS_VFS
+#include "console.h"
+#endif
+#ifdef LOSCFG_BLACKBOX
+#include "los_blackbox.h"
+#endif
+
+
+#define INVALID_CPUID 0xFFFF
+#define OS_EXC_VMM_NO_REGION 0x0U
+#define OS_EXC_VMM_ALL_REGION 0x1U
+
+STATIC UINTPTR g_minAddr;
+STATIC UINTPTR g_maxAddr;
+STATIC UINT32 g_currHandleExcCpuID = INVALID_CPUID;
+VOID OsExcHook(UINT32 excType, ExcContext *excBufAddr, UINT32 far, UINT32 fsr);
+UINT32 g_curNestCount[LOSCFG_KERNEL_CORE_NUM] = { 0 };
+BOOL g_excFromUserMode[LOSCFG_KERNEL_CORE_NUM];
+STATIC EXC_PROC_FUNC g_excHook = (EXC_PROC_FUNC)OsExcHook;
+#ifdef LOSCFG_KERNEL_SMP
+STATIC SPIN_LOCK_INIT(g_excSerializerSpin);
+STATIC UINT32 g_currHandleExcPID = OS_INVALID_VALUE;
+STATIC UINT32 g_nextExcWaitCpu = INVALID_CPUID;
+#endif
+
+#define OS_MAX_BACKTRACE 15U
+#define DUMPSIZE 128U
+#define DUMPREGS 12U
+#define INSTR_SET_MASK 0x01000020U
+#define THUMB_INSTR_LEN 2U
+#define ARM_INSTR_LEN 4U
+#define POINTER_SIZE 4U
+#define WNR_BIT 11U
+#define FSR_FLAG_OFFSET_BIT 10U
+#define FSR_BITS_BEGIN_BIT 3U
+
+
+#define GET_FS(fsr) (((fsr) & 0xFU) | (((fsr) & (1U << 10)) >> 6))
+#define GET_WNR(dfsr) ((dfsr) & (1U << 11))
+
+#define IS_VALID_ADDR(ptr) (((ptr) >= g_minAddr) && \
+ ((ptr) <= g_maxAddr) && \
+ (IS_ALIGNED((ptr), sizeof(CHAR *))))
+
+STATIC const StackInfo g_excStack[] = {
+ { &__svc_stack, OS_EXC_SVC_STACK_SIZE, "svc_stack" },
+ { &__exc_stack, OS_EXC_STACK_SIZE, "exc_stack" }
+};
+
+UINT32 OsGetSystemStatus(VOID)
+{
+ UINT32 flag;
+ UINT32 cpuID = g_currHandleExcCpuID;
+
+ if (cpuID == INVALID_CPUID) {
+ flag = OS_SYSTEM_NORMAL;
+ } else if (cpuID == ArchCurrCpuid()) {
+ flag = OS_SYSTEM_EXC_CURR_CPU;
+ } else {
+ flag = OS_SYSTEM_EXC_OTHER_CPU;
+ }
+
+ return flag;
+}
+
+STATIC INT32 OsDecodeFS(UINT32 bitsFS)
+{
+ switch (bitsFS) {
+ case 0x05: /* 0b00101 */
+ case 0x07: /* 0b00111 */
+ PrintExcInfo("Translation fault, %s\n", (bitsFS & 0x2) ? "page" : "section");
+ break;
+ case 0x09: /* 0b01001 */
+ case 0x0b: /* 0b01011 */
+ PrintExcInfo("Domain fault, %s\n", (bitsFS & 0x2) ? "page" : "section");
+ break;
+ case 0x0d: /* 0b01101 */
+ case 0x0f: /* 0b01111 */
+ PrintExcInfo("Permission fault, %s\n", (bitsFS & 0x2) ? "page" : "section");
+ break;
+ default:
+ PrintExcInfo("Unknown fault! FS:0x%x. "
+ "Check IFSR and DFSR in ARM Architecture Reference Manual.\n",
+ bitsFS);
+ break;
+ }
+
+ return LOS_OK;
+}
+
+STATIC INT32 OsDecodeInstructionFSR(UINT32 regIFSR)
+{
+ INT32 ret;
+ UINT32 bitsFS = GET_FS(regIFSR); /* FS bits[4]+[3:0] */
+
+ ret = OsDecodeFS(bitsFS);
+ return ret;
+}
+
+STATIC INT32 OsDecodeDataFSR(UINT32 regDFSR)
+{
+ INT32 ret = 0;
+ UINT32 bitWnR = GET_WNR(regDFSR); /* WnR bit[11] */
+ UINT32 bitsFS = GET_FS(regDFSR); /* FS bits[4]+[3:0] */
+
+ if (bitWnR) {
+ PrintExcInfo("Abort caused by a write instruction. ");
+ } else {
+ PrintExcInfo("Abort caused by a read instruction. ");
+ }
+
+ if (bitsFS == 0x01) { /* 0b00001 */
+ PrintExcInfo("Alignment fault.\n");
+ return ret;
+ }
+ ret = OsDecodeFS(bitsFS);
+ return ret;
+}
+
+#ifdef LOSCFG_KERNEL_VM
+UINT32 OsArmSharedPageFault(UINT32 excType, ExcContext *frame, UINT32 far, UINT32 fsr)
+{
+ BOOL instructionFault = FALSE;
+ UINT32 pfFlags = 0;
+ UINT32 fsrFlag;
+ BOOL write = FALSE;
+ UINT32 ret;
+
+ PRINT_INFO("page fault entry!!!\n");
+ if (OsGetSystemStatus() == OS_SYSTEM_EXC_CURR_CPU) {
+ return LOS_ERRNO_VM_NOT_FOUND;
+ }
+#if defined(LOSCFG_KERNEL_SMP) && defined(LOSCFG_DEBUG_VERSION)
+ BOOL irqEnable = !(LOS_SpinHeld(&g_taskSpin) && OsSchedIsLock());
+ if (irqEnable) {
+ ArchIrqEnable();
+ } else {
+ PrintExcInfo("[ERR][%s] may be held scheduler lock when entering [%s] on cpu [%u]\n",
+ OsCurrTaskGet()->taskName, __FUNCTION__, ArchCurrCpuid());
+ }
+#else
+ ArchIrqEnable();
+#endif
+ if (excType == OS_EXCEPT_PREFETCH_ABORT) {
+ instructionFault = TRUE;
+ } else {
+ write = !!BIT_GET(fsr, WNR_BIT);
+ }
+
+ fsrFlag = ((BIT_GET(fsr, FSR_FLAG_OFFSET_BIT) ? 0b10000 : 0) | BITS_GET(fsr, FSR_BITS_BEGIN_BIT, 0));
+ switch (fsrFlag) {
+ case 0b00101:
+ /* translation fault */
+ case 0b00111:
+ /* translation fault */
+ case 0b01101:
+ /* permission fault */
+ case 0b01111: {
+ /* permission fault */
+ BOOL user = (frame->regCPSR & CPSR_MODE_MASK) == CPSR_MODE_USR;
+ pfFlags |= write ? VM_MAP_PF_FLAG_WRITE : 0;
+ pfFlags |= user ? VM_MAP_PF_FLAG_USER : 0;
+ pfFlags |= instructionFault ? VM_MAP_PF_FLAG_INSTRUCTION : 0;
+ pfFlags |= VM_MAP_PF_FLAG_NOT_PRESENT;
+ OsSigIntLock();
+ ret = OsVmPageFaultHandler(far, pfFlags, frame);
+ OsSigIntUnlock();
+ break;
+ }
+ default:
+ OsArmWriteTlbimvaais(ROUNDDOWN(far, PAGE_SIZE));
+ ret = LOS_OK;
+ break;
+ }
+#if defined(LOSCFG_KERNEL_SMP) && defined(LOSCFG_DEBUG_VERSION)
+ if (irqEnable) {
+ ArchIrqDisable();
+ }
+#else
+ ArchIrqDisable();
+#endif
+ return ret;
+}
+#endif
+
+STATIC VOID OsExcType(UINT32 excType, ExcContext *excBufAddr, UINT32 far, UINT32 fsr)
+{
+ /* undefined exception handling or software interrupt */
+ if ((excType == OS_EXCEPT_UNDEF_INSTR) || (excType == OS_EXCEPT_SWI)) {
+ if ((excBufAddr->regCPSR & INSTR_SET_MASK) == 0) { /* work status: ARM */
+ excBufAddr->PC = excBufAddr->PC - ARM_INSTR_LEN;
+ } else if ((excBufAddr->regCPSR & INSTR_SET_MASK) == 0x20) { /* work status: Thumb */
+ excBufAddr->PC = excBufAddr->PC - THUMB_INSTR_LEN;
+ }
+ }
+
+ if (excType == OS_EXCEPT_PREFETCH_ABORT) {
+ PrintExcInfo("prefetch_abort fault fsr:0x%x, far:0x%0+8x\n", fsr, far);
+ (VOID)OsDecodeInstructionFSR(fsr);
+ } else if (excType == OS_EXCEPT_DATA_ABORT) {
+ PrintExcInfo("data_abort fsr:0x%x, far:0x%0+8x\n", fsr, far);
+ (VOID)OsDecodeDataFSR(fsr);
+ }
+}
+
+STATIC const CHAR *g_excTypeString[] = {
+ "reset",
+ "undefined instruction",
+ "software interrupt",
+ "prefetch abort",
+ "data abort",
+ "fiq",
+ "address abort",
+ "irq"
+};
+
+#ifdef LOSCFG_KERNEL_VM
+STATIC VADDR_T OsGetTextRegionBase(LosVmMapRegion *region, LosProcessCB *runProcess)
+{
+ struct Vnode *curVnode = NULL;
+ struct Vnode *lastVnode = NULL;
+ LosVmMapRegion *curRegion = NULL;
+ LosVmMapRegion *lastRegion = NULL;
+
+ if ((region == NULL) || (runProcess == NULL)) {
+ return 0;
+ }
+
+ if (!LOS_IsRegionFileValid(region)) {
+ return region->range.base;
+ }
+
+ lastRegion = region;
+ do {
+ curRegion = lastRegion;
+ lastRegion = LOS_RegionFind(runProcess->vmSpace, curRegion->range.base - 1);
+ if ((lastRegion == NULL) || !LOS_IsRegionFileValid(lastRegion)) {
+ goto DONE;
+ }
+ curVnode = curRegion->unTypeData.rf.vnode;
+ lastVnode = lastRegion->unTypeData.rf.vnode;
+ } while (curVnode == lastVnode);
+
+DONE:
+#ifdef LOSCFG_KERNEL_DYNLOAD
+ if (curRegion->range.base == EXEC_MMAP_BASE) {
+ return 0;
+ }
+#endif
+ return curRegion->range.base;
+}
+#endif
+
+STATIC VOID OsExcSysInfo(UINT32 excType, const ExcContext *excBufAddr)
+{
+ LosTaskCB *runTask = OsCurrTaskGet();
+ LosProcessCB *runProcess = OsCurrProcessGet();
+
+ PrintExcInfo("excType: %s\n"
+ "processName = %s\n"
+ "processID = %u\n"
+#ifdef LOSCFG_KERNEL_VM
+ "process aspace = 0x%08x -> 0x%08x\n"
+#endif
+ "taskName = %s\n"
+ "taskID = %u\n",
+ g_excTypeString[excType],
+ runProcess->processName,
+ runProcess->processID,
+#ifdef LOSCFG_KERNEL_VM
+ runProcess->vmSpace->base,
+ runProcess->vmSpace->base + runProcess->vmSpace->size,
+#endif
+ runTask->taskName,
+ runTask->taskID);
+
+#ifdef LOSCFG_KERNEL_VM
+ if (OsProcessIsUserMode(runProcess)) {
+ PrintExcInfo("task user stack = 0x%08x -> 0x%08x\n",
+ runTask->userMapBase, runTask->userMapBase + runTask->userMapSize);
+ } else
+#endif
+ {
+ PrintExcInfo("task kernel stack = 0x%08x -> 0x%08x\n",
+ runTask->topOfStack, runTask->topOfStack + runTask->stackSize);
+ }
+
+ PrintExcInfo("pc = 0x%x ", excBufAddr->PC);
+#ifdef LOSCFG_KERNEL_VM
+ LosVmMapRegion *region = NULL;
+ if (g_excFromUserMode[ArchCurrCpuid()] == TRUE) {
+ if (LOS_IsUserAddress((vaddr_t)excBufAddr->PC)) {
+ region = LOS_RegionFind(runProcess->vmSpace, (VADDR_T)excBufAddr->PC);
+ if (region != NULL) {
+ PrintExcInfo("in %s ---> 0x%x", OsGetRegionNameOrFilePath(region),
+ (VADDR_T)excBufAddr->PC - OsGetTextRegionBase(region, runProcess));
+ }
+ }
+
+ PrintExcInfo("\nulr = 0x%x ", excBufAddr->ULR);
+ region = LOS_RegionFind(runProcess->vmSpace, (VADDR_T)excBufAddr->ULR);
+ if (region != NULL) {
+ PrintExcInfo("in %s ---> 0x%x", OsGetRegionNameOrFilePath(region),
+ (VADDR_T)excBufAddr->ULR - OsGetTextRegionBase(region, runProcess));
+ }
+ PrintExcInfo("\nusp = 0x%x", excBufAddr->USP);
+ } else
+#endif
+ {
+ PrintExcInfo("\nklr = 0x%x\n"
+ "ksp = 0x%x\n",
+ excBufAddr->LR,
+ excBufAddr->SP);
+ }
+
+ PrintExcInfo("\nfp = 0x%x\n", excBufAddr->R11);
+}
+
+STATIC VOID OsExcRegsInfo(const ExcContext *excBufAddr)
+{
+ /*
+ * Split register information into two parts:
+ * Ensure printing does not rely on memory modules.
+ */
+ PrintExcInfo("R0 = 0x%x\n"
+ "R1 = 0x%x\n"
+ "R2 = 0x%x\n"
+ "R3 = 0x%x\n"
+ "R4 = 0x%x\n"
+ "R5 = 0x%x\n"
+ "R6 = 0x%x\n",
+ excBufAddr->R0, excBufAddr->R1, excBufAddr->R2, excBufAddr->R3,
+ excBufAddr->R4, excBufAddr->R5, excBufAddr->R6);
+ PrintExcInfo("R7 = 0x%x\n"
+ "R8 = 0x%x\n"
+ "R9 = 0x%x\n"
+ "R10 = 0x%x\n"
+ "R11 = 0x%x\n"
+ "R12 = 0x%x\n"
+ "CPSR = 0x%x\n",
+ excBufAddr->R7, excBufAddr->R8, excBufAddr->R9, excBufAddr->R10,
+ excBufAddr->R11, excBufAddr->R12, excBufAddr->regCPSR);
+}
+
+LITE_OS_SEC_TEXT_INIT UINT32 LOS_ExcRegHook(EXC_PROC_FUNC excHook)
+{
+ UINT32 intSave;
+
+ intSave = LOS_IntLock();
+ g_excHook = excHook;
+ LOS_IntRestore(intSave);
+
+ return LOS_OK;
+}
+
+EXC_PROC_FUNC OsExcRegHookGet(VOID)
+{
+ return g_excHook;
+}
+
+#ifdef LOSCFG_KERNEL_VM
+STATIC VOID OsDumpExcVaddrRegion(LosVmSpace *space, LosVmMapRegion *region)
+{
+ INT32 i, numPages, pageCount;
+ paddr_t addr, oldAddr, startVaddr, startPaddr;
+ vaddr_t pageBase;
+ BOOL mmuFlag = FALSE;
+
+ numPages = region->range.size >> PAGE_SHIFT;
+ mmuFlag = TRUE;
+ for (pageCount = 0, startPaddr = 0, startVaddr = 0, i = 0; i < numPages; i++) {
+ pageBase = region->range.base + i * PAGE_SIZE;
+ addr = 0;
+ if (LOS_ArchMmuQuery(&space->archMmu, pageBase, &addr, NULL) != LOS_OK) {
+ if (startPaddr == 0) {
+ continue;
+ }
+ } else if (startPaddr == 0) {
+ startVaddr = pageBase;
+ startPaddr = addr;
+ oldAddr = addr;
+ pageCount++;
+ if (numPages > 1) {
+ continue;
+ }
+ } else if (addr == (oldAddr + PAGE_SIZE)) {
+ pageCount++;
+ oldAddr = addr;
+ if (i < (numPages - 1)) {
+ continue;
+ }
+ }
+ if (mmuFlag == TRUE) {
+ PrintExcInfo(" uvaddr kvaddr mapped size\n");
+ mmuFlag = FALSE;
+ }
+ PrintExcInfo(" 0x%08x 0x%08x 0x%08x\n",
+ startVaddr, LOS_PaddrToKVaddr(startPaddr), (UINT32)pageCount << PAGE_SHIFT);
+ pageCount = 0;
+ startPaddr = 0;
+ }
+}
+
+STATIC VOID OsDumpProcessUsedMemRegion(LosProcessCB *runProcess, LosVmSpace *runspace, UINT16 vmmFlags)
+{
+ LosVmMapRegion *region = NULL;
+ LosRbNode *pstRbNodeTemp = NULL;
+ LosRbNode *pstRbNodeNext = NULL;
+ UINT32 count = 0;
+
+ /* search the region list */
+ RB_SCAN_SAFE(&runspace->regionRbTree, pstRbNodeTemp, pstRbNodeNext)
+ region = (LosVmMapRegion *)pstRbNodeTemp;
+ PrintExcInfo("%3u -> regionBase: 0x%08x regionSize: 0x%08x\n", count, region->range.base, region->range.size);
+ if (vmmFlags == OS_EXC_VMM_ALL_REGION) {
+ OsDumpExcVaddrRegion(runspace, region);
+ }
+ count++;
+ (VOID)OsRegionOverlapCheckUnlock(runspace, region);
+ RB_SCAN_SAFE_END(&space->regionRbTree, pstRbNodeTemp, pstRbNodeNext)
+}
+
+STATIC VOID OsDumpProcessUsedMemNode(UINT16 vmmFlags)
+{
+ LosProcessCB *runProcess = NULL;
+ LosVmSpace *runspace = NULL;
+
+ runProcess = OsCurrProcessGet();
+ if (runProcess == NULL) {
+ return;
+ }
+
+ if (!OsProcessIsUserMode(runProcess)) {
+ return;
+ }
+
+ PrintExcInfo("\n ******Current process %u vmm regions: ******\n", runProcess->processID);
+
+ runspace = runProcess->vmSpace;
+ if (!runspace) {
+ return;
+ }
+
+ OsDumpProcessUsedMemRegion(runProcess, runspace, vmmFlags);
+ return;
+}
+#endif
+
+VOID OsDumpContextMem(const ExcContext *excBufAddr)
+{
+ UINT32 count = 0;
+ const UINT32 *excReg = NULL;
+ if (g_excFromUserMode[ArchCurrCpuid()] == TRUE) {
+ return;
+ }
+
+ for (excReg = &(excBufAddr->R0); count <= DUMPREGS; excReg++, count++) {
+ if (IS_VALID_ADDR(*excReg)) {
+ PrintExcInfo("\ndump mem around R%u:%p", count, (*excReg));
+ OsDumpMemByte(DUMPSIZE, ((*excReg) - (DUMPSIZE >> 1)));
+ }
+ }
+
+ if (IS_VALID_ADDR(excBufAddr->SP)) {
+ PrintExcInfo("\ndump mem around SP:%p", excBufAddr->SP);
+ OsDumpMemByte(DUMPSIZE, (excBufAddr->SP - (DUMPSIZE >> 1)));
+ }
+}
+
+STATIC VOID OsExcRestore(VOID)
+{
+ UINT32 currCpuID = ArchCurrCpuid();
+
+ g_excFromUserMode[currCpuID] = FALSE;
+ g_intCount[currCpuID] = 0;
+ g_curNestCount[currCpuID] = 0;
+#ifdef LOSCFG_KERNEL_SMP
+ OsCpuStatusSet(CPU_RUNNING);
+#endif
+ OsSchedLockSet(0);
+}
+
+STATIC VOID OsUserExcHandle(ExcContext *excBufAddr)
+{
+ UINT32 intSave;
+ UINT32 currCpu = ArchCurrCpuid();
+ LosTaskCB *runTask = OsCurrTaskGet();
+ LosProcessCB *runProcess = OsCurrProcessGet();
+
+ if (g_excFromUserMode[ArchCurrCpuid()] == FALSE) {
+ return;
+ }
+
+#ifdef LOSCFG_KERNEL_SMP
+ LOS_SpinLock(&g_excSerializerSpin);
+ if (g_nextExcWaitCpu != INVALID_CPUID) {
+ g_currHandleExcCpuID = g_nextExcWaitCpu;
+ g_nextExcWaitCpu = INVALID_CPUID;
+ } else {
+ g_currHandleExcCpuID = INVALID_CPUID;
+ }
+ g_currHandleExcPID = OS_INVALID_VALUE;
+ LOS_SpinUnlock(&g_excSerializerSpin);
+#else
+ g_currHandleExcCpuID = INVALID_CPUID;
+#endif
+
+#ifdef LOSCFG_KERNEL_SMP
+#ifdef LOSCFG_FS_VFS
+ OsWakeConsoleSendTask();
+#endif
+#endif
+
+#ifdef LOSCFG_BLACKBOX
+ BBoxNotifyError("USER_CRASH", MODULE_SYSTEM, "Crash in user", 0);
+#endif
+ SCHEDULER_LOCK(intSave);
+#ifdef LOSCFG_SAVE_EXCINFO
+ OsProcessExitCodeCoreDumpSet(runProcess);
+#endif
+ OsProcessExitCodeSignalSet(runProcess, SIGUSR2);
+
+ /* An exception was raised by a task during the exit process of
+ * the current process.
+ */
+ if (runProcess->processStatus & OS_PROCESS_FLAG_EXIT) {
+ SCHEDULER_UNLOCK(intSave);
+ /* Exception handling All operations should be kept prior to that operation */
+ OsExcRestore();
+ OsRunningTaskToExit(runTask, OS_PRO_EXIT_OK);
+ } else {
+ SCHEDULER_UNLOCK(intSave);
+
+ /* Exception handling All operations should be kept prior to that operation */
+ OsExcRestore();
+ /* kill user exc process */
+ LOS_Exit(OS_PRO_EXIT_OK);
+ }
+
+ /* User mode exception handling failed , which normally does not exist */
+ g_curNestCount[currCpu]++;
+ g_intCount[currCpu]++;
+ PrintExcInfo("User mode exception ends unscheduled!\n");
+}
+
+/* this function is used to validate fp or validate the checking range start and end. */
+STATIC INLINE BOOL IsValidFP(UINTPTR regFP, UINTPTR start, UINTPTR end, vaddr_t *vaddr)
+{
+ VADDR_T kvaddr = regFP;
+
+ if (!((regFP > start) && (regFP < end) && IS_ALIGNED(regFP, sizeof(CHAR *)))) {
+ return FALSE;
+ }
+
+#ifdef LOSCFG_KERNEL_VM
+ PADDR_T paddr;
+ if (g_excFromUserMode[ArchCurrCpuid()] == TRUE) {
+ LosProcessCB *runProcess = OsCurrProcessGet();
+ LosVmSpace *runspace = runProcess->vmSpace;
+ if (runspace == NULL) {
+ return FALSE;
+ }
+
+ if (LOS_ArchMmuQuery(&runspace->archMmu, regFP, &paddr, NULL) != LOS_OK) {
+ return FALSE;
+ }
+
+ kvaddr = (PADDR_T)(UINTPTR)LOS_PaddrToKVaddr(paddr);
+ }
+#endif
+ if (vaddr != NULL) {
+ *vaddr = kvaddr;
+ }
+
+ return TRUE;
+}
+
+STATIC INLINE BOOL FindSuitableStack(UINTPTR regFP, UINTPTR *start, UINTPTR *end, vaddr_t *vaddr)
+{
+ UINT32 index, stackStart, stackEnd;
+ BOOL found = FALSE;
+ LosTaskCB *taskCB = NULL;
+ const StackInfo *stack = NULL;
+ vaddr_t kvaddr;
+
+ if (g_excFromUserMode[ArchCurrCpuid()] == TRUE) {
+ taskCB = OsCurrTaskGet();
+ stackStart = taskCB->userMapBase;
+ stackEnd = taskCB->userMapBase + taskCB->userMapSize;
+ if (IsValidFP(regFP, stackStart, stackEnd, &kvaddr) == TRUE) {
+ found = TRUE;
+ goto FOUND;
+ }
+ return found;
+ }
+
+ /* Search in the task stacks */
+ for (index = 0; index < g_taskMaxNum; index++) {
+ taskCB = &g_taskCBArray[index];
+ if (OsTaskIsUnused(taskCB)) {
+ continue;
+ }
+
+ stackStart = taskCB->topOfStack;
+ stackEnd = taskCB->topOfStack + taskCB->stackSize;
+ if (IsValidFP(regFP, stackStart, stackEnd, &kvaddr) == TRUE) {
+ found = TRUE;
+ goto FOUND;
+ }
+ }
+
+ /* Search in the exc stacks */
+ for (index = 0; index < sizeof(g_excStack) / sizeof(StackInfo); index++) {
+ stack = &g_excStack[index];
+ stackStart = (UINTPTR)stack->stackTop;
+ stackEnd = stackStart + LOSCFG_KERNEL_CORE_NUM * stack->stackSize;
+ if (IsValidFP(regFP, stackStart, stackEnd, &kvaddr) == TRUE) {
+ found = TRUE;
+ goto FOUND;
+ }
+ }
+
+FOUND:
+ if (found == TRUE) {
+ *start = stackStart;
+ *end = stackEnd;
+ *vaddr = kvaddr;
+ }
+
+ return found;
+}
+
+BOOL OsGetUsrIpInfo(UINTPTR ip, IpInfo *info)
+{
+ if (info == NULL) {
+ return FALSE;
+ }
+#ifdef LOSCFG_KERNEL_VM
+ BOOL ret = FALSE;
+ const CHAR *name = NULL;
+ LosVmMapRegion *region = NULL;
+ LosProcessCB *runProcess = OsCurrProcessGet();
+
+ if (LOS_IsUserAddress((VADDR_T)ip) == FALSE) {
+ info->ip = ip;
+ name = "kernel";
+ ret = FALSE;
+ goto END;
+ }
+
+ region = LOS_RegionFind(runProcess->vmSpace, (VADDR_T)ip);
+ if (region == NULL) {
+ info->ip = ip;
+ name = "invalid";
+ ret = FALSE;
+ goto END;
+ }
+
+ info->ip = ip - OsGetTextRegionBase(region, runProcess);
+ name = OsGetRegionNameOrFilePath(region);
+ ret = TRUE;
+ if (strcmp(name, "/lib/libc.so") != 0) {
+ PRINT_ERR("ip = 0x%x, %s\n", info->ip, name);
+ }
+END:
+ info->len = strlen(name);
+ if (strncpy_s(info->f_path, REGION_PATH_MAX, name, REGION_PATH_MAX - 1) != EOK) {
+ info->f_path[0] = '\0';
+ info->len = 0;
+ PRINT_ERR("copy f_path failed, %s\n", name);
+ }
+ return ret;
+#else
+ info->ip = ip;
+ return FALSE;
+#endif
+}
+
+UINT32 BackTraceGet(UINTPTR regFP, IpInfo *callChain, UINT32 maxDepth)
+{
+ UINTPTR tmpFP, backLR;
+ UINTPTR stackStart, stackEnd;
+ UINTPTR backFP = regFP;
+ UINT32 count = 0;
+ BOOL ret;
+ VADDR_T kvaddr;
+
+ if (FindSuitableStack(regFP, &stackStart, &stackEnd, &kvaddr) == FALSE) {
+ if (callChain == NULL) {
+ PrintExcInfo("traceback error fp = 0x%x\n", regFP);
+ }
+ return 0;
+ }
+
+ /*
+ * Check whether it is the leaf function.
+ * Generally, the frame pointer points to the address of link register, while in the leaf function,
+ * there's no function call, and compiler will not store the link register, but the frame pointer
+ * will still be stored and updated. In that case we needs to find the right position of frame pointer.
+ */
+ tmpFP = *(UINTPTR *)(UINTPTR)kvaddr;
+ if (IsValidFP(tmpFP, stackStart, stackEnd, NULL) == TRUE) {
+ backFP = tmpFP;
+ if (callChain == NULL) {
+ PrintExcInfo("traceback fp fixed, trace using fp = 0x%x\n", backFP);
+ }
+ }
+
+ while (IsValidFP(backFP, stackStart, stackEnd, &kvaddr) == TRUE) {
+ tmpFP = backFP;
+#ifdef LOSCFG_COMPILER_CLANG_LLVM
+ backFP = *(UINTPTR *)(UINTPTR)kvaddr;
+ if (IsValidFP(tmpFP + POINTER_SIZE, stackStart, stackEnd, &kvaddr) == FALSE) {
+ if (callChain == NULL) {
+ PrintExcInfo("traceback backLR check failed, backLP: 0x%x\n", tmpFP + POINTER_SIZE);
+ }
+ return 0;
+ }
+ backLR = *(UINTPTR *)(UINTPTR)kvaddr;
+#else
+ backLR = *(UINTPTR *)(UINTPTR)kvaddr;
+ if (IsValidFP(tmpFP - POINTER_SIZE, stackStart, stackEnd, &kvaddr) == FALSE) {
+ if (callChain == NULL) {
+ PrintExcInfo("traceback backFP check failed, backFP: 0x%x\n", tmpFP - POINTER_SIZE);
+ }
+ return 0;
+ }
+ backFP = *(UINTPTR *)(UINTPTR)kvaddr;
+#endif
+ IpInfo info = {0};
+ ret = OsGetUsrIpInfo((VADDR_T)backLR, &info);
+ if (callChain == NULL) {
+ PrintExcInfo("traceback %u -- lr = 0x%x fp = 0x%x ", count, backLR, backFP);
+ if (ret) {
+#ifdef LOSCFG_KERNEL_VM
+ PrintExcInfo("lr in %s --> 0x%x\n", info.f_path, info.ip);
+#else
+ PrintExcInfo("\n");
+#endif
+ } else {
+ PrintExcInfo("\n");
+ }
+ } else {
+ (VOID)memcpy_s(&callChain[count], sizeof(IpInfo), &info, sizeof(IpInfo));
+ }
+ count++;
+ if ((count == maxDepth) || (backFP == tmpFP)) {
+ break;
+ }
+ }
+ return count;
+}
+
+VOID BackTraceSub(UINTPTR regFP)
+{
+ (VOID)BackTraceGet(regFP, NULL, OS_MAX_BACKTRACE);
+}
+
+VOID BackTrace(UINT32 regFP)
+{
+ PrintExcInfo("*******backtrace begin*******\n");
+
+ BackTraceSub(regFP);
+}
+
+VOID OsExcInit(VOID)
+{
+ OsExcStackInfoReg(g_excStack, sizeof(g_excStack) / sizeof(g_excStack[0]));
+}
+
+VOID OsExcHook(UINT32 excType, ExcContext *excBufAddr, UINT32 far, UINT32 fsr)
+{
+ OsExcType(excType, excBufAddr, far, fsr);
+ OsExcSysInfo(excType, excBufAddr);
+ OsExcRegsInfo(excBufAddr);
+
+ BackTrace(excBufAddr->R11);
+
+ (VOID)OsShellCmdTskInfoGet(OS_ALL_TASK_MASK, NULL, OS_PROCESS_INFO_ALL);
+
+#ifndef LOSCFG_DEBUG_VERSION
+ if (g_excFromUserMode[ArchCurrCpuid()] != TRUE) {
+#endif
+#ifdef LOSCFG_KERNEL_VM
+ OsDumpProcessUsedMemNode(OS_EXC_VMM_NO_REGION);
+#endif
+ OsExcStackInfo();
+#ifndef LOSCFG_DEBUG_VERSION
+ }
+#endif
+
+ OsDumpContextMem(excBufAddr);
+
+ (VOID)OsShellCmdMemCheck(0, NULL);
+
+#ifdef LOSCFG_COREDUMP
+ LOS_CoreDumpV2(excType, excBufAddr);
+#endif
+
+ OsUserExcHandle(excBufAddr);
+}
+
+VOID OsCallStackInfo(VOID)
+{
+ UINT32 count = 0;
+ LosTaskCB *runTask = OsCurrTaskGet();
+ UINTPTR stackBottom = runTask->topOfStack + runTask->stackSize;
+ UINT32 *stackPointer = (UINT32 *)stackBottom;
+
+ PrintExcInfo("runTask->stackPointer = 0x%x\n"
+ "runTask->topOfStack = 0x%x\n"
+ "text_start:0x%x,text_end:0x%x\n",
+ stackPointer, runTask->topOfStack, &__text_start, &__text_end);
+
+ while ((stackPointer > (UINT32 *)runTask->topOfStack) && (count < OS_MAX_BACKTRACE)) {
+ if ((*stackPointer > (UINTPTR)(&__text_start)) &&
+ (*stackPointer < (UINTPTR)(&__text_end)) &&
+ IS_ALIGNED((*stackPointer), POINTER_SIZE)) {
+ if ((*(stackPointer - 1) > (UINT32)runTask->topOfStack) &&
+ (*(stackPointer - 1) < stackBottom) &&
+ IS_ALIGNED((*(stackPointer - 1)), POINTER_SIZE)) {
+ count++;
+ PrintExcInfo("traceback %u -- lr = 0x%x\n", count, *stackPointer);
+ }
+ }
+ stackPointer--;
+ }
+ PRINTK("\n");
+}
+
+VOID OsTaskBackTrace(UINT32 taskID)
+{
+ LosTaskCB *taskCB = NULL;
+
+ if (OS_TID_CHECK_INVALID(taskID)) {
+ PRINT_ERR("\r\nTask ID is invalid!\n");
+ return;
+ }
+ taskCB = OS_TCB_FROM_TID(taskID);
+ if (OsTaskIsUnused(taskCB) || (taskCB->taskEntry == NULL)) {
+ PRINT_ERR("\r\nThe task is not created!\n");
+ return;
+ }
+ PRINTK("TaskName = %s\n", taskCB->taskName);
+ PRINTK("TaskID = 0x%x\n", taskCB->taskID);
+ BackTrace(((TaskContext *)(taskCB->stackPointer))->R11); /* R11 : FP */
+}
+
+VOID OsBackTrace(VOID)
+{
+ UINT32 regFP = Get_Fp();
+ LosTaskCB *runTask = OsCurrTaskGet();
+ PrintExcInfo("OsBackTrace fp = 0x%x\n", regFP);
+ PrintExcInfo("runTask->taskName = %s\n", runTask->taskName);
+ PrintExcInfo("runTask->taskID = %u\n", runTask->taskID);
+ BackTrace(regFP);
+}
+
+#ifdef LOSCFG_GDB
+VOID OsUndefIncExcHandleEntry(ExcContext *excBufAddr)
+{
+ excBufAddr->PC -= 4; /* lr in undef is pc + 4 */
+
+ if (gdb_undef_hook(excBufAddr, OS_EXCEPT_UNDEF_INSTR)) {
+ return;
+ }
+
+ if (g_excHook != NULL) {
+ /* far, fsr are unused in exc type of OS_EXCEPT_UNDEF_INSTR */
+ g_excHook(OS_EXCEPT_UNDEF_INSTR, excBufAddr, 0, 0);
+ }
+ while (1) {}
+}
+
+#if __LINUX_ARM_ARCH__ >= 7
+VOID OsPrefetchAbortExcHandleEntry(ExcContext *excBufAddr)
+{
+ UINT32 far;
+ UINT32 fsr;
+
+ excBufAddr->PC -= 4; /* lr in prefetch abort is pc + 4 */
+
+ if (gdbhw_hook(excBufAddr, OS_EXCEPT_PREFETCH_ABORT)) {
+ return;
+ }
+
+ if (g_excHook != NULL) {
+ far = OsArmReadIfar();
+ fsr = OsArmReadIfsr();
+ g_excHook(OS_EXCEPT_PREFETCH_ABORT, excBufAddr, far, fsr);
+ }
+ while (1) {}
+}
+
+VOID OsDataAbortExcHandleEntry(ExcContext *excBufAddr)
+{
+ UINT32 far;
+ UINT32 fsr;
+
+ excBufAddr->PC -= 8; /* lr in data abort is pc + 8 */
+
+ if (gdbhw_hook(excBufAddr, OS_EXCEPT_DATA_ABORT)) {
+ return;
+ }
+
+ if (g_excHook != NULL) {
+ far = OsArmReadDfar();
+ fsr = OsArmReadDfsr();
+ g_excHook(OS_EXCEPT_DATA_ABORT, excBufAddr, far, fsr);
+ }
+ while (1) {}
+}
+#endif /* __LINUX_ARM_ARCH__ */
+#endif /* LOSCFG_GDB */
+
+#ifdef LOSCFG_KERNEL_SMP
+#define EXC_WAIT_INTER 50U
+#define EXC_WAIT_TIME 2000U
+
+STATIC VOID WaitAllCpuStop(UINT32 cpuID)
+{
+ UINT32 i;
+ UINT32 time = 0;
+
+ while (time < EXC_WAIT_TIME) {
+ for (i = 0; i < LOSCFG_KERNEL_CORE_NUM; i++) {
+ if ((i != cpuID) && !OsCpuStatusIsHalt(i)) {
+ LOS_Mdelay(EXC_WAIT_INTER);
+ time += EXC_WAIT_INTER;
+ break;
+ }
+ }
+ /* Other CPUs are all haletd or in the exc. */
+ if (i == LOSCFG_KERNEL_CORE_NUM) {
+ break;
+ }
+ }
+ return;
+}
+
+STATIC VOID OsWaitOtherCoresHandleExcEnd(UINT32 currCpuID)
+{
+ while (1) {
+ LOS_SpinLock(&g_excSerializerSpin);
+ if ((g_currHandleExcCpuID == INVALID_CPUID) || (g_currHandleExcCpuID == currCpuID)) {
+ g_currHandleExcCpuID = currCpuID;
+ g_currHandleExcPID = OsCurrProcessGet()->processID;
+ LOS_SpinUnlock(&g_excSerializerSpin);
+ break;
+ }
+
+ if (g_nextExcWaitCpu == INVALID_CPUID) {
+ g_nextExcWaitCpu = currCpuID;
+ }
+ LOS_SpinUnlock(&g_excSerializerSpin);
+ LOS_Mdelay(EXC_WAIT_INTER);
+ }
+}
+
+STATIC VOID OsCheckAllCpuStatus(VOID)
+{
+ UINT32 currCpuID = ArchCurrCpuid();
+ UINT32 ret, target;
+
+ OsCpuStatusSet(CPU_EXC);
+ LOCKDEP_CLEAR_LOCKS();
+
+ LOS_SpinLock(&g_excSerializerSpin);
+ /* Only the current CPU anomaly */
+ if (g_currHandleExcCpuID == INVALID_CPUID) {
+ g_currHandleExcCpuID = currCpuID;
+ g_currHandleExcPID = OsCurrProcessGet()->processID;
+ LOS_SpinUnlock(&g_excSerializerSpin);
+#ifndef LOSCFG_SAVE_EXCINFO
+ if (g_excFromUserMode[currCpuID] == FALSE) {
+ target = (UINT32)(OS_MP_CPU_ALL & ~CPUID_TO_AFFI_MASK(currCpuID));
+ HalIrqSendIpi(target, LOS_MP_IPI_HALT);
+ }
+#endif
+ } else if (g_excFromUserMode[currCpuID] == TRUE) {
+ /* Both cores raise exceptions, and the current core is a user-mode exception.
+ * Both cores are abnormal and come from the same process
+ */
+ if (OsCurrProcessGet()->processID == g_currHandleExcPID) {
+ LOS_SpinUnlock(&g_excSerializerSpin);
+ OsExcRestore();
+ ret = LOS_TaskDelete(OsCurrTaskGet()->taskID);
+ LOS_Panic("%s supend task :%u failed: 0x%x\n", __FUNCTION__, OsCurrTaskGet()->taskID, ret);
+ }
+ LOS_SpinUnlock(&g_excSerializerSpin);
+
+ OsWaitOtherCoresHandleExcEnd(currCpuID);
+ } else {
+ if ((g_currHandleExcCpuID < LOSCFG_KERNEL_CORE_NUM) && (g_excFromUserMode[g_currHandleExcCpuID] == TRUE)) {
+ g_currHandleExcCpuID = currCpuID;
+ LOS_SpinUnlock(&g_excSerializerSpin);
+ target = (UINT32)(OS_MP_CPU_ALL & ~CPUID_TO_AFFI_MASK(currCpuID));
+ HalIrqSendIpi(target, LOS_MP_IPI_HALT);
+ } else {
+ LOS_SpinUnlock(&g_excSerializerSpin);
+ while (1) {}
+ }
+ }
+#ifndef LOSCFG_SAVE_EXCINFO
+ /* use halt ipi to stop other active cores */
+ if (g_excFromUserMode[ArchCurrCpuid()] == FALSE) {
+ WaitAllCpuStop(currCpuID);
+ }
+#endif
+}
+#endif
+
+STATIC VOID OsCheckCpuStatus(VOID)
+{
+#ifdef LOSCFG_KERNEL_SMP
+ OsCheckAllCpuStatus();
+#else
+ g_currHandleExcCpuID = ArchCurrCpuid();
+#endif
+}
+
+LITE_OS_SEC_TEXT VOID STATIC OsExcPriorDisposal(ExcContext *excBufAddr)
+{
+ if ((excBufAddr->regCPSR & CPSR_MASK_MODE) == CPSR_USER_MODE) {
+ g_minAddr = USER_ASPACE_BASE;
+ g_maxAddr = USER_ASPACE_BASE + USER_ASPACE_SIZE;
+ g_excFromUserMode[ArchCurrCpuid()] = TRUE;
+ } else {
+ g_minAddr = KERNEL_ASPACE_BASE;
+ g_maxAddr = KERNEL_ASPACE_BASE + KERNEL_ASPACE_SIZE;
+ g_excFromUserMode[ArchCurrCpuid()] = FALSE;
+ }
+
+ OsCheckCpuStatus();
+
+#ifdef LOSCFG_KERNEL_SMP
+#ifdef LOSCFG_FS_VFS
+ /* Wait for the end of the Console task to avoid multicore printing code */
+ OsWaitConsoleSendTaskPend(OsCurrTaskGet()->taskID);
+#endif
+#endif
+}
+
+LITE_OS_SEC_TEXT_INIT STATIC VOID OsPrintExcHead(UINT32 far)
+{
+#ifdef LOSCFG_BLACKBOX
+#ifdef LOSCFG_SAVE_EXCINFO
+ SetExcInfoIndex(0);
+#endif
+#endif
+#ifdef LOSCFG_KERNEL_VM
+ /* You are not allowed to add any other print information before this exception information */
+ if (g_excFromUserMode[ArchCurrCpuid()] == TRUE) {
+#ifdef LOSCFG_DEBUG_VERSION
+ VADDR_T vaddr = ROUNDDOWN(far, PAGE_SIZE);
+ LosVmSpace *space = LOS_SpaceGet(vaddr);
+ if (space != NULL) {
+ LOS_DumpMemRegion(vaddr);
+ }
+#endif
+ PrintExcInfo("##################excFrom: User!####################\n");
+ } else
+#endif
+ {
+ PrintExcInfo("##################excFrom: kernel!###################\n");
+ }
+}
+
+#ifdef LOSCFG_SAVE_EXCINFO
+STATIC VOID OsSysStateSave(UINT32 *intCount, UINT32 *lockCount)
+{
+ *intCount = g_intCount[ArchCurrCpuid()];
+ *lockCount = OsSchedLockCountGet();
+ g_intCount[ArchCurrCpuid()] = 0;
+ OsSchedLockSet(0);
+}
+
+STATIC VOID OsSysStateRestore(UINT32 intCount, UINT32 lockCount)
+{
+ g_intCount[ArchCurrCpuid()] = intCount;
+ OsSchedLockSet(lockCount);
+}
+#endif
+
+/*
+ * Description : EXC handler entry
+ * Input : excType --- exc type
+ * excBufAddr --- address of EXC buf
+ */
+LITE_OS_SEC_TEXT_INIT VOID OsExcHandleEntry(UINT32 excType, ExcContext *excBufAddr, UINT32 far, UINT32 fsr)
+{
+#ifdef LOSCFG_SAVE_EXCINFO
+ UINT32 intCount;
+ UINT32 lockCount;
+#endif
+
+ /* Task scheduling is not allowed during exception handling */
+ OsSchedLock();
+
+ g_curNestCount[ArchCurrCpuid()]++;
+
+ OsExcPriorDisposal(excBufAddr);
+
+ OsPrintExcHead(far);
+
+#ifdef LOSCFG_KERNEL_SMP
+ OsAllCpuStatusOutput();
+#endif
+
+#ifdef LOSCFG_SAVE_EXCINFO
+ log_read_write_fn func = GetExcInfoRW();
+#endif
+
+ if (g_excHook != NULL) {
+ if (g_curNestCount[ArchCurrCpuid()] == 1) {
+#ifdef LOSCFG_SAVE_EXCINFO
+ if (func != NULL) {
+#ifndef LOSCFG_BLACKBOX
+ SetExcInfoIndex(0);
+#endif
+ OsSysStateSave(&intCount, &lockCount);
+ OsRecordExcInfoTime();
+ OsSysStateRestore(intCount, lockCount);
+ }
+#endif
+ g_excHook(excType, excBufAddr, far, fsr);
+ } else {
+ OsCallStackInfo();
+ }
+
+#ifdef LOSCFG_SAVE_EXCINFO
+ if (func != NULL) {
+ PrintExcInfo("Be sure flash space bigger than GetExcInfoIndex():0x%x\n", GetExcInfoIndex());
+ OsSysStateSave(&intCount, &lockCount);
+ func(GetRecordAddr(), GetRecordSpace(), 0, GetExcInfoBuf());
+ OsSysStateRestore(intCount, lockCount);
+ }
+#endif
+ }
+
+#ifdef LOSCFG_SHELL_CMD_DEBUG
+ SystemRebootFunc rebootHook = OsGetRebootHook();
+ if ((OsSystemExcIsReset() == TRUE) && (rebootHook != NULL)) {
+ LOS_Mdelay(3000); /* 3000: System dead, delay 3 seconds after system restart */
+ rebootHook();
+ }
+#endif
+
+#ifdef LOSCFG_BLACKBOX
+ BBoxNotifyError(EVENT_PANIC, MODULE_SYSTEM, "Crash in kernel", 1);
+#endif
+ while (1) {}
+}
+
+__attribute__((noinline)) VOID LOS_Panic(const CHAR *fmt, ...)
+{
+ va_list ap;
+ va_start(ap, fmt);
+ OsVprintf(fmt, ap, EXC_OUTPUT);
+ va_end(ap);
+ __asm__ __volatile__("swi 0");
+ while (1) {}
+}
+
+/* stack protector */
+USED UINT32 __stack_chk_guard = 0xd00a0dff;
+
+VOID __stack_chk_fail(VOID)
+{
+ /* __builtin_return_address is a builtin function, building in gcc */
+ LOS_Panic("stack-protector: Kernel stack is corrupted in: %p\n",
+ __builtin_return_address(0));
+}
+
+VOID LOS_RecordLR(UINTPTR *LR, UINT32 LRSize, UINT32 recordCount, UINT32 jumpCount)
+{
+ UINT32 count = 0;
+ UINT32 index = 0;
+ UINT32 stackStart, stackEnd;
+ LosTaskCB *taskCB = NULL;
+ UINTPTR framePtr, tmpFramePtr, linkReg;
+
+ if (LR == NULL) {
+ return;
+ }
+ /* if LR array is not enough,just record LRSize. */
+ if (LRSize < recordCount) {
+ recordCount = LRSize;
+ }
+
+ taskCB = OsCurrTaskGet();
+ stackStart = taskCB->topOfStack;
+ stackEnd = stackStart + taskCB->stackSize;
+
+ framePtr = Get_Fp();
+ while ((framePtr > stackStart) && (framePtr < stackEnd) && IS_ALIGNED(framePtr, sizeof(CHAR *))) {
+ tmpFramePtr = framePtr;
+#ifdef LOSCFG_COMPILER_CLANG_LLVM
+ linkReg = *(UINTPTR *)(tmpFramePtr + sizeof(UINTPTR));
+#else
+ linkReg = *(UINTPTR *)framePtr;
+#endif
+ if (index >= jumpCount) {
+ LR[count++] = linkReg;
+ if (count == recordCount) {
+ break;
+ }
+ }
+ index++;
+#ifdef LOSCFG_COMPILER_CLANG_LLVM
+ framePtr = *(UINTPTR *)framePtr;
+#else
+ framePtr = *(UINTPTR *)(tmpFramePtr - sizeof(UINTPTR));
+#endif
+ }
+
+ /* if linkReg is not enough,clean up the last of the effective LR as the end. */
+ if (count < recordCount) {
+ LR[count] = 0;
+ }
+}
+
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/los_hw.c b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/los_hw.c
new file mode 100644
index 00000000..617c7c57
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/los_hw.c
@@ -0,0 +1,179 @@
+/*
+ * 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_hw_pri.h"
+#include "los_task_pri.h"
+
+/* support cpu vendors */
+CpuVendor g_cpuTable[] = {
+ /* armv7-a */
+ { 0xc07, "Cortex-A7" },
+ { 0xc09, "Cortex-A9" },
+ { 0, NULL }
+};
+
+/* logical cpu mapping */
+UINT64 g_cpuMap[LOSCFG_KERNEL_CORE_NUM] = {
+ [0 ... LOSCFG_KERNEL_CORE_NUM - 1] = (UINT64)(-1)
+};
+
+/* bit[30] is enable FPU */
+#define FP_EN (1U << 30)
+LITE_OS_SEC_TEXT_INIT VOID OsTaskExit(VOID)
+{
+ __asm__ __volatile__("swi 0");
+}
+
+#ifdef LOSCFG_GDB
+STATIC VOID OsTaskEntrySetupLoopFrame(UINT32) __attribute__((noinline, naked));
+VOID OsTaskEntrySetupLoopFrame(UINT32 arg0)
+{
+ asm volatile("\tsub fp, sp, #0x4\n"
+ "\tpush {fp, lr}\n"
+ "\tadd fp, sp, #0x4\n"
+ "\tpush {fp, lr}\n"
+
+ "\tadd fp, sp, #0x4\n"
+ "\tbl OsTaskEntry\n"
+
+ "\tpop {fp, lr}\n"
+ "\tpop {fp, pc}\n");
+}
+#endif
+
+LITE_OS_SEC_TEXT_INIT VOID *OsTaskStackInit(UINT32 taskID, UINT32 stackSize, VOID *topStack, BOOL initFlag)
+{
+ if (initFlag == TRUE) {
+ OsStackInit(topStack, stackSize);
+ }
+ TaskContext *taskContext = (TaskContext *)(((UINTPTR)topStack + stackSize) - sizeof(TaskContext));
+
+ /* initialize the task context */
+#ifdef LOSCFG_GDB
+ taskContext->PC = (UINTPTR)OsTaskEntrySetupLoopFrame;
+#else
+ taskContext->PC = (UINTPTR)OsTaskEntry;
+#endif
+ taskContext->LR = (UINTPTR)OsTaskExit; /* LR should be kept, to distinguish it's THUMB or ARM instruction */
+ taskContext->R0 = taskID; /* R0 */
+
+#ifdef LOSCFG_THUMB
+ taskContext->regCPSR = PSR_MODE_SVC_THUMB; /* CPSR (Enable IRQ and FIQ interrupts, THUMNB-mode) */
+#else
+ taskContext->regCPSR = PSR_MODE_SVC_ARM; /* CPSR (Enable IRQ and FIQ interrupts, ARM-mode) */
+#endif
+
+#if !defined(LOSCFG_ARCH_FPU_DISABLE)
+ /* 0xAAA0000000000000LL : float reg initialed magic word */
+ for (UINT32 index = 0; index < FP_REGS_NUM; index++) {
+ taskContext->D[index] = 0xAAA0000000000000LL + index; /* D0 - D31 */
+ }
+ taskContext->regFPSCR = 0;
+ taskContext->regFPEXC = FP_EN;
+#endif
+
+ return (VOID *)taskContext;
+}
+
+LITE_OS_SEC_TEXT VOID OsUserCloneParentStack(VOID *childStack, UINTPTR parentTopOfStack, UINT32 parentStackSize)
+{
+ LosTaskCB *task = OsCurrTaskGet();
+ sig_cb *sigcb = &task->sig;
+ VOID *cloneStack = NULL;
+
+ if (sigcb->sigContext != NULL) {
+ cloneStack = (VOID *)((UINTPTR)sigcb->sigContext - sizeof(TaskContext));
+ } else {
+ cloneStack = (VOID *)(((UINTPTR)parentTopOfStack + parentStackSize) - sizeof(TaskContext));
+ }
+
+ (VOID)memcpy_s(childStack, sizeof(TaskContext), cloneStack, sizeof(TaskContext));
+ ((TaskContext *)childStack)->R0 = 0;
+}
+
+LITE_OS_SEC_TEXT_INIT VOID OsUserTaskStackInit(TaskContext *context, UINTPTR taskEntry, UINTPTR stack)
+{
+ LOS_ASSERT(context != NULL);
+
+#ifdef LOSCFG_THUMB
+ context->regCPSR = PSR_MODE_USR_THUMB;
+#else
+ context->regCPSR = PSR_MODE_USR_ARM;
+#endif
+ context->R0 = stack;
+ context->USP = TRUNCATE(stack, LOSCFG_STACK_POINT_ALIGN_SIZE);
+ context->ULR = 0;
+ context->PC = (UINTPTR)taskEntry;
+}
+
+VOID OsInitSignalContext(const VOID *sp, VOID *signalContext, UINTPTR sigHandler, UINT32 signo, UINT32 param)
+{
+ IrqContext *newSp = (IrqContext *)signalContext;
+ (VOID)memcpy_s(signalContext, sizeof(IrqContext), sp, sizeof(IrqContext));
+ newSp->PC = sigHandler;
+ newSp->R0 = signo;
+ newSp->R1 = param;
+}
+
+DEPRECATED VOID Dmb(VOID)
+{
+ __asm__ __volatile__ ("dmb" : : : "memory");
+}
+
+DEPRECATED VOID Dsb(VOID)
+{
+ __asm__ __volatile__("dsb" : : : "memory");
+}
+
+DEPRECATED VOID Isb(VOID)
+{
+ __asm__ __volatile__("isb" : : : "memory");
+}
+
+VOID FlushICache(VOID)
+{
+ /*
+ * Use ICIALLUIS instead of ICIALLU. ICIALLUIS operates on all processors in the Inner
+ * shareable domain of the processor that performs the operation.
+ */
+ __asm__ __volatile__ ("mcr p15, 0, %0, c7, c1, 0" : : "r" (0) : "memory");
+}
+
+VOID DCacheFlushRange(UINT32 start, UINT32 end)
+{
+ arm_clean_cache_range(start, end);
+}
+
+VOID DCacheInvRange(UINT32 start, UINT32 end)
+{
+ arm_inv_cache_range(start, end);
+}
+
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/los_hw_exc.S b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/los_hw_exc.S
new file mode 100644
index 00000000..18805462
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/los_hw_exc.S
@@ -0,0 +1,424 @@
+/*
+ * 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 "asm.h"
+#include "arch_config.h"
+
+ .extern g_losTask
+ .extern g_intCount
+ .extern g_curNestCount
+ .extern OsExcHandleEntry
+ .extern __svc_stack_top
+ .extern __exc_stack_top
+ .extern __stack_chk_guard
+ .extern OsRandomStackGuard
+#ifdef LOSCFG_GDB
+ .extern OsUndefIncExcHandleEntry
+#if __LINUX_ARM_ARCH__ >= 7
+ .extern OsPrefetchAbortExcHandleEntry
+ .extern OsDataAbortExcHandleEntry
+#endif
+#endif
+ .extern OsSaveSignalContext
+ .extern OsRestorSignalContext
+ .extern OsArmSharedPageFault
+ .extern OsArmA32SyscallHandle
+
+ .global _osExceptFiqHdl
+ .global _osExceptAddrAbortHdl
+ .global _osExceptDataAbortHdl
+ .global _osExceptPrefetchAbortHdl
+ .global _osExceptSwiHdl
+ .global _osExceptUndefInstrHdl
+#if defined(LOSCFG_CC_STACKPROTECTOR_ALL) || \
+ defined(LOSCFG_CC_STACKPROTECTOR_STRONG) || \
+ defined(LOSCFG_CC_STACKPROTECTOR)
+ .global __stack_chk_guard_setup
+#endif
+
+ .fpu vfpv4
+
+.macro PUSH_FPU_REGS reg1
+#if !defined(LOSCFG_ARCH_FPU_DISABLE)
+ VMRS \reg1, FPEXC
+ PUSH {\reg1}
+ VMRS \reg1, FPSCR
+ PUSH {\reg1}
+#if defined(LOSCFG_ARCH_FPU_VFP_D32)
+ VPUSH {D16-D31}
+#endif
+ VPUSH {D0-D15}
+#endif
+.endm
+
+.macro POP_FPU_REGS reg1
+#if !defined(LOSCFG_ARCH_FPU_DISABLE)
+ VPOP {D0-D15}
+#if defined(LOSCFG_ARCH_FPU_VFP_D32)
+ VPOP {D16-D31}
+#endif
+ POP {\reg1}
+ VMSR FPSCR, \reg1
+ POP {\reg1}
+ VMSR FPEXC, \reg1
+#endif
+.endm
+
+#ifdef LOSCFG_GDB
+.macro GDB_HANDLE fun
+ SUB SP, SP, #12
+
+ STMFD SP!, {R0-R12}
+ MRS R1, SPSR
+ STMFD SP!, {R1} @save spsr
+
+ ADD R0, SP, #14 * 4
+ MOV R3, LR @save pc
+
+ MRS R1, CPSR
+ MRS R2, SPSR
+ MOV R4, SP
+
+ ORR R2, R2, #(CPSR_INT_DISABLE)
+ MSR CPSR_c, R2
+
+ STR SP, [R0] @SP
+ STR LR, [R0, #4] @LR
+ STR R3, [R0, #8] @PC
+
+ ORR R1, R1, #(CPSR_INT_DISABLE)
+ BIC R1, R1, #OS_PSR_THUMB
+ MSR CPSR_c, R1
+ MOV R0, R4
+
+ BL \fun
+
+ ADD SP, SP, #4
+ LDMFD SP!, {R0-R12}
+
+ MOV R0, SP
+ ADD SP, SP, #8
+
+ LDR R1, [R0, #8] @get pc
+ STMFD SP!, {R1}
+
+ AND R1, R1, #0x03
+ CMP R1, #0
+ BEQ 1f
+ LDR R1, [R0, #-14 * 4]
+ ORR R1, R1, #OS_PSR_THUMB
+ B 2f
+1:
+ LDR R1, [R0, #-14 * 4]
+
+2:
+ MSR SPSR, R1
+
+ LDR R1, [R0, #-12 * 4] @get R1
+ STMFD SP!, {R1}
+ LDR R1, [R0,#-13 * 4] @get R0
+ STMFD SP!, {R1}
+
+ LDMFD SP!, {R0-R1, PC}^
+.endm
+#endif
+
+#if defined(LOSCFG_CC_STACKPROTECTOR_ALL) || \
+ defined(LOSCFG_CC_STACKPROTECTOR_STRONG) || \
+ defined(LOSCFG_CC_STACKPROTECTOR)
+@ Description: Stack-Protector Init
+__stack_chk_guard_setup:
+ PUSH {FP, LR}
+#if defined(LOSCFG_PLATFORM_HI3516DV300) || defined(LOSCFG_PLATFORM_HI3518EV300)
+ /* Randomize __stack_chk_quard using platform-specific function. */
+ BL OsRandomStackGuard
+ LDR R1, =__stack_chk_guard
+ MOV R3, R0
+ ORR R2, R3, #0X80000000
+ STR R2, [R1]
+#endif
+ POP {FP, PC}
+#endif
+
+@ Description: Undefined instruction exception handler
+_osExceptUndefInstrHdl:
+#ifdef LOSCFG_GDB
+ GDB_HANDLE OsUndefIncExcHandleEntry
+#else
+ SRSFD #CPSR_SVC_MODE! @ Save pc and cpsr to svc sp, ARMv6 and above support
+ MSR CPSR_c, #(CPSR_INT_DISABLE | CPSR_SVC_MODE) @ Switch to svc mode, and disable all interrupt
+ STMFD SP!, {R0-R3, R12, LR}
+ STMFD SP, {R13, R14}^ @ push user sp and lr
+ SUB SP, SP, #(2 * 4)
+ MOV R2, #0
+ MOV R3, #0
+ STMFD SP!, {R2-R3} @ far and fsr fields, are 0 under this anomaly
+ STMFD SP!, {R4-R11}
+
+ MOV R0, #OS_EXCEPT_UNDEF_INSTR @ Set exception ID to OS_EXCEPT_UNDEF_INSTR.
+ B _osExceptDispatch @ Branch to global exception handler.
+#endif
+
+@ Description: Software interrupt exception handler
+_osExceptSwiHdl:
+ SRSFD #CPSR_SVC_MODE! @ Save pc and cpsr to svc sp, ARMv6 and above support
+ STMFD SP!, {R0-R3, R12, LR}
+ STMFD SP, {R13, R14}^
+ SUB SP, SP, #(4 * 4) @ push user sp and lr and jump reserved field
+ STR R7, [SP, #0] @ Save system call number to reserved2 filed
+
+#ifdef LOSCFG_KERNEL_SYSCALL
+ LDR R3, [SP, #(11 * 4)]
+ AND R1, R3, #CPSR_MASK_MODE @ Interrupted mode
+ CMP R1, #CPSR_USER_MODE @ User mode
+ BNE _osKernelSVCHandler @ Branch if not user mode
+
+ CMP R7, #119 @ __NR_sigreturn
+ BNE _osIsSyscall
+ MOV R0, SP
+ BLX OsRestorSignalContext
+ MOV SP, R0
+ B _osSyscallReturn
+
+_osIsSyscall:
+ STMFD SP!, {R4-R11}
+
+ PUSH_FPU_REGS R1
+
+ MOV R0, SP
+ MOV FP, #0 @ Init frame pointer
+ CPSIE I
+ BLX OsArmA32SyscallHandle
+ CPSID I
+
+ POP_FPU_REGS R1
+ LDMFD SP!, {R4-R11}
+
+ MOV R0, SP
+ SUB SP, SP, #(12 * 4) @ sp - sizeof(IrqContext), reserved for signal
+ MOV R1, SP
+ BLX OsSaveSignalContext
+ MOV SP, R0
+
+_osSyscallReturn:
+ LDR R7, [SP, #0]
+ ADD SP, SP, #(2 * 4) @ jump reserved filed
+ LDMFD SP, {R13, R14}^ @ Restore user mode R13/R14
+ ADD SP, SP, #(2 * 4)
+ LDMFD SP!, {R0-R3, R12, LR}
+ RFEIA SP! @ Return to user
+
+_osKernelSVCHandler:
+#endif
+ MOV R0, #0
+ STR R0, [SP, #0]
+ STR R0, [SP, #4]
+ STMFD SP!, {R4-R11}
+ MOV R0, #OS_EXCEPT_SWI @ Set exception ID to OS_EXCEPT_SWI.
+ B _osExceptDispatch @ Branch to global exception handler.
+
+@ Description: Prefectch abort exception handler
+_osExceptPrefetchAbortHdl:
+#ifdef LOSCFG_GDB
+#if __LINUX_ARM_ARCH__ >= 7
+ GDB_HANDLE OsPrefetchAbortExcHandleEntry
+#endif
+#else
+ SUB LR, LR, #4 @ LR offset to return from this exception: -4.
+
+ SRSFD #CPSR_SVC_MODE! @ Save pc and cpsr to svc sp, ARMv6 and above support
+ MSR CPSR_c, #(CPSR_INT_DISABLE | CPSR_SVC_MODE) @ Switch to svc mode, and disable all interrupt
+ STMFD SP!, {R0-R3, R12, LR}
+ STMFD SP, {R13, R14}^
+ SUB SP, SP, #(2 * 4)
+
+ MRC P15, 0, R2, C6, C0, 2
+ MRC P15, 0, R3, C5, C0, 1
+ STMFD SP!, {R2-R3} @ Save far and fsr
+ STMFD SP!, {R4-R11}
+
+#ifdef LOSCFG_KERNEL_VM
+ LDR R0, [SP, #(19 * 4)]
+ AND R0, R0, #CPSR_MASK_MODE @ Interrupted mode
+ CMP R0, #CPSR_USER_MODE @ User mode
+ BNE _osKernelExceptPrefetchAbortHdl
+
+ MOV R1, SP
+ PUSH_FPU_REGS R0
+
+ MOV R0, #OS_EXCEPT_PREFETCH_ABORT
+ BLX OsArmSharedPageFault
+ CMP R0, #0
+
+ POP_FPU_REGS R0
+ BEQ _osExcPageFaultReturn
+#endif
+
+_osKernelExceptPrefetchAbortHdl:
+ MOV R0, #OS_EXCEPT_PREFETCH_ABORT
+ B _osExceptDispatch @ Branch to global exception handler.
+#endif
+
+@ Description: Data abort exception handler
+_osExceptDataAbortHdl:
+#ifdef LOSCFG_GDB
+#if __LINUX_ARM_ARCH__ >= 7
+ GDB_HANDLE OsDataAbortExcHandleEntry
+#endif
+#else
+ SUB LR, LR, #8 @ LR offset to return from this exception: -8.
+
+ SRSFD #CPSR_SVC_MODE! @ Save pc and cpsr to svc sp, ARMv6 and above support
+ MSR CPSR_c, #(CPSR_INT_DISABLE | CPSR_SVC_MODE) @ Switch to svc mode, and disable all interrupt
+ STMFD SP!, {R0-R3, R12, LR}
+ STMFD SP, {R13, R14}^
+ SUB SP, SP, #(2 * 4)
+
+ MRC P15, 0, R2, C6, C0, 0
+ MRC P15, 0, R3, C5, C0, 0
+ STMFD SP!, {R2-R3} @ Save far and fsr
+ STMFD SP!, {R4-R11}
+
+#ifdef LOSCFG_KERNEL_VM
+ MOV R1, SP
+ PUSH_FPU_REGS R0
+
+ MOV R0, #OS_EXCEPT_DATA_ABORT @ Set exception ID to OS_EXCEPT_DATA_ABORT.
+ BLX OsArmSharedPageFault
+ CMP R0, #0
+ POP_FPU_REGS R0
+ BEQ _osExcPageFaultReturn
+#endif
+
+ MOV R0, #OS_EXCEPT_DATA_ABORT
+ B _osExceptDispatch
+#endif
+
+#ifdef LOSCFG_KERNEL_VM
+_osExcPageFaultReturn:
+ LDMFD SP!, {R4-R11}
+
+ MOV R0, SP
+ STR R7, [SP, #0]
+ SUB SP, SP, #(12 * 4) @ sp - sizeof(IrqContext), reserved for signal
+ MOV R1, SP
+ BLX OsSaveSignalContext
+ MOV SP, R0
+
+ ADD SP, SP, #(2 * 4)
+ LDMFD SP, {R13, R14}^
+ ADD SP, SP, #(2 * 4) @ Jump reserved fileds
+ LDMFD SP!, {R0-R3, R12, LR}
+ RFEIA SP!
+#endif
+
+@ Description: Address abort exception handler
+_osExceptAddrAbortHdl:
+ SUB LR, LR, #8 @ LR offset to return from this exception: -8.
+
+ SRSFD #CPSR_SVC_MODE! @ Save pc and cpsr to svc sp, ARMv6 and above support
+ MSR CPSR_c, #(CPSR_INT_DISABLE | CPSR_SVC_MODE) @ Switch to svc mode, and disable all interrupt
+ STMFD SP!, {R0-R3, R12, LR}
+ STMFD SP, {R13, R14}^
+ SUB SP, SP, #(2 * 4)
+
+ MOV R2, #0
+ MOV R3, #0
+ STMFD SP!, {R2-R3} @ far and fsr fields, are 0 under this anomaly
+ STMFD SP!, {R4-R11}
+
+ MOV R0, #OS_EXCEPT_ADDR_ABORT @ Set exception ID to OS_EXCEPT_ADDR_ABORT.
+ B _osExceptDispatch @ Branch to global exception handler.
+
+@ Description: Fast interrupt request exception handler
+_osExceptFiqHdl:
+ SUB LR, LR, #4 @ LR offset to return from this exception: -4.
+
+ SRSFD #CPSR_SVC_MODE! @ Save pc and cpsr to svc sp, ARMv6 and above support
+ MSR CPSR_c, #(CPSR_INT_DISABLE | CPSR_SVC_MODE) @ Switch to svc mode, and disable all interrupt
+ STMFD SP!, {R0-R3, R12, LR}
+ STMFD SP, {R13, R14}^
+ SUB SP, SP, #(2 * 4)
+
+ MOV R2, #0
+ MOV R3, #0
+ STMFD SP!, {R2-R3} @ far and fsr fields, are 0 under this anomaly
+ STMFD SP!, {R4-R11}
+
+@ Description: Exception handler
+@ Parameter : R0 Exception Type
+@ Regs Hold : R3 Exception`s CPSR
+_osExceptDispatch:
+ LDR R8, [SP, #(8 * 4)] @ Get far
+ LDR R9, [SP, #(9 * 4)] @ Get fsr
+
+ ADD R2, SP, #(20 * 4) @ sp + sizeof(ExcContext), position of SVC stack before exception
+ STR R2, [SP, #(8 * 4)] @ Save svc sp
+
+ MOV R1, SP
+
+#ifdef LOSCFG_KERNEL_VM
+ LDR R2, [SP, #(19 * 4)] @ Get CPSR
+ AND R2, R2, #CPSR_MASK_MODE @ Interrupted mode
+ CMP R2, #CPSR_USER_MODE @ User mode
+ BEQ _osExceptionGetSP
+#endif
+
+ EXC_SP_SET __exc_stack_top, OS_EXC_STACK_SIZE, R6, R7
+
+ MRC P15, 0, R4, C0, C0, 5
+ AND R4, R4, #MPIDR_CPUID_MASK @ Get Current cpu id
+ LSL R2, R4, #2
+ LDR R3, =g_curNestCount @ if(g_curNestCount > 0) dump to _osExceptionGetSP
+ ADD R3, R3, R2
+ LDR R4, [R3]
+
+ CMP R4, #0
+ BNE _osExceptionGetSP
+
+ LDR R3, =g_intCount @ Judge the exception is occur in task stack or system stack
+ ADD R3, R3, R2
+ LDR R4, [R3]
+
+ CMP R4, #0 @ if (g_intCount[ArchCurrCpuid()] > 0)
+ BNE _osExceptionGetSP @ can not switch svc stack
+
+ EXC_SP_SET __svc_stack_top, OS_EXC_SVC_STACK_SIZE, R6, R7 @ Switch to unified exception stack.
+ ADD R4, R4, #1
+ STR R4, [R3]
+
+_osExceptionGetSP:
+ MOV R2, R8 @ far
+ MOV R3, R9 @ fsr
+ LDR R5, =OsExcHandleEntry @ OsExcHandleEntry(UINT32 excType, ExcContext * excBufAddr)
+ BX R5
+
+ .end
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/los_hw_runstop.S b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/los_hw_runstop.S
new file mode 100644
index 00000000..b8f8cf74
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/los_hw_runstop.S
@@ -0,0 +1,132 @@
+/*
+ * 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 "arch_config.h"
+
+ .equ MPIDR_CPUID_MASK, 0xffU
+
+ .extern g_saveAR
+ .extern g_saveSRContext
+
+ .global OsSRSaveRegister
+ .global OsSRRestoreRegister
+
+ .fpu vfpv4
+ @.fpu neon
+ .arch armv7a
+
+ .text
+
+OsSRSaveRegister:
+ PUSH {R2}
+ LDR R2, =g_saveAR
+ STR R0, [R2]
+ STR R1, [R2, #4]
+ POP {R2}
+
+ MRC P15, 0, R0, c0, c0, 5
+ AND R0, R0, #MPIDR_CPUID_MASK
+ MOV R1, #72 @This number is the total number of bytes in the task context register(R0~R15, SPSR, CPSR).
+ MUL R1, R1, R0
+
+ LDR R0, =g_saveSRContext
+ ADD R0, R0, R1
+ ADD R0, R0, #72
+
+ MOV R1, SP
+ STMFD R0!, {R1}
+
+ MRS R1, SPSR
+ STMFD R0!, {R1}
+
+ MOV R1, LR
+ STMFD R0!, {R1} @PC
+ STMFD R0!, {R1} @LR
+
+ STMFD R0!, {R12}
+
+ MOV R12, R0
+
+ LDR R0, =g_saveAR
+ LDR R0, [R0]
+ LDR R1, =g_saveAR
+ LDR R1, [R1, #4]
+
+ STMFD R12!, {R0-R3}
+ STMFD R12!, {R4-R11}
+
+ MRS R0, CPSR
+ STMFD R12!, {R0}
+
+ BX LR
+
+OsSRRestoreRegister:
+ MRC P15, 0, R0, c0, c0, 5
+ AND R0, R0, #MPIDR_CPUID_MASK
+ MOV R1, #72 @This number is the total number of bytes in the task context register(R0~R15, SPSR, CPSR).
+ MUL R1, R1, R0
+
+ LDR R12, =g_saveSRContext
+ ADD R12, R12, R1
+
+ LDMFD R12!, {R0}
+ MSR CPSR_cxsf, R0
+
+ LDMFD R12!, {R4-R11}
+ LDMFD R12!, {R0-R3}
+
+ PUSH {R2}
+ LDR R2, =g_saveAR
+ STR R0, [R2]
+ STR R1, [R2, #4]
+ POP {R2}
+
+ MOV R0, R12
+ LDMFD R0!, {R12}
+ LDMFD R0!, {R1} @LR
+ LDMFD R0!, {R1} @PC
+
+ MOV LR, R1
+
+ LDMFD R0!, {R1}
+ MSR SPSR_cxsf, R1
+
+ LDMFD R0!, {R1}
+ MOV SP, R1
+
+ LDR R0, =g_saveAR
+ LDR R0, [R0]
+ LDR R1, =g_saveAR
+ LDR R1, [R1, #4]
+
+ BX LR
+
+ .end
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/los_hw_tick.c b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/los_hw_tick.c
new file mode 100644
index 00000000..4210f638
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/los_hw_tick.c
@@ -0,0 +1,76 @@
+/*
+ * 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_sys_pri.h"
+#include "los_hwi.h"
+
+
+LITE_OS_SEC_TEXT_INIT UINT32 OsTickInit(UINT32 systemClock, UINT32 tickPerSecond)
+{
+ if ((systemClock == 0) ||
+ (tickPerSecond == 0) ||
+ (tickPerSecond > systemClock)) {
+ return LOS_ERRNO_TICK_CFG_INVALID;
+ }
+ HalClockInit();
+
+ return LOS_OK;
+}
+
+LITE_OS_SEC_TEXT_INIT VOID OsTickStart(VOID)
+{
+ HalClockStart();
+}
+
+LITE_OS_SEC_TEXT_MINOR VOID LOS_GetCpuCycle(UINT32 *highCnt, UINT32 *lowCnt)
+{
+ UINT64 cycle = HalClockGetCycles();
+
+ *highCnt = cycle >> 32; /* 32: offset 32 bits and retain high bits */
+ *lowCnt = cycle & 0xFFFFFFFFU;
+}
+
+LITE_OS_SEC_TEXT_MINOR UINT64 LOS_CurrNanosec(VOID)
+{
+ UINT64 cycle = HalClockGetCycles();
+ return (cycle / g_sysClock) * OS_SYS_NS_PER_SECOND + (cycle % g_sysClock) * OS_SYS_NS_PER_SECOND / g_sysClock;
+}
+
+LITE_OS_SEC_TEXT_MINOR VOID LOS_Udelay(UINT32 usecs)
+{
+ HalDelayUs(usecs);
+}
+
+LITE_OS_SEC_TEXT_MINOR VOID LOS_Mdelay(UINT32 msecs)
+{
+ HalDelayUs(msecs * 1000); /* 1000 : 1ms = 1000us */
+}
+
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/los_hwi.c b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/los_hwi.c
new file mode 100644
index 00000000..0fd86da5
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/los_hwi.c
@@ -0,0 +1,350 @@
+/*
+ * 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_hwi.h"
+#include "los_memory.h"
+#include "los_spinlock.h"
+#ifdef LOSCFG_KERNEL_CPUP
+#include "los_cpup_pri.h"
+#endif
+#include "los_sched_pri.h"
+#include "los_hook.h"
+
+/* spinlock for hwi module, only available on SMP mode */
+LITE_OS_SEC_BSS SPIN_LOCK_INIT(g_hwiSpin);
+#define HWI_LOCK(state) LOS_SpinLockSave(&g_hwiSpin, &(state))
+#define HWI_UNLOCK(state) LOS_SpinUnlockRestore(&g_hwiSpin, (state))
+
+size_t g_intCount[LOSCFG_KERNEL_CORE_NUM] = {0};
+HwiHandleForm g_hwiForm[OS_HWI_MAX_NUM];
+STATIC CHAR *g_hwiFormName[OS_HWI_MAX_NUM] = {0};
+STATIC UINT32 g_hwiFormCnt[OS_HWI_MAX_NUM] = {0};
+
+VOID OsIncHwiFormCnt(UINT32 index)
+{
+ g_hwiFormCnt[index]++;
+}
+
+UINT32 OsGetHwiFormCnt(UINT32 index)
+{
+ return g_hwiFormCnt[index];
+}
+
+CHAR *OsGetHwiFormName(UINT32 index)
+{
+ return g_hwiFormName[index];
+}
+
+UINT32 LOS_GetSystemHwiMaximum(VOID)
+{
+ return OS_HWI_MAX_NUM;
+}
+
+typedef VOID (*HWI_PROC_FUNC0)(VOID);
+typedef VOID (*HWI_PROC_FUNC2)(INT32, VOID *);
+VOID OsInterrupt(UINT32 intNum)
+{
+ HwiHandleForm *hwiForm = NULL;
+ UINT32 *intCnt = NULL;
+
+ /* Must keep the operation at the beginning of the interface */
+ intCnt = &g_intCount[ArchCurrCpuid()];
+ *intCnt = *intCnt + 1;
+
+ OsSchedIrqStartTime();
+
+#ifdef LOSCFG_CPUP_INCLUDE_IRQ
+ OsCpupIrqStart();
+#endif
+ OsHookCall(LOS_HOOK_TYPE_ISR_ENTER, intNum);
+ hwiForm = (&g_hwiForm[intNum]);
+#ifndef LOSCFG_NO_SHARED_IRQ
+ while (hwiForm->pstNext != NULL) {
+ hwiForm = hwiForm->pstNext;
+#endif
+ if (hwiForm->uwParam) {
+ HWI_PROC_FUNC2 func = (HWI_PROC_FUNC2)hwiForm->pfnHook;
+ if (func != NULL) {
+ UINTPTR *param = (UINTPTR *)(hwiForm->uwParam);
+ func((INT32)(*param), (VOID *)(*(param + 1)));
+ }
+ } else {
+ HWI_PROC_FUNC0 func = (HWI_PROC_FUNC0)hwiForm->pfnHook;
+ if (func != NULL) {
+ func();
+ }
+ }
+#ifndef LOSCFG_NO_SHARED_IRQ
+ }
+#endif
+ ++g_hwiFormCnt[intNum];
+
+ OsHookCall(LOS_HOOK_TYPE_ISR_EXIT, intNum);
+#ifdef LOSCFG_CPUP_INCLUDE_IRQ
+ OsCpupIrqEnd(intNum);
+#endif
+ OsSchedIrqUpdateUsedTime();
+
+ /* Must keep the operation at the end of the interface */
+ *intCnt = *intCnt - 1;
+}
+
+STATIC HWI_ARG_T OsHwiCpIrqParam(const HwiIrqParam *irqParam)
+{
+ HwiIrqParam *paramByAlloc = NULL;
+
+ if (irqParam != NULL) {
+ paramByAlloc = (HwiIrqParam *)LOS_MemAlloc(m_aucSysMem0, sizeof(HwiIrqParam));
+ if (paramByAlloc == NULL) {
+ return LOS_NOK;
+ }
+ (VOID)memcpy_s(paramByAlloc, sizeof(HwiIrqParam), irqParam, sizeof(HwiIrqParam));
+ }
+ /* When "irqParam" is NULL, the function return 0(LOS_OK). */
+ return (HWI_ARG_T)paramByAlloc;
+}
+
+#ifdef LOSCFG_NO_SHARED_IRQ
+STATIC UINT32 OsHwiDelNoShared(HWI_HANDLE_T hwiNum)
+{
+ UINT32 intSave;
+
+ HWI_LOCK(intSave);
+ g_hwiForm[hwiNum].pfnHook = NULL;
+ if (g_hwiForm[hwiNum].uwParam) {
+ (VOID)LOS_MemFree(m_aucSysMem0, (VOID *)g_hwiForm[hwiNum].uwParam);
+ }
+ g_hwiForm[hwiNum].uwParam = 0;
+
+ HWI_UNLOCK(intSave);
+ return LOS_OK;
+}
+
+STATIC UINT32 OsHwiCreateNoShared(HWI_HANDLE_T hwiNum, HWI_MODE_T hwiMode,
+ HWI_PROC_FUNC hwiHandler, const HwiIrqParam *irqParam)
+{
+ HWI_ARG_T retParam;
+ UINT32 intSave;
+
+ HWI_LOCK(intSave);
+ if (g_hwiForm[hwiNum].pfnHook == NULL) {
+ g_hwiForm[hwiNum].pfnHook = hwiHandler;
+
+ retParam = OsHwiCpIrqParam(irqParam);
+ if (retParam == LOS_NOK) {
+ HWI_UNLOCK(intSave);
+ return OS_ERRNO_HWI_NO_MEMORY;
+ }
+ g_hwiForm[hwiNum].uwParam = retParam;
+ } else {
+ HWI_UNLOCK(intSave);
+ return OS_ERRNO_HWI_ALREADY_CREATED;
+ }
+ HWI_UNLOCK(intSave);
+ return LOS_OK;
+}
+#else
+STATIC UINT32 OsHwiDelShared(HWI_HANDLE_T hwiNum, const HwiIrqParam *irqParam)
+{
+ HwiHandleForm *hwiForm = NULL;
+ HwiHandleForm *hwiFormtmp = NULL;
+ UINT32 hwiValid = FALSE;
+ UINT32 intSave;
+
+ HWI_LOCK(intSave);
+ hwiForm = &g_hwiForm[hwiNum];
+ hwiFormtmp = hwiForm;
+
+ if ((hwiForm->uwParam & IRQF_SHARED) && ((irqParam == NULL) || (irqParam->pDevId == NULL))) {
+ HWI_UNLOCK(intSave);
+ return OS_ERRNO_HWI_SHARED_ERROR;
+ }
+
+ if ((hwiForm->pstNext != NULL) && !(hwiForm->uwParam & IRQF_SHARED)) {
+ hwiForm = hwiForm->pstNext;
+ if (hwiForm->uwParam) {
+ (VOID)LOS_MemFree(m_aucSysMem0, (VOID *)hwiForm->uwParam);
+ }
+ (VOID)LOS_MemFree(m_aucSysMem0, hwiForm);
+ hwiFormtmp->pstNext = NULL;
+
+ g_hwiFormName[hwiNum] = NULL;
+
+ HWI_UNLOCK(intSave);
+ return LOS_OK;
+ }
+ hwiForm = hwiForm->pstNext;
+ while (hwiForm != NULL) {
+ if (((HwiIrqParam *)(hwiForm->uwParam))->pDevId != irqParam->pDevId) {
+ hwiFormtmp = hwiForm;
+ hwiForm = hwiForm->pstNext;
+ } else {
+ hwiFormtmp->pstNext = hwiForm->pstNext;
+ (VOID)LOS_MemFree(m_aucSysMem0, (VOID *)hwiForm->uwParam);
+ (VOID)LOS_MemFree(m_aucSysMem0, hwiForm);
+
+ hwiValid = TRUE;
+ break;
+ }
+ }
+
+ if (hwiValid != TRUE) {
+ HWI_UNLOCK(intSave);
+ return OS_ERRNO_HWI_HWINUM_UNCREATE;
+ }
+
+ if (g_hwiForm[hwiNum].pstNext == NULL) {
+ g_hwiForm[hwiNum].uwParam = 0;
+ g_hwiFormName[hwiNum] = NULL;
+ }
+
+ HWI_UNLOCK(intSave);
+ return LOS_OK;
+}
+
+STATIC UINT32 OsHwiCreateShared(HWI_HANDLE_T hwiNum, HWI_MODE_T hwiMode,
+ HWI_PROC_FUNC hwiHandler, const HwiIrqParam *irqParam)
+{
+ UINT32 intSave;
+ HwiHandleForm *hwiFormNode = NULL;
+ HwiHandleForm *hwiForm = NULL;
+ HwiIrqParam *hwiParam = NULL;
+ HWI_MODE_T modeResult = hwiMode & IRQF_SHARED;
+
+ if (modeResult && ((irqParam == NULL) || (irqParam->pDevId == NULL))) {
+ return OS_ERRNO_HWI_SHARED_ERROR;
+ }
+
+ HWI_LOCK(intSave);
+
+ hwiForm = &g_hwiForm[hwiNum];
+ if ((hwiForm->pstNext != NULL) && ((modeResult == 0) || (!(hwiForm->uwParam & IRQF_SHARED)))) {
+ HWI_UNLOCK(intSave);
+ return OS_ERRNO_HWI_SHARED_ERROR;
+ }
+
+ while (hwiForm->pstNext != NULL) {
+ hwiForm = hwiForm->pstNext;
+ hwiParam = (HwiIrqParam *)(hwiForm->uwParam);
+ if (hwiParam->pDevId == irqParam->pDevId) {
+ HWI_UNLOCK(intSave);
+ return OS_ERRNO_HWI_ALREADY_CREATED;
+ }
+ }
+
+ hwiFormNode = (HwiHandleForm *)LOS_MemAlloc(m_aucSysMem0, sizeof(HwiHandleForm));
+ if (hwiFormNode == NULL) {
+ HWI_UNLOCK(intSave);
+ return OS_ERRNO_HWI_NO_MEMORY;
+ }
+
+ hwiFormNode->uwParam = OsHwiCpIrqParam(irqParam);
+ if (hwiFormNode->uwParam == LOS_NOK) {
+ HWI_UNLOCK(intSave);
+ (VOID)LOS_MemFree(m_aucSysMem0, hwiFormNode);
+ return OS_ERRNO_HWI_NO_MEMORY;
+ }
+
+ hwiFormNode->pfnHook = hwiHandler;
+ hwiFormNode->pstNext = (struct tagHwiHandleForm *)NULL;
+ hwiForm->pstNext = hwiFormNode;
+
+ if ((irqParam != NULL) && (irqParam->pName != NULL)) {
+ g_hwiFormName[hwiNum] = (CHAR *)irqParam->pName;
+ }
+
+ g_hwiForm[hwiNum].uwParam = modeResult;
+
+ HWI_UNLOCK(intSave);
+ return LOS_OK;
+}
+#endif
+
+/*
+ * Description : initialization of the hardware interrupt
+ */
+LITE_OS_SEC_TEXT_INIT VOID OsHwiInit(VOID)
+{
+ UINT32 hwiNum;
+
+ for (hwiNum = 0; hwiNum < OS_HWI_MAX_NUM; hwiNum++) {
+ g_hwiForm[hwiNum].pfnHook = NULL;
+ g_hwiForm[hwiNum].uwParam = 0;
+ g_hwiForm[hwiNum].pstNext = NULL;
+ }
+
+ (VOID)memset_s(g_hwiFormName, (sizeof(CHAR *) * OS_HWI_MAX_NUM), 0, (sizeof(CHAR *) * OS_HWI_MAX_NUM));
+
+ HalIrqInit();
+
+ return;
+}
+
+LITE_OS_SEC_TEXT_INIT UINT32 LOS_HwiCreate(HWI_HANDLE_T hwiNum,
+ HWI_PRIOR_T hwiPrio,
+ HWI_MODE_T hwiMode,
+ HWI_PROC_FUNC hwiHandler,
+ HwiIrqParam *irqParam)
+{
+ UINT32 ret;
+
+ (VOID)hwiPrio;
+ if (hwiHandler == NULL) {
+ return OS_ERRNO_HWI_PROC_FUNC_NULL;
+ }
+ if ((hwiNum > OS_USER_HWI_MAX) || ((INT32)hwiNum < OS_USER_HWI_MIN)) {
+ return OS_ERRNO_HWI_NUM_INVALID;
+ }
+
+#ifdef LOSCFG_NO_SHARED_IRQ
+ ret = OsHwiCreateNoShared(hwiNum, hwiMode, hwiHandler, irqParam);
+#else
+ ret = OsHwiCreateShared(hwiNum, hwiMode, hwiHandler, irqParam);
+#endif
+ return ret;
+}
+
+LITE_OS_SEC_TEXT_INIT UINT32 LOS_HwiDelete(HWI_HANDLE_T hwiNum, HwiIrqParam *irqParam)
+{
+ UINT32 ret;
+
+ if ((hwiNum > OS_USER_HWI_MAX) || ((INT32)hwiNum < OS_USER_HWI_MIN)) {
+ return OS_ERRNO_HWI_NUM_INVALID;
+ }
+
+#ifdef LOSCFG_NO_SHARED_IRQ
+ ret = OsHwiDelNoShared(hwiNum);
+#else
+ ret = OsHwiDelShared(hwiNum, irqParam);
+#endif
+ return ret;
+}
+
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/pmu/armv7_pmu.c b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/pmu/armv7_pmu.c
new file mode 100644
index 00000000..df17555b
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/pmu/armv7_pmu.c
@@ -0,0 +1,373 @@
+/*
+ * 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 "armv7_pmu_pri.h"
+#include "perf_pmu_pri.h"
+#include "los_hw_cpu.h"
+#include "asm/platform.h"
+
+OS_PMU_INTS(LOSCFG_KERNEL_CORE_NUM, g_pmuIrqNr);
+STATIC HwPmu g_armv7Pmu;
+
+STATIC INLINE UINT32 Armv7PmncRead(VOID)
+{
+ UINT32 value = 0;
+ __asm__ volatile("mrc p15, 0, %0, c9, c12, 0" : "=r"(value));
+ return value;
+}
+
+STATIC INLINE VOID Armv7PmncWrite(UINT32 value)
+{
+ value &= ARMV7_PMNC_MASK;
+ __asm__ volatile("mcr p15, 0, %0, c9, c12, 0" : : "r"(value));
+ ISB;
+}
+
+STATIC INLINE UINT32 Armv7PmuOverflowed(UINT32 pmnc)
+{
+ return pmnc & ARMV7_OVERFLOWED_MASK;
+}
+
+STATIC INLINE UINT32 Armv7PmuCntOverflowed(UINT32 pmnc, UINT32 index)
+{
+ return pmnc & ARMV7_CNT2BIT(ARMV7_IDX2CNT(index));
+}
+
+STATIC INLINE UINT32 Armv7CntValid(UINT32 index)
+{
+ return index <= ARMV7_IDX_COUNTER_LAST;
+}
+
+STATIC INLINE VOID Armv7PmuSelCnt(UINT32 index)
+{
+ UINT32 counter = ARMV7_IDX2CNT(index);
+ __asm__ volatile("mcr p15, 0, %0, c9, c12, 5" : : "r" (counter));
+ ISB;
+}
+
+STATIC INLINE VOID Armv7PmuSetCntPeriod(UINT32 index, UINT32 period)
+{
+ if (!Armv7CntValid(index)) {
+ PRINT_ERR("CPU writing wrong counter %u\n", index);
+ } else if (index == ARMV7_IDX_CYCLE_COUNTER) {
+ __asm__ volatile("mcr p15, 0, %0, c9, c13, 0" : : "r" (period));
+ } else {
+ Armv7PmuSelCnt(index);
+ __asm__ volatile("mcr p15, 0, %0, c9, c13, 2" : : "r" (period));
+ }
+}
+
+STATIC INLINE VOID Armv7BindEvt2Cnt(UINT32 index, UINT32 value)
+{
+ PRINT_DEBUG("bind event: %u to counter: %u\n", value, index);
+ Armv7PmuSelCnt(index);
+ value &= ARMV7_EVTYPE_MASK;
+ __asm__ volatile("mcr p15, 0, %0, c9, c13, 1" : : "r" (value));
+}
+
+STATIC INLINE VOID Armv7EnableCnt(UINT32 index)
+{
+ UINT32 counter = ARMV7_IDX2CNT(index);
+ PRINT_DEBUG("index : %u, counter: %u\n", index, counter);
+ __asm__ volatile("mcr p15, 0, %0, c9, c12, 1" : : "r" (ARMV7_CNT2BIT(counter)));
+}
+
+STATIC INLINE VOID Armv7DisableCnt(UINT32 index)
+{
+ UINT32 counter = ARMV7_IDX2CNT(index);
+ PRINT_DEBUG("index : %u, counter: %u\n", index, counter);
+ __asm__ volatile("mcr p15, 0, %0, c9, c12, 2" : : "r" (ARMV7_CNT2BIT(counter)));
+}
+
+STATIC INLINE VOID Armv7EnableCntInterrupt(UINT32 index)
+{
+ UINT32 counter = ARMV7_IDX2CNT(index);
+ __asm__ volatile("mcr p15, 0, %0, c9, c14, 1" : : "r" (ARMV7_CNT2BIT(counter)));
+ ISB;
+}
+
+STATIC INLINE VOID Armv7DisableCntInterrupt(UINT32 index)
+{
+ UINT32 counter = ARMV7_IDX2CNT(index);
+ __asm__ volatile("mcr p15, 0, %0, c9, c14, 2" : : "r" (ARMV7_CNT2BIT(counter)));
+ /* Clear the overflow flag in case an interrupt is pending. */
+ __asm__ volatile("mcr p15, 0, %0, c9, c12, 3" : : "r" (ARMV7_CNT2BIT(counter)));
+ ISB;
+}
+
+STATIC INLINE UINT32 Armv7PmuGetOverflowStatus(VOID)
+{
+ UINT32 value;
+
+ __asm__ volatile("mrc p15, 0, %0, c9, c12, 3" : "=r" (value));
+ value &= ARMV7_FLAG_MASK;
+ __asm__ volatile("mcr p15, 0, %0, c9, c12, 3" : : "r" (value));
+
+ return value;
+}
+
+STATIC VOID Armv7EnableEvent(Event *event)
+{
+ UINT32 cnt = event->counter;
+
+ if (!Armv7CntValid(cnt)) {
+ PRINT_ERR("CPU enabling wrong PMNC counter IRQ enable %u\n", cnt);
+ return;
+ }
+
+ if (event->period == 0) {
+ PRINT_INFO("event period value not valid, counter: %u\n", cnt);
+ return;
+ }
+ /*
+ * Enable counter and interrupt, and set the counter to count
+ * the event that we're interested in.
+ */
+ UINT32 intSave = LOS_IntLock();
+
+ Armv7DisableCnt(cnt);
+
+ /*
+ * Set event (if destined for PMNx counters)
+ * We only need to set the event for the cycle counter if we
+ * have the ability to perform event filtering.
+ */
+ if (cnt != ARMV7_IDX_CYCLE_COUNTER) {
+ Armv7BindEvt2Cnt(cnt, event->eventId);
+ }
+
+ /* Enable interrupt for this counter */
+ Armv7EnableCntInterrupt(cnt);
+ Armv7EnableCnt(cnt);
+ LOS_IntRestore(intSave);
+
+ PRINT_DEBUG("enabled event: %u cnt: %u\n", event->eventId, cnt);
+}
+
+STATIC VOID Armv7DisableEvent(Event *event)
+{
+ UINT32 cnt = event->counter;
+
+ if (!Armv7CntValid(cnt)) {
+ PRINT_ERR("CPU enabling wrong PMNC counter IRQ enable %u\n", cnt);
+ return;
+ }
+
+ UINT32 intSave = LOS_IntLock();
+ Armv7DisableCnt(cnt);
+ Armv7DisableCntInterrupt(cnt);
+ LOS_IntRestore(intSave);
+}
+
+
+STATIC VOID Armv7StartAllCnt(VOID)
+{
+ PRINT_DEBUG("starting pmu...\n");
+
+ /* Enable all counters */
+ UINT32 reg = Armv7PmncRead() | ARMV7_PMNC_E;
+ if (g_armv7Pmu.cntDivided) {
+ reg |= ARMV7_PMNC_D;
+ } else {
+ reg &= ~ARMV7_PMNC_D;
+ }
+
+ Armv7PmncWrite(reg);
+ HalIrqUnmask(g_pmuIrqNr[ArchCurrCpuid()]);
+}
+
+STATIC VOID Armv7StopAllCnt(VOID)
+{
+ PRINT_DEBUG("stopping pmu...\n");
+ /* Disable all counters */
+ Armv7PmncWrite(Armv7PmncRead() & ~ARMV7_PMNC_E);
+
+ HalIrqMask(g_pmuIrqNr[ArchCurrCpuid()]);
+}
+
+STATIC VOID Armv7ResetAllCnt(VOID)
+{
+ UINT32 index;
+
+ /* The counter and interrupt enable registers are unknown at reset. */
+ for (index = ARMV7_IDX_CYCLE_COUNTER; index < ARMV7_IDX_MAX_COUNTER; index++) {
+ Armv7DisableCnt(index);
+ Armv7DisableCntInterrupt(index);
+ }
+
+ /* Initialize & Reset PMNC: C and P bits and D bits */
+ UINT32 reg = ARMV7_PMNC_P | ARMV7_PMNC_C | (g_armv7Pmu.cntDivided ? ARMV7_PMNC_D : 0);
+ Armv7PmncWrite(reg);
+}
+
+STATIC VOID Armv7SetEventPeriod(Event *event)
+{
+ if (event->period != 0) {
+ PRINT_INFO("counter: %u, period: 0x%x\n", event->counter, event->period);
+ Armv7PmuSetCntPeriod(event->counter, PERIOD_CALC(event->period));
+ }
+}
+
+STATIC UINTPTR Armv7ReadEventCnt(Event *event)
+{
+ UINT32 value = 0;
+ UINT32 index = event->counter;
+
+ if (!Armv7CntValid(index)) {
+ PRINT_ERR("CPU reading wrong counter %u\n", index);
+ } else if (index == ARMV7_IDX_CYCLE_COUNTER) {
+ __asm__ volatile("mrc p15, 0, %0, c9, c13, 0" : "=r" (value));
+ } else {
+ Armv7PmuSelCnt(index);
+ __asm__ volatile("mrc p15, 0, %0, c9, c13, 2" : "=r" (value));
+ }
+
+ if (value < PERIOD_CALC(event->period)) {
+ if (Armv7PmuCntOverflowed(Armv7PmuGetOverflowStatus(), event->counter)) {
+ value += event->period;
+ }
+ } else {
+ value -= PERIOD_CALC(event->period);
+ }
+ return value;
+}
+
+STATIC const UINT32 g_armv7Map[] = {
+ [PERF_COUNT_HW_CPU_CYCLES] = ARMV7_PERF_HW_CYCLES,
+ [PERF_COUNT_HW_INSTRUCTIONS] = ARMV7_PERF_HW_INSTRUCTIONS,
+ [PERF_COUNT_HW_DCACHE_REFERENCES] = ARMV7_PERF_HW_DCACHES,
+ [PERF_COUNT_HW_DCACHE_MISSES] = ARMV7_PERF_HW_DCACHE_MISSES,
+ [PERF_COUNT_HW_ICACHE_REFERENCES] = ARMV7_PERF_HW_ICACHES,
+ [PERF_COUNT_HW_ICACHE_MISSES] = ARMV7_PERF_HW_ICACHE_MISSES,
+ [PERF_COUNT_HW_BRANCH_INSTRUCTIONS] = ARMV7_PERF_HW_BRANCHES,
+ [PERF_COUNT_HW_BRANCH_MISSES] = ARMV7_PERF_HW_BRANCE_MISSES,
+};
+
+UINT32 Armv7PmuMapEvent(UINT32 eventType, BOOL reverse)
+{
+ if (!reverse) { /* Common event to armv7 real event */
+ if (eventType < ARRAY_SIZE(g_armv7Map)) {
+ return g_armv7Map[eventType];
+ }
+ return eventType;
+ } else { /* Armv7 real event to common event */
+ UINT32 i;
+ for (i = 0; i < ARRAY_SIZE(g_armv7Map); i++) {
+ if (g_armv7Map[i] == eventType) {
+ return i;
+ }
+ }
+ return PERF_HW_INVALID_EVENT_TYPE;
+ }
+}
+
+STATIC VOID Armv7PmuIrqHandler(VOID)
+{
+ UINT32 index;
+ PerfRegs regs;
+
+ PerfEvent *events = &(g_armv7Pmu.pmu.events);
+ UINT32 eventNum = events->nr;
+
+ /* Get and reset the IRQ flags */
+ UINT32 pmnc = Armv7PmuGetOverflowStatus();
+ if (!Armv7PmuOverflowed(pmnc)) {
+ return;
+ }
+
+ (VOID)memset_s(®s, sizeof(PerfRegs), 0, sizeof(PerfRegs));
+ OsPerfFetchIrqRegs(®s);
+
+ Armv7StopAllCnt();
+
+ for (index = 0; index < eventNum; index++) {
+ Event *event = &(events->per[index]);
+ /*
+ * We have a single interrupt for all counters. Check that
+ * each counter has overflowed before we process it.
+ */
+ if (!Armv7PmuCntOverflowed(pmnc, event->counter) || (event->period == 0)) {
+ continue;
+ }
+
+ Armv7PmuSetCntPeriod(event->counter, PERIOD_CALC(event->period));
+
+ OsPerfUpdateEventCount(event, event->period);
+ OsPerfHandleOverFlow(event, ®s);
+ }
+ Armv7StartAllCnt();
+}
+
+UINT32 OsGetPmuMaxCounter(VOID)
+{
+ return ARMV7_IDX_MAX_COUNTER;
+}
+
+UINT32 OsGetPmuCycleCounter(VOID)
+{
+ return ARMV7_IDX_CYCLE_COUNTER;
+}
+
+UINT32 OsGetPmuCounter0(VOID)
+{
+ return ARMV7_IDX_COUNTER0;
+}
+
+STATIC HwPmu g_armv7Pmu = {
+ .canDivided = TRUE,
+ .enable = Armv7EnableEvent,
+ .disable = Armv7DisableEvent,
+ .start = Armv7StartAllCnt,
+ .stop = Armv7StopAllCnt,
+ .clear = Armv7ResetAllCnt,
+ .setPeriod = Armv7SetEventPeriod,
+ .readCnt = Armv7ReadEventCnt,
+ .mapEvent = Armv7PmuMapEvent,
+};
+
+UINT32 OsHwPmuInit(VOID)
+{
+ UINT32 ret;
+ UINT32 index;
+
+ for (index = 0; index < LOSCFG_KERNEL_CORE_NUM; index++) {
+ ret = LOS_HwiCreate(g_pmuIrqNr[index], 0, 0, Armv7PmuIrqHandler, 0);
+ if (ret != LOS_OK) {
+ PRINT_ERR("pmu %u irq handler register failed\n", g_pmuIrqNr[index]);
+ return ret;
+ }
+#ifdef LOSCFG_KERNEL_SMP
+ HalIrqSetAffinity(g_pmuIrqNr[index], CPUID_TO_AFFI_MASK(index));
+#endif
+ }
+ ret = OsPerfHwInit(&g_armv7Pmu);
+ return ret;
+}
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/smp.c b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/smp.c
new file mode 100644
index 00000000..fef09f13
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/smp.c
@@ -0,0 +1,104 @@
+/*
+ * 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 "smp.h"
+#include "arch_config.h"
+#include "los_base.h"
+#include "los_hw.h"
+#include "los_atomic.h"
+#include "los_arch_mmu.h"
+#include "gic_common.h"
+#include "los_task_pri.h"
+
+#ifdef LOSCFG_KERNEL_SMP
+
+extern VOID reset_vector(VOID);
+
+struct OsCpuInit {
+ ArchCpuStartFunc cpuStart;
+ VOID *arg;
+ Atomic initFlag;
+};
+
+STATIC struct OsCpuInit g_cpuInit[CORE_NUM - 1] = {0};
+
+VOID HalArchCpuOn(UINT32 cpuNum, ArchCpuStartFunc func, struct SmpOps *ops, VOID *arg)
+{
+ struct OsCpuInit *cpuInit = &g_cpuInit[cpuNum - 1];
+ UINTPTR startEntry = (UINTPTR)&reset_vector - KERNEL_VMM_BASE + SYS_MEM_BASE;
+ INT32 ret;
+
+ cpuInit->cpuStart = func;
+ cpuInit->arg = arg;
+ cpuInit->initFlag = 0;
+
+ DCacheFlushRange((UINTPTR)cpuInit, (UINTPTR)cpuInit + sizeof(struct OsCpuInit));
+
+ LOS_ASSERT(ops != NULL);
+
+
+ ret = ops->SmpCpuOn(cpuNum, startEntry);
+ if (ret < 0) {
+ PRINT_ERR("cpu start failed, cpu num: %u, ret: %d\n", cpuNum, ret);
+ return;
+ }
+
+ while (!LOS_AtomicRead(&cpuInit->initFlag)) {
+ WFE;
+ }
+}
+
+VOID HalSecondaryCpuStart(VOID)
+{
+ UINT32 cpuid = ArchCurrCpuid();
+ struct OsCpuInit *cpuInit = &g_cpuInit[cpuid - 1];
+
+ OsCurrTaskSet(OsGetMainTask());
+
+ LOS_AtomicSet(&cpuInit->initFlag, 1);
+ SEV;
+
+#ifdef LOSCFG_KERNEL_MMU
+ OsArchMmuInitPerCPU();
+#endif
+
+ /* store each core's hwid */
+ CPU_MAP_SET(cpuid, OsHwIDGet());
+ HalIrqInitPercpu();
+
+ cpuInit->cpuStart(cpuInit->arg);
+
+ while (1) {
+ WFI;
+ }
+}
+#endif
+
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/startup/reset_vector_mp.S b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/startup/reset_vector_mp.S
new file mode 100644
index 00000000..7f7e2962
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/startup/reset_vector_mp.S
@@ -0,0 +1,458 @@
+/*
+ * 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.
+ */
+
+#define ASSEMBLY
+#include "arch_config.h"
+#include "los_vm_boot.h"
+#include "los_vm_zone.h"
+#include "los_mmu_descriptor_v6.h"
+#undef ASSEMBLY
+
+
+ .global __exc_stack_top
+ .global __svc_stack_top
+ .global __exc_stack
+ .global __svc_stack
+
+ .extern __bss_start
+ .extern __bss_end
+ .extern hal_clock_initialize_start
+ .extern los_bss_init
+ .extern _osExceptFiqHdl
+ .extern _osExceptAddrAbortHdl
+ .extern _osExceptDataAbortHdl
+ .extern _osExceptPrefetchAbortHdl
+ .extern _osExceptSwiHdl
+ .extern _osExceptUndefInstrHdl
+ .extern __stack_chk_guard_setup
+ .extern g_firstPageTable
+ .extern g_mmuJumpPageTable
+ .extern g_archMmuInitMapping
+ .extern HalSecondaryCpuStart
+
+ .equ MPIDR_CPUID_MASK, 0xffU
+
+ .fpu neon-vfpv4
+ .syntax unified
+ .arch armv7-a
+ .arm
+
+/* param0 is stack bottom, param1 is stack size, r12 hold cpu id */
+.macro EXC_SP_SET param0, param1
+ ldr r1, =\param0
+ mov r0, \param1
+ bl sp_set
+.endm
+
+/* param0 is stack top, param1 is stack size, param2 is magic num */
+.macro STACK_MAGIC_SET param0, param1, param2
+ ldr r0, =\param0
+ mov r1, \param1
+ ldr r2, =\param2
+ bl excstack_magic
+.endm
+
+ .code 32
+ .section ".vectors","ax"
+
+ .global __exception_handlers
+__exception_handlers:
+ /*
+ *Assumption: ROM code has these vectors at the hardware reset address.
+ *A simple jump removes any address-space dependencies [i.e. safer]
+ */
+ b reset_vector
+ b _osExceptUndefInstrHdl
+ b _osExceptSwiHdl
+ b _osExceptPrefetchAbortHdl
+ b _osExceptDataAbortHdl
+ b _osExceptAddrAbortHdl
+ b OsIrqHandler
+ b _osExceptFiqHdl
+
+ /* Startup code which will get the machine into supervisor mode */
+ .global reset_vector
+ .type reset_vector,function
+
+#ifdef LOSCFG_BOOTENV_RAM
+__quickstart_args_start:
+ .fill LOSCFG_BOOTENV_RAMSIZE,1,0
+__quickstart_args_end:
+
+.global OsGetArgsAddr
+.type OsGetArgsAddr,function
+
+OsGetArgsAddr:
+ ldr r0, =__quickstart_args_start
+ bx lr
+#endif
+
+reset_vector:
+ /* clear register TPIDRPRW */
+ mov r0, #0
+ mcr p15, 0, r0, c13, c0, 4
+ /* do some early cpu setup: i/d cache disable, mmu disabled */
+ mrc p15, 0, r0, c1, c0, 0
+ bic r0, #(1<<12)
+ bic r0, #(1<<2 | 1<<0)
+ mcr p15, 0, r0, c1, c0, 0
+
+ /* enable fpu+neon */
+#ifndef LOSCFG_TEE_ENABLE
+ MRC p15, 0, r0, c1, c1, 2
+ ORR r0, r0, #0xC00
+ BIC r0, r0, #0xC000
+ MCR p15, 0, r0, c1, c1, 2
+
+ LDR r0, =(0xF << 20)
+ MCR p15, 0, r0, c1, c0, 2
+ ISB
+#endif
+ MOV r3, #0x40000000
+ VMSR FPEXC, r3
+
+ /* r11: delta of physical address and virtual address */
+ adr r11, pa_va_offset
+ ldr r0, [r11]
+ sub r11, r11, r0
+
+ mrc p15, 0, r12, c0, c0, 5 /* r12: get cpuid */
+ and r12, r12, #MPIDR_CPUID_MASK
+ cmp r12, #0
+ bne secondary_cpu_init
+
+ /* if we need to relocate to proper location or not */
+ adr r4, __exception_handlers /* r4: base of load address */
+ ldr r5, =SYS_MEM_BASE /* r5: base of physical address */
+ subs r12, r4, r5 /* r12: delta of load address and physical address */
+ beq reloc_img_to_bottom_done /* if we load image at the bottom of physical address */
+
+ /* we need to relocate image at the bottom of physical address */
+ ldr r7, =__exception_handlers /* r7: base of linked address (or vm address) */
+ ldr r6, =__bss_start /* r6: end of linked address (or vm address) */
+ sub r6, r7 /* r6: delta of linked address (or vm address) */
+ add r6, r4 /* r6: end of load address */
+
+reloc_img_to_bottom_loop:
+ ldr r7, [r4], #4
+ str r7, [r5], #4
+ cmp r4, r6
+ bne reloc_img_to_bottom_loop
+ sub pc, r12
+ nop
+ sub r11, r11, r12 /* r11: eventual address offset */
+
+reloc_img_to_bottom_done:
+#ifdef LOSCFG_KERNEL_MMU
+ ldr r4, =g_firstPageTable /* r4: physical address of translation table and clear it */
+ add r4, r4, r11
+ mov r0, r4
+ mov r1, #0
+ mov r2, #MMU_DESCRIPTOR_L1_SMALL_ENTRY_NUMBERS
+ bl memset_optimized /* optimized memset since r0 is 64-byte aligned */
+
+ ldr r5, =g_archMmuInitMapping
+ add r5, r5, r11
+init_mmu_loop:
+ ldmia r5!, {r6-r10} /* r6 = phys, r7 = virt, r8 = size, r9 = mmu_flags, r10 = name */
+ cmp r8, 0 /* if size = 0, the mmu init done */
+ beq init_mmu_done
+ bl page_table_build
+ b init_mmu_loop
+init_mmu_done:
+ orr r8, r4, #MMU_TTBRx_FLAGS /* r8 = r4 and set cacheable attributes on translation walk */
+ ldr r4, =g_mmuJumpPageTable /* r4: jump pagetable vaddr */
+ add r4, r4, r11
+ ldr r4, [r4]
+ add r4, r4, r11 /* r4: jump pagetable paddr */
+
+ /* build 1M section mapping, in order to jump va during turing on mmu:pa == pa, va == pa */
+ mov r6, pc
+ mov r7, r6 /* r7: pa (MB aligned)*/
+ lsr r6, r6, #20 /* r6: va l1 index */
+ ldr r10, =MMU_DESCRIPTOR_KERNEL_L1_PTE_FLAGS
+ add r12, r10, r6, lsl #20 /* r12: pa |flags */
+ str r12, [r4, r7, lsr #(20 - 2)] /* jumpTable[paIndex] = pt entry */
+ rsb r7, r11, r6, lsl #20 /* r7: va */
+ str r12, [r4, r7, lsr #(20 - 2)] /* jumpTable[vaIndex] = pt entry */
+
+ bl mmu_setup /* set up the mmu */
+#endif
+ /* clear out the interrupt and exception stack and set magic num to check the overflow */
+ ldr r0, =__svc_stack
+ ldr r1, =__exc_stack_top
+ bl stack_init
+
+ STACK_MAGIC_SET __svc_stack, #OS_EXC_SVC_STACK_SIZE, OS_STACK_MAGIC_WORD
+ STACK_MAGIC_SET __exc_stack, #OS_EXC_STACK_SIZE, OS_STACK_MAGIC_WORD
+
+warm_reset:
+ /* initialize CPSR (machine state register) */
+ mov r0, #(CPSR_IRQ_DISABLE|CPSR_FIQ_DISABLE|CPSR_SVC_MODE)
+ msr cpsr, r0
+
+ /* Note: some functions in LIBGCC1 will cause a "restore from SPSR"!! */
+ msr spsr, r0
+
+ /* get cpuid and keep it in r12 */
+ mrc p15, 0, r12, c0, c0, 5
+ and r12, r12, #MPIDR_CPUID_MASK
+
+ /* set svc stack, every cpu has OS_EXC_SVC_STACK_SIZE stack */
+ ldr r0, =__svc_stack_top
+ mov r2, #OS_EXC_SVC_STACK_SIZE
+ mul r2, r2, r12
+ sub r0, r0, r2
+ mov sp, r0
+
+ LDR r0, =__exception_handlers
+ MCR p15, 0, r0, c12, c0, 0
+
+ cmp r12, #0
+ bne cpu_start
+
+clear_bss:
+ ldr r0, =__bss_start
+ ldr r2, =__bss_end
+ mov r1, #0
+ sub r2, r2, r0
+ bl memset
+
+#if defined(LOSCFG_CC_STACKPROTECTOR_ALL) || \
+ defined(LOSCFG_CC_STACKPROTECTOR_STRONG) || \
+ defined(LOSCFG_CC_STACKPROTECTOR)
+ bl __stack_chk_guard_setup
+#endif
+
+#ifdef LOSCFG_GDB_DEBUG
+ /* GDB_START - generate a compiled_breadk,This function will get GDB stubs started, with a proper environment */
+ bl GDB_START
+ .word 0xe7ffdeff
+#endif
+
+ bl main
+
+_start_hang:
+ b _start_hang
+#ifdef LOSCFG_KERNEL_MMU
+mmu_setup:
+ mov r12, #0
+ mcr p15, 0, r12, c8, c7, 0 /* Set c8 to control the TLB and set the mapping to invalid */
+ isb
+ mcr p15, 0, r12, c2, c0, 2 /* Initialize the c2 register */
+ isb
+ orr r12, r4, #MMU_TTBRx_FLAGS
+ mcr p15, 0, r12, c2, c0, 0 /* Set attributes and set temp page table */
+ isb
+ mov r12, #0x7 /* 0b0111 */
+ mcr p15, 0, r12, c3, c0, 0 /* Set DACR with 0b0111, client and manager domian */
+ isb
+ mrc p15, 0, r12, c1, c0, 1 /* ACTLR, Auxlliary Control Register */
+ orr r12, r12, #(1 << 6) /* SMP, Enables coherent requests to the processor. */
+ orr r12, r12, #(1 << 2) /* Enable D-side prefetch */
+ orr r12, r12, #(1 << 11) /* Global BP Enable bit */
+ mcr p15, 0, r12, c1, c0, 1 /* ACTLR, Auxlliary Control Register */
+ dsb
+ mrc p15, 0, r12, c1, c0, 0
+ bic r12, #(1 << 29 | 1 << 28)
+ orr r12, #(1 << 0)
+ bic r12, #(1 << 1)
+ orr r12, #(1 << 2)
+ orr r12, #(1 << 12)
+ mcr p15, 0, r12, c1, c0, 0 /* Set SCTLR with r12: Turn on the MMU, I/D cache Disable TRE/AFE */
+ isb
+ ldr pc, =1f /* Convert to VA */
+1:
+ mcr p15, 0, r8, c2, c0, 0 /* Go to the base address saved in C2: Jump to the page table */
+ isb
+ mov r12, #0
+ mcr p15, 0, r12, c8, c7, 0
+ isb
+ sub lr, r11 /* adjust lr with delta of physical address and virtual address */
+ bx lr
+#endif
+ .code 32
+
+ .global reset_platform
+ .type reset_platform,function
+reset_platform:
+#ifdef A7SEM_HAL_ROM_MONITOR
+ /* initialize CPSR (machine state register) */
+ mov r0, #(CPSR_IRQ_DISABLE|CPSR_FIQ_DISABLE|CPSR_SVC_MODE)
+ msr cpsr, r0
+ b warm_reset
+#else
+ mov r0, #0
+ mov pc, r0 // Jump to reset vector
+#endif
+
+cpu_start:
+#ifdef LOSCFG_KERNEL_MMU
+ ldr r4, =g_firstPageTable /* r4 = physical address of translation table and clear it */
+ add r4, r4, r11
+ orr r8, r4, #MMU_TTBRx_FLAGS
+
+ ldr r4, =g_mmuJumpPageTable /* r4 = tt_trampoline vaddr */
+ add r4, r4, r11
+ ldr r4, [r4]
+ add r4, r4, r11 /* r4 = tt_trampoline paddr */
+
+ bl mmu_setup
+#endif
+
+ bl HalSecondaryCpuStart
+ b .
+
+secondary_cpu_init:
+#ifdef LOSCFG_TEE_ENABLE
+ /* enable fpu+neon */
+ ldr r0, =0x60c00
+ MCR p15, 0, r0, c1, c1, 2
+
+ LDR r0, =(0xF << 20)
+ MCR p15, 0, r0, c1, c0, 2
+ cps #0x16
+ mov r1, #0x25
+ mcr p15, 0, r1, c1, c1, 0
+ cps #0x13
+#endif
+ bl warm_reset
+
+/*
+ * set sp for current cpu
+ * r1 is stack bottom, r0 is stack size, r12 hold cpu id
+ */
+sp_set:
+ mrc p15, 0, r12, c0, c0, 5
+ and r12, r12, #MPIDR_CPUID_MASK
+ mul r3, r0, r12
+ sub r2, r1, r3
+ mov sp, r2
+ bx lr /* set sp */
+
+/*
+ * r4: page table base address
+ * r6: physical address
+ * r7: virtual address
+ * r8: sizes
+ * r10: flags
+ * r9 and r12 will be used as variable
+ */
+#ifdef LOSCFG_KERNEL_MMU
+page_table_build:
+ mov r10, r6
+ bfc r10, #20, #12 /* r9: pa % MB */
+ add r8, r8, r10
+ add r8, r8, #(1 << 20)
+ sub r8, r8, #1
+ lsr r6, #20 /* r6 = physical address / MB */
+ lsr r7, #20 /* r7 = virtual address / MB */
+ lsr r8, #20 /* r8 = roundup(size, MB) */
+
+page_table_build_loop:
+ orr r12, r9, r6, lsl #20 /* r12: flags | physAddr */
+ str r12, [r4, r7, lsl #2] /* gPgTable[l1Index] = physAddr | flags */
+ add r6, #1 /* physAddr+ */
+ add r7, #1 /* l1Index++ */
+ subs r8, #1 /* sizes-- */
+ bne page_table_build_loop
+ bx lr
+#endif
+/*
+ * init stack to initial value
+ * r0 is stack mem start, r1 is stack mem end
+ */
+stack_init:
+ ldr r2, =OS_STACK_INIT
+ ldr r3, =OS_STACK_INIT
+ /* Main loop sets 32 bytes at a time. */
+stack_init_loop:
+ .irp offset, #0, #8, #16, #24
+ strd r2, r3, [r0, \offset]
+ .endr
+ add r0, #32
+ cmp r0, r1
+ blt stack_init_loop
+ bx lr
+
+pa_va_offset:
+ .word .
+
+/*
+ * set magic num to stack top for all cpu
+ * r0 is stack top, r1 is stack size, r2 is magic num
+ */
+excstack_magic:
+ mov r3, #0
+excstack_magic_loop:
+ str r2, [r0]
+ add r0, r0, r1
+ add r3, r3, #1
+ cmp r3, #CORE_NUM
+ blt excstack_magic_loop
+ bx lr
+
+#ifdef LOSCFG_KERNEL_MMU
+memset_optimized:
+ mov r3, r0
+ vdup.8 q0, r1
+ vmov q1, q0
+ vmov q2, q0
+ vmov q3, q0
+memset_optimized_loop:
+ subs r2, #64
+ vstmia r3!, {d0 - d7}
+ bge memset_optimized_loop
+ bx lr
+#endif
+init_done:
+ .long 0xDEADB00B
+
+ .code 32
+ .data
+
+init_flag:
+ .balign 4
+ .long 0
+
+ /*
+ * Temporary interrupt stack
+ */
+ .section ".int_stack", "wa", %nobits
+ .align 3
+
+__svc_stack:
+ .space OS_EXC_SVC_STACK_SIZE * CORE_NUM
+__svc_stack_top:
+
+__exc_stack:
+ .space OS_EXC_STACK_SIZE * CORE_NUM
+__exc_stack_top:
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/startup/reset_vector_up.S b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/startup/reset_vector_up.S
new file mode 100644
index 00000000..75994ac1
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/startup/reset_vector_up.S
@@ -0,0 +1,414 @@
+/*
+ * 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.
+ */
+
+#define ASSEMBLY
+#include "arch_config.h"
+#include "los_vm_boot.h"
+#include "los_vm_zone.h"
+#include "los_mmu_descriptor_v6.h"
+#undef ASSEMBLY
+
+
+ .global __exc_stack_top
+ .global __svc_stack_top
+ .global __exc_stack
+ .global __svc_stack
+
+ .extern __bss_start
+ .extern __bss_end
+ .extern hal_clock_initialize_start
+ .extern _osExceptFiqHdl
+ .extern _osExceptAddrAbortHdl
+ .extern _osExceptDataAbortHdl
+ .extern _osExceptPrefetchAbortHdl
+ .extern _osExceptSwiHdl
+ .extern _osExceptUndefInstrHdl
+ .extern __stack_chk_guard_setup
+ .extern g_firstPageTable
+ .extern g_mmuJumpPageTable
+ .extern g_archMmuInitMapping
+
+ .equ MPIDR_CPUID_MASK, 0xffU
+
+ .fpu neon-vfpv4
+ .syntax unified
+ .arch armv7-a
+ .arm
+
+/* param0 is stack bottom, param1 is stack size, r11 hold cpu id */
+.macro EXC_SP_SET param0, param1
+ ldr r1, =\param0
+ mov r0, \param1
+ bl sp_set
+.endm
+
+/* param0 is stack top, param1 is stack size, param2 is magic num */
+.macro STACK_MAGIC_SET param0, param1, param2
+ ldr r0, =\param0
+ mov r1, \param1
+ ldr r2, =\param2
+ bl excstack_magic
+.endm
+
+ .code 32
+ .section ".vectors","ax"
+
+__exception_handlers:
+ /*
+ *Assumption: ROM code has these vectors at the hardware reset address.
+ *A simple jump removes any address-space dependencies [i.e. safer]
+ */
+ b reset_vector
+ b _osExceptUndefInstrHdl
+ b _osExceptSwiHdl
+ b _osExceptPrefetchAbortHdl
+ b _osExceptDataAbortHdl
+ b _osExceptAddrAbortHdl
+ b OsIrqHandler
+ b _osExceptFiqHdl
+
+ /* Startup code which will get the machine into supervisor mode */
+ .global reset_vector
+ .type reset_vector,function
+reset_vector:
+ /* do some early cpu setup: i/d cache disable, mmu disabled */
+ mrc p15, 0, r0, c1, c0, 0
+ bic r0, #(1<<12)
+ bic r0, #(1<<2 | 1<<0)
+ mcr p15, 0, r0, c1, c0, 0
+
+ /* enable fpu+neon */
+#ifndef LOSCFG_TEE_ENABLE
+ MRC p15, 0, r0, c1, c1, 2
+ ORR r0, r0, #0xC00
+ BIC r0, r0, #0xC000
+ MCR p15, 0, r0, c1, c1, 2
+
+ LDR r0, =(0xF << 20)
+ MCR p15, 0, r0, c1, c0, 2
+ ISB
+#endif
+ MOV r3, #0x40000000
+ VMSR FPEXC, r3
+
+ /* r11: delta of physical address and virtual address */
+ adr r11, pa_va_offset
+ ldr r0, [r11]
+ sub r11, r11, r0
+
+ /* if we need to relocate to proper location or not */
+ adr r4, __exception_handlers /* r4: base of load address */
+ ldr r5, =SYS_MEM_BASE /* r5: base of physical address */
+ subs r12, r4, r5 /* r12: delta of load address and physical address */
+ beq reloc_img_to_bottom_done /* if we load image at the bottom of physical address */
+
+ /* we need to relocate image at the bottom of physical address */
+ ldr r7, =__exception_handlers /* r7: base of linked address (or vm address) */
+ ldr r6, =__bss_start /* r6: end of linked address (or vm address) */
+ sub r6, r7 /* r6: delta of linked address (or vm address) */
+ add r6, r4 /* r6: end of load address */
+
+reloc_img_to_bottom_loop:
+ ldr r7, [r4], #4
+ str r7, [r5], #4
+ cmp r4, r6
+ bne reloc_img_to_bottom_loop
+ sub pc, r12
+ nop
+ sub r11, r11, r12 /* r11: eventual address offset */
+
+reloc_img_to_bottom_done:
+#ifdef LOSCFG_KERNEL_MMU
+ ldr r4, =g_firstPageTable /* r4: physical address of translation table and clear it */
+ add r4, r4, r11
+ mov r0, r4
+ mov r1, #0
+ mov r2, #MMU_DESCRIPTOR_L1_SMALL_ENTRY_NUMBERS
+ bl memset_optimized /* optimized memset since r0 is 64-byte aligned */
+
+ ldr r5, =g_archMmuInitMapping
+ add r5, r5, r11
+init_mmu_loop:
+ ldmia r5!, {r6-r10} /* r6 = phys, r7 = virt, r8 = size, r9 = mmu_flags, r10 = name */
+ cmp r8, 0 /* if size = 0, the mmu init done */
+ beq init_mmu_done
+ bl page_table_build
+ b init_mmu_loop
+init_mmu_done:
+ orr r8, r4, #MMU_TTBRx_FLAGS /* r8 = r4 and set cacheable attributes on translation walk */
+ ldr r4, =g_mmuJumpPageTable /* r4: jump pagetable vaddr */
+ add r4, r4, r11
+ ldr r4, [r4]
+ add r4, r4, r11 /* r4: jump pagetable paddr */
+
+ /* build 1M section mapping, in order to jump va during turing on mmu:pa == pa, va == pa */
+ mov r6, pc
+ mov r7, r6 /* r7: pa (MB aligned)*/
+ lsr r6, r6, #20 /* r6: va l1 index */
+ ldr r10, =MMU_DESCRIPTOR_KERNEL_L1_PTE_FLAGS
+ add r12, r10, r6, lsl #20 /* r12: pa |flags */
+ str r12, [r4, r7, lsr #(20 - 2)] /* jumpTable[paIndex] = pt entry */
+ rsb r7, r11, r6, lsl #20 /* r7: va */
+ str r12, [r4, r7, lsr #(20 - 2)] /* jumpTable[vaIndex] = pt entry */
+
+ bl mmu_setup /* set up the mmu */
+#endif
+ /* get cpuid and keep it in r11 */
+ mrc p15, 0, r11, c0, c0, 5
+ and r11, r11, #MPIDR_CPUID_MASK
+ cmp r11, #0
+ bne excstatck_loop_done
+
+excstatck_loop:
+ /* clear out the interrupt and exception stack and set magic num to check the overflow */
+ ldr r0, =__svc_stack
+ ldr r1, =__exc_stack_top
+ bl stack_init
+
+ STACK_MAGIC_SET __svc_stack, #OS_EXC_SVC_STACK_SIZE, OS_STACK_MAGIC_WORD
+ STACK_MAGIC_SET __exc_stack, #OS_EXC_STACK_SIZE, OS_STACK_MAGIC_WORD
+
+excstatck_loop_done:
+warm_reset:
+ /* initialize CPSR (machine state register) */
+ mov r0, #(CPSR_IRQ_DISABLE|CPSR_FIQ_DISABLE|CPSR_SVC_MODE)
+ msr cpsr, r0
+
+ /* Note: some functions in LIBGCC1 will cause a "restore from SPSR"!! */
+ msr spsr, r0
+
+ /* set svc stack, every cpu has OS_EXC_SVC_STACK_SIZE stack */
+ ldr r0, =__svc_stack_top
+ mov r2, #OS_EXC_SVC_STACK_SIZE
+ mul r2, r2, r11
+ sub r0, r0, r2
+ mov sp, r0
+
+ /* enable fpu+neon */
+ MRC p15, 0, r0, c1, c1, 2
+ ORR r0, r0, #0xC00
+ BIC r0, r0, #0xC000
+ MCR p15, 0, r0, c1, c1, 2
+
+ LDR r0, =(0xF << 20)
+ MCR p15, 0, r0, c1, c0, 2
+
+ MOV r3, #0x40000000
+ VMSR FPEXC, r3
+
+ LDR r0, =__exception_handlers
+ MCR p15, 0, r0, c12, c0, 0
+
+clear_bss:
+ ldr r0, =__bss_start
+ ldr r2, =__bss_end
+ mov r1, #0
+ sub r2, r2, r0
+ bl memset
+
+#if defined(LOSCFG_CC_STACKPROTECTOR_ALL) || \
+ defined(LOSCFG_CC_STACKPROTECTOR_STRONG) || \
+ defined(LOSCFG_CC_STACKPROTECTOR)
+ bl __stack_chk_guard_setup
+#endif
+
+#ifdef LOSCFG_GDB_DEBUG
+ /* GDB_START - generate a compiled_breadk,This function will get GDB stubs started, with a proper environment */
+ bl GDB_START
+ .word 0xe7ffdeff
+#endif
+
+ bl main
+
+_start_hang:
+ b _start_hang
+
+#ifdef LOSCFG_KERNEL_MMU
+mmu_setup:
+ mov r12, #0
+ mcr p15, 0, r12, c8, c7, 0 /* Set c8 to control the TLB and set the mapping to invalid */
+ isb
+
+ mcr p15, 0, r12, c2, c0, 2 /* Initialize the c2 register */
+ isb
+
+ orr r12, r4, #MMU_TTBRx_FLAGS
+ mcr p15, 0, r12, c2, c0, 0 /* Set attributes and set temp page table */
+ isb
+
+ mov r12, #0x7 /* 0b0111 */
+ mcr p15, 0, r12, c3, c0, 0 /* Set DACR with 0b0111, client and manager domian */
+ isb
+
+ mrc p15, 0, r12, c1, c0, 0
+ bic r12, #(1 << 29 | 1 << 28)
+ orr r12, #(1 << 0)
+ bic r12, #(1 << 1)
+ orr r12, #(1 << 2)
+ orr r12, #(1 << 12)
+ mcr p15, 0, r12, c1, c0, 0 /* Set SCTLR with r12: Turn on the MMU, I/D cache Disable TRE/AFE */
+ isb
+
+ ldr pc, =1f /* Convert to VA */
+1:
+ mcr p15, 0, r8, c2, c0, 0 /* Go to the base address saved in C2: Jump to the page table */
+ isb
+
+ mov r12, #0
+ mcr p15, 0, r12, c8, c7, 0
+ isb
+
+ sub lr, r11 /* adjust lr with delta of physical address and virtual address */
+ bx lr
+#endif
+ .code 32
+
+ .global reset_platform
+ .type reset_platform,function
+reset_platform:
+#ifdef A7SEM_HAL_ROM_MONITOR
+ /* initialize CPSR (machine state register) */
+ mov r0, #(CPSR_IRQ_DISABLE|CPSR_FIQ_DISABLE|CPSR_SVC_MODE)
+ msr cpsr, r0
+ b warm_reset
+#else
+ mov r0, #0
+ mov pc, r0 // Jump to reset vector
+#endif
+
+/*
+ * set sp for current cpu
+ * r1 is stack bottom, r0 is stack size, r11 hold cpu id
+ */
+sp_set:
+ mul r3, r0, r11
+ sub r2, r1, r3
+ mov sp, r2
+ bx lr /* set sp */
+
+/*
+ * r4: page table base address
+ * r6: physical address
+ * r7: virtual address
+ * r8: sizes
+ * r10: flags
+ * r9 and r12 will be used as variable
+ */
+#ifdef LOSCFG_KERNEL_MMU
+page_table_build:
+ mov r10, r6
+ bfc r10, #20, #12 /* r9: pa % MB */
+ add r8, r8, r10
+ add r8, r8, #(1 << 20)
+ sub r8, r8, #1
+ lsr r6, #20 /* r6 = physical address / MB */
+ lsr r7, #20 /* r7 = virtual address / MB */
+ lsr r8, #20 /* r8 = roundup(size, MB) */
+
+page_table_build_loop:
+ orr r12, r9, r6, lsl #20 /* r12: flags | physAddr */
+ str r12, [r4, r7, lsl #2] /* gPgTable[l1Index] = physAddr | flags */
+ add r6, #1 /* physAddr+ */
+ add r7, #1 /* l1Index++ */
+ subs r8, #1 /* sizes-- */
+ bne page_table_build_loop
+ bx lr
+#endif
+/*
+ * init stack to initial value
+ * r0 is stack mem start, r1 is stack mem end
+ */
+stack_init:
+ ldr r2, =OS_STACK_INIT
+ ldr r3, =OS_STACK_INIT
+ /* Main loop sets 32 bytes at a time. */
+stack_init_loop:
+ .irp offset, #0, #8, #16, #24
+ strd r2, r3, [r0, \offset]
+ .endr
+ add r0, #32
+ cmp r0, r1
+ blt stack_init_loop
+ bx lr
+
+pa_va_offset:
+ .word .
+
+/*
+ * set magic num to stack top for all cpu
+ * r0 is stack top, r1 is stack size, r2 is magic num
+ */
+excstack_magic:
+ mov r3, #0
+excstack_magic_loop:
+ str r2, [r0]
+ add r0, r0, r1
+ add r3, r3, #1
+ cmp r3, #CORE_NUM
+ blt excstack_magic_loop
+ bx lr
+
+#ifdef LOSCFG_KERNEL_MMU
+memset_optimized:
+ mov r3, r0
+ vdup.8 q0, r1
+ vmov q1, q0
+ vmov q2, q0
+ vmov q3, q0
+memset_optimized_loop:
+ subs r2, #64
+ vstmia r3!, {d0 - d7}
+ bge memset_optimized_loop
+ bx lr
+#endif
+init_done:
+ .long 0xDEADB00B
+
+ .code 32
+ .data
+
+init_flag:
+ .balign 4
+ .long 0
+
+ /*
+ * Temporary interrupt stack
+ */
+ .section ".int_stack", "wa", %nobits
+ .align 3
+
+__svc_stack:
+ .space OS_EXC_SVC_STACK_SIZE * CORE_NUM
+__svc_stack_top:
+
+__exc_stack:
+ .space OS_EXC_STACK_SIZE * CORE_NUM
+__exc_stack_top:
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/strncpy_from_user.c b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/strncpy_from_user.c
new file mode 100644
index 00000000..5d3e9cd5
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/strncpy_from_user.c
@@ -0,0 +1,64 @@
+/*
+ * 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_strncpy_from_user.h"
+#include "los_user_get.h"
+#include "los_vm_map.h"
+
+
+INT32 LOS_StrncpyFromUser(CHAR *dst, const CHAR *src, INT32 count)
+{
+ CHAR character;
+ INT32 i;
+ INT32 maxCount;
+ size_t offset = 0;
+
+ if ((!LOS_IsKernelAddress((VADDR_T)(UINTPTR)dst)) || (!LOS_IsUserAddress((VADDR_T)(UINTPTR)src)) || (count <= 0)) {
+ return -EFAULT;
+ }
+
+ maxCount = (LOS_IsUserAddressRange((VADDR_T)(UINTPTR)src, (size_t)count)) ? \
+ count : (USER_ASPACE_TOP_MAX - (UINTPTR)src);
+
+ for (i = 0; i < maxCount; ++i) {
+ if (LOS_GetUser(&character, src + offset) != LOS_OK) {
+ return -EFAULT;
+ }
+ *(CHAR *)(dst + offset) = character;
+ if (character == '\0') {
+ return offset;
+ }
+ ++offset;
+ }
+
+ return offset;
+}
+
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/strnlen_user.c b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/strnlen_user.c
new file mode 100644
index 00000000..356742f7
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/strnlen_user.c
@@ -0,0 +1,63 @@
+/*
+ * 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_strnlen_user.h"
+#include "los_user_get.h"
+#include "los_vm_map.h"
+
+
+INT32 LOS_StrnlenUser(const CHAR *src, INT32 count)
+{
+ CHAR character;
+ INT32 maxCount;
+ INT32 i;
+ size_t offset = 0;
+
+ if ((!LOS_IsUserAddress((VADDR_T)(UINTPTR)src)) || (count <= 0)) {
+ return 0;
+ }
+
+ maxCount = (LOS_IsUserAddressRange((VADDR_T)(UINTPTR)src, (size_t)count)) ? \
+ count : (USER_ASPACE_TOP_MAX - (UINTPTR)src);
+
+ for (i = 0; i < maxCount; ++i) {
+ if (LOS_GetUser(&character, src + offset) != LOS_OK) {
+ return 0;
+ }
+ ++offset;
+ if (character == '\0') {
+ return offset;
+ }
+ }
+
+ return count + 1;
+}
+
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/user_copy.c b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/user_copy.c
new file mode 100644
index 00000000..081bc413
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/arm/src/user_copy.c
@@ -0,0 +1,107 @@
+/*
+ * 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 "user_copy.h"
+#include "arm_user_copy.h"
+#include "arm_user_clear.h"
+#include "securec.h"
+#include "los_memory.h"
+#include "los_vm_map.h"
+
+
+size_t arch_copy_from_user(void *dst, const void *src, size_t len)
+{
+ return LOS_ArchCopyFromUser(dst, src, len);
+}
+
+size_t LOS_ArchCopyFromUser(void *dst, const void *src, size_t len)
+{
+ if (!LOS_IsUserAddressRange((VADDR_T)(UINTPTR)src, len)) {
+ return len;
+ }
+
+ return _arm_user_copy(dst, src, len);
+}
+
+size_t arch_copy_to_user(void *dst, const void *src, size_t len)
+{
+ return LOS_ArchCopyToUser(dst, src, len);
+}
+
+size_t LOS_ArchCopyToUser(void *dst, const void *src, size_t len)
+{
+ if (!LOS_IsUserAddressRange((VADDR_T)(UINTPTR)dst, len)) {
+ return len;
+ }
+
+ return _arm_user_copy(dst, src, len);
+}
+
+INT32 LOS_CopyFromKernel(VOID *dest, UINT32 max, const VOID *src, UINT32 count)
+{
+ INT32 ret;
+
+ if (!LOS_IsUserAddressRange((VADDR_T)(UINTPTR)dest, count)) {
+ ret = memcpy_s(dest, max, src, count);
+ } else {
+ ret = ((max >= count) ? _arm_user_copy(dest, src, count) : ERANGE_AND_RESET);
+ }
+
+ return ret;
+}
+
+INT32 LOS_CopyToKernel(VOID *dest, UINT32 max, const VOID *src, UINT32 count)
+{
+ INT32 ret;
+
+ if (!LOS_IsUserAddressRange((vaddr_t)(UINTPTR)src, count)) {
+ ret = memcpy_s(dest, max, src, count);
+ } else {
+ ret = ((max >= count) ? _arm_user_copy(dest, src, count) : ERANGE_AND_RESET);
+ }
+
+ return ret;
+}
+
+INT32 LOS_UserMemClear(unsigned char *buf, UINT32 len)
+{
+ INT32 ret = 0;
+ if (!LOS_IsUserAddressRange((vaddr_t)(UINTPTR)buf, len)) {
+ (VOID)memset_s(buf, len, 0, len);
+ } else {
+ if (_arm_clear_user(buf, len)) {
+ return -EFAULT;
+ }
+ }
+ return ret;
+}
+
+
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/gic/BUILD.gn b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/gic/BUILD.gn
new file mode 100644
index 00000000..127100f5
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/gic/BUILD.gn
@@ -0,0 +1,41 @@
+# 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("//kernel/liteos_a/liteos.gni")
+
+module_name = get_path_info(rebase_path("."), "name")
+kernel_module(module_name) {
+ sources = []
+
+ if (defined(LOSCFG_ARCH_GIC_V2)) {
+ sources += [ "gic_v2.c" ]
+ } else if (defined(LOSCFG_ARCH_GIC_V3)) {
+ sources += [ "gic_v3.c" ]
+ }
+}
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/gic/Makefile b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/gic/Makefile
new file mode 100644
index 00000000..376cfa2e
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/gic/Makefile
@@ -0,0 +1,40 @@
+# 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 $(LITEOSTOPDIR)/config.mk
+
+MODULE_NAME := $(notdir $(shell pwd))
+
+ifeq ($(LOSCFG_ARCH_GIC_V2), y)
+LOCAL_SRCS := gic_v2.c
+else ifeq ($(LOSCFG_ARCH_GIC_V3), y)
+LOCAL_SRCS := gic_v3.c
+endif
+
+include $(MODULE)
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/gic/gic_v2.c b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/gic/gic_v2.c
new file mode 100644
index 00000000..14aa69af
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/gic/gic_v2.c
@@ -0,0 +1,197 @@
+/*
+ * 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 "gic_common.h"
+#include "los_hwi.h"
+#include "los_hwi_pri.h"
+#include "los_mp.h"
+
+STATIC_ASSERT(OS_USER_HWI_MAX <= 1020, "hwi max is too large!");
+
+#ifdef LOSCFG_ARCH_GIC_V2
+
+STATIC UINT32 g_curIrqNum = 0;
+
+#ifdef LOSCFG_KERNEL_SMP
+/*
+ * filter description
+ * 0b00: forward to the cpu interfaces specified in cpu_mask
+ * 0b01: forward to all cpu interfaces
+ * 0b10: forward only to the cpu interface that request the irq
+ */
+STATIC VOID GicWriteSgi(UINT32 vector, UINT32 cpuMask, UINT32 filter)
+{
+ UINT32 val = ((filter & 0x3) << 24) | ((cpuMask & 0xFF) << 16) | /* 24, 16: Register bit offset */
+ (vector & 0xF);
+
+ GIC_REG_32(GICD_SGIR) = val;
+}
+
+VOID HalIrqSendIpi(UINT32 target, UINT32 ipi)
+{
+ GicWriteSgi(ipi, target, 0);
+}
+
+VOID HalIrqSetAffinity(UINT32 vector, UINT32 cpuMask)
+{
+ UINT32 offset = vector / 4; /* 4: Interrupt bit width */
+ UINT32 index = vector & 0x3;
+
+ GIC_REG_8(GICD_ITARGETSR(offset) + index) = cpuMask;
+}
+#endif
+
+UINT32 HalCurIrqGet(VOID)
+{
+ return g_curIrqNum;
+}
+
+VOID HalIrqMask(UINT32 vector)
+{
+ if ((vector > OS_USER_HWI_MAX) || (vector < OS_USER_HWI_MIN)) {
+ return;
+ }
+
+ GIC_REG_32(GICD_ICENABLER(vector / 32)) = 1U << (vector % 32); /* 32: Interrupt bit width */
+}
+
+VOID HalIrqUnmask(UINT32 vector)
+{
+ if ((vector > OS_USER_HWI_MAX) || (vector < OS_USER_HWI_MIN)) {
+ return;
+ }
+
+ GIC_REG_32(GICD_ISENABLER(vector >> 5)) = 1U << (vector % 32); /* 5, 32: Register bit offset */
+}
+
+VOID HalIrqPending(UINT32 vector)
+{
+ if ((vector > OS_USER_HWI_MAX) || (vector < OS_USER_HWI_MIN)) {
+ return;
+ }
+
+ GIC_REG_32(GICD_ISPENDR(vector >> 5)) = 1U << (vector % 32); /* 5, 32: Register bit offset */
+}
+
+VOID HalIrqClear(UINT32 vector)
+{
+ GIC_REG_32(GICC_EOIR) = vector;
+}
+
+VOID HalIrqInitPercpu(VOID)
+{
+ /* unmask interrupts */
+ GIC_REG_32(GICC_PMR) = 0xFF;
+
+ /* enable gic cpu interface */
+ GIC_REG_32(GICC_CTLR) = 1;
+}
+
+VOID HalIrqInit(VOID)
+{
+ UINT32 i;
+
+ /* set external interrupts to be level triggered, active low. */
+ for (i = 32; i < OS_HWI_MAX_NUM; i += 16) { /* 32: Start interrupt number, 16: Interrupt bit width */
+ GIC_REG_32(GICD_ICFGR(i / 16)) = 0; /* 16: Register bit offset */
+ }
+
+ /* set external interrupts to CPU 0 */
+ for (i = 32; i < OS_HWI_MAX_NUM; i += 4) { /* 32: Start interrupt number, 4: Interrupt bit width */
+ GIC_REG_32(GICD_ITARGETSR(i / 4)) = 0x01010101;
+ }
+
+ /* set priority on all interrupts */
+ for (i = 0; i < OS_HWI_MAX_NUM; i += 4) { /* 4: Interrupt bit width */
+ GIC_REG_32(GICD_IPRIORITYR(i / 4)) = GICD_INT_DEF_PRI_X4;
+ }
+
+ /* disable all interrupts. */
+ for (i = 0; i < OS_HWI_MAX_NUM; i += 32) { /* 32: Interrupt bit width */
+ GIC_REG_32(GICD_ICENABLER(i / 32)) = ~0; /* 32: Interrupt bit width */
+ }
+
+ HalIrqInitPercpu();
+
+ /* enable gic distributor control */
+ GIC_REG_32(GICD_CTLR) = 1;
+
+#ifdef LOSCFG_KERNEL_SMP
+ /* register inter-processor interrupt */
+ (VOID)LOS_HwiCreate(LOS_MP_IPI_WAKEUP, 0xa0, 0, OsMpWakeHandler, 0);
+ (VOID)LOS_HwiCreate(LOS_MP_IPI_SCHEDULE, 0xa0, 0, OsMpScheduleHandler, 0);
+ (VOID)LOS_HwiCreate(LOS_MP_IPI_HALT, 0xa0, 0, OsMpHaltHandler, 0);
+#ifdef LOSCFG_KERNEL_SMP_CALL
+ (VOID)LOS_HwiCreate(LOS_MP_IPI_FUNC_CALL, 0xa0, 0, OsMpFuncCallHandler, 0);
+#endif
+#endif
+}
+
+VOID HalIrqHandler(VOID)
+{
+ UINT32 iar = GIC_REG_32(GICC_IAR);
+ UINT32 vector = iar & 0x3FFU;
+
+ /*
+ * invalid irq number, mainly the spurious interrupts 0x3ff,
+ * gicv2 valid irq ranges from 0~1019, we use OS_HWI_MAX_NUM
+ * to do the checking.
+ */
+ if (vector >= OS_HWI_MAX_NUM) {
+ return;
+ }
+ g_curIrqNum = vector;
+
+ OsInterrupt(vector);
+
+ /* use original iar to do the EOI */
+ GIC_REG_32(GICC_EOIR) = iar;
+}
+
+CHAR *HalIrqVersion(VOID)
+{
+ UINT32 pidr = GIC_REG_32(GICD_PIDR2V2);
+ CHAR *irqVerString = NULL;
+
+ switch (pidr >> GIC_REV_OFFSET) {
+ case GICV1:
+ irqVerString = "GICv1";
+ break;
+ case GICV2:
+ irqVerString = "GICv2";
+ break;
+ default:
+ irqVerString = "unknown";
+ }
+ return irqVerString;
+}
+
+#endif
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/gic/gic_v3.c b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/gic/gic_v3.c
new file mode 100644
index 00000000..50039776
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/gic/gic_v3.c
@@ -0,0 +1,450 @@
+/*
+ * 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 "gic_common.h"
+#include "gic_v3.h"
+#include "los_typedef.h"
+#include "los_hwi.h"
+#include "los_hwi_pri.h"
+#include "los_mp.h"
+
+#ifdef LOSCFG_ARCH_GIC_V3
+
+STATIC UINT32 g_curIrqNum = 0;
+
+STATIC INLINE UINT64 MpidrToAffinity(UINT64 mpidr)
+{
+ return ((MPIDR_AFF_LEVEL(mpidr, 3) << 32) | /* 3: Serial number, 32: Register bit offset */
+ (MPIDR_AFF_LEVEL(mpidr, 2) << 16) | /* 2: Serial number, 16: Register bit offset */
+ (MPIDR_AFF_LEVEL(mpidr, 1) << 8) | /* 1: Serial number, 8: Register bit offset */
+ (MPIDR_AFF_LEVEL(mpidr, 0)));
+}
+
+#ifdef LOSCFG_KERNEL_SMP
+
+STATIC UINT32 NextCpu(UINT32 cpu, UINT32 cpuMask)
+{
+ UINT32 next = cpu + 1;
+
+ while (next < LOSCFG_KERNEL_CORE_NUM) {
+ if (cpuMask & (1U << next)) {
+ goto OUT;
+ }
+
+ next++;
+ }
+
+OUT:
+ return next;
+}
+
+STATIC UINT16 GicTargetList(UINT32 *base, UINT32 cpuMask, UINT64 cluster)
+{
+ UINT32 nextCpu;
+ UINT16 tList = 0;
+ UINT32 cpu = *base;
+ UINT64 mpidr = CPU_MAP_GET(cpu);
+ while (cpu < LOSCFG_KERNEL_CORE_NUM) {
+ tList |= 1U << (mpidr & 0xf);
+
+ nextCpu = NextCpu(cpu, cpuMask);
+ if (nextCpu >= LOSCFG_KERNEL_CORE_NUM) {
+ goto out;
+ }
+
+ cpu = nextCpu;
+ mpidr = CPU_MAP_GET(cpu);
+ if (cluster != (mpidr & ~0xffUL)) {
+ cpu--;
+ goto out;
+ }
+ }
+
+out:
+ *base = cpu;
+ return tList;
+}
+
+STATIC VOID GicSgi(UINT32 irq, UINT32 cpuMask)
+{
+ UINT16 tList;
+ UINT32 cpu = 0;
+ UINT64 val, cluster;
+
+ while (cpuMask && (cpu < LOSCFG_KERNEL_CORE_NUM)) {
+ if (cpuMask & (1U << cpu)) {
+ cluster = CPU_MAP_GET(cpu) & ~0xffUL;
+
+ tList = GicTargetList(&cpu, cpuMask, cluster);
+
+ /* Generates a Group 1 interrupt for the current security state */
+ val = ((MPIDR_AFF_LEVEL(cluster, 3) << 48) | /* 3: Serial number, 48: Register bit offset */
+ (MPIDR_AFF_LEVEL(cluster, 2) << 32) | /* 2: Serial number, 32: Register bit offset */
+ (MPIDR_AFF_LEVEL(cluster, 1) << 16) | /* 1: Serial number, 16: Register bit offset */
+ (irq << 24) | tList); /* 24: Register bit offset */
+
+ GiccSetSgi1r(val);
+ }
+
+ cpu++;
+ }
+}
+
+VOID HalIrqSendIpi(UINT32 target, UINT32 ipi)
+{
+ GicSgi(ipi, target);
+}
+
+VOID HalIrqSetAffinity(UINT32 irq, UINT32 cpuMask)
+{
+ UINT64 affinity = MpidrToAffinity(NextCpu(0, cpuMask));
+
+ /* When ARE is on, use router */
+ GIC_REG_64(GICD_IROUTER(irq)) = affinity;
+}
+
+#endif
+
+STATIC VOID GicWaitForRwp(UINT64 reg)
+{
+ INT32 count = 1000000; /* 1s */
+
+ while (GIC_REG_32(reg) & GICD_CTLR_RWP) {
+ count -= 1;
+ if (!count) {
+ PRINTK("gic_v3: rwp timeout 0x%x\n", GIC_REG_32(reg));
+ return;
+ }
+ }
+}
+
+STATIC INLINE VOID GicdSetGroup(UINT32 irq)
+{
+ /* configure spi as group 0 on secure mode and group 1 on unsecure mode */
+#ifdef LOSCFG_ARCH_SECURE_MONITOR_MODE
+ GIC_REG_32(GICD_IGROUPR(irq / 32)) = 0; /* 32: Interrupt bit width */
+#else
+ GIC_REG_32(GICD_IGROUPR(irq / 32)) = 0xffffffff; /* 32: Interrupt bit width */
+#endif
+}
+
+STATIC INLINE VOID GicrSetWaker(UINT32 cpu)
+{
+ GIC_REG_32(GICR_WAKER(cpu)) &= ~GICR_WAKER_PROCESSORSLEEP;
+ DSB;
+ ISB;
+ while ((GIC_REG_32(GICR_WAKER(cpu)) & 0x4) == GICR_WAKER_CHILDRENASLEEP);
+}
+
+STATIC INLINE VOID GicrSetGroup(UINT32 cpu)
+{
+ /* configure sgi/ppi as group 0 on secure mode and group 1 on unsecure mode */
+#ifdef LOSCFG_ARCH_SECURE_MONITOR_MODE
+ GIC_REG_32(GICR_IGROUPR0(cpu)) = 0;
+ GIC_REG_32(GICR_IGRPMOD0(cpu)) = 0;
+#else
+ GIC_REG_32(GICR_IGROUPR0(cpu)) = 0xffffffff;
+#endif
+}
+
+STATIC VOID GicdSetPmr(UINT32 irq, UINT8 priority)
+{
+ UINT32 pos = irq >> 2; /* one irq have the 8-bit interrupt priority field */
+ UINT32 newPri = GIC_REG_32(GICD_IPRIORITYR(pos));
+
+ /* Shift and mask the correct bits for the priority */
+ newPri &= ~(GIC_PRIORITY_MASK << ((irq % 4) * GIC_PRIORITY_OFFSET));
+ newPri |= priority << ((irq % 4) * GIC_PRIORITY_OFFSET);
+
+ GIC_REG_32(GICD_IPRIORITYR(pos)) = newPri;
+}
+
+STATIC VOID GicrSetPmr(UINT32 irq, UINT8 priority)
+{
+ UINT32 cpu = ArchCurrCpuid();
+ UINT32 pos = irq >> 2; /* one irq have the 8-bit interrupt priority field */
+ UINT32 newPri = GIC_REG_32(GICR_IPRIORITYR0(cpu) + pos * 4);
+
+ /* Clear priority offset bits and set new priority */
+ newPri &= ~(GIC_PRIORITY_MASK << ((irq % 4) * GIC_PRIORITY_OFFSET));
+ newPri |= priority << ((irq % 4) * GIC_PRIORITY_OFFSET);
+
+ GIC_REG_32(GICR_IPRIORITYR0(cpu) + pos * 4) = newPri;
+}
+
+STATIC VOID GiccInitPercpu(VOID)
+{
+ /* enable system register interface */
+ UINT32 sre = GiccGetSre();
+ if (!(sre & 0x1)) {
+ GiccSetSre(sre | 0x1);
+
+ /*
+ * Need to check that the SRE bit has actually been set. If
+ * not, it means that SRE is disabled at up EL level. We're going to
+ * die painfully, and there is nothing we can do about it.
+ */
+ sre = GiccGetSre();
+ LOS_ASSERT(sre & 0x1);
+ }
+
+#ifdef LOSCFG_ARCH_SECURE_MONITOR_MODE
+ /* Enable group 0 and disable grp1ns grp1s interrupts */
+ GiccSetIgrpen0(1);
+ GiccSetIgrpen1(0);
+
+ /*
+ * For priority grouping.
+ * The value of this field control show the 8-bit interrupt priority field
+ * is split into a group priority field, that determines interrupt preemption,
+ * and a subpriority field.
+ */
+ GiccSetBpr0(MAX_BINARY_POINT_VALUE);
+#else
+ /* enable group 1 interrupts */
+ GiccSetIgrpen1(1);
+#endif
+
+ /* set priority threshold to max */
+ GiccSetPmr(0xff);
+
+ /* EOI deactivates interrupt too (mode 0) */
+ GiccSetCtlr(0);
+}
+
+UINT32 HalCurIrqGet(VOID)
+{
+ return g_curIrqNum;
+}
+
+VOID HalIrqMask(UINT32 vector)
+{
+ INT32 i;
+ const UINT32 mask = 1U << (vector % 32); /* 32: Interrupt bit width */
+
+ if ((vector > OS_USER_HWI_MAX) || (vector < OS_USER_HWI_MIN)) {
+ return;
+ }
+
+ if (vector < 32) { /* 32: Interrupt bit width */
+ for (i = 0; i < LOSCFG_KERNEL_CORE_NUM; i++) {
+ GIC_REG_32(GICR_ICENABLER0(i)) = mask;
+ GicWaitForRwp(GICR_CTLR(i));
+ }
+ } else {
+ GIC_REG_32(GICD_ICENABLER(vector >> 5)) = mask;
+ GicWaitForRwp(GICD_CTLR);
+ }
+}
+
+VOID HalIrqUnmask(UINT32 vector)
+{
+ INT32 i;
+ const UINT32 mask = 1U << (vector % 32); /* 32: Interrupt bit width */
+
+ if ((vector > OS_USER_HWI_MAX) || (vector < OS_USER_HWI_MIN)) {
+ return;
+ }
+
+ if (vector < 32) { /* 32: Interrupt bit width */
+ for (i = 0; i < LOSCFG_KERNEL_CORE_NUM; i++) {
+ GIC_REG_32(GICR_ISENABLER0(i)) = mask;
+ GicWaitForRwp(GICR_CTLR(i));
+ }
+ } else {
+ GIC_REG_32(GICD_ISENABLER(vector >> 5)) = mask; /* 5: Register bit offset */
+ GicWaitForRwp(GICD_CTLR);
+ }
+}
+
+VOID HalIrqPending(UINT32 vector)
+{
+ if ((vector > OS_USER_HWI_MAX) || (vector < OS_USER_HWI_MIN)) {
+ return;
+ }
+
+ GIC_REG_32(GICD_ISPENDR(vector >> 5)) = 1U << (vector % 32); /* 5: Register bit offset, 32: Interrupt bit width */
+}
+
+VOID HalIrqClear(UINT32 vector)
+{
+ GiccSetEoir(vector);
+ ISB;
+}
+
+UINT32 HalIrqSetPrio(UINT32 vector, UINT8 priority)
+{
+ UINT8 prio = priority;
+
+ if (vector > OS_HWI_MAX_NUM) {
+ PRINT_ERR("Invalid irq value %u, max irq is %u\n", vector, OS_HWI_MAX_NUM);
+ return LOS_NOK;
+ }
+
+ prio = prio & (UINT8)GIC_INTR_PRIO_MASK;
+
+ if (vector >= GIC_MIN_SPI_NUM) {
+ GicdSetPmr(vector, prio);
+ } else {
+ GicrSetPmr(vector, prio);
+ }
+
+ return LOS_OK;
+}
+
+VOID HalIrqInitPercpu(VOID)
+{
+ INT32 idx;
+ UINT32 cpu = ArchCurrCpuid();
+
+ /* GICR init */
+ GicrSetWaker(cpu);
+ GicrSetGroup(cpu);
+ GicWaitForRwp(GICR_CTLR(cpu));
+
+ /* GICR: clear and mask sgi/ppi */
+ GIC_REG_32(GICR_ICENABLER0(cpu)) = 0xffffffff;
+ GIC_REG_32(GICR_ICPENDR0(cpu)) = 0xffffffff;
+
+ GIC_REG_32(GICR_ISENABLER0(cpu)) = 0xffffffff;
+
+ for (idx = 0; idx < GIC_MIN_SPI_NUM; idx += 1) {
+ GicrSetPmr(idx, MIN_INTERRUPT_PRIORITY);
+ }
+
+ GicWaitForRwp(GICR_CTLR(cpu));
+
+ /* GICC init */
+ GiccInitPercpu();
+
+#ifdef LOSCFG_KERNEL_SMP
+ /* unmask ipi interrupts */
+ HalIrqUnmask(LOS_MP_IPI_WAKEUP);
+ HalIrqUnmask(LOS_MP_IPI_HALT);
+#endif
+}
+
+VOID HalIrqInit(VOID)
+{
+ UINT32 i;
+ UINT64 affinity;
+
+ /* disable distributor */
+ GIC_REG_32(GICD_CTLR) = 0;
+ GicWaitForRwp(GICD_CTLR);
+ ISB;
+
+ /* set external interrupts to be level triggered, active low. */
+ for (i = 32; i < OS_HWI_MAX_NUM; i += 16) { /* 32: Start interrupt number, 16: Interrupt bit width */
+ GIC_REG_32(GICD_ICFGR(i / 16)) = 0;
+ }
+
+ /* config distributer, mask and clear all spis, set group x */
+ for (i = 32; i < OS_HWI_MAX_NUM; i += 32) { /* 32: Start interrupt number, 32: Interrupt bit width */
+ GIC_REG_32(GICD_ICENABLER(i / 32)) = 0xffffffff; /* 32: Interrupt bit width */
+ GIC_REG_32(GICD_ICPENDR(i / 32)) = 0xffffffff; /* 32: Interrupt bit width */
+ GIC_REG_32(GICD_IGRPMODR(i / 32)) = 0; /* 32: Interrupt bit width */
+
+ GicdSetGroup(i);
+ }
+
+ /* set spi priority as default */
+ for (i = 32; i < OS_HWI_MAX_NUM; i++) { /* 32: Start interrupt number */
+ GicdSetPmr(i, MIN_INTERRUPT_PRIORITY);
+ }
+
+ GicWaitForRwp(GICD_CTLR);
+
+ /* disable all interrupts. */
+ for (i = 0; i < OS_HWI_MAX_NUM; i += 32) { /* 32: Interrupt bit width */
+ GIC_REG_32(GICD_ICENABLER(i / 32)) = 0xffffffff; /* 32: Interrupt bit width */
+ }
+
+ /* enable distributor with ARE, group 1 enabled */
+ GIC_REG_32(GICD_CTLR) = CTLR_ENALBE_G0 | CTLR_ENABLE_G1NS | CTLR_ARE_S;
+
+ /* set spi to boot cpu only. ARE must be enabled */
+ affinity = MpidrToAffinity(AARCH64_SYSREG_READ(mpidr_el1));
+ for (i = 32; i < OS_HWI_MAX_NUM; i++) { /* 32: Start interrupt number */
+ GIC_REG_64(GICD_IROUTER(i)) = affinity;
+ }
+
+ HalIrqInitPercpu();
+
+#ifdef LOSCFG_KERNEL_SMP
+ /* register inter-processor interrupt */
+ (VOID)LOS_HwiCreate(LOS_MP_IPI_WAKEUP, 0xa0, 0, OsMpWakeHandler, 0);
+ (VOID)LOS_HwiCreate(LOS_MP_IPI_SCHEDULE, 0xa0, 0, OsMpScheduleHandler, 0);
+ (VOID)LOS_HwiCreate(LOS_MP_IPI_HALT, 0xa0, 0, OsMpScheduleHandler, 0);
+#ifdef LOSCFG_KERNEL_SMP_CALL
+ (VOID)LOS_HwiCreate(LOS_MP_IPI_FUNC_CALL, 0xa0, 0, OsMpFuncCallHandler, 0);
+#endif
+#endif
+}
+
+VOID HalIrqHandler(VOID)
+{
+ UINT32 iar = GiccGetIar();
+ UINT32 vector = iar & 0x3FFU;
+
+ /*
+ * invalid irq number, mainly the spurious interrupts 0x3ff,
+ * valid irq ranges from 0~1019, we use OS_HWI_MAX_NUM to do
+ * the checking.
+ */
+ if (vector >= OS_HWI_MAX_NUM) {
+ return;
+ }
+ g_curIrqNum = vector;
+
+ OsInterrupt(vector);
+ GiccSetEoir(vector);
+}
+
+CHAR *HalIrqVersion(VOID)
+{
+ UINT32 pidr = GIC_REG_32(GICD_PIDR2V3);
+ CHAR *irqVerString = NULL;
+
+ switch (pidr >> GIC_REV_OFFSET) {
+ case GICV3:
+ irqVerString = "GICv3";
+ break;
+ case GICV4:
+ irqVerString = "GICv4";
+ break;
+ default:
+ irqVerString = "unknown";
+ }
+ return irqVerString;
+}
+
+#endif
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/include/gic_common.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/include/gic_common.h
new file mode 100644
index 00000000..e9ac5622
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/include/gic_common.h
@@ -0,0 +1,123 @@
+/*
+ * 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 _GIC_COMMON_H
+#define _GIC_COMMON_H
+
+#include "stdint.h"
+#include "target_config.h"
+#include "los_config.h"
+
+/* gic arch revision */
+enum {
+ GICV1 = 1,
+ GICV2,
+ GICV3,
+ GICV4
+};
+
+#define GIC_REV_MASK 0xF0
+#define GIC_REV_OFFSET 0x4
+
+#ifdef LOSCFG_ARCH_GIC_V2
+#define GICC_CTLR (GICC_OFFSET + 0x00) /* CPU Interface Control Register */
+#define GICC_PMR (GICC_OFFSET + 0x04) /* Interrupt Priority Mask Register */
+#define GICC_BPR (GICC_OFFSET + 0x08) /* Binary Point Register */
+#define GICC_IAR (GICC_OFFSET + 0x0c) /* Interrupt Acknowledge Register */
+#define GICC_EOIR (GICC_OFFSET + 0x10) /* End of Interrupt Register */
+#define GICC_RPR (GICC_OFFSET + 0x14) /* Running Priority Register */
+#define GICC_HPPIR (GICC_OFFSET + 0x18) /* Highest Priority Pending Interrupt Register */
+#endif
+
+#define GICD_CTLR (GICD_OFFSET + 0x000) /* Distributor Control Register */
+#define GICD_TYPER (GICD_OFFSET + 0x004) /* Interrupt Controller Type Register */
+#define GICD_IIDR (GICD_OFFSET + 0x008) /* Distributor Implementer Identification Register */
+#define GICD_IGROUPR(n) (GICD_OFFSET + 0x080 + (n) * 4) /* Interrupt Group Registers */
+#define GICD_ISENABLER(n) (GICD_OFFSET + 0x100 + (n) * 4) /* Interrupt Set-Enable Registers */
+#define GICD_ICENABLER(n) (GICD_OFFSET + 0x180 + (n) * 4) /* Interrupt Clear-Enable Registers */
+#define GICD_ISPENDR(n) (GICD_OFFSET + 0x200 + (n) * 4) /* Interrupt Set-Pending Registers */
+#define GICD_ICPENDR(n) (GICD_OFFSET + 0x280 + (n) * 4) /* Interrupt Clear-Pending Registers */
+#define GICD_ISACTIVER(n) (GICD_OFFSET + 0x300 + (n) * 4) /* GICv2 Interrupt Set-Active Registers */
+#define GICD_ICACTIVER(n) (GICD_OFFSET + 0x380 + (n) * 4) /* Interrupt Clear-Active Registers */
+#define GICD_IPRIORITYR(n) (GICD_OFFSET + 0x400 + (n) * 4) /* Interrupt Priority Registers */
+#define GICD_ITARGETSR(n) (GICD_OFFSET + 0x800 + (n) * 4) /* Interrupt Processor Targets Registers */
+#define GICD_ICFGR(n) (GICD_OFFSET + 0xc00 + (n) * 4) /* Interrupt Configuration Registers */
+#define GICD_SGIR (GICD_OFFSET + 0xf00) /* Software Generated Interrupt Register */
+#define GICD_CPENDSGIR(n) (GICD_OFFSET + 0xf10 + (n) * 4) /* SGI Clear-Pending Registers; NOT available on cortex-a9 */
+#define GICD_SPENDSGIR(n) (GICD_OFFSET + 0xf20 + (n) * 4) /* SGI Set-Pending Registers; NOT available on cortex-a9 */
+#define GICD_PIDR2V2 (GICD_OFFSET + 0xfe8)
+#define GICD_PIDR2V3 (GICD_OFFSET + 0xffe8)
+
+#ifdef LOSCFG_ARCH_GIC_V3
+#define GICD_IGRPMODR(n) (GICD_OFFSET + 0x0d00 + (n) * 4) /* Interrupt Group Mode Registers */
+#define GICD_IROUTER(n) (GICD_OFFSET + 0x6000 + (n) * 8) /* Interrupt Rounter Registers */
+#endif
+
+#define GIC_REG_8(reg) (*(volatile UINT8 *)((UINTPTR)(GIC_BASE_ADDR + (reg))))
+#define GIC_REG_32(reg) (*(volatile UINT32 *)((UINTPTR)(GIC_BASE_ADDR + (reg))))
+#define GIC_REG_64(reg) (*(volatile UINT64 *)((UINTPTR)(GIC_BASE_ADDR + (reg))))
+
+#define GICD_INT_DEF_PRI 0xa0U
+#define GICD_INT_DEF_PRI_X4 (((UINT32)GICD_INT_DEF_PRI << 24) | \
+ ((UINT32)GICD_INT_DEF_PRI << 16) | \
+ ((UINT32)GICD_INT_DEF_PRI << 8) | \
+ (UINT32)GICD_INT_DEF_PRI)
+
+#define GIC_MIN_SPI_NUM 32
+
+/* Interrupt preemption config */
+#define GIC_PRIORITY_MASK 0xFFU
+#define GIC_PRIORITY_OFFSET 8
+
+/*
+ * The number of bits to shift for an interrupt priority is dependent
+ * on the number of bits implemented by the interrupt controller.
+ * If the MAX_BINARY_POINT_VALUE is 7,
+ * it means that interrupt preemption is not supported.
+ */
+#ifndef LOSCFG_ARCH_INTERRUPT_PREEMPTION
+#define MAX_BINARY_POINT_VALUE 7
+#define PRIORITY_SHIFT 0
+#define GIC_MAX_INTERRUPT_PREEMPTION_LEVEL 0U
+#else
+#define PRIORITY_SHIFT ((MAX_BINARY_POINT_VALUE + 1) % GIC_PRIORITY_OFFSET)
+#define GIC_MAX_INTERRUPT_PREEMPTION_LEVEL ((UINT8)((GIC_PRIORITY_MASK + 1) >> PRIORITY_SHIFT))
+#endif
+
+#define GIC_INTR_PRIO_MASK ((UINT8)(0xFFFFFFFFU << PRIORITY_SHIFT))
+
+/*
+ * The preemption level is up to 128, and the maximum value corresponding to the interrupt priority is 254 [7:1].
+ * If the GIC_MAX_INTERRUPT_PREEMPTION_LEVEL is 0, the minimum priority is 0xff.
+ */
+#define MIN_INTERRUPT_PRIORITY ((UINT8)((GIC_MAX_INTERRUPT_PREEMPTION_LEVEL - 1) << PRIORITY_SHIFT))
+
+#endif
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/include/gic_v3.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/include/gic_v3.h
new file mode 100644
index 00000000..7f846732
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/include/gic_v3.h
@@ -0,0 +1,203 @@
+/*
+ * 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 _GIC_V3_H_
+#define _GIC_V3_H_
+
+#include "stdint.h"
+#include "target_config.h"
+#include "los_hw_cpu.h"
+
+#define BIT_32(bit) (1u << bit)
+#define BIT_64(bit) (1ul << bit)
+
+#define ICC_CTLR_EL1 "S3_0_C12_C12_4"
+#define ICC_PMR_EL1 "S3_0_C4_C6_0"
+#define ICC_IAR1_EL1 "S3_0_C12_C12_0"
+#define ICC_SRE_EL1 "S3_0_C12_C12_5"
+#define ICC_BPR0_EL1 "S3_0_C12_C8_3"
+#define ICC_BPR1_EL1 "S3_0_C12_C12_3"
+#define ICC_IGRPEN0_EL1 "S3_0_C12_C12_6"
+#define ICC_IGRPEN1_EL1 "S3_0_C12_C12_7"
+#define ICC_EOIR1_EL1 "S3_0_C12_C12_1"
+#define ICC_SGI1R_EL1 "S3_0_C12_C11_5"
+#define ICC_EOIR0_EL1 "S3_0_c12_c8_1"
+#define ICC_IAR0_EL1 "S3_0_C12_C8_0"
+
+#define ICC_CTLR_EL3 "S3_6_C12_C12_4"
+#define ICC_SRE_EL3 "S3_6_C12_C12_5"
+#define ICC_IGRPEN1_EL3 "S3_6_C12_C12_7"
+
+/* GICD_CTLR bit definitions */
+#define CTLR_ENALBE_G0 BIT_32(0)
+#define CTLR_ENABLE_G1NS BIT_32(1)
+#define CTLR_ENABLE_G1S BIT_32(2)
+#define CTLR_RES0 BIT_32(3)
+#define CTLR_ARE_S BIT_32(4)
+#define CTLR_ARE_NS BIT_32(5)
+#define CTLR_DS BIT_32(6)
+#define CTLR_E1NWF BIT_32(7)
+#define GICD_CTLR_RWP BIT_32(31)
+
+/* peripheral identification registers */
+#define GICD_CIDR0 (GICD_OFFSET + 0xfff0)
+#define GICD_CIDR1 (GICD_OFFSET + 0xfff4)
+#define GICD_CIDR2 (GICD_OFFSET + 0xfff8)
+#define GICD_CIDR3 (GICD_OFFSET + 0xfffc)
+#define GICD_PIDR0 (GICD_OFFSET + 0xffe0)
+#define GICD_PIDR1 (GICD_OFFSET + 0xffe4)
+#define GICD_PIDR2 (GICD_OFFSET + 0xffe8)
+#define GICD_PIDR3 (GICD_OFFSET + 0xffec)
+
+/* GICD_PIDR bit definitions and masks */
+#define GICD_PIDR2_ARCHREV_SHIFT 4
+#define GICD_PIDR2_ARCHREV_MASK 0xf
+
+/* redistributor registers */
+#define GICR_SGI_OFFSET (GICR_OFFSET + 0x10000)
+
+#define GICR_CTLR(i) (GICR_OFFSET + GICR_STRIDE * (i) + 0x0000)
+#define GICR_IIDR(i) (GICR_OFFSET + GICR_STRIDE * (i) + 0x0004)
+#define GICR_TYPER(i, n) (GICR_OFFSET + GICR_STRIDE * (i) + 0x0008 + (n)*4)
+#define GICR_STATUSR(i) (GICR_OFFSET + GICR_STRIDE * (i) + 0x0010)
+#define GICR_WAKER(i) (GICR_OFFSET + GICR_STRIDE * (i) + 0x0014)
+#define GICR_IGROUPR0(i) (GICR_SGI_OFFSET + GICR_STRIDE * (i) + 0x0080)
+#define GICR_IGRPMOD0(i) (GICR_SGI_OFFSET + GICR_STRIDE * (i) + 0x0d00)
+#define GICR_ISENABLER0(i) (GICR_SGI_OFFSET + GICR_STRIDE * (i) + 0x0100)
+#define GICR_ICENABLER0(i) (GICR_SGI_OFFSET + GICR_STRIDE * (i) + 0x0180)
+#define GICR_ISPENDR0(i) (GICR_SGI_OFFSET + GICR_STRIDE * (i) + 0x0200)
+#define GICR_ICPENDR0(i) (GICR_SGI_OFFSET + GICR_STRIDE * (i) + 0x0280)
+#define GICR_ISACTIVER0(i) (GICR_SGI_OFFSET + GICR_STRIDE * (i) + 0x0300)
+#define GICR_ICACTIVER0(i) (GICR_SGI_OFFSET + GICR_STRIDE * (i) + 0x0380)
+#define GICR_IPRIORITYR0(i) (GICR_SGI_OFFSET + GICR_STRIDE * (i) + 0x0400)
+#define GICR_ICFGR0(i) (GICR_SGI_OFFSET + GICR_STRIDE * (i) + 0x0c00)
+#define GICR_ICFGR1(i) (GICR_SGI_OFFSET + GICR_STRIDE * (i) + 0x0c04)
+#define GICR_NSACR(i) (GICR_SGI_OFFSET + GICR_STRIDE * (i) + 0x0e00)
+
+#define GICR_WAKER_PROCESSORSLEEP_LEN 1U
+#define GICR_WAKER_PROCESSORSLEEP_OFFSET 1
+#define GICR_WAKER_CHILDRENASLEEP_LEN 1U
+#define GICR_WAKER_CHILDRENASLEEP_OFFSET 2
+#define GICR_WAKER_PROCESSORSLEEP (GICR_WAKER_PROCESSORSLEEP_LEN << GICR_WAKER_PROCESSORSLEEP_OFFSET)
+#define GICR_WAKER_CHILDRENASLEEP (GICR_WAKER_CHILDRENASLEEP_LEN << GICR_WAKER_CHILDRENASLEEP_OFFSET)
+
+STATIC INLINE VOID GiccSetCtlr(UINT32 val)
+{
+#ifdef LOSCFG_ARCH_SECURE_MONITOR_MODE
+ __asm__ volatile("msr " ICC_CTLR_EL3 ", %0" ::"r"(val));
+#else
+ __asm__ volatile("msr " ICC_CTLR_EL1 ", %0" ::"r"(val));
+#endif
+ ISB;
+}
+
+STATIC INLINE VOID GiccSetPmr(UINT32 val)
+{
+ __asm__ volatile("msr " ICC_PMR_EL1 ", %0" ::"r"(val));
+ ISB;
+ DSB;
+}
+
+STATIC INLINE VOID GiccSetIgrpen0(UINT32 val)
+{
+ __asm__ volatile("msr " ICC_IGRPEN0_EL1 ", %0" ::"r"(val));
+ ISB;
+}
+
+STATIC INLINE VOID GiccSetIgrpen1(UINT32 val)
+{
+#ifdef LOSCFG_ARCH_SECURE_MONITOR_MODE
+ __asm__ volatile("msr " ICC_IGRPEN1_EL3 ", %0" ::"r"(val));
+#else
+ __asm__ volatile("msr " ICC_IGRPEN1_EL1 ", %0" ::"r"(val));
+#endif
+ ISB;
+}
+
+STATIC INLINE UINT32 GiccGetSre(VOID)
+{
+ UINT32 temp;
+#ifdef LOSCFG_ARCH_SECURE_MONITOR_MODE
+ __asm__ volatile("mrs %0, " ICC_SRE_EL3 : "=r"(temp));
+#else
+ __asm__ volatile("mrs %0, " ICC_SRE_EL1 : "=r"(temp));
+#endif
+ return temp;
+}
+
+STATIC INLINE VOID GiccSetSre(UINT32 val)
+{
+#ifdef LOSCFG_ARCH_SECURE_MONITOR_MODE
+ __asm__ volatile("msr " ICC_SRE_EL3 ", %0" ::"r"(val));
+#else
+ __asm__ volatile("msr " ICC_SRE_EL1 ", %0" ::"r"(val));
+#endif
+ ISB;
+}
+
+STATIC INLINE VOID GiccSetEoir(UINT32 val)
+{
+#ifdef LOSCFG_ARCH_SECURE_MONITOR_MODE
+ __asm__ volatile("msr " ICC_EOIR0_EL1 ", %0" ::"r"(val));
+#else
+ __asm__ volatile("msr " ICC_EOIR1_EL1 ", %0" ::"r"(val));
+#endif
+ ISB;
+}
+
+STATIC INLINE UINT32 GiccGetIar(VOID)
+{
+ UINT32 temp;
+
+#ifdef LOSCFG_ARCH_SECURE_MONITOR_MODE
+ __asm__ volatile("mrs %0, " ICC_IAR0_EL1 : "=r"(temp));
+#else
+ __asm__ volatile("mrs %0, " ICC_IAR1_EL1 : "=r"(temp));
+#endif
+ DSB;
+
+ return temp;
+}
+
+STATIC INLINE VOID GiccSetSgi1r(UINT64 val)
+{
+ __asm__ volatile("msr " ICC_SGI1R_EL1 ", %0" ::"r"(val));
+ ISB;
+ DSB;
+}
+
+STATIC INLINE VOID GiccSetBpr0(UINT32 val)
+{
+ __asm__ volatile("msr " ICC_BPR0_EL1 ", %0" ::"r"(val));
+ ISB;
+ DSB;
+}
+#endif
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/include/hal_hwi.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/include/hal_hwi.h
new file mode 100644
index 00000000..4b068e41
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/include/hal_hwi.h
@@ -0,0 +1,63 @@
+/*
+ * 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 _HWI_H
+#define _HWI_H
+
+#include "los_typedef.h"
+
+#ifdef __cplusplus
+#if __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+extern VOID HalIrqInit(VOID);
+extern VOID HalIrqInitPercpu(VOID);
+extern VOID HalIrqMask(UINT32 vector);
+extern VOID HalIrqUnmask(UINT32 vector);
+extern VOID HalIrqPending(UINT32 vector);
+extern VOID HalIrqClear(UINT32 vector);
+extern CHAR *HalIrqVersion(VOID);
+extern UINT32 HalCurIrqGet(VOID);
+extern UINT32 HalIrqSetPrio(UINT32 vector, UINT8 priority);
+#ifdef LOSCFG_KERNEL_SMP
+extern VOID HalIrqSendIpi(UINT32 target, UINT32 ipi);
+extern VOID HalIrqSetAffinity(UINT32 vector, UINT32 cpuMask);
+#endif
+
+#ifdef __cplusplus
+#if __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+#endif /* _HWI_H */
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/include/in_cksum.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/include/in_cksum.h
new file mode 100644
index 00000000..e86c4966
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/include/in_cksum.h
@@ -0,0 +1,52 @@
+/*
+ * 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 __LINUX_CHECKSUM_H__
+#define __LINUX_CHECKSUM_H__
+
+#ifdef __cplusplus
+#if __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+unsigned int csum_partial(const void *buf, int len, unsigned int wsum);
+unsigned int csum_partial_copy_nocheck(const void *src, void *dst, int len, unsigned int wsum);
+unsigned short in_cksum(const void *buf, int len);
+unsigned short in_cksum_copy(const void *src, void *dst, int len);
+
+#ifdef __cplusplus
+#if __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+#endif
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/include/los_exc.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/include/los_exc.h
new file mode 100644
index 00000000..893f06e0
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/include/los_exc.h
@@ -0,0 +1,254 @@
+/*
+ * 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.
+ */
+
+/**
+ * @defgroup los_exc Exception handling
+ * @ingroup kernel
+ */
+#ifndef _LOS_EXC_H
+#define _LOS_EXC_H
+
+#include "los_typedef.h"
+#include "arch_config.h"
+
+#ifdef __cplusplus
+#if __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+/**
+ * @ingroup los_exc
+ * Register information structure
+ *
+ * Description: register information stored when an exception occurs on an LPC2458 platform.
+ *
+ * Note: The following register names without uw are the register names used in the chip manual.
+ */
+#ifdef LOSCFG_ARCH_ARM_AARCH64
+#define EXC_GEN_REGS_NUM 30
+typedef struct {
+ UINT64 X[EXC_GEN_REGS_NUM]; /**< Register X0-X29 */
+ UINT64 LR; /**< Program returning address. X30 */
+ UINT64 SP;
+ UINT64 regELR;
+ UINT64 SPSR;
+} ExcContext;
+#else
+/* It has the same structure as TaskContext */
+typedef struct {
+ UINT32 R4;
+ UINT32 R5;
+ UINT32 R6;
+ UINT32 R7;
+ UINT32 R8;
+ UINT32 R9;
+ UINT32 R10;
+ UINT32 R11;
+
+ UINT32 SP; /**< svc sp */
+ UINT32 reserved; /**< Reserved, multiplexing register */
+ UINT32 USP;
+ UINT32 ULR;
+ UINT32 R0; /**< Register R0 */
+ UINT32 R1; /**< Register R1 */
+ UINT32 R2; /**< Register R2 */
+ UINT32 R3; /**< Register R3 */
+ UINT32 R12; /**< Register R12 */
+ UINT32 LR; /**< Program returning address. */
+ UINT32 PC; /**< PC pointer of the exceptional function */
+ UINT32 regCPSR;
+} ExcContext;
+#endif
+
+/**
+ * @ingroup los_exc
+ * Exception information structure
+ *
+ * Description: exception information stored when an exception occurs on an LPC2458 platform.
+ *
+ */
+typedef struct {
+ UINT16 phase; /**< Phase in which an exception occurs */
+ UINT16 type; /**< Exception type */
+ UINT16 nestCnt; /**< Count of nested exception */
+ UINT16 reserved; /**< Reserved for alignment */
+ ExcContext *context; /**< Hardware context when an exception occurs */
+} ExcInfo;
+
+/**
+ * @ingroup los_exc
+ * @brief Kernel FP Register address obtain function.
+ *
+ * @par Description:
+ * The API is used to obtain the FP Register address.
+ * @attention None.
+ *
+ * @param None.
+ *
+ * @retval #UINTPTR The FP Register address.
+ *
+ * @par Dependency:
+ * los_exc.h: the header file that contains the API declaration.
+ * @see None.
+ */
+STATIC INLINE UINTPTR Get_Fp(VOID)
+{
+ UINTPTR regFp;
+
+#ifdef LOSCFG_ARCH_ARM_AARCH64
+ __asm__ __volatile__("mov %0, X29" : "=r"(regFp));
+#else
+ __asm__ __volatile__("mov %0, fp" : "=r"(regFp));
+#endif
+
+ return regFp;
+}
+
+/**
+ * @ingroup los_exc
+ * @brief Define an exception handling function hook.
+ *
+ * @par Description:
+ * This API is used to define the exception handling function hook based on the type of
+ * the exception handling function and record exceptions.
+ * @attention None.
+ *
+ * @param None.
+ *
+ * @retval None.
+ *
+ * @par Dependency:
+ * los_exc.h: the header file that contains the API declaration.
+ * @see None.
+ */
+typedef VOID (*EXC_PROC_FUNC)(UINT32, ExcContext *, UINT32, UINT32);
+
+/**
+ * @ingroup los_exc
+ * @brief Register an exception handling hook.
+ *
+ * @par Description:
+ * This API is used to register an exception handling hook.
+ * @attention If the hook is registered for multiple times, the hook registered at the last time is effective.
+ * @attention The hook can be registered as NULL, indicating that the hook registration is canceled.
+ * @param excHook [IN] Type #EXC_PROC_FUNC: hook function.
+ *
+ * @retval #LOS_OK The exception handling hook is successfully registered.
+ *
+ * @par Dependency:
+ * los_exc.h: the header file that contains the API declaration.
+ * @see None.
+ */
+extern UINT32 LOS_ExcRegHook(EXC_PROC_FUNC excHook);
+
+/**
+ * @ingroup los_exc
+ * @brief Kernel panic function.
+ *
+ * @par Description:
+ * Stack function that prints kernel panics.
+ * @attention After this function is called and stack information is printed, the system will fail to respond.
+ * @attention The input parameter can be NULL.
+ * @param fmt [IN] Type #CHAR* : variadic argument.
+ *
+ * @retval #None.
+ *
+ * @par Dependency:
+ * los_exc.h: the header file that contains the API declaration.
+ * @see None.
+ */
+NORETURN VOID LOS_Panic(const CHAR *fmt, ...);
+
+/**
+ * @ingroup los_exc
+ * @brief record LR function.
+ *
+ * @par Description:
+ * @attention
+ * @param LR [IN] Type #UINTPTR * LR buffer.
+ * @param recordCount [IN] Type UINT32 record LR lay number.
+ * @param jumpCount [IN] Type UINT32 ignore LR lay number.
+ *
+ * @retval #None.
+ *
+ * @par Dependency:
+ * los_exc.h: the header file that contains the API declaration.
+ * @see None.
+ */
+VOID LOS_RecordLR(UINTPTR *LR, UINT32 LRSize, UINT32 recordCount, UINT32 jumpCount);
+
+/**
+ * @ingroup los_exc
+ * @brief Kernel backtrace function.
+ *
+ * @par Description:
+ * Backtrace function that prints task call stack information traced from the running task.
+ * @attention None.
+ *
+ * @param None.
+ *
+ * @retval #None.
+ *
+ * @par Dependency:
+ * los_exc.h: the header file that contains the API declaration.
+ * @see None.
+ */
+extern VOID OsBackTrace(VOID);
+
+/**
+ * @ingroup los_exc
+ * @brief Kernel task backtrace function.
+ *
+ * @par Description:
+ * Backtrace function that prints task call stack information traced from the input task.
+ * @attention
+ *
+ *
The input taskID should be valid.
+ *
+ *
+ * @param taskID [IN] Type #UINT32 Task ID.
+ *
+ * @retval #None.
+ *
+ * @par Dependency:
+ * los_exc.h: the header file that contains the API declaration.
+ * @see None.
+ */
+extern VOID OsTaskBackTrace(UINT32 taskID);
+
+#ifdef __cplusplus
+#if __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+#endif /* _LOS_EXC_H */
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/include/los_hw.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/include/los_hw.h
new file mode 100644
index 00000000..18f13e43
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/include/los_hw.h
@@ -0,0 +1,190 @@
+/*
+ * 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.
+ */
+
+/**
+ * @defgroup los_hw Hardware
+ * @ingroup kernel
+ */
+#ifndef _LOS_HW_H
+#define _LOS_HW_H
+
+#include "los_typedef.h"
+#include "los_hw_cpu.h"
+#ifdef __cplusplus
+#if __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+#define OS_SCHEDULE_IN_IRQ 0x0
+#define OS_SCHEDULE_IN_TASK 0x1
+
+#define PSR_T_ARM 0x00000000u
+#define PSR_T_THUMB 0x00000020u
+#define PSR_MODE_SVC 0x00000013u
+#define PSR_MODE_SYS 0x0000001Fu
+#define PSR_FIQ_DIS 0x00000040u
+#define PSR_IRQ_DIS 0x00000080u
+#define PSR_MODE_USR 0x00000010u
+
+#define PSR_MODE_SVC_THUMB (PSR_MODE_SVC | PSR_T_THUMB | PSR_FIQ_DIS | PSR_IRQ_DIS)
+#define PSR_MODE_SVC_ARM (PSR_MODE_SVC | PSR_T_ARM | PSR_FIQ_DIS | PSR_IRQ_DIS)
+
+#define PSR_MODE_SYS_THUMB (PSR_MODE_SYS | PSR_T_THUMB)
+#define PSR_MODE_SYS_ARM (PSR_MODE_SYS | PSR_T_ARM)
+
+#define PSR_MODE_USR_THUMB (PSR_MODE_USR | PSR_T_THUMB)
+#define PSR_MODE_USR_ARM (PSR_MODE_USR | PSR_T_ARM)
+
+#define LOS_CHECK_SCHEDULE ((!OS_INT_ACTIVE) && OsPreemptable())
+
+typedef struct {
+ const UINT32 partNo;
+ const CHAR *cpuName;
+} CpuVendor;
+
+extern CpuVendor g_cpuTable[];
+extern UINT64 g_cpuMap[];
+
+#define CPU_MAP_GET(cpuid) g_cpuMap[(cpuid)]
+#define CPU_MAP_SET(cpuid, hwid) g_cpuMap[(cpuid)] = (hwid)
+
+/**
+ * @ingroup los_hw
+ * @brief Invalidate instruction cache.
+ *
+ * @par Description:
+ *
+ *
This API is used to invalidate the instruction cache.
This API is used to flush the data cache to the memory.
+ *
+ * @attention
+ *
+ *
The input end address must be greater than the input start address.
+ *
+ *
+ * @param start [IN] Type #int Flush start address.
+ * @param end [IN] Type #int Flush end address.
+ *
+ * @retval #None.
+ *
+ * @par Dependency:
+ * los_hw.h: the header file that contains the API declaration.
+ * @see None.
+ */
+extern VOID DCacheFlushRange(UINTPTR start, UINTPTR end);
+
+/**
+ * @ingroup los_hw
+ * @brief Invalidate data cache.
+ *
+ * @par Description:
+ *
+ *
This API is used to Invalidate the data in cache.
+ *
+ * @attention
+ *
+ *
The input end address must be greater than the input start address.
+ *
+ *
+ * @param start [IN] Type #int Invalidate start address.
+ * @param end [IN] Type #int Invalidate end address .
+ *
+ * @retval #None.
+ *
+ * @par Dependency:
+ * los_hw.h: the header file that contains the API declaration.
+ * @see None.
+ */
+extern VOID DCacheInvRange(UINTPTR start, UINTPTR end);
+
+/**
+ * @ingroup los_hw
+ * @brief Get cpu core name.
+ *
+ * @par Description:
+ *
+ *
This API is used to get cpu core name.
+ *
+ * @attention
+ *
+ *
None.
+ *
+ *
+ * @param
+ * @retval #CHAR * cpu core name.
+ *
+ * @par Dependency:
+ * los_hw.h: the header file that contains the API declaration.
+ * @see None.
+ */
+STATIC INLINE const CHAR *LOS_CpuInfo(VOID)
+{
+ INT32 i;
+ UINT32 midr = OsMainIDGet();
+ /* [15:4] is the primary part number */
+ UINT32 partNo = (midr & 0xFFF0) >> 0x4;
+
+ for (i = 0; g_cpuTable[i].partNo != 0; i++) {
+ if (partNo == g_cpuTable[i].partNo) {
+ return g_cpuTable[i].cpuName;
+ }
+ }
+
+ return "unknown";
+}
+
+#ifdef __cplusplus
+#if __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+#endif /* _LOS_HW_H */
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/include/los_hw_arch.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/include/los_hw_arch.h
new file mode 100644
index 00000000..3539d928
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/include/los_hw_arch.h
@@ -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.
+ */
+
+/**
+ * @defgroup los_hw Hardware
+ * @ingroup kernel
+ */
+
+#ifndef _LOS_HW_ARCH_H
+#define _LOS_HW_ARCH_H
+
+# if defined(__GNUC__)
+# if defined(__aarch64__)
+# define LOSCFG_ARM_AARCH64 1
+# endif
+#
+# define LOSCFG_ARM_ARCH __ARM_ARCH
+# else
+# error "unsupported compiler!"
+# endif
+
+#endif
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/include/los_hw_tick_pri.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/include/los_hw_tick_pri.h
new file mode 100644
index 00000000..1b893176
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/include/los_hw_tick_pri.h
@@ -0,0 +1,52 @@
+/*
+ * 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 _LOS_HW_TICK_PRI_H
+#define _LOS_HW_TICK_PRI_H
+
+#include "los_typedef.h"
+
+#ifdef __cplusplus
+#if __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+extern UINT32 OsTickInit(UINT32 systemClock, UINT32 tickPerSecond);
+extern VOID OsTickStart(VOID);
+
+#ifdef __cplusplus
+#if __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+#endif /* _LOS_HW_TICK_PRI_H */
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/include/los_hwi.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/include/los_hwi.h
new file mode 100644
index 00000000..cee783dc
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/include/los_hwi.h
@@ -0,0 +1,439 @@
+/*
+ * 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.
+ */
+
+/**
+ * @defgroup los_hwi Hardware interrupt
+ * @ingroup kernel
+ */
+#ifndef _LOS_HWI_H
+#define _LOS_HWI_H
+
+#include "los_base.h"
+#include "los_hw_cpu.h"
+#include "hal_hwi.h"
+
+#ifdef __cplusplus
+#if __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+/**
+ * @ingroup los_hwi
+ * Count of interrupts.
+ */
+extern size_t g_intCount[];
+
+/**
+ * @ingroup los_hwi
+ * An interrupt is active.
+ */
+#define OS_INT_ACTIVE ({ \
+ size_t intCount; \
+ UINT32 intSave_ = LOS_IntLock(); \
+ intCount = g_intCount[ArchCurrCpuid()]; \
+ LOS_IntRestore(intSave_); \
+ intCount; \
+})
+
+/**
+ * @ingroup los_hwi
+ * An interrupt is inactive.
+ */
+#define OS_INT_INACTIVE (!(OS_INT_ACTIVE))
+
+/**
+ * @ingroup los_hwi
+ * Highest priority of a hardware interrupt.
+ */
+#define OS_HWI_PRIO_HIGHEST 0
+
+/**
+ * @ingroup los_hwi
+ * Lowest priority of a hardware interrupt.
+ */
+#define OS_HWI_PRIO_LOWEST 31
+
+/**
+ * @ingroup los_hwi
+ * Max name length of a hardware interrupt.
+ */
+#define OS_HWI_MAX_NAMELEN 10
+
+/**
+ * @ingroup los_hwi
+ * Hardware interrupt error code: Invalid interrupt number.
+ *
+ * Value: 0x02000900
+ *
+ * Solution: Ensure that the interrupt number is valid.
+ */
+#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.
+ */
+#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 API is called during an interrupt, which is forbidden.
+ *
+ * Value: 0x02000908
+ *
+ * * Solution: Do not call the API during an interrupt.
+ */
+#define OS_ERRNO_HWI_INTERR LOS_ERRNO_OS_ERROR(LOS_MOD_HWI, 0x08)
+
+/**
+ * @ingroup los_hwi
+ * Hardware interrupt error code:the hwi support SHARED error.
+ *
+ * Value: 0x02000909
+ *
+ * * Solution: Check the input params hwiMode and irqParam of LOS_HwiCreate or
+ * LOS_HwiDelete whether adapt the current hwi.
+ */
+#define OS_ERRNO_HWI_SHARED_ERROR LOS_ERRNO_OS_ERROR(LOS_MOD_HWI, 0x09)
+
+/**
+ * @ingroup los_hwi
+ * Hardware interrupt error code:Invalid interrupt Arg when interrupt mode is IRQF_SHARED.
+ *
+ * Value: 0x0200090a
+ *
+ * * Solution: Check the interrupt Arg, Arg should not be NULL and pDevId should not be NULL.
+ */
+#define OS_ERRNO_HWI_ARG_INVALID LOS_ERRNO_OS_ERROR(LOS_MOD_HWI, 0x0a)
+
+/**
+ * @ingroup los_hwi
+ * Hardware interrupt error code:The interrupt corresponded to the hwi number or devid has not been created.
+ *
+ * Value: 0x0200090b
+ *
+ * * Solution: Check the hwi number or devid, make sure the hwi number or devid need to delete.
+ */
+#define OS_ERRNO_HWI_HWINUM_UNCREATE LOS_ERRNO_OS_ERROR(LOS_MOD_HWI, 0x0b)
+
+/**
+ * @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 UINTPTR HWI_ARG_T;
+
+/**
+ * @ingroup los_hwi
+ * Define the type of a hardware interrupt handling function.
+ */
+typedef VOID (*HWI_PROC_FUNC)(VOID);
+
+/*
+ * These flags used only by the kernel as part of the
+ * irq handling routines.
+ *
+ * IRQF_SHARED - allow sharing the irq among several devices
+ */
+#define IRQF_SHARED 0x8000U
+
+typedef struct tagHwiHandleForm {
+ HWI_PROC_FUNC pfnHook;
+ HWI_ARG_T uwParam;
+ struct tagHwiHandleForm *pstNext;
+} HwiHandleForm;
+
+typedef struct tagIrqParam {
+ int swIrq;
+ VOID *pDevId;
+ const CHAR *pName;
+} HwiIrqParam;
+
+extern HwiHandleForm g_hwiForm[OS_HWI_MAX_NUM];
+
+/**
+ * @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 #UINT32 CPSR value obtained before all interrupts are disabled.
+ * @par Dependency:
+ *
los_hwi.h: the header file that contains the API declaration.
los_hwi.h: the header file that contains the API declaration.
+ */
+extern UINT32 LOS_GetSystemHwiMaximum(VOID);
+
+/**
+ * @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_USER_HWI_MIN,OS_USER_HWI_MAX].
+ *
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.
+ *
The parameter handler of this interface is a interrupt handler, it should be correct, otherwise,
+ * the system may be abnormal.
+ *
The input irqParam could be NULL, if not, it should be address which point to a struct HwiIrqParam
+ *
+ *
+ * @param hwiNum [IN] Type #HWI_HANDLE_T: hardware interrupt number.
+ * for an ARM926 platform is [0,31].
+ * @param hwiPrio [IN] Type #HWI_PRIOR_T: hardware interrupt priority. The value range is
+ * [0, GIC_MAX_INTERRUPT_PREEMPTION_LEVEL - 1] << PRIORITY_SHIFT.
+ * @param hwiMode [IN] Type #HWI_MODE_T: hardware interrupt mode. Ignore this parameter temporarily.
+ * @param hwiHandler [IN] Type #HWI_PROC_FUNC: interrupt handler used when a hardware interrupt is triggered.
+ * @param irqParam [IN] Type #HwiIrqParam: input parameter of the interrupt handler used when
+ * a hardware interrupt is triggered.
+ *
+ * @retval #OS_ERRNO_HWI_PROC_FUNC_NULL Null hardware interrupt handling function.
+ * @retval #OS_ERRNO_HWI_NUM_INVALID Invalid interrupt number.
+ * @retval #OS_ERRNO_HWI_NO_MEMORY Insufficient memory for hardware interrupt creation.
+ * @retval #OS_ERRNO_HWI_ALREADY_CREATED The interrupt handler being created has already been created.
+ * @retval #LOS_OK 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 hwiMode,
+ HWI_PROC_FUNC hwiHandler,
+ HwiIrqParam *irqParam);
+
+/**
+ * @ingroup los_hwi
+ * @brief delete a hardware interrupt.
+ *
+ * @par Description:
+ * This API is used to delete a 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_USER_HWI_MIN,OS_USER_HWI_MAX].
+ *
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.
+ * @param irqParam [IN] Type #HwiIrqParam *: id of hardware interrupt which will base on
+ * when delete the hardware interrupt.
+ *
+ * @retval #OS_ERRNO_HWI_NUM_INVALID Invalid interrupt number.
+ * @retval #OS_ERRNO_HWI_SHARED_ERROR Invalid interrupt mode.
+ * @retval #LOS_OK The interrupt is successfully deleted.
+ * @retval #LOS_NOK The interrupt is failed deleted based on the pDev_ID.
+
+ * @par Dependency:
+ *
los_hwi.h: the header file that contains the API declaration.
+ * @see None.
+ */
+extern UINT32 LOS_HwiDelete(HWI_HANDLE_T hwiNum, HwiIrqParam *irqParam);
+
+#ifdef __cplusplus
+#if __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+#endif /* _LOS_HWI_H */
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/include/los_strncpy_from_user.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/include/los_strncpy_from_user.h
new file mode 100644
index 00000000..7b0024ec
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/include/los_strncpy_from_user.h
@@ -0,0 +1,64 @@
+/*
+ * 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 _LOS_STRNCPY_FROM_USER_H
+#define _LOS_STRNCPY_FROM_USER_H
+
+#include "los_typedef.h"
+
+#ifdef __cplusplus
+#if __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+/*
+ * @brief Copy a string end with NULL from userspace to kernelspace
+ *
+ * This function validates that usermode has access to src before copying the
+ * data.
+ *
+ * @param dst The destination buffer in kernel space.
+ * @param src The source buffer in user space.
+ * @param count Max number of bytes to copy.
+ *
+ * @return Return -EFAULT if src is not in user space or count <= 0 or copy out of range. Return the length of
+ * the string if success, if count is smaller than the length of the string then copy count bytes and return count.
+ */
+INT32 LOS_StrncpyFromUser(CHAR *dst, const CHAR *src, INT32 count);
+
+#ifdef __cplusplus
+#if __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+#endif /* _LOS_STRNCPY_FROM_USER_H */
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/include/los_strnlen_user.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/include/los_strnlen_user.h
new file mode 100644
index 00000000..39371a8c
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/include/los_strnlen_user.h
@@ -0,0 +1,63 @@
+/*
+ * 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 _LOS_STRNLEN_USER_H
+#define _LOS_STRNLEN_USER_H
+
+#include "los_typedef.h"
+
+#ifdef __cplusplus
+#if __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+/*
+ * @brief Get the length of string including final NULL.
+ *
+ * This function validates that usermode has access to src before measuring the string.
+ *
+ * @param src The string in userspace to measure.
+ * @param count Max count.
+ *
+ * @return Return the length of the string including final NULL. Return 0 if src is not in user space or count <= 0 or
+ * visit the memory out of range. Return a number larger than count if the string is too long, User should handle
+ * this situation.
+ */
+INT32 LOS_StrnlenUser(const CHAR *src, INT32 count);
+
+#ifdef __cplusplus
+#if __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+#endif /* _LOS_STRNLEN_USER_H */
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/include/los_sys_stack_pri.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/include/los_sys_stack_pri.h
new file mode 100644
index 00000000..fb968fd9
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/include/los_sys_stack_pri.h
@@ -0,0 +1,59 @@
+/*
+ * 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 _LOS_SYS_STACK_H
+#define _LOS_SYS_STACK_H
+
+#include "los_typedef.h"
+
+#ifdef __cplusplus
+#if __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+#ifdef LOSCFG_AARCH64
+extern UINTPTR __stack_startup;
+extern UINTPTR __stack_startup_top;
+#else
+extern UINTPTR __svc_stack_top;
+extern UINTPTR __exc_stack_top;
+extern UINTPTR __svc_stack;
+extern UINTPTR __exc_stack;
+#endif
+
+#ifdef __cplusplus
+#if __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+#endif
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/include/los_user_get.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/include/los_user_get.h
new file mode 100644
index 00000000..de882a77
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/include/los_user_get.h
@@ -0,0 +1,65 @@
+/*
+ * 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 _LOS_USER_GET_H
+#define _LOS_USER_GET_H
+
+#include "los_typedef.h"
+#include "arm_user_get.h"
+
+#ifdef __cplusplus
+#if __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+/*
+ * @brief Get data from userspace into kernelspace
+ *
+ * This function validates that usermode has access to src before copying the
+ * data.
+ *
+ * @param dst The destination buffer in kernel space.
+ * @param src The source buffer in user space.
+ *
+ * @note The data type is simple such as char, short, int, long in 32bits platform.
+ *
+ * @return Return -EFAULT if error. Return 0 if success.
+ */
+#define LOS_GetUser(dst, src) _arm_get_user((dst), (src), sizeof(*(dst)), sizeof(*(src)))
+
+#ifdef __cplusplus
+#if __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+#endif /* _LOS_USER_GET_H */
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/include/los_user_put.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/include/los_user_put.h
new file mode 100644
index 00000000..f8e74535
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/include/los_user_put.h
@@ -0,0 +1,65 @@
+/*
+ * 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 _LOS_USER_PUT_H
+#define _LOS_USER_PUT_H
+
+#include "los_typedef.h"
+#include "arm_user_put.h"
+
+#ifdef __cplusplus
+#if __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+/*
+ * @brief put data from kernelspace into userspace
+ *
+ * This function validates that usermode has access to dst before copying the
+ * data.
+ *
+ * @param dst The destination buffer in user space.
+ * @param src The source buffer in kernel space.
+ *
+ * @note The data type is simple such as char, short, int, long in 32bits platform.
+ *
+ * @return Return -EFAULT if error. Return 0 if success.
+ */
+#define LOS_PutUser(src, dst) _arm_put_user((dst), (src), sizeof(*(dst)), sizeof(*(src)))
+
+#ifdef __cplusplus
+#if __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+#endif /* _LOS_USER_PUT_H */
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/include/perf.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/include/perf.h
new file mode 100644
index 00000000..cb9ecd4d
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/include/perf.h
@@ -0,0 +1,61 @@
+/*
+ * 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 _PERF_H
+#define _PERF_H
+
+#include "los_typedef.h"
+
+#ifdef __cplusplus
+#if __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+#define OsPerfArchFetchCallerRegs(regs) \
+ do { \
+ (regs)->pc = (UINTPTR)__builtin_return_address(0); \
+ (regs)->fp = (UINTPTR)__builtin_frame_address(0); \
+ } while (0)
+
+#define OsPerfArchFetchIrqRegs(regs, tcb) \
+ do { \
+ (regs)->pc = (tcb)->pc; \
+ (regs)->fp = (tcb)->fp; \
+ } while (0)
+
+#ifdef __cplusplus
+#if __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+#endif /* _PERF_H */
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/include/user_copy.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/include/user_copy.h
new file mode 100644
index 00000000..293d4e34
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/arm/include/user_copy.h
@@ -0,0 +1,103 @@
+/*
+ * 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_typedef.h"
+#pragma once
+
+/*
+ * @brief Copy data from userspace into kernelspace
+ *
+ * This function validates that usermode has access to src before copying the
+ * data.
+ *
+ * @param dst The destination buffer.
+ * @param src The source buffer.
+ * @param len The number of bytes to copy.
+ *
+ * @return bytes not copied
+ */
+size_t LOS_ArchCopyFromUser(void *dst, const void *src, size_t len);
+
+/*
+ * @brief Copy data from kernelspace into userspace
+ *
+ * This function validates that usermode has access to dst before copying the
+ * data.
+ *
+ * @param dst The destination buffer.
+ * @param src The source buffer.
+ * @param len The number of bytes to copy.
+ *
+ * @return bytes not copied
+ */
+size_t LOS_ArchCopyToUser(void *dst, const void *src, size_t len);
+
+/*
+ * @brief Copy data from src to dst
+ *
+ * This function will use different copy methods to copy src data to dst, according to
+ * the different spaces (userspace or kernelspace) of dst data.
+ *
+ * @param dst The destination buffer, can be userspace address.
+ * @param max The maxsimum number of bytes to copy.
+ * @param src The source buffer.
+ * @param len The number of bytes to copy.
+ *
+ * @return zero on success; non-zero on failure.
+ */
+INT32 LOS_CopyFromKernel(VOID *dest, UINT32 max, const VOID *src, UINT32 count);
+
+/*
+ * @brief Copy data from src to dst
+ *
+ * This function will use different copy methods to copy src data to dst, according to
+ * the different spaces (userspace or kernelspace) of src data.
+ *
+ * @param dst The destination buffer.
+ * @param max The maxsimum number of bytes to copy.
+ * @param src The source buffer, can be userspace address.
+ * @param len The number of bytes to copy.
+ *
+ * @return zero on success; non-zero on failure.
+ */
+INT32 LOS_CopyToKernel(VOID *dest, UINT32 max, const VOID *src, UINT32 count);
+
+/*
+ * @brief Clear data in buf
+ *
+ * This function will clear buf from buf to buf + len.
+ *
+ * @param buf The destination buffer, can be userspace address.
+ * @param len The number of bytes to clear.
+ *
+ * @return zero on success; non-zero on failure.
+ */
+INT32 LOS_UserMemClear(unsigned char *buf, UINT32 len);
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/cpu.mk b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/cpu.mk
new file mode 100644
index 00000000..856099ef
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/arch/cpu.mk
@@ -0,0 +1,32 @@
+# 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.
+
+ifeq ($(LOSCFG_ARCH_ARM), y)
+-include $(LITEOSTOPDIR)/arch/arm/arm.mk
+endif
\ No newline at end of file
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/bsd/BUILD.gn b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/bsd/BUILD.gn
new file mode 100644
index 00000000..fac70d00
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/bsd/BUILD.gn
@@ -0,0 +1,86 @@
+# 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("//kernel/liteos_a/liteos.gni")
+
+module_switch = defined(LOSCFG_COMPAT_BSD)
+module_name = "libbsd"
+kernel_module(module_name) {
+ sources = [
+ "kern/bus_if.c",
+ "kern/device_if.c",
+ "kern/kern_condvar.c",
+ "kern/kern_timeout.c",
+ "kern/subr_bus.c",
+ "kern/subr_kobj.c",
+ ]
+
+ if (defined(LOSCFG_ARCH_ARM_AARCH32)) {
+ sources += [
+ "arm/autoconf.c",
+ "arm/hw_user_copy.S",
+ "arm/in_cksum.c",
+ "arm/in_cksum_arm.S",
+ "arm/nexus.c",
+ ]
+ }
+
+ if (defined(LOSCFG_DRIVERS_RANDOM)) {
+ sources += [
+ "crypto/rijndael/rijndael-alg-fst.c",
+ "crypto/rijndael/rijndael-api-fst.c",
+ "crypto/sha2/sha256c.c",
+ "dev/random/hash.c",
+ "dev/random/yarrow.c",
+ "libkern/explicit_bzero.c",
+ ]
+ }
+
+ public_configs = [ ":public" ]
+}
+
+group("bsd") {
+ public_deps = [ ":$module_name" ]
+
+ deps = [
+ "compat/linuxkpi",
+ "dev/usb",
+ ]
+}
+
+config("public") {
+ include_dirs = [
+ ".",
+ "kern",
+ ]
+ configs = [
+ "compat/linuxkpi:public",
+ "dev/usb:public",
+ ]
+}
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/bsd/Kconfig b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/bsd/Kconfig
new file mode 100644
index 00000000..c19d8cd8
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/bsd/Kconfig
@@ -0,0 +1,14 @@
+config COMPAT_BSD
+ bool "Enable FreeBSD"
+ default y
+ select COMPAT_LINUXKPI
+
+ help
+ Answer Y to enable LiteOS support FreeBSD.
+
+config COMPAT_LINUXKPI
+ bool "Enable linuxkpi" if COMPAT_BSD
+ default y
+
+ help
+ Answer Y to enable LiteOS support compatible layer for linuxkpi.
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/bsd/Makefile b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/bsd/Makefile
new file mode 100644
index 00000000..353779cd
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/bsd/Makefile
@@ -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.
+
+include $(LITEOSTOPDIR)/config.mk
+
+MODULE_NAME := $(notdir $(shell pwd))
+
+LOCAL_SRCS := $(wildcard kern/*.c)
+
+LOCAL_SRCS += $(wildcard $(ARCH)/*.c)
+LOCAL_SRCS += $(wildcard $(ARCH)/*.S)
+
+ifeq ($(LOSCFG_DRIVERS_RANDOM), y)
+LOCAL_SRCS += $(wildcard crypto/rijndael/*.c) \
+ $(wildcard crypto/sha2/*.c) \
+ $(wildcard dev/random/*.c) \
+ $(wildcard libkern/*.c)
+endif
+
+include $(MODULE)
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/bsd/compat/linuxkpi/BUILD.gn b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/bsd/compat/linuxkpi/BUILD.gn
new file mode 100644
index 00000000..01c73efb
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/bsd/compat/linuxkpi/BUILD.gn
@@ -0,0 +1,57 @@
+# 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("//kernel/liteos_a/liteos.gni")
+
+module_switch = defined(LOSCFG_COMPAT_BSD)
+module_name = get_path_info(rebase_path("."), "name")
+kernel_module(module_name) {
+ sources = [
+ "src/adp.c",
+ "src/linux_completion.c",
+ "src/linux_interrupt.c",
+ "src/linux_sched.c",
+ "src/linux_semaphore.c",
+ "src/linux_timer.c",
+ "src/linux_wakelock.c",
+ "src/linux_workqueue.c",
+ "src/prctl.c",
+ "src/tzdst.c",
+ ]
+
+ if (defined(LOSCFG_HRTIMER_ENABLE)) {
+ sources += [ "src/linux_hrtimer.c" ]
+ }
+
+ public_configs = [ ":public" ]
+}
+
+config("public") {
+ include_dirs = [ "include" ]
+}
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/bsd/compat/linuxkpi/Makefile b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/bsd/compat/linuxkpi/Makefile
new file mode 100644
index 00000000..d4e304db
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/bsd/compat/linuxkpi/Makefile
@@ -0,0 +1,40 @@
+# 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 $(LITEOSTOPDIR)/config.mk
+
+MODULE_NAME := $(notdir $(shell pwd))
+
+LOCAL_SRCS := $(wildcard src/*.c)
+
+ifneq ($(LOSCFG_HRTIMER_ENABLE), y)
+LOCAL_SRCS := $(filter-out src/linux_hrtimer.c, $(LOCAL_SRCS))
+endif
+
+include $(MODULE)
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/bsd/dev/usb/BUILD.gn b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/bsd/dev/usb/BUILD.gn
new file mode 100644
index 00000000..205a8f51
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/bsd/dev/usb/BUILD.gn
@@ -0,0 +1,149 @@
+# 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("//kernel/liteos_a/liteos.gni")
+
+module_switch = defined(LOSCFG_DRIVERS_USB)
+module_name = "usb_base"
+kernel_module(module_name) {
+ sources = [
+ "implementation/bsd_busspace.c",
+ "implementation/bsd_kernel.c",
+ "implementation/usb_btree.c",
+ "implementation/usb_busdma_loader.c",
+ "implementation/usb_init.c",
+ "implementation/usb_version.c",
+ "usb_debug.c",
+ ]
+
+ if (defined(LOSCFG_DRIVERS_USB)) {
+ sources += [
+ "controller/usb_controller.c",
+ "quirk/usb_quirk.c",
+ "usb_dev.c",
+ "usb_device.c",
+ "usb_dynamic.c",
+ "usb_error.c",
+ "usb_generic.c",
+ "usb_handle_request.c",
+ "usb_hub.c",
+ "usb_if.c",
+ "usb_lookup.c",
+ "usb_mbuf.c",
+ "usb_parse.c",
+ "usb_process.c",
+ "usb_request.c",
+ "usb_transfer.c",
+ "usb_util.c",
+ ]
+ }
+
+ if (defined(LOSCFG_DRIVERS_USB_4G_MODEM)) {
+ sources += [ "net/if_cdce.c" ]
+ }
+
+ if (defined(LOSCFG_DRIVERS_USB_ETHERNET)) {
+ sources += [
+ "net/if_axe.c",
+ "net/if_axge.c",
+ ]
+ }
+
+ if (defined(LOSCFG_DRIVERS_USB_RNDIS_HOST)) {
+ sources += [ "net/if_urndis.c" ]
+ }
+
+ if (defined(LOSCFG_DRIVERS_USB_4G_MODEM) ||
+ defined(LOSCFG_DRIVERS_USB_ETHERNET) ||
+ defined(LOSCFG_DRIVERS_USB_RNDIS_HOST)) {
+ sources += [
+ "net/usb_eth_drv.c",
+ "net/usb_ethernet.c",
+ ]
+ }
+
+ if (defined(LOSCFG_DRIVERS_USB_4G_MODEM) ||
+ defined(LOSCFG_DRIVERS_USB_SERIAL)) {
+ sources += [
+ "serial/u3g.c",
+ "serial/usb_serial.c",
+ ]
+ }
+
+ if (defined(LOSCFG_DRIVERS_USB_HOST_EHCI)) {
+ sources += [
+ "controller/ehci.c",
+ "controller/ehci_pci.c",
+ ]
+ }
+
+ if (defined(LOSCFG_DRIVERS_USB_HOST_XHCI) ||
+ defined(LOSCFG_DRIVERS_USB_HOST_XHCI_FOR_PORT2)) {
+ sources += [
+ "controller/xhci.c",
+ "controller/xhci_pci.c",
+ ]
+ }
+
+ if (defined(LOSCFG_DRIVERS_USB_WIRELESS)) {
+ sources += [ "linux_usb.c" ]
+ }
+
+ if (defined(LOSCFG_DRIVERS_USB_MASS_STORAGE)) {
+ sources += [ "storage/umass.c" ]
+ }
+
+ if (defined(LOSCFG_DRIVERS_USB_HID_CLASS) &&
+ defined(LOSCFG_DRIVERS_HDF_INPUT)) {
+ sources += [
+ "input/uhid.c",
+ "usb_hid.c",
+ ]
+
+ include_dirs = [
+ "//drivers/framework/model/input/driver",
+ "//drivers/framework/include/core",
+ "//drivers/framework/core/common/include/host",
+ "//drivers/framework/utils",
+ "//drivers/framework/osal",
+ "//drivers/framework/ability/sbuf/include",
+ "//drivers/framework/include/osal",
+ ]
+ }
+
+ configs += [ "$HDFTOPDIR:hdf_config" ]
+
+ public_configs = [ ":public" ]
+}
+
+config("public") {
+ defines = [ "USB_DEBUG_VAR=5" ]
+ include_dirs = [ "." ]
+ include_dirs += [ "$LITEOSTHIRDPARTY/FreeBSD/sys/dev/evdev" ]
+}
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/bsd/dev/usb/Kconfig b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/bsd/dev/usb/Kconfig
new file mode 100644
index 00000000..6d365d5e
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/bsd/dev/usb/Kconfig
@@ -0,0 +1,102 @@
+config DRIVERS_USB
+ bool "Enable USB"
+ default y
+ depends on DRIVERS && COMPAT_BSD
+ help
+ Answer Y to enable LiteOS support usb.
+
+config DRIVERS_USB_HOST_DRIVER
+ bool "Enable USB HCD"
+ default y
+ depends on DRIVERS_USB && DRIVERS
+ help
+ Answer Y to enable LiteOS to support usb host controller driver.
+
+choice
+ depends on DRIVERS_USB_HOST_DRIVER
+ prompt "USB HCD"
+ default DRIVERS_USB_HOST_EHCI
+ help
+ Enable EHCI for USB 2.0.
+ Enable XHCI for USB 3.0
+
+config DRIVERS_USB_HOST_EHCI
+ bool "Enable EHCI HCD (USB 2.0)"
+ depends on DRIVERS_USB
+
+config DRIVERS_USB_HOST_XHCI
+ bool "Enable XHCI HCD (USB 3.0)"
+ depends on DRIVERS_USB
+
+endchoice
+
+choice
+ depends on PLATFORM_HI3556AV100 && DRIVERS_USB_HOST_XHCI
+ prompt ""
+ default DRIVERS_USB3_HOST_FOR_PORT1
+ help
+ This selects the usb3.0 port or usb2.0 port.
+
+config DRIVERS_USB3_HOST_FOR_PORT1
+ bool "Enable USB3.0 Host Controller For USB3.0 Port1"
+
+config DRIVERS_USB3_HOST_FOR_PORT2
+ bool "Enable USB3.0 Host Controller For USB2.0 Port2"
+
+endchoice
+
+config DRIVERS_USB_DEVICE_CLASS_DRIVERS
+ bool "Enable USB Device Class Drivers"
+ default y
+ depends on DRIVERS_USB && DRIVERS && DRIVERS_USB_HOST_DRIVER
+ help
+ Answer Y to enable LiteOS to support usb device class drivers.
+
+menu "USB Device Class Drivers"
+ depends on DRIVERS_USB_DEVICE_CLASS_DRIVERS
+config DRIVERS_USB_MASS_STORAGE
+ bool "Enable USB Mass Storage Support"
+ default y
+ depends on DRIVERS_USB_DEVICE_CLASS_DRIVERS && FS_VFS
+ help
+ Say Y here if you want to connect USB mass storage devices to your system's USB port.
+
+config DRIVERS_USB_RNDIS_HOST
+ bool "Enable USB Rndis Host Support"
+ default y
+ depends on DRIVERS_USB_DEVICE_CLASS_DRIVERS && NET_LWIP_SACK
+ help
+ Say Y here if you want to connect USB Rndis Host devices to your system's USB port.
+
+config DRIVERS_USB_4G_MODEM
+ bool "Enable USB 4G Modem Support"
+ default y
+ depends on DRIVERS_USB_DEVICE_CLASS_DRIVERS && NET_LWIP_SACK
+ help
+ Say Y here if you want to connect USB 4G devices to your system's USB port.
+
+config DRIVERS_USB_SERIAL
+ bool "Enable USB Serial Converter Support"
+ default y
+ depends on DRIVERS_USB_DEVICE_CLASS_DRIVERS
+ help
+ Say Y here if you want to connect USB serial devices to your system's USB port.
+
+config DRIVERS_USB_ETHERNET
+ bool "Enable USB Ethernet Support"
+ depends on NET_LWIP_SACK && DRIVERS_USB_DEVICE_CLASS_DRIVERS
+ help
+ Say Y here if you want to connect USB ethernet devices to your system's USB port.
+
+config DRIVERS_USB_WIRELESS
+ bool "Enable USB Wireless Device Support"
+ depends on NET_LWIP_SACK && DRIVERS_USB_DEVICE_CLASS_DRIVERS
+ help
+ Say Y here if you want to connect usb-wifi devices to your system's USB port.
+config DRIVERS_USB_HID_CLASS
+ bool "Enable USB HID Device Support"
+ depends on DRIVERS_USB_DEVICE_CLASS_DRIVERS && FS_VFS
+ help
+ Say Y here if you want to connect hid devices to your system's USB port.
+
+endmenu
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/bsd/dev/usb/Makefile b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/bsd/dev/usb/Makefile
new file mode 100644
index 00000000..f01ea12d
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/bsd/dev/usb/Makefile
@@ -0,0 +1,138 @@
+# 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 $(LITEOSTOPDIR)/config.mk
+include $(LITEOSTOPDIR)/../../drivers/adapter/khdf/liteos/lite.mk
+
+MODULE_NAME := usb_base
+
+CONTROLLER_HOST_SRC = controller
+CORE_SRC = .
+IMPLEMENTATION_SRC = implementation
+Net_SRC = net
+QUIRK_SRC = quirk
+SERIAL_SRC = serial
+STORAGE_SRC = storage
+INPUT_SRC = input
+LOCAL_SRCS := $(CORE_SRC)/usb_debug.c \
+ $(IMPLEMENTATION_SRC)/bsd_busspace.c \
+ $(IMPLEMENTATION_SRC)/usb_busdma_loader.c \
+ $(IMPLEMENTATION_SRC)/bsd_kernel.c \
+ $(IMPLEMENTATION_SRC)/usb_init.c \
+ $(IMPLEMENTATION_SRC)/usb_version.c \
+ $(IMPLEMENTATION_SRC)/usb_btree.c
+
+ifeq ($(LOSCFG_DRIVERS_USB), y)
+LOCAL_SRCS += $(CORE_SRC)/usb_dynamic.c \
+ $(CORE_SRC)/usb_parse.c \
+ $(CORE_SRC)/usb_error.c \
+ $(CORE_SRC)/usb_handle_request.c \
+ $(CORE_SRC)/usb_util.c \
+ $(CORE_SRC)/usb_lookup.c \
+ $(CONTROLLER_HOST_SRC)/usb_controller.c \
+ $(QUIRK_SRC)/usb_quirk.c \
+ $(CORE_SRC)/usb_device.c \
+ $(CORE_SRC)/usb_process.c \
+ $(CORE_SRC)/usb_hub.c \
+ $(CORE_SRC)/usb_request.c \
+ $(CORE_SRC)/usb_transfer.c \
+ $(CORE_SRC)/usb_dev.c \
+ $(CORE_SRC)/usb_mbuf.c \
+ $(CORE_SRC)/usb_generic.c \
+ $(CORE_SRC)/usb_if.c
+endif
+
+ifeq ($(LOSCFG_DRIVERS_USB_4G_MODEM), y)
+LOCAL_SRCS += $(Net_SRC)/if_cdce.c
+endif
+
+ifeq ($(LOSCFG_DRIVERS_USB_ETHERNET), y)
+LOCAL_SRCS += $(Net_SRC)/if_axe.c \
+ $(Net_SRC)/if_axge.c
+endif
+
+ifeq ($(LOSCFG_DRIVERS_USB_RNDIS_HOST), y)
+LOCAL_SRCS += $(Net_SRC)/if_urndis.c
+endif
+
+ifeq ($(LOSCFG_DRIVERS_USB_4G_MODEM), y)
+LOCAL_SRCS += $(Net_SRC)/usb_eth_drv.c \
+ $(Net_SRC)/usb_ethernet.c
+else ifeq ($(LOSCFG_DRIVERS_USB_ETHERNET), y)
+LOCAL_SRCS += $(Net_SRC)/usb_eth_drv.c \
+ $(Net_SRC)/usb_ethernet.c
+else ifeq ($(LOSCFG_DRIVERS_USB_RNDIS_HOST), y)
+LOCAL_SRCS += $(Net_SRC)/usb_eth_drv.c\
+ $(Net_SRC)/usb_ethernet.c
+endif
+
+ifeq ($(LOSCFG_DRIVERS_USB_4G_MODEM), y)
+LOCAL_SRCS += $(SERIAL_SRC)/usb_serial.c \
+ $(SERIAL_SRC)/u3g.c
+else ifeq ($(LOSCFG_DRIVERS_USB_SERIAL), y)
+LOCAL_SRCS += $(SERIAL_SRC)/usb_serial.c \
+ $(SERIAL_SRC)/u3g.c
+endif
+
+ifeq ($(LOSCFG_DRIVERS_USB_HOST_EHCI), y)
+LOCAL_SRCS += $(CONTROLLER_HOST_SRC)/ehci_pci.c \
+ $(CONTROLLER_HOST_SRC)/ehci.c
+endif
+
+ifeq ($(LOSCFG_DRIVERS_USB_HOST_XHCI), y)
+LOCAL_SRCS += $(CONTROLLER_HOST_SRC)/xhci.c \
+ $(CONTROLLER_HOST_SRC)/xhci_pci.c
+else ifeq ($(LOSCFG_DRIVERS_USB_HOST_XHCI_FOR_PORT2), y)
+LOCAL_SRCS += $(CONTROLLER_HOST_SRC)/xhci.c \
+ $(CONTROLLER_HOST_SRC)/xhci_pci.c
+endif
+
+ifeq ($(LOSCFG_DRIVERS_USB_WIRELESS), y)
+LOCAL_SRCS += $(CORE_SRC)/linux_usb.c
+endif
+
+ifeq ($(LOSCFG_DRIVERS_USB_MASS_STORAGE), y)
+LOCAL_SRCS += $(STORAGE_SRC)/umass.c
+endif
+
+ifeq ($(LOSCFG_DRIVERS_USB_HID_CLASS)_$(LOSCFG_DRIVERS_HDF_INPUT), y_y)
+LOCAL_FLAGS += -I$(LITEOSTOPDIR)/../../drivers/framework/model/input/driver \
+ -I$(LITEOSTOPDIR)/../../drivers/framework/include/core \
+ -I$(LITEOSTOPDIR)/../../drivers/framework/core/common/include/host \
+ -I$(LITEOSTOPDIR)/../../drivers/framework/utils \
+ -I$(LITEOSTOPDIR)/../../drivers/framework/osal \
+ -I$(LITEOSTOPDIR)/../../drivers/framework/ability/sbuf/include \
+ -I$(LITEOSTOPDIR)/../../drivers/framework/include/osal \
+ -I$(LITEOSTOPDIR)/../../third_party/FreeBSD/sys/dev/evdev
+
+LOCAL_SRCS += $(INPUT_SRC)/uhid.c \
+ $(CORE_SRC)/usb_hid.c
+endif
+
+include $(HDF_DRIVER)
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/build.sh b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/build.sh
new file mode 100644
index 00000000..52c19e53
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/build.sh
@@ -0,0 +1,69 @@
+#!/bin/bash
+#
+# 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.
+set -e
+
+board_name=${1}
+ohos_build_compiler=${2}
+root_build_dir=${3}
+ohos_build_type=${4}
+tee_enable=${5}
+device_company=${6}
+product_path=${7}
+outdir=${8}
+ohos_version=${9}
+sysroot_path=${10}
+arch_cflags=${11}
+device_path=${12}
+compile_prefix=${13}
+liteos_config_file=${14}
+
+echo "sh param:" "$@"
+
+if [ "x" != "x${sysroot_path}" ]; then
+ export SYSROOT_PATH=${sysroot_path}
+fi
+
+if [ "x" != "x${arch_cflags}" ]; then
+ export ARCH_CFLAGS="${arch_cflags}"
+fi
+
+export PRODUCT_PATH="${product_path}"
+export DEVICE_PATH="${device_path}"
+
+export OUTDIR="${outdir}"
+export KCONFIG_CONFIG="${liteos_config_file}"
+export LITEOS_MENUCONFIG_H="${outdir}/config.h"
+export LITEOS_CONFIG_FILE="${outdir}/.config"
+export LITEOS_COMPILER_PATH="${compile_prefix%/*}/"
+export CROSS_COMPILE="${compile_prefix##*/}"
+
+mkdir -p "${outdir}"
+make -j all VERSION="${ohos_version}"
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/bundle.json b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/bundle.json
new file mode 100644
index 00000000..1a70a918
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/bundle.json
@@ -0,0 +1,65 @@
+{
+ "name": "@ohos/liteos_a",
+ "version": "3.1.0",
+ "description": "liteos-a kernel",
+ "homePage": "https://gitee.com/openharmony",
+ "license": "BSD 3-clause",
+ "repository": "https://gitee.com/openharmony/kernel_liteos_a",
+ "domain": "os",
+ "language": "",
+ "publishAs": "code-segment",
+ "private": false,
+ "scripts": {},
+ "tags": [
+ "kernel"
+ ],
+ "keywords": [
+ "kernel",
+ "liteos-a"
+ ],
+ "envs": [],
+ "dirs": [],
+ "author": {},
+ "contributors": [],
+ "segment": {
+ "destPath": "kernel/liteos_a"
+ },
+ "component": {
+ "name": "liteos_a",
+ "subsystem": "kernel",
+ "syscap": [
+ "SystemCapability.Kernel.liteos-a"
+ ],
+ "features": [],
+ "adated_system_type": [
+ "small"
+ ],
+ "rom": "1.5MB",
+ "ram": "2MB",
+ "deps": {
+ "components": [
+ ],
+ "third_party": [
+ "bounds_checking_function",
+ "toybox",
+ "NuttX",
+ "FatFs",
+ "mksh",
+ "musl",
+ "mbedtls",
+ "FreeBSD",
+ "zlib",
+ "lwip",
+ "optimized-routines",
+ "googletest"
+ ]
+ },
+ "build": {
+ "sub_component": [
+ "//kernel/liteos_a:liteos_a"
+ ],
+ "inner_kits": [],
+ "test": []
+ }
+ }
+}
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/BUILD.gn b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/BUILD.gn
new file mode 100644
index 00000000..300dcf3e
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/BUILD.gn
@@ -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.
+
+import("//kernel/liteos_a/liteos.gni")
+
+group("compat") {
+ deps = [ "posix" ]
+}
+
+config("public") {
+ configs = [ "posix:public" ]
+}
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/BUILD.gn b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/BUILD.gn
new file mode 100644
index 00000000..31210665
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/BUILD.gn
@@ -0,0 +1,59 @@
+# 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("//kernel/liteos_a/liteos.gni")
+
+module_switch = defined(LOSCFG_COMPAT_POSIX)
+module_name = get_path_info(rebase_path("."), "name")
+kernel_module(module_name) {
+ sources = [
+ "src/errno.c",
+ "src/malloc.c",
+ "src/map_error.c",
+ "src/misc.c",
+ "src/mqueue.c",
+ "src/posix_memalign.c",
+ "src/pthread.c",
+ "src/pthread_attr.c",
+ "src/pthread_cond.c",
+ "src/pthread_mutex.c",
+ "src/sched.c",
+ "src/semaphore.c",
+ "src/socket.c",
+ "src/stdio.c",
+ "src/stdlib.c",
+ "src/time.c",
+ ]
+
+ public_configs = [ ":public" ]
+}
+
+config("public") {
+ include_dirs = [ "include" ]
+}
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/Kconfig b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/Kconfig
new file mode 100644
index 00000000..1d0c733e
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/Kconfig
@@ -0,0 +1,6 @@
+config COMPAT_POSIX
+ bool "Enable Posix"
+ default y
+
+ help
+ Answer Y to enable LiteOS support posix interface.
\ No newline at end of file
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/Makefile b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/Makefile
new file mode 100644
index 00000000..cfeb6a3a
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/Makefile
@@ -0,0 +1,40 @@
+# 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 $(LITEOSTOPDIR)/config.mk
+
+MODULE_NAME := $(notdir $(shell pwd))
+
+LOCAL_SRCS := $(wildcard src/*.c)
+
+LOCAL_INCLUDE := -I $(LITEOSTOPDIR)/compat/posix/src
+
+LOCAL_FLAGS := $(LOCAL_INCLUDE)
+
+include $(MODULE)
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/include/mqueue.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/include/mqueue.h
new file mode 100644
index 00000000..c15554a2
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/include/mqueue.h
@@ -0,0 +1,434 @@
+/*
+ * 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.
+ */
+
+/**
+ * @defgroup mqueue Message queue
+ * @ingroup posix
+ */
+
+#ifndef _HWLITEOS_POSIX_MQUEUE_H
+#define _HWLITEOS_POSIX_MQUEUE_H
+
+/* INCLUDES */
+#include "stdarg.h"
+#include "stdlib.h"
+#include "limits.h"
+#include "los_typedef.h"
+#include "time.h"
+#include
+#include
+#include
+
+#include "los_queue_pri.h"
+
+#ifdef __cplusplus
+#if __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+/**
+ * @ingroup mqueue
+ * Maximum number of messages in a message queue
+ */
+#define MQ_MAX_MSG_NUM 16
+
+/**
+ * @ingroup mqueue
+ * Maximum size of a single message in a message queue
+ */
+#define MQ_MAX_MSG_LEN 64
+
+
+/* CONSTANTS */
+
+#define MQ_USE_MAGIC 0x89abcdef
+/* not support prio */
+#define MQ_PRIO_MAX 1
+
+typedef union send_receive_t {
+ unsigned oth : 3;
+ unsigned grp : 6;
+ unsigned usr : 9;
+ short data;
+} mode_s;
+
+struct mqnotify {
+ pid_t pid;
+ struct sigevent notify;
+};
+
+/* TYPE DEFINITIONS */
+struct mqarray {
+ UINT32 mq_id : 31;
+ UINT32 unlinkflag : 1;
+ char *mq_name;
+ UINT32 unlink_ref;
+ mode_s mode_data; /* mode data of mqueue */
+ uid_t euid; /* euid of mqueue */
+ gid_t egid; /* egid of mqueue */
+ struct mqnotify mq_notify;
+ LosQueueCB *mqcb;
+ struct mqpersonal *mq_personal;
+};
+
+struct mqpersonal {
+ struct mqarray *mq_posixdes;
+ struct mqpersonal *mq_next;
+ int mq_flags;
+ int mq_mode; /* Mode of mqueue */
+ UINT32 mq_status;
+ UINT32 mq_refcount;
+};
+
+/**
+ * @ingroup mqueue
+ * Message queue attribute structure
+ */
+struct mq_attr {
+ long mq_flags; /**< Message queue flags */
+ long mq_maxmsg; /**< Maximum number of messages */
+ long mq_msgsize; /**< Maximum size of a message */
+ long mq_curmsgs; /**< Number of messages in the current message queue */
+};
+
+/**
+ * @ingroup mqueue
+ * Handle type of a message queue
+ */
+typedef UINTPTR mqd_t;
+
+/**
+ * @ingroup mqueue
+ *
+ * @par Description:
+ * This API is used to open an existed message queue that has a specified name or create a new message queue.
+ * @attention
+ *
+ *
A message queue does not restrict the read and write permissions.
+ *
The length of mqueue name must less than 256.
+ *
This operation and closed mqueue scheduling must be used in coordination to release the resource.
+ *
The parameter "mode" is not supported.
+ *
The "mq_curmsgs" member of the mq_attr structure is not supported.
+ *
+ *
+ * @param mqName [IN] Message queue name.
+ * @param openFlag [IN] Permission attributes of the message queue. The value range is
+ * [O_RDONLY, O_WRONLY, O_RDWR, O_CREAT, O_EXCL, O_NONBLOCK].
+ * @param mode [IN] Message queue mode (variadic argument). When oflag is O_CREAT, it requires
+ * two additional arguments: mode, which shall be of type mode_t, and attr,
+ * which shall be a pointer to an mq_attr structure.
+ * @param attr [IN] Message queue attribute (variadic argument).
+ *
+ * @retval mqd_t The message queue is successfully opened or created.
+ * @retval (mqd_t)-1 The message queue fails to be opened or created, with any of the following error codes in errno.
+ *
+ *
+ * @par Errors
+ *
+ *
ENOENT: O_CREAT flag is not set for oflag, and the message queue specified by name does not exist.
+ *
EEXIST: Both O_CREAT and O_EXCL are set for oflag, but the message queue
+ * specified by name already exists.
+ *
EINVAL: invalid parameter.
+ *
ENFILE: The number of opened message queues exceeds the maximum limit.
+ *
ENOSPC: insufficient memory.
+ *
ENAMETOOLONG: The message queue name specified by name is too long.
+ *
+ *
+ * @par Dependency:
+ *
mqueue.h
+ * @see mq_close
+ */
+extern mqd_t mq_open(const char *mqName, int openFlag, ...);
+
+/**
+ * @ingroup mqueue
+ *
+ * @par Description:
+ * This API is used to close a message queue that has a specified descriptor.
+ * @attention
+ *
+ *
If the message queue is empty, it will be reclaimed, which is similar to when mq_unlink is called.
+ *
+ *
+ * @param personal [IN] Message queue descriptor.
+ *
+ * @retval 0 The message queue is successfully closed.
+ * @retval -1 The message queue fails to be closed, with either of the following error codes in errno.
+ *
+ * @par Errors
+ *
+ *
EBADF: Invalid message queue descriptor.
+ *
EAGAIN: Failed to delete the message queue.
+ *
EFAULT: Failed to free the message queue.
+ *
EINVAL: Invalid parameter.
+ *
+ *
+ * @par Dependency:
+ *
mqueue.h
+ * @see mq_open
+ */
+extern int mq_close(mqd_t personal);
+
+/**
+ * @ingroup mqueue
+ *
+ * @par Description:
+ * This API is used to remove a message queue that has a specified name.
+ * @attention
+ *
+ *
If the message queue is empty, it will be reclaimed, which is similar to when mq_close is called.
+ *
The length of mqueue name must less than 256.
+ *
+ *
+ * @param mqName [IN] Message queue name.
+ *
+ * @retval 0 The message queue is successfully removed.
+ * @retval -1 The message queue fails to be removed, with any of the following error codes in errno.
+ *
+ * @par Errors
+ *
+ *
ENOENT: The message queue specified by name does not exist.
+ *
EAGAIN: Failed to delete the message queue.
+ *
EBUSY: The message queue to be removed is being used.
+ *
EINVAL: Invalid parameter.
+ *
ENAMETOOLONG: The name of mqueue is too long.
+ *
+ *
+ * @par Dependency:
+ *
mqueue.h
+ * @see mq_close
+ */
+extern int mq_unlink(const char *mqName);
+
+/**
+ * @ingroup mqueue
+ *
+ * @par Description:
+ * This API is used to put a message with specified message content and length into
+ * a message queue that has a specified descriptor.
+ * @attention
+ *
+ *
Priority-based message processing is not supported.
+ *
The msg_len should be same to the length of string which msg_ptr point to.
+ *
+ *
+ * @param personal [IN] Message queue descriptor.
+ * @param msg [IN] Pointer to the message content to be sent.
+ * @param msgLen [IN] Length of the message to be sent.
+ * @param msgPrio [IN] Priority of the message to be sent (the value of this parameter must
+ * be 0 because priority-based message sending is not supported. If the
+ * value is not 0, this API will cease to work.)
+ *
+ * @retval 0 The message is successfully sent.
+ * @retval -1 The message fails to be sent, with any of the following error codes in errno.
+ *
+ * @par Errors
+ *
+ *
EINTR: An interrupt is in progress while the message is being sent.
+ *
EBADF: The message queue is invalid or not writable.
+ *
EAGAIN: The message queue is full.
+ *
EINVAL: Invalid parameter.
+ *
ENOSPC: Insufficient memory.
+ *
EMSGSIZE: The message to be sent is too long.
+ *
EOPNOTSUPP: The operation is not supported.
+ *
ETIMEDOUT: The operation times out.
+ *
+ *
+ * @par Dependency:
+ *
mqueue.h
+ * @see mq_receive
+ */
+extern int mq_send(mqd_t personal, const char *msg, size_t msgLen, unsigned int msgPrio);
+
+/**
+ * @ingroup mqueue
+ *
+ * @par Description:
+ * This API is used to remove the oldest message from the message queue that has a specified descriptor,
+ * and puts it in the buffer pointed to by msg_ptr.
+ * @attention
+ *
+ *
Priority-based message processing is not supported.
+ *
The msg_len should be same to the length of string which msg_ptr point to.
+ *
+ *
+ * @param personal [IN] Message queue descriptor.
+ * @param msg [IN] Pointer to the message content to be received.
+ * @param msgLen [IN] Length of the message to be received.
+ * @param msgPrio [OUT] Priority of the message to be received
+ * because priority-based message processing is not supported, this parameter is useless).
+ *
+ * @retval 0 The message is successfully received.
+ * @retval -1 The message fails to be received, with any of the following error codes in the errno.
+ *
+ * @par Errors
+ *
+ *
EINTR: An interrupt is in progress while the message is being received.
+ *
EBADF: The message queue is invalid or not readable.
+ *
EAGAIN: The message queue is empty.
+ *
EINVAL: invalid parameter.
+ *
EMSGSIZE: The message to be received is too long.
+ *
ETIMEDOUT: The operation times out.
+ *
+ *
+ * @par Dependency:
+ *
mqueue.h
+ * @see mq_send
+ */
+extern ssize_t mq_receive(mqd_t personal, char *msg, size_t msgLen, unsigned int *msgPrio);
+
+/**
+ * @ingroup mqueue
+ *
+ * @par Description:
+ * This API is used to obtain or modify attributes of the message queue that has a specified descriptor.
+ * @attention
+ *
+ *
The mq_maxmsg, mq_msgsize, and mq_curmsgs attributes are not modified
+ * in the message queue attribute setting.
+ *
+ *
+ * @param personal [IN] Message queue descriptor.
+ * @param mqSetAttr [IN] New attribute of the message queue.
+ * @param MqOldAttr [OUT] Old attribute of the message queue.
+ *
+ * @retval 0 The message queue attributes are successfully set or get.
+ * @retval -1 The message queue attributes fail to be set or get,
+ * with either of the following error codes in the errno.
+ *
+ * @par Errors
+ *
+ *
EBADF: Invalid message queue.
+ *
EINVAL: Invalid parameter.
+ *
+ *
+ * @par Dependency:
+ *
mqueue.h
+ * @see sys_mq_getsetattr
+ */
+extern int mq_getsetattr(mqd_t personal, const struct mq_attr *mqSetAttr, struct mq_attr *MqOldAttr);
+
+/**
+ * @ingroup mqueue
+ *
+ * @par Description:
+ * This API is used to put a message with specified message content and length into
+ * a message queue that has a descriptor at a scheduled time.
+ * @attention
+ *
+ *
Priority-based message processing is not supported.
+ *
The expiry time must be later than the current time.
+ *
The wait time is a relative time.
+ *
The msg_len should be same to the length of string which msg_ptr point to.
+ *
+ *
+ * @param mqdes [IN] Message queue descriptor.
+ * @param msg [IN] Pointer to the message content to be sent.
+ * @param msgLen [IN] Length of the message to be sent.
+ * @param msgPrio [IN] Priority of the message to be sent (the value of this parameter must be 0
+ * because priority-based message processing is not supported).
+ * @param absTimeout [IN] Scheduled time at which the message will be sent. If the value is 0,
+ * the message is an instant message.
+ *
+ * @retval 0 The message is successfully sent.
+ * @retval -1 The message fails to be sent, with any of the following error codes in errno.
+ *
+ * @par Errors
+ *
+ *
EINTR: An interrupt is in progress while the message is being sent.
+ *
EBADF: The message queue is invalid or not writable.
+ *
EAGAIN: The message queue is full.
+ *
EINVAL: Invalid parameter.
+ *
EMSGSIZE: The message to be sent is too long.
+ *
EOPNOTSUPP: The operation is not supported.
+ *
ETIMEDOUT: The operation times out.
+ *
+ *
+ * @par Dependency:
+ *
mqueue.h
+ * @see mq_receive
+ */
+extern int mq_timedsend(mqd_t personal, const char *msg, size_t msgLen,
+ unsigned int msgPrio, const struct timespec *absTimeout);
+
+/**
+ * @ingroup mqueue
+ *
+ * @par Description:
+ * This API is used to obtain a message with specified message content and length from
+ * a message queue message that has a specified descriptor.
+ * @attention
+ *
+ *
Priority-based message processing is not supported.
+ *
The expiry time must be later than the current time.
+ *
The wait time is a relative time.
+ *
The msg_len should be same to the length of string which msg_ptr point to.
+ *
+ *
+ * @param personal [IN] Message queue descriptor.
+ * @param msg [IN] Pointer to the message content to be received.
+ * @param msgLen [IN] Length of the message to be received.
+ * @param msgPrio [OUT] Priority of the message to be received (because priority-based message
+ * processing is not supported, this parameter is useless ).
+ * @param absTimeout [IN] Scheduled time at which the messagewill be received. If the value is 0,
+ * the message is an instant message.
+ *
+ * @retval 0 The message is successfully received.
+ * @retval -1 The message fails to be received, with any of the following error codes in errno.
+ *
+ * @par Errors
+ *
+ *
EINTR: An interrupt is in progress while the message is being received.
+ *
EBADF: The message queue is invalid or not readable.
+ *
EAGAIN: The message queue is empty.
+ *
EINVAL: invalid parameter.
+ *
EMSGSIZE: The message to be received is too long.
+ *
ETIMEDOUT: The operation times out.
+ *
+ *
+ * @par Dependency:
+ *
mqueue.h
+ * @see mq_send
+ */
+extern ssize_t mq_timedreceive(mqd_t personal, char *msg, size_t msgLen,
+ unsigned int *msgPrio, const struct timespec *absTimeout);
+
+extern void MqueueRefer(int sysFd);
+extern int OsMqNotify(mqd_t personal, const struct sigevent *sigev);
+
+#ifdef __cplusplus
+#if __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+#endif
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/include/time_posix.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/include/time_posix.h
new file mode 100644
index 00000000..3f19bde8
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/include/time_posix.h
@@ -0,0 +1,96 @@
+/*
+ * 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 _TIME_PRI_H
+#define _TIME_PRI_H
+
+#include "time.h"
+#include "errno.h"
+#include "los_sys_pri.h"
+
+#ifdef __cplusplus
+#if __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+struct ksigevent {
+ union sigval sigev_value;
+ int sigev_signo;
+ int sigev_notify;
+ int sigev_tid;
+};
+
+/* 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 OsTimerCreate(clockid_t, struct ksigevent *__restrict, timer_t *__restrict);
+void OsAdjTime(void);
+
+#ifdef __cplusplus
+#if __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+#endif /* _TIME_PRI_H */
\ No newline at end of file
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/src/errno.c b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/src/errno.c
new file mode 100644
index 00000000..ca487216
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/src/errno.c
@@ -0,0 +1,51 @@
+/*
+ * 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 "errno.h"
+#include "los_errno.h"
+#include "los_task_pri.h"
+
+/* the specific errno get or set in interrupt service routine */
+static int errno_isr;
+
+int *__errno_location(void)
+{
+ LosTaskCB *runTask = NULL;
+
+ if (OS_INT_INACTIVE) {
+ runTask = OsCurrTaskGet();
+ return &runTask->errorNo;
+ } else {
+ return &errno_isr;
+ }
+}
+
+int *__errno(void) __attribute__((__weak__, __alias__("__errno_location")));
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/src/malloc.c b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/src/malloc.c
new file mode 100644
index 00000000..50e4f8dc
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/src/malloc.c
@@ -0,0 +1,145 @@
+/*
+ * 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 "stdlib.h"
+#include "string.h"
+#include "los_vm_map.h"
+
+/*
+ * Allocates the requested memory and returns a pointer to it. The requested
+ * size is nitems each size bytes long (total memory requested is nitems*size).
+ * The space is initialized to all zero bits.
+ */
+
+void *calloc(size_t nitems, size_t size)
+{
+ size_t real_size;
+ void *ptr = NULL;
+
+ if (nitems == 0 || size == 0) {
+ return NULL;
+ }
+
+ real_size = (size_t)(nitems * size);
+ ptr = LOS_KernelMalloc((UINT32) real_size);
+ if (ptr != NULL) {
+ (void) memset_s((void *) ptr, real_size, 0, real_size);
+ }
+ return ptr;
+}
+
+/*
+ * Deallocates the memory previously allocated by a call to calloc, malloc, or
+ * realloc. The argument ptr points to the space that was previously allocated.
+ * If ptr points to a memory block that was not allocated with calloc, malloc,
+ * or realloc, or is a space that has been deallocated, then the result is undefined.
+ */
+
+void free(void *ptr)
+{
+ if (ptr == NULL) {
+ return;
+ }
+
+ LOS_KernelFree(ptr);
+}
+
+/*
+ * Allocates the requested memory and returns a pointer to it. The requested
+ * size is size bytes. The value of the space is indeterminate.
+ */
+
+void *malloc(size_t size)
+{
+ if (size == 0) {
+ return NULL;
+ }
+
+ return LOS_KernelMalloc((UINT32) size);
+}
+
+void *zalloc(size_t size)
+{
+ void *ptr = NULL;
+
+ if (size == 0) {
+ return NULL;
+ }
+
+ ptr = LOS_KernelMalloc((UINT32) size);
+ if (ptr != NULL) {
+ (void) memset_s(ptr, size, 0, size);
+ }
+ return ptr;
+}
+
+/*
+ * allocates a block of size bytes whose address is a multiple of boundary.
+ * The boundary must be a power of two!
+ */
+
+void *memalign(size_t boundary, size_t size)
+{
+ if (size == 0) {
+ return NULL;
+ }
+
+ return LOS_KernelMallocAlign((UINT32) size, (UINT32) boundary);
+}
+
+/*
+ * Attempts to resize the memory block pointed to by ptr that was previously
+ * allocated with a call to malloc or calloc. The contents pointed to by ptr are
+ * unchanged. If the value of size is greater than the previous size of the
+ * block, then the additional bytes have an undeterminate value. If the value
+ * of size is less than the previous size of the block, then the difference of
+ * bytes at the end of the block are freed. If ptr is null, then it behaves like
+ * malloc. If ptr points to a memory block that was not allocated with calloc
+ * or malloc, or is a space that has been deallocated, then the result is
+ * undefined. If the new space cannot be allocated, then the contents pointed
+ * to by ptr are unchanged. If size is zero, then the memory block is completely
+ * freed.
+ */
+
+void *realloc(void *ptr, size_t size)
+{
+ if (ptr == NULL) {
+ ptr = malloc(size);
+ return ptr;
+ }
+
+ if (size == 0) {
+ free(ptr);
+ return NULL;
+ }
+
+ return LOS_KernelRealloc(ptr, (UINT32) size);
+}
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/src/map_error.c b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/src/map_error.c
new file mode 100644
index 00000000..c25d1133
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/src/map_error.c
@@ -0,0 +1,112 @@
+/*
+ * 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_mux.h"
+#include "los_queue.h"
+#include "los_sem.h"
+#include "los_task.h"
+
+
+int map_errno(UINT32 err)
+{
+ if (err == LOS_OK) {
+ return ENOERR;
+ }
+ switch (err) {
+ case LOS_ERRNO_QUEUE_INVALID:
+ case LOS_ERRNO_QUEUE_WRITE_PTR_NULL:
+ case LOS_ERRNO_QUEUE_WRITESIZE_ISZERO:
+ case LOS_ERRNO_QUEUE_SIZE_TOO_BIG:
+ case LOS_ERRNO_QUEUE_CREAT_PTR_NULL:
+ case LOS_ERRNO_QUEUE_PARA_ISZERO:
+ case LOS_ERRNO_QUEUE_WRITE_SIZE_TOO_BIG:
+ errno = EINVAL;
+ break;
+ case LOS_ERRNO_QUEUE_ISFULL:
+ case LOS_ERRNO_QUEUE_ISEMPTY:
+ errno = EAGAIN;
+ break;
+ case LOS_ERRNO_QUEUE_CREATE_NO_MEMORY:
+ errno = ENOSPC;
+ break;
+ case LOS_ERRNO_QUEUE_TIMEOUT:
+ errno = ETIMEDOUT;
+ break;
+ case LOS_ERRNO_QUEUE_CB_UNAVAILABLE:
+ errno = ENFILE;
+ break;
+ case LOS_ERRNO_QUEUE_READ_IN_INTERRUPT:
+ case LOS_ERRNO_QUEUE_WRITE_IN_INTERRUPT:
+ errno = EINTR;
+ break;
+ case LOS_ERRNO_TSK_ID_INVALID:
+ case LOS_ERRNO_TSK_PTR_NULL:
+ case LOS_ERRNO_TSK_NAME_EMPTY:
+ case LOS_ERRNO_TSK_ENTRY_NULL:
+ case LOS_ERRNO_TSK_PRIOR_ERROR:
+ case LOS_ERRNO_TSK_STKSZ_TOO_LARGE:
+ case LOS_ERRNO_TSK_STKSZ_TOO_SMALL:
+ case LOS_ERRNO_TSK_NOT_CREATED:
+ case LOS_ERRNO_TSK_CPU_AFFINITY_MASK_ERR:
+ case OS_ERROR:
+ case LOS_ERRNO_SEM_INVALID:
+ case LOS_ERRNO_SEM_UNAVAILABLE:
+ errno = EINVAL;
+ break;
+ case LOS_ERRNO_TSK_TCB_UNAVAILABLE:
+ case LOS_ERRNO_TSK_MP_SYNC_RESOURCE:
+ case LOS_ERRNO_SEM_ALL_BUSY:
+ errno = ENOSPC;
+ break;
+ case LOS_ERRNO_TSK_NO_MEMORY:
+ case LOS_ERRNO_SEM_OVERFLOW:
+ errno = ENOMEM;
+ break;
+ case LOS_ERRNO_SEM_PENDED:
+ case LOS_ERRNO_EVENT_SHOULD_NOT_DESTROY:
+ errno = EBUSY;
+ break;
+ case LOS_ERRNO_SEM_PEND_IN_LOCK:
+ errno = EPERM;
+ break;
+ case LOS_ERRNO_SEM_PEND_INTERR:
+ errno = EINTR;
+ break;
+ case LOS_ERRNO_SEM_TIMEOUT:
+ errno = ETIMEDOUT;
+ break;
+ default:
+ errno = EINVAL;
+ break;
+ }
+ return errno;
+}
+
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/src/map_error.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/src/map_error.h
new file mode 100644
index 00000000..935b2d5e
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/src/map_error.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 _HWLITEOS_POSIX_MAP_ERROR_H
+#define _HWLITEOS_POSIX_MAP_ERROR_H
+
+#ifdef __cplusplus
+#if __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+int map_errno(unsigned int err);
+
+#ifdef __cplusplus
+#if __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+#endif
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/src/misc.c b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/src/misc.c
new file mode 100644
index 00000000..d3ae7e4d
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/src/misc.c
@@ -0,0 +1,230 @@
+/*
+ * 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 "sys/types.h"
+#include "sys/resource.h"
+#include "unistd.h"
+#include "stdio.h"
+#include "pthread.h"
+#include "sys/utsname.h"
+#include "mqueue.h"
+#include "semaphore.h"
+#include "los_process_pri.h"
+#include "los_hw.h"
+
+/*
+ * Supply some suitable values for constants that may not be present
+ * in all configurations.
+ */
+#define SC_ENABLE 1
+#define SC_DISABLE (-1)
+
+#define CONF_CASE_RETURN(name, val) \
+ case (name): \
+ return (val)
+
+int uname(struct utsname *name)
+{
+ INT32 ret;
+ const char *cpuInfo = NULL;
+
+ if (name == NULL) {
+ return -EFAULT;
+ }
+ (VOID)strcpy_s(name->sysname, sizeof(name->sysname), KERNEL_NAME);
+ (VOID)strcpy_s(name->nodename, sizeof(name->nodename), "hisilicon");
+ ret = sprintf_s(name->version, sizeof(name->version), "%s %u.%u.%u.%u %s %s",
+ KERNEL_NAME, KERNEL_MAJOR, KERNEL_MINOR, KERNEL_PATCH, KERNEL_ITRE, __DATE__, __TIME__);
+ if (ret < 0) {
+ return -EIO;
+ }
+
+ cpuInfo = LOS_CpuInfo();
+ (VOID)strcpy_s(name->machine, sizeof(name->machine), cpuInfo);
+ ret = sprintf_s(name->release, sizeof(name->release), "%u.%u.%u.%u",
+ KERNEL_MAJOR, KERNEL_MINOR, KERNEL_PATCH, KERNEL_ITRE);
+ if (ret < 0) {
+ return -EIO;
+ }
+
+ name->domainname[0] = '\0';
+ return 0;
+}
+
+long sysconf(int name)
+{
+ switch (name) {
+ CONF_CASE_RETURN(_SC_AIO_LISTIO_MAX, SC_DISABLE);
+ CONF_CASE_RETURN(_SC_AIO_MAX, SC_DISABLE);
+ CONF_CASE_RETURN(_SC_AIO_PRIO_DELTA_MAX, SC_DISABLE);
+ CONF_CASE_RETURN(_SC_ARG_MAX, ARG_MAX);
+ CONF_CASE_RETURN(_SC_ASYNCHRONOUS_IO, SC_DISABLE);
+ CONF_CASE_RETURN(_SC_CHILD_MAX, CHILD_MAX);
+ CONF_CASE_RETURN(_SC_CLK_TCK, SYS_CLK_TCK);
+ CONF_CASE_RETURN(_SC_DELAYTIMER_MAX, DELAYTIMER_MAX);
+ CONF_CASE_RETURN(_SC_FSYNC, SC_DISABLE);
+ CONF_CASE_RETURN(_SC_GETGR_R_SIZE_MAX, GETGR_R_SIZE_MAX);
+ CONF_CASE_RETURN(_SC_GETPW_R_SIZE_MAX, GETPW_R_SIZE_MAX);
+ CONF_CASE_RETURN(_SC_JOB_CONTROL, SC_DISABLE);
+ CONF_CASE_RETURN(_SC_LOGIN_NAME_MAX, LOGIN_NAME_MAX);
+ CONF_CASE_RETURN(_SC_MAPPED_FILES, SC_DISABLE);
+ CONF_CASE_RETURN(_SC_MEMLOCK, SC_DISABLE);
+ CONF_CASE_RETURN(_SC_MEMLOCK_RANGE, SC_DISABLE);
+ CONF_CASE_RETURN(_SC_MEMORY_PROTECTION, SC_DISABLE);
+ CONF_CASE_RETURN(_SC_MESSAGE_PASSING, SC_DISABLE);
+#ifdef LOSCFG_BASE_IPC_QUEUE
+ CONF_CASE_RETURN(_SC_MQ_OPEN_MAX, MQ_OPEN_MAX);
+ CONF_CASE_RETURN(_SC_MQ_PRIO_MAX, MQ_PRIO_MAX);
+#endif
+ CONF_CASE_RETURN(_SC_NGROUPS_MAX, NGROUPS_MAX);
+ CONF_CASE_RETURN(_SC_OPEN_MAX, OPEN_MAX);
+ CONF_CASE_RETURN(_SC_PAGESIZE, 0x1000);
+ CONF_CASE_RETURN(_SC_PRIORITIZED_IO, SC_DISABLE);
+ CONF_CASE_RETURN(_SC_PRIORITY_SCHEDULING, SC_DISABLE);
+ CONF_CASE_RETURN(_SC_REALTIME_SIGNALS, SC_DISABLE);
+ CONF_CASE_RETURN(_SC_RTSIG_MAX, RTSIG_MAX);
+ CONF_CASE_RETURN(_SC_SAVED_IDS, SC_DISABLE);
+
+#ifdef LOSCFG_BASE_IPC_SEM
+ CONF_CASE_RETURN(_SC_SEMAPHORES, SC_ENABLE);
+ CONF_CASE_RETURN(_SC_SEM_NSEMS_MAX, SEM_NSEMS_MAX);
+ CONF_CASE_RETURN(_SC_SEM_VALUE_MAX, SEM_VALUE_MAX);
+#endif
+
+ CONF_CASE_RETURN(_SC_SHARED_MEMORY_OBJECTS, SC_DISABLE);
+ CONF_CASE_RETURN(_SC_SIGQUEUE_MAX, SIGQUEUE_MAX);
+ CONF_CASE_RETURN(_SC_STREAM_MAX, STREAM_MAX);
+ CONF_CASE_RETURN(_SC_SYNCHRONIZED_IO, SC_DISABLE);
+ CONF_CASE_RETURN(_SC_THREADS, SC_ENABLE);
+ CONF_CASE_RETURN(_SC_THREAD_ATTR_STACKADDR, SC_ENABLE);
+ CONF_CASE_RETURN(_SC_THREAD_ATTR_STACKSIZE, PTHREAD_ATTR_STACKSIZE);
+ CONF_CASE_RETURN(_SC_THREAD_DESTRUCTOR_ITERATIONS, PTHREAD_DESTRUCTOR_ITERATIONS);
+ CONF_CASE_RETURN(_SC_THREAD_KEYS_MAX, PTHREAD_KEYS_MAX);
+ CONF_CASE_RETURN(_SC_THREAD_PRIO_INHERIT, PTHREAD_PRIO_INHERIT);
+ CONF_CASE_RETURN(_SC_THREAD_PRIO_PROTECT, PTHREAD_PRIO_PROTECT);
+ CONF_CASE_RETURN(_SC_THREAD_PRIORITY_SCHEDULING, PTHREAD_PRIORITY_SCHEDULING);
+ CONF_CASE_RETURN(_SC_THREAD_PROCESS_SHARED, PTHREAD_PROCESS_SHARED);
+ CONF_CASE_RETURN(_SC_THREAD_SAFE_FUNCTIONS, SC_DISABLE);
+ CONF_CASE_RETURN(_SC_THREAD_STACK_MIN, PTHREAD_STACK_MIN);
+ CONF_CASE_RETURN(_SC_THREAD_THREADS_MAX, PTHREAD_THREADS_MAX);
+ CONF_CASE_RETURN(_SC_TIMERS, TIMERS);
+ CONF_CASE_RETURN(_SC_TIMER_MAX, TIMER_MAX);
+ CONF_CASE_RETURN(_SC_TTY_NAME_MAX, TTY_NAME_MAX);
+ CONF_CASE_RETURN(_SC_TZNAME_MAX, TZNAME_MAX);
+ CONF_CASE_RETURN(_SC_VERSION, POSIX_VERSION);
+
+ default:
+ set_errno(EINVAL);
+ return -1;
+ }
+}
+
+pid_t getpid(void)
+{
+ return ((LosTaskCB *)(OsCurrTaskGet()))->taskID;
+}
+
+int getrlimit(int resource, struct rlimit *rlim)
+{
+ unsigned int intSave;
+ LosProcessCB *pcb = OsCurrProcessGet();
+ struct rlimit *resourceLimit = pcb->resourceLimit;
+
+ switch (resource) {
+ case RLIMIT_NOFILE:
+ case RLIMIT_FSIZE:
+ break;
+ default:
+ return -EINVAL;
+ }
+
+ if (resourceLimit == NULL) {
+ rlim->rlim_cur = 0;
+ rlim->rlim_max = 0;
+
+ return 0;
+ }
+
+ SCHEDULER_LOCK(intSave);
+ rlim->rlim_cur = resourceLimit[resource].rlim_cur;
+ rlim->rlim_max = resourceLimit[resource].rlim_max;
+ SCHEDULER_UNLOCK(intSave);
+
+ return 0;
+}
+
+#define FSIZE_RLIMIT 0XFFFFFFFF
+#ifndef NR_OPEN_DEFAULT
+#define NR_OPEN_DEFAULT 1024
+#endif
+int setrlimit(int resource, const struct rlimit *rlim)
+{
+ unsigned int intSave;
+ struct rlimit *resourceLimit = NULL;
+ LosProcessCB *pcb = OsCurrProcessGet();
+
+ if (rlim->rlim_cur > rlim->rlim_max) {
+ return -EINVAL;
+ }
+ switch (resource) {
+ case RLIMIT_NOFILE:
+ if (rlim->rlim_max > NR_OPEN_DEFAULT) {
+ return -EPERM;
+ }
+ break;
+ case RLIMIT_FSIZE:
+ if (rlim->rlim_max > FSIZE_RLIMIT) {
+ return -EPERM;
+ }
+ break;
+ default:
+ return -EINVAL;
+ }
+
+ if (pcb->resourceLimit == NULL) {
+ resourceLimit = LOS_MemAlloc((VOID *)m_aucSysMem0, RLIM_NLIMITS * sizeof(struct rlimit));
+ if (resourceLimit == NULL) {
+ return -EINVAL;
+ }
+ }
+
+ SCHEDULER_LOCK(intSave);
+ if (pcb->resourceLimit == NULL) {
+ pcb->resourceLimit = resourceLimit;
+ resourceLimit = NULL;
+ }
+ pcb->resourceLimit[resource].rlim_cur = rlim->rlim_cur;
+ pcb->resourceLimit[resource].rlim_max = rlim->rlim_max;
+ SCHEDULER_UNLOCK(intSave);
+
+ (VOID)LOS_MemFree((VOID *)m_aucSysMem0, resourceLimit);
+ return 0;
+}
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/src/mqueue.c b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/src/mqueue.c
new file mode 100644
index 00000000..8e67b035
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/src/mqueue.c
@@ -0,0 +1,946 @@
+/*
+ * 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 "mqueue.h"
+#ifdef LOSCFG_FS_VFS
+#include "fcntl.h"
+#include "pthread.h"
+#include "map_error.h"
+#include "time_posix.h"
+#include "los_memory.h"
+#include "los_vm_map.h"
+#include "los_process_pri.h"
+#include "fs/file.h"
+#include "user_copy.h"
+
+
+#define FNONBLOCK O_NONBLOCK
+
+#ifndef MAX_MQ_FD
+#define MAX_MQ_FD CONFIG_NQUEUE_DESCRIPTORS
+#endif
+
+/* GLOBALS */
+STATIC fd_set g_queueFdSet;
+STATIC struct mqarray g_queueTable[LOSCFG_BASE_IPC_QUEUE_LIMIT];
+STATIC pthread_mutex_t g_mqueueMutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
+STATIC struct mqpersonal *g_mqPrivBuf[MAX_MQ_FD];
+
+/* LOCAL FUNCTIONS */
+STATIC INLINE INT32 MqNameCheck(const CHAR *mqName)
+{
+ if (mqName == NULL) {
+ errno = EINVAL;
+ return -1;
+ }
+
+ if (strlen(mqName) == 0) {
+ errno = EINVAL;
+ return -1;
+ }
+
+ if (strlen(mqName) > (PATH_MAX - 1)) {
+ errno = ENAMETOOLONG;
+ return -1;
+ }
+ return 0;
+}
+
+STATIC INLINE UINT32 GetMqueueCBByID(UINT32 queueID, LosQueueCB **queueCB)
+{
+ LosQueueCB *tmpQueueCB = NULL;
+ if (queueCB == NULL) {
+ errno = EINVAL;
+ return LOS_ERRNO_QUEUE_READ_PTR_NULL;
+ }
+ tmpQueueCB = GET_QUEUE_HANDLE(queueID);
+ if ((GET_QUEUE_INDEX(queueID) >= LOSCFG_BASE_IPC_QUEUE_LIMIT) || (tmpQueueCB->queueID != queueID)) {
+ return LOS_ERRNO_QUEUE_INVALID;
+ }
+ *queueCB = tmpQueueCB;
+
+ return LOS_OK;
+}
+
+STATIC INLINE struct mqarray *GetMqueueCBByName(const CHAR *name)
+{
+ UINT32 index;
+ UINT32 mylen = strlen(name);
+
+ for (index = 0; index < LOSCFG_BASE_IPC_QUEUE_LIMIT; index++) {
+ if ((g_queueTable[index].mq_name == NULL) || (strlen(g_queueTable[index].mq_name) != mylen)) {
+ continue;
+ }
+
+ if (strncmp(name, (const CHAR *)(g_queueTable[index].mq_name), mylen) == 0) {
+ return &(g_queueTable[index]);
+ }
+ }
+ return NULL;
+}
+
+STATIC INT32 DoMqueueDelete(struct mqarray *mqueueCB)
+{
+ UINT32 ret;
+
+ if (mqueueCB->mq_name != NULL) {
+ LOS_MemFree(OS_SYS_MEM_ADDR, mqueueCB->mq_name);
+ mqueueCB->mq_name = NULL;
+ }
+
+ mqueueCB->mqcb = NULL;
+ /* When mqueue-list head node needed free ,reset the mode_data */
+ mqueueCB->mode_data.data = 0;
+ mqueueCB->euid = -1;
+ mqueueCB->egid = -1;
+ mqueueCB->mq_notify.pid = 0;
+
+ ret = LOS_QueueDelete(mqueueCB->mq_id);
+ switch (ret) {
+ case LOS_OK:
+ return 0;
+ case LOS_ERRNO_QUEUE_NOT_FOUND:
+ case LOS_ERRNO_QUEUE_NOT_CREATE:
+ case LOS_ERRNO_QUEUE_IN_TSKUSE:
+ case LOS_ERRNO_QUEUE_IN_TSKWRITE:
+ errno = EAGAIN;
+ return -1;
+ default:
+ errno = EINVAL;
+ return -1;
+ }
+}
+
+STATIC int SaveMqueueName(const CHAR *mqName, struct mqarray *mqueueCB)
+{
+ size_t nameLen;
+
+ nameLen = strlen(mqName); /* sys_mq_open has checked name and name length */
+ mqueueCB->mq_name = (char *)LOS_MemAlloc(OS_SYS_MEM_ADDR, nameLen + 1);
+ if (mqueueCB->mq_name == NULL) {
+ errno = ENOMEM;
+ return LOS_NOK;
+ }
+
+ if (strncpy_s(mqueueCB->mq_name, (nameLen + 1), mqName, nameLen) != EOK) {
+ LOS_MemFree(OS_SYS_MEM_ADDR, mqueueCB->mq_name);
+ mqueueCB->mq_name = NULL;
+ errno = EINVAL;
+ return LOS_NOK;
+ }
+ mqueueCB->mq_name[nameLen] = '\0';
+ return LOS_OK;
+}
+
+STATIC struct mqpersonal *DoMqueueCreate(const struct mq_attr *attr, const CHAR *mqName, INT32 openFlag, UINT32 mode)
+{
+ struct mqarray *mqueueCB = NULL;
+ UINT32 mqueueID;
+
+ UINT32 err = LOS_QueueCreate(NULL, attr->mq_maxmsg, &mqueueID, 0, attr->mq_msgsize);
+ if (map_errno(err) != ENOERR) {
+ goto ERROUT;
+ }
+
+ if (g_queueTable[GET_QUEUE_INDEX(mqueueID)].mqcb == NULL) {
+ mqueueCB = &(g_queueTable[GET_QUEUE_INDEX(mqueueID)]);
+ mqueueCB->mq_id = mqueueID;
+ }
+
+ if (mqueueCB == NULL) {
+ errno = EINVAL;
+ goto ERROUT;
+ }
+
+ if (SaveMqueueName(mqName, mqueueCB) != LOS_OK) {
+ goto ERROUT;
+ }
+
+ if (GetMqueueCBByID(mqueueCB->mq_id, &(mqueueCB->mqcb)) != LOS_OK) {
+ errno = ENOSPC;
+ goto ERROUT;
+ }
+
+ mqueueCB->mq_personal = (struct mqpersonal *)LOS_MemAlloc(OS_SYS_MEM_ADDR, sizeof(struct mqpersonal));
+ if (mqueueCB->mq_personal == NULL) {
+ (VOID)LOS_QueueDelete(mqueueCB->mq_id);
+ mqueueCB->mqcb->queueHandle = NULL;
+ mqueueCB->mqcb = NULL;
+ errno = ENOSPC;
+ goto ERROUT;
+ }
+
+ mqueueCB->unlinkflag = FALSE;
+ mqueueCB->unlink_ref = 0;
+ mqueueCB->mq_personal->mq_status = MQ_USE_MAGIC;
+ mqueueCB->mq_personal->mq_next = NULL;
+ mqueueCB->mq_personal->mq_posixdes = mqueueCB;
+ mqueueCB->mq_personal->mq_flags = (INT32)((UINT32)openFlag | ((UINT32)attr->mq_flags & (UINT32)FNONBLOCK));
+ mqueueCB->mq_personal->mq_mode = mode;
+ mqueueCB->mq_personal->mq_refcount = 0;
+ mqueueCB->mq_notify.pid = 0;
+
+ return mqueueCB->mq_personal;
+ERROUT:
+
+ if ((mqueueCB != NULL) && (mqueueCB->mq_name != NULL)) {
+ LOS_MemFree(OS_SYS_MEM_ADDR, mqueueCB->mq_name);
+ mqueueCB->mq_name = NULL;
+ }
+ return (struct mqpersonal *)-1;
+}
+
+STATIC struct mqpersonal *DoMqueueOpen(struct mqarray *mqueueCB, INT32 openFlag)
+{
+ struct mqpersonal *privateMqPersonal = NULL;
+
+ /* already have the same name of g_squeuetable */
+ if (mqueueCB->unlinkflag == TRUE) {
+ errno = EINVAL;
+ goto ERROUT;
+ }
+ /* alloc mqprivate and add to mqarray */
+ privateMqPersonal = (struct mqpersonal *)LOS_MemAlloc(OS_SYS_MEM_ADDR, sizeof(struct mqpersonal));
+ if (privateMqPersonal == NULL) {
+ errno = ENOSPC;
+ goto ERROUT;
+ }
+
+ privateMqPersonal->mq_next = mqueueCB->mq_personal;
+ mqueueCB->mq_personal = privateMqPersonal;
+
+ privateMqPersonal->mq_posixdes = mqueueCB;
+ privateMqPersonal->mq_flags = openFlag;
+ privateMqPersonal->mq_status = MQ_USE_MAGIC;
+ privateMqPersonal->mq_refcount = 0;
+
+ return privateMqPersonal;
+
+ERROUT:
+ return (struct mqpersonal *)-1;
+}
+
+STATIC INT32 DoMqueueClose(struct mqpersonal *privateMqPersonal)
+{
+ struct mqarray *mqueueCB = NULL;
+ struct mqpersonal *tmp = NULL;
+
+ mqueueCB = privateMqPersonal->mq_posixdes;
+ if (mqueueCB == NULL || mqueueCB->mq_personal == NULL) {
+ errno = EBADF;
+ return LOS_NOK;
+ }
+
+ /* find the personal and remove */
+ if (mqueueCB->mq_personal == privateMqPersonal) {
+ mqueueCB->mq_personal = privateMqPersonal->mq_next;
+ } else {
+ for (tmp = mqueueCB->mq_personal; tmp->mq_next != NULL; tmp = tmp->mq_next) {
+ if (tmp->mq_next == privateMqPersonal) {
+ break;
+ }
+ }
+ if (tmp->mq_next == NULL) {
+ errno = EBADF;
+ return LOS_NOK;
+ }
+ tmp->mq_next = privateMqPersonal->mq_next;
+ }
+ /* flag no use */
+ privateMqPersonal->mq_status = 0;
+
+ /* free the personal */
+ (VOID)LOS_MemFree(OS_SYS_MEM_ADDR, privateMqPersonal);
+
+ if ((mqueueCB->unlinkflag == TRUE) && (mqueueCB->mq_personal == NULL)) {
+ return DoMqueueDelete(mqueueCB);
+ }
+ return LOS_OK;
+}
+
+/* Translate a sysFd into privateMqPersonal */
+STATIC struct mqpersonal *MqGetPrivDataBuff(mqd_t personal)
+{
+ INT32 sysFd = (INT32)personal;
+ INT32 id = sysFd - MQUEUE_FD_OFFSET;
+
+ /* Filter illegal id */
+ if ((id < 0) || (id >= MAX_MQ_FD)) {
+ errno = EBADF;
+ return NULL;
+ }
+ return g_mqPrivBuf[id];
+}
+
+/**
+ * Alloc sysFd, storage mq private data, set using bit.
+ *
+ * @param maxfdp: Maximum allowed application of mqueue sysFd.
+ * @param fdset: Mqueue sysFd bit map.
+ * @param privateMqPersonal: Private data.
+ * @return the index of the new fd; -1 on error
+ */
+STATIC INT32 MqAllocSysFd(int maxfdp, struct mqpersonal *privateMqPersonal)
+{
+ INT32 i;
+ fd_set *fdset = &g_queueFdSet;
+ for (i = 0; i < maxfdp; i++) {
+ /* sysFd: used bit setting, and get the index of swtmrID buffer */
+ if (fdset && !(FD_ISSET(i + MQUEUE_FD_OFFSET, fdset))) {
+ FD_SET(i + MQUEUE_FD_OFFSET, fdset);
+ if (!g_mqPrivBuf[i]) {
+ g_mqPrivBuf[i] = privateMqPersonal;
+ return i + MQUEUE_FD_OFFSET;
+ }
+ }
+ }
+ return -1;
+}
+
+STATIC VOID MqFreeSysFd(mqd_t personal)
+{
+ INT32 sysFd = (INT32)personal;
+ fd_set *fdset = &g_queueFdSet;
+ if (fdset && FD_ISSET(sysFd, fdset)) {
+ FD_CLR(sysFd, fdset);
+ g_mqPrivBuf[sysFd - MQUEUE_FD_OFFSET] = NULL;
+ }
+}
+
+/* Mqueue fd reference count */
+void MqueueRefer(int sysFd)
+{
+ struct mqarray *mqueueCB = NULL;
+ struct mqpersonal *privateMqPersonal = NULL;
+
+ (VOID)pthread_mutex_lock(&g_mqueueMutex);
+ /* Get the personal sysFd and reset personal fd -1 */
+ privateMqPersonal = MqGetPrivDataBuff((mqd_t)sysFd);
+ if (privateMqPersonal == NULL) {
+ goto OUT_UNLOCK;
+ }
+ mqueueCB = privateMqPersonal->mq_posixdes;
+ if (mqueueCB == NULL) {
+ goto OUT_UNLOCK;
+ }
+
+ privateMqPersonal->mq_refcount++;
+OUT_UNLOCK:
+ (VOID)pthread_mutex_unlock(&g_mqueueMutex);
+ return;
+}
+
+STATIC INT32 MqTryClose(struct mqpersonal *privateMqPersonal)
+{
+ struct mqarray *mqueueCB = NULL;
+ mqueueCB = privateMqPersonal->mq_posixdes;
+ if (mqueueCB == NULL) {
+ errno = ENFILE;
+ return false;
+ }
+
+ if (privateMqPersonal->mq_refcount == 0) {
+ return TRUE;
+ }
+ privateMqPersonal->mq_refcount--;
+ return FALSE;
+}
+
+/* Set the mode data bit,for consumer's mode comparing. */
+STATIC INT32 MqueueModeAnalysisSet(struct mqpersonal *privateMqPersonal)
+{
+ UINT32 mode;
+ UINT32 intSave;
+ User *user = NULL;
+ struct mqarray *mqueueCB = NULL;
+
+ if ((INT32)(UINTPTR)privateMqPersonal < 0) {
+ return -1;
+ }
+ /* Get mqueueCB of first time creating mqueue */
+ mqueueCB = privateMqPersonal->mq_posixdes;
+ if (mqueueCB == NULL) {
+ errno = ENFILE;
+ return -1;
+ }
+
+ mode = mqueueCB->mq_personal->mq_mode;
+ /* Set mqueue gid uid */
+ SCHEDULER_LOCK(intSave);
+ user = OsCurrUserGet();
+ mqueueCB->euid = user->effUserID;
+ mqueueCB->egid = user->effGid;
+ SCHEDULER_UNLOCK(intSave);
+
+ /* Set mode data bit */
+ if (mode & S_IRUSR) {
+ mqueueCB->mode_data.usr |= S_IRUSR;
+ }
+ if (mode & S_IWUSR) {
+ mqueueCB->mode_data.usr |= S_IWUSR;
+ }
+ if (mode & S_IRGRP) {
+ mqueueCB->mode_data.grp |= S_IRGRP;
+ }
+ if (mode & S_IWGRP) {
+ mqueueCB->mode_data.grp |= S_IWGRP;
+ }
+ if (mode & S_IROTH) {
+ mqueueCB->mode_data.oth |= S_IROTH;
+ }
+ if (mode & S_IWOTH) {
+ mqueueCB->mode_data.oth |= S_IWOTH;
+ }
+ return 0;
+}
+
+STATIC INT32 GetPermissionOfVisitor(struct mqarray *mqueueCB)
+{
+ uid_t euid;
+ gid_t egid;
+ UINT32 intSave;
+ User *user = NULL;
+
+ if (mqueueCB == NULL) {
+ errno = ENOENT;
+ return -EPERM;
+ }
+
+ /* Get the visitor process euid and egid */
+ SCHEDULER_LOCK(intSave);
+ user = OsCurrUserGet();
+ euid = user->effUserID;
+ egid = user->effGid;
+ SCHEDULER_UNLOCK(intSave);
+
+ /* root */
+ if (euid == 0) {
+ return ENOERR;
+ }
+ if (euid == mqueueCB->euid) { /* usr */
+ if (!((mqueueCB->mode_data.usr & S_IRUSR) || (mqueueCB->mode_data.usr & S_IWUSR))) {
+ errno = EACCES;
+ goto ERR_OUT;
+ }
+ } else if (egid == mqueueCB->egid) { /* grp */
+ if (!((mqueueCB->mode_data.grp & S_IRGRP) || (mqueueCB->mode_data.grp & S_IWGRP))) {
+ errno = EACCES;
+ goto ERR_OUT;
+ }
+ } else { /* oth */
+ if (!((mqueueCB->mode_data.oth & S_IROTH) || (mqueueCB->mode_data.oth & S_IWOTH))) {
+ errno = EACCES;
+ goto ERR_OUT;
+ }
+ }
+ return ENOERR;
+
+ERR_OUT:
+ return -EPERM;
+}
+
+STATIC INT32 GetMqueueAttr(struct mq_attr *defaultAttr, struct mq_attr *attr)
+{
+ if (attr != NULL) {
+ if (LOS_ArchCopyFromUser(defaultAttr, attr, sizeof(struct mq_attr))) {
+ errno = EFAULT;
+ return -1;
+ }
+ if ((defaultAttr->mq_maxmsg < 0) || (defaultAttr->mq_maxmsg > (long int)USHRT_MAX) ||
+ (defaultAttr->mq_msgsize < 0) || (defaultAttr->mq_msgsize > (long int)(USHRT_MAX - sizeof(UINT32)))) {
+ errno = EINVAL;
+ return -1;
+ }
+ }
+ return 0;
+}
+
+mqd_t mq_open(const char *mqName, int openFlag, ...)
+{
+ struct mqarray *mqueueCB = NULL;
+ struct mqpersonal *privateMqPersonal = (struct mqpersonal *)-1;
+ struct mq_attr *attr = NULL;
+ struct mq_attr defaultAttr = { 0, MQ_MAX_MSG_NUM, MQ_MAX_MSG_LEN, 0 };
+ va_list ap;
+ int sysFd;
+ mqd_t mqFd = -1;
+ unsigned int mode = 0;
+
+ if (MqNameCheck(mqName) == -1) {
+ return (mqd_t)-1;
+ }
+
+ (VOID)pthread_mutex_lock(&g_mqueueMutex);
+ mqueueCB = GetMqueueCBByName(mqName);
+ if ((UINT32)openFlag & (UINT32)O_CREAT) {
+ if (mqueueCB != NULL) {
+ if (((UINT32)openFlag & (UINT32)O_EXCL)) {
+ errno = EEXIST;
+ goto OUT;
+ }
+ privateMqPersonal = DoMqueueOpen(mqueueCB, openFlag);
+ } else {
+ va_start(ap, openFlag);
+ mode = va_arg(ap, unsigned int);
+ attr = va_arg(ap, struct mq_attr *);
+ va_end(ap);
+
+ if (GetMqueueAttr(&defaultAttr, attr)) {
+ goto OUT;
+ }
+ privateMqPersonal = DoMqueueCreate(&defaultAttr, mqName, openFlag, mode);
+ }
+ /* Set mode data bit ,just for the first node */
+ if (MqueueModeAnalysisSet(privateMqPersonal)) {
+ if ((INT32)(UINTPTR)privateMqPersonal > 0) {
+ (VOID)DoMqueueClose(privateMqPersonal);
+ }
+ goto OUT;
+ }
+ } else {
+ if (GetPermissionOfVisitor(mqueueCB)) {
+ goto OUT;
+ }
+ privateMqPersonal = DoMqueueOpen(mqueueCB, openFlag);
+ }
+
+ if ((INT32)(UINTPTR)privateMqPersonal > 0) {
+ /* alloc sysFd */
+ sysFd = MqAllocSysFd(MAX_MQ_FD, privateMqPersonal);
+ if (sysFd == -1) {
+ /* there are no more mq sysFd to use, close the personal */
+ (VOID)DoMqueueClose(privateMqPersonal);
+ errno = ENFILE;
+ }
+ mqFd = (mqd_t)sysFd;
+ }
+OUT:
+ (VOID)pthread_mutex_unlock(&g_mqueueMutex);
+ return mqFd;
+}
+
+int mq_close(mqd_t personal)
+{
+ INT32 ret = -1;
+ struct mqpersonal *privateMqPersonal = NULL;
+
+ (VOID)pthread_mutex_lock(&g_mqueueMutex);
+
+ /* Get the personal sysFd and reset personal fd -1 */
+ privateMqPersonal = MqGetPrivDataBuff(personal);
+ if (privateMqPersonal == NULL) {
+ goto OUT_UNLOCK;
+ }
+
+ if (privateMqPersonal->mq_status != MQ_USE_MAGIC) {
+ errno = EBADF;
+ goto OUT_UNLOCK;
+ }
+
+ if (!MqTryClose(privateMqPersonal)) {
+ ret = 0;
+ goto OUT_UNLOCK;
+ }
+
+ ret = DoMqueueClose(privateMqPersonal);
+ if (ret < 0) {
+ goto OUT_UNLOCK;
+ }
+ MqFreeSysFd(personal);
+
+OUT_UNLOCK:
+ (VOID)pthread_mutex_unlock(&g_mqueueMutex);
+ return ret;
+}
+
+int OsMqGetAttr(mqd_t personal, struct mq_attr *mqAttr)
+{
+ struct mqarray *mqueueCB = NULL;
+ struct mqpersonal *privateMqPersonal = NULL;
+
+ privateMqPersonal = MqGetPrivDataBuff(personal);
+ if (privateMqPersonal == NULL) {
+ return -1;
+ }
+
+ if (mqAttr == NULL) {
+ errno = EINVAL;
+ return -1;
+ }
+
+ (VOID)pthread_mutex_lock(&g_mqueueMutex);
+ if (privateMqPersonal->mq_status != MQ_USE_MAGIC) {
+ errno = EBADF;
+ (VOID)pthread_mutex_unlock(&g_mqueueMutex);
+ return -1;
+ }
+
+ mqueueCB = privateMqPersonal->mq_posixdes;
+ mqAttr->mq_maxmsg = mqueueCB->mqcb->queueLen;
+ mqAttr->mq_msgsize = mqueueCB->mqcb->queueSize - sizeof(UINT32);
+ mqAttr->mq_curmsgs = mqueueCB->mqcb->readWriteableCnt[OS_QUEUE_READ];
+ mqAttr->mq_flags = privateMqPersonal->mq_flags;
+ (VOID)pthread_mutex_unlock(&g_mqueueMutex);
+ return 0;
+}
+
+int OsMqSetAttr(mqd_t personal, const struct mq_attr *mqSetAttr, struct mq_attr *mqOldAttr)
+{
+ struct mqpersonal *privateMqPersonal = NULL;
+
+ privateMqPersonal = MqGetPrivDataBuff(personal);
+ if (privateMqPersonal == NULL) {
+ return -1;
+ }
+
+ if (mqSetAttr == NULL) {
+ errno = EINVAL;
+ return -1;
+ }
+
+ (VOID)pthread_mutex_lock(&g_mqueueMutex);
+ if (privateMqPersonal->mq_status != MQ_USE_MAGIC) {
+ errno = EBADF;
+ (VOID)pthread_mutex_unlock(&g_mqueueMutex);
+ return -1;
+ }
+
+ if (mqOldAttr != NULL) {
+ (VOID)OsMqGetAttr(personal, mqOldAttr);
+ }
+
+ privateMqPersonal->mq_flags = (INT32)((UINT32)privateMqPersonal->mq_flags & (UINT32)(~FNONBLOCK)); /* clear */
+ if (((UINT32)mqSetAttr->mq_flags & (UINT32)FNONBLOCK) == (UINT32)FNONBLOCK) {
+ privateMqPersonal->mq_flags = (INT32)((UINT32)privateMqPersonal->mq_flags | (UINT32)FNONBLOCK);
+ }
+ (VOID)pthread_mutex_unlock(&g_mqueueMutex);
+ return 0;
+}
+
+int mq_getsetattr(mqd_t mqd, const struct mq_attr *new, struct mq_attr *old)
+{
+ if (new == NULL) {
+ return OsMqGetAttr(mqd, old);
+ }
+ return OsMqSetAttr(mqd, new, old);
+}
+
+int mq_unlink(const char *mqName)
+{
+ INT32 ret = 0;
+ struct mqarray *mqueueCB = NULL;
+
+ if (MqNameCheck(mqName) == -1) {
+ return -1;
+ }
+
+ (VOID)pthread_mutex_lock(&g_mqueueMutex);
+ mqueueCB = GetMqueueCBByName(mqName);
+ if (mqueueCB == NULL) {
+ errno = ENOENT;
+ goto ERROUT_UNLOCK;
+ }
+
+ if (mqueueCB->mq_personal != NULL) {
+ mqueueCB->unlinkflag = TRUE;
+ } else if (mqueueCB->unlink_ref == 0) {
+ ret = DoMqueueDelete(mqueueCB);
+ }
+
+ (VOID)pthread_mutex_unlock(&g_mqueueMutex);
+ return ret;
+
+ERROUT_UNLOCK:
+ (VOID)pthread_mutex_unlock(&g_mqueueMutex);
+ return -1;
+}
+
+STATIC INT32 ConvertTimeout(long flags, const struct timespec *absTimeout, UINT64 *ticks)
+{
+ if ((UINT32)flags & (UINT32)FNONBLOCK) {
+ *ticks = LOS_NO_WAIT;
+ return 0;
+ }
+
+ if (absTimeout == NULL) {
+ *ticks = LOS_WAIT_FOREVER;
+ return 0;
+ }
+
+ if (!ValidTimeSpec(absTimeout)) {
+ errno = EINVAL;
+ return -1;
+ }
+
+ *ticks = OsTimeSpec2Tick(absTimeout);
+ return 0;
+}
+
+STATIC INLINE BOOL MqParamCheck(mqd_t personal, const char *msg, size_t msgLen)
+{
+ if (personal < 0) {
+ return FALSE;
+ }
+
+ if ((msg == NULL) || (msgLen == 0)) {
+ errno = EINVAL;
+ return FALSE;
+ }
+ return TRUE;
+}
+
+/*
+ * Send realtime a signal to process which registered itself
+ * successfully by mq_notify.
+ */
+static void MqSendNotify(struct mqarray *mqueueCB)
+{
+ struct mqnotify *mqnotify = &mqueueCB->mq_notify;
+
+ if ((mqnotify->pid) && (mqueueCB->mqcb->readWriteableCnt[OS_QUEUE_READ] == 0)) {
+ siginfo_t info;
+
+ switch (mqnotify->notify.sigev_notify) {
+ case SIGEV_SIGNAL:
+ /* sends signal */
+ /* Create the siginfo structure */
+ info.si_signo = mqnotify->notify.sigev_signo;
+ info.si_code = SI_MESGQ;
+ info.si_value = mqnotify->notify.sigev_value;
+ OsDispatch(mqnotify->pid, &info, OS_USER_KILL_PERMISSION);
+ break;
+ case SIGEV_NONE:
+ default:
+ break;
+ }
+ /* after notification unregisters process */
+ mqnotify->pid = 0;
+ }
+}
+
+#define OS_MQ_GOTO_ERROUT_UNLOCK_IF(expr, errcode) \
+ if (expr) { \
+ errno = errcode; \
+ goto ERROUT_UNLOCK; \
+ }
+#define OS_MQ_GOTO_ERROUT_IF(expr, errcode) \
+ if (expr) { \
+ errno = errcode; \
+ goto ERROUT; \
+ }
+int mq_timedsend(mqd_t personal, const char *msg, size_t msgLen, unsigned int msgPrio,
+ const struct timespec *absTimeout)
+{
+ UINT32 mqueueID, err;
+ UINT64 absTicks;
+ struct mqarray *mqueueCB = NULL;
+ struct mqpersonal *privateMqPersonal = NULL;
+
+ OS_MQ_GOTO_ERROUT_IF(!MqParamCheck(personal, msg, msgLen), errno);
+ OS_MQ_GOTO_ERROUT_IF(msgPrio > (MQ_PRIO_MAX - 1), EINVAL);
+
+ (VOID)pthread_mutex_lock(&g_mqueueMutex);
+ privateMqPersonal = MqGetPrivDataBuff(personal);
+
+ OS_MQ_GOTO_ERROUT_UNLOCK_IF(privateMqPersonal == NULL || privateMqPersonal->mq_status != MQ_USE_MAGIC, EBADF);
+
+ mqueueCB = privateMqPersonal->mq_posixdes;
+ OS_MQ_GOTO_ERROUT_UNLOCK_IF(msgLen > (size_t)(mqueueCB->mqcb->queueSize - sizeof(UINT32)), EMSGSIZE);
+
+ OS_MQ_GOTO_ERROUT_UNLOCK_IF((((UINT32)privateMqPersonal->mq_flags & (UINT32)O_WRONLY) != (UINT32)O_WRONLY) &&
+ (((UINT32)privateMqPersonal->mq_flags & (UINT32)O_RDWR) != (UINT32)O_RDWR),
+ EBADF);
+
+ OS_MQ_GOTO_ERROUT_UNLOCK_IF(ConvertTimeout(privateMqPersonal->mq_flags, absTimeout, &absTicks) == -1, errno);
+ mqueueID = mqueueCB->mq_id;
+ (VOID)pthread_mutex_unlock(&g_mqueueMutex);
+
+ if (LOS_ListEmpty(&mqueueCB->mqcb->readWriteList[OS_QUEUE_READ])) {
+ MqSendNotify(mqueueCB);
+ }
+
+ err = LOS_QueueWriteCopy(mqueueID, (VOID *)msg, (UINT32)msgLen, (UINT32)absTicks);
+ if (map_errno(err) != ENOERR) {
+ goto ERROUT;
+ }
+ return 0;
+ERROUT_UNLOCK:
+ (VOID)pthread_mutex_unlock(&g_mqueueMutex);
+ERROUT:
+ return -1;
+}
+
+ssize_t mq_timedreceive(mqd_t personal, char *msg, size_t msgLen, unsigned int *msgPrio,
+ const struct timespec *absTimeout)
+{
+ UINT32 mqueueID, err;
+ UINT32 receiveLen;
+ UINT64 absTicks;
+ struct mqarray *mqueueCB = NULL;
+ struct mqpersonal *privateMqPersonal = NULL;
+
+ if (!MqParamCheck(personal, msg, msgLen)) {
+ goto ERROUT;
+ }
+
+ if (msgPrio != NULL) {
+ *msgPrio = 0;
+ }
+
+ (VOID)pthread_mutex_lock(&g_mqueueMutex);
+ privateMqPersonal = MqGetPrivDataBuff(personal);
+ if (privateMqPersonal == NULL || privateMqPersonal->mq_status != MQ_USE_MAGIC) {
+ errno = EBADF;
+ goto ERROUT_UNLOCK;
+ }
+
+ mqueueCB = privateMqPersonal->mq_posixdes;
+ if (msgLen < (size_t)(mqueueCB->mqcb->queueSize - sizeof(UINT32))) {
+ errno = EMSGSIZE;
+ goto ERROUT_UNLOCK;
+ }
+
+ if (((UINT32)privateMqPersonal->mq_flags & (UINT32)O_WRONLY) == (UINT32)O_WRONLY) {
+ errno = EBADF;
+ goto ERROUT_UNLOCK;
+ }
+
+ if (ConvertTimeout(privateMqPersonal->mq_flags, absTimeout, &absTicks) == -1) {
+ goto ERROUT_UNLOCK;
+ }
+
+ receiveLen = msgLen;
+ mqueueID = mqueueCB->mq_id;
+ (VOID)pthread_mutex_unlock(&g_mqueueMutex);
+
+ err = LOS_QueueReadCopy(mqueueID, (VOID *)msg, &receiveLen, (UINT32)absTicks);
+ if (map_errno(err) == ENOERR) {
+ return (ssize_t)receiveLen;
+ } else {
+ goto ERROUT;
+ }
+
+ERROUT_UNLOCK:
+ (VOID)pthread_mutex_unlock(&g_mqueueMutex);
+ERROUT:
+ return -1;
+}
+
+/* not support the prio */
+int mq_send(mqd_t personal, const char *msg_ptr, size_t msg_len, unsigned int msg_prio)
+{
+ return mq_timedsend(personal, msg_ptr, msg_len, msg_prio, NULL);
+}
+
+ssize_t mq_receive(mqd_t personal, char *msg_ptr, size_t msg_len, unsigned int *msg_prio)
+{
+ return mq_timedreceive(personal, msg_ptr, msg_len, msg_prio, NULL);
+}
+
+STATIC INLINE BOOL MqNotifyParamCheck(mqd_t personal, const struct sigevent *sigev)
+{
+ if (personal < 0) {
+ errno = EBADF;
+ goto ERROUT;
+ }
+
+ if (sigev != NULL) {
+ if (sigev->sigev_notify != SIGEV_NONE && sigev->sigev_notify != SIGEV_SIGNAL) {
+ errno = EINVAL;
+ goto ERROUT;
+ }
+ if (sigev->sigev_notify == SIGEV_SIGNAL && !GOOD_SIGNO(sigev->sigev_signo)) {
+ errno = EINVAL;
+ goto ERROUT;
+ }
+ }
+
+ return TRUE;
+ERROUT:
+ return FALSE;
+}
+
+int OsMqNotify(mqd_t personal, const struct sigevent *sigev)
+{
+ struct mqarray *mqueueCB = NULL;
+ struct mqnotify *mqnotify = NULL;
+ struct mqpersonal *privateMqPersonal = NULL;
+
+ if (!MqNotifyParamCheck(personal, sigev)) {
+ goto ERROUT;
+ }
+
+ (VOID)pthread_mutex_lock(&g_mqueueMutex);
+ privateMqPersonal = MqGetPrivDataBuff(personal);
+ if (privateMqPersonal == NULL) {
+ goto OUT_UNLOCK;
+ }
+
+ if (privateMqPersonal->mq_status != MQ_USE_MAGIC) {
+ errno = EBADF;
+ goto OUT_UNLOCK;
+ }
+
+ mqueueCB = privateMqPersonal->mq_posixdes;
+ mqnotify = &mqueueCB->mq_notify;
+
+ if (sigev == NULL) {
+ if (mqnotify->pid == LOS_GetCurrProcessID()) {
+ mqnotify->pid = 0;
+ }
+ } else if (mqnotify->pid != 0) {
+ errno = EBUSY;
+ goto OUT_UNLOCK;
+ } else {
+ switch (sigev->sigev_notify) {
+ case SIGEV_NONE:
+ mqnotify->notify.sigev_notify = SIGEV_NONE;
+ break;
+ case SIGEV_SIGNAL:
+ mqnotify->notify.sigev_signo = sigev->sigev_signo;
+ mqnotify->notify.sigev_value = sigev->sigev_value;
+ mqnotify->notify.sigev_notify = SIGEV_SIGNAL;
+ break;
+ default:
+ break;
+ }
+
+ mqnotify->pid = LOS_GetCurrProcessID();
+ }
+
+ (VOID)pthread_mutex_unlock(&g_mqueueMutex);
+ return 0;
+OUT_UNLOCK:
+ (VOID)pthread_mutex_unlock(&g_mqueueMutex);
+ERROUT:
+ return -1;
+}
+#endif
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/src/posix_memalign.c b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/src/posix_memalign.c
new file mode 100644
index 00000000..5b93834e
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/src/posix_memalign.c
@@ -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.
+ */
+
+#include "los_typedef.h"
+#include "los_memory.h"
+
+
+int posix_memalign(void **memAddr, size_t alignment, size_t size)
+{
+ if ((alignment == 0) || ((alignment & (alignment - 1)) != 0) || ((alignment % sizeof(void *)) != 0)) {
+ return EINVAL;
+ }
+
+ *memAddr = LOS_MemAllocAlign(OS_SYS_MEM_ADDR, size, alignment);
+ if (*memAddr == NULL) {
+ return ENOMEM;
+ }
+
+ return ENOERR;
+}
+
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/src/pprivate.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/src/pprivate.h
new file mode 100644
index 00000000..85f358ef
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/src/pprivate.h
@@ -0,0 +1,87 @@
+/*
+ * 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 _HWLITEOS_POSIX_PPRIVATE_H
+#define _HWLITEOS_POSIX_PPRIVATE_H
+
+#include "los_process.h"
+#include "pthread.h"
+#include "sys/types.h"
+#include "los_sem_pri.h"
+#include "los_task_pri.h"
+
+#ifdef __cplusplus
+#if __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+#define PTHREAD_DATA_NAME_MAX 20
+/*
+ * Thread control data structure
+ * Per-thread information needed by POSIX
+ */
+typedef struct {
+ pthread_attr_t attr; /* Current thread attributes */
+ pthread_t id; /* My thread ID */
+ LosTaskCB *task; /* pointer to Huawei LiteOS thread object */
+ CHAR name[PTHREAD_DATA_NAME_MAX]; /* name string for debugging */
+ UINT8 state; /* Thread state */
+ UINT8 cancelstate; /* Cancel state of thread */
+ volatile UINT8 canceltype; /* Cancel type of thread */
+ volatile UINT8 canceled; /* pending cancel flag */
+ struct pthread_cleanup_buffer *cancelbuffer; /* stack of cleanup buffers */
+ UINT32 freestack; /* stack malloced, must be freed */
+ UINT32 stackmem; /* base of stack memory area only valid if freestack == true */
+ VOID **thread_data; /* Per-thread data table pointer */
+} _pthread_data;
+
+/*
+ * Values for the state field. These are solely concerned with the
+ * states visible to POSIX. The thread's run state is stored in the
+ * struct _pthread_data about thread object.
+ * Note: numerical order here is important, do not rearrange.
+ */
+#define PTHREAD_STATE_FREE 0 /* This structure is free for reuse */
+#define PTHREAD_STATE_DETACHED 1 /* The thread is running but detached */
+#define PTHREAD_STATE_RUNNING 2 /* The thread is running and will wait to join when it exits */
+#define PTHREAD_STATE_JOIN 3 /* The thread has exited and is waiting to be joined */
+#define PTHREAD_STATE_EXITED 4 /* The thread has exited and is ready to be reaped */
+#define PTHREAD_STATE_ALRDY_JOIN 5 /* The thread state is in join */
+
+
+#ifdef __cplusplus
+#if __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+#endif
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/src/pthread.c b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/src/pthread.c
new file mode 100644
index 00000000..1fd5c4ff
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/src/pthread.c
@@ -0,0 +1,806 @@
+/*
+ * 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 "pprivate.h"
+#include "pthread.h"
+#include "sched.h"
+
+#include "stdio.h"
+#include "map_error.h"
+#include "los_process_pri.h"
+#include "los_sched_pri.h"
+
+
+/*
+ * Array of pthread control structures. A pthread_t object is
+ * "just" an index into this array.
+ */
+STATIC _pthread_data g_pthreadData[LOSCFG_BASE_CORE_TSK_LIMIT + 1];
+
+/* Count of number of threads that have exited and not been reaped. */
+STATIC INT32 g_pthreadsExited = 0;
+
+/* this is to protect the pthread data */
+STATIC pthread_mutex_t g_pthreadsDataMutex = PTHREAD_MUTEX_INITIALIZER;
+
+/* pointed to by PTHREAD_CANCELED */
+UINTPTR g_pthreadCanceledDummyVar;
+
+/*
+ * Private version of pthread_self() that returns a pointer to our internal
+ * control structure.
+ */
+_pthread_data *pthread_get_self_data(void)
+{
+ UINT32 runningTaskPID = ((LosTaskCB *)(OsCurrTaskGet()))->taskID;
+ _pthread_data *data = &g_pthreadData[runningTaskPID];
+
+ return data;
+}
+
+_pthread_data *pthread_get_data(pthread_t id)
+{
+ _pthread_data *data = NULL;
+
+ if (OS_TID_CHECK_INVALID(id)) {
+ return NULL;
+ }
+
+ data = &g_pthreadData[id];
+ /* Check that this is a valid entry */
+ if ((data->state == PTHREAD_STATE_FREE) || (data->state == PTHREAD_STATE_EXITED)) {
+ return NULL;
+ }
+
+ /* Check that the entry matches the id */
+ if (data->id != id) {
+ return NULL;
+ }
+
+ /* Return the pointer */
+ return data;
+}
+
+/*
+ * Check whether there is a cancel pending and if so, whether
+ * cancellations are enabled. We do it in this order to reduce the
+ * number of tests in the common case - when no cancellations are
+ * pending. We make this inline so it can be called directly below for speed
+ */
+STATIC INT32 CheckForCancel(VOID)
+{
+ _pthread_data *self = pthread_get_self_data();
+ if (self->canceled && (self->cancelstate == PTHREAD_CANCEL_ENABLE)) {
+ return 1;
+ }
+ return 0;
+}
+
+STATIC VOID ProcessUnusedStatusTask(_pthread_data *data)
+{
+ data->state = PTHREAD_STATE_FREE;
+ (VOID)memset_s(data, sizeof(_pthread_data), 0, sizeof(_pthread_data));
+}
+
+/*
+ * This function is called to tidy up and dispose of any threads that have
+ * exited. This work must be done from a thread other than the one exiting.
+ * Note: this function must be called with pthread_mutex locked.
+ */
+STATIC VOID PthreadReap(VOID)
+{
+ UINT32 i;
+ _pthread_data *data = NULL;
+ /*
+ * Loop over the thread table looking for exited threads. The
+ * g_pthreadsExited counter springs us out of this once we have
+ * found them all (and keeps us out if there are none to do).
+ */
+ for (i = 0; g_pthreadsExited && (i < g_taskMaxNum); i++) {
+ data = &g_pthreadData[i];
+ if (data->state == PTHREAD_STATE_EXITED) {
+ /* the Huawei LiteOS not delete the dead TCB,so need to delete the TCB */
+ (VOID)LOS_TaskDelete(data->task->taskID);
+ if (data->task->taskStatus & OS_TASK_STATUS_UNUSED) {
+ ProcessUnusedStatusTask(data);
+ g_pthreadsExited--;
+ }
+ }
+ }
+}
+
+STATIC VOID SetPthreadAttr(const _pthread_data *self, const pthread_attr_t *attr, pthread_attr_t *outAttr)
+{
+ /*
+ * Set use_attr to the set of attributes we are going to
+ * actually use. Either those passed in, or the default set.
+ */
+ if (attr == NULL) {
+ (VOID)pthread_attr_init(outAttr);
+ } else {
+ (VOID)memcpy_s(outAttr, sizeof(pthread_attr_t), attr, sizeof(pthread_attr_t));
+ }
+
+ /*
+ * If the stack size is not valid, we can assume that it is at
+ * least PTHREAD_STACK_MIN bytes.
+ */
+ if (!outAttr->stacksize_set) {
+ outAttr->stacksize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE;
+ }
+ if (outAttr->inheritsched == PTHREAD_INHERIT_SCHED) {
+ if (self->task == NULL) {
+ outAttr->schedparam.sched_priority = ((LosTaskCB *)(OsCurrTaskGet()))->priority;
+ } else {
+ outAttr->schedpolicy = self->attr.schedpolicy;
+ outAttr->schedparam = self->attr.schedparam;
+ outAttr->scope = self->attr.scope;
+ }
+ }
+}
+
+STATIC VOID SetPthreadDataAttr(const pthread_attr_t *userAttr, const pthread_t threadID,
+ LosTaskCB *taskCB, _pthread_data *created)
+{
+ created->attr = *userAttr;
+ created->id = threadID;
+ created->task = taskCB;
+ created->state = (userAttr->detachstate == PTHREAD_CREATE_JOINABLE) ?
+ PTHREAD_STATE_RUNNING : PTHREAD_STATE_DETACHED;
+ /* need to confirmation */
+ created->cancelstate = PTHREAD_CANCEL_ENABLE;
+ created->canceltype = PTHREAD_CANCEL_DEFERRED;
+ created->cancelbuffer = NULL;
+ created->canceled = 0;
+ created->freestack = 0; /* no use default : 0 */
+ created->stackmem = taskCB->topOfStack;
+ created->thread_data = NULL;
+}
+
+STATIC UINT32 InitPthreadData(pthread_t threadID, pthread_attr_t *userAttr,
+ const CHAR name[], size_t len)
+{
+ errno_t err;
+ UINT32 ret = LOS_OK;
+ LosTaskCB *taskCB = OS_TCB_FROM_TID(threadID);
+ _pthread_data *created = &g_pthreadData[threadID];
+
+ err = strncpy_s(created->name, sizeof(created->name), name, len);
+ if (err != EOK) {
+ PRINT_ERR("%s: %d, err: %d\n", __FUNCTION__, __LINE__, err);
+ return LOS_NOK;
+ }
+ userAttr->stacksize = taskCB->stackSize;
+ err = OsSetTaskName(taskCB, created->name, FALSE);
+ if (err != LOS_OK) {
+ PRINT_ERR("%s: %d, err: %d\n", __FUNCTION__, __LINE__, err);
+ return LOS_NOK;
+ }
+#ifdef LOSCFG_KERNEL_SMP
+ if (userAttr->cpuset.__bits[0] > 0) {
+ taskCB->cpuAffiMask = (UINT16)userAttr->cpuset.__bits[0];
+ }
+#endif
+
+ SetPthreadDataAttr(userAttr, threadID, taskCB, created);
+ return ret;
+}
+
+int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
+ void *(*startRoutine)(void *), void *arg)
+{
+ pthread_attr_t userAttr;
+ UINT32 ret;
+ CHAR name[PTHREAD_DATA_NAME_MAX] = {0};
+ STATIC UINT16 pthreadNumber = 1;
+ TSK_INIT_PARAM_S taskInitParam = {0};
+ UINT32 taskHandle;
+ _pthread_data *self = pthread_get_self_data();
+
+ if ((thread == NULL) || (startRoutine == NULL)) {
+ return EINVAL;
+ }
+
+ SetPthreadAttr(self, attr, &userAttr);
+
+ (VOID)snprintf_s(name, sizeof(name), sizeof(name) - 1, "pth%02d", pthreadNumber);
+ pthreadNumber++;
+
+ taskInitParam.pcName = name;
+ taskInitParam.pfnTaskEntry = (TSK_ENTRY_FUNC)startRoutine;
+ taskInitParam.auwArgs[0] = (UINTPTR)arg;
+ taskInitParam.usTaskPrio = (UINT16)userAttr.schedparam.sched_priority;
+ taskInitParam.uwStackSize = userAttr.stacksize;
+ if (OsProcessIsUserMode(OsCurrProcessGet())) {
+ taskInitParam.processID = OsGetKernelInitProcessID();
+ } else {
+ taskInitParam.processID = OsCurrProcessGet()->processID;
+ }
+ if (userAttr.detachstate == PTHREAD_CREATE_DETACHED) {
+ taskInitParam.uwResved = LOS_TASK_STATUS_DETACHED;
+ } else {
+ /* Set the pthread default joinable */
+ taskInitParam.uwResved = LOS_TASK_ATTR_JOINABLE;
+ }
+
+ PthreadReap();
+ ret = LOS_TaskCreateOnly(&taskHandle, &taskInitParam);
+ if (ret == LOS_OK) {
+ *thread = (pthread_t)taskHandle;
+ ret = InitPthreadData(*thread, &userAttr, name, PTHREAD_DATA_NAME_MAX);
+ if (ret != LOS_OK) {
+ goto ERROR_OUT_WITH_TASK;
+ }
+ (VOID)LOS_SetTaskScheduler(taskHandle, SCHED_RR, taskInitParam.usTaskPrio);
+ }
+
+ if (ret == LOS_OK) {
+ return ENOERR;
+ } else {
+ goto ERROR_OUT;
+ }
+
+ERROR_OUT_WITH_TASK:
+ (VOID)LOS_TaskDelete(taskHandle);
+ERROR_OUT:
+ *thread = (pthread_t)-1;
+
+ return map_errno(ret);
+}
+
+void pthread_exit(void *retVal)
+{
+ _pthread_data *self = pthread_get_self_data();
+ UINT32 intSave;
+
+ if (pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, (int *)0) != ENOERR) {
+ PRINT_ERR("%s: %d failed\n", __FUNCTION__, __LINE__);
+ }
+
+ if (pthread_mutex_lock(&g_pthreadsDataMutex) != ENOERR) {
+ PRINT_ERR("%s: %d failed\n", __FUNCTION__, __LINE__);
+ }
+
+ self->task->joinRetval = retVal;
+ /*
+ * If we are already detached, go to EXITED state, otherwise
+ * go into JOIN state.
+ */
+ if (self->state == PTHREAD_STATE_DETACHED) {
+ self->state = PTHREAD_STATE_EXITED;
+ g_pthreadsExited++;
+ } else {
+ self->state = PTHREAD_STATE_JOIN;
+ }
+
+ if (pthread_mutex_unlock(&g_pthreadsDataMutex) != ENOERR) {
+ PRINT_ERR("%s: %d failed\n", __FUNCTION__, __LINE__);
+ }
+ SCHEDULER_LOCK(intSave);
+ /* If the thread is the highest thread,it can't schedule in LOS_SemPost. */
+ OsTaskJoinPostUnsafe(self->task);
+ if (self->task->taskStatus & OS_TASK_STATUS_RUNNING) {
+ OsSchedResched();
+ }
+ SCHEDULER_UNLOCK(intSave);
+}
+
+STATIC INT32 ProcessByJoinState(_pthread_data *joined)
+{
+ UINT32 intSave;
+ INT32 err = 0;
+ UINT32 ret;
+ switch (joined->state) {
+ case PTHREAD_STATE_RUNNING:
+ /* The thread is still running, we must wait for it. */
+ SCHEDULER_LOCK(intSave);
+ ret = OsTaskJoinPendUnsafe(joined->task);
+ SCHEDULER_UNLOCK(intSave);
+ if (ret != LOS_OK) {
+ err = (INT32)ret;
+ break;
+ }
+
+ joined->state = PTHREAD_STATE_ALRDY_JOIN;
+ break;
+ /*
+ * The thread has become unjoinable while we waited, so we
+ * fall through to complain.
+ */
+ case PTHREAD_STATE_FREE:
+ case PTHREAD_STATE_DETACHED:
+ case PTHREAD_STATE_EXITED:
+ /* None of these may be joined. */
+ err = EINVAL;
+ break;
+ case PTHREAD_STATE_ALRDY_JOIN:
+ err = EINVAL;
+ break;
+ case PTHREAD_STATE_JOIN:
+ break;
+ default:
+ PRINT_ERR("state: %u is not supported\n", (UINT32)joined->state);
+ break;
+ }
+ return err;
+}
+
+int pthread_join(pthread_t thread, void **retVal)
+{
+ INT32 err;
+ UINT8 status;
+ _pthread_data *self = NULL;
+ _pthread_data *joined = NULL;
+
+ /* Check for cancellation first. */
+ pthread_testcancel();
+
+ /* Dispose of any dead threads */
+ (VOID)pthread_mutex_lock(&g_pthreadsDataMutex);
+ PthreadReap();
+ (VOID)pthread_mutex_unlock(&g_pthreadsDataMutex);
+
+ self = pthread_get_self_data();
+ joined = pthread_get_data(thread);
+ if (joined == NULL) {
+ return ESRCH;
+ }
+ status = joined->state;
+
+ if (joined == self) {
+ return EDEADLK;
+ }
+
+ err = ProcessByJoinState(joined);
+ (VOID)pthread_mutex_lock(&g_pthreadsDataMutex);
+
+ if (!err) {
+ /*
+ * Here, we know that joinee is a thread that has exited and is
+ * ready to be joined.
+ */
+ if (retVal != NULL) {
+ /* Get the retVal */
+ *retVal = joined->task->joinRetval;
+ }
+
+ /* Set state to exited. */
+ joined->state = PTHREAD_STATE_EXITED;
+ g_pthreadsExited++;
+
+ /* Dispose of any dead threads */
+ PthreadReap();
+ } else {
+ joined->state = status;
+ }
+
+ (VOID)pthread_mutex_unlock(&g_pthreadsDataMutex);
+ /* Check for cancellation before returning */
+ pthread_testcancel();
+
+ return err;
+}
+
+/*
+ * Set the detachstate of the thread to "detached". The thread then does not
+ * need to be joined and its resources will be freed when it exits.
+ */
+int pthread_detach(pthread_t thread)
+{
+ int ret = 0;
+ UINT32 intSave;
+
+ _pthread_data *detached = NULL;
+
+ if (pthread_mutex_lock(&g_pthreadsDataMutex) != ENOERR) {
+ ret = ESRCH;
+ }
+ detached = pthread_get_data(thread);
+ if (detached == NULL) {
+ ret = ESRCH; /* No such thread */
+ } else if (detached->state == PTHREAD_STATE_DETACHED) {
+ ret = EINVAL; /* Already detached! */
+ } else if (detached->state == PTHREAD_STATE_JOIN) {
+ detached->state = PTHREAD_STATE_EXITED;
+ g_pthreadsExited++;
+ } else {
+ /* Set state to detached and kick any joinees to make them return. */
+ SCHEDULER_LOCK(intSave);
+ if (!(detached->task->taskStatus & OS_TASK_STATUS_EXIT)) {
+ ret = OsTaskSetDetachUnsafe(detached->task);
+ if (ret == ESRCH) {
+ ret = LOS_OK;
+ } else if (ret == LOS_OK) {
+ detached->state = PTHREAD_STATE_DETACHED;
+ }
+ } else {
+ detached->state = PTHREAD_STATE_EXITED;
+ g_pthreadsExited++;
+ }
+ SCHEDULER_UNLOCK(intSave);
+ }
+
+ /* Dispose of any dead threads */
+ PthreadReap();
+ if (pthread_mutex_unlock(&g_pthreadsDataMutex) != ENOERR) {
+ ret = ESRCH;
+ }
+
+ return ret;
+}
+
+int pthread_setschedparam(pthread_t thread, int policy, const struct sched_param *param)
+{
+ _pthread_data *data = NULL;
+ int ret;
+
+ if ((param == NULL) || (param->sched_priority > OS_TASK_PRIORITY_LOWEST)) {
+ return EINVAL;
+ }
+
+ if (policy != SCHED_RR) {
+ return EINVAL;
+ }
+
+ /* The parameters seem OK, change the thread. */
+ ret = pthread_mutex_lock(&g_pthreadsDataMutex);
+ if (ret != ENOERR) {
+ return ret;
+ }
+
+ data = pthread_get_data(thread);
+ if (data == NULL) {
+ ret = pthread_mutex_unlock(&g_pthreadsDataMutex);
+ if (ret != ENOERR) {
+ return ret;
+ }
+ return ESRCH;
+ }
+
+ /* Only support one policy now */
+ data->attr.schedpolicy = SCHED_RR;
+ data->attr.schedparam = *param;
+
+ ret = pthread_mutex_unlock(&g_pthreadsDataMutex);
+ if (ret != ENOERR) {
+ return ret;
+ }
+ (VOID)LOS_TaskPriSet((UINT32)thread, (UINT16)param->sched_priority);
+
+ return ENOERR;
+}
+
+int pthread_getschedparam(pthread_t thread, int *policy, struct sched_param *param)
+{
+ _pthread_data *data = NULL;
+ int ret;
+
+ if ((policy == NULL) || (param == NULL)) {
+ return EINVAL;
+ }
+
+ ret = pthread_mutex_lock(&g_pthreadsDataMutex);
+ if (ret != ENOERR) {
+ return ret;
+ }
+
+ data = pthread_get_data(thread);
+ if (data == NULL) {
+ goto ERR_OUT;
+ }
+
+ *policy = data->attr.schedpolicy;
+ *param = data->attr.schedparam;
+
+ ret = pthread_mutex_unlock(&g_pthreadsDataMutex);
+ return ret;
+ERR_OUT:
+ ret = pthread_mutex_unlock(&g_pthreadsDataMutex);
+ if (ret != ENOERR) {
+ return ret;
+ }
+ return ESRCH;
+}
+
+/* Call initRoutine just the once per control variable. */
+int pthread_once(pthread_once_t *onceControl, void (*initRoutine)(void))
+{
+ pthread_once_t old;
+ int ret;
+
+ if ((onceControl == NULL) || (initRoutine == NULL)) {
+ return EINVAL;
+ }
+
+ /* Do a test and set on the onceControl object. */
+ ret = pthread_mutex_lock(&g_pthreadsDataMutex);
+ if (ret != ENOERR) {
+ return ret;
+ }
+
+ old = *onceControl;
+ *onceControl = 1;
+
+ ret = pthread_mutex_unlock(&g_pthreadsDataMutex);
+ if (ret != ENOERR) {
+ return ret;
+ }
+ /* If the onceControl was zero, call the initRoutine(). */
+ if (!old) {
+ initRoutine();
+ }
+
+ return ENOERR;
+}
+
+/* Thread specific data */
+int pthread_key_create(pthread_key_t *key, void (*destructor)(void *))
+{
+ (VOID)key;
+ (VOID)destructor;
+ PRINT_ERR("[%s] is not support.\n", __FUNCTION__);
+ return 0;
+}
+
+/* Store the pointer value in the thread-specific data slot addressed by the key. */
+int pthread_setspecific(pthread_key_t key, const void *pointer)
+{
+ (VOID)key;
+ (VOID)pointer;
+ PRINT_ERR("[%s] is not support.\n", __FUNCTION__);
+ return 0;
+}
+
+/* Retrieve the pointer value in the thread-specific data slot addressed by the key. */
+void *pthread_getspecific(pthread_key_t key)
+{
+ (VOID)key;
+ PRINT_ERR("[%s] is not support.\n", __FUNCTION__);
+ return NULL;
+}
+
+/*
+ * Set cancel state of current thread to ENABLE or DISABLE.
+ * Returns old state in *oldState.
+ */
+int pthread_setcancelstate(int state, int *oldState)
+{
+ _pthread_data *self = NULL;
+ int ret;
+
+ if ((state != PTHREAD_CANCEL_ENABLE) && (state != PTHREAD_CANCEL_DISABLE)) {
+ return EINVAL;
+ }
+
+ ret = pthread_mutex_lock(&g_pthreadsDataMutex);
+ if (ret != ENOERR) {
+ return ret;
+ }
+
+ self = pthread_get_self_data();
+
+ if (oldState != NULL) {
+ *oldState = self->cancelstate;
+ }
+
+ self->cancelstate = (UINT8)state;
+
+ ret = pthread_mutex_unlock(&g_pthreadsDataMutex);
+ if (ret != ENOERR) {
+ return ret;
+ }
+
+ return ENOERR;
+}
+
+/*
+ * Set cancel type of current thread to ASYNCHRONOUS or DEFERRED.
+ * Returns old type in *oldType.
+ */
+int pthread_setcanceltype(int type, int *oldType)
+{
+ _pthread_data *self = NULL;
+ int ret;
+
+ if ((type != PTHREAD_CANCEL_ASYNCHRONOUS) && (type != PTHREAD_CANCEL_DEFERRED)) {
+ return EINVAL;
+ }
+
+ ret = pthread_mutex_lock(&g_pthreadsDataMutex);
+ if (ret != ENOERR) {
+ return ret;
+ }
+
+ self = pthread_get_self_data();
+ if (oldType != NULL) {
+ *oldType = self->canceltype;
+ }
+
+ self->canceltype = (UINT8)type;
+
+ ret = pthread_mutex_unlock(&g_pthreadsDataMutex);
+ if (ret != ENOERR) {
+ return ret;
+ }
+
+ return ENOERR;
+}
+
+STATIC UINT32 DoPthreadCancel(_pthread_data *data)
+{
+ UINT32 ret = LOS_OK;
+ UINT32 intSave;
+ LOS_TaskLock();
+ data->canceled = 0;
+ if ((data->task->taskStatus & OS_TASK_STATUS_EXIT) || (LOS_TaskSuspend(data->task->taskID) != ENOERR)) {
+ ret = LOS_NOK;
+ goto OUT;
+ }
+
+ if (data->task->taskStatus & OS_TASK_FLAG_PTHREAD_JOIN) {
+ SCHEDULER_LOCK(intSave);
+ OsTaskJoinPostUnsafe(data->task);
+ SCHEDULER_UNLOCK(intSave);
+ g_pthreadCanceledDummyVar = (UINTPTR)PTHREAD_CANCELED;
+ data->task->joinRetval = (VOID *)g_pthreadCanceledDummyVar;
+ } else if (data->state && !(data->task->taskStatus & OS_TASK_STATUS_UNUSED)) {
+ data->state = PTHREAD_STATE_EXITED;
+ g_pthreadsExited++;
+ PthreadReap();
+ } else {
+ ret = LOS_NOK;
+ }
+OUT:
+ LOS_TaskUnlock();
+ return ret;
+}
+
+int pthread_cancel(pthread_t thread)
+{
+ _pthread_data *data = NULL;
+
+ if (pthread_mutex_lock(&g_pthreadsDataMutex) != ENOERR) {
+ PRINT_ERR("%s: %d failed\n", __FUNCTION__, __LINE__);
+ }
+
+ data = pthread_get_data(thread);
+ if (data == NULL) {
+ if (pthread_mutex_unlock(&g_pthreadsDataMutex) != ENOERR) {
+ PRINT_ERR("%s: %d failed\n", __FUNCTION__, __LINE__);
+ }
+ return ESRCH;
+ }
+
+ data->canceled = 1;
+
+ if ((data->cancelstate == PTHREAD_CANCEL_ENABLE) &&
+ (data->canceltype == PTHREAD_CANCEL_ASYNCHRONOUS)) {
+ /*
+ * If the thread has cancellation enabled, and it is in
+ * asynchronous mode, suspend it and set corresponding thread's status.
+ * We also release the thread out of any current wait to make it wake up.
+ */
+ if (DoPthreadCancel(data) == LOS_NOK) {
+ goto ERROR_OUT;
+ }
+ }
+
+ /*
+ * Otherwise the thread has cancellation disabled, in which case
+ * it is up to the thread to enable cancellation
+ */
+ if (pthread_mutex_unlock(&g_pthreadsDataMutex) != ENOERR) {
+ PRINT_ERR("%s: %d failed\n", __FUNCTION__, __LINE__);
+ }
+
+ return ENOERR;
+ERROR_OUT:
+ if (pthread_mutex_unlock(&g_pthreadsDataMutex) != ENOERR) {
+ PRINT_ERR("%s: %d failed\n", __FUNCTION__, __LINE__);
+ }
+ return ESRCH;
+}
+
+/*
+ * Test for a pending cancellation for the current thread and terminate
+ * the thread if there is one.
+ */
+void pthread_testcancel(void)
+{
+ if (CheckForCancel()) {
+ /*
+ * If we have cancellation enabled, and there is a cancellation
+ * pending, then go ahead and do the deed.
+ * Exit now with special retVal. pthread_exit() calls the
+ * cancellation handlers implicitly.
+ */
+ pthread_exit((void *)PTHREAD_CANCELED);
+ }
+}
+
+/* Get current thread id. */
+pthread_t pthread_self(void)
+{
+ _pthread_data *data = pthread_get_self_data();
+
+ return data->id;
+}
+
+/* Compare two thread identifiers. */
+int pthread_equal(pthread_t thread1, pthread_t thread2)
+{
+ return thread1 == thread2;
+}
+
+void pthread_cleanup_push_inner(struct pthread_cleanup_buffer *buffer,
+ void (*routine)(void *), void *arg)
+{
+ (VOID)buffer;
+ (VOID)routine;
+ (VOID)arg;
+ PRINT_ERR("[%s] is not support.\n", __FUNCTION__);
+ return;
+}
+
+void pthread_cleanup_pop_inner(struct pthread_cleanup_buffer *buffer, int execute)
+{
+ (VOID)buffer;
+ (VOID)execute;
+ PRINT_ERR("[%s] is not support.\n", __FUNCTION__);
+ return;
+}
+
+/*
+ * Set the cpu affinity mask for the thread
+ */
+int pthread_setaffinity_np(pthread_t thread, size_t cpusetsize, const cpu_set_t* cpuset)
+{
+ INT32 ret = sched_setaffinity(thread, cpusetsize, cpuset);
+ if (ret == -1) {
+ return errno;
+ } else {
+ return ENOERR;
+ }
+}
+
+/*
+ * Get the cpu affinity mask from the thread
+ */
+int pthread_getaffinity_np(pthread_t thread, size_t cpusetsize, cpu_set_t* cpuset)
+{
+ INT32 ret = sched_getaffinity(thread, cpusetsize, cpuset);
+ if (ret == -1) {
+ return errno;
+ } else {
+ return ENOERR;
+ }
+}
+
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/src/pthread_attr.c b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/src/pthread_attr.c
new file mode 100644
index 00000000..0368b7bb
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/src/pthread_attr.c
@@ -0,0 +1,277 @@
+/*
+ * 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 "pthread.h"
+#include "pprivate.h"
+
+
+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;
+
+#ifdef LOSCFG_KERNEL_SMP
+ attr->cpuset.__bits[0] = 0;
+#endif
+
+ return ENOERR;
+}
+
+int pthread_attr_destroy(pthread_attr_t *attr)
+{
+ if (attr == NULL) {
+ return EINVAL;
+ }
+
+ /* Nothing to do here... */
+ return ENOERR;
+}
+
+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 ENOERR;
+ }
+
+ 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 ENOERR;
+}
+
+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 ENOERR;
+ }
+
+ 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 ENOERR;
+}
+
+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 ENOERR;
+ }
+
+ 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 ENOERR;
+}
+
+int pthread_attr_setschedpolicy(pthread_attr_t *attr, int policy)
+{
+ if ((attr != NULL) && (policy == SCHED_RR)) {
+ attr->schedpolicy = SCHED_RR;
+ return ENOERR;
+ }
+
+ 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 ENOERR;
+}
+
+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 < 0) || (param->sched_priority > OS_TASK_PRIORITY_LOWEST)) {
+ return ENOTSUP;
+ }
+
+ attr->schedparam = *param;
+
+ return ENOERR;
+}
+
+int pthread_attr_getschedparam(const pthread_attr_t *attr, struct sched_param *param)
+{
+ if ((attr == NULL) || (param == NULL)) {
+ return EINVAL;
+ }
+
+ *param = attr->schedparam;
+
+ return ENOERR;
+}
+
+/*
+ * 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 ENOERR;
+}
+
+int pthread_attr_getstackaddr(const pthread_attr_t *attr, void **stackAddr)
+{
+ if (((attr != NULL) && (stackAddr != NULL)) && attr->stackaddr_set) {
+ *stackAddr = attr->stackaddr;
+ return ENOERR;
+ }
+
+ 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 ENOERR;
+}
+
+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 ENOERR;
+}
+
+/*
+ * Set the cpu affinity mask
+ */
+int pthread_attr_setaffinity_np(pthread_attr_t* attr, size_t cpusetsize, const cpu_set_t* cpuset)
+{
+#ifdef LOSCFG_KERNEL_SMP
+ if (attr == NULL) {
+ return EINVAL;
+ }
+
+ if ((cpuset == NULL) || (cpusetsize == 0)) {
+ attr->cpuset.__bits[0] = 0;
+ return ENOERR;
+ }
+
+ if ((cpusetsize != sizeof(cpu_set_t)) || (cpuset->__bits[0] > LOSCFG_KERNEL_CPU_MASK)) {
+ return EINVAL;
+ }
+
+ attr->cpuset = *cpuset;
+#endif
+
+ return ENOERR;
+}
+
+/*
+ * Get the cpu affinity mask
+ */
+int pthread_attr_getaffinity_np(const pthread_attr_t* attr, size_t cpusetsize, cpu_set_t* cpuset)
+{
+#ifdef LOSCFG_KERNEL_SMP
+ if ((attr == NULL) || (cpuset == NULL) || (cpusetsize != sizeof(cpu_set_t))) {
+ return EINVAL;
+ }
+
+ *cpuset = attr->cpuset;
+#endif
+
+ return ENOERR;
+}
+
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/src/pthread_cond.c b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/src/pthread_cond.c
new file mode 100644
index 00000000..425d6cc8
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/src/pthread_cond.c
@@ -0,0 +1,348 @@
+/*
+ * 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 "pprivate.h"
+#include "pthread.h"
+#include "stdlib.h"
+#include "time_posix.h"
+#include "los_atomic.h"
+#include "los_event_pri.h"
+
+
+#define BROADCAST_EVENT 1
+#define COND_COUNTER_STEP 0x0004U
+#define COND_FLAGS_MASK 0x0003U
+#define COND_COUNTER_MASK (~COND_FLAGS_MASK)
+
+STATIC INLINE INT32 CondInitCheck(const pthread_cond_t *cond)
+{
+ if ((cond->event.stEventList.pstPrev == NULL) &&
+ (cond->event.stEventList.pstNext == NULL)) {
+ return 1;
+ }
+ return 0;
+}
+
+int pthread_condattr_getpshared(const pthread_condattr_t *attr, int *shared)
+{
+ if ((attr == NULL) || (shared == NULL)) {
+ return EINVAL;
+ }
+
+ *shared = PTHREAD_PROCESS_PRIVATE;
+
+ return 0;
+}
+
+int pthread_condattr_setpshared(pthread_condattr_t *attr, int shared)
+{
+ (VOID)attr;
+ if ((shared != PTHREAD_PROCESS_PRIVATE) && (shared != PTHREAD_PROCESS_SHARED)) {
+ return EINVAL;
+ }
+
+ if (shared != PTHREAD_PROCESS_PRIVATE) {
+ return ENOSYS;
+ }
+
+ return 0;
+}
+
+int pthread_condattr_destroy(pthread_condattr_t *attr)
+{
+ if (attr == NULL) {
+ return EINVAL;
+ }
+
+ return 0;
+}
+
+int pthread_condattr_init(pthread_condattr_t *attr)
+{
+ if (attr == NULL) {
+ return EINVAL;
+ }
+
+ return 0;
+}
+
+int pthread_cond_destroy(pthread_cond_t *cond)
+{
+ if (cond == NULL) {
+ return EINVAL;
+ }
+
+ if (CondInitCheck(cond)) {
+ return ENOERR;
+ }
+
+ if (LOS_EventDestroy(&cond->event) != LOS_OK) {
+ return EBUSY;
+ }
+ if (pthread_mutex_destroy(cond->mutex) != ENOERR) {
+ PRINT_ERR("%s mutex destroy fail!\n", __FUNCTION__);
+ return EINVAL;
+ }
+ free(cond->mutex);
+ cond->mutex = NULL;
+ return ENOERR;
+}
+
+int pthread_cond_init(pthread_cond_t *cond, const pthread_condattr_t *attr)
+{
+ int ret = ENOERR;
+
+ if (cond == NULL) {
+ return EINVAL;
+ }
+ (VOID)attr;
+ (VOID)LOS_EventInit(&(cond->event));
+
+ cond->mutex = (pthread_mutex_t *)malloc(sizeof(pthread_mutex_t));
+ if (cond->mutex == NULL) {
+ return ENOMEM;
+ }
+
+ (VOID)pthread_mutex_init(cond->mutex, NULL);
+
+ cond->value = 0;
+ (VOID)pthread_mutex_lock(cond->mutex);
+ cond->count = 0;
+ (VOID)pthread_mutex_unlock(cond->mutex);
+
+ return ret;
+}
+
+STATIC VOID PthreadCondValueModify(pthread_cond_t *cond)
+{
+ UINT32 flags = ((UINT32)cond->value & COND_FLAGS_MASK);
+ INT32 oldVal, newVal;
+
+ while (true) {
+ oldVal = cond->value;
+ newVal = (INT32)(((UINT32)(oldVal - COND_COUNTER_STEP) & COND_COUNTER_MASK) | flags);
+ if (LOS_AtomicCmpXchg32bits(&cond->value, newVal, oldVal) == 0) {
+ break;
+ }
+ }
+}
+
+int pthread_cond_broadcast(pthread_cond_t *cond)
+{
+ int ret = ENOERR;
+
+ if (cond == NULL) {
+ return EINVAL;
+ }
+
+ (VOID)pthread_mutex_lock(cond->mutex);
+ if (cond->count > 0) {
+ cond->count = 0;
+ (VOID)pthread_mutex_unlock(cond->mutex);
+
+ PthreadCondValueModify(cond);
+
+ (VOID)LOS_EventWrite(&(cond->event), BROADCAST_EVENT);
+ return ret;
+ }
+ (VOID)pthread_mutex_unlock(cond->mutex);
+
+ return ret;
+}
+
+int pthread_cond_signal(pthread_cond_t *cond)
+{
+ int ret = ENOERR;
+
+ if (cond == NULL) {
+ return EINVAL;
+ }
+
+ (VOID)pthread_mutex_lock(cond->mutex);
+ if (cond->count > 0) {
+ cond->count--;
+ (VOID)pthread_mutex_unlock(cond->mutex);
+ PthreadCondValueModify(cond);
+ (VOID)OsEventWriteOnce(&(cond->event), 0x01);
+
+ return ret;
+ }
+ (VOID)pthread_mutex_unlock(cond->mutex);
+
+ return ret;
+}
+
+STATIC INT32 PthreadCondWaitSub(pthread_cond_t *cond, INT32 value, UINT32 ticks)
+{
+ EventCond eventCond = { &cond->value, value, ~0x01U };
+ /*
+ * When the scheduling lock is held:
+ * (1) value is not equal to cond->value, clear the event message and
+ * do not block the current thread, because other threads is calling pthread_cond_broadcast or
+ * pthread_cond_signal to modify cond->value and wake up the current thread,
+ * and others threads will block on the scheduling lock until the current thread releases
+ * the scheduling lock.
+ * (2) value is equal to cond->value, block the current thread
+ * and wait to be awakened by other threads.
+ */
+ return (int)OsEventReadWithCond(&eventCond, &(cond->event), 0x0fU,
+ LOS_WAITMODE_OR | LOS_WAITMODE_CLR, ticks);
+}
+STATIC VOID PthreadCountSub(pthread_cond_t *cond)
+{
+ (VOID)pthread_mutex_lock(cond->mutex);
+ if (cond->count > 0) {
+ cond->count--;
+ }
+ (VOID)pthread_mutex_unlock(cond->mutex);
+}
+
+STATIC INT32 ProcessReturnVal(pthread_cond_t *cond, INT32 val)
+{
+ INT32 ret;
+ switch (val) {
+ /* 0: event does not occur */
+ case 0:
+ case BROADCAST_EVENT:
+ ret = ENOERR;
+ break;
+ case LOS_ERRNO_EVENT_READ_TIMEOUT:
+ PthreadCountSub(cond);
+ ret = ETIMEDOUT;
+ break;
+ default:
+ PthreadCountSub(cond);
+ ret = EINVAL;
+ break;
+ }
+ return ret;
+}
+
+int pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex,
+ const struct timespec *absTime)
+{
+ UINT32 absTicks;
+ INT32 ret;
+ INT32 oldValue;
+
+ pthread_testcancel();
+ if ((cond == NULL) || (mutex == NULL) || (absTime == NULL)) {
+ return EINVAL;
+ }
+
+ if (CondInitCheck(cond)) {
+ ret = pthread_cond_init(cond, NULL);
+ if (ret != ENOERR) {
+ return ret;
+ }
+ }
+ oldValue = cond->value;
+
+ (VOID)pthread_mutex_lock(cond->mutex);
+ cond->count++;
+ (VOID)pthread_mutex_unlock(cond->mutex);
+
+ if ((absTime->tv_sec == 0) && (absTime->tv_nsec == 0)) {
+ return ETIMEDOUT;
+ }
+
+ if (!ValidTimeSpec(absTime)) {
+ return EINVAL;
+ }
+
+ absTicks = OsTimeSpec2Tick(absTime);
+ if (pthread_mutex_unlock(mutex) != ENOERR) {
+ PRINT_ERR("%s: %d failed\n", __FUNCTION__, __LINE__);
+ }
+
+#ifndef LOSCFG_ARCH_CORTEX_M7
+ ret = PthreadCondWaitSub(cond, oldValue, absTicks);
+#else
+ ret = (INT32)LOS_EventRead(&(cond->event), 0x0f, LOS_WAITMODE_OR | LOS_WAITMODE_CLR, absTicks);
+#endif
+ if (pthread_mutex_lock(mutex) != ENOERR) {
+ PRINT_ERR("%s: %d failed\n", __FUNCTION__, __LINE__);
+ }
+
+ ret = ProcessReturnVal(cond, ret);
+ pthread_testcancel();
+ return ret;
+}
+
+int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
+{
+ int ret;
+ int oldValue;
+
+ if ((cond == NULL) || (mutex == NULL)) {
+ return EINVAL;
+ }
+
+ if (CondInitCheck(cond)) {
+ ret = pthread_cond_init(cond, NULL);
+ if (ret != ENOERR) {
+ return ret;
+ }
+ }
+ oldValue = cond->value;
+
+ (VOID)pthread_mutex_lock(cond->mutex);
+ cond->count++;
+ (VOID)pthread_mutex_unlock(cond->mutex);
+
+ if (pthread_mutex_unlock(mutex) != ENOERR) {
+ PRINT_ERR("%s: %d failed\n", __FUNCTION__, __LINE__);
+ }
+
+#ifndef LOSCFG_ARCH_CORTEX_M7
+ ret = PthreadCondWaitSub(cond, oldValue, LOS_WAIT_FOREVER);
+#else
+ ret = (INT32)LOS_EventRead(&(cond->event), 0x0f, LOS_WAITMODE_OR | LOS_WAITMODE_CLR, LOS_WAIT_FOREVER);
+#endif
+ if (pthread_mutex_lock(mutex) != ENOERR) {
+ PRINT_ERR("%s: %d failed\n", __FUNCTION__, __LINE__);
+ }
+
+ switch (ret) {
+ /* 0: event does not occur */
+ case 0:
+ case BROADCAST_EVENT:
+ ret = ENOERR;
+ break;
+ default:
+ PthreadCountSub(cond);
+ ret = EINVAL;
+ break;
+ }
+
+ return ret;
+}
+
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/src/pthread_mutex.c b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/src/pthread_mutex.c
new file mode 100644
index 00000000..35c838bd
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/src/pthread_mutex.c
@@ -0,0 +1,136 @@
+/*
+ * 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 "pthread.h"
+
+
+int pthread_mutexattr_init(pthread_mutexattr_t *attr)
+{
+ unsigned int ret = LOS_MuxAttrInit(attr);
+ if (ret != LOS_OK) {
+ return (int)ret;
+ }
+
+#if defined POSIX_MUTEX_DEFAULT_INHERIT
+ attr->protocol = PTHREAD_PRIO_INHERIT;
+#elif defined POSIX_MUTEX_DEFAULT_PROTECT
+ attr->protocol = PTHREAD_PRIO_PROTECT;
+#else
+ attr->protocol = PTHREAD_PRIO_NONE;
+#endif
+ attr->type = PTHREAD_MUTEX_NORMAL;
+ return LOS_OK;
+}
+
+int pthread_mutexattr_destroy(pthread_mutexattr_t *attr)
+{
+ return LOS_MuxAttrDestroy(attr);
+}
+
+int pthread_mutexattr_setprotocol(pthread_mutexattr_t *attr, int protocol)
+{
+ return LOS_MuxAttrSetProtocol(attr, protocol);
+}
+
+int pthread_mutexattr_getprotocol(const pthread_mutexattr_t *attr, int *protocol)
+{
+ return LOS_MuxAttrGetProtocol(attr, protocol);
+}
+
+int pthread_mutexattr_setprioceiling(pthread_mutexattr_t *attr, int prioceiling)
+{
+ return LOS_MuxAttrSetPrioceiling(attr, prioceiling);
+}
+
+int pthread_mutexattr_getprioceiling(const pthread_mutexattr_t *attr, int *prioceiling)
+{
+ return LOS_MuxAttrGetPrioceiling(attr, prioceiling);
+}
+
+int pthread_mutex_setprioceiling(pthread_mutex_t *mutex, int prioceiling, int *oldPrioceiling)
+{
+ return LOS_MuxSetPrioceiling(mutex, prioceiling, oldPrioceiling);
+}
+
+int pthread_mutex_getprioceiling(const pthread_mutex_t *mutex, int *prioceiling)
+{
+ return LOS_MuxGetPrioceiling(mutex, prioceiling);
+}
+
+int pthread_mutexattr_gettype(const pthread_mutexattr_t *attr, int *outType)
+{
+ return LOS_MuxAttrGetType(attr, outType);
+}
+
+int pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type)
+{
+ return LOS_MuxAttrSetType(attr, type);
+}
+
+/* Initialize mutex. If mutexAttr is NULL, use default attributes. */
+int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *mutexAttr)
+{
+ unsigned int ret = LOS_MuxInit(mutex, mutexAttr);
+ if ((ret == LOS_OK) && (mutexAttr == NULL)) {
+#if defined POSIX_MUTEX_DEFAULT_INHERIT
+ mutex->attr.protocol = PTHREAD_PRIO_INHERIT;
+#elif defined POSIX_MUTEX_DEFAULT_PROTECT
+ mutex->attr.protocol = PTHREAD_PRIO_PROTECT;
+#else
+ mutex->attr.protocol = PTHREAD_PRIO_NONE;
+#endif
+ mutex->attr.type = PTHREAD_MUTEX_NORMAL;
+ }
+
+ return (int)ret;
+}
+
+int pthread_mutex_destroy(pthread_mutex_t *mutex)
+{
+ return LOS_MuxDestroy(mutex);
+}
+
+/* Lock mutex, waiting for it if necessary. */
+int pthread_mutex_lock(pthread_mutex_t *mutex)
+{
+ return LOS_MuxLock(mutex, LOS_WAIT_FOREVER);
+}
+
+int pthread_mutex_trylock(pthread_mutex_t *mutex)
+{
+ return LOS_MuxTrylock(mutex);
+}
+
+int pthread_mutex_unlock(pthread_mutex_t *mutex)
+{
+ return LOS_MuxUnlock(mutex);
+}
+
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/src/sched.c b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/src/sched.c
new file mode 100644
index 00000000..7ff7a5a5
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/src/sched.c
@@ -0,0 +1,145 @@
+/*
+ * 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 "sched.h"
+#include "map_error.h"
+#include "sys/types.h"
+#include "unistd.h"
+#include "los_task_pri.h"
+
+
+int sched_get_priority_min(int policy)
+{
+ if (policy != SCHED_RR) {
+ errno = EINVAL;
+ return -1;
+ }
+
+ return OS_TASK_PRIORITY_HIGHEST;
+}
+
+int sched_get_priority_max(int policy)
+{
+ if (policy != SCHED_RR) {
+ errno = EINVAL;
+ return -1;
+ }
+
+ return OS_TASK_PRIORITY_LOWEST;
+}
+
+/*
+ * This API is Linux-specific, not conforming to POSIX.
+ */
+int sched_setaffinity(pid_t pid, size_t set_size, const cpu_set_t* set)
+{
+#ifdef LOSCFG_KERNEL_SMP
+ UINT32 taskID = (UINT32)pid;
+ UINT32 ret;
+
+ if ((set == NULL) || (set_size != sizeof(cpu_set_t)) || (set->__bits[0] > LOSCFG_KERNEL_CPU_MASK)) {
+ errno = EINVAL;
+ return -1;
+ }
+
+ if (taskID == 0) {
+ taskID = LOS_CurTaskIDGet();
+ if (taskID == LOS_ERRNO_TSK_ID_INVALID) {
+ errno = EINVAL;
+ return -1;
+ }
+ }
+
+ ret = LOS_TaskCpuAffiSet(taskID, (UINT16)set->__bits[0]);
+ if (ret != LOS_OK) {
+ errno = map_errno(ret);
+ return -1;
+ }
+#endif
+
+ return 0;
+}
+
+/*
+ * This API is Linux-specific, not conforming to POSIX.
+ */
+int sched_getaffinity(pid_t pid, size_t set_size, cpu_set_t* set)
+{
+#ifdef LOSCFG_KERNEL_SMP
+ UINT32 taskID = (UINT32)pid;
+ UINT16 cpuAffiMask;
+
+ if ((set == NULL) || (set_size != sizeof(cpu_set_t))) {
+ errno = EINVAL;
+ return -1;
+ }
+
+ if (taskID == 0) {
+ taskID = LOS_CurTaskIDGet();
+ if (taskID == LOS_ERRNO_TSK_ID_INVALID) {
+ errno = EINVAL;
+ return -1;
+ }
+ }
+
+ cpuAffiMask = LOS_TaskCpuAffiGet(taskID);
+ if (cpuAffiMask == 0) {
+ errno = EINVAL;
+ return -1;
+ }
+
+ set->__bits[0] = cpuAffiMask;
+#endif
+
+ return 0;
+}
+
+int __sched_cpucount(size_t set_size, const cpu_set_t* set)
+{
+ INT32 count = 0;
+ UINT32 i;
+
+ if ((set_size != sizeof(cpu_set_t)) || (set == NULL)) {
+ return 0;
+ }
+
+ for (i = 0; i < set_size / sizeof(__CPU_BITTYPE); i++) {
+ count += __builtin_popcountl(set->__bits[i]);
+ }
+
+ return count;
+}
+
+int sched_yield()
+{
+ (void)LOS_TaskYield();
+ return 0;
+}
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/src/semaphore.c b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/src/semaphore.c
new file mode 100644
index 00000000..71b8f32b
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/src/semaphore.c
@@ -0,0 +1,194 @@
+/*
+ * 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 "semaphore.h"
+#include "sys/types.h"
+#include "map_error.h"
+#include "time_posix.h"
+
+
+/* Initialize semaphore to value, shared is not supported in Huawei LiteOS. */
+int sem_init(sem_t *sem, int shared, unsigned int value)
+{
+ UINT32 semHandle = 0;
+ UINT32 ret;
+
+ (VOID)shared;
+ if ((sem == NULL) || (value > OS_SEM_COUNT_MAX)) {
+ errno = EINVAL;
+ return -1;
+ }
+
+ ret = LOS_SemCreate(value, &semHandle);
+ if (map_errno(ret) != ENOERR) {
+ return -1;
+ }
+
+ sem->sem = GET_SEM(semHandle);
+
+ return 0;
+}
+
+int sem_destroy(sem_t *sem)
+{
+ UINT32 ret;
+
+ if ((sem == NULL) || (sem->sem == NULL)) {
+ errno = EINVAL;
+ return -1;
+ }
+
+ ret = LOS_SemDelete(sem->sem->semID);
+ if (map_errno(ret) != ENOERR) {
+ return -1;
+ }
+ return 0;
+}
+
+/* Decrement value if >0 or wait for a post. */
+int sem_wait(sem_t *sem)
+{
+ UINT32 ret;
+
+ if ((sem == NULL) || (sem->sem == NULL)) {
+ errno = EINVAL;
+ return -1;
+ }
+
+ ret = LOS_SemPend(sem->sem->semID, LOS_WAIT_FOREVER);
+ if (map_errno(ret) == ENOERR) {
+ return 0;
+ } else {
+ return -1;
+ }
+}
+
+/* Decrement value if >0, return -1 if not. */
+int sem_trywait(sem_t *sem)
+{
+ UINT32 ret;
+
+ if ((sem == NULL) || (sem->sem == NULL)) {
+ errno = EINVAL;
+ return -1;
+ }
+
+ ret = LOS_SemPend(sem->sem->semID, LOS_NO_WAIT);
+ if (map_errno(ret) == ENOERR) {
+ return 0;
+ } else {
+ if ((errno != EINVAL) || (ret == LOS_ERRNO_SEM_UNAVAILABLE)) {
+ errno = EAGAIN;
+ }
+ return -1;
+ }
+}
+
+int sem_timedwait(sem_t *sem, const struct timespec *timeout)
+{
+ UINT32 ret;
+ UINT32 tickCnt;
+
+ if ((sem == NULL) || (sem->sem == NULL)) {
+ errno = EINVAL;
+ return -1;
+ }
+
+ if (!ValidTimeSpec(timeout)) {
+ errno = EINVAL;
+ return -1;
+ }
+
+ tickCnt = OsTimeSpec2Tick(timeout);
+ ret = LOS_SemPend(sem->sem->semID, tickCnt);
+ if (map_errno(ret) == ENOERR) {
+ return 0;
+ } else {
+ return -1;
+ }
+}
+
+int sem_post(sem_t *sem)
+{
+ UINT32 ret;
+
+ if ((sem == NULL) || (sem->sem == NULL)) {
+ errno = EINVAL;
+ return -1;
+ }
+
+ ret = LOS_SemPost(sem->sem->semID);
+ if (map_errno(ret) != ENOERR) {
+ return -1;
+ }
+
+ return 0;
+}
+
+int sem_getvalue(sem_t *sem, int *currVal)
+{
+ INT32 val;
+
+ if ((sem == NULL) || (currVal == NULL)) {
+ errno = EINVAL;
+ return -1;
+ }
+ val = sem->sem->semCount;
+ if (val < 0) {
+ val = 0;
+ }
+
+ *currVal = val;
+ return 0;
+}
+
+sem_t *sem_open(const char *name, int openFlag, ...)
+{
+ (VOID)name;
+ (VOID)openFlag;
+ errno = ENOSYS;
+ return NULL;
+}
+
+int sem_close(sem_t *sem)
+{
+ (VOID)sem;
+ errno = ENOSYS;
+ return -1;
+}
+
+int sem_unlink(const char *name)
+{
+ (VOID)name;
+ errno = ENOSYS;
+ return -1;
+}
+
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/src/socket.c b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/src/socket.c
new file mode 100644
index 00000000..23d00cf7
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/src/socket.c
@@ -0,0 +1,188 @@
+/*
+ * 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
+
+#ifdef LOSCFG_NET_LWIP_SACK
+#include
+
+#if !LWIP_COMPAT_SOCKETS
+
+#define CHECK_NULL_PTR(ptr) do { if (ptr == NULL) { set_errno(EFAULT); return -1; } } while (0)
+
+int accept(int s, struct sockaddr *addr, socklen_t *addrlen)
+{
+ return lwip_accept(s, addr, addrlen);
+}
+
+int bind(int s, const struct sockaddr *name, socklen_t namelen)
+{
+ CHECK_NULL_PTR(name);
+ if (namelen < sizeof(*name)) {
+ set_errno(EINVAL);
+ return -1;
+ }
+ return lwip_bind(s, name, namelen);
+}
+
+int shutdown(int s, int how)
+{
+ return lwip_shutdown(s, how);
+}
+
+int getpeername(int s, struct sockaddr *name, socklen_t *namelen)
+{
+ CHECK_NULL_PTR(name);
+ CHECK_NULL_PTR(namelen);
+ return lwip_getpeername(s, name, namelen);
+}
+
+int getsockname(int s, struct sockaddr *name, socklen_t *namelen)
+{
+ CHECK_NULL_PTR(name);
+ CHECK_NULL_PTR(namelen);
+ return lwip_getsockname(s, name, namelen);
+}
+
+int getsockopt(int s, int level, int optname, void *optval, socklen_t *optlen)
+{
+ return lwip_getsockopt(s, level, optname, optval, optlen);
+}
+
+int setsockopt(int s, int level, int optname, const void *optval, socklen_t optlen)
+{
+ return lwip_setsockopt(s, level, optname, optval, optlen);
+}
+
+int closesocket(int s)
+{
+ return lwip_close(s);
+}
+
+int connect(int s, const struct sockaddr *name, socklen_t namelen)
+{
+ CHECK_NULL_PTR(name);
+ if (namelen < sizeof(*name)) {
+ set_errno(EINVAL);
+ return -1;
+ }
+ return lwip_connect(s, name, namelen);
+}
+
+int listen(int s, int backlog)
+{
+ return lwip_listen(s, backlog);
+}
+
+ssize_t recv(int s, void *mem, size_t len, int flags)
+{
+ CHECK_NULL_PTR(mem);
+ return lwip_recv(s, mem, len, flags);
+}
+
+ssize_t recvfrom(int s, void *mem, size_t len, int flags,
+ struct sockaddr *from, socklen_t *fromlen)
+{
+ CHECK_NULL_PTR(mem);
+ return lwip_recvfrom(s, mem, len, flags, from, fromlen);
+}
+
+ssize_t recvmsg(int s, struct msghdr *message, int flags)
+{
+ CHECK_NULL_PTR(message);
+ if (message->msg_iovlen) {
+ CHECK_NULL_PTR(message->msg_iov);
+ }
+ return lwip_recvmsg(s, message, flags);
+}
+
+ssize_t send(int s, const void *dataptr, size_t size, int flags)
+{
+ CHECK_NULL_PTR(dataptr);
+ return lwip_send(s, dataptr, size, flags);
+}
+
+ssize_t sendmsg(int s, const struct msghdr *message, int flags)
+{
+ return lwip_sendmsg(s, message, flags);
+}
+
+ssize_t sendto(int s, const void *dataptr, size_t size, int flags,
+ const struct sockaddr *to, socklen_t tolen)
+{
+ CHECK_NULL_PTR(dataptr);
+ if (to && tolen < sizeof(*to)) {
+ set_errno(EINVAL);
+ return -1;
+ }
+ return lwip_sendto(s, dataptr, size, flags, to, tolen);
+}
+
+int socket(int domain, int type, int protocol)
+{
+ return lwip_socket(domain, type, protocol);
+}
+
+const char *inet_ntop(int af, const void *src, char *dst, socklen_t size)
+{
+ return lwip_inet_ntop(af, src, dst, size);
+}
+
+int inet_pton(int af, const char *src, void *dst)
+{
+ return lwip_inet_pton(af, src, dst);
+}
+
+#ifndef LWIP_INET_ADDR_FUNC
+in_addr_t inet_addr(const char* cp)
+{
+ return ipaddr_addr(cp);
+}
+#endif
+
+#ifndef LWIP_INET_ATON_FUNC
+int inet_aton(const char* cp, struct in_addr* inp)
+{
+ return ip4addr_aton(cp, (ip4_addr_t*)inp);
+}
+#endif
+
+#ifndef LWIP_INET_NTOA_FUNC
+char* inet_ntoa(struct in_addr in)
+{
+ return ip4addr_ntoa((const ip4_addr_t*)&(in));
+}
+#endif
+
+#endif /* !LWIP_COMPAT_SOCKETS */
+#endif /* LOSCFG_NET_LWIP_SACK */
\ No newline at end of file
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/src/stdio.c b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/src/stdio.c
new file mode 100644
index 00000000..f2182d44
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/src/stdio.c
@@ -0,0 +1,121 @@
+/*
+ * 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
+#ifdef LOSCFG_FS_VFS
+#include
+
+off_t _lseek(int fd, off_t offset, int whence)
+{
+ int ret;
+ struct file *filep = NULL;
+
+ /* Get the file structure corresponding to the file descriptor. */
+ ret = fs_getfilep(fd, &filep);
+ if (ret < 0) {
+ /* The errno value has already been set */
+ return (off_t)-get_errno();
+ }
+
+ /* libc seekdir function should set the whence to SEEK_SET, so we can discard
+ * the whence argument here */
+ if (filep->f_oflags & O_DIRECTORY) {
+ /* defensive coding */
+ if (filep->f_dir == NULL) {
+ return (off_t)-EINVAL;
+ }
+ if (offset == 0) {
+ rewinddir(filep->f_dir);
+ } else {
+ seekdir(filep->f_dir, offset);
+ }
+ ret = telldir(filep->f_dir);
+ if (ret < 0) {
+ return (off_t)-get_errno();
+ }
+ return ret;
+ }
+
+ /* Then let file_seek do the real work */
+ ret = file_seek(filep, offset, whence);
+ if (ret < 0) {
+ return -get_errno();
+ }
+ return ret;
+}
+
+off64_t _lseek64(int fd, int offsetHigh, int offsetLow, off64_t *result, int whence)
+{
+ off64_t ret;
+ struct file *filep = NULL;
+ off64_t offset = ((off64_t)offsetHigh << 32) + (uint)offsetLow; /* 32: offsetHigh is high 32 bits */
+
+ /* Get the file structure corresponding to the file descriptor. */
+ ret = fs_getfilep(fd, &filep);
+ if (ret < 0) {
+ /* The errno value has already been set */
+ return (off64_t)-get_errno();
+ }
+
+ /* libc seekdir function should set the whence to SEEK_SET, so we can discard
+ * the whence argument here */
+ if (filep->f_oflags & O_DIRECTORY) {
+ /* defensive coding */
+ if (filep->f_dir == NULL) {
+ return (off64_t)-EINVAL;
+ }
+ if (offsetLow == 0) {
+ rewinddir(filep->f_dir);
+ } else {
+ seekdir(filep->f_dir, offsetLow);
+ }
+ ret = telldir(filep->f_dir);
+ if (ret < 0) {
+ return (off64_t)-get_errno();
+ }
+ goto out;
+ }
+
+ /* Then let file_seek do the real work */
+ ret = file_seek64(filep, offset, whence);
+ if (ret < 0) {
+ return (off64_t)-get_errno();
+ }
+
+out:
+ *result = ret;
+
+ return 0;
+}
+
+#endif
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/src/stdlib.c b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/src/stdlib.c
new file mode 100644
index 00000000..cbab4f7d
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/src/stdlib.c
@@ -0,0 +1,71 @@
+/*
+ * 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 "los_printf.h"
+#include "los_exc.h"
+
+char *getenv(const char *name)
+{
+ return NULL;
+}
+
+void srand(unsigned s)
+{
+ return srandom(s);
+}
+
+int rand(void)
+{
+ return random();
+}
+
+void _exit(int status)
+{
+ PRINT_ERR("%s NOT SUPPORT\n", __FUNCTION__);
+ errno = ENOSYS;
+ while (1);
+}
+
+void exit(int status)
+{
+ PRINT_ERR("%s NOT SUPPORT\n", __FUNCTION__);
+ errno = ENOSYS;
+ while (1);
+}
+
+void abort(void)
+{
+ LOS_Panic("System was being aborted\n");
+ while (1);
+}
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/src/time.c b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/src/time.c
new file mode 100644
index 00000000..8803b586
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/compat/posix/src/time.c
@@ -0,0 +1,1157 @@
+/*
+ * 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 "time.h"
+#include "stdint.h"
+#include "stdio.h"
+#include "sys/times.h"
+#include "time_posix.h"
+#include "unistd.h"
+#ifdef LOSCFG_SECURITY_CAPABILITY
+#include "capability_api.h"
+#endif
+#include "los_signal.h"
+#ifdef LOSCFG_KERNEL_VDSO
+#include "los_vdso.h"
+#endif
+#ifdef LOSCFG_SECURITY_VID
+#include "vid_api.h"
+#endif
+#include "user_copy.h"
+#include "los_process_pri.h"
+#include "los_swtmr_pri.h"
+#include "los_sys_pri.h"
+
+#define CPUCLOCK_PERTHREAD_MASK 4
+#define CPUCLOCK_ID_OFFSET 3
+
+/*
+ * Do a time package defined return. This requires the error code
+ * to be placed in errno, and if it is non-zero, -1 returned as the
+ * result of the function. This also gives us a place to put any
+ * generic tidyup handling needed for things like signal delivery and
+ * cancellation.
+ */
+#define TIME_RETURN(err) do { \
+ INT32 retVal = 0; \
+ if ((err) != 0) { \
+ retVal = -1; \
+ errno = (err); \
+ } \
+ return retVal; \
+} while (0)
+
+#ifdef LOSCFG_AARCH64
+/*
+ * This two structures originally did't exit,
+ * they added by liteos to support 64bit interfaces on 32bit platform,
+ * in 64bit platform, timeval64 define to timeval which is platform adaptive.
+ */
+#define timeval64 timeval
+#define timespec64 timespec
+#endif
+
+STATIC INLINE BOOL ValidTimeval(const struct timeval *tv)
+{
+ /* Fail a NULL pointer */
+ if (tv == NULL) {
+ return FALSE;
+ }
+
+ /* Fail illegal microseconds values */
+ if ((tv->tv_usec < 0) || (tv->tv_usec >= OS_SYS_US_PER_SECOND) || (tv->tv_sec < 0)) {
+ return FALSE;
+ }
+
+ return TRUE;
+}
+
+STATIC INLINE BOOL ValidTimeval64(const struct timeval64 *tv)
+{
+ /* Fail a NULL pointer */
+ if (tv == NULL) {
+ return FALSE;
+ }
+
+ /* Fail illegal microseconds values */
+ if ((tv->tv_usec < 0) || (tv->tv_usec >= OS_SYS_US_PER_SECOND) || (tv->tv_sec < 0)) {
+ return FALSE;
+ }
+
+ return TRUE;
+}
+
+STATIC INLINE BOOL ValidTimerID(UINT16 swtmrID)
+{
+ /* check timer id */
+ if (swtmrID >= OS_SWTMR_MAX_TIMERID) {
+ return FALSE;
+ }
+
+ /* check owner of this timer */
+ if (OS_SWT_FROM_SID(swtmrID)->uwOwnerPid != LOS_GetCurrProcessID()) {
+ return FALSE;
+ }
+
+ return TRUE;
+}
+
+STATIC SPIN_LOCK_INIT(g_timeSpin);
+STATIC long long g_adjTimeLeft; /* absolute value of adjtime */
+STATIC INT32 g_adjDirection; /* 1, speed up; 0, slow down; */
+
+/* Adjust pacement, nanoseconds per SCHED_CLOCK_INTETRVAL_TICKS ticks */
+STATIC const long long g_adjPacement = (((LOSCFG_BASE_CORE_ADJ_PER_SECOND * SCHED_CLOCK_INTETRVAL_TICKS) /
+ LOSCFG_BASE_CORE_TICK_PER_SECOND) * OS_SYS_NS_PER_US);
+
+/* accumulative time delta from continuous modify, such as adjtime */
+STATIC struct timespec64 g_accDeltaFromAdj;
+/* accumulative time delta from discontinuous modify, such as settimeofday */
+STATIC struct timespec64 g_accDeltaFromSet;
+
+VOID OsAdjTime(VOID)
+{
+ UINT32 intSave;
+
+ LOS_SpinLockSave(&g_timeSpin, &intSave);
+ if (!g_adjTimeLeft) {
+ LOS_SpinUnlockRestore(&g_timeSpin, intSave);
+ return;
+ }
+
+ if (g_adjTimeLeft > g_adjPacement) {
+ if (g_adjDirection) {
+ if ((g_accDeltaFromAdj.tv_nsec + g_adjPacement) >= OS_SYS_NS_PER_SECOND) {
+ g_accDeltaFromAdj.tv_sec++;
+ g_accDeltaFromAdj.tv_nsec = (g_accDeltaFromAdj.tv_nsec + g_adjPacement) % OS_SYS_NS_PER_SECOND;
+ } else {
+ g_accDeltaFromAdj.tv_nsec = g_accDeltaFromAdj.tv_nsec + g_adjPacement;
+ }
+ } else {
+ if ((g_accDeltaFromAdj.tv_nsec - g_adjPacement) < 0) {
+ g_accDeltaFromAdj.tv_sec--;
+ g_accDeltaFromAdj.tv_nsec = g_accDeltaFromAdj.tv_nsec - g_adjPacement + OS_SYS_NS_PER_SECOND;
+ } else {
+ g_accDeltaFromAdj.tv_nsec = g_accDeltaFromAdj.tv_nsec - g_adjPacement;
+ }
+ }
+
+ g_adjTimeLeft -= g_adjPacement;
+ } else {
+ if (g_adjDirection) {
+ if ((g_accDeltaFromAdj.tv_nsec + g_adjTimeLeft) >= OS_SYS_NS_PER_SECOND) {
+ g_accDeltaFromAdj.tv_sec++;
+ g_accDeltaFromAdj.tv_nsec = (g_accDeltaFromAdj.tv_nsec + g_adjTimeLeft) % OS_SYS_NS_PER_SECOND;
+ } else {
+ g_accDeltaFromAdj.tv_nsec = g_accDeltaFromAdj.tv_nsec + g_adjTimeLeft;
+ }
+ } else {
+ if ((g_accDeltaFromAdj.tv_nsec - g_adjTimeLeft) < 0) {
+ g_accDeltaFromAdj.tv_sec--;
+ g_accDeltaFromAdj.tv_nsec = g_accDeltaFromAdj.tv_nsec - g_adjTimeLeft + OS_SYS_NS_PER_SECOND;
+ } else {
+ g_accDeltaFromAdj.tv_nsec = g_accDeltaFromAdj.tv_nsec - g_adjTimeLeft;
+ }
+ }
+
+ g_adjTimeLeft = 0;
+ }
+ LOS_SpinUnlockRestore(&g_timeSpin, intSave);
+ return;
+}
+
+/*
+ * Function: adjtime
+ * Description: correct the time to synchronize the system clock.
+ * Input: delta - The amount of time by which the clock is to be adjusted.
+ * Output: oldDelta - the amount of time remaining from any previous adjustment that has not yet been completed.
+ * Return: On success, returns 0. On failure, -1 is returned, and errno is set to indicate the error.
+ */
+int adjtime(const struct timeval *delta, struct timeval *oldDelta)
+{
+ UINT32 intSave;
+ LOS_SpinLockSave(&g_timeSpin, &intSave);
+ /* return the amount of time remaining from any previous adjustment that has not yet been completed. */
+ if (oldDelta != NULL) {
+ if (g_adjDirection == 1) {
+ oldDelta->tv_sec = g_adjTimeLeft / OS_SYS_NS_PER_SECOND;
+ oldDelta->tv_usec = (g_adjTimeLeft % OS_SYS_NS_PER_SECOND) / OS_SYS_NS_PER_US;
+ } else {
+ oldDelta->tv_sec = -(g_adjTimeLeft / OS_SYS_NS_PER_SECOND);
+ oldDelta->tv_usec = -((g_adjTimeLeft % OS_SYS_NS_PER_SECOND) / OS_SYS_NS_PER_US);
+ }
+ }
+
+ if ((delta == NULL) || ((delta->tv_sec == 0) && (delta->tv_usec == 0))) {
+ LOS_SpinUnlockRestore(&g_timeSpin, intSave);
+ return 0;
+ }
+
+ if ((delta->tv_usec > OS_SYS_US_PER_SECOND) || (delta->tv_usec < -OS_SYS_US_PER_SECOND)) {
+ LOS_SpinUnlockRestore(&g_timeSpin, intSave);
+ TIME_RETURN(EINVAL);
+ }
+
+ /*
+ * 2: in the glibc implementation, delta must be less than or equal to (INT_MAX / 1000000 - 2) and
+ * greater than or equal to (INT_MIN / 1000000 + 2)
+ */
+ if ((delta->tv_sec < (INT_MIN / OS_SYS_US_PER_SECOND + 2)) ||
+ (delta->tv_sec > (INT_MAX / OS_SYS_US_PER_SECOND + 2))) {
+ LOS_SpinUnlockRestore(&g_timeSpin, intSave);
+ TIME_RETURN(EINVAL);
+ }
+
+ g_adjTimeLeft = (INT64)delta->tv_sec * OS_SYS_NS_PER_SECOND + delta->tv_usec * OS_SYS_NS_PER_US;
+ if (g_adjTimeLeft > 0) {
+ g_adjDirection = 1;
+ } else {
+ g_adjDirection = 0;
+ g_adjTimeLeft = -g_adjTimeLeft;
+ }
+
+ LOS_SpinUnlockRestore(&g_timeSpin, intSave);
+ return 0;
+}
+
+STATIC INLINE struct timespec64 OsTimeSpecAdd(const struct timespec64 t1, const struct timespec64 t2)
+{
+ struct timespec64 ret = {0};
+
+ ret.tv_sec = t1.tv_sec + t2.tv_sec;
+ ret.tv_nsec = t1.tv_nsec + t2.tv_nsec;
+ if (ret.tv_nsec >= OS_SYS_NS_PER_SECOND) {
+ ret.tv_sec += 1;
+ ret.tv_nsec -= OS_SYS_NS_PER_SECOND;
+ } else if (ret.tv_nsec < 0L) {
+ ret.tv_sec -= 1;
+ ret.tv_nsec += OS_SYS_NS_PER_SECOND;
+ }
+
+ return ret;
+}
+
+STATIC INLINE struct timespec64 OsTimeSpecSub(const struct timespec64 t1, const struct timespec64 t2)
+{
+ struct timespec64 ret = {0};
+
+ ret.tv_sec = t1.tv_sec - t2.tv_sec;
+ ret.tv_nsec = t1.tv_nsec - t2.tv_nsec;
+ if (ret.tv_nsec < 0) {
+ ret.tv_sec -= 1;
+ ret.tv_nsec += OS_SYS_NS_PER_SECOND;
+ }
+
+ return ret;
+}
+
+STATIC VOID OsGetHwTime(struct timespec64 *hwTime)
+{
+ UINT64 nowNsec;
+
+ nowNsec = LOS_CurrNanosec();
+ hwTime->tv_sec = nowNsec / OS_SYS_NS_PER_SECOND;
+ hwTime->tv_nsec = nowNsec - hwTime->tv_sec * OS_SYS_NS_PER_SECOND;
+}
+
+STATIC INT32 OsSetTimeOfDay(const struct timeval64 *tv, const struct timezone *tz)
+{
+ UINT32 intSave;
+ struct timespec64 setTime = {0};
+ struct timespec64 hwTime = {0};
+ struct timespec64 realTime = {0};
+ struct timespec64 tmp = {0};
+
+#ifdef LOSCFG_SECURITY_CAPABILITY
+ if (!IsCapPermit(CAP_SET_TIMEOFDAY)) {
+ TIME_RETURN(EPERM);
+ }
+#endif
+
+ (VOID)tz;
+ OsGetHwTime(&hwTime);
+ setTime.tv_sec = tv->tv_sec;
+ setTime.tv_nsec = tv->tv_usec * OS_SYS_NS_PER_US;
+
+ LOS_SpinLockSave(&g_timeSpin, &intSave);
+ /* stop on-going continuous adjusement */
+ if (g_adjTimeLeft) {
+ g_adjTimeLeft = 0;
+ }
+ realTime = OsTimeSpecAdd(hwTime, g_accDeltaFromAdj);
+ realTime = OsTimeSpecAdd(realTime, g_accDeltaFromSet);
+
+ tmp = OsTimeSpecSub(setTime, realTime);
+ g_accDeltaFromSet = OsTimeSpecAdd(g_accDeltaFromSet, tmp);
+
+ LOS_SpinUnlockRestore(&g_timeSpin, intSave);
+
+ return 0;
+}
+
+int settimeofday(const struct timeval *tv, const struct timezone *tz)
+{
+ struct timeval64 stTimeVal64 = {0};
+
+ if (!ValidTimeval(tv)) {
+ TIME_RETURN(EINVAL);
+ }
+
+ stTimeVal64.tv_sec = tv->tv_sec;
+ stTimeVal64.tv_usec = tv->tv_usec;
+
+ return OsSetTimeOfDay(&stTimeVal64, tz);
+}
+
+#ifndef LOSCFG_AARCH64
+int settimeofday64(const struct timeval64 *tv, const struct timezone *tz)
+{
+ if (!ValidTimeval64(tv)) {
+ TIME_RETURN(EINVAL);
+ }
+
+ return OsSetTimeOfDay(tv, tz);
+}
+#endif
+
+int setlocalseconds(int seconds)
+{
+ struct timeval tv = {0};
+
+ tv.tv_sec = seconds;
+ tv.tv_usec = 0;
+
+ return settimeofday(&tv, NULL);
+}
+
+STATIC INT32 OsGetTimeOfDay(struct timeval64 *tv, struct timezone *tz)
+{
+ UINT32 intSave;
+
+ (VOID)tz;
+ struct timespec64 hwTime = {0};
+ struct timespec64 realTime = {0};
+
+ OsGetHwTime(&hwTime);
+
+ LOS_SpinLockSave(&g_timeSpin, &intSave);
+ realTime = OsTimeSpecAdd(hwTime, g_accDeltaFromAdj);
+ realTime = OsTimeSpecAdd(realTime, g_accDeltaFromSet);
+ LOS_SpinUnlockRestore(&g_timeSpin, intSave);
+
+ tv->tv_sec = realTime.tv_sec;
+ tv->tv_usec = realTime.tv_nsec / OS_SYS_NS_PER_US;
+
+ if (tv->tv_sec < 0) {
+ TIME_RETURN(EINVAL);
+ }
+ return 0;
+}
+
+#ifndef LOSCFG_AARCH64
+int gettimeofday64(struct timeval64 *tv, struct timezone *tz)
+{
+ if (tv == NULL) {
+ TIME_RETURN(EINVAL);
+ }
+
+ return OsGetTimeOfDay(tv, tz);
+}
+#endif
+
+int gettimeofday(struct timeval *tv, struct timezone *tz)
+{
+ struct timeval64 stTimeVal64 = {0};
+
+ if (tv == NULL) {
+ TIME_RETURN(EINVAL);
+ }
+
+ if (OsGetTimeOfDay(&stTimeVal64, tz) == -1) {
+ return -1;
+ }
+
+#ifdef LOSCFG_AARCH64
+ tv->tv_sec = stTimeVal64.tv_sec;
+ tv->tv_usec = stTimeVal64.tv_usec;
+#else
+ if (stTimeVal64.tv_sec > (long long)LONG_MAX) {
+ return -1;
+ }
+ tv->tv_sec = (time_t)stTimeVal64.tv_sec;
+ tv->tv_usec = (suseconds_t)stTimeVal64.tv_usec;
+#endif
+
+ return 0;
+}
+
+int clock_settime(clockid_t clockID, const struct timespec *tp)
+{
+ struct timeval tv = {0};
+
+ switch (clockID) {
+ case CLOCK_REALTIME:
+ /* we only support the realtime clock currently */
+ break;
+ case CLOCK_MONOTONIC_COARSE:
+ case CLOCK_REALTIME_COARSE:
+ case CLOCK_MONOTONIC_RAW:
+ case CLOCK_PROCESS_CPUTIME_ID:
+ case CLOCK_BOOTTIME:
+ case CLOCK_REALTIME_ALARM:
+ case CLOCK_BOOTTIME_ALARM:
+ case CLOCK_TAI:
+ case CLOCK_THREAD_CPUTIME_ID:
+ TIME_RETURN(ENOTSUP);
+ case CLOCK_MONOTONIC:
+ default:
+ TIME_RETURN(EINVAL);
+ }
+
+ if (!ValidTimeSpec(tp)) {
+ TIME_RETURN(EINVAL);
+ }
+
+#ifdef LOSCFG_SECURITY_CAPABILITY
+ if (!IsCapPermit(CAP_CLOCK_SETTIME)) {
+ TIME_RETURN(EPERM);
+ }
+#endif
+
+ tv.tv_sec = tp->tv_sec;
+ tv.tv_usec = tp->tv_nsec / OS_SYS_NS_PER_US;
+ return settimeofday(&tv, NULL);
+}
+
+#ifdef LOSCFG_KERNEL_CPUP
+inline UINT32 GetTidFromClockID(clockid_t clockID)
+{
+ // In musl/src/thread/pthread_getcpuclockid.c, we know 'clockid = (-tid - 1) * 8 + 6'
+ UINT32 tid = -(clockID - 6) / 8 - 1; // 6 8 1 inverse operation from clockID to tid
+ return tid;
+}
+
+inline const pid_t GetPidFromClockID(clockid_t clockID)
+{
+ // In musl/src/time/clock_getcpuclockid.c, we know 'clockid = (-pid - 1) * 8 + 2'
+ const pid_t pid = -(clockID - 2) / 8 - 1; // 2 8 1 inverse operation from clockID to pid
+ return pid;
+}
+
+static int PthreadGetCputime(clockid_t clockID, struct timespec *ats)
+{
+ uint64_t runtime;
+ UINT32 intSave;
+ UINT32 tid = GetTidFromClockID(clockID);
+
+ if (OS_TID_CHECK_INVALID(tid)) {
+ return -EINVAL;
+ }
+
+ LosTaskCB *task = OsGetTaskCB(tid);
+
+ if (OsCurrTaskGet()->processID != task->processID) {
+ return -EINVAL;
+ }
+
+ SCHEDULER_LOCK(intSave);
+ runtime = task->taskCpup.allTime;
+ SCHEDULER_UNLOCK(intSave);
+
+ ats->tv_sec = runtime / OS_SYS_NS_PER_SECOND;
+ ats->tv_nsec = runtime % OS_SYS_NS_PER_SECOND;
+
+ return 0;
+}
+
+static int ProcessGetCputime(clockid_t clockID, struct timespec *ats)
+{
+ UINT64 runtime;
+ UINT32 intSave;
+ const pid_t pid = GetPidFromClockID(clockID);
+ LosProcessCB *spcb = NULL;
+
+ if (OsProcessIDUserCheckInvalid(pid) || pid < 0) {
+ return -EINVAL;
+ }
+
+ spcb = OS_PCB_FROM_PID(pid);
+ if (OsProcessIsUnused(spcb)) {
+ return -EINVAL;
+ }
+
+ SCHEDULER_LOCK(intSave);
+ if (spcb->processCpup == NULL) {
+ SCHEDULER_UNLOCK(intSave);
+ return -EINVAL;
+ }
+ runtime = spcb->processCpup->allTime;
+ SCHEDULER_UNLOCK(intSave);
+
+ ats->tv_sec = runtime / OS_SYS_NS_PER_SECOND;
+ ats->tv_nsec = runtime % OS_SYS_NS_PER_SECOND;
+
+ return 0;
+}
+
+static int GetCputime(clockid_t clockID, struct timespec *tp)
+{
+ int ret;
+
+ if (clockID >= 0) {
+ return -EINVAL;
+ }
+
+ if ((UINT32)clockID & CPUCLOCK_PERTHREAD_MASK) {
+ ret = PthreadGetCputime(clockID, tp);
+ } else {
+ ret = ProcessGetCputime(clockID, tp);
+ }
+
+ return ret;
+}
+
+static int CheckClock(const clockid_t clockID)
+{
+ int error = 0;
+ const pid_t pid = GetPidFromClockID(clockID);
+
+ if (!((UINT32)clockID & CPUCLOCK_PERTHREAD_MASK)) {
+ LosProcessCB *spcb = NULL;
+ if (OsProcessIDUserCheckInvalid(pid) || pid < 0) {
+ return -EINVAL;
+ }
+ spcb = OS_PCB_FROM_PID(pid);
+ if (OsProcessIsUnused(spcb)) {
+ error = -EINVAL;
+ }
+ } else {
+ error = -EINVAL;
+ }
+
+ return error;
+}
+
+static int CpuClockGetres(const clockid_t clockID, struct timespec *tp)
+{
+ if (clockID > 0) {
+ return -EINVAL;
+ }
+
+ int error = CheckClock(clockID);
+ if (!error) {
+ error = ProcessGetCputime(clockID, tp);
+ }
+
+ return error;
+}
+#endif
+
+int clock_gettime(clockid_t clockID, struct timespec *tp)
+{
+ UINT32 intSave;
+ struct timespec64 tmp = {0};
+ struct timespec64 hwTime = {0};
+
+ if (clockID > MAX_CLOCKS) {
+ goto ERROUT;
+ }
+
+ if (tp == NULL) {
+ goto ERROUT;
+ }
+
+ OsGetHwTime(&hwTime);
+
+ switch (clockID) {
+ case CLOCK_MONOTONIC_RAW:
+ tp->tv_sec = hwTime.tv_sec;
+ tp->tv_nsec = hwTime.tv_nsec;
+ break;
+ case CLOCK_MONOTONIC:
+ LOS_SpinLockSave(&g_timeSpin, &intSave);
+ tmp = OsTimeSpecAdd(hwTime, g_accDeltaFromAdj);
+ LOS_SpinUnlockRestore(&g_timeSpin, intSave);
+ tp->tv_sec = tmp.tv_sec;
+ tp->tv_nsec = tmp.tv_nsec;
+ break;
+ case CLOCK_REALTIME:
+ LOS_SpinLockSave(&g_timeSpin, &intSave);
+ tmp = OsTimeSpecAdd(hwTime, g_accDeltaFromAdj);
+ tmp = OsTimeSpecAdd(tmp, g_accDeltaFromSet);
+ LOS_SpinUnlockRestore(&g_timeSpin, intSave);
+ tp->tv_sec = tmp.tv_sec;
+ tp->tv_nsec = tmp.tv_nsec;
+ break;
+ case CLOCK_MONOTONIC_COARSE:
+ case CLOCK_REALTIME_COARSE:
+ case CLOCK_THREAD_CPUTIME_ID:
+ case CLOCK_PROCESS_CPUTIME_ID:
+ case CLOCK_BOOTTIME:
+ case CLOCK_REALTIME_ALARM:
+ case CLOCK_BOOTTIME_ALARM:
+ case CLOCK_TAI:
+ TIME_RETURN(ENOTSUP);
+ default:
+ {
+#ifdef LOSCFG_KERNEL_CPUP
+ int ret = GetCputime(clockID, tp);
+ TIME_RETURN(-ret);
+#else
+ TIME_RETURN(EINVAL);
+#endif
+ }
+ }
+
+ return 0;
+
+ ERROUT:
+ TIME_RETURN(EINVAL);
+}
+
+int clock_getres(clockid_t clockID, struct timespec *tp)
+{
+ if (tp == NULL) {
+ TIME_RETURN(EINVAL);
+ }
+
+ switch (clockID) {
+ case CLOCK_MONOTONIC_RAW:
+ case CLOCK_MONOTONIC:
+ case CLOCK_REALTIME:
+ /* the accessible rtc resolution */
+ tp->tv_nsec = OS_SYS_NS_PER_US; /* the precision of clock_gettime is 1us */
+ tp->tv_sec = 0;
+ break;
+ case CLOCK_MONOTONIC_COARSE:
+ case CLOCK_REALTIME_COARSE:
+ /* the clock coarse resolution, supported by vdso.
+ * the precision of clock_gettime is 1tick */
+ tp->tv_nsec = OS_SYS_NS_PER_SECOND / LOSCFG_BASE_CORE_TICK_PER_SECOND;
+ tp->tv_sec = 0;
+ break;
+ case CLOCK_THREAD_CPUTIME_ID:
+ case CLOCK_PROCESS_CPUTIME_ID:
+ case CLOCK_BOOTTIME:
+ case CLOCK_REALTIME_ALARM:
+ case CLOCK_BOOTTIME_ALARM:
+ case CLOCK_TAI:
+ TIME_RETURN(ENOTSUP);
+ default:
+#ifdef LOSCFG_KERNEL_CPUP
+ {
+ int ret = CpuClockGetres(clockID, tp);
+ TIME_RETURN(-ret);
+ }
+#else
+ TIME_RETURN(EINVAL);
+#endif
+ }
+
+ TIME_RETURN(0);
+}
+
+int clock_nanosleep(clockid_t clk, int flags, const struct timespec *req, struct timespec *rem)
+{
+ switch (clk) {
+ case CLOCK_REALTIME:
+ if (flags == 0) {
+ /* we only support the realtime clock currently */
+ return nanosleep(req, rem);
+ }
+ /* fallthrough */
+ case CLOCK_MONOTONIC_COARSE:
+ case CLOCK_REALTIME_COARSE:
+ case CLOCK_MONOTONIC_RAW:
+ case CLOCK_MONOTONIC:
+ case CLOCK_PROCESS_CPUTIME_ID:
+ case CLOCK_BOOTTIME:
+ case CLOCK_REALTIME_ALARM:
+ case CLOCK_BOOTTIME_ALARM:
+ case CLOCK_TAI:
+ if (flags == 0 || flags == TIMER_ABSTIME) {
+ TIME_RETURN(ENOTSUP);
+ }
+ /* fallthrough */
+ case CLOCK_THREAD_CPUTIME_ID:
+ default:
+ TIME_RETURN(EINVAL);
+ }
+
+ TIME_RETURN(0);
+}
+
+typedef struct {
+ int sigev_signo;
+ pid_t pid;
+ unsigned int tid;
+ union sigval sigev_value;
+} swtmr_proc_arg;
+
+static VOID SwtmrProc(UINTPTR tmrArg)
+{
+ INT32 sig, ret;
+ UINT32 intSave;
+ pid_t pid;
+ siginfo_t info;
+ LosTaskCB *stcb = NULL;
+
+ swtmr_proc_arg *arg = (swtmr_proc_arg *)tmrArg;
+ OS_GOTO_EXIT_IF(arg == NULL, EINVAL);
+
+ sig = arg->sigev_signo;
+ pid = arg->pid;
+ OS_GOTO_EXIT_IF(!GOOD_SIGNO(sig), EINVAL);
+
+ /* Create the siginfo structure */
+ info.si_signo = sig;
+ info.si_code = SI_TIMER;
+ info.si_value.sival_ptr = arg->sigev_value.sival_ptr;
+
+ /* Send signals to threads or processes */
+ if (arg->tid > 0) {
+ /* Make sure that the para is valid */
+ OS_GOTO_EXIT_IF(OS_TID_CHECK_INVALID(arg->tid), EINVAL);
+ stcb = OsGetTaskCB(arg->tid);
+ ret = OsUserProcessOperatePermissionsCheck(stcb, stcb->processID);
+ OS_GOTO_EXIT_IF(ret != LOS_OK, -ret);
+
+ /* Dispatch the signal to thread, bypassing normal task group thread
+ * dispatch rules. */
+ SCHEDULER_LOCK(intSave);
+ ret = OsTcbDispatch(stcb, &info);
+ SCHEDULER_UNLOCK(intSave);
+ OS_GOTO_EXIT_IF(ret != LOS_OK, -ret);
+ } else {
+ /* Make sure that the para is valid */
+ OS_GOTO_EXIT_IF(pid <= 0 || OS_PID_CHECK_INVALID(pid), EINVAL);
+ /* Dispatch the signal to process */
+ SCHEDULER_LOCK(intSave);
+ OsDispatch(pid, &info, OS_USER_KILL_PERMISSION);
+ SCHEDULER_UNLOCK(intSave);
+ }
+ return;
+EXIT:
+ PRINT_ERR("Dispatch signals failed!, ret: %d\r\n", ret);
+ return;
+}
+
+int OsTimerCreate(clockid_t clockID, struct ksigevent *evp, timer_t *timerID)
+{
+ UINT32 ret;
+ UINT16 swtmrID;
+ swtmr_proc_arg *arg = NULL;
+ int signo;
+#ifdef LOSCFG_SECURITY_VID
+ UINT16 vid;
+#endif
+
+ if ((clockID != CLOCK_REALTIME) || (timerID == NULL)) {
+ errno = EINVAL;
+ return -1;
+ }
+
+ signo = evp ? evp->sigev_signo : SIGALRM;
+ if (signo > SIGRTMAX || signo < 1) {
+ errno = EINVAL;
+ return -1;
+ }
+ if (evp && (evp->sigev_notify != SIGEV_SIGNAL && evp->sigev_notify != SIGEV_THREAD_ID)) {
+ errno = ENOTSUP;
+ return -1;
+ }
+
+ arg = (swtmr_proc_arg *)malloc(sizeof(swtmr_proc_arg));
+ if (arg == NULL) {
+ errno = ENOMEM;
+ return -1;
+ }
+
+ arg->tid = evp ? evp->sigev_tid : 0;
+ arg->sigev_signo = signo;
+ arg->pid = LOS_GetCurrProcessID();
+ arg->sigev_value.sival_ptr = evp ? evp->sigev_value.sival_ptr : NULL;
+ ret = LOS_SwtmrCreate(1, LOS_SWTMR_MODE_ONCE, SwtmrProc, &swtmrID, (UINTPTR)arg);
+ if (ret != LOS_OK) {
+ errno = (ret == LOS_ERRNO_SWTMR_MAXSIZE) ? EAGAIN : EINVAL;
+ free(arg);
+ return -1;
+ }
+
+#ifdef LOSCFG_SECURITY_VID
+ vid = AddNodeByRid(swtmrID);
+ if (vid == MAX_INVALID_TIMER_VID) {
+ free(arg);
+ (VOID)LOS_SwtmrDelete(swtmrID);
+ return -1;
+ }
+ swtmrID = vid;
+#endif
+ *timerID = (timer_t)(UINTPTR)swtmrID;
+ return 0;
+}
+
+int timer_delete(timer_t timerID)
+{
+ UINT16 swtmrID = (UINT16)(UINTPTR)timerID;
+ VOID *arg = NULL;
+
+#ifdef LOSCFG_SECURITY_VID
+ swtmrID = GetRidByVid(swtmrID);
+#endif
+ if (OS_INT_ACTIVE || !ValidTimerID(swtmrID)) {
+ goto ERROUT;
+ }
+
+ arg = (VOID *)OS_SWT_FROM_SID(swtmrID)->uwArg;
+ if (LOS_SwtmrDelete(swtmrID)) {
+ goto ERROUT;
+ }
+ if (arg != NULL) {
+ free(arg);
+ }
+
+#ifdef LOSCFG_SECURITY_VID
+ RemoveNodeByVid((UINT16)(UINTPTR)timerID);
+#endif
+ return 0;
+
+ERROUT:
+ errno = EINVAL;
+ return -1;
+}
+
+int timer_settime(timer_t timerID, int flags,
+ const struct itimerspec *value, /* new value */
+ struct itimerspec *oldValue) /* old value to return, always 0 */
+{
+ UINT16 swtmrID = (UINT16)(UINTPTR)timerID;
+ SWTMR_CTRL_S *swtmr = NULL;
+ UINT32 interval, expiry, ret;
+ UINT32 intSave;
+
+ if (flags != 0) {
+ /* flags not supported currently */
+ errno = ENOSYS;
+ return -1;
+ }
+
+#ifdef LOSCFG_SECURITY_VID
+ swtmrID = GetRidByVid(swtmrID);
+#endif
+ if ((value == NULL) || OS_INT_ACTIVE || !ValidTimerID(swtmrID)) {
+ errno = EINVAL;
+ return -1;
+ }
+
+ if (!ValidTimeSpec(&value->it_value) || !ValidTimeSpec(&value->it_interval)) {
+ errno = EINVAL;
+ return -1;
+ }
+
+ if (oldValue) {
+ (VOID)timer_gettime(timerID, oldValue);
+ }
+
+ swtmr = OS_SWT_FROM_SID(swtmrID);
+ ret = LOS_SwtmrStop(swtmr->usTimerID);
+ if ((ret != LOS_OK) && (ret != LOS_ERRNO_SWTMR_NOT_STARTED)) {
+ errno = EINVAL;
+ return -1;
+ }
+
+ expiry = OsTimeSpec2Tick(&value->it_value);
+ interval = OsTimeSpec2Tick(&value->it_interval);
+
+ LOS_SpinLockSave(&g_swtmrSpin, &intSave);
+ swtmr->ucMode = interval ? LOS_SWTMR_MODE_OPP : LOS_SWTMR_MODE_NO_SELFDELETE;
+ swtmr->uwExpiry = expiry + !!expiry; // PS: skip the first tick because it is NOT a full tick.
+ swtmr->uwInterval = interval;
+ swtmr->uwOverrun = 0;
+ LOS_SpinUnlockRestore(&g_swtmrSpin, intSave);
+
+ 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)) {
+ 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;
+
+#ifdef LOSCFG_SECURITY_VID
+ swtmrID = GetRidByVid(swtmrID);
+#endif
+ 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;
+ SWTMR_CTRL_S *swtmr = NULL;
+ INT32 overRun;
+
+#ifdef LOSCFG_SECURITY_VID
+ swtmrID = GetRidByVid(swtmrID);
+#endif
+ if (!ValidTimerID(swtmrID)) {
+ errno = EINVAL;
+ return -1;
+ }
+
+ swtmr = OS_SWT_FROM_SID(swtmrID);
+ if (swtmr->usTimerID >= OS_SWTMR_MAX_TIMERID) {
+ errno = EINVAL;
+ return -1;
+ }
+
+ overRun = (INT32)(swtmr->uwOverrun);
+ return (overRun > DELAYTIMER_MAX) ? DELAYTIMER_MAX : overRun;
+}
+
+STATIC INT32 DoNanoSleep(UINT64 nanoseconds)
+{
+ UINT32 ret;
+
+ ret = LOS_TaskDelay(OsNS2Tick(nanoseconds));
+ if (ret == LOS_OK || ret == LOS_ERRNO_TSK_YIELD_NOT_ENOUGH_TASK) {
+ return 0;
+ }
+ return -1;
+}
+
+int usleep(unsigned useconds)
+{
+ return DoNanoSleep((UINT64)useconds * OS_SYS_NS_PER_US);
+}
+
+int nanosleep(const struct timespec *rqtp, struct timespec *rmtp)
+{
+ UINT64 nanoseconds;
+ INT32 ret = -1;
+
+ (VOID)rmtp;
+ /* expire time */
+
+ if (!ValidTimeSpec(rqtp)) {
+ errno = EINVAL;
+ return ret;
+ }
+
+ nanoseconds = (UINT64)rqtp->tv_sec * OS_SYS_NS_PER_SECOND + rqtp->tv_nsec;
+
+ return DoNanoSleep(nanoseconds);
+}
+
+unsigned int sleep(unsigned int seconds)
+{
+ return DoNanoSleep((UINT64)seconds * OS_SYS_NS_PER_SECOND);
+}
+
+double difftime(time_t time2, time_t time1)
+{
+ return (double)(time2 - time1);
+}
+
+clock_t clock(VOID)
+{
+ clock_t clockMsec;
+ UINT64 nowNsec;
+
+ nowNsec = LOS_CurrNanosec();
+ clockMsec = (clock_t)(nowNsec / (OS_SYS_NS_PER_SECOND / CLOCKS_PER_SEC));
+
+ return clockMsec;
+}
+
+clock_t times(struct tms *buf)
+{
+ clock_t clockTick = -1;
+
+ (void)buf;
+ set_errno(ENOSYS);
+
+ return clockTick;
+}
+
+int setitimer(int which, const struct itimerval *value, struct itimerval *ovalue)
+{
+ UINT32 intSave;
+ LosTaskCB *taskCB = OS_TCB_FROM_TID(LOS_CurTaskIDGet());
+ LosProcessCB *processCB = OS_PCB_FROM_PID(taskCB->processID);
+ timer_t timerID = 0;
+ struct itimerspec spec;
+ struct itimerspec ospec;
+ int ret = LOS_OK;
+
+ /* we only support the realtime clock timer currently */
+ if (which != ITIMER_REAL || !value) {
+ set_errno(EINVAL);
+ return -1;
+ }
+
+ /* To avoid creating an invalid timer after the timer has already been create */
+ if (processCB->timerID == (timer_t)(UINTPTR)MAX_INVALID_TIMER_VID) {
+ ret = OsTimerCreate(CLOCK_REALTIME, NULL, &timerID);
+ if (ret != LOS_OK) {
+ return ret;
+ }
+ }
+
+ /* The initialization of this global timer must be in spinlock
+ * OsTimerCreate cannot be located in spinlock.
+ */
+ SCHEDULER_LOCK(intSave);
+ if (processCB->timerID == (timer_t)(UINTPTR)MAX_INVALID_TIMER_VID) {
+ processCB->timerID = timerID;
+ SCHEDULER_UNLOCK(intSave);
+ } else {
+ SCHEDULER_UNLOCK(intSave);
+ if (timerID) {
+ timer_delete(timerID);
+ }
+ }
+
+ if (!ValidTimeval(&value->it_value) || !ValidTimeval(&value->it_interval)) {
+ set_errno(EINVAL);
+ return -1;
+ }
+
+ TIMEVAL_TO_TIMESPEC(&value->it_value, &spec.it_value);
+ TIMEVAL_TO_TIMESPEC(&value->it_interval, &spec.it_interval);
+
+ ret = timer_settime(processCB->timerID, 0, &spec, ovalue ? &ospec : NULL);
+ if (ret == LOS_OK && ovalue) {
+ TIMESPEC_TO_TIMEVAL(&ovalue->it_value, &ospec.it_value);
+ TIMESPEC_TO_TIMEVAL(&ovalue->it_interval, &ospec.it_interval);
+ }
+
+ return ret;
+}
+
+int getitimer(int which, struct itimerval *value)
+{
+ LosTaskCB *taskCB = OS_TCB_FROM_TID(LOS_CurTaskIDGet());
+ LosProcessCB *processCB = OS_PCB_FROM_PID(taskCB->processID);
+ struct itimerspec spec = {};
+
+ int ret = LOS_OK;
+
+ /* we only support the realtime clock timer currently */
+ if (which != ITIMER_REAL || !value) {
+ set_errno(EINVAL);
+ return -1;
+ }
+
+ if (processCB->timerID != (timer_t)(UINTPTR)MAX_INVALID_TIMER_VID) {
+ ret = timer_gettime(processCB->timerID, &spec);
+ }
+
+ if (ret == LOS_OK) {
+ TIMESPEC_TO_TIMEVAL(&value->it_value, &spec.it_value);
+ TIMESPEC_TO_TIMEVAL(&value->it_interval, &spec.it_interval);
+ }
+
+ return ret;
+}
+
+#ifdef LOSCFG_KERNEL_VDSO
+VOID OsVdsoTimeGet(VdsoDataPage *vdsoDataPage)
+{
+ UINT32 intSave;
+ struct timespec64 tmp = {0};
+ struct timespec64 hwTime = {0};
+
+ if (vdsoDataPage == NULL) {
+ return;
+ }
+
+ OsGetHwTime(&hwTime);
+
+ LOS_SpinLockSave(&g_timeSpin, &intSave);
+ tmp = OsTimeSpecAdd(hwTime, g_accDeltaFromAdj);
+ vdsoDataPage->monoTimeSec = tmp.tv_sec;
+ vdsoDataPage->monoTimeNsec = tmp.tv_nsec;
+
+ tmp = OsTimeSpecAdd(tmp, g_accDeltaFromSet);
+ vdsoDataPage->realTimeSec = tmp.tv_sec;
+ vdsoDataPage->realTimeNsec = tmp.tv_nsec;
+ LOS_SpinUnlockRestore(&g_timeSpin, intSave);
+}
+#endif
+
+time_t time(time_t *t)
+{
+ struct timeval tp;
+ int ret;
+
+ /* Get the current time from the system */
+ ret = gettimeofday(&tp, (struct timezone *)NULL);
+ if (ret == LOS_OK) {
+ /* Return the seconds since the epoch */
+ if (t) {
+ *t = tp.tv_sec;
+ }
+ return tp.tv_sec;
+ }
+ return (time_t)OS_ERROR;
+}
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/config.mk b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/config.mk
new file mode 100644
index 00000000..8007d9ed
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/config.mk
@@ -0,0 +1,68 @@
+# 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.
+
+############### this is a makefile that you can config it ###############
+-include $(LITEOSTOPDIR)/tools/build/mk/los_config.mk
+##### liteos tables -u ldflags #####
+-include $(LITEOSTOPDIR)/tools/build/mk/liteos_tables_ldflags.mk
+
+LITEOS_COPTS := $(LITEOS_COPTS_DEBUG) $(LITEOS_COPTS_BASE) \
+ $(LITEOS_COPTS_EXTRA) $(LITEOS_CORE_COPTS)
+LITEOS_CXXOPTS := $(LITEOS_CXXOPTS_BASE)
+LITEOS_INCLUDE := $(LITEOS_KERNEL_INCLUDE) $(LITEOS_EXTKERNEL_INCLUDE) \
+ $(LITEOS_COMPAT_INCLUDE) $(LITEOS_FS_INCLUDE) \
+ $(LITEOS_NET_INCLUDE) $(LITEOS_LIB_INCLUDE) \
+ $(LITEOS_DRIVERS_INCLUDE) $(LITEOS_TOOLS_DEBUG_INCLUDE) \
+ $(LITEOS_PLATFORM_INCLUDE) $(LITEOS_DFX_INCLUDE) \
+ $(LITEOS_SECURITY_INCLUDE)
+LITEOS_LIBDEP := $(LITEOS_BASELIB)
+LITEOS_ASFLAGS := $(LITEOS_ASOPTS) $(LITEOS_INCLUDE)
+LITEOS_CFLAGS := $(LITEOS_COPTS) $(LITEOS_CMACRO) \
+ $(LITEOS_CMACRO_TEST) $(LITEOS_IMAGE_MACRO) \
+ $(LITEOS_INCLUDE)
+LITEOS_CXXFLAGS := $(LITEOS_CXXOPTS) $(LITEOS_CXXMACRO) \
+ $(LITEOS_CMACRO) $(LITEOS_CXXINCLUDE)
+LITEOS_LDFLAGS := $(LITEOS_LD_OPTS) $(LITEOS_LD_PATH) \
+ $(LITEOS_LD_SCRIPT)
+
+# clear all local variables
+LOCAL_FLAGS =
+LOCAL_CFLAGS =
+LOCAL_CPPFLAGS =
+LOCAL_ASFLAGS =
+LOCAL_SRCS =
+LOCAL_CHS =
+LOCAL_CPPHS =
+
+# basic build flags
+CFLAGS := $(LITEOS_CFLAGS)
+CXXFLAGS := $(LITEOS_CXXFLAGS)
+ASFLAGS := $(LITEOS_ASFLAGS)
+LDFLAGS := $(LITEOS_LDFLAGS)
+ARFLAGS := rc
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/BUILD.gn b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/BUILD.gn
new file mode 100644
index 00000000..d9e29eaa
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/BUILD.gn
@@ -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.
+
+import("//kernel/liteos_a/liteos.gni")
+
+module_group("drivers") {
+ modules = [
+ "block",
+ "char",
+ "mtd",
+ ]
+}
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/Kconfig b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/Kconfig
new file mode 100644
index 00000000..c603f8a9
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/Kconfig
@@ -0,0 +1,21 @@
+config DRIVERS
+ bool "Enable Driver"
+ default y
+ help
+ Answer Y to enable LiteOS support driver.
+
+source "bsd/dev/usb/Kconfig"
+source "../../drivers/adapter/khdf/liteos/Kconfig"
+
+# Device driver Kconfig import
+source "$(DEVICE_PATH)/drivers/Kconfig"
+
+source "drivers/char/mem/Kconfig"
+source "drivers/char/quickstart/Kconfig"
+source "drivers/char/random/Kconfig"
+source "drivers/char/video/Kconfig"
+source "drivers/char/trace/Kconfig"
+source "drivers/char/perf/Kconfig"
+
+source "../../drivers/liteos/tzdriver/Kconfig"
+source "../../drivers/liteos/hievent/Kconfig"
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/block/BUILD.gn b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/block/BUILD.gn
new file mode 100644
index 00000000..d41dafe4
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/block/BUILD.gn
@@ -0,0 +1,34 @@
+# 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("//kernel/liteos_a/liteos.gni")
+
+module_group("block") {
+ modules = [ "disk" ]
+}
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/block/disk/BUILD.gn b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/block/disk/BUILD.gn
new file mode 100644
index 00000000..48e42b06
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/block/disk/BUILD.gn
@@ -0,0 +1,45 @@
+# 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("//kernel/liteos_a/liteos.gni")
+
+module_switch = defined(LOSCFG_FS_FAT_DISK)
+module_name = get_path_info(rebase_path("."), "name")
+kernel_module(module_name) {
+ sources = [
+ "src/disk.c",
+ "src/disk_shellcmd.c",
+ ]
+
+ public_configs = [ ":public" ]
+}
+
+config("public") {
+ include_dirs = [ "include" ]
+}
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/block/disk/Makefile b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/block/disk/Makefile
new file mode 100644
index 00000000..4e35bd1b
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/block/disk/Makefile
@@ -0,0 +1,36 @@
+# 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 $(LITEOSTOPDIR)/config.mk
+
+MODULE_NAME := $(notdir $(shell pwd))
+
+LOCAL_SRCS := $(wildcard src/*.c)
+
+include $(MODULE)
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/block/disk/include/disk.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/block/disk/include/disk.h
new file mode 100644
index 00000000..8f79cea3
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/block/disk/include/disk.h
@@ -0,0 +1,742 @@
+/*
+ * 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.
+ */
+
+/**
+ * @defgroup disk Disk
+ * @ingroup filesystem
+ */
+
+#ifndef _DISK_H
+#define _DISK_H
+
+#include "fs/driver.h"
+#include "los_base.h"
+#include "pthread.h"
+
+#ifdef LOSCFG_FS_FAT_CACHE
+#include "bcache.h"
+#endif
+
+#ifdef __cplusplus
+#if __cplusplus
+extern "C" {
+#endif
+#endif /* __cplusplus */
+
+#define SYS_MAX_DISK 5
+#define MAX_DIVIDE_PART_PER_DISK 16
+#define MAX_PRIMARY_PART_PER_DISK 4
+#define SYS_MAX_PART (SYS_MAX_DISK * MAX_DIVIDE_PART_PER_DISK)
+#define DISK_NAME 255
+#define DISK_MAX_SECTOR_SIZE 512
+
+#define PAR_OFFSET 446 /* MBR: Partition table offset (2) */
+#define BS_SIG55AA 510 /* Signature word (2) */
+#define BS_FILSYSTEMTYPE32 82 /* File system type (1) */
+#define BS_JMPBOOT 0 /* x86 jump instruction (3-byte) */
+#define BS_FILSYSTYPE 0x36 /* File system type (2) */
+#define BS_SIG55AA_VALUE 0xAA55
+
+#define PAR_TYPE_OFFSET 4
+#define PAR_START_OFFSET 8
+#define PAR_COUNT_OFFSET 12
+#define PAR_TABLE_SIZE 16
+#define EXTENDED_PAR 0x0F
+#define EXTENDED_8G 0x05
+#define EMMC 0xEC
+#define OTHERS 0x01 /* sdcard or umass */
+
+#define BS_FS_TYPE_MASK 0xFFFFFF
+#define BS_FS_TYPE_VALUE 0x544146
+#define BS_FS_TYPE_FAT 0x0B
+#define BS_FS_TYPE_NTFS 0x07
+
+#define FIRST_BYTE 1
+#define SECOND_BYTE 2
+#define THIRD_BYTE 3
+#define FOURTH_BYTE 4
+
+#define BIT_FOR_BYTE 8
+
+#define LD_WORD_DISK(ptr) (UINT16)(((UINT16)*((UINT8 *)(ptr) + FIRST_BYTE) << (BIT_FOR_BYTE * FIRST_BYTE)) | \
+ (UINT16)*(UINT8 *)(ptr))
+#define LD_DWORD_DISK(ptr) (UINT32)(((UINT32)*((UINT8 *)(ptr) + THIRD_BYTE) << (BIT_FOR_BYTE * THIRD_BYTE)) | \
+ ((UINT32)*((UINT8 *)(ptr) + SECOND_BYTE) << (BIT_FOR_BYTE * SECOND_BYTE)) | \
+ ((UINT16)*((UINT8 *)(ptr) + FIRST_BYTE) << (BIT_FOR_BYTE * FIRST_BYTE)) | \
+ (*(UINT8 *)(ptr)))
+
+#define LD_QWORD_DISK(ptr) ((UINT64)(((UINT64)LD_DWORD_DISK(&(ptr)[FOURTH_BYTE]) << (BIT_FOR_BYTE * FOURTH_BYTE)) | \
+ LD_DWORD_DISK(ptr)))
+
+/* Check VBR string, including FAT, NTFS */
+#define VERIFY_FS(ptr) (((LD_DWORD_DISK(&(ptr)[BS_FILSYSTEMTYPE32]) & BS_FS_TYPE_MASK) == BS_FS_TYPE_VALUE) || \
+ !strncmp(&(ptr)[BS_FILSYSTYPE], "FAT", strlen("FAT")) || \
+ !strncmp(&(ptr)[BS_JMPBOOT], "\xEB\x52\x90" "NTFS ", \
+ strlen("\xEB\x52\x90" "NTFS ")))
+
+#define PARTION_MODE_BTYE (PAR_OFFSET + PAR_TYPE_OFFSET) /* 0xEE: GPT(GUID), else: MBR */
+#define PARTION_MODE_GPT 0xEE /* 0xEE: GPT(GUID), else: MBR */
+#define SIGNATURE_OFFSET 0 /* The offset of GPT partition header signature */
+#define SIGNATURE_LEN 8 /* The length of GPT signature */
+#define HEADER_SIZE_OFFSET 12 /* The offset of GPT header size */
+#define TABLE_SIZE_OFFSET 84 /* The offset of GPT table size */
+#define TABLE_NUM_OFFSET 80 /* The number of GPT table */
+#define TABLE_START_SECTOR 2
+#define TABLE_MAX_NUM 128
+#define TABLE_SIZE 128
+#define GPT_PAR_START_OFFSET 32
+#define GPT_PAR_END_OFFSET 40
+#define PAR_ENTRY_NUM_PER_SECTOR 4
+#define HEADER_SIZE_MASK 0xFFFFFFFF
+#define HEADER_SIZE 0x5C
+#define HARD_DISK_GUID_OFFSET 56
+#define HARD_DISK_GUID_FOR_ESP 0x0020004900460045
+#define HARD_DISK_GUID_FOR_MSP 0x007200630069004D
+#define PAR_VALID_OFFSET0 0
+#define PAR_VALID_OFFSET1 4
+#define PAR_VALID_OFFSET2 8
+#define PAR_VALID_OFFSET3 12
+
+#define VERIFY_GPT(ptr) ((!strncmp(&(ptr)[SIGNATURE_OFFSET], "EFI PART", SIGNATURE_LEN)) && \
+ ((LD_DWORD_DISK(&(ptr)[HEADER_SIZE_OFFSET]) & HEADER_SIZE_MASK) == HEADER_SIZE))
+
+#define VERITY_PAR_VALID(ptr) ((LD_DWORD_DISK(&(ptr)[PAR_VALID_OFFSET0]) + \
+ LD_DWORD_DISK(&(ptr)[PAR_VALID_OFFSET1]) + \
+ LD_DWORD_DISK(&(ptr)[PAR_VALID_OFFSET2]) + \
+ LD_DWORD_DISK(&(ptr)[PAR_VALID_OFFSET3])) != 0)
+
+/* ESP MSP */
+#define VERITY_AVAILABLE_PAR(ptr) ((LD_QWORD_DISK(&(ptr)[HARD_DISK_GUID_OFFSET]) != HARD_DISK_GUID_FOR_ESP) && \
+ (LD_QWORD_DISK(&(ptr)[HARD_DISK_GUID_OFFSET]) != HARD_DISK_GUID_FOR_MSP))
+
+/* Command code for disk_ioctrl function */
+/* Generic command (Used by FatFs) */
+#define DISK_CTRL_SYNC 0 /* Complete pending write process */
+#define DISK_GET_SECTOR_COUNT 1 /* Get media size */
+#define DISK_GET_SECTOR_SIZE 2 /* Get sector size */
+#define DISK_GET_BLOCK_SIZE 3 /* Get erase block size */
+#define DISK_CTRL_TRIM 4 /* Inform device that the data on the block of sectors is no longer used */
+
+/* Generic command (Not used by FatFs) */
+#define DISK_CTRL_POWER 5 /* Get/Set power status */
+#define DISK_CTRL_LOCK 6 /* Lock/Unlock media removal */
+#define DISK_CTRL_EJECT 7 /* Eject media */
+#define DISK_CTRL_FORMAT 8 /* Create physical format on the media */
+
+/* MMC/SDC specific ioctl command */
+#define DISK_MMC_GET_TYPE 10 /* Get card type */
+#define DISK_MMC_GET_CSD 11 /* Get CSD */
+#define DISK_MMC_GET_CID 12 /* Get CID */
+#define DISK_MMC_GET_OCR 13 /* Get OCR */
+#define DISK_MMC_GET_SDSTAT 14 /* Get SD status */
+
+/* ATA/CF specific ioctl command */
+#define DISK_ATA_GET_REV 20 /* Get F/W revision */
+#define DISK_ATA_GET_MODEL 21 /* Get model name */
+#define DISK_ATA_GET_SN 22 /* Get serial number */
+
+#ifdef LOSCFG_FS_FAT_CACHE
+#define DISK_DIRECT_BUFFER_SIZE 4 /* los_disk direct io buffer when bcache is off */
+#endif
+
+typedef enum _disk_status_ {
+ STAT_UNUSED,
+ STAT_INUSED,
+ STAT_UNREADY
+} disk_status_e;
+
+typedef struct _los_disk_ {
+ UINT32 disk_id : 8; /* physics disk number */
+ UINT32 disk_status : 2; /* status of disk */
+ UINT32 part_count : 8; /* current partition count */
+ UINT32 reserved : 14;
+ struct Vnode *dev; /* device */
+#ifdef LOSCFG_FS_FAT_CACHE
+ OsBcache *bcache; /* cache of the disk, shared in all partitions */
+#endif
+ UINT32 sector_size; /* disk sector size */
+ UINT64 sector_start; /* disk start sector */
+ UINT64 sector_count; /* disk sector number */
+ UINT8 type;
+ CHAR *disk_name;
+ LOS_DL_LIST head; /* link head of all the partitions */
+ struct pthread_mutex disk_mutex;
+#ifndef LOSCFG_FS_FAT_CACHE
+ UINT8 *buff;
+#endif
+} los_disk;
+
+typedef struct _los_part_ {
+ UINT32 disk_id : 8; /* physics disk number */
+ UINT32 part_id : 8; /* partition number in the system */
+ UINT32 part_no_disk : 8; /* partition number in the disk */
+ UINT32 part_no_mbr : 5; /* partition number in the mbr */
+ UINT32 reserved : 3;
+ UINT8 filesystem_type; /* filesystem used in the partition */
+ UINT8 type;
+ struct Vnode *dev; /* dev devices used in the partition */
+ CHAR *part_name;
+ UINT64 sector_start; /*
+ * offset of a partition to the primary devices
+ * (multi-mbr partitions are seen as same parition)
+ */
+ UINT64 sector_count; /*
+ * sector numbers of a partition. If there is no addpartition operation,
+ * then all the mbr devices equal to the primary device count.
+ */
+ LOS_DL_LIST list; /* linklist of partition */
+} los_part;
+
+struct partition_info {
+ UINT8 type;
+ UINT64 sector_start;
+ UINT64 sector_count;
+};
+
+struct disk_divide_info {
+ UINT64 sector_count;
+ UINT32 sector_size;
+ UINT32 part_count;
+ /*
+ * The primary partition place should be reversed and set to 0 in case all the partitions are
+ * logical partition (maximum 16 currently). So the maximum part number should be 4 + 16.
+ */
+ struct partition_info part[MAX_DIVIDE_PART_PER_DISK + MAX_PRIMARY_PART_PER_DISK];
+};
+
+/**
+ * @ingroup disk
+ * @brief Disk driver initialization.
+ *
+ * @par Description:
+ * Initializate a disk dirver, and set the block cache.
+ *
+ * @attention
+ *
+ *
The parameter diskName must point a valid string, which end with the terminating null byte.
+ *
The total length of parameter diskName must be less than the value defined by PATH_MAX.
+ *
The parameter bops must pointed the right functions, otherwise the system
+ * will crash when the disk is being operated.
+ *
The parameter info can be null or point to struct disk_divide_info. when info is null,
+ * the disk will be divided base the information of MBR, otherwise,
+ * the disk will be divided base the information of parameter info.
+ *
+ *
+ * @param diskName [IN] Type #const CHAR * disk driver name.
+ * @param bops [IN] Type #const struct block_operations * block driver control structure.
+ * @param priv [IN] Type #VOID * private data of vnode.
+ * @param diskID [IN] Type #INT32 disk id number, less than SYS_MAX_DISK.
+ * @param info [IN] Type #VOID * disk driver partition information.
+ *
+ * @retval #0 Initialization success.
+ * @retval #-1 Initialization failed.
+ *
+ * @par Dependency:
+ *
disk.h
+ * @see los_disk_deinit
+ *
+ */
+INT32 los_disk_init(const CHAR *diskName, const struct block_operations *bops,
+ VOID *priv, INT32 diskID, VOID *info);
+
+/**
+ * @ingroup disk
+ * @brief Destroy a disk driver.
+ *
+ * @par Description:
+ * Destroy a disk driver, free the dependent resource.
+ *
+ * @attention
+ *
+ * None
+ *
+ *
+ * @param diskID [IN] Type #INT32 disk driver id number, less than the value defined by SYS_MAX_DISK.
+ *
+ * @retval #0 Destroy success.
+ * @retval #-1 Destroy failed.
+ *
+ * @par Dependency:
+ *
disk.h
+ * @see los_disk_init
+ *
+ */
+INT32 los_disk_deinit(INT32 diskID);
+
+/**
+ * @ingroup disk
+ * @brief Read data from disk driver.
+ *
+ * @par Description:
+ * Read data from disk driver.
+ *
+ * @attention
+ *
+ *
The sector size of the disk to be read should be acquired by los_part_ioctl before calling this function.
+ *
The parameter buf must point to a valid memory and the buf size is count * sector_size.
+ *
+ *
+ * @param drvID [IN] Type #INT32 disk driver id number, less than the value defined by SYS_MAX_DISK.
+ * @param buf [OUT] Type #VOID * memory which used to store read data.
+ * @param sector [IN] Type #UINT64 expected start sector number to read.
+ * @param count [IN] Type #UINT32 expected sector count to read.
+ * @param useRead [IN] Type #BOOL set FALSE to use the write block for optimization
+ *
+ * @retval #0 Read success.
+ * @retval #-1 Read failed.
+ *
+ * @par Dependency:
+ *
disk.h
+ * @see los_disk_write
+ *
+ */
+INT32 los_disk_read(INT32 drvID, VOID *buf, UINT64 sector, UINT32 count, BOOL useRead);
+
+/**
+ * @ingroup disk
+ * @brief Write data to a disk driver.
+ *
+ * @par Description:
+ * Write data to a disk driver.
+ *
+ * @attention
+ *
+ *
The sector size of the disk to be read should be acquired by los_part_ioctl before calling this function.
+ *
The parameter buf must point to a valid memory and the buf size is count * sector_size.
+ *
+ *
+ * @param drvID [IN] Type #INT32 disk driver id number, less than the value defined by SYS_MAX_DISK.
+ * @param buf [IN] Type #const VOID * memory which used to storage write data.
+ * @param sector [IN] Type #UINT64 expected start sector number to read.
+ * @param count [IN] Type #UINT32 experted sector count of write.
+ *
+ * @retval #0 Write success.
+ * @retval #-1 Write failed.
+ *
+ * @par Dependency:
+ *
disk.h
+ * @see los_disk_read
+ *
+ */
+INT32 los_disk_write(INT32 drvID, const VOID *buf, UINT64 sector, UINT32 count);
+
+/**
+ * @ingroup disk
+ * @brief Get information of disk driver.
+ *
+ * @par Description:
+ * Get information of disk driver.
+ *
+ * @attention
+ *
+ * None
+ *
+ *
+ * @param drvID [IN] Type #INT32 disk driver id number, less than the value defined by SYS_MAX_DISK.
+ * @param cmd [IN] Type #INT32 command to issu, currently support GET_SECTOR_COUNT, GET_SECTOR_SIZE,
+ * GET_BLOCK_SIZE, CTRL_SYNC.
+ * @param buf [OUT] Type #VOID * memory to storage the information, the size must enough for data type(UINT64)
+ * when cmd type is DISK_GET_SECTOR_COUNT, others is size_t.
+ *
+ * @retval #0 Get information success.
+ * @retval #-1 Get information failed.
+ *
+ * @par Dependency:
+ *
+ *
+ * @param drvID [IN] Type #INT32 disk driver id number, less than the value defined by SYS_MAX_DISK.
+ *
+ * @retval #0 Sync success.
+ * @retval #INT32 Sync failed.
+ *
+ * @par Dependency:
+ *
disk.h
+ * @see None
+ *
+ */
+INT32 los_disk_sync(INT32 drvID);
+
+/**
+ * @ingroup disk
+ * @brief Set blib cache for the disk driver.
+ *
+ * @par Description:
+ * Set blib cache for the disk driver, users can set the number of sectors of per block,
+ * and the number of blocks.
+ *
+ * @attention
+ *
+ * None
+ *
+ *
+ * @param drvID [IN] Type #INT32 disk driver id number, less than the value defined by SYS_MAX_DISK.
+ * @param sectorPerBlock [IN] Type #UINT32 sector number of per block, only can be 32 * (1, 2, ..., 8).
+ * @param blockNum [IN] Type #UINT32 block number of cache.
+ *
+ * @retval #0 Set success.
+ * @retval #INT32 Set failed.
+ *
+ * @par Dependency:
+ *
disk.h
+ * @see None
+ *
+ */
+INT32 los_disk_set_bcache(INT32 drvID, UINT32 sectorPerBlock, UINT32 blockNum);
+
+/**
+ * @ingroup disk
+ * @brief Read data from chosen partition.
+ *
+ * @par Description:
+ * Read data from chosen partition.
+ *
+ * @attention
+ *
+ *
The sector size of the disk to be read should be acquired by los_part_ioctl before calling this function.
+ *
The parameter buf must point to valid memory and the buf size is count * sector_size.
+ *
+ *
+ * @param pt [IN] Type #INT32 partition number, less than the value defined by SYS_MAX_PART.
+ * @param buf [OUT] Type #VOID * memory which used to store the data to be read.
+ * @param sector [IN] Type #UINT64 start sector number of chosen partition.
+ * @param count [IN] Type #UINT32 the expected sector count for reading.
+ * @param useRead [IN] Type #BOOL FALSE when reading large contiguous data, TRUE for other situations
+ *
+ * @retval #0 Read success.
+ * @retval #-1 Read failed.
+ *
+ * @par Dependency:
+ *
The sector size of the disk to be write should be acquired by los_part_ioctl before calling this function.
+ *
The parameter buf must point to valid memory and the buf size is count * sector_size.
+ *
+ *
+ * @param pt [IN] Type #INT32 partition number,less than the value defined by SYS_MAX_PART.
+ * @param buf [IN] Type #VOID * memory which used to storage the written data.
+ * @param sector [IN] Type #UINT64 start sector number of chosen partition.
+ * @param count [IN] Type #UINT32 the expected sector count for write.
+ *
+ * @retval #0 Write success.
+ * @retval #-1 Write failed.
+ *
+ * @par Dependency:
+ *
disk.h
+ * @see los_part_read
+ *
+ */
+INT32 los_part_write(INT32 pt, const VOID *buf, UINT64 sector, UINT32 count);
+
+/**
+ * @ingroup disk
+ * @brief Clear the bcache data
+ *
+ * @par Description:
+ * Flush the data and mark the block as unused.
+ *
+ * @attention
+ *
+ * @see los_part_read
+ *
+ */
+INT32 los_disk_cache_clear(INT32 drvID);
+
+/**
+ * @ingroup disk
+ * @brief Get information of chosen partition.
+ *
+ * @par Description:
+ * By passed command to get information of chosen partition.
+ *
+ * @attention
+ *
+ * None
+ *
+ *
+ * @param pt [IN] Type #INT32 partition number,less than the value defined by SYS_MAX_PART.
+ * @param cmd [IN] Type #INT32 command to issu, currently support GET_SECTOR_COUNT, GET_SECTOR_SIZE,
+ * GET_BLOCK_SIZE, CTRL_SYNC.
+ * @param buf [OUT] Type #VOID * memory to store the information, the size must enough for data type (UINT64)
+ * when cmd type is DISK_GET_SECTOR_COUNT, others is size_t.
+ *
+ * @retval #0 Get information success.
+ * @retval #-1 Get information failed.
+ *
+ * @par Dependency:
+ *
disk.h
+ * @see None
+ *
+ */
+INT32 los_part_ioctl(INT32 pt, INT32 cmd, VOID *buf);
+
+/**
+ * @ingroup disk
+ * @brief Decide the chosen partition is exist or not.
+ *
+ * @par Description:
+ * Decide the chosen partition is exist or not.
+ *
+ * @attention
+ *
+ *
The parameter dev is a full path, which begin with '/' and end with '/0'.
+ *
+ *
+ * @param dev [IN] Type #const CHAR * partition driver name.
+ * @param mode [IN] Type #mode_t access modd.
+ *
+ * @retval #0 The chosen partition is exist.
+ * @retval #-1 The chosen partition is not exist.
+ *
+ * @par Dependency:
+ *
disk.h
+ * @see None
+ *
+ */
+INT32 los_part_access(const CHAR *dev, mode_t mode);
+
+/**
+ * @ingroup disk
+ * @brief Find disk partition.
+ *
+ * @par Description:
+ * By driver partition vnode to find disk partition.
+ *
+ * @attention
+ *
+ * None
+ *
+ *
+ * @param blkDriver [IN] Type #struct Vnode * partition driver vnode.
+ *
+ * @retval #NULL Can't find chosen disk partition.
+ * @retval #los_part * This is partition structure pointer of chosen disk partition.
+ *
+ * @par Dependency:
+ *
disk.h
+ * @see None
+ *
+ */
+los_part *los_part_find(struct Vnode *blkDriver);
+
+/**
+ * @ingroup disk
+ * @brief Find disk driver.
+ *
+ * @par Description:
+ * By disk driver id number to find disk dirver.
+ *
+ * @attention
+ *
+ * None
+ *
+ *
+ * @param id [IN] Type #INT32 disk id number,less than the value defined by SYS_MAX_DISK.
+ *
+ * @retval #NULL Can't find chosen disk driver.
+ * @retval #los_disk * This is disk structure pointer of chosen disk driver.
+ *
+ * @par Dependency:
+ *
disk.h
+ * @see None
+ *
+ */
+los_disk *get_disk(INT32 id);
+
+/**
+ * @ingroup disk
+ * @brief Find disk partition.
+ *
+ * @par Description:
+ * By driver partition id number to find disk partition.
+ *
+ * @attention
+ *
+ * None
+ *
+ *
+ * @param id [IN] Type #INT32 partition id number,less than the value defined by SYS_MAX_PART.
+ *
+ * @retval #NULL Can't find chosen disk partition.
+ * @retval #los_part * This is partition structure pointer of chosen disk partition.
+ *
+ * @par Dependency:
+ *
+ *
+ * @param part [IN] Type #los_part * partition control structure pointer
+ *
+ * @par Dependency:
+ *
disk.h
+ * @see None
+ *
+ */
+VOID show_part(los_part *part);
+
+/**
+ * @ingroup disk
+ * @brief Add a new mmc partition.
+ *
+ * @par Description:
+ * Add a new mmc partition, users can set the start sector and size of the new partition.
+ *
+ * @attention
+ *
+ * None
+ *
+ *
+ * @param info [IN] Type #struct disk_divide_info * Disk driver information structure pointer.
+ * @param sectorStart [IN] Type #size_t Start sector number of the new partition.
+ * @param sectorCount [IN] Type #size_t Sector count of the new partition.
+ *
+ * @retval #0 Add partition success.
+ * @retval #-1 Add partition failed.
+ *
+ * @par Dependency:
+ *
disk.h
+ * @see None
+ *
+ */
+INT32 add_mmc_partition(struct disk_divide_info *info, size_t sectorStart, size_t sectorCount);
+
+/**
+ * @ingroup disk
+ * @brief alloc a new UNUSED disk id.
+ *
+ * @par Description:
+ * Get a free disk id for new device.
+ *
+ * @attention
+ *
+ *
The parameter diskName must point a valid string, which end with the null byte ('\0')
+ *
The total length of parameter diskName must be less than the value defined by DISK_NAME
+ *
+ *
+ * @param diskName [IN] Type #const CHAR * device name.
+ *
+ * @retval #INT32 available disk id
+ * @retval #-1 alloc disk id failed
+
+ * @par Dependency:
+ *
disk.h
+ * @see los_get_diskid_byname
+ *
+ */
+INT32 los_alloc_diskid_byname(const CHAR *diskName);
+
+/**
+ * @ingroup disk
+ * @brief get the INUSED disk id.
+ *
+ * @par Description:
+ * Get the corresponding INUSED disk id by diskName.
+ *
+ * @attention
+ *
+ *
The parameter diskName must point a valid string, which end with the null byte ('\0')
+ *
The total length of parameter diskName must be less than the value defined by DISK_NAME
+ *
+ *
+ * @param diskName [IN] Type #const CHAR * device name.
+ *
+ * @retval #INT32 available disk id
+ * @retval #-1 get disk id failed
+
+ * @par Dependency:
+ *
disk.h
+ * @see los_alloc_diskid_byname
+ *
+ */
+INT32 los_get_diskid_byname(const CHAR *diskName);
+
+
+los_disk *los_get_mmcdisk_bytype(UINT8 type);
+
+#ifdef __cplusplus
+#if __cplusplus
+}
+#endif
+#endif /* __cplusplus */
+
+#endif
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/block/disk/include/disk_pri.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/block/disk/include/disk_pri.h
new file mode 100644
index 00000000..eecc8667
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/block/disk/include/disk_pri.h
@@ -0,0 +1,69 @@
+/*
+ * 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.
+ */
+
+/**
+ * @defgroup disk Disk
+ * @ingroup filesystem
+ */
+
+#ifndef _DISK_PRI_H
+#define _DISK_PRI_H
+
+#include "linux/spinlock.h"
+#include "disk.h"
+
+#ifdef __cplusplus
+#if __cplusplus
+extern "C"{
+#endif
+#endif /* __cplusplus */
+
+extern spinlock_t g_diskSpinlock;
+extern spinlock_t g_diskFatBlockSpinlock;
+
+#ifdef LOSCFG_FS_FAT_CACHE
+extern UINT32 GetFatBlockNums(VOID);
+extern VOID SetFatBlockNums(UINT32 blockNums);
+extern UINT32 GetFatSectorsPerBlock(VOID);
+extern VOID SetFatSectorsPerBlock(UINT32 sectorsPerBlock);
+#endif
+
+extern INT32 SetDiskPartName(los_part *part, const CHAR *src);
+
+extern INT32 EraseDiskByID(UINT32 diskID, size_t startSector, UINT32 sectors);
+
+#ifdef __cplusplus
+#if __cplusplus
+}
+#endif
+#endif /* __cplusplus */
+
+#endif
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/block/disk/include/driver.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/block/disk/include/driver.h
new file mode 100644
index 00000000..d2dcf27f
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/block/disk/include/driver.h
@@ -0,0 +1,104 @@
+/*
+ * 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 __FS_DRIVER_DRIVER_H
+#define __FS_DRIVER_DRIVER_H
+
+/****************************************************************************
+ * Included Files
+ ****************************************************************************/
+
+#include "vfs_config.h"
+#include "fs/file.h"
+
+
+#ifdef __cplusplus
+#if __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+/****************************************************************************
+ * Pre-processor Definitions
+ ****************************************************************************/
+
+/****************************************************************************
+* Global Variables
+****************************************************************************/
+
+/**
+ * @ingroup disk
+ * @brief Set usb mode.
+ *
+ * @par Description:
+ * Set the corresponding bit of g_usbMode as usb host mode.
+ *
+ * @attention
+ *
+ *
diskId should be [0,SYS_MAX_DISK)
+ *
+ *
+ * @param diskId [IN] Type # unsigned int disk id.
+ *
+ * @par Dependency:
+ *
driver.h
+ * @see OsClearUsbStatus
+ *
+ */
+VOID OsSetUsbStatus(UINT32 diskId);
+
+/**
+ * @ingroup disk
+ * @brief Set usb mode.
+ *
+ * @par Description:
+ * Clear the corresponding bit of g_usbMode as usb host mode.
+ *
+ * @attention
+ *
+ *
diskId should be [0,SYS_MAX_DISK)
+ *
+ *
+ * @param diskId [IN] Type # unsigned int disk id.
+ *
+ * @par Dependency:
+ *
driver.h
+ * @see OsSetUsbStatus
+ *
+ */
+VOID OsClearUsbStatus(UINT32 diskId);
+
+#ifdef __cplusplus
+#if __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+#endif /* __FS_DRIVER_DRIVER_H */
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/block/disk/src/disk.c b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/block/disk/src/disk.c
new file mode 100644
index 00000000..6db419cb
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/block/disk/src/disk.c
@@ -0,0 +1,1799 @@
+/*
+ * 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 "disk.h"
+#include "stdio.h"
+#include "stdlib.h"
+#include "unistd.h"
+#include "sys/mount.h"
+#include "linux/spinlock.h"
+#include "path_cache.h"
+#ifndef LOSCFG_FS_FAT_CACHE
+#include "los_vm_common.h"
+#include "user_copy.h"
+#endif
+
+los_disk g_sysDisk[SYS_MAX_DISK];
+los_part g_sysPart[SYS_MAX_PART];
+
+UINT32 g_uwFatSectorsPerBlock = CONFIG_FS_FAT_SECTOR_PER_BLOCK;
+UINT32 g_uwFatBlockNums = CONFIG_FS_FAT_BLOCK_NUMS;
+
+spinlock_t g_diskSpinlock;
+spinlock_t g_diskFatBlockSpinlock;
+
+UINT32 g_usbMode = 0;
+
+#define MEM_ADDR_ALIGN_BYTE 64
+#define RWE_RW_RW 0755
+
+#define DISK_LOCK(mux) do { \
+ if (pthread_mutex_lock(mux) != 0) { \
+ PRINT_ERR("%s %d, mutex lock failed\n", __FUNCTION__, __LINE__); \
+ } \
+} while (0)
+
+#define DISK_UNLOCK(mux) do { \
+ if (pthread_mutex_unlock(mux) != 0) { \
+ PRINT_ERR("%s %d, mutex unlock failed\n", __FUNCTION__, __LINE__); \
+ } \
+} while (0)
+
+typedef VOID *(*StorageHookFunction)(VOID *);
+
+#ifdef LOSCFG_FS_FAT_CACHE
+static UINT32 OsReHookFuncAddDiskRef(StorageHookFunction handler,
+ VOID *param) __attribute__((weakref("osReHookFuncAdd")));
+
+static UINT32 OsReHookFuncDelDiskRef(StorageHookFunction handler) __attribute__((weakref("osReHookFuncDel")));
+
+UINT32 GetFatBlockNums(VOID)
+{
+ return g_uwFatBlockNums;
+}
+
+VOID SetFatBlockNums(UINT32 blockNums)
+{
+ g_uwFatBlockNums = blockNums;
+}
+
+UINT32 GetFatSectorsPerBlock(VOID)
+{
+ return g_uwFatSectorsPerBlock;
+}
+
+VOID SetFatSectorsPerBlock(UINT32 sectorsPerBlock)
+{
+ if (((sectorsPerBlock % UNSIGNED_INTEGER_BITS) == 0) &&
+ ((sectorsPerBlock >> UNINT_LOG2_SHIFT) <= BCACHE_BLOCK_FLAGS)) {
+ g_uwFatSectorsPerBlock = sectorsPerBlock;
+ }
+}
+#endif
+
+INT32 los_alloc_diskid_byname(const CHAR *diskName)
+{
+ INT32 diskID;
+ los_disk *disk = NULL;
+ UINT32 intSave;
+ size_t nameLen;
+
+ if (diskName == NULL) {
+ PRINT_ERR("The parameter disk_name is NULL");
+ return VFS_ERROR;
+ }
+
+ nameLen = strlen(diskName);
+ if (nameLen > DISK_NAME) {
+ PRINT_ERR("diskName is too long!\n");
+ return VFS_ERROR;
+ }
+ spin_lock_irqsave(&g_diskSpinlock, intSave);
+
+ for (diskID = 0; diskID < SYS_MAX_DISK; diskID++) {
+ disk = get_disk(diskID);
+ if ((disk != NULL) && (disk->disk_status == STAT_UNUSED)) {
+ disk->disk_status = STAT_UNREADY;
+ break;
+ }
+ }
+
+ spin_unlock_irqrestore(&g_diskSpinlock, intSave);
+
+ if ((disk == NULL) || (diskID == SYS_MAX_DISK)) {
+ PRINT_ERR("los_alloc_diskid_byname failed %d!\n", diskID);
+ return VFS_ERROR;
+ }
+
+ if (disk->disk_name != NULL) {
+ LOS_MemFree(m_aucSysMem0, disk->disk_name);
+ disk->disk_name = NULL;
+ }
+
+ disk->disk_name = LOS_MemAlloc(m_aucSysMem0, (nameLen + 1));
+ if (disk->disk_name == NULL) {
+ PRINT_ERR("los_alloc_diskid_byname alloc disk name failed\n");
+ return VFS_ERROR;
+ }
+
+ if (strncpy_s(disk->disk_name, (nameLen + 1), diskName, nameLen) != EOK) {
+ PRINT_ERR("The strncpy_s failed.\n");
+ LOS_MemFree(m_aucSysMem0, disk->disk_name);
+ disk->disk_name = NULL;
+ return VFS_ERROR;
+ }
+
+ disk->disk_name[nameLen] = '\0';
+
+ return diskID;
+}
+
+INT32 los_get_diskid_byname(const CHAR *diskName)
+{
+ INT32 diskID;
+ los_disk *disk = NULL;
+ size_t diskNameLen;
+
+ if (diskName == NULL) {
+ PRINT_ERR("The parameter diskName is NULL");
+ return VFS_ERROR;
+ }
+
+ diskNameLen = strlen(diskName);
+ if (diskNameLen > DISK_NAME) {
+ PRINT_ERR("diskName is too long!\n");
+ return VFS_ERROR;
+ }
+
+ for (diskID = 0; diskID < SYS_MAX_DISK; diskID++) {
+ disk = get_disk(diskID);
+ if ((disk != NULL) && (disk->disk_name != NULL) && (disk->disk_status == STAT_INUSED)) {
+ if (strlen(disk->disk_name) != diskNameLen) {
+ continue;
+ }
+ if (strcmp(diskName, disk->disk_name) == 0) {
+ break;
+ }
+ }
+ }
+ if ((disk == NULL) || (diskID == SYS_MAX_DISK)) {
+ PRINT_ERR("los_get_diskid_byname failed!\n");
+ return VFS_ERROR;
+ }
+ return diskID;
+}
+
+los_disk *los_get_mmcdisk_bytype(UINT8 type)
+{
+ const CHAR *mmcDevHead = "/dev/mmcblk";
+
+ for (INT32 diskId = 0; diskId < SYS_MAX_DISK; diskId++) {
+ los_disk *disk = get_disk(diskId);
+ if (disk == NULL) {
+ continue;
+ } else if ((disk->type == type) && (strncmp(disk->disk_name, mmcDevHead, strlen(mmcDevHead)) == 0)) {
+ return disk;
+ }
+ }
+ PRINT_ERR("Cannot find the mmc disk!\n");
+ return NULL;
+}
+
+VOID OsSetUsbStatus(UINT32 diskID)
+{
+ if (diskID < SYS_MAX_DISK) {
+ g_usbMode |= (1u << diskID) & UINT_MAX;
+ }
+}
+
+VOID OsClearUsbStatus(UINT32 diskID)
+{
+ if (diskID < SYS_MAX_DISK) {
+ g_usbMode &= ~((1u << diskID) & UINT_MAX);
+ }
+}
+
+#ifdef LOSCFG_FS_FAT_CACHE
+static BOOL GetDiskUsbStatus(UINT32 diskID)
+{
+ return (g_usbMode & (1u << diskID)) ? TRUE : FALSE;
+}
+#endif
+
+los_disk *get_disk(INT32 id)
+{
+ if ((id >= 0) && (id < SYS_MAX_DISK)) {
+ return &g_sysDisk[id];
+ }
+
+ return NULL;
+}
+
+los_part *get_part(INT32 id)
+{
+ if ((id >= 0) && (id < SYS_MAX_PART)) {
+ return &g_sysPart[id];
+ }
+
+ return NULL;
+}
+
+static UINT64 GetFirstPartStart(const los_part *part)
+{
+ los_part *firstPart = NULL;
+ los_disk *disk = get_disk((INT32)part->disk_id);
+ firstPart = (disk == NULL) ? NULL : LOS_DL_LIST_ENTRY(disk->head.pstNext, los_part, list);
+ return (firstPart == NULL) ? 0 : firstPart->sector_start;
+}
+
+static VOID DiskPartAddToDisk(los_disk *disk, los_part *part)
+{
+ part->disk_id = disk->disk_id;
+ part->part_no_disk = disk->part_count;
+ LOS_ListTailInsert(&disk->head, &part->list);
+ disk->part_count++;
+}
+
+static VOID DiskPartDelFromDisk(los_disk *disk, los_part *part)
+{
+ LOS_ListDelete(&part->list);
+ disk->part_count--;
+}
+
+static los_part *DiskPartAllocate(struct Vnode *dev, UINT64 start, UINT64 count)
+{
+ UINT32 i;
+ los_part *part = get_part(0); /* traversing from the beginning of the array */
+
+ if (part == NULL) {
+ return NULL;
+ }
+
+ for (i = 0; i < SYS_MAX_PART; i++) {
+ if (part->dev == NULL) {
+ part->part_id = i;
+ part->part_no_mbr = 0;
+ part->dev = dev;
+ part->sector_start = start;
+ part->sector_count = count;
+ part->part_name = NULL;
+ LOS_ListInit(&part->list);
+
+ return part;
+ }
+ part++;
+ }
+
+ return NULL;
+}
+
+static VOID DiskPartRelease(los_part *part)
+{
+ part->dev = NULL;
+ part->part_no_disk = 0;
+ part->part_no_mbr = 0;
+ if (part->part_name != NULL) {
+ free(part->part_name);
+ part->part_name = NULL;
+ }
+}
+
+/*
+ * name is a combination of disk_name, 'p' and part_count, such as "/dev/mmcblk0p0"
+ * disk_name : DISK_NAME + 1
+ * 'p' : 1
+ * part_count: 1
+ */
+#define DEV_NAME_BUFF_SIZE (DISK_NAME + 3)
+
+static INT32 DiskAddPart(los_disk *disk, UINT64 sectorStart, UINT64 sectorCount, BOOL IsValidPart)
+{
+ CHAR devName[DEV_NAME_BUFF_SIZE];
+ struct Vnode *diskDev = NULL;
+ struct Vnode *partDev = NULL;
+ los_part *part = NULL;
+ INT32 ret;
+
+ if ((disk == NULL) || (disk->disk_status == STAT_UNUSED) ||
+ (disk->dev == NULL)) {
+ return VFS_ERROR;
+ }
+
+ if ((sectorCount > disk->sector_count) || ((disk->sector_count - sectorCount) < sectorStart)) {
+ PRINT_ERR("DiskAddPart failed: sector start is %llu, sector count is %llu\n", sectorStart, sectorCount);
+ return VFS_ERROR;
+ }
+
+ diskDev = disk->dev;
+ if (IsValidPart == TRUE) {
+ ret = snprintf_s(devName, sizeof(devName), sizeof(devName) - 1, "%s%c%u",
+ ((disk->disk_name == NULL) ? "null" : disk->disk_name), 'p', disk->part_count);
+ if (ret < 0) {
+ return VFS_ERROR;
+ }
+
+ if (register_blockdriver(devName, ((struct drv_data *)diskDev->data)->ops,
+ RWE_RW_RW, ((struct drv_data *)diskDev->data)->priv)) {
+ PRINT_ERR("DiskAddPart : register %s fail!\n", devName);
+ return VFS_ERROR;
+ }
+
+ VnodeHold();
+ VnodeLookup(devName, &partDev, 0);
+
+ part = DiskPartAllocate(partDev, sectorStart, sectorCount);
+ VnodeDrop();
+ if (part == NULL) {
+ (VOID)unregister_blockdriver(devName);
+ return VFS_ERROR;
+ }
+ } else {
+ part = DiskPartAllocate(diskDev, sectorStart, sectorCount);
+ if (part == NULL) {
+ return VFS_ERROR;
+ }
+ }
+
+ DiskPartAddToDisk(disk, part);
+ if (disk->type == EMMC) {
+ part->type = EMMC;
+ }
+ return (INT32)part->part_id;
+}
+
+static INT32 DiskDivide(los_disk *disk, struct disk_divide_info *info)
+{
+ UINT32 i;
+ INT32 ret;
+
+ disk->type = info->part[0].type;
+ for (i = 0; i < info->part_count; i++) {
+ if (info->sector_count < info->part[i].sector_start) {
+ return VFS_ERROR;
+ }
+ if (info->part[i].sector_count > (info->sector_count - info->part[i].sector_start)) {
+ PRINT_ERR("Part[%u] sector_start:%llu, sector_count:%llu, exceed emmc sector_count:%llu.\n", i,
+ info->part[i].sector_start, info->part[i].sector_count,
+ (info->sector_count - info->part[i].sector_start));
+ info->part[i].sector_count = info->sector_count - info->part[i].sector_start;
+ PRINT_ERR("Part[%u] sector_count change to %llu.\n", i, info->part[i].sector_count);
+
+ ret = DiskAddPart(disk, info->part[i].sector_start, info->part[i].sector_count, TRUE);
+ if (ret == VFS_ERROR) {
+ return VFS_ERROR;
+ }
+ break;
+ }
+ ret = DiskAddPart(disk, info->part[i].sector_start, info->part[i].sector_count, TRUE);
+ if (ret == VFS_ERROR) {
+ return VFS_ERROR;
+ }
+ }
+
+ return ENOERR;
+}
+
+static CHAR GPTPartitionTypeRecognition(const CHAR *parBuf)
+{
+ const CHAR *buf = parBuf;
+ const CHAR *fsType = "FAT";
+ const CHAR *str = "\xEB\x52\x90" "NTFS "; /* NTFS Boot entry point */
+
+ if (((LD_DWORD_DISK(&buf[BS_FILSYSTEMTYPE32]) & BS_FS_TYPE_MASK) == BS_FS_TYPE_VALUE) ||
+ (strncmp(&buf[BS_FILSYSTYPE], fsType, strlen(fsType)) == 0)) {
+ return BS_FS_TYPE_FAT;
+ } else if (strncmp(&buf[BS_JMPBOOT], str, strlen(str)) == 0) {
+ return BS_FS_TYPE_NTFS;
+ }
+
+ return ENOERR;
+}
+
+static INT32 DiskPartitionMemZalloc(size_t boundary, size_t size, CHAR **gptBuf, CHAR **partitionBuf)
+{
+ CHAR *buffer1 = NULL;
+ CHAR *buffer2 = NULL;
+
+ buffer1 = (CHAR *)memalign(boundary, size);
+ if (buffer1 == NULL) {
+ PRINT_ERR("%s buffer1 malloc %lu failed! %d\n", __FUNCTION__, size, __LINE__);
+ return -ENOMEM;
+ }
+ buffer2 = (CHAR *)memalign(boundary, size);
+ if (buffer2 == NULL) {
+ PRINT_ERR("%s buffer2 malloc %lu failed! %d\n", __FUNCTION__, size, __LINE__);
+ free(buffer1);
+ return -ENOMEM;
+ }
+ (VOID)memset_s(buffer1, size, 0, size);
+ (VOID)memset_s(buffer2, size, 0, size);
+
+ *gptBuf = buffer1;
+ *partitionBuf = buffer2;
+
+ return ENOERR;
+}
+
+static INT32 GPTInfoGet(struct Vnode *blkDrv, CHAR *gptBuf)
+{
+ INT32 ret;
+
+ struct block_operations *bops = (struct block_operations *)((struct drv_data *)blkDrv->data)->ops;
+
+ ret = bops->read(blkDrv, (UINT8 *)gptBuf, 1, 1); /* Read the device first sector */
+ if (ret != 1) { /* Read failed */
+ PRINT_ERR("%s %d\n", __FUNCTION__, __LINE__);
+ return -EIO;
+ }
+
+ if (!VERIFY_GPT(gptBuf)) {
+ PRINT_ERR("%s %d\n", __FUNCTION__, __LINE__);
+ return VFS_ERROR;
+ }
+
+ return ENOERR;
+}
+
+static INT32 OsGPTPartitionRecognitionSub(struct disk_divide_info *info, const CHAR *partitionBuf,
+ UINT32 *partitionCount, UINT64 partitionStart, UINT64 partitionEnd)
+{
+ CHAR partitionType;
+
+ if (VERIFY_FS(partitionBuf)) {
+ partitionType = GPTPartitionTypeRecognition(partitionBuf);
+ if (partitionType) {
+ if (*partitionCount >= MAX_DIVIDE_PART_PER_DISK) {
+ return VFS_ERROR;
+ }
+ info->part[*partitionCount].type = partitionType;
+ info->part[*partitionCount].sector_start = partitionStart;
+ info->part[*partitionCount].sector_count = (partitionEnd - partitionStart) + 1;
+ (*partitionCount)++;
+ } else {
+ PRINT_ERR("The partition type is not allowed to use!\n");
+ }
+ } else {
+ PRINT_ERR("Do not support the partition type!\n");
+ }
+ return ENOERR;
+}
+
+static INT32 OsGPTPartitionRecognition(struct Vnode *blkDrv, struct disk_divide_info *info,
+ const CHAR *gptBuf, CHAR *partitionBuf, UINT32 *partitionCount)
+{
+ UINT32 j;
+ INT32 ret = VFS_ERROR;
+ UINT64 partitionStart, partitionEnd;
+ struct block_operations *bops = NULL;
+
+ for (j = 0; j < PAR_ENTRY_NUM_PER_SECTOR; j++) {
+ if (!VERITY_AVAILABLE_PAR(&gptBuf[j * TABLE_SIZE])) {
+ PRINTK("The partition type is ESP or MSR!\n");
+ continue;
+ }
+
+ if (!VERITY_PAR_VALID(&gptBuf[j * TABLE_SIZE])) {
+ return VFS_ERROR;
+ }
+
+ partitionStart = LD_QWORD_DISK(&gptBuf[(j * TABLE_SIZE) + GPT_PAR_START_OFFSET]);
+ partitionEnd = LD_QWORD_DISK(&gptBuf[(j * TABLE_SIZE) + GPT_PAR_END_OFFSET]);
+ if ((partitionStart >= partitionEnd) || (partitionEnd > info->sector_count)) {
+ PRINT_ERR("GPT partition %u recognition failed : partitionStart = %llu, partitionEnd = %llu\n",
+ j, partitionStart, partitionEnd);
+ return VFS_ERROR;
+ }
+
+ (VOID)memset_s(partitionBuf, info->sector_size, 0, info->sector_size);
+
+ bops = (struct block_operations *)((struct drv_data *)blkDrv->data)->ops;
+
+ ret = bops->read(blkDrv, (UINT8 *)partitionBuf, partitionStart, 1);
+ if (ret != 1) { /* read failed */
+ PRINT_ERR("%s %d\n", __FUNCTION__, __LINE__);
+ return -EIO;
+ }
+
+ ret = OsGPTPartitionRecognitionSub(info, partitionBuf, partitionCount, partitionStart, partitionEnd);
+ if (ret != ENOERR) {
+ return VFS_ERROR;
+ }
+ }
+
+ return ret;
+}
+
+static INT32 DiskGPTPartitionRecognition(struct Vnode *blkDrv, struct disk_divide_info *info)
+{
+ CHAR *gptBuf = NULL;
+ CHAR *partitionBuf = NULL;
+ UINT32 tableNum, i, index;
+ UINT32 partitionCount = 0;
+ INT32 ret;
+
+ ret = DiskPartitionMemZalloc(MEM_ADDR_ALIGN_BYTE, info->sector_size, &gptBuf, &partitionBuf);
+ if (ret != ENOERR) {
+ return ret;
+ }
+
+ ret = GPTInfoGet(blkDrv, gptBuf);
+ if (ret < 0) {
+ goto OUT_WITH_MEM;
+ }
+
+ tableNum = LD_DWORD_DISK(&gptBuf[TABLE_NUM_OFFSET]);
+ if (tableNum > TABLE_MAX_NUM) {
+ tableNum = TABLE_MAX_NUM;
+ }
+
+ index = (tableNum % PAR_ENTRY_NUM_PER_SECTOR) ? ((tableNum / PAR_ENTRY_NUM_PER_SECTOR) + 1) :
+ (tableNum / PAR_ENTRY_NUM_PER_SECTOR);
+
+ for (i = 0; i < index; i++) {
+ (VOID)memset_s(gptBuf, info->sector_size, 0, info->sector_size);
+ struct block_operations *bops = (struct block_operations *)((struct drv_data *)blkDrv->data)->ops;
+ ret = bops->read(blkDrv, (UINT8 *)gptBuf, TABLE_START_SECTOR + i, 1);
+ if (ret != 1) { /* read failed */
+ PRINT_ERR("%s %d\n", __FUNCTION__, __LINE__);
+ ret = -EIO;
+ goto OUT_WITH_MEM;
+ }
+
+ ret = OsGPTPartitionRecognition(blkDrv, info, gptBuf, partitionBuf, &partitionCount);
+ if (ret < 0) {
+ if (ret == VFS_ERROR) {
+ ret = (INT32)partitionCount;
+ }
+ goto OUT_WITH_MEM;
+ }
+ }
+ ret = (INT32)partitionCount;
+
+OUT_WITH_MEM:
+ free(gptBuf);
+ free(partitionBuf);
+ return ret;
+}
+
+static INT32 OsMBRInfoGet(struct Vnode *blkDrv, CHAR *mbrBuf)
+{
+ INT32 ret;
+
+ /* read MBR, start from sector 0, length is 1 sector */
+ struct block_operations *bops = (struct block_operations *)((struct drv_data *)blkDrv->data)->ops;
+
+ ret = bops->read(blkDrv, (UINT8 *)mbrBuf, 0, 1);
+ if (ret != 1) { /* read failed */
+ PRINT_ERR("driver read return error: %d\n", ret);
+ return -EIO;
+ }
+
+ /* Check boot record signature. */
+ if (LD_WORD_DISK(&mbrBuf[BS_SIG55AA]) != BS_SIG55AA_VALUE) {
+ return VFS_ERROR;
+ }
+
+ return ENOERR;
+}
+
+static INT32 OsEBRInfoGet(struct Vnode *blkDrv, const struct disk_divide_info *info,
+ CHAR *ebrBuf, const CHAR *mbrBuf)
+{
+ INT32 ret;
+
+ if (VERIFY_FS(mbrBuf)) {
+ if (info->sector_count <= LD_DWORD_DISK(&mbrBuf[PAR_OFFSET + PAR_START_OFFSET])) {
+ return VFS_ERROR;
+ }
+
+ struct block_operations *bops = (struct block_operations *)((struct drv_data *)blkDrv->data)->ops;
+ ret = bops->read(blkDrv, (UINT8 *)ebrBuf, LD_DWORD_DISK(&mbrBuf[PAR_OFFSET + PAR_START_OFFSET]), 1);
+ if ((ret != 1) || (!VERIFY_FS(ebrBuf))) { /* read failed */
+ PRINT_ERR("OsEBRInfoGet, verify_fs error, ret = %d\n", ret);
+ return -EIO;
+ }
+ }
+
+ return ENOERR;
+}
+
+static INT32 OsPrimaryPartitionRecognition(const CHAR *mbrBuf, struct disk_divide_info *info,
+ INT32 *extendedPos, INT32 *mbrCount)
+{
+ INT32 i;
+ CHAR mbrPartitionType;
+ INT32 extendedFlag = 0;
+ INT32 count = 0;
+
+ for (i = 0; i < MAX_PRIMARY_PART_PER_DISK; i++) {
+ mbrPartitionType = mbrBuf[PAR_OFFSET + PAR_TYPE_OFFSET + (i * PAR_TABLE_SIZE)];
+ if (mbrPartitionType) {
+ info->part[i].type = mbrPartitionType;
+ info->part[i].sector_start = LD_DWORD_DISK(&mbrBuf[PAR_OFFSET + PAR_START_OFFSET + (i * PAR_TABLE_SIZE)]);
+ info->part[i].sector_count = LD_DWORD_DISK(&mbrBuf[PAR_OFFSET + PAR_COUNT_OFFSET + (i * PAR_TABLE_SIZE)]);
+ if ((mbrPartitionType == EXTENDED_PAR) || (mbrPartitionType == EXTENDED_8G)) {
+ extendedFlag = 1;
+ *extendedPos = i;
+ continue;
+ }
+ count++;
+ }
+ }
+ *mbrCount = count;
+
+ return extendedFlag;
+}
+
+static INT32 OsLogicalPartitionRecognition(struct Vnode *blkDrv, struct disk_divide_info *info,
+ UINT32 extendedAddress, CHAR *ebrBuf, INT32 mbrCount)
+{
+ INT32 ret;
+ UINT32 extendedOffset = 0;
+ CHAR ebrPartitionType;
+ INT32 ebrCount = 0;
+
+ do {
+ (VOID)memset_s(ebrBuf, info->sector_size, 0, info->sector_size);
+ if (((UINT64)(extendedAddress) + extendedOffset) >= info->sector_count) {
+ PRINT_ERR("extended partition is out of disk range: extendedAddress = %u, extendedOffset = %u\n",
+ extendedAddress, extendedOffset);
+ break;
+ }
+ struct block_operations *bops = (struct block_operations *)((struct drv_data *)blkDrv->data)->ops;
+ ret = bops->read(blkDrv, (UINT8 *)ebrBuf, extendedAddress + extendedOffset, 1);
+ if (ret != 1) { /* read failed */
+ PRINT_ERR("driver read return error: %d, extendedAddress = %u, extendedOffset = %u\n", ret,
+ extendedAddress, extendedOffset);
+ return -EIO;
+ }
+ ebrPartitionType = ebrBuf[PAR_OFFSET + PAR_TYPE_OFFSET];
+ if (ebrPartitionType && ((mbrCount + ebrCount) < MAX_DIVIDE_PART_PER_DISK)) {
+ info->part[MAX_PRIMARY_PART_PER_DISK + ebrCount].type = ebrPartitionType;
+ info->part[MAX_PRIMARY_PART_PER_DISK + ebrCount].sector_start = extendedAddress + extendedOffset +
+ LD_DWORD_DISK(&ebrBuf[PAR_OFFSET +
+ PAR_START_OFFSET]);
+ info->part[MAX_PRIMARY_PART_PER_DISK + ebrCount].sector_count = LD_DWORD_DISK(&ebrBuf[PAR_OFFSET +
+ PAR_COUNT_OFFSET]);
+ ebrCount++;
+ }
+ extendedOffset = LD_DWORD_DISK(&ebrBuf[PAR_OFFSET + PAR_START_OFFSET + PAR_TABLE_SIZE]);
+ } while ((ebrBuf[PAR_OFFSET + PAR_TYPE_OFFSET + PAR_TABLE_SIZE] != 0) &&
+ ((mbrCount + ebrCount) < MAX_DIVIDE_PART_PER_DISK));
+
+ return ebrCount;
+}
+
+static INT32 DiskPartitionRecognition(struct Vnode *blkDrv, struct disk_divide_info *info)
+{
+ INT32 ret;
+ INT32 extendedFlag;
+ INT32 extendedPos = 0;
+ INT32 mbrCount = 0;
+ UINT32 extendedAddress;
+ CHAR *mbrBuf = NULL;
+ CHAR *ebrBuf = NULL;
+
+ if (blkDrv == NULL) {
+ return -EINVAL;
+ }
+
+ struct block_operations *bops = (struct block_operations *)((struct drv_data *)blkDrv->data)->ops;
+
+ if ((bops == NULL) || (bops->read == NULL)) {
+ return -EINVAL;
+ }
+
+ ret = DiskPartitionMemZalloc(MEM_ADDR_ALIGN_BYTE, info->sector_size, &mbrBuf, &ebrBuf);
+ if (ret != ENOERR) {
+ return ret;
+ }
+
+ ret = OsMBRInfoGet(blkDrv, mbrBuf);
+ if (ret < 0) {
+ goto OUT_WITH_MEM;
+ }
+
+ /* The partition type is GPT */
+ if (mbrBuf[PARTION_MODE_BTYE] == (CHAR)PARTION_MODE_GPT) {
+ ret = DiskGPTPartitionRecognition(blkDrv, info);
+ goto OUT_WITH_MEM;
+ }
+
+ ret = OsEBRInfoGet(blkDrv, info, ebrBuf, mbrBuf);
+ if (ret < 0) {
+ ret = 0; /* no mbr */
+ goto OUT_WITH_MEM;
+ }
+
+ extendedFlag = OsPrimaryPartitionRecognition(mbrBuf, info, &extendedPos, &mbrCount);
+ if (extendedFlag) {
+ extendedAddress = LD_DWORD_DISK(&mbrBuf[PAR_OFFSET + PAR_START_OFFSET + (extendedPos * PAR_TABLE_SIZE)]);
+ ret = OsLogicalPartitionRecognition(blkDrv, info, extendedAddress, ebrBuf, mbrCount);
+ if (ret <= 0) {
+ goto OUT_WITH_MEM;
+ }
+ }
+ ret += mbrCount;
+
+OUT_WITH_MEM:
+ free(ebrBuf);
+ free(mbrBuf);
+ return ret;
+}
+
+INT32 DiskPartitionRegister(los_disk *disk)
+{
+ INT32 count;
+ UINT32 i, partSize;
+ los_part *part = NULL;
+ struct disk_divide_info parInfo;
+
+ /* Fill disk_divide_info structure to set partition's information. */
+ (VOID)memset_s(parInfo.part, sizeof(parInfo.part), 0, sizeof(parInfo.part));
+ partSize = sizeof(parInfo.part) / sizeof(parInfo.part[0]);
+
+ parInfo.sector_size = disk->sector_size;
+ parInfo.sector_count = disk->sector_count;
+ count = DiskPartitionRecognition(disk->dev, &parInfo);
+ if (count == VFS_ERROR) {
+ part = get_part(DiskAddPart(disk, 0, disk->sector_count, FALSE));
+ if (part == NULL) {
+ return VFS_ERROR;
+ }
+ part->part_no_mbr = 0;
+ PRINTK("Disk %s doesn't contain a valid partition table.\n", disk->disk_name);
+ return ENOERR;
+ } else if (count < 0) {
+ return VFS_ERROR;
+ }
+
+ parInfo.part_count = count;
+ if (count == 0) {
+ part = get_part(DiskAddPart(disk, 0, disk->sector_count, TRUE));
+ if (part == NULL) {
+ return VFS_ERROR;
+ }
+ part->part_no_mbr = 0;
+
+ PRINTK("No MBR detected.\n");
+ return ENOERR;
+ }
+
+ for (i = 0; i < partSize; i++) {
+ /* Read the disk_divide_info structure to get partition's information. */
+ if ((parInfo.part[i].type != 0) && (parInfo.part[i].type != EXTENDED_PAR) &&
+ (parInfo.part[i].type != EXTENDED_8G)) {
+ part = get_part(DiskAddPart(disk, parInfo.part[i].sector_start, parInfo.part[i].sector_count, TRUE));
+ if (part == NULL) {
+ return VFS_ERROR;
+ }
+ part->part_no_mbr = i + 1;
+ part->filesystem_type = parInfo.part[i].type;
+ }
+ }
+
+ return ENOERR;
+}
+
+#ifndef LOSCFG_FS_FAT_CACHE
+static INT32 disk_read_directly(los_disk *disk, VOID *buf, UINT64 sector, UINT32 count)
+{
+ INT32 result = VFS_ERROR;
+ struct block_operations *bops = (struct block_operations *)((struct drv_data *)disk->dev->data)->ops;
+ if ((bops == NULL) || (bops->read == NULL)) {
+ return VFS_ERROR;
+ }
+ if (LOS_IsUserAddressRange((VADDR_T)buf, count * disk->sector_size)) {
+ UINT32 cnt = 0;
+ UINT8 *buffer = disk->buff;
+ for (; count != 0; count -= cnt) {
+ cnt = (count > DISK_DIRECT_BUFFER_SIZE) ? DISK_DIRECT_BUFFER_SIZE : count;
+ result = bops->read(disk->dev, buffer, sector, cnt);
+ if (result == (INT32)cnt) {
+ result = ENOERR;
+ } else {
+ break;
+ }
+ if (LOS_CopyFromKernel(buf, disk->sector_size * cnt, buffer, disk->sector_size * cnt)) {
+ result = VFS_ERROR;
+ break;
+ }
+ buf = (UINT8 *)buf + disk->sector_size * cnt;
+ sector += cnt;
+ }
+ } else {
+ result = bops->read(disk->dev, buf, sector, count);
+ if (result == count) {
+ result = ENOERR;
+ }
+ }
+
+ return result;
+}
+
+static INT32 disk_write_directly(los_disk *disk, const VOID *buf, UINT64 sector, UINT32 count)
+{
+ struct block_operations *bops = (struct block_operations *)((struct drv_data *)disk->dev->data)->ops;
+ INT32 result = VFS_ERROR;
+ if ((bops == NULL) || (bops->read == NULL)) {
+ return VFS_ERROR;
+ }
+ if (LOS_IsUserAddressRange((VADDR_T)buf, count * disk->sector_size)) {
+ UINT32 cnt = 0;
+ UINT8 *buffer = disk->buff;
+ for (; count != 0; count -= cnt) {
+ cnt = (count > DISK_DIRECT_BUFFER_SIZE) ? DISK_DIRECT_BUFFER_SIZE : count;
+ if (LOS_CopyToKernel(buffer, disk->sector_size * cnt, buf, disk->sector_size * cnt)) {
+ result = VFS_ERROR;
+ break;
+ }
+ result = bops->write(disk->dev, buffer, sector, cnt);
+ if (result == (INT32)cnt) {
+ result = ENOERR;
+ } else {
+ break;
+ }
+ buf = (UINT8 *)buf + disk->sector_size * cnt;
+ sector += cnt;
+ }
+ } else {
+ result = bops->write(disk->dev, buf, sector, count);
+ if (result == count) {
+ result = ENOERR;
+ }
+ }
+
+ return result;
+}
+#endif
+
+INT32 los_disk_read(INT32 drvID, VOID *buf, UINT64 sector, UINT32 count, BOOL useRead)
+{
+#ifdef LOSCFG_FS_FAT_CACHE
+ UINT32 len;
+#endif
+ INT32 result = VFS_ERROR;
+ los_disk *disk = get_disk(drvID);
+
+ if ((buf == NULL) || (count == 0)) { /* buff equal to NULL or count equal to 0 */
+ return result;
+ }
+
+ if (disk == NULL) {
+ return result;
+ }
+
+ DISK_LOCK(&disk->disk_mutex);
+
+ if (disk->disk_status != STAT_INUSED) {
+ goto ERROR_HANDLE;
+ }
+
+ if ((count > disk->sector_count) || ((disk->sector_count - count) < sector)) {
+ goto ERROR_HANDLE;
+ }
+
+#ifdef LOSCFG_FS_FAT_CACHE
+ if (disk->bcache != NULL) {
+ if (((UINT64)(disk->bcache->sectorSize) * count) > UINT_MAX) {
+ goto ERROR_HANDLE;
+ }
+ len = disk->bcache->sectorSize * count;
+ /* useRead should be FALSE when reading large contiguous data */
+ result = BlockCacheRead(disk->bcache, (UINT8 *)buf, &len, sector, useRead);
+ if (result != ENOERR) {
+ PRINT_ERR("los_disk_read read err = %d, sector = %llu, len = %u\n", result, sector, len);
+ }
+ } else {
+ result = VFS_ERROR;
+ }
+#else
+ if (disk->dev == NULL) {
+ goto ERROR_HANDLE;
+ }
+ result = disk_read_directly(disk, buf, sector, count);
+#endif
+ if (result != ENOERR) {
+ goto ERROR_HANDLE;
+ }
+
+ DISK_UNLOCK(&disk->disk_mutex);
+ return ENOERR;
+
+ERROR_HANDLE:
+ DISK_UNLOCK(&disk->disk_mutex);
+ return VFS_ERROR;
+}
+
+INT32 los_disk_write(INT32 drvID, const VOID *buf, UINT64 sector, UINT32 count)
+{
+#ifdef LOSCFG_FS_FAT_CACHE
+ UINT32 len;
+#endif
+ INT32 result = VFS_ERROR;
+ los_disk *disk = get_disk(drvID);
+ if (disk == NULL || disk->dev == NULL || disk->dev->data == NULL) {
+ return result;
+ }
+
+ if ((buf == NULL) || (count == 0)) { /* buff equal to NULL or count equal to 0 */
+ return result;
+ }
+
+ DISK_LOCK(&disk->disk_mutex);
+
+ if (disk->disk_status != STAT_INUSED) {
+ goto ERROR_HANDLE;
+ }
+
+ if ((count > disk->sector_count) || ((disk->sector_count - count) < sector)) {
+ goto ERROR_HANDLE;
+ }
+
+#ifdef LOSCFG_FS_FAT_CACHE
+ if (disk->bcache != NULL) {
+ if (((UINT64)(disk->bcache->sectorSize) * count) > UINT_MAX) {
+ goto ERROR_HANDLE;
+ }
+ len = disk->bcache->sectorSize * count;
+ result = BlockCacheWrite(disk->bcache, (const UINT8 *)buf, &len, sector);
+ if (result != ENOERR) {
+ PRINT_ERR("los_disk_write write err = %d, sector = %llu, len = %u\n", result, sector, len);
+ }
+ } else {
+ result = VFS_ERROR;
+ }
+#else
+ if (disk->dev == NULL) {
+ goto ERROR_HANDLE;
+ }
+ result = disk_write_directly(disk, buf, sector, count);
+#endif
+ if (result != ENOERR) {
+ goto ERROR_HANDLE;
+ }
+
+ DISK_UNLOCK(&disk->disk_mutex);
+ return ENOERR;
+
+ERROR_HANDLE:
+ DISK_UNLOCK(&disk->disk_mutex);
+ return VFS_ERROR;
+}
+
+INT32 los_disk_ioctl(INT32 drvID, INT32 cmd, VOID *buf)
+{
+ struct geometry info;
+ los_disk *disk = get_disk(drvID);
+ if (disk == NULL) {
+ return VFS_ERROR;
+ }
+
+ DISK_LOCK(&disk->disk_mutex);
+
+ if ((disk->dev == NULL) || (disk->disk_status != STAT_INUSED)) {
+ goto ERROR_HANDLE;
+ }
+
+ if (cmd == DISK_CTRL_SYNC) {
+ DISK_UNLOCK(&disk->disk_mutex);
+ return ENOERR;
+ }
+
+ if (buf == NULL) {
+ goto ERROR_HANDLE;
+ }
+
+ (VOID)memset_s(&info, sizeof(info), 0, sizeof(info));
+
+ struct block_operations *bops = (struct block_operations *)((struct drv_data *)disk->dev->data)->ops;
+ if ((bops == NULL) || (bops->geometry == NULL) ||
+ (bops->geometry(disk->dev, &info) != 0)) {
+ goto ERROR_HANDLE;
+ }
+
+ if (cmd == DISK_GET_SECTOR_COUNT) {
+ *(UINT64 *)buf = info.geo_nsectors;
+ if (info.geo_nsectors == 0) {
+ goto ERROR_HANDLE;
+ }
+ } else if (cmd == DISK_GET_SECTOR_SIZE) {
+ *(size_t *)buf = info.geo_sectorsize;
+ } else if (cmd == DISK_GET_BLOCK_SIZE) { /* Get erase block size in unit of sectors (UINT32) */
+ /* Block Num SDHC == 512, SD can be set to 512 or other */
+ *(size_t *)buf = DISK_MAX_SECTOR_SIZE / info.geo_sectorsize;
+ } else {
+ goto ERROR_HANDLE;
+ }
+
+ DISK_UNLOCK(&disk->disk_mutex);
+ return ENOERR;
+
+ERROR_HANDLE:
+ DISK_UNLOCK(&disk->disk_mutex);
+ return VFS_ERROR;
+}
+
+INT32 los_part_read(INT32 pt, VOID *buf, UINT64 sector, UINT32 count, BOOL useRead)
+{
+ const los_part *part = get_part(pt);
+ los_disk *disk = NULL;
+ INT32 ret;
+
+ if (part == NULL) {
+ return VFS_ERROR;
+ }
+
+ disk = get_disk((INT32)part->disk_id);
+ if (disk == NULL) {
+ return VFS_ERROR;
+ }
+
+ DISK_LOCK(&disk->disk_mutex);
+ if ((part->dev == NULL) || (disk->disk_status != STAT_INUSED)) {
+ goto ERROR_HANDLE;
+ }
+
+ if (count > part->sector_count) {
+ PRINT_ERR("los_part_read failed, invalid count, count = %u\n", count);
+ goto ERROR_HANDLE;
+ }
+
+ /* Read from absolute sector. */
+ if (part->type == EMMC) {
+ if ((disk->sector_count - part->sector_start) > sector) {
+ sector += part->sector_start;
+ } else {
+ PRINT_ERR("los_part_read failed, invalid sector, sector = %llu\n", sector);
+ goto ERROR_HANDLE;
+ }
+ }
+
+ if ((sector >= GetFirstPartStart(part)) &&
+ (((sector + count) > (part->sector_start + part->sector_count)) || (sector < part->sector_start))) {
+ PRINT_ERR("los_part_read error, sector = %llu, count = %u, part->sector_start = %llu, "
+ "part->sector_count = %llu\n", sector, count, part->sector_start, part->sector_count);
+ goto ERROR_HANDLE;
+ }
+
+ /* useRead should be FALSE when reading large contiguous data */
+ ret = los_disk_read((INT32)part->disk_id, buf, sector, count, useRead);
+ if (ret < 0) {
+ goto ERROR_HANDLE;
+ }
+
+ DISK_UNLOCK(&disk->disk_mutex);
+ return ENOERR;
+
+ERROR_HANDLE:
+ DISK_UNLOCK(&disk->disk_mutex);
+ return VFS_ERROR;
+}
+
+INT32 los_part_write(INT32 pt, const VOID *buf, UINT64 sector, UINT32 count)
+{
+ const los_part *part = get_part(pt);
+ los_disk *disk = NULL;
+ INT32 ret;
+
+ if (part == NULL) {
+ return VFS_ERROR;
+ }
+
+ disk = get_disk((INT32)part->disk_id);
+ if (disk == NULL) {
+ return VFS_ERROR;
+ }
+
+ DISK_LOCK(&disk->disk_mutex);
+ if ((part->dev == NULL) || (disk->disk_status != STAT_INUSED)) {
+ goto ERROR_HANDLE;
+ }
+
+ if (count > part->sector_count) {
+ PRINT_ERR("los_part_write failed, invalid count, count = %u\n", count);
+ goto ERROR_HANDLE;
+ }
+
+ /* Write to absolute sector. */
+ if (part->type == EMMC) {
+ if ((disk->sector_count - part->sector_start) > sector) {
+ sector += part->sector_start;
+ } else {
+ PRINT_ERR("los_part_write failed, invalid sector, sector = %llu\n", sector);
+ goto ERROR_HANDLE;
+ }
+ }
+
+ if ((sector >= GetFirstPartStart(part)) &&
+ (((sector + count) > (part->sector_start + part->sector_count)) || (sector < part->sector_start))) {
+ PRINT_ERR("los_part_write, sector = %llu, count = %u, part->sector_start = %llu, "
+ "part->sector_count = %llu\n", sector, count, part->sector_start, part->sector_count);
+ goto ERROR_HANDLE;
+ }
+
+ ret = los_disk_write((INT32)part->disk_id, buf, sector, count);
+ if (ret < 0) {
+ goto ERROR_HANDLE;
+ }
+
+ DISK_UNLOCK(&disk->disk_mutex);
+ return ENOERR;
+
+ERROR_HANDLE:
+ DISK_UNLOCK(&disk->disk_mutex);
+ return VFS_ERROR;
+}
+
+#define GET_ERASE_BLOCK_SIZE 0x2
+
+INT32 los_part_ioctl(INT32 pt, INT32 cmd, VOID *buf)
+{
+ struct geometry info;
+ los_part *part = get_part(pt);
+ los_disk *disk = NULL;
+
+ if (part == NULL) {
+ return VFS_ERROR;
+ }
+
+ disk = get_disk((INT32)part->disk_id);
+ if (disk == NULL) {
+ return VFS_ERROR;
+ }
+
+ DISK_LOCK(&disk->disk_mutex);
+ if ((part->dev == NULL) || (disk->disk_status != STAT_INUSED)) {
+ goto ERROR_HANDLE;
+ }
+
+ if (cmd == DISK_CTRL_SYNC) {
+ DISK_UNLOCK(&disk->disk_mutex);
+ return ENOERR;
+ }
+
+ if (buf == NULL) {
+ goto ERROR_HANDLE;
+ }
+
+ (VOID)memset_s(&info, sizeof(info), 0, sizeof(info));
+
+ struct block_operations *bops = (struct block_operations *)((struct drv_data *)part->dev->data)->ops;
+ if ((bops == NULL) || (bops->geometry == NULL) ||
+ (bops->geometry(part->dev, &info) != 0)) {
+ goto ERROR_HANDLE;
+ }
+
+ if (cmd == DISK_GET_SECTOR_COUNT) {
+ *(UINT64 *)buf = part->sector_count;
+ if (*(UINT64 *)buf == 0) {
+ goto ERROR_HANDLE;
+ }
+ } else if (cmd == DISK_GET_SECTOR_SIZE) {
+ *(size_t *)buf = info.geo_sectorsize;
+ } else if (cmd == DISK_GET_BLOCK_SIZE) { /* Get erase block size in unit of sectors (UINT32) */
+ if ((bops->ioctl == NULL) ||
+ (bops->ioctl(part->dev, GET_ERASE_BLOCK_SIZE, (UINTPTR)buf) != 0)) {
+ goto ERROR_HANDLE;
+ }
+ } else {
+ goto ERROR_HANDLE;
+ }
+
+ DISK_UNLOCK(&disk->disk_mutex);
+ return ENOERR;
+
+ERROR_HANDLE:
+ DISK_UNLOCK(&disk->disk_mutex);
+ return VFS_ERROR;
+}
+
+INT32 los_disk_cache_clear(INT32 drvID)
+{
+ INT32 result = ENOERR;
+#ifdef LOSCFG_FS_FAT_CACHE
+ los_part *part = get_part(drvID);
+ los_disk *disk = NULL;
+
+ if (part == NULL) {
+ return VFS_ERROR;
+ }
+ result = OsSdSync(part->disk_id);
+ if (result != ENOERR) {
+ PRINTK("[ERROR]disk_cache_clear SD sync failed!\n");
+ return result;
+ }
+
+ disk = get_disk(part->disk_id);
+ if (disk == NULL) {
+ return VFS_ERROR;
+ }
+
+ DISK_LOCK(&disk->disk_mutex);
+ result = BcacheClearCache(disk->bcache);
+ DISK_UNLOCK(&disk->disk_mutex);
+#endif
+ return result;
+}
+
+#ifdef LOSCFG_FS_FAT_CACHE
+static VOID DiskCacheThreadInit(UINT32 diskID, OsBcache *bc)
+{
+ bc->prereadFun = NULL;
+
+ if (GetDiskUsbStatus(diskID) == FALSE) {
+ if (BcacheAsyncPrereadInit(bc) == LOS_OK) {
+ bc->prereadFun = ResumeAsyncPreread;
+ }
+
+#ifdef LOSCFG_FS_FAT_CACHE_SYNC_THREAD
+ BcacheSyncThreadInit(bc, diskID);
+#endif
+ }
+
+ if (OsReHookFuncAddDiskRef != NULL) {
+ (VOID)OsReHookFuncAddDiskRef((StorageHookFunction)OsSdSync, (VOID *)0);
+ (VOID)OsReHookFuncAddDiskRef((StorageHookFunction)OsSdSync, (VOID *)1);
+ }
+}
+
+static OsBcache *DiskCacheInit(UINT32 diskID, const struct geometry *diskInfo, struct Vnode *blkDriver)
+{
+#define SECTOR_SIZE 512
+
+ OsBcache *bc = NULL;
+ UINT32 sectorPerBlock = diskInfo->geo_sectorsize / SECTOR_SIZE;
+ if (sectorPerBlock != 0) {
+ sectorPerBlock = g_uwFatSectorsPerBlock / sectorPerBlock;
+ if (sectorPerBlock != 0) {
+ bc = BlockCacheInit(blkDriver, diskInfo->geo_sectorsize, sectorPerBlock,
+ g_uwFatBlockNums, diskInfo->geo_nsectors / sectorPerBlock);
+ }
+ }
+
+ if (bc == NULL) {
+ PRINT_ERR("disk_init : disk have not init bcache cache!\n");
+ return NULL;
+ }
+
+ DiskCacheThreadInit(diskID, bc);
+ return bc;
+}
+
+static VOID DiskCacheDeinit(los_disk *disk)
+{
+ UINT32 diskID = disk->disk_id;
+ if (GetDiskUsbStatus(diskID) == FALSE) {
+ if (BcacheAsyncPrereadDeinit(disk->bcache) != LOS_OK) {
+ PRINT_ERR("Blib async preread deinit failed in %s, %d\n", __FUNCTION__, __LINE__);
+ }
+#ifdef LOSCFG_FS_FAT_CACHE_SYNC_THREAD
+ BcacheSyncThreadDeinit(disk->bcache);
+#endif
+ }
+
+ BlockCacheDeinit(disk->bcache);
+ disk->bcache = NULL;
+
+ if (OsReHookFuncDelDiskRef != NULL) {
+ (VOID)OsReHookFuncDelDiskRef((StorageHookFunction)OsSdSync);
+ }
+}
+#endif
+
+static VOID DiskStructInit(const CHAR *diskName, INT32 diskID, const struct geometry *diskInfo,
+ struct Vnode *blkDriver, los_disk *disk)
+{
+ size_t nameLen;
+ disk->disk_id = diskID;
+ disk->dev = blkDriver;
+ disk->sector_start = 0;
+ disk->sector_size = diskInfo->geo_sectorsize;
+ disk->sector_count = diskInfo->geo_nsectors;
+
+ nameLen = strlen(diskName); /* caller los_disk_init has chek name */
+
+ if (disk->disk_name != NULL) {
+ LOS_MemFree(m_aucSysMem0, disk->disk_name);
+ disk->disk_name = NULL;
+ }
+
+ disk->disk_name = LOS_MemAlloc(m_aucSysMem0, (nameLen + 1));
+ if (disk->disk_name == NULL) {
+ PRINT_ERR("DiskStructInit alloc memory failed.\n");
+ return;
+ }
+
+ if (strncpy_s(disk->disk_name, (nameLen + 1), diskName, nameLen) != EOK) {
+ PRINT_ERR("DiskStructInit strncpy_s failed.\n");
+ LOS_MemFree(m_aucSysMem0, disk->disk_name);
+ disk->disk_name = NULL;
+ return;
+ }
+ disk->disk_name[nameLen] = '\0';
+ LOS_ListInit(&disk->head);
+}
+
+static INT32 DiskDivideAndPartitionRegister(struct disk_divide_info *info, los_disk *disk)
+{
+ INT32 ret;
+
+ if (info != NULL) {
+ ret = DiskDivide(disk, info);
+ if (ret != ENOERR) {
+ PRINT_ERR("DiskDivide failed, ret = %d\n", ret);
+ return ret;
+ }
+ } else {
+ ret = DiskPartitionRegister(disk);
+ if (ret != ENOERR) {
+ PRINT_ERR("DiskPartitionRegister failed, ret = %d\n", ret);
+ return ret;
+ }
+ }
+ return ENOERR;
+}
+
+static INT32 DiskDeinit(los_disk *disk)
+{
+ los_part *part = NULL;
+ char *diskName = NULL;
+ CHAR devName[DEV_NAME_BUFF_SIZE];
+ INT32 ret;
+
+ if (LOS_ListEmpty(&disk->head) == FALSE) {
+ part = LOS_DL_LIST_ENTRY(disk->head.pstNext, los_part, list);
+ while (&part->list != &disk->head) {
+ diskName = (disk->disk_name == NULL) ? "null" : disk->disk_name;
+ ret = snprintf_s(devName, sizeof(devName), sizeof(devName) - 1, "%s%c%d",
+ diskName, 'p', disk->part_count - 1);
+ if (ret < 0) {
+ return -ENAMETOOLONG;
+ }
+ DiskPartDelFromDisk(disk, part);
+ (VOID)unregister_blockdriver(devName);
+ DiskPartRelease(part);
+
+ part = LOS_DL_LIST_ENTRY(disk->head.pstNext, los_part, list);
+ }
+ }
+
+ DISK_LOCK(&disk->disk_mutex);
+
+#ifdef LOSCFG_FS_FAT_CACHE
+ DiskCacheDeinit(disk);
+#else
+ if (disk->buff != NULL) {
+ free(disk->buff);
+ }
+#endif
+
+ disk->dev = NULL;
+ DISK_UNLOCK(&disk->disk_mutex);
+ (VOID)unregister_blockdriver(disk->disk_name);
+ if (disk->disk_name != NULL) {
+ LOS_MemFree(m_aucSysMem0, disk->disk_name);
+ disk->disk_name = NULL;
+ }
+ ret = pthread_mutex_destroy(&disk->disk_mutex);
+ if (ret != 0) {
+ PRINT_ERR("%s %d, mutex destroy failed, ret = %d\n", __FUNCTION__, __LINE__, ret);
+ return -EFAULT;
+ }
+
+ disk->disk_status = STAT_UNUSED;
+
+ return ENOERR;
+}
+
+static UINT32 OsDiskInitSub(const CHAR *diskName, INT32 diskID, los_disk *disk,
+ struct geometry *diskInfo, struct Vnode *blkDriver)
+{
+ pthread_mutexattr_t attr;
+#ifdef LOSCFG_FS_FAT_CACHE
+ OsBcache *bc = DiskCacheInit((UINT32)diskID, diskInfo, blkDriver);
+ if (bc == NULL) {
+ return VFS_ERROR;
+ }
+ disk->bcache = bc;
+#endif
+
+ (VOID)pthread_mutexattr_init(&attr);
+ attr.type = PTHREAD_MUTEX_RECURSIVE;
+ (VOID)pthread_mutex_init(&disk->disk_mutex, &attr);
+
+ DiskStructInit(diskName, diskID, diskInfo, blkDriver, disk);
+
+#ifndef LOSCFG_FS_FAT_CACHE
+ disk->buff = malloc(diskInfo->geo_sectorsize * DISK_DIRECT_BUFFER_SIZE);
+ if (disk->buff == NULL) {
+ PRINT_ERR("OsDiskInitSub: direct buffer of disk init failed\n");
+ return VFS_ERROR;
+ }
+#endif
+
+ return ENOERR;
+}
+
+INT32 los_disk_init(const CHAR *diskName, const struct block_operations *bops,
+ VOID *priv, INT32 diskID, VOID *info)
+{
+ struct geometry diskInfo;
+ struct Vnode *blkDriver = NULL;
+ los_disk *disk = get_disk(diskID);
+ INT32 ret;
+
+ if ((diskName == NULL) || (disk == NULL) ||
+ (disk->disk_status != STAT_UNREADY) || (strlen(diskName) > DISK_NAME)) {
+ return VFS_ERROR;
+ }
+
+ if (register_blockdriver(diskName, bops, RWE_RW_RW, priv) != 0) {
+ PRINT_ERR("disk_init : register %s fail!\n", diskName);
+ return VFS_ERROR;
+ }
+
+ VnodeHold();
+ ret = VnodeLookup(diskName, &blkDriver, 0);
+ if (ret < 0) {
+ VnodeDrop();
+ ret = ENOENT;
+ goto DISK_FIND_ERROR;
+ }
+ struct block_operations *bops2 = (struct block_operations *)((struct drv_data *)blkDriver->data)->ops;
+
+ if ((bops2 == NULL) || (bops2->geometry == NULL) || (bops2->geometry(blkDriver, &diskInfo) != 0)) {
+ goto DISK_BLKDRIVER_ERROR;
+ }
+
+ if (diskInfo.geo_sectorsize < DISK_MAX_SECTOR_SIZE) {
+ goto DISK_BLKDRIVER_ERROR;
+ }
+
+ ret = OsDiskInitSub(diskName, diskID, disk, &diskInfo, blkDriver);
+ if (ret != ENOERR) {
+ (VOID)DiskDeinit(disk);
+ VnodeDrop();
+ return VFS_ERROR;
+ }
+ VnodeDrop();
+ if (DiskDivideAndPartitionRegister(info, disk) != ENOERR) {
+ (VOID)DiskDeinit(disk);
+ return VFS_ERROR;
+ }
+
+ disk->disk_status = STAT_INUSED;
+ if (info != NULL) {
+ disk->type = EMMC;
+ } else {
+ disk->type = OTHERS;
+ }
+ return ENOERR;
+
+DISK_BLKDRIVER_ERROR:
+ PRINT_ERR("disk_init : register %s ok but get disk info fail!\n", diskName);
+ VnodeDrop();
+DISK_FIND_ERROR:
+ (VOID)unregister_blockdriver(diskName);
+ return VFS_ERROR;
+}
+
+INT32 los_disk_deinit(INT32 diskID)
+{
+ int ret;
+ los_disk *disk = get_disk(diskID);
+ if (disk == NULL) {
+ return -EINVAL;
+ }
+ ret = ForceUmountDev(disk->dev);
+ PRINTK("warning: %s lost, force umount ret = %d\n", disk->disk_name, ret);
+
+ DISK_LOCK(&disk->disk_mutex);
+
+ if (disk->disk_status != STAT_INUSED) {
+ DISK_UNLOCK(&disk->disk_mutex);
+ return -EINVAL;
+ }
+
+ disk->disk_status = STAT_UNREADY;
+ DISK_UNLOCK(&disk->disk_mutex);
+
+ return DiskDeinit(disk);
+}
+
+INT32 los_disk_sync(INT32 drvID)
+{
+ INT32 ret = ENOERR;
+ los_disk *disk = get_disk(drvID);
+ if (disk == NULL) {
+ return EINVAL;
+ }
+
+ DISK_LOCK(&disk->disk_mutex);
+ if (disk->disk_status != STAT_INUSED) {
+ DISK_UNLOCK(&disk->disk_mutex);
+ return EINVAL;
+ }
+
+#ifdef LOSCFG_FS_FAT_CACHE
+ if (disk->bcache != NULL) {
+ ret = BlockCacheSync(disk->bcache);
+ }
+#endif
+
+ DISK_UNLOCK(&disk->disk_mutex);
+ return ret;
+}
+
+INT32 los_disk_set_bcache(INT32 drvID, UINT32 sectorPerBlock, UINT32 blockNum)
+{
+#ifdef LOSCFG_FS_FAT_CACHE
+
+ INT32 ret;
+ UINT32 intSave;
+ OsBcache *bc = NULL;
+ los_disk *disk = get_disk(drvID);
+ if ((disk == NULL) || (sectorPerBlock == 0)) {
+ return EINVAL;
+ }
+
+ /*
+ * Because we use UINT32 flag[BCACHE_BLOCK_FLAGS] in bcache for sectors bitmap tag, so it must
+ * be less than 32 * BCACHE_BLOCK_FLAGS.
+ */
+ if (((sectorPerBlock % UNSIGNED_INTEGER_BITS) != 0) ||
+ ((sectorPerBlock >> UNINT_LOG2_SHIFT) > BCACHE_BLOCK_FLAGS)) {
+ return EINVAL;
+ }
+
+ DISK_LOCK(&disk->disk_mutex);
+
+ if (disk->disk_status != STAT_INUSED) {
+ goto ERROR_HANDLE;
+ }
+
+ if (disk->bcache != NULL) {
+ ret = BlockCacheSync(disk->bcache);
+ if (ret != ENOERR) {
+ DISK_UNLOCK(&disk->disk_mutex);
+ return ret;
+ }
+ }
+
+ spin_lock_irqsave(&g_diskFatBlockSpinlock, intSave);
+ DiskCacheDeinit(disk);
+
+ g_uwFatBlockNums = blockNum;
+ g_uwFatSectorsPerBlock = sectorPerBlock;
+
+ bc = BlockCacheInit(disk->dev, disk->sector_size, sectorPerBlock, blockNum, disk->sector_count / sectorPerBlock);
+ if ((bc == NULL) && (blockNum != 0)) {
+ spin_unlock_irqrestore(&g_diskFatBlockSpinlock, intSave);
+ DISK_UNLOCK(&disk->disk_mutex);
+ return ENOMEM;
+ }
+
+ if (bc != NULL) {
+ DiskCacheThreadInit((UINT32)drvID, bc);
+ }
+
+ disk->bcache = bc;
+ spin_unlock_irqrestore(&g_diskFatBlockSpinlock, intSave);
+ DISK_UNLOCK(&disk->disk_mutex);
+ return ENOERR;
+
+ERROR_HANDLE:
+ DISK_UNLOCK(&disk->disk_mutex);
+ return EINVAL;
+#else
+ return VFS_ERROR;
+#endif
+}
+
+static los_part *OsPartFind(los_disk *disk, const struct Vnode *blkDriver)
+{
+ los_part *part = NULL;
+
+ DISK_LOCK(&disk->disk_mutex);
+ if ((disk->disk_status != STAT_INUSED) || (LOS_ListEmpty(&disk->head) == TRUE)) {
+ goto EXIT;
+ }
+ part = LOS_DL_LIST_ENTRY(disk->head.pstNext, los_part, list);
+ if (disk->dev == blkDriver) {
+ goto EXIT;
+ }
+
+ while (&part->list != &disk->head) {
+ if (part->dev == blkDriver) {
+ goto EXIT;
+ }
+ part = LOS_DL_LIST_ENTRY(part->list.pstNext, los_part, list);
+ }
+ part = NULL;
+
+EXIT:
+ DISK_UNLOCK(&disk->disk_mutex);
+ return part;
+}
+
+los_part *los_part_find(struct Vnode *blkDriver)
+{
+ INT32 i;
+ los_disk *disk = NULL;
+ los_part *part = NULL;
+
+ if (blkDriver == NULL) {
+ return NULL;
+ }
+
+ for (i = 0; i < SYS_MAX_DISK; i++) {
+ disk = get_disk(i);
+ if (disk == NULL) {
+ continue;
+ }
+ part = OsPartFind(disk, blkDriver);
+ if (part != NULL) {
+ return part;
+ }
+ }
+
+ return NULL;
+}
+
+INT32 los_part_access(const CHAR *dev, mode_t mode)
+{
+ los_part *part = NULL;
+ struct Vnode *node = NULL;
+
+ VnodeHold();
+ if (VnodeLookup(dev, &node, 0) < 0) {
+ VnodeDrop();
+ return VFS_ERROR;
+ }
+
+ part = los_part_find(node);
+ VnodeDrop();
+ if (part == NULL) {
+ return VFS_ERROR;
+ }
+
+ return ENOERR;
+}
+
+INT32 SetDiskPartName(los_part *part, const CHAR *src)
+{
+ size_t len;
+ los_disk *disk = NULL;
+
+ if ((part == NULL) || (src == NULL)) {
+ return VFS_ERROR;
+ }
+
+ len = strlen(src);
+ if ((len == 0) || (len >= DISK_NAME)) {
+ return VFS_ERROR;
+ }
+
+ disk = get_disk((INT32)part->disk_id);
+ if (disk == NULL) {
+ return VFS_ERROR;
+ }
+
+ DISK_LOCK(&disk->disk_mutex);
+ if (disk->disk_status != STAT_INUSED) {
+ goto ERROR_HANDLE;
+ }
+
+ part->part_name = (CHAR *)zalloc(len + 1);
+ if (part->part_name == NULL) {
+ PRINT_ERR("%s[%d] zalloc failure\n", __FUNCTION__, __LINE__);
+ goto ERROR_HANDLE;
+ }
+
+ if (strcpy_s(part->part_name, len + 1, src) != EOK) {
+ free(part->part_name);
+ part->part_name = NULL;
+ goto ERROR_HANDLE;
+ }
+
+ DISK_UNLOCK(&disk->disk_mutex);
+ return ENOERR;
+
+ERROR_HANDLE:
+ DISK_UNLOCK(&disk->disk_mutex);
+ return VFS_ERROR;
+}
+
+INT32 add_mmc_partition(struct disk_divide_info *info, size_t sectorStart, size_t sectorCount)
+{
+ UINT32 index, i;
+
+ if (info == NULL) {
+ return VFS_ERROR;
+ }
+
+ if ((info->part_count >= MAX_DIVIDE_PART_PER_DISK) || (sectorCount == 0)) {
+ return VFS_ERROR;
+ }
+
+ if ((sectorCount > info->sector_count) || ((info->sector_count - sectorCount) < sectorStart)) {
+ return VFS_ERROR;
+ }
+
+ index = info->part_count;
+ for (i = 0; i < index; i++) {
+ if (sectorStart < (info->part[i].sector_start + info->part[i].sector_count)) {
+ return VFS_ERROR;
+ }
+ }
+
+ info->part[index].sector_start = sectorStart;
+ info->part[index].sector_count = sectorCount;
+ info->part[index].type = EMMC;
+ info->part_count++;
+
+ return ENOERR;
+}
+
+VOID show_part(los_part *part)
+{
+ if ((part == NULL) || (part->dev == NULL)) {
+ PRINT_ERR("part is NULL\n");
+ return;
+ }
+
+ PRINTK("\npart info :\n");
+ PRINTK("disk id : %u\n", part->disk_id);
+ PRINTK("part_id in system: %u\n", part->part_id);
+ PRINTK("part no in disk : %u\n", part->part_no_disk);
+ PRINTK("part no in mbr : %u\n", part->part_no_mbr);
+ PRINTK("part filesystem : %02X\n", part->filesystem_type);
+ PRINTK("part sec start : %llu\n", part->sector_start);
+ PRINTK("part sec count : %llu\n", part->sector_count);
+}
+
+#ifdef LOSCFG_DRIVERS_MMC
+ssize_t StorageBlockMmcErase(uint32_t blockId, size_t secStart, size_t secNr);
+#endif
+
+INT32 EraseDiskByID(UINT32 diskID, size_t startSector, UINT32 sectors)
+{
+ INT32 ret = VFS_ERROR;
+#ifdef LOSCFG_DRIVERS_MMC
+ los_disk *disk = get_disk((INT32)diskID);
+ if (disk != NULL) {
+ ret = StorageBlockMmcErase(diskID, startSector, sectors);
+ }
+#endif
+
+ return ret;
+}
+
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/block/disk/src/disk_shellcmd.c b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/block/disk/src/disk_shellcmd.c
new file mode 100644
index 00000000..38227121
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/block/disk/src/disk_shellcmd.c
@@ -0,0 +1,76 @@
+/*
+ * 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 "stdio.h"
+#include "stdlib.h"
+#include "los_config.h"
+#ifdef LOSCFG_SHELL_CMD_DEBUG
+#include "disk.h"
+#include "shcmd.h"
+#include "shell.h"
+#include "path_cache.h"
+
+INT32 osShellCmdPartInfo(INT32 argc, const CHAR **argv)
+{
+ struct Vnode *node = NULL;
+ los_part *part = NULL;
+ const CHAR *str = "/dev";
+ int ret;
+
+ if ((argc != 1) || (strncmp(argv[0], str, strlen(str)) != 0)) {
+ PRINTK("Usage :\n");
+ PRINTK(" partinfo \n");
+ PRINTK(" dev_vnodename : the name of dev\n");
+ PRINTK("Example:\n");
+ PRINTK(" partinfo /dev/sdap0 \n");
+
+ set_errno(EINVAL);
+ return -LOS_NOK;
+ }
+ VnodeHold();
+ ret = VnodeLookup(argv[0], &node, 0);
+ if (ret < 0) {
+ PRINT_ERR("no part found\n");
+ VnodeDrop();
+ set_errno(ENOENT);
+ return -LOS_NOK;
+ }
+
+ part = los_part_find(node);
+ VnodeDrop();
+ show_part(part);
+
+ return LOS_OK;
+}
+
+SHELLCMD_ENTRY(partinfo_shellcmd, CMD_TYPE_EX, "partinfo", XARGS, (CmdCallBackFunc)osShellCmdPartInfo);
+
+#endif
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/BUILD.gn b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/BUILD.gn
new file mode 100644
index 00000000..9044b2f8
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/BUILD.gn
@@ -0,0 +1,42 @@
+# 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("//kernel/liteos_a/liteos.gni")
+
+module_group("char") {
+ modules = [
+ "bch",
+ "mem",
+ "perf",
+ "quickstart",
+ "random",
+ "trace",
+ "video",
+ ]
+}
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/bch/BUILD.gn b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/bch/BUILD.gn
new file mode 100644
index 00000000..634b1e7c
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/bch/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("//kernel/liteos_a/liteos.gni")
+import("//third_party/NuttX/NuttX.gni")
+
+module_switch = defined(LOSCFG_FS_VFS_BLOCK_DEVICE)
+module_name = get_path_info(rebase_path("."), "name")
+kernel_module(module_name) {
+ sources = NUTTX_DRIVERS_BCH_SRC_FILES
+
+ public_configs = [ ":public" ]
+}
+
+config("public") {
+ include_dirs = [ "include" ]
+}
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/bch/Makefile b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/bch/Makefile
new file mode 100644
index 00000000..6774a104
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/bch/Makefile
@@ -0,0 +1,41 @@
+# 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 $(LITEOSTOPDIR)/config.mk
+
+MODULE_NAME := $(notdir $(shell pwd))
+
+LOCAL_SRCS := $(wildcard $(LITEOSTHIRDPARTY)/NuttX/drivers/bch/*.c)
+
+LOCAL_INCLUDE := \
+ -I $(LITEOSTHIRDPARTY)/NuttX/drivers/bch
+
+LOCAL_FLAGS := $(LOCAL_INCLUDE)
+
+include $(MODULE)
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/bch/include/blockproxy.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/bch/include/blockproxy.h
new file mode 100644
index 00000000..4d884e79
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/bch/include/blockproxy.h
@@ -0,0 +1,53 @@
+/*
+ * 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 __FS_DRIVER_BLOCKPROXY_H
+#define __FS_DRIVER_BLOCKPROXY_H
+
+#ifdef __cplusplus
+#if __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+int bchdev_register(const char *blkdev, const char *chardev, bool readonly);
+
+int block_proxy(const char *blkdev, int oflags);
+
+int bchdev_unregister(const char *blkdev);
+
+#ifdef __cplusplus
+#if __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+#endif /* __FS_DRIVER_BLOCKPROXY_H */
+
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/mem/BUILD.gn b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/mem/BUILD.gn
new file mode 100644
index 00000000..aad2d717
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/mem/BUILD.gn
@@ -0,0 +1,42 @@
+# 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("//kernel/liteos_a/liteos.gni")
+
+module_switch = defined(LOSCFG_DRIVERS_MEM)
+module_name = get_path_info(rebase_path("."), "name")
+kernel_module(module_name) {
+ sources = [ "src/mem.c" ]
+
+ public_configs = [ ":public" ]
+}
+
+config("public") {
+ include_dirs = [ "include" ]
+}
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/mem/Kconfig b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/mem/Kconfig
new file mode 100644
index 00000000..7cfed492
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/mem/Kconfig
@@ -0,0 +1,6 @@
+config DRIVERS_MEM
+ bool "Enable MEM"
+ default y
+ depends on DRIVERS && FS_VFS
+ help
+ Answer Y to enable LiteOS support mem.
\ No newline at end of file
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/mem/Makefile b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/mem/Makefile
new file mode 100644
index 00000000..4e35bd1b
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/mem/Makefile
@@ -0,0 +1,36 @@
+# 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 $(LITEOSTOPDIR)/config.mk
+
+MODULE_NAME := $(notdir $(shell pwd))
+
+LOCAL_SRCS := $(wildcard src/*.c)
+
+include $(MODULE)
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/mem/include/los_dev_mem.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/mem/include/los_dev_mem.h
new file mode 100644
index 00000000..cb5989e8
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/mem/include/los_dev_mem.h
@@ -0,0 +1,51 @@
+/*
+ * 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 __LOS_DEV_MEM_H__
+#define __LOS_DEV_MEM_H__
+
+#include "los_typedef.h"
+
+#ifdef __cplusplus
+#if __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+extern int DevMemRegister(void);
+
+#ifdef __cplusplus
+#if __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+#endif
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/mem/src/mem.c b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/mem/src/mem.c
new file mode 100644
index 00000000..4030a29c
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/mem/src/mem.c
@@ -0,0 +1,101 @@
+/*
+ * 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 "fcntl.h"
+#include "linux/kernel.h"
+#include "fs/driver.h"
+
+static int MemOpen(struct file *filep)
+{
+ return 0;
+}
+
+static int MemClose(struct file *filep)
+{
+ return 0;
+}
+
+static ssize_t MemRead(struct file *filep, char *buffer, size_t buflen)
+{
+ return 0;
+}
+
+static ssize_t MemWrite(struct file *filep, const char *buffer, size_t buflen)
+{
+ return 0;
+}
+
+static ssize_t MemMap(struct file *filep, LosVmMapRegion *region)
+{
+#ifdef LOSCFG_KERNEL_VM
+ size_t size = region->range.size;
+ PADDR_T paddr = region->pgOff << PAGE_SHIFT;
+ VADDR_T vaddr = region->range.base;
+ LosVmSpace *space = LOS_SpaceGet(vaddr);
+
+ if ((paddr >= SYS_MEM_BASE) && (paddr < SYS_MEM_END)) {
+ return -EINVAL;
+ }
+
+ /* Peripheral register memory adds strongly ordered attributes */
+ region->regionFlags |= VM_MAP_REGION_FLAG_STRONGLY_ORDERED;
+
+ if (space == NULL) {
+ return -EAGAIN;
+ }
+ if (LOS_ArchMmuMap(&space->archMmu, vaddr, paddr, size >> PAGE_SHIFT, region->regionFlags) <= 0) {
+ return -EAGAIN;
+ }
+#else
+ UNUSED(filep);
+ UNUSED(region);
+#endif
+ return 0;
+}
+
+static const struct file_operations_vfs g_memDevOps = {
+ MemOpen, /* open */
+ MemClose, /* close */
+ MemRead, /* read */
+ MemWrite, /* write */
+ NULL, /* seek */
+ NULL, /* ioctl */
+ MemMap, /* mmap */
+#ifndef CONFIG_DISABLE_POLL
+ NULL, /* poll */
+#endif
+ NULL, /* unlink */
+};
+
+int DevMemRegister(void)
+{
+ return register_driver("/dev/mem", &g_memDevOps, 0666, 0); /* 0666: file mode */
+}
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/perf/BUILD.gn b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/perf/BUILD.gn
new file mode 100644
index 00000000..223bc274
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/perf/BUILD.gn
@@ -0,0 +1,42 @@
+# 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("//kernel/liteos_a/liteos.gni")
+
+module_switch = defined(LOSCFG_DRIVERS_PERF)
+module_name = "perf_dev"
+kernel_module(module_name) {
+ sources = [ "src/perf.c" ]
+
+ public_configs = [ ":public" ]
+}
+
+config("public") {
+ include_dirs = [ "include" ]
+}
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/perf/Kconfig b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/perf/Kconfig
new file mode 100644
index 00000000..b760bb57
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/perf/Kconfig
@@ -0,0 +1,6 @@
+config DRIVERS_PERF
+ bool "Enable PERF DRIVER"
+ default y
+ depends on DRIVERS && FS_VFS && KERNEL_PERF
+ help
+ Answer Y to enable LiteOS support perf in userspace.
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/perf/Makefile b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/perf/Makefile
new file mode 100644
index 00000000..f3b7fe20
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/perf/Makefile
@@ -0,0 +1,36 @@
+# 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 $(LITEOSTOPDIR)/config.mk
+
+MODULE_NAME := perf_dev
+
+LOCAL_SRCS := $(wildcard src/*.c)
+
+include $(MODULE)
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/perf/include/los_dev_perf.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/perf/include/los_dev_perf.h
new file mode 100644
index 00000000..414f1211
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/perf/include/los_dev_perf.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 __LOS_DEV_PERF_H__
+#define __LOS_DEV_PERF_H__
+
+#ifdef __cplusplus
+#if __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+int DevPerfRegister(void);
+
+#ifdef __cplusplus
+#if __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+#endif
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/perf/src/perf.c b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/perf/src/perf.c
new file mode 100644
index 00000000..b5a29287
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/perf/src/perf.c
@@ -0,0 +1,153 @@
+/*
+ * 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 "fcntl.h"
+#include "user_copy.h"
+#include "sys/ioctl.h"
+#include "fs/driver.h"
+#include "los_dev_perf.h"
+#include "los_perf.h"
+#include "los_init.h"
+
+#define PERF_DRIVER "/dev/perf"
+#define PERF_DRIVER_MODE 0666
+
+/* perf ioctl */
+#define PERF_IOC_MAGIC 'T'
+#define PERF_START _IO(PERF_IOC_MAGIC, 1)
+#define PERF_STOP _IO(PERF_IOC_MAGIC, 2)
+
+static int PerfOpen(struct file *filep)
+{
+ (void)filep;
+ return 0;
+}
+
+static int PerfClose(struct file *filep)
+{
+ (void)filep;
+ return 0;
+}
+
+static ssize_t PerfRead(struct file *filep, char *buffer, size_t buflen)
+{
+ /* perf record buffer read */
+ (void)filep;
+ int ret;
+ int realLen;
+
+ char *records = LOS_MemAlloc(m_aucSysMem0, buflen);
+ if (records == NULL) {
+ return -ENOMEM;
+ }
+
+ realLen = LOS_PerfDataRead(records, buflen); /* get sample data */
+ if (realLen == 0) {
+ PRINT_ERR("Perf read failed, check whether perf is configured to sample mode.\n");
+ ret = -EINVAL;
+ goto EXIT;
+ }
+
+ ret = LOS_CopyFromKernel((void *)buffer, buflen, (void *)records, realLen);
+ if (ret != 0) {
+ ret = -EINVAL;
+ goto EXIT;
+ }
+
+ ret = realLen;
+EXIT:
+ LOS_MemFree(m_aucSysMem0, records);
+ return ret;
+}
+
+static ssize_t PerfConfig(struct file *filep, const char *buffer, size_t buflen)
+{
+ (void)filep;
+ int ret;
+ PerfConfigAttr attr = {0};
+ int attrlen = sizeof(PerfConfigAttr);
+
+ if (buflen != attrlen) {
+ PRINT_ERR("PerfConfigAttr is %d bytes not %d\n", attrlen, buflen);
+ return -EINVAL;
+ }
+
+ ret = LOS_CopyToKernel(&attr, attrlen, buffer, buflen);
+ if (ret != 0) {
+ return -EINVAL;
+ }
+
+ ret = LOS_PerfConfig(&attr);
+ if (ret != LOS_OK) {
+ PRINT_ERR("perf config error %u\n", ret);
+ return -EINVAL;
+ }
+
+ return 0;
+}
+
+static int PerfIoctl(struct file *filep, int cmd, unsigned long arg)
+{
+ (void)filep;
+ switch (cmd) {
+ case PERF_START:
+ LOS_PerfStart((UINT32)arg);
+ break;
+ case PERF_STOP:
+ LOS_PerfStop();
+ break;
+ default:
+ PRINT_ERR("Unknown perf ioctl cmd:%d\n", cmd);
+ return -EINVAL;
+ }
+ return 0;
+}
+
+static const struct file_operations_vfs g_perfDevOps = {
+ PerfOpen, /* open */
+ PerfClose, /* close */
+ PerfRead, /* read */
+ PerfConfig, /* write */
+ NULL, /* seek */
+ PerfIoctl, /* ioctl */
+ NULL, /* mmap */
+#ifndef CONFIG_DISABLE_POLL
+ NULL, /* poll */
+#endif
+ NULL, /* unlink */
+};
+
+int DevPerfRegister(void)
+{
+ return register_driver(PERF_DRIVER, &g_perfDevOps, PERF_DRIVER_MODE, 0); /* 0666: file mode */
+}
+
+LOS_MODULE_INIT(DevPerfRegister, LOS_INIT_LEVEL_KMOD_EXTENDED);
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/quickstart/BUILD.gn b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/quickstart/BUILD.gn
new file mode 100644
index 00000000..9f2cb98d
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/quickstart/BUILD.gn
@@ -0,0 +1,42 @@
+# 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("//kernel/liteos_a/liteos.gni")
+
+module_switch = defined(LOSCFG_DRIVERS_QUICKSTART)
+module_name = get_path_info(rebase_path("."), "name")
+kernel_module(module_name) {
+ sources = [ "src/quickstart.c" ]
+
+ public_configs = [ ":public" ]
+}
+
+config("public") {
+ include_dirs = [ "include" ]
+}
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/quickstart/Kconfig b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/quickstart/Kconfig
new file mode 100644
index 00000000..5ff73fe5
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/quickstart/Kconfig
@@ -0,0 +1,6 @@
+config DRIVERS_QUICKSTART
+ bool "Enable QUICKSTART"
+ default y
+ depends on DRIVERS && FS_VFS
+ help
+ Answer Y to enable LiteOS support quickstart frame dev.
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/quickstart/Makefile b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/quickstart/Makefile
new file mode 100644
index 00000000..4e35bd1b
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/quickstart/Makefile
@@ -0,0 +1,36 @@
+# 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 $(LITEOSTOPDIR)/config.mk
+
+MODULE_NAME := $(notdir $(shell pwd))
+
+LOCAL_SRCS := $(wildcard src/*.c)
+
+include $(MODULE)
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/quickstart/include/los_dev_quickstart.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/quickstart/include/los_dev_quickstart.h
new file mode 100644
index 00000000..8d9ff447
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/quickstart/include/los_dev_quickstart.h
@@ -0,0 +1,87 @@
+/*
+ * 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 __LOS_DEV_QUICKSTART_H__
+#define __LOS_DEV_QUICKSTART_H__
+
+#include "los_typedef.h"
+#include "sys/ioctl.h"
+
+#ifdef __cplusplus
+#if __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+typedef enum {
+ QS_STAGE1 = 1, /* 1: start from stage1, 0 is already called in kernel process */
+ QS_STAGE2, /* system init stage No 2 */
+ QS_STAGE3, /* system init stage No 3 */
+ QS_STAGE_LIMIT
+} QuickstartStage;
+
+typedef enum {
+ QS_NOTIFY = QS_STAGE_LIMIT, /* quickstart notify */
+ QS_LISTEN, /* quickstart listen */
+ QS_CTL_LIMIT
+} QuickstartConctrl;
+
+typedef struct {
+ unsigned int events;
+ unsigned int wait;
+} QuickstartListenArgs;
+
+#define QUICKSTART_IOC_MAGIC 'T'
+#define QUICKSTART_NOTIFY _IO(QUICKSTART_IOC_MAGIC, QS_NOTIFY)
+#define QUICKSTART_LISTEN _IOR(QUICKSTART_IOC_MAGIC, QS_LISTEN, QuickstartListenArgs)
+#define QUICKSTART_STAGE(x) _IO(QUICKSTART_IOC_MAGIC, (x))
+
+#define QUICKSTART_NODE "/dev/quickstart"
+
+#define QS_STAGE_CNT (QS_STAGE_LIMIT - QS_STAGE1)
+
+typedef void (*SysteminitHook)(void);
+
+typedef struct {
+ SysteminitHook func[QS_STAGE_CNT];
+} LosSysteminitHook;
+
+extern void QuickstartHookRegister(LosSysteminitHook hooks);
+
+extern int QuickstartDevRegister(void);
+
+#ifdef __cplusplus
+#if __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+#endif
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/quickstart/src/quickstart.c b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/quickstart/src/quickstart.c
new file mode 100644
index 00000000..5f55bc14
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/quickstart/src/quickstart.c
@@ -0,0 +1,142 @@
+/*
+ * 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_dev_quickstart.h"
+#include "fcntl.h"
+#include "linux/kernel.h"
+#include "los_process_pri.h"
+#include "fs/file.h"
+#include "fs/driver.h"
+
+EVENT_CB_S g_qsEvent;
+static SysteminitHook g_systemInitFunc[QS_STAGE_CNT] = {0};
+static char g_callOnce[QS_STAGE_CNT] = {0};
+
+static int QuickstartOpen(struct file *filep)
+{
+ return 0;
+}
+
+static int QuickstartClose(struct file *filep)
+{
+ return 0;
+}
+
+static int QuickstartNotify(unsigned int events)
+{
+ int ret = LOS_EventWrite((PEVENT_CB_S)&g_qsEvent, events);
+ if (ret != 0) {
+ PRINT_ERR("%s,%d:0x%x\n", __FUNCTION__, __LINE__, ret);
+ ret = -EINVAL;
+ }
+ return ret;
+}
+
+#define WAITLIMIT 300000 /* 5min = 5*60*1000*1tick(1ms) */
+
+static int QuickstartListen(unsigned long arg)
+{
+ QuickstartListenArgs args;
+ if (copy_from_user(&args, (QuickstartListenArgs __user *)arg, sizeof(QuickstartListenArgs)) != LOS_OK) {
+ PRINT_ERR("%s,%d,failed!\n", __FUNCTION__, __LINE__);
+ return -EINVAL;
+ }
+ if (args.wait > WAITLIMIT) {
+ args.wait = WAITLIMIT;
+ PRINT_ERR("%s wait arg is too longer, set to WAITLIMIT!\n", __FUNCTION__);
+ }
+ int ret = LOS_EventRead((PEVENT_CB_S)&g_qsEvent, args.events, LOS_WAITMODE_AND | LOS_WAITMODE_CLR, args.wait);
+ if (ret != args.events && ret != 0) { /* 0: nowait is normal case */
+ PRINT_ERR("%s,%d:0x%x\n", __FUNCTION__, __LINE__, ret);
+ ret = -EINVAL;
+ }
+ return ret;
+}
+
+void QuickstartHookRegister(LosSysteminitHook hooks)
+{
+ for (int i = 0; i < QS_STAGE_CNT; i++) {
+ g_systemInitFunc[i] = hooks.func[i];
+ }
+}
+
+static int QuickstartStageWorking(unsigned int level)
+{
+ if ((level < QS_STAGE_CNT) && (g_callOnce[level] == 0) && (g_systemInitFunc[level] != NULL)) {
+ g_callOnce[level] = 1; /* 1: Already called */
+ g_systemInitFunc[level]();
+ } else {
+ PRINT_WARN("Trigger quickstart,but doing nothing!!\n");
+ }
+ return 0;
+}
+
+static int QuickstartDevUnlink(struct Vnode *node)
+{
+ (void)node;
+ return unregister_driver(QUICKSTART_NODE);
+}
+
+static ssize_t QuickstartIoctl(struct file *filep, int cmd, unsigned long arg)
+{
+ ssize_t ret;
+ if (cmd == QUICKSTART_NOTIFY) {
+ return QuickstartNotify(arg);
+ }
+
+ if (OsGetUserInitProcessID() != LOS_GetCurrProcessID()) {
+ PRINT_ERR("Permission denios!\n");
+ return -EACCES;
+ }
+ switch (cmd) {
+ case QUICKSTART_LISTEN:
+ ret = QuickstartListen(arg);
+ break;
+ default:
+ ret = QuickstartStageWorking(cmd - QUICKSTART_STAGE(QS_STAGE1)); /* ioctl cmd converted to stage level */
+ break;
+ }
+ return ret;
+}
+
+static const struct file_operations_vfs g_quickstartDevOps = {
+ .open = QuickstartOpen, /* open */
+ .close = QuickstartClose, /* close */
+ .ioctl = QuickstartIoctl, /* ioctl */
+ .unlink = QuickstartDevUnlink, /* unlink */
+};
+
+int QuickstartDevRegister(void)
+{
+ LOS_EventInit(&g_qsEvent);
+ return register_driver(QUICKSTART_NODE, &g_quickstartDevOps, 0644, 0); /* 0644: file mode */
+}
+
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/random/BUILD.gn b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/random/BUILD.gn
new file mode 100644
index 00000000..0410df5b
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/random/BUILD.gn
@@ -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.
+
+import("//kernel/liteos_a/liteos.gni")
+
+module_switch = defined(LOSCFG_DRIVERS_RANDOM)
+module_name = get_path_info(rebase_path("."), "name")
+kernel_module(module_name) {
+ sources = [ "src/random.c" ]
+
+ if (defined(LOSCFG_HW_RANDOM_ENABLE)) {
+ sources += [ "src/random_hw.c" ]
+ }
+
+ public_configs = [ ":public" ]
+}
+
+config("public") {
+ include_dirs = [ "include" ]
+}
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/random/Kconfig b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/random/Kconfig
new file mode 100644
index 00000000..5b75e0e5
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/random/Kconfig
@@ -0,0 +1,12 @@
+config DRIVERS_RANDOM
+ bool "Enable random"
+ default y
+ depends on DRIVERS && FS_VFS && COMPAT_BSD
+ help
+ Answer Y to support random.
+config HW_RANDOM_ENABLE
+ depends on DRIVERS_RANDOM && (PLATFORM_HI3518EV300 || PLATFORM_HI3516CV300 || PLATFORM_HI3516DV300 || PLATFORM_HI3556V200 || PLATFORM_QEMU_ARM_VIRT_CA7)
+ bool "Select hw random"
+ default y
+ help
+ Answer Y to select hw random.
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/random/Makefile b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/random/Makefile
new file mode 100644
index 00000000..6f43d9ee
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/random/Makefile
@@ -0,0 +1,40 @@
+# 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 $(LITEOSTOPDIR)/config.mk
+
+MODULE_NAME := $(notdir $(shell pwd))
+
+LOCAL_SRCS := $(wildcard src/random.c)
+
+ifdef LOSCFG_HW_RANDOM_ENABLE
+LOCAL_SRCS += $(wildcard src/random_hw.c)
+endif
+
+include $(MODULE)
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/random/include/los_random.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/random/include/los_random.h
new file mode 100644
index 00000000..298449ea
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/random/include/los_random.h
@@ -0,0 +1,66 @@
+/*
+ * 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 __LOS_RANDOM_H__
+#define __LOS_RANDOM_H__
+
+#include "los_typedef.h"
+#include "sys/ioctl.h"
+
+#ifdef __cplusplus
+#if __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+#define RAMDOM_IOC_MAGIC 'r'
+#define RANDOM_SET_MAX _IO(RAMDOM_IOC_MAGIC, 1)
+
+int DevRandomRegister(void);
+int DevUrandomRegister(void);
+
+typedef struct {
+ int (*support)(void); /* Whether hard random numbers are supported */
+ void (*init)(void); /* Initializing the hard random number generator */
+ void (*deinit)(void); /* Deinitializing the hard random number generator */
+ int (*read)(char *buffer, size_t buflen); /* Read hard random number */
+ int (*ioctl)(int cmd, unsigned long arg); /* Control hard random number generator */
+} RandomOperations;
+
+void RandomOperationsInit(const RandomOperations *r);
+
+#ifdef __cplusplus
+#if __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+#endif
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/random/src/random.c b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/random/src/random.c
new file mode 100644
index 00000000..365249e1
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/random/src/random.c
@@ -0,0 +1,119 @@
+/*
+ * 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_random.h"
+#include "fcntl.h"
+#include "linux/kernel.h"
+#include "fs/driver.h"
+
+
+static unsigned long g_randomMax = 0x7FFFFFFF;
+
+static long DoRand(unsigned long *value)
+{
+ long quotient, remainder, t;
+
+ quotient = *value / 127773L;
+ remainder = *value % 127773L;
+ t = 16807L * remainder - 2836L * quotient;
+ if (t <= 0) {
+ t += 0x7fffffff;
+ }
+ return ((*value = t) % (g_randomMax + 1));
+}
+
+static unsigned long g_seed = 1;
+
+int RanOpen(struct file *filep)
+{
+ g_seed = (unsigned long)(LOS_CurrNanosec() & 0xffffffff);
+ return 0;
+}
+
+static int RanClose(struct file *filep)
+{
+ return 0;
+}
+
+int RanIoctl(struct file *filep, int cmd, unsigned long arg)
+{
+ PRINT_ERR("random ioctl is not supported\n");
+ return -ENOTSUP;
+}
+
+ssize_t RanRead(struct file *filep, char *buffer, size_t buflen)
+{
+ ssize_t len = buflen;
+ char *buf = buffer;
+ unsigned int temp;
+ int ret;
+
+ if (len % sizeof(unsigned int)) {
+ PRINT_ERR("random size not aligned by 4 bytes\n");
+ return -EINVAL;
+ }
+ while (len > 0) {
+ temp = DoRand(&g_seed);
+ ret = LOS_CopyFromKernel((void *)buf, sizeof(unsigned int), (void *)&temp, sizeof(unsigned int));
+ if (ret) {
+ break;
+ }
+ len -= sizeof(unsigned int);
+ buf += sizeof(unsigned int);
+ }
+ return (buflen - len); /* return a successful len */
+}
+
+static ssize_t RanMap(struct file *filep, LosVmMapRegion *region)
+{
+ PRINTK("%s %d, mmap is not support\n", __FUNCTION__, __LINE__);
+ return 0;
+}
+
+static const struct file_operations_vfs g_ranDevOps = {
+ RanOpen, /* open */
+ RanClose, /* close */
+ RanRead, /* read */
+ NULL, /* write */
+ NULL, /* seek */
+ RanIoctl, /* ioctl */
+ RanMap, /* mmap */
+#ifndef CONFIG_DISABLE_POLL
+ NULL, /* poll */
+#endif
+ NULL, /* unlink */
+};
+
+int DevRandomRegister(void)
+{
+ return register_driver("/dev/random", &g_ranDevOps, 0666, 0); /* 0666: file mode */
+}
+
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/random/src/random_hw.c b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/random/src/random_hw.c
new file mode 100644
index 00000000..04934a14
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/random/src/random_hw.c
@@ -0,0 +1,123 @@
+/*
+ * 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_random.h"
+#include "fcntl.h"
+#include "hisoc/random.h"
+#include "linux/kernel.h"
+#include "fs/driver.h"
+
+static RandomOperations g_randomOp;
+void RandomOperationsInit(const RandomOperations *r)
+{
+ if (r != NULL) {
+ (void)memcpy_s(&g_randomOp, sizeof(RandomOperations), r, sizeof(RandomOperations));
+ } else {
+ PRINT_ERR("%s %d param is invalid\n", __FUNCTION__, __LINE__);
+ }
+ return;
+}
+static int RandomHwOpen(struct file *filep)
+{
+ if (g_randomOp.init != NULL) {
+ g_randomOp.init();
+ return ENOERR;
+ }
+ return -1;
+}
+
+static int RandomHwClose(struct file *filep)
+{
+ if (g_randomOp.deinit != NULL) {
+ g_randomOp.deinit();
+ return ENOERR;
+ }
+ return -1;
+}
+
+static int RandomHwIoctl(struct file *filep, int cmd, unsigned long arg)
+{
+ int ret = -1;
+
+ switch (cmd) {
+ default:
+ PRINT_ERR("!!!bad command!!!\n");
+ return -EINVAL;
+ }
+ return ret;
+}
+
+static ssize_t RandomHwRead(struct file *filep, char *buffer, size_t buflen)
+{
+ int ret = -1;
+
+ if (g_randomOp.read != NULL) {
+ ret = g_randomOp.read(buffer, buflen);
+ if (ret == ENOERR) {
+ ret = buflen;
+ }
+ } else {
+ ret = -1;
+ }
+ return ret;
+}
+
+static ssize_t RandomMap(struct file *filep, LosVmMapRegion *region)
+{
+ PRINTK("%s %d, mmap is not support\n", __FUNCTION__, __LINE__);
+ return 0;
+}
+
+static const struct file_operations_vfs g_randomHwDevOps = {
+ RandomHwOpen, /* open */
+ RandomHwClose, /* close */
+ RandomHwRead, /* read */
+ NULL, /* write */
+ NULL, /* seek */
+ RandomHwIoctl, /* ioctl */
+ RandomMap, /* mmap */
+#ifndef CONFIG_DISABLE_POLL
+ NULL, /* poll */
+#endif
+ NULL, /* unlink */
+};
+
+int DevUrandomRegister(void)
+{
+ if (g_randomOp.support != NULL) {
+ int ret = g_randomOp.support();
+ if (ret) {
+ return register_driver("/dev/urandom", &g_randomHwDevOps, 0666, 0); /* 0666: file mode */
+ }
+ }
+ return -EPERM;
+}
+
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/trace/BUILD.gn b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/trace/BUILD.gn
new file mode 100644
index 00000000..4411dbe8
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/trace/BUILD.gn
@@ -0,0 +1,42 @@
+# 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("//kernel/liteos_a/liteos.gni")
+
+module_switch = defined(LOSCFG_DRIVERS_TRACE)
+module_name = "trace_dev"
+kernel_module(module_name) {
+ sources = [ "src/trace.c" ]
+
+ public_configs = [ ":public" ]
+}
+
+config("public") {
+ include_dirs = [ "include" ]
+}
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/trace/Kconfig b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/trace/Kconfig
new file mode 100644
index 00000000..70cc87cb
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/trace/Kconfig
@@ -0,0 +1,6 @@
+config DRIVERS_TRACE
+ bool "Enable TRACE DRIVER"
+ default y
+ depends on DRIVERS && FS_VFS && KERNEL_TRACE
+ help
+ Answer Y to enable LiteOS support trace in userspace.
\ No newline at end of file
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/trace/Makefile b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/trace/Makefile
new file mode 100644
index 00000000..f4fa8887
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/trace/Makefile
@@ -0,0 +1,40 @@
+# 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 $(LITEOSTOPDIR)/config.mk
+
+MODULE_NAME := trace_dev
+
+LOCAL_SRCS := $(wildcard src/*.c)
+
+LOCAL_INCLUDE := -I $(LITEOSTOPDIR)/drivers/char/trace/include
+
+LOCAL_FLAGS := $(LOCAL_INCLUDE)
+
+include $(MODULE)
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/trace/include/los_dev_trace.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/trace/include/los_dev_trace.h
new file mode 100644
index 00000000..da9901eb
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/trace/include/los_dev_trace.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 __LOS_DEV_TRACE_H__
+#define __LOS_DEV_TRACE_H__
+
+#ifdef __cplusplus
+#if __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+int DevTraceRegister(void);
+
+#ifdef __cplusplus
+#if __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+#endif
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/trace/src/trace.c b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/trace/src/trace.c
new file mode 100644
index 00000000..9bb001fa
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/trace/src/trace.c
@@ -0,0 +1,160 @@
+/*
+ * 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 "fcntl.h"
+#include "linux/kernel.h"
+#include "sys/ioctl.h"
+#include "fs/driver.h"
+#include "los_dev_trace.h"
+#include "los_trace.h"
+#include "los_hook.h"
+#include "los_init.h"
+
+#define TRACE_DRIVER "/dev/trace"
+#define TRACE_DRIVER_MODE 0666
+
+/* trace ioctl */
+#define TRACE_IOC_MAGIC 'T'
+#define TRACE_START _IO(TRACE_IOC_MAGIC, 1)
+#define TRACE_STOP _IO(TRACE_IOC_MAGIC, 2)
+#define TRACE_RESET _IO(TRACE_IOC_MAGIC, 3)
+#define TRACE_DUMP _IO(TRACE_IOC_MAGIC, 4)
+#define TRACE_SET_MASK _IO(TRACE_IOC_MAGIC, 5)
+
+static int TraceOpen(struct file *filep)
+{
+ return 0;
+}
+
+static int TraceClose(struct file *filep)
+{
+ return 0;
+}
+
+static ssize_t TraceRead(struct file *filep, char *buffer, size_t buflen)
+{
+ /* trace record buffer read */
+ ssize_t len = buflen;
+ OfflineHead *records;
+ int ret;
+ int realLen;
+
+ if (len % sizeof(unsigned int)) {
+ PRINT_ERR("Buffer size not aligned by 4 bytes\n");
+ return -EINVAL;
+ }
+
+ records = LOS_TraceRecordGet();
+ if (records == NULL) {
+ PRINT_ERR("Trace read failed, check whether trace mode is set to offline\n");
+ return -EINVAL;
+ }
+
+ realLen = buflen < records->totalLen ? buflen : records->totalLen;
+ ret = LOS_CopyFromKernel((void *)buffer, buflen, (void *)records, realLen);
+ if (ret != 0) {
+ return -EINVAL;
+ }
+
+ return realLen;
+}
+
+static ssize_t TraceWrite(struct file *filep, const char *buffer, size_t buflen)
+{
+ /* trace usr event here */
+ int ret;
+ UsrEventInfo *info = NULL;
+ int infoLen = sizeof(UsrEventInfo);
+
+ if (buflen != infoLen) {
+ PRINT_ERR("Buffer size not %d bytes\n", infoLen);
+ return -EINVAL;
+ }
+
+ info = LOS_MemAlloc(m_aucSysMem0, infoLen);
+ if (info == NULL) {
+ return -ENOMEM;
+ }
+ (void)memset_s(info, infoLen, 0, infoLen);
+
+ ret = LOS_CopyToKernel(info, infoLen, buffer, buflen);
+ if (ret != 0) {
+ LOS_MemFree(m_aucSysMem0, info);
+ return -EINVAL;
+ }
+ OsHookCall(LOS_HOOK_TYPE_USR_EVENT, info, infoLen);
+ return 0;
+}
+
+static int TraceIoctl(struct file *filep, int cmd, unsigned long arg)
+{
+ switch (cmd) {
+ case TRACE_START:
+ return LOS_TraceStart();
+ case TRACE_STOP:
+ LOS_TraceStop();
+ break;
+ case TRACE_RESET:
+ LOS_TraceReset();
+ break;
+ case TRACE_DUMP:
+ LOS_TraceRecordDump((BOOL)arg);
+ break;
+ case TRACE_SET_MASK:
+ LOS_TraceEventMaskSet((UINT32)arg);
+ break;
+ default:
+ PRINT_ERR("Unknown trace ioctl cmd:%d\n", cmd);
+ return -EINVAL;
+ }
+ return 0;
+}
+
+static const struct file_operations_vfs g_traceDevOps = {
+ TraceOpen, /* open */
+ TraceClose, /* close */
+ TraceRead, /* read */
+ TraceWrite, /* write */
+ NULL, /* seek */
+ TraceIoctl, /* ioctl */
+ NULL, /* mmap */
+#ifndef CONFIG_DISABLE_POLL
+ NULL, /* poll */
+#endif
+ NULL, /* unlink */
+};
+
+int DevTraceRegister(void)
+{
+ return register_driver(TRACE_DRIVER, &g_traceDevOps, TRACE_DRIVER_MODE, 0); /* 0666: file mode */
+}
+
+LOS_MODULE_INIT(DevTraceRegister, LOS_INIT_LEVEL_KMOD_EXTENDED);
\ No newline at end of file
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/video/BUILD.gn b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/video/BUILD.gn
new file mode 100644
index 00000000..a7fcc3f9
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/video/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("//kernel/liteos_a/liteos.gni")
+import("//third_party/NuttX/NuttX.gni")
+
+module_switch = defined(LOSCFG_DRIVERS_VIDEO)
+module_name = get_path_info(rebase_path("."), "name")
+kernel_module(module_name) {
+ sources = NUTTX_DRIVERS_VIDEO_SRC_FILES
+
+ public_configs = [ ":public" ]
+}
+
+config("public") {
+ include_dirs = NUTTX_DRIVERS_VIDEO_INCLUDE_DIRS
+}
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/video/Kconfig b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/video/Kconfig
new file mode 100644
index 00000000..3fad196a
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/video/Kconfig
@@ -0,0 +1,6 @@
+config DRIVERS_VIDEO
+ bool "Enable Video"
+ default y
+ depends on DRIVERS
+ help
+ Answer Y to enable LiteOS support video driver.
\ No newline at end of file
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/video/Makefile b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/video/Makefile
new file mode 100644
index 00000000..790d2e62
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/char/video/Makefile
@@ -0,0 +1,40 @@
+# 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 $(LITEOSTOPDIR)/config.mk
+
+MODULE_NAME := $(notdir $(shell pwd))
+
+LOCAL_SRCS := $(LITEOSTHIRDPARTY)/NuttX/drivers/video/fb.c
+
+LOCAL_INCLUDE := -I $(LITEOSTHIRDPARTY)/NuttX/include/nuttx/video
+
+LOCAL_FLAGS := $(LOCAL_INCLUDE)
+
+include $(MODULE)
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/mtd/BUILD.gn b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/mtd/BUILD.gn
new file mode 100644
index 00000000..5a1be361
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/mtd/BUILD.gn
@@ -0,0 +1,34 @@
+# 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("//kernel/liteos_a/liteos.gni")
+
+module_group("mtd") {
+ modules = [ "multi_partition" ]
+}
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/mtd/multi_partition/BUILD.gn b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/mtd/multi_partition/BUILD.gn
new file mode 100644
index 00000000..5278330a
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/mtd/multi_partition/BUILD.gn
@@ -0,0 +1,51 @@
+# 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("//kernel/liteos_a/liteos.gni")
+
+module_switch = defined(LOSCFG_FS_VFS)
+module_name = get_path_info(rebase_path("."), "name")
+kernel_module(module_name) {
+ sources = [
+ "src/mtd_partition.c",
+ "src/mtd_shellcmd.c",
+ ]
+
+ include_dirs = [ "$LITEOSTOPDIR/fs/jffs2/include" ]
+
+ if (defined(LOSCFG_PLATFORM_QEMU_ARM_VIRT_CA7)) {
+ include_dirs += [ "//device/qemu/drivers/cfiflash" ]
+ }
+
+ public_configs = [ ":public" ]
+}
+
+config("public") {
+ include_dirs = [ "include" ]
+}
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/mtd/multi_partition/Makefile b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/mtd/multi_partition/Makefile
new file mode 100644
index 00000000..76f8973f
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/mtd/multi_partition/Makefile
@@ -0,0 +1,45 @@
+# 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 $(LITEOSTOPDIR)/config.mk
+
+MODULE_NAME := $(notdir $(shell pwd))
+
+LOCAL_SRCS := $(wildcard src/*.c)
+
+LOCAL_INCLUDE := \
+ -I $(LITEOSTOPDIR)/fs/jffs2/include
+
+ifeq ($(LOSCFG_PLATFORM_QEMU_ARM_VIRT_CA7), y)
+LOCAL_INCLUDE += -I $(LITEOSTOPDIR)/../../device/qemu/drivers/cfiflash
+endif
+
+LOCAL_FLAGS := $(LOCAL_INCLUDE)
+
+include $(MODULE)
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/mtd/multi_partition/include/mtd_dev.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/mtd/multi_partition/include/mtd_dev.h
new file mode 100644
index 00000000..30f41da6
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/mtd/multi_partition/include/mtd_dev.h
@@ -0,0 +1,59 @@
+/*
+ * 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 __MTD_DEV_H__
+#define __MTD_DEV_H__
+
+#include "los_typedef.h"
+
+#define MTD_NORFLASH 3
+#define MTD_NANDFLASH 4
+#define MTD_DATAFLASH 6
+#define MTD_MLCNANDFLASH 8
+
+struct MtdNorDev {
+ unsigned long blockSize;
+ unsigned long blockStart;
+ unsigned long blockEnd;
+};
+
+struct MtdDev {
+ VOID *priv;
+ UINT32 type;
+
+ UINT64 size;
+ UINT32 eraseSize;
+
+ int (*erase)(struct MtdDev *mtd, UINT64 start, UINT64 len, UINT64 *failAddr);
+ int (*read)(struct MtdDev *mtd, UINT64 start, UINT64 len, const char *buf);
+ int (*write)(struct MtdDev *mtd, UINT64 start, UINT64 len, const char *buf);
+};
+
+#endif /* __MTD_DEV_H__ */
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/mtd/multi_partition/include/mtd_list.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/mtd/multi_partition/include/mtd_list.h
new file mode 100644
index 00000000..cf4f7725
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/mtd/multi_partition/include/mtd_list.h
@@ -0,0 +1,62 @@
+/*
+ * 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 __MTD_LIST_H__
+#define __MTD_LIST_H__
+
+#include "sys/types.h"
+#include "mtd_dev.h"
+
+#ifdef __cplusplus
+#if __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+typedef struct Node {
+ char *type;
+ int status;
+ struct MtdDev *mtd;
+ struct Node *next;
+} Lnode, *Linklist;
+
+void* GetMtd(const char *type);
+int GetMtdInfo(const char *type);
+int FreeMtd(struct MtdDev *mtd);
+int DelMtdList(struct MtdDev *mtd);
+void AddMtdList(char *type, struct MtdDev *mtd);
+
+#ifdef __cplusplus
+#if __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+#endif /* __MTD_LIST_H__ */
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/mtd/multi_partition/include/mtd_partition.h b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/mtd/multi_partition/include/mtd_partition.h
new file mode 100644
index 00000000..2fec42d7
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/mtd/multi_partition/include/mtd_partition.h
@@ -0,0 +1,160 @@
+/*
+ * 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.
+ */
+
+/**
+ * @defgroup filesystem FileSystem
+ * @defgroup mtd_partition Multi Partition
+ * @ingroup filesystem
+ */
+#ifndef _MTD_PARTITION_H
+#define _MTD_PARTITION_H
+
+#include "sys/types.h"
+#include "los_mux.h"
+#include "mtd_list.h"
+
+#ifdef __cplusplus
+#if __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+#define SPIBLK_NAME "/dev/spinorblk"
+#define SPICHR_NAME "/dev/spinorchr"
+
+#define NANDBLK_NAME "/dev/nandblk"
+#define NANDCHR_NAME "/dev/nandchr"
+
+typedef struct mtd_node {
+ UINT32 start_block;
+ UINT32 end_block;
+ UINT32 patitionnum;
+ CHAR *blockdriver_name;
+ CHAR *chardriver_name;
+ CHAR *mountpoint_name;
+ VOID *mtd_info; /* Driver used by a partition */
+ LOS_DL_LIST node_info;
+ LosMux lock;
+ UINT32 user_num;
+} mtd_partition;
+
+typedef struct par_param {
+ mtd_partition *partition_head;
+ struct MtdDev *flash_mtd;
+ const struct block_operations *flash_ops;
+ const struct file_operations_vfs *char_ops;
+ CHAR *blockname;
+ CHAR *charname;
+ UINT32 block_size;
+} partition_param;
+
+#define CONFIG_MTD_PATTITION_NUM 20
+
+#define ALIGN_ASSIGN(len, startAddr, startBlk, endBlk, blkSize) do { \
+ (len) = (((len) + ((blkSize) - 1)) & ~((blkSize) - 1)); \
+ (startAddr) = ((startAddr) & ~((blkSize) - 1)); \
+ (startBlk) = (startAddr) / (blkSize); \
+ (endBlk) = (len) / (blkSize) + ((startBlk) - 1); \
+} while (0)
+
+#define PAR_ASSIGNMENT(node, len, startAddr, num, mtd, blkSize) do { \
+ (node)->start_block = (startAddr) / (blkSize); \
+ (node)->end_block = (len) / (blkSize) + ((node)->start_block - 1); \
+ (node)->patitionnum = (num); \
+ (node)->mtd_info = (mtd); \
+ (node)->mountpoint_name = NULL; \
+} while (0)
+
+partition_param *GetNandPartParam(VOID);
+partition_param *GetSpinorPartParam(VOID);
+mtd_partition *GetSpinorPartitionHead(VOID);
+
+/**
+ * @ingroup mtd_partition
+ * @brief Add a partition.
+ *
+ * @par Description:
+ *
+ *
This API is used to add a partition according to the passed-in parameters.
+ *
+ * @attention
+ *
+ *
None.
+ *
+ *
+ * @param type [IN] Storage medium type, support "nand" and "spinor" currently.
+ * @param startAddr [IN] Starting address of a partition.
+ * @param length [IN] Partition size.
+ * @param partitionNum [IN] Partition number, less than the value defined by CONFIG_MTD_PATTITION_NUM.
+ *
+ * @retval #-ENODEV The driver is not found.
+ * @retval #-EINVAL Invalid parameter.
+ * @retval #-ENOMEM Insufficient memory.
+ * @retval #ENOERR The partition is successfully created.
+ *
+ * @par Dependency:
+ *
mtd_partition.h: the header file that contains the API declaration.
This API is used to delete a partition according to its partition number and storage medium type.
+ *
+ * @attention
+ *
+ *
None.
+ *
+ *
+ * @param partitionNum [IN] Partition number, less than the value defined by CONFIG_MTD_PATTITION_NUM.
+ * @param type [IN] Storage medium type, support "nand" and "spinor" currently.
+ *
+ * @retval #-EINVAL Invalid parameter.
+ * @retval #ENOERR The partition is successfully deleted.
+ *
+ * @par Dependency:
+ *
mtd_partition.h: the header file that contains the API declaration.
+ * @see add_mtd_partition
+ */
+extern INT32 delete_mtd_partition(UINT32 partitionNum, const CHAR *type);
+
+#ifdef __cplusplus
+#if __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* __cplusplus */
+
+#endif /* _MTD_PARTITION_H */
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/mtd/multi_partition/src/mtd_partition.c b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/mtd/multi_partition/src/mtd_partition.c
new file mode 100644
index 00000000..e5414618
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/mtd/multi_partition/src/mtd_partition.c
@@ -0,0 +1,554 @@
+/*
+ * 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 "mtd_partition.h"
+#include "stdlib.h"
+#include "stdio.h"
+#include "pthread.h"
+#include "mtd_list.h"
+#include "los_config.h"
+#include "los_mux.h"
+#include "fs/driver.h"
+#include "mtd/mtd_legacy_lite.h"
+
+#ifdef LOSCFG_PLATFORM_QEMU_ARM_VIRT_CA7
+#include "cfiflash.h"
+#endif
+
+
+#define DRIVER_NAME_ADD_SIZE 3
+pthread_mutex_t g_mtdPartitionLock = PTHREAD_MUTEX_INITIALIZER;
+
+static VOID YaffsLockInit(VOID) __attribute__((weakref("yaffsfs_OSInitialisation")));
+static VOID YaffsLockDeinit(VOID) __attribute__((weakref("yaffsfs_OsDestroy")));
+static INT32 Jffs2LockInit(VOID) __attribute__((weakref("Jffs2MutexCreate")));
+static VOID Jffs2LockDeinit(VOID) __attribute__((weakref("Jffs2MutexDelete")));
+
+partition_param *g_nandPartParam = NULL;
+partition_param *g_spinorPartParam = NULL;
+mtd_partition *g_spinorPartitionHead = NULL;
+mtd_partition *g_nandPartitionHead = NULL;
+
+#define RWE_RW_RW 0755
+
+partition_param *GetNandPartParam(VOID)
+{
+ return g_nandPartParam;
+}
+
+partition_param *GetSpinorPartParam(VOID)
+{
+ return g_spinorPartParam;
+}
+
+mtd_partition *GetSpinorPartitionHead(VOID)
+{
+ return g_spinorPartitionHead;
+}
+
+
+static VOID MtdNandParamAssign(partition_param *nandParam, const struct MtdDev *nandMtd)
+{
+ LOS_ListInit(&g_nandPartitionHead->node_info);
+ /*
+ * If the user do not want to use block mtd or char mtd ,
+ * you can change the NANDBLK_NAME or NANDCHR_NAME to NULL.
+ */
+ nandParam->flash_mtd = (struct MtdDev *)nandMtd;
+ nandParam->flash_ops = GetDevNandOps();
+ nandParam->char_ops = GetMtdCharFops();
+ nandParam->blockname = NANDBLK_NAME;
+ nandParam->charname = NANDCHR_NAME;
+ nandParam->partition_head = g_nandPartitionHead;
+ nandParam->block_size = nandMtd->eraseSize;
+}
+
+static VOID MtdDeinitNandParam(VOID)
+{
+ if (YaffsLockDeinit != NULL) {
+ YaffsLockDeinit();
+ }
+}
+
+static partition_param *MtdInitNandParam(partition_param *nandParam)
+{
+ struct MtdDev *nandMtd = GetMtd("nand");
+ if (nandMtd == NULL) {
+ return NULL;
+ }
+ if (nandParam == NULL) {
+ if (YaffsLockInit != NULL) {
+ YaffsLockInit();
+ }
+ nandParam = (partition_param *)zalloc(sizeof(partition_param));
+ if (nandParam == NULL) {
+ MtdDeinitNandParam();
+ return NULL;
+ }
+ g_nandPartitionHead = (mtd_partition *)zalloc(sizeof(mtd_partition));
+ if (g_nandPartitionHead == NULL) {
+ MtdDeinitNandParam();
+ free(nandParam);
+ return NULL;
+ }
+
+ MtdNandParamAssign(nandParam, nandMtd);
+ }
+
+ return nandParam;
+}
+
+static VOID MtdNorParamAssign(partition_param *spinorParam, const struct MtdDev *spinorMtd)
+{
+ LOS_ListInit(&g_spinorPartitionHead->node_info);
+ /*
+ * If the user do not want to use block mtd or char mtd ,
+ * you can change the SPIBLK_NAME or SPICHR_NAME to NULL.
+ */
+ spinorParam->flash_mtd = (struct MtdDev *)spinorMtd;
+#ifndef LOSCFG_PLATFORM_QEMU_ARM_VIRT_CA7
+ spinorParam->flash_ops = GetDevSpinorOps();
+ spinorParam->char_ops = GetMtdCharFops();
+ spinorParam->blockname = SPIBLK_NAME;
+ spinorParam->charname = SPICHR_NAME;
+#else
+ spinorParam->flash_ops = GetCfiBlkOps();
+ spinorParam->char_ops = NULL;
+ spinorParam->blockname = CFI_DRIVER;
+ spinorParam->charname = NULL;
+#endif
+ spinorParam->partition_head = g_spinorPartitionHead;
+ spinorParam->block_size = spinorMtd->eraseSize;
+}
+
+static VOID MtdDeinitSpinorParam(VOID)
+{
+ if (Jffs2LockDeinit != NULL) {
+ Jffs2LockDeinit();
+ }
+}
+
+static partition_param *MtdInitSpinorParam(partition_param *spinorParam)
+{
+#ifndef LOSCFG_PLATFORM_QEMU_ARM_VIRT_CA7
+ struct MtdDev *spinorMtd = GetMtd("spinor");
+#else
+ struct MtdDev *spinorMtd = GetCfiMtdDev();
+#endif
+ if (spinorMtd == NULL) {
+ return NULL;
+ }
+ if (spinorParam == NULL) {
+ if (Jffs2LockInit != NULL) {
+ if (Jffs2LockInit() != 0) { /* create jffs2 lock failed */
+ return NULL;
+ }
+ }
+ spinorParam = (partition_param *)zalloc(sizeof(partition_param));
+ if (spinorParam == NULL) {
+ PRINT_ERR("%s, partition_param malloc failed\n", __FUNCTION__);
+ MtdDeinitSpinorParam();
+ return NULL;
+ }
+ g_spinorPartitionHead = (mtd_partition *)zalloc(sizeof(mtd_partition));
+ if (g_spinorPartitionHead == NULL) {
+ PRINT_ERR("%s, mtd_partition malloc failed\n", __FUNCTION__);
+ MtdDeinitSpinorParam();
+ free(spinorParam);
+ return NULL;
+ }
+
+ MtdNorParamAssign(spinorParam, spinorMtd);
+ }
+
+ return spinorParam;
+}
+
+/* According the flash-type to init the param of the partition. */
+static INT32 MtdInitFsparParam(const CHAR *type, partition_param **fsparParam)
+{
+ if (strcmp(type, "nand") == 0) {
+ g_nandPartParam = MtdInitNandParam(g_nandPartParam);
+ *fsparParam = g_nandPartParam;
+ } else if (strcmp(type, "spinor") == 0 || strcmp(type, "cfi-flash") == 0) {
+ g_spinorPartParam = MtdInitSpinorParam(g_spinorPartParam);
+ *fsparParam = g_spinorPartParam;
+ } else {
+ return -EINVAL;
+ }
+
+ if ((*fsparParam == NULL) || ((VOID *)((*fsparParam)->flash_mtd) == NULL)) {
+ return -ENODEV;
+ }
+
+ return ENOERR;
+}
+
+/* According the flash-type to deinit the param of the partition. */
+static INT32 MtdDeinitFsparParam(const CHAR *type)
+{
+ if (strcmp(type, "nand") == 0) {
+ MtdDeinitNandParam();
+ g_nandPartParam = NULL;
+ } else if (strcmp(type, "spinor") == 0 || strcmp(type, "cfi-flash") == 0) {
+ MtdDeinitSpinorParam();
+ g_spinorPartParam = NULL;
+ } else {
+ return -EINVAL;
+ }
+
+ return ENOERR;
+}
+
+static INT32 AddParamCheck(UINT32 startAddr,
+ const partition_param *param,
+ UINT32 partitionNum,
+ UINT32 length)
+{
+ UINT32 startBlk, endBlk;
+ mtd_partition *node = NULL;
+ if ((param->blockname == NULL) && (param->charname == NULL)) {
+ return -EINVAL;
+ }
+
+ if ((length == 0) || (length < param->block_size) ||
+ (((UINT64)(startAddr) + length) > param->flash_mtd->size)) {
+ return -EINVAL;
+ }
+
+ ALIGN_ASSIGN(length, startAddr, startBlk, endBlk, param->block_size);
+
+ if (startBlk > endBlk) {
+ return -EINVAL;
+ }
+ LOS_DL_LIST_FOR_EACH_ENTRY(node, ¶m->partition_head->node_info, mtd_partition, node_info) {
+ if ((node->start_block != 0) && (node->patitionnum == partitionNum)) {
+ return -EINVAL;
+ }
+ if ((startBlk > node->end_block) || (endBlk < node->start_block)) {
+ continue;
+ }
+ return -EINVAL;
+ }
+
+ return ENOERR;
+}
+
+static INT32 BlockDriverRegisterOperate(mtd_partition *newNode,
+ const partition_param *param,
+ UINT32 partitionNum)
+{
+ INT32 ret;
+ size_t driverNameSize;
+
+ if (param->blockname != NULL) {
+ driverNameSize = strlen(param->blockname) + DRIVER_NAME_ADD_SIZE;
+ newNode->blockdriver_name = (CHAR *)malloc(driverNameSize);
+ if (newNode->blockdriver_name == NULL) {
+ return -ENOMEM;
+ }
+
+ ret = snprintf_s(newNode->blockdriver_name, driverNameSize,
+ driverNameSize - 1, "%s%u", param->blockname, partitionNum);
+ if (ret < 0) {
+ free(newNode->blockdriver_name);
+ newNode->blockdriver_name = NULL;
+ return -ENAMETOOLONG;
+ }
+
+ ret = register_blockdriver(newNode->blockdriver_name, param->flash_ops,
+ RWE_RW_RW, newNode);
+ if (ret) {
+ free(newNode->blockdriver_name);
+ newNode->blockdriver_name = NULL;
+ PRINT_ERR("register blkdev partition error\n");
+ return ret;
+ }
+ } else {
+ newNode->blockdriver_name = NULL;
+ }
+ return ENOERR;
+}
+
+static INT32 CharDriverRegisterOperate(mtd_partition *newNode,
+ const partition_param *param,
+ UINT32 partitionNum)
+{
+ INT32 ret;
+ size_t driverNameSize;
+
+ if (param->charname != NULL) {
+ driverNameSize = strlen(param->charname) + DRIVER_NAME_ADD_SIZE;
+ newNode->chardriver_name = (CHAR *)malloc(driverNameSize);
+ if (newNode->chardriver_name == NULL) {
+ return -ENOMEM;
+ }
+
+ ret = snprintf_s(newNode->chardriver_name, driverNameSize,
+ driverNameSize - 1, "%s%u", param->charname, partitionNum);
+ if (ret < 0) {
+ free(newNode->chardriver_name);
+ newNode->chardriver_name = NULL;
+ return -ENAMETOOLONG;
+ }
+
+ ret = register_driver(newNode->chardriver_name, param->char_ops, RWE_RW_RW, newNode);
+ if (ret) {
+ PRINT_ERR("register chardev partition error\n");
+ free(newNode->chardriver_name);
+ newNode->chardriver_name = NULL;
+ return ret;
+ }
+ } else {
+ newNode->chardriver_name = NULL;
+ }
+ return ENOERR;
+}
+
+static INT32 BlockDriverUnregister(mtd_partition *node)
+{
+ INT32 ret;
+
+ if (node->blockdriver_name != NULL) {
+ ret = unregister_blockdriver(node->blockdriver_name);
+ if (ret == -EBUSY) {
+ PRINT_ERR("unregister blkdev partition error:%d\n", ret);
+ return ret;
+ }
+ free(node->blockdriver_name);
+ node->blockdriver_name = NULL;
+ }
+ return ENOERR;
+}
+
+static INT32 CharDriverUnregister(mtd_partition *node)
+{
+ INT32 ret;
+
+ if (node->chardriver_name != NULL) {
+ ret = unregister_driver(node->chardriver_name);
+ if (ret == -EBUSY) {
+ PRINT_ERR("unregister chardev partition error:%d\n", ret);
+ return ret;
+ }
+ free(node->chardriver_name);
+ node->chardriver_name = NULL;
+ }
+
+ return ENOERR;
+}
+
+/*
+ * Attention: both startAddr and length should be aligned with block size.
+ * If not, the actual start address and length won't be what you expected.
+ */
+INT32 add_mtd_partition(const CHAR *type, UINT32 startAddr,
+ UINT32 length, UINT32 partitionNum)
+{
+ INT32 ret;
+ mtd_partition *newNode = NULL;
+ partition_param *param = NULL;
+
+ if ((partitionNum >= CONFIG_MTD_PATTITION_NUM) || (type == NULL)) {
+ return -EINVAL;
+ }
+
+ ret = pthread_mutex_lock(&g_mtdPartitionLock);
+ if (ret != ENOERR) {
+ PRINT_ERR("%s %d, mutex lock failed, error:%d\n", __FUNCTION__, __LINE__, ret);
+ }
+
+ ret = MtdInitFsparParam(type, ¶m);
+ if (ret != ENOERR) {
+ goto ERROR_OUT;
+ }
+
+ ret = AddParamCheck(startAddr, param, partitionNum, length);
+ if (ret != ENOERR) {
+ goto ERROR_OUT;
+ }
+
+ newNode = (mtd_partition *)zalloc(sizeof(mtd_partition));
+ if (newNode == NULL) {
+ (VOID)pthread_mutex_unlock(&g_mtdPartitionLock);
+ return -ENOMEM;
+ }
+
+ PAR_ASSIGNMENT(newNode, length, startAddr, partitionNum, param->flash_mtd, param->block_size);
+
+ ret = BlockDriverRegisterOperate(newNode, param, partitionNum);
+ if (ret) {
+ goto ERROR_OUT1;
+ }
+
+ ret = CharDriverRegisterOperate(newNode, param, partitionNum);
+ if (ret) {
+ goto ERROR_OUT2;
+ }
+
+ LOS_ListTailInsert(¶m->partition_head->node_info, &newNode->node_info);
+ (VOID)LOS_MuxInit(&newNode->lock, NULL);
+
+ ret = pthread_mutex_unlock(&g_mtdPartitionLock);
+ if (ret != ENOERR) {
+ PRINT_ERR("%s %d, mutex unlock failed, error:%d\n", __FUNCTION__, __LINE__, ret);
+ }
+
+ return ENOERR;
+ERROR_OUT2:
+ (VOID)BlockDriverUnregister(newNode);
+ERROR_OUT1:
+ free(newNode);
+ERROR_OUT:
+ (VOID)pthread_mutex_unlock(&g_mtdPartitionLock);
+ return ret;
+}
+
+static INT32 DeleteParamCheck(UINT32 partitionNum,
+ const CHAR *type,
+ partition_param **param)
+{
+ if (strcmp(type, "nand") == 0) {
+ *param = g_nandPartParam;
+ } else if (strcmp(type, "spinor") == 0 || strcmp(type, "cfi-flash") == 0) {
+ *param = g_spinorPartParam;
+ } else {
+ PRINT_ERR("type error \n");
+ return -EINVAL;
+ }
+
+ if ((partitionNum >= CONFIG_MTD_PATTITION_NUM) ||
+ ((*param) == NULL) || ((*param)->flash_mtd == NULL)) {
+ return -EINVAL;
+ }
+ return ENOERR;
+}
+
+static INT32 DeletePartitionUnregister(mtd_partition *node)
+{
+ INT32 ret;
+
+ ret = BlockDriverUnregister(node);
+ if (ret == -EBUSY) {
+ return ret;
+ }
+
+ ret = CharDriverUnregister(node);
+ if (ret == -EBUSY) {
+ return ret;
+ }
+
+ return ENOERR;
+}
+
+static INT32 OsNodeGet(mtd_partition **node, UINT32 partitionNum, const partition_param *param)
+{
+ LOS_DL_LIST_FOR_EACH_ENTRY(*node, ¶m->partition_head->node_info, mtd_partition, node_info) {
+ if ((*node)->patitionnum == partitionNum) {
+ break;
+ }
+ }
+ if ((*node == NULL) || ((*node)->patitionnum != partitionNum) ||
+ ((*node)->mountpoint_name != NULL)) {
+ return -EINVAL;
+ }
+
+ return ENOERR;
+}
+
+static INT32 OsResourceRelease(mtd_partition *node, const CHAR *type, partition_param *param)
+{
+ (VOID)LOS_MuxDestroy(&node->lock);
+ LOS_ListDelete(&node->node_info);
+ (VOID)memset_s(node, sizeof(mtd_partition), 0, sizeof(mtd_partition));
+ free(node);
+ (VOID)FreeMtd(param->flash_mtd);
+ if (LOS_ListEmpty(¶m->partition_head->node_info)) {
+ free(param->partition_head);
+ param->partition_head = NULL;
+ free(param);
+
+ if (MtdDeinitFsparParam(type) != ENOERR) {
+ return -EINVAL;
+ }
+ }
+ return ENOERR;
+}
+
+INT32 delete_mtd_partition(UINT32 partitionNum, const CHAR *type)
+{
+ INT32 ret;
+ mtd_partition *node = NULL;
+ partition_param *param = NULL;
+
+ if (type == NULL) {
+ return -EINVAL;
+ }
+
+ ret = pthread_mutex_lock(&g_mtdPartitionLock);
+ if (ret != ENOERR) {
+ PRINT_ERR("%s %d, mutex lock failed, error:%d\n", __FUNCTION__, __LINE__, ret);
+ }
+
+ ret = DeleteParamCheck(partitionNum, type, ¶m);
+ if (ret) {
+ PRINT_ERR("delete_mtd_partition param invalid\n");
+ (VOID)pthread_mutex_unlock(&g_mtdPartitionLock);
+ return ret;
+ }
+
+ ret = OsNodeGet(&node, partitionNum, param);
+ if (ret) {
+ (VOID)pthread_mutex_unlock(&g_mtdPartitionLock);
+ return ret;
+ }
+
+ ret = DeletePartitionUnregister(node);
+ if (ret) {
+ PRINT_ERR("DeletePartitionUnregister error:%d\n", ret);
+ (VOID)pthread_mutex_unlock(&g_mtdPartitionLock);
+ return ret;
+ }
+
+ ret = OsResourceRelease(node, type, param);
+ if (ret) {
+ PRINT_ERR("DeletePartitionUnregister error:%d\n", ret);
+ (VOID)pthread_mutex_unlock(&g_mtdPartitionLock);
+ return ret;
+ }
+
+ ret = pthread_mutex_unlock(&g_mtdPartitionLock);
+ if (ret != ENOERR) {
+ PRINT_ERR("%s %d, mutex unlock failed, error:%d\n", __FUNCTION__, __LINE__, ret);
+ }
+ return ENOERR;
+}
+
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/mtd/multi_partition/src/mtd_shellcmd.c b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/mtd/multi_partition/src/mtd_shellcmd.c
new file mode 100644
index 00000000..ef72e50b
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/drivers/mtd/multi_partition/src/mtd_shellcmd.c
@@ -0,0 +1,78 @@
+/*
+ * 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 "mtd_partition.h"
+#include "stdlib.h"
+#include "stdio.h"
+#include "los_config.h"
+
+#ifdef LOSCFG_SHELL_CMD_DEBUG
+#include "shcmd.h"
+
+INT32 osShellCmdPartitionShow(INT32 argc, const CHAR **argv)
+{
+ mtd_partition *node = NULL;
+ const CHAR *fs = NULL;
+ partition_param *param = NULL;
+
+ if (argc != 1) {
+ PRINT_ERR("partition [nand/spinor]\n");
+ return -EPERM;
+ } else {
+ fs = argv[0];
+ }
+
+ if (strcmp(fs, "nand") == 0) {
+ param = GetNandPartParam();
+ } else if (strcmp(fs, "spinor") == 0) {
+ param = GetSpinorPartParam();
+ } else {
+ PRINT_ERR("not supported!\n");
+ return -EINVAL;
+ }
+
+ if ((param == NULL) || (param->flash_mtd == NULL)) {
+ PRINT_ERR("no partition!\n");
+ return -EINVAL;
+ }
+
+ LOS_DL_LIST_FOR_EACH_ENTRY(node, ¶m->partition_head->node_info, mtd_partition, node_info) {
+ PRINTK("%s partition num:%u, blkdev name:%s, mountpt:%s, startaddr:0x%08x, length:0x%08x\n",
+ fs, node->patitionnum, node->blockdriver_name, node->mountpoint_name,
+ (node->start_block * param->block_size),
+ ((node->end_block - node->start_block) + 1) * param->block_size);
+ }
+ return ENOERR;
+}
+
+SHELLCMD_ENTRY(partition_shellcmd, CMD_TYPE_EX, "partition", XARGS, (CmdCallBackFunc)osShellCmdPartitionShow);
+
+#endif /* LOSCFG_SHELL */
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/figures/OpenHarmony-LiteOS-A内核架构图.png b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/figures/OpenHarmony-LiteOS-A内核架构图.png
new file mode 100644
index 00000000..b2ff552d
Binary files /dev/null and b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/figures/OpenHarmony-LiteOS-A内核架构图.png differ
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/figures/architecture-of-the-openharmony-liteos-cortex-a-kernel.png b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/figures/architecture-of-the-openharmony-liteos-cortex-a-kernel.png
new file mode 100644
index 00000000..27b8a0e0
Binary files /dev/null and b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/figures/architecture-of-the-openharmony-liteos-cortex-a-kernel.png differ
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/fs/BUILD.gn b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/fs/BUILD.gn
new file mode 100644
index 00000000..26b27df3
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/fs/BUILD.gn
@@ -0,0 +1,60 @@
+# 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("//kernel/liteos_a/liteos.gni")
+
+group("fs") {
+ deps = [
+ "fat",
+ "fat/virpart",
+ "jffs2",
+ "nfs",
+ "patchfs",
+ "proc",
+ "ramfs",
+ "romfs",
+ "rootfs",
+ "vfs",
+ "vfs/bcache",
+ "zpfs",
+ ]
+}
+
+config("public") {
+ include_dirs = [ "include" ]
+ configs = [
+ "vfs:public",
+ "vfs/bcache:public",
+ "fat:public",
+ "fat/virpart:public",
+ "proc:public",
+ "patchfs:public",
+ "rootfs:public",
+ ]
+}
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/fs/Kconfig b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/fs/Kconfig
new file mode 100644
index 00000000..032668fb
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/fs/Kconfig
@@ -0,0 +1,10 @@
+source "fs/vfs/Kconfig"
+source "fs/fat/Kconfig"
+source "fs/ramfs/Kconfig"
+source "fs/romfs/Kconfig"
+source "fs/nfs/Kconfig"
+source "fs/proc/Kconfig"
+#source "fs/jffs2/Kconfig"
+source "fs/rootfs/Kconfig"
+source "fs/patchfs/Kconfig"
+source "fs/zpfs/Kconfig"
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/fs/fat/BUILD.gn b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/fs/fat/BUILD.gn
new file mode 100644
index 00000000..921f9ea6
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/fs/fat/BUILD.gn
@@ -0,0 +1,51 @@
+# 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("//kernel/liteos_a/liteos.gni")
+import("//third_party/FatFs/FatFs.gni")
+
+module_switch = defined(LOSCFG_FS_FAT)
+module_name = get_path_info(rebase_path("."), "name")
+kernel_module(module_name) {
+ sources = [
+ "os_adapt/fat_shellcmd.c",
+ "os_adapt/fatfs.c",
+ "os_adapt/format.c",
+ ]
+
+ sources += FATFS_SRC_FILES
+
+ include_dirs = [ "os_adapt" ]
+
+ public_configs = [ ":public" ]
+}
+
+config("public") {
+ include_dirs = FATFS_INCLUDE_DIRS
+}
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/fs/fat/Kconfig b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/fs/fat/Kconfig
new file mode 100644
index 00000000..6d7060fa
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/fs/fat/Kconfig
@@ -0,0 +1,43 @@
+config FS_FAT
+ bool "Enable FAT"
+ default y
+ depends on FS_VFS
+ help
+ Answer Y to enable LiteOS support fat filesystem.
+
+config FS_FAT_CACHE
+ bool "Enable FAT Cache"
+ default y
+ depends on FS_FAT
+ help
+ Answer Y to enable LiteOS fat filesystem support cache.
+
+config FS_FAT_CACHE_SYNC_THREAD
+ bool "Enable FAT Cache Sync Thread"
+ default n
+ depends on FS_FAT_CACHE
+ help
+ Answer Y to enable LiteOS fat filesystem support cache sync thread.
+
+config FS_FAT_CHINESE
+ bool "Enable Chinese"
+ default y
+ depends on FS_FAT
+ help
+ Answer Y to enable LiteOS fat filesystem support Chinese.
+
+config FS_FAT_VIRTUAL_PARTITION
+ bool "Enable Virtual Partition"
+ default n
+ depends on FS_FAT
+
+config FS_FAT_VOLUMES
+ int
+ depends on FS_FAT
+ default 32 if PLATFORM_HI3731
+ default 16
+
+config FS_FAT_DISK
+ bool "Enable partinfo for storage device"
+ depends on FS_VFS && (FS_FAT || DRIVERS_MMC || DRIVERS_USB)
+ default y
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/fs/fat/Makefile b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/fs/fat/Makefile
new file mode 100644
index 00000000..cc615847
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/fs/fat/Makefile
@@ -0,0 +1,42 @@
+# 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 $(LITEOSTOPDIR)/config.mk
+
+MODULE_NAME := $(notdir $(shell pwd))
+
+LOCAL_SRCS := $(wildcard os_adapt/*.c)
+LOCAL_SRCS += $(wildcard $(LITEOSTHIRDPARTY)/FatFs/source/*.c)
+
+LOCAL_INCLUDE := -I $(LITEOSTOPDIR)/fs/fat/os_adapt
+
+LOCAL_FLAGS := $(LOCAL_INCLUDE)
+
+include $(MODULE)
+
diff --git a/kernel_liteos_a-OpenHarmony-v3.1.7-Release/fs/fat/os_adapt/fat_shellcmd.c b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/fs/fat/os_adapt/fat_shellcmd.c
new file mode 100644
index 00000000..74e25a89
--- /dev/null
+++ b/kernel_liteos_a-OpenHarmony-v3.1.7-Release/fs/fat/os_adapt/fat_shellcmd.c
@@ -0,0 +1,80 @@
+/*
+ * 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 defined(LOSCFG_SHELL) && defined(LOSCFG_FS_FAT)
+#include "stdlib.h"
+#include "stdio.h"
+#include "errno.h"
+#include "shcmd.h"
+#include "shell.h"
+#include "fatfs.h"
+
+int osShellCmdFormat(int argc, char **argv)
+{
+ if (argc < 3) { /* 3, at least 3 params for this shell command. */
+ perror("format error");
+ PRINTK("Usage :\n");
+ PRINTK(" format